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

main
ts 253 lines 10 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * `@alchemy.run/frontend-frameworks/react-router/aws` — the AWS Lambda
4 * deploy target for the React Router v7 integration.
5 *
6 * React Router builds through Vite: `reactRouter()` in the project's
7 * `vite.config.ts` builds a `client` environment into
8 * `<buildDirectory>/client` and a server environment into
9 * `<buildDirectory>/server`. Its server output is a `ServerBuild` MANIFEST
10 * (`{ entry, routes, assets, ... }`) with no default export and nothing to
11 * call, so the framework half makes the server build's rollup input a
12 * wrapper that turns the manifest into a fetch handler with
13 * `createRequestHandler` from `react-router` (see `serverEntrySource` in
14 * `ReactRouter.ts` — it runs at build time because `react-router` itself
15 * has to end up inside the emitted bundle). What this target owns is the
16 * Lambda packaging on top of that fetch handler:
17 *
18 * - **`serverEntryFileName`** — `index.js`, the chunk the server pass emits
19 * (React Router's `serverBuildFile`); the finishing pass wraps it.
20 * - **`finish`** — emits the Lambda deployment surface next to the entry:
21 * a `package.json` (`type: "module"` — the Lambda Node.js runtime
22 * classifies `.js` by the nearest manifest, and `<buildDirectory>/server`
23 * ships without one), a copy of this package's self-contained
24 * `aws-lambda` web adapter, and `lambda.mjs` exporting `handler` — the
25 * fetch handler wrapped with `awslambda.streamifyResponse` (or the
26 * buffered payload-v2 wrapper with `streaming: false`). The rewritten
27 * `BuildOutput` puts `server/lambda.mjs` first, so it becomes the
28 * deployed Lambda entry. (`lambda.mjs`, not `index.mjs`: React Router's
29 * server build already occupies `index.js`, and the Lambda runtime
30 * resolves a handler module extensionless.)
31 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
32 * (the Lambda Node.js runtime ships SDK v3) for callers that post-process
33 * server code.
34 *
35 * No `devPlatform`: `dev` runs React Router's own Vite dev server, which is
36 * already the AWS Lambda programming model (plain Node).
37 */
38 import * as Effect from "effect/Effect";
39 import * as FileSystem from "effect/FileSystem";
40 import * as Path from "effect/Path";
41 import { runBuildChild } from "../core/BuildChild.ts";
42 import {
43 DeployTargetError,
44 makeDeployTarget,
45 readServerModulesFromDisk,
46 sortServerModules,
47 type BuildOutput,
48 type DeployTargetFinishContext,
49 } from "../core/index.ts";
50 import {
51 DEFAULT_SERVER_BUILD_FILE,
52 make,
53 type ReactRouterTarget,
54 type ReactRouterTargetConfig,
55 } from "./ReactRouter.ts";
56
57 /** The server entry file name React Router's server pass emits. */
58 export const SERVER_ENTRY_FILE_NAME = DEFAULT_SERVER_BUILD_FILE;
59
60 /**
61 * The Lambda entry module the finishing pass emits beside the server entry.
62 * Deliberately NOT `index.mjs`: the server build is `index.js`, and the
63 * Lambda Node.js runtime resolves the handler module without an extension.
64 */
65 export const LAMBDA_ENTRY_FILE_NAME = "lambda.mjs";
66
67 /** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
68 export const LAMBDA_ADAPTER_FILE_NAME = "react-router-aws-lambda.mjs";
69
70 /** AWS-specific knobs carried on the shared {@link ReactRouterTargetConfig}. */
71 export interface ReactRouterAwsTargetConfig extends ReactRouterTargetConfig {
72 /**
73 * Whether the emitted Lambda handler streams its response
74 * (`awslambda.streamifyResponse`, requires a Function URL with
75 * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
76 * APIGW/Function-URL events with a complete response object.
77 * @default true
78 */
79 readonly streaming?: boolean | undefined;
80 }
81
82 /** The AWS {@link ReactRouterTarget}, carrying the AWS-specific config. */
83 export interface ReactRouterAwsTarget extends ReactRouterTarget {
84 readonly config: ReactRouterAwsTargetConfig;
85 }
86
87 const fail = (message: string, cause?: unknown) =>
88 new DeployTargetError({ platform: "aws", message, cause });
89
90 /**
91 * The generated Lambda entry: imports the server build's fetch handler and
92 * exports it wrapped for the Lambda Node.js runtime.
93 *
94 * The entry module default-exports `{ fetch }` (the shape the integration's
95 * virtual server entry produces). A project whose own entry default-exports
96 * the bare fetch function is accepted too.
97 */
98 export const generateLambdaEntry = (options: {
99 readonly streaming: boolean;
100 readonly serverEntryFileName: string;
101 }): string => {
102 const wrap = options.streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
103 return `// Auto-generated by @alchemy.run/frontend-frameworks/react-router/aws — do not edit.
104 import * as serverEntry from "./${options.serverEntryFileName}";
105 import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";
106
107 const entry = serverEntry.default ?? serverEntry;
108 const fetchHandler =
109 typeof entry === "function"
110 ? entry
111 : (request) => entry.fetch(request);
112
113 export const handler = ${wrap}(fetchHandler);
114 `;
115 };
116
117 /**
118 * Resolve this package's built, self-contained `aws-lambda` adapter module
119 * on disk (it has no imports of its own, so a byte copy deploys as-is).
120 */
121 const resolveLambdaAdapterPath = Effect.try({
122 try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
123 catch: (cause) =>
124 fail(
125 'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
126 cause,
127 ),
128 });
129
130 const finish = (
131 config: ReactRouterAwsTargetConfig,
132 output: BuildOutput,
133 context: DeployTargetFinishContext,
134 ): Effect.Effect<BuildOutput, DeployTargetError, FileSystem.FileSystem | Path.Path> =>
135 Effect.gen(function* () {
136 const fs = yield* FileSystem.FileSystem;
137 const path = yield* Path.Path;
138 if (context.entry === undefined) {
139 return yield* fail("The React Router build produced no on-disk server entry to finish");
140 }
141 const serverDir = path.dirname(context.entry);
142 const serverEntryFileName = path.basename(context.entry);
143
144 // The Lambda Node.js runtime classifies `.js` modules by the nearest
145 // package.json, and the server directory ships as the deployment root
146 // without one — the ESM server build and its chunks need the marker.
147 yield* fs.writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n');
148
149 const adapterPath = yield* resolveLambdaAdapterPath;
150 const adapterSource = yield* fs.readFileString(adapterPath);
151 yield* fs.writeFileString(
152 path.join(serverDir, LAMBDA_ADAPTER_FILE_NAME),
153 // Drop the sourcemap pointer — the map is not copied into the bundle.
154 adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
155 );
156
157 yield* fs.writeFileString(
158 path.join(serverDir, LAMBDA_ENTRY_FILE_NAME),
159 generateLambdaEntry({
160 streaming: config.streaming !== false,
161 serverEntryFileName,
162 }),
163 );
164
165 // Re-read the server directory so the emitted files are part of the
166 // output, with the Lambda entry first.
167 const modules = yield* readServerModulesFromDisk({
168 directory: serverDir,
169 prefix: "server",
170 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
171 return {
172 ...output,
173 serverModules: sortServerModules(modules, `server/${LAMBDA_ENTRY_FILE_NAME}`),
174 };
175 }).pipe(
176 Effect.catchTag("PlatformError", (error) =>
177 Effect.fail(fail("Failed to emit the Lambda entry", error)),
178 ),
179 );
180
181 /**
182 * The finish-only target — the shape the framework's regular build/finish
183 * pipeline consumes. Used directly in the build child (where `cwd === root`
184 * holds); {@link makeAwsTarget} wraps it with the wholesale `build` hook
185 * that spawns the child.
186 */
187 const makeAwsFinishTarget = (config: ReactRouterAwsTargetConfig = {}): ReactRouterAwsTarget =>
188 makeDeployTarget({
189 platform: "aws",
190 config,
191 bundle: {
192 conditions: ["node", "import", "module"],
193 external: ["@aws-sdk/"],
194 },
195 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
196 finish: (output, context) => finish(config, output, context),
197 });
198
199 /**
200 * A React Router build loads and executes the project's `vite.config.*` and
201 * `react-router.config.ts` (user plugins may mutate `process.env` or
202 * `process.chdir`, and React Router's config loader spins its own vite-node
203 * server) — none of which may touch the engine process, where many deploys
204 * share one event loop. This target's wholesale `build` therefore runs the
205 * framework in a disposable child process whose working directory IS the
206 * project root (see `core/BuildChild.ts`). The shared
207 * `core/BuildChildRunner` entry imports this module in the child and calls
208 * the exported {@link buildInChild}.
209 */
210 export interface ReactRouterAwsBuildChildConfig {
211 readonly rootDir: string;
212 /** The (JSON-serializable) target config the parent was created with. */
213 readonly config: ReactRouterAwsTargetConfig;
214 }
215
216 export const buildInChild = (config: ReactRouterAwsBuildChildConfig) =>
217 Effect.gen(function* () {
218 const framework = yield* make({
219 root: config.rootDir,
220 // The finish-only target: no wholesale `build` hook, so the child
221 // runs the regular vite build + finish pipeline (no recursion).
222 target: makeAwsFinishTarget(config.config),
223 buildDirectory: config.config.buildDirectory,
224 });
225 return yield* framework.build({ root: config.rootDir });
226 });
227
228 /**
229 * Create the AWS Lambda {@link ReactRouterTarget}. See the module doc for
230 * the seams.
231 */
232 export const makeAwsTarget = (config: ReactRouterAwsTargetConfig = {}): ReactRouterAwsTarget => ({
233 ...makeAwsFinishTarget(config),
234 build: (context) =>
235 runBuildChild({
236 module: import.meta.url,
237 rootDir: context.root,
238 env: context.env,
239 framework: "react-router",
240 config: {
241 rootDir: context.root,
242 config,
243 } satisfies ReactRouterAwsBuildChildConfig,
244 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
245 });
246
247 /**
248 * The deploy-target module contract (`resolveDeployTarget` accepts the
249 * default export — or the named `target` export — as a value or factory).
250 */
251 export const target = makeAwsTarget;
252
253 export default makeAwsTarget;