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

cli.ts

209 lines7.9 KB

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 { Command, Flag } from "effect/cli";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11​
12import { DEVELOPMENT_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
13import { findEsmImportsOfExternalPackages } from "../../../scripts/lib/cli-executable-imports.ts";
14import rootPackageJson from "../../../package.json" with { type: "json" };
15import { resolveSpawnCommand } from "@t3tools/shared/shell";
16import {
17 ServerCliBuildAssetMissingError,
18 ServerCliCommandExitError,
19 ServerCliDevelopmentIconSourceMissingError,
20 ServerCliDevelopmentIconTargetMissingError,
21 ServerCliExecutableImportError,
22} from "./cliErrors.ts";
23​
24const RepoRoot = Effect.service(Path.Path).pipe(
25 Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
26);
27​
28const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.StandardCommand) {
29 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
30 const child = yield* spawner.spawn(command);
31 const exitCode = yield* child.exitCode;
32​
33 if (exitCode !== 0) {
34 return yield* new ServerCliCommandExitError({
35 command: command.command,
36 args: command.args,
37 cwd: command.options.cwd,
38 exitCode,
39 });
40 }
41});
42​
43const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
44 repoRoot: string,
45 serverDir: string,
46) {
47 const path = yield* Path.Path;
48 const fs = yield* FileSystem.FileSystem;
49​
50 for (const override of DEVELOPMENT_ICON_OVERRIDES) {
51 const sourcePath = path.join(repoRoot, override.sourceRelativePath);
52 const targetPath = path.join(serverDir, override.targetRelativePath);
53​
54 if (!(yield* fs.exists(sourcePath))) {
55 return yield* new ServerCliDevelopmentIconSourceMissingError({ sourcePath });
56 }
57 if (!(yield* fs.exists(targetPath))) {
58 return yield* new ServerCliDevelopmentIconTargetMissingError({ targetPath });
59 }
60​
61 yield* fs.copyFile(sourcePath, targetPath);
62 }
63​
64 yield* Effect.log("[cli] Applied development icon overrides to dist/client");
65});
66​
67const buildCmd = Command.make(
68 "build",
69 {
70 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
71 },
72 (config) =>
73 Effect.gen(function* () {
74 const path = yield* Path.Path;
75 const fs = yield* FileSystem.FileSystem;
76 const repoRoot = yield* RepoRoot;
77 const serverDir = path.join(repoRoot, "apps/server");
78​
79 yield* Effect.log("[cli] Running tsdown...");
80 yield* runCommand(
81 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
82 cwd: serverDir,
83 stdout: config.verbose ? "inherit" : "ignore",
84 stderr: "inherit",
85 shell: false,
86 }),
87 );
88​
89 const webDist = path.join(repoRoot, "apps/web/dist");
90 const clientTarget = path.join(serverDir, "dist/client");
91​
92 if (yield* fs.exists(webDist)) {
93 yield* fs.copy(webDist, clientTarget);
94 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
95 yield* Effect.log("[cli] Bundled web app into dist/client");
96 } else {
97 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
98 }
99 }),
100).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
101​
102const buildExeCmd = Command.make(
103 "build-exe",
104 {
105 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
106 target: Flag.String("target").pipe(
107 Flag.withDescription(
108 "Cross-build for <platform>-<arch> in nodejs.org naming (for example darwin-x64); defaults to the host.",
109 ),
110 Flag.optional,
111 ),
112 },
113 (config) =>
114 Effect.gen(function* () {
115 const path = yield* Path.Path;
116 const fs = yield* FileSystem.FileSystem;
117 const repoRoot = yield* RepoRoot;
118 const serverDir = path.join(repoRoot, "apps/server");
119​
120 yield* Effect.log("[cli] Building single-executable...");
121 const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
122 yield* runCommand(
123 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
124 cwd: serverDir,
125 env: {
126 ...process.env,
127 T3CODE_PACK_EXE: "1",
128 ...Option.match(config.target, {
129 onNone: () => ({}),
130 onSome: (target) => ({ T3CODE_PACK_EXE_TARGET: target }),
131 }),
132 },
133 stdout: config.verbose ? "inherit" : "ignore",
134 stderr: "inherit",
135 shell: spawnCommand.shell,
136 }),
137 );
138​
139 // The executable can only `import` built-ins. A file-backed import
140 // passes the bundler and `node dist/bin.mjs`, then throws inside the
141 // binary, so read the emitted module graph rather than trusting config.
142 const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
143 const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
144 if (specifiers.length > 0) {
145 return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
146 }
147 yield* Effect.log(
148 "[cli] Built dist-exe/t3 (expects client/, resource-monitor/, and the runtime-external node_modules beside it; scripts/build-cli-archive.ts assembles that tree)",
149 );
150 }),
151).pipe(
152 Command.withDescription(
153 `Build the server as a Node single-executable. Native builds require Node ${rootPackageJson.engines.node}; explicit cross-target builds need a Node 25.7+ host for --build-sea. The binary still resolves native packages from a node_modules tree beside it.`,
154 ),
155);
156​
157/**
158 * Publishes the `t3.tgz` launcher scripts/build-npm-launcher.ts produced. The
159 * launcher downloads its executable from the GitHub Release, so the release
160 * workflow runs this only after that release is published.
161 */
162const publishCmd = Command.make(
163 "publish",
164 {
165 packagesDir: Flag.String("packages-dir").pipe(
166 Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
167 ),
168 tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
169 access: Flag.String("access").pipe(Flag.withDefault("public")),
170 provenance: Flag.Boolean("provenance").pipe(Flag.withDefault(false)),
171 dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
172 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
173 },
174 (config) =>
175 Effect.gen(function* () {
176 const path = yield* Path.Path;
177 const fs = yield* FileSystem.FileSystem;
178 const packagesDir = path.resolve(config.packagesDir);
179 const launcherTarball = path.join(packagesDir, "t3.tgz");
180 if (!(yield* fs.exists(launcherTarball))) {
181 return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
182 }
183​
184 const args = ["publish", "--access", config.access, "--tag", config.tag];
185 if (config.provenance) args.push("--provenance");
186 if (config.dryRun) args.push("--dry-run");
187 const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
188 yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
189 yield* runCommand(
190 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
191 cwd: packagesDir,
192 stdout: config.verbose ? "inherit" : "ignore",
193 stderr: "inherit",
194 shell: spawnCommand.shell,
195 }),
196 );
197 }),
198).pipe(Command.withDescription("Publish the t3 launcher to npm."));
199​
200const cli = Command.make("cli").pipe(
201 Command.withDescription("T3 server build & publish CLI."),
202 Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
203);
204​
205Command.run(cli, { version: "0.0.0" }).pipe(
206 Effect.scoped,
207 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
208 NodeRuntime.runMain,
209);