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

main
ts 228 lines 9.16 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * `@alchemy.run/frontend-frameworks/octane/aws` — the AWS Lambda deploy target
4 * for the Octane integration.
5 *
6 * `AWS.Website.Octane` selects this target, which automatically wraps
7 * Octane's default native Node output. No adapter is required in
8 * `octane.config.ts`: the project's own `vite build` emits
9 * `dist/server/entry.js`, a self-contained Node ESM bundle (only `node:`
10 * externals) exporting a web-standard fetch `handler` that never boots a
11 * listener when imported. What this target owns:
12 *
13 * - **`adapterName` / `adapterPackage`** — identify the optional legacy AWS
14 * marker adapter, still accepted for existing projects.
15 * - **`serverEntryFileName`** — `entry.js`, Octane's emitted node entry;
16 * the finishing pass wraps it.
17 * - **`finish`** — emits the Lambda deployment surface next to the entry:
18 * a `package.json` (`type: "module"` — the Lambda Node.js runtime
19 * classifies extensionless `.js` by the nearest manifest, and `dist/server`
20 * ships without one), a copy of this package's self-contained
21 * `aws-lambda` web adapter, and `index.mjs` exporting `handler` — the
22 * fetch handler wrapped with `awslambda.streamifyResponse` (or the
23 * buffered payload-v2 wrapper with `streaming: false`). The rewritten
24 * `BuildOutput` puts `server/index.mjs` first, so it becomes the deployed
25 * Lambda entry.
26 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
27 * (the Lambda Node.js runtime ships SDK v3) for callers that post-process
28 * server code.
29 *
30 * No `devPlatform`: `dev` runs Octane's own Vite dev server, which is
31 * already the AWS Lambda programming model (plain Node; note Octane's dev
32 * middleware supplies no request-scoped platform bindings — an upstream
33 * limitation shared with the Cloudflare target).
34 */
35 import * as Effect from "effect/Effect";
36 import * as FileSystem from "effect/FileSystem";
37 import * as Path from "effect/Path";
38 import { runBuildChild } from "../core/BuildChild.ts";
39 import {
40 DeployTargetError,
41 makeDeployTarget,
42 readServerModulesFromDisk,
43 sortServerModules,
44 type BuildOutput,
45 type DeployTargetFinishContext,
46 } from "../core/index.ts";
47 import { make, type OctaneTarget, type OctaneTargetConfig } from "./Octane.ts";
48
49 /** The `adapter.name` the AWS marker adapter declares. */
50 export const ADAPTER_NAME = "aws";
51
52 /** The optional legacy AWS marker adapter module for existing configs. */
53 export const ADAPTER_PACKAGE = "@alchemy.run/frontend-frameworks/octane/aws-adapter";
54
55 /** Octane's emitted node server entry within the server output directory. */
56 export const SERVER_ENTRY_FILE_NAME = "entry.js";
57
58 /** The Lambda entry module the finishing pass emits beside `entry.js`. */
59 export const LAMBDA_ENTRY_FILE_NAME = "index.mjs";
60
61 /** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
62 export const LAMBDA_ADAPTER_FILE_NAME = "octane-aws-lambda.mjs";
63
64 /** AWS-specific knobs carried on the shared {@link OctaneTargetConfig}. */
65 export interface OctaneAwsTargetConfig extends OctaneTargetConfig {
66 /**
67 * Whether the emitted Lambda handler streams its response
68 * (`awslambda.streamifyResponse`, requires a Function URL with
69 * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
70 * APIGW/Function-URL events with a complete response object.
71 * @default true
72 */
73 readonly streaming?: boolean | undefined;
74 }
75
76 const fail = (message: string, cause?: unknown) =>
77 new DeployTargetError({ platform: "aws", message, cause });
78
79 /**
80 * The generated Lambda entry: imports Octane's fetch handler from
81 * `entry.js` and exports it wrapped for the Lambda Node.js runtime.
82 */
83 const generateLambdaEntry = (streaming: boolean): string => {
84 const wrap = streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
85 return `// Auto-generated by ${ADAPTER_PACKAGE.replace("/aws-adapter", "/aws")} — do not edit.
86 import { handler as fetchHandler } from "./${SERVER_ENTRY_FILE_NAME}";
87 import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";
88
89 export const handler = ${wrap}(fetchHandler);
90 `;
91 };
92
93 /**
94 * Resolve this package's built, self-contained `aws-lambda` adapter module
95 * on disk (it has no imports of its own, so a byte copy deploys as-is).
96 */
97 const resolveLambdaAdapterPath = Effect.try({
98 try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
99 catch: (cause) =>
100 fail(
101 'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
102 cause,
103 ),
104 });
105
106 const finish = (
107 config: OctaneAwsTargetConfig,
108 output: BuildOutput,
109 context: DeployTargetFinishContext,
110 ): Effect.Effect<BuildOutput, DeployTargetError, FileSystem.FileSystem | Path.Path> =>
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 if (context.entry === undefined) {
115 return yield* fail("The Octane build produced no on-disk server entry to finish");
116 }
117 const serverDir = path.dirname(context.entry);
118
119 // The Lambda Node.js runtime classifies `.js` modules by the nearest
120 // package.json, and `dist/server` ships as the deployment root without
121 // one — Octane's ESM `entry.js` needs the marker to load as ESM.
122 yield* fs.writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n');
123
124 const adapterPath = yield* resolveLambdaAdapterPath;
125 const adapterSource = yield* fs.readFileString(adapterPath);
126 yield* fs.writeFileString(
127 path.join(serverDir, LAMBDA_ADAPTER_FILE_NAME),
128 // Drop the sourcemap pointer — the map is not copied into the bundle.
129 adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
130 );
131
132 yield* fs.writeFileString(
133 path.join(serverDir, LAMBDA_ENTRY_FILE_NAME),
134 generateLambdaEntry(config.streaming !== false),
135 );
136
137 // Re-read the server directory so the emitted files (and runtime inputs
138 // like the SSR `index.html` the entry reads beside itself) are part of
139 // the output, with the Lambda entry first.
140 const modules = yield* readServerModulesFromDisk({
141 directory: serverDir,
142 prefix: "server",
143 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
144 return {
145 ...output,
146 serverModules: sortServerModules(modules, `server/${LAMBDA_ENTRY_FILE_NAME}`),
147 };
148 }).pipe(
149 Effect.catchTag("PlatformError", (error) =>
150 Effect.fail(fail("Failed to emit the Lambda entry", error)),
151 ),
152 );
153
154 /**
155 * The native Node output target — the shape the framework's regular
156 * build/finish pipeline consumes. Used directly in the build child (where
157 * `cwd === root` holds); {@link makeAwsTarget} wraps it with the wholesale
158 * `build` hook that spawns the child.
159 */
160 const makeAwsAdapterTarget = (config: OctaneAwsTargetConfig = {}): OctaneTarget =>
161 makeDeployTarget({
162 platform: "aws",
163 config,
164 bundle: {
165 conditions: ["node", "import", "module"],
166 external: ["@aws-sdk/"],
167 },
168 adapterName: ADAPTER_NAME,
169 adapterPackage: ADAPTER_PACKAGE,
170 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
171 finish: (output, context) => finish(config, output, context),
172 });
173
174 /**
175 * Octane's production build runs the project's own `vite build`, whose
176 * natively-loaded `vite.config.*` / `octane.config.ts` execute user plugins
177 * that may read the cwd, mutate `process.env`, or `process.chdir` — none of
178 * which may touch the engine process (many deploys share one event loop).
179 * This target's wholesale `build` therefore runs the framework in a
180 * disposable child process whose working directory IS the project root (see
181 * `core/BuildChild.ts`). The shared `core/BuildChildRunner` entry imports
182 * this module in the child and calls the exported {@link buildInChild}.
183 */
184 export interface OctaneAwsBuildChildConfig {
185 readonly rootDir: string;
186 /** The (JSON-serializable) target config the parent was created with. */
187 readonly config: OctaneAwsTargetConfig;
188 }
189
190 export const buildInChild = (config: OctaneAwsBuildChildConfig) =>
191 Effect.gen(function* () {
192 const framework = yield* make({
193 root: config.rootDir,
194 // The finish-only target: no wholesale `build` hook, so the child
195 // runs the regular vite build + finish pipeline (no recursion).
196 target: makeAwsAdapterTarget(config.config),
197 compatibilityDate: config.config.compatibilityDate,
198 compatibilityFlags: config.config.compatibilityFlags,
199 });
200 return yield* framework.build({ root: config.rootDir });
201 });
202
203 /**
204 * Create the AWS Lambda {@link OctaneTarget}. See the module doc for the
205 * seams.
206 */
207 export const makeAwsTarget = (config: OctaneAwsTargetConfig = {}): OctaneTarget => ({
208 ...makeAwsAdapterTarget(config),
209 build: (context) =>
210 runBuildChild({
211 module: import.meta.url,
212 rootDir: context.root,
213 env: context.env,
214 framework: "octane",
215 config: {
216 rootDir: context.root,
217 config,
218 } satisfies OctaneAwsBuildChildConfig,
219 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
220 });
221
222 /**
223 * The deploy-target module contract (`resolveDeployTarget` accepts the
224 * default export — or the named `target` export — as a value or factory).
225 */
226 export const target = makeAwsTarget;
227
228 export default makeAwsTarget;