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 5321c866c02..c7efa7f3000 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"; @@ -175,6 +179,25 @@ 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 — 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", + * command: "npm run build", + * outdir: "dist", + * main: "./src/worker.ts", + * memo: { + * include: ["**\/*", "../../packages/env/src/**"], + * lockfile: true, + * }, + * }); + * ``` + * * @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 @@ -241,7 +264,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) => ({ @@ -258,7 +281,7 @@ const makeStaticSite = < cwd: props.cwd, memo: props.memo, outdir: props.outdir, - env: serializeEnv(props.env), + env: yield* serializeEnv(props.env), }); // Pure-static sites (neither `main` nor `script`) deploy as @@ -281,17 +304,71 @@ 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 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 (`null`, 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)) { + entries.push([k, v]); + } else if (Output.isOutput(v)) { + entries.push([k, Output.map(v, serializeEnvValue)]); + } else if (isYieldableEffectLike(v)) { + const resolved = serializeEnvValue( + yield* asEffect(v as YieldableEffectLike).pipe( + Effect.orDie, + ), + ); + if (resolved === undefined) continue; + 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; + } else { + entries.push([k, JSON.stringify(v)]); + } + } + return Object.fromEntries(entries) as Record< + string, + 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 d980c527301..f09ef18e029 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,22 @@ 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 — 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, + * }, + * }); + * ``` + * * @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 +164,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 320cc589216..b14e855d275 100644 --- a/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts +++ b/packages/alchemy/src/Cloudflare/Workers/Compatibility.ts @@ -24,6 +24,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 ?? []; const python = isPythonMain(props.main); @@ -54,15 +61,28 @@ export const getCompatibility = (props: WorkerProps) => { // Required while Python Workers are in open beta — the upload API // rejects Python modules without it. ...(python ? ["python_workers"] : []), + // Every JS 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). Python Workers don't go through the JS bundler, so they get + // no default. An explicit `no_nodejs_compat` opts out — appending + // `nodejs_compat` alongside it would send Cloudflare a contradictory + // flag pair. + ...(python || userFlags.includes("no_nodejs_compat") + ? [] + : props.isExternal + ? // ISO dates compare lexically. + date >= NODEJS_COMPAT_V2_DATE + ? ["nodejs_compat"] + : [] + : ["nodejs_compat"]), ...(props.isExternal ? [] - : [ - "nodejs_compat", - // ISO dates compare lexically. - ...(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/Cloudflare/Workers/LocalWorkerProvider.ts b/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts index 1d695313700..17e9a5cac25 100644 --- a/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts +++ b/packages/alchemy/src/Cloudflare/Workers/LocalWorkerProvider.ts @@ -573,7 +573,11 @@ export const LocalWorkerProvider = () => workerBindings, durableObjectNamespaces: Object.values(durableObjectNamespaces), workflows: Object.values(workflows), - 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, // Substitute `Worker.URL` sentinels so the Vite dev server inlines diff --git a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts index 41a221317c4..8656293eb07 100644 --- a/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts +++ b/packages/alchemy/src/Cloudflare/Workers/WorkerProvider.ts @@ -1423,7 +1423,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, @@ -3364,6 +3374,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( @@ -3385,7 +3396,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..4acd5edcecb 100644 --- a/packages/alchemy/src/Command/Memo.ts +++ b/packages/alchemy/src/Command/Memo.ts @@ -16,10 +16,18 @@ 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. + * + * 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) */ include?: string[]; /** @@ -98,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( @@ -141,7 +158,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/Cloudflare/Website/StaticSite.test.ts b/packages/alchemy/test/Cloudflare/Website/StaticSite.test.ts index e4441c47dca..4dc1c4ffeb0 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/Alchemy"; import { expect } from "alchemy-test"; +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, 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"); + }); +}); 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 f8f8fc64538..512b210ad21 100644 --- a/packages/alchemy/test/Command/Build.test.ts +++ b/packages/alchemy/test/Command/Build.test.ts @@ -165,3 +165,69 @@ 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); + + // 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 }, +);