build.ts
This file
Path
apps/cli/build.ts
412 lines · 11.8 KiB · TypeScript
Last changed by
Merge perf/cheap into mainoscabrielbefore adoptionc007606
History of this fileTake it
1import { BunRuntime, BunServices } from "@effect/platform-bun";2import { Brand } from "@repo/brand";3import {4 Data,5 Effect,6 FileSystem,7 Option,8 Path,9 Predicate,10 Schema,11 Stdio,12} from "effect";13import { CliConfig, Command, Flag, GlobalFlag } from "effect/cli";14import { ChildProcess, ChildProcessSpawner } from "effect/process";15import { build } from "tsdown";1617import { NATIVE, npmMachineOf } from "./build-targets.ts";18import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";19import {20 declarations,21 library,22 npm,23 UNSTAMPED,24 versionDefine,25} from "./tsdown.config.ts";2627// Re-exported: tsdown.config.ts defines it, as importing this module would be a cycle.28export { versionDefine } from "./tsdown.config.ts";2930export interface BuildOptions {31 readonly targets: readonly string[];32 readonly version: string;33}3435export const compileArgs = (input: {36 readonly entry: string;37 readonly outfile: string;38 readonly target?: string;39 readonly version: string;40}) => [41 "build",42 "--compile",43 // Bytecode: the binary starts by loading its bundle, and a bytecode cache44 // skips the parse of the whole bundle each start. ESM is what bytecode takes.45 "--bytecode",46 "--format=esm",47 "--minify",48 ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [49 "--define",50 `${key}=${value}`,51 ]),52 ...(input.target === undefined ? [] : [`--target=bun-${input.target}`]),53 input.entry,54 "--outfile",55 input.outfile,56];5758class BuildFailed extends Data.TaggedError("BuildFailed")<{59 readonly step: string;60 readonly detail: string;61}> {}6263interface Tsconfig {64 readonly compilerOptions: {65 readonly declaration?: boolean;66 readonly emitDeclarationOnly?: boolean;67 readonly noCheck?: boolean;68 readonly noEmit?: boolean;69 readonly outDir?: string;70 readonly paths: Readonly<Record<string, readonly string[]>>;71 readonly rootDir?: string;72 };73 readonly extends?: string;74 readonly files: readonly string[];75 readonly include?: readonly string[];76}7778const NativeManifest = Schema.fromJsonString(79 Schema.Struct({80 optionalDependencies: Schema.Record(Schema.String, Schema.String),81 })82);8384const Manifest = Schema.fromJsonString(85 Schema.Struct({86 exports: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),87 name: Schema.String,88 })89);9091const run = (92 step: string,93 command: string,94 args: readonly string[],95 options: {96 readonly cwd?: string;97 readonly env?: Readonly<Record<string, string>>;98 } = {}99) =>100 Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>101 spawner.exitCode(102 ChildProcess.make(command, args, {103 cwd: options.cwd,104 env: { ...options.env },105 extendEnv: true,106 stderr: "inherit",107 stdin: "ignore",108 stdout: "inherit",109 })110 )111 ).pipe(112 Effect.mapError(113 (failure) => new BuildFailed({ detail: failure.message, step })114 ),115 Effect.filterOrFail(116 (exitCode) => exitCode === 0,117 (exitCode) => new BuildFailed({ detail: `exit code ${exitCode}`, step })118 ),119 Effect.asVoid120 );121122const tsdown = (step: string, config: Parameters<typeof build>[0]) =>123 Effect.tryPromise({124 catch: (cause) => new BuildFailed({ detail: String(cause), step }),125 try: () => build(config),126 });127128const make = ({ targets, version }: BuildOptions) =>129 Effect.gen(function* () {130 const fs = yield* FileSystem.FileSystem;131 const path = yield* Path.Path;132 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));133 const repo = path.join(root, "..", "..");134 const dist = path.join(root, "dist");135136 const workspacePaths = (onto: (file: string) => string) =>137 Effect.gen(function* () {138 const packages = path.join(repo, "packages");139 const paths: Record<string, readonly string[]> = {};140141 for (const folder of yield* fs.readDirectory(packages)) {142 const manifest = path.join(packages, folder, "package.json");143144 if (yield* fs.exists(manifest)) {145 const { exports = {}, name } = yield* fs146 .readFileString(manifest)147 .pipe(Effect.flatMap(Schema.decodeEffect(Manifest)));148149 for (const [subpath, file] of Object.entries(exports)) {150 if (Predicate.isString(file)) {151 paths[`${name}${subpath.slice(1)}`] = [152 onto(path.join(packages, folder, file)),153 ];154 }155 }156 }157 }158159 return paths;160 });161162 const tsconfigIn = (dir: string, name: string, config: Tsconfig) =>163 Effect.as(164 fs.writeFileString(path.join(dir, name), JSON.stringify(config)),165 path.join(dir, name)166 );167168 for (const config of npm(version)) {169 yield* tsdown(`tsdown ${Object.keys(config.entry).join(", ")}`, {170 ...config,171 config: false,172 cwd: root,173 });174 }175176 // A fixed path, not a temp folder: the bundled .d.ts files keep each177 // source path in a comment, so a random name would change every build.178 const scratch = path.join(dist, ".types");179180 yield* Effect.acquireRelease(181 fs.makeDirectory(scratch, { recursive: true }),182 () => Effect.orDie(fs.remove(scratch, { recursive: true }))183 );184185 const declared = path.join(scratch, "declared");186187 const declaration = (file: string) =>188 path.join(declared, path.relative(repo, file)).replace(/\.ts$/u, ".d.ts");189190 const emit = yield* tsconfigIn(scratch, "emit.json", {191 compilerOptions: {192 declaration: true,193 emitDeclarationOnly: true,194 // Typecheck has checked these sources; this only declares them.195 noCheck: true,196 noEmit: false,197 outDir: declared,198 paths: yield* workspacePaths((file) => file),199 rootDir: repo,200 },201 extends: path.join(root, "tsconfig.json"),202 files: Object.values(library).map((entry) => path.join(root, entry)),203 include: [],204 });205206 yield* run("tsgo", "bun", [207 path.join(root, "node_modules", "typescript", "bin", "tsc"),208 "--project",209 emit,210 ]);211212 const types = yield* tsconfigIn(scratch, "types.json", {213 compilerOptions: { paths: yield* workspacePaths(declaration) },214 files: [],215 });216217 yield* tsdown("declarations", {218 ...declarations(219 {220 protocol: declaration(path.join(root, library.protocol)),221 rules: declaration(path.join(root, library.rules)),222 },223 types224 ),225 config: false,226 cwd: root,227 });228229 // Bundled whole (a machine with only the binary has no node_modules);230 // runtime.ts sets their embedded paths before src/bin.ts runs.231 const compile = path.join(dist, ".compile");232233 yield* Effect.acquireRelease(234 fs.makeDirectory(compile, { recursive: true }),235 () => Effect.orDie(fs.remove(compile, { recursive: true }))236 );237238 for (const [name, source] of [239 ["sdk.js", path.join(repo, "packages", "sdk", "src", "index.ts")],240 ["entry.js", path.join(repo, "packages", "rules", "src", "entry.ts")],241 ] as const) {242 yield* run(`bundle ${name}`, "bun", [243 "build",244 "--no-macros",245 "--target=browser",246 "--format=esm",247 source,248 "--outfile",249 path.join(compile, name),250 ]);251 }252253 yield* fs.writeFileString(254 path.join(compile, "runtime.ts"),255 [256 'import entry from "./entry.js" with { type: "file" };',257 'import sdk from "./sdk.js" with { type: "file" };',258 "",259 `Object.assign(globalThis, { ${EMBEDDED_KEY}: { entry, sdk } });`,260 "",261 ].join("\n")262 );263264 yield* fs.writeFileString(265 path.join(compile, "main.ts"),266 [267 'import "./runtime.ts";',268 `import ${JSON.stringify(path.join(root, "src", "bin.ts"))};`,269 "",270 ].join("\n")271 );272273 /** `bun install` installed only this machine's native packages. */274 const nativeFor = (target: string) =>275 Effect.gen(function* () {276 const machine = yield* Effect.fromOption(npmMachineOf(target)).pipe(277 Effect.mapError(278 () =>279 new BuildFailed({280 detail: `Bun names no machine ${target}`,281 step: "native packages",282 })283 )284 );285286 const dependencies: Record<string, string> = {};287288 for (const name of NATIVE) {289 const manifest = yield* path.fromFileUrl(290 new URL(import.meta.resolve(`${name}/package.json`))291 );292293 const { optionalDependencies } = yield* fs294 .readFileString(manifest)295 .pipe(Effect.flatMap(Schema.decodeEffect(NativeManifest)));296297 Object.assign(dependencies, optionalDependencies);298 }299300 const folder = yield* fs.makeTempDirectoryScoped({301 prefix: `${Brand.slug}-native-`,302 });303304 yield* fs.writeFileString(305 path.join(folder, "package.json"),306 JSON.stringify({ dependencies, name: "native", private: true })307 );308309 yield* run(310 `native packages for ${target}`,311 "bun",312 [313 "install",314 "--no-save",315 `--os=${machine.os}`,316 `--cpu=${machine.cpu}`,317 ],318 { cwd: folder }319 );320321 return path.join(folder, "node_modules");322 });323324 const outputs =325 targets.length === 0326 ? [{ dir: path.join(dist, "bin"), target: Option.none<string>() }]327 : targets.map((target) => ({328 dir: path.join(dist, "bin", target),329 target: Option.some(target),330 }));331332 for (const { dir, target } of outputs) {333 const env = yield* Option.match(target, {334 onNone: () => Effect.succeed({}),335 onSome: (name) =>336 Effect.map(nativeFor(name), (modules) => ({ NODE_PATH: modules })),337 });338339 yield* run(340 "bun build --compile",341 "bun",342 compileArgs({343 entry: path.join(compile, "main.ts"),344 outfile: path.join(dir, Brand.cli),345 version,346 ...Option.match(target, {347 onNone: () => ({}),348 onSome: (name) => ({ target: name }),349 }),350 }),351 { env }352 );353354 yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));355 }356 }).pipe(Effect.scoped);357358const targets = Flag.String("targets").pipe(359 Flag.withDescription(360 "Cross-compile for these Bun targets, comma-separated (linux-x64,darwin-arm64); each binary goes to dist/bin/<target>/."361 ),362 Flag.optional363);364365const version = Flag.String("version").pipe(366 Flag.withDescription(367 `The version both builds are stamped with, which the CLI's --version prints (default ${UNSTAMPED}).`368 ),369 Flag.optional370);371372const command = <E, R>(373 then: (options: BuildOptions) => Effect.Effect<void, E, R>374) =>375 Command.make("build", { targets, version }, (flags) =>376 then({377 targets: Option.match(flags.targets, {378 onNone: () => [],379 onSome: (list) =>380 list381 .split(",")382 .map((target) => target.trim().replace(/^bun-/u, ""))383 .filter((target) => target.length > 0),384 }),385 version: Option.getOrElse(flags.version, () => UNSTAMPED),386 })387 ).pipe(388 Command.withDescription(389 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."390 )391 );392393// The build's `--version` takes a value, so effect/cli's boolean one is dropped.394const builtIns = CliConfig.make({395 builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),396});397398export const parseBuild = <E, R>(399 argv: readonly string[],400 then: (options: BuildOptions) => Effect.Effect<void, E, R>401) =>402 Command.runWith(command(then), { version: UNSTAMPED })(argv).pipe(403 Effect.provideService(CliConfig.CliConfig, builtIns)404 );405406if (import.meta.main) {407 BunRuntime.runMain(408 Stdio.Stdio.use(({ args }) =>409 Effect.flatMap(args, (argv) => parseBuild(argv, make))410 ).pipe(Effect.provide(BunServices.layer))411 );412}