1/**
2 * Build-side wiring for the `prerender` environment when it runs under
3 * workerd (`prerenderEnvironment: "workerd"`, the default — the analogue of
4 * upstream `@astrojs/cloudflare`'s `experimental.prerenderWorker` on
5 * `@cloudflare/vite-plugin`).
6 *
7 * Astro builds the `prerender` environment before the `ssr` environment
8 * (`buildApp` in astro's static build). When a custom prerenderer is
9 * registered, astro core deliberately does not set the environment's build
10 * input (its stock node entry `astro/entrypoints/prerender` would be wrong) —
11 * the adapter must supply it. This plugin points the input at the same
12 * vendored Worker server entrypoint the `ssr` environment builds, wrapped in
13 * the rolldown plugin's worker-entry virtual module so the bundle gets the
14 * identical treatment (unenv polyfill injection, default-export wrapping).
15 * The `virtual:astro-cloudflare:config` module evaluates
16 * `isPrerender === true` in this environment, which activates the vendored
17 * runtime's `__astro_*` prerender protocol endpoints in the built worker.
18 *
19 * The rest of the worker treatment (workerd resolve conditions, `cloudflare:`
20 * externals, nodejs-compat polyfills) comes from listing `prerender` as a
21 * child worker environment of the Cloudflare vite plugin instead of skipping
22 * it — see `makeIntegrationPluginOptions`.
23 */
24import { WORKER_ENTRY_PREFIX } from "@alchemy.run/cloudflare-runtime/rolldown/plugins";
25import type * as vite from "vite";
26
27/**
28 * Vite plugin that assigns the worker-wrapped server entrypoint as the
29 * `prerender` environment's build input. Build-only: the environment does not
30 * exist in dev (workerd mode serves prerenderable routes through the entry
31 * worker's dev-match path instead).
32 */
33export function createWorkerdPrerenderEnvironmentPlugin(
34 serverEntrypoint: string,
35): vite.Plugin {
36 return {
37 name: "@alchemy.run/frontend-frameworks/astro:workerd-prerender-environment",
38 apply: "build",
39 configEnvironment(name) {
40 if (name !== "prerender") return;
41 return {
42 build: {
43 rolldownOptions: {
44 input: `${WORKER_ENTRY_PREFIX}${serverEntrypoint}`,
45 },
46 },
47 };
48 },
49 };
50}