Skip to content
TypeScript

build(server): make the CLI bundle loadable as a Node single-executable (#11316)

Julius Marminge06de59b3d67e
diff --git a/.gitignore b/.gitignore
index 79f8735b25e..8482c5a290e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,7 @@ node_modules
*.log
*.tsbuildinfo
apps/*/dist
+apps/*/dist-exe
infra/*/dist
.astro
packages/*/dist
diff --git a/apps/server/package.json b/apps/server/package.json
index 9b5f2fb2d7d..1892f7f3d6d 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -17,16 +17,15 @@
"scripts": {
"dev": "node --watch src/bin.ts",
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
+ "build:exe": "node scripts/cli.ts build-exe",
"start": "node dist/bin.mjs",
"typecheck": "tsc --noEmit",
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.260",
- "@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
- "@effect/sql-sqlite-bun": "catalog:",
"@ff-labs/fff-node": "0.9.4",
"@opencode-ai/sdk": "^1.3.15",
"effect": "catalog:",
@@ -44,7 +43,6 @@
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"@t3tools/web": "workspace:*",
- "@types/bun": "1.3.14",
"@types/node": "catalog:",
"@types/yauzl": "^3.4.0",
"effect-acp": "workspace:*",
diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts
index 2de5b702a28..f77cff2c4c4 100644
--- a/apps/server/scripts/cli.ts
+++ b/apps/server/scripts/cli.ts
@@ -15,6 +15,7 @@ import {
resolveWebAssetBrandForPackageVersion,
resolveWebIconOverrides,
} from "../../../scripts/lib/brand-assets.ts";
+import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-external-packages.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import { fromYaml } from "@t3tools/shared/schemaYaml";
@@ -25,6 +26,7 @@ import {
ServerCliCommandExitError,
ServerCliDevelopmentIconSourceMissingError,
ServerCliDevelopmentIconTargetMissingError,
+ ServerCliExecutableImportError,
ServerCliPublishIconSourceMissingError,
ServerCliPublishIconTargetMissingError,
} from "./cliErrors.ts";
@@ -175,6 +177,52 @@ const buildCmd = Command.make(
}),
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
+// ---------------------------------------------------------------------------
+// build-exe subcommand
+// ---------------------------------------------------------------------------
+
+const buildExeCmd = Command.make(
+ "build-exe",
+ {
+ verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
+ },
+ (config) =>
+ Effect.gen(function* () {
+ const path = yield* Path.Path;
+ const fs = yield* FileSystem.FileSystem;
+ const repoRoot = yield* RepoRoot;
+ const serverDir = path.join(repoRoot, "apps/server");
+
+ yield* Effect.log("[cli] Building single-executable...");
+ const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
+ yield* runCommand(
+ ChildProcess.make(spawnCommand.command, spawnCommand.args, {
+ cwd: serverDir,
+ env: { ...process.env, T3CODE_PACK_EXE: "1" },
+ stdout: config.verbose ? "inherit" : "ignore",
+ stderr: "inherit",
+ shell: spawnCommand.shell,
+ }),
+ );
+
+ // The executable can only `import` built-ins. A file-backed import
+ // passes the bundler and `node dist/bin.mjs`, then throws inside the
+ // binary, so read the emitted module graph rather than trusting config.
+ const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
+ const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
+ if (specifiers.length > 0) {
+ return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
+ }
+ yield* Effect.log(
+ "[cli] Built dist-exe/t3 (expects client/, resource-monitor/, and the runtime-external node_modules beside it; scripts/build-cli-archive.ts assembles that tree)",
+ );
+ }),
+).pipe(
+ Command.withDescription(
+ "Build the server as a Node single-executable (needs a Node 25.7+ host for --build-sea). The binary still resolves native packages from a node_modules tree beside it.",
+ ),
+);
+
// ---------------------------------------------------------------------------
// publish subcommand
// ---------------------------------------------------------------------------
@@ -309,7 +357,7 @@ const publishCmd = Command.make(
const cli = Command.make("cli").pipe(
Command.withDescription("T3 server build & publish CLI."),
- Command.withSubcommands([buildCmd, publishCmd]),
+ Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
);
Command.run(cli, { version: "0.0.0" }).pipe(
diff --git a/apps/server/scripts/cliErrors.ts b/apps/server/scripts/cliErrors.ts
index d2a410a6e0f..ce4bb6c2f8e 100644
--- a/apps/server/scripts/cliErrors.ts
+++ b/apps/server/scripts/cliErrors.ts
@@ -68,3 +68,15 @@ export class ServerCliBuildAssetMissingError extends Schema.TaggedError<ServerCl
return `Missing build asset: ${this.assetPath}. Run the build subcommand first.`;
}
}
+
+export class ServerCliExecutableImportError extends Schema.TaggedError<ServerCliExecutableImportError>()(
+ "ServerCliExecutableImportError",
+ {
+ bundlePath: Schema.String,
+ specifiers: Schema.Array(Schema.String),
+ },
+) {
+ override get message(): string {
+ return `${this.bundlePath} imports file-backed packages that a single-executable cannot resolve: ${this.specifiers.join(", ")}. Load them through createRequire instead.`;
+ }
+}
diff --git a/apps/server/src/persistence/Errors.test.ts b/apps/server/src/persistence/Errors.test.ts
index bd3e5128b1f..dfa35020df3 100644
--- a/apps/server/src/persistence/Errors.test.ts
+++ b/apps/server/src/persistence/Errors.test.ts
@@ -3,7 +3,6 @@ import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
-import { classifySqliteError, SqlError } from "effect/unstable/sql/SqlError";
import { PersistenceDecodeError, PersistenceSqlError, toPersistenceSqlError } from "./Errors.ts";
@@ -55,24 +54,6 @@ it("reads the condition through a wrapping driver error", () => {
assert.equal(error.detail, "SQLITE(5) database is locked");
});
-it.each([{ errno: 1555, code: "SQLITE_CONSTRAINT_PRIMARYKEY" }, { errno: 1 }])(
- "names Bun SQLite condition $errno through the SQL error wrapper",
- (condition) => {
- const driver = Object.assign(new Error("bun-sql-private-sentinel"), {
- name: "SQLiteError",
- ...condition,
- });
- const cause = new SqlError({ reason: classifySqliteError(driver) });
- const error = toPersistenceSqlError("AuthSessionRepository.create:query")(cause);
-
- assert.equal(
- error.message,
- `SQL error in AuthSessionRepository.create:query: SQLITE(${condition.errno})`,
- );
- assert.equal(error.cause, cause);
- },
-);
-
it.each([
new Error("unhelpful"),
Object.assign(new Error("file not found"), { errno: -2, code: "ENOENT" }),
diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.ts
index 7d6cf170195..2715bf65a7b 100644
--- a/apps/server/src/persistence/Errors.ts
+++ b/apps/server/src/persistence/Errors.ts
@@ -75,7 +75,7 @@ const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
/**
* Read a SQLite condition through SQL error wrappers.
- * Use Node's fixed description or Bun's numeric code, never the driver message.
+ * Use node:sqlite's fixed description, never the driver message.
*/
function sqliteCondition(cause: unknown): string | undefined {
let value = cause;
@@ -88,15 +88,6 @@ function sqliteCondition(cause: unknown): string | undefined {
) {
return `SQLITE(${value.errcode}) ${value.errstr}`;
}
- if (
- "name" in value &&
- value.name === "SQLiteError" &&
- "errno" in value &&
- typeof value.errno === "number" &&
- Number.isInteger(value.errno)
- ) {
- return `SQLITE(${value.errno})`;
- }
value = "cause" in value ? value.cause : undefined;
}
return undefined;
diff --git a/apps/server/src/persistence/Layers/Sqlite.ts b/apps/server/src/persistence/Layers/Sqlite.ts
index 41d8f5baf3f..88342cbf1fa 100644
--- a/apps/server/src/persistence/Layers/Sqlite.ts
+++ b/apps/server/src/persistence/Layers/Sqlite.ts
@@ -3,33 +3,11 @@ import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as SqlClient from "effect/unstable/sql/SqlClient";
-import type { SqlError } from "effect/unstable/sql/SqlError";
+import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import { runMigrations } from "../Migrations.ts";
import { ServerConfig } from "../../config.ts";
-type RuntimeSqliteLayerConfig = {
- readonly filename: string;
- readonly spanAttributes?: Record<string, unknown>;
-};
-
-type Loader = {
- layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient, SqlError>;
-};
-const defaultSqliteClientLoaders = {
- bun: () => import("@effect/sql-sqlite-bun/SqliteClient"),
- node: () => import("@t3tools/shared/nodeSqliteClient"),
-} satisfies Record<string, () => Promise<Loader>>;
-
-const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
- config: RuntimeSqliteLayerConfig,
-) {
- const runtime = process.versions.bun !== undefined ? "bun" : "node";
- const loader = defaultSqliteClientLoaders[runtime];
- const clientModule = yield* Effect.promise<Loader>(loader);
- return clientModule.layer(config);
-}, Layer.unwrap);
-
const setup = Layer.effectDiscard(
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -50,7 +28,7 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
return Layer.provideMerge(
setup,
- makeRuntimeSqliteLayer({
+ NodeSqliteClient.layer({
filename: dbPath,
spanAttributes: {
"db.name": path.basename(dbPath),
@@ -62,7 +40,7 @@ export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
- makeRuntimeSqliteLayer({ filename: ":memory:" }),
+ NodeSqliteClient.layer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index b8c3ca6096e..6fdbda5ce54 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -1,3 +1,8 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeHttp from "node:http";
+
+import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
+import * as NodeServices from "@effect/platform-node/NodeServices";
import {
EnvironmentHttpApi,
ProviderDriverKind,
@@ -29,6 +34,7 @@ import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
import { fixPath } from "./os-jank.ts";
import { websocketRpcRouteLayer } from "./ws.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
+import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts";
import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
import * as PullRequestService from "./pullRequest/PullRequestService.ts";
@@ -163,17 +169,7 @@ const ApplicationObservabilityLive = ObservabilityLive.pipe(
Layer.provideMerge(ResourceAttributionLayerLive),
);
-const PtyAdapterLive = Layer.unwrap(
- Effect.gen(function* () {
- if (typeof Bun !== "undefined") {
- const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
- return BunPtyAdapter.layer;
- } else {
- const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
- return NodePtyAdapter.layer;
- }
- }),
-);
+const PtyAdapterLive = NodePtyAdapter.layer;
const ServerSettingsLayerLive = ServerSettings.layer.pipe(
Layer.provide(ServerSecretStore.layer),
@@ -226,61 +222,22 @@ const RelayClientLive = Layer.unwrap(
const HttpServerLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
- if (typeof Bun !== "undefined") {
- const BunHttpServer = yield* Effect.promise(
- () => import("@effect/platform-bun/BunHttpServer"),
- );
- return BunHttpServer.layer({
- port: config.port,
- hostname: config.host ?? "127.0.0.1",
- gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
- websocket: {
- // Negotiate permessage-deflate with clients that offer it; clients
- // that don't still get uncompressed frames on their connection. A
- // dedicated compressor keeps a per-connection sliding window
- // (context takeover) so the compression dictionary is shared across
- // server-to-client frames. Decompression uses the shared
- // decompressor: uWebSockets' dedicated decompressor path can abort
- // connections (close 1006) on valid DEFLATE input — see
- // https://github.com/uNetworking/uWebSockets.js/issues/633.
- perMessageDeflate: {
- compress: "dedicated",
- decompress: "shared",
- },
- },
- });
- } else {
- const [NodeHttpServer, NodeHttp] = yield* Effect.all([
- Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
- Effect.promise(() => import("node:http")),
- ]);
- return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
- host: config.host ?? "127.0.0.1",
- port: config.port,
- gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
- // Negotiate permessage-deflate with clients that offer it; clients
- // that don't still get uncompressed frames on their connection.
- // Context takeover stays enabled (ws default) so the compression
- // window is shared across frames — that also makes small frames cheap
- // to compress, so no size threshold is set (ws only honors
- // `threshold` when context takeover is disabled).
- websocket: { perMessageDeflate: true },
- });
- }
+ return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
+ host: config.host ?? "127.0.0.1",
+ port: config.port,
+ gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
+ // Negotiate permessage-deflate with clients that offer it; clients
+ // that don't still get uncompressed frames on their connection.
+ // Context takeover stays enabled (ws default) so the compression
+ // window is shared across frames — that also makes small frames cheap
+ // to compress, so no size threshold is set (ws only honors
+ // `threshold` when context takeover is disabled).
+ websocket: { perMessageDeflate: true },
+ });
}),
);
-const PlatformServicesLive = Layer.unwrap(
- Effect.gen(function* () {
- if (typeof Bun !== "undefined") {
- const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
- return layer;
- } else {
- const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
- return layer;
- }
- }),
-);
+const PlatformServicesLive = NodeServices.layer;
const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(OrchestrationReactorLive),
diff --git a/apps/server/src/terminal/BunPtyAdapter.test.ts b/apps/server/src/terminal/BunPtyAdapter.test.ts
deleted file mode 100644
index e04a54e6d33..00000000000
--- a/apps/server/src/terminal/BunPtyAdapter.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { assert, expect, it } from "@effect/vitest";
-import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
-import * as Cause from "effect/Cause";
-import * as Effect from "effect/Effect";
-import * as Exit from "effect/Exit";
-
-import * as BunPtyAdapter from "./BunPtyAdapter.ts";
-
-it("describes unavailable Bun PTY operations structurally", () => {
- const error = new BunPtyAdapter.BunPtyOperationUnavailableError({
- operation: "resize",
- pid: 42,
- });
-
- expect(error).toMatchObject({
- _tag: "BunPtyOperationUnavailableError",
- operation: "resize",
- pid: 42,
- });
- expect(error.message).toBe("Bun PTY resize is unavailable for process 42.");
-});
-
-it.effect("reports unsupported platforms with a structured startup defect", () =>
- Effect.gen(function* () {
- const exit = yield* BunPtyAdapter.make().pipe(
- Effect.provideService(HostProcessPlatform, "win32"),
- Effect.exit,
- );
-
- expect(Exit.isFailure(exit)).toBe(true);
- if (Exit.isFailure(exit)) {
- expect(Cause.hasDies(exit.cause)).toBe(true);
- const error = Cause.squash(exit.cause);
- assert.instanceOf(error, BunPtyAdapter.BunPtyUnsupportedPlatformError);
- expect(error).toMatchObject({
- _tag: "BunPtyUnsupportedPlatformError",
- platform: "win32",
- });
- expect(error.message).toBe(
- "Bun PTY terminal support is unavailable on win32. Please use Node.js (e.g. by running `npx t3`) instead.",
- );
- }
- }),
-);
diff --git a/apps/server/src/terminal/BunPtyAdapter.ts b/apps/server/src/terminal/BunPtyAdapter.ts
deleted file mode 100644
index 1a3f26ceb67..00000000000
--- a/apps/server/src/terminal/BunPtyAdapter.ts
+++ /dev/null
@@ -1,155 +0,0 @@
-/// <reference types="bun" />
-
-import * as Effect from "effect/Effect";
-import * as Layer from "effect/Layer";
-import * as Schema from "effect/Schema";
-import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
-
-import * as PtyAdapter from "./PtyAdapter.ts";
-
-export class BunPtyUnsupportedPlatformError extends Schema.TaggedError<BunPtyUnsupportedPlatformError>()(
- "BunPtyUnsupportedPlatformError",
- {
- platform: Schema.Literal("win32"),
- },
-) {
- override get message(): string {
- return `Bun PTY terminal support is unavailable on ${this.platform}. Please use Node.js (e.g. by running \`npx t3\`) instead.`;
- }
-}
-
-export class BunPtyOperationUnavailableError extends Schema.TaggedError<BunPtyOperationUnavailableError>()(
- "BunPtyOperationUnavailableError",
- {
- operation: Schema.Literals(["write", "resize"]),
- pid: Schema.Number,
- },
-) {
- override get message(): string {
- return `Bun PTY ${this.operation} is unavailable for process ${this.pid}.`;
- }
-}
-
-class BunPtyProcess implements PtyAdapter.PtyProcess {
- private readonly dataListeners = new Set<(data: string) => void>();
- private readonly exitListeners = new Set<(event: PtyAdapter.PtyExitEvent) => void>();
- private readonly decoder = new TextDecoder();
- private readonly process: Bun.Subprocess;
- private didExit = false;
-
- constructor(process: Bun.Subprocess) {
- this.process = process;
- void this.process.exited
- .then((exitCode) => {
- this.emitExit({
- exitCode: Number.isInteger(exitCode) ? exitCode : 0,
- signal: typeof this.process.signalCode === "number" ? this.process.signalCode : null,
- });
- })
- .catch(() => {
- this.emitExit({ exitCode: 1, signal: null });
- });
- }
-
- get pid(): number {
- return this.process.pid;
- }
-
- write(data: string): void {
- if (!this.process.terminal) {
- throw new BunPtyOperationUnavailableError({ operation: "write", pid: this.pid });
- }
- this.process.terminal.write(data);
- }
-
- resize(cols: number, rows: number): void {
- if (!this.process.terminal?.resize) {
- throw new BunPtyOperationUnavailableError({ operation: "resize", pid: this.pid });
- }
- this.process.terminal.resize(cols, rows);
- }
-
- kill(signal?: string): void {
- if (!signal) {
- this.process.kill();
- return;
- }
- this.process.kill(signal as NodeJS.Signals);
- }
-
- onData(callback: (data: string) => void): () => void {
- this.dataListeners.add(callback);
- return () => {
- this.dataListeners.delete(callback);
- };
- }
-
- onExit(callback: (event: PtyAdapter.PtyExitEvent) => void): () => void {
- this.exitListeners.add(callback);
- return () => {
- this.exitListeners.delete(callback);
- };
- }
-
- emitData(data: Uint8Array): void {
- if (this.didExit) return;
- const text = this.decoder.decode(data, { stream: true });
- if (text.length === 0) return;
- for (const listener of this.dataListeners) {
- listener(text);
- }
- }
-
- private emitExit(event: PtyAdapter.PtyExitEvent): void {
- if (this.didExit) return;
- this.didExit = true;
-
- const remainder = this.decoder.decode();
- if (remainder.length > 0) {
- for (const listener of this.dataListeners) {
- listener(remainder);
- }
- }
-
- for (const listener of this.exitListeners) {
- listener(event);
- }
- }
-}
-
-export const make = Effect.fn("BunPtyAdapter.make")(function* () {
- const platform = yield* HostProcessPlatform;
- if (platform === "win32") {
- return yield* Effect.die(new BunPtyUnsupportedPlatformError({ platform }));
- }
- return PtyAdapter.PtyAdapter.of({
- spawn: (input) =>
- Effect.try({
- try: () => {
- let processHandle: BunPtyProcess | null = null;
- const command = [input.shell, ...(input.args ?? [])];
- const subprocess = Bun.spawn(command, {
- cwd: input.cwd,
- env: input.env,
- terminal: {
- cols: input.cols,
- rows: input.rows,
- data: (_terminal, data) => {
- processHandle?.emitData(data);
- },
- },
- });
- processHandle = new BunPtyProcess(subprocess);
- return processHandle;
- },
- catch: (cause) =>
- new PtyAdapter.PtySpawnError({
- adapter: "bun",
- shell: input.shell,
- cause,
- }),
- }),
- });
-});
-
-export const layer = Layer.effect(PtyAdapter.PtyAdapter, make());
diff --git a/apps/server/src/terminal/NodePtyAdapter.test.ts b/apps/server/src/terminal/NodePtyAdapter.test.ts
index 066cf01f261..e6650025f70 100644
--- a/apps/server/src/terminal/NodePtyAdapter.test.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.test.ts
@@ -19,7 +19,7 @@ const spawn = vi.fn(() => ({
onExit: vi.fn(() => ({ dispose: vi.fn() })),
}));
-vi.mock("node-pty", () => ({ spawn }));
+const fakeNodePty = { spawn } as unknown as typeof import("node-pty");
const makeTestLayer = (platform: NodeJS.Platform = "win32") =>
NodePtyAdapter.layer.pipe(
@@ -28,6 +28,7 @@ const makeTestLayer = (platform: NodeJS.Platform = "win32") =>
NodeServices.layer,
Layer.succeed(HostProcessPlatform, platform),
Layer.succeed(HostProcessArchitecture, "x64"),
+ Layer.succeed(NodePtyAdapter.NodePtyModuleLoaderRef, () => Promise.resolve(fakeNodePty)),
),
),
);
@@ -125,7 +126,10 @@ it.effect("preserves a caller-provided TERM in the spawn env on win32", () =>
it.effect("reports native module load failures as structured startup defects", () =>
Effect.gen(function* () {
const cause = new Error("native binding could not be loaded");
- const exit = yield* NodePtyAdapter.make(() => Promise.reject(cause)).pipe(Effect.exit);
+ const exit = yield* NodePtyAdapter.make().pipe(
+ Effect.provideService(NodePtyAdapter.NodePtyModuleLoaderRef, () => Promise.reject(cause)),
+ Effect.exit,
+ );
assert.isTrue(Exit.isFailure(exit));
if (Exit.isFailure(exit)) {
diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts
index 8f238ac60c3..67cdcecdd53 100644
--- a/apps/server/src/terminal/NodePtyAdapter.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.ts
@@ -1,5 +1,6 @@
import * as NodeModule from "node:module";
+import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -24,10 +25,24 @@ export class NodePtyModuleLoadError extends Schema.TaggedError<NodePtyModuleLoad
type NodePtyModuleLoader = () => Promise<typeof import("node-pty")>;
+// node-pty stays external to the CLI bundle because it dlopens a native
+// addon. Inside a Node single-executable, `import()` cannot load files from
+// disk (only built-ins resolve), while `require` always reads the real
+// filesystem, so both the module and its spawn-helper resolve through it.
+const requireForNodePty = NodeModule.createRequire(import.meta.url);
+
+const loadNodePty: NodePtyModuleLoader = () =>
+ Promise.resolve().then(() => requireForNodePty("node-pty") as typeof import("node-pty"));
+
+/** Injectable so tests can substitute a fake module; `require` bypasses module mocks. */
+export const NodePtyModuleLoaderRef = Context.Reference<NodePtyModuleLoader>(
+ "server/terminal/NodePtyModuleLoader",
+ { defaultValue: () => loadNodePty },
+);
+
let didEnsureSpawnHelperExecutable = false;
const resolveNodePtySpawnHelperPath = Effect.gen(function* () {
- const requireForNodePty = NodeModule.createRequire(import.meta.url);
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const platform = yield* HostProcessPlatform;
@@ -113,9 +128,8 @@ class NodePtyProcess implements PtyAdapter.PtyProcess {
}
}
-export const make = Effect.fn("NodePtyAdapter.make")(function* (
- loadNodePtyModule: NodePtyModuleLoader = () => import("node-pty"),
-) {
+export const make = Effect.fn("NodePtyAdapter.make")(function* () {
+ const loadNodePtyModule = yield* NodePtyModuleLoaderRef;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const platform = yield* HostProcessPlatform;
diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts
index 44a9c3397c6..cac501aede0 100644
--- a/apps/server/src/workspace/WorkspaceSearchIndex.ts
+++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts
@@ -1,13 +1,15 @@
-import {
- type DirItem,
- type DirSearchResult,
- type FileItem,
- FileFinder,
- type GrepCursor,
- type MixedItem,
- type MixedSearchResult,
- type Result,
- type SearchResult,
+import * as NodeModule from "node:module";
+
+import type {
+ DirItem,
+ DirSearchResult,
+ FileItem,
+ FileFinder as FileFinderType,
+ GrepCursor,
+ MixedItem,
+ MixedSearchResult,
+ Result,
+ SearchResult,
} from "@ff-labs/fff-node";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -25,6 +27,13 @@ import type {
} from "@t3tools/contracts";
import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
+// fff-node stays external to the CLI bundle because it dlopens a native
+// library. A static `import` of an external package is a hard error inside a
+// Node single-executable (only built-ins resolve there), so load it through
+// `require`, which reads from the real filesystem in every runtime.
+const requireForFff = NodeModule.createRequire(import.meta.url);
+const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node");
+
const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;
const WORKSPACE_INDEX_SCAN_TIMEOUT = "15 seconds";
@@ -330,7 +339,7 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* (
const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* <E>(
cwd: string,
- finder: FileFinder,
+ finder: FileFinderType,
onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,
): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {
const result = yield* Effect.tryPromise({
diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts
index 621a1f7bf66..a6e356c6996 100644
--- a/apps/server/vite.config.ts
+++ b/apps/server/vite.config.ts
@@ -23,6 +23,12 @@ export { shouldBundleCliDependency };
const repoEnv = loadRepoEnv();
const cliBuildChannel = packageJson.version.includes("-nightly.") ? "nightly" : "latest";
+// `build:exe` wraps the same bundle in a Node single-executable. tsdown's exe
+// step refuses multi-chunk output and counts the sourcemap as a chunk, and the
+// executable needs a host Node that supports `--build-sea` (25.7+), so this is
+// a separate mode rather than a second entry in the default build.
+const packExecutable = process.env.T3CODE_PACK_EXE === "1";
+
export default mergeConfig(
baseConfig,
defineConfig({
@@ -36,10 +42,25 @@ export default mergeConfig(
},
},
pack: {
- entry: ["src/bin.ts", "src/claudeHistoryWorker.ts"],
- outDir: "dist",
- sourcemap: true,
+ // The executable embeds one entry; the history worker becomes a hidden
+ // subcommand there instead of a sibling script.
+ entry: packExecutable ? ["src/bin.ts"] : ["src/bin.ts", "src/claudeHistoryWorker.ts"],
+ outDir: packExecutable ? "dist-exe" : "dist",
+ sourcemap: !packExecutable,
clean: true,
+ ...(packExecutable
+ ? {
+ exe: {
+ fileName: "t3",
+ outDir: "dist-exe",
+ // Node's SEA docs: `import()` does not work when useCodeCache is
+ // true, and the server reaches several modules that way. The
+ // cache is also platform-bound, so leaving it off keeps the
+ // build correct on any host.
+ seaConfig: { useCodeCache: false },
+ },
+ }
+ : {}),
deps: {
// Both halves are required. `alwaysBundle` forces the JS dependencies in
// (declared deps are external by default, which is what this change is
diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts
index 3716f0ee484..d156d4cc3e5 100644
--- a/packages/shared/src/nodeSqliteClient.ts
+++ b/packages/shared/src/nodeSqliteClient.ts
@@ -7,7 +7,6 @@
import * as NodeSqlite from "node:sqlite";
import * as Cache from "effect/Cache";
-import * as Config from "effect/Config";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
@@ -26,10 +25,6 @@ import * as Statement from "effect/unstable/sql/Statement";
const ATTR_DB_SYSTEM_NAME = "db.system.name";
-export const TypeId: TypeId = "~local/sqlite-node/SqliteClient";
-
-export type TypeId = "~local/sqlite-node/SqliteClient";
-
export interface SqliteClientConfig {
readonly filename: string;
readonly readonly?: boolean | undefined;
@@ -315,13 +310,6 @@ const makeMemory = (
},
);
-export const layerConfig = (
- config: Config.Wrap<SqliteClientConfig>,
-): Layer.Layer<Client.SqlClient, Config.ConfigError | SqlError> =>
- Layer.effect(Client.SqlClient, Config.unwrap(config).pipe(Effect.flatMap(make))).pipe(
- Layer.provide(Reactivity.layer),
- );
-
export const layer = (config: SqliteClientConfig): Layer.Layer<Client.SqlClient, SqlError> =>
Layer.effect(Client.SqlClient, make(config)).pipe(Layer.provide(Reactivity.layer));
diff --git a/patches/@[email protected] b/patches/@[email protected]
index 74c132926d9..04c2a803056 100644
--- a/patches/@[email protected]
+++ b/patches/@[email protected]
@@ -37,3 +37,17 @@ index ee181aef5007e4bf34a49479c089ca30f73a320b..327e2c55c83cc4c50d396a3109190ef1
}
}
catch {
+diff --git a/package.json b/package.json
+--- a/package.json
++++ b/package.json
+@@ -8,8 +8,9 @@
+ "types": "dist/src/index.d.ts",
+ "exports": {
+ ".": {
++ "types": "./dist/src/index.d.ts",
+ "import": "./dist/src/index.js",
+- "types": "./dist/src/index.d.ts"
++ "require": "./dist/src/index.js"
+ }
+ },
+ "files": [
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 26f13005de4..5a37d9bf6fa 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -59,11 +59,9 @@ overrides:
'@clerk/react': 6.14.7
'@clerk/shared': 4.30.1
'@effect/atom-react': 4.0.0-rc.112
- '@effect/platform-bun': 4.0.0-rc.112
'@effect/platform-node': 4.0.0-rc.112
'@effect/platform-node-shared': 4.0.0-rc.112
'@effect/sql-pg': 4.0.0-rc.112
- '@effect/sql-sqlite-bun': 4.0.0-rc.112
'@effect/vitest': 4.0.0-rc.112
'@effect/vitest>vitest': '-'
'@expo/dom-webview': 57.0.1
@@ -90,7 +88,7 @@ patchedDependencies:
'@clerk/[email protected]': 72e426f44fc1cde16fc2cbba3d1e96cdca7c6d957faa73d0fe6b43948608a6c1
'@effect/[email protected]': a16b1e870d8c29e4a98b17cc4c638a4ff471753d8ca3487f78a22b759caf951b
'@expo/[email protected]': 96f1a75347e6ea02dc4b7034ace815d8ee39e18b8166ebfb573d9e58328f0dc2
- '@ff-labs/[email protected]': ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368
+ '@ff-labs/[email protected]': c4e3cc2420ceb9dc650f9d189e9c24baf7e83f342998bacda5f459a4ce7927a8
'@legendapp/[email protected]': 680cc6a5c5b4a4032e467e7b3fde22f89a84c0ee2e6eac6fda737d6277cc0806
'@pierre/[email protected]': 0ccee155b93b63d810e2c1a40c1fd676fb6fbcfa72cf6430dcedf1a3ae475ab4
'@react-native-ai/[email protected]': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
@@ -499,21 +497,15 @@ importers:
'@anthropic-ai/claude-agent-sdk':
specifier: ^0.3.260
version: 0.3.260(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
- '@effect/platform-bun':
- specifier: 4.0.0-rc.112
- version: 4.0.0-rc.112([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])
'@effect/platform-node':
specifier: 4.0.0-rc.112
version: 4.0.0-rc.112([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])([email protected])
'@effect/platform-node-shared':
specifier: 4.0.0-rc.112
version: 4.0.0-rc.112([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])
- '@effect/sql-sqlite-bun':
- specifier: 4.0.0-rc.112
- version: 4.0.0-rc.112([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))
'@ff-labs/fff-node':
specifier: 0.9.4
- version: 0.9.4(patch_hash=ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368)
+ version: 0.9.4(patch_hash=c4e3cc2420ceb9dc650f9d189e9c24baf7e83f342998bacda5f459a4ce7927a8)
'@opencode-ai/sdk':
specifier: ^1.3.15
version: 1.15.13
@@ -557,9 +549,6 @@ importers:
'@t3tools/web':
specifier: workspace:*
version: link:../web
- '@types/bun':
- specifier: 1.3.14
- version: 1.3.14
'@types/node':
specifier: 24.12.4
version: 24.12.4
@@ -1069,7 +1058,7 @@ packages:
resolution: {integrity: sha512-rH5BFh0Xq7aExpSpITyQbC+Jqfc9XgwJXidHVHTi1tNRC6/KAWg4tOzBfwiFIxljFLLYcApzlYFvLa/fTYcEjw==}
peerDependencies:
'@distilled.cloud/cloudflare': 1.0.0-rc.8
- '@effect/platform-bun': 4.0.0-rc.112
+ '@effect/platform-bun': '>=4.0.0-rc.112 || >=4.0.0'
'@effect/platform-node': 4.0.0-rc.112
effect: 4.0.0-rc.112
rolldown: 1.2.5
@@ -5353,9 +5342,6 @@ packages:
resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==}
- '@types/[email protected]':
- resolution: {integrity: sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==}
-
resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==}
@@ -6093,7 +6079,7 @@ packages:
peerDependencies:
'@alchemy.run/frontend-frameworks': 2.0.0-beta.76
'@aws/durable-execution-sdk-js': ^2.1.0
- '@effect/platform-bun': 4.0.0-rc.112
+ '@effect/platform-bun': '>=4.0.0-rc.112 || >=4.0.0'
'@effect/platform-node': 4.0.0-rc.112
'@effect/sql-mysql2': '>=4.0.0-rc.112 || >=4.0.0'
'@effect/sql-pg': 4.0.0-rc.112
@@ -6973,7 +6959,7 @@ packages:
'@effect/sql-mysql2': '>=4.0.0-beta.105 || >=4.0.0'
'@effect/sql-pg': 4.0.0-rc.112
'@effect/sql-pglite': '>=4.0.0-beta.105 || >=4.0.0'
- '@effect/sql-sqlite-bun': 4.0.0-rc.112
+ '@effect/sql-sqlite-bun': '>=4.0.0-beta.105 || >=4.0.0'
'@effect/sql-sqlite-do': '>=4.0.0-beta.105 || >=4.0.0'
'@effect/sql-sqlite-node': '>=4.0.0-beta.105 || >=4.0.0'
'@effect/sql-sqlite-wasm': '>=4.0.0-beta.105 || >=4.0.0'
@@ -12675,6 +12661,7 @@ snapshots:
transitivePeerDependencies:
- bufferutil
- utf-8-validate
+ optional: true
'@effect/[email protected]([email protected])([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))([email protected])':
dependencies:
@@ -12715,6 +12702,7 @@ snapshots:
'@effect/[email protected]([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))':
dependencies:
effect: 4.0.0-rc.112(patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2)
+ optional: true
'@effect/[email protected]([email protected](patch_hash=8bef799f35729cf3465eb428196f617b434a7c9f658d56acb2874d74b21b98b2))':
dependencies:
@@ -13664,7 +13652,7 @@ snapshots:
'@ff-labs/[email protected]':
optional: true
- '@ff-labs/[email protected](patch_hash=ab9ff544009e1891cfe3930105862d3699007f38922a79f3c98d90018deca368)':
+ '@ff-labs/[email protected](patch_hash=c4e3cc2420ceb9dc650f9d189e9c24baf7e83f342998bacda5f459a4ce7927a8)':
dependencies:
ffi-rs: 1.3.2
optionalDependencies:
@@ -15848,10 +15836,6 @@ snapshots:
'@types/connect': 3.4.38
'@types/node': 24.12.4
- '@types/[email protected]':
- dependencies:
- bun-types: 1.3.14
-
dependencies:
'@types/http-cache-semantics': 4.2.0
@@ -17009,6 +16993,7 @@ snapshots:
dependencies:
'@types/node': 24.12.4
+ optional: true
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index e2c683e9bab..f121121251d 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -32,11 +32,9 @@ catalog:
"@clerk/shared": 4.30.1
"@effect/atom-react": 4.0.0-rc.112
"@effect/openapi-generator": 4.0.0-rc.112
- "@effect/platform-bun": 4.0.0-rc.112
"@effect/platform-node": 4.0.0-rc.112
"@effect/platform-node-shared": 4.0.0-rc.112
"@effect/sql-pg": 4.0.0-rc.112
- "@effect/sql-sqlite-bun": 4.0.0-rc.112
"@effect/tsgo": 0.41.0
"@effect/vitest": 4.0.0-rc.112
"@legendapp/list": 3.3.5
@@ -71,11 +69,9 @@ minimumReleaseAgeExclude:
- "@distilled.cloud/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- - "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- "@effect/[email protected]"
- - "@effect/[email protected]"
- "@effect/[email protected]"
@@ -121,11 +117,9 @@ overrides:
"@clerk/react": "catalog:"
"@clerk/shared": "catalog:"
"@effect/atom-react": "catalog:"
- "@effect/platform-bun": "catalog:"
"@effect/platform-node": "catalog:"
"@effect/platform-node-shared": "catalog:"
"@effect/sql-pg": "catalog:"
- "@effect/sql-sqlite-bun": "catalog:"
"@effect/vitest": "catalog:"
"@effect/vitest>vitest": "-"
"@expo/dom-webview": 57.0.1
diff --git a/scripts/lib/cli-external-packages.test.ts b/scripts/lib/cli-external-packages.test.ts
index e894359eccb..775c77fef1d 100644
--- a/scripts/lib/cli-external-packages.test.ts
+++ b/scripts/lib/cli-external-packages.test.ts
@@ -11,6 +11,7 @@ import serverPackageJson from "../../apps/server/package.json" with { type: "jso
import {
CLI_RUNTIME_EXTERNAL_PREFIXES,
+ findEsmImportsOfExternalPackages,
findInlinedExternalPackages,
selectCliRuntimeExternalDependencies,
shouldBundleCliDependency,
@@ -55,11 +56,6 @@ describe("shouldBundleCliDependency", () => {
}
});
- it("leaves bun-only entry points external", () => {
- assert.strictEqual(shouldBundleCliDependency("@effect/platform-bun"), false);
- assert.strictEqual(shouldBundleCliDependency("@effect/sql-sqlite-bun"), false);
- });
-
// The real package is `node-gyp-build-optional-packages`, reached by prefix.
// It is transitive to a selected dependency root, so the runtime closure test
// below ensures it follows that root into the sidecar.
@@ -72,7 +68,6 @@ describe("selectCliRuntimeExternalDependencies", () => {
it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
assert.deepStrictEqual(
selectCliRuntimeExternalDependencies({
- "@effect/platform-bun": "1.0.0",
"@ff-labs/fff-node": "2.0.0",
effect: "3.0.0",
"node-pty": "4.0.0",
@@ -281,3 +276,41 @@ var x = 1;
assert.deepStrictEqual(result.inlined, []);
});
});
+
+// The single-executable build can only `import` built-ins. A file-backed
+// import of an external package passes every bundler check and the regular
+// `node dist/bin.mjs` path, then fails inside the executable, so the scan
+// reads the emitted module graph instead.
+describe("findEsmImportsOfExternalPackages", () => {
+ it("flags static and dynamic imports of file-backed packages", () => {
+ const source = [
+ 'import { FileFinder } from "@ff-labs/fff-node";',
+ 'import * as fs from "fs";',
+ 'import { createRequire } from "node:module";',
+ 'const pty = () => import("node-pty");',
+ 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
+ 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
+ 'const local = () => import("./chunk-abc.mjs");',
+ ].join("\n");
+
+ assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
+ "@ff-labs/fff-bin-linux-x64-gnu",
+ "@ff-labs/fff-node",
+ "ffi-rs",
+ "node-pty",
+ ]);
+ });
+
+ it("flags side-effect imports and re-exports too", () => {
+ const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
+ assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
+ "ffi-rs",
+ "msgpackr-extract",
+ ]);
+ });
+
+ it("does not mistake createRequire calls for imports", () => {
+ const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
+ assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
+ });
+});
diff --git a/scripts/lib/cli-external-packages.ts b/scripts/lib/cli-external-packages.ts
index d7a89bc408a..254ce3dc271 100644
--- a/scripts/lib/cli-external-packages.ts
+++ b/scripts/lib/cli-external-packages.ts
@@ -1,3 +1,6 @@
+// @effect-diagnostics nodeBuiltinImport:off
+import * as NodeModule from "node:module";
+
/**
* The single source of truth for packages the server CLI bundle must NOT inline.
*
@@ -50,24 +53,6 @@ export const CLI_RUNTIME_EXTERNAL_PREFIXES = [
"utf-8-validate",
] as const;
-/**
- * External only so the bundler never has to resolve them.
- *
- * These are reached through a runtime-conditional dynamic import that Node
- * never takes, and they resolve `bun:*` specifiers that do not exist when
- * bundling for Node. Because Node never loads them, their dependency closure
- * does not need to be external — only the entry point must stay unbundled.
- */
-export const CLI_BUILD_ONLY_EXTERNAL_PREFIXES = [
- "@effect/platform-bun",
- "@effect/sql-sqlite-bun",
-] as const;
-
-export const CLI_EXTERNAL_PACKAGE_PREFIXES = [
- ...CLI_RUNTIME_EXTERNAL_PREFIXES,
- ...CLI_BUILD_ONLY_EXTERNAL_PREFIXES,
-] as const;
-
export function isRuntimeExternalCliDependency(id: string): boolean {
return CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => id.startsWith(prefix));
}
@@ -83,7 +68,7 @@ export function isRuntimeExternalCliDependency(id: string): boolean {
* inlined while node-pty (a declared dependency) stayed external.
*/
export function isExternalCliDependency(id: string): boolean {
- return CLI_EXTERNAL_PACKAGE_PREFIXES.some((prefix) => id.startsWith(prefix));
+ return isRuntimeExternalCliDependency(id);
}
/** True when the CLI bundle should inline `id` rather than leave it external. */
@@ -101,6 +86,40 @@ export function selectCliRuntimeExternalDependencies(
);
}
+/**
+ * Scan an emitted bundle chunk for ESM imports of packages that are not Node
+ * built-ins.
+ *
+ * Inside a Node single-executable, `import` statements and `import()` can only
+ * resolve built-in modules; any file-backed specifier throws at module
+ * evaluation (static) or at first use (dynamic). External packages therefore
+ * have to be reached through `createRequire`, which reads the real filesystem
+ * in every runtime. The bundler cannot enforce this, so the check reads what it
+ * produced.
+ */
+export function findEsmImportsOfExternalPackages(source: string): ReadonlyArray<string> {
+ const specifiers = new Set<string>();
+ // `import x from`, `import "side-effect"`, `export ... from`, and `import()`
+ // all resolve through the module loader.
+ const patterns = [
+ /^import\s[^;]*?\sfrom\s+["']([^"']+)["']/gm,
+ /^import\s+["']([^"']+)["']/gm,
+ /^export\s[^;]*?\sfrom\s+["']([^"']+)["']/gm,
+ // Rolldown may leave a `/* @vite-ignore */` style comment before the specifier.
+ /\bimport\(\s*(?:\/\*[\s\S]*?\*\/\s*)*["']([^"']+)["']\s*[,)]/g,
+ ];
+ for (const pattern of patterns) {
+ for (const match of source.matchAll(pattern)) {
+ const specifier = match[1];
+ if (specifier === undefined) continue;
+ if (NodeModule.isBuiltin(specifier)) continue;
+ if (specifier.startsWith("./") || specifier.startsWith("../")) continue;
+ specifiers.add(specifier);
+ }
+ }
+ return [...specifiers].sort();
+}
+
/**
* Scan an emitted bundle chunk for runtime-external packages that were inlined.
*