The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodeCrypto from "node:crypto"; |
| 2 | import { createRequire } from "node:module"; |
| 3 | import type { |
| 4 | BindingHook, |
| 5 | BindingServices, |
| 6 | HyperdriveOrigin, |
| 7 | Assets as RuntimeAssets, |
| 8 | DurableObjectNamespace as RuntimeDurableObject, |
| 9 | QueueConsumer as RuntimeQueueConsumer, |
| 10 | RuntimeServices, |
| 11 | RuntimeWorker, |
| 12 | } from "@alchemy.run/cloudflare-runtime/core"; |
| 13 | import type * as Context from "effect/Context"; |
| 14 | import * as Data from "effect/Data"; |
| 15 | import * as Effect from "effect/Effect"; |
| 16 | import * as FileSystem from "effect/FileSystem"; |
| 17 | import * as Layer from "effect/Layer"; |
| 18 | import * as Path from "effect/Path"; |
| 19 | import type { PlatformError } from "effect/PlatformError"; |
| 20 | import type * as Scope from "effect/Scope"; |
| 21 | import * as Semaphore from "effect/Semaphore"; |
| 22 | import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts"; |
| 23 | import * as FrameworkCore from "../core/index.ts"; |
| 24 | import { makeWakuCloudflareTarget } from "./cloudflare.ts"; |
| 25 | import { layer as wakuFrameworkLayer } from "./Waku.ts"; |
| 26 | |
| 27 | // ───────────────────────────────────────────────────────────────────────────── |
| 28 | // Structural mirror of alchemy's Worker source-provider contract. |
| 29 | // |
| 30 | // This module is loaded dynamically by alchemy's `loadSource` (see |
| 31 | // `packages/cloudflare/src/Workers/Source.ts` — `WorkerSourceModule`, |
| 32 | // `SourceProvider`, `SourceContext`, `DevContext`, `SourceBuildOutput`). The |
| 33 | // contract is deliberately implemented STRUCTURALLY — no alchemy import — so |
| 34 | // version skew degrades to a load-time `SourceProviderError` instead of a |
| 35 | // crash. Keep these shapes in sync with the alchemy interfaces. |
| 36 | // ───────────────────────────────────────────────────────────────────────────── |
| 37 | |
| 38 | /** Mirror of alchemy `Cloudflare/Workers/Source.SourceHash`. */ |
| 39 | export interface SourceHash { |
| 40 | readonly bundle: string | undefined; |
| 41 | readonly assets: string | undefined; |
| 42 | readonly input: string | undefined; |
| 43 | readonly additionalWorkspaces: Array<string> | undefined; |
| 44 | } |
| 45 | |
| 46 | /** Mirror of alchemy `Bundle/Bundle.BundleFile`. */ |
| 47 | export interface BundleFile { |
| 48 | readonly path: string; |
| 49 | readonly content: string | Uint8Array; |
| 50 | readonly hash: string; |
| 51 | } |
| 52 | |
| 53 | /** Mirror of alchemy `Bundle/Bundle.BundleOutput`. */ |
| 54 | export interface BundleOutput { |
| 55 | readonly files: [BundleFile, ...Array<BundleFile>]; |
| 56 | readonly hash: string; |
| 57 | } |
| 58 | |
| 59 | /** Mirror of alchemy `Cloudflare/Workers/Assets.AssetReadResult`. */ |
| 60 | export interface AssetReadResult { |
| 61 | directory: string; |
| 62 | config: Record<string, unknown> | undefined; |
| 63 | manifest: Record<string, { hash: string; size: number }>; |
| 64 | _headers: string | undefined; |
| 65 | _redirects: string | undefined; |
| 66 | hash: string; |
| 67 | } |
| 68 | |
| 69 | /** Mirror of alchemy `Cloudflare/Workers/Source.SourceBuildOutput`. */ |
| 70 | export interface SourceBuildOutput { |
| 71 | readonly bundle: BundleOutput | undefined; |
| 72 | readonly assets: AssetReadResult | undefined; |
| 73 | readonly hash: SourceHash; |
| 74 | } |
| 75 | |
| 76 | /** Mirror of alchemy `Cloudflare/Workers/Source.SourceContext`. */ |
| 77 | export interface SourceContext { |
| 78 | readonly id: string; |
| 79 | readonly workerName: string; |
| 80 | readonly compatibility: { |
| 81 | readonly date: string; |
| 82 | readonly flags: Array<string>; |
| 83 | }; |
| 84 | readonly entry: |
| 85 | | { readonly kind: "external" } |
| 86 | | { readonly kind: "effect"; readonly exports: Record<string, unknown> }; |
| 87 | readonly stack: { readonly name: string; readonly stage: string }; |
| 88 | readonly env: Record<string, unknown> | undefined; |
| 89 | readonly extraOptions: unknown; |
| 90 | /** Raw `props.assets` (routing config; sources that own assets merge it in). */ |
| 91 | readonly assets: unknown; |
| 92 | } |
| 93 | |
| 94 | /** Mirror of alchemy `Cloudflare/Workers/Source.DevContext`. */ |
| 95 | export interface DevContext extends SourceContext { |
| 96 | readonly worker: { |
| 97 | readonly bindings: Array<BindingHook<BindingServices>>; |
| 98 | readonly durableObjectNamespaces: Array<RuntimeDurableObject & { uniqueKey: string }>; |
| 99 | readonly hyperdrives: Record<string, Required<HyperdriveOrigin>>; |
| 100 | readonly queueConsumers: Effect.Effect<Array<RuntimeQueueConsumer>>; |
| 101 | readonly assets: RuntimeAssets | undefined; |
| 102 | /** |
| 103 | * The Worker's other runtime settings (crons, Workflows, tail consumers, |
| 104 | * Cache API, `request.cf`, zone, Access), spread whole into the runtime |
| 105 | * Worker. |
| 106 | */ |
| 107 | readonly options: Pick< |
| 108 | RuntimeWorker, |
| 109 | "workflows" | "crons" | "tails" | "streamingTails" | "cache" | "cf" | "zone" | "access" |
| 110 | >; |
| 111 | }; |
| 112 | readonly runtimeContext: Context.Context<RuntimeServices>; |
| 113 | } |
| 114 | |
| 115 | /** The `server`-mode arm of alchemy's `SourceDevHandle` (waku dev is a vite dev server). */ |
| 116 | export interface ServerDevHandle { |
| 117 | readonly mode: "server"; |
| 118 | readonly url: URL; |
| 119 | } |
| 120 | |
| 121 | /** |
| 122 | * Tag-compatible mirror of alchemy's |
| 123 | * `Cloudflare.Workers.SourceProviderError` — same `_tag`, same fields, so |
| 124 | * `Effect.catchTag` on the alchemy side matches errors raised here. |
| 125 | */ |
| 126 | export class SourceProviderError extends Data.TaggedError( |
| 127 | "Cloudflare.Workers.SourceProviderError", |
| 128 | )<{ |
| 129 | readonly provider: string; |
| 130 | readonly message: string; |
| 131 | readonly cause?: unknown; |
| 132 | }> {} |
| 133 | |
| 134 | export type WakuSourceError = SourceProviderError | PlatformError; |
| 135 | |
| 136 | export type SourceRequirements = FileSystem.FileSystem | Path.Path; |
| 137 | |
| 138 | /** Mirror of alchemy `Cloudflare/Workers/Source.SourceProvider` (narrowed E/R). */ |
| 139 | export interface SourceProvider { |
| 140 | readonly ownsAssets: boolean; |
| 141 | readonly devAssetsBinding?: boolean; |
| 142 | readonly build: ( |
| 143 | ctx: SourceContext, |
| 144 | ) => Effect.Effect<SourceBuildOutput, WakuSourceError, SourceRequirements>; |
| 145 | readonly hash: ( |
| 146 | ctx: SourceContext, |
| 147 | previous: SourceHash | undefined, |
| 148 | ) => Effect.Effect<Partial<SourceHash>, WakuSourceError, SourceRequirements>; |
| 149 | readonly dev: ( |
| 150 | ctx: DevContext, |
| 151 | ) => Effect.Effect<ServerDevHandle, WakuSourceError, SourceRequirements | Scope.Scope>; |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Serializable options of the waku source descriptor |
| 156 | * (`{ provider: "@alchemy.run/frontend-frameworks/waku/source", options }` on alchemy's |
| 157 | * `WorkerProps.source`). MUST stay plain JSON data — the descriptor persists |
| 158 | * in alchemy state and participates in the Worker metadata hash. |
| 159 | */ |
| 160 | export interface WakuSourceOptions { |
| 161 | /** Project root. Defaults to the process working directory. */ |
| 162 | readonly rootDir?: string | undefined; |
| 163 | /** |
| 164 | * The user's own worker entry (the user-entry seam, |
| 165 | * `DeployTarget.entry`): a module that wraps waku's handler — imported |
| 166 | * from `virtual:waku/server-entry` — and re-exports extras (Durable |
| 167 | * Object classes, additional handlers). Relative paths resolve against |
| 168 | * the root. When unset, waku's own rsc server entry is deployed. |
| 169 | */ |
| 170 | readonly main?: string | undefined; |
| 171 | /** Waku `srcDir` (relative to the root). @default "src" */ |
| 172 | readonly srcDir?: string | undefined; |
| 173 | /** |
| 174 | * Waku `distDir` (relative to the root). If `waku.config.ts` customizes |
| 175 | * `distDir`, mirror it here (or add it to `memo.exclude`) so the build |
| 176 | * output stays excluded from the rebuild-deciding input hash. |
| 177 | * @default "dist" |
| 178 | */ |
| 179 | readonly distDir?: string | undefined; |
| 180 | /** Waku `basePath`. @default "/" */ |
| 181 | readonly basePath?: string | undefined; |
| 182 | /** Controls which files feed the rebuild-deciding `input` hash. */ |
| 183 | readonly memo?: WakuMemoOptions | undefined; |
| 184 | } |
| 185 | |
| 186 | const wakuConfigFor = (options: WakuSourceOptions) => ({ |
| 187 | ...(options.srcDir !== undefined ? { srcDir: options.srcDir } : undefined), |
| 188 | ...(options.distDir !== undefined ? { distDir: options.distDir } : undefined), |
| 189 | ...(options.basePath !== undefined ? { basePath: options.basePath } : undefined), |
| 190 | }); |
| 191 | |
| 192 | /** |
| 193 | * Input-hash scoping, mirroring the semantics of alchemy's `MemoOptions` |
| 194 | * (`Command/Memo.ts`): by default every non-gitignored file under the root is |
| 195 | * hashed plus the nearest package-manager lockfile; explicit `include` / |
| 196 | * `exclude` globs narrow the scope. |
| 197 | * |
| 198 | * The glob support is a self-contained subset (`**`, `*`, `?`; gitignore-style |
| 199 | * anchoring). Negated (`!`) gitignore rules are ignored (files they would |
| 200 | * re-include stay excluded from the hash). |
| 201 | */ |
| 202 | export interface WakuMemoOptions { |
| 203 | /** Glob patterns of files to hash, relative to the root. @default all files */ |
| 204 | readonly include?: Array<string> | undefined; |
| 205 | /** Glob patterns to exclude. @default gitignore rules from the root up to the repo root */ |
| 206 | readonly exclude?: Array<string> | undefined; |
| 207 | /** |
| 208 | * Whether to include the nearest package-manager lockfile in the hash. |
| 209 | * @default true when both `include` and `exclude` are unset; false otherwise |
| 210 | */ |
| 211 | readonly lockfile?: boolean | undefined; |
| 212 | } |
| 213 | |
| 214 | // ───────────────────────────────────────────────────────────────────────────── |
| 215 | // Hashing primitives |
| 216 | // ───────────────────────────────────────────────────────────────────────────── |
| 217 | |
| 218 | const sha256 = (input: string | Uint8Array): string => |
| 219 | NodeCrypto.createHash("sha256").update(input).digest("hex"); |
| 220 | |
| 221 | const stableValue = (value: unknown): unknown => { |
| 222 | if (Array.isArray(value)) { |
| 223 | return value.map(stableValue); |
| 224 | } |
| 225 | if (value !== null && typeof value === "object" && value.constructor === Object) { |
| 226 | return Object.fromEntries( |
| 227 | Object.entries(value as Record<string, unknown>) |
| 228 | .sort(([a], [b]) => a.localeCompare(b)) |
| 229 | .map(([key, nested]) => [key, stableValue(nested)]), |
| 230 | ); |
| 231 | } |
| 232 | return value; |
| 233 | }; |
| 234 | |
| 235 | const sha256Object = (value: unknown): string => sha256(JSON.stringify(stableValue(value))); |
| 236 | |
| 237 | /** The integration's own version — included in the input hash so upgrading the |
| 238 | * adapter busts the build memo even when project sources are unchanged. */ |
| 239 | const PACKAGE_VERSION: string = ( |
| 240 | createRequire(import.meta.url)("../../package.json") as { version: string } |
| 241 | ).version; |
| 242 | |
| 243 | // ───────────────────────────────────────────────────────────────────────────── |
| 244 | // Minimal gitignore-style matching (documented subset, zero dependencies) |
| 245 | // ───────────────────────────────────────────────────────────────────────────── |
| 246 | |
| 247 | const escapeRegExpChar = (char: string): string => |
| 248 | /[.*+?^${}()|[\]\\]/.test(char) ? `\\${char}` : char; |
| 249 | |
| 250 | const globBodyToRegExpSource = (glob: string): string => { |
| 251 | let source = ""; |
| 252 | let i = 0; |
| 253 | while (i < glob.length) { |
| 254 | const char = glob[i]!; |
| 255 | if (char === "*") { |
| 256 | if (glob[i + 1] === "*") { |
| 257 | if (glob[i + 2] === "/") { |
| 258 | source += "(?:[^/]+/)*"; |
| 259 | i += 3; |
| 260 | } else { |
| 261 | source += ".*"; |
| 262 | i += 2; |
| 263 | } |
| 264 | } else { |
| 265 | source += "[^/]*"; |
| 266 | i += 1; |
| 267 | } |
| 268 | } else if (char === "?") { |
| 269 | source += "[^/]"; |
| 270 | i += 1; |
| 271 | } else { |
| 272 | source += escapeRegExpChar(char); |
| 273 | i += 1; |
| 274 | } |
| 275 | } |
| 276 | return source; |
| 277 | }; |
| 278 | |
| 279 | /** |
| 280 | * Compile one gitignore-style rule into a RegExp over root-relative posix |
| 281 | * paths. The RegExp matches the path itself and everything under it (so a |
| 282 | * rule matching a directory also matches its files). Returns `undefined` for |
| 283 | * blank lines, comments, and negated rules (unsupported). |
| 284 | */ |
| 285 | const compileIgnoreRule = (raw: string): RegExp | undefined => { |
| 286 | let rule = raw.trim(); |
| 287 | if (rule.length === 0 || rule.startsWith("#") || rule.startsWith("!")) { |
| 288 | return undefined; |
| 289 | } |
| 290 | if (rule.endsWith("/")) { |
| 291 | rule = rule.slice(0, -1); |
| 292 | } |
| 293 | if (rule.length === 0) { |
| 294 | return undefined; |
| 295 | } |
| 296 | // Anchored when the rule contains a `/` (the trailing directory `/` was |
| 297 | // already stripped above); otherwise it matches a basename at any depth. |
| 298 | const anchored = rule.includes("/"); |
| 299 | if (rule.startsWith("/")) { |
| 300 | rule = rule.slice(1); |
| 301 | } |
| 302 | const body = globBodyToRegExpSource(rule); |
| 303 | const prefix = anchored ? "^" : "^(?:.*/)?"; |
| 304 | return new RegExp(`${prefix}${body}(?:/.*)?$`); |
| 305 | }; |
| 306 | |
| 307 | const compileIgnoreRules = (rules: ReadonlyArray<string>): Array<RegExp> => |
| 308 | rules.map(compileIgnoreRule).filter((regex): regex is RegExp => regex !== undefined); |
| 309 | |
| 310 | const compileIncludeGlobs = (globs: ReadonlyArray<string>): Array<RegExp> => |
| 311 | globs.map((glob) => new RegExp(`^${globBodyToRegExpSource(glob)}$`)); |
| 312 | |
| 313 | const matchesAny = (regexes: ReadonlyArray<RegExp>, path: string): boolean => |
| 314 | regexes.some((regex) => regex.test(path)); |
| 315 | |
| 316 | // ───────────────────────────────────────────────────────────────────────────── |
| 317 | // Input-tree hashing (the rebuild-free change signal, mirroring the semantics |
| 318 | // of alchemy's `hashViteInput` / `hashDirectory`) |
| 319 | // ───────────────────────────────────────────────────────────────────────────── |
| 320 | |
| 321 | const LOCKFILE_NAMES = [ |
| 322 | "bun.lock", |
| 323 | "bun.lockb", |
| 324 | "package-lock.json", |
| 325 | "pnpm-lock.yaml", |
| 326 | "yarn.lock", |
| 327 | ]; |
| 328 | |
| 329 | const findUp = Effect.fn(function* (startDir: string, filenames: ReadonlyArray<string>) { |
| 330 | const fs = yield* FileSystem.FileSystem; |
| 331 | const path = yield* Path.Path; |
| 332 | let dir = startDir; |
| 333 | for (;;) { |
| 334 | for (const filename of filenames) { |
| 335 | const candidate = path.join(dir, filename); |
| 336 | if (yield* fs.exists(candidate)) { |
| 337 | return candidate; |
| 338 | } |
| 339 | } |
| 340 | const parent = path.dirname(dir); |
| 341 | if (parent === dir) { |
| 342 | return undefined; |
| 343 | } |
| 344 | dir = parent; |
| 345 | } |
| 346 | }); |
| 347 | |
| 348 | /** Collect `.gitignore` rules from `rootDir` up to the repo root (the first |
| 349 | * directory containing `.git`), outermost first — same walk as alchemy's |
| 350 | * `Command/Memo.ts`. Rules apply relative to `rootDir` (simplification). */ |
| 351 | const readGitIgnoreRules = Effect.fn(function* (rootDir: string) { |
| 352 | const fs = yield* FileSystem.FileSystem; |
| 353 | const path = yield* Path.Path; |
| 354 | const chain: Array<Array<string>> = []; |
| 355 | let dir = rootDir; |
| 356 | for (;;) { |
| 357 | const gitignore = path.join(dir, ".gitignore"); |
| 358 | if (yield* fs.exists(gitignore)) { |
| 359 | const content = yield* fs.readFileString(gitignore); |
| 360 | chain.unshift(content.split("\n")); |
| 361 | } |
| 362 | if (yield* fs.exists(path.join(dir, ".git"))) { |
| 363 | break; |
| 364 | } |
| 365 | const parent = path.dirname(dir); |
| 366 | if (parent === dir) { |
| 367 | break; |
| 368 | } |
| 369 | dir = parent; |
| 370 | } |
| 371 | return chain.flat(); |
| 372 | }); |
| 373 | |
| 374 | interface ResolvedMemo { |
| 375 | readonly include: Array<RegExp> | undefined; |
| 376 | readonly exclude: Array<RegExp>; |
| 377 | readonly lockfile: boolean; |
| 378 | } |
| 379 | |
| 380 | const resolveMemo = Effect.fn(function* ( |
| 381 | rootDir: string, |
| 382 | distDir: string, |
| 383 | memo: WakuMemoOptions | undefined, |
| 384 | ) { |
| 385 | const exclude = |
| 386 | memo?.exclude !== undefined |
| 387 | ? compileIgnoreRules(memo.exclude) |
| 388 | : compileIgnoreRules(yield* readGitIgnoreRules(rootDir)); |
| 389 | return { |
| 390 | include: memo?.include !== undefined ? compileIncludeGlobs(memo.include) : undefined, |
| 391 | exclude: [ |
| 392 | // Always excluded regardless of gitignore: dependency trees, VCS |
| 393 | // metadata, and the build output waku itself writes (hashing `distDir` |
| 394 | // would make every build bust its own memo). |
| 395 | ...compileIgnoreRules(["node_modules", ".git", `/${distDir}`]), |
| 396 | ...exclude, |
| 397 | ], |
| 398 | lockfile: memo?.lockfile ?? !(memo?.include || memo?.exclude), |
| 399 | } satisfies ResolvedMemo; |
| 400 | }); |
| 401 | |
| 402 | /** Deterministic, machine-independent content hash of one directory tree: |
| 403 | * sorted `[relativePosixPath, sha256(content)]` pairs (never absolute paths). */ |
| 404 | const hashDirectory = Effect.fn(function* (rootDir: string, memo: ResolvedMemo) { |
| 405 | const fs = yield* FileSystem.FileSystem; |
| 406 | const path = yield* Path.Path; |
| 407 | |
| 408 | const files: Array<string> = []; |
| 409 | const walk: (dir: string, rel: string) => Effect.Effect<void, PlatformError> = Effect.fn( |
| 410 | function* (dir: string, rel: string) { |
| 411 | const entries = (yield* fs.readDirectory(dir)).sort(); |
| 412 | for (const entry of entries) { |
| 413 | const relPath = rel === "" ? entry : `${rel}/${entry}`; |
| 414 | if (matchesAny(memo.exclude, relPath)) { |
| 415 | continue; |
| 416 | } |
| 417 | const absPath = path.join(dir, entry); |
| 418 | const stat = yield* fs.stat(absPath); |
| 419 | if (stat.type === "Directory") { |
| 420 | yield* walk(absPath, relPath); |
| 421 | } else if (stat.type === "File") { |
| 422 | if (memo.include !== undefined && !matchesAny(memo.include, relPath)) { |
| 423 | continue; |
| 424 | } |
| 425 | files.push(relPath); |
| 426 | } |
| 427 | } |
| 428 | }, |
| 429 | ); |
| 430 | yield* walk(rootDir, ""); |
| 431 | |
| 432 | if (memo.lockfile) { |
| 433 | const lockfile = yield* findUp(rootDir, LOCKFILE_NAMES); |
| 434 | if (lockfile !== undefined) { |
| 435 | const relative = path.relative(rootDir, lockfile).replaceAll("\\", "/"); |
| 436 | if (!files.includes(relative)) { |
| 437 | files.push(relative); |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | const hashes = yield* Effect.forEach( |
| 443 | files.sort(), |
| 444 | Effect.fn(function* (file) { |
| 445 | const content = yield* fs.readFile(path.join(rootDir, file)); |
| 446 | return `${file}:${sha256(content)}`; |
| 447 | }), |
| 448 | { concurrency: 16 }, |
| 449 | ); |
| 450 | return sha256Object(hashes); |
| 451 | }); |
| 452 | |
| 453 | /** |
| 454 | * The `input` hash slot: the project tree (+ workspaces + lockfile), the |
| 455 | * integration's own package version, and the build-affecting waku options. |
| 456 | * Deterministic for an unchanged tree and stable across `rootDir` moves. |
| 457 | */ |
| 458 | const hashWakuInput = Effect.fn(function* (params: { |
| 459 | rootDir: string; |
| 460 | distDir: string; |
| 461 | memo: WakuMemoOptions | undefined; |
| 462 | options: WakuSourceOptions; |
| 463 | /** Workspace directories, absolute. */ |
| 464 | workspaces: Iterable<string>; |
| 465 | }) { |
| 466 | const path = yield* Path.Path; |
| 467 | const memo = yield* resolveMemo(params.rootDir, params.distDir, params.memo); |
| 468 | const workspaceMemo = yield* resolveMemo(params.rootDir, params.distDir, undefined); |
| 469 | const [root, ...workspaceHashes] = yield* Effect.all( |
| 470 | [ |
| 471 | hashDirectory(params.rootDir, memo), |
| 472 | ...Array.from(params.workspaces).map((workspace) => |
| 473 | Effect.gen(function* () { |
| 474 | const resolved = path.resolve(params.rootDir, workspace); |
| 475 | const rules = yield* readGitIgnoreRules(resolved); |
| 476 | const hash = yield* hashDirectory(resolved, { |
| 477 | ...workspaceMemo, |
| 478 | exclude: [...workspaceMemo.exclude, ...compileIgnoreRules(rules)], |
| 479 | }); |
| 480 | return `${path.relative(params.rootDir, resolved).replaceAll("\\", "/")}:${hash}`; |
| 481 | }), |
| 482 | ), |
| 483 | ], |
| 484 | { concurrency: 4 }, |
| 485 | ); |
| 486 | const hash = sha256Object({ |
| 487 | version: PACKAGE_VERSION, |
| 488 | root, |
| 489 | workspaces: workspaceHashes.sort(), |
| 490 | options: { |
| 491 | // Build-affecting: a changed user entry must bust the memo. |
| 492 | main: params.options.main, |
| 493 | srcDir: params.options.srcDir, |
| 494 | distDir: params.options.distDir, |
| 495 | basePath: params.options.basePath, |
| 496 | }, |
| 497 | }); |
| 498 | const workspaces = Array.from(params.workspaces).map((workspace) => |
| 499 | path.relative(params.rootDir, path.resolve(params.rootDir, workspace)).replaceAll("\\", "/"), |
| 500 | ); |
| 501 | return { hash, workspaces }; |
| 502 | }); |
| 503 | |
| 504 | // ───────────────────────────────────────────────────────────────────────────── |
| 505 | // Client-asset reading (mirror of alchemy `Cloudflare/Workers/Assets.readAssets`) |
| 506 | // ───────────────────────────────────────────────────────────────────────────── |
| 507 | |
| 508 | const SPECIAL_ASSET_FILES = [".assetsignore", "_headers", "_redirects"]; |
| 509 | |
| 510 | const maybeReadString = Effect.fn(function* (file: string) { |
| 511 | const fs = yield* FileSystem.FileSystem; |
| 512 | return yield* fs.readFileString(file).pipe( |
| 513 | Effect.catchIf( |
| 514 | (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound", |
| 515 | () => Effect.undefined, |
| 516 | ), |
| 517 | ); |
| 518 | }); |
| 519 | |
| 520 | /** |
| 521 | * Read the client output directory into the manifest shape alchemy's |
| 522 | * `putWorker`/`uploadAssets` consume: per-file `sha256(content).slice(0, 32)` |
| 523 | * + byte size, keyed by `/`-prefixed posix path; the aggregate hash covers |
| 524 | * only upload-affecting inputs (manifest, config, `_headers`, `_redirects` — |
| 525 | * never the absolute directory path). |
| 526 | */ |
| 527 | const readClientAssets = Effect.fn(function* ( |
| 528 | directory: string, |
| 529 | config: Record<string, unknown> | undefined, |
| 530 | ) { |
| 531 | const fs = yield* FileSystem.FileSystem; |
| 532 | const path = yield* Path.Path; |
| 533 | const [entries, ignoreFile, _headers, _redirects] = yield* Effect.all([ |
| 534 | fs.readDirectory(directory, { recursive: true }), |
| 535 | maybeReadString(path.join(directory, ".assetsignore")), |
| 536 | maybeReadString(path.join(directory, "_headers")), |
| 537 | maybeReadString(path.join(directory, "_redirects")), |
| 538 | ]); |
| 539 | const ignores = compileIgnoreRules([...SPECIAL_ASSET_FILES, ...(ignoreFile?.split("\n") ?? [])]); |
| 540 | const manifest = new Map<string, { hash: string; size: number }>(); |
| 541 | yield* Effect.forEach( |
| 542 | entries, |
| 543 | Effect.fn(function* (name) { |
| 544 | const relPath = name.replaceAll("\\", "/"); |
| 545 | if (matchesAny(ignores, relPath)) { |
| 546 | return; |
| 547 | } |
| 548 | const file = path.join(directory, name); |
| 549 | const stat = yield* fs.stat(file); |
| 550 | if (stat.type !== "File") { |
| 551 | return; |
| 552 | } |
| 553 | const content = yield* fs.readFile(file); |
| 554 | manifest.set(relPath.startsWith("/") ? relPath : `/${relPath}`, { |
| 555 | hash: sha256(content).slice(0, 32), |
| 556 | size: Number(stat.size), |
| 557 | }); |
| 558 | }), |
| 559 | { concurrency: 16 }, |
| 560 | ); |
| 561 | const sortedManifest = Object.fromEntries( |
| 562 | Array.from(manifest.entries()).sort((a, b) => a[0].localeCompare(b[0])), |
| 563 | ); |
| 564 | return { |
| 565 | directory, |
| 566 | config, |
| 567 | manifest: sortedManifest, |
| 568 | _headers, |
| 569 | _redirects, |
| 570 | hash: sha256Object({ |
| 571 | config, |
| 572 | manifest: sortedManifest, |
| 573 | _headers, |
| 574 | _redirects, |
| 575 | }), |
| 576 | } satisfies AssetReadResult; |
| 577 | }); |
| 578 | |
| 579 | // ───────────────────────────────────────────────────────────────────────────── |
| 580 | // The provider |
| 581 | // ───────────────────────────────────────────────────────────────────────────── |
| 582 | |
| 583 | const PROVIDER = "@alchemy.run/frontend-frameworks/waku/source"; |
| 584 | |
| 585 | export interface WakuLikeSourceIntegration { |
| 586 | readonly provider: string; |
| 587 | readonly framework: string; |
| 588 | readonly displayName: string; |
| 589 | readonly buildModule: string; |
| 590 | readonly layer: (options: { |
| 591 | root: string; |
| 592 | target: ReturnType<typeof makeWakuCloudflareTarget>; |
| 593 | }) => Layer.Layer<FrameworkCore.Framework, never, SourceRequirements>; |
| 594 | } |
| 595 | |
| 596 | /** |
| 597 | * Waku assumes `process.cwd()` is the project root in several places (the |
| 598 | * html-shell plugin's `index.html` input resolves against the cwd, and |
| 599 | * rolldown resolves relative inputs from the cwd), exactly like its CLI, |
| 600 | * which always runs from the project. |
| 601 | * |
| 602 | * The production **build** therefore runs in a disposable child process |
| 603 | * whose working directory IS the project root (see `core/BuildChild.ts`) — |
| 604 | * no in-process `chdir`, no lock, unbounded build concurrency. The shared `core/BuildChildRunner` |
| 605 | * entry imports this module in the child and calls the exported |
| 606 | * {@link buildInChild}. |
| 607 | * |
| 608 | * The **dev server** cannot cross a process boundary (its inputs — |
| 609 | * `ctx.worker.bindings` hooks and `ctx.runtimeContext` — are live objects), |
| 610 | * so only its startup window still chdirs in-process, serialized through |
| 611 | * {@link cwdLock}; the cwd is restored as soon as the server is listening. |
| 612 | */ |
| 613 | const cwdLock = Semaphore.makeUnsafe(1); |
| 614 | |
| 615 | const withRootCwd = <A, E, R>( |
| 616 | rootDir: string, |
| 617 | effect: Effect.Effect<A, E, R>, |
| 618 | ): Effect.Effect<A, E, R> => |
| 619 | Semaphore.withPermits( |
| 620 | cwdLock, |
| 621 | 1, |
| 622 | )( |
| 623 | Effect.acquireUseRelease( |
| 624 | Effect.sync(() => { |
| 625 | const previous = process.cwd(); |
| 626 | process.chdir(rootDir); |
| 627 | return previous; |
| 628 | }), |
| 629 | () => effect, |
| 630 | (previous) => Effect.sync(() => process.chdir(previous)), |
| 631 | ), |
| 632 | ); |
| 633 | |
| 634 | /** JSON config the build child reconstructs the waku framework from. */ |
| 635 | export interface WakuBuildChildConfig { |
| 636 | readonly rootDir: string; |
| 637 | readonly compatibilityDate: string; |
| 638 | readonly compatibilityFlags: Array<string>; |
| 639 | readonly main: string | undefined; |
| 640 | readonly waku: { |
| 641 | readonly srcDir?: string; |
| 642 | readonly distDir?: string; |
| 643 | readonly basePath?: string; |
| 644 | }; |
| 645 | } |
| 646 | |
| 647 | export const buildInChild = (config: WakuBuildChildConfig) => |
| 648 | Effect.gen(function* () { |
| 649 | const waku = yield* FrameworkCore.Framework; |
| 650 | return yield* waku.build({ root: config.rootDir }); |
| 651 | }).pipe( |
| 652 | Effect.provide( |
| 653 | wakuFrameworkLayer({ |
| 654 | root: config.rootDir, |
| 655 | waku: config.waku, |
| 656 | target: makeWakuCloudflareTarget({ |
| 657 | compatibilityDate: config.compatibilityDate, |
| 658 | compatibilityFlags: config.compatibilityFlags, |
| 659 | ...(config.main !== undefined ? { main: config.main } : undefined), |
| 660 | }), |
| 661 | }), |
| 662 | ), |
| 663 | ); |
| 664 | |
| 665 | /** Routing config from the raw `props.assets` (directory/hash keys are |
| 666 | * path-level concerns owned by alchemy; only the routing config passes through). */ |
| 667 | const assetsConfigOf = (assets: unknown): Record<string, unknown> | undefined => { |
| 668 | if (assets === undefined || assets === null || typeof assets !== "object") { |
| 669 | return undefined; |
| 670 | } |
| 671 | const { directory: _directory, hash: _hash, ...config } = assets as Record<string, unknown>; |
| 672 | return Object.keys(config).length > 0 ? config : undefined; |
| 673 | }; |
| 674 | |
| 675 | export const makeWakuSourceProvider = ( |
| 676 | options: WakuSourceOptions, |
| 677 | integration: WakuLikeSourceIntegration = { |
| 678 | provider: PROVIDER, |
| 679 | framework: "waku", |
| 680 | displayName: "Waku", |
| 681 | buildModule: import.meta.url, |
| 682 | layer: ({ root, target }) => wakuFrameworkLayer({ root, waku: wakuConfigFor(options), target }), |
| 683 | }, |
| 684 | ): SourceProvider => { |
| 685 | const rootDirOf = (path: Path.Path): string => |
| 686 | options.rootDir !== undefined ? path.resolve(options.rootDir) : process.cwd(); |
| 687 | const distDir = options.distDir ?? "dist"; |
| 688 | const wakuConfig = wakuConfigFor(options); |
| 689 | |
| 690 | return { |
| 691 | // Waku's assets are a build product (`dist/public`), not a props-level |
| 692 | // directory — the provider reads and diffs them itself. |
| 693 | ownsAssets: true, |
| 694 | // Dev runs the Worker in workerd with the Vite plugin's assets service. |
| 695 | devAssetsBinding: true, |
| 696 | |
| 697 | build: Effect.fn(function* (ctx) { |
| 698 | const path = yield* Path.Path; |
| 699 | const rootDir = rootDirOf(path); |
| 700 | // The build runs in a child process with cwd = rootDir (waku resolves |
| 701 | // inputs relative to the cwd); `buildInChild` reconstructs the |
| 702 | // framework + cloudflare target from this JSON config on the far side. |
| 703 | const output = yield* runBuildChild({ |
| 704 | module: integration.buildModule, |
| 705 | rootDir, |
| 706 | framework: integration.framework, |
| 707 | env: resolveBuildEnv(ctx.env), |
| 708 | config: { |
| 709 | rootDir, |
| 710 | compatibilityDate: ctx.compatibility.date, |
| 711 | compatibilityFlags: ctx.compatibility.flags, |
| 712 | // The user-entry seam: surfaced as `DeployTarget.entry` and made |
| 713 | // the vite plugin's `main` (resolved against the root by |
| 714 | // `makeWakuPluginOptions`). |
| 715 | main: options.main, |
| 716 | waku: wakuConfig, |
| 717 | } satisfies WakuBuildChildConfig, |
| 718 | }).pipe( |
| 719 | Effect.mapError( |
| 720 | (error) => |
| 721 | new SourceProviderError({ |
| 722 | provider: integration.provider, |
| 723 | message: `${integration.displayName} build failed`, |
| 724 | cause: error.cause ?? error, |
| 725 | }), |
| 726 | ), |
| 727 | ); |
| 728 | |
| 729 | if (output.serverModules === undefined || output.serverModules.length === 0) { |
| 730 | return yield* new SourceProviderError({ |
| 731 | provider: integration.provider, |
| 732 | message: `${integration.displayName} build produced no server modules`, |
| 733 | }); |
| 734 | } |
| 735 | const [entry, ...rest] = output.serverModules; |
| 736 | const files: [BundleFile, ...Array<BundleFile>] = [entry!, ...rest].map((file) => ({ |
| 737 | path: file.name.replaceAll("\\", "/"), |
| 738 | content: file.content, |
| 739 | hash: file.hash, |
| 740 | })) as [BundleFile, ...Array<BundleFile>]; |
| 741 | const bundle: BundleOutput = { |
| 742 | files, |
| 743 | hash: sha256Object(files.map((file) => [file.path, file.hash])), |
| 744 | }; |
| 745 | |
| 746 | const [assets, input] = yield* Effect.all( |
| 747 | [ |
| 748 | output.clientDirectory !== undefined |
| 749 | ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx.assets)) |
| 750 | : Effect.undefined, |
| 751 | hashWakuInput({ |
| 752 | rootDir, |
| 753 | distDir, |
| 754 | memo: options.memo, |
| 755 | options, |
| 756 | workspaces: output.externalWorkspaces, |
| 757 | }), |
| 758 | ], |
| 759 | { concurrency: "unbounded" }, |
| 760 | ); |
| 761 | |
| 762 | return { |
| 763 | bundle, |
| 764 | assets, |
| 765 | hash: { |
| 766 | bundle: bundle.hash, |
| 767 | assets: assets?.hash, |
| 768 | input: input.hash, |
| 769 | additionalWorkspaces: input.workspaces, |
| 770 | }, |
| 771 | } satisfies SourceBuildOutput; |
| 772 | }), |
| 773 | |
| 774 | // Rebuild-free: re-hash the project tree (+ previously-discovered |
| 775 | // workspaces) — the same recipe as alchemy's vite source. `previous` is |
| 776 | // only used for the auxiliary workspace list, never to skip recomputation. |
| 777 | hash: Effect.fn(function* (_ctx, previous) { |
| 778 | const path = yield* Path.Path; |
| 779 | const rootDir = rootDirOf(path); |
| 780 | const input = yield* hashWakuInput({ |
| 781 | rootDir, |
| 782 | distDir, |
| 783 | memo: options.memo, |
| 784 | options, |
| 785 | workspaces: (previous?.additionalWorkspaces ?? []).map((workspace) => |
| 786 | path.resolve(rootDir, workspace), |
| 787 | ), |
| 788 | }); |
| 789 | return { input: input.hash, additionalWorkspaces: input.workspaces }; |
| 790 | }), |
| 791 | |
| 792 | // Waku dev is a vite dev server with the cloudflare plugin embedded in |
| 793 | // waku's own plugin stack (the rsc environment runs in workerd against |
| 794 | // the host-provided worker wiring) — a `server`-mode dev handle. |
| 795 | dev: Effect.fn(function* (ctx) { |
| 796 | const path = yield* Path.Path; |
| 797 | const rootDir = rootDirOf(path); |
| 798 | const queueConsumers = yield* ctx.worker.queueConsumers; |
| 799 | const framework = integration.layer({ |
| 800 | root: rootDir, |
| 801 | target: makeWakuCloudflareTarget({ |
| 802 | compatibilityDate: ctx.compatibility.date, |
| 803 | compatibilityFlags: ctx.compatibility.flags, |
| 804 | // Dev serves the wrapped user entry too, so DO classes exported |
| 805 | // from it exist in dev. |
| 806 | ...(options.main !== undefined ? { main: options.main } : undefined), |
| 807 | worker: { |
| 808 | ...ctx.worker.options, |
| 809 | name: ctx.workerName, |
| 810 | bindings: ctx.worker.bindings, |
| 811 | durableObjectNamespaces: ctx.worker.durableObjectNamespaces, |
| 812 | hyperdrives: ctx.worker.hyperdrives, |
| 813 | queueConsumers, |
| 814 | assets: ctx.worker.assets, |
| 815 | }, |
| 816 | context: ctx.runtimeContext, |
| 817 | }), |
| 818 | }); |
| 819 | // The dev server *starts* under the project cwd (waku resolves its |
| 820 | // html shell and relative inputs from the cwd at startup); the cwd is |
| 821 | // restored once the server is listening. |
| 822 | const server = yield* withRootCwd( |
| 823 | rootDir, |
| 824 | Effect.gen(function* () { |
| 825 | const waku = yield* FrameworkCore.Framework; |
| 826 | return yield* waku.dev({ root: rootDir }); |
| 827 | }).pipe( |
| 828 | Effect.provide(framework), |
| 829 | Effect.mapError( |
| 830 | (cause) => |
| 831 | new SourceProviderError({ |
| 832 | provider: integration.provider, |
| 833 | message: `Failed to start the ${integration.framework} dev server`, |
| 834 | cause, |
| 835 | }), |
| 836 | ), |
| 837 | ), |
| 838 | ); |
| 839 | return { |
| 840 | mode: "server", |
| 841 | url: new URL(server.url), |
| 842 | } satisfies ServerDevHandle; |
| 843 | }), |
| 844 | }; |
| 845 | }; |
| 846 | |
| 847 | /** |
| 848 | * The dynamic-module contract alchemy's `loadSource` expects: the default |
| 849 | * export's `make(options)` builds a `SourceProvider` from the descriptor's |
| 850 | * JSON-serializable options. |
| 851 | */ |
| 852 | const sourceModule = { |
| 853 | make: (options: unknown): Effect.Effect<SourceProvider, SourceProviderError> => { |
| 854 | if (options !== undefined && (typeof options !== "object" || options === null)) { |
| 855 | return Effect.fail( |
| 856 | new SourceProviderError({ |
| 857 | provider: PROVIDER, |
| 858 | message: `Invalid options for ${PROVIDER}: expected an object, got ${typeof options}`, |
| 859 | }), |
| 860 | ); |
| 861 | } |
| 862 | return Effect.succeed(makeWakuSourceProvider((options ?? {}) as WakuSourceOptions)); |
| 863 | }, |
| 864 | }; |
| 865 | |
| 866 | export default sourceModule; |