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

cli.ts

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