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