@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 181 lines 7.1 KB
Raw
1 import * as NodePath from "node:path";
2 // Alchemy modifications are licensed under Apache-2.0.
3 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
4 /**
5 * `@alchemy.run/frontend-frameworks/sveltekit/cloudflare` — the Cloudflare Workers deploy
6 * target for `@alchemy.run/frontend-frameworks/sveltekit`.
7 *
8 * Everything Cloudflare-specific lives here (and in the modules this file
9 * imports): the wrangler-free in-memory kit adapter (worker shim, `_headers`
10 * / `_redirects` / `.assetsignore` generation, the proxy-backed dev
11 * platform) and the finishing pass that re-bundles kit's node-flavored
12 * `_worker.js` output for workerd with rolldown +
13 * `@alchemy.run/cloudflare-runtime/rolldown`.
14 *
15 * The default export is the target factory the framework package applies to
16 * the config it assembles from `SvelteKitOptions`
17 * (`resolveDeployTarget(root, target, config)` — a value, a factory, or this
18 * module's specifier).
19 */
20 import cloudflare from "@alchemy.run/cloudflare-runtime/rolldown";
21 import * as Effect from "effect/Effect";
22 import * as FileSystem from "effect/FileSystem";
23 import * as Path from "effect/Path";
24 import { rolldown } from "rolldown";
25 import * as FrameworkCore from "../core/index.ts";
26 import { DeployTargetError, makeDeployTarget } from "../core/index.ts";
27 import { makeCloudflareAdapter } from "./Adapter.ts";
28 import type { SvelteKitTarget, SvelteKitTargetConfig } from "./SvelteKit.ts";
29
30 export {
31 appendHeaders,
32 generateAssetsIgnore,
33 generateHeaders,
34 generateRedirects,
35 makeCloudflareAdapter,
36 makeDevPlatformEmulator,
37 type CloudflareAdapter,
38 type CloudflareAdapterOptions,
39 type CloudflareAdapterResult,
40 type CloudflareDevPlatformOptions,
41 type CloudflareEmulator,
42 type DevPlatformProxy,
43 type OpenDevPlatformProxy,
44 type OpenDevPlatformProxyOptions,
45 } from "./Adapter.ts";
46 export { generateWorkerShim, type WorkerShimOptions } from "./WorkerShim.ts";
47
48 const fail = (message: string, cause?: unknown) =>
49 new DeployTargetError({ platform: "cloudflare", message, cause });
50
51 /**
52 * Create the Cloudflare Workers {@link SvelteKitTarget}:
53 *
54 * - `adapter(context)` — the in-memory, wrangler-free fork of
55 * `@sveltejs/adapter-cloudflare` (always Workers mode; generates the worker
56 * shim with real relative imports). In dev it supplies the proxy-backed
57 * `platform`: `context.dev.bindings` (cloudflare-runtime binding hooks)
58 * served through `getPlatformProxy`'s workerd instance, `context.dev.env`
59 * literals overriding same-named proxied values, a `caches` that actually
60 * round-trips, and wrangler-parity `cf`/`ctx` mocks.
61 * - `finish(output, context)` — re-bundles the adapter's unbundled
62 * `_worker.js` (and the whole `.svelte-kit/output/server` graph it imports)
63 * for workerd, replacing the bundling `wrangler deploy` performs for the
64 * upstream adapter. Produces entry-first `serverModules` plus the external
65 * workspace set.
66 * - `bundle` — workerd resolve conditions and the `cloudflare:` externals.
67 */
68 export const makeCloudflareTarget = (config: SvelteKitTargetConfig = {}): SvelteKitTarget =>
69 makeDeployTarget({
70 platform: "cloudflare",
71 config,
72 bundle: {
73 conditions: ["workerd", "worker", "module", "browser"],
74 external: ["cloudflare:"],
75 },
76 adapter: (context) =>
77 makeCloudflareAdapter({
78 ...config.adapter,
79 root: context.root,
80 ...(context.dev !== undefined
81 ? {
82 platform: {
83 env: context.dev.env,
84 bindings: context.dev.bindings,
85 services: context.dev.services,
86 workerd: context.dev.workerd,
87 assetsDirectory: context.dev.assetsDirectory,
88 compatibilityDate: config.compatibilityDate,
89 compatibilityFlags: config.compatibilityFlags,
90 },
91 }
92 : undefined),
93 }),
94 finish: (output, context) =>
95 Effect.gen(function* () {
96 const fs = yield* FileSystem.FileSystem;
97 const path = yield* Path.Path;
98 const entry = context.entry;
99 if (entry === undefined) {
100 return yield* fail(
101 "The SvelteKit build produced no on-disk worker entry for the finishing pass " +
102 "(context.entry is missing)",
103 );
104 }
105 const root = context.root;
106 const distDirectory = output.distDirectory ?? path.resolve(root, "dist");
107 const serverOutDir = path.join(distDirectory, "server");
108 yield* fs
109 .remove(serverOutDir, { recursive: true, force: true })
110 .pipe(Effect.mapError((error) => fail("Failed to clean dist/server", error)));
111
112 const externalDirectories = yield* Effect.tryPromise({
113 try: async () => {
114 const bundle = await rolldown({
115 cwd: root,
116 input: entry,
117 plugins: cloudflare({
118 ...(config.compatibilityDate !== undefined
119 ? { compatibilityDate: config.compatibilityDate }
120 : undefined),
121 compatibilityFlags: config.compatibilityFlags ?? ["nodejs_compat"],
122 exports: ["default"],
123 }),
124 });
125 try {
126 const { output: chunks } = await bundle.write({
127 dir: serverOutDir,
128 format: "esm",
129 entryFileNames: "index.js",
130 chunkFileNames: "chunks/[name].js",
131 sourcemap: false,
132 });
133 const directories = new Set<string>();
134 for (const chunk of chunks) {
135 if (chunk.type !== "chunk") continue;
136 for (const id of Object.keys(chunk.modules)) {
137 if (
138 !NodePath.isAbsolute(id) ||
139 id.includes("node_modules") ||
140 id.startsWith(root)
141 ) {
142 continue;
143 }
144 directories.add(NodePath.dirname(id));
145 }
146 }
147 return directories;
148 } finally {
149 await bundle.close();
150 }
151 },
152 catch: (error) => fail("Failed to bundle the worker for workerd", error),
153 });
154
155 const wrapCollectorError = (error: FrameworkCore.CollectorError) =>
156 fail(error.message, error.cause);
157 const modules = yield* FrameworkCore.readServerModulesFromDisk({
158 directory: serverOutDir,
159 prefix: "server",
160 }).pipe(Effect.mapError(wrapCollectorError));
161 const serverModules = FrameworkCore.sortServerModules(modules, "server/index.js");
162 const externalWorkspaces = yield* FrameworkCore.collectExternalWorkspaces(
163 externalDirectories,
164 ).pipe(Effect.mapError(wrapCollectorError));
165
166 return {
167 ...output,
168 distDirectory,
169 serverModules,
170 externalWorkspaces,
171 } satisfies FrameworkCore.BuildOutput;
172 }),
173 });
174
175 /**
176 * The deploy-target module contract (`resolveDeployTarget` accepts the
177 * default export — or the named `target` export — as a value or factory).
178 */
179 export const target = makeCloudflareTarget;
180
181 export default makeCloudflareTarget;