From 2e2d783134fe85f6d07d9bdbfe88723ef1a2d65b Mon Sep 17 00:00:00 2001 From: Sam Goodwin Date: Thu, 9 Jul 2026 16:01:27 -0700 Subject: [PATCH 1/4] =?UTF-8?q?fix(cloudflare):=20beta.61=20integration=20?= =?UTF-8?q?bug=20reports=20=E2=80=94=20nodejs=5Fcompat=20default,=20Static?= =?UTF-8?q?Site=20Config=20env,=20vite=20main=20resolution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes from the create-better-t-stack integration reports: - default nodejs_compat now reaches external Workers (plain `export default { fetch }` entrypoints set isExternal, which excluded them from the default); gated on compatibility date >= 2024-09-23 so pinned old dates don't get the broken v1 mode - precreate placeholder spread getCompatibility() as date/flags — wrong metadata keys, so the stub uploaded with no compatibility date or flags - StaticSite serializeEnv resolves Config/Effect env values instead of JSON.stringifying them into the build subprocess ({"_id":"Config"}); Outputs pass through for the engine to resolve - relative vite.main resolves from rootDir (the rolldown plugin resolves the worker entry with no importer, so it resolved against process.cwd()) - memo include globs escaping cwd are documented + absolute matches normalized to cwd-relative so machine paths never leak into the hash - alchemy logs explains the missing workers_observability:read scope on Unauthorized instead of surfacing the bare tag Co-Authored-By: Claude Fable 5 --- packages/alchemy/src/Cloudflare/Logs.ts | 86 +++++++++++++------ .../src/Cloudflare/Website/StaticSite.ts | 84 +++++++++++++++--- .../alchemy/src/Cloudflare/Website/Vite.ts | 50 +++++++---- .../src/Cloudflare/Workers/Compatibility.ts | 18 +++- .../Cloudflare/Workers/LocalWorkerProvider.ts | 6 +- .../src/Cloudflare/Workers/WorkerProvider.ts | 19 +++- packages/alchemy/src/Command/Memo.ts | 15 +++- packages/alchemy/test/Command/Build.test.ts | 50 +++++++++++ 8 files changed, 262 insertions(+), 66 deletions(-) diff --git a/packages/alchemy/src/Cloudflare/Logs.ts b/packages/alchemy/src/Cloudflare/Logs.ts index ff35c53ee3c..909dff9c916 100644 --- a/packages/alchemy/src/Cloudflare/Logs.ts +++ b/packages/alchemy/src/Cloudflare/Logs.ts @@ -78,6 +78,30 @@ export const CloudflareLogs = Effect.gen(function* () { const createScriptTail = yield* workers.createScriptTail; const deleteScriptTail = yield* workers.deleteScriptTail; + /** + * The telemetry query needs the `workers_observability:read` OAuth scope. + * A token minted by an older `alchemy login` (before the scope joined the + * defaults) keeps its original grants forever, so the query fails with a + * bare `Unauthorized`/`Forbidden` even though a fresh login would work — + * explain the fix instead of surfacing the raw tag. + */ + const explainMissingObservabilityScope = ( + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.catchTag("Unauthorized", () => + Effect.die( + new Error( + "Cloudflare rejected the observability telemetry query (Unauthorized). " + + 'Your stored credentials are likely missing the "workers_observability:read" scope — ' + + "OAuth tokens keep the scopes they were minted with, so tokens from an older " + + "`alchemy login` won't have it. Run `alchemy login` again to mint a token with " + + "the current default scopes, or use an API token that grants Workers Observability read access.", + ), + ), + ), + ); + const queryLogs = (opts: { accountId: string; filters: TelemetryFilter[]; @@ -88,30 +112,34 @@ export const CloudflareLogs = Effect.gen(function* () { const limit = opts.options.limit ?? 100; if (opts.options.since) { - const response = yield* queryTelemetry({ + const response = yield* explainMissingObservabilityScope( + queryTelemetry({ + accountId: opts.accountId, + queryId: "events", + view: "events", + timeframe: { from: opts.options.since.getTime(), to: now }, + limit, + parameters: { + filters: opts.filters, + // orderBy: { value: "timestamp", order: "desc" }, + }, + }), + ); + return parseEvents(response); + } + + const response = yield* explainMissingObservabilityScope( + queryTelemetry({ accountId: opts.accountId, queryId: "events", view: "events", - timeframe: { from: opts.options.since.getTime(), to: now }, + timeframe: { from: now - DEFAULT_LOOKBACK_MS, to: now }, limit, parameters: { filters: opts.filters, - // orderBy: { value: "timestamp", order: "desc" }, }, - }); - return parseEvents(response); - } - - const response = yield* queryTelemetry({ - accountId: opts.accountId, - queryId: "events", - view: "events", - timeframe: { from: now - DEFAULT_LOOKBACK_MS, to: now }, - limit, - parameters: { - filters: opts.filters, - }, - }); + }), + ); return parseEvents(response); }); @@ -207,17 +235,19 @@ export const CloudflareLogs = Effect.gen(function* () { yield* Effect.sleep("2 seconds"); const now = Date.now(); - const response = yield* queryTelemetry({ - accountId: opts.accountId, - queryId: "events", - view: "events", - timeframe: { from: since, to: now }, - limit: 100, - parameters: { - filters: opts.filters, - orderBy: { value: "timestamp", order: "asc" }, - }, - }); + const response = yield* explainMissingObservabilityScope( + queryTelemetry({ + accountId: opts.accountId, + queryId: "events", + view: "events", + timeframe: { from: since, to: now }, + limit: 100, + parameters: { + filters: opts.filters, + orderBy: { value: "timestamp", order: "asc" }, + }, + }), + ); const lines = parseEvents(response); const nextSince = diff --git a/packages/alchemy/src/Cloudflare/Website/StaticSite.ts b/packages/alchemy/src/Cloudflare/Website/StaticSite.ts index 002fabad41d..1dbcfec3034 100644 --- a/packages/alchemy/src/Cloudflare/Website/StaticSite.ts +++ b/packages/alchemy/src/Cloudflare/Website/StaticSite.ts @@ -6,7 +6,11 @@ import * as Command from "../../Command/index.ts"; import type { Input, InputProps } from "../../Input.ts"; import * as Namespace from "../../Namespace.ts"; import * as Output from "../../Output.ts"; -import { effectClass } from "../../Util/effect.ts"; +import { + effectClass, + isYieldableEffectLike, + type YieldableEffectLike, +} from "../../Util/effect.ts"; import { asEffect } from "../../Util/types.ts"; import type { Providers } from "../Providers.ts"; import type { AssetsConfig } from "../Workers/Assets.ts"; @@ -167,6 +171,23 @@ type StaticSiteWorker = Worker<{ * }); * ``` * + * @example Rebuilding when a sibling workspace package changes + * The default scope only hashes files under `cwd` (plus the nearest + * lockfile), so edits to a sibling workspace package the app imports do + * not retrigger the build on their own. Add the sibling's sources with a + * `../` include glob: + * ```typescript + * const site = yield* Cloudflare.Website.StaticSite("Web", { + * cwd: "apps/web", + * command: "npm run build", + * outdir: "dist", + * main: "./src/worker.ts", + * memo: { + * include: ["**\/*", "../../packages/env/src/**"], + * }, + * }); + * ``` + * * @section Class Form * Calling `StaticSite` with no arguments returns a constructor you can * `extend` to declare the Worker as a named class. The class is both @@ -233,7 +254,7 @@ const makeStaticSite = < cwd: props.dev.cwd ?? (typeof props.cwd === "string" ? props.cwd : undefined), - env: serializeEnv(props.dev.env ?? props.env), + env: yield* serializeEnv(props.dev.env ?? props.env), }).pipe( Effect.map((d) => Output.map(d.url, (url) => ({ @@ -250,7 +271,7 @@ const makeStaticSite = < cwd: props.cwd, memo: props.memo, outdir: props.outdir, - env: serializeEnv(props.env), + env: yield* serializeEnv(props.env), }); // Pure-static sites don't need a custom Worker entrypoint — @@ -278,17 +299,56 @@ const makeStaticSite = < }); }).pipe(Namespace.push(id)); -const serializeEnv = ( +/** + * Serialize the site's `env` for the build/dev subprocess. The same record + * doubles as the Worker's binding props, so entries may be plain strings, + * `Redacted` secrets, `effect/Config` values, `Output` references, or + * binding Effects: + * + * - strings and `Redacted` values pass through unchanged + * - `Config` (and any other runnable Effect) is resolved here, at stack + * construction — passing it through unresolved would hand the subprocess + * the JSON-serialized `Config` object (`{"_id":"Config"}`) instead of its + * value (#796) + * - `Output` references pass through raw; `Command.Build`/`Command.Dev` + * declare `env` as plain strings so the engine resolves them at reconcile + * - binding Effects (`~alchemy/Kind`-marked, e.g. a `WorkerLoader`) have no + * env-var representation and are dropped + * - remaining plain values (numbers, JSON objects) are stringified + */ +const serializeEnv = Effect.fn(function* ( env: Input< | WorkerBindingProps | Record> | undefined >, -) => - Object.fromEntries( - Object.entries(env ?? {}).flatMap(([k, v]) => { - if (v === undefined) return []; - if (typeof v === "string" || Redacted.isRedacted(v)) return [[k, v]]; - return [[k, JSON.stringify(v)]]; - }), - ); +) { + const entries: [string, unknown][] = []; + for (const [k, v] of Object.entries(env ?? {})) { + if (v === undefined) continue; + if (typeof v === "string" || Redacted.isRedacted(v) || Output.isOutput(v)) { + entries.push([k, v]); + } else if (isYieldableEffectLike(v)) { + const resolved = yield* asEffect( + v as YieldableEffectLike, + ).pipe(Effect.orDie); + if (resolved === undefined) continue; + entries.push([ + k, + typeof resolved === "string" || Redacted.isRedacted(resolved) + ? resolved + : JSON.stringify(resolved), + ]); + } else if (typeof v === "object" && "~alchemy/Kind" in (v as object)) { + // A binding Effect (e.g. WorkerLoader) — deploy-time only, nothing to + // expose to the build subprocess. + continue; + } else { + entries.push([k, JSON.stringify(v)]); + } + } + return Object.fromEntries(entries) as Record< + string, + string | Redacted.Redacted + >; +}); diff --git a/packages/alchemy/src/Cloudflare/Website/Vite.ts b/packages/alchemy/src/Cloudflare/Website/Vite.ts index d980c527301..f336f3530ba 100644 --- a/packages/alchemy/src/Cloudflare/Website/Vite.ts +++ b/packages/alchemy/src/Cloudflare/Website/Vite.ts @@ -47,28 +47,34 @@ export interface ViteProps * ``` * * @section SSR Frameworks - * For SSR frameworks like TanStack Start or SolidStart, enable - * `nodejs_compat` so the server bundle can use Node.js APIs. + * SSR frameworks like TanStack Start or SolidStart work with a single + * call — the `nodejs_compat` compatibility flag is enabled by default + * so the server bundle can use Node.js APIs. * * @example TanStack Start * ```typescript - * const app = yield* Cloudflare.Website.Vite("TanStackStart", { - * compatibility: { - * flags: ["nodejs_compat"], - * }, - * }); + * const app = yield* Cloudflare.Website.Vite("TanStackStart"); * ``` * * @example SolidStart with worker-first routing * ```typescript * const app = yield* Cloudflare.Website.Vite("SolidStart", { - * compatibility: { - * flags: ["nodejs_compat"], - * }, * assets: { runWorkerFirst: true }, * }); * ``` * + * @example React Router + * React Router's server build (`virtual:react-router/server-build`) is a + * build manifest with no default export, so it cannot be deployed as the + * Worker entry directly. Point `main` at a module that wraps it with + * `createRequestHandler` (React Router's Cloudflare template ships this + * as `workers/app.ts`): + * ```typescript + * const app = yield* Cloudflare.Website.Vite("ReactRouter", { + * main: "workers/app.ts", + * }); + * ``` + * * @section React Server Components * Frameworks that emit more than one server environment (e.g. React * Server Components, which split into an `rsc` environment and an `ssr` @@ -80,9 +86,6 @@ export interface ViteProps * @example React Router with RSC * ```typescript * const app = yield* Cloudflare.Website.Vite("ReactRouterRSC", { - * compatibility: { - * flags: ["nodejs_compat"], - * }, * viteEnvironments: { * entry: "rsc", * children: ["ssr"], @@ -116,9 +119,6 @@ export interface ViteProps * @example Vue SPA * ```typescript * const app = yield* Cloudflare.Website.Vite("Vue", { - * compatibility: { - * flags: ["nodejs_compat"], - * }, * assets: { * htmlHandling: "auto-trailing-slash", * notFoundHandling: "single-page-application", @@ -140,6 +140,20 @@ export interface ViteProps * }); * ``` * + * @example Rebuilding when a sibling workspace package changes + * The default scope only hashes files under the project root (plus the + * nearest lockfile), so edits to a sibling workspace package the app + * imports do not retrigger the build on their own. Add the sibling's + * sources with a `../` include glob: + * ```typescript + * const site = yield* Cloudflare.Website.Vite("Web", { + * rootDir: "apps/web", + * memo: { + * include: ["**\/*", "../../packages/env/src/**"], + * }, + * }); + * ``` + * * @section Class Form * Calling `Vite` with no arguments returns a constructor you can * `extend` to declare the Worker as a named class. The class is both @@ -148,9 +162,7 @@ export interface ViteProps * * @example Declaring a Worker class * ```typescript - * class Website extends Cloudflare.Website.Vite()("Website", { - * compatibility: { flags: ["nodejs_compat"] }, - * }) {} + * class Website extends Cloudflare.Website.Vite()("Website") {} * * const site = yield* Website; * ``` diff --git a/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts b/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts index b46c44b9dc8..f1c66ad9f1c 100644 --- a/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts +++ b/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts @@ -23,6 +23,13 @@ const CROSS_REQUEST_PROMISE_RESOLUTION = // need to be specified anymore"), so it is only appended for older dates. const CROSS_REQUEST_PROMISE_RESOLUTION_DEFAULT_ON = "2024-10-14"; +// The compatibility date from which `nodejs_compat` selects the full (v2) +// Node.js compatibility mode. Older dates get the legacy v1 mode, which +// lacks APIs the build-side unenv transform relies on (e.g. +// `process.getBuiltinModule`) — deploying that combination fails at script +// startup, so the default flag is only applied from this date onward. +const NODEJS_COMPAT_V2_DATE = "2024-09-23"; + export const getCompatibility = (props: WorkerProps) => { const userFlags = props.compatibility?.flags ?? []; if ( @@ -41,11 +48,18 @@ export const getCompatibility = (props: WorkerProps) => { date, flags: [ ...userFlags, + // Every Worker gets `nodejs_compat` by default — Effect-native Workers + // need it for the bundled Effect runtime, and external Workers (plain + // `export default { fetch }` entrypoints, vite builds) routinely import + // `node:*` built-ins. Without it the bundle uploads fine but Cloudflare + // rejects the script with `No such module "node:crypto"` (#796). ...(props.isExternal - ? [] + ? // ISO dates compare lexically. + date >= NODEJS_COMPAT_V2_DATE + ? ["nodejs_compat"] + : [] : [ "nodejs_compat", - // ISO dates compare lexically. ...(date < CROSS_REQUEST_PROMISE_RESOLUTION_DEFAULT_ON ? [CROSS_REQUEST_PROMISE_RESOLUTION] : []), diff --git a/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts b/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts index 09a68a858a9..1f22b6dd646 100644 --- a/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts +++ b/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts @@ -329,7 +329,11 @@ export const LocalWorkerProvider = () => compatibility, workerBindings, durableObjectNamespaces: Object.values(durableObjectNamespaces), - viteMain: props.vite?.main, + // Relative `vite.main` resolves from the Vite root (see the + // matching normalization in WorkerProvider's `viteBuild`). + viteMain: props.vite?.main + ? path.resolve(props.vite.rootDir ?? process.cwd(), props.vite.main) + : undefined, viteEnvironments: props.vite?.viteEnvironments, hyperdrives, env: props.env, diff --git a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts index 9c48aef1fc6..1eb6f1212ed 100644 --- a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts +++ b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts @@ -1055,7 +1055,17 @@ export const LiveWorkerProvider = () => )).filter(([_, value]) => value !== undefined), ), { - main: props.vite?.main, + // A relative `vite.main` is documented to resolve from the Vite + // root. The rolldown plugin resolves the worker entry with no + // importer (i.e. against `process.cwd()`), which breaks when the + // deploy runs from a different directory (e.g. a monorepo infra + // package) — absolutize before handing it over (#796). + main: props.vite?.main + ? path.resolve( + props.vite.rootDir ?? process.cwd(), + props.vite.main, + ) + : undefined, compatibilityDate: compatibility.date, compatibilityFlags: compatibility.flags, viteEnvironments: props.vite?.viteEnvironments, @@ -2074,6 +2084,7 @@ export const LiveWorkerProvider = () => ); } else { yield* session.note("Pre-creating worker..."); + const compatibility = getCompatibility(news); const mainModule = "main.js"; const placeholderScript = `${doClasses.length > 0 ? 'import { DurableObject } from "cloudflare:workers";\n\n' : ""}export default { fetch() { return new Response("Alchemy worker is being deployed...") } };\n${doClasses .map( @@ -2095,7 +2106,11 @@ export const LiveWorkerProvider = () => className, })) : undefined, - ...getCompatibility(news), + // Spreading `getCompatibility` here would set `date`/`flags`, + // which are not metadata keys — the placeholder would upload + // with no compatibility date or flags at all. + compatibilityDate: compatibility.date, + compatibilityFlags: compatibility.flags, containers, migrations: doClasses.length > 0 diff --git a/packages/alchemy/src/Command/Memo.ts b/packages/alchemy/src/Command/Memo.ts index c94dff08de0..4112651f0d7 100644 --- a/packages/alchemy/src/Command/Memo.ts +++ b/packages/alchemy/src/Command/Memo.ts @@ -16,10 +16,14 @@ import { sha256, sha256Object } from "../Util/sha256.ts"; */ export interface MemoOptions { /** - * Glob patterns of files to hash. Paths are relative to the working directory. + * Glob patterns of files to hash. Paths are relative to the working + * directory and may reach outside it with `../` segments — useful in a + * monorepo where the build consumes sibling workspace packages that the + * default (files under the working directory) does not cover. * * @default ["**\/*"] (all files, filtered by `exclude`) * @example ["src/**", "package.json", "tsconfig.json"] + * @example ["**\/*", "../env/src/**"] (also rebuild when a sibling workspace package changes) */ include?: string[]; /** @@ -141,7 +145,14 @@ const Memo = Effect.gen(function* () { if (lockfile && !files.includes(lockfile)) { files.push(lockfile); } - return files.sort(); + // Absolute include patterns produce absolute matches; normalize them to + // cwd-relative (like the lockfile above) so `hashFiles` resolves them + // correctly and machine-specific path prefixes never leak into the hash. + return files + .map((file) => + path.isAbsolute(file) ? path.relative(options.cwd, file) : file, + ) + .sort(); }); const hashFiles = Effect.fn(function* ( diff --git a/packages/alchemy/test/Command/Build.test.ts b/packages/alchemy/test/Command/Build.test.ts index ffb2914b7f2..a2930577698 100644 --- a/packages/alchemy/test/Command/Build.test.ts +++ b/packages/alchemy/test/Command/Build.test.ts @@ -165,3 +165,53 @@ test.provider("rebuilds memoized output if outdir is missing", (stack) => yield* stack.destroy(); }), ); + +test.provider( + "memo include globs can reach outside cwd (monorepo workspace deps)", + (stack) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + + yield* stack.destroy(); + + // A monorepo shape: the app builds from `app/` and imports a sibling + // workspace package at `packages/env/` that the default memo scope + // (files under `cwd`) does not cover. + const tempDir = yield* fs.makeTempDirectoryScoped(); + const appDir = pathe.join(tempDir, "app"); + const siblingDir = pathe.join(tempDir, "packages", "env"); + yield* fs.copy(FIXTURE_DIR, appDir); + yield* fs.makeDirectory(siblingDir, { recursive: true }); + const siblingFile = pathe.join(siblingDir, "value.ts"); + yield* fs.writeFileString(siblingFile, 'export const value = "a";\n'); + + const outputFile = pathe.join(appDir, "dist", "output.txt"); + const deploy = () => + stack.deploy( + Command.Build("test-build", { + command: "bash build.sh", + cwd: appDir, + outdir: "dist", + memo: { include: ["**/*", "../packages/env/**"] }, + }), + ); + + const build1 = yield* deploy(); + const firstOutput = yield* fs.readFileString(outputFile); + + // Nothing changed (including the sibling): the build memoizes. + yield* Effect.sleep(1100); + const build2 = yield* deploy(); + expect(build2.hash).toMatchObject(build1.hash); + expect(yield* fs.readFileString(outputFile)).toBe(firstOutput); + + // Editing only the sibling package busts the input hash and rebuilds. + yield* fs.writeFileString(siblingFile, 'export const value = "b";\n'); + const build3 = yield* deploy(); + expect(build3.hash.input).not.toBe(build1.hash.input); + expect(yield* fs.readFileString(outputFile)).not.toBe(firstOutput); + + yield* stack.destroy(); + }), + { timeout: 60000 }, +); From 5067066afb9b94788f5f010e09f948ae252a23fe Mon Sep 17 00:00:00 2001 From: Sam Goodwin Date: Fri, 10 Jul 2026 09:27:33 -0700 Subject: [PATCH 2/4] fix(cloudflare): address review audit of #796 - serializeEnv: null no longer throws on the ~alchemy/Kind probe; Output values are serialized after resolution via Output.map so Output reaches the build subprocess as JSON, not [object Object] - getCompatibility: an explicit no_nodejs_compat opts out of the default nodejs_compat instead of sending Cloudflare a contradictory flag pair - memo monorepo examples pair ../ include globs with lockfile: true (include flips the lockfile default off) and MemoOptions documents the interaction - add a StaticSite regression test covering Config, Output, Output, and null env values reaching the build env (verified it fails against the previous serializer) Co-Authored-By: Claude Fable 5 --- .../src/Cloudflare/Website/StaticSite.ts | 47 +++++++--- .../alchemy/src/Cloudflare/Website/Vite.ts | 4 +- .../src/Cloudflare/Workers/Compatibility.ts | 25 +++-- packages/alchemy/src/Command/Memo.ts | 4 + .../Cloudflare/Website/StaticSite.test.ts | 92 +++++++++++++++++++ 5 files changed, 146 insertions(+), 26 deletions(-) diff --git a/packages/alchemy/src/Cloudflare/Website/StaticSite.ts b/packages/alchemy/src/Cloudflare/Website/StaticSite.ts index 1dbcfec3034..4d94184d03a 100644 --- a/packages/alchemy/src/Cloudflare/Website/StaticSite.ts +++ b/packages/alchemy/src/Cloudflare/Website/StaticSite.ts @@ -175,7 +175,8 @@ type StaticSiteWorker = Worker<{ * The default scope only hashes files under `cwd` (plus the nearest * lockfile), so edits to a sibling workspace package the app imports do * not retrigger the build on their own. Add the sibling's sources with a - * `../` include glob: + * `../` include glob — and keep `lockfile: true`, since providing + * `include` otherwise drops the lockfile from the hash: * ```typescript * const site = yield* Cloudflare.Website.StaticSite("Web", { * cwd: "apps/web", @@ -184,6 +185,7 @@ type StaticSiteWorker = Worker<{ * main: "./src/worker.ts", * memo: { * include: ["**\/*", "../../packages/env/src/**"], + * lockfile: true, * }, * }); * ``` @@ -310,11 +312,12 @@ const makeStaticSite = < * construction — passing it through unresolved would hand the subprocess * the JSON-serialized `Config` object (`{"_id":"Config"}`) instead of its * value (#796) - * - `Output` references pass through raw; `Command.Build`/`Command.Dev` - * declare `env` as plain strings so the engine resolves them at reconcile + * - `Output` references resolve at reconcile; the resolved value is + * serialized the same way inline values are (an `Output` must + * reach the subprocess as JSON, not `[object Object]`) * - binding Effects (`~alchemy/Kind`-marked, e.g. a `WorkerLoader`) have no * env-var representation and are dropped - * - remaining plain values (numbers, JSON objects) are stringified + * - remaining plain values (`null`, numbers, JSON objects) are stringified */ const serializeEnv = Effect.fn(function* ( env: Input< @@ -326,20 +329,19 @@ const serializeEnv = Effect.fn(function* ( const entries: [string, unknown][] = []; for (const [k, v] of Object.entries(env ?? {})) { if (v === undefined) continue; - if (typeof v === "string" || Redacted.isRedacted(v) || Output.isOutput(v)) { + if (typeof v === "string" || Redacted.isRedacted(v)) { entries.push([k, v]); + } else if (Output.isOutput(v)) { + entries.push([k, Output.map(v, serializeEnvValue)]); } else if (isYieldableEffectLike(v)) { - const resolved = yield* asEffect( - v as YieldableEffectLike, - ).pipe(Effect.orDie); + const resolved = serializeEnvValue( + yield* asEffect(v as YieldableEffectLike).pipe( + Effect.orDie, + ), + ); if (resolved === undefined) continue; - entries.push([ - k, - typeof resolved === "string" || Redacted.isRedacted(resolved) - ? resolved - : JSON.stringify(resolved), - ]); - } else if (typeof v === "object" && "~alchemy/Kind" in (v as object)) { + entries.push([k, resolved]); + } else if (v !== null && typeof v === "object" && "~alchemy/Kind" in v) { // A binding Effect (e.g. WorkerLoader) — deploy-time only, nothing to // expose to the build subprocess. continue; @@ -352,3 +354,18 @@ const serializeEnv = Effect.fn(function* ( string | Redacted.Redacted >; }); + +/** + * Serialize one resolved env value for the build/dev subprocess: strings and + * `Redacted` pass through, everything else becomes JSON. + */ +const serializeEnvValue = ( + value: unknown, +): string | Redacted.Redacted | undefined => + value === undefined + ? undefined + : typeof value === "string" + ? value + : Redacted.isRedacted(value) + ? (value as Redacted.Redacted) + : JSON.stringify(value); diff --git a/packages/alchemy/src/Cloudflare/Website/Vite.ts b/packages/alchemy/src/Cloudflare/Website/Vite.ts index f336f3530ba..f09ef18e029 100644 --- a/packages/alchemy/src/Cloudflare/Website/Vite.ts +++ b/packages/alchemy/src/Cloudflare/Website/Vite.ts @@ -144,12 +144,14 @@ export interface ViteProps * The default scope only hashes files under the project root (plus the * nearest lockfile), so edits to a sibling workspace package the app * imports do not retrigger the build on their own. Add the sibling's - * sources with a `../` include glob: + * sources with a `../` include glob — and keep `lockfile: true`, since + * providing `include` otherwise drops the lockfile from the hash: * ```typescript * const site = yield* Cloudflare.Website.Vite("Web", { * rootDir: "apps/web", * memo: { * include: ["**\/*", "../../packages/env/src/**"], + * lockfile: true, * }, * }); * ``` diff --git a/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts b/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts index f1c66ad9f1c..c462b616e5f 100644 --- a/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts +++ b/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts @@ -53,17 +53,22 @@ export const getCompatibility = (props: WorkerProps) => { // `export default { fetch }` entrypoints, vite builds) routinely import // `node:*` built-ins. Without it the bundle uploads fine but Cloudflare // rejects the script with `No such module "node:crypto"` (#796). + // An explicit `no_nodejs_compat` opts out of the default — appending + // `nodejs_compat` alongside it would send Cloudflare a contradictory + // flag pair. + ...(userFlags.includes("no_nodejs_compat") + ? [] + : props.isExternal + ? // ISO dates compare lexically. + date >= NODEJS_COMPAT_V2_DATE + ? ["nodejs_compat"] + : [] + : ["nodejs_compat"]), ...(props.isExternal - ? // ISO dates compare lexically. - date >= NODEJS_COMPAT_V2_DATE - ? ["nodejs_compat"] - : [] - : [ - "nodejs_compat", - ...(date < CROSS_REQUEST_PROMISE_RESOLUTION_DEFAULT_ON - ? [CROSS_REQUEST_PROMISE_RESOLUTION] - : []), - ]), + ? [] + : date < CROSS_REQUEST_PROMISE_RESOLUTION_DEFAULT_ON + ? [CROSS_REQUEST_PROMISE_RESOLUTION] + : []), ].filter((value, index, self) => self.indexOf(value) === index), }; }; diff --git a/packages/alchemy/src/Command/Memo.ts b/packages/alchemy/src/Command/Memo.ts index 4112651f0d7..3f2cc55fa6a 100644 --- a/packages/alchemy/src/Command/Memo.ts +++ b/packages/alchemy/src/Command/Memo.ts @@ -21,6 +21,10 @@ export interface MemoOptions { * monorepo where the build consumes sibling workspace packages that the * default (files under the working directory) does not cover. * + * Note: providing `include` (or `exclude`) flips the {@link lockfile} + * default to `false` — pair it with `lockfile: true` to keep rebuilding + * when dependencies change. + * * @default ["**\/*"] (all files, filtered by `exclude`) * @example ["src/**", "package.json", "tsconfig.json"] * @example ["**\/*", "../env/src/**"] (also rebuild when a sibling workspace package changes) diff --git a/packages/alchemy/test/Cloudflare/Website/StaticSite.test.ts b/packages/alchemy/test/Cloudflare/Website/StaticSite.test.ts index f16b83d051c..44f81318e98 100644 --- a/packages/alchemy/test/Cloudflare/Website/StaticSite.test.ts +++ b/packages/alchemy/test/Cloudflare/Website/StaticSite.test.ts @@ -1,9 +1,12 @@ import { CloudflareEnvironment } from "@/Cloudflare/CloudflareEnvironment"; import * as Cloudflare from "@/Cloudflare/index.ts"; +import * as Command from "@/Command/index.ts"; +import * as Output from "@/Output.ts"; import { Stack } from "@/Stack"; import { type ResourceState, State } from "@/State"; import * as Test from "@/Test/Vitest"; import { expect } from "@effect/vitest"; +import * as Config from "effect/Config"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -559,6 +562,95 @@ test.provider( { timeout: 360_000 }, ); +test.provider( + "StaticSite: build env resolves Config, Output, and JSON values (#796)", + (stack) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + yield* stack.destroy(); + + // A build that snapshots the env vars it receives into its output. + const cwd = yield* fs.makeTempDirectory({ + prefix: "alchemy-staticsite-env-", + }); + yield* fs.writeFileString( + path.join(cwd, "build.sh"), + [ + "#!/bin/bash", + "set -euo pipefail", + "mkdir -p dist", + "{", + ' echo "FROM_STRING=${FROM_STRING:-missing}"', + ' echo "FROM_CONFIG=${FROM_CONFIG:-missing}"', + ' echo "FROM_OUTPUT=${FROM_OUTPUT:-missing}"', + ' echo "FROM_OUTPUT_OBJECT=${FROM_OUTPUT_OBJECT:-missing}"', + ' echo "FROM_NULL=${FROM_NULL:-missing}"', + "} > dist/env.txt", + ].join("\n"), + ); + + // A sibling resource whose attributes provide real `Output` values. + const depCwd = yield* fs.makeTempDirectory({ + prefix: "alchemy-staticsite-env-dep-", + }); + yield* fs.writeFileString( + path.join(depCwd, "build.sh"), + "#!/bin/bash\nmkdir -p dist\necho dep > dist/dep.txt\n", + ); + + yield* Effect.sync(() => { + process.env.STATICSITE_ENV_TEST = "from-config"; + }); + + yield* stack.deploy( + Effect.gen(function* () { + const dep = yield* Command.Build("EnvDep", { + command: "bash build.sh", + shell: true, + cwd: depCwd, + outdir: "dist", + }); + return yield* Cloudflare.Website.StaticSite("EnvSite", { + command: "bash build.sh", + shell: true, + cwd, + outdir: "dist", + url: false, + env: { + FROM_STRING: "plain", + FROM_CONFIG: Config.string("STATICSITE_ENV_TEST"), + FROM_OUTPUT: dep.outdir, + FROM_OUTPUT_OBJECT: Output.map(dep.outdir, (dir) => ({ dir })), + // JS callers can pass `null`; it must serialize, not throw. + FROM_NULL: null as unknown as string, + }, + }); + }), + ); + + const envFile = yield* fs.readFileString( + path.join(cwd, "dist", "env.txt"), + ); + expect(envFile).toContain("FROM_STRING=plain"); + expect(envFile).toContain("FROM_CONFIG=from-config"); + // Resolved Output — the dep's outdir path, not garbage. + const fromOutput = envFile.match(/FROM_OUTPUT=(.*)/)?.[1]; + expect(fromOutput).toBeDefined(); + expect(fromOutput).not.toBe("missing"); + expect(fromOutput).toContain("dist"); + expect(fromOutput).not.toContain("[object"); + // Resolved Output — serialized as JSON. + const fromOutputObject = envFile.match(/FROM_OUTPUT_OBJECT=(.*)/)?.[1]; + expect(fromOutputObject).toContain('{"dir":'); + expect(envFile).toContain("FROM_NULL=null"); + + yield* stack.destroy(); + }).pipe(logLevel), + { timeout: 360_000 }, +); + const staticSiteProps = (cwd: string): Cloudflare.Website.StaticSiteProps => ({ command: "bash build.sh", shell: true, From 2113ee01276649cb3c1e8a93e7b38abcf7571092 Mon Sep 17 00:00:00 2001 From: Sam Goodwin Date: Tue, 28 Jul 2026 15:18:22 -0700 Subject: [PATCH 3/4] test(cloudflare): unit-test getCompatibility's nodejs_compat contract Covers the #796 default (Effect-native + external workers), the v2-date gate, the no_nodejs_compat opt-out, python_workers exclusion, and the cross-request-promise-resolution behavior. Co-Authored-By: Claude Fable 5 --- .../Cloudflare/Workers/Compatibility.test.ts | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 packages/alchemy/test/Cloudflare/Workers/Compatibility.test.ts diff --git a/packages/alchemy/test/Cloudflare/Workers/Compatibility.test.ts b/packages/alchemy/test/Cloudflare/Workers/Compatibility.test.ts new file mode 100644 index 00000000000..b836fd593f9 --- /dev/null +++ b/packages/alchemy/test/Cloudflare/Workers/Compatibility.test.ts @@ -0,0 +1,80 @@ +import { getCompatibility } from "@/Cloudflare/Workers/Compatibility"; +import type { WorkerProps } from "@/Cloudflare/Workers/Worker"; +import { describe, expect, test } from "alchemy-test"; + +describe("getCompatibility", () => { + // The default nodejs_compat contract from #796: every JS Worker gets the + // flag — Effect-native Workers need it for the bundled Effect runtime, + // external Workers (plain `export default { fetch }`, vite builds) + // routinely import `node:*` built-ins. + test("defaults nodejs_compat for Effect-native workers", () => { + const { flags } = getCompatibility({} as WorkerProps); + expect(flags).toContain("nodejs_compat"); + }); + + test("defaults nodejs_compat for external workers", () => { + const { flags } = getCompatibility({ isExternal: true } as WorkerProps); + expect(flags).toContain("nodejs_compat"); + }); + + test("does not duplicate an explicit nodejs_compat", () => { + const { flags } = getCompatibility({ + isExternal: true, + compatibility: { flags: ["nodejs_compat"] }, + } as WorkerProps); + expect(flags.filter((f) => f === "nodejs_compat")).toHaveLength(1); + }); + + // nodejs_compat with a date before 2024-09-23 selects the legacy v1 mode, + // which lacks `process.getBuiltinModule` — the build-side unenv transform + // emits code that needs it, so the deploy would fail at script startup. + test("skips the external-worker default for pre-v2 compatibility dates", () => { + const { flags } = getCompatibility({ + isExternal: true, + compatibility: { date: "2024-01-01" }, + } as WorkerProps); + expect(flags).not.toContain("nodejs_compat"); + }); + + test("applies the external-worker default from the v2 date onward", () => { + const { flags } = getCompatibility({ + isExternal: true, + compatibility: { date: "2024-09-23" }, + } as WorkerProps); + expect(flags).toContain("nodejs_compat"); + }); + + // An explicit no_nodejs_compat opts out — appending nodejs_compat + // alongside it would send Cloudflare a contradictory flag pair. + test("no_nodejs_compat opts out of the default", () => { + const { flags } = getCompatibility({ + isExternal: true, + compatibility: { flags: ["no_nodejs_compat"] }, + } as WorkerProps); + expect(flags).toContain("no_nodejs_compat"); + expect(flags).not.toContain("nodejs_compat"); + }); + + // Python Workers don't go through the JS bundler: they get the beta + // python_workers flag and no nodejs_compat default. + test("python workers get python_workers and no nodejs_compat default", () => { + const { flags } = getCompatibility({ + isExternal: true, + main: "./src/entry.py", + } as WorkerProps); + expect(flags).toContain("python_workers"); + expect(flags).not.toContain("nodejs_compat"); + }); + + test("forces handle_cross_request_promise_resolution for Effect workers on old dates", () => { + const { flags } = getCompatibility({ + compatibility: { date: "2024-10-01" }, + } as WorkerProps); + expect(flags).toContain("handle_cross_request_promise_resolution"); + }); + + test("omits handle_cross_request_promise_resolution once default-on", () => { + const { flags } = getCompatibility({} as WorkerProps); + expect(flags).not.toContain("handle_cross_request_promise_resolution"); + }); +}); From 55258a16ca20eb1780d5afab590537ad70481e2b Mon Sep 17 00:00:00 2001 From: Sam Goodwin Date: Tue, 28 Jul 2026 15:57:53 -0700 Subject: [PATCH 4/4] test(cloudflare): live regressions for nodejs_compat default and absolute memo globs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - deploy a plain worker importing node:crypto with no compatibility props — the end-to-end repro for the default-nodejs_compat fix - assert an absolute memo include glob hashes identically to its ../ form; this exposed fast-glob silently dropping absolute patterns when mixed with relative ones, fixed by rewriting absolute includes to cwd-relative in resolveMemoOptions Co-Authored-By: Claude Fable 5 --- packages/alchemy/src/Command/Memo.ts | 11 +++- .../test/Cloudflare/Workers/Worker.test.ts | 50 +++++++++++++++++++ packages/alchemy/test/Command/Build.test.ts | 16 ++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/packages/alchemy/src/Command/Memo.ts b/packages/alchemy/src/Command/Memo.ts index 3f2cc55fa6a..4acd5edcecb 100644 --- a/packages/alchemy/src/Command/Memo.ts +++ b/packages/alchemy/src/Command/Memo.ts @@ -106,7 +106,16 @@ const Memo = Effect.gen(function* () { const resolvedCwd = cwd ? path.resolve(cwd) : process.cwd(); return { cwd: resolvedCwd, - include: options.include ?? ["**/*"], + // Rewrite absolute include patterns to cwd-relative ones: fast-glob + // silently drops an absolute pattern's matches when the same call also + // contains relative patterns, and relative patterns keep the matched + // keys (and therefore the memo hash) free of machine-specific path + // prefixes. + include: (options.include ?? ["**/*"]).map((pattern) => + path.isAbsolute(pattern) + ? path.relative(resolvedCwd, pattern).replaceAll("\\", "/") + : pattern, + ), exclude: options.exclude ?? (yield* readGitIgnoreRules(resolvedCwd).pipe( diff --git a/packages/alchemy/test/Cloudflare/Workers/Worker.test.ts b/packages/alchemy/test/Cloudflare/Workers/Worker.test.ts index 0ad920c05c9..00448e957db 100644 --- a/packages/alchemy/test/Cloudflare/Workers/Worker.test.ts +++ b/packages/alchemy/test/Cloudflare/Workers/Worker.test.ts @@ -1518,4 +1518,54 @@ describe.concurrent("Cloudflare.Worker", () => { }).pipe(logLevel), { timeout: 360_000 }, ); + + test.provider( + "plain worker importing node builtins deploys without explicit compatibility flags", + (stack) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { accountId } = yield* yield* CloudflareEnvironment; + + yield* stack.destroy(); + + // Regression for #796: a plain (external) `export default { fetch }` + // Worker importing `node:crypto`, with NO `compatibility` prop. The + // default `nodejs_compat` must reach both the bundler (so `node:*` + // stays external instead of warning) and the upload metadata (so + // Cloudflare doesn't reject with `No such module "node:crypto"`). + const workerDir = yield* fs.makeTempDirectory({ + prefix: "alchemy-worker-node-compat-", + }); + const workerPath = path.join(workerDir, "worker.ts"); + yield* fs.writeFileString( + workerPath, + `import { randomBytes } from "node:crypto"; +export default { + fetch: async () => + new Response("node-compat:" + randomBytes(8).toString("hex")), +}; +`, + ); + + const worker = yield* stack.deploy( + Effect.gen(function* () { + return yield* Cloudflare.Worker("NodeCompatDefault", { + main: workerPath, + url: true, + subdomain: { enabled: true, previewsEnabled: true }, + }); + }), + ); + + yield* expectUrlContains(worker.url!, "node-compat:", { + timeout: "60 seconds", + label: "node:crypto served under default nodejs_compat", + }); + + yield* stack.destroy(); + yield* waitForWorkerToBeDeleted(worker.workerName, accountId); + }).pipe(logLevel), + { timeout: 360_000 }, + ); }); diff --git a/packages/alchemy/test/Command/Build.test.ts b/packages/alchemy/test/Command/Build.test.ts index bd12674c3ee..512b210ad21 100644 --- a/packages/alchemy/test/Command/Build.test.ts +++ b/packages/alchemy/test/Command/Build.test.ts @@ -211,6 +211,22 @@ test.provider( expect(build3.hash.input).not.toBe(build1.hash.input); expect(yield* fs.readFileString(outputFile)).not.toBe(firstOutput); + // An *absolute* include glob matches the same files: its matches are + // normalized back to cwd-relative keys, so the input hash is identical + // to the `../` form — machine-specific path prefixes never leak into + // the hash (and the build memoizes instead of rerunning). + const build4 = yield* stack.deploy( + Command.Build("test-build", { + command: "bash build.sh", + cwd: appDir, + outdir: "dist", + memo: { + include: ["**/*", pathe.join(siblingDir, "**")], + }, + }), + ); + expect(build4.hash.input).toBe(build3.hash.input); + yield* stack.destroy(); }), { timeout: 60000 },