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

cli.ts

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