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

main
ts 273 lines 11.5 KB
Raw
1 /**
2 * `@alchemy.run/frontend-frameworks/astro/aws` — the AWS Lambda deploy target
3 * for the Astro integration.
4 *
5 * Astro's AWS story is a plain Node SSR bundle behind a Lambda Function
6 * URL: the adapter integration pins this package's `aws-server` entrypoint
7 * (which wraps `App.render` with the `@alchemy.run/frontend-frameworks/aws-lambda`
8 * handler adapter) as the build's server entry, and forces the server build
9 * to be **self-contained** (`vite.ssr.noExternal: true`) so `dist/server`
10 * can ship to Lambda as-is (`bundle: false`). What this target owns:
11 *
12 * - **`integration`** — the adapter integration: registers itself via
13 * `setAdapter` at `astro:config:done` (rejecting a user-declared adapter
14 * with an actionable error), pins the `aws-server` entrypoint, and
15 * configures the server build for self-containment.
16 * - **`finish`** — a fully-static build (`output: "static"`: every route
17 * prerendered) deploys ASSETS-ONLY: `serverModules` is dropped so the
18 * composite skips the Lambda entirely.
19 * - **`selectServerEntry`** — pins the adapter's entry chunk as
20 * `serverModules[0]` (astro's page modules are rolldown inputs in the
21 * same environment, so the entry environment emits many entry chunks).
22 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
23 * (the Lambda Node.js runtime ships SDK v3) for callers that post-process
24 * server code.
25 *
26 * No `devPlatform`: `dev` runs Astro's own Node dev server, which is
27 * already the AWS Lambda programming model (plain Node).
28 */
29 import type { AstroInlineConfig, AstroIntegration } from "astro";
30 import * as Effect from "effect/Effect";
31 import { runBuildChild } from "../core/BuildChild.ts";
32 import { DeployTargetError, makeDeployTarget, type ServerEntryChunk } from "../core/index.ts";
33 import { make } from "./Astro.ts";
34 import type { AstroTarget, AstroTargetBuildContext } from "./Target.ts";
35
36 /**
37 * The importable specifier of this package's AWS Lambda server entrypoint —
38 * the module the adapter pins as `serverEntrypoint`. It exports the Lambda
39 * `handler` (streaming by default).
40 */
41 export const SERVER_ENTRYPOINT = "@alchemy.run/frontend-frameworks/astro/entrypoints/aws-server";
42
43 /** AWS-specific target configuration. */
44 export interface AstroAwsConfig {
45 /**
46 * Whether the emitted Lambda handler streams its response
47 * (`awslambda.streamifyResponse`, requires a Function URL with
48 * `invokeMode: RESPONSE_STREAM`). With `false` — or whenever the
49 * `awslambda` global is absent — the buffered handler answers
50 * APIGW/Function-URL events with a complete payload-v2 response object.
51 * @default true
52 */
53 readonly streaming?: boolean | undefined;
54 }
55
56 export interface AstroAwsTarget extends AstroTarget<AstroAwsConfig> {}
57
58 /** Options for {@link distilledAws} (the adapter integration). */
59 export interface DistilledAwsOptions {
60 /** See {@link AstroAwsConfig.streaming}. @default true */
61 readonly streaming?: boolean | undefined;
62 /**
63 * Reports the resolved build output mode (`astro:config:done`'s
64 * `buildOutput`): `"static"` when every route is prerendered, `"server"`
65 * when any route renders on demand. The target's `finish` pass uses it to
66 * strip `serverModules` from a fully-static build so the deploy is
67 * assets-only (no Lambda).
68 * @internal
69 */
70 readonly onBuildOutput?: ((buildOutput: "static" | "server") => void) | undefined;
71 /**
72 * Reports the resolved server-entry file name (`config.build.serverEntry`,
73 * `entry.mjs` by default) so the entry chunk can be pinned as
74 * `serverModules[0]`.
75 * @internal
76 */
77 readonly onServerEntryName?: ((name: string) => void) | undefined;
78 }
79
80 /**
81 * The AWS Lambda adapter integration for Astro. Injected via
82 * `integrations` (after the user's) rather than `adapter`: it registers
83 * itself as the adapter at `astro:config:done`, where it also rejects a
84 * user-declared adapter with an actionable error.
85 */
86 export const distilledAws = (options: DistilledAwsOptions = {}): AstroIntegration => {
87 // Whether WE satisfied `config.adapter`. The user's astro.config.* loads
88 // natively and this integration is injected via `integrations`, but
89 // astro's build refuses server output unless `config.adapter` is set — so
90 // `astro:config:setup` injects a hookless marker when the config declares
91 // no adapter (the real adapter registration is `setAdapter` at
92 // `astro:config:done`). When the flag is still false at
93 // `astro:config:done`, the user declared their own adapter — a conflict.
94 let injectedAdapterMarker = false;
95 return {
96 name: "@alchemy.run/frontend-frameworks/astro-aws",
97 hooks: {
98 "astro:config:setup": ({ config, updateConfig }) => {
99 if (config.adapter === undefined) {
100 injectedAdapterMarker = true;
101 updateConfig({
102 adapter: {
103 name: "@alchemy.run/frontend-frameworks/astro-aws",
104 hooks: {},
105 },
106 });
107 }
108 },
109 "astro:config:done": ({ setAdapter, config, buildOutput }) => {
110 if (config.adapter !== undefined && !injectedAdapterMarker) {
111 throw new Error(
112 `@alchemy.run/frontend-frameworks/astro/aws: the Astro config declares the adapter "${config.adapter.name}", ` +
113 "but the deploy target already provides the AWS Lambda adapter. " +
114 "Remove `adapter` from your astro.config file — user integrations " +
115 "(react, mdx, tailwind, ...) are honored, and the adapter is injected by the toolchain.",
116 );
117 }
118 options.onBuildOutput?.(buildOutput);
119 options.onServerEntryName?.(config.build.serverEntry);
120 setAdapter({
121 name: "@alchemy.run/frontend-frameworks/astro-aws",
122 entrypointResolution: "auto",
123 serverEntrypoint: SERVER_ENTRYPOINT,
124 adapterFeatures: {
125 buildOutput,
126 middlewareMode: "classic",
127 preserveBuildClientDir: true,
128 preserveBuildServerDir: true,
129 },
130 supportedAstroFeatures: {
131 serverOutput: "stable",
132 hybridOutput: "stable",
133 staticOutput: "stable",
134 i18nDomains: "experimental",
135 envGetSecret: "stable",
136 sharpImageService: {
137 support: "limited",
138 message:
139 "sharp is not shipped with the Lambda server bundle; install it as a project dependency to optimize images at build time",
140 },
141 },
142 });
143 },
144 "astro:build:setup": ({ vite: viteConfig, target }) => {
145 if (target === "server") {
146 // Self-contained dist/server: Lambda ships the directory as-is
147 // (`bundle: false`), so every server dependency must be bundled
148 // into the emitted chunks. Node builtins stay external
149 // automatically; sharp is a native module that can never bundle,
150 // and the Lambda Node.js runtime provides `@aws-sdk/*` v3.
151 viteConfig.ssr ||= {};
152 viteConfig.ssr.noExternal = true;
153 viteConfig.build ||= {};
154 const build = viteConfig.build as Record<string, any>;
155 build.rolldownOptions ||= {};
156 build.rolldownOptions.external = ["sharp", /^@aws-sdk\//];
157 viteConfig.define = {
158 __ALCHEMY_ASTRO_AWS_STREAMING__: JSON.stringify(options.streaming ?? true),
159 ...viteConfig.define,
160 };
161 }
162 },
163 },
164 };
165 };
166
167 const fail = (message: string, cause?: unknown) =>
168 new DeployTargetError({ platform: "aws", message, cause });
169
170 /**
171 * The adapter-driven target — the shape the framework's regular
172 * build/finish pipeline consumes. Used directly in the build child (where
173 * `cwd === root` holds); {@link target} wraps it with the wholesale
174 * `build` hook that spawns the child.
175 */
176 const makeAwsAdapterTarget = (config: AstroAwsConfig = {}): AstroAwsTarget => {
177 // The resolved build output mode from `astro:config:done`: `"static"`
178 // means every route is prerendered, so the deploy must be assets-only.
179 let buildOutput: "static" | "server" | undefined;
180 // The resolved server-entry file name (`entry.mjs` by default).
181 let serverEntryName: string | undefined;
182 return makeDeployTarget({
183 platform: "aws",
184 config,
185 bundle: {
186 conditions: ["node", "import", "module"],
187 external: ["@aws-sdk/"],
188 },
189 integration: () =>
190 distilledAws({
191 streaming: config.streaming,
192 onBuildOutput: (mode) => {
193 buildOutput = mode;
194 },
195 onServerEntryName: (name) => {
196 serverEntryName = name;
197 },
198 }),
199 // Astro's page modules are rolldown inputs of the `ssr` environment, so
200 // it emits many entry chunks; pin the adapter's server entry (renamed to
201 // `config.build.serverEntry` by astro, facade = the aws-server module).
202 selectServerEntry: (chunk: ServerEntryChunk): boolean =>
203 chunk.fileName === (serverEntryName ?? "entry.mjs") ||
204 (chunk.facadeModuleId !== null &&
205 /\/entrypoints\/aws-server\.(?:ts|js|mjs)$/.test(
206 chunk.facadeModuleId.replaceAll("\\", "/"),
207 )),
208 // A fully-static build deploys ASSETS-ONLY: the SSR entry astro bundled
209 // for prerendering is dropped from the output and the client directory
210 // carries all prerendered HTML, `404.html` included.
211 finish: (output) =>
212 Effect.succeed(buildOutput === "static" ? { ...output, serverModules: undefined } : output),
213 });
214 };
215
216 /**
217 * The natively-loaded `astro.config.*` executes user plugins/integrations
218 * that may read the cwd, mutate `process.env`, or `process.chdir` — none of
219 * which may touch the engine process (many deploys share one event loop).
220 * This target's wholesale `build` therefore runs the framework in a
221 * disposable child process whose working directory IS the project root (see
222 * `core/BuildChild.ts`). The shared `core/BuildChildRunner` entry imports
223 * this module in the child and calls the exported {@link buildInChild}.
224 */
225 export interface AstroAwsBuildChildConfig {
226 readonly rootDir: string;
227 /** The (JSON-serializable) target config the parent was created with. */
228 readonly config: AstroAwsConfig;
229 /**
230 * The inline Astro overlay the framework was constructed with
231 * (`AstroFrameworkOptions.astro`, carried through the build context).
232 * Only JSON-serializable fields cross the process boundary.
233 */
234 readonly astro: AstroInlineConfig | undefined;
235 }
236
237 export const buildInChild = (config: AstroAwsBuildChildConfig) =>
238 Effect.gen(function* () {
239 const framework = yield* make({
240 root: config.rootDir,
241 // The adapter-only target: no wholesale `build` hook, so the child
242 // runs the regular astro build + finish pipeline (no recursion).
243 target: makeAwsAdapterTarget(config.config),
244 astro: config.astro,
245 });
246 return yield* framework.build({ root: config.rootDir });
247 });
248
249 /**
250 * Build the AWS Lambda {@link AstroTarget}. See the module doc for the
251 * seams.
252 */
253 export const target = (config: AstroAwsConfig = {}): AstroAwsTarget => ({
254 ...makeAwsAdapterTarget(config),
255 build: (context: AstroTargetBuildContext) =>
256 runBuildChild({
257 module: import.meta.url,
258 rootDir: context.root,
259 env: context.env,
260 framework: "astro",
261 config: {
262 rootDir: context.root,
263 config,
264 astro: context.astro,
265 } satisfies AstroAwsBuildChildConfig,
266 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
267 });
268
269 /**
270 * The deploy-target module contract (`resolveDeployTarget` accepts the
271 * default export — or the named `target` export — as a value or factory).
272 */
273 export default target;