Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli.ts

293 lines10.5 KB

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