Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
6import { Command, Flag } from "effect/unstable/cli";
7import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
8
9import {
10 DEVELOPMENT_ICON_OVERRIDES,
11 PUBLISH_ICON_OVERRIDES,
12} from "../../../scripts/lib/brand-assets.ts";
13import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
14import rootPackageJson from "../../../package.json" with { type: "json" };
15import serverPackageJson from "../package.json" with { type: "json" };
16
17interface PackageJson {
18 name: string;
19 repository: {
20 type: string;
21 url: string;
22 directory: string;
23 };
24 bin: Record<string, string>;
25 type: string;
26 version: string;
27 engines: Record<string, string>;
28 files: string[];
29 dependencies: Record<string, string>;
30 overrides: Record<string, string>;
31}
32
33class CliError extends Data.TaggedError("CliError")<{
34 readonly message: string;
35 readonly cause?: unknown;
36}> {}
37
38const RepoRoot = Effect.service(Path.Path).pipe(
39 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
40);
41
42const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
43 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
44 const child = yield* spawner.spawn(command);
45 const exitCode = yield* child.exitCode;
46
47 if (exitCode !== 0) {
48 return yield* new CliError({
49 message: `Command exited with non-zero exit code (${exitCode})`,
50 });
51 }
52});
53
54interface PublishIconBackup {
55 readonly targetPath: string;
56 readonly backupPath: string;
57}
58
59const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
60 repoRoot: string,
61 serverDir: string,
62) {
63 const path = yield* Path.Path;
64 const fs = yield* FileSystem.FileSystem;
65 const backups: PublishIconBackup[] = [];
66
67 for (const override of PUBLISH_ICON_OVERRIDES) {
68 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
69 const targetPath = path.join(serverDir, override.targetRelativePath);
70 const backupPath = `${targetPath}.publish-bak`;
71
72 if (!(yield* fs.exists(sourcePath))) {
73 return yield* new CliError({
74 message: `Missing publish icon source: ${sourcePath}`,
75 });
76 }
77 if (!(yield* fs.exists(targetPath))) {
78 return yield* new CliError({
79 message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
80 });
81 }
82
83 yield* fs.copyFile(targetPath, backupPath);
84 yield* fs.copyFile(sourcePath, targetPath);
85 backups.push({ targetPath, backupPath });
86 }
87
88 yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
89 return backups as ReadonlyArray<PublishIconBackup>;
90});
91
92const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
93 backups: ReadonlyArray<PublishIconBackup>,
94) {
95 const fs = yield* FileSystem.FileSystem;
96 for (const backup of backups) {
97 if (!(yield* fs.exists(backup.backupPath))) {
98 continue;
99 }
100 yield* fs.rename(backup.backupPath, backup.targetPath);
101 }
102});
103
104const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
105 repoRoot: string,
106 serverDir: string,
107) {
108 const path = yield* Path.Path;
109 const fs = yield* FileSystem.FileSystem;
110
111 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
112 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
113 const targetPath = path.join(serverDir, override.targetRelativePath);
114
115 if (!(yield* fs.exists(sourcePath))) {
116 return yield* new CliError({
117 message: `Missing development icon source: ${sourcePath}`,
118 });
119 }
120 if (!(yield* fs.exists(targetPath))) {
121 return yield* new CliError({
122 message: `Missing development icon target: ${targetPath}. Build web first.`,
123 });
124 }
125
126 yield* fs.copyFile(sourcePath, targetPath);
127 }
128
129 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
130});
131
132// ---------------------------------------------------------------------------
133// build subcommand
134// ---------------------------------------------------------------------------
135
136const buildCmd = Command.make(
137 "build",
138 {
139 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
140 },
141 (config) =>
142 Effect.gen(function* () {
143 const path = yield* Path.Path;
144 const fs = yield* FileSystem.FileSystem;
145 const repoRoot = yield* RepoRoot;
146 const serverDir = path.join(repoRoot, "apps/server");
147
148 yield* Effect.log("[cli] Running tsdown...");
149 yield* runCommand(
150 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
151 cwd: serverDir,
152 stdout: config.verbose ? "inherit" : "ignore",
153 stderr: "inherit",
154 // Windows needs shell mode to resolve `.cmd` shims on PATH.
155 shell: process.platform === "win32",
156 }),
157 );
158
159 const webDist = path.join(repoRoot, "apps/web/dist");
160 const clientTarget = path.join(serverDir, "dist/client");
161
162 if (yield* fs.exists(webDist)) {
163 yield* fs.copy(webDist, clientTarget);
164 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
165 yield* Effect.log("[cli] Bundled web app into dist/client");
166 } else {
167 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
168 }
169 }),
170).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
171
172// ---------------------------------------------------------------------------
173// publish subcommand
174// ---------------------------------------------------------------------------
175
176const publishCmd = Command.make(
177 "publish",
178 {
179 tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
180 access: Flag.string("access").pipe(Flag.withDefault("public")),
181 appVersion: Flag.string("app-version").pipe(Flag.optional),
182 provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
183 dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
184 verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
185 },
186 (config) =>
187 Effect.gen(function* () {
188 const path = yield* Path.Path;
189 const fs = yield* FileSystem.FileSystem;
190 const repoRoot = yield* RepoRoot;
191 const serverDir = path.join(repoRoot, "apps/server");
192 const packageJsonPath = path.join(serverDir, "package.json");
193 const backupPath = `${packageJsonPath}.bak`;
194
195 // Assert build assets exist
196 for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
197 const abs = path.join(serverDir, relPath);
198 if (!(yield* fs.exists(abs))) {
199 return yield* new CliError({
200 message: `Missing build asset: ${abs}. Run the build subcommand first.`,
201 });
202 }
203 }
204
205 yield* Effect.acquireUseRelease(
206 // Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
207 Effect.gen(function* () {
208 const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
209 const pkg: PackageJson = {
210 name: serverPackageJson.name,
211 repository: serverPackageJson.repository,
212 bin: serverPackageJson.bin,
213 type: serverPackageJson.type,
214 version,
215 engines: serverPackageJson.engines,
216 files: serverPackageJson.files,
217 dependencies: resolveCatalogDependencies(
218 serverPackageJson.dependencies,
219 rootPackageJson.workspaces.catalog,
220 "apps/server",
221 ),
222 overrides: resolveCatalogDependencies(
223 rootPackageJson.overrides,
224 rootPackageJson.workspaces.catalog,
225 "apps/server",
226 ),
227 };
228
229 const original = yield* fs.readFileString(packageJsonPath);
230 yield* fs.writeFileString(backupPath, original);
231 yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
232 yield* Effect.log("[cli] Prepared package.json for publish");
233
234 const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
235 return { iconBackups };
236 }),
237 // Use: npm publish
238 () =>
239 Effect.gen(function* () {
240 const args = ["publish", "--access", config.access, "--tag", config.tag];
241 if (config.provenance) args.push("--provenance");
242 if (config.dryRun) args.push("--dry-run");
243
244 yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
245 yield* runCommand(
246 ChildProcess.make("npm", [...args], {
247 cwd: serverDir,
248 stdout: config.verbose ? "inherit" : "ignore",
249 stderr: "inherit",
250 // Windows needs shell mode to resolve .cmd shims.
251 shell: process.platform === "win32",
252 }),
253 );
254 }),
255 // Release: restore
256 (resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
257 Effect.gen(function* () {
258 yield* restorePublishIconOverrides(resource.iconBackups).pipe(
259 Effect.catch((error) =>
260 Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
261 ),
262 );
263 yield* fs.rename(backupPath, packageJsonPath);
264 if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
265 }),
266 );
267 }),
268).pipe(Command.withDescription("Publish the server package to npm."));
269
270// ---------------------------------------------------------------------------
271// root command
272// ---------------------------------------------------------------------------
273
274const cli = Command.make("cli").pipe(
275 Command.withDescription("T3 server build & publish CLI."),
276 Command.withSubcommands([buildCmd, publishCmd]),
277);
278
279Command.run(cli, { version: "0.0.0" }).pipe(
280 Effect.scoped,
281 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
282 NodeRuntime.runMain,
283);