@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 181 lines 6.53 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Path from "effect/Path";
6 import type { PlatformError } from "effect/PlatformError";
7 import * as ChildProcess from "effect/process/ChildProcess";
8 import type * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9 import * as Schema from "effect/Schema";
10 import * as Stream from "effect/Stream";
11 import { logChildOutput } from "../core/ChildOutput.ts";
12
13 export class RunnerError extends Data.TaggedError<"RunnerError">("RunnerError")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /**
19 * The JSON configuration passed to `runner.mjs` (as `process.argv[2]`).
20 * Mirrors the shape the runner script parses.
21 */
22 export interface RunnerConfig {
23 /** The Next.js application root. */
24 readonly appDir: string;
25 /** Explicit config relative to `appDir`; otherwise discover `open-next.config.ts`. */
26 readonly configPath?: string | undefined;
27 /** Resource-selected cache configuration when no native config file is present. */
28 readonly cache?: "static-assets" | "kv" | undefined;
29 /** `compatibility_date` of the in-memory wrangler-config stand-in. */
30 readonly compatibilityDate: string;
31 /** Skip the internal `next build` (reuse an existing `.next`). @default false */
32 readonly skipNextBuild?: boolean | undefined;
33 /** Minify the OpenNext bundling steps. @default false */
34 readonly minify?: boolean | undefined;
35 /** Enable OpenNext debug logging. @default false */
36 readonly debug?: boolean | undefined;
37 /**
38 * The command the pipeline runs to build the Next.js app. Defaults (in the
39 * runner) to `npx next build` — NOT the app's `build` script, which by
40 * fixture convention is `e2e build` and would recurse into this runner.
41 */
42 readonly buildCommand?: string | undefined;
43 }
44
45 const BuildPaths = Schema.Struct({
46 openNextDirectory: Schema.String,
47 appBuildOutputPath: Schema.String,
48 });
49
50 /** Discover the same default filename as the native Cloudflare OpenNext CLI. */
51 export const resolveConfigPath = Effect.fn(function* (
52 config: Pick<RunnerConfig, "appDir" | "configPath">,
53 ) {
54 const fs = yield* FileSystem.FileSystem;
55 const path = yield* Path.Path;
56 const candidate = path.resolve(config.appDir, config.configPath ?? "open-next.config.ts");
57 if (yield* fs.exists(candidate)) {
58 if ((yield* fs.stat(candidate)).type !== "File") {
59 return yield* new RunnerError({
60 message: `OpenNext config is not a file: ${candidate}`,
61 });
62 }
63 return candidate;
64 }
65 if (config.configPath !== undefined) {
66 return yield* new RunnerError({
67 message: `OpenNext config file not found: ${candidate}`,
68 });
69 }
70 return undefined;
71 });
72
73 /** Absolute path of the runner script in the package's `nextjs` directory. */
74 export const runnerPath = (): string =>
75 fileURLToPath(new URL("../nextjs/runner.mjs", import.meta.url));
76
77 /**
78 * Run the programmatic `@opennextjs/cloudflare` build pipeline in a
79 * disposable `node` child process (`runner.mjs`). The pipeline mutates
80 * cwd-coupled module state, spawns `next build`, and can `process.exit(1)`,
81 * so it must never run inside the calling process.
82 *
83 * Output is piped and re-emitted through the parent's own
84 * `process.stdout`/`process.stderr` JS streams — NOT `stdio: "inherit"`.
85 * `inherit` writes straight to the process file descriptors, bypassing any
86 * in-process stdout capture (e.g. a test runner's log file), which silently
87 * discards `next build`'s failure output when the pipeline exits non-zero.
88 */
89 export const runOpenNextBuild = (
90 config: RunnerConfig,
91 ): Effect.Effect<
92 typeof BuildPaths.Type,
93 RunnerError,
94 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
95 > =>
96 Effect.scoped(
97 Effect.gen(function* () {
98 const fs = yield* FileSystem.FileSystem;
99 const path = yield* Path.Path;
100 const configPath = yield* resolveConfigPath(config);
101 // The parent owns cleanup even if OpenNext calls process.exit in the child.
102 const directory = yield* fs.makeTempDirectoryScoped({
103 prefix: "alchemy-nextjs-config-",
104 });
105 const outputPath = path.join(directory, "build-paths.json");
106 const child = yield* ChildProcess.make(
107 "node",
108 [
109 runnerPath(),
110 JSON.stringify({
111 ...config,
112 configPath,
113 generatedConfigPath:
114 configPath === undefined ? path.join(directory, "open-next.config.mjs") : undefined,
115 outputPath,
116 }),
117 ],
118 {
119 cwd: config.appDir,
120 // Keep upstream compiler scratch files inside the parent's scope too.
121 env: { TMPDIR: directory, TMP: directory, TEMP: directory },
122 extendEnv: true,
123 stdin: "ignore",
124 stdout: "pipe",
125 stderr: "pipe",
126 },
127 ).pipe(
128 Effect.mapError(
129 (cause) =>
130 new RunnerError({
131 message: "Failed to spawn the OpenNext build runner (is `node` on PATH?)",
132 cause,
133 }),
134 ),
135 );
136 // Build output becomes log records, so the process that renders logs
137 // shows it and in-process capture (a test runner's log file) sees it.
138 const forward = (
139 stream: Stream.Stream<Uint8Array, PlatformError>,
140 name: "stdout" | "stderr",
141 ) =>
142 stream.pipe(
143 Stream.decodeText,
144 Stream.splitLines,
145 Stream.runForEach((line) => logChildOutput(line, name)),
146 );
147 const { exitCode } = yield* Effect.all(
148 {
149 exitCode: child.exitCode,
150 stdout: forward(child.stdout, "stdout"),
151 stderr: forward(child.stderr, "stderr"),
152 },
153 { concurrency: "unbounded" },
154 ).pipe(
155 Effect.mapError(
156 (cause) =>
157 new RunnerError({
158 message: "Failed reading the OpenNext build runner's output",
159 cause,
160 }),
161 ),
162 );
163 if (exitCode !== 0) {
164 return yield* new RunnerError({
165 message: `The OpenNext build pipeline exited with code ${exitCode}`,
166 });
167 }
168 return yield* fs
169 .readFileString(outputPath)
170 .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(BuildPaths))));
171 }).pipe(
172 Effect.mapError((cause) =>
173 cause instanceof RunnerError
174 ? cause
175 : new RunnerError({
176 message: "Failed to prepare or read the OpenNext build configuration",
177 cause,
178 }),
179 ),
180 ),
181 );