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

main
ts 192 lines 6.87 KB
Raw
1 import * as NodePath from "node:path";
2 /**
3 * AWS Lambda adapter for waku, forked from waku's own aws-lambda adapter
4 * (upstream `packages/waku/src/adapters/aws-lambda.ts` @ waku 1.0.0-beta.7).
5 *
6 * Functional changes from upstream:
7 *
8 * - The Lambda handler wrapper is this package's own streaming adapter
9 * (`../aws-lambda/index.ts` — `awslambda.streamifyResponse` +
10 * `HttpResponseStream` for a Function URL with `invokeMode:
11 * RESPONSE_STREAM`; `toBufferedLambdaHandler` when `streaming: false`)
12 * instead of `hono/aws-lambda`'s `streamHandle`/`handle`. The wrapper is
13 * published on `globalThis.__ALCHEMY_WAKU_AWS_LAMBDA_HANDLE__` at
14 * server-entry module scope, mirroring upstream's
15 * `__WAKU_AWS_LAMBDA_HANDLE__` global trick — the serve entry that reads
16 * it stays free of bare imports, so the shipped `dist/server` directory
17 * needs no `node_modules`.
18 * - `buildEnhancers` is empty: upstream's enhancer writes the
19 * `serve-aws-lambda.js` entry via a `waku/adapters/*` module resolved from
20 * the project, which is not guaranteed to exist for the pinned waku
21 * version's export map. The AWS deploy target's finishing pass
22 * (`./aws.ts`) writes the equivalent serve entry instead.
23 *
24 * Everything else (Hono app, rsc middleware, SSG static serving during
25 * build) is behavior-identical to upstream.
26 *
27 * This module is bundled into the Lambda server bundle by waku's vite
28 * pipeline (selected via the in-memory `Config.unstable_adapter`); it is not
29 * Node service code.
30 */
31 import type { Context, MiddlewareHandler, Next } from "hono";
32 import { bodyLimit } from "hono/body-limit";
33 import { Hono } from "hono/tiny";
34 import { unstable_createServerEntryAdapter as createServerEntryAdapter } from "waku/adapter-builders";
35 import {
36 unstable_constants as constants,
37 unstable_honoMiddleware as honoMiddleware,
38 } from "waku/internals";
39 import {
40 toBufferedLambdaHandler,
41 toLambdaHandler,
42 type FetchHandler,
43 } from "../aws-lambda/index.ts";
44
45 const { DIST_PUBLIC } = constants;
46 const { rscMiddleware, middlewareRunner } = honoMiddleware;
47
48 import { AWS_LAMBDA_HANDLE_GLOBAL } from "./aws-shared.ts";
49
50 export { AWS_LAMBDA_HANDLE_GLOBAL } from "./aws-shared.ts";
51
52 const DEFAULT_BODY_LIMIT_MAX_SIZE = 100 * 1024 * 1024;
53
54 const DO_NOT_BUNDLE = "";
55
56 const MIME_TYPES: Record<string, string> = {
57 ".html": "text/html; charset=utf-8",
58 ".js": "text/javascript; charset=utf-8",
59 ".mjs": "text/javascript; charset=utf-8",
60 ".css": "text/css; charset=utf-8",
61 ".json": "application/json",
62 ".txt": "text/plain; charset=utf-8",
63 ".svg": "image/svg+xml",
64 ".png": "image/png",
65 ".jpg": "image/jpeg",
66 ".jpeg": "image/jpeg",
67 ".gif": "image/gif",
68 ".ico": "image/x-icon",
69 ".webp": "image/webp",
70 ".woff": "font/woff",
71 ".woff2": "font/woff2",
72 ".wasm": "application/wasm",
73 };
74
75 /**
76 * Minimal static-file middleware over `node:fs`, replacing upstream's
77 * `@hono/node-server/serve-static` (a waku dependency this package cannot
78 * rely on resolving from the built server bundle). Only ever active during
79 * the SSG pass (`isBuild`), which runs in Node — the dynamic `node:fs`
80 * import keeps the module loadable on any runtime.
81 */
82 const makeBuildStaticMiddleware =
83 (root: string): MiddlewareHandler =>
84 async (c: Context, next: Next) => {
85 if (c.req.method !== "GET" && c.req.method !== "HEAD") {
86 return next();
87 }
88 const fs = (await import(
89 /* @vite-ignore */ DO_NOT_BUNDLE + "node:fs/promises"
90 )) as typeof import("node:fs/promises");
91 let pathname: string;
92 try {
93 pathname = decodeURIComponent(new URL(c.req.url).pathname);
94 } catch {
95 return next();
96 }
97 if (pathname.includes("..")) {
98 return next();
99 }
100 if (pathname.endsWith("/")) {
101 pathname += "index.html";
102 }
103 const filePath = NodePath.join(root, pathname);
104 let data: Uint8Array;
105 try {
106 data = await fs.readFile(filePath);
107 } catch {
108 return next();
109 }
110 const contentType =
111 MIME_TYPES[NodePath.extname(filePath).toLowerCase()] ?? "application/octet-stream";
112 return c.body(data as never, 200, { "content-type": contentType });
113 };
114
115 /** Options accepted by the adapter (superset of upstream's). */
116 export interface AwsLambdaAdapterOptions {
117 /**
118 * Whether the emitted Lambda handler streams its response
119 * (`awslambda.streamifyResponse`, requires a Function URL with
120 * `invokeMode: RESPONSE_STREAM`). `false` produces the buffered
121 * payload-v2 handler.
122 * @default true
123 */
124 streaming?: boolean;
125 bodyLimit?: Parameters<typeof bodyLimit>[0] | false;
126 middlewareFns?: Array<(opts: { app: Hono }) => MiddlewareHandler>;
127 middlewareModules?: Record<string, () => Promise<unknown>>;
128 }
129
130 /**
131 * Annotated via an instantiation expression over the public
132 * `createServerEntryAdapter` so the emitted declaration never references
133 * waku's non-exported `lib/types` module (TS2883).
134 */
135 const awsLambdaAdapter: ReturnType<
136 typeof createServerEntryAdapter<AwsLambdaAdapterOptions | undefined>
137 > = createServerEntryAdapter(
138 (
139 { processRequest, processBuild, config, isBuild, notFoundHtml },
140 options?: AwsLambdaAdapterOptions,
141 ) => {
142 const {
143 bodyLimit: bodyLimitOptions,
144 middlewareFns = [],
145 middlewareModules = {},
146 } = options || {};
147 const app = new Hono();
148 app.notFound((c) => {
149 if (notFoundHtml) {
150 return c.html(notFoundHtml, 404);
151 }
152 return c.text("404 Not Found", 404);
153 });
154 if (isBuild) {
155 // SSG pass only (runs in Node during `waku build`): serve the already
156 // emitted static files so prerender requests resolve assets. Never on
157 // Lambda — there the CDN serves `dist/public`.
158 app.use(makeBuildStaticMiddleware(NodePath.join(config.distDir, DIST_PUBLIC)));
159 }
160 if (bodyLimitOptions !== false) {
161 app.use(bodyLimit(bodyLimitOptions ?? { maxSize: DEFAULT_BODY_LIMIT_MAX_SIZE }));
162 }
163 for (const middlewareFn of middlewareFns) {
164 app.use(middlewareFn({ app }));
165 }
166 app.use(middlewareRunner(middlewareModules as never, { app }));
167 app.use(rscMiddleware({ processRequest }));
168
169 // The serve entry (written by the AWS target's finishing pass) passes its
170 // own `{ streaming }` choice — the target config's knob — with the
171 // adapter option as fallback.
172 (globalThis as Record<string, unknown>)[AWS_LAMBDA_HANDLE_GLOBAL] = (
173 fetchHandler: FetchHandler,
174 serveOptions?: { streaming?: boolean },
175 ) =>
176 (serveOptions?.streaming ?? options?.streaming ?? true)
177 ? toLambdaHandler(fetchHandler)
178 : toBufferedLambdaHandler(fetchHandler);
179
180 return {
181 fetch: app.fetch,
182 build: processBuild,
183 buildOptions: { distDir: config.distDir },
184 // Upstream lists `waku/adapters/aws-lambda-build-enhancer` here (the
185 // serve-entry writer). Dropped: the AWS deploy target's finishing pass
186 // owns the serve entry.
187 buildEnhancers: [],
188 };
189 },
190 );
191
192 export default awsLambdaAdapter;