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/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 { 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
66const buildCmd = Command.make(
67 "build",
68 {
69 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
70 },
71 (config) =>
72 Effect.gen(function* () {
73 const path = yield* Path.Path;
74 const fs = yield* FileSystem.FileSystem;
75 const repoRoot = yield* RepoRoot;
76 const serverDir = path.join(repoRoot, "apps/server");
77
78 yield* Effect.log("[cli] Running tsdown...");
79 yield* runCommand(
80 ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
81 cwd: serverDir,
82 stdout: config.verbose ? "inherit" : "ignore",
83 stderr: "inherit",
84 shell: false,
85 }),
86 );
87
88 const webDist = path.join(repoRoot, "apps/web/dist");
89 const clientTarget = path.join(serverDir, "dist/client");
90
91 if (yield* fs.exists(webDist)) {
92 yield* fs.copy(webDist, clientTarget);
93 yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
94 yield* Effect.log("[cli] Bundled web app into dist/client");
95 } else {
96 yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
97 }
98 }),
99).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
100
101const buildExeCmd = Command.make(
102 "build-exe",
103 {
104 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
105 target: Flag.String("target").pipe(
106 Flag.withDescription(
107 "Cross-build for <platform>-<arch> in nodejs.org naming (for example darwin-x64); defaults to the host.",
108 ),
109 Flag.optional,
110 ),
111 },
112 (config) =>
113 Effect.gen(function* () {
114 const path = yield* Path.Path;
115 const fs = yield* FileSystem.FileSystem;
116 const repoRoot = yield* RepoRoot;
117 const serverDir = path.join(repoRoot, "apps/server");
118
119 yield* Effect.log("[cli] Building single-executable...");
120 const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]);
121 yield* runCommand(
122 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
123 cwd: serverDir,
124 env: {
125 ...process.env,
126 T3CODE_PACK_EXE: "1",
127 ...Option.match(config.target, {
128 onNone: () => ({}),
129 onSome: (target) => ({ T3CODE_PACK_EXE_TARGET: target }),
130 }),
131 },
132 stdout: config.verbose ? "inherit" : "ignore",
133 stderr: "inherit",
134 shell: spawnCommand.shell,
135 }),
136 );
137
138 // The executable can only `import` built-ins. A file-backed import
139 // passes the bundler and `node dist/bin.mjs`, then throws inside the
140 // binary, so read the emitted module graph rather than trusting config.
141 const bundlePath = path.join(serverDir, "dist-exe/bin.mjs");
142 const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath));
143 if (specifiers.length > 0) {
144 return yield* new ServerCliExecutableImportError({ bundlePath, specifiers });
145 }
146 yield* Effect.log(
147 "[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)",
148 );
149 }),
150).pipe(
151 Command.withDescription(
152 "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.",
153 ),
154);
155
156/**
157 * Publishes the `t3.tgz` launcher scripts/build-npm-launcher.ts produced. The
158 * launcher downloads its executable from the GitHub Release, so the release
159 * workflow runs this only after that release is published.
160 */
161const publishCmd = Command.make(
162 "publish",
163 {
164 packagesDir: Flag.String("packages-dir").pipe(
165 Flag.withDescription("Output dir of scripts/build-npm-launcher.ts."),
166 ),
167 tag: Flag.String("tag").pipe(Flag.withDefault("latest")),
168 access: Flag.String("access").pipe(Flag.withDefault("public")),
169 provenance: Flag.Boolean("provenance").pipe(Flag.withDefault(false)),
170 dryRun: Flag.Boolean("dry-run").pipe(Flag.withDefault(false)),
171 verbose: Flag.Boolean("verbose").pipe(Flag.withDefault(false)),
172 },
173 (config) =>
174 Effect.gen(function* () {
175 const path = yield* Path.Path;
176 const fs = yield* FileSystem.FileSystem;
177 const packagesDir = path.resolve(config.packagesDir);
178 const launcherTarball = path.join(packagesDir, "t3.tgz");
179 if (!(yield* fs.exists(launcherTarball))) {
180 return yield* new ServerCliBuildAssetMissingError({ assetPath: launcherTarball });
181 }
182
183 const args = ["publish", "--access", config.access, "--tag", config.tag];
184 if (config.provenance) args.push("--provenance");
185 if (config.dryRun) args.push("--dry-run");
186 const spawnCommand = yield* resolveSpawnCommand("npm", [...args, launcherTarball]);
187 yield* Effect.log(`[cli] npm ${args.join(" ")} t3.tgz`);
188 yield* runCommand(
189 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
190 cwd: packagesDir,
191 stdout: config.verbose ? "inherit" : "ignore",
192 stderr: "inherit",
193 shell: spawnCommand.shell,
194 }),
195 );
196 }),
197).pipe(Command.withDescription("Publish the t3 launcher to npm."));
198
199const cli = Command.make("cli").pipe(
200 Command.withDescription("T3 server build & publish CLI."),
201 Command.withSubcommands([buildCmd, buildExeCmd, publishCmd]),
202);
203
204Command.run(cli, { version: "0.0.0" }).pipe(
205 Effect.scoped,
206 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
207 NodeRuntime.runMain,
208);