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 if (yield* fs.exists(webDist)) {
184 yield* fs.copy(webDist, clientTarget);
185 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
186 yield* Effect.log("[cli] Bundled web app into dist/client");
187 } else {
188 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
189 }
190 }),
191).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
192
193// ---------------------------------------------------------------------------
194// publish subcommand
195// ---------------------------------------------------------------------------
196
197interface PublishCommandConfig {
198 readonly access: string;
199 readonly tag: string;
200 readonly provenance: boolean;
201 readonly dryRun: boolean;
202}
203
204const createVpPmPublishArgs = (config: PublishCommandConfig): ReadonlyArray<string> => {
205 const args = [
206 "publish",
207 "--filter",
208 "t3",
209 "--access",
210 config.access,
211 "--tag",
212 config.tag,
213 "--no-git-checks",
214 ];
215
216 if (config.provenance) args.push("--provenance");
217 if (config.dryRun) args.push("--dry-run");
218
219 return args;
220};
221
222const publishCmd = Command.make(
223 "publish",
224 {
225 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
226 access: Flag.string("access").pipe(Flag.withDefault("public")),
227 appVersion: Flag.string("app-version").pipe(Flag.optional),
228 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
229 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
230 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
231 },
232 (config) =>
233 Effect.gen(function* () {
234 const path = yield* Path.Path;
235 const fs = yield* FileSystem.FileSystem;
236 const repoRoot = yield* RepoRoot;
237 const serverDir = path.join(repoRoot, "apps/server");
238 const packageJsonPath = path.join(serverDir, "package.json");
239 const backupPath = `${packageJsonPath}.bak`;
240
241 // Assert build assets exist
242 for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
243 const abs = path.join(serverDir, relPath);
244 if (!(yield* fs.exists(abs))) {
245 return yield* new ServerCliBuildAssetMissingError({ assetPath: abs });
246 }
247 }
248
249 yield* Effect.acquireUseRelease(
250 // Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
251 Effect.gen(function* () {
252 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
253 const workspaceConfig = yield* readWorkspaceConfig();
254 const workspaceCatalog = workspaceConfig.catalog ?? {};
255 const workspaceOverrides = workspaceConfig.overrides ?? {};
256 const pkg: PackageJson = {
257 name: serverPackageJson.name,
258 repository: serverPackageJson.repository,
259 bin: serverPackageJson.bin,
260 type: serverPackageJson.type,
261 version,
262 engines: serverPackageJson.engines,
263 files: serverPackageJson.files,
264 dependencies: resolveCatalogDependencies(
265 serverPackageJson.dependencies,
266 workspaceCatalog,
267 "apps/server",
268 ),
269 overrides: resolveCatalogDependencies(
270 workspaceOverrides,
271 workspaceCatalog,
272 "apps/server",
273 ),
274 };
275
276 const original = yield* fs.readFileString(packageJsonPath);
277 const packageJsonString = yield* encodePackageJson(pkg);
278 yield* fs.writeFileString(backupPath, original);
279 yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
280 yield* Effect.log("[cli] Prepared package.json for publish");
281
282 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
283 return { iconBackups };
284 }),
285 // Use: pnpm publish from the workspace root so pnpm-only workspace
286 // config, including override selectors, is interpreted correctly.
287 () =>
288 Effect.gen(function* () {
289 const args = createVpPmPublishArgs(config);
290 const spawnCommand = yield* resolveSpawnCommand("vp", ["pm", ...args]);
291
292 yield* Effect.log(`[cli] Running: vp pm ${args.join(" ")}`);
293 yield* runCommand(
294 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
295 cwd: repoRoot,
296 stdout: config.verbose ? "inherit" : "ignore",
297 stderr: "inherit",
298 shell: spawnCommand.shell,
299 }),
300 );
301 }),
302 // Release: restore
303 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
304 Effect.gen(function* () {
305 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
306 Effect.catch((error) =>
307 Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
308 ),
309 );
310 yield* fs.rename(backupPath, packageJsonPath);
311 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
312 }),
313 );
314 }),
315).pipe(Command.withDescription("Publish the server package to npm."));
316
317// ---------------------------------------------------------------------------
318// root command
319// ---------------------------------------------------------------------------
320
321const cli = Command.make("cli").pipe(
322 Command.withDescription("T3 server build & publish CLI."),
323 Command.withSubcommands([buildCmd, publishCmd]),
324);
325
326Command.run(cli, { version: "0.0.0" }).pipe(
327 Effect.scoped,
328 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
329 NodeRuntime.runMain,
330);