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