@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 706 lines 31.6 KB
Raw
1 import { appendFile, readFile, rename, unlink, writeFile } from "node:fs/promises";
2 import { fileURLToPath } from "node:url";
3 import { KvNamespace } from "@alchemy.run/cloudflare-runtime/core/bindings";
4 import type { CloudflareVitePluginOptions } from "@alchemy.run/cloudflare-runtime/vite";
5 import cloudflareVitePlugin from "@alchemy.run/cloudflare-runtime/vite";
6 // Alchemy modifications are licensed under Apache-2.0.
7 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
8 /**
9 * Wrangler-free fork of `@astrojs/cloudflare`'s `createIntegration`
10 * (v14.1.3, `src/index.ts`) with:
11 *
12 * - `@cloudflare/vite-plugin` swapped for `@alchemy.run/cloudflare-runtime/vite`
13 * (main defaults to this package's vendored server entrypoint, entry env `ssr`,
14 * Astro's node-side `astro`/`prerender` environments in `skipEnvironments`).
15 * - `loadWranglerEnv`, wrangler config watchers, `previewEntrypoint`, and the
16 * output-wrangler.json patch dropped.
17 * (The `astro:build:done` wrangler.json assets-directory patch is replaced
18 * by the cloudflare target's `finish` pass over `BuildOutput` — see
19 * `cloudflare.ts` — and the vestigial parse of a pre-existing `_redirects`
20 * file, whose result upstream never uses, is dropped.)
21 * - `prerenderEnvironment: 'workerd'` by default like upstream, but the
22 * prerenderer serves the built `prerender` environment through
23 * `cloudflare-runtime` instead of a Vite preview server wrapped around
24 * `@cloudflare/vite-plugin` (see `prerenderer.ts`); `'node'` falls back to
25 * Astro's stock node prerenderer.
26 * - Zero-config sessions mirrored from upstream: when `config.session.driver`
27 * is unset, the `cloudflareKVBinding` driver is configured against the
28 * `sessionKVBindingName` KV binding; in dev, a local in-memory KV namespace
29 * (`KvNamespace.local`) is injected into the worker bindings. Opt out with
30 * `sessions: false`.
31 * - The image service is `passthrough` (workerd cannot run sharp, and the
32 * IMAGES binding is remote-only in our runtime).
33 */
34 import { removeTrailingForwardSlash } from "@astrojs/internal-helpers/path";
35 import { createRedirectsFromAstroRoutes, printAsRedirects } from "@astrojs/underscore-redirects";
36 import type { AstroConfig, AstroIntegration, IntegrationResolvedRoute } from "astro";
37 import { passthroughImageService, sessionDrivers } from "astro/config";
38 import type * as vite from "vite";
39 import { usesCloudflareCacheProvider } from "./cache.ts";
40 import { createConfigPlugin } from "./config-plugin.ts";
41 import { NODE_ENVIRONMENTS } from "./environments.ts";
42 import { buildAssetsHeadersContent } from "./headers.ts";
43 import { createWorkerdPrerenderEnvironmentPlugin } from "./prerender-environment.ts";
44 import { createNodePrerenderPlugin } from "./prerender-middleware.ts";
45
46 /** The Worker entry module (the vendored `@astrojs/cloudflare` server entrypoint). */
47 export const SERVER_ENTRYPOINT = "@alchemy.run/frontend-frameworks/astro/entrypoints/server";
48
49 /** The production endpoint of the passthrough image service. */
50 export const IMAGE_PASSTHROUGH_ENDPOINT = fileURLToPath(
51 import.meta.resolve("@alchemy.run/frontend-frameworks/astro/image-passthrough-endpoint"),
52 );
53
54 export interface DistilledCloudflareOptions {
55 /**
56 * Options forwarded to `@alchemy.run/cloudflare-runtime/vite`
57 * (compatibility date/flags, worker name/bindings/assets, runtime context).
58 * `viteEnvironments` and the Astro node environments in `skipEnvironments`
59 * are managed by the integration. `main` defaults to the vendored server
60 * entrypoint ({@link SERVER_ENTRYPOINT}); set it to deploy a custom Worker
61 * entry that wraps that entrypoint's handler.
62 */
63 readonly vite?: CloudflareVitePluginOptions | undefined;
64 /**
65 * Which runtime prerenders static pages at build time.
66 *
67 * - `'workerd'` (default, matching upstream): the `prerender` environment
68 * is built as a Worker (same treatment as the `ssr` environment) and
69 * served from workerd via `cloudflare-runtime`, so prerendered pages run
70 * in the production runtime — top-level `cloudflare:*` imports and the
71 * configured worker bindings included.
72 * - `'node'`: Astro's stock node prerender environment. Fallback for pages
73 * that depend on Node-only APIs at build time.
74 * @default "workerd"
75 */
76 readonly prerenderEnvironment?: "workerd" | "node" | undefined;
77 /**
78 * The name of the KV binding injected into Astro's session config when
79 * present on the Worker env.
80 * @default "SESSION"
81 */
82 readonly sessionKVBindingName?: string | undefined;
83 /**
84 * Zero-config sessions (mirrors upstream `@astrojs/cloudflare`): when no
85 * `session.driver` is configured, Astro's `cloudflareKVBinding` session
86 * driver is configured against the {@link sessionKVBindingName} KV
87 * binding. Set to `false` to leave the session config untouched (sessions
88 * stay off unless you configure a driver yourself).
89 * @default true
90 */
91 readonly sessions?: boolean | undefined;
92 /**
93 * Automatically add an in-memory local KV namespace
94 * (`KvNamespace.local({ binding: sessionKVBindingName })`) so zero-config
95 * sessions work without any setup: in dev it is appended to the dev worker
96 * bindings; at build time (workerd prerendering) it is appended to the
97 * prerender environment worker's bindings so session-touching pages can
98 * prerender (the deployed Worker still uses its real KV binding — the
99 * prerender KV is ephemeral, matching upstream's local preview bindings).
100 * Disable when the bindings already carry a KV binding with that name
101 * (binding names must be unique) — e.g. when an outer toolchain provisions
102 * the session namespace itself and passes it through
103 * `vite.worker.bindings`.
104 * @default true
105 */
106 readonly sessionDevKV?: boolean | undefined;
107 /**
108 * Reports the absolute path of the *original* client build directory
109 * (`config.build.client` before the `base !== "/"` remap nests it). The
110 * cloudflare target's `finish` pass uses it to point
111 * `BuildOutput.clientDirectory` back at the directory that should be
112 * served at the URL root.
113 * @internal
114 */
115 readonly onOriginalClientDir?: ((dir: string) => void) | undefined;
116 /**
117 * Reports the resolved build output mode (`astro:config:done`'s
118 * `buildOutput`): `"static"` when every route is prerendered, `"server"`
119 * when any route renders on demand. The cloudflare target's `finish` pass
120 * uses it to strip `serverModules` from a fully-static build so the deploy
121 * is assets-only (no worker).
122 * @internal
123 */
124 readonly onBuildOutput?: ((buildOutput: "static" | "server") => void) | undefined;
125 }
126
127 /**
128 * Upstream `@astrojs/cloudflare` adapter options this fork deliberately does
129 * not support, with the reason / migration. Passing one raises immediately
130 * instead of being silently ignored.
131 */
132 const UNSUPPORTED_UPSTREAM_OPTIONS: Record<string, string> = {
133 imageService:
134 "the image service is hardwired to `passthrough` (workerd cannot run sharp, and the IMAGES binding is remote-only in our runtime)",
135 imagesBindingName:
136 "the Cloudflare Images binding image service is not supported (the IMAGES binding is remote-only in our runtime)",
137 platformProxy:
138 "there is no wrangler platform proxy; dev bindings are passed via `vite.worker.bindings`",
139 configPath: "there is no wrangler config file; pass worker options via `vite`",
140 persistState: "workerd state is in-memory in this fork's dev runtime",
141 auxiliaryWorkers:
142 "auxiliary workers are not supported; compose bindings via `vite.worker.bindings`",
143 inspectorPort: "the workerd inspector is not exposed by this fork's dev runtime",
144 viteEnvironment: "the worker environment is pinned to Astro's `ssr` environment",
145 cloudflareModules:
146 "`.wasm`/`.bin`/`.txt` worker modules are handled by `@alchemy.run/cloudflare-runtime/vite`",
147 experimental: "upstream experimental options are not supported by this fork",
148 };
149
150 /** Reject upstream adapter options we would otherwise silently ignore. */
151 const assertSupportedOptions = (options: DistilledCloudflareOptions): void => {
152 const offending = Object.keys(options).filter((key) => key in UNSUPPORTED_UPSTREAM_OPTIONS);
153 if (offending.length > 0) {
154 throw new Error(
155 "@alchemy.run/frontend-frameworks/astro: unsupported @astrojs/cloudflare option(s):\n" +
156 offending.map((key) => ` - \`${key}\`: ${UNSUPPORTED_UPSTREAM_OPTIONS[key]}`).join("\n") +
157 "\nSupported options: `vite`, `prerenderEnvironment`, `sessionKVBindingName`, `sessions`, `sessionDevKV`.",
158 );
159 }
160 };
161
162 /**
163 * Whether the (possibly zero-config-defaulted) session config uses Astro's
164 * `cloudflareKVBinding` driver — vendored from upstream
165 * (`usesCloudflareKVSessionDriver`).
166 */
167 const CLOUDFLARE_KV_SESSION_DRIVER_ENTRYPOINT = sessionDrivers.cloudflareKVBinding().entrypoint;
168
169 type SessionConfigLike =
170 | {
171 // Astro types `entrypoint` as optional `any` (it comes from a
172 // `z.instanceof(URL)` schema), though its config validation requires it.
173 driver?: string | { entrypoint?: string | URL } | undefined;
174 cookie?: unknown;
175 ttl?: unknown;
176 }
177 | undefined;
178
179 export const usesCloudflareKVSessionDriver = (session: SessionConfigLike): boolean => {
180 const driver = session?.driver;
181 if (!driver) {
182 return false;
183 }
184 if (typeof driver === "string") {
185 return driver === "cloudflareKVBinding" || driver === "cloudflare-kv-binding";
186 }
187 if (driver.entrypoint == null) {
188 return false;
189 }
190 const entrypoint = String(driver.entrypoint);
191 return (
192 entrypoint === CLOUDFLARE_KV_SESSION_DRIVER_ENTRYPOINT ||
193 entrypoint.endsWith("cloudflare-kv-binding")
194 );
195 };
196
197 /**
198 * Append the in-memory local session KV namespace to the dev worker
199 * bindings (exported for testing). Binding names must be unique per worker:
200 * if the dev bindings already carry a `sessionKVBindingName` KV binding,
201 * disable this injection with `sessionDevKV: false` (or rename via
202 * `sessionKVBindingName`).
203 */
204 export const withDevSessionKv = (
205 viteOptions: CloudflareVitePluginOptions | undefined,
206 binding: string,
207 ): CloudflareVitePluginOptions => ({
208 ...viteOptions,
209 // A bindings-only worker is fine: the dev server generates a worker name
210 // when none is configured.
211 worker: {
212 ...viteOptions?.worker,
213 bindings: [...(viteOptions?.worker?.bindings ?? []), KvNamespace.local({ binding })],
214 } as CloudflareVitePluginOptions["worker"],
215 });
216
217 /**
218 * The workerd prerenderer's vite-plugin options (exported for testing): when
219 * zero-config sessions resolved to the Cloudflare KV driver, the same
220 * in-memory local KV namespace that dev injects is appended to the prerender
221 * worker's bindings — session-touching pages can then prerender without the
222 * deployed Worker's real KV namespace existing at build time (upstream's
223 * prerender worker receives the local preview bindings the same way). The
224 * KV is ephemeral: session state written during prerendering is discarded
225 * with the prerender worker. `sessionDevKV: false` opts out (e.g. when the
226 * caller's own `vite.worker.bindings` already carry the session binding).
227 */
228 export const withPrerenderSessionKv = (
229 viteOptions: CloudflareVitePluginOptions | undefined,
230 options: {
231 readonly needsSessionKVBinding: boolean;
232 readonly sessionDevKV: boolean;
233 readonly binding: string;
234 },
235 ): CloudflareVitePluginOptions | undefined =>
236 options.needsSessionKVBinding && options.sessionDevKV
237 ? withDevSessionKv(viteOptions, options.binding)
238 : viteOptions;
239
240 /**
241 * The `@alchemy.run/cloudflare-runtime/vite` options for an Astro project:
242 * user options with `main` defaulted to the vendored server entrypoint, the
243 * worker pinned to Astro's `ssr` environment, and Astro's node-side
244 * environments merged into `skipEnvironments` (exported for testing).
245 *
246 * A user `main` (the deploy target's user-entry seam) takes precedence: a
247 * Worker entry that wraps the vendored entrypoint's handler (imported from
248 * {@link SERVER_ENTRYPOINT}) and adds exports of its own — Durable Object
249 * classes, a `scheduled` handler. The vite plugin resolves it against the
250 * Astro root. The workerd `prerender` environment keeps building the vendored
251 * entrypoint: prerendering only needs Astro's handler.
252 *
253 * During a `build` with `prerenderEnvironment: "workerd"`, the `prerender`
254 * environment stops being a skipped node environment and becomes a child
255 * worker environment instead: it gets the full worker treatment (workerd
256 * resolve conditions, unenv polyfills, `cloudflare:` externals) so its
257 * output can be loaded into workerd by the prerenderer. In dev, `prerender`
258 * stays skipped in both modes — workerd mode has no prerender dev
259 * environment at all (prerenderable routes are served through the entry
260 * worker's dev-match path).
261 */
262 export const makeIntegrationPluginOptions = (
263 viteOptions: CloudflareVitePluginOptions = {},
264 {
265 prerenderEnvironment = "node",
266 command = "dev",
267 }: {
268 prerenderEnvironment?: "workerd" | "node";
269 command?: "dev" | "build" | "preview" | "sync";
270 } = {},
271 ): CloudflareVitePluginOptions => {
272 const workerdPrerender = prerenderEnvironment === "workerd" && command === "build";
273 return {
274 ...viteOptions,
275 main: viteOptions.main ?? SERVER_ENTRYPOINT,
276 viteEnvironments: workerdPrerender
277 ? { entry: "ssr", children: ["prerender"] }
278 : { entry: "ssr" },
279 skipEnvironments: [
280 ...new Set(
281 [...NODE_ENVIRONMENTS, ...(viteOptions.skipEnvironments ?? [])].filter(
282 (name) => !(workerdPrerender && name === "prerender"),
283 ),
284 ),
285 ],
286 };
287 };
288
289 export function distilledCloudflare(options: DistilledCloudflareOptions = {}): AstroIntegration {
290 assertSupportedOptions(options);
291 const prerenderEnvironment = options.prerenderEnvironment ?? "workerd";
292 const sessionKVBindingName = options.sessionKVBindingName ?? "SESSION";
293 const sessions = options.sessions ?? true;
294 const sessionDevKV = options.sessionDevKV ?? true;
295 let _config: AstroConfig;
296 let _buildOutput: "static" | "server";
297 let _originalClientDir: URL;
298 let _routes: Array<IntegrationResolvedRoute> = [];
299 // Whether the (possibly zero-config-defaulted) session config resolved to
300 // the Cloudflare KV driver — set at `astro:config:setup`, read at
301 // `astro:build:start` to give the workerd prerender worker a local
302 // session KV.
303 let _needsSessionKVBinding = false;
304 // Whether WE satisfied `config.adapter`. The user's astro.config.* loads
305 // natively and this integration is injected via `integrations`, but
306 // astro's build refuses server output unless `config.adapter` is set — so
307 // `astro:config:setup` injects a hookless marker when the config declares
308 // no adapter (the real adapter registration is `setAdapter` at
309 // `astro:config:done`). When the flag is still false at
310 // `astro:config:done`, the user declared their own adapter — a conflict.
311 let _injectedAdapterMarker = false;
312 return {
313 name: "@alchemy.run/frontend-frameworks/astro",
314 hooks: {
315 "astro:config:setup": ({ command, config, updateConfig, logger }) => {
316 const isTypeGenPhase = command === "build" || command === "sync";
317 const userOptimizeDeps = config.vite?.optimizeDeps;
318 // Route caching through Workers Cache (mirrors upstream's
319 // `needsWorkerCache`). The provider module is pre-bundled with the
320 // rest of the server runtime so dev does not re-optimize on first use.
321 const needsWorkerCache = usesCloudflareCacheProvider(config);
322 const cacheProviderEntrypoint = config.cache?.provider?.entrypoint;
323
324 // Zero-config sessions (mirrors upstream): default the session
325 // driver to Cloudflare KV against `sessionKVBindingName` when the
326 // user hasn't configured one.
327 // `session: false` is the user explicitly disabling sessions —
328 // respect it and skip the zero-config defaulting.
329 let session = config.session;
330 if (sessions && session !== false && !session?.driver) {
331 logger.info(
332 `Enabling sessions with Cloudflare KV with the "${sessionKVBindingName}" KV binding.`,
333 );
334 session = {
335 driver: sessionDrivers.cloudflareKVBinding({
336 binding: sessionKVBindingName,
337 }),
338 cookie: session?.cookie,
339 ttl: session?.ttl,
340 } as typeof config.session;
341 }
342 const needsSessionKVBinding =
343 sessions && session !== false && usesCloudflareKVSessionDriver(session);
344 _needsSessionKVBinding = needsSessionKVBinding;
345
346 // In dev, satisfy the session KV binding with an in-memory local KV
347 // namespace so zero-config sessions work without any setup.
348 const viteOptions =
349 command === "dev" && needsSessionKVBinding && sessionDevKV
350 ? withDevSessionKv(options.vite, sessionKVBindingName)
351 : options.vite;
352
353 const cloudflarePlugins = cloudflareVitePlugin(
354 makeIntegrationPluginOptions(viteOptions, {
355 prerenderEnvironment,
356 command,
357 }),
358 ) as Array<vite.Plugin>;
359
360 // Same trick as upstream (astro#16332): `build`/`sync` run type
361 // generation, which creates a temporary Vite server and fires
362 // `configureServer` — that would boot workerd mid-build. Stripping
363 // the hook degrades our dev environments to runnable stubs, a
364 // supported contract of the dev plugin.
365 if (isTypeGenPhase) {
366 for (const plugin of cloudflarePlugins) {
367 plugin.configureServer = undefined;
368 }
369 }
370
371 if (config.adapter === undefined) {
372 // Satisfy astro's `config.adapter` existence check (the build
373 // refuses server output without it). Hookless on purpose: the
374 // marker is inert even if a later `runHookConfigSetup` pass
375 // unshifts it into `integrations`; the real adapter is registered
376 // via `setAdapter` at `astro:config:done`.
377 _injectedAdapterMarker = true;
378 updateConfig({
379 adapter: {
380 name: "@alchemy.run/frontend-frameworks/astro",
381 hooks: {},
382 },
383 });
384 }
385
386 updateConfig({
387 build: { redirects: false },
388 session,
389 vite: {
390 plugins: [
391 // Node mode only: in workerd mode dev has no prerender
392 // environment — prerenderable routes are served through the
393 // entry worker's dev-match path, same as upstream.
394 ...(command === "dev" && prerenderEnvironment === "node"
395 ? [createNodePrerenderPlugin()]
396 : []),
397 ...(prerenderEnvironment === "workerd"
398 ? [createWorkerdPrerenderEnvironmentPlugin(SERVER_ENTRYPOINT)]
399 : []),
400 cloudflarePlugins,
401 {
402 name: "@alchemy.run/frontend-frameworks/astro:cf-imports",
403 enforce: "pre",
404 resolveId: {
405 filter: { id: /^cloudflare:/ },
406 handler(id) {
407 return { id, external: true };
408 },
409 },
410 } satisfies vite.Plugin,
411 {
412 name: "@alchemy.run/frontend-frameworks/astro:environment",
413 configEnvironment(environmentName, environmentOptions) {
414 if (isTypeGenPhase) {
415 return { optimizeDeps: { noDiscovery: true, include: [] } };
416 }
417 const isServerEnvironment = ["astro", "ssr", "prerender"].includes(
418 environmentName,
419 );
420 if (isServerEnvironment && !environmentOptions.optimizeDeps?.noDiscovery) {
421 return {
422 optimizeDeps: {
423 include: [
424 SERVER_ENTRYPOINT,
425 "astro",
426 "astro/runtime/**",
427 "astro > html-escaper",
428 "astro > mrmime",
429 "astro > zod/v4",
430 "astro > zod/v4/core",
431 "astro > clsx",
432 "astro > cookie",
433 "astro > devalue",
434 "astro > @oslojs/encoding",
435 "astro > es-module-lexer",
436 "astro > unstorage",
437 "astro > neotraverse/modern",
438 "astro > piccolore",
439 "astro > picomatch",
440 "astro/app",
441 "astro/app/manifest",
442 "astro/logger/console",
443 "astro/app/fetch/default-handler",
444 "astro/fetch",
445 "astro/assets",
446 "astro/assets/services/noop",
447 "astro/assets/runtime",
448 "astro/assets/utils/inferRemoteSize.js",
449 "astro/assets/fonts/runtime.js",
450 "astro/compiler-runtime",
451 "astro/jsx-runtime",
452 "astro/app/entrypoint/dev",
453 "astro/virtual-modules/middleware.js",
454 "astro/virtual-modules/transitions.js",
455 "astro/virtual-modules/transitions-events.js",
456 "astro/virtual-modules/transitions-router.js",
457 "astro/virtual-modules/transitions-swap-functions.js",
458 "astro/virtual-modules/transitions-types.js",
459 "astro/components",
460 ...(needsWorkerCache && typeof cacheProviderEntrypoint === "string"
461 ? [cacheProviderEntrypoint]
462 : []),
463 ...(Array.isArray(userOptimizeDeps?.include)
464 ? userOptimizeDeps.include
465 : []),
466 ],
467 exclude: [
468 "unstorage/drivers/cloudflare-kv-binding",
469 "astro:*",
470 "virtual:astro:*",
471 "virtual:astro-cloudflare:*",
472 "virtual:@astrojs/*",
473 "@astrojs/starlight",
474 ...(Array.isArray(userOptimizeDeps?.exclude)
475 ? userOptimizeDeps.exclude
476 : []),
477 ],
478 },
479 };
480 } else if (environmentName === "client") {
481 return {
482 optimizeDeps: {
483 include: ["astro/runtime/client/dev-toolbar/entrypoint.js"],
484 ignoreOutdatedRequests: true,
485 },
486 };
487 }
488 return undefined;
489 },
490 } satisfies vite.Plugin,
491 {
492 enforce: "post",
493 name: "@alchemy.run/frontend-frameworks/astro:cf-externals",
494 applyToEnvironment: (environment) =>
495 environment.name === "ssr" || environment.name === "prerender",
496 config(conf) {
497 if (conf.ssr) {
498 // Cloudflare does not support externalizing modules in server environments
499 conf.ssr.external = undefined;
500 }
501 },
502 } satisfies vite.Plugin,
503 createConfigPlugin({
504 sessionKVBindingName,
505 compileImageConfig: null,
506 cacheProviderEnabled: needsWorkerCache,
507 }),
508 ],
509 },
510 image: {
511 ...config.image,
512 service: passthroughImageService(),
513 endpoint: (command === "dev"
514 ? { entrypoint: "astro/assets/endpoint/generic" }
515 : { entrypoint: IMAGE_PASSTHROUGH_ENDPOINT }) as never,
516 },
517 });
518 },
519 "astro:routes:resolved": ({ routes }) => {
520 _routes = routes;
521 },
522 "astro:config:done": ({ setAdapter, config, injectTypes, buildOutput }) => {
523 // The user's astro.config.* loads natively and this integration is
524 // merged over it, so a user-declared adapter (e.g. upstream
525 // @astrojs/cloudflare) would collide with the one the deploy target
526 // provides. Fail with an actionable error instead of letting the two
527 // adapters race.
528 if (config.adapter !== undefined && !_injectedAdapterMarker) {
529 throw new Error(
530 `@alchemy.run/frontend-frameworks/astro: the Astro config declares the adapter "${config.adapter.name}", ` +
531 "but the deploy target already provides the Cloudflare adapter. " +
532 "Remove `adapter` from your astro.config file — user integrations " +
533 "(react, mdx, tailwind, ...) are honored, and the adapter is injected by the toolchain.",
534 );
535 }
536 _config = config;
537 _buildOutput = buildOutput;
538 options.onBuildOutput?.(buildOutput);
539 _originalClientDir = new URL(config.build.client.href);
540 if (config.base !== "/") {
541 // Nest the client build under the base so the assets directory can
542 // be served at the URL root (`/base/foo.css` →
543 // `dist/client/base/foo.css`). `astro:build:done` moves the special
544 // files back up, and the cloudflare target's `finish` pass points
545 // `BuildOutput.clientDirectory` back at the original directory.
546 config.build.client = new URL("." + config.base + "/", config.build.client);
547 }
548 options.onOriginalClientDir?.(fileURLToPath(_originalClientDir));
549 injectTypes({
550 filename: "cloudflare.d.ts",
551 content: '/// <reference types="@alchemy.run/frontend-frameworks/astro/types.d.ts" />',
552 });
553 setAdapter({
554 name: "@alchemy.run/frontend-frameworks/astro",
555 adapterFeatures: {
556 buildOutput,
557 middlewareMode: "classic",
558 preserveBuildClientDir: true,
559 preserveBuildServerDir: true,
560 },
561 entrypointResolution: "auto",
562 supportedAstroFeatures: {
563 serverOutput: "stable",
564 hybridOutput: "stable",
565 staticOutput: "stable",
566 i18nDomains: "experimental",
567 sharpImageService: {
568 support: "limited",
569 message: "workerd cannot run sharp",
570 },
571 envGetSecret: "stable",
572 },
573 });
574 },
575 "astro:build:start": async ({ setPrerenderer }) => {
576 if (prerenderEnvironment !== "workerd") {
577 return;
578 }
579 // Lazy: the prerenderer pulls Effect + cloudflare-runtime, which
580 // `astro dev` and node-mode builds never need.
581 const { createWorkerdPrerenderer } = await import("./prerenderer.ts");
582 setPrerenderer(
583 createWorkerdPrerenderer({
584 serverDir: _config.build.server,
585 // With `base !== "/"` the client build is nested under the base
586 // (`astro:config:done` above); assets are served from the
587 // original client root, so that is the prerender worker's assets
588 // directory too.
589 clientDir: _originalClientDir,
590 trailingSlash: _config.trailingSlash,
591 // Zero-config sessions: the prerender worker gets an ephemeral
592 // in-memory SESSION KV (the deployed Worker's real namespace
593 // need not exist at build time). See `withPrerenderSessionKv`.
594 vite: withPrerenderSessionKv(options.vite, {
595 needsSessionKVBinding: _needsSessionKVBinding,
596 sessionDevKV,
597 binding: sessionKVBindingName,
598 }),
599 }),
600 );
601 },
602 "astro:build:setup": ({ vite: viteConfig, target }) => {
603 if (target === "server") {
604 viteConfig.resolve ||= {};
605 viteConfig.resolve.alias ||= {};
606 viteConfig.ssr ||= {};
607 viteConfig.ssr.noExternal = true;
608
609 viteConfig.build ||= {};
610 const build = viteConfig.build as Record<string, any>;
611 build.rolldownOptions ||= {};
612 build.rolldownOptions.output ||= {};
613 build.rolldownOptions.external = ["sharp"];
614 build.rolldownOptions.output.banner ||=
615 "globalThis.process ??= {}; globalThis.process.env ??= {};";
616
617 viteConfig.define = {
618 "process.env": "process.env",
619 "globalThis.__ASTRO_IMAGES_BINDING_NAME": JSON.stringify("IMAGES"),
620 ...viteConfig.define,
621 };
622 }
623 },
624 "astro:build:done": async ({ dir, logger, assets }) => {
625 // base !== "/": the client build was nested under the base
626 // (`astro:config:done` above); the asset-server special files must
627 // live at the served directory's root, so move them back up.
628 if (_config.base !== "/") {
629 for (const file of [".assetsignore", "_headers", "_redirects"]) {
630 try {
631 await rename(
632 new URL(`./${file}`, _config.build.client),
633 new URL(`./${file}`, _originalClientDir),
634 );
635 } catch {
636 // The file was not emitted for this build.
637 }
638 }
639 // Upstream also patches the emitted wrangler.json's
640 // `assets.directory` here; this build has no wrangler.json — the
641 // cloudflare target's `finish` pass rewrites
642 // `BuildOutput.clientDirectory` instead (see `cloudflare.ts`).
643 }
644
645 // Immutable Cache-Control for the content-hashed assets directory.
646 if (_config.build.assetsPrefix) {
647 logger.debug(
648 "Skipping Cache-Control injection for assets — `build.assetsPrefix` is set, so assets are served from a different origin.",
649 );
650 } else {
651 const headersPath = new URL("./_headers", _originalClientDir);
652 const result = await buildAssetsHeadersContent(
653 {
654 assetsDir: _config.build.assets,
655 basePrefix: removeTrailingForwardSlash(_config.base),
656 headersPath,
657 },
658 (path) => readFile(path, "utf-8"),
659 );
660 if (result === null) {
661 logger.debug(
662 "Skipping Cache-Control injection — _headers already sets Cache-Control on a matching rule.",
663 );
664 } else {
665 const tempPath = new URL("./_headers.tmp", _originalClientDir);
666 try {
667 await writeFile(tempPath, result.content);
668 await rename(tempPath, headersPath);
669 } catch (err) {
670 await unlink(tempPath).catch(() => {});
671 throw err;
672 }
673 logger.info(
674 `Injected immutable Cache-Control for ${result.assetsPattern} into _headers.`,
675 );
676 }
677 }
678
679 // Emit `_redirects` entries for Astro's redirect routes (config
680 // `redirects` + `Astro.redirect` route files) so prerendered/static
681 // redirects are handled by the asset server ahead of the Worker.
682 const trueRedirects = createRedirectsFromAstroRoutes({
683 config: _config,
684 routeToDynamicTargetMap: new Map(
685 Array.from(
686 _routes.filter((route) => route.type === "redirect").map((route) => [route, ""]),
687 ),
688 ),
689 dir,
690 buildOutput: _buildOutput,
691 assets,
692 });
693 if (!trueRedirects.empty()) {
694 try {
695 await appendFile(
696 new URL("./_redirects", _originalClientDir),
697 printAsRedirects(trueRedirects),
698 );
699 } catch {
700 logger.error("Failed to write _redirects file");
701 }
702 }
703 },
704 },
705 };
706 }