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 PUBLISH_ICON_OVERRIDES,
16} from "../../../scripts/lib/brand-assets.ts";
17import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
18import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
19import { fromYaml } from "@t3tools/shared/schemaYaml";
20import { resolveSpawnCommand } from "@t3tools/shared/shell";
21import serverPackageJson from "../package.json" with { type: "json" };
22import {
23 ServerCliBuildAssetMissingError,
24 ServerCliCommandExitError,
25 ServerCliDevelopmentIconSourceMissingError,
26 ServerCliDevelopmentIconTargetMissingError,
27 ServerCliPublishIconSourceMissingError,
28 ServerCliPublishIconTargetMissingError,
29} from "./cliErrors.ts";
30
31interface PackageJson {
32 name: string;
33 repository: {
34 type: string;
35 url: string;
36 directory: string;
37 };
38 bin: Record<string, string>;
39 type: string;
40 version: string;
41 engines: Record<string, string>;
42 files: string[];
43 dependencies: Record<string, string>;
44 overrides: Record<string, string>;
45}
46
47const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
48const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
49
50const WorkspaceConfig = Schema.Struct({
51 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
52 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
53});
54type WorkspaceConfig = typeof WorkspaceConfig.Type;
55const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
56
57const RepoRoot = Effect.service(Path.Path).pipe(
58 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
59);
60
61const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
62 const path = yield* Path.Path;
63 const fs = yield* FileSystem.FileSystem;
64 const repoRoot = yield* RepoRoot;
65 const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
66 return yield* decodeWorkspaceConfig(workspaceYaml);
67});
68
69const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
70 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
71 const child = yield* spawner.spawn(command);
72 const exitCode = yield* child.exitCode;
73
74 if (exitCode !== 0) {
75 return yield* new ServerCliCommandExitError({
76 command: command.command,
77 args: command.args,
78 cwd: command.options.cwd,
79 exitCode,
80 });
81 }
82});
83
84interface PublishIconBackup {
85 readonly targetPath: string;
86 readonly backupPath: string;
87}
88
89const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
90 repoRoot: string,
91 serverDir: string,
92) {
93 const path = yield* Path.Path;
94 const fs = yield* FileSystem.FileSystem;
95 const backups: PublishIconBackup[] = [];
96
97 for (const override of PUBLISH_ICON_OVERRIDES) {
98 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
99 const targetPath = path.join(serverDir, override.targetRelativePath);
100 const backupPath = `${targetPath}.publish-bak`;
101
102 if (!(yield* fs.exists(sourcePath))) {
103 return yield* new ServerCliPublishIconSourceMissingError({ sourcePath });
104 }
105 if (!(yield* fs.exists(targetPath))) {
106 return yield* new ServerCliPublishIconTargetMissingError({ targetPath });
107 }
108
109 yield* fs.copyFile(targetPath, backupPath);
110 yield* fs.copyFile(sourcePath, targetPath);
111 backups.push({ targetPath, backupPath });
112 }
113
114 yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
115 return backups as ReadonlyArray<PublishIconBackup>;
116});
117
118const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
119 backups: ReadonlyArray<PublishIconBackup>,
120) {
121 const fs = yield* FileSystem.FileSystem;
122 for (const backup of backups) {
123 if (!(yield* fs.exists(backup.backupPath))) {
124 continue;
125 }
126 yield* fs.rename(backup.backupPath, backup.targetPath);
127 }
128});
129
130const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
131 repoRoot: string,
132 serverDir: string,
133) {
134 const path = yield* Path.Path;
135 const fs = yield* FileSystem.FileSystem;
136
137 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
138 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
139 const targetPath = path.join(serverDir, override.targetRelativePath);
140
141 if (!(yield* fs.exists(sourcePath))) {
142 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
143 }
144 if (!(yield* fs.exists(targetPath))) {
145 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
146 }
147
148 yield* fs.copyFile(sourcePath, targetPath);
149 }
150
151 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
152});
153
154// ---------------------------------------------------------------------------
155// build subcommand
156// ---------------------------------------------------------------------------
157
158const buildCmd = Command.make(
159 "build",
160 {
161 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
162 },
163 (config) =>
164 Effect.gen(function* () {
165 const path = yield* Path.Path;
166 const fs = yield* FileSystem.FileSystem;
167 const repoRoot = yield* RepoRoot;
168 const serverDir = path.join(repoRoot, "apps/server");
169
170 yield* Effect.log("[cli] Running tsdown...");
171 yield* runCommand(
172 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
173 cwd: serverDir,
174 stdout: config.verbose ? "inherit" : "ignore",
175 stderr: "inherit",
176 shell: false,
177 }),
178 );
179
180 const webDist = path.join(repoRoot, "apps/web/dist");
181 const clientTarget = path.join(serverDir, "dist/client");
182
183 // Pi loads the approval-gate extension at runtime; vp pack won't emit it, so copy it next to the bundle.
184 const piExtensionSource = path.join(serverDir, "src/provider/assets/pi/t3-approvals.ts");
185 const piAssetTargetDir = path.join(serverDir, "dist/assets/pi");
186 if (yield* fs.exists(piExtensionSource)) {
187 yield* fs.makeDirectory(piAssetTargetDir, { recursive: true });
188 yield* fs.copyFile(piExtensionSource, path.join(piAssetTargetDir, "t3-approvals.ts"));
189 yield* Effect.log("[cli] Bundled Pi approval extension into dist/assets/pi");
190 } else {
191 return yield* new ServerCliBuildAssetMissingError({ assetPath: piExtensionSource });
192 }
193
194 if (yield* fs.exists(webDist)) {
195 yield* fs.copy(webDist, clientTarget);
196 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
197 yield* Effect.log("[cli] Bundled web app into dist/client");
198 } else {
199 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
200 }
201 }),
202).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
203
204// ---------------------------------------------------------------------------
205// publish subcommand
206// ---------------------------------------------------------------------------
207
208interface PublishCommandConfig {
209 readonly access: string;
210 readonly tag: string;
211 readonly provenance: boolean;
212 readonly dryRun: boolean;
213}
214
215const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
216 const args = [
217 "publish",
218 "--filter",
219 "t3",
220 "--access",
221 config.access,
222 "--tag",
223 config.tag,
224 "--no-git-checks",
225 ];
226
227 if (config.provenance) args.push("--provenance");
228 if (config.dryRun) args.push("--dry-run");
229
230 return args;
231};
232
233const publishCmd = Command.make(
234 "publish",
235 {
236 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
237 access: Flag.string("access").pipe(Flag.withDefault("public")),
238 appVersion: Flag.string("app-version").pipe(Flag.optional),
239 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
240 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
241 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
242 },
243 (config) =>
244 Effect.gen(function* () {
245 const path = yield* Path.Path;
246 const fs = yield* FileSystem.FileSystem;
247 const repoRoot = yield* RepoRoot;
248 const serverDir = path.join(repoRoot, "apps/server");
249 const packageJsonPath = path.join(serverDir, "package.json");
250 const backupPath = `${packageJsonPath}.bak`;
251
252 // Assert build assets exist
253 for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
254 const abs = path.join(serverDir, relPath);
255 if (!(yield* fs.exists(abs))) {
256 return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
257 }
258 }
259
260 yield* Effect.acquireUseRelease(
261 // Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
262 Effect.gen(function* () {
263 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
264 const workspaceConfig = yield* readWorkspaceConfig();
265 const workspaceCatalog = workspaceConfig.catalog ?? {};
266 const workspaceOverrides = workspaceConfig.overrides ?? {};
267 const pkg: PackageJson = {
268 name: serverPackageJson.name,
269 repository: serverPackageJson.repository,
270 bin: serverPackageJson.bin,
271 type: serverPackageJson.type,
272 version,
273 engines: serverPackageJson.engines,
274 files: serverPackageJson.files,
275 dependencies: resolveCatalogDependencies(
276 serverPackageJson.dependencies,
277 workspaceCatalog,
278 "apps/server",
279 ),
280 overrides: resolveCatalogDependencies(
281 workspaceOverrides,
282 workspaceCatalog,
283 "apps/server",
284 ),
285 };
286
287 const original = yield* fs.readFileString(packageJsonPath);
288 const packageJsonString = yield* encodePackageJson(pkg);
289 yield* fs.writeFileString(backupPath, original);
290 yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
291 yield* Effect.log("[cli] Prepared package.json for publish");
292
293 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
294 return { iconBackups };
295 }),
296 // Use: pnpm publish from the workspace root so pnpm-only workspace
297 // config, including override selectors, is interpreted correctly.
298 () =>
299 Effect.gen(function* () {
300 const args = createVpPmPublishArgs(config);
301 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
302
303 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
304 yield* runCommand(
305 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
306 cwd: repoRoot,
307 stdout: config.verbose ? "inherit" : "ignore",
308 stderr: "inherit",
309 shell: spawnCommand.shell,
310 }),
311 );
312 }),
313 // Release: restore
314 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
315 Effect.gen(function* () {
316 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
317 Effect.catch((error) =>
318 Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
319 ),
320 );
321 yield* fs.rename(backupPath, packageJsonPath);
322 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
323 }),
324 );
325 }),
326).pipe(Command.withDescription("Publish the server package to npm."));
327
328// ---------------------------------------------------------------------------
329// root command
330// ---------------------------------------------------------------------------
331
332const cli = Command.make("cli").pipe(
333 Command.withDescription("T3 server build & publish CLI."),
334 Command.withSubcommands([buildCmd, publishCmd]),
335);
336
337Command.run(cli, { version: "0.0.0" }).pipe(
338 Effect.scoped,
339 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
340 NodeRuntime.runMain,
341);