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
| 1 | import * as NodeCrypto from "node:crypto"; |
| 2 | import * as NodePath from "node:path"; |
| 3 | import { fileURLToPath } from "node:url"; |
| 4 | /** |
| 5 | * `@alchemy.run/frontend-frameworks/sveltekit/source` — alchemy Worker source provider for |
| 6 | * SvelteKit projects. |
| 7 | * |
| 8 | * The default export satisfies alchemy's `WorkerSourceModule` contract |
| 9 | * (`packages/cloudflare/src/Workers/Source.ts`) **structurally**: |
| 10 | * the `Source*` shapes below mirror alchemy's `SourceProvider` / |
| 11 | * `SourceContext` / `SourceBuildOutput` interfaces rather than importing |
| 12 | * them, so this package carries no dependency on alchemy. Version skew |
| 13 | * degrades to a load-time `SourceProviderError` on the alchemy side. |
| 14 | * |
| 15 | * Semantics mirror alchemy's built-in vite source |
| 16 | * (`Workers/Sources/Vite.ts`): |
| 17 | * |
| 18 | * - `build()` runs the SvelteKit Framework service (programmatic Vite build |
| 19 | * with the wrangler-free in-memory Cloudflare adapter + workerd rolldown |
| 20 | * re-bundle) and maps its `BuildOutput` onto the source contract: |
| 21 | * `serverModules` (entry first) → bundle files, `clientDirectory` → |
| 22 | * assets (manifest-hashed, honoring `.assetsignore` / `_headers` / |
| 23 | * `_redirects`), project-tree hash → the `input` hash slot. |
| 24 | * - `hash()` recomputes the `input` hash **without building** — a memo hash |
| 25 | * over the project tree (gitignore-aware by default, narrowable via |
| 26 | * `memo.include`/`memo.exclude`), the discovered external workspaces, the |
| 27 | * lockfile, this package's version, and the build-affecting options. |
| 28 | * - `dev()` starts SvelteKit's own Vite dev server (Node SSR, full HMR) |
| 29 | * with the proxy-backed `platform`: the Worker's binding hooks |
| 30 | * (`ctx.worker.bindings`) are served on `platform.env` through |
| 31 | * cloudflare-runtime's platform proxy (workerd hosting the real local |
| 32 | * bindings), `caches` round-trips, and `cf`/`ctx` match wrangler's |
| 33 | * `getPlatformProxy` mocks. Literal `props.env` values are additionally |
| 34 | * applied as `platform.env` overrides. |
| 35 | */ |
| 36 | import * as Data from "effect/Data"; |
| 37 | import * as Effect from "effect/Effect"; |
| 38 | import * as FileSystem from "effect/FileSystem"; |
| 39 | import type * as Path from "effect/Path"; |
| 40 | import type { PlatformError } from "effect/PlatformError"; |
| 41 | import * as Redacted from "effect/Redacted"; |
| 42 | import type * as Scope from "effect/Scope"; |
| 43 | import { glob } from "tinyglobby"; |
| 44 | import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts"; |
| 45 | import { makeCloudflareTarget } from "./cloudflare.ts"; |
| 46 | import { |
| 47 | make as makeSvelteKit, |
| 48 | type SvelteKitAdapterOptions, |
| 49 | type SvelteKitOptions, |
| 50 | } from "./SvelteKit.ts"; |
| 51 | |
| 52 | const PROVIDER = "@alchemy.run/frontend-frameworks/sveltekit/source"; |
| 53 | |
| 54 | // ───────────────────────────────────────────────────────────────────── |
| 55 | // Structural mirror of alchemy's Worker source contract |
| 56 | // (packages/cloudflare/src/Workers/Source.ts). Do not import |
| 57 | // alchemy here — the contract is structural by design. |
| 58 | // ───────────────────────────────────────────────────────────────────── |
| 59 | |
| 60 | /** Mirror of alchemy's `SourceHash`. */ |
| 61 | export interface SourceHash { |
| 62 | readonly bundle: string | undefined; |
| 63 | readonly assets: string | undefined; |
| 64 | readonly input: string | undefined; |
| 65 | readonly additionalWorkspaces: Array<string> | undefined; |
| 66 | } |
| 67 | |
| 68 | /** Mirror of alchemy's `Bundle.BundleFile` / `Bundle.BundleOutput`. */ |
| 69 | export interface SourceBundleFile { |
| 70 | readonly path: string; |
| 71 | readonly content: string | Uint8Array; |
| 72 | readonly hash: string; |
| 73 | } |
| 74 | |
| 75 | export interface SourceBundleOutput { |
| 76 | readonly files: [SourceBundleFile, ...Array<SourceBundleFile>]; |
| 77 | readonly hash: string; |
| 78 | } |
| 79 | |
| 80 | /** Mirror of alchemy's `AssetReadResult` (`Workers/Assets.ts`). */ |
| 81 | export interface SourceAssetReadResult { |
| 82 | directory: string; |
| 83 | config: Record<string, unknown> | undefined; |
| 84 | manifest: Record<string, { hash: string; size: number }>; |
| 85 | _headers: string | undefined; |
| 86 | _redirects: string | undefined; |
| 87 | hash: string; |
| 88 | } |
| 89 | |
| 90 | /** Mirror of alchemy's `SourceBuildOutput`. */ |
| 91 | export interface SourceBuildOutput { |
| 92 | readonly bundle: SourceBundleOutput | undefined; |
| 93 | readonly assets: SourceAssetReadResult | undefined; |
| 94 | readonly hash: SourceHash; |
| 95 | } |
| 96 | |
| 97 | /** Mirror of alchemy's `SourceContext` (the subset this source reads). */ |
| 98 | export interface SourceContext { |
| 99 | readonly id: string; |
| 100 | readonly workerName: string; |
| 101 | readonly compatibility: { |
| 102 | readonly date: string; |
| 103 | readonly flags: Array<string>; |
| 104 | }; |
| 105 | readonly stack: { readonly name: string; readonly stage: string }; |
| 106 | readonly env: Record<string, unknown> | undefined; |
| 107 | readonly assets: Record<string, unknown> | string | undefined; |
| 108 | } |
| 109 | |
| 110 | /** Mirror of alchemy's `DevContext` (the subset this source reads). */ |
| 111 | export interface SourceDevContext extends SourceContext { |
| 112 | /** |
| 113 | * Runtime wiring derived by alchemy's LocalWorkerProvider. `bindings` are |
| 114 | * cloudflare-runtime `BindingHook`s — typed opaquely here to keep this |
| 115 | * module free of an alchemy/cloudflare-runtime type dependency; they are |
| 116 | * fed to the dev platform proxy as-is. |
| 117 | */ |
| 118 | readonly worker: { |
| 119 | readonly name: string; |
| 120 | readonly bindings: ReadonlyArray<unknown>; |
| 121 | /** The Worker's runtime settings; `workerd` reaches the dev platform proxy. */ |
| 122 | readonly options: { readonly workerd?: unknown }; |
| 123 | }; |
| 124 | /** |
| 125 | * The host's pre-built `Context<RuntimeServices>` (opaque here). Handed |
| 126 | * to the dev platform proxy so remote()-lowered bindings resolve against |
| 127 | * the host's runtime stack. |
| 128 | */ |
| 129 | readonly runtimeContext: unknown; |
| 130 | } |
| 131 | |
| 132 | /** Mirror of alchemy's server-mode `SourceDevHandle`. */ |
| 133 | export interface SourceDevHandle { |
| 134 | readonly mode: "server"; |
| 135 | readonly url: URL; |
| 136 | readonly serviceBinding?: "http"; |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * Same tag as alchemy's `Cloudflare.Workers.SourceProviderError`, so the |
| 141 | * errors this module raises are members of alchemy's closed `SourceError` |
| 142 | * union structurally. |
| 143 | */ |
| 144 | export class SourceProviderError extends Data.TaggedError( |
| 145 | "Cloudflare.Workers.SourceProviderError", |
| 146 | )<{ |
| 147 | readonly provider: string; |
| 148 | readonly message: string; |
| 149 | readonly cause?: unknown; |
| 150 | }> {} |
| 151 | |
| 152 | export type SourceError = SourceProviderError | PlatformError; |
| 153 | |
| 154 | type SourceServices = FileSystem.FileSystem | Path.Path; |
| 155 | |
| 156 | /** Mirror of alchemy's `SourceProvider` (structural). */ |
| 157 | export interface SourceProvider { |
| 158 | readonly ownsAssets: boolean; |
| 159 | readonly devAssetsBinding?: boolean; |
| 160 | readonly build: ( |
| 161 | ctx: SourceContext, |
| 162 | ) => Effect.Effect<SourceBuildOutput, SourceError, SourceServices>; |
| 163 | readonly hash: ( |
| 164 | ctx: SourceContext, |
| 165 | previous: SourceHash | undefined, |
| 166 | ) => Effect.Effect<Partial<SourceHash>, SourceError, SourceServices>; |
| 167 | readonly dev: ( |
| 168 | ctx: SourceDevContext, |
| 169 | ) => Effect.Effect<SourceDevHandle, SourceError, SourceServices | Scope.Scope>; |
| 170 | } |
| 171 | |
| 172 | // ───────────────────────────────────────────────────────────────────── |
| 173 | // Descriptor options (JSON-serializable — they persist in alchemy state |
| 174 | // and participate in the Worker's metadata hash) |
| 175 | // ───────────────────────────────────────────────────────────────────── |
| 176 | |
| 177 | export interface SvelteKitMemoOptions { |
| 178 | /** Glob patterns of files to hash, relative to `rootDir`. @default all non-gitignored files */ |
| 179 | readonly include?: Array<string> | undefined; |
| 180 | /** Glob patterns to exclude. @default gitignore rules from `rootDir` up to the repo root */ |
| 181 | readonly exclude?: Array<string> | undefined; |
| 182 | /** |
| 183 | * Include the nearest package-manager lockfile in the hash. |
| 184 | * @default true when both `include` and `exclude` are unset |
| 185 | */ |
| 186 | readonly lockfile?: boolean | undefined; |
| 187 | } |
| 188 | |
| 189 | export interface SvelteKitSourceOptions { |
| 190 | /** |
| 191 | * SvelteKit project root. Relative paths resolve from the process working |
| 192 | * directory. @default process.cwd() |
| 193 | */ |
| 194 | readonly rootDir?: string | undefined; |
| 195 | /** Narrows the rebuild-detection input hash. */ |
| 196 | readonly memo?: SvelteKitMemoOptions | undefined; |
| 197 | /** |
| 198 | * SvelteKit configuration overrides. With a project-owned |
| 199 | * `vite.config.*` (loaded natively), these merge over the options of the |
| 200 | * user's own `sveltekit(...)` call (integration wins); without one they |
| 201 | * are passed to `sveltekit(config)` wholesale. Must be JSON-serializable |
| 202 | * — it persists in state. |
| 203 | */ |
| 204 | readonly kit?: Record<string, unknown> | undefined; |
| 205 | /** Options for the wrangler-free Cloudflare adapter. */ |
| 206 | readonly adapter?: SvelteKitAdapterOptions | undefined; |
| 207 | } |
| 208 | |
| 209 | // ───────────────────────────────────────────────────────────────────── |
| 210 | // Hashing (mirrors alchemy's Command/Memo.ts + Util/sha256.ts semantics: |
| 211 | // machine-independent — only relative paths and file bytes are hashed) |
| 212 | // ───────────────────────────────────────────────────────────────────── |
| 213 | |
| 214 | const sha256Hex = (input: string | Uint8Array): Effect.Effect<string> => |
| 215 | Effect.sync(() => NodeCrypto.createHash("sha256").update(input).digest("hex")); |
| 216 | |
| 217 | /** Recursively sort object keys so JSON.stringify is order-stable. */ |
| 218 | const stableValue = (value: unknown): unknown => { |
| 219 | if (Array.isArray(value)) { |
| 220 | return value.map(stableValue); |
| 221 | } |
| 222 | if (value !== null && typeof value === "object") { |
| 223 | return Object.fromEntries( |
| 224 | Object.entries(value as Record<string, unknown>) |
| 225 | .filter(([, v]) => v !== undefined) |
| 226 | .sort(([a], [b]) => a.localeCompare(b)) |
| 227 | .map(([k, v]) => [k, stableValue(v)]), |
| 228 | ); |
| 229 | } |
| 230 | return value; |
| 231 | }; |
| 232 | |
| 233 | const sha256Stable = (input: unknown): Effect.Effect<string> => |
| 234 | sha256Hex(JSON.stringify(stableValue(input) ?? null)); |
| 235 | |
| 236 | /** |
| 237 | * Convert gitignore-style rules into glob `ignore` patterns — a copy of |
| 238 | * alchemy's `Util/gitignore-rules-to-globs.ts` (common cases only). |
| 239 | */ |
| 240 | const gitignoreRulesToGlobs = (rules: ReadonlyArray<string>): Array<string> => { |
| 241 | const out: Array<string> = []; |
| 242 | for (const raw of rules) { |
| 243 | const line = raw.trim(); |
| 244 | if (line.length === 0 || line.startsWith("#") || line.startsWith("!")) { |
| 245 | continue; |
| 246 | } |
| 247 | let rest = line; |
| 248 | const dirOnly = rest.endsWith("/"); |
| 249 | if (dirOnly) { |
| 250 | rest = rest.slice(0, -1); |
| 251 | } |
| 252 | rest = rest.replace(/\\/g, "/"); |
| 253 | if (rest.length === 0) continue; |
| 254 | const anchored = rest.startsWith("/"); |
| 255 | if (anchored) { |
| 256 | rest = rest.slice(1); |
| 257 | } |
| 258 | if (rest.length === 0) continue; |
| 259 | const hasSlash = rest.includes("/"); |
| 260 | if (dirOnly) { |
| 261 | out.push(anchored || hasSlash ? `${rest}/**` : `**/${rest}/**`); |
| 262 | } else if (anchored || hasSlash) { |
| 263 | out.push(rest, `${rest}/**`); |
| 264 | } else { |
| 265 | out.push(`**/${rest}`, `**/${rest}/**`); |
| 266 | } |
| 267 | } |
| 268 | return out; |
| 269 | }; |
| 270 | |
| 271 | const findUp = Effect.fnUntraced(function* ( |
| 272 | fs: FileSystem.FileSystem, |
| 273 | cwd: string, |
| 274 | filenames: Array<string>, |
| 275 | ) { |
| 276 | let dir = cwd; |
| 277 | for (;;) { |
| 278 | for (const filename of filenames) { |
| 279 | const file = NodePath.join(dir, filename); |
| 280 | if (yield* fs.exists(file)) { |
| 281 | return file; |
| 282 | } |
| 283 | } |
| 284 | const parent = NodePath.dirname(dir); |
| 285 | if (parent === dir) { |
| 286 | return undefined; |
| 287 | } |
| 288 | dir = parent; |
| 289 | } |
| 290 | }); |
| 291 | |
| 292 | /** Collect `.gitignore` rules from `cwd` up to the repo root (parents first). */ |
| 293 | const readGitIgnoreRules = ( |
| 294 | fs: FileSystem.FileSystem, |
| 295 | cwd: string, |
| 296 | ): Effect.Effect<Array<string>, PlatformError> => |
| 297 | Effect.gen(function* () { |
| 298 | const rules = yield* fs.readFileString(NodePath.join(cwd, ".gitignore")).pipe( |
| 299 | Effect.map((file) => file.split("\n")), |
| 300 | Effect.catchTag("PlatformError", () => Effect.succeed([] as Array<string>)), |
| 301 | ); |
| 302 | const parent = NodePath.dirname(cwd); |
| 303 | if (parent === cwd || (yield* fs.exists(NodePath.join(cwd, ".git")))) { |
| 304 | return rules; |
| 305 | } |
| 306 | const parentRules = yield* readGitIgnoreRules(fs, parent); |
| 307 | return [...parentRules, ...rules]; |
| 308 | }); |
| 309 | |
| 310 | /** |
| 311 | * Deterministic content hash of the files in `cwd` matched by `memo` — |
| 312 | * mirror of alchemy's `hashDirectory` (`Command/Memo.ts`). |
| 313 | */ |
| 314 | const hashDirectory = Effect.fnUntraced(function* ( |
| 315 | cwd: string, |
| 316 | memo: SvelteKitMemoOptions | undefined, |
| 317 | ) { |
| 318 | const fs = yield* FileSystem.FileSystem; |
| 319 | const include = memo?.include ?? ["**/*"]; |
| 320 | const exclude = memo?.exclude ?? [ |
| 321 | "**/.git/**", |
| 322 | ...gitignoreRulesToGlobs(yield* readGitIgnoreRules(fs, cwd)), |
| 323 | ]; |
| 324 | const lockfile = memo?.lockfile ?? !(memo?.include || memo?.exclude); |
| 325 | const [files, lockfilePath] = yield* Effect.all( |
| 326 | [ |
| 327 | Effect.promise(() => |
| 328 | glob(include, { |
| 329 | cwd, |
| 330 | ignore: exclude, |
| 331 | onlyFiles: true, |
| 332 | expandDirectories: false, |
| 333 | dot: true, |
| 334 | }), |
| 335 | ), |
| 336 | lockfile |
| 337 | ? Effect.map( |
| 338 | findUp(fs, cwd, [ |
| 339 | "bun.lock", |
| 340 | "bun.lockb", |
| 341 | "package-lock.json", |
| 342 | "pnpm-lock.yaml", |
| 343 | "yarn.lock", |
| 344 | ]), |
| 345 | (file) => (file ? NodePath.relative(cwd, file) : undefined), |
| 346 | ) |
| 347 | : Effect.undefined, |
| 348 | ], |
| 349 | { concurrency: "unbounded" }, |
| 350 | ); |
| 351 | if (lockfilePath && !files.includes(lockfilePath)) { |
| 352 | files.push(lockfilePath); |
| 353 | } |
| 354 | const hashes = yield* Effect.forEach( |
| 355 | files.sort(), |
| 356 | (file) => |
| 357 | fs.readFile(NodePath.join(cwd, file)).pipe( |
| 358 | Effect.flatMap(sha256Hex), |
| 359 | Effect.map((hash) => `${file}:${hash}`), |
| 360 | ), |
| 361 | { concurrency: 16 }, |
| 362 | ); |
| 363 | return yield* sha256Stable(hashes); |
| 364 | }); |
| 365 | |
| 366 | /** This package's version — part of the `input` hash so an adapter upgrade busts the memo. */ |
| 367 | const packageVersion = Effect.gen(function* () { |
| 368 | const fs = yield* FileSystem.FileSystem; |
| 369 | const dir = NodePath.dirname(fileURLToPath(import.meta.url)); |
| 370 | const content = yield* fs.readFileString(NodePath.join(dir, "../../package.json")); |
| 371 | return (JSON.parse(content) as { version: string }).version; |
| 372 | }); |
| 373 | |
| 374 | /** |
| 375 | * The rebuild-free `input` hash: project tree + external workspaces + |
| 376 | * package version + build-affecting options. Mirrors alchemy's |
| 377 | * `hashViteInput` semantics (`Workers/Sources/Vite.ts`) — never hashes |
| 378 | * absolute paths, so relocating an identical tree is a no-op. |
| 379 | */ |
| 380 | const hashSvelteKitInput = Effect.fnUntraced(function* ( |
| 381 | rootDir: string, |
| 382 | options: SvelteKitSourceOptions, |
| 383 | workspaces: Iterable<string>, |
| 384 | ) { |
| 385 | const version = yield* packageVersion; |
| 386 | const hashWorkspace = (cwd: string, memo?: SvelteKitMemoOptions) => |
| 387 | hashDirectory(NodePath.resolve(rootDir, cwd), memo).pipe( |
| 388 | Effect.map((hash) => `${NodePath.relative(rootDir, NodePath.resolve(rootDir, cwd))}:${hash}`), |
| 389 | ); |
| 390 | const [root, ...workspaceHashes] = yield* Effect.all( |
| 391 | [hashWorkspace(rootDir, options.memo), ...Array.from(workspaces, (cwd) => hashWorkspace(cwd))], |
| 392 | { concurrency: "unbounded" }, |
| 393 | ); |
| 394 | const hash = yield* sha256Stable({ |
| 395 | version, |
| 396 | options: { |
| 397 | memo: options.memo, |
| 398 | kit: options.kit, |
| 399 | adapter: options.adapter, |
| 400 | }, |
| 401 | tree: [root, ...workspaceHashes.sort()], |
| 402 | }); |
| 403 | return { |
| 404 | hash, |
| 405 | workspaces: Array.from(workspaces, (cwd) => |
| 406 | NodePath.relative(rootDir, NodePath.resolve(rootDir, cwd)), |
| 407 | ), |
| 408 | }; |
| 409 | }); |
| 410 | |
| 411 | // ───────────────────────────────────────────────────────────────────── |
| 412 | // Assets (mirror of alchemy's `readAssets` in `Workers/Assets.ts`: |
| 413 | // manifest of 32-hex content hashes, honoring `.assetsignore`, |
| 414 | // `_headers`, `_redirects`; the overall hash excludes the directory |
| 415 | // path so identical bytes hash identically across machines) |
| 416 | // ───────────────────────────────────────────────────────────────────── |
| 417 | |
| 418 | const MAX_ASSET_SIZE = 1024 * 1024 * 25; // 25MB (Cloudflare limit) |
| 419 | const MAX_ASSET_COUNT = 20_000; |
| 420 | |
| 421 | const maybeReadString = (fs: FileSystem.FileSystem, file: string) => |
| 422 | fs |
| 423 | .readFileString(file) |
| 424 | .pipe( |
| 425 | Effect.catchTag("PlatformError", (error) => |
| 426 | error.reason._tag === "NotFound" ? Effect.undefined : Effect.fail(error), |
| 427 | ), |
| 428 | ); |
| 429 | |
| 430 | const readAssetsDirectory = Effect.fnUntraced(function* ( |
| 431 | directory: string, |
| 432 | config: Record<string, unknown> | undefined, |
| 433 | ) { |
| 434 | const fs = yield* FileSystem.FileSystem; |
| 435 | const [ignore, _headers, _redirects] = yield* Effect.all([ |
| 436 | maybeReadString(fs, NodePath.join(directory, ".assetsignore")), |
| 437 | maybeReadString(fs, NodePath.join(directory, "_headers")), |
| 438 | maybeReadString(fs, NodePath.join(directory, "_redirects")), |
| 439 | ]); |
| 440 | const files = yield* Effect.promise(() => |
| 441 | glob(["**/*"], { |
| 442 | cwd: directory, |
| 443 | ignore: [ |
| 444 | ".assetsignore", |
| 445 | "_headers", |
| 446 | "_redirects", |
| 447 | ...gitignoreRulesToGlobs(ignore?.split("\n") ?? []), |
| 448 | ], |
| 449 | onlyFiles: true, |
| 450 | expandDirectories: false, |
| 451 | dot: true, |
| 452 | }), |
| 453 | ); |
| 454 | if (files.length > MAX_ASSET_COUNT) { |
| 455 | return yield* new SourceProviderError({ |
| 456 | provider: PROVIDER, |
| 457 | message: `Too many assets in ${directory} (maximum is ${MAX_ASSET_COUNT}, found ${files.length})`, |
| 458 | }); |
| 459 | } |
| 460 | const entries = yield* Effect.forEach( |
| 461 | files.sort(), |
| 462 | Effect.fnUntraced(function* (name) { |
| 463 | const file = NodePath.join(directory, name); |
| 464 | const content = yield* fs.readFile(file); |
| 465 | if (content.byteLength > MAX_ASSET_SIZE) { |
| 466 | return yield* new SourceProviderError({ |
| 467 | provider: PROVIDER, |
| 468 | message: `Asset ${name} is too large (the maximum size is 25 MB)`, |
| 469 | }); |
| 470 | } |
| 471 | const hash = (yield* sha256Hex(content)).slice(0, 32); |
| 472 | return [`/${name.replaceAll("\\", "/")}`, { hash, size: content.byteLength }] as const; |
| 473 | }), |
| 474 | { concurrency: 16 }, |
| 475 | ); |
| 476 | const manifest = Object.fromEntries([...entries].sort((a, b) => a[0].localeCompare(b[0]))); |
| 477 | const hash = yield* sha256Stable({ config, manifest, _headers, _redirects }); |
| 478 | return { |
| 479 | directory, |
| 480 | config, |
| 481 | manifest, |
| 482 | _headers, |
| 483 | _redirects, |
| 484 | hash, |
| 485 | } satisfies SourceAssetReadResult; |
| 486 | }); |
| 487 | |
| 488 | // ───────────────────────────────────────────────────────────────────── |
| 489 | // The provider |
| 490 | // ───────────────────────────────────────────────────────────────────── |
| 491 | |
| 492 | const wrapFrameworkError = (error: { readonly message: string; readonly cause?: unknown }) => |
| 493 | new SourceProviderError({ |
| 494 | provider: PROVIDER, |
| 495 | message: error.message, |
| 496 | cause: error.cause ?? error, |
| 497 | }); |
| 498 | |
| 499 | const assetsConfig = (assets: SourceContext["assets"]): Record<string, unknown> | undefined => { |
| 500 | if (assets === undefined || typeof assets === "string") { |
| 501 | return undefined; |
| 502 | } |
| 503 | const { directory: _directory, hash: _hash, ...config } = assets; |
| 504 | return Object.keys(config).length > 0 ? config : undefined; |
| 505 | }; |
| 506 | |
| 507 | /** |
| 508 | * Resolve the Worker's literal env values as dev `platform.env` overrides: |
| 509 | * strings pass through, `Redacted<string>`s are unwrapped, everything else |
| 510 | * (Effects, resource bindings) is skipped — those are delivered as real |
| 511 | * bindings through the platform proxy via `ctx.worker.bindings`. A |
| 512 | * same-named literal wins over the proxied value. |
| 513 | */ |
| 514 | const resolveDevEnvOverrides = ( |
| 515 | env: Record<string, unknown> | undefined, |
| 516 | ): Record<string, unknown> => { |
| 517 | const out: Record<string, unknown> = {}; |
| 518 | for (const [key, value] of Object.entries(env ?? {})) { |
| 519 | if (typeof value === "string") { |
| 520 | out[key] = value; |
| 521 | } else if (Redacted.isRedacted(value) && typeof Redacted.value(value) === "string") { |
| 522 | out[key] = Redacted.value(value); |
| 523 | } |
| 524 | } |
| 525 | return out; |
| 526 | }; |
| 527 | |
| 528 | /** |
| 529 | * SvelteKit resolves its config (and the postbuild analyse/prerender worker |
| 530 | * threads re-derive `outDir`) relative to `process.cwd()` — with the |
| 531 | * in-memory config there is no `vite.config` file for the workers to |
| 532 | * re-load, so their fallback resolves against the cwd. The build therefore |
| 533 | * runs in a disposable child process whose working directory IS the project |
| 534 | * root (see `core/BuildChild.ts`) — no in-process `chdir`, no process-level |
| 535 | * lock, unbounded build concurrency. The shared `core/BuildChildRunner` |
| 536 | * entry imports this module in the child and calls the exported |
| 537 | * {@link buildInChild}. |
| 538 | */ |
| 539 | export interface SvelteKitBuildChildConfig { |
| 540 | readonly rootDir: string; |
| 541 | readonly compatibilityDate: string; |
| 542 | readonly compatibilityFlags: Array<string>; |
| 543 | readonly kit: Record<string, unknown> | undefined; |
| 544 | readonly adapter: SvelteKitAdapterOptions | undefined; |
| 545 | } |
| 546 | |
| 547 | export const buildInChild = (config: SvelteKitBuildChildConfig) => |
| 548 | Effect.gen(function* () { |
| 549 | const framework = yield* makeSvelteKit({ |
| 550 | root: config.rootDir, |
| 551 | target: makeCloudflareTarget, |
| 552 | compatibilityDate: config.compatibilityDate, |
| 553 | compatibilityFlags: config.compatibilityFlags, |
| 554 | kit: config.kit, |
| 555 | adapter: config.adapter, |
| 556 | }); |
| 557 | return yield* framework.build({ root: config.rootDir }); |
| 558 | }); |
| 559 | |
| 560 | export const makeSvelteKitSource = (options: SvelteKitSourceOptions): SourceProvider => { |
| 561 | const rootDir = NodePath.resolve(options.rootDir ?? process.cwd()); |
| 562 | const frameworkOptions = ( |
| 563 | ctx: SourceContext, |
| 564 | dev?: SvelteKitOptions["dev"], |
| 565 | ): SvelteKitOptions => ({ |
| 566 | root: rootDir, |
| 567 | // This module is Cloudflare-specific by contract (it implements alchemy's |
| 568 | // Cloudflare Worker source), so it passes the target factory directly |
| 569 | // instead of relying on specifier resolution from the project's |
| 570 | // node_modules. |
| 571 | target: makeCloudflareTarget, |
| 572 | compatibilityDate: ctx.compatibility.date, |
| 573 | compatibilityFlags: ctx.compatibility.flags, |
| 574 | kit: options.kit, |
| 575 | adapter: options.adapter, |
| 576 | dev, |
| 577 | }); |
| 578 | return { |
| 579 | ownsAssets: true, |
| 580 | // The dev platform proxy serves kit's static directory to `ASSETS`. |
| 581 | devAssetsBinding: true, |
| 582 | build: Effect.fnUntraced(function* (ctx) { |
| 583 | const output = yield* runBuildChild({ |
| 584 | module: import.meta.url, |
| 585 | rootDir, |
| 586 | framework: "sveltekit", |
| 587 | env: resolveBuildEnv(ctx.env), |
| 588 | config: { |
| 589 | rootDir, |
| 590 | compatibilityDate: ctx.compatibility.date, |
| 591 | compatibilityFlags: ctx.compatibility.flags, |
| 592 | kit: options.kit, |
| 593 | adapter: options.adapter, |
| 594 | } satisfies SvelteKitBuildChildConfig, |
| 595 | }).pipe(Effect.mapError(wrapFrameworkError)); |
| 596 | if (output.serverModules === undefined || output.serverModules.length === 0) { |
| 597 | return yield* new SourceProviderError({ |
| 598 | provider: PROVIDER, |
| 599 | message: "The SvelteKit build produced no server modules", |
| 600 | }); |
| 601 | } |
| 602 | if (output.clientDirectory === undefined) { |
| 603 | return yield* new SourceProviderError({ |
| 604 | provider: PROVIDER, |
| 605 | message: "The SvelteKit build produced no client directory", |
| 606 | }); |
| 607 | } |
| 608 | const files = output.serverModules.map((module): SourceBundleFile => ({ |
| 609 | path: module.name, |
| 610 | content: module.content, |
| 611 | hash: module.hash, |
| 612 | })) as [SourceBundleFile, ...Array<SourceBundleFile>]; |
| 613 | const [bundleHash, assets, input] = yield* Effect.all( |
| 614 | [ |
| 615 | sha256Stable(files.map((file) => `${file.path}:${file.hash}`)), |
| 616 | readAssetsDirectory( |
| 617 | NodePath.resolve(rootDir, output.clientDirectory), |
| 618 | assetsConfig(ctx.assets), |
| 619 | ), |
| 620 | hashSvelteKitInput(rootDir, options, output.externalWorkspaces), |
| 621 | ], |
| 622 | { concurrency: "unbounded" }, |
| 623 | ); |
| 624 | return { |
| 625 | bundle: { files, hash: bundleHash }, |
| 626 | assets, |
| 627 | hash: { |
| 628 | bundle: bundleHash, |
| 629 | assets: assets.hash, |
| 630 | input: input.hash, |
| 631 | additionalWorkspaces: input.workspaces, |
| 632 | }, |
| 633 | } satisfies SourceBuildOutput; |
| 634 | }), |
| 635 | hash: Effect.fnUntraced(function* (_ctx, previous) { |
| 636 | const { hash, workspaces } = yield* hashSvelteKitInput( |
| 637 | rootDir, |
| 638 | options, |
| 639 | previous?.additionalWorkspaces ?? [], |
| 640 | ); |
| 641 | return { input: hash, additionalWorkspaces: workspaces }; |
| 642 | }), |
| 643 | dev: Effect.fnUntraced(function* (ctx: SourceDevContext) { |
| 644 | const framework = yield* makeSvelteKit( |
| 645 | frameworkOptions(ctx, { |
| 646 | env: resolveDevEnvOverrides(ctx.env), |
| 647 | bindings: ctx.worker.bindings, |
| 648 | // The host's runtime stack (includes remote-bindings support) — |
| 649 | // the dev platform proxy is hosted in it instead of the |
| 650 | // credential-free internal layer, so `Alchemy.remote()` bindings |
| 651 | // resolve in dev. |
| 652 | services: ctx.runtimeContext, |
| 653 | workerd: ctx.worker.options.workerd, |
| 654 | }), |
| 655 | ); |
| 656 | const server = yield* framework |
| 657 | .dev({ root: rootDir, port: 0 }) |
| 658 | .pipe(Effect.mapError(wrapFrameworkError)); |
| 659 | return { |
| 660 | mode: "server", |
| 661 | url: new URL(server.url), |
| 662 | serviceBinding: "http", |
| 663 | } satisfies SourceDevHandle; |
| 664 | }), |
| 665 | }; |
| 666 | }; |
| 667 | |
| 668 | /** |
| 669 | * The `WorkerSourceModule` contract: alchemy dynamically imports this module |
| 670 | * and calls `make(descriptor.options)`. |
| 671 | */ |
| 672 | const sourceModule = { |
| 673 | make: (options: unknown): Effect.Effect<SourceProvider, SourceProviderError> => |
| 674 | Effect.succeed(makeSvelteKitSource((options ?? {}) as SvelteKitSourceOptions)), |
| 675 | }; |
| 676 | |
| 677 | export default sourceModule; |