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

main
ts 311 lines 11.2 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import type * as Scope from "effect/Scope";
6 import { runBuildChild } from "../core/BuildChild.ts";
7 /**
8 * `@alchemy.run/frontend-frameworks/vinext/aws` — vinext on AWS Lambda.
9 *
10 * AWS uses Vinext's Vite build in Node (no Cloudflare Vite
11 * plugin) plus a finishing pass that wraps the App Router RSC entry
12 * (`dist/server/index.js`) as a streaming Lambda handler via
13 * `@alchemy.run/frontend-frameworks/aws-lambda`. Static assets in
14 * `dist/client` are uploaded to S3 by `AWS.Website.Vinext`.
15 *
16 * - **`build`** runs vinext's Vite build in a disposable child, then writes
17 * `dist/server/serve-aws-lambda.mjs` exporting `handler`, or with
18 * `server: "web-function"` `dist/server/serve-node.mjs`, a Node HTTP
19 * server on `AWS_LAMBDA_HTTP_ENDPOINT` for a Lambda Web Function.
20 * - **`dev`** runs the real `vinext dev` CLI (plain Node), scoped.
21 *
22 * This is **not** OpenNext and **not** `Cloudflare.Website.Vinext`.
23 * App Router only — Pages Router has no single fetch handler to wrap.
24 *
25 * Composites should load this module as both the framework specifier and
26 * the deploy target (same shape as `nextjs/aws`).
27 */
28 import * as FrameworkCore from "../core/index.ts";
29 import { DeployTargetError, makeDeployTarget, type DeployTarget } from "../core/index.ts";
30 import { resolveProjectPackageDirectory } from "../core/Loader.ts";
31 import { makeNodeServeEntrySource, NODE_SERVE_ENTRY_FILE_NAME } from "../core/NodeServe.ts";
32 import {
33 awaitVinextDevReady,
34 collectVinextDist,
35 failFramework,
36 pickEphemeralPort,
37 pinServeModule,
38 resolveVinextCli,
39 runVinextBuild,
40 spawnVinextDev,
41 VINEXT_RSC_ENTRY,
42 } from "./cli.ts";
43
44 const failTarget = (message: string, cause?: unknown) =>
45 new DeployTargetError({ platform: "aws", message, cause });
46
47 /** Options for the vinext AWS framework module / deploy target. */
48 export interface VinextAwsOptions {
49 readonly root?: string | undefined;
50 /**
51 * The deploy target module specifier the caller resolved this module as.
52 * This module IS the AWS target — accepted and ignored.
53 */
54 readonly target?: string | undefined;
55 /**
56 * Whether the emitted Lambda handler streams its response
57 * (`awslambda.streamifyResponse`, requires a Function URL with
58 * `invokeMode: RESPONSE_STREAM`).
59 * @default true
60 */
61 readonly streaming?: boolean | undefined;
62 /**
63 * What runs the server. `"web-function"` writes
64 * `dist/server/serve-node.mjs`, a Node HTTP server on
65 * `AWS_LAMBDA_HTTP_ENDPOINT` for a Lambda Web Function; `"function"`
66 * writes the Lambda handler.
67 * @default "function"
68 */
69 readonly server?: "web-function" | "function" | undefined;
70 }
71
72 export interface VinextAwsTargetConfig {
73 readonly root?: string | undefined;
74 readonly streaming?: boolean | undefined;
75 readonly server?: "web-function" | "function" | undefined;
76 }
77
78 export interface VinextAwsTarget extends DeployTarget<VinextAwsTargetConfig> {}
79
80 /** The Lambda entry the finishing pass writes into `dist/server`. */
81 export const SERVE_ENTRY_NAME = "server/serve-aws-lambda.mjs";
82
83 /** The Web Function entry the finishing pass writes into `dist/server`. */
84 export const WEB_SERVE_ENTRY_NAME = `server/${NODE_SERVE_ENTRY_FILE_NAME}`;
85
86 /** vinext's App Router fetch handler, as both entries call it. */
87 const FETCH_HANDLER_SOURCE = `import rsc from "./index.js";
88
89 const fetchHandler = (request) => {
90 const ctx = {
91 hostRuntime: "node",
92 waitUntil(promise) {
93 Promise.resolve(promise).catch(() => {});
94 },
95 passThroughOnException() {},
96 };
97 if (typeof rsc === "function") return rsc(request, ctx);
98 return rsc.fetch(request, process.env, ctx);
99 };`;
100
101 /**
102 * The generated Web Function entry: a Node HTTP server around vinext's App
103 * Router fetch handler. Assets are served from S3, so there is no static
104 * directory.
105 */
106 export const makeWebEntrySource = (): string =>
107 makeNodeServeEntrySource({
108 handler: { kind: "fetch", imports: FETCH_HANDLER_SOURCE, expr: "fetchHandler" },
109 });
110
111 /** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
112 export const LAMBDA_ADAPTER_FILE_NAME = "vinext-aws-lambda.mjs";
113
114 /**
115 * The generated Lambda entry: imports vinext's App Router fetch handler
116 * and exports it wrapped for the Lambda Node.js runtime.
117 */
118 export const makeLambdaEntrySource = (streaming: boolean): string => {
119 const wrap = streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
120 return `// Generated by @alchemy.run/frontend-frameworks/vinext/aws — do not edit.
121 import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";
122 ${FETCH_HANDLER_SOURCE}
123
124 export const handler = ${wrap}(fetchHandler);
125 `;
126 };
127
128 const resolveLambdaAdapterPath = Effect.try({
129 try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
130 catch: (cause) =>
131 failFramework(
132 'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
133 )(cause),
134 });
135
136 export interface VinextAwsBuildChildConfig {
137 readonly rootDir: string;
138 readonly config: VinextAwsTargetConfig;
139 }
140
141 export const buildInChild = (config: VinextAwsBuildChildConfig) =>
142 Effect.gen(function* () {
143 const fs = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145 const root = config.rootDir;
146 yield* runVinextBuild({ root, cache: "s3" });
147 const dist = yield* collectVinextDist(root);
148 if (!dist.hasRsc) {
149 return yield* failFramework(
150 `The vinext AWS target requires an App Router build (${VINEXT_RSC_ENTRY}). Pages Router is supported on Node containers, not Lambda.`,
151 )(undefined);
152 }
153 const adapterPath = yield* resolveLambdaAdapterPath;
154 const adapterSource = yield* fs
155 .readFileString(adapterPath)
156 .pipe(Effect.mapError(failFramework("Failed to read the aws-lambda adapter module")));
157 yield* fs
158 .writeFileString(
159 path.join(dist.serverDir, LAMBDA_ADAPTER_FILE_NAME),
160 adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
161 )
162 .pipe(
163 Effect.mapError(failFramework("Failed to write the aws-lambda adapter into dist/server")),
164 );
165 const output =
166 config.config.server === "web-function"
167 ? yield* pinServeModule(dist, WEB_SERVE_ENTRY_NAME, makeWebEntrySource())
168 : yield* pinServeModule(
169 dist,
170 SERVE_ENTRY_NAME,
171 makeLambdaEntrySource(config.config.streaming !== false),
172 );
173 // Preserve vinext's separate RSC/SSR module graphs and package its externals.
174 const vinextRoot = yield* resolveProjectPackageDirectory(root, "vinext").pipe(
175 Effect.flatMap((directory) => fs.realPath(directory)),
176 );
177 const standaloneUrl = yield* path.toFileUrl(path.join(vinextRoot, "dist/build/standalone.js"));
178 const standalone = yield* Effect.tryPromise({
179 try: () =>
180 import(/* @vite-ignore */ standaloneUrl.href) as Promise<{
181 emitStandaloneOutput(options: {
182 root: string;
183 outDir: string;
184 vinextPackageRoot: string;
185 }): { standaloneDir: string };
186 }>,
187 catch: failFramework(
188 "Failed to load vinext standalone packaging; install vinext 1.0.1 or newer",
189 ),
190 });
191 const packaged = yield* Effect.try({
192 try: () =>
193 standalone.emitStandaloneOutput({
194 root,
195 outDir: dist.distDirectory!,
196 vinextPackageRoot: vinextRoot,
197 }),
198 catch: failFramework("Failed to package vinext Lambda runtime dependencies"),
199 });
200 yield* fs.rename(
201 path.join(packaged.standaloneDir, "node_modules"),
202 path.join(dist.serverDir, "node_modules"),
203 );
204 yield* fs.remove(packaged.standaloneDir, { recursive: true });
205 yield* fs.writeFileString(path.join(dist.serverDir, "package.json"), '{"type":"module"}');
206 return output;
207 });
208
209 const makeAwsChildTarget = (config: VinextAwsTargetConfig = {}): VinextAwsTarget =>
210 makeDeployTarget({
211 platform: "aws",
212 config,
213 bundle: {
214 conditions: ["node", "import", "module"],
215 external: ["@aws-sdk/"],
216 },
217 });
218
219 /**
220 * Create the AWS Lambda {@link VinextAwsTarget}. See the module doc.
221 */
222 export const makeAwsTarget = (config: VinextAwsTargetConfig = {}): VinextAwsTarget => ({
223 ...makeAwsChildTarget(config),
224 build: (context) =>
225 runBuildChild({
226 runtime: "node",
227 module: import.meta.url,
228 rootDir: context.root,
229 env: context.env,
230 framework: "vinext",
231 config: {
232 rootDir: context.root,
233 config,
234 } satisfies VinextAwsBuildChildConfig,
235 }).pipe(Effect.mapError((error) => failTarget(error.message, error.cause))),
236 });
237
238 export const target = makeAwsTarget;
239
240 export default makeAwsTarget;
241
242 export interface VinextAwsService {
243 readonly build: (options?: FrameworkCore.FrameworkBuildOptions) => Effect.Effect<
244 {
245 readonly distDirectory: string;
246 readonly clientDirectory: string | undefined;
247 readonly serverModules: Array<{ readonly name: string }>;
248 },
249 FrameworkCore.FrameworkError
250 >;
251 readonly dev: (
252 options?: FrameworkCore.FrameworkDevOptions,
253 ) => Effect.Effect<FrameworkCore.FrameworkDevServer, FrameworkCore.FrameworkError, Scope.Scope>;
254 }
255
256 /**
257 * Build the vinext-on-AWS framework service. See the module doc for the
258 * `build`/`dev` semantics.
259 */
260 export const make: (
261 options?: VinextAwsOptions,
262 ) => Effect.Effect<VinextAwsService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
263 function* (options?: VinextAwsOptions) {
264 const fs = yield* FileSystem.FileSystem;
265 const path = yield* Path.Path;
266 const resolveRoot = (override: string | undefined) =>
267 Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));
268
269 const build: VinextAwsService["build"] = Effect.fn(function* (
270 buildOptions?: FrameworkCore.FrameworkBuildOptions,
271 ) {
272 const root = yield* resolveRoot(buildOptions?.root);
273 const awsTarget = makeAwsTarget({
274 root,
275 streaming: options?.streaming,
276 server: options?.server,
277 });
278 const output = yield* awsTarget.build!({
279 root,
280 framework: "vinext",
281 env: buildOptions?.env,
282 }).pipe(
283 Effect.provideService(FileSystem.FileSystem, fs),
284 Effect.provideService(Path.Path, path),
285 Effect.mapError((error) => failFramework(error.message)(error.cause)),
286 );
287 return {
288 distDirectory: output.distDirectory ?? path.join(root, "dist"),
289 clientDirectory: output.clientDirectory,
290 serverModules: (output.serverModules ?? []).map((module_) => ({
291 name: module_.name,
292 })),
293 };
294 });
295
296 const dev: VinextAwsService["dev"] = Effect.fn(function* (
297 devOptions?: FrameworkCore.FrameworkDevOptions,
298 ) {
299 const root = yield* resolveRoot(devOptions?.root);
300 const port = devOptions?.port ?? (yield* pickEphemeralPort);
301 const cli = yield* resolveVinextCli(root);
302 const host = devOptions?.host ?? "127.0.0.1";
303 const child = yield* spawnVinextDev({ root, cli, port, host });
304 const url = `http://${host}:${port}`;
305 yield* awaitVinextDevReady({ url, child });
306 return { url };
307 });
308
309 return { build, dev };
310 },
311 );