@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 450 lines 16.7 KB
Raw
1 import type * as NodeChildProcessModule from "node:child_process";
2 import { createRequire } from "node:module";
3 import type * as NodeNet from "node:net";
4 import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
9 import type { PlatformError } from "effect/PlatformError";
10 import * as ChildProcess from "effect/process/ChildProcess";
11 import * as Schema from "effect/Schema";
12 import type * as Scope from "effect/Scope";
13 import * as Stream from "effect/Stream";
14 import { runBuildChild } from "../core/BuildChild.ts";
15 import { makeChildOutput } from "../core/ChildOutput.ts";
16 import { logChildOutput } from "../core/ChildOutput.ts";
17 /**
18 * `@alchemy.run/frontend-frameworks/nextjs/node` — Next.js on a Node
19 * container (`next build` + a custom `next({ dev: false })` server).
20 *
21 * Unlike the Cloudflare (`./index.ts`, OpenNext CF) and AWS (`./aws.ts`,
22 * OpenNext AWS) integrations, this module does **not** use OpenNext. The
23 * container-optimal path is a long-running Node process:
24 *
25 * - **`build`** runs the project's `next build` in a disposable child
26 * (cwd = project root), then writes the shared Node serve entry
27 * (`GET /health`, listens on `PORT`, default 3000) around
28 * {@link NEXT_PRODUCTION_APP_SOURCE}: `next({ dev: false }).prepare()`
29 * over the resolved build config + `getRequestHandler()`.
30 * - **`dev`** runs the real `next dev` CLI (plain Node), scoped.
31 *
32 * Composites should load this module as the framework specifier (same
33 * shape as `./aws`) or pass `target:
34 * "@alchemy.run/frontend-frameworks/nextjs/node"`.
35 */
36 import * as FrameworkCore from "../core/index.ts";
37 import { DeployTargetError, makeDeployTarget, type DeployTarget } from "../core/index.ts";
38 import {
39 NODE_BUNDLE_CONDITIONS,
40 NODE_SERVE_ENTRY_FILE_NAME,
41 writeNodeServeEntry,
42 type NodeServeHandler,
43 } from "../core/NodeServe.ts";
44
45 const failFramework = (message: string) => (cause: unknown) =>
46 new FrameworkCore.FrameworkError({ framework: "nextjs", message, cause });
47
48 const failTarget = (message: string, cause?: unknown) =>
49 new DeployTargetError({ platform: "node", message, cause });
50
51 /** Options for the Next.js Node framework module / deploy target. */
52 export interface NextjsNodeOptions {
53 readonly root?: string | undefined;
54 /**
55 * The deploy target module specifier the caller resolved this module as.
56 * This module IS the Node target — accepted and ignored (parity with
57 * `./aws`).
58 */
59 readonly target?: string | undefined;
60 }
61
62 export interface NextjsNodeTargetConfig {
63 readonly root?: string | undefined;
64 }
65
66 export interface NextjsNodeTarget extends DeployTarget<NextjsNodeTargetConfig> {}
67
68 /** Serve-entry module name relative to the project root. */
69 export const SERVER_ENTRY_NAME = NODE_SERVE_ENTRY_FILE_NAME;
70
71 /**
72 * Serve-entry statements that start Next in production mode as `app`.
73 * Mirrors Next's standalone `server.js`: the resolved build config from
74 * `.next/required-server-files.json` is handed over via
75 * `__NEXT_PRIVATE_STANDALONE_CONFIG`, so Next never reloads
76 * `next.config.*` at runtime (which would recompile TypeScript configs
77 * and download SWC into a possibly read-only bundle). Expects `fs`,
78 * `path` and `fileURLToPath` in scope (both serve templates import them).
79 */
80 export const NEXT_PRODUCTION_APP_SOURCE = [
81 'import next from "next";',
82 "const dir = path.dirname(fileURLToPath(import.meta.url));",
83 'process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(JSON.parse(fs.readFileSync(path.join(dir, ".next", "required-server-files.json"), "utf8")).config);',
84 "const app = next({ dev: false, dir });",
85 "await app.prepare();",
86 ].join("\n");
87
88 /** The production Next request listener for the shared Node serve entry. */
89 export const nextNodeServeHandler: NodeServeHandler = {
90 kind: "node",
91 imports: `${NEXT_PRODUCTION_APP_SOURCE}\nconst nextHandler = app.getRequestHandler();`,
92 expr: "nextHandler",
93 };
94
95 const resolveNextCli = (root: string) =>
96 Effect.try({
97 try: () => {
98 const require = createRequire(`${root.replace(/\/+$/, "")}/package.json`);
99 return require.resolve("next/dist/bin/next");
100 },
101 catch: failFramework(
102 `Failed to resolve "next" from ${root}. ` + "It must be installed in your project.",
103 ),
104 });
105
106 const runNextBuild = (options: { readonly root: string; readonly cli: string }) =>
107 Effect.scoped(
108 Effect.gen(function* () {
109 const env = yield* Effect.sync(() => ({ ...process.env, NODE_ENV: "production" }));
110 const child = yield* ChildProcess.make("node", [options.cli, "build"], {
111 cwd: options.root,
112 stdin: "ignore",
113 stdout: "pipe",
114 stderr: "pipe",
115 env,
116 }).pipe(
117 Effect.mapError(failFramework("Failed to spawn the next build CLI (is `node` on PATH?)")),
118 );
119 // Build output becomes log records, so the process that renders logs
120 // shows it and in-process capture (a test runner's log file) sees it.
121 const forward = (
122 stream: Stream.Stream<Uint8Array, PlatformError>,
123 name: "stdout" | "stderr",
124 ) =>
125 stream.pipe(
126 Stream.decodeText,
127 Stream.splitLines,
128 Stream.runForEach((line) => logChildOutput(line, name)),
129 );
130 const { exitCode } = yield* Effect.all(
131 {
132 exitCode: child.exitCode,
133 stdout: forward(child.stdout, "stdout"),
134 stderr: forward(child.stderr, "stderr"),
135 },
136 { concurrency: "unbounded" },
137 ).pipe(Effect.mapError(failFramework("Failed reading next build output")));
138 if (exitCode !== 0) {
139 return yield* failFramework(`The next build exited with code ${exitCode}`)(undefined);
140 }
141 }),
142 );
143
144 /** The slice of `.next/required-server-files.json` the build inspects. */
145 const RequiredServerFiles = Schema.Struct({
146 config: Schema.Struct({ output: Schema.optional(Schema.String) }),
147 });
148
149 const collectNextOutput = (root: string) =>
150 Effect.gen(function* () {
151 const fs = yield* FileSystem.FileSystem;
152 const path = yield* Path.Path;
153 const nextDir = path.join(root, ".next");
154 const hasNext = yield* fs.exists(nextDir).pipe(Effect.orElseSucceed(() => false));
155 if (!hasNext) {
156 return yield* failFramework(`The next build produced no ${nextDir}`)(undefined);
157 }
158 const serverFilesPath = path.join(nextDir, "required-server-files.json");
159 const { config } = yield* fs
160 .readFileString(serverFilesPath)
161 .pipe(
162 Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(RequiredServerFiles))),
163 Effect.mapError(failFramework(`Failed to read the built Next config ${serverFilesPath}`)),
164 );
165 if (config.output === "export") {
166 return yield* failFramework(
167 '`output: "export"` builds a static site with no Next server, so it ' +
168 'cannot run on the Node target. Remove `output: "export"` from ' +
169 "next.config, or deploy the exported `out/` directory as a static site.",
170 )(undefined);
171 }
172 const publicDir = path.join(root, "public");
173 const hasPublic = yield* fs.exists(publicDir).pipe(Effect.orElseSucceed(() => false));
174 // No `clientDirExpression`: Next serves `.next/static` and `public/`
175 // itself from the serve entry's `dir` (the project root).
176 return yield* writeNodeServeEntry({
177 output: {
178 distDirectory: root,
179 clientDirectory: hasPublic ? root : nextDir,
180 serverModules: [],
181 externalWorkspaces: new Set<string>(),
182 },
183 servePath: path.join(root, SERVER_ENTRY_NAME),
184 serveModuleName: SERVER_ENTRY_NAME,
185 handler: nextNodeServeHandler,
186 }).pipe(Effect.mapError((error) => failFramework(error.message)(error.cause)));
187 });
188
189 export interface NextjsNodeBuildChildConfig {
190 readonly rootDir: string;
191 readonly config: NextjsNodeTargetConfig;
192 }
193
194 export const buildInChild = (config: NextjsNodeBuildChildConfig) =>
195 Effect.gen(function* () {
196 const fs = yield* FileSystem.FileSystem;
197 const path = yield* Path.Path;
198 const root = config.rootDir;
199 const cli = yield* resolveNextCli(root);
200 const spawnerLayer = NodeChildProcessSpawner.layer.pipe(
201 Layer.provide(
202 Layer.merge(Layer.succeed(FileSystem.FileSystem)(fs), Layer.succeed(Path.Path)(path)),
203 ),
204 );
205 yield* runNextBuild({ root, cli }).pipe(Effect.provide(spawnerLayer));
206 return yield* collectNextOutput(root);
207 });
208
209 const makeNodeChildTarget = (config: NextjsNodeTargetConfig = {}): NextjsNodeTarget =>
210 makeDeployTarget({
211 platform: "node",
212 config,
213 bundle: { conditions: [...NODE_BUNDLE_CONDITIONS] },
214 });
215
216 /**
217 * Create the Node {@link NextjsNodeTarget}: wholesale `next build` in a
218 * child process, then a custom-server serve entry.
219 */
220 export const makeNodeTarget = (config: NextjsNodeTargetConfig = {}): NextjsNodeTarget => ({
221 ...makeNodeChildTarget(config),
222 build: (context) =>
223 runBuildChild({
224 module: import.meta.url,
225 rootDir: context.root,
226 env: context.env,
227 framework: "nextjs",
228 config: { rootDir: context.root, config } satisfies NextjsNodeBuildChildConfig,
229 }).pipe(Effect.mapError((error) => failTarget(error.message, error.cause))),
230 });
231
232 export const target = makeNodeTarget;
233
234 export default makeNodeTarget;
235
236 // ---------------------------------------------------------------------------
237 // Framework-module contract (AWS.Website.Server / container composites)
238 // ---------------------------------------------------------------------------
239
240 const pickEphemeralPort: Effect.Effect<number, FrameworkCore.FrameworkError> = Effect.callback(
241 (resume) => {
242 const net = createRequire(import.meta.url)("net") as typeof NodeNet;
243 const server = net.createServer();
244 server.once("error", (cause) =>
245 resume(Effect.fail(failFramework("Failed to allocate an ephemeral port")(cause))),
246 );
247 server.listen(0, "127.0.0.1", () => {
248 const address = server.address();
249 if (address === null || typeof address === "string") {
250 server.close();
251 resume(Effect.fail(failFramework("No TCP address for the port probe")(null)));
252 return;
253 }
254 const port = address.port;
255 server.close(() => resume(Effect.succeed(port)));
256 });
257 },
258 );
259
260 interface NextDevChild {
261 readonly exited: () => boolean;
262 readonly output: () => string;
263 }
264
265 const spawnNextDev = (options: {
266 readonly root: string;
267 readonly cli: string;
268 readonly port: number;
269 readonly host?: string | undefined;
270 }): Effect.Effect<NextDevChild, FrameworkCore.FrameworkError, Scope.Scope> =>
271 Effect.acquireRelease(
272 Effect.flatMap(makeChildOutput, (childOutput) =>
273 Effect.try({
274 try: () => {
275 const cp = createRequire(import.meta.url)(
276 "child_process",
277 ) as typeof NodeChildProcessModule;
278 const child = cp.spawn(
279 "node",
280 [
281 options.cli,
282 "dev",
283 "-p",
284 String(options.port),
285 ...(options.host !== undefined ? ["-H", options.host] : []),
286 ],
287 { cwd: options.root, stdio: ["ignore", "pipe", "pipe"], detached: false },
288 );
289 let exited = false;
290 let output = "";
291 const capture = (chunk: unknown) => {
292 output += String(chunk);
293 if (output.length > 65536) output = output.slice(-32768);
294 };
295 child.stdout?.on("data", (chunk: unknown) => {
296 capture(chunk);
297 childOutput.stdout.push(String(chunk));
298 });
299 child.stderr?.on("data", (chunk: unknown) => {
300 capture(chunk);
301 childOutput.stderr.push(String(chunk));
302 });
303 // Output without a trailing newline is still a line once the
304 // streams close.
305 child.once("close", () => {
306 childOutput.stdout.flush();
307 childOutput.stderr.flush();
308 });
309 child.once("exit", () => {
310 exited = true;
311 });
312 return {
313 child,
314 handle: { exited: () => exited, output: () => output } satisfies NextDevChild,
315 };
316 },
317 catch: failFramework("Failed to spawn the next dev CLI (is `node` on PATH?)"),
318 }),
319 ),
320 ({ child }) =>
321 Effect.callback<void>((resume) => {
322 if (child.exitCode !== null) {
323 resume(Effect.void);
324 return;
325 }
326 const killTimer = setTimeout(() => child.kill("SIGKILL"), 3000);
327 child.once("exit", () => {
328 clearTimeout(killTimer);
329 resume(Effect.void);
330 });
331 child.kill("SIGTERM");
332 }),
333 ).pipe(Effect.map(({ handle }) => handle));
334
335 /**
336 * Poll until the allocated port accepts a TCP connection. Next 16 prints
337 * Ready and binds before loading next.config / compiling App Router, so a
338 * GET / probe with a 2s abort restarts the first compile and never
339 * converges.
340 */
341 const awaitNextDevReady = (options: {
342 readonly url: string;
343 readonly child: NextDevChild;
344 }): Effect.Effect<void, FrameworkCore.FrameworkError> =>
345 Effect.gen(function* () {
346 const parsed = yield* Effect.try({
347 try: () => new URL(options.url),
348 catch: failFramework(`Invalid next dev URL: ${options.url}`),
349 });
350 const port = Number(parsed.port);
351 const hostname = parsed.hostname;
352 for (let attempt = 0; attempt < 240; attempt++) {
353 if (options.child.exited()) {
354 return yield* failFramework(
355 `The next dev CLI exited before becoming ready:\n${options.child.output().slice(-4000)}`,
356 )(undefined);
357 }
358 const ready = yield* Effect.callback<boolean>((resume) => {
359 const net = createRequire(import.meta.url)("net") as typeof NodeNet;
360 let settled = false;
361 const finish = (value: boolean) => {
362 if (settled) return;
363 settled = true;
364 resume(Effect.succeed(value));
365 };
366 const socket = net.connect({ host: hostname, port }, () => {
367 socket.destroy();
368 finish(true);
369 });
370 socket.setTimeout(2000, () => {
371 socket.destroy();
372 finish(false);
373 });
374 socket.once("error", () => {
375 socket.destroy();
376 finish(false);
377 });
378 return Effect.sync(() => {
379 settled = true;
380 socket.destroy();
381 });
382 });
383 if (ready) return;
384 yield* Effect.sleep(500);
385 }
386 return yield* failFramework(`Timed out waiting for the next dev server at ${options.url}`)(
387 undefined,
388 );
389 });
390
391 export interface NextjsNodeService {
392 readonly build: (options?: FrameworkCore.FrameworkBuildOptions) => Effect.Effect<
393 {
394 readonly distDirectory: string;
395 readonly clientDirectory: string;
396 readonly serverModules: Array<{ readonly name: string }>;
397 },
398 FrameworkCore.FrameworkError
399 >;
400 readonly dev: (
401 options?: FrameworkCore.FrameworkDevOptions,
402 ) => Effect.Effect<FrameworkCore.FrameworkDevServer, FrameworkCore.FrameworkError, Scope.Scope>;
403 }
404
405 /**
406 * Build the Next.js-on-Node framework service. See the module doc for the
407 * `build`/`dev` semantics.
408 */
409 export const make: (
410 options?: NextjsNodeOptions,
411 ) => Effect.Effect<NextjsNodeService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
412 function* (options?: NextjsNodeOptions) {
413 const fs = yield* FileSystem.FileSystem;
414 const path = yield* Path.Path;
415 const resolveRoot = (override: string | undefined) =>
416 Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));
417
418 const build: NextjsNodeService["build"] = Effect.fn(function* (
419 buildOptions?: FrameworkCore.FrameworkBuildOptions,
420 ) {
421 const root = yield* resolveRoot(buildOptions?.root);
422 const nodeTarget = makeNodeTarget({ root });
423 const output = yield* nodeTarget.build!({ root, framework: "nextjs" }).pipe(
424 Effect.provideService(FileSystem.FileSystem, fs),
425 Effect.provideService(Path.Path, path),
426 Effect.mapError((error) => failFramework(error.message)(error.cause)),
427 );
428 return {
429 distDirectory: output.distDirectory ?? root,
430 clientDirectory: output.clientDirectory ?? path.join(root, ".next"),
431 serverModules: (output.serverModules ?? []).map((module_) => ({ name: module_.name })),
432 };
433 });
434
435 const dev: NextjsNodeService["dev"] = Effect.fn(function* (
436 devOptions?: FrameworkCore.FrameworkDevOptions,
437 ) {
438 const root = yield* resolveRoot(devOptions?.root);
439 const port = devOptions?.port ?? (yield* pickEphemeralPort);
440 const cli = yield* resolveNextCli(root);
441 const host = devOptions?.host ?? "127.0.0.1";
442 const child = yield* spawnNextDev({ root, cli, port, host });
443 const url = `http://${host}:${port}`;
444 yield* awaitNextDevReady({ url, child });
445 return { url };
446 });
447
448 return { build, dev };
449 },
450 );