Open History to see the last commit
1#!/usr/bin/env node
2import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import * as Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Logger from "effect/Logger";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import { Command, Flag } from "effect/unstable/cli";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12
13import {
14 DEVELOPMENT_ICON_OVERRIDES,
15 resolveWebAssetBrandForPackageVersion,
16 resolveWebIconOverrides,
17} from "../../../scripts/lib/brand-assets.ts";
18import { findEagerBunRuntimeImports } from "../../../scripts/lib/cli-external-packages.ts";
19import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
20import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
21import { fromYaml } from "@t3tools/shared/schemaYaml";
22import { resolveSpawnCommand } from "@t3tools/shared/shell";
23import serverPackageJson from "../package.json" with { type: "json" };
24import {
25 ServerCliBuildAssetMissingError,
26 ServerCliCommandExitError,
27 ServerCliDevelopmentIconSourceMissingError,
28 ServerCliEagerBunImportError,
29 ServerCliDevelopmentIconTargetMissingError,
30 ServerCliPublishIconSourceMissingError,
31 ServerCliPublishIconTargetMissingError,
32} from "./cliErrors.ts";
33
34interface PackageJson {
35 name: string;
36 repository: {
37 type: string;
38 url: string;
39 directory: string;
40 };
41 bin: Record<string, string>;
42 type: string;
43 version: string;
44 engines: Record<string, string>;
45 files: string[];
46 dependencies: Record<string, string>;
47 overrides: Record<string, string>;
48}
49
50const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
51const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
52
53const WorkspaceConfig = Schema.Struct({
54 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
55 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
56});
57type WorkspaceConfig = typeof WorkspaceConfig.Type;
58const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
59
60const RepoRoot = Effect.service(Path.Path).pipe(
61 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
62);
63
64const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
65 const path = yield* Path.Path;
66 const fs = yield* FileSystem.FileSystem;
67 const repoRoot = yield* RepoRoot;
68 const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
69 return yield* decodeWorkspaceConfig(workspaceYaml);
70});
71
72const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
73 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
74 const child = yield* spawner.spawn(command);
75 const exitCode = yield* child.exitCode;
76
77 if (exitCode !== 0) {
78 return yield* new ServerCliCommandExitError({
79 command: command.command,
80 args: command.args,
81 cwd: command.options.cwd,
82 exitCode,
83 });
84 }
85});
86
87const preparePublishIcons = Effect.fn("preparePublishIcons")(function* (
88 repoRoot: string,
89 serverDir: string,
90 version: string,
91) {
92 const path = yield* Path.Path;
93 const fs = yield* FileSystem.FileSystem;
94 const brand = resolveWebAssetBrandForPackageVersion(version);
95 const icons = resolveWebIconOverrides(brand, "dist/client").map((override) => ({
96 sourcePath: path.join(repoRoot, override.sourceRelativePath),
97 targetPath: path.join(serverDir, override.targetRelativePath),
98 }));
99
100 for (const icon of icons) {
101 if (!(yield* fs.exists(icon.sourcePath))) {
102 return yield* new ServerCliPublishIconSourceMissingError({ sourcePath: icon.sourcePath });
103 }
104 if (!(yield* fs.exists(icon.targetPath))) {
105 return yield* new ServerCliPublishIconTargetMissingError({ targetPath: icon.targetPath });
106 }
107 }
108
109 return yield* Effect.forEach(icons, (icon) =>
110 Effect.all({
111 original: fs.readFile(icon.targetPath),
112 publish: fs.readFile(icon.sourcePath),
113 }).pipe(Effect.map((contents) => ({ ...icon, ...contents }))),
114 );
115});
116
117const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
118 repoRoot: string,
119 serverDir: string,
120) {
121 const path = yield* Path.Path;
122 const fs = yield* FileSystem.FileSystem;
123
124 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
125 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
126 const targetPath = path.join(serverDir, override.targetRelativePath);
127
128 if (!(yield* fs.exists(sourcePath))) {
129 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
130 }
131 if (!(yield* fs.exists(targetPath))) {
132 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
133 }
134
135 yield* fs.copyFile(sourcePath, targetPath);
136 }
137
138 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
139});
140
141// ---------------------------------------------------------------------------
142// build subcommand
143// ---------------------------------------------------------------------------
144
145/**
146 * Fail the build if a chunk Node loads eagerly imports a Bun module.
147 *
148 * `@effect/platform-bun` and `@effect/sql-sqlite-bun` are inlined so that a
149 * Bun-hosted server shares the bundle's single `effect` instance — two
150 * instances silently broke CORS, compression and auth headers, because Effect
151 * keys per-request pre-response handlers off a module-level WeakMap. Inlining
152 * them also pulls `bun:sqlite` into the bundle, which is only safe while it
153 * sits in a chunk reached solely through `import()`.
154 *
155 * Rolldown merges a dynamic import into its importer's chunk with only an
156 * INEFFECTIVE_DYNAMIC_IMPORT warning and exit 0, so read the artifact instead
157 * of trusting the build to fail. This runs on every PR through
158 * `vp run build:desktop`, unlike the desktop self-containment probe.
159 */
160const assertNoEagerBunImports = Effect.fn("assertNoEagerBunImports")(function* (distDir: string) {
161 const path = yield* Path.Path;
162 const fs = yield* FileSystem.FileSystem;
163
164 const chunks = new Map<string, string>();
165 for (const name of yield* fs.readDirectory(distDir)) {
166 if (!name.endsWith(".mjs")) continue;
167 chunks.set(name, yield* fs.readFileString(path.join(distDir, name)));
168 }
169
170 // Both entries are packed separately into the same flat directory, so each
171 // owns a graph that has to be walked.
172 const entryChunks = ["bin.mjs", "service-launcher.mjs"];
173 for (const entry of entryChunks) {
174 if (!chunks.has(entry)) {
175 return yield* new ServerCliBuildAssetMissingError({ assetPath: path.join(distDir, entry) });
176 }
177 }
178
179 const { reachable, violations } = findEagerBunRuntimeImports(chunks, entryChunks);
180 if (violations.length > 0) {
181 return yield* new ServerCliEagerBunImportError({
182 imports: violations.map(({ chunk, specifier }) => `${chunk} -> ${specifier}`),
183 eagerChunkCount: reachable.length,
184 });
185 }
186
187 yield* Effect.log(
188 `[cli] Verified ${reachable.length} eagerly loaded chunks import no Bun modules`,
189 );
190});
191
192const buildCmd = Command.make(
193 "build",
194 {
195 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
196 },
197 (config) =>
198 Effect.gen(function* () {
199 const path = yield* Path.Path;
200 const fs = yield* FileSystem.FileSystem;
201 const repoRoot = yield* RepoRoot;
202 const serverDir = path.join(repoRoot, "apps/server");
203
204 yield* Effect.log("[cli] Running tsdown...");
205 yield* runCommand(
206 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
207 cwd: serverDir,
208 stdout: config.verbose ? "inherit" : "ignore",
209 stderr: "inherit",
210 shell: false,
211 }),
212 );
213
214 yield* assertNoEagerBunImports(path.join(serverDir, "dist"));
215
216 const webDist = path.join(repoRoot, "apps/web/dist");
217 const clientTarget = path.join(serverDir, "dist/client");
218
219 if (yield* fs.exists(webDist)) {
220 yield* fs.copy(webDist, clientTarget);
221 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
222 yield* Effect.log("[cli] Bundled web app into dist/client");
223 } else {
224 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
225 }
226 }),
227).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
228
229// ---------------------------------------------------------------------------
230// publish subcommand
231// ---------------------------------------------------------------------------
232
233interface PublishCommandConfig {
234 readonly access: string;
235 readonly tag: string;
236 readonly provenance: boolean;
237 readonly dryRun: boolean;
238}
239
240const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
241 const args = [
242 "publish",
243 "--filter",
244 "t3",
245 "--access",
246 config.access,
247 "--tag",
248 config.tag,
249 "--no-git-checks",
250 ];
251
252 if (config.provenance) args.push("--provenance");
253 if (config.dryRun) args.push("--dry-run");
254
255 return args;
256};
257
258const publishCmd = Command.make(
259 "publish",
260 {
261 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
262 access: Flag.string("access").pipe(Flag.withDefault("public")),
263 appVersion: Flag.string("app-version").pipe(Flag.optional),
264 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
265 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
266 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
267 },
268 (config) =>
269 Effect.gen(function* () {
270 const path = yield* Path.Path;
271 const fs = yield* FileSystem.FileSystem;
272 const repoRoot = yield* RepoRoot;
273 const serverDir = path.join(repoRoot, "apps/server");
274 const packageJsonPath = path.join(serverDir, "package.json");
275
276 // Assert build assets exist
277 for (const relPath of [
278 "dist/bin.mjs",
279 "dist/service-launcher.mjs",
280 "dist/client/index.html",
281 ]) {
282 const abs = path.join(serverDir, relPath);
283 if (!(yield* fs.exists(abs))) {
284 return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
285 }
286 }
287
288 yield* Effect.acquireUseRelease(
289 // Acquire: resolve publish metadata and read every original before mutation.
290 Effect.gen(function* () {
291 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
292 const workspaceConfig = yield* readWorkspaceConfig();
293 const workspaceCatalog = workspaceConfig.catalog ?? {};
294 const workspaceOverrides = workspaceConfig.overrides ?? {};
295 const pkg: PackageJson = {
296 name: serverPackageJson.name,
297 repository: serverPackageJson.repository,
298 bin: serverPackageJson.bin,
299 type: serverPackageJson.type,
300 version,
301 engines: serverPackageJson.engines,
302 files: serverPackageJson.files,
303 dependencies: resolveCatalogDependencies(
304 serverPackageJson.dependencies,
305 workspaceCatalog,
306 "apps/server",
307 ),
308 overrides: resolveCatalogDependencies(
309 workspaceOverrides,
310 workspaceCatalog,
311 "apps/server",
312 ),
313 };
314
315 return {
316 packageJsonString: yield* encodePackageJson(pkg),
317 originalPackageJson: yield* fs.readFile(packageJsonPath),
318 icons: yield* preparePublishIcons(repoRoot, serverDir, version),
319 };
320 }),
321 // Use: pnpm publish from the workspace root so pnpm-only workspace
322 // config, including override selectors, is interpreted correctly.
323 (resource) =>
324 Effect.gen(function* () {
325 yield* fs.writeFileString(packageJsonPath, `${resource.packageJsonString}\n`);
326 for (const icon of resource.icons) {
327 yield* fs.writeFile(icon.targetPath, icon.publish);
328 }
329 yield* Effect.log("[cli] Applied package metadata and publish icon overrides");
330
331 const args = createVpPmPublishArgs(config);
332 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
333
334 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
335 yield* runCommand(
336 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
337 cwd: repoRoot,
338 stdout: config.verbose ? "inherit" : "ignore",
339 stderr: "inherit",
340 shell: spawnCommand.shell,
341 }),
342 );
343 }),
344 // Release: restore every file even if applying overrides or publishing fails.
345 (resource) =>
346 Effect.gen(function* () {
347 yield* fs.writeFile(packageJsonPath, resource.originalPackageJson);
348 for (const icon of resource.icons) {
349 yield* fs.writeFile(icon.targetPath, icon.original);
350 }
351 if (config.verbose) yield* Effect.log("[cli] Restored original publish assets");
352 }),
353 );
354 }),
355).pipe(Command.withDescription("Publish the server package to npm."));
356
357// ---------------------------------------------------------------------------
358// root command
359// ---------------------------------------------------------------------------
360
361const cli = Command.make("cli").pipe(
362 Command.withDescription("T3 server build & publish CLI."),
363 Command.withSubcommands([buildCmd, publishCmd]),
364);
365
366Command.run(cli, { version: "0.0.0" }).pipe(
367 Effect.scoped,
368 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
369 NodeRuntime.runMain,
370);