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

main
ts 527 lines 20 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 type * as Scope from "effect/Scope";
12 import * as Stream from "effect/Stream";
13 import { makeChildOutput } from "../core/ChildOutput.ts";
14 import { logChildOutput } from "../core/ChildOutput.ts";
15 /**
16 * `@alchemy.run/frontend-frameworks/nextjs/aws` — Next.js on AWS Lambda via
17 * `@opennextjs/aws`.
18 *
19 * Unlike the Cloudflare Next.js integration (`./index.ts`, a
20 * `Layer<Framework>` over the `@opennextjs/cloudflare` pipeline), this module
21 * exports the standalone framework-module contract alchemy's
22 * `AWS.Website.Server` resource drives directly: `make(options)` resolves to
23 * `{ build, dev }`.
24 *
25 * - **`build`** drives the `@opennextjs/aws` build CLI (resolved from the
26 * *project's* dependency tree) in a disposable child process — the pipeline
27 * mutates cwd-coupled module state, spawns `next build`, and can
28 * `process.exit(1)`, so it must never run in the calling process. When the
29 * project has no `open-next.config.ts`, a minimal default is generated with
30 * the `aws-lambda-streaming` wrapper so the emitted handler streams on a
31 * Lambda Function URL (`invokeMode: RESPONSE_STREAM`). After the build, the
32 * authoritative `.open-next/open-next.output.json` manifest is read to
33 * verify the default origin is a streaming function.
34 * - **`dev`** runs the real `next dev` through Next's documented custom-server
35 * API (`next({ dev: true })` + `prepare()` + `getRequestHandler()` on an
36 * http server we own) — plain Node, which is already the AWS Lambda
37 * programming model. Scoped: closing the Scope stops the app and the server.
38 *
39 * The OpenNext output topology the alchemy composite (`AWS.Website.Nextjs`)
40 * deploys from `.open-next/`:
41 *
42 * - `server-functions/default/` — the SSR server Lambda (`index.handler`)
43 * - `image-optimization-function/` — the image optimizer Lambda (sharp, arm64)
44 * - `revalidation-function/` — the ISR revalidation consumer Lambda
45 * - `assets/` — static assets for the CDN (`_next/static`, `public/`, BUILD_ID)
46 * - `cache/` — the ISR/fetch cache seed (uploaded under the cache prefix)
47 * - `dynamodb-provider/` — the tag-cache table seed function
48 */
49 import * as FrameworkCore from "../core/index.ts";
50 import { buildStandalone } from "./standalone.ts";
51
52 const fail = (message: string) => (cause: unknown) =>
53 new FrameworkCore.FrameworkError({ framework: "nextjs", message, cause });
54
55 /** Options for the Next.js AWS framework module. */
56 export interface NextjsAwsOptions {
57 /** Project root. Defaults to the process working directory. */
58 readonly root?: string | undefined;
59 /**
60 * The deploy target module specifier the caller resolved this module as.
61 * This module IS the AWS target — the option is accepted (the
62 * `AWS.Website.Server` resource always passes it) and ignored.
63 */
64 readonly target?: string | undefined;
65 /**
66 * Path of the OpenNext config, relative to the project root. When the file
67 * does not exist, a minimal default with the `aws-lambda-streaming` wrapper
68 * is generated ({@link DEFAULT_OPEN_NEXT_CONFIG}).
69 * @default "open-next.config.ts"
70 */
71 readonly configPath?: string | undefined;
72 /**
73 * Extra CLI arguments appended to `open-next build` (e.g.
74 * `["--dangerously-use-unsupported-next-version"]`).
75 */
76 readonly buildArgs?: ReadonlyArray<string> | undefined;
77 /**
78 * What runs the server. `"web-function"` builds Next's own standalone
79 * server for a Lambda Web Function, with no OpenNext (see
80 * `./standalone.ts`). `"function"` builds the OpenNext topology with a
81 * streaming Lambda handler for a Function URL.
82 * @default "function"
83 */
84 readonly server?: "web-function" | "function" | undefined;
85 }
86
87 /** The default server-module name of the server's Lambda entry (the actual
88 * name is derived from `open-next.output.json` after the build). */
89 export const SERVER_ENTRY_NAME = "server-functions/default/index.mjs";
90
91 /**
92 * Derive the entry-module name (relative to `.open-next/`) from the output
93 * manifest's default origin: `bundle` (e.g. `.open-next/server-functions/
94 * default`) plus the file half of `handler` (`index.handler` → `index.mjs`).
95 */
96 export const deriveServerEntryName = (origin: {
97 readonly handler?: string;
98 readonly bundle?: string;
99 }): string => {
100 const bundle = (origin.bundle ?? ".open-next/server-functions/default")
101 .replace(/^\.open-next\//, "")
102 .replace(/\/+$/, "");
103 const handler = origin.handler ?? "index.handler";
104 const file = handler.split(".").slice(0, -1).join(".") || "index";
105 return `${bundle}/${file}.mjs`;
106 };
107
108 /** First line of every config this module generates. */
109 const GENERATED_CONFIG_HEADER = "// Generated by @alchemy.run/frontend-frameworks/nextjs/aws.";
110
111 /**
112 * The minimal `open-next.config.ts` generated when the project has none:
113 * the default (and only) server uses the `aws-lambda-streaming` wrapper so
114 * the emitted handler wraps `awslambda.streamifyResponse` and expects a
115 * Function URL with `invokeMode: RESPONSE_STREAM`.
116 */
117 export const DEFAULT_OPEN_NEXT_CONFIG = `${GENERATED_CONFIG_HEADER}
118 // The default OpenNext config for the AWS topology alchemy deploys: the
119 // server streams its response on a Lambda Function URL. Edit freely, but
120 // keep the streaming wrapper — the Function URL is created with
121 // invokeMode: RESPONSE_STREAM.
122 const config = {
123 default: {
124 override: {
125 wrapper: "aws-lambda-streaming",
126 },
127 },
128 };
129
130 export default config;
131 `;
132
133 /** The structural slice of `open-next.output.json` this module reads. */
134 interface OpenNextOutputManifest {
135 readonly origins?: {
136 readonly default?: {
137 readonly type?: string;
138 readonly handler?: string;
139 readonly bundle?: string;
140 readonly streaming?: boolean;
141 };
142 };
143 }
144
145 /**
146 * Resolve the `@opennextjs/aws` CLI entry (`dist/index.js`, the `open-next`
147 * bin) from the *project's* dependency tree. The package's exports map has
148 * only a `"./*" -> "./dist/*"` pattern (no `"."` and no `./package.json`
149 * subpath), so the `index.js` subpath is the one stable resolvable path.
150 */
151 const resolveOpenNextCli = (root: string) =>
152 Effect.try({
153 try: () => {
154 const require = createRequire(`${root.replace(/\/+$/, "")}/package.json`);
155 return require.resolve("@opennextjs/aws/index.js");
156 },
157 catch: fail(
158 `Failed to resolve "@opennextjs/aws" from ${root}. ` +
159 "It must be installed in your project (it drives the Next.js build).",
160 ),
161 });
162
163 /**
164 * Run `open-next build` in a disposable node child process with the project
165 * root as cwd. Output is piped and re-emitted through the parent's own
166 * stdout/stderr JS streams (NOT `stdio: "inherit"`) so in-process capture —
167 * a test runner's log file — sees the build output.
168 */
169 const runOpenNextBuild = (options: {
170 readonly root: string;
171 readonly cli: string;
172 readonly configPath: string;
173 readonly extraArgs: ReadonlyArray<string>;
174 readonly env: Record<string, string> | undefined;
175 }) =>
176 Effect.scoped(
177 Effect.gen(function* () {
178 // Always plain `node` (never bun/`process.execPath`): the OpenNext CLI
179 // mutates its own process.env (NEXT_PRIVATE_STANDALONE,
180 // NEXT_PRIVATE_OUTPUT_TRACE_ROOT) before exec'ing `next build`, and
181 // those mutations do not reliably reach execSync children under bun.
182 // `next build` must run as production, like `nextjs/node.ts` and
183 // `BuildChild`: an inherited NODE_ENV (left by an in-process dev server
184 // in the same long-lived process) breaks prerendering `/_global-error`
185 // ("Cannot read properties of null (reading 'useContext')").
186 const env = yield* Effect.sync(() => ({
187 ...process.env,
188 NODE_ENV: "production",
189 ...options.env,
190 }));
191 const child = yield* ChildProcess.make(
192 "node",
193 [options.cli, "build", "--config-path", options.configPath, ...options.extraArgs],
194 {
195 cwd: options.root,
196 stdin: "ignore",
197 stdout: "pipe",
198 stderr: "pipe",
199 env,
200 },
201 ).pipe(
202 Effect.mapError(fail("Failed to spawn the @opennextjs/aws build CLI (is `node` on PATH?)")),
203 );
204 // Build output becomes log records, so the process that renders logs
205 // shows it and in-process capture (a test runner's log file) sees it.
206 const forward = (
207 stream: Stream.Stream<Uint8Array, PlatformError>,
208 name: "stdout" | "stderr",
209 ) =>
210 stream.pipe(
211 Stream.decodeText,
212 Stream.splitLines,
213 Stream.runForEach((line) => logChildOutput(line, name)),
214 );
215 const { exitCode } = yield* Effect.all(
216 {
217 exitCode: child.exitCode,
218 stdout: forward(child.stdout, "stdout"),
219 stderr: forward(child.stderr, "stderr"),
220 },
221 { concurrency: "unbounded" },
222 ).pipe(Effect.mapError(fail("Failed reading the OpenNext build's output")));
223 if (exitCode !== 0) {
224 return yield* fail(`The OpenNext build exited with code ${exitCode}`)(undefined);
225 }
226 }),
227 );
228
229 // ---------------------------------------------------------------------------
230 // dev — the real `next dev` CLI in a child process
231 // ---------------------------------------------------------------------------
232
233 /**
234 * Resolve the *project's* `next` CLI entry (`next/dist/bin/next`). The
235 * app's installed copy is the one driven, never a hoisted sibling.
236 */
237 const resolveNextCli = (root: string) =>
238 Effect.try({
239 try: () => {
240 const require = createRequire(`${root.replace(/\/+$/, "")}/package.json`);
241 return require.resolve("next/dist/bin/next");
242 },
243 catch: fail(
244 `Failed to resolve "next" from ${root}. ` + "It must be installed in your project.",
245 ),
246 });
247
248 /** Bind an ephemeral port and release it, returning the port number. */
249 const pickEphemeralPort: Effect.Effect<number, FrameworkCore.FrameworkError> = Effect.callback(
250 (resume) => {
251 const net = createRequire(import.meta.url)("net") as typeof NodeNet;
252 const server = net.createServer();
253 server.once("error", (cause) =>
254 resume(Effect.fail(fail("Failed to allocate an ephemeral port")(cause))),
255 );
256 server.listen(0, "127.0.0.1", () => {
257 const address = server.address();
258 if (address === null || typeof address === "string") {
259 server.close();
260 resume(Effect.fail(fail("No TCP address for the port probe")(null)));
261 return;
262 }
263 const port = address.port;
264 server.close(() => resume(Effect.succeed(port)));
265 });
266 },
267 );
268
269 interface NextDevChild {
270 readonly exited: () => boolean;
271 readonly output: () => string;
272 }
273
274 /**
275 * Spawn `node <next CLI> dev -p <port>` with the project root as cwd,
276 * scoped: closing the Scope kills the process tree (SIGTERM, then SIGKILL).
277 * Always plain `node` — the AWS Lambda programming model.
278 */
279 const spawnNextDev = (options: {
280 readonly root: string;
281 readonly cli: string;
282 readonly port: number;
283 readonly host?: string | undefined;
284 }): Effect.Effect<NextDevChild, FrameworkCore.FrameworkError, Scope.Scope> =>
285 Effect.acquireRelease(
286 Effect.flatMap(makeChildOutput, (childOutput) =>
287 Effect.try({
288 try: () => {
289 const cp = createRequire(import.meta.url)(
290 "child_process",
291 ) as typeof NodeChildProcessModule;
292 const child = cp.spawn(
293 "node",
294 [
295 options.cli,
296 "dev",
297 "-p",
298 String(options.port),
299 ...(options.host !== undefined ? ["-H", options.host] : []),
300 ],
301 {
302 cwd: options.root,
303 stdio: ["ignore", "pipe", "pipe"],
304 detached: false,
305 },
306 );
307 let exited = false;
308 let output = "";
309 const capture = (chunk: unknown) => {
310 output += String(chunk);
311 if (output.length > 65536) output = output.slice(-32768);
312 };
313 child.stdout?.on("data", (chunk: unknown) => {
314 capture(chunk);
315 childOutput.stdout.push(String(chunk));
316 });
317 child.stderr?.on("data", (chunk: unknown) => {
318 capture(chunk);
319 childOutput.stderr.push(String(chunk));
320 });
321 // Output without a trailing newline is still a line once the
322 // streams close.
323 child.once("close", () => {
324 childOutput.stdout.flush();
325 childOutput.stderr.flush();
326 });
327 child.once("exit", () => {
328 exited = true;
329 });
330 return {
331 child,
332 handle: {
333 exited: () => exited,
334 output: () => output,
335 } satisfies NextDevChild,
336 };
337 },
338 catch: fail("Failed to spawn the next dev CLI (is `node` on PATH?)"),
339 }),
340 ),
341 ({ child }) =>
342 Effect.callback<void>((resume) => {
343 if (child.exitCode !== null) {
344 resume(Effect.void);
345 return;
346 }
347 const killTimer = setTimeout(() => child.kill("SIGKILL"), 3000);
348 child.once("exit", () => {
349 clearTimeout(killTimer);
350 resume(Effect.void);
351 });
352 child.kill("SIGTERM");
353 }),
354 ).pipe(Effect.map(({ handle }) => handle));
355
356 /**
357 * Poll the dev server URL until it answers any HTTP response. Fails fast
358 * when the child exits before becoming ready.
359 */
360 const awaitNextDevReady = (options: {
361 readonly url: string;
362 readonly child: NextDevChild;
363 }): Effect.Effect<void, FrameworkCore.FrameworkError> =>
364 Effect.gen(function* () {
365 for (let attempt = 0; attempt < 240; attempt++) {
366 if (options.child.exited()) {
367 return yield* fail(
368 `The next dev CLI exited before becoming ready:\n${options.child.output().slice(-4000)}`,
369 )(undefined);
370 }
371 const ready = yield* Effect.tryPromise({
372 try: async () => {
373 const response = await fetch(options.url, {
374 signal: AbortSignal.timeout(2000),
375 });
376 return response.status < 600;
377 },
378 catch: () => "not-ready" as const,
379 }).pipe(Effect.orElseSucceed(() => false));
380 if (ready) return;
381 yield* Effect.sleep(500);
382 }
383 return yield* fail(`Timed out waiting for the next dev server at ${options.url}`)(undefined);
384 });
385
386 /** The service shape {@link make} resolves to (the framework-module contract
387 * `AWS.Website.Server` drives; `serverModules` carries names only — the AWS
388 * deploy ships the OpenNext bundles from disk, never in-memory). */
389 export interface NextjsAwsService {
390 readonly build: (options?: FrameworkCore.FrameworkBuildOptions) => Effect.Effect<
391 {
392 readonly distDirectory: string;
393 readonly clientDirectory: string;
394 readonly serverModules: Array<{ readonly name: string }>;
395 },
396 FrameworkCore.FrameworkError
397 >;
398 readonly dev: (
399 options?: FrameworkCore.FrameworkDevOptions,
400 ) => Effect.Effect<FrameworkCore.FrameworkDevServer, FrameworkCore.FrameworkError, Scope.Scope>;
401 }
402
403 /**
404 * Build the Next.js-on-AWS framework service. See the module doc for the
405 * `build`/`dev` semantics.
406 */
407 export const make: (
408 options?: NextjsAwsOptions,
409 ) => Effect.Effect<NextjsAwsService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
410 function* (options?: NextjsAwsOptions) {
411 const fs = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413
414 const spawnerLayer = NodeChildProcessSpawner.layer.pipe(
415 Layer.provide(
416 Layer.merge(Layer.succeed(FileSystem.FileSystem)(fs), Layer.succeed(Path.Path)(path)),
417 ),
418 );
419
420 const standaloneLayer = Layer.mergeAll(
421 spawnerLayer,
422 Layer.succeed(FileSystem.FileSystem)(fs),
423 Layer.succeed(Path.Path)(path),
424 );
425
426 const resolveRoot = (override: string | undefined) =>
427 Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));
428
429 const build: NextjsAwsService["build"] = Effect.fn(function* (
430 buildOptions?: FrameworkCore.FrameworkBuildOptions,
431 ) {
432 const root = yield* resolveRoot(buildOptions?.root);
433 if (options?.server === "web-function") {
434 return yield* buildStandalone({
435 root,
436 cli: yield* resolveNextCli(root),
437 env: buildOptions?.env,
438 }).pipe(Effect.provide(standaloneLayer));
439 }
440 const configPath = options?.configPath ?? "open-next.config.ts";
441
442 // Generate the minimal streaming config when the project has none. The
443 // file lands in the project root (OpenNext resolves the config relative
444 // to its cwd) and is left in place so subsequent builds — and the memo
445 // input hash — see a stable tree.
446 const absoluteConfigPath = path.resolve(root, configPath);
447 const hasConfig = yield* fs
448 .exists(absoluteConfigPath)
449 .pipe(Effect.orElseSucceed(() => false));
450 if (!hasConfig) {
451 yield* fs
452 .writeFileString(absoluteConfigPath, DEFAULT_OPEN_NEXT_CONFIG)
453 .pipe(
454 Effect.mapError(
455 fail(`Failed to write the default OpenNext config at ${absoluteConfigPath}`),
456 ),
457 );
458 }
459
460 const cli = yield* resolveOpenNextCli(root);
461 yield* runOpenNextBuild({
462 root,
463 cli,
464 configPath,
465 extraArgs: options?.buildArgs ?? [],
466 env: buildOptions?.env,
467 }).pipe(Effect.provide(spawnerLayer));
468
469 const distDirectory = path.join(root, ".open-next");
470 const clientDirectory = path.join(distDirectory, "assets");
471
472 // The authoritative manifest: verify the topology the composite deploys
473 // (a streaming default server function) actually came out of the build.
474 const manifestPath = path.join(distDirectory, "open-next.output.json");
475 const manifestRaw = yield* fs
476 .readFileString(manifestPath)
477 .pipe(Effect.mapError(fail(`The build produced no ${manifestPath}`)));
478 const manifest = yield* Effect.try({
479 try: () => JSON.parse(manifestRaw) as OpenNextOutputManifest,
480 catch: fail(`Failed to parse ${manifestPath}`),
481 });
482 const defaultOrigin = manifest.origins?.default;
483 if (defaultOrigin?.type !== "function") {
484 return yield* fail(
485 `The OpenNext build's default origin is "${defaultOrigin?.type}", not a Lambda function. ` +
486 "The AWS deploy target only supports the function topology (no generateDockerfile).",
487 )(undefined);
488 }
489 if (defaultOrigin.streaming !== true) {
490 return yield* fail(
491 "The OpenNext build's default server does not stream. The Lambda Function URL is " +
492 "created with invokeMode: RESPONSE_STREAM, so open-next.config.ts must keep the streaming wrapper: " +
493 '`default: { override: { wrapper: "aws-lambda-streaming" } }`.',
494 )(undefined);
495 }
496
497 const entryName = deriveServerEntryName(defaultOrigin);
498 const entryPath = path.join(distDirectory, entryName);
499 if (!(yield* fs.exists(entryPath).pipe(Effect.orElseSucceed(() => false)))) {
500 return yield* fail(`The build produced no server entry at ${entryPath}`)(undefined);
501 }
502
503 return {
504 distDirectory,
505 clientDirectory,
506 serverModules: [{ name: entryName }],
507 };
508 });
509
510 const dev: NextjsAwsService["dev"] = Effect.fn(function* (
511 devOptions?: FrameworkCore.FrameworkDevOptions,
512 ) {
513 const root = yield* resolveRoot(devOptions?.root);
514 const port = devOptions?.port ?? (yield* pickEphemeralPort);
515 const cli = yield* resolveNextCli(root);
516 const host = devOptions?.host;
517 const child = yield* spawnNextDev({ root, cli, port, host });
518 const url = `http://${host ?? "localhost"}:${port}`;
519 yield* awaitNextDevReady({ url, child });
520 return { url };
521 });
522
523 return { build, dev };
524 },
525 );
526
527 export default make;