@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, 04:45 UTC

main
ts 568 lines 22 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodePath from "node:path";
3 import { pathToFileURL } from "node:url";
4 // Alchemy modifications are licensed under Apache-2.0.
5 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
6 /**
7 * In-memory SvelteKit `Adapter` — a wrangler-free fork of
8 * `@sveltejs/adapter-cloudflare`'s `adapt()`.
9 *
10 * Differences from upstream:
11 *
12 * - No `unstable_readConfig` / wrangler.json: always Workers mode with plain
13 * options (`dest` fixed to kit's `cloudflare` build directory, assets
14 * binding defaults to `ASSETS`).
15 * - No Pages mode, no `_routes.json`.
16 * - The worker shim is generated directly with real relative import paths
17 * (see `WorkerShim.ts`); upstream ships a prebuilt `files/worker.js` and
18 * string-replaces `SERVER`/`MANIFEST` placeholders.
19 * - `emulate()` supplies the dev `platform` from `cloudflare-runtime`'s
20 * platform proxy (`getPlatformProxy`) instead of wrangler's: real bindings
21 * round-trip through a workerd instance, `caches` actually stores/matches
22 * (wrangler's is a no-op), `cf`/`ctx` mocks match wrangler's.
23 *
24 * The adapter does **not** bundle the app: `adapt()` records the assets
25 * directory and the unbundled worker entry on `result`, and the `SvelteKit`
26 * Framework service runs the rolldown pass afterwards (replacing the bundling
27 * `wrangler deploy` performs for the upstream adapter).
28 *
29 * Note: this module runs as a SvelteKit build callback (kit calls `adapt()`
30 * inside Vite's `buildApp`), so it uses kit's synchronous `Builder` API and
31 * `node:fs` directly like upstream — it is framework-callback code, not an
32 * Effect service.
33 */
34 import type { BindingHooks } from "@alchemy.run/cloudflare-runtime/core";
35 import type { Adapter, Builder, Emulator } from "@sveltejs/kit";
36 import { generateWorkerShim } from "./WorkerShim.ts";
37
38 export interface CloudflareAdapterResult {
39 /**
40 * The static-assets directory (client build + prerendered pages +
41 * `_headers`/`_redirects`/`.assetsignore`) — upload wholesale as the
42 * Worker's assets directory; becomes `BuildOutput.clientDirectory`.
43 */
44 readonly dest: string;
45 /** The generated (unbundled) worker entry — input for the rolldown pass. */
46 readonly workerEntry: string;
47 }
48
49 export interface CloudflareAdapterOptions {
50 /**
51 * Name of the static-assets binding the worker shim serves files through.
52 * @default "ASSETS"
53 */
54 readonly assetsBinding?: string | undefined;
55 /**
56 * Mirror of Workers static assets `not_found_handling`, driving fallback
57 * page generation: `"404-page"` writes `404.html`,
58 * `"single-page-application"` writes `index.html` AND makes the worker
59 * shim defer router-level not-founds on navigation-shaped requests to the
60 * assets layer so the fallback governs (see `WorkerShim.ts`).
61 * @default "none"
62 */
63 readonly notFoundHandling?: "none" | "404-page" | "single-page-application" | undefined;
64 /**
65 * With `notFoundHandling: "404-page"`: `"spa"` renders the app shell as the
66 * fallback, `"plaintext"` writes a plain `Not Found` page.
67 * @default "plaintext"
68 */
69 readonly fallback?: "spa" | "plaintext" | undefined;
70 /**
71 * Project root used to locate user-authored `_headers` / `_redirects`
72 * files.
73 * @default process.cwd()
74 */
75 readonly root?: string | undefined;
76 /**
77 * Inputs for the dev platform returned from `emulate()` (see
78 * {@link CloudflareDevPlatformOptions}). When present, `emulate()` serves
79 * `platform = { env, ctx, caches, cf }` through `cloudflare-runtime`'s
80 * platform proxy; when absent (production builds), `emulate()` returns an
81 * inert empty platform.
82 */
83 readonly platform?: CloudflareDevPlatformOptions | undefined;
84 }
85
86 export interface CloudflareAdapter extends Adapter {
87 /** Populated by `adapt()`; consumed by the SvelteKit Framework service. */
88 readonly result: { current?: CloudflareAdapterResult };
89 /**
90 * Tear down dev resources held by the adapter (the platform-proxy workerd
91 * instance, when one was opened). Safe to call multiple times; a no-op
92 * when the proxy was never opened.
93 */
94 readonly dispose: () => Promise<void>;
95 }
96
97 /**
98 * Render kit's fallback page (the SPA / 404 app shell) in-process.
99 *
100 * `builder.generateFallback` delegates to a `worker_threads` fork whose
101 * ready/args handshake matches messages on the module's `import.meta.url`
102 * string. Under bun on Windows the parent and child spell that URL
103 * differently, the handshake never completes, and no fallback is written —
104 * the deployed site then 404s every client route (the assets layer has no
105 * shell to fall back to). These are kit's own `core/postbuild/fallback.js`
106 * steps, minus the fork; the build process is short-lived in every context
107 * that runs `adapt` (harness build, alchemy source build), so the fork's
108 * dangling-handle isolation buys nothing here.
109 */
110 const generateFallbackInProcess = async (builder: Builder, dest: string): Promise<void> => {
111 const kit = builder.config;
112 const serverRoot = NodePath.join(kit.outDir, "output", "server");
113 const load = async (file: string): Promise<Record<string, any>> =>
114 await import(/* @vite-ignore */ pathToFileURL(NodePath.join(serverRoot, file)).href);
115 const { configure } = await load("index.js");
116 const { manifest } = await load("manifest-full.js");
117
118 // kit's builder loads .env files through vite's `loadEnv`; the adapter
119 // only runs inside a build, where vite is importable. Fall back to the
120 // process env when it isn't (the shell render rarely reads env at all).
121 const env: Record<string, string> = await import("vite").then(
122 (vite) => vite.loadEnv("production", kit.env.dir, ""),
123 () =>
124 Object.fromEntries(
125 Object.entries(process.env).filter(
126 (entry): entry is [string, string] => typeof entry[1] === "string",
127 ),
128 ),
129 );
130
131 const { init, respond } = await configure({ building: true, manifest, env });
132 await init();
133 const origin = kit.paths.origin || "http://sveltekit-prerender";
134 const response: Response = await respond(new Request(`${origin}/[fallback]`), {
135 getClientAddress: () => {
136 throw new Error("Cannot read clientAddress during prerendering");
137 },
138 prerendering: {
139 fallback: true,
140 dependencies: new Map(),
141 remote_responses: new Map(),
142 resolved_route_ids: new Set(),
143 },
144 read: (file: string) => NodeFs.readFileSync(NodePath.join(kit.files.assets, file)),
145 });
146 if (!response.ok) {
147 throw new Error(`Could not create a fallback page — failed with status ${response.status}`);
148 }
149 NodeFs.writeFileSync(dest, await response.text());
150 };
151
152 export const makeCloudflareAdapter = (
153 options: CloudflareAdapterOptions = {},
154 ): CloudflareAdapter => {
155 const result: { current?: CloudflareAdapterResult } = {};
156 let emulator: CloudflareEmulator | undefined;
157 return {
158 name: "@alchemy.run/frontend-frameworks/sveltekit",
159 result,
160 async adapt(builder: Builder) {
161 const root = options.root ?? process.cwd();
162 const assetsBinding = options.assetsBinding ?? "ASSETS";
163 const dest = builder.getBuildDirectory("cloudflare");
164 const tmp = builder.getBuildDirectory("cloudflare-tmp");
165
166 builder.rimraf(dest);
167 builder.rimraf(tmp);
168 builder.mkdirp(dest);
169 builder.mkdirp(tmp);
170
171 // client assets and prerendered pages
172 const assetsDest = dest + builder.config.paths.base;
173 builder.mkdirp(assetsDest);
174 if (options.notFoundHandling === "404-page") {
175 // generate plaintext 404.html first, which can then be overridden by
176 // prerendering if the user defined such a page
177 const fallback = NodePath.join(assetsDest, "404.html");
178 if (options.fallback === "spa") {
179 await generateFallbackInProcess(builder, fallback);
180 } else {
181 NodeFs.writeFileSync(fallback, "Not Found");
182 }
183 }
184 builder.writeClient(assetsDest);
185 builder.writePrerendered(assetsDest);
186 if (options.notFoundHandling === "single-page-application") {
187 await generateFallbackInProcess(builder, NodePath.join(assetsDest, "index.html"));
188 }
189
190 // pre-built server instance: kit 3.0 no longer exposes the internal
191 // SSR manifest (`generateManifest` throws), so `generateServerInstance`
192 // writes `export const server = new Server(manifest)` straight to
193 // disk itself instead of returning a manifest string to embed.
194 builder.generateServerInstance(NodePath.join(tmp, "server.js"));
195
196 // route manifest module — built from kit's public Builder surface
197 // (`builder.manifest`, `builder.routes`, `builder.getAppPath()`) since
198 // the internal SSR manifest is no longer reachable outside the
199 // generated server module above.
200 NodeFs.writeFileSync(
201 NodePath.join(tmp, "manifest.js"),
202 `export const assets = new Set(${JSON.stringify(builder.manifest.assets.map((asset) => asset.path))});\n\n` +
203 `export const app_path = ${JSON.stringify(builder.getAppPath())};\n\n` +
204 `export const prerendered = new Set(${JSON.stringify(builder.prerendered.paths)});\n\n` +
205 `export const base_path = ${JSON.stringify(builder.config.paths.base)};\n\n` +
206 `export const routes = [${builder.routes.map((route) => `{ pattern: ${route.pattern} }`).join(", ")}];\n`,
207 );
208
209 // worker entry (unbundled shim; relative imports into `output/server`)
210 const workerEntry = NodePath.join(dest, "_worker.js");
211 NodeFs.writeFileSync(
212 workerEntry,
213 generateWorkerShim({
214 serverImport: `./${posixify(NodePath.relative(dest, tmp))}/server.js`,
215 manifestImport: `./${posixify(NodePath.relative(dest, tmp))}/manifest.js`,
216 assetsBinding,
217 notFoundHandling: options.notFoundHandling,
218 }),
219 );
220 if (
221 typeof builder.hasServerInstrumentationFile === "function" &&
222 builder.hasServerInstrumentationFile()
223 ) {
224 // kit 3.0 requires an explicit initializer module that populates
225 // `$env/dynamic/private` before instrumentation runs. Source it from
226 // `cloudflare:workers` (the same binding source the worker shim
227 // uses) rather than the `process.env` default, which workerd doesn't
228 // populate with real bindings.
229 const initializer = builder.createInstrumentationInitializer({
230 outputDirectory: tmp,
231 environment: "export { env as default } from 'cloudflare:workers';",
232 });
233 builder.instrument({
234 entrypoint: workerEntry,
235 instrumentation: NodePath.join(builder.getServerDirectory(), "instrumentation.server.js"),
236 initializer,
237 });
238 }
239
240 // _headers
241 const userHeaders = readOptionalFile(NodePath.join(root, "_headers"));
242 NodeFs.writeFileSync(
243 NodePath.join(dest, "_headers"),
244 generateHeaders(builder.getAppPath(), userHeaders),
245 );
246
247 // _redirects
248 const userRedirects = readOptionalFile(NodePath.join(root, "_redirects"));
249 const redirects = generateRedirects(builder.prerendered.redirects, userRedirects);
250 if (redirects !== undefined) {
251 NodeFs.writeFileSync(NodePath.join(dest, "_redirects"), redirects);
252 }
253
254 // Workers-mode assets ignore file
255 NodeFs.writeFileSync(NodePath.join(dest, ".assetsignore"), generateAssetsIgnore());
256
257 result.current = { dest, workerEntry };
258 },
259 emulate: () =>
260 (emulator ??=
261 options.platform !== undefined
262 ? makeDevPlatformEmulator(options.platform)
263 : makeBuildEmulator()),
264 dispose: async () => {
265 await emulator?.dispose();
266 },
267 supports: {
268 read: () => true,
269 instrumentation: () => true,
270 },
271 };
272 };
273
274 const readOptionalFile = (path: string): string | undefined =>
275 NodeFs.existsSync(path) ? NodeFs.readFileSync(path, "utf8") : undefined;
276
277 const posixify = (str: string): string => str.replace(/\\/g, "/");
278
279 /**
280 * Add a rule block for `url` to a `_headers` file, merging into an existing
281 * block for the same URL if present (upstream `append_headers`).
282 */
283 export const appendHeaders = (url: string, rules: Array<string>, content: string): string => {
284 const regex = new RegExp(`^(${url.replaceAll("*", "\\*")})$`, "m");
285 const formattedHeaders = rules.map((rule) => ` ${rule}`).join("\n");
286
287 // if the URL already exists, just add header rules to it
288 if (regex.test(content)) {
289 return content.replace(regex, `$1\n${formattedHeaders}`);
290 }
291
292 // otherwise, we add the url and header rules
293 return `
294 ${content}
295 # === START AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
296 ${url}
297 ${formattedHeaders}
298 # === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
299 `.trim();
300 };
301
302 /**
303 * Merge the user's `_headers` content with the generated kit rules
304 * (`noindex` for the app dir, immutable caching for hashed assets).
305 */
306 export const generateHeaders = (appDir: string, content = ""): string => {
307 content = appendHeaders(
308 `/${appDir}/*`,
309 ["X-Robots-Tag: noindex", "Cache-Control: no-cache"],
310 content,
311 );
312 content = appendHeaders(
313 `/${appDir}/immutable/*`,
314 ["! Cache-Control", "Cache-Control: public, immutable, max-age=31536000"],
315 content,
316 );
317 return content;
318 };
319
320 /**
321 * Merge the user's `_redirects` content with rules for kit's prerendered
322 * redirects. Returns `undefined` when there is nothing to write.
323 */
324 export const generateRedirects = (
325 redirects: Map<string, { status: number; location: string }>,
326 content?: string,
327 ): string | undefined => {
328 const parts: Array<string> = [];
329 if (content !== undefined) {
330 parts.push(content);
331 }
332 if (redirects.size > 0) {
333 const rules = Array.from(
334 redirects.entries(),
335 ([path, redirect]) => `${path} ${redirect.location} ${redirect.status}`,
336 ).join("\n");
337 parts.push(
338 `
339 # === START AUTOGENERATED SVELTE PRERENDERED REDIRECTS ===
340 ${rules}
341 # === END AUTOGENERATED SVELTE PRERENDERED REDIRECTS ===
342 `.trimEnd(),
343 );
344 }
345 if (parts.length === 0) {
346 return undefined;
347 }
348 return parts.join("\n");
349 };
350
351 /** Workers-mode `.assetsignore`: files in `dest` that are not static assets. */
352 export const generateAssetsIgnore = (): string =>
353 `
354 _worker.js
355 _routes.json
356 _headers
357 _redirects
358 `.trimStart();
359
360 // ---------------------------------------------------------------------------
361 // Dev platform emulation (cloudflare-runtime platform proxy)
362 // ---------------------------------------------------------------------------
363
364 /** Inputs for the proxy-backed dev platform served from `emulate()`. */
365 export interface CloudflareDevPlatformOptions {
366 /**
367 * Literal `platform.env` overrides. Applied on top of the proxied binding
368 * values — a same-named literal always wins (back-compat with the phase-1
369 * stub platform, whose env was literals only).
370 */
371 readonly env?: Record<string, unknown> | undefined;
372 /**
373 * Bindings to expose on `platform.env` — the same hook shapes
374 * `cloudflare-runtime`'s `Runtime.start` accepts (`Text.local`,
375 * `KvNamespace.local`, `D1.local`, remote bindings, …). Typed opaquely
376 * because the specs travel through the target-agnostic framework half;
377 * the values must be `cloudflare-runtime` `BindingHooks`.
378 */
379 readonly bindings?: ReadonlyArray<unknown> | undefined;
380 /**
381 * Pre-built `Context<RuntimeServices>` to host the proxy in (opaque —
382 * travels through the target-agnostic framework half). Enables
383 * remote()-lowered bindings, which the proxy's internal local-only layer
384 * cannot serve.
385 */
386 readonly services?: unknown;
387 /** `cloudflare-runtime` `WorkerdOptions` for the proxy's workerd process. */
388 readonly workerd?: unknown;
389 /**
390 * Directory whose files the `ASSETS` binding in `bindings` serves (kit's
391 * static directory), as the deployed Worker's assets do.
392 */
393 readonly assetsDirectory?: string | undefined;
394 /** Compatibility date for the binding-proxy workerd instance. */
395 readonly compatibilityDate?: string | undefined;
396 /** Compatibility flags for the binding-proxy workerd instance. */
397 readonly compatibilityFlags?: ReadonlyArray<string> | undefined;
398 /** Name of the proxy workerd service. @default "sveltekit-dev-platform-proxy" */
399 readonly name?: string | undefined;
400 /**
401 * Override how the platform proxy is opened. A test seam — the default
402 * dynamically imports `cloudflare-runtime`'s `getPlatformProxy`.
403 */
404 readonly openProxy?: OpenDevPlatformProxy | undefined;
405 }
406
407 /** The subset of `cloudflare-runtime`'s `PlatformProxy` the emulator serves. */
408 export interface DevPlatformProxy {
409 readonly env: Record<string, unknown>;
410 readonly cf: Record<string, unknown>;
411 readonly ctx: unknown;
412 readonly caches: unknown;
413 readonly dispose: () => Promise<void>;
414 }
415
416 export interface OpenDevPlatformProxyOptions {
417 readonly name: string;
418 readonly compatibilityDate?: string | undefined;
419 readonly compatibilityFlags?: ReadonlyArray<string> | undefined;
420 readonly bindings: ReadonlyArray<unknown>;
421 /** See {@link CloudflareDevPlatformOptions.services}. */
422 readonly services?: unknown;
423 /** See {@link CloudflareDevPlatformOptions.workerd}. */
424 readonly workerd?: unknown;
425 /** Static assets served to an `Assets.local` binding. */
426 readonly assets?: { readonly directory: string } | undefined;
427 }
428
429 export type OpenDevPlatformProxy = (
430 options: OpenDevPlatformProxyOptions,
431 ) => Promise<DevPlatformProxy>;
432
433 /** A kit `Emulator` that owns a disposable platform proxy. */
434 export interface CloudflareEmulator extends Emulator {
435 /** Tear down the proxy. No-op when it was never opened. */
436 readonly dispose: () => Promise<void>;
437 }
438
439 /**
440 * The default proxy opener: `cloudflare-runtime`'s `getPlatformProxy`
441 * (workerd hosting the bindings behind the internal proxy worker, local-only
442 * layer, state in a temp directory). Imported lazily so production builds
443 * never load the runtime machinery.
444 */
445 const openPlatformProxy: OpenDevPlatformProxy = async (options) => {
446 const { getPlatformProxy } = await import("@alchemy.run/cloudflare-runtime/core/platform-proxy");
447 return await getPlatformProxy({
448 name: options.name,
449 ...(options.compatibilityDate !== undefined
450 ? { compatibilityDate: options.compatibilityDate }
451 : undefined),
452 ...(options.compatibilityFlags !== undefined
453 ? { compatibilityFlags: [...options.compatibilityFlags] }
454 : undefined),
455 bindings: options.bindings as BindingHooks,
456 ...(options.assets !== undefined ? { assets: { ...options.assets } } : undefined),
457 ...(options.services !== undefined
458 ? {
459 services: options.services as Parameters<typeof getPlatformProxy>[0]["services"],
460 }
461 : undefined),
462 ...(options.workerd !== undefined
463 ? { workerd: options.workerd as Parameters<typeof getPlatformProxy>[0]["workerd"] }
464 : undefined),
465 });
466 };
467
468 /**
469 * `platform.env` for prerenderable routes: any key access throws (mirroring
470 * upstream), because prerendered pages must not depend on request-time
471 * bindings.
472 */
473 const guardPrerenderEnv = (env: Record<string, unknown>): Record<string, unknown> => {
474 const guarded: Record<string, unknown> = {};
475 for (const key of Object.keys(env)) {
476 Object.defineProperty(guarded, key, {
477 get: () => {
478 throw new Error(`Cannot access platform.env.${key} in a prerenderable route`);
479 },
480 });
481 }
482 return guarded;
483 };
484
485 /**
486 * The dev-platform emulator: serves `platform = { env, ctx, caches, cf }`
487 * from `cloudflare-runtime`'s platform proxy — our wrangler-free equivalent
488 * of upstream `adapter-cloudflare`'s `getPlatformProxy`-based `emulate()`.
489 *
490 * - The proxy (a workerd instance hosting the bindings) is opened lazily on
491 * the first `platform()` call and shared across requests; dispose it with
492 * the dev server via {@link CloudflareEmulator.dispose}.
493 * - `env` carries every configured binding, callable from Node
494 * (`env.KV.get("key")`, `env.DB.prepare("...").all()`); literal
495 * `options.env` values override same-named proxied values.
496 * - `caches` actually round-trips (`put`/`match`/`delete` hit an in-memory
497 * store in the proxy worker — unlike wrangler, whose dev `caches` is a
498 * no-op); `cf` is the same mock object miniflare falls back to; `ctx` is
499 * wrangler's no-op `ExecutionContext` mock.
500 * - Inherited proxy limitations: binding methods returning rich class
501 * instances (e.g. `R2Object`) are unsupported, and intermediate values
502 * (e.g. `DurableObjectId`) need an explicit `await` before synchronous use
503 * — see `cloudflare-runtime/platform-proxy`.
504 */
505 export const makeDevPlatformEmulator = (
506 options: CloudflareDevPlatformOptions = {},
507 ): CloudflareEmulator => {
508 const openProxy = options.openProxy ?? openPlatformProxy;
509 let opened: Promise<DevPlatformProxy> | undefined;
510 const open = () =>
511 (opened ??= openProxy({
512 name: options.name ?? "sveltekit-dev-platform-proxy",
513 compatibilityDate: options.compatibilityDate,
514 compatibilityFlags: options.compatibilityFlags,
515 bindings: options.bindings ?? [],
516 services: options.services,
517 workerd: options.workerd,
518 ...(options.assetsDirectory !== undefined
519 ? { assets: { directory: options.assetsDirectory } }
520 : undefined),
521 }));
522 return {
523 platform: async ({ prerender }) => {
524 const proxy = await open();
525 const env = { ...proxy.env, ...options.env };
526 return {
527 env: prerender ? guardPrerenderEnv(env) : env,
528 ctx: proxy.ctx,
529 caches: proxy.caches,
530 cf: proxy.cf,
531 } as unknown as App.Platform;
532 },
533 dispose: async () => {
534 if (opened === undefined) return;
535 const proxy = await opened.catch(() => undefined);
536 await proxy?.dispose();
537 },
538 };
539 };
540
541 /**
542 * The inert platform used when the adapter is constructed without dev
543 * platform options (production builds): empty env, no-op `ctx`/`caches`,
544 * empty `cf`. Never opens a proxy.
545 */
546 const makeBuildEmulator = (): CloudflareEmulator => {
547 const noopCache = {
548 match: async () => undefined,
549 put: async () => {},
550 delete: async () => false,
551 };
552 const platform = {
553 env: {},
554 ctx: {
555 waitUntil: (_promise: Promise<unknown>) => {},
556 passThroughOnException: () => {},
557 },
558 caches: {
559 default: noopCache,
560 open: async () => noopCache,
561 },
562 cf: {},
563 };
564 return {
565 platform: () => platform as unknown as App.Platform,
566 dispose: async () => {},
567 };
568 };