| 1 | /** |
| 2 | * `@alchemy.run/frontend-frameworks/astro/entrypoints/aws-server` — the AWS |
| 3 | * Lambda server entrypoint the AWS deploy target pins as the adapter's |
| 4 | * `serverEntrypoint`. |
| 5 | * |
| 6 | * Compiled by astro's `ssr` environment build (the `astro/app/entrypoint` |
| 7 | * virtual modules only resolve there), it builds the production `App` from |
| 8 | * the serialized manifest and exports the Lambda `handler`: |
| 9 | * |
| 10 | * - **streaming** (`awslambda.streamifyResponse`, requires a Function URL |
| 11 | * with `invokeMode: RESPONSE_STREAM`) when the `awslambda` global exists — |
| 12 | * i.e. on the AWS Lambda Node.js runtime — and streaming is enabled |
| 13 | * (the deploy target's default); |
| 14 | * - **buffered** (a complete payload-v2 response object) otherwise, so the |
| 15 | * module stays importable outside the Lambda sandbox (local invocation |
| 16 | * harnesses, `streaming: false` deployments behind buffered Function URLs |
| 17 | * or API Gateway). |
| 18 | */ |
| 19 | import { createApp } from "astro/app/entrypoint"; |
| 20 | import { setGetEnv } from "astro/env/setup"; |
| 21 | import { |
| 22 | toBufferedLambdaHandler, |
| 23 | toLambdaHandler, |
| 24 | type FetchHandler, |
| 25 | } from "../../aws-lambda/index.ts"; |
| 26 | |
| 27 | /** |
| 28 | * Replaced by the AWS deploy target's vite `define` at build time |
| 29 | * (see `astro/aws.ts`). Falls back to `true` when left unreplaced. |
| 30 | */ |
| 31 | declare const __ALCHEMY_ASTRO_AWS_STREAMING__: boolean | undefined; |
| 32 | |
| 33 | // astro:env `getSecret` reads process.env on the Lambda Node.js runtime. |
| 34 | setGetEnv((key) => process.env[key]); |
| 35 | |
| 36 | const app = createApp(); |
| 37 | |
| 38 | const fetchHandler: FetchHandler = (request) => |
| 39 | app.render(request, { |
| 40 | addCookieHeader: true, |
| 41 | // The Function URL (and CloudFront in front of it) prepend the viewer |
| 42 | // ip to `x-forwarded-for`; surface it as `Astro.clientAddress`. |
| 43 | clientAddress: |
| 44 | request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || |
| 45 | undefined, |
| 46 | }); |
| 47 | |
| 48 | const streaming = |
| 49 | typeof __ALCHEMY_ASTRO_AWS_STREAMING__ === "boolean" |
| 50 | ? __ALCHEMY_ASTRO_AWS_STREAMING__ |
| 51 | : true; |
| 52 | |
| 53 | export const handler = |
| 54 | streaming && (globalThis as { awslambda?: unknown }).awslambda !== undefined |
| 55 | ? toLambdaHandler(fetchHandler) |
| 56 | : toBufferedLambdaHandler(fetchHandler); |