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

main
ts 302 lines 11.6 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodePath from "node:path";
3 import type { Builder } from "@sveltejs/kit";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import * as Path from "effect/Path";
7 import { rolldown } from "rolldown";
8 import { runBuildChild } from "../core/BuildChild.ts";
9 /**
10 * `@alchemy.run/frontend-frameworks/sveltekit/aws` — the AWS Lambda deploy
11 * target for `@alchemy.run/frontend-frameworks/sveltekit`.
12 *
13 * SvelteKit's AWS story mirrors adapter-node: kit's server graph
14 * (`.svelte-kit/output/server`) is Node-flavored ESM, so the Lambda ships
15 * a Node bundle whose entry wraps kit's `Server.respond` fetch handler with
16 * the `@alchemy.run/frontend-frameworks/aws-lambda` adapter
17 * (`awslambda.streamifyResponse` behind a Function URL with
18 * `invokeMode: RESPONSE_STREAM`). What this target owns:
19 *
20 * - **`adapter(context)`** — an in-memory kit `Adapter` that writes client
21 * assets + prerendered pages into the static-assets directory (uploaded
22 * wholesale to S3), generates the route manifest module, and emits an
23 * unbundled Lambda entry importing kit's server from
24 * `.svelte-kit/output/server`.
25 * - **`finish(output, context)`** — re-bundles the entry (and the whole
26 * server graph it imports, including the aws-lambda adapter) for Node
27 * with rolldown into `dist/server` — a self-contained deployment unit
28 * the Lambda ships as-is (`bundle: false`).
29 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
30 * (the Lambda Node.js runtime ships SDK v3).
31 *
32 * No dev platform: `dev` runs kit's own Vite dev server (Node SSR), which
33 * is already the AWS Lambda programming model (plain Node, `process.env`).
34 */
35 import * as FrameworkCore from "../core/index.ts";
36 import { DeployTargetError, makeDeployTarget } from "../core/index.ts";
37 import {
38 make,
39 type SvelteKitAdapter,
40 type SvelteKitAdapterResult,
41 type SvelteKitTarget,
42 type SvelteKitTargetConfig,
43 } from "./SvelteKit.ts";
44
45 const fail = (message: string, cause?: unknown) =>
46 new DeployTargetError({ platform: "aws", message, cause });
47
48 /** AWS-specific knobs carried on the shared {@link SvelteKitTargetConfig}. */
49 export interface SvelteKitAwsTargetConfig extends SvelteKitTargetConfig {
50 /**
51 * Whether the emitted Lambda handler streams its response
52 * (`awslambda.streamifyResponse`, requires a Function URL with
53 * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
54 * APIGW/Function-URL events with a complete response object.
55 * @default true
56 */
57 readonly streaming?: boolean | undefined;
58 }
59
60 /** The entry module name the finishing pass writes (`dist/server/index.mjs`). */
61 export const SERVER_ENTRY_NAME = "server/index.mjs";
62
63 /**
64 * The generated (unbundled) Lambda entry: kit's pre-built server instance
65 * (`generateServerInstance` output), wrapped with the aws-lambda web
66 * adapter. The `@alchemy.run/frontend-frameworks/aws-lambda` import is
67 * inlined by the finishing pass's rolldown bundle, so the shipped
68 * `dist/server` has no runtime dependency on this package.
69 */
70 const generateLambdaEntry = (options: {
71 readonly serverImport: string;
72 readonly streaming: boolean;
73 }): string => {
74 const wrap = options.streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
75 return /* js */ `
76 import { server } from ${JSON.stringify(options.serverImport)};
77 import { ${wrap} } from '@alchemy.run/frontend-frameworks/aws-lambda';
78
79 const initialized = server.init({ env: process.env });
80
81 const respond = async (request) => {
82 // always await initialization to prevent race condition with concurrent requests
83 await initialized;
84 return await server.respond(request, {
85 getClientAddress: () =>
86 request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ?? '127.0.0.1',
87 });
88 };
89
90 export const handler = ${wrap}(respond);
91 `.trimStart();
92 };
93
94 /**
95 * The in-memory kit `Adapter` for AWS: writes the static-assets directory
96 * (client build + prerendered pages) and the unbundled Lambda entry, and
97 * records both on `result` for the framework half. Bundling happens later
98 * in the target's `finish` pass.
99 */
100 export const makeAwsAdapter = (options: {
101 readonly streaming?: boolean | undefined;
102 }): SvelteKitAdapter => {
103 const result: { current?: SvelteKitAdapterResult | undefined } = {};
104 return {
105 name: "@alchemy.run/frontend-frameworks/sveltekit/aws",
106 result,
107 async adapt(builder: Builder) {
108 const dest = builder.getBuildDirectory("aws");
109 const tmp = builder.getBuildDirectory("aws-tmp");
110
111 builder.rimraf(dest);
112 builder.rimraf(tmp);
113 builder.mkdirp(dest);
114 builder.mkdirp(tmp);
115
116 // client assets and prerendered pages — uploaded wholesale to S3;
117 // the CloudFront edge router serves them by exact match.
118 const assetsDest = dest + builder.config.paths.base;
119 builder.mkdirp(assetsDest);
120 builder.writeClient(assetsDest);
121 builder.writePrerendered(assetsDest);
122
123 // pre-built server instance: kit 3.0 no longer exposes the internal
124 // SSR manifest (`generateManifest` throws), so `generateServerInstance`
125 // writes `export const server = new Server(manifest)` straight to
126 // disk itself instead of returning a manifest string to embed. Lambda
127 // routing is all-or-nothing (S3/CloudFront handle static assets), so
128 // unlike the Cloudflare worker shim there's no route manifest to build.
129 builder.generateServerInstance(NodePath.join(tmp, "server.js"));
130
131 // Lambda entry (unbundled; relative imports into `output/server`)
132 const workerEntry = NodePath.join(tmp, "lambda.js");
133 NodeFs.writeFileSync(
134 workerEntry,
135 generateLambdaEntry({
136 serverImport: "./server.js",
137 streaming: options.streaming ?? true,
138 }),
139 );
140 if (
141 typeof builder.hasServerInstrumentationFile === "function" &&
142 builder.hasServerInstrumentationFile()
143 ) {
144 // kit 3.0 requires an explicit initializer module that populates
145 // `$env/dynamic/private` before instrumentation runs; the default
146 // (`process.env`) is correct for the Lambda Node runtime.
147 const initializer = builder.createInstrumentationInitializer({
148 outputDirectory: tmp,
149 });
150 builder.instrument({
151 entrypoint: workerEntry,
152 instrumentation: NodePath.join(builder.getServerDirectory(), "instrumentation.server.js"),
153 initializer,
154 });
155 }
156
157 result.current = { dest, workerEntry };
158 },
159 dispose: async () => {},
160 };
161 };
162
163 /**
164 * The adapter-driven target — the shape the framework's regular
165 * build/finish pipeline consumes. Used directly in the build child (where
166 * `cwd === root` holds); {@link makeAwsTarget} wraps it with the wholesale
167 * `build` hook that spawns the child.
168 */
169 const makeAwsAdapterTarget = (config: SvelteKitAwsTargetConfig = {}): SvelteKitTarget =>
170 makeDeployTarget({
171 platform: "aws",
172 config,
173 bundle: {
174 conditions: ["node", "import", "module"],
175 external: ["@aws-sdk/"],
176 },
177 adapter: (_context) =>
178 makeAwsAdapter({
179 streaming: config.streaming,
180 }),
181 finish: (output, context) =>
182 Effect.gen(function* () {
183 const fs = yield* FileSystem.FileSystem;
184 const path = yield* Path.Path;
185 const entry = context.entry;
186 if (entry === undefined) {
187 return yield* fail(
188 "The SvelteKit build produced no on-disk Lambda entry for the finishing pass " +
189 "(context.entry is missing)",
190 );
191 }
192 const root = context.root;
193 const distDirectory = output.distDirectory ?? path.resolve(root, "dist");
194 const serverOutDir = path.join(distDirectory, "server");
195 yield* fs
196 .remove(serverOutDir, { recursive: true, force: true })
197 .pipe(Effect.mapError((error) => fail("Failed to clean dist/server", error)));
198
199 // Re-bundle the entry (kit's server graph + the aws-lambda adapter)
200 // for Node. `dist/server` must be self-contained: the Lambda ships
201 // it as-is (`bundle: false`), so only Node builtins and the
202 // runtime-provided `@aws-sdk/*` stay external.
203 yield* Effect.tryPromise({
204 try: async () => {
205 const bundle = await rolldown({
206 cwd: root,
207 input: entry,
208 platform: "node",
209 resolve: {
210 conditionNames: ["node", "import", "module"],
211 },
212 external: [/^@aws-sdk\//, /^node:/],
213 });
214 try {
215 await bundle.write({
216 dir: serverOutDir,
217 format: "esm",
218 entryFileNames: "index.mjs",
219 chunkFileNames: "chunks/[name].mjs",
220 sourcemap: false,
221 });
222 } finally {
223 await bundle.close();
224 }
225 },
226 catch: (error) => fail("Failed to bundle the Lambda server for Node", error),
227 });
228
229 const modules = yield* FrameworkCore.readServerModulesFromDisk({
230 directory: serverOutDir,
231 prefix: "server",
232 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
233 const serverModules = FrameworkCore.sortServerModules(modules, SERVER_ENTRY_NAME);
234
235 return {
236 ...output,
237 distDirectory,
238 serverModules,
239 } satisfies FrameworkCore.BuildOutput;
240 }),
241 });
242
243 /**
244 * SvelteKit resolves its config (and the postbuild analyse/prerender worker
245 * threads re-derive `outDir`) relative to `process.cwd()`, so a production
246 * build only works when `cwd === root`. The engine process can't guarantee
247 * that (many deploys share one event loop), so this target's wholesale
248 * `build` runs the framework in a disposable child process whose working
249 * directory IS the project root (see `core/BuildChild.ts`). The shared
250 * `core/BuildChildRunner` entry imports this module in the child and calls
251 * the exported {@link buildInChild}.
252 */
253 export interface SvelteKitAwsBuildChildConfig {
254 readonly rootDir: string;
255 /** The (JSON-serializable) target config the parent was created with. */
256 readonly config: SvelteKitAwsTargetConfig;
257 }
258
259 export const buildInChild = (config: SvelteKitAwsBuildChildConfig) =>
260 Effect.gen(function* () {
261 const framework = yield* make({
262 root: config.rootDir,
263 // The adapter-only target: no wholesale `build` hook, so the child
264 // runs the regular vite build + finish pipeline (no recursion).
265 target: makeAwsAdapterTarget(config.config),
266 compatibilityDate: config.config.compatibilityDate,
267 compatibilityFlags:
268 config.config.compatibilityFlags !== undefined
269 ? [...config.config.compatibilityFlags]
270 : undefined,
271 kit: config.config.kit,
272 adapter: config.config.adapter,
273 });
274 return yield* framework.build({ root: config.rootDir });
275 });
276
277 /**
278 * Create the AWS Lambda {@link SvelteKitTarget}. See the module doc for
279 * the seams.
280 */
281 export const makeAwsTarget = (config: SvelteKitAwsTargetConfig = {}): SvelteKitTarget => ({
282 ...makeAwsAdapterTarget(config),
283 build: (context) =>
284 runBuildChild({
285 module: import.meta.url,
286 rootDir: context.root,
287 env: context.env,
288 framework: "sveltekit",
289 config: {
290 rootDir: context.root,
291 config,
292 } satisfies SvelteKitAwsBuildChildConfig,
293 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
294 });
295
296 /**
297 * The deploy-target module contract (`resolveDeployTarget` accepts the
298 * default export — or the named `target` export — as a value or factory).
299 */
300 export const target = makeAwsTarget;
301
302 export default makeAwsTarget;