diff --git a/.changeset/browser-run-local-quick-actions.md b/.changeset/browser-run-local-quick-actions.md deleted file mode 100644 index c7bd7bdf14..0000000000 --- a/.changeset/browser-run-local-quick-actions.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -"miniflare": minor ---- - -Support Browser Run quick actions in local development - -`env.BROWSER.quickAction(action, options)` now works with a local browser binding instead of failing with `The RPC receiver does not implement the method "quickAction"`. The `screenshot`, `pdf`, `content`, `markdown`, `snapshot`, `scrape`, `links` and `accessibilityTree` actions run in a local Chrome and return the same responses and errors as Browser Run. - -Workers AI isn't available locally, so the `json` action returns placeholder data shaped like `response_format.json_schema` and logs a warning. The `kitesurf` browser isn't supported locally either. Set `"remote": true` on the browser binding to use Browser Run for these. diff --git a/.changeset/browser-run-session-disconnect.md b/.changeset/browser-run-session-disconnect.md deleted file mode 100644 index 6937e41066..0000000000 --- a/.changeset/browser-run-session-disconnect.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -"miniflare": patch ---- - -Clear a local Browser Run session's `connectionId` when its client disconnects - -Sessions connected through `/v1/devtools/browser/:sessionId`, which current versions of `@cloudflare/puppeteer` and `@cloudflare/playwright` use, kept reporting a `connectionId` after the client closed its WebSocket. Reusing a session by picking one without a `connectionId` therefore never found a free session in local development. diff --git a/.changeset/default-compat-date-16849.md b/.changeset/default-compat-date-16849.md deleted file mode 100644 index cc3d4c34b4..0000000000 --- a/.changeset/default-compat-date-16849.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -"@cloudflare/workers-utils": patch -"@cloudflare/autoconfig": patch -"@cloudflare/build-output-utils": patch -"@cloudflare/cli-shared-helpers": patch -"@cloudflare/codemods": patch -"@cloudflare/config": patch -"@cloudflare/containers-shared": patch -"@cloudflare/deploy-helpers": patch -"@cloudflare/pages-functions": patch -"@cloudflare/pages-shared": patch -"@cloudflare/runtime-types": patch -"@cloudflare/vite-plugin": patch -"@cloudflare/vitest-plugin": patch -"@cloudflare/workers-auth": patch -"create-cloudflare": patch -"miniflare": patch -"wrangler": patch ---- - -Update `DEFAULT_COMPAT_DATE` to 2026-11-12 - -Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. diff --git a/.changeset/dependabot-update-16849.md b/.changeset/dependabot-update-16849.md deleted file mode 100644 index c86ad40cba..0000000000 --- a/.changeset/dependabot-update-16849.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -"miniflare": patch -"wrangler": patch ---- - -Update dependencies of "miniflare", "wrangler" - -The following dependency versions have been updated: - -| Dependency | From | To | -| ------------------------- | ------------- | ------------- | -| @cloudflare/workers-types | ^5.20261110.1 | ^5.20261112.1 | -| workerd | 1.20261110.1 | 1.20261112.1 | diff --git a/.changeset/miniflare-email-can-be-forwarded.md b/.changeset/miniflare-email-can-be-forwarded.md new file mode 100644 index 0000000000..0f1c772ee5 --- /dev/null +++ b/.changeset/miniflare-email-can-be-forwarded.md @@ -0,0 +1,7 @@ +--- +"miniflare": patch +--- + +Expose `canBeForwarded` boolean property on `ForwardableEmailMessage` in email handler + +Previously, in `wrangler dev`, the `ForwardableEmailMessage` passed to a Worker's `email()` handler did not expose the documented `canBeForwarded` property, causing it to read as `undefined` locally while production exposes it as a read-only boolean. `canBeForwarded: true` is now set on the incoming message object in Miniflare, matching production behavior. diff --git a/.changeset/tidy-proxy-reload-retries.md b/.changeset/tidy-proxy-reload-retries.md deleted file mode 100644 index c2bc2187ca..0000000000 --- a/.changeset/tidy-proxy-reload-retries.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -"wrangler": patch ---- - -Fix requests hanging when a local Worker reload finishes before an inflight request fails - -Wrangler now immediately processes retriable requests when the replacement Worker is already ready. Previously, these requests could remain queued until another request arrived, particularly on Windows where connection failures can take longer to report. diff --git a/.changeset/vpc-custom-certificates.md b/.changeset/vpc-custom-certificates.md new file mode 100644 index 0000000000..c3d3373ae3 --- /dev/null +++ b/.changeset/vpc-custom-certificates.md @@ -0,0 +1,56 @@ +--- +"wrangler": minor +--- + +Add custom CA and client certificate references to Workers VPC service TLS settings + +Workers VPC (open beta) service create and update commands accept `--certificate-authority` and `--client-certificate` UUIDs. Use either flag alone or both together. Whenever you supply either reference, explicitly choose `--cert-verification-mode`: + +- `verify_full`: verify the origin certificate chain and hostname (the platform default). +- `verify_ca`: verify the chain but skip hostname verification, weakening origin identity checks. +- `disabled`: do not verify the origin certificate; this allows connections to impersonated origins and is unsafe for production. + +For HTTP services, these settings apply to HTTPS connections, not plaintext HTTP. TCP services can use them for upstream TLS, including PostgreSQL. + +TLS settings are per-service only: host and resolver networks have no TLS settings or inheritance. Omitting TLS settings uses platform defaults (certificate chain and hostname verification). Explicit mode-only configuration, including `verify_full`, is accepted. A custom CA cannot be combined with `disabled`; a client certificate without a custom CA can. + +Upload certificates using the existing commands, then use the returned IDs below. Replace ``, ``, ``, and service IDs with your own values; certificate references must be valid UUIDs. Upload replacement certificates the same way before rotating their references. + +```sh +pnpm exec wrangler cert upload certificate-authority --ca-cert ./ca.pem --name private-ca +pnpm exec wrangler cert upload mtls-certificate --cert ./client.pem --key ./client-key.pem --name private-client +``` + +Create an HTTPS service with both a custom trust chain and an mTLS client certificate, or a PostgreSQL TCP service with only a custom CA: + +```sh +pnpm exec wrangler vpc service create private-web \ + --type http --https-port 443 --ipv4 10.0.0.10 --tunnel-id \ + --certificate-authority --client-certificate \ + --cert-verification-mode verify_full + +pnpm exec wrangler vpc service create private-db \ + --type tcp --tcp-port 5432 --app-protocol postgresql \ + --hostname db.internal.example --resolver-ips 10.0.0.53 --tunnel-id \ + --certificate-authority --cert-verification-mode verify_full +``` + +For client-certificate-only configuration, use `--client-certificate --cert-verification-mode verify_full` instead of the certificate flags in either create command. + +Updates replace the complete service configuration, including TLS settings, in a single request, the same as `cf workers-vpc services update`. Pass every TLS option the service should keep: certificate references and the verification mode that you omit are cleared, and an update without TLS options returns the service to the platform defaults. Removing a reference releases its backend certificate binding but does not delete the uploaded account certificate. For example, rotate the web service's client certificate while keeping its CA: + +```sh +pnpm exec wrangler vpc service update \ + --name private-web --type http --https-port 443 \ + --ipv4 10.0.0.10 --tunnel-id \ + --certificate-authority --client-certificate \ + --cert-verification-mode verify_full +``` + +To remove the CA while keeping the client certificate, repeat the update with only `--client-certificate ` and a verification mode. + +Inspect the service's verification mode and CA/client certificate UUIDs (or `None`), without exposing certificate or private-key contents: + +```sh +pnpm exec wrangler vpc service get +``` diff --git a/.github/workflows/c3-e2e.yml b/.github/workflows/c3-e2e.yml index c41ccaeee6..9f019e9977 100644 --- a/.github/workflows/c3-e2e.yml +++ b/.github/workflows/c3-e2e.yml @@ -75,6 +75,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' @@ -231,6 +233,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/e2e-local-explorer-ui.yml b/.github/workflows/e2e-local-explorer-ui.yml index bb5657c384..956115748d 100644 --- a/.github/workflows/e2e-local-explorer-ui.yml +++ b/.github/workflows/e2e-local-explorer-ui.yml @@ -29,6 +29,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | relevant: - 'packages/local-explorer-ui/**' diff --git a/.github/workflows/e2e-vite.yml b/.github/workflows/e2e-vite.yml index 90fcbf7058..42e6526a45 100644 --- a/.github/workflows/e2e-vite.yml +++ b/.github/workflows/e2e-vite.yml @@ -36,6 +36,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/e2e-wrangler.yml b/.github/workflows/e2e-wrangler.yml index 8a1a88a288..29f0b68efa 100644 --- a/.github/workflows/e2e-wrangler.yml +++ b/.github/workflows/e2e-wrangler.yml @@ -39,6 +39,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/test-and-check-other-node.yml b/.github/workflows/test-and-check-other-node.yml index 9f6eef9194..66d2bf293d 100644 --- a/.github/workflows/test-and-check-other-node.yml +++ b/.github/workflows/test-and-check-other-node.yml @@ -47,6 +47,8 @@ jobs: uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/test-and-check.yml b/.github/workflows/test-and-check.yml index c3244c8347..11eac34f4a 100644 --- a/.github/workflows/test-and-check.yml +++ b/.github/workflows/test-and-check.yml @@ -63,6 +63,8 @@ jobs: uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | miniflare_openapi: - 'packages/miniflare/src/workers/local-explorer/openapi.local.json' @@ -152,6 +154,8 @@ jobs: uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/validate-pr-description.yml b/.github/workflows/validate-pr-description.yml index 4b16334470..08ac3a4ff7 100644 --- a/.github/workflows/validate-pr-description.yml +++ b/.github/workflows/validate-pr-description.yml @@ -38,6 +38,8 @@ jobs: - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/.github/workflows/vite-plugin-playgrounds.yml b/.github/workflows/vite-plugin-playgrounds.yml index 913f5d0d82..fd5fb4352f 100644 --- a/.github/workflows/vite-plugin-playgrounds.yml +++ b/.github/workflows/vite-plugin-playgrounds.yml @@ -44,6 +44,8 @@ jobs: uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: changes with: + # Detect changes with local git: a single transient GitHub API error would fail the job + token: "" filters: | everything_but_markdown: - '!**/*.md' diff --git a/fixtures/get-platform-proxy-remote-bindings/tests/index.test.ts b/fixtures/get-platform-proxy-remote-bindings/tests/index.test.ts index 2cdfaa8f3c..6c1453683c 100644 --- a/fixtures/get-platform-proxy-remote-bindings/tests/index.test.ts +++ b/fixtures/get-platform-proxy-remote-bindings/tests/index.test.ts @@ -1,5 +1,4 @@ import { execSync } from "node:child_process"; -import { randomUUID } from "node:crypto"; import { mkdirSync, rmSync, writeFileSync } from "node:fs"; import { afterAll, @@ -27,7 +26,13 @@ const execOptions = { } as const; const remoteWorkerName = `preserve-e2e-get-platform-proxy-remote`; const remoteStagingWorkerName = `preserve-e2e-get-platform-proxy-remote-staging`; -const remoteKvName = `tmp-e2e-kv${Date.now()}-test-remote-bindings-${randomUUID().split("-")[0]}`; +// Shared across runs like the Workers above, and kept out of the scheduled +// cleanup by its `preserve-e2e-` prefix. A brand-new namespace can reject +// writes with "namespace not found" for longer than setup can wait, so reusing +// one means only the very first run ever has to wait for that. +const remoteKvName = "preserve-e2e-get-platform-proxy-kv"; +const remoteKvKey = "test-key"; +const remoteKvValue = "remote-kv-value"; if (auth) { describe("getPlatformProxy - remote bindings", { timeout: 50_000 }, () => { @@ -69,39 +74,27 @@ if (auth) { ); } - const kvAddOut = execSync( - `pnpm wrangler kv namespace create ${remoteKvName}`, - execOptions - ); + remoteKvId = ensureKvNamespace(remoteKvName); - const createdKvRegexMatch = kvAddOut.match(/"id": "(?[^"]*?)"/); - const maybeRemoteKvId = createdKvRegexMatch?.groups?.["id"]; - assert(maybeRemoteKvId, `Failed to create remote kv ${remoteKvName}`); - remoteKvId = maybeRemoteKvId; - - // Newly created namespaces may not be available to the KV write API yet. - await vi.waitFor( - () => { - execSync( - `pnpm wrangler kv key put test-key remote-kv-value --namespace-id=${remoteKvId} --remote`, - { ...execOptions, timeout: 10_000 } - ); - }, - { timeout: 15_000, interval: 1_000 } - ); + // Only a newly created (or emptied) namespace needs the write. Brand-new + // namespaces may not be available to the KV write API yet. + if (readKvValue(remoteKvId, remoteKvKey) !== remoteKvValue) { + await vi.waitFor( + () => { + execSync( + `pnpm wrangler kv key put ${remoteKvKey} ${remoteKvValue} --namespace-id=${remoteKvId} --remote`, + { ...execOptions, timeout: 10_000 } + ); + }, + { timeout: 45_000, interval: 2_000 } + ); + } rmSync("./.tmp", { recursive: true, force: true }); mkdirSync("./.tmp"); - }, 60_000); + }, 90_000); afterAll(() => { - try { - execSync( - `pnpm wrangler kv namespace delete --namespace-id=${remoteKvId}`, - execOptions - ); - } catch {} - try { rmSync("./.tmp", { recursive: true, @@ -355,3 +348,52 @@ function getAuthenticatedEnv() { "Skipping vitest-plugin remote bindings tests because the environment is not authenticated with Cloudflare." ); } + +/** + * Lists the account's KV namespaces through Wrangler. + */ +function listKvNamespaces(): { id: string; title: string }[] { + const out = execSync("pnpm wrangler kv namespace list", execOptions); + return JSON.parse(out.slice(out.search(/^\[/m))); +} + +/** + * Returns the ID of the KV namespace with the given title, creating it if it + * doesn't exist yet. + */ +function ensureKvNamespace(title: string): string { + const existing = listKvNamespaces().find((ns) => ns.title === title); + if (existing) { + return existing.id; + } + try { + const out = execSync( + `pnpm wrangler kv namespace create ${title}`, + execOptions + ); + const id = out.match(/"id": "(?[^"]*?)"/)?.groups?.["id"]; + if (id) { + return id; + } + } catch { + // Another CI job may have created it at the same time; look it up below. + } + const created = listKvNamespaces().find((ns) => ns.title === title); + assert(created, `Failed to find or create KV namespace ${title}`); + return created.id; +} + +/** + * Reads a KV value as text, or returns `undefined` if the key is missing or the + * read fails. + */ +function readKvValue(namespaceId: string, key: string): string | undefined { + try { + return execSync( + `pnpm wrangler kv key get ${key} --namespace-id=${namespaceId} --remote --text`, + { ...execOptions, timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] } + ).trim(); + } catch { + return undefined; + } +} diff --git a/fixtures/get-platform-proxy-remote-bindings/vitest.config.e2e.mts b/fixtures/get-platform-proxy-remote-bindings/vitest.config.e2e.mts index b362bc404f..600b3d2398 100644 --- a/fixtures/get-platform-proxy-remote-bindings/vitest.config.e2e.mts +++ b/fixtures/get-platform-proxy-remote-bindings/vitest.config.e2e.mts @@ -5,8 +5,9 @@ export default mergeConfig( configShared, defineProject({ test: { - // Preview API failures can outlast the short per-request retry window. - retry: { count: 1, delay: 5_000 }, + // Preview API failures can outlast the short per-request retry window, + // sometimes for 40s or more, so space the retries out to ride that out. + retry: { count: 2, delay: 15_000 }, }, }) ); diff --git a/packages/autoconfig/CHANGELOG.md b/packages/autoconfig/CHANGELOG.md index a40b1903eb..2cf97bbdcf 100644 --- a/packages/autoconfig/CHANGELOG.md +++ b/packages/autoconfig/CHANGELOG.md @@ -1,5 +1,47 @@ # @cloudflare/autoconfig +## 0.13.0 + +### Minor Changes + +- [#16803](https://github.com/cloudflare/workers-sdk/pull/16803) [`b219078`](https://github.com/cloudflare/workers-sdk/commit/b219078a4c1b008485ce022f01ad7292d613d9f0) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Run experimental cf projects with their installed Vite or Vite+ commands + + `cf dev`, `cf build`, and deployments that build your project can use Vite or Vite+ even when no framework command is detected. This removes the need for the internal `cf-vite` delegate and supports dependencies declared and hoisted at the root of a configured workspace. A workspace application using a custom-named Vite config should declare `@cloudflare/vite-plugin` in its own manifest, or add `vite` or `vite-plus` as a dependency or dev dependency to identify its tooling; this keeps shared root tools from selecting Vite for non-Vite siblings. Configs passed later via `--config` are evaluated by Vite when the command runs. Existing framework commands keep their priority. Consumers resolve bare executables using the detected `nodeModulesPaths` in order, adding `.bin` to each directory. Lookup stops at the validated workspace root; standalone applications use only their own `node_modules/.bin`. + + Project inspection can recognize an existing Cloudflare configuration before dependencies are installed. Running a command provides guidance when the required tools are missing or the plugin version does not support cf profiles (`>=2.0.0-beta.v.13 <3`). Vite evaluates the project configuration when the command runs, including dynamic configs and custom config files. Repair guidance uses the project’s detected package manager. Automatic setup asks users to convert CommonJS `.cjs` and `.cts` Vite configs to ESM imports and exports in `.mjs` or `.mts` before adding the ESM-only Cloudflare plugin. Native builds also work with the Windows shell. Pages migration safeguards, unsupported-framework setup checks, and Wrangler command selection retain their existing behavior. + +### Patch Changes + +- [#16921](https://github.com/cloudflare/workers-sdk/pull/16921) [`6785363`](https://github.com/cloudflare/workers-sdk/commit/6785363bc2d9b7cda463d8cc71765c4780f8d64d) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Install the Vite plugin release candidate when configuring projects for `cf` + + Configuring a Vite project for `cf` now installs `@cloudflare/vite-plugin@^2.0.0-rc.0` instead of `^2.0.0-beta.v.0`, so an existing lockfile can't keep a beta that doesn't support the generated configuration. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155)]: + - @cloudflare/config@1.0.0-rc.0 + - @cloudflare/workers-utils@0.54.1 + - @cloudflare/cli-shared-helpers@0.3.9 + +## 0.12.1 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985)]: + - @cloudflare/workers-utils@0.54.0 + - @cloudflare/cli-shared-helpers@0.3.8 + - @cloudflare/config@0.32.1 + ## 0.12.0 ### Minor Changes diff --git a/packages/autoconfig/package.json b/packages/autoconfig/package.json index 5128150d4a..58961da62c 100644 --- a/packages/autoconfig/package.json +++ b/packages/autoconfig/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/autoconfig", - "version": "0.12.0", + "version": "0.13.0", "description": "Framework autoconfig detection and configuration for Cloudflare Workers", "license": "MIT OR Apache-2.0", "repository": { diff --git a/packages/autoconfig/src/context.ts b/packages/autoconfig/src/context.ts index 0a27bf2762..49f2f1d6dc 100644 --- a/packages/autoconfig/src/context.ts +++ b/packages/autoconfig/src/context.ts @@ -87,8 +87,9 @@ export interface AutoConfigContext { * Runs a shell command in the given directory. * * For the cf target, commands may use bare framework executables. Implementations - * must resolve executables from `cwd/node_modules/.bin` and ancestor directories' - * `node_modules/.bin`, including for standalone applications. + * must resolve executables from the detected details' `nodeModulesPaths`, adding + * `.bin` to each directory. These paths stop at the detected workspace root; + * standalone applications must not use unrelated parent installations. * * @param command - The shell command string to execute * @param cwd - The working directory for the command diff --git a/packages/autoconfig/src/details/framework-detection.ts b/packages/autoconfig/src/details/framework-detection.ts index d6445bd98e..679ac36de5 100644 --- a/packages/autoconfig/src/details/framework-detection.ts +++ b/packages/autoconfig/src/details/framework-detection.ts @@ -60,6 +60,7 @@ export async function detectFramework( detectedFramework: DetectedFramework; packageManager: PackageManager; isWorkspaceRoot?: boolean; + workspaceRoot?: string; }> { const fs = new NodeFS(); @@ -157,6 +158,7 @@ export async function detectFramework( dist: wranglerConfig?.pages_build_output_dir, }, packageManager, + workspaceRoot, }; } @@ -184,6 +186,7 @@ export async function detectFramework( detectedFramework, packageManager, isWorkspaceRoot, + workspaceRoot, }; } @@ -305,7 +308,8 @@ function throwMultipleFrameworksNonInteractiveError( ); } -type DetectedFramework = { +/** Framework metadata, commands, and output directory found during detection. */ +export type DetectedFramework = { baseDirectory?: string; framework: { name: string; diff --git a/packages/autoconfig/src/details/index.ts b/packages/autoconfig/src/details/index.ts index 6e75bfc0ac..e36b51ddb7 100644 --- a/packages/autoconfig/src/details/index.ts +++ b/packages/autoconfig/src/details/index.ts @@ -1,7 +1,7 @@ import assert from "node:assert"; import { existsSync, statSync, type Stats } from "node:fs"; import { readdir, stat } from "node:fs/promises"; -import { join, relative, resolve } from "node:path"; +import { dirname, join, relative, resolve } from "node:path"; import { brandColor } from "@cloudflare/cli-shared-helpers/colors"; import { checkWorkerNameValidity, @@ -10,18 +10,23 @@ import { parsePackageJSON, readFileSync, } from "@cloudflare/workers-utils"; -import { AutoConfigDetectionError } from "../errors"; +import { + AutoConfigDetectionError, + AutoConfigFrameworkConfigurationError, +} from "../errors"; import { getFrameworkClassInstance } from "../frameworks"; import { getAllFrameworksInfos, staticFramework, } from "../frameworks/all-frameworks"; import { detectFramework } from "./framework-detection"; +import { getViteProjectCommands, usesVitePlus } from "./vite-commands"; import type { AutoConfigContext, AutoConfigTarget } from "../context"; import type { AutoConfigDetails, AutoConfigDetailsForNonConfiguredProject, } from "../types"; +import type { DetectedFramework } from "./framework-detection"; import type { PackageManager } from "@cloudflare/workers-utils"; import type { Config, PackageJSON } from "@cloudflare/workers-utils"; @@ -116,8 +121,15 @@ function normalizeOutputDir(projectPath: string, outputDir: string): string { * detection instead. * * For the cf target, build and dev commands may use bare framework executables. - * Callers must resolve these from the application's and ancestor directories' - * `node_modules/.bin`, including for standalone applications. + * Callers must resolve these from `nodeModulesPaths`, which includes the + * application and its detected workspace, excluding unrelated parent installs. + * Command readiness problems are reported in `commandError` without preventing + * inspection of the project's configuration. + * Workspace applications with custom-named Vite configs must identify their + * tooling in their own manifest: declare the Cloudflare plugin, or Vite/Vite+ + * as a dependency or dev dependency. Config paths forwarded to the eventual + * command are not available during detection; root tools alone do not identify + * which sibling applications use Vite. * * @param options - Detection options including project path, wrangler config, and context. * @returns The detected project details. @@ -171,8 +183,9 @@ export async function getDetailsForAutoConfig({ }; } - const { detectedFramework, packageManager, isWorkspaceRoot } = + const { detectedFramework, packageManager, isWorkspaceRoot, workspaceRoot } = await detectFramework(projectPath, context, { wranglerConfig, target }); + const nodeModulesPaths = getNodeModulesPaths(projectPath, workspaceRoot); const detectedFrameworkInstance = getFrameworkClassInstance( detectedFramework.framework.id, @@ -185,7 +198,7 @@ export async function getDetailsForAutoConfig({ !configured && requestedOutputDir !== undefined && detectedFramework.framework.id !== "cloudflare-pages"; - const framework = useStaticAssets + let framework = useStaticAssets ? getFrameworkClassInstance(staticFramework.id, target) : detectedFrameworkInstance; const packageJsonPath = resolve(projectPath, "package.json"); @@ -201,20 +214,62 @@ export async function getDetailsForAutoConfig({ logger.debug("No package.json found when running autoconfig"); } - const outputDir = - requestedOutputDir !== undefined && framework.id === staticFramework.id + let outputDir = configured + ? undefined + : requestedOutputDir !== undefined && framework.id === staticFramework.id ? normalizeOutputDir(projectPath, requestedOutputDir) - : (detectedFramework?.dist ?? (await findAssetsDir(projectPath))); + : (detectedFramework.dist ?? (await findAssetsDir(projectPath))); + + // Unknown frameworks also use the static class. Validate its assets before + // a native Vite fallback can replace the framework and output directory. + if (!configured && framework.id === staticFramework.id) { + await assertNoPagesFunctionsWithRootAssets( + projectPath, + outputDir, + target, + context + ); + } + + const inspectViteProject = canInspectViteProject({ + target, + useStaticAssets, + configured, + detectedFramework, + }); + const useNativeCommands = + !detectedFramework.devCommand && !detectedFramework.buildCommand; + const viteCommands = inspectViteProject + ? getViteProjectCommands({ + projectPath, + packageJson, + workspaceRoot: configured ? workspaceRoot : undefined, + packageManager, + isWorkspaceRoot, + nodeModulesPaths, + resolveCommands: useNativeCommands || framework.id === "vite", + }) + : undefined; + const fallbackCommands = useNativeCommands ? viteCommands : undefined; + if (fallbackCommands) { + framework = getFrameworkClassInstance("vite", target); + } + + if (fallbackCommands && detectedFramework.dist === undefined) { + outputDir = "dist"; + } const baseDetails = { projectPath, framework, packageJson, packageManager, + nodeModulesPaths, + commandError: viteCommands?.error, devCommand: useStaticAssets ? undefined : getProjectCommand( - detectedFramework.devCommand, + detectedFramework.devCommand ?? fallbackCommands?.devCommand, packageManager, packageJson, target @@ -222,7 +277,7 @@ export async function getDetailsForAutoConfig({ buildCommand: useStaticAssets ? undefined : getProjectCommand( - detectedFramework.buildCommand, + detectedFramework.buildCommand ?? fallbackCommands?.buildCommand, packageManager, packageJson, target @@ -252,38 +307,6 @@ export async function getDetailsForAutoConfig({ }); } - // A `functions` directory next to static files in the project root usually - // means a Cloudflare Pages project using Pages Functions. Interactively the - // user is asked whether it is a Pages project; non-interactive runs assume it - // is not and continue as a static site, which would deploy the project root - // as assets and silently drop the Functions (the API routes). Stop instead. - // This checks the framework class rather than the detected id, because - // detected frameworks missing from `allFrameworksInfos` are also configured as - // static sites and would deploy the project root the same way. - if ( - framework.id === staticFramework.id && - (context.isNonInteractiveOrCI?.() ?? false) && - resolve(projectPath, outputDir) === resolve(projectPath) && - (await getPathStats(join(projectPath, "functions")))?.isDirectory() - ) { - const configFile = - target === "cf" - ? `a \`${CLOUDFLARE_CONFIG_FILE}\` file` - : "a Wrangler configuration file"; - throw new AutoConfigDetectionError( - "This project has a `functions` directory and static files in its root, which looks like a Cloudflare Pages project using Pages Functions. " + - "Automatic configuration cannot migrate Pages Functions to Workers yet, and deploying the project root as static assets would leave the Functions undeployed.\n" + - "If `functions` contains Pages Functions, move the static files into a subdirectory (for example `public/`) and deploy with `wrangler pages deploy public --project-name `, " + - "or migrate the Functions to a Worker: https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/\n" + - `If \`functions\` is not Pages Functions, move the static files into a subdirectory or add ${configFile} for the Worker.`, - { - telemetryMessage: "autoconfig details pages functions with root assets", - frameworkId: framework.id, - configured, - } - ); - } - return { ...baseDetails, outputDir, @@ -292,6 +315,113 @@ export async function getDetailsForAutoConfig({ }; } +/** + * Rejects unconfigured static sites whose root assets would silently omit Pages + * Functions. Interactive detection can ask the user whether this is a Pages + * project, but non-interactive detection assumes it is a static site. + */ +async function assertNoPagesFunctionsWithRootAssets( + projectPath: string, + outputDir: string | undefined, + target: AutoConfigTarget, + context: AutoConfigContext +): Promise { + if ( + !(context.isNonInteractiveOrCI?.() ?? false) || + outputDir === undefined || + resolve(projectPath, outputDir) !== resolve(projectPath) || + !(await getPathStats(join(projectPath, "functions")))?.isDirectory() + ) { + return; + } + + const configFile = + target === "cf" + ? `a \`${CLOUDFLARE_CONFIG_FILE}\` file` + : "a Wrangler configuration file"; + throw new AutoConfigDetectionError( + "This project has a `functions` directory and static files in its root, which looks like a Cloudflare Pages project using Pages Functions. " + + "Automatic configuration cannot migrate Pages Functions to Workers yet, and deploying the project root as static assets would leave the Functions undeployed.\n" + + "If `functions` contains Pages Functions, move the static files into a subdirectory (for example `public/`) and deploy with `wrangler pages deploy public --project-name `, " + + "or migrate the Functions to a Worker: https://developers.cloudflare.com/workers/static-assets/migration-guides/migrate-from-pages/\n" + + `If \`functions\` is not Pages Functions, move the static files into a subdirectory or add ${configFile} for the Worker.`, + { + telemetryMessage: "autoconfig details pages functions with root assets", + frameworkId: staticFramework.id, + configured: false, + } + ); +} + +/** + * Keeps native execution from bypassing Pages detection or unsupported setup. + * An existing configuration can opt an otherwise unsupported project into execution. + */ +function canInspectViteProject({ + target, + useStaticAssets, + configured, + detectedFramework, +}: { + target: AutoConfigTarget; + useStaticAssets: boolean; + configured: boolean; + detectedFramework: DetectedFramework; +}): boolean { + if ( + target !== "cf" || + useStaticAssets || + detectedFramework.framework.id === "cloudflare-pages" + ) { + return false; + } + if (configured) { + return true; + } + + const frameworkInfo = getAllFrameworksInfos(target).find( + ({ id }) => id === detectedFramework.framework.id + ); + return frameworkInfo?.supported === true && frameworkInfo.supportsCf; +} + +/** + * Requires runnable project commands at an execution boundary. Read-only callers + * can inspect detection results, including missing installs, without throwing. + * + * @param details The detected project details + * @throws {AutoConfigFrameworkConfigurationError} If project commands are unavailable + */ +export function assertProjectCommandsAvailable( + details: AutoConfigDetails +): void { + if (details.commandError) { + throw new AutoConfigFrameworkConfigurationError( + details.commandError.message, + { + telemetryMessage: "autoconfig vite command unavailable", + } + ); + } +} + +/** Restricts package lookup to the application and its validated workspace. */ +function getNodeModulesPaths( + projectPath: string, + workspaceRoot?: string +): string[] { + const directories: string[] = []; + const root = resolve(workspaceRoot ?? projectPath); + let directory = resolve(projectPath); + while (true) { + directories.push(join(directory, "node_modules")); + if (directory === root || dirname(directory) === directory) { + return directories; + } + directory = dirname(directory); + } +} + /** * Converts a detected project command for the target's command runner. The cf * runner must resolve local executables, while Wrangler commands include @@ -315,10 +445,7 @@ export function getProjectCommand( const { type, dlx, npx } = packageManager; const executablePrefix = target === "cf" ? "" : `${npx} `; - if ( - packageJson?.dependencies?.["vite-plus"] || - packageJson?.devDependencies?.["vite-plus"] - ) { + if (usesVitePlus(packageJson)) { if ( ["vite", "vite dev", `${npx} vite`, `${npx} vite dev`].includes(command) ) { diff --git a/packages/autoconfig/src/details/vite-commands.ts b/packages/autoconfig/src/details/vite-commands.ts new file mode 100644 index 0000000000..532173d3f4 --- /dev/null +++ b/packages/autoconfig/src/details/vite-commands.ts @@ -0,0 +1,217 @@ +import { existsSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { parsePackageJSON, readFileSync } from "@cloudflare/workers-utils"; +import semiver from "semiver"; +import { hasViteConfig } from "../frameworks/utils/vite-config"; +import type { AutoConfigCommandError } from "../types"; +import type { PackageJSON, PackageManager } from "@cloudflare/workers-utils"; + +type ProjectPackageJSON = PackageJSON & { + peerDependencies?: Record; + optionalDependencies?: Record; +}; + +/** Whether the project uses Vite+ as its Vite command runner. */ +export function usesVitePlus(packageJson?: PackageJSON): boolean { + return Boolean( + packageJson?.dependencies?.["vite-plus"] || + packageJson?.devDependencies?.["vite-plus"] + ); +} + +/** + * Inspect plugin readiness for cf projects, resolving native commands when no + * framework commands exist. Report failures as data so detection remains useful + * before dependencies have been installed or framework setup has been applied. + * + * Shared workspace tools require an application-level signal: a plugin or + * runner declaration, or a default-named Vite config. An application using a + * custom config must declare the plugin or runner itself; arbitrary config + * paths forwarded at execution time are not available during detection. + */ +export function getViteProjectCommands({ + projectPath, + packageJson, + workspaceRoot, + packageManager, + isWorkspaceRoot, + nodeModulesPaths, + resolveCommands, +}: { + projectPath: string; + packageJson?: ProjectPackageJSON; + /** Only provided for configured applications inside a validated workspace. */ + workspaceRoot?: string; + packageManager: PackageManager; + isWorkspaceRoot?: boolean; + nodeModulesPaths: readonly string[]; + resolveCommands: boolean; +}): + | { + devCommand?: string; + buildCommand?: string; + error?: AutoConfigCommandError; + } + | undefined { + const projectRunner = getViteRunner(packageJson); + const projectDependencies = getDeclaredDependencies(packageJson); + // A sibling's shared tools do not make this a Vite application. A local + // plugin/runner declaration or Vite config opts it in without evaluating it. + const workspacePackageJson = + workspaceRoot && + ("@cloudflare/vite-plugin" in projectDependencies || + projectRunner || + hasViteConfig(projectPath)) + ? readPackage(join(workspaceRoot, "package.json")) + : undefined; + const dependencies = { + ...getDeclaredDependencies(workspacePackageJson), + ...projectDependencies, + }; + if (!("@cloudflare/vite-plugin" in dependencies)) { + return; + } + + const plugin = readProjectPackage( + nodeModulesPaths, + "@cloudflare/vite-plugin" + ); + const requirement = + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3 for cf dev, cf build, cf deploy, and cf previews deploy."; + // An application's explicit runner takes priority over workspace defaults. + const packageName = + projectRunner ?? getViteRunner(workspacePackageJson) ?? "vite"; + const install = getInstallCommand( + packageManager.type, + packageName, + isWorkspaceRoot + ); + if (!plugin) { + return { + error: { + code: "vite-plugin-not-installed", + message: `@cloudflare/vite-plugin is declared in package.json but is not installed. ${requirement} Run ${install}.`, + }, + }; + } + const version = plugin.packageJson.version; + if ( + !version?.match(/^2\.\d+\.\d+(?:[-+].+)?$/) || + semiver(version.split("+")[0], "2.0.0-beta.v.13") < 0 + ) { + return { + error: { + code: "vite-plugin-incompatible", + message: `@cloudflare/vite-plugin@${plugin.packageJson.version ?? "unknown"} is installed, but it is not compatible with cf's local runtime. ${requirement} Run ${install}.`, + }, + }; + } + if (!resolveCommands) { + return {}; + } + + const commandName = packageName === "vite-plus" ? "vp" : "vite"; + const tool = readProjectPackage(nodeModulesPaths, packageName); + const bin = tool?.packageJson.bin; + const relativeBinary = typeof bin === "string" ? bin : bin?.[commandName]; + const binary = + tool && relativeBinary + ? resolve(tool.directory, relativeBinary) + : undefined; + if (!binary || !existsSync(binary)) { + return { + error: { + code: "vite-tool-not-installed", + message: `@cloudflare/vite-plugin is installed, but the project's ${commandName} executable could not be found. ${requirement} Run ${install}.`, + }, + }; + } + + // The same command can be parsed into argv by cf or passed to a shell by + // runAutoConfig. cmd.exe needs Node explicitly and does not accept POSIX quotes. + const executable = + process.platform === "win32" + ? `"${process.execPath}" "${binary}"` + : `'${binary.replaceAll("'", "'\\''")}'`; + return { + devCommand: `${executable} dev`, + buildCommand: `${executable} build`, + }; +} + +/** Peer and optional declarations alone do not select a project's command runner. */ +function getViteRunner( + packageJson?: PackageJSON +): "vite" | "vite-plus" | undefined { + if (usesVitePlus(packageJson)) { + return "vite-plus"; + } + if (packageJson?.dependencies?.vite || packageJson?.devDependencies?.vite) { + return "vite"; + } +} + +function getDeclaredDependencies(packageJson?: ProjectPackageJSON) { + return { + ...packageJson?.dependencies, + ...packageJson?.devDependencies, + ...packageJson?.peerDependencies, + ...packageJson?.optionalDependencies, + }; +} + +function readPackage(path: string): ProjectPackageJSON | undefined { + try { + return parsePackageJSON(readFileSync(path), path); + } catch { + return; + } +} + +function readProjectPackage( + nodeModulesPaths: readonly string[], + packageName: string +): + | { + directory: string; + packageJson: PackageJSON & { bin?: string | Record }; + } + | undefined { + for (const nodeModules of nodeModulesPaths) { + const directory = join(nodeModules, packageName); + const path = join(directory, "package.json"); + if (!existsSync(path)) { + continue; + } + try { + return { + directory, + packageJson: parsePackageJSON(readFileSync(path), path), + }; + } catch { + // A broken nearer install must not silently select another version. + return; + } + } +} + +/** Suggests a repair command using the project's package manager and workspace flags. */ +function getInstallCommand( + packageManager: PackageManager["type"], + packageName: string, + isWorkspaceRoot = false +): string { + const command = + packageManager === "yarn" || packageManager === "bun" + ? "add --dev" + : "install --save-dev"; + const workspaceFlags = { + npm: "", + pnpm: " --workspace-root", + yarn: " -W", + bun: "", + nub: " --workspace-root", + }; + const workspaceFlag = isWorkspaceRoot ? workspaceFlags[packageManager] : ""; + return `${packageManager} ${command} @cloudflare/vite-plugin@beta ${packageName}${workspaceFlag}`; +} diff --git a/packages/autoconfig/src/frameworks/react-router.ts b/packages/autoconfig/src/frameworks/react-router.ts index a6c7c82409..47b202a3c3 100644 --- a/packages/autoconfig/src/frameworks/react-router.ts +++ b/packages/autoconfig/src/frameworks/react-router.ts @@ -10,6 +10,7 @@ import dedent from "ts-dedent"; import { Framework } from "./framework-class"; import { transformViteConfig } from "./utils/vite-config"; import { installCloudflareVitePlugin } from "./utils/vite-plugin"; +import { CF_VITE_PLUGIN_VERSION_RANGE } from "./utils/vite-plugin-version"; import type { AutoConfigContext } from "../context"; import type { ConfigurationOptions, @@ -490,7 +491,7 @@ export class ReactRouter extends Framework { packageManager: packageManager.type, projectPath, isWorkspaceRoot, - version: target === "cf" ? "^2.0.0-beta.v.0" : undefined, + version: target === "cf" ? CF_VITE_PLUGIN_VERSION_RANGE : undefined, }); mkdirSync("workers"); diff --git a/packages/autoconfig/src/frameworks/solid-start.ts b/packages/autoconfig/src/frameworks/solid-start.ts index 87630b09cd..625a4174b1 100644 --- a/packages/autoconfig/src/frameworks/solid-start.ts +++ b/packages/autoconfig/src/frameworks/solid-start.ts @@ -16,6 +16,7 @@ import { transformViteConfig, } from "./utils/vite-config"; import { installCloudflareVitePlugin } from "./utils/vite-plugin"; +import { CF_VITE_PLUGIN_VERSION_RANGE } from "./utils/vite-plugin-version"; import type { AutoConfigContext } from "../context"; import type { ConfigurationOptions, @@ -39,7 +40,7 @@ export class SolidStart extends Framework { packageManager: packageManager.type, isWorkspaceRoot, projectPath, - version: "^2.0.0-beta.v.0", + version: CF_VITE_PLUGIN_VERSION_RANGE, }); transformViteConfig(projectPath); excludeSolidStartFromServerPrebundling(projectPath, context); diff --git a/packages/autoconfig/src/frameworks/tanstack.ts b/packages/autoconfig/src/frameworks/tanstack.ts index 1cdafc6ea5..4f21912f44 100644 --- a/packages/autoconfig/src/frameworks/tanstack.ts +++ b/packages/autoconfig/src/frameworks/tanstack.ts @@ -1,6 +1,7 @@ import { Framework } from "./framework-class"; import { transformViteConfig } from "./utils/vite-config"; import { installCloudflareVitePlugin } from "./utils/vite-plugin"; +import { CF_VITE_PLUGIN_VERSION_RANGE } from "./utils/vite-plugin-version"; import type { ConfigurationOptions, ConfigurationResults, @@ -23,7 +24,7 @@ export class TanstackStart extends Framework { packageManager: packageManager.type, isWorkspaceRoot, projectPath, - version: target === "cf" ? "^2.0.0-beta.v.0" : undefined, + version: target === "cf" ? CF_VITE_PLUGIN_VERSION_RANGE : undefined, }); transformViteConfig(projectPath, { viteEnvironmentName: "ssr" }); diff --git a/packages/autoconfig/src/frameworks/utils/vite-config.ts b/packages/autoconfig/src/frameworks/utils/vite-config.ts index 50dfda8d64..e853da48d8 100644 --- a/packages/autoconfig/src/frameworks/utils/vite-config.ts +++ b/packages/autoconfig/src/frameworks/utils/vite-config.ts @@ -64,6 +64,7 @@ function extractFromBlockStatement( return null; } +/** Recognizes existing plugin setup without reconfiguring legacy Wrangler projects. */ export function checkIfViteConfigUsesCloudflarePlugin( projectPath: string, context?: AutoConfigContext @@ -142,14 +143,20 @@ export function checkIfViteConfigUsesCloudflarePlugin( return importsCloudflarePlugin && usesCloudflarePlugin; } -/** - * Returns whether a Vite config file (`vite.config.ts` or `vite.config.js`) - * exists in the given project directory. - */ +// Match Vite's DEFAULT_CONFIG_FILES order so inspection and execution use the same file. +const VITE_CONFIG_FILES = [ + "vite.config.js", + "vite.config.mjs", + "vite.config.ts", + "vite.config.cjs", + "vite.config.mts", + "vite.config.cts", +]; + +/** Returns whether the project has a Vite configuration file. */ export function hasViteConfig(projectPath: string): boolean { - return ( - existsSync(path.join(projectPath, "vite.config.ts")) || - existsSync(path.join(projectPath, "vite.config.js")) + return VITE_CONFIG_FILES.some((name) => + existsSync(path.join(projectPath, name)) ); } @@ -157,24 +164,17 @@ export function hasViteConfig(projectPath: string): boolean { * Finds the project's Vite config file. * * @param projectPath The path of the project - * @returns The path of `vite.config.ts`, or of `vite.config.js` if there is no TypeScript config - * @throws If the project has neither + * @returns The first existing file in Vite's default configuration-file order + * @throws If the project has no Vite config file */ export function getViteConfigPath(projectPath: string): string { - const filePathTS = path.join(projectPath, `vite.config.ts`); - const filePathJS = path.join(projectPath, `vite.config.js`); - - let filePath: string; - - if (existsSync(filePathTS)) { - filePath = filePathTS; - } else if (existsSync(filePathJS)) { - filePath = filePathJS; - } else { + const file = VITE_CONFIG_FILES.map((name) => + path.join(projectPath, name) + ).find((filePath) => existsSync(filePath)); + if (!file) { throw new Error("Could not find Vite config file to modify"); } - - return filePath; + return file; } /** @@ -208,6 +208,19 @@ function hasIdentifierOutsideImport( return hasIdentifier; } +/** Checks unsupported CommonJS files before setup installs or changes any files. */ +export function assertViteConfigCanBeTransformed(projectPath: string): void { + const filePath = getViteConfigPath(projectPath); + if ([".cjs", ".cts"].includes(path.extname(filePath))) { + // Vite bundles these extensions as CommonJS even when they use ESM syntax. + // The Cloudflare plugin only exposes an ESM import entry point. + throw new UserError( + "Cannot automatically modify a CommonJS Vite configuration. Convert it to ESM (import/export) in vite.config.mjs or vite.config.mts before adding the Cloudflare plugin.", + { telemetryMessage: "autoconfig CommonJS vite config unsupported" } + ); + } +} + export function transformViteConfig( projectPath: string, options: { @@ -216,6 +229,7 @@ export function transformViteConfig( } = {} ) { const filePath = getViteConfigPath(projectPath); + assertViteConfigCanBeTransformed(projectPath); const removedIncompatiblePlugins = new Set(); transformFile(filePath, { diff --git a/packages/autoconfig/src/frameworks/utils/vite-plugin-version.ts b/packages/autoconfig/src/frameworks/utils/vite-plugin-version.ts new file mode 100644 index 0000000000..23921ab90b --- /dev/null +++ b/packages/autoconfig/src/frameworks/utils/vite-plugin-version.ts @@ -0,0 +1,5 @@ +/** + * The `@cloudflare/vite-plugin` versions that support the configuration + * generated for `cf`: the v2 release candidates and every later v2 release. + */ +export const CF_VITE_PLUGIN_VERSION_RANGE = "^2.0.0-rc.0"; diff --git a/packages/autoconfig/src/frameworks/vite.ts b/packages/autoconfig/src/frameworks/vite.ts index e0b8bdced0..e613f81b0b 100644 --- a/packages/autoconfig/src/frameworks/vite.ts +++ b/packages/autoconfig/src/frameworks/vite.ts @@ -3,11 +3,13 @@ import { join } from "node:path"; import { usesTypescript } from "../uses-typescript"; import { Framework } from "./framework-class"; import { + assertViteConfigCanBeTransformed, checkIfViteConfigUsesCloudflarePlugin, hasViteConfig, transformViteConfig, } from "./utils/vite-config"; import { installCloudflareVitePlugin } from "./utils/vite-plugin"; +import { CF_VITE_PLUGIN_VERSION_RANGE } from "./utils/vite-plugin-version"; import type { AutoConfigTarget } from "../context"; import type { ConfigurationOptions, @@ -41,12 +43,15 @@ export class Vite extends Framework { isWorkspaceRoot, target, }: ConfigurationOptions): Promise { + if (hasViteConfig(projectPath)) { + assertViteConfigCanBeTransformed(projectPath); + } if (!dryRun) { await installCloudflareVitePlugin({ packageManager: packageManager.type, isWorkspaceRoot, projectPath, - version: target === "cf" ? "^2.0.0-beta.v.0" : undefined, + version: target === "cf" ? CF_VITE_PLUGIN_VERSION_RANGE : undefined, }); if (hasViteConfig(projectPath)) { diff --git a/packages/autoconfig/src/index.ts b/packages/autoconfig/src/index.ts index d925f29d32..9d79dc3356 100644 --- a/packages/autoconfig/src/index.ts +++ b/packages/autoconfig/src/index.ts @@ -5,7 +5,10 @@ export type { AutoConfigDialogs, } from "./context"; -export { getDetailsForAutoConfig } from "./details"; +export { + getDetailsForAutoConfig, + assertProjectCommandsAvailable, +} from "./details"; export { runAutoConfig, buildOperationsSummary } from "./run"; export { Framework } from "./frameworks/framework-class"; @@ -27,6 +30,7 @@ export { displayAutoConfigDetails, confirmAutoConfigDetails } from "./details"; export type { AutoConfigDetails, + AutoConfigCommandError, AutoConfigDetailsForConfiguredProject, AutoConfigDetailsForNonConfiguredProject, AutoConfigOptions, diff --git a/packages/autoconfig/src/run.ts b/packages/autoconfig/src/run.ts index a6baae2440..7067d8cd0e 100644 --- a/packages/autoconfig/src/run.ts +++ b/packages/autoconfig/src/run.ts @@ -11,7 +11,10 @@ import { installPackages, installWrangler, } from "@cloudflare/cli-shared-helpers/packages"; -import { convertToWranglerConfig, InputConfigSchema } from "@cloudflare/config"; +import { + convertToWranglerConfig, + CloudflareConfigSchema, +} from "@cloudflare/config"; import { DEFAULT_COMPAT_DATE, FatalError, @@ -20,9 +23,11 @@ import { } from "@cloudflare/workers-utils"; import { assertNonConfigured, + assertProjectCommandsAvailable, confirmAutoConfigDetails, displayAutoConfigDetails, getProjectCommand, + getDetailsForAutoConfig, } from "./details"; import { isFrameworkSupported, @@ -32,6 +37,7 @@ import { } from "./frameworks"; import { getFrameworkPackageInfo } from "./frameworks/all-frameworks"; import { Static } from "./frameworks/static"; +import { CF_VITE_PLUGIN_VERSION_RANGE } from "./frameworks/utils/vite-plugin-version"; import { CLOUDFLARE_TYPES_INCLUDE, getCloudflareTypesTsconfigUpdate, @@ -168,7 +174,10 @@ export async function runAutoConfig( const { npx } = packageManager; let buildCommand = dryRunConfigurationResults.buildCommandOverride ?? - autoConfigDetails.buildCommand; + autoConfigDetails.buildCommand ?? + (autoConfigDetails.commandError && autoConfigDetails.framework.id === "vite" + ? "vite build" + : undefined); // Preserve shell commands while normalizing Vite selected by framework overrides. if (buildCommand === "vite build" || buildCommand === `${npx} vite build`) { buildCommand = getProjectCommand( @@ -360,6 +369,29 @@ export async function runAutoConfig( } } + // Setup can install missing packages or activate the plugin. Recheck command + // readiness after those changes, only when a build will actually be executed. + if (target === "cf" && runBuild && autoConfigDetails.commandError) { + const configuredDetails = await getDetailsForAutoConfig({ + projectPath: autoConfigDetails.projectPath, + target, + context, + }); + assertProjectCommandsAvailable(configuredDetails); + buildCommand = + configurationResults.buildCommandOverride ?? + configuredDetails.buildCommand ?? + buildCommand; + if (buildCommand === "vite build" || buildCommand === `${npx} vite build`) { + buildCommand = getProjectCommand( + buildCommand, + packageManager, + configuredDetails.packageJson, + target + ); + } + autoConfigSummary.buildCommand = buildCommand; + } if (buildCommand && runBuild) { await context.runCommand( buildCommand, @@ -402,7 +434,7 @@ function getWranglerConfig( return null; } - const parsedConfig = InputConfigSchema.parse({ worker: workerConfig }); + const parsedConfig = CloudflareConfigSchema.parse({ worker: workerConfig }); const convertedWranglerConfig = convertToWranglerConfig(parsedConfig); const wranglerConfig = ensureNodejsCompatIsEnabled({ $schema: "node_modules/wrangler/config-schema.json", @@ -610,7 +642,7 @@ export async function buildOperationsSummary( if (configurationResults.buildTool === "vite") { packagesToInstall.add( target === "cf" - ? "@cloudflare/vite-plugin@^2.0.0-beta.v.0" + ? `@cloudflare/vite-plugin@${CF_VITE_PLUGIN_VERSION_RANGE}` : "@cloudflare/vite-plugin" ); } else if ( diff --git a/packages/autoconfig/src/types.ts b/packages/autoconfig/src/types.ts index 05fe65766f..9a8f92d9bd 100644 --- a/packages/autoconfig/src/types.ts +++ b/packages/autoconfig/src/types.ts @@ -8,6 +8,15 @@ import type { PackageJSON, RawConfig } from "@cloudflare/workers-utils"; /** Makes the specified keys of T optional. */ type Optional = Omit & Partial>; +/** Why detected project commands cannot currently be executed. */ +export type AutoConfigCommandError = { + code: + | "vite-plugin-not-installed" + | "vite-plugin-incompatible" + | "vite-tool-not-installed"; + message: string; +}; + type AutoConfigDetailsBase = { /** The name of the worker */ workerName: string; @@ -23,6 +32,10 @@ type AutoConfigDetailsBase = { devCommand?: string; /** The build command used to build the project (if any) */ buildCommand?: string; + /** Command readiness failure. Detection succeeds; execution must validate this field. */ + commandError?: AutoConfigCommandError; + /** Application and enclosing workspace node_modules directories, nearest first. */ + nodeModulesPaths?: readonly string[]; /** Environment required when running the detected dev or build commands. */ env?: Readonly>; /** The output directory (if no framework is used, points to the raw asset files) */ diff --git a/packages/autoconfig/tests/details/vite-fallback-commands.test.ts b/packages/autoconfig/tests/details/vite-fallback-commands.test.ts new file mode 100644 index 0000000000..a13442ef96 --- /dev/null +++ b/packages/autoconfig/tests/details/vite-fallback-commands.test.ts @@ -0,0 +1,858 @@ +import { execSync } from "node:child_process"; +import { chmod, rm } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { removeDir } from "@cloudflare/workers-utils"; +import { + mockConsoleMethods, + runInTempDir, + seed, +} from "@cloudflare/workers-utils/test-helpers"; +import { describe, it, vi } from "vitest"; +import { + assertProjectCommandsAvailable, + getDetailsForAutoConfig, +} from "../../src/details"; +import * as frameworkDetection from "../../src/details/framework-detection"; +import { runAutoConfig } from "../../src/run"; +import { createMockContext } from "../helpers/mock-context"; +import type { Config } from "@cloudflare/workers-utils"; + +function invocation(binary: string): string { + return process.platform === "win32" + ? `"${process.execPath}" "${binary}"` + : `'${binary.replaceAll("'", "'\\''")}'`; +} + +describe("Vite-plugin fallback commands", () => { + runInTempDir(); + mockConsoleMethods(); + const context = createMockContext(); + + async function seedProject(vitePlus = false, version = "2.0.0-beta.v.13") { + const packageName = vitePlus ? "vite-plus" : "vite"; + const command = vitePlus ? "vp" : "vite"; + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "beta", + ...(vitePlus ? { "vite-plus": "1.5.0" } : {}), + wrangler: "^4.136.0", + }, + }), + "cloudflare.config.ts": "export default {};", + "vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; +export default { plugins: [cloudflare()] };`, + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version, + }), + [`node_modules/${packageName}/package.json`]: JSON.stringify({ + name: packageName, + version: "8.1.0", + bin: { [command]: "custom cli.js" }, + }), + [`node_modules/${packageName}/custom cli.js`]: "#!/usr/bin/env node\n", + }); + return resolve("node_modules", packageName, "custom cli.js"); + } + + async function omitFrameworkCommands(projectPath = process.cwd()) { + const detected = await frameworkDetection.detectFramework( + projectPath, + context, + { + target: "cf", + } + ); + vi.spyOn(frameworkDetection, "detectFramework").mockResolvedValue({ + ...detected, + detectedFramework: { + ...detected.detectedFramework, + devCommand: undefined, + buildCommand: undefined, + }, + }); + } + + it.for([false, true])( + "returns the installed native commands without detected framework commands (Vite+: %s)", + async (vitePlus, { expect }) => { + const binary = await seedProject(vitePlus); + await omitFrameworkCommands(); + const details = await getDetailsForAutoConfig({ context }); + + expect(details).toMatchObject({ + configured: true, + devCommand: `${invocation(binary)} dev`, + buildCommand: `${invocation(binary)} build`, + framework: { id: "vite", supportsMode: true }, + env: { CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true" }, + }); + } + ); + + it("preserves a detected framework's commands", async ({ expect }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ + dependencies: { astro: "6", "@cloudflare/vite-plugin": "beta" }, + }), + }); + const details = await getDetailsForAutoConfig({ context }); + + expect(details).toMatchObject({ + devCommand: "astro dev", + buildCommand: "astro build", + framework: { id: "astro" }, + }); + }); + + it("uses native commands for a configured unsupported framework", async ({ + expect, + }) => { + const binary = await seedProject(); + await seed({ + "package.json": JSON.stringify({ + dependencies: { hono: "4", "@cloudflare/vite-plugin": "beta" }, + scripts: { dev: "cf dev", build: "cf build" }, + }), + }); + const details = await getDetailsForAutoConfig({ context }); + + expect(details.devCommand).toBe(`${invocation(binary)} dev`); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + }); + + it("can plan setup for an undetected project before the plugin is configured", async ({ + expect, + }) => { + const binary = await seedProject(); + await rm("cloudflare.config.ts"); + await rm("vite.config.ts"); + const details = await getDetailsForAutoConfig({ context }); + + expect(details).toMatchObject({ + configured: false, + framework: { id: "vite" }, + devCommand: `${invocation(binary)} dev`, + buildCommand: `${invocation(binary)} build`, + outputDir: "dist", + commandError: undefined, + }); + }); + + it.for(["config", "cache", "functions"] as const)( + "preserves Pages detected from %s instead of migrating it through Vite", + async (detection, { expect }) => { + await seedProject(); + await rm("cloudflare.config.ts"); + await rm("vite.config.ts"); + const cacheFolder = resolve(".cache"); + await seed({ + "public/index.html": "

Pages

", + ...(detection === "cache" ? { ".cache/pages.json": "{}" } : {}), + ...(detection === "functions" + ? { "functions/hello.js": "export function onRequest() {}" } + : {}), + }); + const pagesContext = createMockContext({ + getCacheFolder: () => cacheFolder, + }); + const options = { + context: pagesContext, + ...(detection === "config" + ? { wranglerConfig: { pages_build_output_dir: "public" } as Config } + : {}), + }; + const details = await getDetailsForAutoConfig(options); + + expect(details).toMatchObject({ + configured: false, + framework: { id: "cloudflare-pages" }, + outputDir: "public", + devCommand: undefined, + buildCommand: undefined, + env: undefined, + }); + await expect( + runAutoConfig(details, { + target: "cf", + context: pagesContext, + dryRun: true, + }) + ).rejects.toThrow( + "Automatically migrating from a Pages project to Workers is not yet supported" + ); + + await removeDir("node_modules"); + await expect(getDetailsForAutoConfig(options)).resolves.toMatchObject({ + framework: { id: "cloudflare-pages" }, + devCommand: undefined, + buildCommand: undefined, + }); + } + ); + + it("preserves Pages detection even with a Cloudflare config", async ({ + expect, + }) => { + await seedProject(); + const details = await getDetailsForAutoConfig({ + context, + wranglerConfig: { pages_build_output_dir: "public" } as Config, + }); + + expect(details).toMatchObject({ + configured: true, + framework: { id: "cloudflare-pages" }, + devCommand: undefined, + buildCommand: undefined, + }); + }); + + it("retains the non-interactive guard for Pages Functions with root assets", async ({ + expect, + }) => { + await seedProject(); + await rm("cloudflare.config.ts"); + await rm("vite.config.ts"); + await seed({ + "index.html": "

Pages

", + "functions/hello.js": "export function onRequest() {}", + }); + const ciContext = createMockContext({ isNonInteractiveOrCI: () => true }); + ciContext.dialogs.confirm = async () => false; + + await expect( + getDetailsForAutoConfig({ context: ciContext }) + ).rejects.toThrow( + "Automatic configuration cannot migrate Pages Functions to Workers yet" + ); + }); + + it.for([ + ["hono", "hono", "4"], + ["hydrogen", "@shopify/hydrogen", "2026.1.0"], + ] as const)( + "does not auto-configure unsupported %s through Vite", + async ([id, pkg, version], { expect }) => { + await seedProject(); + await rm("cloudflare.config.ts"); + await seed({ + "package.json": JSON.stringify({ + dependencies: { [pkg]: version, "@cloudflare/vite-plugin": "beta" }, + }), + "public/index.html": "

Unsupported framework

", + }); + const details = await getDetailsForAutoConfig({ context }); + + expect(details).toMatchObject({ + configured: false, + framework: { id }, + devCommand: undefined, + buildCommand: undefined, + }); + await expect( + runAutoConfig(details, { target: "cf", context, dryRun: true }) + ).rejects.toThrow("cannot be automatically configured"); + } + ); + + it.for([ + ["angular", "@angular/cli", "22"], + ["nuxt", "nuxt", "4"], + ] as const)( + "retains the cf support check for %s", + async ([id, pkg, version], { expect }) => { + await seedProject(); + await rm("cloudflare.config.ts"); + await seed({ + "package.json": JSON.stringify({ + dependencies: { [pkg]: version, "@cloudflare/vite-plugin": "beta" }, + }), + "public/index.html": "

Wrangler-only framework

", + }); + const details = await getDetailsForAutoConfig({ context }); + + expect(details.framework.id).toBe(id); + await expect( + runAutoConfig(details, { target: "cf", context, dryRun: true }) + ).rejects.toThrow("You can still use Wrangler"); + } + ); + + it("does not replace an unconfigured unknown framework with Vite", async ({ + expect, + }) => { + await seedProject(); + await rm("cloudflare.config.ts"); + await seed({ + "package.json": JSON.stringify({ + dependencies: { gatsby: "5", "@cloudflare/vite-plugin": "beta" }, + }), + "public/index.html": "

Gatsby

", + }); + const details = await getDetailsForAutoConfig({ context }); + + expect(details).toMatchObject({ + configured: false, + framework: { id: "static" }, + devCommand: undefined, + buildCommand: undefined, + }); + }); + + it.for([ + "1.61.0", + "2.0.0-beta.1", + "2.0.0-beta.v.12", + "2.0.0-beta.v.12+build.100", + "3.0.0-beta.1", + "invalid", + ])( + "reports an incompatible plugin %s without failing detection", + async (version, { expect }) => { + await seedProject(false, version); + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError?.code).toBe("vite-plugin-incompatible"); + expect(() => assertProjectCommandsAvailable(details)).toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + ); + } + ); + + it("does not take an executable from a parent project", async ({ + expect, + }) => { + await seedProject(); + await seed({ + "child/package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + "child/cloudflare.config.ts": "export default {};", + "child/node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify( + { + name: "@cloudflare/vite-plugin", + version: "2.0.0-beta.v.13", + } + ), + }); + + const details = await getDetailsForAutoConfig({ + projectPath: resolve("child"), + context, + }); + expect(details.commandError?.code).toBe("vite-tool-not-installed"); + expect(details.nodeModulesPaths).toEqual([resolve("child/node_modules")]); + }); + + it("does not take the plugin from a parent project", async ({ expect }) => { + await seedProject(); + await seed({ + "child/package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + "child/cloudflare.config.ts": "export default {};", + }); + + const details = await getDetailsForAutoConfig({ + projectPath: resolve("child"), + context, + }); + expect(details.commandError?.code).toBe("vite-plugin-not-installed"); + expect(details.configured).toBe(true); + expect(details.devCommand).toBeUndefined(); + }); + + it("reports which Vite+ tool needs installing", async ({ expect }) => { + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": "beta", + "vite-plus": "1", + }, + }), + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-beta.v.13", + }), + }); + + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError?.message).toContain( + "npm install --save-dev @cloudflare/vite-plugin@beta vite-plus" + ); + }); + + it.for([ + ["npm", "package-lock.json", "install --save-dev"], + ["pnpm", "pnpm-lock.yaml", "install --save-dev"], + ["yarn", "yarn.lock", "add --dev"], + ["bun", "bun.lock", "add --dev"], + ["nub", "nub.lock", "install --save-dev"], + ])( + "uses %s in dependency repair guidance", + async ([manager, lockFile, command], { expect }) => { + await seedProject(); + await seed({ [lockFile]: "" }); + await removeDir("node_modules/@cloudflare/vite-plugin"); + const details = await getDetailsForAutoConfig({ context }); + expect(details.packageManager.type).toBe(manager); + expect(details.commandError?.message).toContain( + `Run ${manager} ${command} @cloudflare/vite-plugin@beta vite.` + ); + } + ); + + it.for([ + ["pnpm", "pnpm-lock.yaml", "install --save-dev", "--workspace-root"], + ["yarn", "yarn.lock", "add --dev", "-W"], + ["nub", "nub.lock", "install --save-dev", "--workspace-root"], + ])( + "includes the %s workspace-root flag in repair guidance", + async ([manager, lockFile, command, flag], { expect }) => { + await seedProject(); + await seed({ + [lockFile]: "", + "package.json": JSON.stringify({ + workspaces: ["apps/*", "."], + devDependencies: { "@cloudflare/vite-plugin": "beta", vite: "*" }, + }), + ...(manager === "yarn" + ? {} + : { "pnpm-workspace.yaml": "packages: ['apps/*', '.']\n" }), + "apps/site/package.json": JSON.stringify({ name: "site" }), + }); + await removeDir("node_modules/@cloudflare/vite-plugin"); + const details = await getDetailsForAutoConfig({ context }); + expect(details.isWorkspaceRoot).toBe(true); + expect(details.packageManager.type).toBe(manager); + expect(details.commandError?.message).toContain( + `Run ${manager} ${command} @cloudflare/vite-plugin@beta vite ${flag}.` + ); + } + ); + + it.for([false, true])( + "uses tools declared only at the validated workspace root (Vite+: %s)", + async (vitePlus, { expect }) => { + const binary = await seedProject(vitePlus); + await seed({ + "package.json": JSON.stringify({ + workspaces: ["apps/*"], + devDependencies: { + "@cloudflare/vite-plugin": "beta", + [vitePlus ? "vite-plus" : "vite"]: "*", + }, + }), + "apps/site/package.json": JSON.stringify({ name: "site" }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/vite.config.ts": + "import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };", + }); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBe(`${invocation(binary)} dev`); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + + await removeDir("node_modules/@cloudflare/vite-plugin"); + const missing = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(missing.commandError?.code).toBe("vite-plugin-not-installed"); + } + ); + + it.for([false, true])( + "uses a custom config with an app plugin declaration and root tooling (Vite+: %s)", + async (vitePlus, { expect }) => { + const binary = await seedProject(vitePlus); + await seed({ + "package.json": JSON.stringify({ + workspaces: ["apps/*"], + devDependencies: { + "@cloudflare/vite-plugin": "beta", + [vitePlus ? "vite-plus" : "vite"]: "*", + }, + }), + "apps/site/package.json": JSON.stringify({ name: "site" }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/site.vite.config.ts": + "import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };", + }); + const projectPath = resolve("apps/site"); + // No application-level Vite signal distinguishes this from a non-Vite + // sibling. Custom paths passed later via --config cannot be inferred. + const ambiguous = await getDetailsForAutoConfig({ projectPath, context }); + expect(ambiguous.devCommand).toBeUndefined(); + expect(ambiguous.buildCommand).toBeUndefined(); + + await seed({ + "apps/site/package.json": JSON.stringify({ + name: "site", + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + }); + const details = await getDetailsForAutoConfig({ projectPath, context }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBe(`${invocation(binary)} dev`); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + } + ); + + it("does not select shared Vite tools for a configured non-Vite sibling", async ({ + expect, + }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ + workspaces: ["apps/*"], + devDependencies: { "@cloudflare/vite-plugin": "beta", vite: "*" }, + }), + "apps/site/package.json": JSON.stringify({ name: "site" }), + "apps/site/vite.config.ts": "export default {};", + "apps/api/package.json": JSON.stringify({ + name: "api", + main: "src/index.ts", + }), + "apps/api/cloudflare.config.ts": "export default {};", + "apps/api/src/index.ts": + "export default { fetch() { return new Response('API'); } };", + }); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/api"), + context, + }); + expect(details.configured).toBe(true); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBeUndefined(); + expect(details.buildCommand).toBeUndefined(); + }); + + it.for(["peerDependencies", "optionalDependencies"])( + "prefers a concrete Vite dependency over Vite+ in %s", + async (dependencyType, { expect }) => { + const binary = await seedProject(); + await seed({ + "package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta", vite: "*" }, + [dependencyType]: { "vite-plus": "*" }, + peerDependenciesMeta: { "vite-plus": { optional: true } }, + }), + }); + await omitFrameworkCommands(); + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBe(`${invocation(binary)} dev`); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + } + ); + + it.for([true, false])( + "does not inherit root tooling for an unconfigured or excluded application (workspace member: %s)", + async (workspaceMember, { expect }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ + workspaces: [workspaceMember ? "apps/*" : "other/*"], + devDependencies: { "@cloudflare/vite-plugin": "beta", vite: "*" }, + }), + "apps/site/package.json": JSON.stringify({ name: "site" }), + "apps/site/public/index.html": "

Site

", + ...(!workspaceMember + ? { "apps/site/cloudflare.config.ts": "export default {};" } + : {}), + }); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBeUndefined(); + expect(details.buildCommand).toBeUndefined(); + } + ); + + it("prefers an application's declared Vite runner over workspace Vite+", async ({ + expect, + }) => { + await seedProject(true); + await seed({ + "package.json": JSON.stringify({ + workspaces: ["apps/*"], + devDependencies: { + "@cloudflare/vite-plugin": "beta", + "vite-plus": "*", + }, + }), + "apps/site/package.json": JSON.stringify({ + name: "site", + devDependencies: { vite: "*" }, + }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/node_modules/vite/package.json": JSON.stringify({ + bin: { vite: "local.js" }, + }), + "apps/site/node_modules/vite/local.js": "#!/usr/bin/env node\n", + }); + await omitFrameworkCommands(resolve("apps/site")); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.buildCommand).toBe( + `${invocation(resolve("apps/site/node_modules/vite/local.js"))} build` + ); + }); + + it.for([false, true])( + "resolves hoisted workspace tools (Vite+: %s)", + async (vitePlus, { expect }) => { + const binary = await seedProject(vitePlus); + await seed({ + "package.json": JSON.stringify({ workspaces: ["apps/*"] }), + "apps/site/package.json": JSON.stringify({ + name: "site", + devDependencies: { + "@cloudflare/vite-plugin": "beta", + ...(vitePlus ? { "vite-plus": "1.5.0" } : {}), + }, + }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };`, + }); + await omitFrameworkCommands(resolve("apps/site")); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.commandError).toBeUndefined(); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + expect(details.nodeModulesPaths).toEqual([ + resolve("apps/site/node_modules"), + resolve("apps/node_modules"), + resolve("node_modules"), + ]); + } + ); + + it("does not use a workspace that excludes the application", async ({ + expect, + }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ workspaces: ["other/*"] }), + "apps/site/package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + "apps/site/cloudflare.config.ts": "export default {};", + }); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.commandError?.code).toBe("vite-plugin-not-installed"); + expect(details.nodeModulesPaths).toEqual([ + resolve("apps/site/node_modules"), + ]); + }); + + it("prefers the application's tool over a hoisted tool", async ({ + expect, + }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ workspaces: ["apps/*"] }), + "apps/site/package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + "apps/site/cloudflare.config.ts": "export default {};", + "apps/site/vite.config.ts": `import { cloudflare } from '@cloudflare/vite-plugin'; export default { plugins: [cloudflare()] };`, + "apps/site/node_modules/vite/package.json": JSON.stringify({ + bin: { vite: "local.js" }, + }), + "apps/site/node_modules/vite/local.js": "#!/usr/bin/env node\n", + }); + const details = await getDetailsForAutoConfig({ + projectPath: resolve("apps/site"), + context, + }); + expect(details.buildCommand).toBe( + `${invocation(resolve("apps/site/node_modules/vite/local.js"))} build` + ); + }); + + it("checks plugin compatibility for canonical framework commands too", async ({ + expect, + }) => { + await seedProject(false, "1.0.0"); + await seed({ + "package.json": JSON.stringify({ + dependencies: { astro: "6", "@cloudflare/vite-plugin": "beta" }, + }), + }); + const details = await getDetailsForAutoConfig({ context }); + expect(details.framework?.id).toBe("astro"); + expect(() => assertProjectCommandsAvailable(details)).toThrow( + "cf requires @cloudflare/vite-plugin >=2.0.0-beta.v.13 <3" + ); + }); + + it.for([ + undefined, + "export default { plugins: [] };", + "export default { plugins: [cloudflare()].filter(Boolean) };", + "const plugins = [cloudflare()]; export default { plugins };", + "export default mergeConfig(base, { plugins: [cloudflare()] });", + "export default vite.defineConfig({ plugins: [cloudflare()] });", + "throw new Error('Config must not be executed during detection');", + "invalid config syntax {{", + ])("leaves config evaluation to Vite: %s", async (config, { expect }) => { + const binary = await seedProject(); + if (config === undefined) { + await rm("vite.config.ts"); + } else { + await seed({ "vite.config.ts": config }); + } + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBe(`${invocation(binary)} dev`); + expect(details.buildCommand).toBe(`${invocation(binary)} build`); + }); + + it.for([false, true])( + "preserves canonical commands with a dynamic config (Vite+: %s)", + async (vitePlus, { expect }) => { + await seedProject(vitePlus); + await seed({ + "package.json": JSON.stringify({ + devDependencies: { + [vitePlus ? "vite-plus" : "vite"]: vitePlus ? "1.5.0" : "8.1.0", + "@cloudflare/vite-plugin": "beta", + }, + }), + "vite.config.ts": + "export default vite.defineConfig({ plugins: [cloudflare()].filter(Boolean) });", + }); + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError).toBeUndefined(); + expect(details.devCommand).toBe(vitePlus ? "vp dev" : "vite"); + expect(details.buildCommand).toBe(vitePlus ? "vp build" : "vite build"); + } + ); + + it.for([ + "2.0.0-beta.v.13", + "2.0.0-beta.v.14", + "2.0.0-beta.v.100+build.1", + "2.0.0", + "2.1.0-alpha.1", + ])( + "accepts plugin %s with cf profile support", + async (version, { expect }) => { + await seedProject(false, version); + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError).toBeUndefined(); + } + ); + + it("retains configured project details before dependencies are installed", async ({ + expect, + }) => { + await seedProject(); + await removeDir("node_modules"); + const details = await getDetailsForAutoConfig({ context }); + expect(details.configured).toBe(true); + expect(details.commandError?.code).toBe("vite-plugin-not-installed"); + expect(details.devCommand).toBeUndefined(); + expect(details.buildCommand).toBeUndefined(); + }); + + it.for(["devCommand", "buildCommand"] as const)( + "preserves partial framework commands when %s is absent", + async (missing, { expect }) => { + await seedProject(); + await seed({ + "package.json": JSON.stringify({ + dependencies: { astro: "6", "@cloudflare/vite-plugin": "beta" }, + }), + }); + const detected = await frameworkDetection.detectFramework( + process.cwd(), + context, + { target: "cf" } + ); + vi.spyOn(frameworkDetection, "detectFramework").mockResolvedValue({ + ...detected, + detectedFramework: { + ...detected.detectedFramework, + [missing]: undefined, + }, + }); + const details = await getDetailsForAutoConfig({ context }); + expect(details.framework?.id).toBe("astro"); + expect(details.env).toEqual(detected.detectedFramework.framework.env); + expect(details[missing]).toBeUndefined(); + expect( + details[missing === "devCommand" ? "buildCommand" : "devCommand"] + ).toBe(missing === "devCommand" ? "astro build" : "astro dev"); + } + ); + + it.for([false, true])( + "executes native commands through the platform shell (Vite+: %s)", + async (vitePlus, { expect }) => { + const binary = await seedProject(vitePlus); + await seed({ + [binary]: + "#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify(process.argv.slice(2)));", + }); + await chmod(binary, 0o755); + await omitFrameworkCommands(); + const details = await getDetailsForAutoConfig({ context }); + if (!details.buildCommand) { + throw new Error("Expected a runnable build command"); + } + // Exercise the shell contract used by Wrangler's runCommand, including cmd.exe on Windows. + expect(execSync(details.buildCommand, { encoding: "utf8" })).toBe( + '["build"]' + ); + } + ); + + it("does not add commands for Wrangler static projects", async ({ + expect, + }) => { + await seedProject(); + await rm("vite.config.ts"); + await seed({ "public/index.html": "

Static

" }); + const details = await getDetailsForAutoConfig({ + target: "wrangler", + context, + }); + + expect(details.devCommand).toBeUndefined(); + expect(details.buildCommand).toBeUndefined(); + }); + + it("does not replace an explicit assets-directory workflow", async ({ + expect, + }) => { + await seed({ + "package.json": JSON.stringify({ + devDependencies: { "@cloudflare/vite-plugin": "beta" }, + }), + "public/index.html": "

Static

", + }); + const details = await getDetailsForAutoConfig({ + outputDir: join(process.cwd(), "public"), + context, + }); + + expect(details.devCommand).toBeUndefined(); + expect(details.buildCommand).toBeUndefined(); + }); +}); diff --git a/packages/autoconfig/tests/frameworks/solid-start.test.ts b/packages/autoconfig/tests/frameworks/solid-start.test.ts index aecb260702..f9750d0179 100644 --- a/packages/autoconfig/tests/frameworks/solid-start.test.ts +++ b/packages/autoconfig/tests/frameworks/solid-start.test.ts @@ -61,7 +61,7 @@ describe("SolidStart", () => { }); // `cloudflare()` relies on plugin v2 defaulting to the `ssr` environment expect(installCloudflareVitePlugin).toHaveBeenCalledWith( - expect.objectContaining({ version: "^2.0.0-beta.v.0" }) + expect.objectContaining({ version: "^2.0.0-rc.0" }) ); expect(readFileSync("vite.config.ts", "utf8")).toMatchInlineSnapshot(` "import { defineConfig } from "vite"; diff --git a/packages/autoconfig/tests/frameworks/vite.test.ts b/packages/autoconfig/tests/frameworks/vite.test.ts index 58a9f231b9..0f07ef9bc7 100644 --- a/packages/autoconfig/tests/frameworks/vite.test.ts +++ b/packages/autoconfig/tests/frameworks/vite.test.ts @@ -39,6 +39,22 @@ describe("Vite framework", () => { expect(framework.isConfigured(".")).toBe(false); }); + it.for([ + "export default mergeConfig(base, defineConfig({ plugins: [cloudflare()] }));", + "export default () => defineConfig({ plugins: [cloudflare()] });", + "const config = defineConfig({ plugins: [cloudflare()] }); export { config as default };", + ])( + "preserves Wrangler detection of wrapped and indirect exports: %s", + async (config, { expect }) => { + await writeFile( + "vite.config.ts", + `import { cloudflare } from '@cloudflare/vite-plugin'; import { defineConfig, mergeConfig } from 'vite'; ${config}` + ); + const framework = new Vite({ id: "vite", name: "Vite" }); + expect(framework.isConfigured(".", { target: "wrangler" })).toBe(true); + } + ); + it("only treats the Cloudflare plugin as configured in legacy Wrangler mode", async ({ expect, }) => { @@ -56,6 +72,53 @@ describe("Vite framework", () => { }); describe("configure()", () => { + it.for([ + { extension: "cjs", dryRun: false }, + { extension: "cjs", dryRun: true }, + { extension: "cts", dryRun: false }, + { extension: "cts", dryRun: true }, + ])( + "rejects CommonJS source before installing (.%s)", + async ({ extension, dryRun }, { expect }) => { + const filePath = `vite.config.${extension}`; + const content = + "const { defineConfig } = require('vite'); module.exports = defineConfig({ plugins: [] });"; + await writeFile(filePath, content); + const framework = new Vite({ id: "vite", name: "Vite" }); + await expect( + framework.configure({ ...BASE_OPTIONS, dryRun }) + ).rejects.toThrow( + "Cannot automatically modify a CommonJS Vite configuration" + ); + expect(cliPackages.installPackages).not.toHaveBeenCalled(); + expect(readFileSync(filePath, "utf8")).toBe(content); + } + ); + + it.for([ + "export default defineConfig({ plugins: [] });", + "const config = defineConfig({ plugins: [] }); export default config;", + "const config = defineConfig({ plugins: [] }); export { config as default };", + "export default defineConfig({ plugins: [] }) as UserConfig;", + ])( + "rejects ESM syntax in .cts before installing: %s", + async (source, { expect }) => { + const filePath = "vite.config.cts"; + const content = `import { defineConfig, type UserConfig } from 'vite'; ${source}`; + await writeFile(filePath, content); + const framework = new Vite({ id: "vite", name: "Vite" }); + for (const dryRun of [true, false]) { + await expect( + framework.configure({ ...BASE_OPTIONS, dryRun }) + ).rejects.toThrow( + "Convert it to ESM (import/export) in vite.config.mjs or vite.config.mts" + ); + expect(cliPackages.installPackages).not.toHaveBeenCalled(); + expect(readFileSync(filePath, "utf8")).toBe(content); + } + } + ); + it("creates a vite config with the cloudflare plugin when no config file exists", async ({ expect, }) => { @@ -63,7 +126,7 @@ describe("Vite framework", () => { const result = await framework.configure(BASE_OPTIONS); expect(cliPackages.installPackages).toHaveBeenCalledWith( "npm", - ["@cloudflare/vite-plugin@^2.0.0-beta.v.0"], + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], expect.anything() ); diff --git a/packages/autoconfig/tests/run-summary.test.ts b/packages/autoconfig/tests/run-summary.test.ts index 1145631f79..77354a4f64 100644 --- a/packages/autoconfig/tests/run-summary.test.ts +++ b/packages/autoconfig/tests/run-summary.test.ts @@ -250,7 +250,7 @@ describe("autoconfig run - buildOperationsSummary()", () => { }); test.for([ - { target: "cf", plugin: "@cloudflare/vite-plugin@^2.0.0-beta.v.0" }, + { target: "cf", plugin: "@cloudflare/vite-plugin@^2.0.0-rc.0" }, { target: "wrangler", plugin: "@cloudflare/vite-plugin" }, ] as const)( "shows that $plugin will be installed for $target", diff --git a/packages/autoconfig/tests/run.test.ts b/packages/autoconfig/tests/run.test.ts index 399609a16f..badfe2f5aa 100644 --- a/packages/autoconfig/tests/run.test.ts +++ b/packages/autoconfig/tests/run.test.ts @@ -15,6 +15,7 @@ import { getDetailsForAutoConfig } from "../src/details"; import { getFrameworkClassInstance } from "../src/frameworks"; import { Framework } from "../src/frameworks/framework-class"; import { Static } from "../src/frameworks/static"; +import { Vite } from "../src/frameworks/vite"; import { runAutoConfig } from "../src/run"; import { createMockContext } from "./helpers/mock-context"; import type { @@ -64,6 +65,61 @@ describe("runAutoConfig()", () => { runInTempDir(); const std = mockConsoleMethods(); + it.for([ + { installTool: true, runBuild: true }, + { installTool: false, runBuild: true }, + { installTool: false, runBuild: false }, + ])( + "checks installed tools after setup only when building (installTool=$installTool, runBuild=$runBuild)", + async ({ installTool, runBuild }, { expect }) => { + await seed({ + "package.json": JSON.stringify({ + name: "vite-app", + devDependencies: { vite: "8.1.0", "@cloudflare/vite-plugin": "beta" }, + }), + "vite.config.ts": "export default { plugins: [] };", + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + version: "2.0.0-beta.v.13", + }), + }); + vi.spyOn(Vite.prototype, "configure").mockImplementation( + async ({ dryRun }) => { + if (!dryRun && installTool) { + await seed({ + "node_modules/vite/package.json": JSON.stringify({ + version: "8.1.0", + bin: { vite: "cli.js" }, + }), + "node_modules/vite/cli.js": "", + }); + } + return { buildTool: "vite", workerConfig: {} }; + } + ); + const context = createMockContext(); + const details = await getDetailsForAutoConfig({ context }); + expect(details.commandError?.code).toBe("vite-tool-not-installed"); + const setup = runAutoConfig(details, { + context, + skipConfirmations: true, + enableTargetCliInstallation: false, + runBuild, + }); + if (runBuild && !installTool) { + await expect(setup).rejects.toThrow( + "project's vite executable could not be found" + ); + } else { + await expect(setup).resolves.toMatchObject({ + buildCommand: "vite build", + }); + } + expect(context.runCommand).toHaveBeenCalledTimes( + runBuild && installTool ? 1 : 0 + ); + } + ); + it("updates the application manifest, not its enclosing workspace", async ({ expect, }) => { diff --git a/packages/autoconfig/tests/vite-config.test.ts b/packages/autoconfig/tests/vite-config.test.ts index e5dfb9314c..7609e5db7c 100644 --- a/packages/autoconfig/tests/vite-config.test.ts +++ b/packages/autoconfig/tests/vite-config.test.ts @@ -7,6 +7,7 @@ import { import { describe, it } from "vitest"; import { checkIfViteConfigUsesCloudflarePlugin, + hasViteConfig, transformViteConfig, } from "../src/frameworks/utils/vite-config"; import { createMockContext } from "./helpers/mock-context"; @@ -75,6 +76,27 @@ export default defineConfig({ } ); + it.for([ + ["js", "mjs"], + ["mjs", "ts"], + ["ts", "cjs"], + ["cjs", "mts"], + ["mts", "cts"], + ])( + "uses Vite's file precedence for .%s before .%s", + async ([first, second], { expect }) => { + const enabled = + "import { defineConfig } from 'vite'; import { cloudflare } from '@cloudflare/vite-plugin'; export default defineConfig({ plugins: [cloudflare()] });"; + const disabled = "export default { plugins: [] };"; + await writeFile(`vite.config.${first}`, enabled); + await writeFile(`vite.config.${second}`, disabled); + expect(checkIfViteConfigUsesCloudflarePlugin(".", context)).toBe(true); + await writeFile(`vite.config.${first}`, disabled); + await writeFile(`vite.config.${second}`, enabled); + expect(checkIfViteConfigUsesCloudflarePlugin(".", context)).toBe(false); + } + ); + it("should detect cloudflare plugin in function-based defineConfig", async ({ expect, }) => { @@ -152,6 +174,47 @@ export default defineConfig({ }); describe("transformViteConfig", () => { + it.for(["cjs", "cts"])( + "does not insert ESM imports into a .%s file even with ESM syntax", + async (extension, { expect }) => { + const filePath = `vite.config.${extension}`; + const content = + "import { defineConfig } from 'vite'; export default defineConfig({ plugins: [] });"; + await writeFile(filePath, content); + expect(() => transformViteConfig(".")).toThrow( + "Cannot automatically modify a CommonJS Vite configuration" + ); + expect(readFileSync(filePath, "utf8")).toBe(content); + } + ); + + it.for(["export type Config = {};", "export const helper = true;"])( + "rejects CommonJS exports alongside TypeScript exports: %s", + async (namedExport, { expect }) => { + const content = `${namedExport} const { defineConfig } = require('vite'); module.exports = defineConfig({ plugins: [] });`; + await writeFile("vite.config.cts", content); + expect(() => transformViteConfig(".")).toThrow( + "Cannot automatically modify a CommonJS Vite configuration" + ); + expect(readFileSync("vite.config.cts", "utf8")).toBe(content); + } + ); + + it.for(["cjs", "cts"])( + "detects .%s configurations without rewriting CommonJS", + async (extension, { expect }) => { + const filePath = `vite.config.${extension}`; + const content = + "const { defineConfig } = require('vite'); module.exports = defineConfig({ plugins: [] });"; + await writeFile(filePath, content); + expect(hasViteConfig(".")).toBe(true); + expect(() => transformViteConfig(".")).toThrow( + "Cannot automatically modify a CommonJS Vite configuration" + ); + expect(readFileSync(filePath, "utf8")).toBe(content); + } + ); + it.for([ "[overrideKey]: shared.plugins", "get plugins() { return shared.plugins; }", diff --git a/packages/build-output-utils/CHANGELOG.md b/packages/build-output-utils/CHANGELOG.md index 1d90b77673..542b53e8cb 100644 --- a/packages/build-output-utils/CHANGELOG.md +++ b/packages/build-output-utils/CHANGELOG.md @@ -1,5 +1,54 @@ # @cloudflare/build-output-utils +## 1.0.0-rc.0 + +### Major Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Release the first `1.0.0` release candidate, which reads and writes Build Output v1 + + Build Output now lives in `.cloudflare/output/v1/`. Only the `.cloudflare/output/v/` naming convention is permanent: a future breaking change to the format would use a new version directory. `readBuildOutput()` lists the version directories first and throws a `BuildOutputError` unless it finds exactly one `v1` directory. This means output written by an older or newer tool, or a stale `v0` tree left next to a fresh one, fails with a clear error instead of being misread or deployed. + + `BuildOutputError` now has a `code` (`not-found`, `newer-version`, `older-version`, `multiple-versions`, `unknown-fields` or `invalid`) plus `foundVersions`, `supportedVersions`, `producer` and `unknownFields`. Consumers can use these to show their own advice instead of parsing the message. When a config contains fields the reader doesn't support, the error lists each field and names the tool that wrote the output. + + The root `config.json` now nests account settings under `settings`, which is left out when none are set, and can record the tool that wrote the output in an optional `producer` field. `writeRootConfig()` takes an options object, matching the other `write*` functions: + + ```ts + // Before + await writeRootConfig(root, settings, buildContext); + + // After + await writeRootConfig({ + root, + settings, + buildContext, + producer: { name: "my-framework-adapter", version: "1.2.3" }, + }); + ``` + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155)]: + - @cloudflare/config@1.0.0-rc.0 + +## 0.9.14 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28)]: + - @cloudflare/config@0.32.1 + ## 0.9.13 ### Patch Changes diff --git a/packages/build-output-utils/README.md b/packages/build-output-utils/README.md index ac44889974..7028368d4e 100644 --- a/packages/build-output-utils/README.md +++ b/packages/build-output-utils/README.md @@ -1,5 +1,3 @@ # `@cloudflare/build-output-utils` Utilities for reading and writing the Build Output Specification directory (`.cloudflare/output/`). - -This is not yet stable enough for external use — APIs may change without notice. diff --git a/packages/build-output-utils/package.json b/packages/build-output-utils/package.json index a91c4a1747..56ef60eb2b 100644 --- a/packages/build-output-utils/package.json +++ b/packages/build-output-utils/package.json @@ -1,7 +1,7 @@ { "name": "@cloudflare/build-output-utils", - "version": "0.9.13", - "description": "Utilities for reading and writing the Build Output Specification directory. This is not yet stable enough for external use — APIs may change without notice.", + "version": "1.0.0-rc.0", + "description": "Utilities for reading and writing the Build Output Specification directory.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/build-output-utils#readme", "bugs": { "url": "https://github.com/cloudflare/workers-sdk/issues" @@ -42,6 +42,10 @@ "vitest": "catalog:default" }, "workers-sdk": { - "prerelease": true + "prerelease": true, + "npmPrerelease": { + "tag": "rc", + "numbered": true + } } } diff --git a/packages/build-output-utils/src/__tests__/paths.test.ts b/packages/build-output-utils/src/__tests__/paths.test.ts index ff79cce6f1..f6bcf512ae 100644 --- a/packages/build-output-utils/src/__tests__/paths.test.ts +++ b/packages/build-output-utils/src/__tests__/paths.test.ts @@ -20,7 +20,7 @@ import { describe("path constants", () => { it("expose the spec's version and root", ({ expect }) => { - expect(BUILD_OUTPUT_VERSION).toBe("v0"); + expect(BUILD_OUTPUT_VERSION).toBe("v1"); expect(BUILD_OUTPUT_ROOT).toBe(".cloudflare/output"); expect(ROOT_CONFIG_FILENAME).toBe("config.json"); expect(WORKER_CONFIG_FILENAME).toBe("worker.config.json"); @@ -31,7 +31,7 @@ describe("path constants", () => { describe("path resolvers", () => { const root = path.resolve("/project"); - const outputDir = path.join(root, ".cloudflare", "output", "v0"); + const outputDir = path.join(root, ".cloudflare", "output", "v1"); it("resolves the root config path", ({ expect }) => { expect(getRootConfigPath(root)).toBe(path.join(outputDir, "config.json")); diff --git a/packages/build-output-utils/src/__tests__/read.test.ts b/packages/build-output-utils/src/__tests__/read.test.ts index 0c582a7a47..cab0e2021d 100644 --- a/packages/build-output-utils/src/__tests__/read.test.ts +++ b/packages/build-output-utils/src/__tests__/read.test.ts @@ -1,10 +1,11 @@ import * as fsp from "node:fs/promises"; import * as path from "node:path"; import { - InputSettingsSchema, - InputWorkerSchema, - OutputContainerSchema, + SettingsSchema, + WorkerConfigSchema, + BuildOutputContainerConfigSchema, } from "@cloudflare/config"; +import { removeDir } from "@cloudflare/workers-utils"; import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; import { beforeEach, describe, it } from "vitest"; import { BuildOutputError } from "../errors"; @@ -25,34 +26,37 @@ import { writeWorkerConfig, } from "../write"; import type { BuildOutputWorker, BuildOutputWorkers } from "../read"; -import type { ParsedOutputWorkerConfig } from "@cloudflare/config"; +import type { ParsedBuildOutputWorkerConfig } from "@cloudflare/config"; -const completeManifest: ParsedOutputWorkerConfig["manifest"] = { +const completeManifest: ParsedBuildOutputWorkerConfig["manifest"] = { type: "complete", mainModule: "index.js", modules: { "index.js": { type: "esm" } }, }; -const parsedSettingsConfig = InputSettingsSchema.parse({ +const producer = { name: "@cloudflare/vite-plugin", version: "2.3.0" }; + +const parsedSettingsConfig = SettingsSchema.parse({ accountId: "1234567890", complianceRegion: "public", }); -const parsedStandardContainerConfig = OutputContainerSchema.parse({ +const parsedStandardContainerConfig = BuildOutputContainerConfigSchema.parse({ name: "api-container", image: { reference: "registry.example.com/api:latest" }, }); -const parsedDurableObjectContainerConfig = OutputContainerSchema.parse({ - name: "session-container", - schedulingPolicy: "durable-object", - images: { - default: { localReference: "session-container:latest" }, - }, -}); +const parsedDurableObjectContainerConfig = + BuildOutputContainerConfigSchema.parse({ + name: "session-container", + schedulingPolicy: "durable-object", + images: { + default: { localReference: "session-container:latest" }, + }, + }); function inputWorkerConfig(name: string) { - return InputWorkerSchema.parse({ + return WorkerConfigSchema.parse({ name, compatibilityDate: "2026-06-01", entrypoint: "index.js", @@ -128,17 +132,19 @@ async function seedWorker( describe("readBuildOutput", () => { runInTempDir(); beforeEach(async () => { - await writeRootConfig(process.cwd(), parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root: process.cwd(), + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); }); it.for([ [".cloudflare", "dir"], [".cloudflare/output", "dir"], - [".cloudflare/output/v0/workers/default/bundle/chunks/module.js", "file"], - [".cloudflare/output/v0/workers/default/assets/nested", "dir"], + [".cloudflare/output/v1", "dir"], + [".cloudflare/output/v1/workers/default/bundle/chunks/module.js", "file"], + [".cloudflare/output/v1/workers/default/assets/nested", "dir"], ] as const)( "rejects a symlink at %s", async ([relativePath, type], { expect }) => { @@ -181,8 +187,8 @@ describe("readBuildOutput", () => { expect(output.workers.default.config.name).toBe("my-worker"); }); - it.for([".cloudflare", ".cloudflare/output", ".cloudflare/output/v0"])( - "reports a missing root config when %s is absent", + it.for([".cloudflare", ".cloudflare/output", ".cloudflare/output/v1"])( + "reports missing build output when %s is absent", async (relativePath, { expect }) => { const root = process.cwd(); await fsp.rename( @@ -190,23 +196,27 @@ describe("readBuildOutput", () => { path.join(root, "old-output") ); - await expect(readBuildOutput(root)).rejects.toThrow( - /no root config found/ - ); + await expect(readBuildOutput(root)).rejects.toMatchObject({ + name: "BuildOutputError", + code: "not-found", + foundVersions: [], + supportedVersions: ["v1"], + message: `Build Output Specification: No Build Output found in ${path.join(root, ".cloudflare/output")}.`, + }); } ); - it.for([".cloudflare", ".cloudflare/output"])( - "reports a missing root config when %s is a file", + it.for([".cloudflare", ".cloudflare/output", ".cloudflare/output/v1"])( + "reports missing build output when %s is a file", async (relativePath, { expect }) => { const root = process.cwd(); const directoryPath = path.join(root, relativePath); await fsp.rename(directoryPath, path.join(root, "old-output")); await fsp.writeFile(directoryPath, ""); - await expect(readBuildOutput(root)).rejects.toThrow( - /no root config found/ - ); + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "not-found", + }); } ); @@ -217,7 +227,7 @@ describe("readBuildOutput", () => { const output = await readBuildOutput(root); const worker = output.workers.default; - expect(output.version).toBe("v0"); + expect(output.version).toBe("v1"); expect(output.root).toBe(root); expect(worker.configPath).toBe(getWorkerConfigPath(root)); expect(worker.bundleDir).toBe(getWorkerBundleDir(root)); @@ -544,16 +554,17 @@ describe("readBuildOutput", () => { it("returns the root config", async ({ expect }) => { const root = process.cwd(); await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root: root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); const { rootConfig } = await readBuildOutput(root); expect(rootConfig).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: false }, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); }); @@ -570,15 +581,16 @@ describe("readBuildOutput", () => { }) => { const root = process.cwd(); await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: true, - mode: "staging", + await writeRootConfig({ + root: root, + settings: parsedSettingsConfig, + buildContext: { isPreview: true, mode: "staging" }, }); const { rootConfig } = await readBuildOutput(root); expect(rootConfig).toEqual({ - ...parsedSettingsConfig, + settings: parsedSettingsConfig, buildContext: { isPreview: true, mode: "staging" }, }); }); @@ -588,9 +600,10 @@ describe("readBuildOutput", () => { }) => { const root = process.cwd(); await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root: root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); const { rootConfig } = await readBuildOutput(root); @@ -632,4 +645,299 @@ describe("readBuildOutput", () => { await expect(readBuildOutput(root)).rejects.toThrow(/invalid root config/); }); + + it("returns the producer recorded in the root config", async ({ expect }) => { + const root = process.cwd(); + await seedWorker(root); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + producer, + }); + + const { rootConfig } = await readBuildOutput(root); + + expect(rootConfig).toEqual({ + producer, + buildContext: { isPreview: false, mode: undefined }, + }); + }); + + it("rejects settings at the top level of the root config", async ({ + expect, + }) => { + const root = process.cwd(); + await seedWorker(root); + await fsp.writeFile( + getRootConfigPath(root), + JSON.stringify({ + accountId: "1234567890", + buildContext: { isPreview: false }, + }) + ); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "unknown-fields", + unknownFields: [{ file: "v1/config.json", path: "accountId" }], + }); + }); +}); + +describe("readBuildOutput version detection", () => { + runInTempDir(); + beforeEach(async () => { + await writeRootConfig({ + root: process.cwd(), + buildContext: { isPreview: false, mode: undefined }, + }); + await seedWorker(process.cwd()); + }); + + function getVersionDir(root: string, version: string): string { + return path.join(root, ".cloudflare/output", version); + } + + it("ignores entries that aren't version directories", async ({ expect }) => { + const root = process.cwd(); + const outputDir = path.join(root, ".cloudflare/output"); + await fsp.writeFile(path.join(outputDir, ".DS_Store"), ""); + await fsp.writeFile(path.join(outputDir, "v2"), ""); + await fsp.mkdir(path.join(outputDir, "v1-old")); + await fsp.mkdir(path.join(outputDir, "v01")); + await fsp.mkdir(path.join(outputDir, "latest")); + + const output = await readBuildOutput(root); + + expect(output.version).toBe("v1"); + }); + + it("ignores symlinks in entries that aren't version directories", async ({ + expect, + }) => { + const root = process.cwd(); + await fsp.symlink( + getVersionDir(root, "v1"), + path.join(root, ".cloudflare/output/latest"), + "dir" + ); + + const output = await readBuildOutput(root); + + expect(output.version).toBe("v1"); + }); + + it("reports multiple versions before symlinks in another version", async ({ + expect, + }) => { + const root = process.cwd(); + const staleVersionDir = getVersionDir(root, "v0"); + await fsp.mkdir(staleVersionDir); + await fsp.symlink( + getRootConfigPath(root), + path.join(staleVersionDir, "config.json"), + "file" + ); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "multiple-versions", + foundVersions: ["v0", "v1"], + }); + }); + + it("reports a newer version without checking its contents", async ({ + expect, + }) => { + const root = process.cwd(); + await fsp.rename(getVersionDir(root, "v1"), getVersionDir(root, "v2")); + await fsp.symlink( + path.join(root, "elsewhere"), + path.join(getVersionDir(root, "v2"), "linked"), + "dir" + ); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "newer-version", + foundVersions: ["v2"], + }); + }); + + it("rejects a newer version", async ({ expect }) => { + const root = process.cwd(); + await fsp.rename(getVersionDir(root, "v1"), getVersionDir(root, "v2")); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + name: "BuildOutputError", + code: "newer-version", + foundVersions: ["v2"], + supportedVersions: ["v1"], + message: + "Build Output Specification: This Build Output uses format v2, but this reader supports v1. Upgrade the tool reading it.", + }); + }); + + it("compares versions numerically", async ({ expect }) => { + const root = process.cwd(); + await fsp.rename(getVersionDir(root, "v1"), getVersionDir(root, "v10")); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "newer-version", + foundVersions: ["v10"], + }); + }); + + it("rejects an older version", async ({ expect }) => { + const root = process.cwd(); + await fsp.rename(getVersionDir(root, "v1"), getVersionDir(root, "v0")); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "older-version", + foundVersions: ["v0"], + supportedVersions: ["v1"], + message: + "Build Output Specification: This Build Output uses the older v0 format. It was written by an out-of-date build tool. Upgrade it and rebuild.", + }); + }); + + it("rejects more than one version directory", async ({ expect }) => { + const root = process.cwd(); + await fsp.mkdir(getVersionDir(root, "v10")); + await fsp.mkdir(getVersionDir(root, "v0")); + const outputDir = path.join(root, ".cloudflare/output"); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "multiple-versions", + foundVersions: ["v0", "v1", "v10"], + supportedVersions: ["v1"], + message: `Build Output Specification: Found Build Output in more than one format (v0, v1, v10) in ${outputDir}. Delete ${outputDir} and rebuild.`, + }); + }); + + it("reports an empty version directory as invalid", async ({ expect }) => { + const root = process.cwd(); + await removeDir(getVersionDir(root, "v1")); + await fsp.mkdir(getVersionDir(root, "v1")); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "invalid", + message: expect.stringMatching(/no root config found/), + }); + }); +}); + +describe("readBuildOutput unknown fields", () => { + runInTempDir(); + + async function writeJson(filePath: string, value: unknown): Promise { + await fsp.writeFile(filePath, JSON.stringify(value)); + } + + it("lists unknown Worker config fields and names the producer", async ({ + expect, + }) => { + const root = process.cwd(); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + producer, + }); + await seedWorker(root, { assets: true }); + const configPath = getWorkerConfigPath(root); + const config: unknown = JSON.parse(await fsp.readFile(configPath, "utf8")); + await writeJson(configPath, { + ...(config as object), + newOption: true, + observability: { enabled: true, newSetting: 1 }, + }); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "unknown-fields", + producer, + unknownFields: [ + { + file: "v1/workers/default/worker.config.json", + path: "observability.newSetting", + }, + { file: "v1/workers/default/worker.config.json", path: "newOption" }, + ], + message: [ + "Build Output Specification: v1/workers/default/worker.config.json contains fields this reader doesn't support:", + " - observability.newSetting", + " - newOption", + "The output was written by @cloudflare/vite-plugin 2.3.0. Upgrade the tool reading it.", + ].join("\n"), + }); + }); + + it("uses a generic message when no producer is recorded", async ({ + expect, + }) => { + const root = process.cwd(); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + }); + await seedWorker(root); + const containerDirectoryName = "api-container"; + await writeContainerConfig({ + root, + config: parsedStandardContainerConfig, + directoryName: containerDirectoryName, + }); + const configPath = getContainerConfigPath(root, containerDirectoryName); + const config: unknown = JSON.parse(await fsp.readFile(configPath, "utf8")); + await writeJson(configPath, { ...(config as object), newOption: true }); + + const error: unknown = await readBuildOutput(root).catch((e: unknown) => e); + + expect(error).toBeInstanceOf(BuildOutputError); + expect(error).toMatchObject({ + code: "unknown-fields", + producer: undefined, + unknownFields: [ + { + file: "v1/containers/api-container/container.config.json", + path: "newOption", + }, + ], + message: expect.stringMatching( + /The output was written by a newer build tool\. Upgrade the tool reading it\.$/ + ), + }); + }); + + it("names the producer for unknown root config fields", async ({ + expect, + }) => { + const root = process.cwd(); + await seedWorker(root); + await writeJson(getRootConfigPath(root), { + producer, + settings: { newSetting: "value" }, + buildContext: { isPreview: false, mode: undefined }, + }); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "unknown-fields", + producer, + unknownFields: [{ file: "v1/config.json", path: "settings.newSetting" }], + }); + }); + + it("reports unknown fields alongside other errors as invalid", async ({ + expect, + }) => { + const root = process.cwd(); + await seedWorker(root); + await writeJson(getRootConfigPath(root), { + producer, + settings: { newSetting: "value" }, + }); + + await expect(readBuildOutput(root)).rejects.toMatchObject({ + code: "invalid", + producer, + unknownFields: undefined, + message: expect.stringMatching(/invalid root config/), + }); + }); }); diff --git a/packages/build-output-utils/src/__tests__/write.test.ts b/packages/build-output-utils/src/__tests__/write.test.ts index b0fbcf91f9..9a0b2fde41 100644 --- a/packages/build-output-utils/src/__tests__/write.test.ts +++ b/packages/build-output-utils/src/__tests__/write.test.ts @@ -1,10 +1,11 @@ import * as fs from "node:fs"; import * as path from "node:path"; import { - InputSettingsSchema, - InputWorkerSchema, - OutputContainerSchema, - OutputWorkerSchema, + SettingsSchema, + WorkerConfigSchema, + BuildOutputContainerConfigSchema, + BuildOutputRootConfigSchema, + BuildOutputWorkerConfigSchema, } from "@cloudflare/config"; import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; import { describe, it } from "vitest"; @@ -24,48 +25,49 @@ import { writeWorkerConfig, } from "../write"; -const parsedWorkerConfig = InputWorkerSchema.parse({ +const parsedWorkerConfig = WorkerConfigSchema.parse({ name: "my-worker", compatibilityDate: "2026-06-01", entrypoint: "index.js", }); -const parsedSettingsConfig = InputSettingsSchema.parse({ +const parsedSettingsConfig = SettingsSchema.parse({ accountId: "1234567890", complianceRegion: "public", }); -const parsedStandardContainerConfig = OutputContainerSchema.parse({ +const parsedStandardContainerConfig = BuildOutputContainerConfigSchema.parse({ name: "api-container", image: { reference: "registry.example.com/api:latest" }, }); -const parsedDurableObjectContainerConfig = OutputContainerSchema.parse({ - name: "session-container", - schedulingPolicy: "durable-object", - images: { - default: { localReference: "session-container:latest" }, - }, -}); +const parsedDurableObjectContainerConfig = + BuildOutputContainerConfigSchema.parse({ + name: "session-container", + schedulingPolicy: "durable-object", + images: { + default: { localReference: "session-container:latest" }, + }, + }); describe("writeRootConfig", () => { runInTempDir(); - it("writes the root config.json with the shared settings", async ({ - expect, - }) => { + function readRootConfigFile(root: string): unknown { + return JSON.parse(fs.readFileSync(getRootConfigPath(root), "utf-8")); + } + + it("writes the shared settings under settings", async ({ expect }) => { const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: false }, + expect(readRootConfigFile(root)).toEqual({ + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); }); @@ -73,48 +75,94 @@ describe("writeRootConfig", () => { expect, }) => { const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: "staging", + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: "staging" }, }); - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ - ...parsedSettingsConfig, + expect(readRootConfigFile(root)).toEqual({ + settings: parsedSettingsConfig, buildContext: { isPreview: false, mode: "staging" }, }); }); - it("writes only build context when there are no settings or mode", async ({ - expect, - }) => { + it.for([ + ["not given", undefined], + ["empty", {}], + ["all undefined", { accountId: undefined, complianceRegion: undefined }], + ] as const)( + "omits settings when they are %s", + async ([, settings], { expect }) => { + const root = process.cwd(); + await writeRootConfig({ + root, + settings, + buildContext: { isPreview: true, mode: "production" }, + }); + + const contents = readRootConfigFile(root); + expect(contents).toEqual({ + buildContext: { isPreview: true, mode: "production" }, + }); + expect(contents).not.toHaveProperty("settings"); + expect(BuildOutputRootConfigSchema.parse(contents)).toEqual(contents); + } + ); + + it("writes settings when only some are set", async ({ expect }) => { const root = process.cwd(); - await writeRootConfig(root, undefined, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root, + settings: { accountId: "1234567890", complianceRegion: undefined }, + buildContext: { isPreview: false, mode: undefined }, }); - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ buildContext: { isPreview: false } }); + expect(readRootConfigFile(root)).toEqual({ + settings: { accountId: "1234567890" }, + buildContext: { isPreview: false }, + }); }); - it("writes build context when there are no settings", async ({ expect }) => { + it("writes the producer when given", async ({ expect }) => { const root = process.cwd(); - await writeRootConfig(root, undefined, { - isPreview: true, - mode: "production", + const producer = { name: "@cloudflare/vite-plugin", version: "2.3.0" }; + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, + producer, }); - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); + const contents = readRootConfigFile(root); expect(contents).toEqual({ - buildContext: { isPreview: true, mode: "production" }, + producer, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); + expect(BuildOutputRootConfigSchema.parse(contents)).toEqual(contents); + }); + + it("omits the producer when not given", async ({ expect }) => { + const root = process.cwd(); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + }); + + expect(readRootConfigFile(root)).not.toHaveProperty("producer"); + }); + + it("writes under the v1 directory", async ({ expect }) => { + const root = process.cwd(); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + }); + + expect( + fs.existsSync(path.join(root, ".cloudflare/output/v1/config.json")) + ).toBe(true); }); }); @@ -139,7 +187,7 @@ describe("writeWorkerConfig", () => { expect(contents).not.toHaveProperty("entrypoint"); expect(contents.manifest).toEqual(manifest); // The written file is a valid Build Output Specification Worker config. - expect(OutputWorkerSchema.parse(contents)).toEqual(contents); + expect(BuildOutputWorkerConfigSchema.parse(contents)).toEqual(contents); }); it("omits the manifest field when no manifest is provided", async ({ @@ -188,7 +236,7 @@ describe("writeContainerConfig", () => { fs.readFileSync(getContainerConfigPath(root, "api-container"), "utf-8") ); expect(contents).toEqual(parsedStandardContainerConfig); - expect(OutputContainerSchema.parse(contents)).toEqual(contents); + expect(BuildOutputContainerConfigSchema.parse(contents)).toEqual(contents); }); it("writes a Durable Object Container config with a local image reference", async ({ @@ -208,7 +256,7 @@ describe("writeContainerConfig", () => { ) ); expect(contents).toEqual(parsedDurableObjectContainerConfig); - expect(OutputContainerSchema.parse(contents)).toEqual(contents); + expect(BuildOutputContainerConfigSchema.parse(contents)).toEqual(contents); }); }); @@ -217,9 +265,10 @@ describe("cleanBuildOutputDir", () => { it("removes the build output directory", async ({ expect }) => { const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); const outputDir = path.join(root, BUILD_OUTPUT_ROOT); expect(fs.existsSync(outputDir)).toBe(true); @@ -227,6 +276,21 @@ describe("cleanBuildOutputDir", () => { await cleanBuildOutputDir(root); expect(fs.existsSync(outputDir)).toBe(false); }); + + it("removes every version directory", async ({ expect }) => { + const root = process.cwd(); + const staleVersionDir = path.join(root, BUILD_OUTPUT_ROOT, "v0"); + fs.mkdirSync(staleVersionDir, { recursive: true }); + await writeRootConfig({ + root, + buildContext: { isPreview: false, mode: undefined }, + }); + + await cleanBuildOutputDir(root); + + expect(fs.existsSync(staleVersionDir)).toBe(false); + expect(fs.existsSync(getRootConfigPath(root))).toBe(false); + }); }); describe("writeAssets", () => { @@ -257,9 +321,10 @@ describe("writeAssets", () => { ); fs.symlinkSync("nested", path.join(sourceDirectory, "linked"), "dir"); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); await writeWorkerConfig({ root, config: parsedWorkerConfig }); await writeAssets({ root, sourceDirectory }); @@ -286,9 +351,10 @@ describe("writeAssets", () => { fs.mkdirSync(path.join(root, "nested")); fs.writeFileSync(path.join(root, "nested/linked.html"), "linked"); fs.symlinkSync("nested", path.join(root, "linked"), "dir"); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, + await writeRootConfig({ + root, + settings: parsedSettingsConfig, + buildContext: { isPreview: false, mode: undefined }, }); await writeAssets({ root, sourceDirectory: root }); diff --git a/packages/build-output-utils/src/errors.ts b/packages/build-output-utils/src/errors.ts index 590d397435..6995652895 100644 --- a/packages/build-output-utils/src/errors.ts +++ b/packages/build-output-utils/src/errors.ts @@ -1,12 +1,69 @@ +import type { ParsedBuildOutputProducer } from "@cloudflare/config"; + const BUILD_OUTPUT_ERROR_PREFIX = "Build Output Specification: "; /** - * Thrown when the Build Output Specification tree is missing, malformed, or - * internally inconsistent. + * Why reading a Build Output Specification tree failed. + * + * - `not-found`: there is no version directory under `.cloudflare/output/`. + * - `newer-version`: the tree uses a newer format than this reader supports. + * - `older-version`: the tree uses an older format than this reader supports. + * - `multiple-versions`: more than one version directory was found. + * - `unknown-fields`: a file contains fields this reader doesn't support. + * - `invalid`: the tree is malformed or internally inconsistent. + */ +export type BuildOutputErrorCode = + | "not-found" + | "newer-version" + | "older-version" + | "multiple-versions" + | "unknown-fields" + | "invalid"; + +/** A field this reader doesn't support. */ +export interface BuildOutputUnknownField { + /** Path of the file, relative to `.cloudflare/output/`, using `/` separators. */ + file: string; + /** Dot-separated JSON path of the field within the file. */ + path: string; +} + +/** Structured details attached to a {@link BuildOutputError}. */ +export interface BuildOutputErrorOptions { + /** Defaults to `"invalid"`. */ + code?: BuildOutputErrorCode; + /** The version directories found, such as `["v2"]` or `["v0", "v1"]`. */ + foundVersions?: string[]; + /** The version directories this reader supports. */ + supportedVersions?: string[]; + /** The tool that wrote the tree, when it was recorded. */ + producer?: ParsedBuildOutputProducer; + /** The fields this reader doesn't support. */ + unknownFields?: BuildOutputUnknownField[]; +} + +/** + * Thrown when the Build Output Specification tree is missing, malformed, + * internally inconsistent, or in a format this reader doesn't support. + * + * The message is neutral about which tool is reading the tree. Consumers can + * use `code` and the other fields to render their own advice instead of + * parsing the message. */ export class BuildOutputError extends Error { - constructor(message: string) { + readonly code: BuildOutputErrorCode; + readonly foundVersions?: string[]; + readonly supportedVersions?: string[]; + readonly producer?: ParsedBuildOutputProducer; + readonly unknownFields?: BuildOutputUnknownField[]; + + constructor(message: string, options: BuildOutputErrorOptions = {}) { super(`${BUILD_OUTPUT_ERROR_PREFIX}${message}`); this.name = "BuildOutputError"; + this.code = options.code ?? "invalid"; + this.foundVersions = options.foundVersions; + this.supportedVersions = options.supportedVersions; + this.producer = options.producer; + this.unknownFields = options.unknownFields; } } diff --git a/packages/build-output-utils/src/index.ts b/packages/build-output-utils/src/index.ts index 53b048ed4d..4634c65f23 100644 --- a/packages/build-output-utils/src/index.ts +++ b/packages/build-output-utils/src/index.ts @@ -26,9 +26,15 @@ export { export type { WriteAssetsOptions, WriteContainerConfigOptions, + WriteRootConfigOptions, WriteWorkerConfigOptions, } from "./write"; export { BuildOutputError } from "./errors"; +export type { + BuildOutputErrorCode, + BuildOutputErrorOptions, + BuildOutputUnknownField, +} from "./errors"; export { readBuildOutput } from "./read"; export type { BuildOutput, diff --git a/packages/build-output-utils/src/paths.ts b/packages/build-output-utils/src/paths.ts index 872392c621..2ec93bc179 100644 --- a/packages/build-output-utils/src/paths.ts +++ b/packages/build-output-utils/src/paths.ts @@ -1,11 +1,13 @@ import * as path from "node:path"; /** - * Initial draft version of the Build Output Specification. + * Version of the Build Output Specification, and the name of its directory + * under {@link BUILD_OUTPUT_ROOT}. * - * Will move to `v1` when the spec stabilises. + * Only the `.cloudflare/output/v/` convention is permanent. Everything + * inside a version directory belongs to that version. */ -export const BUILD_OUTPUT_VERSION = "v0"; +export const BUILD_OUTPUT_VERSION = "v1"; /** Build output directory relative to the project root. */ export const BUILD_OUTPUT_ROOT = ".cloudflare/output"; diff --git a/packages/build-output-utils/src/read.ts b/packages/build-output-utils/src/read.ts index efce044d4c..903216b954 100644 --- a/packages/build-output-utils/src/read.ts +++ b/packages/build-output-utils/src/read.ts @@ -2,9 +2,10 @@ import * as fs from "node:fs"; import * as fsp from "node:fs/promises"; import * as path from "node:path"; import { - OutputContainerSchema, - OutputRootConfigSchema, - OutputWorkerSchema, + BuildOutputContainerConfigSchema, + BuildOutputProducerSchema, + BuildOutputRootConfigSchema, + BuildOutputWorkerConfigSchema, } from "@cloudflare/config"; import { BuildOutputError } from "./errors"; import { @@ -20,25 +21,43 @@ import { getWorkerDir, getWorkersDir, } from "./paths"; +import type { BuildOutputUnknownField } from "./errors"; import type { ModuleType, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputProducer, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; +/** Matches version directory names such as `v0`, `v1` and `v12`. */ +const VERSION_DIRECTORY_PATTERN = /^v(0|[1-9]\d*)$/; + +/** The parts of a schema validation issue needed to report unknown fields. */ +interface ValidationIssue { + code: string; + path: PropertyKey[]; + keys?: string[]; +} + +/** The parts of a failed schema validation needed to report it. */ +interface ValidationFailure { + message: string; + issues: readonly ValidationIssue[]; +} + type ManifestModules = NonNullable< - ParsedOutputWorkerConfig["manifest"] + ParsedBuildOutputWorkerConfig["manifest"] >["modules"]; type CompleteManifest = Omit< - NonNullable, + NonNullable, "type" > & { type: "complete" }; /** A parsed Worker config whose manifest has been fully resolved. */ export type ResolvedOutputWorkerConfig = Omit< - ParsedOutputWorkerConfig, + ParsedBuildOutputWorkerConfig, "manifest" > & { manifest?: CompleteManifest; @@ -86,7 +105,7 @@ export interface BuildOutputContainer { /** Absolute path to the Container's `container.config.json`. */ configPath: string; /** The parsed Container config. */ - config: ParsedOutputContainerConfig; + config: ParsedBuildOutputContainerConfig; } /** Containers found in the Build Output Specification tree. */ @@ -98,22 +117,22 @@ export type BuildOutputContainers = BuildOutputContainer[]; export interface BuildOutput { /** Absolute project root from which the output was read. */ root: string; - /** Version of the spec the tree conforms to. */ + /** The version directory that was read, such as `"v1"`. */ version: string; /** * The parsed root `config.json`. */ - rootConfig: ParsedOutputRootConfig; + rootConfig: ParsedBuildOutputRootConfig; /** * The deployable Workers found under - * `/.cloudflare/output/v0/workers/`, keyed by their directory names. + * `/.cloudflare/output/v1/workers/`, keyed by their directory names. * Worker configs without a `bundle/` or `assets/` directory are omitted. * Guaranteed to contain the `default` Worker. */ workers: BuildOutputWorkers; /** * The Containers found under - * `/.cloudflare/output/v0/containers/`. Their order has no semantic + * `/.cloudflare/output/v1/containers/`. Their order has no semantic * meaning. */ containers: BuildOutputContainers; @@ -121,41 +140,110 @@ export interface BuildOutput { /** * Read and parse the Build Output Specification tree at - * `/.cloudflare/output/v0/`. + * `/.cloudflare/output/v1/`. * - * Reads the root `config.json`, then reads and parses each - * `worker.config.json` and `container.config.json`, and resolves each Worker's - * `bundle/` / `assets/` directories. Partial manifests are resolved into - * complete manifests using the files in `bundle/`. + * Lists the version directories under `/.cloudflare/output/` first and + * fails unless exactly one, `v1`, is present. Then reads the root + * `config.json`, reads and parses each `worker.config.json` and + * `container.config.json`, and resolves each Worker's `bundle/` / `assets/` + * directories. Partial manifests are resolved into complete manifests using + * the files in `bundle/`. * - * @throws {BuildOutputError} if the root `config.json` is missing or - * invalid, if a Worker or Container config is missing, is not valid JSON, - * or does not match its schema, or if the build output contains a symlink. + * @throws {BuildOutputError} with a `code` describing the failure: if no + * version directory is found (`not-found`), if the only version directory is + * newer or older than `v1` (`newer-version` / `older-version`), if more than + * one version directory is found (`multiple-versions`), if a config contains + * fields this reader doesn't support (`unknown-fields`), or if the tree is + * otherwise malformed, such as a missing or invalid config or a symlink + * (`invalid`). */ export async function readBuildOutput(root: string): Promise { const absoluteRoot = path.resolve(root); - await validateBuildOutputDirectory(absoluteRoot); + assertBuildOutputDirectoryNotLinked(absoluteRoot); + const version = await detectVersion(absoluteRoot); + await assertNoSymlinksInVersion(absoluteRoot, version); const rootConfig = await readRootConfig(absoluteRoot); const [workers, containers] = await Promise.all([ - readWorkers(absoluteRoot), - readContainers(absoluteRoot), + readWorkers({ root: absoluteRoot, producer: rootConfig.producer }), + readContainers({ root: absoluteRoot, producer: rootConfig.producer }), ]); return { root: absoluteRoot, - version: BUILD_OUTPUT_VERSION, + version, rootConfig, workers, containers, }; } -/** Reject symlinks so build output remains portable and self-contained. */ -async function validateBuildOutputDirectory(root: string): Promise { +/** + * Find the single version directory under `.cloudflare/output/` and check + * that this reader supports it. + * + * Entries not named `v` are ignored so that files such as `.DS_Store` + * don't break deploys. More than one version directory is an error because a + * stale tree next to a fresh one could otherwise deploy old code. A symlink + * named `v` counts as a version directory, so that it is rejected as a + * symlink rather than reported as missing output. + * + * @returns the name of the version directory, such as `"v1"`. + * @throws {BuildOutputError} if there isn't exactly one supported version + * directory. + */ +async function detectVersion(root: string): Promise { const buildOutputDir = getBuildOutputDir(root); + const isDirectory = + fs.statSync(buildOutputDir, { throwIfNoEntry: false })?.isDirectory() ?? + false; + const foundVersions = isDirectory + ? (await fsp.readdir(buildOutputDir, { withFileTypes: true })) + .filter( + (entry) => + (entry.isDirectory() || entry.isSymbolicLink()) && + VERSION_DIRECTORY_PATTERN.test(entry.name) + ) + .map((entry) => entry.name) + .sort((a, b) => Number(a.slice(1)) - Number(b.slice(1))) + : []; + const details = { foundVersions, supportedVersions: [BUILD_OUTPUT_VERSION] }; - // Check the output path itself before scanning to avoid following a linked - // `.cloudflare` or `output` directory. + const [version, ...otherVersions] = foundVersions; + if (version === undefined) { + throw new BuildOutputError(`No Build Output found in ${buildOutputDir}.`, { + code: "not-found", + ...details, + }); + } + if (otherVersions.length > 0) { + throw new BuildOutputError( + `Found Build Output in more than one format (${foundVersions.join(", ")}) in ${buildOutputDir}. Delete ${buildOutputDir} and rebuild.`, + { code: "multiple-versions", ...details } + ); + } + if (version === BUILD_OUTPUT_VERSION) { + return version; + } + + if (Number(version.slice(1)) > Number(BUILD_OUTPUT_VERSION.slice(1))) { + throw new BuildOutputError( + `This Build Output uses format ${version}, but this reader supports ${BUILD_OUTPUT_VERSION}. Upgrade the tool reading it.`, + { code: "newer-version", ...details } + ); + } + throw new BuildOutputError( + `This Build Output uses the older ${version} format. It was written by an out-of-date build tool. Upgrade it and rebuild.`, + { code: "older-version", ...details } + ); +} + +/** + * Reject a linked `.cloudflare` or `.cloudflare/output` directory before + * anything reads `.cloudflare/output`, so that reading never follows a link + * out of the project. + */ +function assertBuildOutputDirectoryNotLinked(root: string): void { + const buildOutputDir = getBuildOutputDir(root); for (const directory of [path.dirname(buildOutputDir), buildOutputDir]) { const entry = fs.lstatSync(directory, { throwIfNoEntry: false }); if (entry === undefined) { @@ -166,8 +254,24 @@ async function validateBuildOutputDirectory(root: string): Promise { return; } } +} - const entries = await fsp.readdir(buildOutputDir, { +/** + * Reject symlinks in the version directory being read, so the build output + * remains portable and self-contained. + * + * Only that directory is scanned. Entries that aren't version directories are + * ignored, and other versions aren't read, so their contents can't fail the + * read. + */ +async function assertNoSymlinksInVersion( + root: string, + version: string +): Promise { + const versionDir = path.join(getBuildOutputDir(root), version); + assertNotSymlink(versionDir, fs.lstatSync(versionDir)); + + const entries = await fsp.readdir(versionDir, { recursive: true, withFileTypes: true, }); @@ -184,16 +288,36 @@ function assertNotSymlink(filePath: string, entry: fs.Stats | fs.Dirent): void { } } +/** Where to read from, and who wrote it for error messages. */ +interface ReadOptions { + root: string; + /** The tool that wrote the tree, attached to any error thrown. */ + producer?: ParsedBuildOutputProducer; +} + +/** Options for reading one Worker or Container directory. */ +interface ReadDirectoryOptions extends ReadOptions { + directoryName: string; +} + /** Read and parse the default Worker and any additional Worker configs. */ -async function readWorkers(root: string): Promise { +async function readWorkers({ + root, + producer, +}: ReadOptions): Promise { const workersDir = getWorkersDir(root); - const defaultWorker = await readWorker(root, DEFAULT_WORKER_DIRECTORY_NAME); + const defaultWorker = await readWorker({ + root, + directoryName: DEFAULT_WORKER_DIRECTORY_NAME, + producer, + }); if (defaultWorker === undefined) { const workerDir = getWorkerDir(root, DEFAULT_WORKER_DIRECTORY_NAME); const bundleDir = getWorkerBundleDir(root, DEFAULT_WORKER_DIRECTORY_NAME); const assetsDir = getWorkerAssetsDir(root, DEFAULT_WORKER_DIRECTORY_NAME); throw new BuildOutputError( - `Default Worker at ${workerDir} has neither a bundle directory (${bundleDir}) nor an assets directory (${assetsDir}).` + `Default Worker at ${workerDir} has neither a bundle directory (${bundleDir}) nor an assets directory (${assetsDir}).`, + { producer } ); } const additionalWorkerDirectoryNames = ( @@ -206,7 +330,11 @@ async function readWorkers(root: string): Promise { .map((entry) => entry.name); const additionalWorkers = await Promise.all( additionalWorkerDirectoryNames.map(async (workerDirectoryName) => { - const worker = await readWorker(root, workerDirectoryName); + const worker = await readWorker({ + root, + directoryName: workerDirectoryName, + producer, + }); return worker === undefined ? undefined : ([workerDirectoryName, worker] as const); @@ -225,7 +353,10 @@ async function readWorkers(root: string): Promise { } /** Read and parse all Container configs, if any. */ -async function readContainers(root: string): Promise { +async function readContainers({ + root, + producer, +}: ReadOptions): Promise { const containersDir = getContainersDir(root); if (!fs.existsSync(containersDir)) { return []; @@ -239,30 +370,37 @@ async function readContainers(root: string): Promise { return Promise.all( containerDirectoryNames.map((containerDirectoryName) => - readContainer(root, containerDirectoryName) + readContainer({ root, directoryName: containerDirectoryName, producer }) ) ); } /** Read and parse one Container config. */ -async function readContainer( - root: string, - containerDirectoryName: string -): Promise { - const configPath = getContainerConfigPath(root, containerDirectoryName); +async function readContainer({ + root, + directoryName, + producer, +}: ReadDirectoryOptions): Promise { + const configPath = getContainerConfigPath(root, directoryName); if (!fs.existsSync(configPath)) { - throw new BuildOutputError(`no Container config found at ${configPath}.`); + throw new BuildOutputError(`no Container config found at ${configPath}.`, { + producer, + }); } const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputContainerSchema.safeParse( - parseJson(contents, configPath) + const result = BuildOutputContainerConfigSchema.safeParse( + parseJson({ contents, configPath, producer }) ); if (!result.success) { - throw new BuildOutputError( - `invalid Container config at ${configPath}.\n${result.error.message}` - ); + throw createValidationError({ + description: "Container config", + root, + configPath, + failure: result.error, + producer, + }); } return { configPath, config: result.data }; @@ -277,31 +415,45 @@ async function readContainer( * @throws {BuildOutputError} if the config is missing, is not valid JSON, or * does not match its schema. */ -async function readWorker( - root: string, - workerDirectoryName: string -): Promise { - const configPath = getWorkerConfigPath(root, workerDirectoryName); +async function readWorker({ + root, + directoryName, + producer, +}: ReadDirectoryOptions): Promise { + const configPath = getWorkerConfigPath(root, directoryName); if (!fs.existsSync(configPath)) { - throw new BuildOutputError(`no Worker config found at ${configPath}.`); + throw new BuildOutputError(`no Worker config found at ${configPath}.`, { + producer, + }); } const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputWorkerSchema.safeParse(parseJson(contents, configPath)); + const result = BuildOutputWorkerConfigSchema.safeParse( + parseJson({ contents, configPath, producer }) + ); if (!result.success) { - throw new BuildOutputError( - `invalid Worker config at ${configPath}.\n${result.error.message}` - ); + throw createValidationError({ + description: "Worker config", + root, + configPath, + failure: result.error, + producer, + }); } - const bundleDir = getWorkerBundleDir(root, workerDirectoryName); - const assetsDir = getWorkerAssetsDir(root, workerDirectoryName); + const bundleDir = getWorkerBundleDir(root, directoryName); + const assetsDir = getWorkerAssetsDir(root, directoryName); const hasBundleDir = fs.existsSync(bundleDir); const hasAssetsDir = fs.existsSync(assetsDir); if (hasBundleDir) { - const config = await resolveManifest(result.data, configPath, bundleDir); + const config = await resolveManifest({ + config: result.data, + configPath, + bundleDir, + producer, + }); return { configPath, config, @@ -324,11 +476,17 @@ async function readWorker( } /** Resolve the manifest against the bundle contents. */ -async function resolveManifest( - config: ParsedOutputWorkerConfig, - configPath: string, - bundleDir: string -): Promise { +async function resolveManifest({ + config, + configPath, + bundleDir, + producer, +}: { + config: ParsedBuildOutputWorkerConfig; + configPath: string; + bundleDir: string; + producer?: ParsedBuildOutputProducer; +}): Promise { const { manifest, ...workerConfig } = config; if (manifest === undefined) { return workerConfig; @@ -343,7 +501,8 @@ async function resolveManifest( const inferredModules = await scanModules(bundleDir); if (inferredModules[manifest.mainModule]?.type !== "esm") { throw new BuildOutputError( - `partial manifest at ${configPath} has main module "${manifest.mainModule}", but it was not found as an ES module in the bundle.` + `partial manifest at ${configPath} has main module "${manifest.mainModule}", but it was not found as an ES module in the bundle.`, + { producer } ); } @@ -402,7 +561,9 @@ function inferModuleType(modulePath: string): ModuleType | undefined { * @throws {BuildOutputError} if the file is missing, is not valid JSON, or * does not match its schema. */ -async function readRootConfig(root: string): Promise { +async function readRootConfig( + root: string +): Promise { const configPath = getRootConfigPath(root); if (!fs.existsSync(configPath)) { @@ -410,25 +571,110 @@ async function readRootConfig(root: string): Promise { } const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputRootConfigSchema.safeParse( - parseJson(contents, configPath) - ); + const rawConfig = parseJson({ contents, configPath }); + const result = BuildOutputRootConfigSchema.safeParse(rawConfig); if (!result.success) { - throw new BuildOutputError( - `invalid root config at ${configPath}.\n${result.error.message}` - ); + throw createValidationError({ + description: "root config", + root, + configPath, + failure: result.error, + producer: readProducer(rawConfig), + }); } return result.data; } -function parseJson(contents: string, configPath: string): unknown { +/** + * Read `producer` from a root config that failed validation, so that errors + * can still name the tool that wrote it. + */ +function readProducer( + rawConfig: unknown +): ParsedBuildOutputProducer | undefined { + if (typeof rawConfig !== "object" || rawConfig === null) { + return undefined; + } + const result = BuildOutputProducerSchema.safeParse( + "producer" in rawConfig ? rawConfig.producer : undefined + ); + return result.success ? result.data : undefined; +} + +/** + * Convert a failed schema validation into a {@link BuildOutputError}. + * + * When every issue is an unknown key, the error lists each field and has the + * `unknown-fields` code: the output was most likely written by a newer build + * tool. Otherwise the error has the `invalid` code and includes the full + * validation message. + */ +function createValidationError({ + description, + root, + configPath, + failure, + producer, +}: { + description: string; + root: string; + configPath: string; + failure: ValidationFailure; + producer?: ParsedBuildOutputProducer; +}): BuildOutputError { + const isUnknownFieldsOnly = + failure.issues.length > 0 && + failure.issues.every((issue) => issue.code === "unrecognized_keys"); + if (!isUnknownFieldsOnly) { + return new BuildOutputError( + `invalid ${description} at ${configPath}.\n${failure.message}`, + { producer } + ); + } + + const file = path + .relative(getBuildOutputDir(root), configPath) + .split(path.sep) + .join("/"); + const unknownFields: BuildOutputUnknownField[] = failure.issues.flatMap( + (issue) => + (issue.keys ?? []).map((key) => ({ + file, + path: [...issue.path.map(String), key].join("."), + })) + ); + const writtenBy = + producer === undefined + ? "a newer build tool" + : `${producer.name} ${producer.version}`; + + return new BuildOutputError( + [ + `${file} contains fields this reader doesn't support:`, + ...unknownFields.map((field) => ` - ${field.path}`), + `The output was written by ${writtenBy}. Upgrade the tool reading it.`, + ].join("\n"), + { code: "unknown-fields", producer, unknownFields } + ); +} + +function parseJson({ + contents, + configPath, + producer, +}: { + contents: string; + configPath: string; + producer?: ParsedBuildOutputProducer; +}): unknown { try { return JSON.parse(contents); } catch (e) { const reason = e instanceof Error ? e.message : String(e); throw new BuildOutputError( - `could not parse JSON at ${configPath}.\n${reason}` + `could not parse JSON at ${configPath}.\n${reason}`, + { producer } ); } } diff --git a/packages/build-output-utils/src/write.ts b/packages/build-output-utils/src/write.ts index 1346127947..aefb097a7a 100644 --- a/packages/build-output-utils/src/write.ts +++ b/packages/build-output-utils/src/write.ts @@ -13,11 +13,12 @@ import { getWorkerDir, } from "./paths"; import type { - ParsedInputSettingsConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedSettings, + ParsedWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputProducer, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, ConfigContext, } from "@cloudflare/config"; @@ -74,8 +75,8 @@ export async function writeAssets({ export interface WriteWorkerConfigOptions { root: string; - config: ParsedInputWorkerConfig; - manifest?: ParsedOutputWorkerConfig["manifest"]; + config: ParsedWorkerConfig; + manifest?: ParsedBuildOutputWorkerConfig["manifest"]; directoryName?: string; } @@ -93,7 +94,7 @@ export async function writeWorkerConfig({ directoryName = DEFAULT_WORKER_DIRECTORY_NAME, }: WriteWorkerConfigOptions): Promise { const { entrypoint: _entrypoint, ...rest } = config; - const outputConfig: ParsedOutputWorkerConfig = { ...rest, manifest }; + const outputConfig: ParsedBuildOutputWorkerConfig = { ...rest, manifest }; await fsp.mkdir(getWorkerDir(root, directoryName), { recursive: true }); await fsp.writeFile( getWorkerConfigPath(root, directoryName), @@ -103,7 +104,7 @@ export async function writeWorkerConfig({ export interface WriteContainerConfigOptions { root: string; - config: ParsedOutputContainerConfig; + config: ParsedBuildOutputContainerConfig; directoryName: string; } @@ -128,22 +129,54 @@ export async function writeContainerConfig({ ); } +export interface WriteRootConfigOptions { + root: string; + /** + * Settings declared at the top level of `cloudflare.config.ts`. Omitted + * from the file when not given or when none of them is set. + */ + settings?: ParsedSettings; + /** Build context supplied at build time. */ + buildContext: ConfigContext; + /** + * The tool writing the tree, such as a framework adapter or build plugin. + * Readers use it only in error messages and diagnostics. Omitted from the + * file when not given. + */ + producer?: ParsedBuildOutputProducer; +} + /** * Write the root `config.json` to the Build Output Specification tree. * - * Holds the settings declared at the top level of `cloudflare.config.ts` and - * build context supplied at build time. + * Holds the tool that wrote the tree, the settings declared at the top level + * of `cloudflare.config.ts` and the build context supplied at build time. */ -export async function writeRootConfig( - root: string, - settings: ParsedInputSettingsConfig | undefined, - buildContext: ConfigContext -): Promise { - const outputConfig: ParsedOutputRootConfig = { - ...settings, +export async function writeRootConfig({ + root, + settings, + buildContext, + producer, +}: WriteRootConfigOptions): Promise { + const outputConfig: ParsedBuildOutputRootConfig = { + ...(producer === undefined ? {} : { producer }), + ...(hasSettings(settings) ? { settings } : {}), buildContext, }; const configPath = getRootConfigPath(root); await fsp.mkdir(path.dirname(configPath), { recursive: true }); await fsp.writeFile(configPath, JSON.stringify(outputConfig)); } + +/** + * Whether any setting is set. Writers emit a key only when it is used, so an + * object whose settings are all `undefined` is left out like a missing one. + */ +function hasSettings( + settings: ParsedSettings | undefined +): settings is ParsedSettings { + return ( + settings !== undefined && + Object.values(settings).some((value) => value !== undefined) + ); +} diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index f166f15226..ce77bfa7cd 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,31 @@ # @cloudflare/cli +## 0.3.9 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155)]: + - @cloudflare/workers-utils@0.54.1 + +## 0.3.8 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985)]: + - @cloudflare/workers-utils@0.54.0 + ## 0.3.7 ### Patch Changes diff --git a/packages/cli/package.json b/packages/cli/package.json index 1b335e5aeb..ef189622ed 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/cli-shared-helpers", - "version": "0.3.7", + "version": "0.3.9", "description": "Internal shared CLI helpers for workers-sdk. Not intended for external use — APIs may change without notice.", "keywords": [ "cli", diff --git a/packages/codemods/CHANGELOG.md b/packages/codemods/CHANGELOG.md index 1dfd028b5d..62a747902e 100644 --- a/packages/codemods/CHANGELOG.md +++ b/packages/codemods/CHANGELOG.md @@ -1,5 +1,52 @@ # @cloudflare/codemods +## 0.8.0 + +### Minor Changes + +- [#16246](https://github.com/cloudflare/workers-sdk/pull/16246) [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155) Thanks [@leostera](https://github.com/leostera)! - Start local Workflows from Artifacts events + + Declare Artifacts events on `exports.workflow({ name, events })` in `cloudflare.config.ts` to start the owning Workflow locally in `cf`, Vite, and Workers Vitest. Wrangler configurations continue to use `triggers.events`. Native config conversion derives those targets from the Workflow export, and `cf migrate` attaches existing event subscriptions to their matching Workflow exports. + + Local Artifacts namespaces publish the documented `cf.artifacts.*` messages for repository create, import, fork, and delete operations and token creation and revocation. Successful create, import, and fork operations also publish the initial token-created event. Delivery follows the committed mutation, is unordered, and does not fail the repository operation if a destination rejects it. Push, clone, and fetch events are not yet published locally. This feature does not provide local Artifacts-to-queue subscriptions. + +### Patch Changes + +- [#16907](https://github.com/cloudflare/workers-sdk/pull/16907) [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Generate the release candidate `@cloudflare/config` field names in `wrangler-to-cf` + + The codemod now writes: + + - `first_party_worker` as `experimental.firstPartyWorker` + - Pipelines bindings as `bindings.pipeline({ streamId })` + - K2 bindings as `bindings.k2({ id })` + - the Analytics SQL binding as `bindings.analyticsSql()` + + A Pipelines binding that uses the deprecated `pipeline` field gets a `STREAM_ID` placeholder and a follow-up asking for the stream ID, because that field names a legacy pipeline, which `@cloudflare/config` doesn't support. + +- [#16921](https://github.com/cloudflare/workers-sdk/pull/16921) [`6785363`](https://github.com/cloudflare/workers-sdk/commit/6785363bc2d9b7cda463d8cc71765c4780f8d64d) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Install the Vite plugin release candidate in `wrangler-to-cf` + + The Wrangler-to-cf migration now installs `@cloudflare/vite-plugin@^2.0.0-rc.0` instead of the `beta` dist tag, which no longer receives new releases. It upgrades projects whose plugin is declared as a dist tag or resolves to a version older than the release candidate, since earlier betas don't support the generated configuration. The range also covers the stable v2 releases, so the migration no longer rewrites `package.json` to a dist tag after installing. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +## 0.7.8 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16864](https://github.com/cloudflare/workers-sdk/pull/16864) [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985) Thanks [@MattieTK](https://github.com/MattieTK)! - Fix packages with nested `package.json` files missing from deploy metadata + + Packages such as `hono`, `stripe` and `@modelcontextprotocol/sdk` were silently omitted from the package dependency metadata reported during `wrangler deploy` and `wrangler versions upload`. These packages are now included with their installed versions. Autoconfig and codemods also detect their installed versions correctly. + ## 0.7.7 ### Patch Changes diff --git a/packages/codemods/README.md b/packages/codemods/README.md index d611d5a133..5435676e13 100644 --- a/packages/codemods/README.md +++ b/packages/codemods/README.md @@ -57,4 +57,4 @@ const result = await migrateWranglerToCf("./wrangler.jsonc", { }); ``` -The options object and all of its fields are optional. The defaults are the Vite bundler, writes enabled, dirty-worktree protection enabled, and automatic dependency installation enabled. The migration installs `cf` when missing, installs `@cloudflare/vite-plugin@beta` when Vite is selected and the plugin is missing or incompatible, and upgrades Wrangler when generated Wrangler tooling requires a newer version. The Vite plugin dependency remains set to the `beta` dist tag in `package.json`; package manager installation updates the project's lockfile. Project-managed Vite plugin specifiers such as `workspace:` and `catalog:` are preserved; incompatible or unverified versions require a manual update. Set `installDependencies` to `false` to prevent dependency changes; required dependencies are then returned as blocking follow-ups. The migration always creates `cloudflare.config.ts`; selecting the Wrangler bundler also creates `wrangler.config.ts` when Wrangler-specific tooling config exists. Existing target files are never overwritten. Inspect `result.followUps` when `result.status` is `needs-intervention`. +The options object and all of its fields are optional. The defaults are the Vite bundler, writes enabled, dirty-worktree protection enabled, and automatic dependency installation enabled. The migration installs `cf` when missing, installs `@cloudflare/vite-plugin@^2.0.0-rc.0` when Vite is selected and the plugin is missing or older than the v2 release candidate, and upgrades Wrangler when generated Wrangler tooling requires a newer version. Dist tags such as `beta` count as incompatible, because they can stop pointing at a compatible release. Project-managed Vite plugin specifiers such as `workspace:` and `catalog:` are preserved; incompatible or unverified versions require a manual update. Set `installDependencies` to `false` to prevent dependency changes; required dependencies are then returned as blocking follow-ups. The migration always creates `cloudflare.config.ts`; selecting the Wrangler bundler also creates `wrangler.config.ts` when Wrangler-specific tooling config exists. Existing target files are never overwritten. Inspect `result.followUps` when `result.status` is `needs-intervention`. diff --git a/packages/codemods/package.json b/packages/codemods/package.json index f0b92bf441..47e4c01736 100644 --- a/packages/codemods/package.json +++ b/packages/codemods/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/codemods", - "version": "0.7.7", + "version": "0.8.0", "description": "Codemods for upgrading Cloudflare developer projects", "keywords": [ "cloudflare", @@ -48,7 +48,9 @@ "@cloudflare/workers-tsconfig": "workspace:*", "@cloudflare/workers-utils": "workspace:*", "@types/node": "catalog:default", + "@types/semver": "^7.5.1", "esbuild": "catalog:default", + "semver": "^7.7.1", "tinyglobby": "catalog:default", "tsup": "8.3.0", "typescript": "catalog:default", diff --git a/packages/codemods/src/codemods/wrangler-to-cf/bindings.ts b/packages/codemods/src/codemods/wrangler-to-cf/bindings.ts index e86fb8e98f..4978a20c85 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/bindings.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/bindings.ts @@ -10,9 +10,16 @@ import { type UnknownRecord, } from "./converter-helpers"; import { WORKFLOW_SETTINGS, isLocalWorkflow } from "./exports"; -import { DURABLE_OBJECT_EXPORTS_DOCS_URL, createFollowUp } from "./follow-ups"; +import { + DURABLE_OBJECT_EXPORTS_DOCS_URL, + createFollowUp, + followUpToComment, +} from "./follow-ups"; import type { MigrationFollowUp, OutputObject, OutputValue } from "./types"; +/** Written in place of a legacy pipeline name, which isn't a stream ID. */ +const LEGACY_PIPELINE_STREAM_ID_PLACEHOLDER = "STREAM_ID"; + function addBinding( bindings: Map, name: unknown, @@ -69,7 +76,7 @@ export function convertBindings( source: UnknownRecord, sourcePrefix: string, imports: Set, - report: (followUp: MigrationFollowUp) => void + report: (followUp: MigrationFollowUp, options?: { inline?: boolean }) => void ): OutputObject | undefined { const bindings = new Map(); const pathFor = (field: string, index?: number) => @@ -221,7 +228,7 @@ export function convertBindings( report ); } - convertArrayBindings("k2", "binding", "bindings.k2", [["stream", "stream"]], { + convertArrayBindings("k2", "binding", "bindings.k2", [["stream", "id"]], { remote: true, }); convertArrayBindings( @@ -239,17 +246,41 @@ export function convertBindings( { remote: true } ); for (const [index, entry] of getRecords(source, "pipelines").entries()) { + const sourcePath = pathFor("pipelines", index); + // The deprecated `pipeline` field names a legacy pipeline, which + // `@cloudflare/config` doesn't support. It isn't a stream ID, so write a + // placeholder for the user to replace instead of copying it. + const isLegacy = entry.stream === undefined && entry.pipeline !== undefined; const options = optionsFromRecord( - { ...entry, name: entry.stream ?? entry.pipeline }, - [["name", "name"]], + { + ...entry, + streamId: isLegacy + ? LEGACY_PIPELINE_STREAM_ID_PLACEHOLDER + : entry.stream, + }, + [["streamId", "streamId"]], true ); + if (isLegacy) { + const followUp = createFollowUp( + "legacy-pipeline-binding", + `The Pipelines binding at \`${sourcePath}\` used the deprecated \`pipeline\` field, which names a legacy pipeline. Set \`streamId\` to the ID of the stream to write to.`, + { sourcePath } + ); + report(followUp, { inline: true }); + const streamId = options.properties.find( + (property) => property.key === "streamId" + ); + if (streamId) { + streamId.comments = [followUpToComment(followUp)]; + } + } imports.add("bindings"); addBinding( bindings, entry.binding, call("bindings.pipeline", options), - pathFor("pipelines", index), + sourcePath, report ); } @@ -619,7 +650,7 @@ export function convertBindings( } convertSingletonBinding("ai", "binding", "bindings.ai", ["staging"]); - convertSingletonBinding("analytics", "binding", "bindings.analytics"); + convertSingletonBinding("analytics", "binding", "bindings.analyticsSql"); convertSingletonBinding("browser", "binding", "bindings.browser"); convertSingletonBinding("images", "binding", "bindings.images"); convertSingletonBinding("media", "binding", "bindings.media"); diff --git a/packages/codemods/src/codemods/wrangler-to-cf/exports.ts b/packages/codemods/src/codemods/wrangler-to-cf/exports.ts index 48ff9a62c8..63e6ba6e80 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/exports.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/exports.ts @@ -54,6 +54,10 @@ function workflowExportOptions(record: UnknownRecord): OutputObject { properties.push({ key, value: camelObject(value) }); } } + const events = getRecords(record, "events"); + if (events.length > 0) { + properties.push({ key: "events", value: events.map(camelObject) }); + } const schedules = toOutputValue(record.schedules); if (schedules !== undefined) { properties.push({ key: "schedules", value: schedules }); @@ -69,6 +73,67 @@ function workflowExportOptions(record: UnknownRecord): OutputObject { return { kind: "object", properties }; } +/** Attaches legacy targets to the exports that actually own the Workflows. */ +function attachWorkflowEvents( + source: UnknownRecord, + sourcePrefix: string, + exports: Map, + report: (followUp: MigrationFollowUp) => void +): void { + const events = getRecord(source, "triggers")?.events; + if (!Array.isArray(events)) { + return; + } + for (const [index, event] of events.entries()) { + const sourcePath = `${sourcePrefix ? sourcePrefix + "." : ""}triggers.events.${index}`; + if ( + !isRecord(event) || + typeof event.type !== "string" || + !Array.isArray(event.targets) || + event.targets.length === 0 || + (event.filter !== undefined && !isRecord(event.filter)) + ) { + report( + createFollowUp( + "invalid-workflow-event", + "This event subscription could not be migrated. Review its type, filter, and Workflow targets.", + { sourcePath } + ) + ); + continue; + } + for (const [targetIndex, target] of event.targets.entries()) { + const owned = + isRecord(target) && target.type === "workflow" + ? [...exports.values()].filter( + (workflow) => workflow.name === target.workflow_name + ) + : []; + if (owned.length !== 1) { + report( + createFollowUp( + "workflow-event-target", + "This event target does not identify one Workflow export owned by this Worker. Its subscription was not migrated.", + { + sourcePath: `${sourcePath}.targets.${targetIndex}`, + } + ) + ); + continue; + } + const workflow = owned[0]; + const previous = getRecords(workflow, "events"); + workflow.events = [ + ...previous, + { + type: event.type, + ...(event.filter === undefined ? {} : { filter: event.filter }), + }, + ]; + } + } +} + export function convertExports( source: UnknownRecord, sourcePrefix: string, @@ -159,8 +224,8 @@ export function convertExports( } // A `workflows` binding to a Workflow this Worker defines becomes an export // here, carrying the Workflow's settings. When the Wrangler `exports` table - // already declares the same Workflow, the two merge the way Wrangler merges - // them (`getWorkflowsOwnedByScript`), with the binding's settings winning. + // already declares the same Workflow, the two merge, with the binding's + // settings winning. for (const [index, entry] of getRecords(source, "workflows").entries()) { if ( !isLocalWorkflow(entry, source) || @@ -197,6 +262,7 @@ export function convertExports( ); } } + attachWorkflowEvents(source, sourcePrefix, workflowExports, report); for (const [property, record] of pendingWorkflows) { property.value = call("exports.workflow", workflowExportOptions(record)); } diff --git a/packages/codemods/src/codemods/wrangler-to-cf/index.ts b/packages/codemods/src/codemods/wrangler-to-cf/index.ts index a2aa8a4a98..5e8d71e78c 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/index.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/index.ts @@ -19,6 +19,7 @@ import { planCfDependencyInstallation, planVitePluginDependencyUpgrade, planWranglerDependencyUpgrade, + VITE_PLUGIN_VERSION_RANGE, } from "./install-dependencies"; import { MINIMUM_WRANGLER_VERSION } from "./wrangler-version"; import type { DependencyToInstall } from "./install-dependencies"; @@ -107,7 +108,9 @@ export async function migrateWranglerToCf( ]); const missingManifestPackages = formatDependencies([ "cf@latest", - ...(bundler === "vite" ? ["@cloudflare/vite-plugin@beta"] : []), + ...(bundler === "vite" + ? [`@cloudflare/vite-plugin@${VITE_PLUGIN_VERSION_RANGE}`] + : []), ]); const dependenciesToInstall: DependencyToInstall[] = []; if (cfDepPlan.action === "install") { @@ -184,12 +187,12 @@ export async function migrateWranglerToCf( if (vitePluginDepPlan.action === "manual") { const instruction = vitePluginDepPlan.managedDependency === "incompatible" - ? "Update the project-managed plugin to a compatible v2 version and refresh its lockfile while preserving the dependency specifier." - : "Install dependencies and verify that the project-managed plugin resolves to v2. If needed, update it and refresh the lockfile while preserving the dependency specifier."; + ? "Update the project-managed plugin to a compatible version and refresh its lockfile while preserving the dependency specifier." + : "Install dependencies and verify that the project-managed plugin resolves to a compatible version. If needed, update it and refresh the lockfile while preserving the dependency specifier."; convertedConfig.followUps.push( createFollowUp( "vite-plugin-upgrade-manual", - `The Vite migration requires @cloudflare/vite-plugin v2. ${instruction}` + `The Vite migration requires @cloudflare/vite-plugin ${VITE_PLUGIN_VERSION_RANGE}. ${instruction}` ) ); } @@ -248,40 +251,22 @@ export async function migrateWranglerToCf( if (error instanceof DependencyInstallError) { changedFiles.push(...error.changedFiles); } - if ( - error instanceof DependencyInstallError && - error.stage !== "install" - ) { - dependencyFollowUp = - error.stage === "lockfile-sync" - ? createFollowUp( - "vite-plugin-lockfile-sync-failed", - `The Vite plugin was installed and package.json now declares \`beta\`, but the lockfile could not be synchronized. Run your package manager's install command to refresh it before using the generated configuration. ${error.message}` - ) - : createFollowUp( - "vite-plugin-manifest-update-failed", - `The Vite plugin was installed, but package.json could not be set to the \`beta\` dist tag. Set it to \`beta\` and run your package manager's install command before using the generated configuration. ${error.message}` - ); - } else { - const reason = - error instanceof Error - ? ` Installation failed: ${error.message}` - : ""; - const packageNames = formatDependencies( - pendingDependencies.map(({ name }) => name) - ); - const packageSpecifiers = formatDependencies( - pendingDependencies.map(({ name, version }) => `${name}@${version}`) - ); - dependencyFollowUp = createFollowUp( - pendingDependencies.some(({ name }) => name === "cf") - ? "cf-install-failed" - : pendingDependencies.some(({ name }) => name === "wrangler") - ? "wrangler-upgrade-failed" - : "vite-plugin-install-failed", - `The generated configuration was written, but ${packageNames} could not be installed automatically. Install ${packageSpecifiers} with your package manager before using it.${reason}` - ); - } + const reason = + error instanceof Error ? ` Installation failed: ${error.message}` : ""; + const packageNames = formatDependencies( + pendingDependencies.map(({ name }) => name) + ); + const packageSpecifiers = formatDependencies( + pendingDependencies.map(({ name, version }) => `${name}@${version}`) + ); + dependencyFollowUp = createFollowUp( + pendingDependencies.some(({ name }) => name === "cf") + ? "cf-install-failed" + : pendingDependencies.some(({ name }) => name === "wrangler") + ? "wrangler-upgrade-failed" + : "vite-plugin-install-failed", + `The generated configuration was written, but ${packageNames} could not be installed automatically. Install ${packageSpecifiers} with your package manager before using it.${reason}` + ); requiresInstall = true; } diff --git a/packages/codemods/src/codemods/wrangler-to-cf/install-dependencies.ts b/packages/codemods/src/codemods/wrangler-to-cf/install-dependencies.ts index 87c9ec2999..513eac2402 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/install-dependencies.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/install-dependencies.ts @@ -1,6 +1,5 @@ -import { readFile, writeFile } from "node:fs/promises"; +import { readFile } from "node:fs/promises"; import path from "node:path"; -import { runCommand } from "@cloudflare/cli-shared-helpers/command"; import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; import { BunPackageManager, @@ -10,6 +9,7 @@ import { PnpmPackageManager, YarnPackageManager, } from "@cloudflare/workers-utils"; +import { satisfies, subset, valid, validRange } from "semver"; import { glob } from "tinyglobby"; import { fileExists } from "../../files"; import { getWranglerUpgradeSpec, isVersionSupported } from "./wrangler-version"; @@ -17,12 +17,11 @@ import type { MigrationBundler } from "./types"; import type { PackageManager } from "@cloudflare/workers-utils"; const VITE_PLUGIN = "@cloudflare/vite-plugin"; -// Recognize full installed v2 versions, including prerelease and build labels. -const VITE_PLUGIN_VERSION_PATTERN = - /^2\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; -// Only these declared ranges stay within v2; the beta tag tracks new prereleases. -const VITE_PLUGIN_RANGE_PATTERN = - /^(?:(?:\^|~)?2(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?|>=2\.0\.0-0 <3\.0\.0-0|beta)$/; +/** + * The Vite plugin versions that support the generated configuration: the v2 + * release candidates and every later v2 release. + */ +export const VITE_PLUGIN_VERSION_RANGE = "^2.0.0-rc.0"; // Managed specifiers need an installed-version check instead of range parsing. const MANAGED_VITE_PLUGIN_SPECIFIER = /^(?:workspace:|file:|link:|portal:|catalog:)/; @@ -84,7 +83,6 @@ export class DependencyInstallError extends Error { constructor( readonly changedFiles: string[], readonly pendingDependencies: DependencyToInstall[], - readonly stage: "install" | "manifest-update" | "lockfile-sync", cause: unknown ) { super( @@ -120,24 +118,6 @@ async function readPackageJson(packageJsonPath: string): Promise { return JSON.parse(await readFile(packageJsonPath, "utf8")) as PackageJson; } -async function setVitePluginDepToBeta( - packageDirectory: string, - dev: boolean -): Promise { - const packageJsonPath = path.join(packageDirectory, "package.json"); - const packageJson = await readPackageJson(packageJsonPath); - const dependencySection = dev ? "devDependencies" : "dependencies"; - const packageDependencies = packageJson[dependencySection] ?? {}; - if (packageDependencies[VITE_PLUGIN] === "beta") { - return false; - } - - packageDependencies[VITE_PLUGIN] = "beta"; - packageJson[dependencySection] = packageDependencies; - await writeFile(packageJsonPath, `${JSON.stringify(packageJson, null, 2)}\n`); - return true; -} - function getPackageJsonWorkspacePatterns( workspaces: unknown ): string[] | undefined { @@ -296,6 +276,30 @@ function hasCfDependency(packageJson: PackageJson): boolean { ); } +/** + * Checks whether every version a declared range can resolve to supports the + * generated configuration. Dist tags and other non-range specifiers are not + * compatible. + */ +function isCompatibleVitePluginRange(declaredVersion: string): boolean { + // `subset()` rejects exact prerelease versions that the range includes. + const exactVersion = valid(declaredVersion); + if (exactVersion !== null) { + return isCompatibleVitePluginVersion(exactVersion); + } + return ( + validRange(declaredVersion) !== null && + subset(declaredVersion, VITE_PLUGIN_VERSION_RANGE) + ); +} + +/** Checks whether an exact version supports the generated configuration. */ +function isCompatibleVitePluginVersion(version: string): boolean { + return satisfies(version, VITE_PLUGIN_VERSION_RANGE, { + includePrerelease: true, + }); +} + function needsVitePluginUpgrade( packageJson: PackageJson, projectDirectory: string @@ -313,9 +317,9 @@ function needsVitePluginUpgrade( ); const compatibleInstalledVersion = installedVersion !== undefined && - VITE_PLUGIN_VERSION_PATTERN.test(installedVersion); + isCompatibleVitePluginVersion(installedVersion); if ( - !VITE_PLUGIN_RANGE_PATTERN.test(declaredVersion) && + !isCompatibleVitePluginRange(declaredVersion) && !( MANAGED_VITE_PLUGIN_SPECIFIER.test(declaredVersion) && compatibleInstalledVersion @@ -619,7 +623,7 @@ export async function planVitePluginDependencyUpgrade( dependency: { dev: packageJson.dependencies?.[VITE_PLUGIN] === undefined, name: VITE_PLUGIN, - version: "beta", + version: VITE_PLUGIN_VERSION_RANGE, }, }; } @@ -742,44 +746,18 @@ export async function installProjectDependencies( .filter((dependency) => dependency.dev === dev) .map(({ name, version }) => `${name}@${version}`); if (packages.length > 0) { - let stage: "install" | "manifest-update" | "lockfile-sync" = "install"; try { await installPackages(packageManager.type, packages, { cwd: packageDirectory, dev, isWorkspaceRoot, }); - if ( - dependencies.some( - (dependency) => - dependency.dev === dev && dependency.name === VITE_PLUGIN - ) - ) { - stage = "manifest-update"; - if (await setVitePluginDepToBeta(packageDirectory, dev)) { - stage = "lockfile-sync"; - if (packageManager.type === "bun") { - await runCommand(["bun", "install"], { - cwd: packageDirectory, - silent: true, - }); - } else { - await installPackages(packageManager.type, [], { - cwd: packageDirectory, - isWorkspaceRoot, - }); - } - } - } } catch (error) { throw new DependencyInstallError( getChangedFiles(before, await readFiles(packageFilePaths)), - stage === "install" - ? dev - ? dependencies - : dependencies.filter((dependency) => !dependency.dev) - : [], - stage, + dev + ? dependencies + : dependencies.filter((dependency) => !dependency.dev), error ); } diff --git a/packages/codemods/src/codemods/wrangler-to-cf/triggers.ts b/packages/codemods/src/codemods/wrangler-to-cf/triggers.ts index 236555f8f9..e6651ae636 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/triggers.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/triggers.ts @@ -124,19 +124,6 @@ export function convertTriggers( }) ); } - - if ( - Array.isArray(triggerConfig.events) && - triggerConfig.events.length > 0 - ) { - report( - createFollowUp( - "artifact-event-triggers", - "Artifact event triggers are not supported by the new config and were not migrated.", - { sourcePath: `${sourcePrefix || "config"}.triggers.events` } - ) - ); - } } const queues = getRecord(source, "queues"); diff --git a/packages/codemods/src/codemods/wrangler-to-cf/worker-config.ts b/packages/codemods/src/codemods/wrangler-to-cf/worker-config.ts index 62afbc8c9e..3ca4c5e588 100644 --- a/packages/codemods/src/codemods/wrangler-to-cf/worker-config.ts +++ b/packages/codemods/src/codemods/wrangler-to-cf/worker-config.ts @@ -96,9 +96,16 @@ export function convertWorkerConfig( ): OutputObject { const properties: OutputProperty[] = []; const comments: OutputComment[] = []; - const report = (followUp: MigrationFollowUp) => { + // `inline` follow-ups are already attached as a comment to the generated + // value they concern, so they aren't repeated at the end of the Worker. + const report = ( + followUp: MigrationFollowUp, + options: { inline?: boolean } = {} + ) => { followUps.push(followUp); - comments.push(followUpToComment(followUp)); + if (!options.inline) { + comments.push(followUpToComment(followUp)); + } }; if (typeof source.name === "string") { @@ -144,7 +151,6 @@ export function convertWorkerConfig( addProperty(properties, source, "main", "entrypoint"); addProperty(properties, source, "workers_dev", "workersDev"); addProperty(properties, source, "preview_urls", "previewUrls"); - addProperty(properties, source, "first_party_worker", "firstPartyWorker"); addProperty(properties, source, "logpush"); addProperty(properties, source, "placement", "placement", (value) => isRecord(value) ? camelObject(value) : undefined @@ -251,18 +257,18 @@ export function convertWorkerConfig( }); } } + const experimental: OutputProperty[] = []; if (streamingTailConsumers.length > 0) { + experimental.push({ + key: "streamingTailConsumers", + value: streamingTailConsumers, + }); + } + addProperty(experimental, source, "first_party_worker", "firstPartyWorker"); + if (experimental.length > 0) { properties.push({ key: "experimental", - value: { - kind: "object", - properties: [ - { - key: "streamingTailConsumers", - value: streamingTailConsumers, - }, - ], - }, + value: { kind: "object", properties: experimental }, }); } diff --git a/packages/codemods/test/__snapshots__/bindings.test.ts.snap b/packages/codemods/test/__snapshots__/bindings.test.ts.snap index f70efcd57e..8b8fa6a754 100644 --- a/packages/codemods/test/__snapshots__/bindings.test.ts.snap +++ b/packages/codemods/test/__snapshots__/bindings.test.ts.snap @@ -238,7 +238,7 @@ exports[`Wrangler binding conversion > converts supported bindings and reports m "properties": [], }, ], - "callee": "bindings.analytics", + "callee": "bindings.analyticsSql", "kind": "call", }, }, diff --git a/packages/codemods/test/runner.test.ts b/packages/codemods/test/runner.test.ts index 84e192bc7f..368d45637e 100644 --- a/packages/codemods/test/runner.test.ts +++ b/packages/codemods/test/runner.test.ts @@ -90,7 +90,7 @@ describe("codemod runner", () => { * This migration needs manual work. Resolve every TODO in this file, then remove the error below. */ /** - * TODO(@cloudflare): cf migrate: No package.json was found. Create or locate the package that owns this Worker, then install \`cf@latest\` and \`@cloudflare/vite-plugin@beta\` as dev dependencies before using the generated configuration. + * TODO(@cloudflare): cf migrate: No package.json was found. Create or locate the package that owns this Worker, then install \`cf@latest\` and \`@cloudflare/vite-plugin@^2.0.0-rc.0\` as dev dependencies before using the generated configuration. */ throw new Error("Migration incomplete. Resolve every cf migrate TODO in \`cloudflare.config.ts\`."); @@ -615,7 +615,7 @@ export default defineWorkersProject({ const cwd = await createProject({ "package.json": JSON.stringify({ devDependencies: { - "@cloudflare/vite-plugin": "^2.0.0-beta.sha-805ec1ff3", + "@cloudflare/vite-plugin": "^2.0.0-rc.0", cf: "1.0.0", }, name: "dry-run-test", diff --git a/packages/codemods/test/worker-config.test.ts b/packages/codemods/test/worker-config.test.ts index b22aba81d2..8ab746e414 100644 --- a/packages/codemods/test/worker-config.test.ts +++ b/packages/codemods/test/worker-config.test.ts @@ -26,6 +26,126 @@ function convert(source: Record): { }; } +describe("Workflow event migration", () => { + it("attaches each event to every matching owned export, preserving crons and filters", ({ + expect, + }) => { + const result = convert({ + name: "app", + compatibility_date: "2026-09-23", + exports: { First: { type: "workflow", name: "first" } }, + workflows: [{ binding: "SECOND", name: "second", class_name: "Second" }], + triggers: { + crons: ["0 * * * *"], + events: [ + { + type: "cf.artifacts.repo.pushed", + filter: { namespace: "ci", repo_name: "app" }, + targets: [ + { type: "workflow", workflow_name: "first" }, + { type: "workflow", workflow_name: "second" }, + ], + }, + ], + }, + }); + expect(result.followUps).toEqual([]); + expect( + result.output.match(/type: "cf.artifacts.repo.pushed"/g) + ).toHaveLength(2); + expect(result.output.match(/events: \[/g)).toHaveLength(2); + expect(result.output).toContain('repoName: "app"'); + expect(result.output).toContain('namespace: "ci"'); + expect(result.output).toContain("First: exports.workflow({"); + expect(result.output).toContain("Second: exports.workflow({"); + expect(result.output).toContain("triggers.scheduled({"); + expect(result.output).not.toContain("targets:"); + expect(result.output).not.toContain("triggers.event"); + }); + + it("does not duplicate events when a binding and export declare the same Workflow", ({ + expect, + }) => { + const result = convert({ + name: "app-staging", + compatibility_date: "2026-09-23", + exports: { Jobs: { type: "workflow", name: "jobs" } }, + workflows: [ + { + binding: "JOBS", + name: "jobs", + class_name: "Jobs", + script_name: "app-staging", + }, + ], + triggers: { + events: [ + { + type: "cf.artifacts.repo.created", + targets: [{ type: "workflow", workflow_name: "jobs" }], + }, + ], + }, + }); + expect(result.followUps).toEqual([]); + expect(result.output.match(/events: \[/g)).toHaveLength(1); + expect(result.output).not.toContain("filter:"); + }); + + it("reports an external or missing target instead of silently dropping it", ({ + expect, + }) => { + const result = convert({ + name: "app", + workflows: [ + { + binding: "REMOTE", + name: "remote", + class_name: "Remote", + script_name: "another-worker", + }, + ], + triggers: { + events: [ + { + type: "cf.artifacts.repo.created", + targets: [ + { type: "workflow", workflow_name: "remote" }, + { type: "workflow", workflow_name: "missing" }, + ], + }, + ], + }, + }); + expect( + result.followUps.filter(({ code }) => code === "workflow-event-target") + ).toMatchObject([ + { blocking: true, sourcePath: "triggers.events.0.targets.0" }, + { blocking: true, sourcePath: "triggers.events.0.targets.1" }, + ]); + expect(result.output).not.toContain("events:"); + }); + + it.for([ + null, + { type: "cf.artifacts.repo.created", targets: [] }, + { type: "cf.artifacts.repo.created", targets: [{}], filter: "invalid" }, + ])("reports malformed subscriptions %j", (event, { expect }) => { + const result = convert({ + name: "app", + compatibility_date: "2026-09-23", + triggers: { events: [event] }, + }); + expect(result.followUps).toMatchObject([ + { + code: "invalid-workflow-event", + blocking: true, + sourcePath: "triggers.events.0", + }, + ]); + }); +}); + describe("Wrangler Worker configuration conversion", () => { it("converts core settings, triggers, bindings, and exports", ({ expect, diff --git a/packages/codemods/test/wrangler-to-cf/experimental.test.ts b/packages/codemods/test/wrangler-to-cf/experimental.test.ts new file mode 100644 index 0000000000..2b7d543c93 --- /dev/null +++ b/packages/codemods/test/wrangler-to-cf/experimental.test.ts @@ -0,0 +1,39 @@ +import { describe, it } from "vitest"; +import { convertWranglerConfig } from "../../src/codemods/wrangler-to-cf/config-converter"; +import { renderCloudflareConfig } from "../../src/codemods/wrangler-to-cf/config-renderer"; +import type { RawConfig } from "@cloudflare/workers-utils"; + +describe("experimental Worker settings", () => { + it("moves `first_party_worker` under `experimental`", ({ expect }) => { + const converted = convertWranglerConfig( + { + compatibility_date: "2026-09-23", + name: "first-party", + first_party_worker: true, + streaming_tail_consumers: [{ service: "streaming-tail" }], + } satisfies RawConfig, + "wrangler", + [] + ); + + expect(renderCloudflareConfig(converted)).toMatchInlineSnapshot(` + "import { defineConfig } from "cf/config"; + + export default defineConfig({ + worker: { + name: "first-party", + compatibilityDate: "2026-09-23", + experimental: { + streamingTailConsumers: [ + { + worker: "streaming-tail", + }, + ], + firstPartyWorker: true, + }, + }, + }); + " + `); + }); +}); diff --git a/packages/codemods/test/wrangler-to-cf/migration-api.test.ts b/packages/codemods/test/wrangler-to-cf/migration-api.test.ts index 8232894d9f..0821171092 100644 --- a/packages/codemods/test/wrangler-to-cf/migration-api.test.ts +++ b/packages/codemods/test/wrangler-to-cf/migration-api.test.ts @@ -9,7 +9,6 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { runCommand } from "@cloudflare/cli-shared-helpers/command"; import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; import { afterEach, describe, it, vi } from "vitest"; import { migrateWranglerToCf } from "../../src"; @@ -23,9 +22,6 @@ const temporaryDirectories: string[] = []; vi.mock("@cloudflare/cli-shared-helpers/packages", () => ({ installPackages: vi.fn(), })); -vi.mock("@cloudflare/cli-shared-helpers/command", () => ({ - runCommand: vi.fn(), -})); vi.mock( "../../src/codemods/wrangler-to-cf/file-writer", @@ -85,7 +81,7 @@ describe("migrateWranglerToCf", () => { }), "package.json": JSON.stringify({ devDependencies: { - "@cloudflare/vite-plugin": "beta", + "@cloudflare/vite-plugin": "^2.0.0-rc.0", cf: "1.0.0", }, }), @@ -206,7 +202,7 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( "pnpm", - ["cf@latest", "@cloudflare/vite-plugin@beta"], + ["cf@latest", "@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd, dev: true, isWorkspaceRoot: false } ); expect(result.changedFiles).toEqual([ @@ -252,7 +248,7 @@ describe("migrateWranglerToCf", () => { path.join(cwd, "package.json"), JSON.stringify({ devDependencies: { - "@cloudflare/vite-plugin": "beta", + "@cloudflare/vite-plugin": "^2.0.0-rc.0", cf: "1.0.0-beta.5", }, packageManager: `${packageManager}@${packageManagerVersion}`, @@ -270,7 +266,7 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( packageManager, - ["@cloudflare/vite-plugin@beta"], + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd, dev: true, isWorkspaceRoot: false } ); expect(result.changedFiles).toEqual([ @@ -283,114 +279,16 @@ describe("migrateWranglerToCf", () => { ); it.for([ - { packageManager: "npm", lockFile: "package-lock.json" }, - { packageManager: "pnpm", lockFile: "pnpm-lock.yaml" }, - { packageManager: "yarn", lockFile: "yarn.lock" }, - { packageManager: "bun", lockFile: "bun.lock" }, - { packageManager: "nub", lockFile: "nub.lock" }, - ] as const)( - "sets beta when $packageManager saves a resolved Vite plugin version", - async ({ packageManager, lockFile }, { expect }) => { - const cwd = await createProject({ - "package.json": JSON.stringify({ - devDependencies: { - "@cloudflare/vite-plugin": "^1.60.2", - cf: "1.0.0-beta.5", - }, - packageManager: `${packageManager}@1.2.0`, - }), - [lockFile]: "old lockfile", - "wrangler.json": JSON.stringify({ - compatibility_date: "2026-09-23", - name: "example-worker", - }), - }); - vi.mocked(installPackages).mockImplementationOnce(async () => { - await writeFile( - path.join(cwd, "package.json"), - JSON.stringify({ - devDependencies: { - "@cloudflare/vite-plugin": "^2.0.0-beta.sha-805ec1ff3", - cf: "1.0.0-beta.5", - }, - packageManager: `${packageManager}@1.2.0`, - }) - ); - await writeFile(path.join(cwd, lockFile), "resolved lockfile"); - }); - const syncLockfile = async () => { - await writeFile(path.join(cwd, lockFile), "synced lockfile"); - }; - if (packageManager === "bun") { - vi.mocked(runCommand).mockImplementationOnce(async () => { - await syncLockfile(); - return ""; - }); - } else { - vi.mocked(installPackages).mockImplementationOnce(syncLockfile); - } - - const result = await migrateWranglerToCf(path.join(cwd, "wrangler.json")); - - expect(vi.mocked(installPackages)).toHaveBeenNthCalledWith( - 1, - packageManager, - ["@cloudflare/vite-plugin@beta"], - { cwd, dev: true, isWorkspaceRoot: false } - ); - if (packageManager === "bun") { - expect(vi.mocked(runCommand)).toHaveBeenCalledWith(["bun", "install"], { - cwd, - silent: true, - }); - } else { - expect(vi.mocked(installPackages)).toHaveBeenNthCalledWith( - 2, - packageManager, - [], - { cwd, isWorkspaceRoot: false } - ); - } - expect( - JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8")) - .devDependencies["@cloudflare/vite-plugin"] - ).toBe("beta"); - expect(await readFile(path.join(cwd, lockFile), "utf8")).toBe( - "synced lockfile" - ); - expect(result.changedFiles).toEqual([ - "cloudflare.config.ts", - "package.json", - lockFile, - ]); - } - ); - - it.for([ + { declaredVersion: "^2.0.0-rc.0", installedVersion: "2.0.0-rc.0" }, + { declaredVersion: "^2.0.0-rc.3", installedVersion: "2.0.0-rc.3" }, + { declaredVersion: "2.0.0-rc.1", installedVersion: "2.0.0-rc.1" }, + { declaredVersion: "^2", installedVersion: "2.1.0" }, { - declaredVersion: "^2.0.0-beta.sha-805ec1ff3", - installedVersion: "2.0.0-beta.sha-805ec1ff3", - }, - { - declaredVersion: "^2.0.0-beta.123", - installedVersion: "2.0.0-beta.123", - }, - { - declaredVersion: "beta", - installedVersion: "2.0.0-beta.sha-805ec1ff3", - }, - { - declaredVersion: ">=2.0.0-0 <3.0.0-0", - installedVersion: "2.0.0-beta.sha-805ec1ff3", - }, - { - declaredVersion: "workspace:*", - installedVersion: "2.0.0-beta.sha-805ec1ff3", - }, - { - declaredVersion: "catalog:default", - installedVersion: "2.0.0-beta.sha-805ec1ff3", + declaredVersion: ">=2.0.0-rc.0 <3.0.0-0", + installedVersion: "2.0.0-rc.0", }, + { declaredVersion: "workspace:*", installedVersion: "2.0.0-rc.0" }, + { declaredVersion: "catalog:default", installedVersion: "2.0.0-rc.0" }, ])( "keeps a compatible Vite plugin declared as $declaredVersion unchanged", async ({ declaredVersion, installedVersion }, { expect }) => { @@ -423,8 +321,48 @@ describe("migrateWranglerToCf", () => { } ); + it.for([ + { declaredVersion: "beta", installedVersion: "2.0.0-beta.v.17" }, + { declaredVersion: "rc", installedVersion: "2.0.0-rc.0" }, + { declaredVersion: "^2.0.0-beta.v.0", installedVersion: "2.0.0-beta.v.17" }, + { + declaredVersion: ">=2.0.0-0 <3.0.0-0", + installedVersion: "2.0.0-beta.v.17", + }, + { declaredVersion: "^2.0.0-rc.0", installedVersion: "2.0.0-beta.v.17" }, + ])( + "upgrades a Vite plugin declared as $declaredVersion with installed version $installedVersion", + async ({ declaredVersion, installedVersion }, { expect }) => { + const cwd = await createProject({ + "node_modules/@cloudflare/vite-plugin/package.json": JSON.stringify({ + name: "@cloudflare/vite-plugin", + version: installedVersion, + }), + "package.json": JSON.stringify({ + devDependencies: { + "@cloudflare/vite-plugin": declaredVersion, + cf: "1.0.0-beta.5", + }, + }), + "wrangler.json": JSON.stringify({ + compatibility_date: "2026-09-23", + name: "example-worker", + }), + }); + + await migrateWranglerToCf(path.join(cwd, "wrangler.json")); + + expect(vi.mocked(installPackages)).toHaveBeenCalledExactlyOnceWith( + "npm", + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], + { cwd, dev: true, isWorkspaceRoot: false } + ); + } + ); + it.for([ { declaredVersion: "workspace:*", installedVersion: "1.60.2" }, + { declaredVersion: "workspace:*", installedVersion: "2.0.0-beta.v.17" }, { declaredVersion: "workspace:*", installedVersion: undefined }, { declaredVersion: "file:../vite-plugin", installedVersion: "1.60.2" }, { declaredVersion: "link:../vite-plugin", installedVersion: "1.60.2" }, @@ -511,7 +449,7 @@ describe("migrateWranglerToCf", () => { }), "package.json": JSON.stringify({ devDependencies: { - "@cloudflare/vite-plugin": "^2.0.0-beta.sha-805ec1ff3", + "@cloudflare/vite-plugin": "^2.0.0-rc.0", cf: "1.0.0-beta.5", }, }), @@ -525,7 +463,7 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( "npm", - ["@cloudflare/vite-plugin@beta"], + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd, dev: true, isWorkspaceRoot: false } ); }); @@ -549,7 +487,7 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( "npm", - ["@cloudflare/vite-plugin@beta"], + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd, dev: true, isWorkspaceRoot: false } ); }); @@ -570,19 +508,9 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( "npm", - ["@cloudflare/vite-plugin@beta"], + ["@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd, dev: false, isWorkspaceRoot: false } ); - const packageJson = JSON.parse( - await readFile(path.join(cwd, "package.json"), "utf8") - ) as { - dependencies: Record; - devDependencies: Record; - }; - expect(packageJson.dependencies["@cloudflare/vite-plugin"]).toBe("beta"); - expect(packageJson.devDependencies).not.toHaveProperty( - "@cloudflare/vite-plugin" - ); }); it("leaves the Vite plugin unchanged for Wrangler migration", async ({ @@ -673,7 +601,7 @@ describe("migrateWranglerToCf", () => { status: "needs-intervention", }); expect(result.followUps[0].message).toContain( - "@cloudflare/vite-plugin@beta" + "@cloudflare/vite-plugin@^2.0.0-rc.0" ); }); @@ -865,7 +793,7 @@ describe("migrateWranglerToCf", () => { expect(vi.mocked(installPackages)).toHaveBeenCalledWith( "pnpm", - ["cf@latest", "@cloudflare/vite-plugin@beta"], + ["cf@latest", "@cloudflare/vite-plugin@^2.0.0-rc.0"], { cwd: workerDirectory, dev: true, isWorkspaceRoot: false } ); expect(previewResult.changedFiles).toContain(rootLockFile); @@ -1089,65 +1017,6 @@ describe("migrateWranglerToCf", () => { expect(cloudflareConfig).toContain("Migration incomplete."); }); - it("reports a lockfile sync failure after installing cf and the Vite plugin", async ({ - expect, - }) => { - const cwd = await createProject({ - "package.json": JSON.stringify({ - devDependencies: { "@cloudflare/vite-plugin": "^1.60.2" }, - packageManager: "pnpm@10.27.0", - }), - "pnpm-lock.yaml": "old lockfile", - "wrangler.json": JSON.stringify({ - compatibility_date: "2026-09-23", - name: "example-worker", - }), - }); - vi.mocked(installPackages) - .mockImplementationOnce(async () => { - await writeFile( - path.join(cwd, "package.json"), - JSON.stringify({ - devDependencies: { - "@cloudflare/vite-plugin": "^2.0.0-beta.123", - cf: "latest", - }, - packageManager: "pnpm@10.27.0", - }) - ); - await writeFile(path.join(cwd, "pnpm-lock.yaml"), "installed lockfile"); - }) - .mockRejectedValueOnce(new Error("Lockfile is read-only.")); - - const result = await migrateWranglerToCf(path.join(cwd, "wrangler.json")); - - expect(vi.mocked(installPackages)).toHaveBeenNthCalledWith(2, "pnpm", [], { - cwd, - isWorkspaceRoot: false, - }); - expect(result).toMatchObject({ - changedFiles: ["cloudflare.config.ts", "package.json", "pnpm-lock.yaml"], - followUps: [{ blocking: true, code: "vite-plugin-lockfile-sync-failed" }], - requiresInstall: true, - status: "needs-intervention", - }); - expect(result.followUps[0].message).toContain( - "lockfile could not be synchronized" - ); - expect(result.followUps[0].message).not.toContain("cf@latest"); - expect(result.followUps[0].message).not.toContain("could not be installed"); - expect( - JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8")) - .devDependencies - ).toMatchObject({ - "@cloudflare/vite-plugin": "beta", - cf: "latest", - }); - expect(await readFile(path.join(cwd, "pnpm-lock.yaml"), "utf8")).toBe( - "installed lockfile" - ); - }); - it("reports package files changed before a later install fails", async ({ expect, }) => { @@ -1361,7 +1230,7 @@ describe("migrateWranglerToCf", () => { }) => { const manifest = JSON.stringify({ devDependencies: { - "@cloudflare/vite-plugin": "beta", + "@cloudflare/vite-plugin": "^2.0.0-rc.0", cf: "^1.0.0", wrangler: "^4.99.0", }, diff --git a/packages/codemods/test/wrangler-to-cf/stream-bindings.test.ts b/packages/codemods/test/wrangler-to-cf/stream-bindings.test.ts new file mode 100644 index 0000000000..fbb0933d9c --- /dev/null +++ b/packages/codemods/test/wrangler-to-cf/stream-bindings.test.ts @@ -0,0 +1,87 @@ +import { describe, it } from "vitest"; +import { convertWranglerConfig } from "../../src/codemods/wrangler-to-cf/config-converter"; +import { renderCloudflareConfig } from "../../src/codemods/wrangler-to-cf/config-renderer"; +import type { RawConfig } from "@cloudflare/workers-utils"; + +const streamId = "0123456789abcdef0123456789abcdef"; + +describe("stream binding conversion", () => { + it("maps Pipelines and K2 stream IDs", ({ expect }) => { + const converted = convertWranglerConfig( + { + compatibility_date: "2026-09-23", + name: "streams", + pipelines: [{ binding: "EVENTS", stream: streamId }], + k2: [{ binding: "ORDERS", stream: streamId }], + } satisfies RawConfig, + "wrangler", + [] + ); + + expect(converted.followUps).toEqual([]); + expect(renderCloudflareConfig(converted)).toMatchInlineSnapshot(` + "import { bindings, defineConfig } from "cf/config"; + + export default defineConfig({ + worker: { + name: "streams", + compatibilityDate: "2026-09-23", + env: { + ORDERS: bindings.k2({ + id: "0123456789abcdef0123456789abcdef", + }), + EVENTS: bindings.pipeline({ + streamId: "0123456789abcdef0123456789abcdef", + }), + }, + }, + }); + " + `); + }); + + it("reports a binding that uses the deprecated `pipeline` field", ({ + expect, + }) => { + const converted = convertWranglerConfig( + { + compatibility_date: "2026-09-23", + name: "legacy-pipeline", + pipelines: [{ binding: "EVENTS", pipeline: "my-pipeline" }], + } satisfies RawConfig, + "wrangler", + [] + ); + + expect(converted.followUps.map(({ code }) => code)).toEqual([ + "legacy-pipeline-binding", + ]); + expect(renderCloudflareConfig(converted)).toMatchInlineSnapshot(` + "import { bindings, defineConfig } from "cf/config"; + + /** + * This migration needs manual work. Resolve every TODO in this file, then remove the error below. + */ + /** + * TODO(@cloudflare): cf migrate: pipelines.0: The Pipelines binding at \`pipelines.0\` used the deprecated \`pipeline\` field, which names a legacy pipeline. Set \`streamId\` to the ID of the stream to write to. + */ + throw new Error("Migration incomplete. Resolve every cf migrate TODO in \`cloudflare.config.ts\`."); + + export default defineConfig({ + worker: { + name: "legacy-pipeline", + compatibilityDate: "2026-09-23", + env: { + EVENTS: bindings.pipeline({ + /** + * TODO(@cloudflare): cf migrate: The Pipelines binding at \`pipelines.0\` used the deprecated \`pipeline\` field, which names a legacy pipeline. Set \`streamId\` to the ID of the stream to write to. + */ + streamId: "STREAM_ID", + }), + }, + }, + }); + " + `); + }); +}); diff --git a/packages/config/CHANGELOG.md b/packages/config/CHANGELOG.md index fc8eb07647..25771a8d65 100644 --- a/packages/config/CHANGELOG.md +++ b/packages/config/CHANGELOG.md @@ -1,5 +1,65 @@ # @cloudflare/config +## 1.0.0-rc.0 + +### Major Changes + +- [#16907](https://github.com/cloudflare/workers-sdk/pull/16907) [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Release the 1.0 release candidate + + This release finalises the binding and Worker field names, and includes breaking changes: + + - `firstPartyWorker` moves from the Worker's top level to `experimental.firstPartyWorker`. + - `bindings.pipeline()` takes `streamId` in place of `name`. Set it to the ID of the Pipelines stream, not its name. Legacy pipelines aren't supported. + - `bindings.k2()` takes `id` in place of `stream`. Set it to the ID of the K2 stream. + - `bindings.analytics()` is renamed to `bindings.analyticsSql()`. Its binding type changes from `"analytics"` to `"analytics-sql"`. The `AnalyticsSQLBinding`, `AnalyticsSQLBindingOptions` and `AnalyticsSQLBindingSchema` exports are renamed to `AnalyticsSqlBinding`, `AnalyticsSqlBindingOptions` and `AnalyticsSqlBindingSchema`. + - The `KVBindingSchema` export is renamed to `KvBindingSchema`. + - The `ConnectTriggerOptionsBase` type is no longer exported. Use `ConnectTriggerOptions` instead. + - The `InputWorkerConfig` type is no longer exported. Use `z.input` if you need it. + - The config schemas and their parsed types are renamed after what they describe. The `Input` and `Output` prefixes are replaced by the public type names and `BuildOutput`: + - `InputConfigSchema` → `CloudflareConfigSchema`, `ParsedInputConfig` → `ParsedCloudflareConfig` + - `InputSettingsSchema` → `SettingsSchema`, `ParsedInputSettingsConfig` → `ParsedSettings` + - `InputWorkerSchema` → `WorkerConfigSchema`, `ParsedInputWorkerConfig` → `ParsedWorkerConfig` + - `InputContainerSchema` → `ContainerConfigSchema`, `ParsedInputContainerConfig` → `ParsedContainerConfig` + - `OutputRootConfigSchema` → `BuildOutputRootConfigSchema`, `ParsedOutputRootConfig` → `ParsedBuildOutputRootConfig` + - `OutputWorkerSchema` → `BuildOutputWorkerConfigSchema`, `ParsedOutputWorkerConfig` → `ParsedBuildOutputWorkerConfig` + - `OutputContainerSchema` → `BuildOutputContainerConfigSchema`, `ParsedOutputContainerConfig` → `ParsedBuildOutputContainerConfig` + + Setting the old `name` or `stream` field fails with an error that names the replacement field. Editors also show both fields as deprecated. + + The schema no longer fills in defaults. A parsed config without Containers leaves `containers` undefined instead of setting it to `[]`, and a Container without `maxInstances` leaves it undefined instead of setting it to `20`. Deploying still uses 20 instances when `maxInstances` isn't set. + + Queue consumer `maxConcurrency` no longer accepts `null`. Wrangler already rejected it. + +### Minor Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Nest settings under an optional `settings` and add an optional `producer` in `BuildOutputRootConfigSchema` + + The root `config.json` in Build Output v1 has the shape `{ producer?, settings?, buildContext }`. `settings` holds the account settings from `cloudflare.config.ts`, is validated strictly, and is left out when none are set. `producer` is `{ name, version }` for the tool that wrote the output and is used only in diagnostics. The new `BuildOutputProducerSchema` and `ParsedBuildOutputProducer` are also exported. + +- [#16246](https://github.com/cloudflare/workers-sdk/pull/16246) [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155) Thanks [@leostera](https://github.com/leostera)! - Start local Workflows from Artifacts events + + Declare Artifacts events on `exports.workflow({ name, events })` in `cloudflare.config.ts` to start the owning Workflow locally in `cf`, Vite, and Workers Vitest. Wrangler configurations continue to use `triggers.events`. Native config conversion derives those targets from the Workflow export, and `cf migrate` attaches existing event subscriptions to their matching Workflow exports. + + Local Artifacts namespaces publish the documented `cf.artifacts.*` messages for repository create, import, fork, and delete operations and token creation and revocation. Successful create, import, and fork operations also publish the initial token-created event. Delivery follows the committed mutation, is unordered, and does not fail the repository operation if a destination rejects it. Push, clone, and fetch events are not yet published locally. This feature does not provide local Artifacts-to-queue subscriptions. + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +## 0.32.1 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + ## 0.32.0 ### Minor Changes diff --git a/packages/config/package.json b/packages/config/package.json index d610641145..cc5916427e 100644 --- a/packages/config/package.json +++ b/packages/config/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/config", - "version": "0.32.0", + "version": "1.0.0-rc.0", "description": "Definitions and utilities for configuring Cloudflare Workers and related products. This is not yet stable enough for external use — APIs may change without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/config#readme", "bugs": { @@ -47,6 +47,10 @@ "vitest": "catalog:default" }, "workers-sdk": { - "prerelease": true + "prerelease": true, + "npmPrerelease": { + "tag": "rc", + "numbered": true + } } } diff --git a/packages/config/src/__tests__/artifacts-events.test.ts b/packages/config/src/__tests__/artifacts-events.test.ts new file mode 100644 index 0000000000..ca43ab040d --- /dev/null +++ b/packages/config/src/__tests__/artifacts-events.test.ts @@ -0,0 +1,122 @@ +import { ARTIFACTS_EVENT_TYPES as WRANGLER_EVENT_TYPES } from "@cloudflare/workers-utils"; +import { describe, it } from "vitest"; +import { convertToWranglerConfig } from "../convert"; +import { exports, triggers } from "../public"; +import { WorkerConfigSchema, BuildOutputWorkerConfigSchema } from "../schema"; +import { ARTIFACTS_EVENT_TYPES } from "../workflow-events"; +import type { WorkerConfig, ArtifactsEventSubscription } from "../public"; + +const event = { + type: "cf.artifacts.repo.created", + filter: { namespace: "examples", repoName: "demo" }, +} satisfies ArtifactsEventSubscription; +const worker = { + name: "example", + compatibilityDate: "2026-09-03", + exports: { OnRepo: exports.workflow({ name: "on-repo", events: [event] }) }, + triggers: [triggers.scheduled({ schedule: "0 * * * *" })], +} satisfies WorkerConfig; + +it("supports the same event types as Wrangler", ({ expect }) => { + expect(ARTIFACTS_EVENT_TYPES).toEqual(WRANGLER_EVENT_TYPES); +}); + +describe.each([ + ["input", WorkerConfigSchema], + ["output", BuildOutputWorkerConfigSchema], +] as const)("%s Workflow events", (_name, schema) => { + it.for(ARTIFACTS_EVENT_TYPES)( + "accepts %s on a Workflow export", + (type, { expect }) => { + const workflow = exports.workflow({ + name: "on-repo", + events: [{ ...event, type }], + }); + expect( + schema.parse({ ...worker, exports: { OnRepo: workflow } }).exports + ).toEqual({ OnRepo: workflow }); + } + ); + it.for([ + { type: "unknown" }, + { filter: { namespace: "" } }, + { filter: { repoName: "" } }, + { filter: { repo_name: "demo" } }, + { targets: [{ type: "workflow", workflowName: "other" }] }, + ])("rejects invalid event properties %j", (invalid, { expect }) => { + expect( + schema.safeParse({ + ...worker, + exports: { + OnRepo: { + type: "workflow", + name: "on-repo", + events: [{ ...event, ...invalid }], + }, + }, + }).success + ).toBe(false); + }); + it("rejects the removed top-level event trigger shape", ({ expect }) => { + expect( + schema.safeParse({ + ...worker, + triggers: [ + { + type: "artifacts-event", + eventType: event.type, + targets: [{ type: "workflow", workflowName: "on-repo" }], + }, + ], + }).success + ).toBe(false); + }); +}); + +it("converts Workflow-owned events to Wrangler subscriptions without losing crons", ({ + expect, +}) => { + const result = convertToWranglerConfig({ + worker: WorkerConfigSchema.parse(worker), + containers: [], + }); + expect(result.triggers).toEqual({ + crons: ["0 * * * *"], + events: [ + { + type: event.type, + filter: { namespace: "examples", repo_name: "demo" }, + targets: [{ type: "workflow", workflow_name: "on-repo" }], + }, + ], + }); + expect(result.exports?.OnRepo).toEqual({ type: "workflow", name: "on-repo" }); +}); + +it("derives each target from its owner and omits absent filters", ({ + expect, +}) => { + const config = { + ...worker, + exports: { + First: exports.workflow({ + name: "first", + events: [{ type: event.type }], + }), + Second: exports.workflow({ + name: "second", + events: [{ type: event.type }], + }), + }, + }; + const result = convertToWranglerConfig({ + worker: WorkerConfigSchema.parse(config), + containers: [], + }); + expect(result.triggers?.events).toEqual( + ["first", "second"].map((workflow_name) => ({ + type: event.type, + targets: [{ type: "workflow", workflow_name }], + })) + ); +}); diff --git a/packages/config/src/__tests__/config-definition.test-d.ts b/packages/config/src/__tests__/config-definition.test-d.ts index 0162b1e193..0c74f25811 100644 --- a/packages/config/src/__tests__/config-definition.test-d.ts +++ b/packages/config/src/__tests__/config-definition.test-d.ts @@ -42,9 +42,9 @@ const inlineConfig = defineConfig({ ], }); -const analyticsBinding = bindings.analytics({ dev: { remote: true } }); -export type AnalyticsBindingTypeTest = Assert< - Equal +const analyticsSqlBinding = bindings.analyticsSql({ dev: { remote: true } }); +export type AnalyticsSqlBindingTypeTest = Assert< + Equal >; // @ts-expect-error a workflow export requires a name diff --git a/packages/config/src/__tests__/config-loader.test.ts b/packages/config/src/__tests__/config-loader.test.ts index 84477b7dc6..54c0a4ee65 100644 --- a/packages/config/src/__tests__/config-loader.test.ts +++ b/packages/config/src/__tests__/config-loader.test.ts @@ -130,9 +130,7 @@ describe("resolveAndParseConfig", () => { } }); - it("accepts an inline Worker and defaults containers to an empty array", async ({ - expect, - }) => { + it("accepts an inline Worker without containers", async ({ expect }) => { const result = await resolveAndParseConfig( { worker: { name: "web", compatibilityDate }, @@ -143,7 +141,7 @@ describe("resolveAndParseConfig", () => { expect(result.success).toBe(true); if (result.success) { expect(result.data.worker?.name).toBe("web"); - expect(result.data.containers).toEqual([]); + expect(result.data.containers).toBeUndefined(); } }); @@ -178,7 +176,6 @@ describe("resolveAndParseConfig", () => { data: { accountId: "account-id", complianceRegion: "public", - containers: [], }, }); }); diff --git a/packages/config/src/__tests__/convert.test.ts b/packages/config/src/__tests__/convert.test.ts index a4c7b53240..88953a4c41 100644 --- a/packages/config/src/__tests__/convert.test.ts +++ b/packages/config/src/__tests__/convert.test.ts @@ -1,6 +1,6 @@ import { describe, it } from "vitest"; import { convertToWranglerConfig } from "../convert"; -import type { ParsedInputConfig } from "../schema"; +import type { ParsedCloudflareConfig } from "../schema"; const baseWorker = { name: "my-worker", @@ -19,7 +19,7 @@ describe("convertToWranglerConfig", () => { workersDev: true, previewUrls: false, logpush: true, - firstPartyWorker: false, + experimental: { firstPartyWorker: false }, }, containers: [], }); @@ -210,7 +210,7 @@ describe("convertToWranglerConfig", () => { env: { MY_AI: { type: "ai" }, MY_BROWSER: { type: "browser" }, - MY_ANALYTICS: { type: "analytics" }, + MY_ANALYTICS: { type: "analytics-sql" }, MY_IMAGES: { type: "images" }, MY_MEDIA: { type: "media" }, MY_STREAM: { type: "stream" }, @@ -421,16 +421,17 @@ describe("convertToWranglerConfig", () => { ]); }); - it("maps pipeline.name to stream", ({ expect }) => { + it("maps pipeline.streamId to stream", ({ expect }) => { + const streamId = "0123456789abcdef0123456789abcdef"; const result = convertToWranglerConfig({ worker: { ...baseWorker, - env: { MY_PIPE: { type: "pipeline", name: "pipe-1" } }, + env: { MY_PIPE: { type: "pipeline", streamId } }, }, containers: [], }); expect(result.pipelines).toEqual([ - { binding: "MY_PIPE", stream: "pipe-1" }, + { binding: "MY_PIPE", stream: streamId }, ]); }); @@ -1209,7 +1210,7 @@ describe("convertToWranglerConfig", () => { exports: { FutureExport: { type: "future" }, }, - } as unknown as NonNullable; + } as unknown as NonNullable; expect(() => convertToWranglerConfig({ worker: config, containers: [] }) @@ -1660,6 +1661,32 @@ describe("convertToWranglerConfig", () => { expect(result).not.toHaveProperty("containers"); }); + it("omits containers when the config has no containers", ({ expect }) => { + const result = convertToWranglerConfig({ worker: baseWorker }); + + expect(result).not.toHaveProperty("containers"); + }); + + it("omits max_instances when maxInstances isn't set", ({ expect }) => { + const result = convertToWranglerConfig({ + worker: baseWorker, + containers: [ + { + name: "default-capacity", + image: { reference: "registry.example.com/image:tag" }, + }, + ], + }); + + expect(result.containers).toEqual([ + { + name: "default-capacity", + image: "registry.example.com/image:tag", + }, + ]); + expect(result.containers?.[0]).not.toHaveProperty("max_instances"); + }); + it("converts standard Container exports to Wrangler containers", ({ expect, }) => { @@ -1694,7 +1721,7 @@ describe("convertToWranglerConfig", () => { targetInstancePercentage: 50, }, unsafe: { experimental: true }, - } satisfies ParsedInputConfig["containers"][number]; + } satisfies NonNullable[number]; const referencedContainer = { name: "referenced-container", image: { reference: "registry.example.com/image:tag" }, @@ -1703,7 +1730,7 @@ describe("convertToWranglerConfig", () => { enabled: true, targetInstanceCount: 2, }, - } satisfies ParsedInputConfig["containers"][number]; + } satisfies NonNullable[number]; const result = convertToWranglerConfig({ worker: baseWorker, containers: [dockerfileContainer, referencedContainer], diff --git a/packages/config/src/__tests__/k2.test-d.ts b/packages/config/src/__tests__/k2.test-d.ts index cf4809b5b5..6af86e3990 100644 --- a/packages/config/src/__tests__/k2.test-d.ts +++ b/packages/config/src/__tests__/k2.test-d.ts @@ -6,7 +6,7 @@ const config = defineWorker({ compatibilityDate: "2025-04-28", env: { ORDERS: bindings.k2({ - stream: "0123456789abcdef0123456789abcdef", + id: "0123456789abcdef0123456789abcdef", }), }, }); diff --git a/packages/config/src/__tests__/k2.test.ts b/packages/config/src/__tests__/k2.test.ts index 40d62a7438..b1246b0d16 100644 --- a/packages/config/src/__tests__/k2.test.ts +++ b/packages/config/src/__tests__/k2.test.ts @@ -9,7 +9,7 @@ describe("K2 producer bindings", () => { it.for([stream, "stream-v2:orders", ""])( "preserves the stream identifier when converting shared configuration: %j", (streamId, { expect }) => { - const binding = bindings.k2({ stream: streamId }); + const binding = bindings.k2({ id: streamId }); expect(BindingSchema.parse(binding)).toEqual(binding); expect( convertToWranglerConfig({ @@ -31,9 +31,7 @@ describe("K2 producer bindings", () => { it.for([undefined, null, 42, {}])( "requires a string stream identifier: %j", (id, { expect }) => { - expect(BindingSchema.safeParse({ type: "k2", stream: id }).success).toBe( - false - ); + expect(BindingSchema.safeParse({ type: "k2", id }).success).toBe(false); } ); @@ -44,7 +42,20 @@ describe("K2 producer bindings", () => { BindingSchema.safeParse({ type: "k2", pipeline: stream }).success ).toBe(false); expect( - BindingSchema.safeParse({ type: "k2", stream, staging: true }).success + BindingSchema.safeParse({ type: "k2", id: stream, staging: true }).success ).toBe(false); }); + + it.for([ + { type: "k2", stream }, + { type: "k2", stream, id: stream }, + ])("explains that `stream` was renamed: %j", (binding, { expect }) => { + const result = BindingSchema.safeParse(binding); + expect(result.success).toBe(false); + expect(result.error?.issues[0]).toMatchObject({ + path: ["stream"], + message: + '"stream" was renamed to "id". Set "id" to the ID of the K2 stream.', + }); + }); }); diff --git a/packages/config/src/__tests__/parsed-config-is-input.test-d.ts b/packages/config/src/__tests__/parsed-config-is-input.test-d.ts new file mode 100644 index 0000000000..3aace52d52 --- /dev/null +++ b/packages/config/src/__tests__/parsed-config-is-input.test-d.ts @@ -0,0 +1,15 @@ +// Parsed configuration must be valid schema input. Consumers such as the Vite +// plugin pass parsed configuration to customizers, then parse what they return. +// If the schema gains a `.transform()` (or a narrower input type) that breaks +// this, these assignments stop compiling. +import type { CloudflareConfigSchema, WorkerConfigSchema } from "../schema"; +import type * as z from "zod"; + +declare const parsedConfig: z.output; +const configInput: z.input = parsedConfig; +void configInput; + +declare const parsedWorkerConfig: z.output; +const workerConfigInput: z.input = + parsedWorkerConfig; +void workerConfigInput; diff --git a/packages/config/src/__tests__/pipeline.test.ts b/packages/config/src/__tests__/pipeline.test.ts new file mode 100644 index 0000000000..6c4b786234 --- /dev/null +++ b/packages/config/src/__tests__/pipeline.test.ts @@ -0,0 +1,34 @@ +import { describe, it } from "vitest"; +import { bindings } from "../bindings"; +import { BindingSchema } from "../schema"; + +const streamId = "0123456789abcdef0123456789abcdef"; + +describe("Pipelines bindings", () => { + it("accepts a stream ID", ({ expect }) => { + const binding = bindings.pipeline({ streamId }); + expect(BindingSchema.parse(binding)).toEqual(binding); + }); + + it.for([undefined, null, 42, {}])( + "requires a string stream ID: %j", + (value, { expect }) => { + expect( + BindingSchema.safeParse({ type: "pipeline", streamId: value }).success + ).toBe(false); + } + ); + + it.for([ + { type: "pipeline", name: "my-stream" }, + { type: "pipeline", name: streamId, streamId }, + ])("explains that `name` was renamed: %j", (binding, { expect }) => { + const result = BindingSchema.safeParse(binding); + expect(result.success).toBe(false); + expect(result.error?.issues[0]).toMatchObject({ + path: ["name"], + message: + '"name" was renamed to "streamId". Set "streamId" to the ID of the Pipelines stream, not its name.', + }); + }); +}); diff --git a/packages/config/src/__tests__/schema.test.ts b/packages/config/src/__tests__/schema.test.ts index 16a6ead8ec..c12c57a2d7 100644 --- a/packages/config/src/__tests__/schema.test.ts +++ b/packages/config/src/__tests__/schema.test.ts @@ -2,15 +2,15 @@ import { describe, it } from "vitest"; import { exports as exportConfig } from "../exports"; import { BindingSchema, - InputConfigSchema, - InputContainerSchema, - InputSettingsSchema, - InputWorkerSchema, - OutputContainerSchema, - OutputRootConfigSchema, - OutputWorkerSchema, + CloudflareConfigSchema, + ContainerConfigSchema, + SettingsSchema, + WorkerConfigSchema, + BuildOutputContainerConfigSchema, + BuildOutputRootConfigSchema, + BuildOutputWorkerConfigSchema, } from "../schema"; -import type { ParsedInputWorkerConfig } from "../schema"; +import type { ParsedWorkerConfig } from "../schema"; const baseConfig = { name: "my-worker", @@ -26,8 +26,8 @@ const baseOutputConfig = { ...baseConfig } as const; const baseOutputContainer = { ...baseContainer } as const; describe.each([ - ["input", InputWorkerSchema], - ["output", OutputWorkerSchema], + ["input", WorkerConfigSchema], + ["output", BuildOutputWorkerConfigSchema], ] as const)("%s Worker domains", (_name, schema) => { it.for([ { production: true, previews: false }, @@ -68,8 +68,8 @@ describe.each([ }); describe.each([ - ["input", InputWorkerSchema], - ["output", OutputWorkerSchema], + ["input", WorkerConfigSchema], + ["output", BuildOutputWorkerConfigSchema], ] as const)("%s Worker tail consumers", (_name, schema) => { it("accepts tail and experimental streaming tail consumers", ({ expect }) => { const result = schema.parse({ @@ -102,28 +102,28 @@ describe.each([ }); }); -describe("InputWorkerSchema", () => { +describe("WorkerConfigSchema", () => { describe("env singleton bindings", () => { it("accepts undefined env", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ ...baseConfig }); + const result = WorkerConfigSchema.safeParse({ ...baseConfig }); expect(result.success).toBe(true); }); it("accepts empty env", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ ...baseConfig, env: {} }); + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: {} }); expect(result.success).toBe(true); }); it("accepts a single singleton binding of each type", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_AI: { type: "ai" }, MY_ASSETS: { type: "assets" }, MY_BROWSER: { type: "browser" }, - MY_ANALYTICS: { type: "analytics" }, + MY_ANALYTICS: { type: "analytics-sql" }, MY_IMAGES: { type: "images" }, MY_MEDIA: { type: "media" }, MY_STREAM: { type: "stream" }, @@ -137,7 +137,7 @@ describe("InputWorkerSchema", () => { it("accepts multiple non-singleton bindings of the same type", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { KV_1: { type: "kv" }, @@ -150,7 +150,7 @@ describe("InputWorkerSchema", () => { }); it("accepts a jurisdiction on D1 bindings", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { DB: { type: "d1", jurisdiction: "eu" }, @@ -161,7 +161,7 @@ describe("InputWorkerSchema", () => { }); it("accepts multiple agent-memory bindings", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MEM_1: { type: "agent-memory", namespace: "ns-1" }, @@ -173,7 +173,7 @@ describe("InputWorkerSchema", () => { }); it("accepts binding options nested under dev", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { KV: { type: "kv", dev: { remote: true } }, @@ -201,7 +201,7 @@ describe("InputWorkerSchema", () => { it("accepts Cloudflare Access local development configuration", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, access: { dev: { @@ -217,7 +217,7 @@ describe("InputWorkerSchema", () => { it("does not require an identity in Cloudflare Access local development configuration", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, access: { dev: { aud: "my-app-aud-tag" } }, }); @@ -228,7 +228,7 @@ describe("InputWorkerSchema", () => { it("requires an audience in Cloudflare Access local development configuration", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, access: { dev: { identity: { email: "user@example.com" } } }, }); @@ -237,7 +237,7 @@ describe("InputWorkerSchema", () => { }); it("rejects remote at the binding root", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { KV: { type: "kv", remote: true } }, }); @@ -249,13 +249,13 @@ describe("InputWorkerSchema", () => { ["ai"], ["assets"], ["browser"], - ["analytics"], + ["analytics-sql"], ["images"], ["media"], ["stream"], ["version-metadata"], ] as const)("rejects two %s bindings", ([type], { expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { BINDING_1: { type }, @@ -275,7 +275,7 @@ describe("InputWorkerSchema", () => { it("rejects multiple duplicate singleton types with 'and' message", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { AI_1: { type: "ai" }, @@ -297,7 +297,7 @@ describe("InputWorkerSchema", () => { it("rejects three duplicate singleton types with oxford comma", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { AI_1: { type: "ai" }, @@ -321,7 +321,7 @@ describe("InputWorkerSchema", () => { it("lists duplicates alphabetically regardless of input order", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { STREAM_1: { type: "stream" }, @@ -341,7 +341,7 @@ describe("InputWorkerSchema", () => { }); it("ignores non-singleton duplicates when reporting", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { AI_1: { type: "ai" }, @@ -448,7 +448,7 @@ describe("InputWorkerSchema", () => { it("accepts a string entrypoint and passes it through unchanged", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, entrypoint: "./src/index.ts", }); @@ -460,7 +460,7 @@ describe("InputWorkerSchema", () => { }); it("rejects a namespace-like object", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, entrypoint: { default: "./src/index.ts" }, }); @@ -471,7 +471,7 @@ describe("InputWorkerSchema", () => { it("rejects a namespace object whose default is not a string", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, entrypoint: { default: 123 }, }); @@ -480,7 +480,7 @@ describe("InputWorkerSchema", () => { }); it("rejects a namespace object missing a default export", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, entrypoint: { other: "value" }, }); @@ -489,7 +489,7 @@ describe("InputWorkerSchema", () => { }); it("accepts an undefined entrypoint", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ ...baseConfig }); + const result = WorkerConfigSchema.safeParse({ ...baseConfig }); expect(result.success).toBe(true); if (result.success) { @@ -500,7 +500,7 @@ describe("InputWorkerSchema", () => { describe("unknown property rejection", () => { it("rejects unknown top-level keys (typo)", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, // Typo: should be `compatibilityDate` compatibilityDates: "2025-01-01", @@ -522,7 +522,7 @@ describe("InputWorkerSchema", () => { it("rejects a top-level `manifest` field (included in output schema only)", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, manifest: { type: "complete", @@ -545,7 +545,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys inside `assets`", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, assets: { // Typo: should be `htmlHandling` @@ -567,7 +567,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys inside a binding", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_KV: { @@ -592,7 +592,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys inside `observability.logs`", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, observability: { logs: { @@ -619,7 +619,7 @@ describe("InputWorkerSchema", () => { it("accepts camelCase query string redaction configuration", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, observability: { enabled: true, @@ -633,7 +633,7 @@ describe("InputWorkerSchema", () => { it("rejects snake_case query string redaction configuration", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, observability: { enabled: true, @@ -645,7 +645,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys inside a trigger", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [ { @@ -671,7 +671,7 @@ describe("InputWorkerSchema", () => { }); it("accepts a connect trigger", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [ { @@ -687,7 +687,7 @@ describe("InputWorkerSchema", () => { }); it("accepts a UDP connect trigger", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [ { @@ -704,7 +704,7 @@ describe("InputWorkerSchema", () => { }); it("rejects UDP options on a TCP connect trigger", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [ { @@ -720,7 +720,7 @@ describe("InputWorkerSchema", () => { }); it("rejects a connect trigger with an invalid protocol", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [{ type: "connect", protocol: "ftp", port: 5432 }], }); @@ -729,7 +729,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys inside a connect trigger", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, triggers: [ { @@ -757,7 +757,7 @@ describe("InputWorkerSchema", () => { it("still accepts unknown keys on `unsafe:*` bindings (looseObject escape hatch)", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_UNSAFE: { @@ -774,7 +774,7 @@ describe("InputWorkerSchema", () => { it("passes the `unsafe:*` `type` through unchanged on parse", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_UNSAFE: { @@ -796,7 +796,7 @@ describe("InputWorkerSchema", () => { }); it("rejects `unsafe:` (empty suffix)", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_UNSAFE: { type: "unsafe:" }, @@ -809,7 +809,7 @@ describe("InputWorkerSchema", () => { it("still accepts arbitrary binding names in `env` (record, not object)", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { MY_WEIRDLY_NAMED_BINDING_1234: { type: "kv" }, @@ -822,7 +822,7 @@ describe("InputWorkerSchema", () => { describe("vpc-network binding", () => { it("accepts a binding with `tunnelId`", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { V: { type: "vpc-network", tunnelId: "tun-1" } }, }); @@ -831,7 +831,7 @@ describe("InputWorkerSchema", () => { }); it("accepts a binding with `networkId`", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { V: { type: "vpc-network", networkId: "net-1" } }, }); @@ -842,7 +842,7 @@ describe("InputWorkerSchema", () => { it("rejects a binding with neither `tunnelId` nor `networkId`", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { V: { type: "vpc-network" } }, }); @@ -853,7 +853,7 @@ describe("InputWorkerSchema", () => { it("rejects a binding with both `tunnelId` and `networkId`", ({ expect, }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { V: { type: "vpc-network", tunnelId: "tun-1", networkId: "net-1" }, @@ -864,7 +864,7 @@ describe("InputWorkerSchema", () => { }); it("rejects unknown keys on a `vpc-network` binding", ({ expect }) => { - const result = InputWorkerSchema.safeParse({ + const result = WorkerConfigSchema.safeParse({ ...baseConfig, env: { V: { type: "vpc-network", tunnelId: "tun-1", unknownField: "x" }, @@ -885,18 +885,18 @@ describe("InputWorkerSchema", () => { }); }); -describe("InputContainerSchema", () => { +describe("ContainerConfigSchema", () => { it("accepts a Container with a Dockerfile", ({ expect }) => { - const result = InputContainerSchema.safeParse(baseContainer); + const result = ContainerConfigSchema.safeParse(baseContainer); expect(result.success).toBe(true); if (result.success) { - expect(result.data).toMatchObject({ maxInstances: 20 }); + expect(result.data).not.toHaveProperty("maxInstances"); } }); it("accepts a Container with an image reference", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, image: { reference: "registry.example.com/my-image:latest" }, }); @@ -905,7 +905,7 @@ describe("InputContainerSchema", () => { }); it("accepts a Container with the us jurisdiction", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, constraints: { jurisdiction: "us" }, }); @@ -919,7 +919,7 @@ describe("InputContainerSchema", () => { }); it("rejects a local image reference", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, image: { localReference: "locally-built-image:latest" }, }); @@ -928,7 +928,7 @@ describe("InputContainerSchema", () => { }); it("accepts all optional fields", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, image: { dockerfile: "./container/Dockerfile", @@ -962,13 +962,13 @@ describe("InputContainerSchema", () => { it.for(["name", "image"] as const)("requires %s", (field, { expect }) => { const { [field]: _omitted, ...container } = baseContainer; - const result = InputContainerSchema.safeParse(container); + const result = ContainerConfigSchema.safeParse(container); expect(result.success).toBe(false); }); it("rejects an empty name", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, name: "", }); @@ -977,7 +977,7 @@ describe("InputContainerSchema", () => { }); it("accepts a Durable Object Container", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", images: { @@ -990,7 +990,7 @@ describe("InputContainerSchema", () => { }); it("accepts a Durable Object Container without images", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", }); @@ -1001,7 +1001,7 @@ describe("InputContainerSchema", () => { it("accepts application-wide observability for a Durable Object Container", ({ expect, }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", observability: { enabled: true, logs: { enabled: true } }, @@ -1011,7 +1011,7 @@ describe("InputContainerSchema", () => { }); it("accepts SSH settings for a Durable Object Container", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", ssh: { enabled: true, port: 2222 }, @@ -1024,7 +1024,7 @@ describe("InputContainerSchema", () => { it.for([{ targetInstancePercentage: 50 }, { targetInstanceCount: 2 }])( "rejects observability instance targeting for a Durable Object Container: %o", (observability, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", observability, @@ -1035,7 +1035,7 @@ describe("InputContainerSchema", () => { ); it("rejects Docker build fields without a Dockerfile", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, image: { reference: "registry.example.com/my-image:latest", @@ -1050,7 +1050,7 @@ describe("InputContainerSchema", () => { { description: "Dockerfile path", image: { dockerfile: "" } }, { description: "image reference", image: { reference: "" } }, ])("rejects an empty $description", ({ image }, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, image, }); @@ -1061,7 +1061,7 @@ describe("InputContainerSchema", () => { it.for([-1, 1.5])( "rejects maxInstances of %s", (maxInstances, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, maxInstances, }); @@ -1077,7 +1077,7 @@ describe("InputContainerSchema", () => { ] as const)( "rejects an invalid custom instance type %s", ([field, value], { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, instanceType: { [field]: value }, }); @@ -1089,7 +1089,7 @@ describe("InputContainerSchema", () => { it.for([-1, 0, 1.5, 65_536])( "rejects an SSH port of %s", (port, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, ssh: { enabled: true, port }, }); @@ -1099,7 +1099,7 @@ describe("InputContainerSchema", () => { ); it("rejects an unsupported rollout step percentage", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, rollout: { stepPercentage: 15 }, }); @@ -1116,7 +1116,7 @@ describe("InputContainerSchema", () => { it.for([5, 10, 20, 25, 50, 100])( "accepts a rollout step percentage of %s", (stepPercentage, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, rollout: { stepPercentage }, }); @@ -1149,7 +1149,7 @@ describe("InputContainerSchema", () => { ])( "rejects a $description rollout plan", ({ stepPercentage, path }, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, rollout: { stepPercentage }, }); @@ -1164,7 +1164,7 @@ describe("InputContainerSchema", () => { ); it("rejects more rollout steps than maximum instances", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, maxInstances: 2, rollout: { stepPercentage: [10, 50, 100] }, @@ -1180,7 +1180,7 @@ describe("InputContainerSchema", () => { }); it("rejects a negative rollout active grace period", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, rollout: { activeGracePeriod: -1 }, }); @@ -1196,7 +1196,7 @@ describe("InputContainerSchema", () => { ])( "rejects an invalid observability target: %o", (observability, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, observability, }); @@ -1208,7 +1208,7 @@ describe("InputContainerSchema", () => { it.for([{ targetInstancePercentage: 100 }, { targetInstanceCount: 0 }])( "accepts an observability target boundary: %o", (observability, { expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, observability, }); @@ -1218,7 +1218,7 @@ describe("InputContainerSchema", () => { ); it("rejects both observability targets together", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, observability: { targetInstancePercentage: 50, @@ -1232,7 +1232,7 @@ describe("InputContainerSchema", () => { it("rejects standard Container fields with durable-object scheduling", ({ expect, }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, schedulingPolicy: "durable-object", }); @@ -1241,7 +1241,7 @@ describe("InputContainerSchema", () => { }); it("rejects unsupported enum values", ({ expect }) => { - const result = InputContainerSchema.safeParse({ + const result = ContainerConfigSchema.safeParse({ ...baseContainer, instanceType: "standard", schedulingPolicy: "random", @@ -1251,9 +1251,9 @@ describe("InputContainerSchema", () => { }); }); -describe("OutputContainerSchema", () => { +describe("BuildOutputContainerConfigSchema", () => { it("accepts a Container with the us jurisdiction", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image: { reference: "registry.example.com/my-image:digest" }, constraints: { jurisdiction: "us" }, @@ -1271,19 +1271,20 @@ describe("OutputContainerSchema", () => { { reference: "registry.example.com/my-image:digest" }, { localReference: "locally-built-image:latest" }, ])("accepts a built image reference: %o", (image, { expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image, }); expect(result.success).toBe(true); if (result.success) { - expect(result.data).toMatchObject({ maxInstances: 20 }); + expect(result.data).not.toHaveProperty("maxInstances"); } }); it("rejects a Dockerfile that has not been built", ({ expect }) => { - const result = OutputContainerSchema.safeParse(baseOutputContainer); + const result = + BuildOutputContainerConfigSchema.safeParse(baseOutputContainer); expect(result.success).toBe(false); }); @@ -1291,7 +1292,7 @@ describe("OutputContainerSchema", () => { it.for([{ reference: "" }, { localReference: "" }])( "rejects an empty image reference: %o", (image, { expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image, }); @@ -1301,7 +1302,7 @@ describe("OutputContainerSchema", () => { ); it("rejects both image reference types together", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image: { reference: "registry.example.com/my-image:digest", @@ -1313,7 +1314,7 @@ describe("OutputContainerSchema", () => { }); it("accepts built Durable Object Container images", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", images: { @@ -1332,7 +1333,7 @@ describe("OutputContainerSchema", () => { ssh: { enabled: true }, authorizedKeys: [{ name: "developer", publicKey: "ssh-ed25519 AAAA" }], }; - const result = OutputContainerSchema.safeParse(container); + const result = BuildOutputContainerConfigSchema.safeParse(container); expect(result.success).toBe(true); if (result.success) { @@ -1341,7 +1342,7 @@ describe("OutputContainerSchema", () => { }); it("rejects unbuilt Durable Object Container images", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ name: "durable-object-container", schedulingPolicy: "durable-object", images: { primary: { dockerfile: "./Dockerfile" } }, @@ -1351,7 +1352,7 @@ describe("OutputContainerSchema", () => { }); it("validates rollout steps against maximum instances", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image: { reference: "registry.example.com/my-image:digest" }, maxInstances: 2, @@ -1362,7 +1363,7 @@ describe("OutputContainerSchema", () => { }); it("rejects invalid custom instance resources", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image: { reference: "registry.example.com/my-image:digest" }, instanceType: { vcpu: 0, memoryMib: -1, diskMb: -1 }, @@ -1372,7 +1373,7 @@ describe("OutputContainerSchema", () => { }); it("rejects invalid observability targets", ({ expect }) => { - const result = OutputContainerSchema.safeParse({ + const result = BuildOutputContainerConfigSchema.safeParse({ ...baseOutputContainer, image: { reference: "registry.example.com/my-image:digest" }, observability: { targetInstancePercentage: 101 }, @@ -1382,9 +1383,11 @@ describe("OutputContainerSchema", () => { }); }); -describe("OutputWorkerSchema", () => { +describe("BuildOutputWorkerConfigSchema", () => { it("accepts a config without manifest (assets-only mode)", ({ expect }) => { - const result = OutputWorkerSchema.safeParse({ ...baseOutputConfig }); + const result = BuildOutputWorkerConfigSchema.safeParse({ + ...baseOutputConfig, + }); expect(result.success).toBe(true); if (result.success) { @@ -1393,7 +1396,7 @@ describe("OutputWorkerSchema", () => { }); it("accepts a config with a valid complete manifest", ({ expect }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "complete", @@ -1414,7 +1417,7 @@ describe("OutputWorkerSchema", () => { it("accepts a partial manifest that omits its main module from modules.manifest", ({ expect, }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "partial", @@ -1429,7 +1432,7 @@ describe("OutputWorkerSchema", () => { it("rejects a partial manifest that includes its main module in modules.manifest", ({ expect, }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "partial", @@ -1444,7 +1447,7 @@ describe("OutputWorkerSchema", () => { it("rejects an entrypoint field (included in input schema only)", ({ expect, }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, entrypoint: "./src/index.ts", }); @@ -1453,7 +1456,7 @@ describe("OutputWorkerSchema", () => { }); it("rejects a manifest with an unknown module type", ({ expect }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "complete", @@ -1468,7 +1471,7 @@ describe("OutputWorkerSchema", () => { }); it("rejects a manifest without mainModule", ({ expect }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "complete", @@ -1482,7 +1485,7 @@ describe("OutputWorkerSchema", () => { it("rejects a complete manifest that does not include its main module", ({ expect, }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "complete", @@ -1495,7 +1498,7 @@ describe("OutputWorkerSchema", () => { }); it("rejects a manifest module entry with unknown keys", ({ expect }) => { - const result = OutputWorkerSchema.safeParse({ + const result = BuildOutputWorkerConfigSchema.safeParse({ ...baseOutputConfig, manifest: { type: "complete", @@ -1510,11 +1513,9 @@ describe("OutputWorkerSchema", () => { }); }); -describe("InputConfigSchema", () => { - it("accepts settings without a Worker and defaults its Containers", ({ - expect, - }) => { - const result = InputConfigSchema.safeParse({ +describe("CloudflareConfigSchema", () => { + it("accepts settings without a Worker or Containers", ({ expect }) => { + const result = CloudflareConfigSchema.safeParse({ accountId: "account-id", complianceRegion: "public", }); @@ -1522,12 +1523,12 @@ describe("InputConfigSchema", () => { expect(result.success).toBe(true); if (result.success) { expect(result.data.worker).toBeUndefined(); - expect(result.data.containers).toEqual([]); + expect(result.data.containers).toBeUndefined(); } }); it("accepts a Container without a Worker", ({ expect }) => { - const result = InputConfigSchema.safeParse({ + const result = CloudflareConfigSchema.safeParse({ containers: [baseContainer], }); @@ -1537,7 +1538,7 @@ describe("InputConfigSchema", () => { it("accepts resolved Container links and unlinked Containers", ({ expect, }) => { - const result = InputConfigSchema.safeParse({ + const result = CloudflareConfigSchema.safeParse({ worker: { ...baseConfig, exports: { @@ -1555,7 +1556,7 @@ describe("InputConfigSchema", () => { }); it("rejects duplicate Container names without a Worker", ({ expect }) => { - const result = InputConfigSchema.safeParse({ + const result = CloudflareConfigSchema.safeParse({ containers: [baseContainer, { ...baseContainer }], }); @@ -1571,7 +1572,7 @@ describe("InputConfigSchema", () => { }); it("rejects references to missing Containers", ({ expect }) => { - const result = InputConfigSchema.safeParse({ + const result = CloudflareConfigSchema.safeParse({ worker: { ...baseConfig, exports: { @@ -1600,7 +1601,7 @@ describe("InputConfigSchema", () => { it("rejects multiple Durable Objects linked to the same Container", ({ expect, }) => { - const result = InputConfigSchema.safeParse({ + const result = CloudflareConfigSchema.safeParse({ worker: { ...baseConfig, exports: { @@ -1633,15 +1634,15 @@ describe("InputConfigSchema", () => { }); }); -describe("InputSettingsSchema", () => { +describe("SettingsSchema", () => { it("accepts a minimal settings config", ({ expect }) => { - const result = InputSettingsSchema.safeParse({}); + const result = SettingsSchema.safeParse({}); expect(result.success).toBe(true); }); it("accepts accountId and complianceRegion", ({ expect }) => { - const result = InputSettingsSchema.safeParse({ + const result = SettingsSchema.safeParse({ accountId: "acc-123", complianceRegion: "fedramp-high", }); @@ -1650,7 +1651,7 @@ describe("InputSettingsSchema", () => { }); it("strips fields outside the account settings", ({ expect }) => { - const result = InputSettingsSchema.safeParse({ + const result = SettingsSchema.safeParse({ accountId: "acc-123", name: "my-worker", mode: "staging", @@ -1663,39 +1664,72 @@ describe("InputSettingsSchema", () => { }); }); -describe("OutputRootConfigSchema", () => { - it("accepts build context alongside the settings fields", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({ - accountId: "acc-123", - complianceRegion: "public", +describe("BuildOutputRootConfigSchema", () => { + it("accepts settings, build context and a producer", ({ expect }) => { + const result = BuildOutputRootConfigSchema.safeParse({ + producer: { name: "@cloudflare/vite-plugin", version: "2.3.0" }, + settings: { accountId: "acc-123", complianceRegion: "public" }, buildContext: { isPreview: false, mode: "staging" }, }); expect(result.success).toBe(true); }); - it("accepts a build context without a mode", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({ + it("accepts no settings, no producer and no mode", ({ expect }) => { + const result = BuildOutputRootConfigSchema.safeParse({ buildContext: { isPreview: false }, }); expect(result.success).toBe(true); }); + it("rejects settings at the top level", ({ expect }) => { + const result = BuildOutputRootConfigSchema.safeParse({ + accountId: "acc-123", + buildContext: { isPreview: false }, + }); + + expect(result.success).toBe(false); + }); + + it("rejects unknown settings", ({ expect }) => { + const result = BuildOutputRootConfigSchema.safeParse({ + settings: { name: "my-worker" }, + buildContext: { isPreview: false }, + }); + + expect(result.success).toBe(false); + }); + + it.for([ + { name: "@cloudflare/vite-plugin" }, + { name: "@cloudflare/vite-plugin", version: 2 }, + { name: "@cloudflare/vite-plugin", version: "2.3.0", url: "x" }, + ])("rejects an invalid producer %o", (producer, { expect }) => { + const result = BuildOutputRootConfigSchema.safeParse({ + producer, + buildContext: { isPreview: false }, + }); + + expect(result.success).toBe(false); + }); + it("requires build context", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({}); + const result = BuildOutputRootConfigSchema.safeParse({}); expect(result.success).toBe(false); }); it("requires Preview intent", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({ buildContext: {} }); + const result = BuildOutputRootConfigSchema.safeParse({ + buildContext: {}, + }); expect(result.success).toBe(false); }); it("rejects a non-string mode", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({ + const result = BuildOutputRootConfigSchema.safeParse({ buildContext: { isPreview: false, mode: 123 }, }); @@ -1703,7 +1737,7 @@ describe("OutputRootConfigSchema", () => { }); it("rejects unknown fields", ({ expect }) => { - const result = OutputRootConfigSchema.safeParse({ + const result = BuildOutputRootConfigSchema.safeParse({ buildContext: { isPreview: false, mode: "staging" }, name: "my-worker", }); @@ -1714,7 +1748,7 @@ describe("OutputRootConfigSchema", () => { describe("ExportSchema", () => { function parseExports(exports: unknown) { - return InputWorkerSchema.safeParse({ ...baseConfig, exports }); + return WorkerConfigSchema.safeParse({ ...baseConfig, exports }); } it("accepts `container` on a live durable-object export", ({ expect }) => { @@ -1908,7 +1942,7 @@ describe("ExportSchema", () => { container: baseContainer, }); - const _exports: NonNullable = { + const _exports: NonNullable = { MyDO: { type: "durable-object", storage: "legacy-kv", diff --git a/packages/config/src/bindings.ts b/packages/config/src/bindings.ts index 82e70ad12f..8cc672f4fe 100644 --- a/packages/config/src/bindings.ts +++ b/packages/config/src/bindings.ts @@ -145,14 +145,18 @@ export interface BrowserBinding extends BrowserBindingOptions { type: "browser"; } -export interface AnalyticsSQLBindingOptions { +export interface AnalyticsSqlBindingOptions { /** Options that only apply during local development. */ dev?: BindingDevOptions; } -/** An Analytics SQL binding. */ -export interface AnalyticsSQLBinding extends AnalyticsSQLBindingOptions { - type: "analytics"; +/** + * An Analytics SQL binding. + * + * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-sql + */ +export interface AnalyticsSqlBinding extends AnalyticsSqlBindingOptions { + type: "analytics-sql"; } export interface D1BindingOptions { @@ -363,15 +367,23 @@ export interface MtlsCertificateBinding extends MtlsCertificateBindingOptions { } export interface PipelineBindingOptions { - /** Name of the Pipeline to bind. */ - name: string; + /** + * The ID of the Pipelines stream to write to + */ + streamId: string; + /** @deprecated Renamed to `streamId`, which takes the stream's ID rather than its name. */ + name?: never; /** Options that only apply during local development. */ dev?: BindingDevOptions; } export interface K2BindingOptions { - /** The ID of the K2 stream. */ - stream: string; + /** + * The ID of the K2 stream to write to + */ + id: string; + /** @deprecated Renamed to `id`. */ + stream?: never; /** Always uses the real stream in development. Set remote to true to suppress the usage warning; false is unsupported. */ dev?: BindingDevOptions; } @@ -763,8 +775,12 @@ export interface Bindings { * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#browser-rendering */ browser(options?: BrowserBindingOptions): BrowserBinding; - /** An Analytics binding. */ - analytics(options?: AnalyticsSQLBindingOptions): AnalyticsSQLBinding; + /** + * Binding to Analytics SQL. + * + * For reference, see https://developers.cloudflare.com/workers/wrangler/configuration/#analytics-sql + */ + analyticsSql(options?: AnalyticsSqlBindingOptions): AnalyticsSqlBinding; /** * Binding to a D1 database. * @@ -938,7 +954,7 @@ export const bindings = { artifacts: (options) => ({ type: "artifacts", ...options }), assets: () => ({ type: "assets" }), browser: (options) => ({ type: "browser", ...options }), - analytics: (options) => ({ type: "analytics", ...options }), + analyticsSql: (options) => ({ type: "analytics-sql", ...options }), d1: (options) => ({ type: "d1", ...options }), dispatchNamespace: (options) => ({ type: "dispatch-namespace", diff --git a/packages/config/src/config-loader.ts b/packages/config/src/config-loader.ts index cd759144e0..aaa087c04b 100644 --- a/packages/config/src/config-loader.ts +++ b/packages/config/src/config-loader.ts @@ -1,8 +1,8 @@ import * as z from "zod"; import { loadConfig } from "./load"; -import { InputConfigSchema, InputSettingsSchema } from "./schema"; +import { CloudflareConfigSchema, SettingsSchema } from "./schema"; import type { ConfigContext } from "./definition"; -import type { ParsedInputConfig, ParsedInputSettingsConfig } from "./schema"; +import type { ParsedCloudflareConfig, ParsedSettings } from "./schema"; const CROSS_WORKER_BINDING_TYPES = new Set([ "durable-object", @@ -18,11 +18,11 @@ interface NormalizeWorkerResult { } export type ConfigParseResult = - | z.ZodSafeParseSuccess + | z.ZodSafeParseSuccess | z.ZodSafeParseError; export type ConfigSettingsParseResult = - | z.ZodSafeParseSuccess + | z.ZodSafeParseSuccess | z.ZodSafeParseError; export interface LoadAndParseConfigResult { @@ -211,7 +211,7 @@ export async function resolveAndParseConfig( const resolveDefinition = createDefinitionResolver(ctx); const resolved = await resolveDefinition(input); if (!isRecord(resolved)) { - return InputConfigSchema.safeParse(resolved); + return CloudflareConfigSchema.safeParse(resolved); } const containerInputs = Array.isArray(resolved.containers) @@ -235,7 +235,7 @@ export async function resolveAndParseConfig( : { worker: normalizedWorker.value }), ...(Array.isArray(resolved.containers) ? { containers } : {}), }; - const result = InputConfigSchema.safeParse(candidate); + const result = CloudflareConfigSchema.safeParse(candidate); const issues = [...prefixIssues(normalizedWorker.issues, "worker")]; if (!result.success) { @@ -253,7 +253,7 @@ export async function resolveAndParseConfigSettings( ctx: ConfigContext ): Promise { const resolved = await createDefinitionResolver(ctx)(input); - return InputSettingsSchema.safeParse(resolved); + return SettingsSchema.safeParse(resolved); } /** Load and parse `cloudflare.config.ts`'s default export. */ diff --git a/packages/config/src/convert.ts b/packages/config/src/convert.ts index 7a18a4395a..aae982ec3e 100644 --- a/packages/config/src/convert.ts +++ b/packages/config/src/convert.ts @@ -7,10 +7,10 @@ import { } from "@cloudflare/workers-utils"; import { isParsedUnsafeBinding } from "./schema"; import type { - ParsedInputConfig, - ParsedInputContainerConfig, - ParsedInputSettingsConfig, - ParsedInputWorkerConfig, + ParsedCloudflareConfig, + ParsedContainerConfig, + ParsedSettings, + ParsedWorkerConfig, } from "./schema"; import type { Json } from "./utils"; @@ -29,9 +29,11 @@ const ROLLOUT_KIND_MAP = { * @param config The parsed configuration. * @returns The corresponding Wrangler `RawConfig`. */ -export function convertToWranglerConfig(config: ParsedInputConfig): RawConfig { +export function convertToWranglerConfig( + config: ParsedCloudflareConfig +): RawConfig { const result: RawConfig = {}; - const { worker, containers } = config; + const { worker, containers = [] } = config; if (worker !== undefined) { convertTopLevel(worker, result); @@ -52,7 +54,7 @@ export function convertToWranglerConfig(config: ParsedInputConfig): RawConfig { return result; } -function convertContainer(container: ParsedInputContainerConfig): ContainerApp { +function convertContainer(container: ParsedContainerConfig): ContainerApp { const converted: ContainerApp = { name: container.name, }; @@ -90,7 +92,9 @@ function convertContainer(container: ParsedInputContainerConfig): ContainerApp { "dockerfile" in container.image ? container.image.dockerfile : container.image.reference; - converted.max_instances = container.maxInstances; + if (container.maxInstances !== undefined) { + converted.max_instances = container.maxInstances; + } if ("dockerfile" in container.image) { if (container.image.buildContext !== undefined) { converted.image_build_context = container.image.buildContext; @@ -143,7 +147,7 @@ function convertContainer(container: ParsedInputContainerConfig): ContainerApp { type DurableObjectInputImage = NonNullable< Extract< - ParsedInputContainerConfig, + ParsedContainerConfig, { schedulingPolicy: "durable-object" } >["images"] >[string]; @@ -168,7 +172,7 @@ function convertDurableObjectContainerImage( } function convertContainerObservability( - observability: NonNullable + observability: NonNullable ): NonNullable { const converted: NonNullable = {}; if (observability.enabled !== undefined) { @@ -197,10 +201,7 @@ function convertContainerObservability( * Merge a parsed settings config's fields (`account_id`, `compliance_region`) * onto an existing Wrangler `RawConfig`. */ -function convertSettings( - settings: ParsedInputSettingsConfig, - result: RawConfig -): void { +function convertSettings(settings: ParsedSettings, result: RawConfig): void { if (settings.accountId !== undefined) { result.account_id = settings.accountId; } @@ -214,10 +215,7 @@ function convertSettings( // TOP-LEVEL FIELDS // ═══════════════════════════════════════════════════════════════════════════ -function convertTopLevel( - config: ParsedInputWorkerConfig, - result: RawConfig -): void { +function convertTopLevel(config: ParsedWorkerConfig, result: RawConfig): void { if (config.name !== undefined) { result.name = config.name; } @@ -239,8 +237,8 @@ function convertTopLevel( if (config.logpush !== undefined) { result.logpush = config.logpush; } - if (config.firstPartyWorker !== undefined) { - result.first_party_worker = config.firstPartyWorker; + if (config.experimental?.firstPartyWorker !== undefined) { + result.first_party_worker = config.experimental.firstPartyWorker; } if (config.placement !== undefined) { // `placement` shapes match 1:1 between the two configs. @@ -278,7 +276,7 @@ function convertTopLevel( } function convertObservability( - observability: NonNullable + observability: NonNullable ): NonNullable { const out: NonNullable = {}; if (observability.enabled !== undefined) { @@ -337,7 +335,7 @@ function convertObservability( } function convertUnsafeTopLevel( - unsafe: NonNullable + unsafe: NonNullable ): NonNullable { const out: NonNullable = {}; if (unsafe.metadata !== undefined) { @@ -361,7 +359,7 @@ function convertUnsafeTopLevel( // ═══════════════════════════════════════════════════════════════════════════ function convertBindingsAndAssets( - config: ParsedInputWorkerConfig, + config: ParsedWorkerConfig, result: RawConfig ): void { let assetsBindingName: string | undefined; @@ -489,7 +487,7 @@ function convertBindingsAndAssets( }); break; } - case "analytics": { + case "analytics-sql": { result.analytics = omitUndefined({ binding: name, remote: binding.dev?.remote, @@ -600,7 +598,7 @@ function convertBindingsAndAssets( pipelines.push( omitUndefined({ binding: name, - stream: binding.name, + stream: binding.streamId, remote: binding.dev?.remote, }) ); @@ -610,7 +608,7 @@ function convertBindingsAndAssets( k2.push( omitUndefined({ binding: name, - stream: binding.stream, + stream: binding.id, remote: binding.dev?.remote, }) ); @@ -879,10 +877,7 @@ function convertBindingsAndAssets( // EXPORTS (Workers + Durable Objects) // ═══════════════════════════════════════════════════════════════════════════ -function convertExports( - config: ParsedInputWorkerConfig, - result: RawConfig -): void { +function convertExports(config: ParsedWorkerConfig, result: RawConfig): void { const exports = config.exports; if (!exports) { return; @@ -896,7 +891,25 @@ function convertExports( continue; } if (value.type === "workflow") { - const { defaultRetention, ...workflow } = value; + const { defaultRetention, events, ...workflow } = value; + if (events?.length) { + result.triggers ??= {}; + result.triggers.events ??= []; + result.triggers.events.push( + ...events.map((event) => ({ + type: event.type, + ...(event.filter === undefined + ? {} + : { + filter: omitUndefined({ + namespace: event.filter.namespace, + repo_name: event.filter.repoName, + }), + }), + targets: [{ type: "workflow" as const, workflow_name: value.name }], + })) + ); + } converted[exportName] = { ...workflow, ...(defaultRetention !== undefined && { @@ -985,10 +998,7 @@ function convertExports( // TRIGGERS (scheduled + fetch + queue consumer + email + connect) // ═══════════════════════════════════════════════════════════════════════════ -function convertTriggers( - config: ParsedInputWorkerConfig, - result: RawConfig -): void { +function convertTriggers(config: ParsedWorkerConfig, result: RawConfig): void { const triggers = config.triggers; if (!triggers || triggers.length === 0) { return; @@ -1062,7 +1072,7 @@ function convertTriggers( } if (crons.length) { - result.triggers = { crons }; + result.triggers = { ...result.triggers, crons }; } if (routes.length) { result.routes = routes; @@ -1083,10 +1093,7 @@ function convertTriggers( // DOMAINS (top-level domains -> custom-domain routes) // ═══════════════════════════════════════════════════════════════════════════ -function convertDomains( - config: ParsedInputWorkerConfig, - result: RawConfig -): void { +function convertDomains(config: ParsedWorkerConfig, result: RawConfig): void { if (!config.domains || config.domains.length === 0) { return; } @@ -1113,7 +1120,7 @@ function convertDomains( // ═══════════════════════════════════════════════════════════════════════════ function convertTailConsumers( - config: ParsedInputWorkerConfig, + config: ParsedWorkerConfig, result: RawConfig ): void { const tailConsumers = config.tailConsumers ?? []; diff --git a/packages/config/src/exports.ts b/packages/config/src/exports.ts index bda3f23668..094f1a226f 100644 --- a/packages/config/src/exports.ts +++ b/packages/config/src/exports.ts @@ -13,6 +13,7 @@ // ═══════════════════════════════════════════════════════════════════════════ import type { ContainerDefinition } from "./definition"; +import type { ArtifactsEventSubscription } from "./workflow-events"; /** * Storage backend for the Durable Object. @@ -164,6 +165,8 @@ export interface WorkerEntrypointExport extends WorkerEntrypointExportOptions { export const WORKFLOW_JURISDICTIONS = ["eu", "fedramp", "us"] as const; export interface WorkflowExportOptions { + /** Events that automatically start this Workflow. Only Artifacts events are currently supported. */ + events?: ArtifactsEventSubscription[]; /** * The name of the Workflow. It identifies the Workflow's instances and must * be unique within the account. diff --git a/packages/config/src/index.ts b/packages/config/src/index.ts index c1283c71fa..2f995b45a7 100644 --- a/packages/config/src/index.ts +++ b/packages/config/src/index.ts @@ -1,7 +1,9 @@ export * from "./public"; export { + ArtifactsEventTypeSchema, + ArtifactsEventSubscriptionSchema, AnalyticsEngineDatasetBindingSchema, - AnalyticsSQLBindingSchema, + AnalyticsSqlBindingSchema, AssetsSchema, BindingSchema, BrowserBindingSchema, @@ -13,15 +15,16 @@ export { DurableObjectTransferredExportSchema, ExportSchema, ExperimentalSchema, - InputConfigSchema, - InputContainerSchema, - InputSettingsSchema, - InputWorkerSchema, + CloudflareConfigSchema, + ContainerConfigSchema, + SettingsSchema, + WorkerConfigSchema, KnownBindingSchema, - KVBindingSchema, - OutputContainerSchema, - OutputRootConfigSchema, - OutputWorkerSchema, + KvBindingSchema, + BuildOutputContainerConfigSchema, + BuildOutputProducerSchema, + BuildOutputRootConfigSchema, + BuildOutputWorkerConfigSchema, ModuleTypeSchema, QueueBindingSchema, R2BindingSchema, @@ -53,13 +56,13 @@ export type { LoadAndParseConfigResult, } from "./config-loader"; export type { - InputWorkerConfig, - ParsedInputConfig, - ParsedInputContainerConfig, - ParsedInputSettingsConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedCloudflareConfig, + ParsedContainerConfig, + ParsedSettings, + ParsedWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputProducer, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, ModuleType, } from "./schema"; diff --git a/packages/config/src/inference.ts b/packages/config/src/inference.ts index dfa21dd23c..72c9583da6 100644 --- a/packages/config/src/inference.ts +++ b/packages/config/src/inference.ts @@ -95,7 +95,7 @@ interface BindingTypeMap { "ai-search": AiSearchInstance; "ai-search-namespace": AiSearchNamespace; "analytics-engine-dataset": AnalyticsEngineDataset; - analytics: AnalyticsSQLBinding; + "analytics-sql": AnalyticsSQLBinding; artifacts: Artifacts; assets: Fetcher; browser: BrowserRun; diff --git a/packages/config/src/public.ts b/packages/config/src/public.ts index 7577ea75ec..faa1b346b5 100644 --- a/packages/config/src/public.ts +++ b/packages/config/src/public.ts @@ -16,8 +16,8 @@ export type { AiSearchNamespaceBindingOptions, AnalyticsEngineDatasetBinding, AnalyticsEngineDatasetBindingOptions, - AnalyticsSQLBinding, - AnalyticsSQLBindingOptions, + AnalyticsSqlBinding, + AnalyticsSqlBindingOptions, ArtifactsBinding, ArtifactsBindingOptions, AssetsBinding, @@ -89,7 +89,6 @@ export type { Triggers, ConnectTrigger, ConnectTriggerOptions, - ConnectTriggerOptionsBase, EmailTrigger, EmailTriggerOptions, FetchTrigger, @@ -100,6 +99,10 @@ export type { ScheduledTriggerOptions, } from "./triggers"; export { triggers } from "./triggers"; +export type { + ArtifactsEventType, + ArtifactsEventSubscription, +} from "./workflow-events"; export type { Exports, DurableObjectCreatedExport, diff --git a/packages/config/src/schema.ts b/packages/config/src/schema.ts index 4956ee0f80..71ee056795 100644 --- a/packages/config/src/schema.ts +++ b/packages/config/src/schema.ts @@ -1,5 +1,6 @@ import * as z from "zod"; import { WORKFLOW_JURISDICTIONS } from "./exports"; +import { ARTIFACTS_EVENT_TYPES } from "./workflow-events"; import type { SendEmailBinding, VpcNetworkBinding } from "./bindings"; import type { Settings } from "./types"; import type { ContainerConfig, WorkerConfig } from "./types"; @@ -29,8 +30,8 @@ export const BrowserBindingSchema = z.strictObject({ dev: RemoteBindingDevSchema.optional(), }); -export const AnalyticsSQLBindingSchema = z.strictObject({ - type: z.literal("analytics"), +export const AnalyticsSqlBindingSchema = z.strictObject({ + type: z.literal("analytics-sql"), dev: RemoteBindingDevSchema.optional(), }); @@ -57,7 +58,7 @@ export const D1BindingSchema = z.strictObject({ dev: RemoteBindingDevSchema.optional(), }); -export const KVBindingSchema = z.strictObject({ +export const KvBindingSchema = z.strictObject({ type: z.literal("kv"), id: z.string().optional(), // TODO: name support not yet implemented @@ -65,6 +66,34 @@ export const KVBindingSchema = z.strictObject({ dev: RemoteBindingDevSchema.optional(), }); +/** + * A field that was renamed. It accepts no value, so setting it fails with a + * message that names its replacement instead of a generic unknown-key error. + */ +function renamedFieldSchema(message: string) { + return z.never({ error: message }).optional(); +} + +const PipelineBindingSchema = z.strictObject({ + type: z.literal("pipeline"), + // Listed first so its error comes before the missing "streamId" error. + name: renamedFieldSchema( + '"name" was renamed to "streamId". Set "streamId" to the ID of the Pipelines stream, not its name.' + ), + streamId: z.string(), + dev: RemoteBindingDevSchema.optional(), +}); + +const K2BindingSchema = z.strictObject({ + type: z.literal("k2"), + // Listed first so its error comes before the missing "id" error. + stream: renamedFieldSchema( + '"stream" was renamed to "id". Set "id" to the ID of the K2 stream.' + ), + id: z.string(), + dev: RemoteBindingDevSchema.optional(), +}); + export const QueueBindingSchema = z.strictObject({ type: z.literal("queue"), name: z.string().optional(), @@ -135,7 +164,7 @@ export const KnownBindingSchema = z.discriminatedUnion("type", [ }), z.strictObject({ type: z.literal("assets") }), BrowserBindingSchema, - AnalyticsSQLBindingSchema, + AnalyticsSqlBindingSchema, D1BindingSchema, z.strictObject({ type: z.literal("dispatch-namespace"), @@ -160,7 +189,7 @@ export const KnownBindingSchema = z.discriminatedUnion("type", [ dev: RemoteBindingDevSchema.optional(), }), z.strictObject({ type: z.literal("json"), value: z.json() }), - KVBindingSchema, + KvBindingSchema, z.strictObject({ type: z.literal("logfwdr"), destination: z.string() }), z.strictObject({ type: z.literal("media"), @@ -171,16 +200,8 @@ export const KnownBindingSchema = z.discriminatedUnion("type", [ id: z.string(), dev: RemoteBindingDevSchema.optional(), }), - z.strictObject({ - type: z.literal("pipeline"), - name: z.string(), - dev: RemoteBindingDevSchema.optional(), - }), - z.strictObject({ - type: z.literal("k2"), - stream: z.string(), - dev: RemoteBindingDevSchema.optional(), - }), + PipelineBindingSchema, + K2BindingSchema, QueueBindingSchema, z.strictObject({ type: z.literal("rate-limit"), @@ -314,7 +335,7 @@ export const SINGLETON_BINDING_TYPES: ReadonlySet = new Set([ "ai", "assets", "browser", - "analytics", + "analytics-sql", "images", "media", "stream", @@ -369,12 +390,12 @@ const ContainerImageLocalReferenceSchema = z.strictObject({ localReference: z.string().min(1), }); -const InputContainerImageSchema = z.union([ +const ContainerImageSchema = z.union([ ContainerImageDockerfileSchema, ContainerImageReferenceSchema, ]); -const OutputContainerImageSchema = z.union([ +const BuildOutputContainerImageSchema = z.union([ ContainerImageReferenceSchema, ContainerImageLocalReferenceSchema, ]); @@ -483,7 +504,7 @@ const BaseContainerSchema = z.strictObject({ const StandardContainerBaseSchema = BaseContainerSchema.extend({ observability: StandardContainerObservabilitySchema.optional(), - maxInstances: z.number().int().nonnegative().default(20), + maxInstances: z.number().int().nonnegative().optional(), instanceType: z .union([ z.enum([ @@ -537,35 +558,37 @@ const DurableObjectContainerBaseSchema = BaseContainerSchema.extend({ }); /** - * Input Container schema — parses user-authored `cloudflare.config.ts` - * Container objects. Dockerfiles are built by the consuming build tool. + * Container schema — parses Container objects from user-authored + * `cloudflare.config.ts` files. Dockerfiles are built by the consuming build + * tool. */ -export const InputContainerSchema = z.union([ +export const ContainerConfigSchema = z.union([ StandardContainerBaseSchema.extend({ - image: InputContainerImageSchema, + image: ContainerImageSchema, }).superRefine(validateContainerRelationships), DurableObjectContainerBaseSchema.extend({ - images: z.record(z.string(), InputContainerImageSchema).optional(), + images: z.record(z.string(), ContainerImageSchema).optional(), }), ]); -export type ParsedInputContainerConfig = z.output; +export type ParsedContainerConfig = z.output; /** - * Output Container schema — parses `container.config.json` files in the Build - * Output Specification, after any Dockerfile has been built into a local image reference. + * Build output Container schema — parses `container.config.json` files in the + * Build Output Specification, after any Dockerfile has been built into a local + * image reference. */ -export const OutputContainerSchema = z.union([ +export const BuildOutputContainerConfigSchema = z.union([ StandardContainerBaseSchema.extend({ - image: OutputContainerImageSchema, + image: BuildOutputContainerImageSchema, }).superRefine(validateContainerRelationships), DurableObjectContainerBaseSchema.extend({ - images: z.record(z.string(), OutputContainerImageSchema).optional(), + images: z.record(z.string(), BuildOutputContainerImageSchema).optional(), }), ]); -export type ParsedOutputContainerConfig = z.output< - typeof OutputContainerSchema +export type ParsedBuildOutputContainerConfig = z.output< + typeof BuildOutputContainerConfigSchema >; // `state` defaults to `"created"` (live) when omitted. Tombstones use one of @@ -613,8 +636,20 @@ const WorkflowRetentionSchema = z.union([ z.string().min(1), ]); +export const ArtifactsEventTypeSchema = z.enum(ARTIFACTS_EVENT_TYPES); +export const ArtifactsEventSubscriptionSchema = z.strictObject({ + type: ArtifactsEventTypeSchema, + filter: z + .strictObject({ + namespace: z.string().min(1).optional(), + repoName: z.string().min(1).optional(), + }) + .optional(), +}); + export const WorkflowExportSchema = z.strictObject({ type: z.literal("workflow"), + events: z.array(ArtifactsEventSubscriptionSchema).optional(), name: z.string(), limits: z .strictObject({ steps: z.number().int().min(1).optional() }) @@ -731,6 +766,8 @@ export const TailConsumerSchema = z.strictObject({ export const ExperimentalSchema = z.strictObject({ streamingTailConsumers: z.array(TailConsumerSchema).optional(), + /** @internal */ + firstPartyWorker: z.boolean().optional(), }); const TriggerSchema = z.discriminatedUnion("type", [ @@ -749,7 +786,7 @@ const TriggerSchema = z.discriminatedUnion("type", [ deadLetterQueue: z.string().optional(), maxBatchSize: z.number().optional(), maxBatchTimeout: z.number().optional(), - maxConcurrency: z.number().nullable().optional(), + maxConcurrency: z.number().optional(), maxRetries: z.number().optional(), retryDelay: z.number().optional(), visibilityTimeoutMs: z.number().optional(), @@ -808,8 +845,8 @@ const DomainSchema = z.union([ ]); /** - * Base Worker schema — the set of fields shared between the input - * (user-authored) and output (on-disk) Worker configs. + * Base Worker schema — the set of fields shared between the user-authored + * Worker config and the Worker config in the build output. */ const BaseWorkerSchema = z.strictObject({ name: z.string(), @@ -827,7 +864,6 @@ const BaseWorkerSchema = z.strictObject({ access: AccessSchema.optional(), workersDev: z.boolean().optional(), previewUrls: z.boolean().optional(), - firstPartyWorker: z.boolean().optional(), experimental: ExperimentalSchema.optional(), unsafe: UnsafeSchema.optional(), // TODO: support previews @@ -836,38 +872,38 @@ const BaseWorkerSchema = z.strictObject({ }); /** - * Input Worker schema — parses Worker definitions from user-authored - * `cloudflare.config.ts` files. Adds an optional string `entrypoint` field to - * the base schema. + * Worker schema — parses Worker definitions from user-authored + * `cloudflare.config.ts` files, after the config loader has resolved + * `defineWorker()` references and module entrypoints. Adds an optional string + * `entrypoint` field to the base schema. */ -export const InputWorkerSchema = BaseWorkerSchema.extend({ +export const WorkerConfigSchema = BaseWorkerSchema.extend({ entrypoint: z.string().optional(), }); -export type InputWorkerConfig = z.input; -export type ParsedInputWorkerConfig = z.output; +export type ParsedWorkerConfig = z.output; /** - * Input settings schema — parses the account settings at the top level of + * Settings schema — parses the account settings at the top level of * `cloudflare.config.ts`. */ -export const InputSettingsSchema = z.object({ +export const SettingsSchema = z.object({ accountId: z.string().optional(), complianceRegion: z.enum(["public", "fedramp-high"]).optional(), }); -export type ParsedInputSettingsConfig = z.output; +export type ParsedSettings = z.output; /** Validate relationships after resource definitions have been resolved to names. */ -function validateInputConfigRelationships( +function validateConfigRelationships( config: { - worker?: ParsedInputWorkerConfig; - containers: ParsedInputContainerConfig[]; + worker?: ParsedWorkerConfig; + containers?: ParsedContainerConfig[]; }, ctx: z.RefinementCtx ): void { const firstIndexByName = new Map(); - for (const [index, container] of config.containers.entries()) { + for (const [index, container] of (config.containers ?? []).entries()) { const firstIndex = firstIndexByName.get(container.name); if (firstIndex !== undefined) { ctx.addIssue({ @@ -915,15 +951,15 @@ function validateInputConfigRelationships( } /** The resolved project configuration, including relationships between resources. */ -export const InputConfigSchema = z +export const CloudflareConfigSchema = z .strictObject({ - ...InputSettingsSchema.shape, - worker: InputWorkerSchema.optional(), - containers: z.array(InputContainerSchema).default([]), + ...SettingsSchema.shape, + worker: WorkerConfigSchema.optional(), + containers: z.array(ContainerConfigSchema).optional(), }) - .superRefine(validateInputConfigRelationships); + .superRefine(validateConfigRelationships); -export type ParsedInputConfig = z.output; +export type ParsedCloudflareConfig = z.output; const BuildContextSchema = z.strictObject({ isPreview: z.boolean(), @@ -931,16 +967,34 @@ const BuildContextSchema = z.strictObject({ }); /** - * The shape of the root `config.json` in the Build Output Specification. - * Account settings remain at the top level while build context is grouped - * under `buildContext`. + * The tool that wrote a Build Output Specification tree, such as a framework + * adapter or build plugin. Used only in diagnostics, never for deploy + * behaviour. */ -export const OutputRootConfigSchema = z.strictObject({ - ...InputSettingsSchema.shape, +export const BuildOutputProducerSchema = z.strictObject({ + name: z.string(), + version: z.string(), +}); + +export type ParsedBuildOutputProducer = z.output< + typeof BuildOutputProducerSchema +>; + +/** + * The shape of the root `config.json` in the Build Output Specification. + * Account settings are grouped under `settings` and build context under + * `buildContext`. `settings` is omitted when there are none. `producer` is + * optional because it doesn't affect what gets deployed. + */ +export const BuildOutputRootConfigSchema = z.strictObject({ + producer: BuildOutputProducerSchema.optional(), + settings: z.strictObject(SettingsSchema.shape).optional(), buildContext: BuildContextSchema, }); -export type ParsedOutputRootConfig = z.output; +export type ParsedBuildOutputRootConfig = z.output< + typeof BuildOutputRootConfigSchema +>; export const ModuleTypeSchema = z.enum([ "esm", @@ -986,18 +1040,20 @@ const ManifestSchema = z }); /** - * Output Worker schema — the shape of the Worker's `worker.config.json` in the + * Build output Worker schema — the shape of the Worker's `worker.config.json` in the * Build Output Specification. Adds an optional `manifest` field to the base * schema. */ -export const OutputWorkerSchema = BaseWorkerSchema.extend({ +export const BuildOutputWorkerConfigSchema = BaseWorkerSchema.extend({ manifest: ManifestSchema.optional(), }); -export type ParsedOutputWorkerConfig = z.output; +export type ParsedBuildOutputWorkerConfig = z.output< + typeof BuildOutputWorkerConfigSchema +>; /** - * Bidirectional drift check between {@link InputWorkerSchema} and the + * Bidirectional drift check between {@link WorkerConfigSchema} and the * public {@link WorkerConfig} interface. The public `entrypoint` type accepts a * `WorkerModule` namespace, which the config loader replaces with its string * specifier before parsing. Excludes `env` and `exports`, which deliberately @@ -1008,7 +1064,7 @@ export type ParsedOutputWorkerConfig = z.output; * - `exports`: see the separate resolved-reference drift check below. */ type _ComparableInput = Omit< - z.input, + z.input, "env" | "exports" >; type _ComparableWorkerConfig = Omit< @@ -1052,13 +1108,13 @@ type _ResolvedWorkerConfigEnv = * differently between the public definitions and the schema. */ type _AssertSchemaEnvMatchesWorkerConfig = [ - _ResolvedWorkerConfigEnv extends z.input["env"] + _ResolvedWorkerConfigEnv extends z.input["env"] ? true : false, - z.output["env"] extends _ResolvedWorkerConfigEnv + z.output["env"] extends _ResolvedWorkerConfigEnv ? true : false, - _ResolvedWorkerConfigEnv extends z.output["env"] + _ResolvedWorkerConfigEnv extends z.output["env"] ? true : false, ]; @@ -1087,17 +1143,17 @@ type _ResolvedWorkerConfigExports = */ type _AssertSchemaExportsMatchWorkerConfig = [ _ResolvedWorkerConfigExports extends z.input< - typeof InputWorkerSchema + typeof WorkerConfigSchema >["exports"] ? true : false, z.output< - typeof InputWorkerSchema + typeof WorkerConfigSchema >["exports"] extends _ResolvedWorkerConfigExports ? true : false, _ResolvedWorkerConfigExports extends z.output< - typeof InputWorkerSchema + typeof WorkerConfigSchema >["exports"] ? true : false, @@ -1107,24 +1163,24 @@ const _assertSchemaExportsMatchWorkerConfig: _AssertSchemaExportsMatchWorkerConf void _assertSchemaExportsMatchWorkerConfig; /** - * Bidirectional drift check between {@link InputContainerSchema} and the + * Bidirectional drift check between {@link ContainerConfigSchema} and the * public {@link ContainerConfig} interface. */ type _AssertInputContainerSchemaMatchesConfig = [ - z.input extends ContainerConfig ? true : false, - ContainerConfig extends z.input ? true : false, + z.input extends ContainerConfig ? true : false, + ContainerConfig extends z.input ? true : false, ]; const _assertInputContainerSchemaMatchesConfig: _AssertInputContainerSchemaMatchesConfig = [true, true]; void _assertInputContainerSchemaMatchesConfig; /** - * Bidirectional drift check between {@link InputSettingsSchema} and the public + * Bidirectional drift check between {@link SettingsSchema} and the public * {@link Settings} interface. */ type _AssertInputSettingsSchemaMatchesConfig = [ - z.input extends Settings ? true : false, - Settings extends z.input ? true : false, + z.input extends Settings ? true : false, + Settings extends z.input ? true : false, ]; const _assertInputSettingsSchemaMatchesConfig: _AssertInputSettingsSchemaMatchesConfig = [true, true]; diff --git a/packages/config/src/triggers.ts b/packages/config/src/triggers.ts index ced25bc18b..71173240b7 100644 --- a/packages/config/src/triggers.ts +++ b/packages/config/src/triggers.ts @@ -40,7 +40,7 @@ export interface QueueConsumerTriggerOptions { * Leaving this unset will allow your consumer to scale to the * maximum concurrency needed to keep up with the message backlog. */ - maxConcurrency?: number | null; + maxConcurrency?: number; /** The maximum number of retries for each message. */ maxRetries?: number; /** The number of seconds to wait before retrying a message. */ @@ -97,7 +97,7 @@ export interface EmailTrigger extends EmailTriggerOptions { type: "email"; } -export interface ConnectTriggerOptionsBase { +interface ConnectTriggerOptionsBase { /** The port to listen on. */ port: number; /** The address to bind to. Defaults to `127.0.0.1`. */ diff --git a/packages/config/src/types.ts b/packages/config/src/types.ts index dc583b8fef..67e6b25e7f 100644 --- a/packages/config/src/types.ts +++ b/packages/config/src/types.ts @@ -12,7 +12,7 @@ import type { AiSearchBinding, AiSearchNamespaceBinding, AnalyticsEngineDatasetBinding, - AnalyticsSQLBinding, + AnalyticsSqlBinding, ArtifactsBinding, AssetsBinding, BrowserBinding, @@ -106,7 +106,7 @@ type Binding = | AiSearchBinding | AiSearchNamespaceBinding | AnalyticsEngineDatasetBinding - | AnalyticsSQLBinding + | AnalyticsSqlBinding | ArtifactsBinding | AssetsBinding | BrowserBinding @@ -366,7 +366,7 @@ export interface DurableObjectContainerConfig extends BaseContainerConfig { /** * Container application configuration. This is the input shape passed to - * `defineContainer` and parsed at runtime by `InputContainerSchema`. + * `defineContainer` and parsed at runtime by `ContainerConfigSchema`. */ export type ContainerConfig = | DurableObjectContainerConfig @@ -376,7 +376,7 @@ export type ContainerConfig = * Worker configuration. This is the input shape passed to * [`defineWorker`](https://developers.cloudflare.com/workers/wrangler/configuration/). * - * Fields are parsed and normalised at runtime by `InputWorkerSchema` before + * Fields are parsed and normalised at runtime by `WorkerConfigSchema` before * being passed to downstream tooling. */ export interface WorkerConfig { @@ -619,13 +619,6 @@ export interface WorkerConfig { */ previewUrls?: boolean; - /** - * Designates this Worker as an internal-only "first-party" Worker. - * - * @internal - */ - firstPartyWorker?: boolean; - /** * Experimental features. Fields here may change or be removed without a * major version bump. @@ -644,6 +637,12 @@ export interface WorkerConfig { /** The name of the service streaming tail events will be forwarded to. */ worker: string; }>; + /** + * Designates this Worker as an internal-only "first-party" Worker. + * + * @internal + */ + firstPartyWorker?: boolean; }; /** diff --git a/packages/config/src/workflow-events.ts b/packages/config/src/workflow-events.ts new file mode 100644 index 0000000000..0562fe4fc7 --- /dev/null +++ b/packages/config/src/workflow-events.ts @@ -0,0 +1,21 @@ +/** Event types Artifacts publishes to subscriptions. */ +export const ARTIFACTS_EVENT_TYPES = [ + "cf.artifacts.repo.created", + "cf.artifacts.repo.deleted", + "cf.artifacts.repo.forked", + "cf.artifacts.repo.imported", + "cf.artifacts.repo.pushed", + "cf.artifacts.repo.cloned", + "cf.artifacts.repo.fetched", + "cf.artifacts.repo.token.created", + "cf.artifacts.repo.token.revoked", +] as const; + +/** A published Artifacts event type. */ +export type ArtifactsEventType = (typeof ARTIFACTS_EVENT_TYPES)[number]; + +/** A subscription to an Artifacts event that starts the Workflow declaring it. */ +export interface ArtifactsEventSubscription { + type: ArtifactsEventType; + filter?: { namespace?: string; repoName?: string }; +} diff --git a/packages/containers-shared/CHANGELOG.md b/packages/containers-shared/CHANGELOG.md index 31f910804f..20c07e1e55 100644 --- a/packages/containers-shared/CHANGELOG.md +++ b/packages/containers-shared/CHANGELOG.md @@ -1,5 +1,37 @@ # @cloudflare/containers-shared +## 0.26.2 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155)]: + - @cloudflare/build-output-utils@1.0.0-rc.0 + - @cloudflare/config@1.0.0-rc.0 + - @cloudflare/workers-utils@0.54.1 + - @cloudflare/cli-shared-helpers@0.3.9 + +## 0.26.1 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985)]: + - @cloudflare/workers-utils@0.54.0 + - @cloudflare/build-output-utils@0.9.14 + - @cloudflare/cli-shared-helpers@0.3.8 + - @cloudflare/config@0.32.1 + ## 0.26.0 ### Minor Changes diff --git a/packages/containers-shared/package.json b/packages/containers-shared/package.json index 5c726618b8..fbbe928b9f 100644 --- a/packages/containers-shared/package.json +++ b/packages/containers-shared/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/containers-shared", - "version": "0.26.0", + "version": "0.26.2", "description": "Internal-only shared container helpers for workers-sdk. Do not use directly; APIs are unstable and may change or disappear without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/containers-shared#readme", "bugs": { diff --git a/packages/containers-shared/src/build-output.ts b/packages/containers-shared/src/build-output.ts index f6a26de974..64876fc869 100644 --- a/packages/containers-shared/src/build-output.ts +++ b/packages/containers-shared/src/build-output.ts @@ -16,12 +16,12 @@ import { runDockerCmdWithOutput, verifyDockerInstalled } from "./utils"; import type { InputContainerImage } from "./input-container-image"; import type { WriteContainerConfigOptions } from "@cloudflare/build-output-utils"; import type { - ParsedInputContainerConfig, - ParsedOutputContainerConfig, + ParsedContainerConfig, + ParsedBuildOutputContainerConfig, } from "@cloudflare/config"; type OutputContainerImage = Extract< - ParsedOutputContainerConfig, + ParsedBuildOutputContainerConfig, { image: unknown } >["image"]; @@ -37,7 +37,7 @@ const DOCKER_REPOSITORY_NAME_LENGTH = 255; * @param options - The validated Container configs and Docker build environment. */ export async function buildAndWriteContainerOutput(options: { - containers: ParsedInputContainerConfig[]; + containers: ParsedContainerConfig[]; root: string; pathToDocker: string; }): Promise { @@ -96,8 +96,8 @@ export async function buildAndWriteContainerOutput(options: { } function resolveContainerDirectories( - containers: ParsedInputContainerConfig[] -): Array<{ config: ParsedInputContainerConfig; directoryName: string }> { + containers: ParsedContainerConfig[] +): Array<{ config: ParsedContainerConfig; directoryName: string }> { const containerNameByDirectory = new Map(); return containers.map((config) => { @@ -116,12 +116,12 @@ function resolveContainerDirectories( } async function buildContainerOutputConfig(options: { - config: ParsedInputContainerConfig; + config: ParsedContainerConfig; root: string; pathToDocker: string; buildId: string; localTags: Set; -}): Promise { +}): Promise { if (options.config.schedulingPolicy === "durable-object") { if (options.config.images === undefined) { return { ...options.config, images: undefined }; @@ -129,7 +129,7 @@ async function buildContainerOutputConfig(options: { const images: NonNullable< Extract< - ParsedOutputContainerConfig, + ParsedBuildOutputContainerConfig, { schedulingPolicy: "durable-object" } >["images"] > = {}; @@ -258,7 +258,7 @@ function createBuildId(): string { return crypto.randomUUID().replaceAll("-", "").slice(0, 12); } -function countDockerfiles(containers: ParsedInputContainerConfig[]): number { +function countDockerfiles(containers: ParsedContainerConfig[]): number { let count = 0; for (const config of containers) { if (config.schedulingPolicy === "durable-object") { diff --git a/packages/containers-shared/src/dev-options.ts b/packages/containers-shared/src/dev-options.ts index 8e26b94ff2..732cb394ca 100644 --- a/packages/containers-shared/src/dev-options.ts +++ b/packages/containers-shared/src/dev-options.ts @@ -16,10 +16,10 @@ import type { ContainerDevRuntimeOptions, } from "./types"; import type { - ParsedInputContainerConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, - ParsedOutputWorkerConfig, + ParsedContainerConfig, + ParsedWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { Config } from "@cloudflare/workers-utils"; @@ -33,8 +33,8 @@ type CreateContainerDevPlanOptions = { type NamedContainerDevOptions = ContainerDevOptions & { image_name: string }; type ContainerPlanExports = - | ParsedInputWorkerConfig["exports"] - | ParsedOutputWorkerConfig["exports"]; + | ParsedWorkerConfig["exports"] + | ParsedBuildOutputWorkerConfig["exports"]; /** * A Worker export of parsed `cloudflare.config.ts` or Build Output @@ -237,8 +237,8 @@ export function createContainerDevPlan( * @throws If a linked Container is missing or image preparation has no build ID. */ export function createContainerDevPlanForCfConfig(options: { - containers: ParsedInputContainerConfig[]; - exports: ParsedInputWorkerConfig["exports"]; + containers: ParsedContainerConfig[]; + exports: ParsedWorkerConfig["exports"]; root: string; containerBuildId?: string; }): ContainerDevPlan | undefined { @@ -290,8 +290,8 @@ export function createContainerDevPlanForCfConfig(options: { * @throws If Build Output omits a Container referenced by a Worker export. */ export function createContainerPreviewPlanForCfConfig(options: { - containers: ParsedOutputContainerConfig[]; - exports: ParsedOutputWorkerConfig["exports"]; + containers: ParsedBuildOutputContainerConfig[]; + exports: ParsedBuildOutputWorkerConfig["exports"]; }): ContainerDevPlan | undefined { return createContainerPlanForCfConfig({ containers: options.containers, diff --git a/packages/containers-shared/src/input-container-image.ts b/packages/containers-shared/src/input-container-image.ts index 881772f218..812f4df6a4 100644 --- a/packages/containers-shared/src/input-container-image.ts +++ b/packages/containers-shared/src/input-container-image.ts @@ -1,8 +1,8 @@ import path from "node:path"; -import type { ParsedInputContainerConfig } from "@cloudflare/config"; +import type { ParsedContainerConfig } from "@cloudflare/config"; export type InputContainerImage = Extract< - ParsedInputContainerConfig, + ParsedContainerConfig, { image: unknown } >["image"]; diff --git a/packages/containers-shared/tests/build-output.test.ts b/packages/containers-shared/tests/build-output.test.ts index 8ce1bd1419..a935903797 100644 --- a/packages/containers-shared/tests/build-output.test.ts +++ b/packages/containers-shared/tests/build-output.test.ts @@ -8,7 +8,7 @@ import { getWorkerDir, writeContainerConfig, } from "@cloudflare/build-output-utils"; -import { InputContainerSchema } from "@cloudflare/config"; +import { ContainerConfigSchema } from "@cloudflare/config"; import { removeDirSync } from "@cloudflare/workers-utils"; import { afterEach, beforeEach, describe, it, vi } from "vitest"; import { @@ -69,7 +69,7 @@ describe("buildAndWriteContainerOutput", () => { it("preserves remote references without invoking Docker", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "remote-container", image: { reference: "registry.example.com/app:latest" }, }); @@ -95,7 +95,7 @@ describe("buildAndWriteContainerOutput", () => { it("builds a standard Container with resolved paths and build variables", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "My_Container", image: { dockerfile: "./container/Dockerfile", @@ -136,7 +136,7 @@ describe("buildAndWriteContainerOutput", () => { it("uses a valid fallback when a Container name has no repository characters", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "🔥", image: { dockerfile: "./container/Dockerfile" }, }); @@ -159,7 +159,7 @@ describe("buildAndWriteContainerOutput", () => { it("trims project-scoped repository names to Docker's length limit", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "a".repeat(240), image: { dockerfile: "./container/Dockerfile" }, }); @@ -178,7 +178,7 @@ describe("buildAndWriteContainerOutput", () => { it("builds Durable Object named images and preserves remote images", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "Session_Container", schedulingPolicy: "durable-object", images: { @@ -252,7 +252,7 @@ describe("buildAndWriteContainerOutput", () => { it("preserves a Durable Object Container with no images", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "Session_Container", schedulingPolicy: "durable-object", }); @@ -275,11 +275,11 @@ describe("buildAndWriteContainerOutput", () => { }); it("cleans images built before a later build fails", async ({ expect }) => { - const first = InputContainerSchema.parse({ + const first = ContainerConfigSchema.parse({ name: "first", image: { dockerfile: "./first/Dockerfile" }, }); - const second = InputContainerSchema.parse({ + const second = ContainerConfigSchema.parse({ name: "second", image: { dockerfile: "./second/Dockerfile" }, }); @@ -310,7 +310,7 @@ describe("buildAndWriteContainerOutput", () => { }); it("normalizes Container directory names", async ({ expect }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "API Container", image: { reference: "registry.example.com/app:latest" }, }); @@ -331,11 +331,11 @@ describe("buildAndWriteContainerOutput", () => { it("removes partial output and current build tags when writing fails", async ({ expect, }) => { - const first = InputContainerSchema.parse({ + const first = ContainerConfigSchema.parse({ name: "first", image: { dockerfile: "./first/Dockerfile" }, }); - const second = InputContainerSchema.parse({ + const second = ContainerConfigSchema.parse({ name: "second", image: { dockerfile: "./second/Dockerfile" }, }); @@ -368,11 +368,11 @@ describe("buildAndWriteContainerOutput", () => { it("rejects Container names with colliding directory names", async ({ expect, }) => { - const first = InputContainerSchema.parse({ + const first = ContainerConfigSchema.parse({ name: "API:prod", image: { reference: "registry.example.com/api:latest" }, }); - const second = InputContainerSchema.parse({ + const second = ContainerConfigSchema.parse({ name: "api-prod", image: { reference: "registry.example.com/api-2:latest" }, }); @@ -395,7 +395,7 @@ describe("buildAndWriteContainerOutput", () => { it("removes complete output when Docker verification fails", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "app", image: { dockerfile: "./Dockerfile" }, }); @@ -418,7 +418,7 @@ describe("buildAndWriteContainerOutput", () => { it("removes the previous tag before rebuilding deleted output", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "api", image: { dockerfile: "./Dockerfile" }, }); @@ -479,11 +479,11 @@ describe("buildAndWriteContainerOutput", () => { it("rejects image names that normalize to the same repository", async ({ expect, }) => { - const first = InputContainerSchema.parse({ + const first = ContainerConfigSchema.parse({ name: "My_-API", image: { dockerfile: "./first/Dockerfile" }, }); - const second = InputContainerSchema.parse({ + const second = ContainerConfigSchema.parse({ name: "my-api", image: { dockerfile: "./second/Dockerfile" }, }); @@ -509,7 +509,7 @@ describe("buildAndWriteContainerOutput", () => { it("does not require Docker to clean a registry-only build", async ({ expect, }) => { - const config = InputContainerSchema.parse({ + const config = ContainerConfigSchema.parse({ name: "remote-container", image: { reference: "registry.example.com/app:latest" }, }); diff --git a/packages/containers-shared/tests/container-plan-for-cf-config.test.ts b/packages/containers-shared/tests/container-plan-for-cf-config.test.ts index 1249736ae8..60bc89f4ce 100644 --- a/packages/containers-shared/tests/container-plan-for-cf-config.test.ts +++ b/packages/containers-shared/tests/container-plan-for-cf-config.test.ts @@ -1,8 +1,8 @@ import path from "node:path"; import { - InputContainerSchema, - InputWorkerSchema, - OutputContainerSchema, + ContainerConfigSchema, + WorkerConfigSchema, + BuildOutputContainerConfigSchema, } from "@cloudflare/config"; import { describe, test } from "vitest"; import { @@ -16,7 +16,7 @@ describe("createContainerDevPlanForCfConfig", () => { expect, }) => { const root = path.resolve("project"); - const standard = InputContainerSchema.parse({ + const standard = ContainerConfigSchema.parse({ name: "standard", image: { dockerfile: "./containers/Dockerfile", @@ -24,7 +24,7 @@ describe("createContainerDevPlanForCfConfig", () => { buildVars: { VERSION: "1" }, }, }); - const managed = InputContainerSchema.parse({ + const managed = ContainerConfigSchema.parse({ name: "managed", schedulingPolicy: "durable-object", images: { @@ -87,7 +87,7 @@ describe("createContainerDevPlanForCfConfig", () => { }) => { const plan = createContainerDevPlanForCfConfig({ containers: [ - InputContainerSchema.parse({ + ContainerConfigSchema.parse({ name: "managed", schedulingPolicy: "durable-object", }), @@ -121,7 +121,7 @@ describe("createContainerDevPlanForCfConfig", () => { }) ).toThrow('Expected Container "missing"'); - const container = InputContainerSchema.parse({ + const container = ContainerConfigSchema.parse({ name: "duplicate", image: { reference: "docker.io/example:latest" }, }); @@ -141,11 +141,11 @@ describe("createContainerPreviewPlanForCfConfig", () => { }) => { const plan = createContainerPreviewPlanForCfConfig({ containers: [ - OutputContainerSchema.parse({ + BuildOutputContainerConfigSchema.parse({ name: "standard", image: { localReference: "cloudflare-build/project/app:123" }, }), - OutputContainerSchema.parse({ + BuildOutputContainerConfigSchema.parse({ name: "managed", schedulingPolicy: "durable-object", images: { @@ -212,7 +212,7 @@ describe("createContainerPreviewPlanForCfConfig", () => { describe("createMiniflareExports", () => { test("replaces Container names with runtime image metadata", ({ expect }) => { - const worker = InputWorkerSchema.parse({ + const worker = WorkerConfigSchema.parse({ name: "worker", compatibilityDate: "2024-12-30", exports: { diff --git a/packages/create-cloudflare/CHANGELOG.md b/packages/create-cloudflare/CHANGELOG.md index fd48a82201..4614cc215b 100644 --- a/packages/create-cloudflare/CHANGELOG.md +++ b/packages/create-cloudflare/CHANGELOG.md @@ -1,5 +1,77 @@ # create-cloudflare +## 2.74.13 + +### Patch Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Find the deployed Worker's name in Build Output v1 + + After `cf deploy`, C3 reads the Worker's name from the Build Output to look up its workers.dev URL. It now reads `.cloudflare/output/v1/`, falling back to `.cloudflare/output/v0/` because C3 installs `cf@latest`, which may still write v0. + +- [#16933](https://github.com/cloudflare/workers-sdk/pull/16933) [`80f0e5b`](https://github.com/cloudflare/workers-sdk/commit/80f0e5b35001b714468cb45bb192dbad2608d57e) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | --------------- | ------ | ------ | + | @angular/create | 22.2.6 | 22.2.7 | + +- [#16934](https://github.com/cloudflare/workers-sdk/pull/16934) [`6a6f10f`](https://github.com/cloudflare/workers-sdk/commit/6a6f10f6a07a898d9454de40d65c089bab8b8c01) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ----------- | ------ | ------ | + | create-qwik | 1.20.3 | 1.20.4 | + +- [#16935](https://github.com/cloudflare/workers-sdk/pull/16935) [`819ed90`](https://github.com/cloudflare/workers-sdk/commit/819ed9035175741c3ff48395ee3e9d257ef50184) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ----------- | ------- | ------- | + | create-vike | 0.0.692 | 0.0.694 | + +- [#16936](https://github.com/cloudflare/workers-sdk/pull/16936) [`f518803`](https://github.com/cloudflare/workers-sdk/commit/f51880365dea6fa40903046e648ce77cfa73b189) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------ | ----- | ----- | + | create-astro | 5.3.1 | 5.3.2 | + +- [#16937](https://github.com/cloudflare/workers-sdk/pull/16937) [`4bca70b`](https://github.com/cloudflare/workers-sdk/commit/4bca70b301302b018ca28c53af0813de430bedd6) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------- | ----- | ----- | + | create-analog | 2.9.6 | 2.9.7 | + +- [#16938](https://github.com/cloudflare/workers-sdk/pull/16938) [`c46d179`](https://github.com/cloudflare/workers-sdk/commit/c46d179e95fcf979ecc6fbea1b1d60ac4e2c6119) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "create-cloudflare" + + The following dependency versions have been updated: + + | Dependency | From | To | + | --------------- | ------ | ------ | + | create-next-app | 16.4.5 | 16.4.6 | + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +## 2.74.12 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + ## 2.74.11 ### Patch Changes diff --git a/packages/create-cloudflare/e2e/helpers/global-setup.ts b/packages/create-cloudflare/e2e/helpers/global-setup.ts index 29b01e87a3..dc7f1536e6 100644 --- a/packages/create-cloudflare/e2e/helpers/global-setup.ts +++ b/packages/create-cloudflare/e2e/helpers/global-setup.ts @@ -9,7 +9,10 @@ export default async function globalSetup() { await startMockNpmRegistry( "create-cloudflare", "@cloudflare/vitest-plugin", - "@cloudflare/vite-plugin" + "@cloudflare/vite-plugin", + // C3 installs `wrangler@latest` (and templates use `wrangler@^4`), so + // publish it at its real version to test the local copy. + "wrangler" ); const onExit = () => { stopMockNpmRegistry?.(); diff --git a/packages/create-cloudflare/package.json b/packages/create-cloudflare/package.json index 6db306fc19..172dfd1d82 100644 --- a/packages/create-cloudflare/package.json +++ b/packages/create-cloudflare/package.json @@ -1,6 +1,6 @@ { "name": "create-cloudflare", - "version": "2.74.11", + "version": "2.74.13", "description": "A CLI for creating and deploying new applications to Cloudflare.", "keywords": [ "cloudflare", diff --git a/packages/create-cloudflare/src/cf/__tests__/deploy.test.ts b/packages/create-cloudflare/src/cf/__tests__/deploy.test.ts index 03229e00c1..84424e0f36 100644 --- a/packages/create-cloudflare/src/cf/__tests__/deploy.test.ts +++ b/packages/create-cloudflare/src/cf/__tests__/deploy.test.ts @@ -9,10 +9,11 @@ import { getDeploymentUrl } from "../deploy"; vi.mock("helpers/command"); vi.mock("which-pm-runs"); -function writeDefaultWorkerConfig(name: string) { - mkdirSync(".cloudflare/output/v0/workers/default", { recursive: true }); +function writeDefaultWorkerConfig(name: string, version = "v1") { + const workerDir = `.cloudflare/output/${version}/workers/default`; + mkdirSync(workerDir, { recursive: true }); writeFileSync( - ".cloudflare/output/v0/workers/default/worker.config.json", + `${workerDir}/worker.config.json`, JSON.stringify({ name, compatibilityDate: "2026-01-01" }) ); } @@ -51,6 +52,42 @@ describe("getDeploymentUrl", () => { ); }); + test("reads the Worker name from Build Output v0", async ({ expect }) => { + writeDefaultWorkerConfig("legacy-worker", "v0"); + vi.mocked(runWranglerCommand).mockResolvedValueOnce( + cfWorkersGetOutput({ + enabled: true, + url: "https://legacy-worker.example.workers.dev", + }) + ); + + await expect(getDeploymentUrl(".", "test1234")).resolves.toBe( + "https://legacy-worker.example.workers.dev" + ); + expect(runWranglerCommand).toHaveBeenCalledWith( + ["npx", "cf", "workers", "get", "legacy-worker"], + expect.anything() + ); + }); + + test("prefers Build Output v1 over v0", async ({ expect }) => { + writeDefaultWorkerConfig("legacy-worker", "v0"); + writeDefaultWorkerConfig("my-worker"); + vi.mocked(runWranglerCommand).mockResolvedValueOnce( + cfWorkersGetOutput({ + enabled: true, + url: "https://my-worker.example.workers.dev", + }) + ); + + await getDeploymentUrl(".", "test1234"); + + expect(runWranglerCommand).toHaveBeenCalledWith( + ["npx", "cf", "workers", "get", "my-worker"], + expect.anything() + ); + }); + test("workers.dev disabled", async ({ expect }) => { writeDefaultWorkerConfig("my-worker"); vi.mocked(runWranglerCommand).mockResolvedValueOnce( @@ -67,7 +104,7 @@ describe("getDeploymentUrl", () => { test("no Build Output", async ({ expect }) => { await expect(getDeploymentUrl(".", "test1234")).rejects.toThrow( - "Failed to find deployment url: could not read the Worker's name from `.cloudflare/output/v0/workers/default/worker.config.json`." + "Failed to find deployment url: could not read the Worker's name from `.cloudflare/output/v1/workers/default/worker.config.json`." ); expect(runWranglerCommand).not.toHaveBeenCalled(); }); diff --git a/packages/create-cloudflare/src/cf/deploy.ts b/packages/create-cloudflare/src/cf/deploy.ts index 2dd2d40347..11ea2092e5 100644 --- a/packages/create-cloudflare/src/cf/deploy.ts +++ b/packages/create-cloudflare/src/cf/deploy.ts @@ -1,3 +1,4 @@ +import { existsSync } from "node:fs"; import { join } from "node:path"; import { CancelError } from "@cloudflare/cli-shared-helpers/error"; import { runWranglerCommand } from "helpers/command"; @@ -9,6 +10,19 @@ import { detectPackageManager } from "helpers/packageManagers"; * passed `--worker`. */ const DEFAULT_WORKER_CONFIG_PATH = + ".cloudflare/output/v1/workers/default/worker.config.json"; + +/** + * Where `cf` versions that write Build Output v0 put the same config. + * + * C3 installs `cf@latest`, which may still write v0 when this version of C3 + * runs. Remove this once the `latest` release of `cf` writes v1. + * + * Only one of the two paths can exist. C3 deploys a project it has just + * created, and every build removes all of `.cloudflare/output` before + * writing, so checking v1 first can't pick up stale output. + */ +const LEGACY_DEFAULT_WORKER_CONFIG_PATH = ".cloudflare/output/v0/workers/default/worker.config.json"; /** The subset of the JSON printed by `cf workers get` that C3 relies on. */ @@ -32,14 +46,20 @@ export async function getDeploymentUrl( projectPath: string, accountId: string ): Promise { + const configPath = [ + DEFAULT_WORKER_CONFIG_PATH, + LEGACY_DEFAULT_WORKER_CONFIG_PATH, + ].find((candidate) => existsSync(join(projectPath, candidate))); let name: string; try { - ({ name } = readJSON(join(projectPath, DEFAULT_WORKER_CONFIG_PATH)) as { + ({ name } = readJSON( + join(projectPath, configPath ?? DEFAULT_WORKER_CONFIG_PATH) + ) as { name: string; }); } catch { throw new Error( - `Failed to find deployment url: could not read the Worker's name from \`${DEFAULT_WORKER_CONFIG_PATH}\`.` + `Failed to find deployment url: could not read the Worker's name from \`${configPath ?? DEFAULT_WORKER_CONFIG_PATH}\`.` ); } diff --git a/packages/create-cloudflare/src/frameworks/package.json b/packages/create-cloudflare/src/frameworks/package.json index 5a1b54d7e7..0bcbb03d14 100644 --- a/packages/create-cloudflare/src/frameworks/package.json +++ b/packages/create-cloudflare/src/frameworks/package.json @@ -1,18 +1,18 @@ { "name": "frameworks_clis_info", "dependencies": { - "@angular/create": "22.2.6", + "@angular/create": "22.2.7", "@tanstack/cli": "0.72.16", - "create-analog": "2.9.6", - "create-astro": "5.3.1", + "create-analog": "2.9.7", + "create-astro": "5.3.2", "create-docusaurus": "3.10.2", "create-hono": "0.19.5", - "create-next-app": "16.4.5", - "create-qwik": "1.20.3", + "create-next-app": "16.4.6", + "create-qwik": "1.20.4", "create-react-router": "8.5.1", "create-rwsdk": "3.1.3", "create-solid": "0.12.0", - "create-vike": "0.0.692", + "create-vike": "0.0.694", "create-vinext-app": "1.1.0", "create-vite": "9.3.4", "create-vue": "3.24.0", diff --git a/packages/deploy-helpers/CHANGELOG.md b/packages/deploy-helpers/CHANGELOG.md index 7fe58f5f3d..591e69b3d4 100644 --- a/packages/deploy-helpers/CHANGELOG.md +++ b/packages/deploy-helpers/CHANGELOG.md @@ -1,5 +1,55 @@ # @cloudflare/deploy-helpers +## 0.27.1 + +### Patch Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Write Build Output to `.cloudflare/output/v1/` and record the producer + + `vite build` and the experimental `wrangler build --experimental-cf-build-output` now write Build Output v1, with account settings nested under `settings` in the root `config.json`. They also record themselves as the `producer`, so readers can name the tool that wrote the output in error messages. Previews from Build Output read the account settings from their new location. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b)]: + - @cloudflare/config@1.0.0-rc.0 + - @cloudflare/workers-utils@0.54.1 + - @cloudflare/cli-shared-helpers@0.3.9 + - @cloudflare/containers-shared@0.26.2 + - miniflare@5.20261116.0-beta + +## 0.27.0 + +### Minor Changes + +- [#16749](https://github.com/cloudflare/workers-sdk/pull/16749) [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373) Thanks [@vaishnav-mk](https://github.com/vaishnav-mk)! - Reject settings on a `workflows` binding to a Workflow declared in `exports` + + A `workflows` binding can still bind a Workflow that the Worker declares in `exports`, but it can no longer set `limits`, `concurrency`, `schedules`, `default_retention`, or `jurisdiction` for it. Set them on the export instead. Previously the binding and the export could both set them as long as they agreed, so configurations that set them on the binding now stop with an error that says which setting to move. + +- [#16749](https://github.com/cloudflare/workers-sdk/pull/16749) [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373) Thanks [@vaishnav-mk](https://github.com/vaishnav-mk)! - Upload Workflow export settings with the Worker + + `wrangler deploy` and `wrangler versions upload` now include the settings of each `workflow` export (`limits`, `concurrency`, `schedules`, `default_retention`, and `jurisdiction`) in the upload, instead of sending only its type and name. Uploads of a Worker with `workflow` exports also send a `Cloudflare-Workers-Script-Api-Date` header, which lets the Workers API provision Workflow exports from these settings as part of the upload. `wrangler deploy` and `wrangler triggers deploy` still create or update each Workflow through the Workflows API afterwards, as before. + + If provisioning a scheduled Workflow fails because the account is on the free plan, `wrangler deploy` now explains that scheduled Workflows require a paid Workers plan. + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985)]: + - miniflare@5.20261113.0-beta + - @cloudflare/workers-utils@0.54.0 + - @cloudflare/cli-shared-helpers@0.3.8 + - @cloudflare/config@0.32.1 + - @cloudflare/containers-shared@0.26.1 + ## 0.26.4 ### Patch Changes diff --git a/packages/deploy-helpers/package.json b/packages/deploy-helpers/package.json index ea2e366dd4..20df7271ed 100644 --- a/packages/deploy-helpers/package.json +++ b/packages/deploy-helpers/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/deploy-helpers", - "version": "0.26.4", + "version": "0.27.1", "description": "Internal deploy helpers for workers-sdk. Not intended for external use — APIs may change without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/deploy-helpers#readme", "bugs": { diff --git a/packages/deploy-helpers/src/deploy/deploy.ts b/packages/deploy-helpers/src/deploy/deploy.ts index 812c31227f..dc2f54a89a 100644 --- a/packages/deploy-helpers/src/deploy/deploy.ts +++ b/packages/deploy-helpers/src/deploy/deploy.ts @@ -51,7 +51,10 @@ import { tagsAreEqual, warnOnErrorUpdatingServiceAndEnvironmentTags, } from "./helpers/environments"; -import { EXPORTS_RECONCILIATION_ERROR_CODE } from "./helpers/error-codes"; +import { + EXPORTS_RECONCILIATION_ERROR_CODE, + WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, +} from "./helpers/error-codes"; import { resolveExportsUploadPayload } from "./helpers/exports"; import { isExportsReconciliationErrorDetails, @@ -286,7 +289,11 @@ async function deployWorker( }); // Durable Object lifecycle is expressed through either legacy `migrations` // or the declarative `exports` map. Only one is sent on each upload. - const { migrations, exports } = await resolveExportsUploadPayload({ + const { + migrations, + exports, + headers: exportsHeaders, + } = await resolveExportsUploadPayload({ scriptName, isDryRun, accountId, @@ -543,9 +550,10 @@ async function deployWorker( { method: "POST", body: workerBundle, - headers: props.sendMetrics - ? { metricsEnabled: "true" } - : undefined, + headers: { + ...exportsHeaders, + ...(props.sendMetrics && { metricsEnabled: "true" }), + }, }, new URLSearchParams({ bindings_inherit: "strict" }) ), @@ -614,9 +622,10 @@ async function deployWorker( { method: "PUT", body: workerBundle, - headers: props.sendMetrics - ? { metricsEnabled: "true" } - : undefined, + headers: { + ...exportsHeaders, + ...(props.sendMetrics && { metricsEnabled: "true" }), + }, }, new URLSearchParams({ // pass excludeScript so the whole body of the @@ -712,6 +721,22 @@ async function deployWorker( ); } + // Workflow exports are provisioned on deploy, so this can come back here + // as well as from `triggers deploy`. + if ( + err instanceof APIError && + err.code === WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE + ) { + err.preventReport(); + throw new UserError( + `A Workflow has "schedules" configured, but scheduled Workflows require a paid Workers plan.`, + { + cause: err, + telemetryMessage: "deploy workflow cron requires paid plan", + } + ); + } + const message = await helpIfErrorIsSizeOrScriptStartup( err, dependencies, diff --git a/packages/deploy-helpers/src/deploy/helpers/exports.ts b/packages/deploy-helpers/src/deploy/helpers/exports.ts index d45558e508..440bf5ef7b 100644 --- a/packages/deploy-helpers/src/deploy/helpers/exports.ts +++ b/packages/deploy-helpers/src/deploy/helpers/exports.ts @@ -2,6 +2,9 @@ import { partitionExports } from "@cloudflare/workers-utils"; import { resolveDoLifecyclePayload } from "./durable"; import type { CfWorkerInit } from "@cloudflare/workers-utils"; +// Tells the upload API that `workflow` exports carry their settings. +const WORKFLOW_EXPORTS_SCRIPT_API_DATE = "2026-11-09"; + type ResolveExportsUploadPayloadProps = Parameters< typeof resolveDoLifecyclePayload >[0]; @@ -11,6 +14,7 @@ export async function resolveExportsUploadPayload( ): Promise<{ migrations: CfWorkerInit["migrations"]; exports: CfWorkerInit["exports"]; + headers: Record | undefined; }> { const partitionedExports = partitionExports(props.config.exports); const { migrations, exports: durableObjectExports } = @@ -20,18 +24,18 @@ export async function resolveExportsUploadPayload( const exports: NonNullable = { ...partitionedExports.worker, ...(durableObjectExports ?? {}), - // Workflow settings are applied when `triggers deploy` provisions the - // Workflow; the upload API only accepts the type and name. - ...Object.fromEntries( - Object.entries(partitionedExports.workflow).map( - ([className, { name }]) => - [className, { type: "workflow", name }] as const - ) - ), + ...partitionedExports.workflow, }; return { migrations, exports: Object.keys(exports).length > 0 ? exports : undefined, + headers: + Object.keys(partitionedExports.workflow).length > 0 + ? { + "Cloudflare-Workers-Script-Api-Date": + WORKFLOW_EXPORTS_SCRIPT_API_DATE, + } + : undefined, }; } diff --git a/packages/deploy-helpers/src/deploy/helpers/owned-workflows.ts b/packages/deploy-helpers/src/deploy/helpers/owned-workflows.ts index 374cc58383..7d2544f827 100644 --- a/packages/deploy-helpers/src/deploy/helpers/owned-workflows.ts +++ b/packages/deploy-helpers/src/deploy/helpers/owned-workflows.ts @@ -1,4 +1,3 @@ -import { isDeepStrictEqual } from "node:util"; import { partitionExports, UserError } from "@cloudflare/workers-utils"; import type { Config, WorkflowBinding } from "@cloudflare/workers-utils"; @@ -16,9 +15,8 @@ export function isWorkflowDefinedInThisScript( /** * Collects the Workflows this script defines, from both `workflows` bindings * and `exports` entries of type `workflow`. A Workflow declared in both places - * is returned once, with the settings of both declarations merged; - * {@link validateOwnedWorkflowDeclarations} guarantees the two declarations - * agree. + * is returned once, with the export's settings; + * {@link validateOwnedWorkflowDeclarations} guarantees the binding sets none. * * @param config - The Worker config * @param scriptName - The name of the script being deployed @@ -37,26 +35,25 @@ export function getWorkflowsOwnedByScript( for (const [className, workflowExport] of Object.entries( partitionExports(config.exports).workflow )) { - const binding = owned.get(workflowExport.name); owned.set(workflowExport.name, { name: workflowExport.name, class_name: className, - limits: binding?.limits ?? workflowExport.limits, - concurrency: binding?.concurrency ?? workflowExport.concurrency, - schedules: binding?.schedules ?? workflowExport.schedules, - default_retention: - binding?.default_retention ?? workflowExport.default_retention, - jurisdiction: binding?.jurisdiction ?? workflowExport.jurisdiction, + limits: workflowExport.limits, + concurrency: workflowExport.concurrency, + schedules: workflowExport.schedules, + default_retention: workflowExport.default_retention, + jurisdiction: workflowExport.jurisdiction, }); } return [...owned.values()]; } /** - * Checks that each `workflows` binding owned by this script agrees with the - * `workflow` export of the same name, so {@link getWorkflowsOwnedByScript} can - * merge them, and that no binding to another script's Workflow shares a name - * with an export, since the export makes this script the Workflow's owner. + * Checks that each `workflows` binding owned by this script only binds the + * `workflow` export of the same name: same class, and no settings, since the + * export holds them. Also checks that no binding to another script's Workflow + * shares a name with an export, since the export makes this script the + * Workflow's owner. * This can't run during config validation: ownership depends on the name the * script is deployed under, which `--name` or a CI override can change after * the config is validated. @@ -64,8 +61,8 @@ export function getWorkflowsOwnedByScript( * @param config - The Worker config * @param scriptName - The name of the script being deployed * @throws {UserError} If a binding and an export for the same Workflow use - * different classes, set the same setting to different values, or disagree - * about which script owns the Workflow + * different classes, the binding sets a setting, or they disagree about which + * script owns the Workflow */ export function validateOwnedWorkflowDeclarations( config: Pick, @@ -73,19 +70,15 @@ export function validateOwnedWorkflowDeclarations( ): void { const exportsByWorkflowName = new Map( Object.entries(partitionExports(config.exports).workflow).map( - ([className, workflowExport]) => [ - workflowExport.name, - { className, workflowExport }, - ] + ([className, workflowExport]) => [workflowExport.name, className] ) ); const errors: string[] = []; for (const [index, workflow] of (config.workflows ?? []).entries()) { - const match = exportsByWorkflowName.get(workflow.name); - if (match === undefined) { + const className = exportsByWorkflowName.get(workflow.name); + if (className === undefined) { continue; } - const { className, workflowExport } = match; if (!isWorkflowDefinedInThisScript(workflow, scriptName)) { errors.push( `"workflows[${index}]" binds the Workflow "${workflow.name}" of the Worker "${workflow.script_name}", but "exports.${className}" declares it in this Worker. Workflow names are unique per account, so remove "script_name" from the binding or give the export a different name.` @@ -104,16 +97,9 @@ export function validateOwnedWorkflowDeclarations( "default_retention", "jurisdiction", ] as const) { - const bindingValue = workflow[key]; - const exportValue = workflowExport[key]; - // `schedules` accepts a string or an array; compare both as arrays. - if ( - bindingValue !== undefined && - exportValue !== undefined && - !isDeepStrictEqual([bindingValue].flat(), [exportValue].flat()) - ) { + if (workflow[key] !== undefined) { errors.push( - `"workflows[${index}].${key}" and "exports.${className}.${key}" both configure the Workflow "${workflow.name}", but with different values. Set "${key}" in only one of them.` + `"workflows[${index}].${key}" configures the Workflow "${workflow.name}", which "exports.${className}" declares. Set "${key}" on the export instead.` ); } } diff --git a/packages/deploy-helpers/src/deploy/versions-upload.ts b/packages/deploy-helpers/src/deploy/versions-upload.ts index 727c8b52d9..ada6c6ff9e 100644 --- a/packages/deploy-helpers/src/deploy/versions-upload.ts +++ b/packages/deploy-helpers/src/deploy/versions-upload.ts @@ -183,7 +183,11 @@ async function uploadWorkerVersion( // script_version row with `SkipDeploy:true`, so reconciliation is // deferred to the subsequent deploy (either `wrangler deploy` or // `wrangler versions deploy `). - const { migrations, exports } = await resolveExportsUploadPayload({ + const { + migrations, + exports, + headers: exportsHeaders, + } = await resolveExportsUploadPayload({ scriptName, isDryRun: props.dryRun, accountId, @@ -359,9 +363,10 @@ async function uploadWorkerVersion( { method: "POST", body: workerBundle, - headers: props.sendMetrics - ? { metricsEnabled: "true" } - : undefined, + headers: { + ...exportsHeaders, + ...(props.sendMetrics && { metricsEnabled: "true" }), + }, }, new URLSearchParams({ bindings_inherit: "strict" }) ), diff --git a/packages/deploy-helpers/src/preview/preview.ts b/packages/deploy-helpers/src/preview/preview.ts index e50248a0df..8a61de894a 100644 --- a/packages/deploy-helpers/src/preview/preview.ts +++ b/packages/deploy-helpers/src/preview/preview.ts @@ -56,10 +56,10 @@ import type { } from "./api"; import type { PullRequestMetadata } from "./shared"; import type { - ParsedInputContainerConfig, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedContainerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { ContainerNormalizedConfig } from "@cloudflare/containers-shared"; import type { @@ -111,13 +111,15 @@ export type PreviewResult = { isNewPreview: boolean; }; -export type PreviewBuildOutputRootConfig = ParsedOutputRootConfig & { - buildContext: ParsedOutputRootConfig["buildContext"] & { isPreview: true }; +export type PreviewBuildOutputRootConfig = ParsedBuildOutputRootConfig & { + buildContext: ParsedBuildOutputRootConfig["buildContext"] & { + isPreview: true; + }; }; export type PreviewBuildOutput = { // Authoritative Worker settings and bindings from Build Output. - workerConfig: ParsedOutputWorkerConfig; + workerConfig: ParsedBuildOutputWorkerConfig; // Account settings and build context from the root Build Output config. rootConfig: PreviewBuildOutputRootConfig; // Compiled Worker code and modules, if this is not an assets-only build. @@ -126,7 +128,7 @@ export type PreviewBuildOutput = { assets?: Pick; // Container definitions are emitted separately from the Worker config because // Build Output records resolved image references rather than source config. - containers?: ParsedOutputContainerConfig[]; + containers?: ParsedBuildOutputContainerConfig[]; }; type PreviewWorkerBuildResult = WorkerBuildResult & { @@ -135,7 +137,7 @@ type PreviewWorkerBuildResult = WorkerBuildResult & { /** Verify that Build Output was produced with Preview configuration. */ export function assertPreviewBuildOutputRootConfig( - rootConfig: ParsedOutputRootConfig | undefined + rootConfig: ParsedBuildOutputRootConfig | undefined ): asserts rootConfig is PreviewBuildOutputRootConfig { if (rootConfig?.buildContext.isPreview !== true) { throw new UserError("Build Output was not created by a Preview build.", { @@ -191,8 +193,8 @@ export type PreviewOptions = { }; function convertBuildOutputContainerToInput( - container: ParsedOutputContainerConfig -): ParsedInputContainerConfig { + container: ParsedBuildOutputContainerConfig +): ParsedContainerConfig { if ("image" in container) { const { image, ...config } = container; return { @@ -214,7 +216,7 @@ function convertBuildOutputContainerToInput( } function getLocalContainerImageReferences( - containers: ParsedOutputContainerConfig[] | undefined, + containers: ParsedBuildOutputContainerConfig[] | undefined, previewContainers: ContainerApp[] ): Map { const localReferences = new Map(); @@ -241,7 +243,7 @@ function getLocalContainerImageReferences( * Converts resolved Build Output containers into preview application configs. */ function convertBuildOutputContainers( - containers: ParsedOutputContainerConfig[] | undefined, + containers: ParsedBuildOutputContainerConfig[] | undefined, exports: Exports | undefined ): ContainerApp[] { const containerClassNames = new Map(); @@ -1378,10 +1380,9 @@ export async function previewBuildOutput( } ); } - const { buildContext: _buildContext, ...settings } = rootConfig; const { manifest: _manifest, ...worker } = workerConfig; const convertedConfig = convertToWranglerConfig({ - ...settings, + ...rootConfig.settings, worker, containers: [], }); diff --git a/packages/deploy-helpers/tests/owned-workflows.test.ts b/packages/deploy-helpers/tests/owned-workflows.test.ts index a06e8090dc..2a66913a48 100644 --- a/packages/deploy-helpers/tests/owned-workflows.test.ts +++ b/packages/deploy-helpers/tests/owned-workflows.test.ts @@ -5,7 +5,7 @@ import { } from "../src/deploy/helpers/owned-workflows"; describe("getWorkflowsOwnedByScript", () => { - it("keeps the jurisdiction from either declaration of a Workflow", ({ + it("takes the settings of a Workflow declared in both places from its export", ({ expect, }) => { expect( @@ -16,11 +16,14 @@ describe("getWorkflowsOwnedByScript", () => { binding: "GREETING", name: "greeting", class_name: "GreetingWorkflow", - jurisdiction: "eu", }, ], exports: { - GreetingWorkflow: { type: "workflow", name: "greeting" }, + GreetingWorkflow: { + type: "workflow", + name: "greeting", + jurisdiction: "eu", + }, OrdersWorkflow: { type: "workflow", name: "orders", @@ -31,16 +34,14 @@ describe("getWorkflowsOwnedByScript", () => { "my-worker" ) ).toMatchObject([ - { name: "greeting", jurisdiction: "eu" }, + { name: "greeting", class_name: "GreetingWorkflow", jurisdiction: "eu" }, { name: "orders", jurisdiction: "us" }, ]); }); }); describe("validateOwnedWorkflowDeclarations", () => { - it("accepts a binding and an export that configure the same Workflow settings in different forms", ({ - expect, - }) => { + it("accepts a binding to a Workflow declared in exports", ({ expect }) => { expect(() => validateOwnedWorkflowDeclarations( { @@ -49,8 +50,7 @@ describe("validateOwnedWorkflowDeclarations", () => { binding: "GREETING", name: "greeting", class_name: "GreetingWorkflow", - limits: { steps: 10 }, - schedules: "0 * * * *", + script_name: "my-worker", }, ], exports: { @@ -58,7 +58,6 @@ describe("validateOwnedWorkflowDeclarations", () => { type: "workflow", name: "greeting", limits: { steps: 10 }, - concurrency: { limit: 1 }, schedules: ["0 * * * *"], }, }, @@ -92,7 +91,7 @@ describe("validateOwnedWorkflowDeclarations", () => { ); }); - it("errors when a binding and an export configure the same Workflow with different settings", ({ + it("errors when a binding sets settings for a Workflow declared in exports", ({ expect, }) => { expect(() => @@ -111,25 +110,17 @@ describe("validateOwnedWorkflowDeclarations", () => { }, ], exports: { - GreetingWorkflow: { - type: "workflow", - name: "greeting", - limits: { steps: 20 }, - concurrency: { limit: 2 }, - schedules: ["30 * * * *"], - default_retention: { success_retention: "2 days" }, - jurisdiction: "us", - }, + GreetingWorkflow: { type: "workflow", name: "greeting" }, }, }, "my-worker" ) ).toThrowErrorMatchingInlineSnapshot(` - [Error: "workflows[0].limits" and "exports.GreetingWorkflow.limits" both configure the Workflow "greeting", but with different values. Set "limits" in only one of them. - "workflows[0].concurrency" and "exports.GreetingWorkflow.concurrency" both configure the Workflow "greeting", but with different values. Set "concurrency" in only one of them. - "workflows[0].schedules" and "exports.GreetingWorkflow.schedules" both configure the Workflow "greeting", but with different values. Set "schedules" in only one of them. - "workflows[0].default_retention" and "exports.GreetingWorkflow.default_retention" both configure the Workflow "greeting", but with different values. Set "default_retention" in only one of them. - "workflows[0].jurisdiction" and "exports.GreetingWorkflow.jurisdiction" both configure the Workflow "greeting", but with different values. Set "jurisdiction" in only one of them.] + [Error: "workflows[0].limits" configures the Workflow "greeting", which "exports.GreetingWorkflow" declares. Set "limits" on the export instead. + "workflows[0].concurrency" configures the Workflow "greeting", which "exports.GreetingWorkflow" declares. Set "concurrency" on the export instead. + "workflows[0].schedules" configures the Workflow "greeting", which "exports.GreetingWorkflow" declares. Set "schedules" on the export instead. + "workflows[0].default_retention" configures the Workflow "greeting", which "exports.GreetingWorkflow" declares. Set "default_retention" on the export instead. + "workflows[0].jurisdiction" configures the Workflow "greeting", which "exports.GreetingWorkflow" declares. Set "jurisdiction" on the export instead.] `); }); diff --git a/packages/deploy-helpers/tests/package-dependencies.test.ts b/packages/deploy-helpers/tests/package-dependencies.test.ts index c3fbe343e7..9f757f29a7 100644 --- a/packages/deploy-helpers/tests/package-dependencies.test.ts +++ b/packages/deploy-helpers/tests/package-dependencies.test.ts @@ -668,6 +668,63 @@ describe("collectPackageDependencies", () => { ]); }); + it("should collect packages whose entry point sits next to a nested package.json", async ({ + expect, + }) => { + // Mirrors the layout of `hono`: no `./package.json` export, and a + // `dist/cjs/package.json` that only contains `{"type": "commonjs"}`. + const pkgPath = path.join(process.cwd(), "node_modules", "hono"); + const cjsPath = path.join(pkgPath, "dist", "cjs"); + fs.mkdirSync(cjsPath, { recursive: true }); + fs.writeFileSync(path.join(cjsPath, "index.js"), "module.exports = {}"); + fs.writeFileSync( + path.join(cjsPath, "package.json"), + JSON.stringify({ type: "commonjs" }, null, 2) + ); + fs.writeFileSync( + path.join(pkgPath, "package.json"), + JSON.stringify( + { + name: "hono", + version: "4.13.18", + type: "module", + exports: { + ".": { + import: "./dist/index.js", + require: "./dist/cjs/index.js", + }, + }, + }, + null, + 2 + ) + ); + + fs.writeFileSync( + "package.json", + JSON.stringify( + { + name: "test-project", + dependencies: { + hono: "^4.13.0", + }, + }, + null, + 2 + ) + ); + + const result = await collectPackageDependencies(process.cwd()); + + expect(result).toEqual([ + { + name: "hono", + packageJsonVersion: "^4.13.0", + installedVersion: "4.13.18", + }, + ]); + }); + it("should use devDependencies version when duplicate exists in dependencies", async ({ expect, }) => { diff --git a/packages/deploy-helpers/tests/preview-build-output.test.ts b/packages/deploy-helpers/tests/preview-build-output.test.ts index 38e5f65594..801a32a435 100644 --- a/packages/deploy-helpers/tests/preview-build-output.test.ts +++ b/packages/deploy-helpers/tests/preview-build-output.test.ts @@ -9,8 +9,8 @@ import type { PreviewOptions, } from "../src/preview/preview"; import type { - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; const mocks = vi.hoisted(() => ({ @@ -78,8 +78,8 @@ const buildResult: PreviewBuildOutput["buildResult"] = { const validRootConfig = { buildContext: { isPreview: true } } as const; function buildOutputConfig( - overrides: Partial = {} -): ParsedOutputWorkerConfig { + overrides: Partial = {} +): ParsedBuildOutputWorkerConfig { return { name: "preview-worker", compatibilityDate: "2026-09-17", @@ -88,7 +88,7 @@ function buildOutputConfig( } function uploadPreview( - config: ParsedOutputWorkerConfig, + config: ParsedBuildOutputWorkerConfig, assets?: PreviewBuildOutput["assets"] ) { return previewBuildOutput( @@ -678,7 +678,7 @@ describe("previewBuildOutput", () => { expect(mocks.createPreviewDeployment).not.toHaveBeenCalled(); }); - it.for<[string, ParsedOutputRootConfig | undefined]>([ + it.for<[string, ParsedBuildOutputRootConfig | undefined]>([ ["missing", undefined], ["non-Preview", { buildContext: { isPreview: false } }], ])("rejects $0 Preview intent", async ([, rootConfig], { expect }) => { @@ -697,7 +697,7 @@ describe("previewBuildOutput", () => { expect(mocks.getPreview).not.toHaveBeenCalled(); }); - it.for>([ + it.for>([ ["example.com"], [{ hostname: "example.com", production: true, previews: false }], [{ hostname: "previews.example.com", production: false, previews: true }], @@ -728,7 +728,7 @@ describe("previewBuildOutput", () => { expect(config.domains).toEqual(domains); }); - it.for<[string, Partial]>([ + it.for<[string, Partial]>([ ["triggers", { triggers: [{ type: "scheduled", schedule: "0 * * * *" }] }], [ "streaming tail consumers", diff --git a/packages/local-explorer-ui/CHANGELOG.md b/packages/local-explorer-ui/CHANGELOG.md index b5dfbbf9ac..9a64e86748 100644 --- a/packages/local-explorer-ui/CHANGELOG.md +++ b/packages/local-explorer-ui/CHANGELOG.md @@ -1,5 +1,11 @@ # @cloudflare/local-explorer-ui +## 0.17.1 + +### Patch Changes + +- [#16831](https://github.com/cloudflare/workers-sdk/pull/16831) [`20f1424`](https://github.com/cloudflare/workers-sdk/commit/20f1424c2c490ad786351f04b74baa9e32f1ca8f) Thanks [@thejus-r](https://github.com/thejus-r)! - fix: prevent New Query button from wrapping and overlapping tab labels in Studio + ## 0.17.0 ### Minor Changes diff --git a/packages/local-explorer-ui/package.json b/packages/local-explorer-ui/package.json index 04e5b62006..c2c360d719 100644 --- a/packages/local-explorer-ui/package.json +++ b/packages/local-explorer-ui/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/local-explorer-ui", - "version": "0.17.0", + "version": "0.17.1", "private": true, "type": "module", "scripts": { diff --git a/packages/local-explorer-ui/src/components/studio/WindowTab/MenuProps.tsx b/packages/local-explorer-ui/src/components/studio/WindowTab/MenuProps.tsx index 49cb4c4a09..e17ac9292a 100644 --- a/packages/local-explorer-ui/src/components/studio/WindowTab/MenuProps.tsx +++ b/packages/local-explorer-ui/src/components/studio/WindowTab/MenuProps.tsx @@ -1,3 +1,4 @@ +import { Button } from "@cloudflare/kumo"; import { PlusIcon } from "@phosphor-icons/react"; import type { JSX } from "react"; @@ -9,12 +10,10 @@ export function StudioWindowTabMenu({ onClick, }: StudioWindowTabMenuProps): JSX.Element { return ( - +
+ +
); } diff --git a/packages/miniflare/AGENTS.md b/packages/miniflare/AGENTS.md index d4fc7e4a97..35b2528f6c 100644 --- a/packages/miniflare/AGENTS.md +++ b/packages/miniflare/AGENTS.md @@ -46,7 +46,7 @@ Local dev simulator for Cloudflare Workers, powered by workerd runtime. Main cla ## Testing - Test files use `.spec.ts` (NOT `.test.ts`) -- `pool: "forks"`, `maxWorkers: 1` (limits test files to one worker) +- `vitest.config.mts` is authoritative for the pool, worker count, and timeouts. Test files run in parallel; `concurrent: false` only serializes tests within a file. - Does NOT extend `vitest.shared.ts` — own full vitest config - Timeouts: 30s test, 30s hook - `globals: true` @@ -55,6 +55,12 @@ Local dev simulator for Cloudflare Workers, powered by workerd runtime. Main cla - `useServer()` — temp HTTP server with auto-cleanup - `TestLog` — captures log entries by level +### Browser tests + +- Tests that launch real Chrome should warm it in `beforeAll`, using `CHROME_INSTALL_TIMEOUT` and `retryBrowserStartup()` from `test/test-shared/browser.ts`. The first launch may download Chrome, and even a cached install can exceed Chrome's readiness deadline on a loaded runner. Increasing the hook timeout does not extend that deadline. +- Check the warm-up response inside the retry callback and include its body in the failure message. Quick actions return launch failures as error responses, so checking only the status hides the error needed to recognize a transient startup failure. +- Keep retries limited to recognized startup failures. Unrelated warm-up failures and functional assertions must still fail immediately. Dispose any Miniflare instances created for individual warm-up attempts before retrying. + ## Generated Files - `src/runtime/config/generated/workerd.ts` — generated Cap'n Proto types, do not edit directly diff --git a/packages/miniflare/CHANGELOG.md b/packages/miniflare/CHANGELOG.md index e9f02e3710..b4c64d205f 100644 --- a/packages/miniflare/CHANGELOG.md +++ b/packages/miniflare/CHANGELOG.md @@ -1,5 +1,94 @@ # miniflare +## 5.20261116.0-beta + +### Minor Changes + +- [#16246](https://github.com/cloudflare/workers-sdk/pull/16246) [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155) Thanks [@leostera](https://github.com/leostera)! - Start local Workflows from Artifacts events + + Declare Artifacts events on `exports.workflow({ name, events })` in `cloudflare.config.ts` to start the owning Workflow locally in `cf`, Vite, and Workers Vitest. Wrangler configurations continue to use `triggers.events`. Native config conversion derives those targets from the Workflow export, and `cf migrate` attaches existing event subscriptions to their matching Workflow exports. + + Local Artifacts namespaces publish the documented `cf.artifacts.*` messages for repository create, import, fork, and delete operations and token creation and revocation. Successful create, import, and fork operations also publish the initial token-created event. Delivery follows the committed mutation, is unordered, and does not fail the repository operation if a destination rejects it. Push, clone, and fetch events are not yet published locally. This feature does not provide local Artifacts-to-queue subscriptions. + +- [#16907](https://github.com/cloudflare/workers-sdk/pull/16907) [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Rename the Pipelines, K2 and Analytics SQL `env` binding fields to match `@cloudflare/config` + + Config-style `env` bindings now use these shapes: + + - `{ type: "pipeline", streamId }` instead of `{ type: "pipeline", name }` + - `{ type: "k2", id }` instead of `{ type: "k2", stream }` + - `{ type: "analytics-sql" }` instead of `{ type: "analytics" }` + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261113.1 | ^5.20261116.1 | + | workerd | 1.20261113.1 | 1.20261116.1 | + +## 5.20261113.0-beta + +### Minor Changes + +- [#16735](https://github.com/cloudflare/workers-sdk/pull/16735) [`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7) Thanks [@leostera](https://github.com/leostera)! - Use the local simulator for Artifacts bindings that omit `remote` + + **Behavior change:** Artifacts bindings now default to the local simulator during development, like KV, R2 and D1. Previously, an omitted `remote` in Wrangler and the Vite plugin used the deployed Artifacts resource. If you want deployed repos in `wrangler dev` or `vite dev`, set `"remote": true` on the binding (`dev: { remote: true }` in `cloudflare.config.ts`). Artifacts is in beta, so this ships as a minor release. + + While `remote` is omitted, `wrangler dev`, `getPlatformProxy()` and the Vite plugin warn when remote bindings are enabled, once for each binding rather than on every config reload: "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning." Workers Vitest and `wrangler dev --local` already used the simulator, so they don't warn. Local Artifacts needs no Cloudflare credentials, but requires Git 2.32 or newer on the host. + +- [#16589](https://github.com/cloudflare/workers-sdk/pull/16589) [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2) Thanks [@mkuritsu](https://github.com/mkuritsu)! - Support Browser Run quick actions in local development + + `env.BROWSER.quickAction(action, options)` now works with a local browser binding instead of failing with `The RPC receiver does not implement the method "quickAction"`. The `screenshot`, `pdf`, `content`, `markdown`, `snapshot`, `scrape`, `links` and `accessibilityTree` actions run in a local Chrome and return the same responses and errors as Browser Run. + + Workers AI isn't available locally, so the `json` action returns placeholder data shaped like `response_format.json_schema` and logs a warning. The `kitesurf` browser isn't supported locally either. Set `"remote": true` on the browser binding to use Browser Run for these. + +### Patch Changes + +- [#16771](https://github.com/cloudflare/workers-sdk/pull/16771) [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6) Thanks [@leostera](https://github.com/leostera)! - Fix several local Artifacts emulator issues found while testing it as a customer + + - The local Git remote keeps its port across dev server restarts, so existing clones keep working, and Wrangler prints each namespace's Git remote prefix at startup. If another process holds the port, a new one is chosen and printed. + - Workers Vitest no longer logs a caught `ArtifactsError` as an uncaught exception. Local bindings now throw errors in the caller's isolate, so they never cross a workerd RPC boundary. + - A push containing a file larger than 32 MiB is rejected, as in production, and a file at that limit can still be read. Reading a larger file throws `ArtifactsError` with code `MEMORY_LIMIT` instead of a raw RPC serialization error. + - `listTokens()` includes revoked and expired tokens with `state: "revoked"` or `state: "expired"`, listed after all active tokens. An expired token can no longer be revoked: `revokeToken()` returns `false` and its state stays `"expired"`. + - Results now follow the published binding types: `list()` items have no `remote`, `log()` caps `limit` at 1000 instead of rejecting it, and `readTree()` and `readCommit()` throw `INTERNAL_ERROR` for an object of another type instead of returning `null`. + +- [#16589](https://github.com/cloudflare/workers-sdk/pull/16589) [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2) Thanks [@mkuritsu](https://github.com/mkuritsu)! - Clear a local Browser Run session's `connectionId` when its client disconnects + + Sessions connected through `/v1/devtools/browser/:sessionId`, which current versions of `@cloudflare/puppeteer` and `@cloudflare/playwright` use, kept reporting a `connectionId` after the client closed its WebSocket. Reusing a session by picking one without a `connectionId` therefore never found a free session in local development. + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261110.1 | ^5.20261112.1 | + | workerd | 1.20261110.1 | 1.20261112.1 | + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261112.1 | ^5.20261113.1 | + | workerd | 1.20261112.1 | 1.20261113.1 | + ## 5.20261110.2-beta ### Patch Changes diff --git a/packages/miniflare/package.json b/packages/miniflare/package.json index 9e26957ba1..a0bf0df5d7 100644 --- a/packages/miniflare/package.json +++ b/packages/miniflare/package.json @@ -1,6 +1,6 @@ { "name": "miniflare", - "version": "5.20261110.2-beta", + "version": "5.20261116.0-beta", "description": "Fun, full-featured, fully-local simulator for Cloudflare Workers", "keywords": [ "cloudflare", diff --git a/packages/miniflare/src/config/local-bindings.ts b/packages/miniflare/src/config/local-bindings.ts index ef07be5c94..ac9a995949 100644 --- a/packages/miniflare/src/config/local-bindings.ts +++ b/packages/miniflare/src/config/local-bindings.ts @@ -1,5 +1,5 @@ import type { WorkerOptions } from "./schema"; -import type { ParsedInputWorkerConfig } from "@cloudflare/config"; +import type { ParsedWorkerConfig } from "@cloudflare/config"; type MiniflareEnv = NonNullable; @@ -24,7 +24,7 @@ export interface ResolveLocalBindingsOptions { /** * Resolves local binding values from the loaded local env. This replaces * declared secret placeholders with text bindings, applies Hyperdrive - * connection-string overrides, and resolves the Artifacts `dev.remote` default. Missing secrets are omitted, with a warning, so + * connection-string overrides. Missing secrets are omitted, with a warning, so * Miniflare doesn't receive an unresolved deployment-only placeholder. * * @param configuredBindings The Worker's configured bindings. @@ -32,7 +32,7 @@ export interface ResolveLocalBindingsOptions { * @returns The complete bindings. */ export function resolveLocalBindings( - configuredBindings: ParsedInputWorkerConfig["env"], + configuredBindings: ParsedWorkerConfig["env"], options: ResolveLocalBindingsOptions ): NonNullable { const { localEnv, devVars, mode, remoteBindings = true } = options; @@ -61,18 +61,6 @@ export function resolveLocalBindings( continue; } - // Artifacts uses the deployed resource unless `dev.remote` is `false`. - // Miniflare routes a binding remotely only for an explicit - // `dev.remote: true`, so resolve the default here, where it is known - // whether remote bindings are enabled. - if (binding.type === "artifacts") { - bindings[name] = - binding.dev?.remote === undefined - ? { ...binding, dev: { ...binding.dev, remote: remoteBindings } } - : binding; - continue; - } - if (binding.type === "secret") { const localValue = localValues[name]; if (localValue !== undefined) { diff --git a/packages/miniflare/src/config/schema.ts b/packages/miniflare/src/config/schema.ts index 370237fdba..c1c8d5e7d1 100644 --- a/packages/miniflare/src/config/schema.ts +++ b/packages/miniflare/src/config/schema.ts @@ -13,9 +13,9 @@ import { FlagshipBindingSchema, HyperdriveBindingSchema, KnownBindingSchema, - KVBindingSchema, + KvBindingSchema, ModuleTypeSchema, - OutputWorkerSchema, + BuildOutputWorkerConfigSchema, QueueBindingSchema, R2BindingSchema, UnsafeBindingSchema, @@ -23,6 +23,7 @@ import { WorkerEntrypointExportSchema, WorkflowBindingSchema, WorkflowExportSchema, + ArtifactsEventSubscriptionSchema, TailConsumerSchema, validateSingletonBindings, } from "@cloudflare/config"; @@ -228,6 +229,7 @@ const MiniflareWorkflowBindingSchema = WorkflowBindingSchema.extend({ unsafeConfig: z .strictObject({ limits: z.strictObject({ steps: z.number().optional() }).optional(), + events: z.array(ArtifactsEventSubscriptionSchema).optional(), }) .optional(), }); @@ -267,7 +269,7 @@ const MiniflareKnownBindingSchema = z.discriminatedUnion("type", [ ...PassthroughBindingSchemas, ]); -const ParsedMiniflareKVBindingSchema = KVBindingSchema.omit({ +const ParsedMiniflareKvBindingSchema = KvBindingSchema.omit({ id: true, }).extend({ id: z.string(), @@ -305,7 +307,7 @@ const ParsedMiniflareQueueBindingSchema = QueueBindingSchema.omit({ }); const OVERRIDDEN_PARSED_BINDING_SCHEMAS = [ - KVBindingSchema, + KvBindingSchema, D1BindingSchema, FlagshipBindingSchema, R2BindingSchema, @@ -325,7 +327,7 @@ const ParsedPassthroughBindingSchemas = >[]; export const ParsedMiniflareKnownBindingSchema = z.discriminatedUnion("type", [ - ParsedMiniflareKVBindingSchema, + ParsedMiniflareKvBindingSchema, ParsedMiniflareD1BindingSchema, ParsedMiniflareFlagshipBindingSchema, ParsedMiniflareR2BindingSchema, @@ -454,7 +456,7 @@ const MiniflareExperimentalSchema = ExperimentalSchema.extend({ }); // --------------------------------------------------------------------------- -// Worker config schema (extends OutputWorkerSchema) +// Worker config schema (extends BuildOutputWorkerConfigSchema) // --------------------------------------------------------------------------- /** A single parsed `config.env` binding (known, miniflare-extended, or unsafe). */ @@ -469,24 +471,25 @@ export function isMiniflareUnsafeBinding( return binding.type.startsWith("unsafe:"); } -export const MiniflareWorkerConfigBaseSchema = OutputWorkerSchema.omit({ - manifest: true, - env: true, - exports: true, - assets: true, - tailConsumers: true, - experimental: true, -}).extend({ - manifest: MiniflareManifestSchema.optional(), - env: z - .record(z.string(), MiniflareBindingSchema) - .superRefine(validateSingletonBindings) - .optional(), - exports: MiniflareExportsSchema.optional(), - assets: MiniflareAssetsSchema.optional(), - tailConsumers: z.array(MiniflareTailConsumerSchema).optional(), - experimental: MiniflareExperimentalSchema.optional(), -}); +export const MiniflareWorkerConfigBaseSchema = + BuildOutputWorkerConfigSchema.omit({ + manifest: true, + env: true, + exports: true, + assets: true, + tailConsumers: true, + experimental: true, + }).extend({ + manifest: MiniflareManifestSchema.optional(), + env: z + .record(z.string(), MiniflareBindingSchema) + .superRefine(validateSingletonBindings) + .optional(), + exports: MiniflareExportsSchema.optional(), + assets: MiniflareAssetsSchema.optional(), + tailConsumers: z.array(MiniflareTailConsumerSchema).optional(), + experimental: MiniflareExperimentalSchema.optional(), + }); export type ParsedMiniflareWorkerConfig = Omit< z.output, diff --git a/packages/miniflare/src/config/v4-convert.ts b/packages/miniflare/src/config/v4-convert.ts index 8a59a11a2b..56f7b3a01f 100644 --- a/packages/miniflare/src/config/v4-convert.ts +++ b/packages/miniflare/src/config/v4-convert.ts @@ -480,6 +480,7 @@ function addWorkflowExports(exports: Exports, worker: ParsedV4WorkerOptions) { exports[className] = { type: "workflow", name: workflow.name, + events: workflow.events, limits: workflow.stepLimit === undefined ? undefined @@ -679,7 +680,7 @@ function addProductBindings( } if (worker.analyticsSql !== undefined) { env[worker.analyticsSql.binding] = { - type: "analytics", + type: "analytics-sql", dev: { remote: isRemote(worker.analyticsSql.remoteProxyConnectionString), }, @@ -740,7 +741,7 @@ function addProductBindings( for (const [name, binding] of Object.entries(worker.k2 ?? {})) { env[name] = { type: "k2", - stream: binding.stream, + id: binding.stream, dev: { remote: isRemote(binding.remoteProxyConnectionString) }, }; } @@ -815,13 +816,7 @@ function addProductBindings( env[name] = { type: "artifacts", namespace: binding.namespace, - // Without a remote proxy connection (for example `wrangler dev - // --local`) the deployed resource is unreachable, so use the simulator. - dev: { - remote: - binding.remote !== false && - isRemote(binding.remoteProxyConnectionString), - }, + dev: { remote: isRemote(binding.remoteProxyConnectionString) }, }; } for (const name of Object.keys(worker.workerLoaders ?? {})) { @@ -847,9 +842,14 @@ function addProductBindings( worker: targetWorkerName, exportName: workflow.className, unsafeConfig: - workflow.stepLimit === undefined + workflow.events === undefined && workflow.stepLimit === undefined ? undefined - : { limits: { steps: workflow.stepLimit } }, + : { + events: workflow.events, + ...(workflow.stepLimit === undefined + ? {} + : { limits: { steps: workflow.stepLimit } }), + }, }; } } @@ -864,14 +864,14 @@ function addPipelineBindings( } if (Array.isArray(pipelines)) { for (const name of pipelines) { - env[name] = { type: "pipeline", name }; + env[name] = { type: "pipeline", streamId: name }; } return; } for (const [name, binding] of Object.entries(pipelines)) { env[name] = { type: "pipeline", - name: + streamId: typeof binding === "string" ? binding : "stream" in binding diff --git a/packages/miniflare/src/config/v4-schema.ts b/packages/miniflare/src/config/v4-schema.ts index 1efb8ec2f6..527a62337b 100644 --- a/packages/miniflare/src/config/v4-schema.ts +++ b/packages/miniflare/src/config/v4-schema.ts @@ -1,3 +1,4 @@ +import { ArtifactsEventSubscriptionSchema } from "@cloudflare/config"; import { AssetConfigSchema, RouterConfigSchema, @@ -15,6 +16,7 @@ import type { RemoteProxyConnectionString } from "../plugins/shared"; import type { Json } from "../shared"; import type { WorkerRegistry } from "../shared/dev-registry-types"; import type { Awaitable } from "../workers"; +import type { ArtifactsEventSubscription } from "@cloudflare/config"; import type { AssetConfig, RouterConfig } from "@cloudflare/workers-shared"; import type * as http from "node:http"; @@ -476,6 +478,7 @@ const V4WorkerOptionsShapeSchema = z.object({ z.object({ name: z.string(), className: z.string(), + events: z.array(ArtifactsEventSubscriptionSchema).optional(), scriptName: z.string().optional(), external: z.boolean().optional(), stepLimit: z.number().int().min(1).optional(), @@ -487,6 +490,7 @@ const V4WorkerOptionsShapeSchema = z.object({ z.string(), z.object({ name: z.string(), + events: z.array(ArtifactsEventSubscriptionSchema).optional(), stepLimit: z.number().int().min(1).optional(), }) ) @@ -641,7 +645,6 @@ const V4WorkerOptionsShapeSchema = z.object({ z.string(), z.object({ namespace: z.string(), - remote: z.boolean().optional(), remoteProxyConnectionString: RemoteProxyConnectionStringSchema.optional(), }) @@ -914,6 +917,7 @@ export type V4WorkerOptionsShape = { className: string; scriptName?: string; external?: boolean; + events?: ArtifactsEventSubscription[]; stepLimit?: number; } >; @@ -921,6 +925,7 @@ export type V4WorkerOptionsShape = { string, { name: string; + events?: ArtifactsEventSubscription[]; stepLimit?: number; } >; @@ -986,10 +991,7 @@ export type V4WorkerOptionsShape = { >; helloWorld?: Record; flagship?: Record; - artifacts?: Record< - string, - { namespace: string; remote?: boolean } & V4RemoteBinding - >; + artifacts?: Record; workerLoaders?: Record>; media?: V4RemoteBindingWithName; versionMetadata?: string; diff --git a/packages/miniflare/src/index.ts b/packages/miniflare/src/index.ts index 1c89d05862..25ee1e48a4 100644 --- a/packages/miniflare/src/index.ts +++ b/packages/miniflare/src/index.ts @@ -76,7 +76,9 @@ import { WORKER_BINDING_SERVICE_LOOPBACK, WORKFLOWS_PLUGIN_NAME, } from "./plugins"; +import { getLocalArtifactsNamespaceNames } from "./plugins/artifacts"; import { ArtifactsController } from "./plugins/artifacts/controller"; +import { getArtifactsEventSubscriptions } from "./plugins/artifacts/events"; import { RPC_PROXY_SERVICE_NAME } from "./plugins/assets/constants"; import { BROWSER_VERSION } from "./plugins/browser-rendering/browser-version"; import { closeBrowserProcess } from "./plugins/browser-rendering/process"; @@ -938,6 +940,11 @@ export class Miniflare { // once per session. #warnedRemoteBindingsAccessBlock = false; + // Set the first time Workflow events are declared without a local + // Artifacts namespace, so the warning appears once per instance rather + // than on every `setOptions()`. + #warnedArtifactsEventsWithoutLocalNamespace = false; + constructor(opts: MiniflareOptions) { // Split and validate options const [sharedOpts, workerOpts] = validateOptions(opts); @@ -2092,6 +2099,24 @@ export class Miniflare { const workflowExporters = getWorkflowExporters(allWorkerOpts); const queueProducers = getQueueProducers(allWorkerOpts); const queueConsumers = getQueueConsumers(allWorkerOpts); + const artifactsEventSubscriptions = + getArtifactsEventSubscriptions(allWorkerOpts); + if ( + !this.#warnedArtifactsEventsWithoutLocalNamespace && + artifactsEventSubscriptions.length > 0 && + !allWorkerOpts.some( + ({ config, dev }) => + getLocalArtifactsNamespaceNames( + getEnvBindingsOfType(config, "artifacts"), + dev + ).size > 0 + ) + ) { + this.#warnedArtifactsEventsWithoutLocalNamespace = true; + this.#log.warn( + "Workflow events are only published by local Artifacts namespaces, and this instance has none." + ); + } // When the dev registry is enabled, queue brokers bind to the dev-registry // proxy so they can deliver to consumers in other `wrangler dev` processes // (see `ExternalQueueProxy`), so the proxy worker must exist whenever @@ -2251,6 +2276,7 @@ export class Miniflare { containerPrivilegesCache: this.#containerPrivilegesCache, hyperdriveProxyController: this.#hyperdriveProxyController, artifactsController: this.#artifactsController, + artifactsEventSubscriptions, }; for (const [key, plugin] of this.#mergedPluginEntries) { const pluginServicesExtensions = await plugin.getServices({ diff --git a/packages/miniflare/src/plugins/analytics-sql/index.ts b/packages/miniflare/src/plugins/analytics-sql/index.ts index a71d76e155..15a8cb97a1 100644 --- a/packages/miniflare/src/plugins/analytics-sql/index.ts +++ b/packages/miniflare/src/plugins/analytics-sql/index.ts @@ -14,7 +14,7 @@ const ANALYTICS_SQL_REMOTE_SERVICE_NAME = "analytics-sql:remote"; export const ANALYTICS_SQL_PLUGIN: Plugin = { bindingTypeDescription: "Analytics SQL", async getBindings(options) { - return getEnvBindingsOfType(options.config, "analytics").map( + return getEnvBindingsOfType(options.config, "analytics-sql").map( ([name, binding]) => ({ name, service: { @@ -29,14 +29,14 @@ export const ANALYTICS_SQL_PLUGIN: Plugin = { }, getNodeBindings(options) { return Object.fromEntries( - getEnvBindingsOfType(options.config, "analytics").map(([name]) => [ + getEnvBindingsOfType(options.config, "analytics-sql").map(([name]) => [ name, new ProxyNodeBinding(), ]) ); }, async getServices({ options }) { - if (getEnvBindingsOfType(options.config, "analytics").length === 0) { + if (getEnvBindingsOfType(options.config, "analytics-sql").length === 0) { return []; } diff --git a/packages/miniflare/src/plugins/artifacts/LOCAL_DEVELOPMENT.md b/packages/miniflare/src/plugins/artifacts/LOCAL_DEVELOPMENT.md index 5ccd67c3c0..b1fa414a80 100644 --- a/packages/miniflare/src/plugins/artifacts/LOCAL_DEVELOPMENT.md +++ b/packages/miniflare/src/plugins/artifacts/LOCAL_DEVELOPMENT.md @@ -6,7 +6,7 @@ This first version of the local Artifacts emulator requires Git 2.32 or newer in Git 2.32 provides `GIT_CONFIG_GLOBAL`, which the emulator uses to isolate host Git settings. Use an up-to-date, security-patched release. -In Wrangler and Vite, a binding with `"remote": true` or an omitted `remote` setting does not start the local emulator and does not need local Git, unless remote bindings are disabled (see below). Workers Vitest uses the local emulator unless `remote` is `true`. Production Artifacts also does not require Git on your machine. We plan to open-source a JavaScript Git engine in the future; it is not part of this initial local release, which uses native Git. +A binding with `"remote": true` does not start the local emulator and does not need local Git, unless remote bindings are disabled (see below). Production Artifacts also does not require Git on your machine. We plan to open-source a JavaScript Git engine in the future; it is not part of this initial local release, which uses native Git. ## Configure a binding @@ -17,9 +17,7 @@ For a Wrangler project, add an Artifacts binding to `wrangler.jsonc`: "name": "example-worker", "main": "src/index.ts", "compatibility_date": "2026-09-03", - "artifacts": [ - { "binding": "REPOS", "namespace": "examples", "remote": false }, - ], + "artifacts": [{ "binding": "REPOS", "namespace": "examples" }], } ``` @@ -34,10 +32,7 @@ export default defineConfig({ entrypoint: "./src/index.ts", compatibilityDate: "2026-09-03", env: { - REPOS: bindings.artifacts({ - namespace: "examples", - dev: { remote: false }, - }), + REPOS: bindings.artifacts({ namespace: "examples" }), }, }, }); @@ -45,9 +40,7 @@ export default defineConfig({ In Workers Vitest, point `cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } })` at the Wrangler config above, or `cloudflareTest({ config: true })` at `cloudflare.config.ts`. These paths share the Miniflare implementation. -In Wrangler and Vite, the local emulator is opt-in: set `remote: false` on the binding. If `remote` is omitted or set to `true`, development uses the deployed Artifacts resource and the credentials required by that tool; with `remote` omitted, the dev tool warns that changes affect real repositories. When remote bindings are disabled (`wrangler dev --local`, or Vite's `remoteBindings: false`), every Artifacts binding uses the local emulator. - -Workers Vitest defaults the other way, so a test suite does not create, push to or delete real repositories by accident: an omitted `remote` uses the local emulator, and `remote: true` opts into the deployed resource. Do not rely on production repositories being available locally. +Artifacts bindings use the local emulator by default in Wrangler, Vite and Workers Vitest, like KV, R2 and D1. Set `remote: true` (`dev: { remote: true }` in `cloudflare.config.ts`) to use deployed repos instead, with the credentials required by your tool. Artifacts used to default to deployed repos, so while `remote` is omitted, `wrangler dev`, `getPlatformProxy()` and Vite warn once for each binding, not on every config reload, that the binding uses the local simulator; set `remote: false` to silence the warning. When remote bindings are disabled (`wrangler dev --local`, or Vite's `remoteBindings: false`), every Artifacts binding uses the local emulator. Do not rely on production repositories being available locally. A Worker can create and inspect a local repository: @@ -71,7 +64,104 @@ GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \ unset REPO_TOKEN ``` -After pushing `hello.txt` to `main`, read it in the Worker with `await repo.readFile({ ref: "main", path: "hello.txt" })` (a `Blob`, or `null` when absent). The initial create token permits writes. Its plaintext is returned only once; if you lose it, use `repo.createToken("read")` for cloning or `repo.createToken("write")` for pushing and save the returned `plaintext` securely. Revoke tokens that are no longer needed. Avoid printing tokens or committing them to config. A plain request without a token cannot clone a private local repository. Git's URL uses an ephemeral loopback port; obtain the current URL after restarting the dev server instead of hardcoding it. +After pushing `hello.txt` to `main`, read it in the Worker with `await repo.readFile({ ref: "main", path: "hello.txt" })` (a `Blob`, or `null` when absent). The initial create token permits writes. Its plaintext is returned only once; if you lose it, use `repo.createToken("read")` for cloning or `repo.createToken("write")` for pushing and save the returned `plaintext` securely. Revoke tokens that are no longer needed. Avoid printing tokens or committing them to config. A plain request without a token cannot clone a private local repository. The dev tool prints the Git remote prefix for each namespace at startup. Its loopback port is recorded with the persisted state, so clones keep working across restarts; if another process has taken that port, a new one is chosen and printed, and `info()` returns the new URL. + +## Receive repository events + +Local namespaces publish the documented [Artifacts events](https://developers.cloudflare.com/artifacts/guides/event-subscriptions/) when you create, import, fork, or delete a repository, and when you create or revoke a repository token. Creation, import, and fork also publish a token-created event for the initial repository token. Push, clone, and fetch events are not yet published locally. Local support does not establish which events are available for each deployed subscription destination. Each delivery has the deployed message shape (`type`, `source`, `payload`, and `metadata`). Locally, `metadata.accountId` is `"local"`, and `metadata.eventSubscriptionId` stays the same while the subscription's configuration does. Identical subscriptions deliver separate copies with distinct IDs. + +### Start a Workflow + +Use the same `triggers.events` configuration you deploy. Each target must be a Workflow defined by the same Worker. A matching event starts a Workflow instance, and the event message is its `event.payload`: + +```jsonc +{ + "name": "example-worker", + "main": "src/index.ts", + "compatibility_date": "2026-09-03", + "artifacts": [ + { "binding": "REPOS", "namespace": "examples", "remote": false }, + ], + "workflows": [ + { + "binding": "ON_REPO_CREATED", + "name": "on-repo-created", + "class_name": "OnRepoCreated", + }, + ], + "triggers": { + "events": [ + { + "type": "cf.artifacts.repo.created", + "filter": { "namespace": "examples" }, + "targets": [{ "type": "workflow", "workflow_name": "on-repo-created" }], + }, + ], + }, +} +``` + +```ts +import { WorkflowEntrypoint } from "cloudflare:workers"; +// Declare the fields this Workflow consumes in your application. +// No dependency on the development-only Miniflare package is needed. +export interface RepoCreated { + type: "cf.artifacts.repo.created"; + source: { type: "artifacts"; namespace: string; repoName: string }; + payload: { repoId: string }; +} + +export class OnRepoCreated extends WorkflowEntrypoint { + async run(event, step) { + const { source, payload } = event.payload; + await step.do("bootstrap repository", async () => { + const repo = await this.env.REPOS.get(source.repoName); + return { repoId: payload.repoId, info: await repo.info() }; + }); + } +} +``` + +Wrangler and Workers Vitest continue to read `triggers.events` from `wrangler.jsonc`. For native `cloudflare.config.ts` projects (including `cf`, Vite, and Workers Vitest), declare events directly on the Workflow export: + +```ts +import { bindings, defineConfig, exports } from "@cloudflare/config"; + +export default defineConfig({ + worker: { + name: "example-worker", + entrypoint: "./src/index.ts", + compatibilityDate: "2026-09-03", + env: { + REPOS: bindings.artifacts({ + namespace: "examples", + dev: { remote: false }, + }), + }, + exports: { + OnRepoCreated: exports.workflow({ + name: "on-repo-created", + events: [ + { + type: "cf.artifacts.repo.created", + filter: { namespace: "examples" }, + }, + ], + }), + }, + }, +}); +``` + +There is no separate target: the Workflow declaring an event receives it. The export key names the Worker's `WorkflowEntrypoint` class. A binding to a Workflow in another Worker cannot declare events for that Workflow. + +Both configuration formats use the same Worker implementation above. Native-to-Wrangler conversion generates `triggers.events` with targets derived from the owning Workflow, preserving any cron triggers. `cf migrate` performs the reverse: it attaches each legacy event subscription to its matching Workflow export, creating exports from local `workflows` bindings when necessary. Subscriptions without a string `type` or any targets, or with a non-object `filter`, and missing, external, or ambiguous targets, produce a blocking migration follow-up rather than silently losing subscriptions. `cf migrate` does not check event types or filter values; Wrangler already rejects unsupported ones. `wrangler dev` rejects a target this Worker does not define, as `wrangler deploy` does. + +Miniflare consumes native Workflow exports directly. Wrangler's legacy `workflows` bindings carry their events in Miniflare's binding-only `unsafeConfig.events`, alongside `unsafeConfig.limits`; this is an adapter detail, not a second public native configuration format. Every declaration Miniflare receives is a separate subscription, so Wrangler gives each event to one declaration: the Workflow export when there is one, otherwise the Worker's first binding to that Workflow. + +Local delivery is unordered: events from consecutive operations (including repository creation and its initial token) may arrive in either order. Do not infer production ordering guarantees from the emulator. + +Delivery happens after the repository change commits and does not fail the repository operation. A failed delivery is logged and not retried by the publisher. Local Artifacts-to-queue delivery is not supported by this feature; queue subscription configuration is outside this change's scope. ## Storage and network boundaries @@ -86,5 +176,7 @@ A local binding does not contact Cloudflare for repository operations. **Explici - If startup says local Artifacts requires Git, install Git globally, check `git --version` in the dev tool's environment, and restart the tool with `git` on PATH. - If Git asks for a username and password, use any username and the repository token as the password. If Git reports unauthorized, check the repository, scope, expiry, and revocation; do not use a Cloudflare or GitHub account password. - If startup reports `Address already in use`, the dev or inspector port may be occupied. Pass `--port=0 --inspector-port=0` and use the printed `Ready on` URL. -- If a Git URL stops responding after restart, get the new `remote` from the binding; the loopback listener is tied to the dev process. +- If a Git URL stops responding after restart, another process probably holds its port. Get the new `remote` from the binding or the startup log, and update your clone with `git remote set-url origin `. +- As in production, a push that contains a file larger than 32 MiB is rejected, and reading such a file throws an `ArtifactsError` with code `MEMORY_LIMIT`. +- `listTokens()` lists active tokens first, then revoked and expired tokens with their `state`. Each repository keeps its 100 most recent inactive tokens. `revokeToken()` returns `false` for an expired token. - Local development is not a replica of production placement or infrastructure. The local Git endpoint is HTTP on loopback only, and local state and tokens do not transfer to a remote namespace. diff --git a/packages/miniflare/src/plugins/artifacts/README.md b/packages/miniflare/src/plugins/artifacts/README.md index 0475cc6788..de6c16148e 100644 --- a/packages/miniflare/src/plugins/artifacts/README.md +++ b/packages/miniflare/src/plugins/artifacts/README.md @@ -9,10 +9,7 @@ available on PATH. Miniflare checks the Git version at local startup and gives installation or upgrade instructions if needed. A Node worker thread runs the native Git backend. Like every other binding, an Artifacts binding uses the remote proxy only when `dev.remote` is `true` and the Worker has a remote proxy -connection string; otherwise it uses local storage. The tools resolve the -Artifacts default (deployed unless `remote: false`) before they reach -Miniflare: Wrangler sets `dev.remote` when converting its config, and -`resolveLocalBindings()` does it for `cloudflare.config.ts`. We plan to +connection string; otherwise it uses local storage. We plan to open-source a JavaScript Git engine in the future; it is not included in this version. @@ -30,7 +27,7 @@ sequenceDiagram Dev->>MF: Configure Artifacts binding MF->>Plugin: getBindings() Plugin->>Plugin: Select local and validate namespace - Plugin-->>MF: Bind to local namespace entrypoint + Plugin-->>MF: Wrapped binding around the local namespace entrypoint MF->>Plugin: getServices() Plugin->>Plugin: Verify host Git is available on PATH Plugin->>Controller: get(Git storage path) @@ -41,10 +38,18 @@ sequenceDiagram MF->>Workerd: Start configured services and socket ``` -`getBindings()` routes each local binding to a namespace-scoped service. +`getBindings()` routes each local binding to a namespace-scoped service through +a wrapped binding (`wrapped-binding.worker.ts`) that runs in the caller's +isolate. The binding Worker and Durable Object return `{ ok, value | error }` +outcomes, and the wrapper throws `ArtifactsError` there: an exception thrown +across a workerd RPC boundary is logged as uncaught under `--verbose`, which +Workers Vitest enables, even when the caller catches it. `getServices()` creates the binding Worker, namespace Durable Object, persistent metadata disk, internal Git backend service, and Git socket. The controller reuses a sidecar per Git storage path and closes it when Miniflare is disposed. +It records the Git socket's port in `git-port` next to the namespace's storage +and reuses it on the next start while it is free, so clones keep their +`origin`. The socket used by Git clients and the sidecar's private HTTP listener are **different endpoints**. If the sidecar exits after startup, the controller forgets its endpoint and warns; an explicit Miniflare configuration reload @@ -141,7 +146,10 @@ secret; the client's `Authorization` header is removed before that hop. For a successful push, the Durable Object refreshes repository metadata before returning the response. The sidecar uses native `git http-backend` for Git smart HTTP rather than reproducing Git's pack protocol. All native Git commands -(including the HTTP backend) override repository-local hook configuration. +override repository-local hook configuration. The HTTP backend instead points +`core.hooksPath` at a private directory with one `pre-receive` hook, which +rejects pushes containing a blob over the 32 MiB per-file limit; reads of a +larger blob written outside the binding fail with `MEMORY_LIMIT`. A failed deletion leaves an inaccessible, persisted tombstone, so retrying `delete()` or creating the same name can finish native Git cleanup even after a process restart. diff --git a/packages/miniflare/src/plugins/artifacts/controller.ts b/packages/miniflare/src/plugins/artifacts/controller.ts index 0b1b75050b..cf28ebe01e 100644 --- a/packages/miniflare/src/plugins/artifacts/controller.ts +++ b/packages/miniflare/src/plugins/artifacts/controller.ts @@ -1,3 +1,5 @@ +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { createServer } from "node:net"; import path from "node:path"; import { Worker } from "node:worker_threads"; import getPort from "get-port"; @@ -9,6 +11,11 @@ export interface LocalArtifactsBackend { port: number; } +export interface LocalArtifactsBackendOptions { + namespace?: string; + portFile?: string; +} + // Node binding proxies make synchronous calls. The Git backend must run on // another thread, otherwise those calls prevent it from answering workerd. export class ArtifactsController { @@ -17,7 +24,7 @@ export class ArtifactsController { #activeRoots = new Set(); #pendingRoots?: Set; - constructor(private readonly getLog?: () => Pick) {} + constructor(private readonly getLog?: () => Pick) {} beginUpdate(): void { if (this.#pendingRoots) { @@ -44,7 +51,15 @@ export class ArtifactsController { await this.#closeExcept(this.#activeRoots); } - get(root: string): Promise { + /** + * @param root Git storage directory for one namespace. + * @param options.namespace Prints the namespace's Git remote prefix. + * @param options.portFile Reuses the Git port recorded here, if it's free. + */ + get( + root: string, + options: LocalArtifactsBackendOptions = {} + ): Promise { root = path.resolve(root); if (!this.#pendingRoots) { throw new Error("Artifacts backend requested outside runtime update"); @@ -52,7 +67,7 @@ export class ArtifactsController { this.#pendingRoots.add(root); let backend = this.#backends.get(root); if (!backend) { - backend = this.#start(root, () => { + backend = this.#start(root, options, () => { if (this.#backends.get(root) === backend) { this.#backends.delete(root); } @@ -69,9 +84,15 @@ export class ArtifactsController { async #start( root: string, + { namespace, portFile }: LocalArtifactsBackendOptions, onExit: () => void ): Promise { - const port = await getPort({ host: "127.0.0.1" }); + const port = await reserveGitPort(portFile); + if (namespace !== undefined) { + this.getLog?.().info( + `Local Artifacts Git remotes for namespace "${namespace}": http://127.0.0.1:${port}/git/${namespace}/.git` + ); + } // __dirname is dist/src in the bundled Miniflare entry point. const worker = new Worker( path.join(__dirname, "plugins/artifacts/git-sidecar.js"), @@ -148,6 +169,44 @@ export class ArtifactsController { } } +/** + * Clones keep their `origin` URL, so reuse the port this storage directory had + * last time. Fall back to any free port if another process now holds it. + */ +async function reserveGitPort(portFile: string | undefined): Promise { + if (portFile === undefined) { + return getPort({ host: "127.0.0.1" }); + } + const previous = Number.parseInt( + await readFile(portFile, "utf8").catch(() => ""), + 10 + ); + // get-port refuses ports it returned in this process during the last + // 15 seconds, which would move the port when Vite restarts its server. + const port = + Number.isInteger(previous) && + previous > 0 && + previous < 65536 && + (await isLoopbackPortFree(previous)) + ? previous + : await getPort({ host: "127.0.0.1" }); + if (port !== previous) { + await mkdir(path.dirname(portFile), { recursive: true }); + await writeFile(portFile, `${port}\n`); + } + return port; +} + +function isLoopbackPortFree(port: number): Promise { + return new Promise((resolve) => { + const server = createServer(); + server.once("error", () => resolve(false)); + server.listen({ host: "127.0.0.1", port, exclusive: true }, () => { + server.close(() => resolve(true)); + }); + }); +} + type SidecarStartupMessage = | Pick | { error: string }; diff --git a/packages/miniflare/src/plugins/artifacts/events.ts b/packages/miniflare/src/plugins/artifacts/events.ts new file mode 100644 index 0000000000..0d292eb0b4 --- /dev/null +++ b/packages/miniflare/src/plugins/artifacts/events.ts @@ -0,0 +1,118 @@ +import { createHash } from "node:crypto"; +import { MiniflareCoreError } from "../../shared"; +import { getEnvBindingsOfType, getExportsOfType } from "../shared"; +import { getWorkflowBindingServiceName } from "../workflows"; +import type { ParsedWorkerOptions } from "../../config/schema"; +import type { Worker_Binding } from "../../runtime"; +import type { + ArtifactsEventRoute, + ArtifactsEventType, +} from "../../workers/artifacts/events"; +import type { ArtifactsEventSubscription } from "@cloudflare/config"; + +/** An event subscription declared by a Workflow in this instance. */ +export interface ArtifactsEventSubscriptionRoute { + id: string; + types: ArtifactsEventType[]; + namespace?: string; + repoName?: string; + workflowName: string; +} + +/** + * Resolves Workflow-owned event declarations into stable local routes. Every + * declaration is its own subscription, whether it sits on an export or on a + * binding, so callers declaring a Workflow both ways put each event on one. + */ +export function getArtifactsEventSubscriptions( + allWorkerOpts: ParsedWorkerOptions[] +): ArtifactsEventSubscriptionRoute[] { + const routes: ArtifactsEventSubscriptionRoute[] = []; + for (const { config } of allWorkerOpts) { + for (const [, workflow] of getExportsOfType(config, "workflow")) { + routes.push( + ...workflowRoutes(config.name, workflow.name, workflow.events) + ); + } + for (const [, binding] of getEnvBindingsOfType(config, "workflow")) { + const events = binding.unsafeConfig?.events; + if (!events?.length) { + continue; + } + if (binding.worker !== config.name) { + throw new MiniflareCoreError( + "ERR_VALIDATION", + `Workflow "${binding.name}" in Worker "${config.name}" cannot declare events for another Worker's Workflow.` + ); + } + routes.push(...workflowRoutes(config.name, binding.name, events)); + } + } + const occurrences = new Map(); + return routes.map((route) => { + const occurrence = occurrences.get(route.id) ?? 0; + occurrences.set(route.id, occurrence + 1); + if (occurrence === 0) { + return route; + } + // Repeated event declarations intentionally create separate deliveries. + return { + ...route, + id: createHash("sha256") + .update(`${route.id}:${occurrence}`) + .digest("hex") + .slice(0, 32), + }; + }); +} + +/** Builds Workflow service bindings and matching routes for a local namespace. */ +export function getArtifactsNamespaceEventBindings( + subscriptions: ArtifactsEventSubscriptionRoute[], + namespace: string +): Worker_Binding[] { + const routes: ArtifactsEventRoute[] = []; + const bindings: Worker_Binding[] = []; + for (const subscription of subscriptions) { + if ( + subscription.namespace !== undefined && + subscription.namespace !== namespace + ) { + continue; + } + const binding = `ARTIFACTS_EVENT_TARGET_${routes.length}`; + bindings.push({ + name: binding, + service: { + name: getWorkflowBindingServiceName(subscription.workflowName), + entrypoint: "WorkflowBinding", + }, + }); + routes.push({ + id: subscription.id, + types: subscription.types, + ...(subscription.repoName === undefined + ? {} + : { repoName: subscription.repoName }), + target: { type: "workflow", binding }, + }); + } + return routes.length === 0 + ? [] + : [{ name: "eventRoutes", json: JSON.stringify(routes) }, ...bindings]; +} + +function workflowRoutes( + owner: string, + workflowName: string, + events: ArtifactsEventSubscription[] = [] +): ArtifactsEventSubscriptionRoute[] { + return events.map((event) => { + const route = { types: [event.type], ...event.filter, workflowName }; + const id = createHash("sha256") + .update(JSON.stringify({ owner, ...route })) + .digest("hex") + .slice(0, 32); + return { id, ...route }; + }); +} diff --git a/packages/miniflare/src/plugins/artifacts/git-client.ts b/packages/miniflare/src/plugins/artifacts/git-client.ts index a87871b001..c86ee6f4bf 100644 --- a/packages/miniflare/src/plugins/artifacts/git-client.ts +++ b/packages/miniflare/src/plugins/artifacts/git-client.ts @@ -237,6 +237,19 @@ export interface GitTreeEntry { type GitObjectType = "blob" | "tree" | "commit" | "tag"; +/** + * Artifacts' documented per-file limit (32 MiB). Larger blobs cannot be + * pushed, and reading one reports `MEMORY_LIMIT`. + */ +export const MAX_BLOB_BYTES = 32 * 1024 * 1024; + +/** A Git object too large to return through the binding (`MEMORY_LIMIT`). */ +export class GitObjectTooLargeError extends Error { + constructor(hash: string) { + super(`Git object ${hash} exceeds the ${MAX_BLOB_BYTES} byte limit`); + } +} + export class LocalRepositoryStorageError extends Error { constructor( readonly kind: "creation-lock" | "on-disk-conflict", @@ -474,12 +487,11 @@ export class GitClient { if ((await this.objectType(hash)) !== "blob") { return null; } - const object = await this.git(["cat-file", "blob", hash]); - return { data: Buffer.from(object.stdout).toString("base64") }; + return this.readBlobData(hash); } async readTree(hash: string): Promise { - if ((await this.objectType(hash)) !== "tree") { + if (!(await this.expectObjectType(hash, "tree"))) { return null; } const tree = await this.git(["ls-tree", "-z", hash]); @@ -503,7 +515,7 @@ export class GitClient { } async readCommit(hash: string): Promise { - if ((await this.objectType(hash)) !== "commit") { + if (!(await this.expectObjectType(hash, "commit"))) { return null; } const object = await this.git(["cat-file", "commit", hash]); @@ -533,12 +545,37 @@ export class GitClient { return null; } // Read the matched object, not a revision expression built from a path. - const object = await this.git(["cat-file", "blob", match[2]], { - allowFailure: true, - }); - return object.status === 0 - ? { data: Buffer.from(object.stdout).toString("base64") } - : null; + if ((await this.objectType(match[2])) !== "blob") { + return null; + } + return this.readBlobData(match[2]); + } + + private async readBlobData(hash: string): Promise<{ data: string }> { + const size = await this.git(["cat-file", "-s", hash]); + if (Number(decoder.decode(size.stdout).trim()) > MAX_BLOB_BYTES) { + throw new GitObjectTooLargeError(hash); + } + const object = await this.git(["cat-file", "blob", hash]); + return { data: Buffer.from(object.stdout).toString("base64") }; + } + + /** + * `null` for a missing object. An object of another type is an error, as + * the public `readTree()` and `readCommit()` contracts require. + */ + private async expectObjectType( + hash: string, + expected: GitObjectType + ): Promise { + const type = await this.objectType(hash); + if (type === null) { + return false; + } + if (type !== expected) { + throw new Error(`Git object ${hash} is a ${type}, not a ${expected}`); + } + return true; } async log(ref?: string, limit = 50, offset = 0): Promise { diff --git a/packages/miniflare/src/plugins/artifacts/git-sidecar.ts b/packages/miniflare/src/plugins/artifacts/git-sidecar.ts index c019608754..c0cd70dcbd 100644 --- a/packages/miniflare/src/plugins/artifacts/git-sidecar.ts +++ b/packages/miniflare/src/plugins/artifacts/git-sidecar.ts @@ -1,12 +1,21 @@ import { Buffer } from "node:buffer"; import { spawn } from "node:child_process"; import { randomBytes } from "node:crypto"; -import { mkdir, mkdtemp, readdir, rename, stat } from "node:fs/promises"; +import { + chmod, + mkdir, + mkdtemp, + readdir, + rename, + stat, + writeFile, +} from "node:fs/promises"; import { createServer, type IncomingMessage, type ServerResponse, } from "node:http"; +import { tmpdir } from "node:os"; import path from "node:path"; import { Transform } from "node:stream"; import { parentPort, workerData } from "node:worker_threads"; @@ -15,7 +24,8 @@ import { z } from "zod"; import { assertGitAvailable, GitClient, - gitArgumentsWithoutHooks, + GitObjectTooLargeError, + MAX_BLOB_BYTES, gitEnvironment, LocalRepositoryStorageError, stopGitProcess, @@ -128,6 +138,32 @@ type ForkRequest = Extract; type ImportRequest = Extract; type NewRepositoryRequest = CreateRequest | ForkRequest | ImportRequest; +// Native Git has no per-file push limit, so a trusted hook enforces the +// Artifacts one. `--not --all` checks only objects new to this repository. +const PRE_RECEIVE_HOOK = `#!/bin/sh +# Installed by Miniflare's local Artifacts simulator. +zero=0000000000000000000000000000000000000000 +while read -r old new ref; do + [ "$new" = "$zero" ] && continue + large=$(git rev-list --objects --filter=blob:limit=${MAX_BLOB_BYTES + 1} --filter-print-omitted "$new" --not --all | sed -n 's/^~//p' | head -n 1) + if [ -n "$large" ]; then + echo "Artifacts does not accept files larger than 32 MiB ($ref contains blob $large)." >&2 + exit 1 + fi +done +`; + +/** Hooks for http-backend only. Repository-local hooks never run. */ +async function createPushHooks(): Promise { + const hooks = await mkdtemp( + path.join(tmpdir(), "miniflare-artifacts-hooks-") + ); + const hook = path.join(hooks, "pre-receive"); + await writeFile(hook, PRE_RECEIVE_HOOK); + await chmod(hook, 0o755); + return hooks; +} + function createGitSecret(): string { return randomBytes(32).toString("hex"); } @@ -138,6 +174,21 @@ export async function startGitSidecar(root: string): Promise { await assertGitAvailable(); await cleanupInterruptedRepositories(root); const secret = createGitSecret(); + const hooks = await createPushHooks(); + try { + return await startGitServer(root, hooks, secret); + } catch (error) { + // close() removes the hooks; a failed start never returns a sidecar. + await removeDir(hooks); + throw error; + } +} + +async function startGitServer( + root: string, + hooks: string, + secret: string +): Promise { const shutdown = new AbortController(); const repositoryLocks: RepositoryLocks = new Map(); const inFlight = new Map(); @@ -148,6 +199,7 @@ export async function startGitSidecar(root: string): Promise { } void handleRequest( root, + hooks, repositoryLocks, inFlight, request, @@ -158,11 +210,15 @@ export async function startGitSidecar(root: string): Promise { response.destroy(error instanceof Error ? error : undefined); } else { const storageError = error instanceof LocalRepositoryStorageError; - response.writeHead(storageError ? 409 : 500, { + const tooLarge = error instanceof GitObjectTooLargeError; + response.writeHead(storageError ? 409 : tooLarge ? 413 : 500, { "Content-Type": "text/plain", ...(storageError ? { "X-Local-Artifacts-Storage-Error": error.kind } : {}), + ...(tooLarge + ? { "X-Local-Artifacts-Object-Error": "memory-limit" } + : {}), }); response.end( error instanceof Error ? error.message : "Native Git backend failed" @@ -188,12 +244,13 @@ export async function startGitSidecar(root: string): Promise { return { address, secret, - close() { + async close() { shutdown.abort(); server.closeAllConnections(); - return new Promise((resolve, reject) => { + await new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())); }); + await removeDir(hooks); }, }; } @@ -218,6 +275,7 @@ function parseGitPath(pathname: string): { // packfiles on node:http rather than buffering them through a Worker router. async function handleRequest( root: string, + hooks: string, locks: RepositoryLocks, inFlight: Map, request: IncomingMessage, @@ -257,6 +315,7 @@ async function handleRequest( try { await runGitHttpBackend( root, + hooks, request, response, `/${repositoryDirectory(namespace, repository)}${suffix}`, @@ -510,6 +569,7 @@ function parseGitBackendHeaders(headerBytes: Buffer): { async function runGitHttpBackend( root: string, + hooks: string, request: IncomingMessage, response: ServerResponse, pathInfo: string, @@ -518,27 +578,31 @@ async function runGitHttpBackend( signal?: AbortSignal ): Promise { return new Promise((resolve, reject) => { - const child = spawn("git", gitArgumentsWithoutHooks(["http-backend"]), { - env: { - ...gitEnvironment(), - GIT_PROJECT_ROOT: root, - GIT_HTTP_EXPORT_ALL: "1", - PATH_INFO: pathInfo, - QUERY_STRING: query, - REQUEST_METHOD: request.method ?? "GET", - CONTENT_TYPE: request.headers["content-type"] ?? "", - CONTENT_LENGTH: request.headers["content-length"] ?? "", - HTTP_CONTENT_ENCODING: String( - request.headers["content-encoding"] ?? "" - ), - HTTP_GIT_PROTOCOL: String(request.headers["git-protocol"] ?? ""), - REMOTE_USER: "local-artifacts", - REMOTE_ADDR: request.socket.remoteAddress ?? "127.0.0.1", - }, - stdio: ["pipe", "pipe", "pipe"], - detached: process.platform !== "win32", - signal, - }); + const child = spawn( + "git", + ["-c", `core.hooksPath=${hooks}`, "http-backend"], + { + env: { + ...gitEnvironment(), + GIT_PROJECT_ROOT: root, + GIT_HTTP_EXPORT_ALL: "1", + PATH_INFO: pathInfo, + QUERY_STRING: query, + REQUEST_METHOD: request.method ?? "GET", + CONTENT_TYPE: request.headers["content-type"] ?? "", + CONTENT_LENGTH: request.headers["content-length"] ?? "", + HTTP_CONTENT_ENCODING: String( + request.headers["content-encoding"] ?? "" + ), + HTTP_GIT_PROTOCOL: String(request.headers["git-protocol"] ?? ""), + REMOTE_USER: "local-artifacts", + REMOTE_ADDR: request.socket.remoteAddress ?? "127.0.0.1", + }, + stdio: ["pipe", "pipe", "pipe"], + detached: process.platform !== "win32", + signal, + } + ); const stop = () => stopGitProcess(child); if (signal?.aborted) { stop(); diff --git a/packages/miniflare/src/plugins/artifacts/index.ts b/packages/miniflare/src/plugins/artifacts/index.ts index 7519f5ba05..49001fdb6d 100644 --- a/packages/miniflare/src/plugins/artifacts/index.ts +++ b/packages/miniflare/src/plugins/artifacts/index.ts @@ -2,6 +2,7 @@ import { createHash } from "node:crypto"; import { mkdir } from "node:fs/promises"; import path from "node:path"; import SCRIPT from "worker:artifacts/binding"; +import SCRIPT_WRAPPED_BINDING from "worker:artifacts/wrapped-binding"; import { buildRemoteProxyProps, getEnvBindingsOfType, @@ -10,32 +11,39 @@ import { ProxyNodeBinding, remoteProxyClientWorker, } from "../shared"; +import { getArtifactsNamespaceEventBindings } from "./events"; import { assertGitAvailable } from "./git-client"; import { assertSupportedGitLayout } from "./storage"; import type { Service, Socket } from "../../runtime"; import type { MiniflareBinding, ParsedDevConfig, Plugin } from "../shared"; import type { ArtifactsController } from "./controller"; +import type { ArtifactsEventSubscriptionRoute } from "./events"; -export { ArtifactsController, type LocalArtifactsBackend } from "./controller"; +export { + ArtifactsController, + type LocalArtifactsBackend, + type LocalArtifactsBackendOptions, +} from "./controller"; export type { GitSidecar } from "./git-sidecar"; +// Referenced by the public `PluginServicesOptions`, so the type bundle needs it. +export type { ArtifactsEventSubscriptionRoute } from "./events"; export const ARTIFACTS_PLUGIN_NAME = "artifacts"; const ARTIFACTS_REMOTE_SERVICE_NAME = `${ARTIFACTS_PLUGIN_NAME}:remote`; const ENTRYPOINT = "LocalArtifactsNamespace"; const OBJECT_CLASS = "LocalArtifactsNamespaceObject"; +const WRAPPED_BINDING_MODULE = `${ARTIFACTS_PLUGIN_NAME}:local-binding`; const LOCAL_NAMESPACE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; -type ArtifactsBinding = Extract; -type ArtifactsEntry = [name: string, binding: ArtifactsBinding]; - // Artifacts routes like every other binding: remote only when `dev.remote` is -// `true` and the Worker has a remote proxy connection. Its deployed-by-default -// rule is resolved before Miniflare, by `resolveBindingRemote()` in -// `@cloudflare/workers-utils` for Wrangler configs and by -// `resolveLocalBindings()` for `cloudflare.config.ts`. +// `true` and the Worker has a remote proxy connection. -function getLocalNamespaceNames( - bindings: ArtifactsEntry[], +/** Returns the namespaces served by the local simulator for these bindings. */ +export function getLocalArtifactsNamespaceNames( + bindings: [ + name: string, + binding: Extract, + ][], dev: ParsedDevConfig | undefined ): Set { return new Set( @@ -73,9 +81,17 @@ export const ARTIFACTS_PLUGIN: Plugin = { validateLocalNamespace(binding.namespace); return { name, - service: { - name: localServiceName(binding.namespace), - entrypoint: ENTRYPOINT, + wrapped: { + moduleName: WRAPPED_BINDING_MODULE, + innerBindings: [ + { + name: "namespace", + service: { + name: localServiceName(binding.namespace), + entrypoint: ENTRYPOINT, + }, + }, + ], }, }; } @@ -97,7 +113,13 @@ export const ARTIFACTS_PLUGIN: Plugin = { ]) ); }, - async getServices({ options, sharedOptions, tmpPath, artifactsController }) { + async getServices({ + options, + sharedOptions, + tmpPath, + artifactsController, + artifactsEventSubscriptions, + }) { const bindings = getEnvBindingsOfType(options.config, "artifacts"); const services: Service[] = []; const sockets: Socket[] = []; @@ -111,7 +133,7 @@ export const ARTIFACTS_PLUGIN: Plugin = { worker: remoteProxyClientWorker(), }); } - const namespaces = getLocalNamespaceNames(bindings, options.dev); + const namespaces = getLocalArtifactsNamespaceNames(bindings, options.dev); if (namespaces.size > 0) { await assertGitAvailable(); } @@ -125,19 +147,42 @@ export const ARTIFACTS_PLUGIN: Plugin = { const local = await createLocalNamespaceRuntime( root, namespace, - artifactsController + artifactsController, + artifactsEventSubscriptions ); sockets.push(local.socket); services.push(...local.services); } return { services, extensions: [], sockets }; }, + getExtensions({ options }) { + const hasLocalBinding = options.some((worker) => + getEnvBindingsOfType(worker.config, "artifacts").some( + ([, binding]) => !getRemoteProxyConnectionString(binding, worker.dev) + ) + ); + if (!hasLocalBinding) { + return []; + } + return [ + { + modules: [ + { + name: WRAPPED_BINDING_MODULE, + esModule: SCRIPT_WRAPPED_BINDING(), + internal: true, + }, + ], + }, + ]; + }, }; async function createLocalNamespaceRuntime( root: string, namespace: string, - artifactsController: ArtifactsController + artifactsController: ArtifactsController, + eventSubscriptions: ArtifactsEventSubscriptionRoute[] ): Promise<{ services: Service[]; socket: Socket }> { await mkdir(root, { recursive: true }); await assertSupportedGitLayout(root); @@ -146,7 +191,8 @@ async function createLocalNamespaceRuntime( await mkdir(metadataPath, { recursive: true }); await assertSupportedGitLayout(metadataPath); const { sidecar, port } = await artifactsController.get( - path.join(persistPath, "git") + path.join(persistPath, "git"), + { namespace, portFile: path.join(persistPath, "git-port") } ); const serviceName = localServiceName(namespace); const storageName = `${serviceName}-storage`; @@ -190,6 +236,7 @@ async function createLocalNamespaceRuntime( durableObjectNamespace: { className: OBJECT_CLASS }, }, { name: "gitBackend", service: { name: backendName } }, + ...getArtifactsNamespaceEventBindings(eventSubscriptions, namespace), ], // Keys must be unique across namespaces in one workerd, but should // not repeat the long service prefix in SQLite's directory name. diff --git a/packages/miniflare/src/plugins/pipelines/index.ts b/packages/miniflare/src/plugins/pipelines/index.ts index 44bdfe3660..68b7f2ee21 100644 --- a/packages/miniflare/src/plugins/pipelines/index.ts +++ b/packages/miniflare/src/plugins/pipelines/index.ts @@ -18,7 +18,7 @@ export const PIPELINE_PLUGIN: Plugin = { getBindings(options) { return getEnvBindingsOfType(options.config, "pipeline").map( ([name, binding]) => { - const id = binding.name; + const id = binding.streamId; const remoteProxyConnectionString = getRemoteProxyConnectionString( binding, options.dev @@ -54,7 +54,7 @@ export const PIPELINE_PLUGIN: Plugin = { continue; } services.push({ - name: `${SERVICE_PIPELINE_PREFIX}:${binding.name}`, + name: `${SERVICE_PIPELINE_PREFIX}:${binding.streamId}`, worker: { compatibilityDate: "2024-12-30", modules: [ diff --git a/packages/miniflare/src/plugins/shared/index.ts b/packages/miniflare/src/plugins/shared/index.ts index c6303e01a7..518d5f4340 100644 --- a/packages/miniflare/src/plugins/shared/index.ts +++ b/packages/miniflare/src/plugins/shared/index.ts @@ -23,6 +23,7 @@ import type { QueueProducerSchema, } from "../../workers"; import type { ArtifactsController } from "../artifacts/controller"; +import type { ArtifactsEventSubscriptionRoute } from "../artifacts/events"; import type { ContainerPrivilegesCache } from "../core/container"; import type { DOContainerOptions } from "../do"; import type { HyperdriveProxyController } from "../hyperdrive/hyperdrive-proxy"; @@ -91,6 +92,7 @@ export interface PluginServicesOptions { containerPrivilegesCache: ContainerPrivilegesCache; hyperdriveProxyController: HyperdriveProxyController; artifactsController: ArtifactsController; + artifactsEventSubscriptions: ArtifactsEventSubscriptionRoute[]; } export interface ServicesExtensions { diff --git a/packages/miniflare/src/workers/artifacts/binding.worker.ts b/packages/miniflare/src/workers/artifacts/binding.worker.ts index 2361e67386..d90cdc1859 100644 --- a/packages/miniflare/src/workers/artifacts/binding.worker.ts +++ b/packages/miniflare/src/workers/artifacts/binding.worker.ts @@ -1,6 +1,15 @@ import { DurableObject, WorkerEntrypoint } from "cloudflare:workers"; +import { + createArtifactsEvent, + matchesArtifactsEventRoute, + toArtifactsEventMessage, + type ArtifactsEvent, + type ArtifactsEventRoute, + type RepoPayload, +} from "./events"; const repoName = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; +const MAX_LOG_LIMIT = 1000; type TokenScope = "read" | "write"; @@ -95,7 +104,10 @@ interface RepositoryListOptions { type RepositoryListResult = { repos: Array< - RepositoryMetadata & { status: "ready"; jurisdiction: "unrestricted" } + Omit & { + status: "ready"; + jurisdiction: "unrestricted"; + } >; total: number; cursor?: string; @@ -148,23 +160,49 @@ interface CommitMetadata { committedAt: number; } +/** Repository handle as sent over RPC; the wrapped binding unwraps each outcome. */ interface LocalArtifactsRepo { - info(): Promise; - createToken(scope?: TokenScope, ttl?: number): Promise; - listTokens(): Promise<{ total: number; tokens: TokenInfo[] }>; - revokeToken(tokenOrId: string): Promise; - readBlob(hash: string): Promise; - readTree(hash: string): Promise; - readCommit(hash: string): Promise; - readFile(args: { ref: string; path: string }): Promise; - log(options?: RepositoryLogOptions): Promise; - fork(name: string, options?: ForkOptions): Promise; + info(): Promise>; + createToken( + scope?: TokenScope, + ttl?: number + ): Promise>; + listTokens(): Promise>; + revokeToken(tokenOrId: string): Promise>; + readBlob(hash: string): Promise>; + readTree(hash: string): Promise>; + readCommit(hash: string): Promise>; + readFile(args: { + ref: string; + path: string; + }): Promise>; + log(options?: RepositoryLogOptions): Promise>; + fork( + name: string, + options?: ForkOptions + ): Promise>; } interface BackendBlob { data: string; } +/** + * File contents as sent over RPC. A `Blob` is serialized whole, and workerd + * caps a serialized RPC value at 32 MiB, so a file at Artifacts' 32 MiB limit + * would not fit. A stream is not subject to that cap; the wrapped binding turns + * it back into a `Blob` in the caller's isolate. + */ +export interface RepoFile { + body: ReadableStream; + /** The `Blob` type; empty for `readBlob()`, as for a typeless `Blob`. */ + type: string; +} + +function repoFile(bytes: Uint8Array, type = ""): RepoFile { + return { body: new Blob([bytes]).stream(), type }; +} + type ArtifactsErrorCode = | "ALREADY_EXISTS" | "NOT_FOUND" @@ -202,10 +240,37 @@ class ArtifactsError extends Error { } } +/** + * Exceptions that cross a workerd RPC boundary are logged as uncaught when + * workerd runs with `--verbose`, as Workers Vitest does by default. Every RPC + * method here returns an outcome instead, and the wrapped binding in + * `wrapped-binding.worker.ts` rethrows failures inside the caller's isolate. + */ +export type Outcome = + | { ok: true; value: T } + | { + ok: false; + error: { code: ArtifactsErrorCode; numericCode: number; message: string }; + }; + interface LocalArtifactsEnvironment { config: { namespace: string; origin: string }; localArtifactsNamespace: DurableObjectNamespace; gitBackend: Fetcher; + /** + * Subscriptions receiving this namespace's events. Miniflare generates these + * routes and their target bindings together, so each target binding exists + * and matches its route's target type. + */ + eventRoutes?: ArtifactsEventRoute[]; + [target: `ARTIFACTS_EVENT_TARGET_${number}`]: + | WorkflowCreateTarget + | undefined; +} + +/** The parts of a Workflow binding service used to start an instance. */ +interface WorkflowCreateTarget { + create(options: { params: unknown }): Promise; } type RepositoryMap = Record; @@ -214,29 +279,33 @@ export class LocalArtifactsNamespace extends WorkerEntrypoint { - return publicCall(() => this.#namespace().create(name, options)); + ): Promise> { + return forward(() => this.#namespace().create(name, options)); } - async get(name: string): Promise { - const repository = await publicCall(() => this.#namespace().get(name)); - return repository as unknown as LocalArtifactsRepo; + async get(name: string): Promise> { + return forward( + () => + this.#namespace().get(name) as unknown as Promise< + Outcome + > + ); } async import( options: ImportRepositoryOptions - ): Promise { - return publicCall(() => this.#namespace().import(options)); + ): Promise> { + return forward(() => this.#namespace().import(options)); } async list( options: RepositoryListOptions = {} - ): Promise { - return publicCall(() => this.#namespace().list(options)); + ): Promise> { + return forward(() => this.#namespace().list(options)); } - async delete(name: string): Promise { - return publicCall(() => this.#namespace().delete(name)); + async delete(name: string): Promise> { + return forward(() => this.#namespace().delete(name)); } override async fetch(request: Request): Promise { @@ -259,6 +328,37 @@ export class LocalArtifactsNamespaceObject extends DurableObject> { + return outcome(() => this.#create(name, options)); + } + + async get(name: string): Promise> { + return outcome(async () => { + validateName(name); + const repository = await this.getRepo(name); + return createRepoHandle(this, repository.name, repository.id); + }); + } + + async import( + options: ImportRepositoryOptions + ): Promise> { + return outcome(() => this.#import(options)); + } + + async list( + options: RepositoryListOptions = {} + ): Promise> { + return outcome(() => this.#list(options)); + } + + async delete(name: string): Promise> { + return outcome(() => this.#delete(name)); + } + + #create( + name: string, + options: RepositoryOptions ): Promise { return this.exclusive(async () => { validateName(name); @@ -295,6 +395,14 @@ export class LocalArtifactsNamespaceObject extends DurableObject { - validateName(name); - const repository = await this.getRepo(name); - return createRepoHandle(this, repository.name, repository.id); - } - - async import( - options: ImportRepositoryOptions - ): Promise { + #import(options: ImportRepositoryOptions): Promise { return this.exclusive(async () => { const { source, target, sourceUrl } = parseImportRequest(options); const repositories = await this.repos(); @@ -361,13 +461,23 @@ export class LocalArtifactsNamespaceObject extends DurableObject { + async #list(options: RepositoryListOptions): Promise { const limit = options.limit ?? 50; if (!Number.isInteger(limit) || limit < 1 || limit > 200) { throw new ArtifactsError( @@ -381,12 +491,16 @@ export class LocalArtifactsNamespaceObject extends DurableObject right.createdAt.localeCompare(left.createdAt)); const page = repositories .slice(offset, offset + limit) - .map((repository) => ({ - ...repoMetadata(repository), - status: "ready" as const, - // Local storage has no placement jurisdiction; this is the public default. - jurisdiction: "unrestricted" as const, - })); + .map((repository) => { + // List items have no `remote`; use info() for the Git URL. + const { remote: _remote, ...metadata } = repoMetadata(repository); + return { + ...metadata, + status: "ready" as const, + // Local storage has no placement jurisdiction; this is the public default. + jurisdiction: "unrestricted" as const, + }; + }); const cursor = offset + page.length < repositories.length ? encodeCursor(offset + page.length) @@ -398,7 +512,7 @@ export class LocalArtifactsNamespaceObject extends DurableObject { + #delete(name: string): Promise { return this.exclusive(async () => { validateName(name); const repositories = await this.repos(); @@ -430,6 +544,7 @@ export class LocalArtifactsNamespaceObject extends DurableObject { const repository = await this.getRepo(name, expectedId); - const active = repository.tokens.filter( - (token) => !token.revokedAt && isActive(token) - ); - const tokens = active - .toReversed() + // Active tokens come first so retained history cannot push a token that + // still authenticates off the 30-item page. Each group is newest first. + const newestFirst = repository.tokens.toReversed(); + const tokens = [ + ...newestFirst.filter((token) => tokenState(token) === "active"), + ...newestFirst.filter((token) => tokenState(token) !== "active"), + ] .slice(0, 30) - .map(({ tokenHash: _tokenHash, revokedAt: _revokedAt, ...token }) => ({ - ...token, - state: "active" as const, + .map((token) => ({ + id: token.id, + scope: token.scope, + createdAt: token.createdAt, + expiresAt: token.expiresAt, + state: tokenState(token), })); - return { total: active.length, tokens }; + return { total: repository.tokens.length, tokens }; } async revokeToken( @@ -475,11 +595,19 @@ export class LocalArtifactsNamespaceObject extends DurableObject { for (const repository of Object.values(repositories)) { - repository.tokens = repository.tokens.filter( - (token) => !token.revokedAt && isActive(token) - ); + repository.tokens = retainTokens(repository.tokens); } return this.ctx.storage.put("repos", repositories); } @@ -585,6 +720,13 @@ export class LocalArtifactsNamespaceObject extends DurableObject { @@ -624,6 +766,16 @@ export class LocalArtifactsNamespaceObject extends DurableObject { + // Name the subscription, never the payload: it may identify tokens. + console.warn( + `Artifacts event delivery failed (event=${event.type} subscription=${route.id} target=${route.target.type}): ${String(error)}` + ); + }) + ); + } + } + } + + private async deliver( + route: ArtifactsEventRoute, + event: ArtifactsEvent + ): Promise { + const message = toArtifactsEventMessage(event, route.id); + const target = + this.env[route.target.binding as `ARTIFACTS_EVENT_TARGET_${number}`]; + if (target === undefined) { + throw new Error(`Missing event target binding ${route.target.binding}`); + } + // The instance handle is an RPC stub; release it straight away. + const instance = await target.create({ params: message }); + (instance as Partial | undefined)?.[Symbol.dispose]?.(); + } + private async exclusive(action: () => Promise): Promise { const previous = this.operations; let release!: () => void; @@ -697,19 +880,47 @@ export class LocalArtifactsNamespaceObject extends DurableObject { + return createArtifactsEvent( + "cf.artifacts.repo.token.created", + eventRepo(repository), + { tokenId: token.id, scope: token.scope, expiresAt: token.expiresAt } + ); +} + function createRepoHandle( namespace: LocalArtifactsNamespaceObject, name: string, id: string ): LocalArtifactsRepo { - const read = (request: BackendRequest): Promise => - publicCall(async () => - namespace.backend(await namespace.getRepo(name, id), request) - ); + const read = async (request: BackendRequest): Promise => + namespace.backend(await namespace.getRepo(name, id), request); const readFile = async (args: { ref: string; path: string; - }): Promise => { + }): Promise => { if (!args?.ref) { throw new ArtifactsError("INVALID_INPUT", "Invalid ref: ref required."); } @@ -729,45 +940,56 @@ function createRepoHandle( return null; } const bytes = decodeBase64(result.data); - return new Blob([bytes], { type: contentType(args.path, bytes) }); + return repoFile(bytes, contentType(args.path, bytes)); }; return { info: () => - publicCall(async () => repoMetadata(await namespace.getRepo(name, id))), + outcome(async () => repoMetadata(await namespace.getRepo(name, id))), createToken: (scope: TokenScope = "write", ttl?: number) => - publicCall(() => namespace.createToken(name, scope, ttl, id)), - listTokens: () => publicCall(() => namespace.listTokens(name, id)), + outcome(() => namespace.createToken(name, scope, ttl, id)), + listTokens: () => outcome(() => namespace.listTokens(name, id)), revokeToken: (tokenOrId: string) => - publicCall(() => namespace.revokeToken(name, tokenOrId, id)), - readBlob: async (hash: string) => { - validateHash(hash); - const result = await read({ - action: "readBlob", - hash, - }); - return result === null ? null : new Blob([decodeBase64(result.data)]); - }, - readTree: async (hash: string) => { - validateHash(hash); - return await read({ action: "readTree", hash }); - }, - readCommit: async (hash: string) => { - validateHash(hash); - return await read({ action: "readCommit", hash }); - }, - readFile, - log: (options: RepositoryLogOptions = {}) => { - validateLogOptions(options); - return read({ - action: "log", - ...(options.ref === undefined ? {} : { ref: options.ref }), - ...(options.limit === undefined ? {} : { limit: options.limit }), - ...(options.offset === undefined ? {} : { offset: options.offset }), - }); - }, + outcome(() => namespace.revokeToken(name, tokenOrId, id)), + readBlob: (hash: string) => + outcome(async () => { + validateHash(hash); + const result = await read({ + action: "readBlob", + hash, + }); + return result === null ? null : repoFile(decodeBase64(result.data)); + }), + readTree: (hash: string) => + outcome(async () => { + validateHash(hash); + return await read({ action: "readTree", hash }); + }), + readCommit: (hash: string) => + outcome(async () => { + validateHash(hash); + return await read({ + action: "readCommit", + hash, + }); + }), + readFile: (args: { ref: string; path: string }) => + outcome(() => readFile(args)), + log: (options: RepositoryLogOptions = {}) => + outcome(async () => { + validateLogOptions(options); + return await read({ + action: "log", + ...(options.ref === undefined ? {} : { ref: options.ref }), + // The public API caps the page size rather than rejecting it. + ...(options.limit === undefined + ? {} + : { limit: Math.min(options.limit, MAX_LOG_LIMIT) }), + ...(options.offset === undefined ? {} : { offset: options.offset }), + }); + }), fork: (targetName: string, options: ForkOptions = {}) => - publicCall(() => namespace.fork(name, targetName, options, id)), + outcome(() => namespace.fork(name, targetName, options, id)), }; } @@ -1152,13 +1374,10 @@ function validateLogOptions( if (ref !== undefined && typeof ref !== "string") { throw new ArtifactsError("INVALID_INPUT", "Invalid ref: must be a string."); } - if ( - limit !== undefined && - (!Number.isInteger(limit) || limit < 1 || limit > 1000) - ) { + if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) { throw new ArtifactsError( "INVALID_INPUT", - "Invalid limit: must be between 1 and 1000." + "Invalid limit: must be a positive integer." ); } if (offset !== undefined && (!Number.isInteger(offset) || offset < 0)) { @@ -1204,6 +1423,32 @@ function isActive(token: Pick): boolean { return Date.parse(token.expiresAt) > Date.now(); } +function tokenState( + token: Pick +): TokenInfo["state"] { + if (token.revokedAt) { + return "revoked"; + } + return isActive(token) ? "active" : "expired"; +} + +// listTokens() reports revoked and expired tokens, so keep a bounded history +// of them rather than letting a long-lived repository grow without limit. +const MAX_INACTIVE_TOKENS = 100; + +function retainTokens(tokens: RepositoryToken[]): RepositoryToken[] { + let inactive = tokens.filter( + (token) => tokenState(token) !== "active" + ).length; + return tokens.filter((token) => { + if (tokenState(token) === "active" || inactive <= MAX_INACTIVE_TOKENS) { + return true; + } + inactive--; + return false; + }); +} + function randomHex(bytes: number): string { return [...crypto.getRandomValues(new Uint8Array(bytes))] .map((byte) => byte.toString(16).padStart(2, "0")) @@ -1303,8 +1548,15 @@ function contentType(path: string, bytes: Uint8Array): string { } } +/** workerd implements `Uint8Array.fromBase64()`; TypeScript's lib doesn't declare it yet. */ +const Base64Bytes = Uint8Array as unknown as { + fromBase64(value: string): Uint8Array; +}; + function decodeBase64(value: string): Uint8Array { - return Uint8Array.from(atob(value), (character) => character.charCodeAt(0)); + // Native decoding takes milliseconds for a 32 MiB file, where mapping each + // `atob()` character takes seconds. + return Base64Bytes.fromBase64(value); } function encodeCursor(offset: number): string { @@ -1327,14 +1579,34 @@ function decodeCursor(cursor: string | undefined): number { } } -async function publicCall(action: () => Promise): Promise { +async function outcome(action: () => Promise): Promise> { try { - return await action(); + return { ok: true, value: await action() }; } catch (error) { - if (isArtifactsError(error)) { - throw error; - } - throw new ArtifactsError("INTERNAL_ERROR", "An internal error occurred."); + const failure = isArtifactsError(error) + ? error + : new ArtifactsError("INTERNAL_ERROR", "An internal error occurred."); + return { + ok: false, + error: { + code: failure.code, + numericCode: failure.numericCode, + message: failure.message, + }, + }; + } +} + +/** Forward an outcome from the namespace object, including a failed call to it. */ +async function forward( + call: () => Promise> +): Promise> { + try { + return await call(); + } catch { + return outcome(() => { + throw new ArtifactsError("INTERNAL_ERROR", "An internal error occurred."); + }); } } diff --git a/packages/miniflare/src/workers/artifacts/events.ts b/packages/miniflare/src/workers/artifacts/events.ts new file mode 100644 index 0000000000..3f30fc2645 --- /dev/null +++ b/packages/miniflare/src/workers/artifacts/events.ts @@ -0,0 +1,215 @@ +// Public Artifacts event messages, as documented at +// https://developers.cloudflare.com/artifacts/guides/event-subscriptions/ + +import type { ArtifactsEventType } from "@cloudflare/config/public"; + +export type { ArtifactsEventType }; + +/** + * Account-level events are published to the `artifacts` source; the remaining + * events are scoped to one repository through the `artifacts.repo` source. + */ +const ACCOUNT_EVENT_TYPES: ReadonlySet = new Set([ + "cf.artifacts.repo.created", + "cf.artifacts.repo.deleted", + "cf.artifacts.repo.forked", + "cf.artifacts.repo.imported", +]); + +/** An Artifacts event source type. */ +export type ArtifactsEventSourceType = "artifacts" | "artifacts.repo"; + +/** + * Returns the subscription source that publishes an event type. + * + * @param type - Event type + * @returns `artifacts` for account-level events, else `artifacts.repo` + */ +export function getArtifactsEventSourceType( + type: ArtifactsEventType +): ArtifactsEventSourceType { + return ACCOUNT_EVENT_TYPES.has(type) ? "artifacts" : "artifacts.repo"; +} + +/** Repository state published in repository lifecycle events. */ +export interface RepoPayload { + repoId: string; + defaultBranch: string; + description: string | null; + readOnly: boolean; + createdAt: string; + updatedAt: string; + lastPushAt: string | null; +} + +/** A Git author or committer. */ +export interface GitIdentity { + name: string; + email: string; +} + +/** A commit summarised in a push event. */ +export interface PushedCommit { + id: string; + message: string; + messageTruncated: boolean; + timestamp: string; + author: GitIdentity; + committer: GitIdentity; + parents: string[]; +} + +/** Payload of each published event type. */ +export interface ArtifactsEventPayloads { + "cf.artifacts.repo.created": RepoPayload; + "cf.artifacts.repo.deleted": RepoPayload; + "cf.artifacts.repo.forked": RepoPayload & { + namespace: string; + repoName: string; + }; + "cf.artifacts.repo.imported": RepoPayload & { + sourceUrl: string; + branch: string | null; + }; + "cf.artifacts.repo.pushed": { + ref: string; + before: string; + after: string; + commits: PushedCommit[]; + totalCommitsCount: number; + commitsTruncated: boolean; + }; + "cf.artifacts.repo.cloned": Record; + "cf.artifacts.repo.fetched": Record; + "cf.artifacts.repo.token.created": { + tokenId: string; + scope: string; + expiresAt: string; + }; + "cf.artifacts.repo.token.revoked": { tokenId: string }; +} + +/** The repository an event happened to. Forks name the source repository. */ +export interface ArtifactsEventSource { + type: ArtifactsEventSourceType; + namespace: string; + repoName: string; +} + +/** An event before it is addressed to a subscription. */ +export interface ArtifactsEvent< + Type extends ArtifactsEventType = ArtifactsEventType, +> { + type: Type; + source: ArtifactsEventSource; + payload: ArtifactsEventPayloads[Type]; + timestamp: string; +} + +/** Delivery metadata added for each subscription. */ +export interface ArtifactsEventMetadata { + accountId: string; + eventSubscriptionId: string; + eventSchemaVersion: 1; + eventTimestamp: string; +} + +/** The message a Workflow receives. */ +export type ArtifactsEventMessage< + Type extends ArtifactsEventType = ArtifactsEventType, +> = { + [T in Type]: { + type: T; + source: ArtifactsEventSource; + payload: ArtifactsEventPayloads[T]; + metadata: ArtifactsEventMetadata; + }; +}[Type]; + +/** Local development has no Cloudflare account. */ +export const LOCAL_ACCOUNT_ID = "local"; + +/** + * Creates an event happening now. + * + * @param type - Event type + * @param repo - Repository the event happened to + * @param payload - Event payload + * @returns The event + */ +export function createArtifactsEvent( + type: Type, + repo: { namespace: string; repoName: string }, + payload: ArtifactsEventPayloads[Type] +): ArtifactsEvent { + return { + type, + source: { type: getArtifactsEventSourceType(type), ...repo }, + payload, + timestamp: new Date().toISOString(), + }; +} + +/** + * Addresses an event to one subscription. + * + * @param event - Event to deliver + * @param eventSubscriptionId - Subscription receiving the event + * @returns The delivered message + */ +export function toArtifactsEventMessage( + event: ArtifactsEvent, + eventSubscriptionId: string +): ArtifactsEventMessage { + return { + type: event.type, + source: event.source, + payload: event.payload, + metadata: { + accountId: LOCAL_ACCOUNT_ID, + eventSubscriptionId, + eventSchemaVersion: 1, + eventTimestamp: event.timestamp, + }, + // TypeScript can't correlate `type` and `payload` through the generic. + } as ArtifactsEventMessage; +} + +/** Where a subscription delivers events. */ +export interface ArtifactsEventTarget { + type: "workflow"; + binding: string; +} + +/** + * A subscription resolved for one local namespace. Subscriptions for other + * namespaces are never passed to the namespace. + */ +export interface ArtifactsEventRoute { + /** Stable local subscription identifier, used as `eventSubscriptionId`. */ + id: string; + /** Event types to deliver; never empty. */ + types: ArtifactsEventType[]; + /** Restricts events to this repository, if set. */ + repoName?: string; + target: ArtifactsEventTarget; +} + +/** + * Returns whether a route should receive an event. + * + * @param route - Subscription route + * @param event - Published event + * @returns Whether the event matches the route's types and repository + */ +export function matchesArtifactsEventRoute( + route: ArtifactsEventRoute, + event: ArtifactsEvent +): boolean { + return ( + route.types.includes(event.type) && + // Match repository lookup identity without changing the published spelling. + (route.repoName === undefined || + route.repoName.toLowerCase() === event.source.repoName.toLowerCase()) + ); +} diff --git a/packages/miniflare/src/workers/artifacts/wrapped-binding.worker.ts b/packages/miniflare/src/workers/artifacts/wrapped-binding.worker.ts new file mode 100644 index 0000000000..778cd4a681 --- /dev/null +++ b/packages/miniflare/src/workers/artifacts/wrapped-binding.worker.ts @@ -0,0 +1,109 @@ +/** + * Wrapped binding for a local Artifacts namespace. It runs in the caller's + * isolate, so an `ArtifactsError` is thrown there and never crosses an RPC + * boundary, where workerd would log it as an uncaught exception. + */ +import type { + LocalArtifactsNamespace, + Outcome, + RepoFile, +} from "./binding.worker"; + +interface Env { + namespace: Pick< + LocalArtifactsNamespace, + "create" | "get" | "import" | "list" | "delete" + >; +} + +type Unwrapped = F extends (...args: infer A) => Promise> + ? (...args: A) => Promise + : never; + +type RepoHandle = Extract< + Awaited>, + { ok: true } +>["value"]; + +type FileReader = F extends ( + ...args: infer A +) => Promise> + ? (...args: A) => Promise + : never; + +type Repo = { + [K in keyof RepoHandle]: K extends "readBlob" | "readFile" + ? FileReader + : Unwrapped; +} & Disposable; + +type Failure = Extract, { ok: false }>["error"]; + +/** The namespace service owns the codes; this only rethrows its failure. */ +class ArtifactsError extends Error { + readonly code: Failure["code"]; + readonly numericCode: number; + + constructor({ code, numericCode, message }: Failure) { + super(message); + this.name = "ArtifactsError"; + this.code = code; + this.numericCode = numericCode; + } +} + +function unwrap(result: Outcome): T { + if (result.ok) { + return result.value; + } + throw new ArtifactsError(result.error); +} + +/** Buffers a streamed file into the `Blob` the public binding returns. */ +async function toBlob(file: RepoFile | null): Promise { + if (file === null) { + return null; + } + const bytes = await new Response(file.body).arrayBuffer(); + return new Blob([bytes], { type: file.type }); +} + +function wrapRepo(handle: RepoHandle, dispose: (() => void) | undefined): Repo { + // A plain object keeps the methods enumerable, like the RPC stub it replaces. + return { + info: async () => unwrap(await handle.info()), + createToken: async (scope, ttl) => + unwrap(await handle.createToken(scope, ttl)), + listTokens: async () => unwrap(await handle.listTokens()), + revokeToken: async (tokenOrId) => + unwrap(await handle.revokeToken(tokenOrId)), + readBlob: async (hash) => toBlob(unwrap(await handle.readBlob(hash))), + readTree: async (hash) => unwrap(await handle.readTree(hash)), + readCommit: async (hash) => unwrap(await handle.readCommit(hash)), + readFile: async (args) => toBlob(unwrap(await handle.readFile(args))), + log: async (options) => unwrap(await handle.log(options)), + fork: async (name, options) => unwrap(await handle.fork(name, options)), + [Symbol.dispose]() { + dispose?.(); + }, + }; +} + +export default function (env: Env) { + const { namespace } = env; + return { + create: async (...args: Parameters) => + unwrap(await namespace.create(...args)), + get: async (name: string) => { + const result = (await namespace.get(name)) as Outcome & + Partial; + const handle = unwrap(result); + return wrapRepo(handle, () => result[Symbol.dispose]?.()); + }, + import: async (...args: Parameters) => + unwrap(await namespace.import(...args)), + list: async (...args: Parameters) => + unwrap(await namespace.list(...args)), + delete: async (name: string) => unwrap(await namespace.delete(name)), + }; +} diff --git a/packages/miniflare/src/workers/core/email.ts b/packages/miniflare/src/workers/core/email.ts index eac1f2be5d..44f341f916 100644 --- a/packages/miniflare/src/workers/core/email.ts +++ b/packages/miniflare/src/workers/core/email.ts @@ -259,6 +259,7 @@ export async function handleEmail( raw: deliveredEmailBody, rawSize: deliveredEmailRaw.byteLength, headers: incomingEmailHeaders, + canBeForwarded: true, setReject: (reason: string): void => { ctx.waitUntil( logEmailToLoopback( diff --git a/packages/miniflare/test/config/local-bindings.spec.ts b/packages/miniflare/test/config/local-bindings.spec.ts index b0e4fd28eb..03bedd2d15 100644 --- a/packages/miniflare/test/config/local-bindings.spec.ts +++ b/packages/miniflare/test/config/local-bindings.spec.ts @@ -74,25 +74,25 @@ describe("resolveLocalBindings", () => { }); test.for([ - { remote: undefined, remoteBindings: true, resolved: true }, - { remote: undefined, remoteBindings: false, resolved: false }, - { remote: false, remoteBindings: true, resolved: false }, - { remote: true, remoteBindings: true, resolved: true }, - // Miniflare uses the simulator without a remote proxy connection. - { remote: true, remoteBindings: false, resolved: true }, + { remote: undefined, remoteBindings: true }, + { remote: undefined, remoteBindings: false }, + { remote: false, remoteBindings: true }, + { remote: true, remoteBindings: true }, ])( - "resolves Artifacts dev.remote=$remote with remoteBindings=$remoteBindings", - ({ remote, remoteBindings, resolved }, { expect }) => { + "passes Artifacts dev.remote=$remote through with remoteBindings=$remoteBindings", + ({ remote, remoteBindings }, { expect }) => { const binding = { type: "artifacts" as const, namespace: "examples", ...(remote === undefined ? {} : { dev: { remote } }), }; - expect( - resolveLocalBindings({ REPOS: binding }, options({ remoteBindings })) - ).toEqual({ - REPOS: { ...binding, dev: { remote: resolved } }, + // Miniflare routes remotely only for `dev.remote: true`, so an omitted + // `remote` uses the local simulator. + const resolveOptions = options({ remoteBindings }); + expect(resolveLocalBindings({ REPOS: binding }, resolveOptions)).toEqual({ + REPOS: binding, }); + expect(resolveOptions.logger.warn).not.toHaveBeenCalled(); } ); }); diff --git a/packages/miniflare/test/config/v4-convert.spec.ts b/packages/miniflare/test/config/v4-convert.spec.ts index 76336f87c2..b11c044ce0 100644 --- a/packages/miniflare/test/config/v4-convert.spec.ts +++ b/packages/miniflare/test/config/v4-convert.spec.ts @@ -41,7 +41,7 @@ describe("convertV4MiniflareOptions", () => { } ); - test("Artifacts uses a connected remote proxy unless local is selected", ({ + test("Artifacts uses a remote proxy only when given a connection string", ({ expect, }) => { const remoteProxyConnectionString = new URL( @@ -51,20 +51,15 @@ describe("convertV4MiniflareOptions", () => { name: "worker", script: "export default {};", artifacts: { - DEFAULT: { namespace: "default", remoteProxyConnectionString }, - LOCAL: { - namespace: "local", - remote: false, - remoteProxyConnectionString, - }, - // `wrangler dev --local` passes no connection string. - OFFLINE: { namespace: "offline" }, + // Wrangler passes a connection string only for `remote: true`. + REMOTE: { namespace: "remote", remoteProxyConnectionString }, + LOCAL: { namespace: "local" }, }, }); const env = converted.workers[0].config.env; - expect(env?.DEFAULT).toEqual({ + expect(env?.REMOTE).toEqual({ type: "artifacts", - namespace: "default", + namespace: "remote", dev: { remote: true }, }); expect(env?.LOCAL).toEqual({ @@ -72,15 +67,44 @@ describe("convertV4MiniflareOptions", () => { namespace: "local", dev: { remote: false }, }); - expect(env?.OFFLINE).toEqual({ - type: "artifacts", - namespace: "offline", - dev: { remote: false }, - }); expect(converted.workers[0].dev?.remoteProxyConnectionString).toBe( remoteProxyConnectionString ); }); + test("carries events on Workflow exports and legacy bindings", ({ + expect, + }) => { + const events = [ + { + type: "cf.artifacts.repo.created" as const, + filter: { repoName: "demo" }, + }, + ]; + const converted = convertV4MiniflareOptions({ + name: "worker", + script: "export default {};", + workflowExports: { + OnCreate: { name: "on-create", events, stepLimit: 2 }, + }, + workflows: { + LEGACY: { name: "legacy", className: "Legacy", events, stepLimit: 3 }, + }, + }); + expect(converted.workers[0].config.exports).toMatchObject({ + OnCreate: { + type: "workflow", + name: "on-create", + events, + limits: { steps: 2 }, + }, + }); + expect(converted.workers[0].config.env).toMatchObject({ + LEGACY: { + type: "workflow", + unsafeConfig: { events, limits: { steps: 3 } }, + }, + }); + }); test("preserves opaque K2 stream IDs through v4 parsing and conversion", ({ expect, }) => { @@ -97,7 +121,7 @@ describe("convertV4MiniflareOptions", () => { expect(converted.workers[0].config.env?.ORDERS).toEqual({ type: "k2", - stream, + id: stream, dev: { remote: true }, }); expect(converted.workers[0].dev?.remoteProxyConnectionString).toEqual( @@ -310,7 +334,7 @@ describe("convertV4MiniflareOptions", () => { }, QUEUE: { type: "queue", name: "queue" }, SERVICE: { type: "worker", worker: "other-worker" }, - ANALYTICS: { type: "analytics", dev: { remote: false } }, + ANALYTICS: { type: "analytics-sql", dev: { remote: false } }, ASSETS: { type: "assets" }, BROWSER: { type: "browser", headful: true }, WORKFLOW: { @@ -455,7 +479,7 @@ describe("convertV4MiniflareOptions", () => { expect(converted.workers[0].config.env?.PIPELINE).toEqual({ type: "pipeline", - name: "PIPELINE", + streamId: "PIPELINE", }); }); diff --git a/packages/miniflare/test/index.spec.ts b/packages/miniflare/test/index.spec.ts index d3e896b925..3fddcd9659 100644 --- a/packages/miniflare/test/index.spec.ts +++ b/packages/miniflare/test/index.spec.ts @@ -246,8 +246,8 @@ test("Miniflare: accepts mixed pipelines record", () => { compatibilityDate: "2025-05-01", manifest: singleModuleManifest(""), env: { - LOCAL_PIPELINE: { type: "pipeline", name: "local-pipeline" }, - REMOTE_PIPELINE: { type: "pipeline", name: "remote-pipeline" }, + LOCAL_PIPELINE: { type: "pipeline", streamId: "local-pipeline" }, + REMOTE_PIPELINE: { type: "pipeline", streamId: "remote-pipeline" }, }, }, }, @@ -2584,6 +2584,70 @@ This is a random email body. expect(await res.text()).toBe("true"); }); +test("Miniflare: manually triggered email handler - exposes canBeForwarded on ForwardableEmailMessage", async ({ + expect, +}) => { + const log = new TestLog(); + + const mf = new Miniflare({ + log, + unsafeTriggerHandlers: true, + workers: [ + { + config: { + name: "", + compatibilityDate: "2025-05-01", + manifest: singleModuleManifest(` + let messageDetails = null; + export default { + fetch() { + return Response.json(messageDetails); + }, + async email(emailMessage) { + messageDetails = { + canBeForwarded: emailMessage.canBeForwarded, + hasCanBeForwarded: "canBeForwarded" in emailMessage, + rawSize: emailMessage.rawSize, + }; + } + }`), + }, + }, + ], + }); + useDispose(mf); + + let res = await mf.dispatchFetch("http://localhost"); + expect(await res.json()).toBe(null); + + res = await mf.dispatchFetch( + "http://localhost/cdn-cgi/local/email?from=someone@example.com&to=someone-else@example.com", + { + body: `From: someone +To: someone else +Message-ID: +MIME-Version: 1.0 +Content-Type: text/plain + +This is a random email body. +`, + method: "POST", + } + ); + expect(await res.text()).toBe("Worker successfully processed email"); + expect(res.status).toBe(200); + + res = await mf.dispatchFetch("http://localhost"); + const details = (await res.json()) as { + canBeForwarded: boolean; + hasCanBeForwarded: boolean; + rawSize: number; + }; + expect(details.canBeForwarded).toBe(true); + expect(details.hasCanBeForwarded).toBe(true); + expect(details.rawSize).toBeGreaterThan(0); +}); + test("Miniflare: manually triggered email handler - invalid email, no message id", async ({ expect, }) => { diff --git a/packages/miniflare/test/plugins/analytics-sql/index.spec.ts b/packages/miniflare/test/plugins/analytics-sql/index.spec.ts index d52d70ddc9..067f31f55c 100644 --- a/packages/miniflare/test/plugins/analytics-sql/index.spec.ts +++ b/packages/miniflare/test/plugins/analytics-sql/index.spec.ts @@ -4,7 +4,7 @@ import { describe, test } from "vitest"; function workerOptions(bindings = true) { return { config: { - env: bindings ? { ANALYTICS: { type: "analytics" } } : {}, + env: bindings ? { ANALYTICS: { type: "analytics-sql" } } : {}, }, } as unknown as Parameters[0]; } diff --git a/packages/miniflare/test/plugins/artifacts/contract.spec.ts b/packages/miniflare/test/plugins/artifacts/contract.spec.ts index 9694a52495..9ca1ce259f 100644 --- a/packages/miniflare/test/plugins/artifacts/contract.spec.ts +++ b/packages/miniflare/test/plugins/artifacts/contract.spec.ts @@ -119,9 +119,17 @@ test("shared Artifacts contract runs against the local RPC binding and cleans up outcome: "value", value: null, }); + } + // Per the binding types, readBlob() returns null for a non-blob, while + // readTree() and readCommit() reject an object of another type. + expect(find("blob wrong type")).toMatchObject({ + outcome: "value", + value: null, + }); + for (const kind of ["tree", "commit"]) { expect(find(`${kind} wrong type`)).toMatchObject({ - outcome: "value", - value: null, + outcome: "error", + value: { code: "INTERNAL_ERROR" }, }); } expect(find("file missing ref")).toMatchObject({ diff --git a/packages/miniflare/test/plugins/artifacts/event-delivery.spec.ts b/packages/miniflare/test/plugins/artifacts/event-delivery.spec.ts new file mode 100644 index 0000000000..ea623db676 --- /dev/null +++ b/packages/miniflare/test/plugins/artifacts/event-delivery.spec.ts @@ -0,0 +1,291 @@ +import { LogLevel, Miniflare, Response } from "miniflare"; +import { onTestFinished, test, vi } from "vitest"; +import { + singleModuleManifest, + TestLog, + useDispose, + useTmp, +} from "../../test-shared"; +import type { ArtifactsEventMessage } from "../../../src/workers/artifacts/events"; +import type { ArtifactsEventSubscription } from "@cloudflare/config"; +import type { MiniflareOptions, WorkerOptions } from "miniflare"; + +const WORKER_NAME = "artifacts-events"; +const SCRIPT = ` +import { WorkflowEntrypoint } from "cloudflare:workers"; +export class OnRepoEvent extends WorkflowEntrypoint { + async run(event, step) { + await step.do("report", () => this.env.REPORTER.fetch("http://reporter", { + method: "POST", body: JSON.stringify(event.payload), + }).then(() => "reported")); + } +} +export default { + async fetch(request, env) { + const { method, name, args = [] } = await request.json(); + const target = name === undefined ? env.REPOS : await env.REPOS.get(name); + return Response.json(await target[method](...args)); + }, +}; +`; + +async function createMiniflare( + events: ArtifactsEventSubscription[], + configure: (config: WorkerOptions["config"]) => void = () => {}, + shared: Partial = {} +) { + const delivered: ArtifactsEventMessage[] = []; + const config: WorkerOptions["config"] = { + name: WORKER_NAME, + compatibilityDate: "2026-09-03", + manifest: singleModuleManifest(SCRIPT), + exports: { + OnRepoEvent: { type: "workflow", name: "on-repo-event", events }, + }, + env: { + REPOS: { + type: "artifacts", + namespace: "examples", + dev: { remote: false }, + }, + REPORTER: { + type: "fetcher", + handler: async (request) => { + delivered.push((await request.json()) as ArtifactsEventMessage); + return new Response(); + }, + }, + }, + }; + configure(config); + const options: MiniflareOptions = { + cf: false, + resourcePersistencePath: await useTmp(), + ...shared, + workers: [{ config }], + }; + const mf = new Miniflare(options); + return { mf, delivered, options }; +} + +async function startMiniflare(...args: Parameters) { + const started = await createMiniflare(...args); + useDispose(started.mf); + await started.mf.ready; + return started; +} + +async function rpc( + mf: Miniflare, + method: string, + args: unknown[] = [], + name?: string +): Promise { + const response = await mf.dispatchFetch("http://localhost", { + method: "POST", + body: JSON.stringify({ method, args, name }), + }); + if (!response.ok) { + throw new Error(await response.text()); + } + return response.json(); +} + +const CREATED: ArtifactsEventSubscription = { + type: "cf.artifacts.repo.created", +}; + +test("warns once when Workflow events have no local namespace", async ({ + expect, +}) => { + const log = new TestLog(); + const { mf, options } = await startMiniflare( + [CREATED], + (config) => { + delete config.env?.REPOS; + }, + { log } + ); + await mf.setOptions(options); + expect(log.logsAtLevel(LogLevel.WARN)).toEqual([ + "Workflow events are only published by local Artifacts namespaces, and this instance has none.", + ]); +}); + +test.for(["export", "binding"] as const)( + "%s-owned events start a Workflow with the documented message", + async (mode, { expect }) => { + const { mf, delivered } = await startMiniflare([CREATED], (config) => { + if (mode === "binding") { + delete config.exports; + config.env = { + ...config.env, + ON_EVENT: { + type: "workflow", + name: "on-repo-event", + worker: WORKER_NAME, + exportName: "OnRepoEvent", + unsafeConfig: { events: [CREATED] }, + }, + }; + } + }); + await rpc(mf, "create", ["demo", { description: "Demo" }]); + await vi.waitFor(() => expect(delivered).toHaveLength(1), { + timeout: 5000, + }); + expect(delivered[0]).toMatchObject({ + type: "cf.artifacts.repo.created", + source: { type: "artifacts", namespace: "examples", repoName: "demo" }, + payload: { + repoId: expect.any(String), + defaultBranch: "main", + description: "Demo", + readOnly: false, + lastPushAt: null, + }, + metadata: { + accountId: "local", + eventSubscriptionId: expect.stringMatching(/^[0-9a-f]{32}$/), + eventSchemaVersion: 1, + eventTimestamp: expect.any(String), + }, + }); + await rpc(mf, "createToken", ["read"], "demo"); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(delivered).toHaveLength(1); + } +); + +test("duplicate event declarations retain separate deliveries and distinct IDs", async ({ + expect, +}) => { + const { mf, delivered } = await startMiniflare([CREATED, CREATED]); + await rpc(mf, "create", ["demo"]); + await vi.waitFor(() => expect(delivered).toHaveLength(2), { timeout: 5000 }); + expect( + new Set(delivered.map((event) => event.metadata.eventSubscriptionId)).size + ).toBe(2); +}); + +test.for([ + { exportEvents: [], deliveries: 1 }, + { exportEvents: [CREATED], deliveries: 2 }, +])( + "events on a binding to a Workflow export subscribe alongside the export's ($deliveries deliveries)", + async ({ exportEvents, deliveries }, { expect }) => { + const { mf, delivered } = await startMiniflare(exportEvents, (config) => { + config.env = { + ...config.env, + ON_EVENT: { + type: "workflow", + name: "on-repo-event", + worker: WORKER_NAME, + exportName: "OnRepoEvent", + unsafeConfig: { events: [CREATED] }, + }, + }; + }); + await rpc(mf, "create", ["demo"]); + await vi.waitFor(() => expect(delivered).toHaveLength(deliveries), { + timeout: 5000, + }); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(delivered).toHaveLength(deliveries); + } +); + +test("namespace filters exclude other local namespaces", async ({ expect }) => { + const { mf, delivered } = await startMiniflare( + [{ ...CREATED, filter: { namespace: "examples" } }], + (config) => { + config.env = { + ...config.env, + OTHER: { + type: "artifacts", + namespace: "other", + dev: { remote: false }, + }, + }; + } + ); + const bindings = await mf.getBindings<{ + OTHER: { create(name: string): Promise }; + }>(); + await bindings.OTHER.create("excluded"); + await rpc(mf, "create", ["included"]); + await vi.waitFor(() => expect(delivered).toHaveLength(1), { timeout: 5000 }); + expect(delivered[0].source.namespace).toBe("examples"); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(delivered).toHaveLength(1); +}); + +test("repository filters match identity without changing published spelling", async ({ + expect, +}) => { + const { mf, delivered } = await startMiniflare([ + { + type: "cf.artifacts.repo.token.revoked", + filter: { namespace: "examples", repoName: "dEMo" }, + }, + ]); + await rpc(mf, "create", ["other"]); + const other = (await rpc(mf, "createToken", ["read"], "other")) as { + id: string; + }; + await rpc(mf, "revokeToken", [other.id], "other"); + await rpc(mf, "create", ["Demo"]); + const token = (await rpc(mf, "createToken", ["read"], "demo")) as { + id: string; + }; + await rpc(mf, "revokeToken", [token.id], "DEMO"); + await vi.waitFor(() => expect(delivered).toHaveLength(1), { timeout: 5000 }); + expect(delivered[0]).toMatchObject({ + type: "cf.artifacts.repo.token.revoked", + source: { namespace: "examples", repoName: "Demo" }, + payload: { tokenId: token.id }, + }); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(delivered).toHaveLength(1); +}); + +test("fork events filter on the source repository", async ({ expect }) => { + const { mf, delivered } = await startMiniflare([ + { + type: "cf.artifacts.repo.forked", + filter: { namespace: "examples", repoName: "source" }, + }, + ]); + await rpc(mf, "create", ["source"]); + await rpc(mf, "create", ["unrelated"]); + await rpc(mf, "fork", ["ignored"], "unrelated"); + await rpc(mf, "fork", ["copy"], "source"); + await vi.waitFor(() => expect(delivered).toHaveLength(1), { timeout: 5000 }); + expect(delivered[0]).toMatchObject({ + type: "cf.artifacts.repo.forked", + source: { namespace: "examples", repoName: "source" }, + payload: { namespace: "examples", repoName: "copy" }, + }); +}); + +test("a binding cannot configure events on another Worker's Workflow", async ({ + expect, +}) => { + const { mf } = await createMiniflare([], (config) => { + delete config.exports; + config.env = { + ...config.env, + ON_EVENT: { + type: "workflow", + name: "on-repo-event", + worker: "another-worker", + exportName: "OnRepoEvent", + unsafeConfig: { events: [CREATED] }, + }, + }; + }); + onTestFinished(() => mf.dispose().catch(() => {})); + await expect(mf.ready).rejects.toThrow( + "cannot declare events for another Worker's Workflow" + ); +}); diff --git a/packages/miniflare/test/plugins/artifacts/events.spec.ts b/packages/miniflare/test/plugins/artifacts/events.spec.ts new file mode 100644 index 0000000000..68fc59f38d --- /dev/null +++ b/packages/miniflare/test/plugins/artifacts/events.spec.ts @@ -0,0 +1,90 @@ +import { test } from "vitest"; +import { + createArtifactsEvent, + getArtifactsEventSourceType, + matchesArtifactsEventRoute, + toArtifactsEventMessage, +} from "../../../src/workers/artifacts/events"; +import type { ArtifactsEventRoute } from "../../../src/workers/artifacts/events"; + +const repo = { namespace: "examples", repoName: "demo" }; + +function route(overrides: Partial): ArtifactsEventRoute { + return { + id: "subscription", + types: ["cf.artifacts.repo.token.revoked"], + target: { type: "workflow", binding: "ARTIFACTS_EVENT_TARGET_0" }, + ...overrides, + }; +} + +test("events use the documented source for each event type", ({ expect }) => { + expect(getArtifactsEventSourceType("cf.artifacts.repo.created")).toBe( + "artifacts" + ); + expect(getArtifactsEventSourceType("cf.artifacts.repo.pushed")).toBe( + "artifacts.repo" + ); + expect(getArtifactsEventSourceType("cf.artifacts.repo.token.revoked")).toBe( + "artifacts.repo" + ); +}); + +test("messages carry the event and per-subscription metadata", ({ expect }) => { + const event = createArtifactsEvent("cf.artifacts.repo.token.revoked", repo, { + tokenId: "token", + }); + + expect(toArtifactsEventMessage(event, "subscription")).toEqual({ + type: "cf.artifacts.repo.token.revoked", + source: { type: "artifacts.repo", ...repo }, + payload: { tokenId: "token" }, + metadata: { + accountId: "local", + eventSubscriptionId: "subscription", + eventSchemaVersion: 1, + eventTimestamp: event.timestamp, + }, + }); +}); + +test.for([ + { published: "Demo", subscribed: "demo" }, + { published: "demo", subscribed: "DEMO" }, + { published: "Demo", subscribed: "dEmO" }, +])( + "routes match repository identity: $published / $subscribed", + ({ published, subscribed }, { expect }) => { + const event = createArtifactsEvent( + "cf.artifacts.repo.token.revoked", + { + ...repo, + repoName: published, + }, + { tokenId: "token" } + ); + expect( + matchesArtifactsEventRoute(route({ repoName: subscribed }), event) + ).toBe(true); + expect(toArtifactsEventMessage(event, "subscription").source.repoName).toBe( + published + ); + } +); + +test("routes match on event type and repository", ({ expect }) => { + const event = createArtifactsEvent("cf.artifacts.repo.token.revoked", repo, { + tokenId: "token", + }); + + expect(matchesArtifactsEventRoute(route({}), event)).toBe(true); + expect( + matchesArtifactsEventRoute( + route({ types: ["cf.artifacts.repo.token.created"] }), + event + ) + ).toBe(false); + expect(matchesArtifactsEventRoute(route({ repoName: "other" }), event)).toBe( + false + ); +}); diff --git a/packages/miniflare/test/plugins/artifacts/git-client.spec.ts b/packages/miniflare/test/plugins/artifacts/git-client.spec.ts index 2b587bacb7..9edd2fced6 100644 --- a/packages/miniflare/test/plugins/artifacts/git-client.spec.ts +++ b/packages/miniflare/test/plugins/artifacts/git-client.spec.ts @@ -164,7 +164,9 @@ test("Git client imports, reads and forks a local repository", async ({ const tag = ( await git(["rev-parse", "refs/tags/v1"], imported.repository) ).stdout.trim(); - expect(await imported.readCommit(tag)).toBeNull(); + await expect(imported.readCommit(tag)).rejects.toThrow( + "is a tag, not a commit" + ); expect(await imported.readBlob(tag)).toBeNull(); const blob = ( await git(["rev-parse", "HEAD:hello.txt"], source) diff --git a/packages/miniflare/test/plugins/artifacts/https-import.spec.ts b/packages/miniflare/test/plugins/artifacts/https-import.spec.ts index 9f6357dcdf..455d77ad0a 100644 --- a/packages/miniflare/test/plugins/artifacts/https-import.spec.ts +++ b/packages/miniflare/test/plugins/artifacts/https-import.spec.ts @@ -1,17 +1,35 @@ +import assert from "node:assert/strict"; import { execFile, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { readdir, readFile, writeFile } from "node:fs/promises"; import { createServer } from "node:https"; import path from "node:path"; import { promisify } from "node:util"; -import { Miniflare } from "miniflare"; -import { test } from "vitest"; +import { Miniflare, Response } from "miniflare"; +import { test, vi } from "vitest"; import { gitEnvironment } from "../../../src/plugins/artifacts/git-client"; import { repositoryPath } from "../../../src/plugins/artifacts/storage"; import { singleModuleManifest, useTmp } from "../../test-shared"; +import type { + ArtifactsEventMessage, + ArtifactsEventType, +} from "../../../src/workers/artifacts/events"; +import type { Request } from "miniflare"; const exec = promisify(execFile); +type Delivery = ArtifactsEventMessage; const WORKER = ` +import { WorkflowEntrypoint } from "cloudflare:workers"; +export class OnEvent extends WorkflowEntrypoint { + async run(event, step) { + await step.do("report", async () => { + await this.env.REPORTER.fetch("http://reporter/workflow", { + method: "POST", body: JSON.stringify(event.payload), + }); + return "reported"; + }); + } +} export default { async fetch(request, env) { const { method, name, args = [] } = await request.json(); @@ -257,7 +275,8 @@ async function withFixture( commits: Awaited>; directory: string; }) => Promise, - trust = true + trust = true, + events?: { repoEvent: ArtifactsEventType; delivered: Delivery[] } ) { const directory = await useTmp(); const commits = await makeSource(directory); @@ -281,12 +300,40 @@ async function withFixture( name: "", compatibilityDate: "2026-09-03", env: { + ...(events && { + REPORTER: { + type: "fetcher" as const, + handler: async (request: Request) => { + events.delivered.push( + (await request.json()) as ArtifactsEventMessage + ); + return new Response(); + }, + }, + }), REPOS: { type: "artifacts", namespace: "https-import", dev: { remote: false }, }, }, + exports: events && { + OnEvent: { + type: "workflow", + name: "on-event", + events: ( + [events.repoEvent, "cf.artifacts.repo.token.created"] as const + ).map((type) => ({ + type, + filter: { + namespace: "https-import", + ...(type === "cf.artifacts.repo.token.created" + ? { repoName: "target" } + : {}), + }, + })), + }, + }, manifest: singleModuleManifest(WORKER), }, }, @@ -313,6 +360,87 @@ function restoreCA(value: string | undefined): void { } } +test.for([ + { operation: "create", repoEvent: "cf.artifacts.repo.created" }, + { operation: "import", repoEvent: "cf.artifacts.repo.imported" }, + { operation: "fork", repoEvent: "cf.artifacts.repo.forked" }, +] as const)( + "$operation publishes its initial token to Workflows only after success", + async ({ operation, repoEvent }, { expect }) => { + const delivered: Delivery[] = []; + await withFixture( + async ({ mf, fixture }) => { + if (operation === "fork") { + expect((await call(mf, "create", ["source"])).ok).toBe(true); + } + const args = + operation === "import" + ? [ + importOptions( + fixture.url.replace( + "https://", + "https://reader:correct-password@" + ), + "target" + ), + ] + : ["target"]; + const name = operation === "fork" ? "source" : undefined; + const result = await call(mf, operation, args, name); + expect(result.ok).toBe(true); + const created = result.body as { token: string }; + const listed = (await call(mf, "listTokens", [], "target")).body as { + total: number; + tokens: { id: string; scope: string; expiresAt: string }[]; + }; + expect(listed.total).toBe(1); + const [initialToken] = listed.tokens; + await vi.waitFor(() => expect(delivered).toHaveLength(2), { + timeout: 5_000, + }); + const messages = delivered; + expect(messages.map(({ type }) => type).sort()).toEqual( + [repoEvent, "cf.artifacts.repo.token.created"].sort() + ); + const token = messages.find( + ({ type }) => type === "cf.artifacts.repo.token.created" + ); + const repo = messages.find(({ type }) => type === repoEvent); + expect(token).toMatchObject({ + source: { namespace: "https-import", repoName: "target" }, + payload: { + tokenId: initialToken.id, + scope: initialToken.scope, + expiresAt: initialToken.expiresAt, + }, + }); + // Publication order is reflected by timestamps, not arrival order. + assert(token && repo); + expect( + Date.parse(token.metadata.eventTimestamp) + ).toBeGreaterThanOrEqual(Date.parse(repo.metadata.eventTimestamp)); + expect(JSON.stringify(delivered)).not.toContain(created.token); + // The plaintext returned by the operation identifies the published token. + expect( + (await call(mf, "revokeToken", [created.token], "target")).body + ).toBe(true); + const afterRevoke = (await call(mf, "listTokens", [], "target")) + .body as { tokens: { state: "active" | "revoked" | "expired" }[] }; + // Revocation must leave no active token, even if history is retained. + expect( + afterRevoke.tokens.filter(({ state }) => state === "active") + ).toEqual([]); + // A duplicate target fails without creating a token or publishing either event. + expect((await call(mf, operation, args, name)).ok).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(delivered).toHaveLength(2); + }, + true, + { repoEvent, delivered } + ); + } +); + test("HTTPS import: credentials never follow a Git redirect", async ({ expect, }) => { diff --git a/packages/miniflare/test/plugins/artifacts/index.spec.ts b/packages/miniflare/test/plugins/artifacts/index.spec.ts index 193f806a79..a144fb20cc 100644 --- a/packages/miniflare/test/plugins/artifacts/index.spec.ts +++ b/packages/miniflare/test/plugins/artifacts/index.spec.ts @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { chmod, mkdir, + readdir, readFile, rename, stat, @@ -14,11 +15,12 @@ import { pipeline } from "node:stream/promises"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { removeDir } from "@cloudflare/workers-utils/fs-helpers"; -import { ArtifactsController, Miniflare } from "miniflare"; +import { ArtifactsController, LogLevel, Miniflare } from "miniflare"; import { test, vi } from "vitest"; import { GitClient, gitEnvironment, + MAX_BLOB_BYTES, withRepositoryCreationLock, } from "../../../src/plugins/artifacts/git-client"; import { @@ -27,7 +29,12 @@ import { type GitSidecar, } from "../../../src/plugins/artifacts/git-sidecar"; import { repositoryPath } from "../../../src/plugins/artifacts/storage"; -import { singleModuleManifest, useDispose, useTmp } from "../../test-shared"; +import { + singleModuleManifest, + TestLog, + useDispose, + useTmp, +} from "../../test-shared"; import type { MiniflareOptions, RemoteProxyConnectionString } from "miniflare"; // Native Git subprocesses can slow down considerably while sharing a Windows @@ -40,11 +47,14 @@ const exec = promisify(execFile); const SCRIPT = ` export default { async fetch(request, env) { - const { method, name, args = [] } = await request.json(); + const { method, name, args = [], sizeOnly } = await request.json(); try { const target = name === undefined ? env.REPOS : await env.REPOS.get(name); if (method === "keys") return Response.json(Object.keys(target)); const result = await target[method](...args); + if (result instanceof Blob && sizeOnly) { + return Response.json({ size: result.size }); + } if (result instanceof Blob) { return Response.json({ bytes: [...new Uint8Array(await result.arrayBuffer())], type: result.type }); } @@ -86,14 +96,30 @@ function rpcRequest( mf: Miniflare, method: string, args: unknown[] = [], - name?: string + name?: string, + sizeOnly = false ): Promise { return mf.dispatchFetch("http://localhost", { method: "POST", - body: JSON.stringify({ method, args, name }), + body: JSON.stringify({ method, args, name, sizeOnly }), }); } +/** Reads a Blob through the binding and returns only its size. */ +async function rpcBlobSize( + mf: Miniflare, + method: string, + args: unknown[], + name: string +): Promise { + const response = await rpcRequest(mf, method, args, name, true); + const result = (await response.json()) as { size: number; error?: string }; + if (!response.ok) { + throw new Error(result.error); + } + return result.size; +} + async function rpc( mf: Miniflare, method: string, @@ -1119,7 +1145,13 @@ test("artifacts: token metadata, revocation and validation", async ({ true ); expect(await rpc(mf, "revokeToken", [readToken.id], "repo")).toBe(false); - expect((await rpc(mf, "listTokens", [], "repo")).total).toBe(1); + const afterRevoke = await rpc(mf, "listTokens", [], "repo"); + expect(afterRevoke.total).toBe(2); + expect( + afterRevoke.tokens.find( + (token: { id: string }) => token.id === readToken.id + ) + ).toMatchObject({ state: "revoked" }); expect( await rpcFailure(mf, "createToken", ["write", 59], "repo") ).toMatchObject({ @@ -1696,3 +1728,189 @@ test("artifacts: disposing the sidecar closes its private listener", async ({ } await expect(fetch(address)).rejects.toThrow(); }); + +test("artifacts: caught binding errors are not logged as uncaught by verbose workerd", async ({ + expect, +}) => { + const logs: string[] = []; + const mf = new Miniflare({ + ...options(), + verbose: true, + handleStructuredLogs: ({ message }) => logs.push(message), + }); + useDispose(mf); + await rpc(mf, "create", ["repo"]); + const failures = [ + await rpcFailure(mf, "get", ["missing"]), + await rpcFailure(mf, "create", ["-bad"]), + await rpcFailure(mf, "readFile", [{ ref: "", path: "x" }], "repo"), + await rpcFailure(mf, "createToken", ["write", 1], "repo"), + ]; + expect(failures.map(({ name, code }) => [name, code])).toEqual([ + ["ArtifactsError", "NOT_FOUND"], + ["ArtifactsError", "INVALID_REPO_NAME"], + ["ArtifactsError", "INVALID_INPUT"], + ["ArtifactsError", "INVALID_TTL"], + ]); + expect(failures[0]).toMatchObject({ numericCode: 10200 }); + expect( + logs.filter((message) => message.includes("uncaught exception")) + ).toEqual([]); +}); + +test("artifacts: the Git port survives a restart with the same persistence", async ({ + expect, +}) => { + const root = await useTmp(); + const log = new TestLog(); + const first = new Miniflare({ + ...options(), + log, + resourcePersistencePath: root, + }); + useDispose(first); + const created = await rpc(first, "create", ["repo"]); + const port = new URL(created.remote).port; + expect(log.logsAtLevel(LogLevel.INFO)).toContain( + `Local Artifacts Git remotes for namespace "test": http://127.0.0.1:${port}/git/test/.git` + ); + await first.dispose(); + + const second = new Miniflare({ ...options(), resourcePersistencePath: root }); + useDispose(second); + const info = await rpc(second, "info", [], "repo"); + expect(info.remote).toBe(created.remote); + const response = await fetch( + `${info.remote}/info/refs?service=git-upload-pack`, + { headers: { Authorization: `Bearer ${created.token}` } } + ); + expect(response.status).toBe(200); + await response.body?.cancel(); +}); + +test("artifacts: pushes reject files over 32 MiB and reads report MEMORY_LIMIT", async ({ + expect, +}) => { + const root = await useTmp(); + const mf = new Miniflare({ ...options(), resourcePersistencePath: root }); + useDispose(mf); + const created = await rpc(mf, "create", ["repo"]); + const source = await useTmp(); + await git(["init", "--initial-branch=main", source]); + // Zeros keep the pack small; the limit applies to the blob's size. + await writeFile( + path.join(source, "large.bin"), + new Uint8Array(MAX_BLOB_BYTES + 1) + ); + await writeFile( + path.join(source, "limit.bin"), + new Uint8Array(MAX_BLOB_BYTES) + ); + await git(["add", "limit.bin"], source); + await git(["commit", "-m", "at the limit"], source); + const push = (ref: string) => + git( + [ + "-c", + `http.extraHeader=Authorization: Bearer ${created.token}`, + "push", + created.remote, + ref, + ], + source + ); + await push("main"); + await git(["add", "large.bin"], source); + await git(["commit", "-m", "over the limit"], source); + await expect(push("HEAD:refs/heads/large")).rejects.toThrow( + /larger than 32 MiB/ + ); + expect( + (await rpc(mf, "log", [{ ref: "main" }], "repo")).map( + (commit: { message: string }) => commit.message + ) + ).toEqual(["at the limit"]); + // A file at the limit still fits through the binding's RPC. + expect( + await rpcBlobSize( + mf, + "readFile", + [{ ref: "main", path: "limit.bin" }], + "repo" + ) + ).toBe(MAX_BLOB_BYTES); + expect(await rpc(mf, "readFile", [{ ref: "large", path: "x" }], "repo")).toBe( + null + ); + + // Repositories written outside the binding can still hold a larger blob. + const [namespaceDirectory] = await readdir(path.join(root, "artifacts")); + const repository = repositoryPath( + path.join(root, "artifacts", namespaceDirectory, "git"), + "test", + "repo" + ); + await git(["push", repository, "HEAD:refs/heads/large"], source); + expect( + await rpcFailure( + mf, + "readFile", + [{ ref: "large", path: "large.bin" }], + "repo" + ) + ).toMatchObject({ code: "MEMORY_LIMIT", numericCode: 10402 }); + const blob = ( + await git(["rev-parse", "HEAD:large.bin"], source) + ).stdout.trim(); + expect(await rpcFailure(mf, "readBlob", [blob], "repo")).toMatchObject({ + code: "MEMORY_LIMIT", + }); +}); + +test("artifacts: list omits remote and log caps its page size", async ({ + expect, +}) => { + const mf = new Miniflare(options()); + useDispose(mf); + await pushFixture(mf, path.join(await useTmp(), "source")); + const { repos } = await rpc(mf, "list"); + expect(repos).toHaveLength(1); + expect(repos[0]).not.toHaveProperty("remote"); + expect(await rpc(mf, "log", [{ limit: 5000 }], "Repo")).toHaveLength(1); + expect(await rpcFailure(mf, "log", [{ limit: 0 }], "Repo")).toMatchObject({ + code: "INVALID_INPUT", + }); +}); + +test("artifacts: disposing a repository handle releases its RPC stubs", async ({ + expect, +}) => { + const script = ` +export default { + async fetch(request, env) { + await env.REPOS.create("repo"); + const repo = await env.REPOS.get("repo"); + const before = (await repo.info()).name; + repo[Symbol.dispose](); + const after = await repo.info().then(() => "callable", (error) => error.message); + return Response.json({ before, after }); + } +};`; + const base = options(); + const mf = new Miniflare({ + ...base, + workers: [ + { + config: { + ...base.workers[0].config, + manifest: singleModuleManifest(script), + }, + }, + ], + }); + useDispose(mf); + expect(await (await mf.dispatchFetch("http://localhost")).json()).toEqual({ + before: "repo", + after: expect.stringContaining("disposed"), + }); +}); diff --git a/packages/miniflare/test/plugins/artifacts/lifecycle.spec.ts b/packages/miniflare/test/plugins/artifacts/lifecycle.spec.ts index 630ff85623..b974483506 100644 --- a/packages/miniflare/test/plugins/artifacts/lifecycle.spec.ts +++ b/packages/miniflare/test/plugins/artifacts/lifecycle.spec.ts @@ -3,7 +3,7 @@ import { once } from "node:events"; import { readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; -import { transform } from "esbuild"; +import { build } from "esbuild"; import { Miniflare } from "miniflare"; import { test } from "vitest"; import { singleModuleManifest, useDispose, useTmp } from "../../test-shared"; @@ -105,7 +105,19 @@ async function clockedWorker(): Promise { source = source.replace(original, replacement); } source = `let testClock = 0;\n${source}\n${clockedFetch}`; - return (await transform(source, { loader: "ts", format: "esm" })).code; + const result = await build({ + stdin: { + contents: source, + resolveDir: path.dirname(workerSource), + sourcefile: workerSource, + loader: "ts", + }, + bundle: true, + format: "esm", + write: false, + external: ["cloudflare:workers"], + }); + return result.outputFiles[0].text; } const clockedFetch = ` @@ -137,8 +149,16 @@ export default { )); } try { - const target = name === undefined ? state : await state.get(name); - return Response.json(await target[method](...args)); + // The namespace object returns outcomes; the wrapped binding unwraps them. + const unwrap = (result) => { + if (result && typeof result === "object" && "ok" in result) { + if (result.ok) return result.value; + throw result.error; + } + return result; + }; + const target = name === undefined ? state : unwrap(await state.get(name)); + return Response.json(unwrap(await target[method](...args))); } catch (error) { return Response.json({ code: error.code, message: error.message }, { status: 400 }); } @@ -259,6 +279,13 @@ async function gitStatus( const start = Date.parse("2026-01-01T00:00:00.000Z"); +async function tokenStates(mf: Miniflare): Promise { + const { tokens } = (await clockRpc(mf, "listTokens", [], "repo")) as { + tokens: { state: string }[]; + }; + return tokens.map(({ state }) => state); +} + test("artifacts: strips authentication headers before forwarding Git requests", async ({ expect, }) => { @@ -376,7 +403,7 @@ test("artifacts: token expiry is exclusive at the exact workerd clock boundary a expect(await gitStatus(first, String(write.plaintext), "upload")).toBe(200); await setClock(first, expiration); - expect((await clockRpc(first, "listTokens", [], "repo")).total).toBe(1); + expect(await tokenStates(first)).toEqual(["active", "expired", "expired"]); expect(await gitStatus(first, String(read.plaintext), "upload")).toBe(401); expect(await gitStatus(first, String(write.plaintext), "receive")).toBe(401); expect(await gitStatus(first, String(read.plaintext), "receive")).toBe(401); @@ -385,7 +412,11 @@ test("artifacts: token expiry is exclusive at the exact workerd clock boundary a const restarted = new Miniflare(clockOptions(script, root)); useDispose(restarted); await setClock(restarted, expiration + 1); - expect((await clockRpc(restarted, "listTokens", [], "repo")).total).toBe(1); + expect(await tokenStates(restarted)).toEqual([ + "active", + "expired", + "expired", + ]); expect(await gitStatus(restarted, String(write.plaintext), "upload")).toBe( 401 ); @@ -409,7 +440,7 @@ test("artifacts: token expiry is exclusive at the exact workerd clock boundary a ).toBe(401); }); -test("artifacts: saving repositories prunes revoked and expired token records", async ({ +test("artifacts: listTokens reports revoked and expired tokens", async ({ expect, }) => { const mf = new Miniflare(clockOptions(await clockedWorker())); @@ -418,18 +449,97 @@ test("artifacts: saving repositories prunes revoked and expired token records", await clockRpc(mf, "create", ["repo"]); const expired = await clockRpc(mf, "createToken", ["read", 60], "repo"); const revoked = await clockRpc(mf, "createToken", ["read", 600], "repo"); + expect(await clockRpc(mf, "revokeToken", [revoked.id], "repo")).toBe(true); await setClock(mf, start + 60_000); const active = await clockRpc(mf, "createToken", ["read", 600], "repo"); - const stored = async () => - (await ( - await clockRequest(mf, { action: "storedTokens", name: "repo" }) - ).json()) as string[]; - expect(await stored()).toHaveLength(3); - expect(await stored()).not.toContain(expired.id); - expect(await stored()).toContain(revoked.id); - expect(await clockRpc(mf, "revokeToken", [revoked.id], "repo")).toBe(true); - expect(await stored()).not.toContain(revoked.id); - expect(await stored()).toContain(active.id); + const listed = (await clockRpc(mf, "listTokens", [], "repo")) as { + total: number; + tokens: { id: string; state: string }[]; + }; + // The creation token plus the three read tokens, newest first. + expect(listed.total).toBe(4); + const states = new Map(listed.tokens.map(({ id, state }) => [id, state])); + expect(listed.tokens[0].id).toBe(active.id); + expect(states.get(String(active.id))).toBe("active"); + expect(states.get(String(revoked.id))).toBe("revoked"); + expect(states.get(String(expired.id))).toBe("expired"); + // Listed history must not let a revoked or expired token authenticate. + expect(await gitStatus(mf, String(expired.plaintext), "upload")).toBe(401); + expect(await gitStatus(mf, String(revoked.plaintext), "upload")).toBe(401); +}); + +test("artifacts: an expired token cannot be revoked and stays expired", async ({ + expect, +}) => { + const mf = new Miniflare(clockOptions(await clockedWorker())); + useDispose(mf); + await setClock(mf, start); + await clockRpc(mf, "create", ["repo"]); + const expired = await clockRpc(mf, "createToken", ["read", 60], "repo"); + await setClock(mf, start + 60_000); + expect(await clockRpc(mf, "revokeToken", [expired.id], "repo")).toBe(false); + const { tokens } = (await clockRpc(mf, "listTokens", [], "repo")) as { + tokens: { id: string; state: string }[]; + }; + expect(tokens.find(({ id }) => id === expired.id)).toMatchObject({ + state: "expired", + }); +}); + +test("artifacts: listTokens keeps active tokens ahead of retained history", async ({ + expect, +}) => { + const mf = new Miniflare(clockOptions(await clockedWorker())); + useDispose(mf); + await setClock(mf, start); + await clockRpc(mf, "create", ["repo"]); + const longLived = await clockRpc( + mf, + "createToken", + ["write", 31_536_000], + "repo" + ); + for (let index = 0; index < 30; index++) { + const token = await clockRpc(mf, "createToken", ["read", 600], "repo"); + await clockRpc(mf, "revokeToken", [token.id], "repo"); + } + const listed = (await clockRpc(mf, "listTokens", [], "repo")) as { + total: number; + tokens: { id: string; state: string }[]; + }; + // The creation token, the long-lived token and 30 revoked tokens. + expect(listed.total).toBe(32); + expect(listed.tokens).toHaveLength(30); + expect(listed.tokens.slice(0, 2).map(({ state }) => state)).toEqual([ + "active", + "active", + ]); + expect(listed.tokens[0].id).toBe(longLived.id); + expect(listed.tokens.slice(2).every(({ state }) => state === "revoked")).toBe( + true + ); +}); + +test("artifacts: saving repositories keeps a bounded token history", async ({ + expect, +}) => { + const mf = new Miniflare(clockOptions(await clockedWorker())); + useDispose(mf); + await setClock(mf, start); + await clockRpc(mf, "create", ["repo"]); + const first = await clockRpc(mf, "createToken", ["read", 60], "repo"); + for (let index = 0; index < 100; index++) { + await clockRpc(mf, "createToken", ["read", 60], "repo"); + } + await setClock(mf, start + 60_000); + // The creation token is still active; 101 read tokens have now expired. + const active = await clockRpc(mf, "createToken", ["read", 600], "repo"); + const stored = (await ( + await clockRequest(mf, { action: "storedTokens", name: "repo" }) + ).json()) as string[]; + expect(stored).toHaveLength(102); + expect(stored).not.toContain(first.id); + expect(stored).toContain(active.id); }); test("artifacts: concurrent same-name creates and forks commit one winner each", async ({ diff --git a/packages/miniflare/test/plugins/browser/index.spec.ts b/packages/miniflare/test/plugins/browser/index.spec.ts index 0d36b8e0a8..077972da07 100644 --- a/packages/miniflare/test/plugins/browser/index.spec.ts +++ b/packages/miniflare/test/plugins/browser/index.spec.ts @@ -12,11 +12,15 @@ import { onTestFinished, describe, test, - type TestOptions, vi, } from "vitest"; import { CERT, KEY } from "../../../src/http/cert"; import { singleModuleManifest, useDispose, useTmp } from "../../test-shared"; +import { + BROWSER_RENDERING_RETRY, + CHROME_INSTALL_TIMEOUT, + retryBrowserStartup, +} from "../../test-shared/browser"; import type { MiniflareOptions } from "miniflare"; async function sendMessage(ws: WebSocket, message: unknown) { @@ -110,23 +114,6 @@ export default { expect(JSON.parse(responseText)).toEqual({ closingState: 2, closedState: 3 }); }); -const BROWSER_RENDERING_RETRY = { - retry: { - condition: - /Chrome readiness probe .* timed out|Test timed out|Failed to launch (the browser process|local browser)/i, - count: 3, - delay: 1_000, - }, -} satisfies TestOptions; - -/** - * Budget for the one-off Chrome download in {@link warmChromeInstall}. - * - * Generous on purpose: a cold CI runner fetches ~150 MB before the first - * browser can start. - */ -const CHROME_INSTALL_TIMEOUT = 10 * 60 * 1_000; - const BROWSER_WORKER_SCRIPT = () => ` export default { async fetch(request, env) { @@ -169,20 +156,7 @@ async function dispatchJson(mf: Miniflare, url: string): Promise { * means the tests only ever see a complete install. */ async function warmChromeInstall(): Promise { - // The first launch of a fresh install is the slowest, and on a loaded - // runner it can outlast Chrome's readiness probe. Retry the same failures, - // as many times, as the tests below do. - const { condition, count, delay } = BROWSER_RENDERING_RETRY.retry; - for (let attempt = 0; ; attempt++) { - try { - return await launchWarmupBrowser(); - } catch (e) { - if (attempt >= count || !condition.test(String(e))) { - throw e; - } - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } + await retryBrowserStartup(launchWarmupBrowser); } async function launchWarmupBrowser(): Promise { @@ -214,7 +188,7 @@ async function launchWarmupBrowser(): Promise { } } -// We need to run browser rendering tests in a serial manner to avoid a race condition installing the browser. +// Keep browser session lifecycle tests serial within this file. describe("browser rendering", { concurrent: false, timeout: 20_000 }, () => { beforeAll(warmChromeInstall, CHROME_INSTALL_TIMEOUT); diff --git a/packages/miniflare/test/plugins/browser/quick-actions.spec.ts b/packages/miniflare/test/plugins/browser/quick-actions.spec.ts index 383d49c188..7f93d3038b 100644 --- a/packages/miniflare/test/plugins/browser/quick-actions.spec.ts +++ b/packages/miniflare/test/plugins/browser/quick-actions.spec.ts @@ -19,6 +19,10 @@ import { singleModuleManifest, TestLog, } from "../../test-shared"; +import { + CHROME_INSTALL_TIMEOUT, + retryBrowserStartup, +} from "../../test-shared/browser"; import type { Browser } from "@cloudflare/puppeteer"; import type { AddressInfo } from "node:net"; @@ -64,8 +68,6 @@ const PAGE = ` Top `; -const CHROME_INSTALL_TIMEOUT = 10 * 60 * 1_000; - let mf: Miniflare; let log: TestLog; let origin: string; @@ -125,8 +127,10 @@ describe( ], }); // Launches (and on a cold machine downloads) Chrome before timed tests - const warm = await quickAction("content", { html: "

warm

" }); - assert.strictEqual(warm.status, 200, await warm.text()); + await retryBrowserStartup(async () => { + const warm = await quickAction("content", { html: "

warm

" }); + assert.strictEqual(warm.status, 200, await warm.text()); + }); }, CHROME_INSTALL_TIMEOUT); afterAll(async () => { diff --git a/packages/miniflare/test/plugins/browser/startup-retry.spec.ts b/packages/miniflare/test/plugins/browser/startup-retry.spec.ts new file mode 100644 index 0000000000..d2d6333055 --- /dev/null +++ b/packages/miniflare/test/plugins/browser/startup-retry.spec.ts @@ -0,0 +1,76 @@ +import assert from "node:assert"; +import { afterEach, beforeEach, test, vi } from "vitest"; +import { retryBrowserStartup } from "../../test-shared/browser"; + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +test("retries a Chrome readiness failure returned by a quick-action warm-up", async ({ + expect, +}) => { + const quickAction = vi + .fn<() => Promise>() + .mockResolvedValueOnce( + Response.json( + { + success: false, + errors: [ + { + code: 6002, + detail: + "Chrome readiness probe at http://127.0.0.1:51397/json/version timed out after 5000ms", + }, + ], + }, + { status: 422 } + ) + ) + .mockResolvedValueOnce(new Response("

warm

")); + const warmup = retryBrowserStartup(async () => { + const response = await quickAction(); + assert.strictEqual(response.status, 200, await response.text()); + }); + const completed = expect(warmup).resolves.toBeUndefined(); + await vi.advanceTimersByTimeAsync(999); + expect(quickAction).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + await completed; + expect(quickAction).toHaveBeenCalledTimes(2); +}); + +test("preserves the final launch error after exhausting the startup retries", async ({ + expect, +}) => { + const error = new Error("Failed to launch the browser process"); + const launch = vi.fn<() => Promise>().mockRejectedValue(error); + const failed = expect(retryBrowserStartup(launch)).rejects.toBe(error); + await vi.runAllTimersAsync(); + await failed; + expect(launch).toHaveBeenCalledTimes(4); +}); + +test("does not retry an unrelated unsuccessful warm-up response", async ({ + expect, +}) => { + const quickAction = vi + .fn<() => Promise>() + .mockResolvedValue( + Response.json( + { success: false, errors: [{ message: "Invalid options" }] }, + { status: 400 } + ) + ); + await expect( + retryBrowserStartup(async () => { + const response = await quickAction(); + assert.strictEqual(response.status, 200, await response.text()); + }) + ).rejects.toThrow("Invalid options"); + expect(quickAction).toHaveBeenCalledTimes(1); + expect(vi.getTimerCount()).toBe(0); +}); diff --git a/packages/miniflare/test/plugins/k2/index.spec.ts b/packages/miniflare/test/plugins/k2/index.spec.ts index a7ab919208..3071159f35 100644 --- a/packages/miniflare/test/plugins/k2/index.spec.ts +++ b/packages/miniflare/test/plugins/k2/index.spec.ts @@ -56,7 +56,7 @@ function producerWorker(proxyUrl?: URL, remote?: boolean) { env: { ORDERS: { type: "k2" as const, - stream, + id: stream, ...(remote === undefined ? {} : { dev: { remote } }), }, }, diff --git a/packages/miniflare/test/plugins/pipelines/index.spec.ts b/packages/miniflare/test/plugins/pipelines/index.spec.ts index 2f6ad2e0ea..c8fc91dd27 100644 --- a/packages/miniflare/test/plugins/pipelines/index.spec.ts +++ b/packages/miniflare/test/plugins/pipelines/index.spec.ts @@ -15,7 +15,7 @@ test("supports declaring pipelines", async () => { return new Response(null, { status: 204 }); }, }`), - env: { PIPELINE: { type: "pipeline", name: "PIPELINE" } }, + env: { PIPELINE: { type: "pipeline", streamId: "PIPELINE" } }, }, }, ], diff --git a/packages/miniflare/test/test-shared/browser.ts b/packages/miniflare/test/test-shared/browser.ts new file mode 100644 index 0000000000..d8b877d9b0 --- /dev/null +++ b/packages/miniflare/test/test-shared/browser.ts @@ -0,0 +1,39 @@ +import type { TestOptions } from "vitest"; + +/** Retry transient Chrome startup failures on loaded CI runners. */ +export const BROWSER_RENDERING_RETRY = { + retry: { + condition: + /Chrome readiness probe .* timed out|Test timed out|Failed to launch (the browser process|local browser)/i, + count: 3, + delay: 1_000, + }, +} satisfies TestOptions; + +/** Allow the first browser warm-up to download Chrome on a cold runner. */ +export const CHROME_INSTALL_TIMEOUT = 10 * 60 * 1_000; + +/** + * Warm Chrome before timed tests, retrying only recognized startup failures. + * + * A generous hook timeout accommodates downloads, but does not extend Chrome's + * readiness deadline. Check unsuccessful responses inside `warmup` and include + * their bodies in the error so the retry condition can recognize launch failures. + * + * @param warmup - Launch Chrome and check that it is ready for the tests. + */ +export async function retryBrowserStartup( + warmup: () => Promise +): Promise { + const { condition, count, delay } = BROWSER_RENDERING_RETRY.retry; + for (let attempt = 0; ; attempt++) { + try { + return await warmup(); + } catch (e) { + if (attempt >= count || !condition.test(String(e))) { + throw e; + } + await new Promise((resolve) => setTimeout(resolve, delay)); + } + } +} diff --git a/packages/mock-npm-registry/README.md b/packages/mock-npm-registry/README.md index a3ab53909e..78c95658be 100644 --- a/packages/mock-npm-registry/README.md +++ b/packages/mock-npm-registry/README.md @@ -31,6 +31,30 @@ are published under that dist-tag, such as `beta`. Other packages use `latest`. This lets tests install the local `@cloudflare/vite-plugin@beta` while stable Vite plugin versions remain available through the public npm registry. +### Versions of local dependencies + +Only the packages passed to `startMockNpmRegistry()` are published under their +real versions. Their local dependencies are published as `0.0.0-local.` +prereleases, such as `@cloudflare/config@0.0.0-local.0.32.1` or +`miniflare@0.0.0-local.5.20261113.0-beta`, with the `local` dist-tag. The local +packages depend on each other by these exact versions. + +This is because an unreleased workspace package has the same version as its +latest npm release. A package installed from npm that depends on that exact +version, such as a published `cf` pinning `@cloudflare/config`, would otherwise +get the local copy, with any unreleased breaking changes. Instead it gets the +copy from npm, and so do `@latest` and ranges such as `^0.32.1` or +`^5.20261113.0-beta`. (A suffix such as `5.20261113.0-beta.local` wouldn't be +enough, since prerelease ranges match later prereleases of the same version.) + +If a test installs a local package directly by version or dist-tag (for +example `wrangler@latest`), pass that package to `startMockNpmRegistry()` too. + +The repository's files aren't modified. Each package is packed with `pnpm pack`, +which resolves `workspace:*` dependencies to exact versions, and its packed +`package.json` is rewritten before publishing. Local packages must depend on +each other with `workspace:*`. + ## Debugging If you are having problems with the mock npm registry, you can get additional debug logging by setting the `NODE_DEBUG` environment variable. diff --git a/packages/mock-npm-registry/package.json b/packages/mock-npm-registry/package.json index 5b2b171757..017e0cd175 100644 --- a/packages/mock-npm-registry/package.json +++ b/packages/mock-npm-registry/package.json @@ -21,8 +21,11 @@ "devDependencies": { "@cloudflare/workers-utils": "workspace:*", "@types/node": "catalog:default", + "@types/semver": "^7.5.1", "@verdaccio/types": "^10.8.0", "get-port": "^7.0.0", + "modern-tar": "^0.8.6", + "semver": "^7.7.1", "tree-kill": "catalog:default", "ts-dedent": "^2.2.0", "typescript": "catalog:default", diff --git a/packages/mock-npm-registry/src/index.ts b/packages/mock-npm-registry/src/index.ts index 5724e8ec7c..305abd9f41 100644 --- a/packages/mock-npm-registry/src/index.ts +++ b/packages/mock-npm-registry/src/index.ts @@ -8,7 +8,9 @@ import getPort from "get-port"; import treeKill from "tree-kill"; import { dedent } from "ts-dedent"; import { ConfigBuilder } from "verdaccio"; +import { getLocalVersion } from "./local-versions.js"; import { publishPackage, restoreLatestTag } from "./publish-package.js"; +import type { LocalVersion } from "./local-versions.js"; export { overrideConfigEnv } from "./config-env.js"; @@ -27,6 +29,12 @@ const EXIT_TIMEOUT = 10_000; * The `targetPackages` will be published to the local npm repository along with any of their local dependencies. * Any non-local dependencies will continue to be pulled from the public npm registry. * + * The target packages keep their real versions, so tests can install them by version or dist-tag. + * Their local dependencies are published under `0.0.0-local.` versions (see `getLocalVersion()`), + * which the local packages depend on exactly. A public package that depends on the same version as + * a local package, such as a published `cf` pinning `@cloudflare/config`, therefore gets the public + * copy rather than unreleased local changes. + * * @param targetPackages a list of primary packages to publish to the local registry. * @returns a function that stops and deletes the registry */ @@ -41,6 +49,7 @@ export async function startMockNpmRegistry(...targetPackages: string[]) { // The packages to publish to the local npm repository. const pkgs = await getPackagesToPublish(targetPackages); + const localVersions = await getLocalVersions(pkgs, new Set(targetPackages)); const configPath = await writeVerdaccioConfig( registryPath, @@ -54,7 +63,10 @@ export async function startMockNpmRegistry(...targetPackages: string[]) { ); for (const [pkg, pkgPath] of pkgs.entries()) { - console.log(` - ${pkg} (${pkgPath})`); + const localVersion = localVersions.get(pkg); + console.log( + ` - ${pkg}${localVersion ? `@${localVersion.to}` : ""} (${pkgPath})` + ); } let stopServer = await startVerdaccioServer(configPath); @@ -140,15 +152,18 @@ export async function startMockNpmRegistry(...targetPackages: string[]) { debugLog(execSync("pnpm config list", { encoding: "utf8" })); } - const prereleasePackages: string[] = []; + // Packages published under a dist-tag other than `latest`. Verdaccio would + // otherwise point their `latest` tag at the local version (see + // `restoreLatestTag()`). + const nonLatestPackages: string[] = []; for (const [pkgName, pkgPath] of pkgs) { debugLog("Publishing package " + pkgName); - const tag = await publishPackage( - path.join(repoRoot, pkgPath), - debugLog.enabled ? "inherit" : "ignore" - ); + const { tag } = await publishPackage(path.join(repoRoot, pkgPath), { + stdio: debugLog.enabled ? "inherit" : "ignore", + localVersions, + }); if (tag !== "latest") { - prereleasePackages.push(pkgName); + nonLatestPackages.push(pkgName); } } @@ -159,7 +174,7 @@ export async function startMockNpmRegistry(...targetPackages: string[]) { }); await stopServer(); stopServer = await startVerdaccioServer(configPath); - for (const name of prereleasePackages) { + for (const name of nonLatestPackages) { await restoreLatestTag(name, `http://localhost:${registryPort}/`); } @@ -181,6 +196,36 @@ export async function startMockNpmRegistry(...targetPackages: string[]) { type PackageInfo = { name: string; path: string }; +/** + * Work out the versions to publish local dependency packages under. + * + * Target packages keep their real versions. Every other package gets a local + * version, so that it can't be mistaken for the public npm release. + * + * @param pkgs A map (name => path) of the packages to publish. + * @param targetPackages The names of the entry-point packages. + * @returns A map (name => versions) of the packages to rename. + */ +async function getLocalVersions( + pkgs: Map, + targetPackages: Set +) { + const localVersions = new Map(); + for (const [name, pkgPath] of pkgs) { + if (targetPackages.has(name)) { + continue; + } + const { version } = JSON.parse( + await fs.readFile(path.join(repoRoot, pkgPath, "package.json"), "utf8") + ) as { version: string }; + localVersions.set(name, { + from: version, + to: getLocalVersion(version), + }); + } + return localVersions; +} + /** * Generate a map (name => path) of local packages that need to be published to the mock npm registry * from a list of "entry-point" package `names`. diff --git a/packages/mock-npm-registry/src/local-versions.ts b/packages/mock-npm-registry/src/local-versions.ts new file mode 100644 index 0000000000..891034050f --- /dev/null +++ b/packages/mock-npm-registry/src/local-versions.ts @@ -0,0 +1,105 @@ +/** + * The dist-tag that local copies of dependency packages are published under. + * + * They aren't published as `latest`, so that `@latest` still resolves + * to the public npm release. + */ +export const LOCAL_DIST_TAG = "local"; + +/** + * The manifest fields whose entries are installed alongside a package, and + * therefore must point at the local versions of other local packages. + */ +const DEPENDENCY_FIELDS = [ + "dependencies", + "optionalDependencies", + "peerDependencies", +] as const; + +export type PackageManifest = { + name: string; + version: string; + dependencies?: Record; + optionalDependencies?: Record; + peerDependencies?: Record; + [field: string]: unknown; +}; + +/** A package's real version and the version it is published under locally. */ +export type LocalVersion = { from: string; to: string }; + +/** + * Create the version for a local copy of a package. + * + * Unreleased workspace packages share their version with the latest npm + * release. Publishing them under that version would mean that any public + * package which pins it exactly (such as `cf`, which pins `@cloudflare/config`) + * gets the local, possibly breaking, copy. + * + * Appending a prerelease suffix to the real version isn't enough: a range that + * includes a prerelease, such as `^5.20261113.0-beta`, also matches any later + * prerelease of the same version, such as `5.20261113.0-beta.local`. So, like + * Changesets snapshot versions, local copies are published as `0.0.0-` + * prereleases, which no range for the real version can match. The real version + * is kept in the prerelease identifiers so that it stays readable. + * + * @param version The package's real version, such as `1.2.3` or `1.2.3-beta`. + * @returns `0.0.0-local.`, such as `0.0.0-local.1.2.3-beta`. + */ +export function getLocalVersion(version: string): string { + return `0.0.0-local.${version}`; +} + +/** + * Point a packed manifest at the local versions of local packages. + * + * `pnpm pack` has already replaced each `workspace:*` specifier with the + * dependency's exact real version, so any dependency on a renamed package must + * still be that version. Anything else (a range, or an alias) can't be safely + * rewritten, so it is reported as an error rather than left pointing at npm. + * + * @param manifest The `package.json` contents from a packed tarball. + * @param localVersions The renamed packages, keyed by name. + * @returns A copy of the manifest with the local versions applied. + */ +export function rewriteManifest( + manifest: PackageManifest, + localVersions: ReadonlyMap +): PackageManifest { + const result: PackageManifest = { ...manifest }; + + const own = localVersions.get(manifest.name); + if (own) { + if (manifest.version !== own.from) { + throw new Error( + `Expected ${manifest.name} to be version ${own.from}, found ${manifest.version}` + ); + } + result.version = own.to; + } + + for (const field of DEPENDENCY_FIELDS) { + const dependencies = manifest[field]; + if (dependencies === undefined) { + continue; + } + const rewritten = { ...dependencies }; + for (const [name, specifier] of Object.entries(dependencies)) { + const local = localVersions.get(name); + if (local === undefined) { + continue; + } + if (specifier !== local.from) { + throw new Error( + `${manifest.name} has ${field} "${name}": "${specifier}", ` + + `but the local copy of ${name} can only replace the exact version ${local.from}. ` + + `Use a "workspace:*" specifier for local packages.` + ); + } + rewritten[name] = local.to; + } + result[field] = rewritten; + } + + return result; +} diff --git a/packages/mock-npm-registry/src/publish-package.ts b/packages/mock-npm-registry/src/publish-package.ts index ee2a075152..2bbb0c10d6 100644 --- a/packages/mock-npm-registry/src/publish-package.ts +++ b/packages/mock-npm-registry/src/publish-package.ts @@ -1,39 +1,107 @@ import { execSync } from "node:child_process"; -import { readFile } from "node:fs/promises"; +import { createReadStream } from "node:fs"; +import { + mkdir, + mkdtemp, + readdir, + readFile, + realpath, + writeFile, +} from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; +import { pipeline } from "node:stream/promises"; +import { createGunzip } from "node:zlib"; +import { removeDir } from "@cloudflare/workers-utils"; +import { unpackTar } from "modern-tar/fs"; import { overrideConfigEnv } from "./config-env.js"; +import { LOCAL_DIST_TAG, rewriteManifest } from "./local-versions.js"; +import type { LocalVersion, PackageManifest } from "./local-versions.js"; -type PackageJson = { +type PackageJson = PackageManifest & { "workers-sdk"?: { npmPrerelease?: { tag: string }; }; }; /** - * Publish a workspace package using its configured npm prerelease tag, or `latest`. + * Publish a workspace package to the registry configured in the environment. + * + * The package is packed (which resolves its `workspace:*` dependencies to exact + * versions), then its manifest is rewritten so that it, and its dependencies on + * other local packages, use the versions in `localVersions`. The package's own + * files in the repository are never modified. + * + * A package that is renamed in `localVersions` is published under the `local` + * dist-tag. Otherwise it uses its configured npm prerelease tag, or `latest`. * * @param packagePath The absolute path to the package directory. - * @param stdio Whether to display the publish command's output. - * @returns The dist-tag used to publish the package. + * @param options.stdio Whether to display the pack and publish commands' output. + * @param options.localVersions The local packages to rename, keyed by name. + * @returns The published version and the dist-tag it was published under. */ export async function publishPackage( packagePath: string, - stdio: "inherit" | "ignore" -) { - const pkg: PackageJson = JSON.parse( - await readFile(path.join(packagePath, "package.json"), "utf8") - ); - const tag = pkg["workers-sdk"]?.npmPrerelease?.tag ?? "latest"; - execSync("pnpm publish", { - cwd: packagePath, + { stdio, - env: overrideConfigEnv(process.env, { tag }).env, - }); - return tag; + localVersions = new Map(), + }: { + stdio: "inherit" | "ignore"; + localVersions?: ReadonlyMap; + } +): Promise<{ version: string; tag: string }> { + const workDir = await realpath( + await mkdtemp(path.join(os.tmpdir(), "mock-npm-publish-")) + ); + try { + // eslint-disable-next-line workers-sdk/no-unsafe-command-execution -- workDir is a temporary directory we created + execSync(`pnpm pack --pack-destination "${workDir}"`, { + cwd: packagePath, + stdio, + }); + const tarballs = (await readdir(workDir)).filter((file) => + file.endsWith(".tgz") + ); + if (tarballs.length !== 1) { + throw new Error( + `Expected \`pnpm pack\` to create one tarball for ${packagePath}, found ${tarballs.length}` + ); + } + + const contentsPath = path.join(workDir, "package"); + await mkdir(contentsPath); + await pipeline( + createReadStream(path.join(workDir, tarballs[0])), + createGunzip(), + unpackTar(contentsPath, { strip: 1 }) + ); + + const manifestPath = path.join(contentsPath, "package.json"); + const packed: PackageJson = JSON.parse( + await readFile(manifestPath, "utf8") + ); + const manifest = rewriteManifest(packed, localVersions); + await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n"); + + const tag = localVersions.has(packed.name) + ? LOCAL_DIST_TAG + : (packed["workers-sdk"]?.npmPrerelease?.tag ?? "latest"); + // The lifecycle scripts already ran when the package was packed. Git + // checks don't apply, since the contents aren't in a repository. + execSync("pnpm publish --ignore-scripts --no-git-checks", { + cwd: contentsPath, + stdio, + env: overrideConfigEnv(process.env, { tag }).env, + }); + return { version: manifest.version, tag }; + } finally { + await removeDir(workDir); + } } /** - * Restore a prerelease package's public `latest` tag after enabling npm uplinks. + * Restore a package's public `latest` tag after enabling npm uplinks, when it + * was published under another dist-tag (a prerelease tag, or `local`). * * Verdaccio assigns `latest` to the first local version, even for a prerelease, * and keeps whichever tag value is greater when merging upstream metadata. diff --git a/packages/mock-npm-registry/tests/local-versions.test.ts b/packages/mock-npm-registry/tests/local-versions.test.ts new file mode 100644 index 0000000000..164204efb2 --- /dev/null +++ b/packages/mock-npm-registry/tests/local-versions.test.ts @@ -0,0 +1,137 @@ +import semver from "semver"; +import { describe, test } from "vitest"; +import { getLocalVersion, rewriteManifest } from "../src/local-versions"; +import type { LocalVersion } from "../src/local-versions"; + +describe("getLocalVersion", () => { + test("puts the real version in a 0.0.0 prerelease", ({ expect }) => { + expect(getLocalVersion("0.32.1")).toBe("0.0.0-local.0.32.1"); + expect(getLocalVersion("5.20261113.0-beta")).toBe( + "0.0.0-local.5.20261113.0-beta" + ); + expect(getLocalVersion("2.0.0-beta.v.17")).toBe( + "0.0.0-local.2.0.0-beta.v.17" + ); + }); + + test("doesn't satisfy ranges for the real version", ({ expect }) => { + const cases = [ + ["0.32.1", "^0.32.1"], + ["0.32.1", "^0.32.1-beta.0"], + ["0.32.1", ">=0.32.1-0"], + ["5.20261113.0-beta", "^5.20261113.0-beta"], + ["5.20261113.0-beta", ">=5.20261113.0-beta"], + ["5.20261113.0-beta", "~5.20261113.0-0"], + ] as const; + for (const [version, range] of cases) { + const localVersion = getLocalVersion(version); + expect(semver.valid(localVersion), localVersion).toBe(localVersion); + expect(semver.satisfies(version, range), `${version} ${range}`).toBe( + true + ); + expect( + semver.satisfies(localVersion, range), + `${localVersion} ${range}` + ).toBe(false); + } + }); +}); + +describe("rewriteManifest", () => { + const localVersions = new Map([ + ["@cloudflare/config", { from: "0.32.1", to: "0.0.0-local.0.32.1" }], + [ + "miniflare", + { from: "5.20261113.0-beta", to: "0.0.0-local.5.20261113.0-beta" }, + ], + ]); + + test("renames the package itself", ({ expect }) => { + const manifest = rewriteManifest( + { name: "@cloudflare/config", version: "0.32.1", type: "module" }, + localVersions + ); + expect(manifest).toEqual({ + name: "@cloudflare/config", + version: "0.0.0-local.0.32.1", + type: "module", + }); + }); + + test("points dependencies on local packages at their local versions", ({ + expect, + }) => { + const manifest = rewriteManifest( + { + name: "@cloudflare/vite-plugin", + version: "2.0.0-beta.v.17", + dependencies: { + "@cloudflare/config": "0.32.1", + miniflare: "5.20261113.0-beta", + ws: "8.21.0", + }, + optionalDependencies: { miniflare: "5.20261113.0-beta" }, + peerDependencies: { "@cloudflare/config": "0.32.1", vite: "^8.0.0" }, + devDependencies: { "@cloudflare/config": "0.32.1" }, + }, + localVersions + ); + expect(manifest).toEqual({ + name: "@cloudflare/vite-plugin", + // Packages that aren't renamed keep their real version. + version: "2.0.0-beta.v.17", + dependencies: { + "@cloudflare/config": "0.0.0-local.0.32.1", + miniflare: "0.0.0-local.5.20261113.0-beta", + ws: "8.21.0", + }, + optionalDependencies: { miniflare: "0.0.0-local.5.20261113.0-beta" }, + peerDependencies: { + "@cloudflare/config": "0.0.0-local.0.32.1", + vite: "^8.0.0", + }, + // devDependencies aren't installed by consumers. + devDependencies: { "@cloudflare/config": "0.32.1" }, + }); + }); + + test("doesn't modify the input", ({ expect }) => { + const input = { + name: "wrangler", + version: "4.162.0", + dependencies: { miniflare: "5.20261113.0-beta" }, + }; + rewriteManifest(input, localVersions); + expect(input).toEqual({ + name: "wrangler", + version: "4.162.0", + dependencies: { miniflare: "5.20261113.0-beta" }, + }); + }); + + test("rejects a dependency on a local package that isn't its exact version", ({ + expect, + }) => { + expect(() => + rewriteManifest( + { + name: "wrangler", + version: "4.162.0", + dependencies: { "@cloudflare/config": "^0.32.1" }, + }, + localVersions + ) + ).toThrow( + 'wrangler has dependencies "@cloudflare/config": "^0.32.1", but the local copy of @cloudflare/config can only replace the exact version 0.32.1.' + ); + }); + + test("rejects a package whose packed version is unexpected", ({ expect }) => { + expect(() => + rewriteManifest( + { name: "@cloudflare/config", version: "0.33.0" }, + localVersions + ) + ).toThrow("Expected @cloudflare/config to be version 0.32.1, found 0.33.0"); + }); +}); diff --git a/packages/mock-npm-registry/tests/publish-package.test.ts b/packages/mock-npm-registry/tests/publish-package.test.ts index 1f0fa53039..edf13b957f 100644 --- a/packages/mock-npm-registry/tests/publish-package.test.ts +++ b/packages/mock-npm-registry/tests/publish-package.test.ts @@ -1,13 +1,138 @@ import { fork } from "node:child_process"; import { once } from "node:events"; -import { mkdirSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; import path from "node:path"; import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; import getPort from "get-port"; -import { describe, test, vi } from "vitest"; +import { describe, onTestFinished, test, vi } from "vitest"; import { packageManager } from "../../../package.json"; import { publishPackage, restoreLatestTag } from "../src/publish-package"; +import type { LocalVersion } from "../src/local-versions"; + +const name = "@cloudflare/mock-npm-registry-dist-tag-test"; + +/** + * Start a fake upstream npm registry that has a single stable version (1.0.0) + * of the test package. + */ +async function startUpstream() { + const upstreamPort = await getPort(); + const upstreamUrl = `http://127.0.0.1:${upstreamPort}/`; + const stable = { + name, + version: "1.0.0", + dist: { + tarball: `${upstreamUrl}stable.tgz`, + shasum: "0".repeat(40), + }, + }; + const upstream = createServer((request, response) => { + response.setHeader("content-type", "application/json"); + response.end( + JSON.stringify( + request.url?.endsWith("/latest") + ? stable + : { + name, + versions: { "1.0.0": stable }, + "dist-tags": { latest: "1.0.0" }, + } + ) + ); + }); + upstream.listen(upstreamPort, "127.0.0.1"); + await once(upstream, "listening"); + onTestFinished( + () => + new Promise((resolve, reject) => { + upstream.close((error) => (error ? reject(error) : resolve())); + }) + ); + return upstreamUrl; +} + +/** + * Configure a local Verdaccio registry, which proxies to `upstreamUrl` when + * started with uplinks. + */ +async function setUpRegistry(upstreamUrl: string) { + const port = await getPort(); + const registry = `http://127.0.0.1:${port}/`; + const configPath = path.resolve("verdaccio.yaml"); + const npmrc = path.resolve(".npmrc"); + writeFileSync( + npmrc, + `registry=${registry}\n//127.0.0.1:${port}/:_authToken=xxxx\ngit-checks=false\n` + ); + vi.stubEnv("NPM_CONFIG_USERCONFIG", npmrc); + vi.stubEnv("npm_config_userconfig", npmrc); + vi.stubEnv("npm_config_registry", registry); + + let stopCurrent: (() => Promise) | undefined; + onTestFinished(() => stopCurrent?.()); + + async function start(withUplinks: boolean) { + await stopCurrent?.(); + writeFileSync( + configPath, + JSON.stringify({ + listen: `127.0.0.1:${port}`, + storage: path.resolve("storage"), + uplinks: { npmJS: { url: upstreamUrl } }, + packages: { + "**": { + access: "$all", + publish: "$all", + ...(withUplinks ? { proxy: "npmJS" } : {}), + }, + }, + log: { type: "stdout", format: "pretty", level: "error" }, + }) + ); + const server = fork( + require.resolve("verdaccio/bin/verdaccio"), + ["-c", configPath], + { stdio: "ignore" } + ); + const exited = new Promise((resolve) => { + server.once("exit", () => resolve()); + }); + await once(server, "message"); + stopCurrent = async () => { + server.kill(); + await exited; + stopCurrent = undefined; + }; + } + + return { registry, start }; +} + +/** Write a package fixture to publish. */ +function writeFixture(manifest: Record) { + const packagePath = path.resolve("package"); + mkdirSync(packagePath, { recursive: true }); + writeFileSync(path.join(packagePath, "index.js"), "module.exports = {};\n"); + writeFileSync( + path.join(packagePath, "package.json"), + JSON.stringify({ packageManager, files: ["index.js"], ...manifest }) + ); + return packagePath; +} + +async function getMetadata(registry: string, packageName: string) { + const response = await fetch( + new URL(encodeURIComponent(packageName), registry) + ); + return (await response.json()) as { + "dist-tags": Record; + versions: Record< + string, + { dependencies?: Record; dist: { tarball: string } } + >; + }; +} describe("publishPackage", () => { runInTempDir(); @@ -15,132 +140,120 @@ describe("publishPackage", () => { test("keeps prerelease tags local and latest on the upstream stable version", async ({ expect, }) => { - const name = "@cloudflare/mock-npm-registry-dist-tag-test"; - const upstreamPort = await getPort(); - const upstreamUrl = `http://127.0.0.1:${upstreamPort}/`; - const stable = { + const upstreamUrl = await startUpstream(); + const { registry, start } = await setUpRegistry(upstreamUrl); + await start(false); + + async function publishFixture( + version: string, + tag?: string, + packageName = name + ) { + const packagePath = writeFixture({ + name: packageName, + version, + publishConfig: { registry }, + "workers-sdk": tag + ? { npmPrerelease: { tag, numbered: true } } + : { prerelease: true }, + }); + return publishPackage(packagePath, { stdio: "ignore" }); + } + expect( + await publishFixture("1.0.0", undefined, "stable-test-package") + ).toEqual({ version: "1.0.0", tag: "latest" }); + expect(await publishFixture("2.0.0-beta.0", "beta")).toEqual({ + version: "2.0.0-beta.0", + tag: "beta", + }); + expect(await publishFixture("2.0.0-rc.0", "rc")).toEqual({ + version: "2.0.0-rc.0", + tag: "rc", + }); + + await expect( + publishPackage(path.resolve("package"), { stdio: "ignore" }) + ).rejects.toThrow("pnpm publish"); + + await start(true); + await restoreLatestTag(name, registry, upstreamUrl); + + const tagsUrl = new URL( + `/-/package/${encodeURIComponent(name)}/dist-tags`, + registry + ); + const tags = await fetch(tagsUrl); + expect(await tags.json()).toEqual({ + latest: "1.0.0", + beta: "2.0.0-beta.0", + rc: "2.0.0-rc.0", + }); + }); + + test("publishes local dependencies alongside the upstream version they share", async ({ + expect, + }) => { + const upstreamUrl = await startUpstream(); + const { registry, start } = await setUpRegistry(upstreamUrl); + await start(false); + + // The local package has the same version as its upstream release. + const localVersions = new Map([ + [name, { from: "1.0.0", to: "0.0.0-local.1.0.0" }], + ]); + const dependencyManifest = { name, version: "1.0.0", - dist: { - tarball: `${upstreamUrl}stable.tgz`, - shasum: "0".repeat(40), - }, + publishConfig: { registry }, }; - const upstream = createServer((request, response) => { - response.setHeader("content-type", "application/json"); - response.end( - JSON.stringify( - request.url?.endsWith("/latest") - ? stable - : { - name, - versions: { "1.0.0": stable }, - "dist-tags": { latest: "1.0.0" }, - } - ) - ); + const dependencyPath = writeFixture(dependencyManifest); + expect( + await publishPackage(dependencyPath, { stdio: "ignore", localVersions }) + ).toEqual({ version: "0.0.0-local.1.0.0", tag: "local" }); + // The package's own files are left alone. + expect( + JSON.parse( + readFileSync(path.join(dependencyPath, "package.json"), "utf8") + ) + ).toMatchObject(dependencyManifest); + + // A target package depends on the local version of its dependency. + const targetPath = writeFixture({ + name: "target-test-package", + version: "3.0.0", + publishConfig: { registry }, + // `pnpm pack` would resolve `workspace:*` to this exact version. + dependencies: { [name]: "1.0.0" }, }); - upstream.listen(upstreamPort, "127.0.0.1"); - await once(upstream, "listening"); - const port = await getPort(); - const registry = `http://127.0.0.1:${port}/`; - const configPath = path.resolve("verdaccio.yaml"); - const npmrc = path.resolve(".npmrc"); - writeFileSync( - npmrc, - `registry=${registry}\n//127.0.0.1:${port}/:_authToken=xxxx\ngit-checks=false\n` + expect( + await publishPackage(targetPath, { stdio: "ignore", localVersions }) + ).toEqual({ version: "3.0.0", tag: "latest" }); + + await start(true); + await restoreLatestTag(name, registry, upstreamUrl); + + const target = await getMetadata(registry, "target-test-package"); + expect(target["dist-tags"]).toEqual({ latest: "3.0.0" }); + expect(target.versions["3.0.0"].dependencies).toEqual({ + [name]: "0.0.0-local.1.0.0", + }); + + // Anything that depends on `1.0.0`, or `latest`, gets the upstream copy. + const dependency = await getMetadata(registry, name); + expect(dependency["dist-tags"]).toEqual({ + latest: "1.0.0", + local: "0.0.0-local.1.0.0", + }); + expect(Object.keys(dependency.versions).sort()).toEqual([ + "0.0.0-local.1.0.0", + "1.0.0", + ]); + // Verdaccio proxies upstream tarballs under their upstream file name. + expect(dependency.versions["1.0.0"].dist.tarball).toMatch( + /\/-\/stable\.tgz$/ + ); + expect(dependency.versions["0.0.0-local.1.0.0"].dist.tarball).toMatch( + /\/-\/mock-npm-registry-dist-tag-test-0\.0\.0-local\.1\.0\.0\.tgz$/ ); - vi.stubEnv("NPM_CONFIG_USERCONFIG", npmrc); - vi.stubEnv("npm_config_userconfig", npmrc); - vi.stubEnv("npm_config_registry", registry); - - async function startRegistry(withUplinks: boolean) { - writeFileSync( - configPath, - JSON.stringify({ - listen: `127.0.0.1:${port}`, - storage: path.resolve("storage"), - uplinks: { npmJS: { url: upstreamUrl } }, - packages: { - "**": { - access: "$all", - publish: "$all", - ...(withUplinks ? { proxy: "npmJS" } : {}), - }, - }, - log: { type: "stdout", format: "pretty", level: "error" }, - }) - ); - const server = fork( - require.resolve("verdaccio/bin/verdaccio"), - ["-c", configPath], - { stdio: "ignore" } - ); - const exited = new Promise((resolve) => { - server.once("exit", () => resolve()); - }); - await once(server, "message"); - return async function stop() { - server.kill(); - await exited; - }; - } - let stopRegistry = await startRegistry(false); - try { - const packagePath = path.resolve("package"); - mkdirSync(packagePath); - writeFileSync( - path.join(packagePath, "index.js"), - "module.exports = {};\n" - ); - async function publishFixture( - version: string, - tag?: string, - packageName = name - ) { - writeFileSync( - path.join(packagePath, "package.json"), - JSON.stringify({ - name: packageName, - version, - packageManager, - files: ["index.js"], - publishConfig: { registry }, - "workers-sdk": tag - ? { npmPrerelease: { tag, numbered: true } } - : { prerelease: true }, - }) - ); - return publishPackage(packagePath, "ignore"); - } - expect( - await publishFixture("1.0.0", undefined, "stable-test-package") - ).toBe("latest"); - expect(await publishFixture("2.0.0-beta.0", "beta")).toBe("beta"); - expect(await publishFixture("2.0.0-rc.0", "rc")).toBe("rc"); - - await expect(publishPackage(packagePath, "ignore")).rejects.toThrow( - "pnpm publish" - ); - await stopRegistry(); - stopRegistry = await startRegistry(true); - await restoreLatestTag(name, registry, upstreamUrl); - - const tagsUrl = new URL( - `/-/package/${encodeURIComponent(name)}/dist-tags`, - registry - ); - const tags = await fetch(tagsUrl); - expect(await tags.json()).toEqual({ - latest: "1.0.0", - beta: "2.0.0-beta.0", - rc: "2.0.0-rc.0", - }); - } finally { - await stopRegistry(); - await new Promise((resolve, reject) => { - upstream.close((error) => (error ? reject(error) : resolve())); - }); - } }); }); diff --git a/packages/pages-functions/CHANGELOG.md b/packages/pages-functions/CHANGELOG.md index 4409f4adb0..d77ce9280b 100644 --- a/packages/pages-functions/CHANGELOG.md +++ b/packages/pages-functions/CHANGELOG.md @@ -1,5 +1,25 @@ # @cloudflare/pages-functions +## 0.1.10 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +## 0.1.9 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + ## 0.1.8 ### Patch Changes diff --git a/packages/pages-functions/package.json b/packages/pages-functions/package.json index a186219846..881b650abf 100644 --- a/packages/pages-functions/package.json +++ b/packages/pages-functions/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/pages-functions", - "version": "0.1.8", + "version": "0.1.10", "description": "Compile a Pages Functions directory into a Cloudflare Worker bundle", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/pages-functions#readme", "bugs": { diff --git a/packages/pages-shared/CHANGELOG.md b/packages/pages-shared/CHANGELOG.md index 74bd7d4c8d..31934c8e3f 100644 --- a/packages/pages-shared/CHANGELOG.md +++ b/packages/pages-shared/CHANGELOG.md @@ -1,5 +1,31 @@ # @cloudflare/pages-shared +## 0.13.215 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b)]: + - miniflare@5.20261116.0-beta + +## 0.13.214 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28)]: + - miniflare@5.20261113.0-beta + ## 0.13.213 ### Patch Changes diff --git a/packages/pages-shared/package.json b/packages/pages-shared/package.json index 543a7c33f8..d0d3a6ea22 100644 --- a/packages/pages-shared/package.json +++ b/packages/pages-shared/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/pages-shared", - "version": "0.13.213", + "version": "0.13.215", "repository": { "type": "git", "url": "https://github.com/cloudflare/workers-sdk.git", diff --git a/packages/remote-bindings/CHANGELOG.md b/packages/remote-bindings/CHANGELOG.md index 1c949ffcfc..0191f1e87f 100644 --- a/packages/remote-bindings/CHANGELOG.md +++ b/packages/remote-bindings/CHANGELOG.md @@ -1,5 +1,25 @@ # @cloudflare/remote-bindings +## 0.0.66 + +### Patch Changes + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`4335eac`](https://github.com/cloudflare/workers-sdk/commit/4335eacef350c98722418fbb58b012a6964e26d7)]: + - @cloudflare/deploy-helpers@0.27.1 + - @cloudflare/workers-utils@0.54.1 + - @cloudflare/workers-auth@0.18.3 + - miniflare@5.20261116.0-beta + +## 0.0.65 + +### Patch Changes + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985), [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373), [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373)]: + - miniflare@5.20261113.0-beta + - @cloudflare/workers-utils@0.54.0 + - @cloudflare/deploy-helpers@0.27.0 + - @cloudflare/workers-auth@0.18.2 + ## 0.0.64 ### Patch Changes diff --git a/packages/remote-bindings/package.json b/packages/remote-bindings/package.json index 8850b6d8bb..cbe338973c 100644 --- a/packages/remote-bindings/package.json +++ b/packages/remote-bindings/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/remote-bindings", - "version": "0.0.64", + "version": "0.0.66", "private": true, "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/remote-bindings#readme", "bugs": { diff --git a/packages/remote-bindings/src/config-bindings.test.ts b/packages/remote-bindings/src/config-bindings.test.ts index d2fe523478..88f0a7c51f 100644 --- a/packages/remote-bindings/src/config-bindings.test.ts +++ b/packages/remote-bindings/src/config-bindings.test.ts @@ -1,38 +1,5 @@ -import { describe, test, vi } from "vitest"; -import { - getRemoteBindings, - warnForDefaultRemoteBindings, -} from "./config-bindings"; - -describe("warnForDefaultRemoteBindings", () => { - test.for([ - { remote: undefined, enabled: true, warns: true }, - { remote: false, enabled: true, warns: false }, - { remote: true, enabled: true, warns: false }, - { remote: undefined, enabled: false, warns: false }, - { remote: false, enabled: false, warns: false }, - { remote: true, enabled: false, warns: false }, - ])( - "remote=$remote enabled=$enabled", - ({ remote, enabled, warns }, { expect }) => { - const warn = vi.fn(); - const bindings = getRemoteBindings({ - env: { - REPOS: { type: "artifacts", namespace: "examples", dev: { remote } }, - KV: { type: "kv", id: "kv-id" }, - }, - }); - warnForDefaultRemoteBindings(bindings, enabled, warn); - if (warns) { - expect(warn).toHaveBeenCalledExactlyOnceWith( - "Artifacts binding REPOS uses the deployed resource. Set `dev: { remote: false }` to use the local simulator, or `dev: { remote: true }` to silence this warning." - ); - } else { - expect(warn).not.toHaveBeenCalled(); - } - } - ); -}); +import { describe, test } from "vitest"; +import { getRemoteBindings } from "./config-bindings"; describe("getRemoteBindings", () => { test("maps supported remote bindings", ({ expect }) => { @@ -40,12 +7,12 @@ describe("getRemoteBindings", () => { getRemoteBindings({ env: { ANALYTICS: { - type: "analytics", + type: "analytics-sql", dev: { remote: true }, }, K2: { type: "k2", - stream: "stream-id", + id: "0123456789abcdef0123456789abcdef", }, HYPERDRIVE: { type: "hyperdrive", @@ -61,7 +28,7 @@ describe("getRemoteBindings", () => { }, K2: { type: "k2", - stream: "stream-id", + stream: "0123456789abcdef0123456789abcdef", remote: undefined, }, HYPERDRIVE: { diff --git a/packages/remote-bindings/src/config-bindings.ts b/packages/remote-bindings/src/config-bindings.ts index 6015cc8b76..2eb08503b4 100644 --- a/packages/remote-bindings/src/config-bindings.ts +++ b/packages/remote-bindings/src/config-bindings.ts @@ -1,46 +1,14 @@ -import { - getBindingLocalSupport, - validateBindingRemoteSetting, -} from "@cloudflare/workers-utils"; import type { - ParsedInputWorkerConfig, - ParsedOutputWorkerConfig, + ParsedWorkerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { Binding } from "@cloudflare/workers-utils"; -type WorkerConfig = ParsedInputWorkerConfig | ParsedOutputWorkerConfig; +type WorkerConfig = ParsedWorkerConfig | ParsedBuildOutputWorkerConfig; /** Bindings as declared in `cloudflare.config.ts`. */ export type ConfigBindings = WorkerConfig["env"]; -/** - * Warns before native-config development accesses deployed data by default. - * Explicit remote settings and sessions with remote bindings disabled are silent. - */ -export function warnForDefaultRemoteBindings( - bindings: Record, - remoteBindingsEnabled: boolean, - warn: (message: string) => void -): void { - for (const [name, binding] of Object.entries(bindings)) { - if ( - getBindingLocalSupport(binding.type) === - "remote-default-with-local-opt-in" - ) { - validateBindingRemoteSetting( - binding.type, - "remote" in binding ? binding.remote : undefined, - warn, - { - binding: name, - remoteBindingsDisabled: !remoteBindingsEnabled, - configFormat: "cloudflare-config", - } - ); - } - } -} - /** * Convert native config bindings to the transport shape consumed by the * remote-bindings session API. Local-only bindings are intentionally omitted. @@ -62,7 +30,7 @@ export function getRemoteBindings( case "ai": bindings[name] = { type: "ai", remote: binding.dev?.remote }; break; - case "analytics": + case "analytics-sql": bindings[name] = { type: "analytics", remote: binding.dev?.remote, @@ -157,14 +125,14 @@ export function getRemoteBindings( case "pipeline": bindings[name] = { type: "pipeline", - stream: binding.name, + stream: binding.streamId, remote: binding.dev?.remote, }; break; case "k2": bindings[name] = { type: "k2", - stream: binding.stream, + stream: binding.id, remote: binding.dev?.remote, }; break; diff --git a/packages/remote-bindings/src/maybe-start-or-update-session.test.ts b/packages/remote-bindings/src/maybe-start-or-update-session.test.ts index 856c6feb68..1115be7a23 100644 --- a/packages/remote-bindings/src/maybe-start-or-update-session.test.ts +++ b/packages/remote-bindings/src/maybe-start-or-update-session.test.ts @@ -54,12 +54,10 @@ describe("maybeStartOrUpdateRemoteProxySession", () => { } ); - it("selects Artifacts remotely by default and locally only when opted in", ({ - expect, - }) => { - const defaultRemote = { + it("selects Artifacts remotely only when opted in", ({ expect }) => { + const defaultLocal = { type: "artifacts" as const, - namespace: "default-remote", + namespace: "default-local", }; const local = { type: "artifacts" as const, @@ -73,15 +71,15 @@ describe("maybeStartOrUpdateRemoteProxySession", () => { }; expect( pickRemoteBindings({ - DEFAULT: defaultRemote, + DEFAULT: defaultLocal, LOCAL: local, REMOTE: remote, }) - ).toEqual({ DEFAULT: defaultRemote, REMOTE: remote }); + ).toEqual({ REMOTE: remote }); }); it.for([undefined, false, true])( - "routes native Artifacts and warns only for the default remote=%s", + "starts a session for native Artifacts only when remote=%s is true", async (remote, { expect }) => { const logger = createTestLogger(); const startSession = vi.fn(async () => @@ -103,22 +101,17 @@ describe("maybeStartOrUpdateRemoteProxySession", () => { { cliDisplayName: "Wrangler", logger }, startSession ); - if (remote === false) { - expect(result).toBeNull(); - expect(startSession).not.toHaveBeenCalled(); - } else { + if (remote === true) { expect(startSession).toHaveBeenCalledWith( { REPOS: { type: "artifacts", namespace: "examples", remote } }, expect.anything() ); - } - if (remote === undefined) { - expect(logger.warn).toHaveBeenCalledExactlyOnceWith( - "Artifacts binding REPOS uses the deployed resource. Set `dev: { remote: false }` to use the local simulator, or `dev: { remote: true }` to silence this warning." - ); } else { - expect(logger.warn).not.toHaveBeenCalled(); + expect(result).toBeNull(); + expect(startSession).not.toHaveBeenCalled(); } + // The dev tools warn about the local default; the session never does. + expect(logger.warn).not.toHaveBeenCalled(); } ); diff --git a/packages/remote-bindings/src/maybe-start-or-update-session.ts b/packages/remote-bindings/src/maybe-start-or-update-session.ts index dce661be35..e9e2fd4aa3 100644 --- a/packages/remote-bindings/src/maybe-start-or-update-session.ts +++ b/packages/remote-bindings/src/maybe-start-or-update-session.ts @@ -1,9 +1,6 @@ import assert from "node:assert"; import { resolveBindingRemote } from "@cloudflare/workers-utils"; -import { - getRemoteBindings, - warnForDefaultRemoteBindings, -} from "./config-bindings"; +import { getRemoteBindings } from "./config-bindings"; import { startRemoteProxySession } from "./start-remote-proxy-session"; import type { ConfigBindings } from "./config-bindings"; import type { RemoteBindingsLogger } from "./logger"; @@ -89,13 +86,6 @@ export async function maybeStartOrUpdateRemoteProxySession( workerConfigObject.target === "cf" ? getRemoteBindings({ env: workerConfigObject.env }) : workerConfigObject.bindings; - if (workerConfigObject.target === "cf") { - // Native-config consumers skip this function when remote bindings are - // disabled. Wrangler emits its warning when building Miniflare options. - warnForDefaultRemoteBindings(bindings, true, (message) => - context.logger.warn(message) - ); - } const remoteBindings = pickRemoteBindings(bindings); if ( Object.keys(remoteBindings).length === 0 && diff --git a/packages/runtime-types/CHANGELOG.md b/packages/runtime-types/CHANGELOG.md index 002c17d796..1d35391dde 100644 --- a/packages/runtime-types/CHANGELOG.md +++ b/packages/runtime-types/CHANGELOG.md @@ -1,5 +1,31 @@ # @cloudflare/runtime-types +## 0.1.29 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b)]: + - miniflare@5.20261116.0-beta + +## 0.1.28 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28)]: + - miniflare@5.20261113.0-beta + ## 0.1.27 ### Patch Changes diff --git a/packages/runtime-types/package.json b/packages/runtime-types/package.json index 7879dcf95f..931a8c6afc 100644 --- a/packages/runtime-types/package.json +++ b/packages/runtime-types/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/runtime-types", - "version": "0.1.27", + "version": "0.1.29", "description": "Utilities for generating Cloudflare Workers runtime types from compatibility dates and flags. This is not yet stable enough for external use — APIs may change without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/runtime-types#readme", "bugs": { diff --git a/packages/vite-plugin-cloudflare/CHANGELOG.md b/packages/vite-plugin-cloudflare/CHANGELOG.md index b517116f29..68a0c16ff9 100644 --- a/packages/vite-plugin-cloudflare/CHANGELOG.md +++ b/packages/vite-plugin-cloudflare/CHANGELOG.md @@ -1,5 +1,63 @@ # @cloudflare/vite-plugin +## 2.0.0-rc.0 + +### Minor Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Write Build Output to `.cloudflare/output/v1/` and record the producer + + `vite build` and the experimental `wrangler build --experimental-cf-build-output` now write Build Output v1, with account settings nested under `settings` in the root `config.json`. They also record themselves as the `producer`, so readers can name the tool that wrote the output in error messages. Previews from Build Output read the account settings from their new location. + +- [#16921](https://github.com/cloudflare/workers-sdk/pull/16921) [`6785363`](https://github.com/cloudflare/workers-sdk/commit/6785363bc2d9b7cda463d8cc71765c4780f8d64d) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Release Vite plugin v2 as a release candidate + + Vite plugin v2 is now published as `2.0.0-rc.` under the `rc` npm tag. The deprecated `ParsedInputConfigWithWorker` type has been removed; use `CloudflareConfig` instead. + +- [#16907](https://github.com/cloudflare/workers-sdk/pull/16907) [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Make `WorkerConfig` the type accepted by auxiliary and prerender Worker `config` + + `WorkerConfig` from `@cloudflare/vite-plugin` is now the parsed Worker configuration that auxiliary and prerender Worker `config` accepts and returns, and that their callbacks receive as `entryWorkerConfig`. It previously re-exported the `defineConfig()` Worker type from `@cloudflare/config`, which didn't type-check as an auxiliary Worker `config`. To type a Worker in `cloudflare.config.ts`, import `WorkerConfig` from `cf/config` instead. + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Ask for a rebuild when preview finds missing or outdated Build Output + + When preview finds no Build Output, Build Output in the older v0 format, or Build Output in more than one format, it now says to build the project and preview again, rather than suggesting an upgrade. + +- Updated dependencies [[`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b)]: + - @cloudflare/build-output-utils@1.0.0-rc.0 + - @cloudflare/config@1.0.0-rc.0 + - @cloudflare/runtime-types@0.1.29 + - miniflare@5.20261116.0-beta + +## 2.0.0-beta.v.17 + +### Minor Changes + +- [#16735](https://github.com/cloudflare/workers-sdk/pull/16735) [`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7) Thanks [@leostera](https://github.com/leostera)! - Use the local simulator for Artifacts bindings that omit `remote` + + **Behavior change:** Artifacts bindings now default to the local simulator during development, like KV, R2 and D1. Previously, an omitted `remote` in Wrangler and the Vite plugin used the deployed Artifacts resource. If you want deployed repos in `wrangler dev` or `vite dev`, set `"remote": true` on the binding (`dev: { remote: true }` in `cloudflare.config.ts`). Artifacts is in beta, so this ships as a minor release. + + While `remote` is omitted, `wrangler dev`, `getPlatformProxy()` and the Vite plugin warn when remote bindings are enabled, once for each binding rather than on every config reload: "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning." Workers Vitest and `wrangler dev --local` already used the simulator, so they don't warn. Local Artifacts needs no Cloudflare credentials, but requires Git 2.32 or newer on the host. + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28)]: + - miniflare@5.20261113.0-beta + - @cloudflare/build-output-utils@0.9.14 + - @cloudflare/config@0.32.1 + - @cloudflare/runtime-types@0.1.28 + ## 2.0.0-beta.v.16 ### Patch Changes diff --git a/packages/vite-plugin-cloudflare/package.json b/packages/vite-plugin-cloudflare/package.json index 86398f8b40..c680556e73 100644 --- a/packages/vite-plugin-cloudflare/package.json +++ b/packages/vite-plugin-cloudflare/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/vite-plugin", - "version": "2.0.0-beta.v.16", + "version": "2.0.0-rc.0", "description": "Cloudflare plugin for Vite", "keywords": [ "cloudflare", @@ -93,7 +93,7 @@ "workers-sdk": { "prerelease": true, "npmPrerelease": { - "tag": "beta", + "tag": "rc", "numbered": true } } diff --git a/packages/vite-plugin-cloudflare/playground/assets/__tests__/no-client-entry/assets.spec.ts b/packages/vite-plugin-cloudflare/playground/assets/__tests__/no-client-entry/assets.spec.ts index ae35fbf553..6c13d2405b 100644 --- a/packages/vite-plugin-cloudflare/playground/assets/__tests__/no-client-entry/assets.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/assets/__tests__/no-client-entry/assets.spec.ts @@ -9,7 +9,7 @@ test.runIf(isBuild)( async ({ expect }) => { const fallbackEntryPath = path.join( testDir, - ".cloudflare/output/v0/workers/default/assets/__cloudflare_fallback_entry__" + ".cloudflare/output/v1/workers/default/assets/__cloudflare_fallback_entry__" ); await vi.waitFor(() => { diff --git a/packages/vite-plugin-cloudflare/playground/assets/__tests__/public-dir-only/assets.spec.ts b/packages/vite-plugin-cloudflare/playground/assets/__tests__/public-dir-only/assets.spec.ts index 20053ab350..b0dc83cc53 100644 --- a/packages/vite-plugin-cloudflare/playground/assets/__tests__/public-dir-only/assets.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/assets/__tests__/public-dir-only/assets.spec.ts @@ -21,7 +21,7 @@ test.runIf(isBuild)( testDir, ".cloudflare", "output", - "v0", + "v1", "workers", "default", "assets", diff --git a/packages/vite-plugin-cloudflare/playground/build-output/__tests__/build-output.spec.ts b/packages/vite-plugin-cloudflare/playground/build-output/__tests__/build-output.spec.ts index 437a8b7df7..1d1932c62f 100644 --- a/packages/vite-plugin-cloudflare/playground/build-output/__tests__/build-output.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/build-output/__tests__/build-output.spec.ts @@ -4,11 +4,11 @@ import { describe, test } from "vitest"; import { getTextResponse, isBuild, rootDir } from "../../__test-utils__"; function getBuildOutputDir() { - return path.join(rootDir, ".cloudflare/output/v0/workers", "default"); + return path.join(rootDir, ".cloudflare/output/v1/workers", "default"); } function getRootConfigPath() { - return path.join(rootDir, ".cloudflare/output/v0", "config.json"); + return path.join(rootDir, ".cloudflare/output/v1", "config.json"); } describe("Build Output Specification", () => { @@ -133,12 +133,18 @@ describe.runIf(isBuild)("Build Output Specification files", () => { expect(fs.existsSync(wranglerJson)).toBe(false); }); - test("emits a root config.json recording the build context", ({ expect }) => { + test("emits a root config.json recording the producer and build context", ({ + expect, + }) => { const contents = JSON.parse( fs.readFileSync(getRootConfigPath(), "utf-8") ) as Record; expect(contents).toEqual({ + producer: { + name: "@cloudflare/vite-plugin", + version: expect.any(String), + }, buildContext: { isPreview: false, mode: "production" }, }); }); diff --git a/packages/vite-plugin-cloudflare/playground/build-output/__tests__/disable-source-maps/build-output.spec.ts b/packages/vite-plugin-cloudflare/playground/build-output/__tests__/disable-source-maps/build-output.spec.ts index d5f9d30a56..37b428e61f 100644 --- a/packages/vite-plugin-cloudflare/playground/build-output/__tests__/disable-source-maps/build-output.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/build-output/__tests__/disable-source-maps/build-output.spec.ts @@ -8,7 +8,7 @@ test.runIf(isBuild)( ({ expect }) => { const workerDir = path.join( rootDir, - ".cloudflare/output/v0/workers/default" + ".cloudflare/output/v1/workers/default" ); const config = JSON.parse( fs.readFileSync(path.join(workerDir, "worker.config.json"), "utf-8") diff --git a/packages/vite-plugin-cloudflare/playground/explicit-resource-management/__tests__/explicit-resource-management.spec.ts b/packages/vite-plugin-cloudflare/playground/explicit-resource-management/__tests__/explicit-resource-management.spec.ts index 1e2e459c7a..3433cd1ce1 100644 --- a/packages/vite-plugin-cloudflare/playground/explicit-resource-management/__tests__/explicit-resource-management.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/explicit-resource-management/__tests__/explicit-resource-management.spec.ts @@ -5,7 +5,7 @@ import { test } from "vitest"; import { getJsonResponse, isBuild, page, rootDir } from "../../__test-utils__"; function getWorkerOutput() { - const workerDir = path.join(rootDir, ".cloudflare/output/v0/workers/default"); + const workerDir = path.join(rootDir, ".cloudflare/output/v1/workers/default"); const config = JSON.parse( fs.readFileSync(path.join(workerDir, "worker.config.json"), "utf-8") ) as { manifest: { mainModule: string } }; @@ -41,7 +41,7 @@ test.runIf(isBuild)( async ({ expect }) => { const clientDir = path.join( rootDir, - ".cloudflare/output/v0/workers/default/assets" + ".cloudflare/output/v1/workers/default/assets" ); const html = fs.readFileSync(path.join(clientDir, "index.html"), "utf-8"); const entry = html.match(/src="\/(assets\/[^"]+\.js)"/)?.[1]; diff --git a/packages/vite-plugin-cloudflare/playground/node-env/__tests__/base-tests.ts b/packages/vite-plugin-cloudflare/playground/node-env/__tests__/base-tests.ts index a37c850884..be920911e3 100644 --- a/packages/vite-plugin-cloudflare/playground/node-env/__tests__/base-tests.ts +++ b/packages/vite-plugin-cloudflare/playground/node-env/__tests__/base-tests.ts @@ -17,7 +17,7 @@ test.skipIf(!isBuild)( "the build output does not include react development code (such is tree-shaken away)", async ({ expect }) => { const outputJs = readFileSync( - "./.cloudflare/output/v0/workers/default/bundle/index.js", + "./.cloudflare/output/v1/workers/default/bundle/index.js", "utf8" ); expect(outputJs).not.toContain("react-dom.development.js"); diff --git a/packages/vite-plugin-cloudflare/playground/prerendering/__tests__/base-tests.ts b/packages/vite-plugin-cloudflare/playground/prerendering/__tests__/base-tests.ts index 935039af38..7167d1c8b4 100644 --- a/packages/vite-plugin-cloudflare/playground/prerendering/__tests__/base-tests.ts +++ b/packages/vite-plugin-cloudflare/playground/prerendering/__tests__/base-tests.ts @@ -32,7 +32,7 @@ describe("pre-rendering", () => { ({ expect }) => { const workerDir = path.join( rootDir, - ".cloudflare/output/v0/workers/prerender" + ".cloudflare/output/v1/workers/prerender" ); const config = JSON.parse( fs.readFileSync(path.join(workerDir, "worker.config.json"), "utf-8") @@ -65,7 +65,7 @@ describe("pre-rendering", () => { async ({ expect }) => { const workerDir = path.join( rootDir, - ".cloudflare/output/v0/workers/prerender" + ".cloudflare/output/v1/workers/prerender" ); const config = JSON.parse( fs.readFileSync(path.join(workerDir, "worker.config.json"), "utf-8") diff --git a/packages/vite-plugin-cloudflare/playground/spa-with-api/__tests__/custom-output-directories/spa-with-api.spec.ts b/packages/vite-plugin-cloudflare/playground/spa-with-api/__tests__/custom-output-directories/spa-with-api.spec.ts index 00b26d894f..7cb8a5106e 100644 --- a/packages/vite-plugin-cloudflare/playground/spa-with-api/__tests__/custom-output-directories/spa-with-api.spec.ts +++ b/packages/vite-plugin-cloudflare/playground/spa-with-api/__tests__/custom-output-directories/spa-with-api.spec.ts @@ -15,7 +15,7 @@ describe.runIf(isBuild)("output directories", () => { rootDir, ".cloudflare", "output", - "v0", + "v1", "workers", "default", "bundle" @@ -28,7 +28,7 @@ describe.runIf(isBuild)("output directories", () => { rootDir, ".cloudflare", "output", - "v0", + "v1", "workers", "default", "assets" diff --git a/packages/vite-plugin-cloudflare/src/__tests__/artifacts-local.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/artifacts-local.spec.ts index 51d5e222f3..df8ad6b164 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/artifacts-local.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/artifacts-local.spec.ts @@ -3,7 +3,7 @@ import * as path from "node:path"; import { cloudflare } from "@cloudflare/vite-plugin"; import { removeDirSync } from "@cloudflare/workers-utils"; import { pushGitFixture } from "@cloudflare/workers-utils/test-helpers"; -import { createServer } from "vite"; +import { createLogger, createServer } from "vite"; import { afterEach, test, vi } from "vitest"; // Excluded from type checking, so a crashed run cannot leave a stray @@ -42,7 +42,11 @@ const WORKER = `export default { } };`; -function createFixture(remote: boolean | undefined): string { +function createFixture( + remote: boolean | undefined, + config = CONFIG, + worker = WORKER +): string { fs.mkdirSync(FIXTURES_ROOT, { recursive: true }); const root = fs.realpathSync( fs.mkdtempSync(path.join(FIXTURES_ROOT, "case-")) @@ -53,19 +57,96 @@ function createFixture(remote: boolean | undefined): string { ); fs.writeFileSync( path.join(root, "cloudflare.config.ts"), - CONFIG.replace( + config.replace( "dev: { remote: false },", remote === undefined ? "" : `dev: { remote: ${remote} },` ) ); - fs.writeFileSync(path.join(root, "index.js"), WORKER); + fs.writeFileSync(path.join(root, "index.js"), worker); return root; } afterEach(() => vi.unstubAllEnvs()); +test("Vite native Artifacts event triggers start a Workflow", async ({ + expect, + onTestFinished, +}) => { + const root = createFixture( + false, + ` +import { defineConfig, exports } from "@cloudflare/config"; +export default defineConfig({ worker: { + name: "vite-artifacts-local", entrypoint: "./index.js", + compatibilityDate: "2026-09-03", + env: { + REPOS: { type: "artifacts", namespace: "examples", dev: { remote: false } }, + EVENTS: { type: "kv" }, + }, + exports: { OnEvent: exports.workflow({ name: "on-event", events: [{ + type: "cf.artifacts.repo.created", filter: { namespace: "examples" }, + }] }) }, +} }); +`, + ` +import { WorkflowEntrypoint } from "cloudflare:workers"; +export class OnEvent extends WorkflowEntrypoint { + async run(event, step) { + await step.do("record", async () => { + await this.env.EVENTS.put("event", JSON.stringify(event.payload)); + return "recorded"; + }); + } +} +export default { + async fetch(request, env) { + if (request.method === "POST") return Response.json(await env.REPOS.create("demo")); + return new Response(await env.EVENTS.get("event")); + } +}; +` + ); + onTestFinished(() => removeDirSync(root)); + const server = await createServer({ + root, + configFile: false, + logLevel: "silent", + server: { port: 0 }, + plugins: [ + cloudflare({ + inspectorPort: false, + persistState: false, + remoteBindings: false, + }), + ], + }); + try { + await server.listen(); + const url = server.resolvedUrls?.local[0]; + if (!url) { + throw new Error("Vite server did not provide a local URL"); + } + expect((await fetch(url, { method: "POST" })).ok).toBe(true); + await vi.waitFor( + async () => { + const message = await (await fetch(url)).json(); + expect(message).toMatchObject({ + type: "cf.artifacts.repo.created", + source: { namespace: "examples", repoName: "demo" }, + }); + }, + { timeout: 10_000 } + ); + } finally { + await server.close(); + } +}); + test.for([ { label: "explicit local", remote: false, remoteBindings: true }, + // Omitted `remote` is local without starting a remote proxy session, so it + // works with no Cloudflare credentials. + { label: "omitted remote", remote: undefined, remoteBindings: true }, { label: "omitted remote with sessions disabled", remote: undefined, @@ -83,10 +164,13 @@ test.for([ vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined); const root = createFixture(remote); onTestFinished(() => removeDirSync(root)); + const warnings: string[] = []; + const customLogger = createLogger("silent"); + customLogger.warn = (message) => void warnings.push(message); const server = await createServer({ root, configFile: false, - logLevel: "silent", + customLogger, server: { port: 0 }, plugins: [ cloudflare({ @@ -126,6 +210,14 @@ test.for([ name: string; }; expect(info.name).toBe("demo"); + // The default changed only where remote bindings are enabled. + const defaultWarning = + "Artifacts binding REPOS uses the local simulator by default. Set `dev: { remote: true }` to use deployed repos, or `dev: { remote: false }` to silence this warning."; + if (remote === undefined && remoteBindings) { + expect(warnings).toContain(defaultWarning); + } else { + expect(warnings).not.toContain(defaultWarning); + } } finally { await server.close(); } diff --git a/packages/vite-plugin-cloudflare/src/__tests__/build-output-preview.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/build-output-preview.spec.ts index d80abb1381..2f3e6c39c0 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/build-output-preview.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/build-output-preview.spec.ts @@ -1,3 +1,4 @@ +import { BuildOutputError } from "@cloudflare/build-output-utils"; import { beforeEach, describe, test, vi } from "vitest"; import { readBuildOutputPreview } from "../build-output-preview"; import type { BuildOutputWorker } from "@cloudflare/build-output-utils"; @@ -112,4 +113,51 @@ describe("readBuildOutputPreview", () => { expect(result.containers).toEqual([container]); }); + + test.for([ + { + code: "not-found", + foundVersions: [], + message: + "No Build Output was found to preview. Build the project, then preview it again.", + }, + { + code: "older-version", + foundVersions: ["v0"], + message: + "The Build Output uses the older v0 format. Build the project, then preview it again.", + }, + { + code: "multiple-versions", + foundVersions: ["v0", "v1"], + message: + "Build Output was found in more than one format (v0, v1). Build the project, then preview it again.", + }, + ] as const)( + "asks for a rebuild when the Build Output is $code", + async ({ code, foundVersions, message }, { expect }) => { + const cause = new BuildOutputError("original", { + code, + foundVersions: [...foundVersions], + supportedVersions: ["v1"], + }); + readBuildOutputMock.mockRejectedValue(cause); + + await expect(readBuildOutputPreview("/project", false)).rejects.toThrow( + expect.objectContaining({ message, cause }) + ); + } + ); + + test.for(["newer-version", "unknown-fields", "invalid"] as const)( + "passes %s errors through unchanged", + async (code, { expect }) => { + const error = new BuildOutputError("original", { code }); + readBuildOutputMock.mockRejectedValue(error); + + await expect(readBuildOutputPreview("/project", false)).rejects.toBe( + error + ); + } + ); }); diff --git a/packages/vite-plugin-cloudflare/src/__tests__/preview-server.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/preview-server.spec.ts index 882171a70e..d18d576dc6 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/preview-server.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/preview-server.spec.ts @@ -53,7 +53,7 @@ describe("preview server", () => { accountId: "customized-account", complianceRegion: "fedramp-high", containers: [ - ...loadedConfig.containers, + ...(loadedConfig.containers ?? []), { name: "customized-container", image: { @@ -76,8 +76,11 @@ describe("preview server", () => { await builder.buildApp(); const output = await readBuildOutput(fixturesPath); expect(output.rootConfig).toMatchObject({ - accountId: "customized-account", - complianceRegion: "fedramp-high", + producer: { name: "@cloudflare/vite-plugin" }, + settings: { + accountId: "customized-account", + complianceRegion: "fedramp-high", + }, }); expect(output.containers.map(({ config }) => config)).toEqual([ expect.objectContaining({ diff --git a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts index 6e178eba69..50f7c15b1f 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts @@ -7,9 +7,9 @@ import type { AssetsOnlyResolvedConfig, PluginConfig, CloudflareConfig, + WorkerConfig, WorkersResolvedConfig, } from "../plugin-config"; -import type { InputWorkerConfig } from "@cloudflare/config"; const { readBuildOutputPreviewMock } = vi.hoisted(() => ({ readBuildOutputPreviewMock: vi.fn(), @@ -76,8 +76,8 @@ describe("resolvePluginConfig", () => { function createAuxiliaryWorkerConfig( name: string, - overrides: Partial = {} - ): InputWorkerConfig { + overrides: Partial = {} + ): WorkerConfig { return { name, entrypoint: "./src/aux.ts", @@ -299,7 +299,7 @@ describe("resolvePluginConfig", () => { accountId: "customized-account", complianceRegion: "fedramp-high", containers: [ - ...loadedConfig.containers, + ...(loadedConfig.containers ?? []), { name: "customized-container", image: { reference: "docker.io/cloudflare/hello-world:latest" }, @@ -372,8 +372,8 @@ describe("resolvePluginConfig", () => { config: (loadedConfig) => ({ ...loadedConfig, containers: [ - ...loadedConfig.containers, - ...loadedConfig.containers, + ...(loadedConfig.containers ?? []), + ...(loadedConfig.containers ?? []), ], }), error: /Container names must be unique/, @@ -387,7 +387,7 @@ describe("resolvePluginConfig", () => { name: "renaming a linked Container without updating its reference", config: (loadedConfig) => ({ ...loadedConfig, - containers: loadedConfig.containers.map((container) => ({ + containers: (loadedConfig.containers ?? []).map((container) => ({ ...container, name: "renamed-api", })), diff --git a/packages/vite-plugin-cloudflare/src/auth.ts b/packages/vite-plugin-cloudflare/src/auth.ts index 638276de16..778dc4c5f9 100644 --- a/packages/vite-plugin-cloudflare/src/auth.ts +++ b/packages/vite-plugin-cloudflare/src/auth.ts @@ -1,4 +1,3 @@ -import { createRequire } from "node:module"; import { format } from "node:util"; import { inputPrompt } from "@cloudflare/cli-shared-helpers/interactive"; import { @@ -6,6 +5,7 @@ import { createCfProfileStore, } from "@cloudflare/workers-auth/cf"; import { isNonInteractiveOrCI } from "@cloudflare/workers-utils"; +import { PACKAGE_INFO } from "./package-info"; import { debuglog } from "./utils"; import type { RemoteBindingsAuth } from "@cloudflare/remote-bindings"; import type { CloudflareAuth } from "@cloudflare/workers-auth/cf"; @@ -20,11 +20,7 @@ class AccountSelectionUnavailable extends Error { } } -const { version: packageVersion } = createRequire(import.meta.url)( - "../package.json" -) as { version: string }; - -export const USER_AGENT = `vite-plugin/${packageVersion}`; +export const USER_AGENT = `vite-plugin/${PACKAGE_INFO.version}`; /** * Set up cf authentication using the profile associated with the Vite project. diff --git a/packages/vite-plugin-cloudflare/src/build-output-preview.ts b/packages/vite-plugin-cloudflare/src/build-output-preview.ts index d99f02a263..55195fcd16 100644 --- a/packages/vite-plugin-cloudflare/src/build-output-preview.ts +++ b/packages/vite-plugin-cloudflare/src/build-output-preview.ts @@ -1,4 +1,5 @@ import { + BuildOutputError, DEFAULT_WORKER_DIRECTORY_NAME, readBuildOutput, } from "@cloudflare/build-output-utils"; @@ -6,9 +7,9 @@ import { PRERENDER_WORKER_DIRECTORY_NAME } from "./build-output"; import type { BuildOutputWorker } from "@cloudflare/build-output-utils"; import type { ModuleType, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputRootConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; export interface Bundle { @@ -18,14 +19,14 @@ export interface Bundle { } export interface BuildOutputPreviewWorker { - config: ParsedOutputWorkerConfig; + config: ParsedBuildOutputWorkerConfig; assetsDir: string | undefined; bundle: Bundle | undefined; } export interface BuildOutputPreview { - rootConfig: ParsedOutputRootConfig; - containers: ParsedOutputContainerConfig[]; + rootConfig: ParsedBuildOutputRootConfig; + containers: ParsedBuildOutputContainerConfig[]; workers: BuildOutputPreviewWorker[]; } @@ -40,7 +41,8 @@ export async function readBuildOutputPreview( ): Promise { // `rootConfig` comes from the top-level `config.json` holding project-level // settings and build context shared by every Worker. - const { workers, rootConfig, containers } = await readBuildOutput(root); + const { workers, rootConfig, containers } = + await readPreviewBuildOutput(root); const defaultWorker = workers[DEFAULT_WORKER_DIRECTORY_NAME]; const entryWorker = isPrerender ? (workers[PRERENDER_WORKER_DIRECTORY_NAME] ?? defaultWorker) @@ -62,6 +64,40 @@ export async function readBuildOutputPreview( }; } +/** + * Read the Build Output, replacing the library's generic advice when the fix + * is to rebuild. + * + * Preview reads the output this plugin wrote. If it is missing, in an older + * format or alongside a stale tree, the build hasn't run since the plugin was + * installed or upgraded, so upgrading isn't the fix. + */ +async function readPreviewBuildOutput( + root: string +): ReturnType { + try { + return await readBuildOutput(root); + } catch (error) { + if ( + error instanceof BuildOutputError && + (error.code === "not-found" || + error.code === "older-version" || + error.code === "multiple-versions") + ) { + const reason = + error.code === "not-found" + ? "No Build Output was found to preview." + : error.code === "older-version" + ? `The Build Output uses the older ${error.foundVersions?.join(", ")} format.` + : `Build Output was found in more than one format (${error.foundVersions?.join(", ")}).`; + throw new Error(`${reason} Build the project, then preview it again.`, { + cause: error, + }); + } + throw error; + } +} + function toPreviewWorker(worker: BuildOutputWorker): BuildOutputPreviewWorker { const { manifest } = worker.config; let bundle: Bundle | undefined; diff --git a/packages/vite-plugin-cloudflare/src/containers.ts b/packages/vite-plugin-cloudflare/src/containers.ts index 77d04b5949..7f232f7023 100644 --- a/packages/vite-plugin-cloudflare/src/containers.ts +++ b/packages/vite-plugin-cloudflare/src/containers.ts @@ -10,7 +10,7 @@ import { UserError, } from "@cloudflare/workers-utils"; import { toApiComplianceRegion } from "./utils"; -import type { ParsedInputSettingsConfig } from "@cloudflare/config"; +import type { ParsedSettings } from "@cloudflare/config"; import type { ContainerDevOptions, ViteLogger, @@ -77,7 +77,7 @@ export function normalizeContainerImageUris(options: { export async function prepareContainerImagesForVite(options: { dockerPath: string; containerOptions: ContainerDevOptions[]; - settings: ParsedInputSettingsConfig; + settings: ParsedSettings; logger: ViteLogger; }): Promise { const complianceRegion = toApiComplianceRegion( diff --git a/packages/vite-plugin-cloudflare/src/context.ts b/packages/vite-plugin-cloudflare/src/context.ts index 524161f198..7412a550b7 100644 --- a/packages/vite-plugin-cloudflare/src/context.ts +++ b/packages/vite-plugin-cloudflare/src/context.ts @@ -16,8 +16,8 @@ import type { } from "./plugin-config"; import type { ModuleType, - ParsedInputWorkerConfig, - ParsedOutputWorkerConfig, + ParsedWorkerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { CloudflareAuth } from "@cloudflare/workers-auth/cf"; import type { Logger } from "@cloudflare/workers-utils"; @@ -245,9 +245,7 @@ export class PluginContext { return this.#getWorker(environmentName)?.config; } - getWorkerNewConfig( - environmentName: string - ): ParsedInputWorkerConfig | undefined { + getWorkerNewConfig(environmentName: string): ParsedWorkerConfig | undefined { return this.#getWorker(environmentName)?.config; } @@ -299,7 +297,7 @@ export class PluginContext { } get allWorkerConfigs(): Array< - ParsedInputWorkerConfig | ParsedOutputWorkerConfig + ParsedWorkerConfig | ParsedBuildOutputWorkerConfig > { if (this.resolvedPluginConfig.type === "preview") { return this.resolvedPluginConfig.workers.map((worker) => worker.config); diff --git a/packages/vite-plugin-cloudflare/src/index.ts b/packages/vite-plugin-cloudflare/src/index.ts index 26a1a66bd5..649dee4c88 100644 --- a/packages/vite-plugin-cloudflare/src/index.ts +++ b/packages/vite-plugin-cloudflare/src/index.ts @@ -49,11 +49,9 @@ export function getLocalWorkerdCompatibilityDate(_options?: { export type { CloudflareConfig, - // eslint-disable-next-line @typescript-eslint/no-deprecated -- Preserve the deprecated public type for compatibility. - ParsedInputConfigWithWorker, PluginConfig, + WorkerConfig, } from "./plugin-config"; -export type { WorkerConfig } from "@cloudflare/config"; const sharedContext: SharedContext = { configChangeCoordinator: new ConfigChangeCoordinator(), diff --git a/packages/vite-plugin-cloudflare/src/miniflare-options.ts b/packages/vite-plugin-cloudflare/src/miniflare-options.ts index e0081fd4d2..cbca3226b9 100644 --- a/packages/vite-plugin-cloudflare/src/miniflare-options.ts +++ b/packages/vite-plugin-cloudflare/src/miniflare-options.ts @@ -18,6 +18,7 @@ import { getLocalObservabilityEnabledFromEnv, getZoneFromRoute, } from "@cloudflare/workers-utils"; +import { createArtifactsLocalDefaultWarner } from "@cloudflare/workers-utils"; import { getDockerPath } from "@cloudflare/workers-utils/docker-path"; import { buildPublicUrl, @@ -58,8 +59,8 @@ import type { } from "./context"; import type { PersistState } from "./plugin-config"; import type { - ParsedInputWorkerConfig, - ParsedOutputWorkerConfig, + ParsedWorkerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { ContainerDevOptions, @@ -216,7 +217,7 @@ function createRemoteBindingsLogger(logger: vite.Logger): RemoteBindingsLogger { } function getWorkerZone( - config: Pick + config: Pick ): string | undefined { // Domains are converted to routes before fetch triggers, so this mirrors the // first-route selection used by Wrangler's Miniflare options. @@ -262,6 +263,7 @@ export async function getDevMiniflareOptions( resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings, resolvedViteConfig.mode, + resolvedViteConfig.root, viteDevServer.config.logger ); const [routerWorkerManifest, assetWorkerManifest, viteProxyWorkerManifest] = @@ -814,6 +816,7 @@ export async function getPreviewMiniflareOptions( resolvedPluginConfig.devVars, resolvedPluginConfig.remoteBindings, resolvedViteConfig.mode, + resolvedViteConfig.root, vitePreviewServer.config.logger ); const containerPlansByWorkerName = new Map(); @@ -957,16 +960,44 @@ export async function getPreviewMiniflareOptions( }; } +// Remembers warnings per project root, so restarting the dev server after a +// config change doesn't repeat them. +const warnForArtifactsLocalDefault = + createArtifactsLocalDefaultWarner("cloudflare-config"); + function resolveLocalBindingsByWorkerName( - workerConfigs: Array, + workerConfigs: Array, localEnv: LoadedEnv, devVars: Record | undefined, remoteBindings: boolean, mode: string, + projectRoot: string, logger: vite.Logger ): Map { const resolvedLocalBindingsByWorkerName = new Map(); for (const config of workerConfigs) { + if (remoteBindings) { + warnForArtifactsLocalDefault( + { + id: projectRoot, + bindings: Object.entries(config.env ?? {}).flatMap( + ([name, binding]) => + binding.type === "artifacts" + ? [ + { + name, + remote: binding.dev?.remote, + // Name the Worker when several could declare the binding. + worker: + workerConfigs.length > 1 ? config.name : undefined, + }, + ] + : [] + ), + }, + (message) => logger.warn(message) + ); + } resolvedLocalBindingsByWorkerName.set( config.name, resolveLocalBindings(config.env, { diff --git a/packages/vite-plugin-cloudflare/src/package-info.ts b/packages/vite-plugin-cloudflare/src/package-info.ts new file mode 100644 index 0000000000..4f9b617b11 --- /dev/null +++ b/packages/vite-plugin-cloudflare/src/package-info.ts @@ -0,0 +1,6 @@ +import { createRequire } from "node:module"; + +/** The name and version of this package, read from its `package.json`. */ +export const PACKAGE_INFO = createRequire(import.meta.url)( + "../package.json" +) as { name: string; version: string }; diff --git a/packages/vite-plugin-cloudflare/src/plugin-config.ts b/packages/vite-plugin-cloudflare/src/plugin-config.ts index 04b188b1f9..94a1a7147c 100644 --- a/packages/vite-plugin-cloudflare/src/plugin-config.ts +++ b/packages/vite-plugin-cloudflare/src/plugin-config.ts @@ -7,8 +7,8 @@ import { } from "@cloudflare/build-output-utils"; import { generateTypes, - InputConfigSchema, - InputWorkerSchema, + CloudflareConfigSchema, + WorkerConfigSchema, loadAndParseConfig, } from "@cloudflare/config"; import { @@ -29,23 +29,22 @@ import { readBuildOutputPreview } from "./build-output-preview"; import { hasNodeJsCompat, NodeJsCompat } from "./nodejs-compat"; import type { BuildOutputPreviewWorker } from "./build-output-preview"; import type { - ParsedInputContainerConfig, - InputWorkerConfig, - ParsedInputConfig, - ParsedInputSettingsConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, + ParsedContainerConfig, + ParsedCloudflareConfig, + ParsedSettings, + ParsedWorkerConfig, + ParsedBuildOutputContainerConfig, } from "@cloudflare/config"; import type { StaticRouting } from "@cloudflare/workers-shared/utils/types"; import type { LoadedEnv } from "@cloudflare/workers-utils/local-env"; /** Parsed configuration with the entry Worker required by the Vite plugin. */ -export type CloudflareConfig = Omit & { - worker: ParsedInputWorkerConfig; +export type CloudflareConfig = Omit & { + worker: ParsedWorkerConfig; }; -/** @deprecated Use `CloudflareConfig` instead. */ -export type ParsedInputConfigWithWorker = CloudflareConfig; +/** Parsed Worker configuration, as used by auxiliary and prerender Worker `config`. */ +export type WorkerConfig = CloudflareConfig["worker"]; export type PersistState = boolean | { path: string }; export type TunnelConfig = { @@ -124,10 +123,8 @@ function normalizeTypes( } type WorkerConfigProvider = - | InputWorkerConfig - | ((options: { - entryWorkerConfig: ParsedInputWorkerConfig; - }) => InputWorkerConfig); + | WorkerConfig + | ((options: { entryWorkerConfig: WorkerConfig }) => WorkerConfig); export interface PluginConfig extends EntryWorkerOptions { /** @@ -152,15 +149,9 @@ export interface PluginConfig extends EntryWorkerOptions { experimental?: Experimental; } -export type ResolvedAssetsOnlyConfig = Omit< - ParsedInputWorkerConfig, - "entrypoint" ->; +export type ResolvedAssetsOnlyConfig = Omit; -export type ResolvedWorkerConfig = Omit< - ParsedInputWorkerConfig, - "entrypoint" -> & { +export type ResolvedWorkerConfig = Omit & { entrypoint: string; }; @@ -180,11 +171,11 @@ interface BaseResolvedConfig { tunnel: TunnelConfig; localEnv: LoadedEnv; devVars: Record | undefined; - settings: ParsedInputSettingsConfig; + settings: ParsedSettings; } interface NonPreviewResolvedConfig extends BaseResolvedConfig { - containers: ParsedInputContainerConfig[]; + containers: ParsedContainerConfig[]; configPaths: Set; environmentNameToWorkerMap: Map; environmentNameToChildEnvironmentNamesMap: Map; @@ -204,7 +195,7 @@ export interface WorkersResolvedConfig extends NonPreviewResolvedConfig { export interface PreviewResolvedConfig extends BaseResolvedConfig { type: "preview"; - containers: ParsedOutputContainerConfig[]; + containers: ParsedBuildOutputContainerConfig[]; workers: BuildOutputPreviewWorker[]; } @@ -217,7 +208,7 @@ type ResolvedWorker = | { type: "assets-only"; config: ResolvedAssetsOnlyConfig } | { type: "worker"; config: ResolvedWorkerConfig }; -function createDefaultWorkerConfig(name: string): ParsedInputWorkerConfig { +function createDefaultWorkerConfig(name: string): ParsedWorkerConfig { return { name, compatibilityDate: DEFAULT_COMPAT_DATE, @@ -227,27 +218,27 @@ function createDefaultWorkerConfig(name: string): ParsedInputWorkerConfig { /** Resolves an auxiliary or prerender Worker config. */ function resolveNonEntryWorkerConfig(options: { config: WorkerConfigProvider; - entryWorkerConfig: ParsedInputWorkerConfig; + entryWorkerConfig: ParsedWorkerConfig; }): Extract { const inputConfig = typeof options.config === "function" ? options.config({ entryWorkerConfig: options.entryWorkerConfig }) : options.config; - const config = InputWorkerSchema.parse(inputConfig); + const config = WorkerConfigSchema.parse(inputConfig); return resolveWorkerType({ config, isEntryWorker: false }); } function resolveWorkerType(options: { - config: ParsedInputWorkerConfig; + config: ParsedWorkerConfig; isEntryWorker: false; }): Extract; function resolveWorkerType(options: { - config: ParsedInputWorkerConfig; + config: ParsedWorkerConfig; isEntryWorker: true; }): ResolvedWorker; function resolveWorkerType(options: { - config: ParsedInputWorkerConfig; + config: ParsedWorkerConfig; isEntryWorker: boolean; }): ResolvedWorker { const { config, isEntryWorker } = options; @@ -342,7 +333,7 @@ export async function resolvePluginConfig( : (pluginConfig.remoteBindings ?? true); if (preview !== undefined) { - const { accountId, complianceRegion } = preview.rootConfig; + const { accountId, complianceRegion } = preview.rootConfig.settings ?? {}; return { ...shared, remoteBindings, @@ -376,7 +367,7 @@ export async function resolvePluginConfig( containers: [], }; const customizedConfig = pluginConfig.config - ? InputConfigSchema.parse(pluginConfig.config(inputConfig)) + ? CloudflareConfigSchema.parse(pluginConfig.config(inputConfig)) : inputConfig; if (customizedConfig.worker === undefined) { throw new Error("The customized configuration must define a `worker`."); @@ -385,7 +376,7 @@ export async function resolvePluginConfig( accountId: customizedConfig.accountId, complianceRegion: customizedConfig.complianceRegion, }; - const containers = customizedConfig.containers; + const containers = customizedConfig.containers ?? []; const entryWorkerResolvedConfig = resolveWorkerType({ config: customizedConfig.worker, isEntryWorker: true, @@ -517,7 +508,7 @@ export async function resolvePluginConfig( function addAuxiliaryWorkers(options: { auxiliaryWorkers: AuxiliaryWorkerOptions[] | undefined; - entryWorkerConfig: ParsedInputWorkerConfig; + entryWorkerConfig: ParsedWorkerConfig; environmentNameToWorkerMap: Map; environmentNameToChildEnvironmentNamesMap: Map; validateAndAddEnvironmentName: (name: string) => void; diff --git a/packages/vite-plugin-cloudflare/src/plugins/build-output.ts b/packages/vite-plugin-cloudflare/src/plugins/build-output.ts index d443c10717..6b9ef1c5de 100644 --- a/packages/vite-plugin-cloudflare/src/plugins/build-output.ts +++ b/packages/vite-plugin-cloudflare/src/plugins/build-output.ts @@ -13,6 +13,7 @@ import { buildApp } from "../build"; import { isPreviewBuild } from "../build-output-env"; import { MAIN_ENTRY_NAME } from "../cloudflare-environment"; import { assertIsNotPreview } from "../context"; +import { PACKAGE_INFO } from "../package-info"; import { resolveDevOnly } from "../plugin-config"; import { createPlugin } from "../utils"; import type { AdditionalModuleMetadata } from "../context"; @@ -209,13 +210,14 @@ export const buildOutputPlugin = createPlugin("build-output", (ctx) => { return; } - await writeBuildOutputRootConfig( - ctx.resolvedViteConfig.root, - ctx.resolvedPluginConfig.settings, - { + await writeBuildOutputRootConfig({ + root: ctx.resolvedViteConfig.root, + settings: ctx.resolvedPluginConfig.settings, + buildContext: { isPreview: isPreviewBuild(), mode: ctx.resolvedViteConfig.mode, - } - ); + }, + producer: { name: PACKAGE_INFO.name, version: PACKAGE_INFO.version }, + }); } }); diff --git a/packages/vite-plugin-cloudflare/src/plugins/shortcuts.ts b/packages/vite-plugin-cloudflare/src/plugins/shortcuts.ts index e4d01bead3..5d8156bb44 100644 --- a/packages/vite-plugin-cloudflare/src/plugins/shortcuts.ts +++ b/packages/vite-plugin-cloudflare/src/plugins/shortcuts.ts @@ -15,10 +15,10 @@ import { createPlugin, satisfiesMinimumViteVersion } from "../utils"; import { extendTunnelExpiry, isTunnelOpen, toggleTunnel } from "./tunnel"; import type { PluginContext } from "../context"; import type { - ParsedInputContainerConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, - ParsedOutputWorkerConfig, + ParsedContainerConfig, + ParsedWorkerConfig, + ParsedBuildOutputContainerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { ContainerApp } from "@cloudflare/workers-utils"; import type * as vite from "vite"; @@ -191,8 +191,8 @@ export function addShortcuts( * from input Container definitions and Worker export links. */ export function getWorkerContainersForDisplay(options: { - workerConfig: ParsedInputWorkerConfig | ParsedOutputWorkerConfig; - containers: Array; + workerConfig: ParsedWorkerConfig | ParsedBuildOutputWorkerConfig; + containers: Array; }): ContainerApp[] { const containersByName = new Map( options.containers.map((container) => [container.name, container]) diff --git a/packages/vite-plugin-cloudflare/src/utils.ts b/packages/vite-plugin-cloudflare/src/utils.ts index 5b09a438b4..bc75098379 100644 --- a/packages/vite-plugin-cloudflare/src/utils.ts +++ b/packages/vite-plugin-cloudflare/src/utils.ts @@ -13,7 +13,7 @@ import * as vite from "vite"; import { PROXY_SHARED_SECRET } from "./constants"; import { warnIfQuickTunnelSseResponse } from "./plugins/tunnel"; import type { PluginContext } from "./context"; -import type { ParsedInputSettingsConfig } from "@cloudflare/config"; +import type { ParsedSettings } from "@cloudflare/config"; import type { ComplianceConfig } from "@cloudflare/workers-utils"; import type * as http from "node:http"; @@ -60,7 +60,7 @@ export type MaybePromise = Promise | T; export type Defined = Exclude; export function toApiComplianceRegion( - region: ParsedInputSettingsConfig["complianceRegion"] + region: ParsedSettings["complianceRegion"] ): ComplianceConfig["compliance_region"] { return region === "fedramp-high" ? "fedramp_high" : region; } diff --git a/packages/vitest-plugin/CHANGELOG.md b/packages/vitest-plugin/CHANGELOG.md index ffe83df12f..ab583e8bd5 100644 --- a/packages/vitest-plugin/CHANGELOG.md +++ b/packages/vitest-plugin/CHANGELOG.md @@ -1,5 +1,33 @@ # @cloudflare/vitest-plugin +## 1.8.3 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`b219078`](https://github.com/cloudflare/workers-sdk/commit/b219078a4c1b008485ce022f01ad7292d613d9f0), [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b), [`db3c071`](https://github.com/cloudflare/workers-sdk/commit/db3c071619a64e0cf267fbadd4be12708c02df2d), [`81e56dd`](https://github.com/cloudflare/workers-sdk/commit/81e56ddf3e1ba28ea2320388fac86011a68f7be4), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b), [`4335eac`](https://github.com/cloudflare/workers-sdk/commit/4335eacef350c98722418fbb58b012a6964e26d7), [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b)]: + - wrangler@4.163.0 + - miniflare@5.20261116.0-beta + +## 1.8.2 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985), [`c889551`](https://github.com/cloudflare/workers-sdk/commit/c889551b0c1b66e5744ba891e207e4283ed3b5a5), [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373), [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373)]: + - wrangler@4.162.0 + - miniflare@5.20261113.0-beta + ## 1.8.1 ### Patch Changes diff --git a/packages/vitest-plugin/package.json b/packages/vitest-plugin/package.json index 1b8edd738e..3c811bd38b 100644 --- a/packages/vitest-plugin/package.json +++ b/packages/vitest-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/vitest-plugin", - "version": "1.8.1", + "version": "1.8.3", "description": "Workers Vitest integration for writing Vitest unit and integration tests that run inside the Workers runtime", "keywords": [ "cloudflare", diff --git a/packages/vitest-plugin/src/pool/config.ts b/packages/vitest-plugin/src/pool/config.ts index 274f6f4adf..5369e26e7b 100644 --- a/packages/vitest-plugin/src/pool/config.ts +++ b/packages/vitest-plugin/src/pool/config.ts @@ -30,10 +30,6 @@ import { getRunnerName, WORKER_NAME_PREFIX, } from "./helpers"; -import { - defaultNewConfigArtifactsToLocal, - defaultWranglerConfigArtifactsToLocal, -} from "./local-artifacts"; import { loadNewConfig, mergeCloudflareConfigWorker, @@ -674,14 +670,7 @@ async function parseCustomPoolOptions( if (newConfig !== undefined) { configPath = path.resolve(rootPath, newConfig.configPath); - const loadedConfig = await loadNewConfig(configPath, mode, envDir); - cloudflareConfig = { - ...loadedConfig, - worker: { - ...loadedConfig.worker, - env: defaultNewConfigArtifactsToLocal(loadedConfig.worker.env), - }, - }; + cloudflareConfig = await loadNewConfig(configPath, mode, envDir); const { worker, settings } = cloudflareConfig; options.resolvedConfig = { path: configPath, @@ -754,12 +743,10 @@ async function parseCustomPoolOptions( // we can pass the parsed config straight into // `unstable_getMiniflareWorkerOptions` without re-parsing it. const wrangler = await import("wrangler"); - config = defaultWranglerConfigArtifactsToLocal( - wrangler.unstable_readConfig({ - config: configPath, - env: environment, - }) - ); + config = wrangler.unstable_readConfig({ + config: configPath, + env: environment, + }); } if (configPath !== undefined && config !== undefined) { diff --git a/packages/vitest-plugin/src/pool/local-artifacts.ts b/packages/vitest-plugin/src/pool/local-artifacts.ts deleted file mode 100644 index ddf1f4e1f1..0000000000 --- a/packages/vitest-plugin/src/pool/local-artifacts.ts +++ /dev/null @@ -1,53 +0,0 @@ -import type { ParsedInputWorkerConfig } from "@cloudflare/config"; -import type { Config } from "@cloudflare/workers-utils"; - -// Tests should not create, push to or delete real repositories by accident, so -// Workers Vitest uses the local Artifacts simulator unless a binding opts into -// the deployed resource with `remote: true`. Wrangler and Vite default to the -// deployed resource instead, with a warning. -// -// Making the omitted setting explicit before anything else reads the config -// keeps the remote proxy session, the default-remote warning and Miniflare's -// routing in agreement. - -/** - * Sets `dev.remote: false` on `cloudflare.config.ts` Artifacts bindings that - * omit it. - * - * @param env The Worker's configured bindings. - * @returns The bindings, with every Artifacts binding's `dev.remote` set. - */ -export function defaultNewConfigArtifactsToLocal( - env: ParsedInputWorkerConfig["env"] -): ParsedInputWorkerConfig["env"] { - if (env === undefined) { - return env; - } - return Object.fromEntries( - Object.entries(env).map(([name, binding]) => [ - name, - binding.type === "artifacts" && binding.dev?.remote === undefined - ? { ...binding, dev: { ...binding.dev, remote: false } } - : binding, - ]) - ); -} - -/** - * Sets `remote: false` on Wrangler config Artifacts bindings that omit it. - * - * @param config The parsed Wrangler config. - * @returns The config, with every Artifacts binding's `remote` set. - */ -export function defaultWranglerConfigArtifactsToLocal(config: Config): Config { - if (config.artifacts.every((binding) => binding.remote !== undefined)) { - return config; - } - return { - ...config, - artifacts: config.artifacts.map((binding) => ({ - ...binding, - remote: binding.remote ?? false, - })), - }; -} diff --git a/packages/vitest-plugin/src/pool/new-config.ts b/packages/vitest-plugin/src/pool/new-config.ts index d630a6cba8..e48ce8fb7c 100644 --- a/packages/vitest-plugin/src/pool/new-config.ts +++ b/packages/vitest-plugin/src/pool/new-config.ts @@ -8,9 +8,9 @@ import { formatZodError, getZoneFromRoute } from "@cloudflare/workers-utils"; import { loadDevVars, loadEnv } from "@cloudflare/workers-utils/local-env"; import { Log, LogLevel, resolveLocalBindings } from "miniflare"; import type { - ParsedInputConfig, - ParsedInputContainerConfig, - ParsedInputWorkerConfig, + ParsedCloudflareConfig, + ParsedContainerConfig, + ParsedWorkerConfig, } from "@cloudflare/config"; import type { ContainerDevRuntimeOptions } from "@cloudflare/containers-shared"; import type { ComplianceConfig } from "@cloudflare/workers-utils"; @@ -21,10 +21,10 @@ export const NEW_CONFIG_FILENAME = "cloudflare.config.ts"; const log = new Log(LogLevel.INFO, { prefix: "vpw" }); export interface LoadedNewConfig { - settings: Pick; - worker: ParsedInputWorkerConfig; + settings: Pick; + worker: ParsedWorkerConfig; /** Containers the config defines; Durable Object exports reference them by name. */ - containers: ParsedInputContainerConfig[]; + containers: ParsedContainerConfig[]; /** The mode config functions were called with. */ mode: string; /** Values resolved from `.env` files and the process environment. */ @@ -102,7 +102,7 @@ export async function loadNewConfig( complianceRegion: result.data.complianceRegion, }, worker, - containers: result.data.containers, + containers: result.data.containers ?? [], mode, localEnv: localEnv.values, devVars, diff --git a/packages/vitest-plugin/test/artifacts-errors.test.ts b/packages/vitest-plugin/test/artifacts-errors.test.ts new file mode 100644 index 0000000000..c46a884058 --- /dev/null +++ b/packages/vitest-plugin/test/artifacts-errors.test.ts @@ -0,0 +1,42 @@ +import dedent from "ts-dedent"; +import { test, vitestConfig } from "./helpers"; + +// workerd logs any exception thrown across an RPC boundary as uncaught when it +// runs with `--verbose`, which Workers Vitest enables by default. +test("Workers Vitest does not report caught local Artifacts errors as uncaught", async ({ + expect, + seed, + vitestRun, +}) => { + await seed({ + "vitest.config.mts": vitestConfig({ + wrangler: { configPath: "./wrangler.jsonc" }, + }), + "wrangler.jsonc": JSON.stringify({ + name: "artifacts-errors-worker", + main: "./index.ts", + compatibility_date: "2026-09-03", + artifacts: [{ binding: "REPOS", namespace: "examples", remote: false }], + }), + "index.ts": "export default { fetch() { return new Response(); } };", + "index.test.ts": dedent` + import { env } from "cloudflare:test"; + import { it } from "vitest"; + + it("throws ArtifactsError in the test isolate", async ({ expect }) => { + const missing = await env.REPOS.get("missing").catch((error) => error); + expect(missing).toMatchObject({ + name: "ArtifactsError", + code: "NOT_FOUND", + numericCode: 10200, + }); + const invalid = await env.REPOS.create("-bad").catch((error) => error); + expect(invalid).toMatchObject({ code: "INVALID_REPO_NAME" }); + }); + `, + }); + + const result = await vitestRun(); + await expect(result.exitCode, result.stderr).resolves.toBe(0); + expect(result.stdout + result.stderr).not.toContain("uncaught exception"); +}); diff --git a/packages/vitest-plugin/test/artifacts-events.test.ts b/packages/vitest-plugin/test/artifacts-events.test.ts new file mode 100644 index 0000000000..c83c09c2ce --- /dev/null +++ b/packages/vitest-plugin/test/artifacts-events.test.ts @@ -0,0 +1,52 @@ +import dedent from "ts-dedent"; +import { test, vitestConfig } from "./helpers"; + +test("Workers Vitest starts Workflows from native Artifacts event triggers", async ({ + expect, + seed, + vitestRun, +}) => { + await seed({ + "vitest.config.mts": vitestConfig({ config: true }), + "cloudflare.config.ts": dedent` + export default { worker: { + name: "artifacts-test-worker", entrypoint: "./index.ts", + compatibilityDate: "2026-09-03", + env: { + REPOS: { type: "artifacts", namespace: "examples" }, + EVENTS: { type: "kv" }, + }, + exports: { OnEvent: { type: "workflow", name: "on-event", events: [{ + type: "cf.artifacts.repo.created", filter: { namespace: "examples" }, + }] } }, + } }; + `, + "index.ts": dedent` + import { WorkflowEntrypoint } from "cloudflare:workers"; + export class OnEvent extends WorkflowEntrypoint { + async run(event, step) { + await step.do("record", async () => { + await this.env.EVENTS.put("event", JSON.stringify(event.payload)); + return "recorded"; + }); + } + } + export default { fetch() { return new Response("ok"); } }; + `, + "index.test.ts": dedent` + import { env } from "cloudflare:test"; + import { it, vi } from "vitest"; + it("delivers a repository event to the configured Workflow", async ({ expect }) => { + await env.REPOS.create("demo"); + await vi.waitFor(async () => { + expect(await env.EVENTS.get("event", "json")).toMatchObject({ + type: "cf.artifacts.repo.created", + source: { namespace: "examples", repoName: "demo" }, + }); + }, { timeout: 5000 }); + }); + `, + }); + const result = await vitestRun(); + await expect(result.exitCode, result.stderr).resolves.toBe(0); +}); diff --git a/packages/vitest-plugin/test/artifacts-local.test.ts b/packages/vitest-plugin/test/artifacts-local.test.ts index b62f816635..a642e643e1 100644 --- a/packages/vitest-plugin/test/artifacts-local.test.ts +++ b/packages/vitest-plugin/test/artifacts-local.test.ts @@ -61,8 +61,8 @@ function cloudflareConfig(): Record { }; } -// Unlike Wrangler and Vite, Workers Vitest keeps tests away from real -// repositories: an omitted `remote` uses the local simulator, without a warning. +// An omitted `remote` uses the local simulator. Workers Vitest always did, so +// unlike Wrangler and Vite it doesn't warn that the default changed. test.for([ { label: "Wrangler config with remote=false", files: wranglerConfig(false) }, { @@ -84,6 +84,8 @@ test.for([ const result = await vitestRun(); await expect(result.exitCode, result.stderr).resolves.toBe(0); - expect(result.stdout + result.stderr).not.toContain("deployed resource"); + expect(result.stdout + result.stderr).not.toContain( + "uses the local simulator by default" + ); } ); diff --git a/packages/workers-auth/CHANGELOG.md b/packages/workers-auth/CHANGELOG.md index 96c4a5633b..3b62ce5302 100644 --- a/packages/workers-auth/CHANGELOG.md +++ b/packages/workers-auth/CHANGELOG.md @@ -1,5 +1,35 @@ # @cloudflare/workers-auth +## 0.18.3 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16874](https://github.com/cloudflare/workers-sdk/pull/16874) [`4335eac`](https://github.com/cloudflare/workers-sdk/commit/4335eacef350c98722418fbb58b012a6964e26d7) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Avoid redundant OAuth refreshes after a sibling process updates credentials + + Check access-token expiry and select the refresh token from the same fresh credential snapshot. When a sibling has already saved a valid access token, reuse it without another exchange or write. This prevents an unnecessary rotation that can let an older response overwrite a newer refresh token. + +- Updated dependencies [[`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155)]: + - @cloudflare/workers-utils@0.54.1 + +## 0.18.2 + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985)]: + - @cloudflare/workers-utils@0.54.0 + ## 0.18.1 ### Patch Changes diff --git a/packages/workers-auth/package.json b/packages/workers-auth/package.json index ba79767889..ba88a1cb3b 100644 --- a/packages/workers-auth/package.json +++ b/packages/workers-auth/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/workers-auth", - "version": "0.18.1", + "version": "0.18.3", "description": "Internal OAuth 2.0 + PKCE flow for Cloudflare CLIs. Not intended for external use — APIs may change without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/workers-auth#readme", "bugs": { diff --git a/packages/workers-auth/src/flow.ts b/packages/workers-auth/src/flow.ts index 86624f74e5..c9a5772e49 100644 --- a/packages/workers-auth/src/flow.ts +++ b/packages/workers-auth/src/flow.ts @@ -334,14 +334,23 @@ export function createOAuthFlow(ctx: OAuthFlowContext): OAuthFlowAPI { async function refreshToken( profile?: string ): Promise<"refreshed" | "rejected" | "unreachable"> { - // `exchangeRefreshTokenForAccessToken` reads the refresh token fresh from - // disk on every call, so we always pick up the latest rotation written by a - // sibling Wrangler process. Refresh tokens are single-use, so a long-lived - // process such as `wrangler dev` would otherwise send a stale value and get - // a 401 from the token endpoint. const storage = getStorage(profile); try { + // A sibling may have refreshed since the caller checked expiry. Use + // one fresh snapshot for both the expiry decision and the exchange. + const stored = readStoredAuthState({ + warningLogger: ctx.logger, + storage, + }); + if ( + stored.accessToken && + new Date() < new Date(stored.accessToken.expiry) + ) { + // Reusing credentials must not write an older snapshot back to disk. + return "refreshed"; + } + const { token: { value: oauth_token, expiry: expiration_time } = { value: "", @@ -353,7 +362,7 @@ export function createOAuthFlow(ctx: OAuthFlowContext): OAuthFlowAPI { ctx.logger, ctx.isNonInteractiveOrCI, getClientId(), - storage, + stored.refreshToken, ctx.cliDisplayName ); storage.write({ diff --git a/packages/workers-auth/src/token-exchange.ts b/packages/workers-auth/src/token-exchange.ts index 0985b375ce..e5a1fcbeb0 100644 --- a/packages/workers-auth/src/token-exchange.ts +++ b/packages/workers-auth/src/token-exchange.ts @@ -27,12 +27,10 @@ import { toErrorClass, } from "./errors"; import { generatePKCECodes, RECOMMENDED_STATE_LENGTH } from "./pkce"; -import { readStoredAuthState, type OAuthFlowState } from "./state"; -import type { AuthConfigStorage } from "./config-file/auth"; import type { OAuthFlowContext } from "./context"; import type { generateAuthUrl as defaultGenerateAuthUrl } from "./generate-auth-url"; import type { generateRandomState as defaultGenerateRandomState } from "./generate-random-state"; -import type { AccessToken, RefreshToken } from "./state"; +import type { AccessToken, OAuthFlowState, RefreshToken } from "./state"; import type { ParsedUrlQuery } from "node:querystring"; import type { Response } from "undici"; @@ -143,7 +141,7 @@ export async function getAuthURL( * @param logger Logger used for token-exchange diagnostics. * @param isNonInteractiveOrCI Whether interactive Access login is unavailable. * @param clientId OAuth client identifier for the consuming CLI. - * @param storage Storage containing the current refresh token. + * @param storedRefreshToken Refresh token from the caller's latest credential snapshot. * @param cliDisplayName Consumer name used in actionable Access errors. * @returns The refreshed OAuth access context. */ @@ -151,15 +149,9 @@ export async function exchangeRefreshTokenForAccessToken( logger: OAuthFlowContext["logger"], isNonInteractiveOrCI: OAuthFlowContext["isNonInteractiveOrCI"], clientId: string, - storage: AuthConfigStorage, + storedRefreshToken: RefreshToken | undefined, cliDisplayName: string ): Promise { - // Read the refresh token fresh from disk on every call so we always pick up - // the latest rotation written by a sibling Wrangler process. - const storedRefreshToken = readStoredAuthState({ - warningLogger: logger, - storage, - }).refreshToken; if (!storedRefreshToken) { logger.warn("No refresh token is present."); } diff --git a/packages/workers-auth/tests/refresh-expiry-recheck.test.ts b/packages/workers-auth/tests/refresh-expiry-recheck.test.ts new file mode 100644 index 0000000000..2daa4de8b4 --- /dev/null +++ b/packages/workers-auth/tests/refresh-expiry-recheck.test.ts @@ -0,0 +1,159 @@ +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, beforeEach, it, vi } from "vitest"; +import { clearAccessCaches } from "../src/access"; +import { createOAuthFlow } from "../src/flow"; +import type { + AuthConfigStorage, + UserAuthConfig, +} from "../src/config-file/auth"; +import type { OAuthFlowContext } from "../src/context"; + +const now = new Date("2026-11-12T12:00:00.000Z"); +const expired: UserAuthConfig = { + oauth_token: "expired-access", + refresh_token: "RT_A", + expiration_time: "2000-01-01T00:00:00.000Z", +}; +const fresh: UserAuthConfig = { + oauth_token: "sibling-access", + refresh_token: "RT_B", + expiration_time: "2099-01-01T00:00:00.000Z", + scopes: ["account:read"], +}; +const msw = setupServer(); +const refreshes: string[] = []; + +beforeAll(() => msw.listen({ onUnhandledRequest: "error" })); +beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(now); + refreshes.length = 0; + msw.use( + http.get("https://dash.cloudflare.com/", () => HttpResponse.text("")), + http.post( + "https://dash.cloudflare.com/oauth2/token", + async ({ request }) => { + const body = new URLSearchParams(await request.text()); + refreshes.push(body.get("refresh_token") ?? ""); + return HttpResponse.json({ + access_token: "refreshed-access", + refresh_token: "RT_C", + expires_in: 3600, + scope: "account:read", + }); + } + ) + ); +}); +afterEach(() => { + msw.resetHandlers(); + clearAccessCaches(); + vi.useRealTimers(); +}); +afterAll(() => msw.close()); + +/** Inject a sibling's write between the caller's expiry check and its refresh snapshot. */ +function storageWithSibling(sibling: UserAuthConfig, onRead: number) { + let stored = expired; + let reads = 0; + const write = vi.fn((config: UserAuthConfig) => { + stored = config; + }); + const storage: AuthConfigStorage = { + read() { + if (++reads === onRead) { + stored = sibling; + } + return stored; + }, + write, + clear() { + throw new Error("Unexpected credential deletion"); + }, + path: () => "", + }; + return { storage, write }; +} + +function flowWithStorage(storage: AuthConfigStorage) { + const ignore = () => {}; + const context: OAuthFlowContext = { + logger: { + debug: ignore, + info: ignore, + log: ignore, + warn: ignore, + error: ignore, + }, + isNonInteractiveOrCI: () => true, + openInBrowser: async () => { + throw new Error("Unexpected interactive login"); + }, + hasEnvCredentials: () => false, + clientId: "test-client-id", + consent: { + granted: { url: "https://example.com/granted" }, + denied: { url: "https://example.com/denied", error: "denied" }, + }, + cliDisplayName: "TestCLI", + deviceLoginCommand: "testcli login --device", + redirectUri: "http://localhost:8976/oauth/callback", + storageFactory: () => storage, + allowGlobalAuthKey: false, + temporary: undefined, + }; + return createOAuthFlow(context); +} + +it("reuses a sibling's valid credentials without refreshing or writing when resolving the access token", async ({ + expect, +}) => { + const { storage, write } = storageWithSibling(fresh, 2); + await expect( + flowWithStorage(storage).getOAuthTokenFromLocalState() + ).resolves.toBe("sibling-access"); + expect(refreshes).toEqual([]); + expect(write).not.toHaveBeenCalled(); + expect(storage.read()).toEqual(fresh); +}); + +it("reuses a sibling's valid credentials without refreshing or writing during login-or-refresh", async ({ + expect, +}) => { + const { storage, write } = storageWithSibling(fresh, 3); + await expect( + flowWithStorage(storage).loginOrRefreshIfRequired({ + complianceConfig: {}, + scopes: ["account:read"], + }) + ).resolves.toEqual({ loggedIn: true }); + expect(refreshes).toEqual([]); + expect(write).not.toHaveBeenCalled(); + expect(storage.read()).toEqual(fresh); +}); + +it.for([ + { name: "already expired", expiry: "2000-01-01T00:00:00.000Z" }, + { name: "expires exactly now", expiry: now.toISOString() }, + { name: "has no expiry", expiry: undefined }, +])( + "still refreshes the latest token when the sibling's access token $name", + async ({ expiry }, { expect }) => { + const { storage, write } = storageWithSibling( + { ...fresh, expiration_time: expiry }, + 2 + ); + await expect( + flowWithStorage(storage).getOAuthTokenFromLocalState() + ).resolves.toBe("refreshed-access"); + expect(refreshes).toEqual(["RT_B"]); + expect(write).toHaveBeenCalledOnce(); + expect(storage.read()).toEqual({ + oauth_token: "refreshed-access", + refresh_token: "RT_C", + expiration_time: new Date(now.getTime() + 3_600_000).toISOString(), + scopes: ["account:read"], + }); + } +); diff --git a/packages/workers-utils/CHANGELOG.md b/packages/workers-utils/CHANGELOG.md index 758212b6f4..6c318f5441 100644 --- a/packages/workers-utils/CHANGELOG.md +++ b/packages/workers-utils/CHANGELOG.md @@ -1,5 +1,43 @@ # @cloudflare/workers-utils +## 0.54.1 + +### Patch Changes + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16246](https://github.com/cloudflare/workers-sdk/pull/16246) [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155) Thanks [@leostera](https://github.com/leostera)! - Start local Workflows from Artifacts events + + Declare Artifacts events on `exports.workflow({ name, events })` in `cloudflare.config.ts` to start the owning Workflow locally in `cf`, Vite, and Workers Vitest. Wrangler configurations continue to use `triggers.events`. Native config conversion derives those targets from the Workflow export, and `cf migrate` attaches existing event subscriptions to their matching Workflow exports. + + Local Artifacts namespaces publish the documented `cf.artifacts.*` messages for repository create, import, fork, and delete operations and token creation and revocation. Successful create, import, and fork operations also publish the initial token-created event. Delivery follows the committed mutation, is unordered, and does not fail the repository operation if a destination rejects it. Push, clone, and fetch events are not yet published locally. This feature does not provide local Artifacts-to-queue subscriptions. + +## 0.54.0 + +### Minor Changes + +- [#16735](https://github.com/cloudflare/workers-sdk/pull/16735) [`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7) Thanks [@leostera](https://github.com/leostera)! - Use the local simulator for Artifacts bindings that omit `remote` + + **Behavior change:** Artifacts bindings now default to the local simulator during development, like KV, R2 and D1. Previously, an omitted `remote` in Wrangler and the Vite plugin used the deployed Artifacts resource. If you want deployed repos in `wrangler dev` or `vite dev`, set `"remote": true` on the binding (`dev: { remote: true }` in `cloudflare.config.ts`). Artifacts is in beta, so this ships as a minor release. + + While `remote` is omitted, `wrangler dev`, `getPlatformProxy()` and the Vite plugin warn when remote bindings are enabled, once for each binding rather than on every config reload: "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning." Workers Vitest and `wrangler dev --local` already used the simulator, so they don't warn. Local Artifacts needs no Cloudflare credentials, but requires Git 2.32 or newer on the host. + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16864](https://github.com/cloudflare/workers-sdk/pull/16864) [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985) Thanks [@MattieTK](https://github.com/MattieTK)! - Fix packages with nested `package.json` files missing from deploy metadata + + Packages such as `hono`, `stripe` and `@modelcontextprotocol/sdk` were silently omitted from the package dependency metadata reported during `wrangler deploy` and `wrangler versions upload`. These packages are now included with their installed versions. Autoconfig and codemods also detect their installed versions correctly. + ## 0.53.1 ### Patch Changes diff --git a/packages/workers-utils/package.json b/packages/workers-utils/package.json index 43f5e36674..d0d927bc35 100644 --- a/packages/workers-utils/package.json +++ b/packages/workers-utils/package.json @@ -1,6 +1,6 @@ { "name": "@cloudflare/workers-utils", - "version": "0.53.1", + "version": "0.54.1", "description": "Internal utility package for workers-sdk. Not intended for external use — APIs may change without notice.", "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/workers-utils#readme", "bugs": { diff --git a/packages/workers-utils/src/config/artifacts-local-default.ts b/packages/workers-utils/src/config/artifacts-local-default.ts new file mode 100644 index 0000000000..ab379acdcf --- /dev/null +++ b/packages/workers-utils/src/config/artifacts-local-default.ts @@ -0,0 +1,69 @@ +/** + * An Artifacts binding as far as its development default is concerned. + */ +export interface ArtifactsDevBinding { + /** The binding name, such as `REPOS`. */ + name: string; + /** The binding's configured `remote` setting. */ + remote: boolean | undefined; + /** + * The Worker that declares the binding. Set it when a config declares + * several Workers, so the warning says which one it means. + */ + worker?: string; +} + +/** + * Warns about Artifacts bindings that use the local simulator only because + * `remote` is omitted. + * + * @param project Identifies the project the bindings come from, such as its + * config path or root. Warnings are remembered per project, so two projects in + * one process each get their own. + */ +export type ArtifactsLocalDefaultWarner = ( + project: { id: string; bindings: Iterable }, + warn: (message: string) => void +) => void; + +/** + * Artifacts bindings used deployed repos by default during development, and + * now use the local simulator like every other binding. Someone who relied on + * the old default would silently stop seeing their deployed repos, so warn + * about an omitted `remote` where the default changed: development sessions + * with remote bindings enabled. Workers Vitest and `--local` sessions already + * used the simulator, so their callers don't warn. + * + * The returned warner warns once per project, Worker and binding, so a session + * that reloads its config doesn't repeat the warning. + * + * TODO: Remove when Artifacts is generally available. + * + * @param configFormat Which config format the bindings come from, so the + * warning names the setting the user can write: `remote` in a Wrangler config, + * `dev: { remote }` in `cloudflare.config.ts`. + */ +export function createArtifactsLocalDefaultWarner( + configFormat: "wrangler" | "cloudflare-config" +): ArtifactsLocalDefaultWarner { + const remoteSetting = (value: boolean) => + configFormat === "cloudflare-config" + ? `\`dev: { remote: ${value} }\`` + : `\`remote: ${value}\``; + const warned = new Set(); + return ({ id, bindings }, warn) => { + for (const { name, remote, worker } of bindings) { + // JSON keeps the parts apart whatever characters they contain. + const key = JSON.stringify([id, worker ?? null, name]); + if (remote !== undefined || warned.has(key)) { + continue; + } + warned.add(key); + const subject = + worker === undefined ? name : `${name} in Worker ${worker}`; + warn( + `Artifacts binding ${subject} uses the local simulator by default. Set ${remoteSetting(true)} to use deployed repos, or ${remoteSetting(false)} to silence this warning.` + ); + } + }; +} diff --git a/packages/workers-utils/src/config/binding-local-support.ts b/packages/workers-utils/src/config/binding-local-support.ts index 43ff6adaed..0c7e9ae5e9 100644 --- a/packages/workers-utils/src/config/binding-local-support.ts +++ b/packages/workers-utils/src/config/binding-local-support.ts @@ -8,8 +8,6 @@ import type { Binding } from "../types"; * `pickRemoteBindings()` and `validateBindingRemoteSetting()`. * * - `local-and-remote`: local simulator; `remote: true` opts into proxying. - * - `remote-default-with-local-opt-in`: remote by default; `remote: false` - * opts into the local simulator. * - `local-only`: local simulator only; `remote: true` is a config error. * - `remote`: no local simulator *yet* — requires explicit `remote: true`. * Move to `local-and-remote` once a simulator lands. @@ -20,7 +18,6 @@ import type { Binding } from "../types"; */ export type BindingLocalSupport = | "local-and-remote" - | "remote-default-with-local-opt-in" | "local-only" | "remote" | "DO-NOT-USE-this-resource-will-never-have-a-local-simulator"; @@ -60,7 +57,7 @@ const BINDING_LOCAL_SUPPORT: Record< // TODO: Miniflare currently ignores `remote: true` on queues, tracked in #13727. queue: "local-and-remote", flagship: "local-and-remote", - artifacts: "remote-default-with-local-opt-in", + artifacts: "local-and-remote", analytics_engine: "local-and-remote", vectorize: "remote", @@ -113,8 +110,6 @@ export function resolveBindingRemote( return true; case "local-only": return false; - case "remote-default-with-local-opt-in": - return !remoteBindingsDisabled && remote !== false; case "local-and-remote": case "remote": return !remoteBindingsDisabled && remote === true; @@ -126,48 +121,16 @@ export function resolveBindingRemote( * binding type's local-development capabilities. Throws `UserError` for * invalid combinations and uses the caller-provided logger for * valid-but-noteworthy ones. - * - * @param options.binding - Binding name, used to identify the binding in warnings - * @param options.remoteBindingsDisabled - Whether the dev session runs without - * remote bindings, as with `wrangler dev --local` - * @param options.configFormat - Which config format the binding came from, so - * warnings name the setting the user can write: `remote` in a Wrangler config, - * `dev: { remote }` in `cloudflare.config.ts`. Defaults to `"wrangler"`. */ export function validateBindingRemoteSetting( type: Binding["type"], remote: boolean | undefined, - warn: (message: string) => void, - { - binding, - remoteBindingsDisabled = false, - configFormat = "wrangler", - }: { - binding?: string; - remoteBindingsDisabled?: boolean; - configFormat?: "wrangler" | "cloudflare-config"; - } = {} + warn: (message: string) => void ) { - const remoteSetting = (value: boolean) => - configFormat === "cloudflare-config" - ? `\`dev: { remote: ${value} }\`` - : `\`remote: ${value}\``; const support = getBindingLocalSupport(type); switch (support) { case "local-and-remote": return; - case "remote-default-with-local-opt-in": - // Changes made during dev affect real data, so make the default visible. - if (remote === undefined && !remoteBindingsDisabled) { - const subject = - binding === undefined - ? `${getBindingTypeFriendlyName(type)} bindings use` - : `${getBindingTypeFriendlyName(type)} binding ${binding} uses`; - warn( - `${subject} the deployed resource. Set ${remoteSetting(false)} to use the local simulator, or ${remoteSetting(true)} to silence this warning.` - ); - } - return; case "local-only": if (remote === true) { throw new UserError( diff --git a/packages/workers-utils/src/config/validation.ts b/packages/workers-utils/src/config/validation.ts index b6756b39a1..d4218a823f 100644 --- a/packages/workers-utils/src/config/validation.ts +++ b/packages/workers-utils/src/config/validation.ts @@ -2403,10 +2403,11 @@ const validateTriggers: ValidatorFn = ( )) { if ( (filterName !== "namespace" && filterName !== "repo_name") || - typeof filterValue !== "string" + typeof filterValue !== "string" || + filterValue.length === 0 ) { diagnostics.errors.push( - `Expected "${eventFieldName}.filter" to contain only string "namespace" and "repo_name" fields, but got ${JSON.stringify(event.filter)}.` + `Expected "${eventFieldName}.filter" to contain only non-empty string "namespace" and "repo_name" fields, but got ${JSON.stringify(event.filter)}.` ); isValid = false; break; diff --git a/packages/workers-utils/src/default-compat-date.ts b/packages/workers-utils/src/default-compat-date.ts index 637a196f76..e80002908c 100644 --- a/packages/workers-utils/src/default-compat-date.ts +++ b/packages/workers-utils/src/default-compat-date.ts @@ -19,4 +19,4 @@ import type { CompatDate } from "./compatibility-date"; * @see https://github.com/cloudflare/workerd/blob/main/src/workerd/io/BUILD.bazel * @see https://github.com/cloudflare/workerd/blob/main/src/workerd/io/compatibility-date.c%2B%2B */ -export const DEFAULT_COMPAT_DATE: CompatDate = "2026-11-12"; +export const DEFAULT_COMPAT_DATE: CompatDate = "2026-11-16"; diff --git a/packages/workers-utils/src/index.ts b/packages/workers-utils/src/index.ts index 7272b52751..9ea06332c2 100644 --- a/packages/workers-utils/src/index.ts +++ b/packages/workers-utils/src/index.ts @@ -87,6 +87,11 @@ export { resolveBindingRemote, validateBindingRemoteSetting, } from "./config/binding-local-support"; +export { + type ArtifactsDevBinding, + type ArtifactsLocalDefaultWarner, + createArtifactsLocalDefaultWarner, +} from "./config/artifacts-local-default"; export { validatePagesConfig } from "./config/validation-pages"; diff --git a/packages/workers-utils/src/package-resolution.ts b/packages/workers-utils/src/package-resolution.ts index c2eebb5819..8cbeac9bf5 100644 --- a/packages/workers-utils/src/package-resolution.ts +++ b/packages/workers-utils/src/package-resolution.ts @@ -78,7 +78,8 @@ export function isPackageInstalled( * @param projectPath - The path of the project to check * @param opts - Options * @param opts.stopAtProjectPath - If `true`, stop walking up at the project's path - * @returns The installed version string, or `undefined` if the package is not installed + * @returns The installed version string, or `undefined` if the package is not + * installed or its manifest lacks a name or version */ export function getInstalledPackageVersion( packageName: string, @@ -94,16 +95,12 @@ export function getInstalledPackageVersion( } const lastDir = opts.stopAtProjectPath === true ? projectPath : undefined; - const packageJsonPath = findFileUp("package.json", packagePath, lastDir); + const packageJson = findPackageRootManifest(packagePath, lastDir); - if (!packageJsonPath) { + if (!packageJson) { return undefined; } - const packageJson = parsePackageJSON( - readFileSync(packageJsonPath), - packageJsonPath - ); // The requested package may be installed under an alias (e.g. vite+ // installs `@voidzero-dev/vite-plus-core` under the `vite` alias). In that // case the resolved package.json belongs to the aliased package, so its @@ -125,40 +122,52 @@ export function getInstalledPackageVersion( } /** - * Walks up from `startDir` looking for a file named `name`. - * Stops at `lastDir` (inclusive) if provided, otherwise walks to the filesystem root. + * Walks up from `startDir` to find and parse a package's root `package.json`. + * + * Dual-format packages (e.g. `hono`, `stripe`) often ship nested `package.json` + * files such as `dist/cjs/package.json` containing only `{"type": "commonjs"}`. + * These tell Node how to load the files in that directory but carry no `name` + * or `version`. When the package is resolved through its entry point, the + * nearest `package.json` may be one of these markers. Skip nameless manifests + * and stop at the first named manifest, returning `undefined` if it has no + * version. This also protects symlinked workspace packages resolved outside + * `node_modules` from inheriting an ancestor's version. Stop at the installed + * package's `node_modules` boundary if no named manifest is found. * - * @param name - The filename to search for * @param startDir - The directory to start searching from * @param lastDir - If provided, stop searching after reaching this directory - * @returns The full path to the found file, or `undefined` + * @returns The parsed root `package.json`, or `undefined` if none is found */ -function findFileUp( - name: string, +function findPackageRootManifest( startDir: string, lastDir?: string -): string | undefined { +): ReturnType | undefined { let dir = startDir; - const root = path.parse(dir).root; while (true) { - const candidate = path.join(dir, name); - try { - if (statSync(candidate).isFile()) { - return candidate; + const packageJsonPath = path.join(dir, "package.json"); + if (statSync(packageJsonPath, { throwIfNoEntry: false })?.isFile()) { + const packageJson = parsePackageJSON( + readFileSync(packageJsonPath), + packageJsonPath + ); + if (packageJson.name !== undefined) { + return packageJson.version !== undefined ? packageJson : undefined; } - } catch {} - - if (lastDir !== undefined && dir === lastDir) { - break; } const parent = path.dirname(dir); - if (parent === dir || dir === root) { - break; + // Use the installed directory rather than the manifest's name, which may + // be missing or differ from the requested name for npm aliases. + if ( + dir === lastDir || + parent === dir || + path.basename(parent) === "node_modules" || + (path.basename(parent).startsWith("@") && + path.basename(path.dirname(parent)) === "node_modules") + ) { + return undefined; } dir = parent; } - - return undefined; } diff --git a/packages/workers-utils/src/types.ts b/packages/workers-utils/src/types.ts index 641764b7fb..266a493b32 100644 --- a/packages/workers-utils/src/types.ts +++ b/packages/workers-utils/src/types.ts @@ -1,6 +1,7 @@ import type { ApiCredentials } from "./cfetch"; import type { Config } from "./config"; import type { + ArtifactsEventTrigger, CustomDomainRoute, ContainerApp, ContainerEngine, @@ -458,7 +459,8 @@ export type Trigger = | ({ type: "route" } & CustomDomainRoute) | { type: "cron"; cron: string } | ({ type: "queue-consumer" } & Omit) - | ({ type: "connect" } & ConnectHandler); + | ({ type: "connect" } & ConnectHandler) + | { type: "artifacts-event"; event: ArtifactsEventTrigger }; type DistributiveOmit = T extends unknown ? Omit diff --git a/packages/workers-utils/tests/config/artifacts-local-default.test.ts b/packages/workers-utils/tests/config/artifacts-local-default.test.ts new file mode 100644 index 0000000000..d4a5022326 --- /dev/null +++ b/packages/workers-utils/tests/config/artifacts-local-default.test.ts @@ -0,0 +1,90 @@ +import { describe, it, vi } from "vitest"; +import { createArtifactsLocalDefaultWarner } from "../../src/config/artifacts-local-default"; + +const REPOS = { name: "REPOS", remote: undefined }; + +describe("createArtifactsLocalDefaultWarner", () => { + it("warns about an omitted remote in a Wrangler config", ({ expect }) => { + const warn = vi.fn(); + createArtifactsLocalDefaultWarner("wrangler")( + { id: "wrangler.jsonc", bindings: [REPOS] }, + warn + ); + expect(warn).toHaveBeenCalledExactlyOnceWith( + "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning." + ); + }); + + it("names `dev: { remote }` for cloudflare.config.ts bindings", ({ + expect, + }) => { + const warn = vi.fn(); + createArtifactsLocalDefaultWarner("cloudflare-config")( + { id: "/project", bindings: [REPOS] }, + warn + ); + expect(warn).toHaveBeenCalledExactlyOnceWith( + "Artifacts binding REPOS uses the local simulator by default. Set `dev: { remote: true }` to use deployed repos, or `dev: { remote: false }` to silence this warning." + ); + }); + + it("does not warn for an explicit setting", ({ expect }) => { + const warn = vi.fn(); + createArtifactsLocalDefaultWarner("wrangler")( + { + id: "wrangler.jsonc", + bindings: [ + { name: "LOCAL", remote: false }, + { name: "REMOTE", remote: true }, + ], + }, + warn + ); + expect(warn).not.toHaveBeenCalled(); + }); + + it("warns once per binding across config reloads", ({ expect }) => { + const warn = vi.fn(); + const warnForDefault = createArtifactsLocalDefaultWarner("wrangler"); + warnForDefault({ id: "wrangler.jsonc", bindings: [REPOS] }, warn); + warnForDefault( + { + id: "wrangler.jsonc", + bindings: [REPOS, { name: "MORE", remote: undefined }], + }, + warn + ); + expect(warn.mock.calls.map(([message]) => message.split(" ")[2])).toEqual([ + "REPOS", + "MORE", + ]); + }); + + it("warns separately for each project in one process", ({ expect }) => { + const warn = vi.fn(); + const warnForDefault = createArtifactsLocalDefaultWarner("wrangler"); + warnForDefault({ id: "a/wrangler.jsonc", bindings: [REPOS] }, warn); + warnForDefault({ id: "b/wrangler.jsonc", bindings: [REPOS] }, warn); + expect(warn).toHaveBeenCalledTimes(2); + }); + + it("names the Worker, and warns for each Worker declaring the binding", ({ + expect, + }) => { + const warn = vi.fn(); + createArtifactsLocalDefaultWarner("cloudflare-config")( + { + id: "/project", + bindings: [ + { ...REPOS, worker: "api" }, + { ...REPOS, worker: "jobs" }, + ], + }, + warn + ); + expect(warn.mock.calls.map(([message]) => message)).toEqual([ + expect.stringMatching(/^Artifacts binding REPOS in Worker api uses /), + expect.stringMatching(/^Artifacts binding REPOS in Worker jobs uses /), + ]); + }); +}); diff --git a/packages/workers-utils/tests/config/binding-local-support.test.ts b/packages/workers-utils/tests/config/binding-local-support.test.ts index 9179106386..42fe6d2065 100644 --- a/packages/workers-utils/tests/config/binding-local-support.test.ts +++ b/packages/workers-utils/tests/config/binding-local-support.test.ts @@ -12,12 +12,12 @@ describe("resolveBindingRemote", () => { remoteBindingsDisabled: boolean; expected: boolean; }>([ - // Remote by default with local opt-in. + // Artifacts is local by default, like every local-and-remote binding. { type: "artifacts", remote: undefined, remoteBindingsDisabled: false, - expected: true, + expected: false, }, { type: "artifacts", @@ -198,46 +198,9 @@ describe("validateBindingRemoteSetting", () => { expect(() => validateBindingRemoteSetting("flagship", undefined, warn) ).not.toThrow(); - expect(warn).not.toHaveBeenCalled(); - }); - }); - - describe("remote-default bindings with local opt-in", () => { - it("warns when `remote` is omitted, naming the binding", ({ expect }) => { - validateBindingRemoteSetting("artifacts", undefined, warn, { - binding: "REPOS", - }); - expect(warn).toHaveBeenCalledWith( - "Artifacts binding REPOS uses the deployed resource. Set `remote: false` to use the local simulator, or `remote: true` to silence this warning." - ); - }); - - it("names `dev: { remote }` for cloudflare.config.ts bindings", ({ - expect, - }) => { - validateBindingRemoteSetting("artifacts", undefined, warn, { - binding: "REPOS", - configFormat: "cloudflare-config", - }); - expect(warn).toHaveBeenCalledWith( - "Artifacts binding REPOS uses the deployed resource. Set `dev: { remote: false }` to use the local simulator, or `dev: { remote: true }` to silence this warning." - ); - }); - - it("does not warn when remote bindings are disabled", ({ expect }) => { - validateBindingRemoteSetting("artifacts", undefined, warn, { - binding: "REPOS", - remoteBindingsDisabled: true, - }); - expect(warn).not.toHaveBeenCalled(); - }); - - it("does not throw or warn for an explicit setting", ({ expect }) => { - for (const remote of [true, false]) { - expect(() => - validateBindingRemoteSetting("artifacts", remote, warn) - ).not.toThrow(); - } + expect(() => + validateBindingRemoteSetting("artifacts", undefined, warn) + ).not.toThrow(); expect(warn).not.toHaveBeenCalled(); }); }); diff --git a/packages/workers-utils/tests/config/config-format.test.ts b/packages/workers-utils/tests/config/config-format.test.ts index 6e2a0910a7..c7380d7fea 100644 --- a/packages/workers-utils/tests/config/config-format.test.ts +++ b/packages/workers-utils/tests/config/config-format.test.ts @@ -48,7 +48,7 @@ describe("configFileName", () => { it("prefers the user-authored configuration path", ({ expect }) => { expect( configFileName( - "/project/.cloudflare/output/v0/workers/default/config.json", + "/project/.cloudflare/output/v1/workers/default/config.json", "/project/cloudflare.config.ts" ) ).toBe("cloudflare.config.ts"); diff --git a/packages/workers-utils/tests/config/validation/normalize-and-validate-config.test.ts b/packages/workers-utils/tests/config/validation/normalize-and-validate-config.test.ts index a94647bbfe..da103eba76 100644 --- a/packages/workers-utils/tests/config/validation/normalize-and-validate-config.test.ts +++ b/packages/workers-utils/tests/config/validation/normalize-and-validate-config.test.ts @@ -839,6 +839,31 @@ describe("normalizeAndValidateConfig()", () => { `); }); + it.for(["namespace", "repo_name"])( + "rejects an empty Artifacts %s filter", + (field, { expect }) => { + const { diagnostics } = normalizeAndValidateConfig( + { + triggers: { + events: [ + { + type: "cf.artifacts.repo.created", + filter: { [field]: "" }, + targets: [{ type: "workflow", workflow_name: "on-repo" }], + }, + ], + }, + }, + "wrangler.json", + "wrangler.json", + { env: undefined } + ); + expect(diagnostics.renderErrors()).toContain( + 'Expected "triggers.events[0].filter" to contain only non-empty string' + ); + } + ); + it("should accept Artifacts event triggers", ({ expect }) => { const expectedConfig: RawConfig = { triggers: { diff --git a/packages/workers-utils/tests/package-resolution.test.ts b/packages/workers-utils/tests/package-resolution.test.ts index 71578555b4..11d388b85c 100644 --- a/packages/workers-utils/tests/package-resolution.test.ts +++ b/packages/workers-utils/tests/package-resolution.test.ts @@ -57,6 +57,48 @@ function createEsmOnlyPackage(name: string, version: string): void { ); } +/** + * Creates a dual-format package in `node_modules/` under the current directory, + * laid out like `hono` or `stripe`: the exports map has no `"./package.json"` + * entry, the `require` entry point lives in a subdirectory, and that + * subdirectory contains a nested `package.json` marker with only a `type` + * field (no `name` or `version`). + * + * @param name - Package name (supports scoped like `@scope/pkg`) + * @param version - Version string to write into the root `package.json` + */ +function createPackageWithNestedTypeManifest( + name: string, + version: string +): void { + const pkgDir = path.join(process.cwd(), "node_modules", name); + const cjsDir = path.join(pkgDir, "dist", "cjs"); + fs.mkdirSync(cjsDir, { recursive: true }); + fs.writeFileSync(path.join(cjsDir, "index.js"), "module.exports = {}"); + fs.writeFileSync( + path.join(cjsDir, "package.json"), + JSON.stringify({ type: "commonjs" }, null, 2) + ); + fs.writeFileSync( + path.join(pkgDir, "package.json"), + JSON.stringify( + { + name, + version, + type: "module", + exports: { + ".": { + import: "./dist/index.js", + require: "./dist/cjs/index.js", + }, + }, + }, + null, + 2 + ) + ); +} + describe("getPackagePath", () => { runInTempDir(); @@ -127,6 +169,183 @@ describe("getInstalledPackageVersion", () => { expect(result).toBe("0.3.0"); }); + it.for(["nameless-pkg", "@scope/nameless-pkg"])( + "should return undefined for %s when its manifest has no name", + (packageName, { expect }) => { + createCjsPackage(packageName, "1.2.3"); + fs.writeFileSync( + path.join("node_modules", packageName, "package.json"), + JSON.stringify({ version: "1.2.3", exports: "./index.js" }) + ); + fs.writeFileSync( + "package.json", + JSON.stringify({ name: "test-project", version: "9.0.0" }) + ); + + expect( + getInstalledPackageVersion(packageName, process.cwd()) + ).toBeUndefined(); + } + ); + + it.for(["versionless-pkg", "@scope/versionless-pkg"])( + "should return undefined for %s when its manifest has no version", + (packageName, { expect }) => { + createCjsPackage(packageName, "1.2.3"); + fs.writeFileSync( + path.join("node_modules", packageName, "package.json"), + JSON.stringify({ name: packageName, exports: "./index.js" }) + ); + fs.writeFileSync( + "package.json", + JSON.stringify({ name: "test-project", version: "9.0.0" }) + ); + + expect( + getInstalledPackageVersion(packageName, process.cwd()) + ).toBeUndefined(); + } + ); + + it.for([ + { packageName: "workspace-pkg", version: undefined }, + { packageName: "@scope/workspace-pkg", version: undefined }, + { packageName: "versioned-workspace-pkg", version: "1.2.3" }, + ])( + "should use the workspace manifest for a symlinked package (%j)", + ({ packageName, version }, { expect }) => { + const workspaceDir = path.join(process.cwd(), "packages", "foo"); + const cjsDir = path.join(workspaceDir, "dist", "cjs"); + fs.mkdirSync(cjsDir, { recursive: true }); + fs.writeFileSync(path.join(cjsDir, "index.js"), "module.exports = {}"); + fs.writeFileSync( + path.join(cjsDir, "package.json"), + JSON.stringify({ type: "commonjs" }) + ); + fs.writeFileSync( + path.join(workspaceDir, "package.json"), + JSON.stringify({ + name: packageName, + version, + private: true, + exports: "./dist/cjs/index.js", + }) + ); + fs.writeFileSync( + "package.json", + JSON.stringify({ name: "monorepo", version: "9.0.0" }) + ); + const linkPath = path.join(process.cwd(), "node_modules", packageName); + fs.mkdirSync(path.dirname(linkPath), { recursive: true }); + fs.symlinkSync(workspaceDir, linkPath, "junction"); + + expect(getPackagePath(packageName, process.cwd())).toBe(cjsDir); + expect(getInstalledPackageVersion(packageName, process.cwd())).toBe( + version + ); + } + ); + + it.for(["anonymous-pkg", "@scope/anonymous-pkg"])( + "should not inherit an ancestor version when %s has no name or version", + (packageName, { expect }) => { + createPackageWithNestedTypeManifest(packageName, "1.2.3"); + fs.writeFileSync( + path.join("node_modules", packageName, "package.json"), + JSON.stringify({ exports: "./dist/cjs/index.js" }) + ); + fs.writeFileSync( + "package.json", + JSON.stringify({ name: "test-project", version: "9.0.0" }) + ); + if (packageName.startsWith("@")) { + fs.writeFileSync( + path.join("node_modules", "@scope", "package.json"), + JSON.stringify({ name: "scope-parent", version: "8.0.0" }) + ); + } + + expect( + getInstalledPackageVersion(packageName, process.cwd()) + ).toBeUndefined(); + } + ); + + it("should preserve bundled versions for an alias with nested type markers", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("vite", "0.1.0"); + fs.writeFileSync( + path.join("node_modules", "vite", "package.json"), + JSON.stringify({ + name: "@voidzero-dev/vite-plus-core", + version: "0.1.0", + bundledVersions: { vite: "7.3.0" }, + exports: "./dist/cjs/index.js", + }) + ); + + expect(getInstalledPackageVersion("vite", process.cwd())).toBe("7.3.0"); + }); + + it("should skip a nested manifest with only a version and return the root version", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("dual-pkg", "4.0.0"); + fs.writeFileSync( + path.join("node_modules", "dual-pkg", "dist", "cjs", "package.json"), + JSON.stringify({ type: "commonjs", version: "1.0.0" }) + ); + + expect(getInstalledPackageVersion("dual-pkg", process.cwd())).toBe("4.0.0"); + }); + + it("should stop at a named nested manifest without a version", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("dual-pkg", "4.0.0"); + fs.writeFileSync( + path.join("node_modules", "dual-pkg", "dist", "cjs", "package.json"), + JSON.stringify({ type: "commonjs", name: "nested-marker" }) + ); + + expect( + getInstalledPackageVersion("dual-pkg", process.cwd()) + ).toBeUndefined(); + }); + + it("should skip a nested package.json without a name and return the root version", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("dual-pkg", "4.13.18"); + + const result = getInstalledPackageVersion("dual-pkg", process.cwd()); + + expect(result).toBe("4.13.18"); + }); + + it("should skip a nested package.json without a name for a scoped package", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("@scope/dual-pkg", "1.32.2"); + + const result = getInstalledPackageVersion("@scope/dual-pkg", process.cwd()); + + expect(result).toBe("1.32.2"); + }); + + it("should skip a nested package.json without a name when stopping at the project path", ({ + expect, + }) => { + createPackageWithNestedTypeManifest("dual-pkg", "2.0.0"); + + const result = getInstalledPackageVersion("dual-pkg", process.cwd(), { + stopAtProjectPath: true, + }); + + expect(result).toBe("2.0.0"); + }); + it("should return undefined for a non-existent package", ({ expect }) => { const result = getInstalledPackageVersion( "nonexistent-package", diff --git a/packages/workers-utils/tests/print-bindings.test.ts b/packages/workers-utils/tests/print-bindings.test.ts index ef17472f47..6503075da4 100644 --- a/packages/workers-utils/tests/print-bindings.test.ts +++ b/packages/workers-utils/tests/print-bindings.test.ts @@ -81,7 +81,7 @@ describe("printBindings", () => { }); test.for([ - { label: "default", remote: undefined, disabled: false, mode: "remote" }, + { label: "default", remote: undefined, disabled: false, mode: "local" }, { label: "explicit local", remote: false, disabled: false, mode: "local" }, { label: "explicit remote", remote: true, disabled: false, mode: "remote" }, { diff --git a/packages/wrangler/AGENTS.md b/packages/wrangler/AGENTS.md index 270f6f5430..fce66c271a 100644 --- a/packages/wrangler/AGENTS.md +++ b/packages/wrangler/AGENTS.md @@ -24,7 +24,7 @@ Main CLI for Cloudflare Workers. ~2k-line yargs command tree in `src/index.ts`. - `src/cli.ts` — Build entry AND library API surface (dual-purpose). Calls `main()` when run directly; re-exports `./api` when imported as library. Also re-exports `parseCfWranglerArgs`, `parseCfWranglerBuildArgs`, `ArgParseError`, `runCfWranglerDev`, and `runCfWranglerBuild` for the `cf-wrangler` bin to call in-process. - `src/index.ts` — Yargs CLI tree builder (large file). Exports `main()`. NOT the package entry point despite the name. - `src/api/index.ts` — Public programmatic API barrel. -- `src/cf-wrangler/` — The `cf-wrangler` delegate entrypoint, an experimental escape hatch for projects that can't use `@cloudflare/vite-plugin`. It exposes `dev` with Wrangler's shared dev options plus `--mode` (mapped to `env`), and `build` with `--mode`. Config discovery, the new config format, and local development are enforced: config/script overrides, Wrangler global options, `--remote`, and `--no-local` are unsupported. See `src/cf-wrangler/README.md` for forwarding examples and limitations. Preview build context is supplied through `CLOUDFLARE_PREVIEW_BUILD`, matching framework-owned build commands. It is NOT a separate package and does NOT use the `unstable_dev` test harness. `bin/cf-wrangler.js` owns verb dispatch and passes the parsed options directly to the runtime. `src/cf-wrangler/dev.ts` (exported as `runCfWranglerDev`) validates options for direct callers, wraps `startDev` in the experimental-flags context and waits for teardown. `src/cf-wrangler/build.ts` (exported as `runCfWranglerBuild`) runs the Build Output Specification path used by `wrangler build --experimental-new-config --experimental-cf-build-output`, producing `.cloudflare/output/v0`. `src/cf-wrangler/args.ts` exports the strict dev and build parsers and `ArgParseError`; dev parsing reuses Wrangler's shared option definitions and validation. Unknown verbs and invalid arguments exit 2; the parent CLI uses unknown verbs for feature detection. +- `src/cf-wrangler/` — The `cf-wrangler` delegate entrypoint, an experimental escape hatch for projects that can't use `@cloudflare/vite-plugin`. It exposes `dev` with Wrangler's shared dev options plus `--mode` (mapped to `env`), and `build` with `--mode`. Config discovery, the new config format, and local development are enforced: config/script overrides, Wrangler global options, `--remote`, and `--no-local` are unsupported. See `src/cf-wrangler/README.md` for forwarding examples and limitations. Preview build context is supplied through `CLOUDFLARE_PREVIEW_BUILD`, matching framework-owned build commands. It is NOT a separate package and does NOT use the `unstable_dev` test harness. `bin/cf-wrangler.js` owns verb dispatch and passes the parsed options directly to the runtime. `src/cf-wrangler/dev.ts` (exported as `runCfWranglerDev`) validates options for direct callers, wraps `startDev` in the experimental-flags context and waits for teardown. `src/cf-wrangler/build.ts` (exported as `runCfWranglerBuild`) runs the Build Output Specification path used by `wrangler build --experimental-new-config --experimental-cf-build-output`, producing `.cloudflare/output/v1`. `src/cf-wrangler/args.ts` exports the strict dev and build parsers and `ArgParseError`; dev parsing reuses Wrangler's shared option definitions and validation. Unknown verbs and invalid arguments exit 2; the parent CLI uses unknown verbs for feature detection. ## Conventions (Wrangler-Specific) diff --git a/packages/wrangler/CHANGELOG.md b/packages/wrangler/CHANGELOG.md index e25fe8e51c..8d2b3381b7 100644 --- a/packages/wrangler/CHANGELOG.md +++ b/packages/wrangler/CHANGELOG.md @@ -1,5 +1,118 @@ # wrangler +## 4.163.0 + +### Minor Changes + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Write Build Output to `.cloudflare/output/v1/` and record the producer + + `vite build` and the experimental `wrangler build --experimental-cf-build-output` now write Build Output v1, with account settings nested under `settings` in the root `config.json`. They also record themselves as the `producer`, so readers can name the tool that wrote the output in error messages. Previews from Build Output read the account settings from their new location. + +- [#16246](https://github.com/cloudflare/workers-sdk/pull/16246) [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155) Thanks [@leostera](https://github.com/leostera)! - Start local Workflows from Artifacts events + + Declare Artifacts events on `exports.workflow({ name, events })` in `cloudflare.config.ts` to start the owning Workflow locally in `cf`, Vite, and Workers Vitest. Wrangler configurations continue to use `triggers.events`. Native config conversion derives those targets from the Workflow export, and `cf migrate` attaches existing event subscriptions to their matching Workflow exports. + + Local Artifacts namespaces publish the documented `cf.artifacts.*` messages for repository create, import, fork, and delete operations and token creation and revocation. Successful create, import, and fork operations also publish the initial token-created event. Delivery follows the committed mutation, is unordered, and does not fail the repository operation if a destination rejects it. Push, clone, and fetch events are not yet published locally. This feature does not provide local Artifacts-to-queue subscriptions. + +### Patch Changes + +- [#16803](https://github.com/cloudflare/workers-sdk/pull/16803) [`b219078`](https://github.com/cloudflare/workers-sdk/commit/b219078a4c1b008485ce022f01ad7292d613d9f0) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Run experimental cf projects with their installed Vite or Vite+ commands + + `cf dev`, `cf build`, and deployments that build your project can use Vite or Vite+ even when no framework command is detected. This removes the need for the internal `cf-vite` delegate and supports dependencies declared and hoisted at the root of a configured workspace. A workspace application using a custom-named Vite config should declare `@cloudflare/vite-plugin` in its own manifest, or add `vite` or `vite-plus` as a dependency or dev dependency to identify its tooling; this keeps shared root tools from selecting Vite for non-Vite siblings. Configs passed later via `--config` are evaluated by Vite when the command runs. Existing framework commands keep their priority. Consumers resolve bare executables using the detected `nodeModulesPaths` in order, adding `.bin` to each directory. Lookup stops at the validated workspace root; standalone applications use only their own `node_modules/.bin`. + + Project inspection can recognize an existing Cloudflare configuration before dependencies are installed. Running a command provides guidance when the required tools are missing or the plugin version does not support cf profiles (`>=2.0.0-beta.v.13 <3`). Vite evaluates the project configuration when the command runs, including dynamic configs and custom config files. Repair guidance uses the project’s detected package manager. Automatic setup asks users to convert CommonJS `.cjs` and `.cts` Vite configs to ESM imports and exports in `.mjs` or `.mts` before adding the ESM-only Cloudflare plugin. Native builds also work with the Windows shell. Pages migration safeguards, unsupported-framework setup checks, and Wrangler command selection retain their existing behavior. + +- [#16944](https://github.com/cloudflare/workers-sdk/pull/16944) [`db3c071`](https://github.com/cloudflare/workers-sdk/commit/db3c071619a64e0cf267fbadd4be12708c02df2d) Thanks [@danlapid](https://github.com/danlapid)! - Stop `wrangler dev` from missing config file changes made soon after a reload + + `wrangler dev` replaced its config file watcher on every reload without waiting for the new one to start, so a change saved in that gap was never applied. It now keeps one watcher while the set of watched files is unchanged, and reports a config as applied only once its files are being watched. A second change saved within 50 ms of the previous one is no longer dropped either. + +- [#16920](https://github.com/cloudflare/workers-sdk/pull/16920) [`81e56dd`](https://github.com/cloudflare/workers-sdk/commit/81e56ddf3e1ba28ea2320388fac86011a68f7be4) Thanks [@benbuzbee](https://github.com/benbuzbee)! - Use the effective `max_instances` value when choosing the default container rollout steps + + When `max_instances` was omitted, Wrangler deployed 20 instances but chose rollout steps as if there were 0 instances, so the rollout used a single 100% step. Wrangler now uses `[10, 100]` for omitted `max_instances`, while still using a single 100% step when `max_instances` is 0 or 1. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-16 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16946](https://github.com/cloudflare/workers-sdk/pull/16946) [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261113.1 | ^5.20261116.1 | + | workerd | 1.20261113.1 | 1.20261116.1 | + +- [#16874](https://github.com/cloudflare/workers-sdk/pull/16874) [`4335eac`](https://github.com/cloudflare/workers-sdk/commit/4335eacef350c98722418fbb58b012a6964e26d7) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Avoid redundant OAuth refreshes after a sibling process updates credentials + + Check access-token expiry and select the refresh token from the same fresh credential snapshot. When a sibling has already saved a valid access token, reuse it without another exchange or write. This prevents an unnecessary rotation that can let an older response overwrite a newer refresh token. + +- [#16917](https://github.com/cloudflare/workers-sdk/pull/16917) [`d36b39d`](https://github.com/cloudflare/workers-sdk/commit/d36b39d440a8f408f41dcf4925a81f2f8a58f73b) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Detect Cloudflare Build Output of any version before deploying + + `wrangler deploy`, `wrangler versions upload` and `wrangler preview` refuse to run in a project that has Cloudflare Build Output, because that output belongs to `cf`. Detection now looks for any `.cloudflare/output/v/` directory rather than only the root config of the current version, so output left by an older or newer `cf` is still caught. + +- Updated dependencies [[`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`e97c9f8`](https://github.com/cloudflare/workers-sdk/commit/e97c9f8bd2cdbd15faf402b146582e49d65dd1a7), [`349fc4e`](https://github.com/cloudflare/workers-sdk/commit/349fc4e7443aa744cbe129f84f28571bf8625155), [`0bf81ac`](https://github.com/cloudflare/workers-sdk/commit/0bf81ac16041a1f47f5474f7d6f5b0da6160f76b)]: + - miniflare@5.20261116.0-beta + +## 4.162.0 + +### Minor Changes + +- [#16735](https://github.com/cloudflare/workers-sdk/pull/16735) [`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7) Thanks [@leostera](https://github.com/leostera)! - Use the local simulator for Artifacts bindings that omit `remote` + + **Behavior change:** Artifacts bindings now default to the local simulator during development, like KV, R2 and D1. Previously, an omitted `remote` in Wrangler and the Vite plugin used the deployed Artifacts resource. If you want deployed repos in `wrangler dev` or `vite dev`, set `"remote": true` on the binding (`dev: { remote: true }` in `cloudflare.config.ts`). Artifacts is in beta, so this ships as a minor release. + + While `remote` is omitted, `wrangler dev`, `getPlatformProxy()` and the Vite plugin warn when remote bindings are enabled, once for each binding rather than on every config reload: "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning." Workers Vitest and `wrangler dev --local` already used the simulator, so they don't warn. Local Artifacts needs no Cloudflare credentials, but requires Git 2.32 or newer on the host. + +- [#16749](https://github.com/cloudflare/workers-sdk/pull/16749) [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373) Thanks [@vaishnav-mk](https://github.com/vaishnav-mk)! - Reject settings on a `workflows` binding to a Workflow declared in `exports` + + A `workflows` binding can still bind a Workflow that the Worker declares in `exports`, but it can no longer set `limits`, `concurrency`, `schedules`, `default_retention`, or `jurisdiction` for it. Set them on the export instead. Previously the binding and the export could both set them as long as they agreed, so configurations that set them on the binding now stop with an error that says which setting to move. + +- [#16749](https://github.com/cloudflare/workers-sdk/pull/16749) [`032f8c2`](https://github.com/cloudflare/workers-sdk/commit/032f8c2b4a9b83970fc4b54de70790b48e3ba373) Thanks [@vaishnav-mk](https://github.com/vaishnav-mk)! - Upload Workflow export settings with the Worker + + `wrangler deploy` and `wrangler versions upload` now include the settings of each `workflow` export (`limits`, `concurrency`, `schedules`, `default_retention`, and `jurisdiction`) in the upload, instead of sending only its type and name. Uploads of a Worker with `workflow` exports also send a `Cloudflare-Workers-Script-Api-Date` header, which lets the Workers API provision Workflow exports from these settings as part of the upload. `wrangler deploy` and `wrangler triggers deploy` still create or update each Workflow through the Workflows API afterwards, as before. + + If provisioning a scheduled Workflow fails because the account is on the free plan, `wrangler deploy` now explains that scheduled Workflows require a paid Workers plan. + +### Patch Changes + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-12 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update `DEFAULT_COMPAT_DATE` to 2026-11-13 + + Use the bundled workerd release's compatibility date by default when scaffolding new projects or when no compatibility date is configured. + +- [#16849](https://github.com/cloudflare/workers-sdk/pull/16849) [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261110.1 | ^5.20261112.1 | + | workerd | 1.20261110.1 | 1.20261112.1 | + +- [#16886](https://github.com/cloudflare/workers-sdk/pull/16886) [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28) Thanks [@dependabot](https://github.com/apps/dependabot)! - Update dependencies of "miniflare", "wrangler" + + The following dependency versions have been updated: + + | Dependency | From | To | + | ------------------------- | ------------- | ------------- | + | @cloudflare/workers-types | ^5.20261112.1 | ^5.20261113.1 | + | workerd | 1.20261112.1 | 1.20261113.1 | + +- [#16864](https://github.com/cloudflare/workers-sdk/pull/16864) [`3b1b408`](https://github.com/cloudflare/workers-sdk/commit/3b1b40832ac323de709001d9cc3823517b988985) Thanks [@MattieTK](https://github.com/MattieTK)! - Fix packages with nested `package.json` files missing from deploy metadata + + Packages such as `hono`, `stripe` and `@modelcontextprotocol/sdk` were silently omitted from the package dependency metadata reported during `wrangler deploy` and `wrangler versions upload`. These packages are now included with their installed versions. Autoconfig and codemods also detect their installed versions correctly. + +- [#16862](https://github.com/cloudflare/workers-sdk/pull/16862) [`c889551`](https://github.com/cloudflare/workers-sdk/commit/c889551b0c1b66e5744ba891e207e4283ed3b5a5) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Fix requests hanging when a local Worker reload finishes before an inflight request fails + + Wrangler now immediately processes retriable requests when the replacement Worker is already ready. Previously, these requests could remain queued until another request arrived, particularly on Windows where connection failures can take longer to report. + +- Updated dependencies [[`f005593`](https://github.com/cloudflare/workers-sdk/commit/f005593c1ed0d1f429dafc6919c4335f4d5070c7), [`61eacca`](https://github.com/cloudflare/workers-sdk/commit/61eacca214a9533f41fac98d732f1cfdd905ddf6), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`856842e`](https://github.com/cloudflare/workers-sdk/commit/856842ec973ddd530dd385d389d68408f8ce58e2), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28), [`3cea40b`](https://github.com/cloudflare/workers-sdk/commit/3cea40b078519222db432b5edf827ddc3e629a2a), [`63eb6da`](https://github.com/cloudflare/workers-sdk/commit/63eb6daa0eda348e1f9e86a506cfd80d104a1e28)]: + - miniflare@5.20261113.0-beta + ## 4.161.0 ### Minor Changes diff --git a/packages/wrangler/e2e/remote-binding/miniflare-remote-resources.test.ts b/packages/wrangler/e2e/remote-binding/miniflare-remote-resources.test.ts index 1d15660c65..f673ea14ff 100644 --- a/packages/wrangler/e2e/remote-binding/miniflare-remote-resources.test.ts +++ b/packages/wrangler/e2e/remote-binding/miniflare-remote-resources.test.ts @@ -531,7 +531,7 @@ const testCases: TestCase[] = [ miniflareConfig: (connection) => ({ PIPELINE: { type: "pipeline", - name: "preserve-e2e-pipelines", + streamId: "preserve-e2e-pipelines", dev: { remote: remote(connection) }, }, }), diff --git a/packages/wrangler/package.json b/packages/wrangler/package.json index 51795cbfe4..b570ca97e1 100644 --- a/packages/wrangler/package.json +++ b/packages/wrangler/package.json @@ -1,6 +1,6 @@ { "name": "wrangler", - "version": "4.161.0", + "version": "4.163.0", "description": "Command-line interface for all things Cloudflare Workers", "keywords": [ "assembly", diff --git a/packages/wrangler/src/__tests__/api/startDevWorker/ConfigController.test.ts b/packages/wrangler/src/__tests__/api/startDevWorker/ConfigController.test.ts index e91b7d16ea..49c0c14ce6 100644 --- a/packages/wrangler/src/__tests__/api/startDevWorker/ConfigController.test.ts +++ b/packages/wrangler/src/__tests__/api/startDevWorker/ConfigController.test.ts @@ -12,6 +12,26 @@ import { mockConsoleMethods } from "../../helpers/mock-console"; import { runWrangler } from "../../helpers/run-wrangler"; import type * as StartDevWorkerApi from "../../../api/startDevWorker"; +// Lets a test simulate a slow initial scan: a config watcher created while +// `initialScanDelayMs` is set only starts watching, and only becomes ready, +// that long after it is created. +const chokidarMock = vi.hoisted(() => ({ initialScanDelayMs: 0 })); +vi.mock("chokidar", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + watch: (...[paths, options]: Parameters) => { + const delay = chokidarMock.initialScanDelayMs; + if (delay === 0) { + return actual.watch(paths, options); + } + const watcher = new actual.FSWatcher(options); + setTimeout(() => watcher.add(paths), delay); + return watcher; + }, + }; +}); + // Declaration-level pins for the exported input chain: a fresh object // literal gets excess-property checking, which fails to compile if any of // these signatures regresses to the base `StartDevWorkerInput` (the @@ -60,6 +80,7 @@ describe("ConfigController", () => { await controller.teardown(); logger.debug("teardown complete"); logger.resetLoggerLevel(); + chokidarMock.initialScanDelayMs = 0; }); it("uses the effective registry for runtime config and the initial bindings display", async ({ @@ -697,4 +718,43 @@ describe("ConfigController", () => { expect(warningCount).toBe(1); }); + + it("should notice config changes made as soon as the previous one is applied", async ({ + expect, + }) => { + vi.stubEnv("WRANGLER_CI_DISABLE_CONFIG_WATCHING", "false"); + chokidarMock.initialScanDelayMs = 500; + const writeConfig = (edit: string) => + seed({ + "wrangler.toml": dedent /* toml */ ` + name = "my-worker" + main = "src/index.js" + compatibility_date = "2024-06-01" + + [vars] + EDIT = "${edit}" + `, + }); + const configUpdateFor = (edit: string) => + bus.waitFor( + "configUpdate", + (e) => + e.config.bindings?.EDIT?.type === "plain_text" && + e.config.bindings.EDIT.value === edit + ); + await seed({ "src/index.js": "export default {}" }); + await writeConfig("0"); + + const initial = configUpdateFor("0"); + await controller.set({ config: "./wrangler.toml" }); + await initial; + + // Each write lands right after the previous one has been applied, so it + // is only noticed if the config file is being watched by then. + for (const edit of ["1", "2", "3"]) { + const update = configUpdateFor(edit); + await writeConfig(edit); + await expect(update).resolves.toBeDefined(); + } + }); }); diff --git a/packages/wrangler/src/__tests__/build-output.test.ts b/packages/wrangler/src/__tests__/build-output.test.ts index 091c67dc28..c3ac6f3c1a 100644 --- a/packages/wrangler/src/__tests__/build-output.test.ts +++ b/packages/wrangler/src/__tests__/build-output.test.ts @@ -23,7 +23,7 @@ const WORKER_NAME = "build-output-test-worker"; // directory. Resolve at call time — `runInTempDir` changes the cwd after this // module is imported. function workerDir(): string { - return path.resolve(".cloudflare/output/v0/workers", "default"); + return path.resolve(".cloudflare/output/v1/workers", "default"); } function readOutputConfig() { @@ -35,7 +35,7 @@ function readOutputConfig() { } function rootConfigPath(): string { - return path.resolve(".cloudflare/output/v0", "config.json"); + return path.resolve(".cloudflare/output/v1", "config.json"); } function readRootConfig() { @@ -573,6 +573,7 @@ describe("wrangler build --experimental-cf-build-output", () => { expect(fs.existsSync(rootConfigPath())).toBe(true); expect(readRootConfig()).toEqual({ + producer: { name: "wrangler", version: "x.x.x" }, buildContext: { isPreview: false }, }); }); @@ -625,8 +626,8 @@ describe("wrangler build --experimental-cf-build-output", () => { ); expect(readRootConfig()).toEqual({ - accountId: "acc-123", - complianceRegion: "public", + producer: { name: "wrangler", version: "x.x.x" }, + settings: { accountId: "acc-123", complianceRegion: "public" }, buildContext: { isPreview: false, mode: "staging" }, }); }); diff --git a/packages/wrangler/src/__tests__/cf-build-output-guard.test.ts b/packages/wrangler/src/__tests__/cf-build-output-guard.test.ts index b4f30b0cd9..4cdd38183e 100644 --- a/packages/wrangler/src/__tests__/cf-build-output-guard.test.ts +++ b/packages/wrangler/src/__tests__/cf-build-output-guard.test.ts @@ -141,7 +141,7 @@ describe("findCloudflareBuildOutput", () => { expect(findCloudflareBuildOutput(process.cwd())).toBeUndefined(); }); - it("ignores a `.cloudflare/output` directory with no versioned root config", async ({ + it("ignores a `.cloudflare/output` directory with no version directory", async ({ expect, }) => { await seed({ ".cloudflare/output/notes.md": "an unrelated output folder" }); @@ -149,8 +149,50 @@ describe("findCloudflareBuildOutput", () => { expect(findCloudflareBuildOutput(process.cwd())).toBeUndefined(); }); - it("ignores a root config path that is a directory", async ({ expect }) => { - fs.mkdirSync(getRootConfigPath(process.cwd()), { recursive: true }); + it.for(["v0", "v2", "v10"])( + "detects Build Output in a %s directory", + async (version, { expect }) => { + await seed({ + [`.cloudflare/output/${version}/config.json`]: JSON.stringify({}), + }); + + expect(findCloudflareBuildOutput(process.cwd())).toBe( + path.resolve(".cloudflare/output") + ); + } + ); + + it("detects a symlinked version directory", async ({ expect }) => { + await seed({ "linked-output/config.json": JSON.stringify({}) }); + fs.mkdirSync(".cloudflare/output", { recursive: true }); + fs.symlinkSync( + path.resolve("linked-output"), + path.resolve(".cloudflare/output/v1"), + "dir" + ); + + expect(findCloudflareBuildOutput(process.cwd())).toBe( + path.resolve(".cloudflare/output") + ); + }); + + it("ignores `.cloudflare/output` entries that aren't version directories", async ({ + expect, + }) => { + await seed({ + ".cloudflare/output/v1": "a file, not a directory", + ".cloudflare/output/v1-old/config.json": JSON.stringify({}), + ".cloudflare/output/v01/config.json": JSON.stringify({}), + ".cloudflare/output/latest/config.json": JSON.stringify({}), + }); + + expect(findCloudflareBuildOutput(process.cwd())).toBeUndefined(); + }); + + it("ignores a `.cloudflare/output` path that is a file", async ({ + expect, + }) => { + await seed({ ".cloudflare/output": "not a directory" }); expect(findCloudflareBuildOutput(process.cwd())).toBeUndefined(); }); diff --git a/packages/wrangler/src/__tests__/cf-wrangler/build.test.ts b/packages/wrangler/src/__tests__/cf-wrangler/build.test.ts index 5267319ca7..97b61d355d 100644 --- a/packages/wrangler/src/__tests__/cf-wrangler/build.test.ts +++ b/packages/wrangler/src/__tests__/cf-wrangler/build.test.ts @@ -35,24 +35,24 @@ describe("cf-wrangler build", () => { expect(exitCode).toBe(0); expect( fs.existsSync( - path.resolve(".cloudflare/output/v0/workers/default/worker.config.json") + path.resolve(".cloudflare/output/v1/workers/default/worker.config.json") ) ).toBe(true); expect( fs.existsSync( - path.resolve(".cloudflare/output/v0/workers/default/bundle/index.js") + path.resolve(".cloudflare/output/v1/workers/default/bundle/index.js") ) ).toBe(true); const worker = JSON.parse( fs.readFileSync( path.resolve( - ".cloudflare/output/v0/workers/default/worker.config.json" + ".cloudflare/output/v1/workers/default/worker.config.json" ), "utf8" ) ); const rootConfig = JSON.parse( - fs.readFileSync(path.resolve(".cloudflare/output/v0/config.json"), "utf8") + fs.readFileSync(path.resolve(".cloudflare/output/v1/config.json"), "utf8") ); expect(worker).toMatchObject({ name: "preview-worker" }); @@ -80,7 +80,7 @@ describe("cf-wrangler build", () => { const exitCode = await runCfWranglerBuild({}); const assetsDir = path.resolve( - ".cloudflare/output/v0/workers/default/assets" + ".cloudflare/output/v1/workers/default/assets" ); expect(exitCode).toBe(0); diff --git a/packages/wrangler/src/__tests__/containers/config.test.ts b/packages/wrangler/src/__tests__/containers/config.test.ts index 1c576760ef..bdfd438a00 100644 --- a/packages/wrangler/src/__tests__/containers/config.test.ts +++ b/packages/wrangler/src/__tests__/containers/config.test.ts @@ -450,43 +450,67 @@ describe("getNormalizedContainerOptions", () => { }); }); - it("should default max_instances and rollout_step_percentage accordingly", async ({ - expect, - }) => { - writeFileSync("Dockerfile", "FROM scratch"); + it.for([ + { + maxInstances: undefined, + expected: { max_instances: 20, rollout_step_percentage: [10, 100] }, + }, + { + maxInstances: 0, + expected: { max_instances: 0, rollout_step_percentage: 100 }, + }, + { + maxInstances: 1, + expected: { max_instances: 1, rollout_step_percentage: 100 }, + }, + { + maxInstances: 2, + expected: { max_instances: 2, rollout_step_percentage: [10, 100] }, + }, + { + maxInstances: 20, + expected: { max_instances: 20, rollout_step_percentage: [10, 100] }, + }, + ])( + "should default rollout_step_percentage when max_instances is $maxInstances", + async ({ maxInstances, expected }, { expect }) => { + writeFileSync("Dockerfile", "FROM scratch"); - const config: Config = { - name: "test-worker", - configPath: "./wrangler.toml", - topLevelName: "test-worker", - containers: [ - { - class_name: "TestContainer", - image: path.resolve("./Dockerfile"), - name: "test-container", - }, - ], - durable_objects: { - bindings: [ + const config: Config = { + name: "test-worker", + configPath: "./wrangler.toml", + topLevelName: "test-worker", + containers: [ { - name: "TEST_DO", class_name: "TestContainer", + image: path.resolve("./Dockerfile"), + name: "test-container", + ...(maxInstances === undefined + ? {} + : { max_instances: maxInstances }), }, ], - }, - migrations: [{ tag: "v1", new_sqlite_classes: ["TestContainer"] }], - } as Partial as Config; + durable_objects: { + bindings: [ + { + name: "TEST_DO", + class_name: "TestContainer", + }, + ], + }, + migrations: [{ tag: "v1", new_sqlite_classes: ["TestContainer"] }], + } as Partial as Config; - const result = await getNormalizedContainerOptions(config, {}); + const result = await getNormalizedContainerOptions(config, {}); - expect(result).toHaveLength(1); - expect(result[0]).toMatchObject({ - name: "test-container", - class_name: "TestContainer", - max_instances: 20, - rollout_step_percentage: 100, - }); - }); + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ + name: "test-container", + class_name: "TestContainer", + ...expected, + }); + } + ); it("should handle custom limit configuration", async ({ expect }) => { // deprecated path for setting custom limits diff --git a/packages/wrangler/src/__tests__/deploy/workflows.test.ts b/packages/wrangler/src/__tests__/deploy/workflows.test.ts index 5e2585f8dd..b04b1afbe9 100644 --- a/packages/wrangler/src/__tests__/deploy/workflows.test.ts +++ b/packages/wrangler/src/__tests__/deploy/workflows.test.ts @@ -145,6 +145,7 @@ describe("deploy", () => { mockDeployWorkflow(expect, "my-workflow"); mockSubDomainRequest(); mockUploadWorkerRequest({ + expectedScriptApiDate: null, expectedBindings: [ { type: "workflow", @@ -1298,8 +1299,13 @@ describe("deploy", () => { mockSubDomainRequest(); mockUploadWorkerRequest({ expectedExports: { - MyWorkflow: { type: "workflow", name: "my-workflow" }, + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + }, }, + expectedScriptApiDate: "2026-11-09", }); await runWrangler("deploy"); @@ -1351,7 +1357,18 @@ describe("deploy", () => { mockSubDomainRequest(); mockUploadWorkerRequest({ expectedExports: { - MyWorkflow: { type: "workflow", name: "my-workflow" }, + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + concurrency: { limit: 5 }, + schedules: ["0 * * * *", "30 * * * *"], + default_retention: { + success_retention: "3 days", + error_retention: 86_400_000, + }, + jurisdiction: "fedramp", + }, }, }); @@ -1383,7 +1400,6 @@ describe("deploy", () => { binding: "WORKFLOW", name: "my-workflow", class_name: "MyWorkflow", - schedules: "0 * * * *", }, ], exports: { @@ -1419,7 +1435,11 @@ describe("deploy", () => { }, ], expectedExports: { - MyWorkflow: { type: "workflow", name: "my-workflow" }, + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + }, }, }); @@ -1430,11 +1450,47 @@ describe("deploy", () => { script_name: "test-name", class_name: "MyWorkflow", limits: { steps: 10 }, - schedules: [{ cron: "0 * * * *" }], }, ]); }); + it("should explain a paid-plan error for scheduled workflow exports returned by the deploy", async ({ + expect, + }) => { + writeWranglerConfig({ + main: "index.js", + exports: { + MyWorkflow: { + type: "workflow", + name: "my-workflow", + schedules: "0 * * * *", + }, + }, + }); + await fs.promises.writeFile("index.js", workflowSource); + + mockUploadWorkerRequest(); + msw.use( + http.post( + "*/accounts/:accountId/workers/scripts/:scriptName/deployments", + () => + HttpResponse.json( + createFetchResult(null, false, [ + { + code: WORKFLOW_CRON_REQUIRES_PAID_PLAN_CODE, + message: "workflow.cron_requires_paid_plan", + }, + ]), + { status: 403 } + ) + ) + ); + + await expect(runWrangler("deploy")).rejects.toThrow( + 'A Workflow has "schedules" configured, but scheduled Workflows require a paid Workers plan.' + ); + }); + it("should check a binding against an export using the name passed to --name", async ({ expect, }) => { diff --git a/packages/wrangler/src/__tests__/dev/artifacts-local.test.ts b/packages/wrangler/src/__tests__/dev/artifacts-local.test.ts index 7befd411b0..291432aeba 100644 --- a/packages/wrangler/src/__tests__/dev/artifacts-local.test.ts +++ b/packages/wrangler/src/__tests__/dev/artifacts-local.test.ts @@ -45,29 +45,50 @@ type Created = { remote: string; token: string }; // Startup and reloads have taken over 20 seconds on shared Windows runners. const READY_TIMEOUT = 45_000; +const eventsWorker = `import { WorkflowEntrypoint } from "cloudflare:workers"; +export class OnRepoCreated extends WorkflowEntrypoint { + async run(event, step) { + await step.do("record", async () => { + await this.env.EVENTS.put(event.payload.source.repoName, JSON.stringify(event.payload)); + return "recorded"; + }); + } +} +export default { + async fetch(request, env) { + const name = new URL(request.url).pathname.slice(1); + if (request.method === "POST") return Response.json(await env.REPOS.create(name)); + return new Response(await env.EVENTS.get(name), { status: 200 }); + } +};`; + async function startLocalDev({ remote = false, args = "", + files, }: { /** `null` omits the setting. */ remote?: boolean | null; args?: string; + files?: Record; } = {}) { - await seed({ - "wrangler.jsonc": JSON.stringify({ - name: "artifacts-local-dev", - main: "index.js", - compatibility_date: "2026-09-03", - artifacts: [ - { - binding: "REPOS", - namespace: "examples", - ...(remote === null ? {} : { remote }), - }, - ], - }), - "index.js": worker, - }); + await seed( + files ?? { + "wrangler.jsonc": JSON.stringify({ + name: "artifacts-local-dev", + main: "index.js", + compatibility_date: "2026-09-03", + artifacts: [ + { + binding: "REPOS", + namespace: "examples", + ...(remote === null ? {} : { remote }), + }, + ], + }), + "index.js": worker, + } + ); const previousOutput = output.out; const stopped = runWrangler(`dev --port=0 --inspector-port=0 ${args}`, { WRANGLER_CI_DISABLE_CONFIG_WATCHING: "false", @@ -198,11 +219,15 @@ describe("Wrangler dev local Artifacts", { concurrent: false }, () => { } ); - it.for([null, true])( - "uses the local simulator for remote=%s with --local", + it.for([ + { remote: null, args: "" }, + { remote: null, args: "--local" }, + { remote: true, args: "--local" }, + ])( + "uses the local simulator for remote=$remote with args '$args'", { timeout: ARTIFACTS_DEV_TEST_TIMEOUT }, - async (remote, { expect }) => { - const dev = await startLocalDev({ remote, args: "--local" }); + async ({ remote, args }, { expect }) => { + const dev = await startLocalDev({ remote, args }); try { expect(output.out).toMatch( /env\.REPOS \(examples\)\s+Artifacts\s+local/ @@ -210,7 +235,87 @@ describe("Wrangler dev local Artifacts", { concurrent: false }, () => { expect( (await request<{ repos: unknown[] }>(dev.url, "/list")).repos ).toEqual([]); - expect(output.warn).not.toContain("uses the deployed resource"); + const defaultWarning = + "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning."; + // `--local` always used the simulator, so only the default warns. + if (remote === null && args === "") { + expect(output.warn).toContain(defaultWarning); + } else { + expect(output.warn).not.toContain(defaultWarning); + } + } finally { + await stopRunningDev(); + await dev.stopped; + } + } + ); + + it.for(["binding", "export"] as const)( + "starts a Workflow %s from Artifacts triggers.events", + async (mode, { expect }) => { + const dev = await startLocalDev({ + files: { + "wrangler.jsonc": JSON.stringify({ + name: "artifacts-local-events", + main: "index.js", + compatibility_date: "2026-09-03", + artifacts: [ + { binding: "REPOS", namespace: "examples", remote: false }, + ], + kv_namespaces: [{ binding: "EVENTS", id: "events" }], + ...(mode === "binding" + ? { + workflows: [ + { + binding: "ON_REPO_CREATED", + name: "on-repo-created", + class_name: "OnRepoCreated", + }, + ], + } + : { + exports: { + OnRepoCreated: { + type: "workflow", + name: "on-repo-created", + }, + }, + }), + triggers: { + events: [ + { + type: "cf.artifacts.repo.created", + filter: { namespace: "examples", repo_name: "demo" }, + targets: [ + { type: "workflow", workflow_name: "on-repo-created" }, + ], + }, + ], + }, + }), + "index.js": eventsWorker, + }, + }); + try { + await fetch(dev.url + "/ignored", { method: "POST" }); + await fetch(dev.url + "/demo", { method: "POST" }); + await vi.waitFor( + async () => { + expect(await (await fetch(dev.url + "/demo")).json()).toMatchObject( + { + type: "cf.artifacts.repo.created", + source: { + type: "artifacts", + namespace: "examples", + repoName: "demo", + }, + payload: { defaultBranch: "main" }, + } + ); + }, + { timeout: 15_000 } + ); + expect(await (await fetch(dev.url + "/ignored")).text()).toBe(""); } finally { await stopRunningDev(); await dev.stopped; diff --git a/packages/wrangler/src/__tests__/dev/miniflare-workflow-events.test.ts b/packages/wrangler/src/__tests__/dev/miniflare-workflow-events.test.ts new file mode 100644 index 0000000000..90f3025184 --- /dev/null +++ b/packages/wrangler/src/__tests__/dev/miniflare-workflow-events.test.ts @@ -0,0 +1,93 @@ +import { describe, it } from "vitest"; +import { buildMiniflareBindingOptions } from "../../dev/miniflare"; +import type { ArtifactsEventTrigger, Binding } from "@cloudflare/workers-utils"; + +const CREATED: ArtifactsEventTrigger = { + type: "cf.artifacts.repo.created", + filter: { namespace: "ci", repo_name: "app" }, + targets: [{ type: "workflow", workflow_name: "jobs" }], +}; + +function buildWorkflowOptions({ + bindings = {}, + exports, + artifactsEvents = [CREATED], +}: { + bindings?: Record; + exports?: Parameters[0]["exports"]; + artifactsEvents?: ArtifactsEventTrigger[]; +}) { + const { bindingOptions } = buildMiniflareBindingOptions( + { + name: "app", + complianceRegion: undefined, + bindings, + queueConsumers: undefined, + migrations: undefined, + exports, + tails: [], + streamingTails: [], + enableContainers: false, + artifactsEvents, + }, + undefined + ); + return { + workflows: bindingOptions.workflows, + workflowExports: bindingOptions.workflowExports, + }; +} + +const JOBS_BINDING: Binding = { + type: "workflow", + name: "jobs", + class_name: "Jobs", +}; +const EXPECTED_EVENTS = [ + { + type: "cf.artifacts.repo.created", + filter: { namespace: "ci", repoName: "app" }, + }, +]; + +describe("Workflow events in local dev", () => { + it("gives events to the export when a binding declares the same Workflow", ({ + expect, + }) => { + const options = buildWorkflowOptions({ + bindings: { JOBS: JOBS_BINDING }, + exports: { Jobs: { type: "workflow", name: "jobs" } }, + }); + expect(options.workflowExports?.Jobs.events).toEqual(EXPECTED_EVENTS); + expect(options.workflows?.JOBS.events).toBeUndefined(); + }); + + it("gives events to the first local binding when there is no export", ({ + expect, + }) => { + const options = buildWorkflowOptions({ + bindings: { + REMOTE: { ...JOBS_BINDING, script_name: "another-worker" }, + JOBS: { ...JOBS_BINDING, script_name: "app" }, + JOBS_AGAIN: JOBS_BINDING, + }, + }); + expect(options.workflows?.REMOTE.events).toBeUndefined(); + expect(options.workflows?.JOBS.events).toEqual(EXPECTED_EVENTS); + expect(options.workflows?.JOBS_AGAIN.events).toBeUndefined(); + }); + + it.for<{ case: string; bindings: Record }>([ + { case: "missing", bindings: {} }, + { + case: "external", + bindings: { + JOBS: { ...JOBS_BINDING, script_name: "another-worker" }, + }, + }, + ])("rejects a $case target like deploy does", ({ bindings }, { expect }) => { + expect(() => buildWorkflowOptions({ bindings })).toThrow( + 'Event trigger "cf.artifacts.repo.created" targets Workflow "jobs", but that Workflow is not defined by this Worker.' + ); + }); +}); diff --git a/packages/wrangler/src/__tests__/dev/remote-bindings.test.ts b/packages/wrangler/src/__tests__/dev/remote-bindings.test.ts index ff3e5e0263..13a5dbebfe 100644 --- a/packages/wrangler/src/__tests__/dev/remote-bindings.test.ts +++ b/packages/wrangler/src/__tests__/dev/remote-bindings.test.ts @@ -543,7 +543,6 @@ describe("dev with remote bindings", { concurrent: false, retry: 2 }, () => { artifacts: { MY_ARTIFACTS: { namespace: "default", - remote: true, remoteProxyConnectionString, }, }, @@ -644,7 +643,6 @@ describe("dev with remote bindings", { concurrent: false, retry: 2 }, () => { expect(proxyWorkerBindings).toEqual(undefined); // Let's make a fetch to the worker to prove it's running before we update the config to add the bindings - // This also should give the config file watching time to settle. const url = match?.groups?.url; if (url === undefined) { throw new Error("No URL found in output"); @@ -709,7 +707,8 @@ describe("dev with remote bindings", { concurrent: false, retry: 2 }, () => { () => std.out.match(/Ready on (?http:\/\/[^:]+:\d{4}.+)/), { timeout: devReadyTimeout } ); - // Give the config file watching time to settle + // By the time `wrangler dev` is ready it is watching the config file, so + // the edits below need no delay before them. const url = match?.groups?.url; assert(url); expect((await fetch(url)).ok).toBe(true); @@ -740,41 +739,51 @@ describe("dev with remote bindings", { concurrent: false, retry: 2 }, () => { await wranglerStopped; }); - it("routes Artifacts remotely when remote is omitted", async ({ expect }) => { + it("routes Artifacts locally when remote is omitted, warning once across config reloads", async ({ + expect, + }) => { + const writeConfig = (vars: Record) => + seed({ + "wrangler.jsonc": JSON.stringify({ + name: "worker", + main: "index.js", + compatibility_date: "2025-01-01", + artifacts: [{ binding: "MY_ARTIFACTS", namespace: "default" }], + vars, + }), + }); + await writeConfig({}); await seed({ - "wrangler.jsonc": JSON.stringify({ - name: "worker", - main: "index.js", - compatibility_date: "2025-01-01", - artifacts: [{ binding: "MY_ARTIFACTS", namespace: "default" }], - }), "index.js": `export default { fetch() { return new Response("hello") } }`, }); - const wranglerStopped = runWrangler("dev --port=0 --inspector-port=0"); + const wranglerStopped = runWrangler("dev --port=0 --inspector-port=0", { + // Config changes only reload when config watching is enabled + WRANGLER_CI_DISABLE_CONFIG_WATCHING: "false", + }); await vi.waitFor(() => expect(std.out).toMatch(/Ready/), { timeout: devReadyTimeout, }); - expect(startRemoteProxySessionCallCount).toBe(1); - expect(proxyWorkerBindings).toEqual({ - MY_ARTIFACTS: expect.objectContaining({ - type: "artifacts", - namespace: "default", - }), - }); + expect(startRemoteProxySessionCallCount).toBe(0); expect(workerOptions).toEqual([ expect.objectContaining({ artifacts: { MY_ARTIFACTS: { namespace: "default", - remote: undefined, - remoteProxyConnectionString, + remoteProxyConnectionString: undefined, }, }, }), ]); - expect(std.warn).toContain( - "Artifacts binding MY_ARTIFACTS uses the deployed resource. Set `remote: false` to use the local simulator, or `remote: true` to silence this warning." + + // A config reload doesn't repeat the warning. + await writeConfig({ EDIT: "1" }); + await vi.waitFor( + () => expect(workerOptions[0]).toMatchObject({ bindings: { EDIT: "1" } }), + { timeout: devReadyTimeout } ); + const warning = + "Artifacts binding MY_ARTIFACTS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning."; + expect(std.warn.split(warning)).toHaveLength(2); await stopWrangler(); await wranglerStopped; }); diff --git a/packages/wrangler/src/__tests__/experimental-config/load.test.ts b/packages/wrangler/src/__tests__/experimental-config/load.test.ts index c08aac8abc..06e75b43a0 100644 --- a/packages/wrangler/src/__tests__/experimental-config/load.test.ts +++ b/packages/wrangler/src/__tests__/experimental-config/load.test.ts @@ -227,11 +227,11 @@ describe("loadNewConfig", () => { const result = await loadNewConfig({ cwd: process.cwd(), args: {} }); - expect(result.parsedConfig.containers.map(({ name }) => name)).toEqual([ + expect(result.parsedConfig.containers?.map(({ name }) => name)).toEqual([ "api", "sessions", ]); - expect(result.parsedConfig.containers[0]).toMatchObject({ + expect(result.parsedConfig.containers?.[0]).toMatchObject({ name: "api", image: { reference: "registry.example.com/api:latest" }, }); @@ -269,7 +269,6 @@ describe("loadNewConfig", () => { { name: "api", image: "registry.example.com/api:latest", - max_instances: 20, }, ]); }); diff --git a/packages/wrangler/src/__tests__/experimental-config/workflows.test.ts b/packages/wrangler/src/__tests__/experimental-config/workflows.test.ts new file mode 100644 index 0000000000..2fe5fa80e5 --- /dev/null +++ b/packages/wrangler/src/__tests__/experimental-config/workflows.test.ts @@ -0,0 +1,121 @@ +import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; +import { http, HttpResponse } from "msw"; +import dedent from "ts-dedent"; +import { beforeEach, describe, it, vi } from "vitest"; +import { mockLastDeploymentRequest } from "../deploy/helpers"; +import { mockAccountId, mockApiToken } from "../helpers/mock-account-id"; +import { mockConsoleMethods } from "../helpers/mock-console"; +import { mockUploadWorkerRequest } from "../helpers/mock-upload-worker"; +import { mockGetSettings } from "../helpers/mock-worker-settings"; +import { mockSubDomainRequest } from "../helpers/mock-workers-subdomain"; +import { createFetchResult, msw } from "../helpers/msw"; +import { mswListNewDeploymentsLatestFull } from "../helpers/msw/handlers/versions"; +import { runWrangler } from "../helpers/run-wrangler"; + +vi.mock("@cloudflare/config", async (importOriginal) => { + const { createConfigMock } = await import("../helpers/mock-new-config"); + return createConfigMock(importOriginal); +}); + +describe("Workflows in cloudflare.config.ts", () => { + runInTempDir(); + mockAccountId(); + mockApiToken(); + mockConsoleMethods(); + beforeEach(() => { + msw.use( + http.get( + "*/accounts/:accountId/workers/scripts/:scriptName/secrets", + () => HttpResponse.json(createFetchResult([])) + ), + http.get("*/accounts/:accountId/workflows/:workflowName", () => + HttpResponse.json( + createFetchResult(null, false, [ + { code: 10200, message: "Workflow not found" }, + ]), + { status: 404 } + ) + ) + ); + }); + + it("deploys a Workflow export that the Worker also binds", async ({ + expect, + }) => { + await seed({ + "cloudflare.config.ts": dedent` + export default { worker: { + name: "test-name", + entrypoint: "./index.js", + compatibilityDate: "2025-12-02", + exports: { + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + schedules: "0 * * * *", + defaultRetention: { successRetention: "3 days" }, + }, + }, + env: { + WORKFLOW: { type: "workflow", name: "my-workflow", worker: "test-name", exportName: "MyWorkflow" }, + }, + } }; + `, + "index.js": dedent` + import { WorkflowEntrypoint } from "cloudflare:workers"; + export default {}; + export class MyWorkflow extends WorkflowEntrypoint {} + `, + }); + mockGetSettings(); + mockLastDeploymentRequest(); + msw.use(...mswListNewDeploymentsLatestFull); + mockSubDomainRequest(); + mockUploadWorkerRequest({ + expectedBindings: [ + { + type: "workflow", + name: "WORKFLOW", + workflow_name: "my-workflow", + class_name: "MyWorkflow", + script_name: "test-name", + }, + ], + expectedExports: { + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + schedules: "0 * * * *", + default_retention: { success_retention: "3 days" }, + }, + }, + expectedScriptApiDate: "2026-11-09", + }); + const putBodies: unknown[] = []; + msw.use( + http.put( + "*/accounts/:accountId/workflows/:workflowName", + async ({ request }) => { + putBodies.push(await request.json()); + return HttpResponse.json( + createFetchResult({ id: "mock-new-workflow-id" }) + ); + } + ) + ); + + await runWrangler("deploy --experimental-new-config"); + + expect(putBodies).toEqual([ + { + script_name: "test-name", + class_name: "MyWorkflow", + limits: { steps: 10 }, + schedules: [{ cron: "0 * * * *" }], + default_retention: { success_retention: "3 days" }, + }, + ]); + }); +}); diff --git a/packages/wrangler/src/__tests__/get-platform-proxy.test.ts b/packages/wrangler/src/__tests__/get-platform-proxy.test.ts index 7955451a09..8a4dcd2984 100644 --- a/packages/wrangler/src/__tests__/get-platform-proxy.test.ts +++ b/packages/wrangler/src/__tests__/get-platform-proxy.test.ts @@ -1,10 +1,12 @@ import { mkdirSync } from "node:fs"; +import path from "node:path"; import { runInTempDir, writeWranglerConfig, } from "@cloudflare/workers-utils/test-helpers"; import { fetch } from "undici"; import { beforeEach, describe, it, vi } from "vitest"; +import { mockConsoleMethods } from "./helpers/mock-console"; const { miniflareInstances } = vi.hoisted(() => ({ miniflareInstances: [] as Array<{ ready: Promise }>, @@ -27,6 +29,7 @@ import { getPlatformProxy } from "../api"; describe("getPlatformProxy", () => { runInTempDir(); + const std = mockConsoleMethods(); beforeEach(() => { miniflareInstances.length = 0; @@ -64,4 +67,66 @@ describe("getPlatformProxy", () => { await platform.dispose(); } }); + + it("warns once about an omitted Artifacts remote when remote bindings are enabled", async ({ + expect, + }) => { + writeWranglerConfig( + { + name: "test-worker", + compatibility_date: "2026-11-02", + artifacts: [{ binding: "REPOS", namespace: "examples" }], + }, + "./wrangler.json" + ); + const warning = + "Artifacts binding REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning."; + const start = async (remoteBindings: boolean) => + ( + await getPlatformProxy({ + configPath: "./wrangler.json", + persist: false, + remoteBindings, + }) + ).dispose(); + + // With remote bindings disabled, Artifacts always used the simulator. + await start(false); + expect(std.warn).not.toContain(warning); + + await start(true); + await start(true); + expect(std.warn.split(warning)).toHaveLength(2); + }); + + it("warns for each project that uses the same relative config path", async ({ + expect, + }) => { + const root = process.cwd(); + const warning = + "Artifacts binding OTHER_REPOS uses the local simulator by default. Set `remote: true` to use deployed repos, or `remote: false` to silence this warning."; + try { + for (const project of ["a", "b"]) { + mkdirSync(path.join(root, project)); + process.chdir(path.join(root, project)); + writeWranglerConfig( + { + name: `worker-${project}`, + compatibility_date: "2026-11-02", + artifacts: [{ binding: "OTHER_REPOS", namespace: "examples" }], + }, + "./wrangler.json" + ); + await ( + await getPlatformProxy({ + configPath: "./wrangler.json", + persist: false, + }) + ).dispose(); + } + } finally { + process.chdir(root); + } + expect(std.warn.split(warning)).toHaveLength(3); + }); }); diff --git a/packages/wrangler/src/__tests__/helpers/mock-upload-worker.ts b/packages/wrangler/src/__tests__/helpers/mock-upload-worker.ts index ee669fcc0f..85272b81f8 100644 --- a/packages/wrangler/src/__tests__/helpers/mock-upload-worker.ts +++ b/packages/wrangler/src/__tests__/helpers/mock-upload-worker.ts @@ -78,6 +78,7 @@ export function mockUploadWorkerRequest( expectedDeploymentMessage?: string; expectedDurableObjectsCodeUpdateStrategy?: DurableObjectCodeUpdateStrategy; expectedBindingsInherit?: "strict"; + expectedScriptApiDate?: string | null; } = {} ) { const handleUpload: HttpResponseResolver = async ({ params, request }) => { @@ -105,6 +106,11 @@ export function mockUploadWorkerRequest( if (expectedDispatchNamespace) { expect(params.dispatchNamespace).toEqual(expectedDispatchNamespace); } + if (options.expectedScriptApiDate !== undefined) { + expect(request.headers.get("Cloudflare-Workers-Script-Api-Date")).toEqual( + options.expectedScriptApiDate + ); + } // eslint-disable-next-line @typescript-eslint/no-deprecated -- formData() is the standard Web API; only deprecated on undici's server-side types const formBody = await request.formData(); diff --git a/packages/wrangler/src/__tests__/print-bindings.test.ts b/packages/wrangler/src/__tests__/print-bindings.test.ts index 3a3a8c33e4..68ab3548f5 100644 --- a/packages/wrangler/src/__tests__/print-bindings.test.ts +++ b/packages/wrangler/src/__tests__/print-bindings.test.ts @@ -177,7 +177,7 @@ describe("printBindings -- Flagship bindings", () => { describe("printBindings -- Artifacts bindings", () => { it.for([ - { label: "default", remote: undefined, mode: "remote" }, + { label: "default", remote: undefined, mode: "local" }, { label: "explicit local", remote: false, mode: "local" }, { label: "explicit remote", remote: true, mode: "remote" }, ])( diff --git a/packages/wrangler/src/__tests__/versions/versions.upload.test.ts b/packages/wrangler/src/__tests__/versions/versions.upload.test.ts index a3b096a1c5..65032e4fdc 100644 --- a/packages/wrangler/src/__tests__/versions/versions.upload.test.ts +++ b/packages/wrangler/src/__tests__/versions/versions.upload.test.ts @@ -3020,7 +3020,7 @@ describe("versions upload", () => { setIsTTY(false); }); - test("sends workflow exports by name without provisioning the Workflow", async ({ + test("sends workflow exports with their settings without provisioning the Workflow", async ({ expect, }) => { mockGetScript(); @@ -3059,9 +3059,17 @@ describe("versions upload", () => { await runWrangler("versions upload --config ./wrangler.json"); - const metadata = await getMetadata(requests[requests.length - 1]); + const request = requests[requests.length - 1]; + expect(request.headers.get("Cloudflare-Workers-Script-Api-Date")).toBe( + "2026-11-09" + ); + const metadata = await getMetadata(request); expect(metadata.exports).toEqual({ - MyWorkflow: { type: "workflow", name: "my-workflow" }, + MyWorkflow: { + type: "workflow", + name: "my-workflow", + limits: { steps: 10 }, + }, }); expect(workflowPuts).toBe(0); }); diff --git a/packages/wrangler/src/__tests__/vpc-tls.test.ts b/packages/wrangler/src/__tests__/vpc-tls.test.ts new file mode 100644 index 0000000000..ba6052ff36 --- /dev/null +++ b/packages/wrangler/src/__tests__/vpc-tls.test.ts @@ -0,0 +1,325 @@ +import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; +import { http, HttpResponse } from "msw"; +import { beforeEach, describe, it, vi } from "vitest"; +import { ServiceType } from "../vpc/index"; +import { mockAccountId, mockApiToken } from "./helpers/mock-account-id"; +import { mockConsoleMethods } from "./helpers/mock-console"; +import { createFetchResult, msw } from "./helpers/msw"; +import { runWrangler } from "./helpers/run-wrangler"; +import type { + ConnectivityService, + ConnectivityServiceRequest, + TlsSettings, +} from "../vpc/index"; + +const servicesUrl = "*/accounts/:accountId/connectivity/directory/services"; +const serviceUrl = `${servicesUrl}/:serviceId`; +const tunnelId = "550e8400-e29b-41d4-a716-446655440000"; +const caId = "550e8400-e29b-41d4-a716-446655440001"; +const clientId = "550e8400-e29b-41d4-a716-446655440002"; +const serviceTls: TlsSettings = { + certificate_authority: caId, + client_certificate: clientId, + cert_verification_mode: "verify_ca", +}; + +function fixture( + hostname = false, + type = ServiceType.Tcp +): ConnectivityService { + return { + service_id: "service-uuid", + name: "database", + type, + ...(type === ServiceType.Tcp ? { tcp_port: 5432 } : { https_port: 443 }), + host: hostname + ? { + hostname: "db.example.com", + resolver_network: { + tunnel_id: tunnelId, + resolver_ips: ["10.0.0.53"], + }, + } + : { + ipv4: "10.0.0.1", + network: { + tunnel_id: tunnelId, + }, + }, + tls_settings: { ...serviceTls }, + created_at: "2024-01-01T00:00:00Z", + updated_at: "2024-01-01T00:00:00Z", + }; +} + +function command( + operation: "create" | "update", + hostname = false, + port = 5432, + type = ServiceType.Tcp +) { + return `vpc service ${operation} ${operation === "create" ? "database" : "service-uuid --name database"} --type ${type} --${type === ServiceType.Tcp ? "tcp" : "https"}-port ${port} --tunnel-id ${tunnelId} ${hostname ? "--hostname db.example.com --resolver-ips 10.0.0.53" : "--ipv4 10.0.0.1"}`; +} + +/** Simulate the replacement API: each write replaces the saved service. */ +function savedService(initial = fixture()) { + let saved = initial; + const calls: string[] = []; + const writes: ConnectivityServiceRequest[] = []; + function replace(body: ConnectivityServiceRequest) { + writes.push(body); + saved = { + ...body, + service_id: initial.service_id, + created_at: initial.created_at, + updated_at: "2024-01-02T00:00:00Z", + }; + return HttpResponse.json(createFetchResult(saved, true)); + } + msw.use( + http.post(servicesUrl, async ({ request }) => { + calls.push("POST"); + return replace((await request.json()) as ConnectivityServiceRequest); + }), + http.get(serviceUrl, () => { + calls.push("GET"); + return HttpResponse.json(createFetchResult(saved, true)); + }), + http.put(serviceUrl, async ({ request }) => { + calls.push("PUT"); + return replace((await request.json()) as ConnectivityServiceRequest); + }) + ); + return { calls, writes, current: () => saved }; +} + +function rejectAllApiCalls() { + const requests = vi.fn(() => + HttpResponse.json(createFetchResult(null, false), { status: 500 }) + ); + msw.use(http.all("*", requests)); + return requests; +} + +describe("VPC TLS configuration", () => { + mockAccountId(); + mockApiToken(); + runInTempDir(); + const std = mockConsoleMethods(); + + beforeEach(() => { + // Avoid the command banner's artificial delay. + // @ts-expect-error this mock only needs to schedule the callback + vi.spyOn(global, "setTimeout").mockImplementation((fn, _period) => { + setImmediate(fn); + }); + }); + + describe.each(["create", "update"] as const)("%s validation", (operation) => { + it.for([ + ["certificate-authority", caId], + ["client-certificate", clientId], + ])( + "requires an explicit mode for --%s before any API call", + async ([flag, id], { expect }) => { + const requests = rejectAllApiCalls(); + await expect( + runWrangler(`${command(operation)} --${flag} ${id}`) + ).rejects.toThrow( + "--cert-verification-mode is required when providing --certificate-authority or --client-certificate. Choose verify_full, verify_ca, or disabled." + ); + expect(requests).not.toHaveBeenCalled(); + } + ); + + it.for(["certificate-authority", "client-certificate"])( + "rejects invalid --%s UUIDs before any API call", + async (flag, { expect }) => { + const requests = rejectAllApiCalls(); + await expect( + runWrangler( + `${command(operation)} --${flag} not-a-uuid --cert-verification-mode verify_ca` + ) + ).rejects.toThrow(); + expect(requests).not.toHaveBeenCalled(); + expect(std.err).toContain(flag); + } + ); + + it("rejects an invalid verification mode before any API call", async ({ + expect, + }) => { + const requests = rejectAllApiCalls(); + await expect( + runWrangler(`${command(operation)} --cert-verification-mode not-a-mode`) + ).rejects.toThrow(); + expect(requests).not.toHaveBeenCalled(); + expect(std.err).toContain("cert-verification-mode"); + }); + + it("rejects a CA with disabled verification before any API call", async ({ + expect, + }) => { + const requests = rejectAllApiCalls(); + await expect( + runWrangler( + `${command(operation)} --certificate-authority ${caId} --cert-verification-mode disabled` + ) + ).rejects.toThrow(/certificate.authority/i); + expect(requests).not.toHaveBeenCalled(); + expect(std.out).not.toContain("Created VPC service"); + expect(std.out).not.toContain("Updated VPC service"); + }); + + it.for([ + `--network-certificate-authority ${caId}`, + `--network-client-certificate ${clientId}`, + "--network-cert-verification-mode verify_ca", + "--remove-network-certificate-authority", + "--remove-network-client-certificate", + "--remove-network-tls-settings", + "--use-network-tls-settings", + "--remove-certificate-authority", + "--remove-client-certificate", + ])( + "rejects unsupported TLS flags rather than silently ignoring them: %s", + async (flags, { expect }) => { + const requests = rejectAllApiCalls(); + await expect( + runWrangler(`${command(operation)} ${flags}`) + ).rejects.toThrow(/Unknown argument/); + expect(requests).not.toHaveBeenCalled(); + } + ); + }); + + const tlsCases = [ + ["no TLS options", "", undefined], + [ + "mode-only verify_full", + "--cert-verification-mode verify_full", + { cert_verification_mode: "verify_full" }, + ], + [ + "mode-only disabled", + "--cert-verification-mode disabled", + { cert_verification_mode: "disabled" }, + ], + [ + "a custom CA", + `--certificate-authority ${caId} --cert-verification-mode verify_full`, + { certificate_authority: caId, cert_verification_mode: "verify_full" }, + ], + [ + "a client certificate with verification disabled", + `--client-certificate ${clientId} --cert-verification-mode disabled`, + { client_certificate: clientId, cert_verification_mode: "disabled" }, + ], + [ + "both certificates", + `--certificate-authority ${caId} --client-certificate ${clientId} --cert-verification-mode verify_ca`, + serviceTls, + ], + ] as const; + + describe.each([ServiceType.Tcp, ServiceType.Http])("%s services", (type) => { + it.for(tlsCases)( + "creates a service with %s", + async ([_label, flags, tls], { expect }) => { + const api = savedService(fixture(false, type)); + await runWrangler(`${command("create", false, 443, type)} ${flags}`); + expect(api.calls).toEqual(["POST"]); + expect(api.writes[0].tls_settings).toEqual(tls); + } + ); + }); + + it.for(tlsCases)( + "replaces the service TLS settings with %s in a single PUT", + async ([_label, flags, tls], { expect }) => { + const api = savedService(); + await runWrangler(`${command("update")} ${flags}`); + expect(api.calls).toEqual(["PUT"]); + expect(api.writes[0].tls_settings).toEqual(tls); + expect(api.current().tls_settings).toEqual(tls); + } + ); + + it.for([false, true])( + "reports configured service TLS without private data (hostname=%s)", + async (hostname, { expect }) => { + const service = { + ...fixture(hostname), + internal_id: "internal-secret-marker", + private_key: "private-key-marker", + certificate: "certificate-pem-marker", + }; + msw.use( + http.get(serviceUrl, () => + HttpResponse.json(createFetchResult(service, true)) + ) + ); + await runWrangler("vpc service get service-uuid"); + for (const id of [caId, clientId]) { + expect(std.out).toContain(id); + } + expect(std.out).toContain("verify_ca"); + for (const secret of [ + "internal-secret-marker", + "private-key-marker", + "certificate-pem-marker", + ]) { + expect(std.out).not.toContain(secret); + } + } + ); + + it.for([ + ["disabled", "None"], + ["verify_ca", "None (system trust store)"], + ["verify_full", "None (system trust store)"], + ] as const)( + "reports the default certificate authority for %s verification", + async ([mode, authority], { expect }) => { + const service = fixture(); + service.tls_settings = { cert_verification_mode: mode }; + savedService(service); + await runWrangler("vpc service get service-uuid"); + expect(std.out).toContain(`Certificate Authority: ${authority}\n`); + } + ); + + it.for(["create", "update"] as const)( + "surfaces certificate API errors on %s without reporting success", + async (operation, { expect }) => { + const writes: ConnectivityServiceRequest[] = []; + const failure = HttpResponse.json( + { + success: false, + errors: [{ code: 1000, message: "Certificate not found" }], + messages: [], + result: null, + }, + { status: 400 } + ); + msw.use( + http.post(servicesUrl, async ({ request }) => { + writes.push((await request.json()) as ConnectivityServiceRequest); + return failure; + }), + http.put(serviceUrl, async ({ request }) => { + writes.push((await request.json()) as ConnectivityServiceRequest); + return failure; + }) + ); + await expect( + runWrangler( + `${command(operation)} --certificate-authority ${caId} --cert-verification-mode verify_ca` + ) + ).rejects.toThrow(); + expect(writes).toHaveLength(1); + expect(std.out).not.toContain("Created VPC service"); + expect(std.out).not.toContain("Updated VPC service"); + } + ); +}); diff --git a/packages/wrangler/src/__tests__/vpc.test.ts b/packages/wrangler/src/__tests__/vpc.test.ts index 0468ab365a..b6099db892 100644 --- a/packages/wrangler/src/__tests__/vpc.test.ts +++ b/packages/wrangler/src/__tests__/vpc.test.ts @@ -573,177 +573,6 @@ describe("vpc service commands", () => { `); }); - it("should handle creating a TCP service with --cert-verification-mode verify_ca", async ({ - expect, - }) => { - const reqProm = mockWvpcServiceCreate(); - await runWrangler( - "vpc service create test-tcp-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.5 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode verify_ca" - ); - - await expect(reqProm).resolves.toMatchInlineSnapshot(` - { - "host": { - "ipv4": "10.0.0.5", - "network": { - "tunnel_id": "550e8400-e29b-41d4-a716-446655440000", - }, - }, - "name": "test-tcp-tls", - "tcp_port": 5432, - "tls_settings": { - "cert_verification_mode": "verify_ca", - }, - "type": "tcp", - } - `); - - expect(std.out).toMatchInlineSnapshot(` - " - ⛅️ wrangler x.x.x - ────────────────── - 🚧 Creating VPC service 'test-tcp-tls' - ✅ Created VPC service: service-uuid - Name: test-tcp-tls - Type: tcp - TCP Port: 5432 - Cert Verification Mode: verify_ca - IPv4: 10.0.0.5 - Tunnel ID: 550e8400-e29b-41d4-a716-446655440000" - `); - }); - - it("should handle creating an HTTP service with --cert-verification-mode disabled", async ({ - expect, - }) => { - const reqProm = mockWvpcServiceCreate(); - await runWrangler( - "vpc service create test-http-tls --type http --http-port 80 --ipv4 10.0.0.1 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode disabled" - ); - - await expect(reqProm).resolves.toMatchInlineSnapshot(` - { - "host": { - "ipv4": "10.0.0.1", - "network": { - "tunnel_id": "550e8400-e29b-41d4-a716-446655440000", - }, - }, - "http_port": 80, - "name": "test-http-tls", - "tls_settings": { - "cert_verification_mode": "disabled", - }, - "type": "http", - } - `); - - expect(std.out).toMatchInlineSnapshot(` - " - ⛅️ wrangler x.x.x - ────────────────── - 🚧 Creating VPC service 'test-http-tls' - ✅ Created VPC service: service-uuid - Name: test-http-tls - Type: http - HTTP Port: 80 - Cert Verification Mode: disabled - IPv4: 10.0.0.1 - Tunnel ID: 550e8400-e29b-41d4-a716-446655440000" - `); - }); - - it("should not include tls_settings when --cert-verification-mode is not specified", async ({ - expect, - }) => { - const reqProm = mockWvpcServiceCreate(); - await runWrangler( - "vpc service create test-no-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.5 --tunnel-id 550e8400-e29b-41d4-a716-446655440000" - ); - - const reqBody = await reqProm; - expect(reqBody.tls_settings).toBeUndefined(); - }); - - it("should handle getting a service with tls_settings", async ({ - expect, - }) => { - const serviceWithTls: ConnectivityService = { - ...mockTcpService, - tls_settings: { - cert_verification_mode: "verify_ca", - }, - }; - - msw.use( - http.get( - "*/accounts/:accountId/connectivity/directory/services/:serviceId", - () => { - return HttpResponse.json(createFetchResult(serviceWithTls, true)); - }, - { once: true } - ) - ); - - await runWrangler("vpc service get tcp-service-uuid"); - - expect(std.out).toMatchInlineSnapshot(` - " - ⛅️ wrangler x.x.x - ────────────────── - 🔍 Getting VPC service 'tcp-service-uuid' - ✅ Retrieved VPC service: tcp-service-uuid - Name: test-tcp-service - Type: tcp - TCP Port: 5432 - App Protocol: postgresql - Cert Verification Mode: verify_ca - IPv4: 10.0.0.5 - Tunnel ID: 550e8400-e29b-41d4-a716-446655440000 - Created: 1/1/2024, 12:00:00 AM - Modified: 1/1/2024, 12:00:00 AM" - `); - }); - - it("should handle updating a service with --cert-verification-mode", async ({ - expect, - }) => { - const reqProm = mockWvpcServiceUpdate(); - await runWrangler( - "vpc service update service-uuid --name test-updated --type http --http-port 80 --ipv4 10.0.0.2 --tunnel-id 550e8400-e29b-41d4-a716-446655440001 --cert-verification-mode verify_full" - ); - - await expect(reqProm).resolves.toMatchInlineSnapshot(` - { - "host": { - "ipv4": "10.0.0.2", - "network": { - "tunnel_id": "550e8400-e29b-41d4-a716-446655440001", - }, - }, - "http_port": 80, - "name": "test-updated", - "tls_settings": { - "cert_verification_mode": "verify_full", - }, - "type": "http", - } - `); - }); - - it("should reject --cert-verification-mode with invalid value", async ({ - expect, - }) => { - await expect(() => - runWrangler( - "vpc service create test-bad-tls --type tcp --tcp-port 5432 --ipv4 10.0.0.1 --tunnel-id 550e8400-e29b-41d4-a716-446655440000 --cert-verification-mode invalid" - ) - ).rejects.toThrow(); - expect(std.err).toContain("Invalid values"); - expect(std.err).toContain("cert-verification-mode"); - expect(std.err).toContain('"invalid"'); - }); - it("should extract port from hostname for TCP services", async ({ expect, }) => { diff --git a/packages/wrangler/src/api/integrations/platform/index.ts b/packages/wrangler/src/api/integrations/platform/index.ts index 94255f7d28..f89572d927 100644 --- a/packages/wrangler/src/api/integrations/platform/index.ts +++ b/packages/wrangler/src/api/integrations/platform/index.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { createContainerDevPlan } from "@cloudflare/containers-shared"; import { + createArtifactsLocalDefaultWarner, DEFAULT_COMPAT_DATE, DEFAULT_MODULE_RULES, extractBindingsOfType, @@ -130,6 +131,11 @@ export type GetPlatformProxyOptions = { remoteBindings?: boolean; }; +// Remembers warnings per config file, so a framework that calls +// `getPlatformProxy()` again after a config change doesn't repeat them. +const warnForArtifactsLocalDefault = + createArtifactsLocalDefaultWarner("wrangler"); + /** * Result of the `getPlatformProxy` utility */ @@ -180,6 +186,20 @@ export async function getPlatformProxy< env, }); + if (options.remoteBindings !== false) { + warnForArtifactsLocalDefault( + { + // A relative path names a different file after a directory change. + id: config.configPath ? path.resolve(config.configPath) : process.cwd(), + bindings: config.artifacts.map(({ binding, remote }) => ({ + name: binding, + remote, + })), + }, + (message) => logger.warn(message) + ); + } + let remoteProxySession: RemoteProxySession | undefined = undefined; if (config.configPath && options.remoteBindings !== false) { remoteProxySession = ( @@ -479,6 +499,7 @@ export function unstable_getMiniflareWorkerOptions( complianceRegion: config.compliance_region, bindings, queueConsumers: config.queues.consumers, + artifactsEvents: config.triggers.events, migrations: config.migrations, exports: config.exports, tails: config.tail_consumers, diff --git a/packages/wrangler/src/api/startDevWorker/ConfigController.ts b/packages/wrangler/src/api/startDevWorker/ConfigController.ts index 208c5fcc00..3b642b2456 100644 --- a/packages/wrangler/src/api/startDevWorker/ConfigController.ts +++ b/packages/wrangler/src/api/startDevWorker/ConfigController.ts @@ -354,7 +354,18 @@ async function resolveTriggers( : {}), })) ?? []; - return [...devRoutes, ...queueConsumers, ...crons, ...connectHandlers]; + const artifactsEvents = + config.triggers.events?.map>( + (event) => ({ type: "artifacts-event", event }) + ) ?? []; + + return [ + ...devRoutes, + ...queueConsumers, + ...crons, + ...connectHandlers, + ...artifactsEvents, + ]; } async function resolveConfig( @@ -674,22 +685,59 @@ export class ConfigController extends Controller { #printCurrentBindings?: (registry: WorkerRegistry | null) => void; #configWatcher?: ReturnType; + // Sorted, so that the same set of paths always compares equal. + #configWatcherPaths: string[] = []; + #configWatcherReady?: Promise; #abortController?: AbortController; - async #ensureWatchingConfig(configPaths: string | string[] | undefined) { - await this.#configWatcher?.close(); - if (configPaths === undefined) { - return; + // Resolves once every path in `configPaths` is being watched, so that any + // change made afterwards emits a `change` event. A change made before a + // path's watcher is ready goes unnoticed, which is why an unchanged set of + // paths keeps its existing watcher rather than getting a new one. + async #ensureWatchingConfig(configPaths: string[], signal: AbortSignal) { + const paths = [...configPaths].sort(); + const unchanged = + paths.length === this.#configWatcherPaths.length && + paths.every((p, i) => p === this.#configWatcherPaths[i]); + if (!unchanged) { + // Update all the state before awaiting anything, so that a concurrent + // update sees the new watcher rather than creating another one. + const previousWatcher = this.#configWatcher; + this.#configWatcher = undefined; + this.#configWatcherReady = undefined; + this.#configWatcherPaths = paths; + if (paths.length > 0) { + const watcher = this.#watchConfig(paths); + this.#configWatcher = watcher; + this.#configWatcherReady = new Promise((resolve) => + watcher.once("ready", () => resolve()) + ); + } + await previousWatcher?.close(); } - const paths = typeof configPaths === "string" ? [configPaths] : configPaths; - if (paths.length === 0) { - return; + const ready = this.#configWatcherReady; + if (ready !== undefined && !signal.aborted) { + // A superseding update or teardown aborts `signal`, possibly by closing + // the watcher before it is ready, so stop waiting then. + await new Promise((resolve) => { + signal.addEventListener("abort", () => resolve()); + void ready.then(resolve); + }); } - this.#configWatcher = watch(paths, { + } + + #watchConfig(paths: string[]) { + const watcher = watch(paths, { persistent: true, ignoreInitial: true, - }).on("change", async (changedPath) => { - if (this.#configWatcher?.closed) { + // Without this, chokidar drops a path's `change` event if it comes + // within 50 ms of the previous one, losing a write made just after a + // reload. Waiting for writes to finish skips that throttle, and also + // avoids reading a partly written file. + awaitWriteFinish: { stabilityThreshold: 50, pollInterval: 10 }, + }); + return watcher.on("change", async (changedPath) => { + if (watcher.closed) { return; } logger.debug(`${path.basename(changedPath)} changed...`); @@ -782,19 +830,19 @@ export class ConfigController extends Controller { } } + let watchPaths: string[] = []; if (!getDisableConfigWatching() && input.dev?.watch !== false) { // Under `--experimental-new-config`, watch the transitive deps of both // `cloudflare.config.ts` and `wrangler.config.ts` (deduped, with // `node_modules` excluded by `@cloudflare/config`'s loader). // Otherwise fall back to the legacy single-file watch. - const watchPaths = newConfig - ? Array.from(newConfig.dependencies) - : fileConfig.configPath; - await this.#ensureWatchingConfig(watchPaths); - } else { - await this.#configWatcher?.close(); - this.#configWatcher = undefined; + if (newConfig) { + watchPaths = Array.from(newConfig.dependencies); + } else if (fileConfig.configPath !== undefined) { + watchPaths = [fileConfig.configPath]; + } } + await this.#ensureWatchingConfig(watchPaths, signal); // Under `--experimental-new-config`, run the new-config type-gen path // instead of the legacy `checkTypesDiff`. @@ -861,6 +909,9 @@ export class ConfigController extends Controller { await super.teardown(); this.#abortController?.abort(); await this.#configWatcher?.close(); + this.#configWatcher = undefined; + this.#configWatcherReady = undefined; + this.#configWatcherPaths = []; logger.debug("ConfigController teardown complete"); } diff --git a/packages/wrangler/src/api/startDevWorker/LocalRuntimeController.ts b/packages/wrangler/src/api/startDevWorker/LocalRuntimeController.ts index bf0d35896f..4dd733818e 100644 --- a/packages/wrangler/src/api/startDevWorker/LocalRuntimeController.ts +++ b/packages/wrangler/src/api/startDevWorker/LocalRuntimeController.ts @@ -2,7 +2,11 @@ import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { isDeepStrictEqual } from "node:util"; import { prepareContainerImagesForDev } from "@cloudflare/containers-shared"; -import { configFileName, getDockerPath } from "@cloudflare/workers-utils"; +import { + configFileName, + createArtifactsLocalDefaultWarner, + getDockerPath, +} from "@cloudflare/workers-utils"; import chalk from "chalk"; import { buildPublicUrl, @@ -115,6 +119,7 @@ export async function convertToConfigBundle( const routes = []; const queueConsumers = []; const connectHandlers = []; + const artifactsEvents = []; for (const trigger of event.config.triggers ?? []) { if (trigger.type === "cron") { crons.push(trigger.cron); @@ -126,6 +131,8 @@ export async function convertToConfigBundle( } else if (trigger.type === "connect") { const { type: _, ...connectHandler } = trigger; connectHandlers.push(connectHandler); + } else if (trigger.type === "artifacts-event") { + artifactsEvents.push(trigger.event); } } if (event.bundle.entry.format === "service-worker") { @@ -202,6 +209,7 @@ export async function convertToConfigBundle( routes: event.config.dev.routeRequestsByRoutes ? routes : undefined, queueConsumers, connectHandlers, + artifactsEvents, outboundService: event.config.dev.outboundService, localProtocol: event.config.dev?.server?.secure ? "https" : "http", localUpstream: event.config.dev?.origin?.hostname, @@ -266,6 +274,9 @@ export class LocalRuntimeController extends RuntimeController { #containerImagePreparationState?: ContainerImagePreparationState; + // Warns once per dev session, not on every config reload. + #warnForArtifactsLocalDefault = createArtifactsLocalDefaultWarner("wrangler"); + // Used to store the information and abort handle for the // current container that is being built containerBeingBuilt?: { @@ -359,6 +370,19 @@ export class LocalRuntimeController extends RuntimeController { const configBundle = await convertToConfigBundle(data); if (data.config.dev?.remote !== false) { + this.#warnForArtifactsLocalDefault( + { + id: data.config.config ?? data.config.name ?? "", + bindings: Object.entries(configBundle.bindings ?? {}).flatMap( + ([name, binding]) => + binding.type === "artifacts" + ? [{ name, remote: binding.remote }] + : [] + ), + }, + (message) => logger.warn(message) + ); + // note: remote bindings use (transitively) LocalRuntimeController, so we need to import // from the module lazily in order to avoid circular dependency issues const { maybeStartOrUpdateRemoteProxySession, pickRemoteBindings } = diff --git a/packages/wrangler/src/build/write-build-output.ts b/packages/wrangler/src/build/write-build-output.ts index c5aafc1ff3..a691b8d6c6 100644 --- a/packages/wrangler/src/build/write-build-output.ts +++ b/packages/wrangler/src/build/write-build-output.ts @@ -8,6 +8,7 @@ import { initContainersSharedContext, } from "@cloudflare/containers-shared"; import { getDockerPath } from "@cloudflare/workers-utils"; +import { version as wranglerVersion } from "../../package.json"; import { fetchResult } from "../cfetch"; import { readNewConfig } from "../config"; import { writeWorkerOutput } from "../deployment-bundle/build-output"; @@ -23,7 +24,7 @@ import type { WorkerBuildResult } from "@cloudflare/deploy-helpers"; /** * Write the standalone Build Output Specification for `wrangler build`. * - * The output is a self-contained `.cloudflare/output/v0/` directory. + * The output is a self-contained `.cloudflare/output/v1/` directory. */ export async function writeBuildOutput({ env, @@ -51,14 +52,15 @@ export async function writeBuildOutput({ } await cleanBuildOutputDir(root); - await writeRootConfig( + await writeRootConfig({ root, - { + settings: { accountId: parsedConfig.accountId, complianceRegion: parsedConfig.complianceRegion, }, - { isPreview, mode } - ); + buildContext: { isPreview, mode }, + producer: { name: "wrangler", version: wranglerVersion }, + }); await writeWorkerOutput({ root, workerConfig: parsedConfig.worker, @@ -72,7 +74,7 @@ export async function writeBuildOutput({ }); const pathToDocker = getDockerPath(); await buildAndWriteContainerOutput({ - containers: parsedConfig.containers, + containers: parsedConfig.containers ?? [], root, pathToDocker, }); diff --git a/packages/wrangler/src/containers/config.ts b/packages/wrangler/src/containers/config.ts index 12c10dfbba..ec8478c69c 100644 --- a/packages/wrangler/src/containers/config.ts +++ b/packages/wrangler/src/containers/config.ts @@ -142,8 +142,8 @@ export const getNormalizedContainerOptions = async ( ); } - const rolloutStepPercentageFallback = - (container.max_instances ?? 0) < 2 ? 100 : [10, 100]; + const maxInstances = container.max_instances ?? 20; + const rolloutStepPercentageFallback = maxInstances < 2 ? 100 : [10, 100]; // tiers will take precedence over tier // if unset, wrangler will default to [1, 2] @@ -175,7 +175,7 @@ export const getNormalizedContainerOptions = async ( const shared: Omit = { name: container.name, class_name: className, - max_instances: container.max_instances ?? 20, + max_instances: maxInstances, scheduling_policy: (container.scheduling_policy ?? SchedulingPolicy.DEFAULT) as SchedulingPolicy, constraints: { diff --git a/packages/wrangler/src/deployment-bundle/build-output.ts b/packages/wrangler/src/deployment-bundle/build-output.ts index ef53b4564f..5a9b109722 100644 --- a/packages/wrangler/src/deployment-bundle/build-output.ts +++ b/packages/wrangler/src/deployment-bundle/build-output.ts @@ -8,21 +8,21 @@ import { import { UserError } from "@cloudflare/workers-utils"; import type { ModuleType, - ParsedInputWorkerConfig, - ParsedOutputWorkerConfig, + ParsedWorkerConfig, + ParsedBuildOutputWorkerConfig, } from "@cloudflare/config"; import type { WorkerBuildResult } from "@cloudflare/deploy-helpers"; import type { AssetsOptions, CfModuleType } from "@cloudflare/workers-utils"; interface WriteWorkerOutputArgs { root: string; - workerConfig: ParsedInputWorkerConfig; + workerConfig: ParsedWorkerConfig; buildResult: WorkerBuildResult | undefined; assetsOptions: AssetsOptions | undefined; } /** - * Write the Worker's `.cloudflare/output/v0/workers/default/` directory + * Write the Worker's `.cloudflare/output/v1/workers/default/` directory * tree from an in-memory `WorkerBuildResult` and `AssetsOptions`. */ export async function writeWorkerOutput({ @@ -56,12 +56,13 @@ async function writeBundle({ }: { root: string; buildResult: WorkerBuildResult; -}): Promise { +}): Promise { const bundleDir = getWorkerBundleDir(root); await fsp.mkdir(bundleDir, { recursive: true }); - const modules: NonNullable["modules"] = - {}; + const modules: NonNullable< + ParsedBuildOutputWorkerConfig["manifest"] + >["modules"] = {}; // Entry module const entryKey = stripLeadingDotSlash( diff --git a/packages/wrangler/src/deployment-bundle/cf-build-output-guard.ts b/packages/wrangler/src/deployment-bundle/cf-build-output-guard.ts index 5a957b377e..ea30fa1bbe 100644 --- a/packages/wrangler/src/deployment-bundle/cf-build-output-guard.ts +++ b/packages/wrangler/src/deployment-bundle/cf-build-output-guard.ts @@ -1,9 +1,6 @@ import * as fs from "node:fs"; import * as path from "node:path"; -import { - BUILD_OUTPUT_ROOT, - getRootConfigPath, -} from "@cloudflare/build-output-utils"; +import { BUILD_OUTPUT_ROOT } from "@cloudflare/build-output-utils"; import { UserError } from "@cloudflare/workers-utils"; import type { Config } from "@cloudflare/workers-utils"; @@ -53,27 +50,43 @@ function getProjectRoots({ return leafRoot === configRoot ? [leafRoot] : [leafRoot, configRoot]; } +/** + * Matches Build Output version directory names such as `v0`, `v1` and `v12`. + * The `.cloudflare/output/v/` convention is the only part of the Build + * Output Specification that never changes between versions. + */ +const VERSION_DIRECTORY_PATTERN = /^v(0|[1-9]\d*)$/; + /** * Find a Cloudflare Build Output Specification directory in `projectRoot`. * - * Requires the versioned root config rather than the directory name, so the - * `.cloudflare/types` directory Wrangler generates itself, or an unrelated - * `output` folder, is not mistaken for Build Output. + * Requires a version directory such as `v1` rather than just the `output` + * directory, so the `.cloudflare/types` directory Wrangler generates itself, + * or an unrelated `output` folder, is not mistaken for Build Output. Any + * version counts, so output left by an older or newer `cf` is still found. */ export function findCloudflareBuildOutput( projectRoot: string ): string | undefined { + const buildOutputDir = path.resolve(projectRoot, BUILD_OUTPUT_ROOT); + let entries: fs.Dirent[]; try { - if (!fs.statSync(getRootConfigPath(projectRoot)).isFile()) { - return undefined; - } + entries = fs.readdirSync(buildOutputDir, { withFileTypes: true }); } catch { // Usually just absent. An unreadable path is treated the same way, so a // filesystem error cannot block a deployment. return undefined; } - return path.resolve(projectRoot, BUILD_OUTPUT_ROOT); + // A symlink counts too, matching the Build Output reader, so linked output + // still stops the deployment. + return entries.some( + (entry) => + (entry.isDirectory() || entry.isSymbolicLink()) && + VERSION_DIRECTORY_PATTERN.test(entry.name) + ) + ? buildOutputDir + : undefined; } /** diff --git a/packages/wrangler/src/dev/miniflare/index.ts b/packages/wrangler/src/dev/miniflare/index.ts index 61b792a5b5..6e70865ec7 100644 --- a/packages/wrangler/src/dev/miniflare/index.ts +++ b/packages/wrangler/src/dev/miniflare/index.ts @@ -23,8 +23,10 @@ import { getDurableObjectClassNameToUseSQLiteMap } from "../class-names-sqlite"; import type { StartDevWorkerInput } from "../../api/startDevWorker/types"; import type { LoggerLevel } from "../../logger"; import type { EsbuildBundle } from "../use-esbuild"; +import type { ArtifactsEventSubscription } from "@cloudflare/config"; import type { ContainerDevRuntimeOptions } from "@cloudflare/containers-shared"; import type { + ArtifactsEventTrigger, AssetsOptions, Binding, CfD1Database, @@ -94,6 +96,7 @@ export interface ConfigBundle { routes: string[] | undefined; queueConsumers: Config["queues"]["consumers"]; connectHandlers: ConnectHandler[]; + artifactsEvents: ArtifactsEventTrigger[]; localProtocol: "http" | "https"; localUpstream: string | undefined; upstreamProtocol: "http" | "https"; @@ -402,18 +405,22 @@ function hyperdriveEntry( return [hyperdrive.binding, hyperdrive.localConnectionString ?? ""]; } -function workflowEntry({ - binding, - name, - class_name: className, - script_name: scriptName, - limits, -}: CfWorkflow): [ +function workflowEntry( + { + binding, + name, + class_name: className, + script_name: scriptName, + limits, + }: CfWorkflow, + events: ArtifactsEventSubscription[] | undefined +): [ string, { name: string; className: string; scriptName?: string; + events?: ArtifactsEventSubscription[]; stepLimit?: number; }, ] { @@ -425,6 +432,7 @@ function workflowEntry({ name, className, scriptName, + events, ...(stepLimit !== undefined && { stepLimit }), }, ]; @@ -547,7 +555,10 @@ type MiniflareBindingsConfig = Pick< | "enableContainers" > & Partial< - Pick + Pick< + ConfigBundle, + "format" | "bundle" | "assets" | "compatibilityFlags" | "artifactsEvents" + > >; // TODO(someday): would be nice to type these methods more, can we export types for @@ -764,11 +775,7 @@ export function buildMiniflareBindingOptions( } for (const artifact of artifactsBindings) { - validateBindingRemoteSetting("artifacts", artifact.remote, logger.warn, { - binding: artifact.binding, - // Without a remote proxy session the binding uses the local simulator. - remoteBindingsDisabled: remoteProxyConnectionString === undefined, - }); + validateBindingRemoteSetting("artifacts", artifact.remote, logger.warn); } for (const flagship of flagshipBindings) { @@ -846,19 +853,25 @@ export function buildMiniflareBindingOptions( // Workflows declared under `exports` (accessible via `ctx.exports`) are // carried to Miniflare separately from `workflows[]` env bindings, keyed by // the exported class name. + const exportedWorkflows = partitionExports(config.exports).workflow; + const workflowEvents = assignWorkflowEvents( + config.artifactsEvents, + config.name, + exportedWorkflows, + workflows + ); const workflowExports: NonNullable = Object.fromEntries( - Object.entries(partitionExports(config.exports).workflow).map( - ([className, workflow]) => [ - className, - { - name: workflow.name, - ...(workflow.limits?.steps !== undefined && { - stepLimit: workflow.limits.steps, - }), - }, - ] - ) + Object.entries(exportedWorkflows).map(([className, workflow]) => [ + className, + { + name: workflow.name, + events: workflowEvents.exports.get(className), + ...(workflow.limits?.steps !== undefined && { + stepLimit: workflow.limits.steps, + }), + }, + ]) ); const bindingOptions: WorkerOptionsBindings = { @@ -995,7 +1008,10 @@ export function buildMiniflareBindingOptions( ); } } - return workflowEntry(workflow); + return workflowEntry( + workflow, + workflowEvents.bindings.get(workflow.binding) + ); }) ), workflowExports, @@ -1015,7 +1031,6 @@ export function buildMiniflareBindingOptions( binding.binding, { namespace: binding.namespace, - remote: binding.remote, remoteProxyConnectionString: resolveBindingRemote( "artifacts", binding.remote @@ -1309,6 +1324,76 @@ export async function buildMiniflareOptions( return options; } +/** Workflow-owned events, keyed by export class name or binding name. */ +interface WorkflowEventAssignment { + exports: Map; + bindings: Map; +} + +/** + * Gives each `triggers.events` target to the one local declaration of its + * Workflow: the export when there is one, otherwise the first local binding. + * Miniflare starts a subscription for every declaration it receives, so a + * Workflow declared both ways must not receive its events twice. + * + * @throws {UserError} If a target is not a Workflow this Worker defines, + * matching the check `wrangler deploy` makes. + */ +function assignWorkflowEvents( + triggers: ArtifactsEventTrigger[] | undefined, + scriptName: string | undefined, + exportedWorkflows: Record, + workflowBindings: CfWorkflow[] +): WorkflowEventAssignment { + const assignment: WorkflowEventAssignment = { + exports: new Map(), + bindings: new Map(), + }; + if (!triggers?.length) { + return assignment; + } + const owners = new Map(); + for (const [className, { name }] of Object.entries(exportedWorkflows)) { + if (!owners.has(name)) { + const events: ArtifactsEventSubscription[] = []; + owners.set(name, events); + assignment.exports.set(className, events); + } + } + for (const workflow of workflowBindings) { + const local = + workflow.script_name === undefined || workflow.script_name === scriptName; + if (local && !owners.has(workflow.name)) { + const events: ArtifactsEventSubscription[] = []; + owners.set(workflow.name, events); + assignment.bindings.set(workflow.binding, events); + } + } + for (const trigger of triggers) { + for (const target of trigger.targets) { + const events = owners.get(target.workflow_name); + if (events === undefined) { + throw new UserError( + `Event trigger "${trigger.type}" targets Workflow "${target.workflow_name}", but that Workflow is not defined by this Worker.\n\nAdd it to the "workflows" configuration or remove the event trigger target.`, + { telemetryMessage: "dev event target workflow not defined" } + ); + } + events.push({ + type: trigger.type, + ...(trigger.filter === undefined + ? {} + : { + filter: { + namespace: trigger.filter.namespace, + repoName: trigger.filter.repo_name, + }, + }), + }); + } + } + return assignment; +} + /** * isUnsafeServiceBindingWithDevCfg is a typeguard that checks whether the user has specified unsafe * service bindings with a local development configuration in their Worker options diff --git a/packages/wrangler/src/experimental-config/load.ts b/packages/wrangler/src/experimental-config/load.ts index 5bf462083e..5792f103d7 100644 --- a/packages/wrangler/src/experimental-config/load.ts +++ b/packages/wrangler/src/experimental-config/load.ts @@ -19,8 +19,8 @@ import { import { resolveWranglerConfig } from "./wrangler-definition"; import type { ParsedWranglerConfig } from "./schema"; import type { - ParsedInputConfig, - ParsedInputWorkerConfig, + ParsedCloudflareConfig, + ParsedWorkerConfig, } from "@cloudflare/config"; import type { RawConfig } from "@cloudflare/workers-utils"; @@ -32,8 +32,8 @@ export interface NormalizedTypes { includeRuntime: boolean; } -export type ParsedProjectConfig = ParsedInputConfig & { - worker: ParsedInputWorkerConfig; +export type ParsedProjectConfig = ParsedCloudflareConfig & { + worker: ParsedWorkerConfig; }; export interface LoadNewConfigResult { @@ -174,7 +174,7 @@ export async function loadNewConfig(options: { * * Worker fields cannot appear in tooling (rejected by `WranglerConfigSchema`). * Tooling fields cannot appear in worker (rejected by `@cloudflare/config`'s - * `InputWorkerSchema.strictObject`). The only overlap is `assets`, where worker + * `WorkerConfigSchema.strictObject`). The only overlap is `assets`, where worker * carries `binding`/`html_handling`/`not_found_handling`/`base_path`/ * `run_worker_first` and tooling carries `directory` (sourced from the flat * top-level `assetsDirectory` field on `wrangler.config.ts`). diff --git a/packages/wrangler/src/experimental-config/schema.ts b/packages/wrangler/src/experimental-config/schema.ts index 16ade34ab4..433d137b3e 100644 --- a/packages/wrangler/src/experimental-config/schema.ts +++ b/packages/wrangler/src/experimental-config/schema.ts @@ -105,7 +105,7 @@ export const WORKER_CONFIG_FIELD_HINTS = new Set([ "workersDev", "previewUrls", "complianceRegion", - "firstPartyWorker", + "experimental", "unsafe", "env", "exports", diff --git a/packages/wrangler/src/type-generation/new-config.ts b/packages/wrangler/src/type-generation/new-config.ts index 1426769643..d5126a6f39 100644 --- a/packages/wrangler/src/type-generation/new-config.ts +++ b/packages/wrangler/src/type-generation/new-config.ts @@ -7,7 +7,7 @@ import { RUNTIME_TYPES_MARKER } from "@cloudflare/runtime-types"; import { logger } from "../logger"; import { generateRuntimeTypes } from "./runtime"; import type { NormalizedTypes } from "../experimental-config/load"; -import type { ParsedInputWorkerConfig } from "@cloudflare/config"; +import type { ParsedWorkerConfig } from "@cloudflare/config"; /** Default generated types path for the experimental configuration. */ const NEW_CONFIG_TYPES_OUTPUT_PATH = ".cloudflare/types/index.d.ts"; @@ -20,7 +20,7 @@ const NEW_CONFIG_TYPES_OUTPUT_PATH = ".cloudflare/types/index.d.ts"; */ export async function regenerateNewConfigTypes(options: { cloudflareConfigPath: string; - workerConfig: ParsedInputWorkerConfig; + workerConfig: ParsedWorkerConfig; types: NormalizedTypes; }): Promise { if (!options.types.generate) { diff --git a/packages/wrangler/src/vpc/index.ts b/packages/wrangler/src/vpc/index.ts index 942b1cfc05..6d0689f955 100644 --- a/packages/wrangler/src/vpc/index.ts +++ b/packages/wrangler/src/vpc/index.ts @@ -26,6 +26,8 @@ export type CertVerificationMode = "verify_full" | "verify_ca" | "disabled"; export interface TlsSettings { cert_verification_mode: CertVerificationMode; + certificate_authority?: string; + client_certificate?: string; } export interface ServicePortOptions { @@ -167,7 +169,17 @@ export const serviceOptions = { type: "string", choices: ["verify_full", "verify_ca", "disabled"] as const, description: - "TLS certificate verification mode for the connection to the origin", + "Origin verification: verify_full checks chain and hostname; verify_ca checks chain only; disabled skips verification and cannot be used with a custom CA. Required when providing certificates. On update, TLS options you omit are cleared", + group: "TLS Options", + }, + "certificate-authority": { + type: "string", + description: "UUID returned by wrangler cert upload certificate-authority", + group: "TLS Options", + }, + "client-certificate": { + type: "string", + description: "UUID returned by wrangler cert upload mtls-certificate", group: "TLS Options", }, } as const; diff --git a/packages/wrangler/src/vpc/shared.ts b/packages/wrangler/src/vpc/shared.ts index 0a8c7a57ac..8abc8a3f20 100644 --- a/packages/wrangler/src/vpc/shared.ts +++ b/packages/wrangler/src/vpc/shared.ts @@ -23,11 +23,20 @@ export function displayServiceDetails(service: ConnectivityService) { } } - // Display TLS settings if (service.tls_settings) { + const defaultCertificateAuthority = + service.tls_settings.cert_verification_mode === "disabled" + ? "None" + : "None (system trust store)"; logger.log( ` Cert Verification Mode: ${service.tls_settings.cert_verification_mode}` ); + logger.log( + ` Certificate Authority: ${service.tls_settings.certificate_authority ?? defaultCertificateAuthority}` + ); + logger.log( + ` Client Certificate: ${service.tls_settings.client_certificate ?? "None"}` + ); } // Display host details diff --git a/packages/wrangler/src/vpc/tls.ts b/packages/wrangler/src/vpc/tls.ts new file mode 100644 index 0000000000..b0191bc38c --- /dev/null +++ b/packages/wrangler/src/vpc/tls.ts @@ -0,0 +1,92 @@ +import { UserError } from "@cloudflare/workers-utils"; +import type { CertVerificationMode, TlsSettings } from "./index"; + +export interface TlsArgs { + certificateAuthority?: string; + clientCertificate?: string; + certVerificationMode?: string; +} + +/** + * Validates the TLS flags of `vpc service create` and `vpc service update` + * before any API call. + * + * A certificate reference requires an explicit verification mode, and a custom + * CA cannot be combined with `disabled`, because it is used only to verify the + * origin certificate. + * + * @param args - The TLS flags supplied on the command line. + * @throws {UserError} If the flags describe invalid TLS settings. + */ +export function validateTlsArgs(args: TlsArgs): void { + if ( + (args.certificateAuthority !== undefined || + args.clientCertificate !== undefined) && + args.certVerificationMode === undefined + ) { + throw new UserError( + "--cert-verification-mode is required when providing --certificate-authority or --client-certificate. Choose verify_full, verify_ca, or disabled.", + { telemetryMessage: "vpc tls missing cert verification mode" } + ); + } + if ( + args.certVerificationMode !== undefined && + !["verify_full", "verify_ca", "disabled"].includes( + args.certVerificationMode + ) + ) { + throw new UserError( + "Invalid --cert-verification-mode. Choose verify_full, verify_ca, or disabled.", + { telemetryMessage: "vpc tls invalid cert verification mode" } + ); + } + for (const [flag, id] of [ + ["certificate-authority", args.certificateAuthority], + ["client-certificate", args.clientCertificate], + ] as const) { + if ( + id !== undefined && + !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( + id + ) + ) { + throw new UserError( + `Invalid --${flag}: '${id}'. Provide the certificate UUID returned by wrangler cert upload.`, + { telemetryMessage: `vpc tls invalid ${flag}` } + ); + } + } + if ( + args.certificateAuthority !== undefined && + args.certVerificationMode === "disabled" + ) { + throw new UserError( + "--certificate-authority requires --cert-verification-mode verify_ca or verify_full; disabled cannot verify a custom CA.", + { + telemetryMessage: + "vpc tls certificate authority with disabled verification", + } + ); + } +} + +/** + * Builds the service TLS settings from the command-line flags alone. + * + * Service updates replace the whole configuration, so settings omitted here are + * not carried over from the existing service. + * + * @param args - TLS flags that have passed {@link validateTlsArgs}. + * @returns The TLS settings to send, or `undefined` when no TLS flags were + * supplied, which leaves the service on the platform defaults. + */ +export function tlsSettingsFromArgs(args: TlsArgs): TlsSettings | undefined { + if (args.certVerificationMode === undefined) { + return undefined; + } + return { + cert_verification_mode: args.certVerificationMode as CertVerificationMode, + certificate_authority: args.certificateAuthority, + client_certificate: args.clientCertificate, + }; +} diff --git a/packages/wrangler/src/vpc/validation.ts b/packages/wrangler/src/vpc/validation.ts index aa3db185e2..277f08da85 100644 --- a/packages/wrangler/src/vpc/validation.ts +++ b/packages/wrangler/src/vpc/validation.ts @@ -1,13 +1,11 @@ import net from "node:net"; import { UserError } from "@cloudflare/workers-utils"; +import { tlsSettingsFromArgs, validateTlsArgs } from "./tls"; import { ServiceType } from "./index"; -import type { - CertVerificationMode, - ConnectivityServiceRequest, - ServiceHost, -} from "./index"; +import type { ConnectivityServiceRequest, ServiceHost } from "./index"; +import type { TlsArgs } from "./tls"; -export interface ServiceArgs { +export interface ServiceArgs extends TlsArgs { name: string; type: ServiceType; tcpPort?: number; @@ -19,7 +17,6 @@ export interface ServiceArgs { hostname?: string; tunnelId: string; resolverIps?: string; - certVerificationMode?: string; } export function validateHostname(hostname: string): void { @@ -116,20 +113,21 @@ export function extractPortFromHostname(hostname: string): { * `--hostname db.internal:5432` is equivalent to * `--hostname db.internal --tcp-port 5432`. */ -export function toServiceArgs(args: { - name: string; - type: string; - tcpPort?: number; - appProtocol?: string; - httpPort?: number; - httpsPort?: number; - ipv4?: string; - ipv6?: string; - hostname?: string; - tunnelId: string; - resolverIps?: string; - certVerificationMode?: string; -}): ServiceArgs { +export function toServiceArgs( + args: { + name: string; + type: string; + tcpPort?: number; + appProtocol?: string; + httpPort?: number; + httpsPort?: number; + ipv4?: string; + ipv6?: string; + hostname?: string; + tunnelId: string; + resolverIps?: string; + } & TlsArgs +): ServiceArgs { const type = args.type as ServiceType; let { hostname } = args; let tcpPort = args.tcpPort; @@ -161,10 +159,13 @@ export function toServiceArgs(args: { tunnelId: args.tunnelId, resolverIps: args.resolverIps, certVerificationMode: args.certVerificationMode, + certificateAuthority: args.certificateAuthority, + clientCertificate: args.clientCertificate, }; } export function validateRequest(args: ServiceArgs) { + validateTlsArgs(args); // Validate host configuration - must have either IP addresses or hostname, not both const hasIpAddresses = Boolean(args.ipv4 || args.ipv6); const hasHostname = Boolean(args.hostname); @@ -261,12 +262,7 @@ export function buildRequest(args: ServiceArgs): ConnectivityServiceRequest { request.https_port = args.httpsPort; } - // Add TLS settings if specified - if (args.certVerificationMode) { - request.tls_settings = { - cert_verification_mode: args.certVerificationMode as CertVerificationMode, - }; - } + request.tls_settings = tlsSettingsFromArgs(args); return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c14bf62ba0..689ab561b6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,8 +10,8 @@ catalogs: specifier: 1.4.3 version: 1.4.3 '@cloudflare/workers-types': - specifier: ^5.20261112.1 - version: 5.20261112.1 + specifier: ^5.20261116.1 + version: 5.20261116.1 '@hey-api/openapi-ts': specifier: 0.94.0 version: 0.94.0 @@ -82,8 +82,8 @@ catalogs: specifier: 5.0.4 version: 5.0.4 workerd: - specifier: 1.20261112.1 - version: 1.20261112.1 + specifier: 1.20261116.1 + version: 1.20261116.1 ws: specifier: 8.21.0 version: 8.21.0 @@ -192,7 +192,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/shared': specifier: workspace:* version: link:../shared @@ -225,7 +225,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -249,7 +249,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -273,7 +273,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -300,7 +300,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@playwright/test': specifier: catalog:default version: 1.61.0 @@ -330,7 +330,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -351,7 +351,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -375,7 +375,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -414,7 +414,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 vitest: specifier: catalog:default version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@22.15.17)(@vitest/ui@5.0.4)(msw@2.14.6(@types/node@22.15.17)(typescript@5.9.3))(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) @@ -429,7 +429,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 undici: specifier: catalog:default version: 7.30.1 @@ -444,7 +444,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/mimetext': specifier: ^2.0.4 version: 2.0.4 @@ -483,7 +483,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/shared': specifier: workspace:* version: link:../shared @@ -510,7 +510,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/jest-image-snapshot': specifier: ^6.4.0 version: 6.4.0 @@ -537,7 +537,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 miniflare: specifier: workspace:* version: link:../../packages/miniflare @@ -607,7 +607,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/is-even': specifier: ^1.0.2 version: 1.0.2 @@ -625,11 +625,11 @@ importers: dependencies: '@sentry/cloudflare': specifier: ^10 - version: 10.50.0(@cloudflare/workers-types@5.20261112.1) + version: 10.50.0(@cloudflare/workers-types@5.20261116.1) devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 vitest: specifier: catalog:default version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@22.15.17)(@vitest/ui@5.0.4)(msw@2.14.6(@types/node@22.15.17)(typescript@5.9.3))(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) @@ -660,7 +660,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -688,7 +688,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -718,7 +718,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 undici: specifier: catalog:default version: 7.30.1 @@ -736,7 +736,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/debug': specifier: 4.1.12 version: 4.1.12 @@ -769,7 +769,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -794,7 +794,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/pages-plugin': specifier: workspace:* version: link:../pages-plugin-example @@ -818,7 +818,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -857,7 +857,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -878,7 +878,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -899,7 +899,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -917,7 +917,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 is-odd: specifier: ^3.0.1 version: 3.0.1 @@ -936,7 +936,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/pages-plugin': specifier: workspace:* version: link:../pages-plugin-example @@ -996,7 +996,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1017,7 +1017,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1173,19 +1173,19 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 fixtures/rules-app: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 fixtures/secrets-store: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 wrangler: specifier: workspace:* version: link:../../packages/wrangler @@ -1212,7 +1212,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/is-even': specifier: ^1.0.2 version: 1.0.2 @@ -1236,7 +1236,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 vitest: specifier: catalog:default version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@22.15.17)(@vitest/ui@5.0.4)(msw@2.14.6(@types/node@22.15.17)(typescript@5.9.3))(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) @@ -1251,7 +1251,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 esbuild: specifier: catalog:default version: 0.28.2 @@ -1269,13 +1269,13 @@ importers: devDependencies: '@better-auth/stripe': specifier: ^1.4.6 - version: 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(better-auth@1.5.4(d0026d6adc26d1c4b53992c680c192b2))(better-call@1.3.2(zod@4.6.5))(stripe@20.4.1(@types/node@22.15.17)) + version: 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(better-auth@1.5.4(8a2b1416db3c9b47c712f528b08b894a))(better-call@1.3.2(zod@4.6.5))(stripe@20.4.1(@types/node@22.15.17)) '@cloudflare/vitest-plugin': specifier: workspace:* version: link:../../packages/vitest-plugin '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@microlabs/otel-cf-workers': specifier: 1.0.0-rc.45 version: 1.0.0-rc.45(@opentelemetry/api@1.9.1) @@ -1296,7 +1296,7 @@ importers: version: 5.0.4(vitest@5.0.4) better-auth: specifier: ^1.4.6 - version: 1.5.4(d0026d6adc26d1c4b53992c680c192b2) + version: 1.5.4(8a2b1416db3c9b47c712f528b08b894a) cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -1373,7 +1373,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/shared': specifier: workspace:* version: link:../shared @@ -1428,7 +1428,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 wrangler: specifier: workspace:* version: link:../../packages/wrangler @@ -1440,7 +1440,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 miniflare: specifier: workspace:* version: link:../../packages/miniflare @@ -1488,7 +1488,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 run-script-os: specifier: ^1.1.6 version: 1.1.6 @@ -1512,7 +1512,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1533,7 +1533,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1554,7 +1554,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1575,7 +1575,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1596,7 +1596,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/jest-image-snapshot': specifier: ^6.4.0 version: 6.4.0 @@ -1629,7 +1629,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -1656,7 +1656,7 @@ importers: version: link:../../packages/workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1674,7 +1674,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 typescript: specifier: catalog:default version: 5.8.3 @@ -1760,7 +1760,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -1828,9 +1828,15 @@ importers: '@types/node': specifier: 22.15.17 version: 22.15.17 + '@types/semver': + specifier: ^7.5.1 + version: 7.7.1 esbuild: specifier: catalog:default version: 0.28.2 + semver: + specifier: ^7.7.1 + version: 7.8.5 tinyglobby: specifier: catalog:default version: 0.2.16 @@ -1855,7 +1861,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -1937,7 +1943,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -2151,7 +2157,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@octokit/types': specifier: ^13.8.0 version: 13.8.0 @@ -2175,7 +2181,7 @@ importers: version: link:../vitest-plugin '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -2199,7 +2205,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -2226,10 +2232,10 @@ importers: devDependencies: '@cloudflare/vitest-plugin': specifier: catalog:default - version: 1.4.3(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17)(vitest@5.0.4) + version: 1.4.3(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17)(vitest@5.0.4) '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/mime': specifier: ^3.0.4 version: 3.0.4 @@ -2386,7 +2392,7 @@ importers: version: 7.30.1 workerd: specifier: catalog:default - version: 1.20261112.1 + version: 1.20261116.1 ws: specifier: catalog:default version: 8.21.0 @@ -2426,7 +2432,7 @@ importers: version: link:../workers-shared '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -2580,12 +2586,21 @@ importers: '@types/node': specifier: 22.15.17 version: 22.15.17 + '@types/semver': + specifier: ^7.5.1 + version: 7.7.1 '@verdaccio/types': specifier: ^10.8.0 version: 10.8.0 get-port: specifier: ^7.0.0 version: 7.0.0 + modern-tar: + specifier: ^0.8.6 + version: 0.8.6 + semver: + specifier: ^7.7.1 + version: 7.8.5 tree-kill: specifier: catalog:default version: 1.2.2 @@ -2638,7 +2653,7 @@ importers: devDependencies: '@cloudflare/vitest-plugin': specifier: catalog:default - version: 1.4.3(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17)(vitest@5.0.4) + version: 1.4.3(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17)(vitest@5.0.4) '@cloudflare/workers-shared': specifier: workspace:* version: link:../workers-shared @@ -2647,7 +2662,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 concurrently: specifier: ^8.2.2 version: 8.2.2 @@ -2675,7 +2690,7 @@ importers: devDependencies: '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -2709,7 +2724,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/node': specifier: 22.15.17 version: 22.15.17 @@ -2733,7 +2748,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 esbuild: specifier: catalog:default version: 0.28.2 @@ -2773,7 +2788,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/ws': specifier: ^8.5.13 version: 8.5.13 @@ -2800,7 +2815,7 @@ importers: version: link:../miniflare workerd: specifier: catalog:default - version: 1.20261112.1 + version: 1.20261116.1 devDependencies: '@cloudflare/workers-tsconfig': specifier: workspace:* @@ -2941,7 +2956,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -3046,7 +3061,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3067,7 +3082,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3088,7 +3103,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3109,7 +3124,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3130,7 +3145,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3151,7 +3166,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3172,7 +3187,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3193,7 +3208,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3214,7 +3229,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3235,7 +3250,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3256,7 +3271,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3277,7 +3292,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3298,7 +3313,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3319,7 +3334,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3340,7 +3355,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3361,7 +3376,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3382,7 +3397,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/mimetext': specifier: ^2.0.4 version: 2.0.4 @@ -3415,7 +3430,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3436,7 +3451,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3457,7 +3472,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3478,7 +3493,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3499,7 +3514,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3520,7 +3535,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3541,7 +3556,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3562,7 +3577,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@playground/main-resolution-package': specifier: file:./package version: file:packages/vite-plugin-cloudflare/playground/main-resolution/package @@ -3586,7 +3601,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/express': specifier: ^5.0.1 version: 5.0.1 @@ -3613,7 +3628,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@playground/module-resolution-excludes': specifier: file:./packages/excludes version: file:packages/vite-plugin-cloudflare/playground/module-resolution/packages/excludes @@ -3625,7 +3640,7 @@ importers: version: file:packages/vite-plugin-cloudflare/playground/module-resolution/packages/requires '@remix-run/cloudflare': specifier: 2.12.0 - version: 2.12.0(@cloudflare/workers-types@5.20261112.1)(typescript@5.8.3) + version: 2.12.0(@cloudflare/workers-types@5.20261116.1)(typescript@5.8.3) '@types/react': specifier: ^18.3.11 version: 18.3.18 @@ -3658,7 +3673,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3679,7 +3694,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@fixture/shared': specifier: workspace:* version: link:../../../../fixtures/shared @@ -3731,7 +3746,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/react': specifier: 19.1.0 version: 19.1.0 @@ -3752,7 +3767,7 @@ importers: dependencies: partyserver: specifier: ^0.3.3 - version: 0.3.3(@cloudflare/workers-types@5.20261112.1) + version: 0.3.3(@cloudflare/workers-types@5.20261116.1) partysocket: specifier: ^1.1.16 version: 1.1.16(react@19.2.1) @@ -3771,7 +3786,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@tailwindcss/vite': specifier: ^4.2.1 version: 4.2.2(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) @@ -3807,7 +3822,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3828,7 +3843,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../../../workers-utils @@ -3852,7 +3867,7 @@ importers: version: 8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0) wrangler: specifier: 4.135.0 - version: 4.135.0(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17) + version: 4.135.0(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17) packages/vite-plugin-cloudflare/playground/react-spa: dependencies: @@ -3871,7 +3886,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/react': specifier: 19.1.0 version: 19.1.0 @@ -3901,7 +3916,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3922,7 +3937,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -3950,7 +3965,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/react': specifier: 19.1.0 version: 19.1.0 @@ -3983,7 +3998,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4004,7 +4019,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4025,7 +4040,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4046,7 +4061,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@vitejs/plugin-basic-ssl': specifier: ^2.2.0 version: 2.2.0(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) @@ -4070,7 +4085,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4091,7 +4106,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4112,7 +4127,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4133,7 +4148,7 @@ importers: version: link:../../../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 cf: specifier: catalog:default version: 1.0.0-beta.17(@types/node@22.15.17) @@ -4188,7 +4203,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -4440,13 +4455,13 @@ importers: devDependencies: '@cloudflare/vitest-plugin': specifier: catalog:default - version: 1.4.3(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17)(vitest@5.0.4) + version: 1.4.3(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17)(vitest@5.0.4) '@cloudflare/workers-tsconfig': specifier: workspace:* version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@sentry/cli': specifier: ^2.37.0 version: 2.41.1(encoding@0.1.13) @@ -4585,13 +4600,13 @@ importers: devDependencies: '@cloudflare/vitest-plugin': specifier: catalog:default - version: 1.4.3(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17)(vitest@5.0.4) + version: 1.4.3(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17)(vitest@5.0.4) '@cloudflare/workers-tsconfig': specifier: workspace:* version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@types/mime': specifier: ^3.0.4 version: 3.0.4 @@ -4633,7 +4648,7 @@ importers: version: 2.0.0-rc.24 workerd: specifier: catalog:default - version: 1.20261112.1 + version: 1.20261116.1 devDependencies: '@aws-sdk/client-s3': specifier: ^3.721.0 @@ -4691,7 +4706,7 @@ importers: version: link:../workers-tsconfig '@cloudflare/workers-types': specifier: catalog:default - version: 5.20261112.1 + version: 5.20261116.1 '@cloudflare/workers-utils': specifier: workspace:* version: link:../workers-utils @@ -5801,8 +5816,8 @@ packages: cpu: [x64] os: [darwin] - '@cloudflare/workerd-darwin-64@1.20261112.1': - resolution: {integrity: sha512-VeHFKYRITaoJScHG1quIEYEfGwrBxzPvBhaVhIv2Gf6iW2XoxQvi0HpUsYPZ69HVmBVf87XK6EF6vDmvDPsZmw==} + '@cloudflare/workerd-darwin-64@1.20261116.1': + resolution: {integrity: sha512-+zzaR7CQXcT10Tbor784vI80+rO0NEy/jkTL7ZJP6PYmwjdDj2udk+sN9Ui1nqDs+frYYUtB+7nI7kycONFb0Q==} engines: {node: '>=16'} cpu: [x64] os: [darwin] @@ -5831,8 +5846,8 @@ packages: cpu: [arm64] os: [darwin] - '@cloudflare/workerd-darwin-arm64@1.20261112.1': - resolution: {integrity: sha512-lBzZv+bM3hxP28p3f6cYJOrE5eYps+s6TrlBgHhyqyrDwMoAHeL28/e3nlLvz7u4imcjbzn/aDMEmRMUV5F2Hg==} + '@cloudflare/workerd-darwin-arm64@1.20261116.1': + resolution: {integrity: sha512-jOZBuQL3FdFC9FcVzfSDEWu1/jx3/asrQAU7TydMop8kdZWhqT4dslE3rC6cMait6w32XaglzEtV6OM1Ove9ZA==} engines: {node: '>=16'} cpu: [arm64] os: [darwin] @@ -5861,8 +5876,8 @@ packages: cpu: [x64] os: [linux] - '@cloudflare/workerd-linux-64@1.20261112.1': - resolution: {integrity: sha512-IPM9rQ5w8076KOjTURcfdugzkhLRN7J9mMpVft7d1seqTs3r3YbM0GSn7vbynQ8+Np/9sVodL4BCOlpe+/PEmg==} + '@cloudflare/workerd-linux-64@1.20261116.1': + resolution: {integrity: sha512-/HnEV29Ykg3t9X6llrnlOJ9+N+cXFNsuPTTdRiE1L/hXIkI39o1RZVjEgj3GtyWtpuhsJ1mNLrNshrEjCvzk0w==} engines: {node: '>=16'} cpu: [x64] os: [linux] @@ -5891,8 +5906,8 @@ packages: cpu: [arm64] os: [linux] - '@cloudflare/workerd-linux-arm64@1.20261112.1': - resolution: {integrity: sha512-Uy5ThzPbIDzaWY94sO8mKbnhtbV5kswCoBAu/+TaJ5BBQxj6THLTMMgW0+ARwfn3FXtaKk1PBwCxW1n7LFJbpw==} + '@cloudflare/workerd-linux-arm64@1.20261116.1': + resolution: {integrity: sha512-hH73ERVfyoQ19DzbjPv/Gp4klU6F7gpx99JIlkmelC3vfsXPpsJdJsNAJA8LIxILa+gfH7tfxSSciCzr+0vqOQ==} engines: {node: '>=16'} cpu: [arm64] os: [linux] @@ -5921,8 +5936,8 @@ packages: cpu: [x64] os: [win32] - '@cloudflare/workerd-windows-64@1.20261112.1': - resolution: {integrity: sha512-k4+8R3gHc5QuNIfx3jYq3jEtX7vEy1y9ZfYbyKaKww6zJscl6R7FE+z8/AAe80PSMrWs0EcCfK1nob5zJqN4sg==} + '@cloudflare/workerd-windows-64@1.20261116.1': + resolution: {integrity: sha512-eUxFymDyGt3jYjE3/OsNZlSYM5jjCKx8h4nlGRdljtK1fRUT+llI8COE/1gaqMppS6x8qN6tc8vcyRXT4pxqxw==} engines: {node: '>=16'} cpu: [x64] os: [win32] @@ -5938,8 +5953,8 @@ packages: '@cloudflare/workers-types@4.20260702.1': resolution: {integrity: sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA==} - '@cloudflare/workers-types@5.20261112.1': - resolution: {integrity: sha512-FhkAlCQ+J/pV89nhehVaarhlvZFz+ybUsePmIDN1yfI7PMmpjwdxV663e9qu+G+oQSw9oM8u5sVmheNBFn4tnw==} + '@cloudflare/workers-types@5.20261116.1': + resolution: {integrity: sha512-bym4dNT9Hnm+goedLTTTH85T6S4wOJJaOpKgk9MlEGU18/JKsChN+wHvSWUAIy5YVSm6LnuaUu3d3N4K0m8Dtg==} '@codemirror/autocomplete@6.20.0': resolution: {integrity: sha512-bOwvTOIJcG5FVo5gUUupiwYh8MioPLQ4UcqbcRf7UQ98X90tCa9E1kZ3Z7tqwpZxYyOvh1YTYbmZE9RTfTp5hg==} @@ -16221,8 +16236,8 @@ packages: engines: {node: '>=16'} hasBin: true - workerd@1.20261112.1: - resolution: {integrity: sha512-ESBRrPFPyAGEW7QD2PuqF2RF+mjO+my1uA3lCfMeK0HfogmMQ9j2M7lain3FOVinD/El6d+77JA5AQJ85GDtFg==} + workerd@1.20261116.1: + resolution: {integrity: sha512-w3uPBuALjYs4n/p6x5SodorOe5y1bsBZ3RYeH1g0W5l73vT+yPGI7/WtxfzXbxZqpeCZ0/RfEwgD8Pc43uzu+w==} engines: {node: '>=16'} hasBin: true @@ -17121,7 +17136,7 @@ snapshots: optionalDependencies: '@types/react': 19.2.13 - '@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1)': + '@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1)': dependencies: '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -17132,9 +17147,9 @@ snapshots: nanostores: 1.1.1 zod: 4.6.5 optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 - '@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@6.2.1)(kysely@0.28.11)(nanostores@1.1.1)': + '@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@6.2.1)(kysely@0.28.11)(nanostores@1.1.1)': dependencies: '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -17145,50 +17160,50 @@ snapshots: nanostores: 1.1.1 zod: 4.6.5 optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 - '@better-auth/drizzle-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261112.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)))': + '@better-auth/drizzle-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261116.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)))': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 - drizzle-orm: 0.45.1(@cloudflare/workers-types@5.20261112.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) + drizzle-orm: 0.45.1(@cloudflare/workers-types@5.20261116.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) - '@better-auth/kysely-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(kysely@0.28.11)': + '@better-auth/kysely-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(kysely@0.28.11)': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 kysely: 0.28.11 - '@better-auth/memory-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)': + '@better-auth/memory-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 - '@better-auth/mongo-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.10))': + '@better-auth/mongo-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.10))': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 mongodb: 7.1.0(socks@2.8.10) - '@better-auth/prisma-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))': + '@better-auth/prisma-adapter@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 '@prisma/client': 7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3) prisma: 7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3) - '@better-auth/stripe@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(better-auth@1.5.4(d0026d6adc26d1c4b53992c680c192b2))(better-call@1.3.2(zod@4.6.5))(stripe@20.4.1(@types/node@22.15.17))': + '@better-auth/stripe@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(better-auth@1.5.4(8a2b1416db3c9b47c712f528b08b894a))(better-call@1.3.2(zod@4.6.5))(stripe@20.4.1(@types/node@22.15.17))': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) - better-auth: 1.5.4(d0026d6adc26d1c4b53992c680c192b2) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + better-auth: 1.5.4(8a2b1416db3c9b47c712f528b08b894a) better-call: 1.3.2(zod@4.6.5) defu: 6.1.4 stripe: 20.4.1(@types/node@22.15.17) zod: 4.6.5 - '@better-auth/telemetry@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))': + '@better-auth/telemetry@1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))': dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1) '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 @@ -17807,13 +17822,13 @@ snapshots: - bufferutil - utf-8-validate - '@cloudflare/vitest-plugin@1.4.3(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17)(vitest@5.0.4)': + '@cloudflare/vitest-plugin@1.4.3(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17)(vitest@5.0.4)': dependencies: cjs-module-lexer: 1.2.3 esbuild: 0.28.2 miniflare: 5.20261012.0-beta(@types/node@22.15.17) vitest: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@22.15.17)(@vitest/ui@5.0.4)(msw@2.14.6(@types/node@22.15.17)(typescript@5.9.3))(vite@8.3.4(@types/node@22.15.17)(esbuild@0.28.2)(jiti@2.6.1)(tsx@4.23.15)(yaml@2.9.0)) - wrangler: 4.151.0(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17) + wrangler: 4.151.0(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17) zod: 4.6.5 transitivePeerDependencies: - '@cloudflare/workers-types' @@ -17833,7 +17848,7 @@ snapshots: '@cloudflare/workerd-darwin-64@1.20261012.1': optional: true - '@cloudflare/workerd-darwin-64@1.20261112.1': + '@cloudflare/workerd-darwin-64@1.20261116.1': optional: true '@cloudflare/workerd-darwin-arm64@1.20260423.1': @@ -17848,7 +17863,7 @@ snapshots: '@cloudflare/workerd-darwin-arm64@1.20261012.1': optional: true - '@cloudflare/workerd-darwin-arm64@1.20261112.1': + '@cloudflare/workerd-darwin-arm64@1.20261116.1': optional: true '@cloudflare/workerd-linux-64@1.20260423.1': @@ -17863,7 +17878,7 @@ snapshots: '@cloudflare/workerd-linux-64@1.20261012.1': optional: true - '@cloudflare/workerd-linux-64@1.20261112.1': + '@cloudflare/workerd-linux-64@1.20261116.1': optional: true '@cloudflare/workerd-linux-arm64@1.20260423.1': @@ -17878,7 +17893,7 @@ snapshots: '@cloudflare/workerd-linux-arm64@1.20261012.1': optional: true - '@cloudflare/workerd-linux-arm64@1.20261112.1': + '@cloudflare/workerd-linux-arm64@1.20261116.1': optional: true '@cloudflare/workerd-windows-64@1.20260423.1': @@ -17893,7 +17908,7 @@ snapshots: '@cloudflare/workerd-windows-64@1.20261012.1': optional: true - '@cloudflare/workerd-windows-64@1.20261112.1': + '@cloudflare/workerd-windows-64@1.20261116.1': optional: true '@cloudflare/workers-editor-shared@0.1.1(@cloudflare/style-const@6.1.3(react@19.2.4))(@cloudflare/style-container@7.12.2(@cloudflare/style-const@6.1.3(react@19.2.4))(react@19.2.4))(react-dom@19.2.4(react@19.2.4))(react@19.2.4)': @@ -17906,7 +17921,7 @@ snapshots: '@cloudflare/workers-types@4.20260702.1': {} - '@cloudflare/workers-types@5.20261112.1': {} + '@cloudflare/workers-types@5.20261116.1': {} '@codemirror/autocomplete@6.20.0': dependencies: @@ -19837,10 +19852,10 @@ snapshots: optionalDependencies: '@types/react': 19.2.13 - '@remix-run/cloudflare@2.12.0(@cloudflare/workers-types@5.20261112.1)(typescript@5.8.3)': + '@remix-run/cloudflare@2.12.0(@cloudflare/workers-types@5.20261116.1)(typescript@5.8.3)': dependencies: '@cloudflare/kv-asset-handler': 0.1.3 - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 '@remix-run/server-runtime': 2.12.0(typescript@5.8.3) optionalDependencies: typescript: 5.8.3 @@ -20312,12 +20327,12 @@ snapshots: - encoding - supports-color - '@sentry/cloudflare@10.50.0(@cloudflare/workers-types@5.20261112.1)': + '@sentry/cloudflare@10.50.0(@cloudflare/workers-types@5.20261116.1)': dependencies: '@opentelemetry/api': 1.9.1 '@sentry/core': 10.50.0 optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 '@sentry/core@10.50.0': {} @@ -21953,15 +21968,15 @@ snapshots: before-after-hook@2.2.3: {} - better-auth@1.5.4(d0026d6adc26d1c4b53992c680c192b2): + better-auth@1.5.4(8a2b1416db3c9b47c712f528b08b894a): dependencies: - '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@6.2.1)(kysely@0.28.11)(nanostores@1.1.1) - '@better-auth/drizzle-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261112.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))) - '@better-auth/kysely-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(kysely@0.28.11) - '@better-auth/memory-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1) - '@better-auth/mongo-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.10)) - '@better-auth/prisma-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) - '@better-auth/telemetry': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261112.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1)) + '@better-auth/core': 1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@6.2.1)(kysely@0.28.11)(nanostores@1.1.1) + '@better-auth/drizzle-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261116.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))) + '@better-auth/kysely-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(kysely@0.28.11) + '@better-auth/memory-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1) + '@better-auth/mongo-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(mongodb@7.1.0(socks@2.8.10)) + '@better-auth/prisma-adapter': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1))(@better-auth/utils@0.3.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) + '@better-auth/telemetry': 1.5.4(@better-auth/core@1.5.4(@better-auth/utils@0.3.1)(@better-fetch/fetch@1.1.21)(@cloudflare/workers-types@5.20261116.1)(better-call@1.3.2(zod@4.6.5))(jose@5.9.3)(kysely@0.28.11)(nanostores@1.1.1)) '@better-auth/utils': 0.3.1 '@better-fetch/fetch': 1.1.21 '@noble/ciphers': 2.1.1 @@ -21974,7 +21989,7 @@ snapshots: zod: 4.6.5 optionalDependencies: '@prisma/client': 7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3) - drizzle-orm: 0.45.1(@cloudflare/workers-types@5.20261112.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) + drizzle-orm: 0.45.1(@cloudflare/workers-types@5.20261116.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)) mongodb: 7.1.0(socks@2.8.10) mysql2: 3.15.3 pg: 8.16.3 @@ -22808,9 +22823,9 @@ snapshots: dependencies: wordwrap: 1.0.0 - drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261112.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)): + drizzle-orm@0.45.1(@cloudflare/workers-types@5.20261116.1)(@electric-sql/pglite@0.4.1)(@opentelemetry/api@1.9.1)(@prisma/client@7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3))(@types/pg@8.15.4)(kysely@0.28.11)(mysql2@3.15.3)(pg@8.16.3)(postgres@3.4.7)(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3)): optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 '@electric-sql/pglite': 0.4.1 '@opentelemetry/api': 1.9.1 '@prisma/client': 7.6.0(prisma@7.6.0(@types/react-dom@19.2.3(@types/react@19.2.13))(@types/react@19.2.13)(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(typescript@5.8.3))(typescript@5.8.3) @@ -25387,9 +25402,9 @@ snapshots: parseurl@1.3.3: {} - partyserver@0.3.3(@cloudflare/workers-types@5.20261112.1): + partyserver@0.3.3(@cloudflare/workers-types@5.20261116.1): dependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 nanoid: 5.1.7 partysocket@1.1.16(react@19.2.1): @@ -28212,15 +28227,15 @@ snapshots: '@cloudflare/workerd-linux-arm64': 1.20261012.1 '@cloudflare/workerd-windows-64': 1.20261012.1 - workerd@1.20261112.1: + workerd@1.20261116.1: optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20261112.1 - '@cloudflare/workerd-darwin-arm64': 1.20261112.1 - '@cloudflare/workerd-linux-64': 1.20261112.1 - '@cloudflare/workerd-linux-arm64': 1.20261112.1 - '@cloudflare/workerd-windows-64': 1.20261112.1 + '@cloudflare/workerd-darwin-64': 1.20261116.1 + '@cloudflare/workerd-darwin-arm64': 1.20261116.1 + '@cloudflare/workerd-linux-64': 1.20261116.1 + '@cloudflare/workerd-linux-arm64': 1.20261116.1 + '@cloudflare/workerd-windows-64': 1.20261116.1 - wrangler@4.135.0(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17): + wrangler@4.135.0(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17): dependencies: '@cloudflare/kv-asset-handler': 0.5.0 '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260918.1) @@ -28231,14 +28246,14 @@ snapshots: unenv: 2.0.0-rc.24 workerd: 1.20260918.1 optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 fsevents: 2.3.3 transitivePeerDependencies: - '@types/node' - bufferutil - utf-8-validate - wrangler@4.151.0(@cloudflare/workers-types@5.20261112.1)(@types/node@22.15.17): + wrangler@4.151.0(@cloudflare/workers-types@5.20261116.1)(@types/node@22.15.17): dependencies: '@cloudflare/kv-asset-handler': 0.5.0 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261012.1) @@ -28249,7 +28264,7 @@ snapshots: unenv: 2.0.0-rc.24 workerd: 1.20261012.1 optionalDependencies: - '@cloudflare/workers-types': 5.20261112.1 + '@cloudflare/workers-types': 5.20261116.1 fsevents: 2.3.3 transitivePeerDependencies: - '@types/node' diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 452c7f93d0..3006f919ed 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -151,8 +151,8 @@ catalog: esbuild: "0.28.2" "@playwright/test": "1.61.0" playwright-chromium: "1.61.0" - "@cloudflare/workers-types": "^5.20261112.1" - workerd: "1.20261112.1" + "@cloudflare/workers-types": "^5.20261116.1" + workerd: "1.20261116.1" jsonc-parser: "3.2.0" smol-toml: "1.9.0" msw: "2.14.6" diff --git a/tools/deployments/__tests__/changeset-version.test.ts b/tools/deployments/__tests__/changeset-version.test.ts index 918ac123db..414ffed8f7 100644 --- a/tools/deployments/__tests__/changeset-version.test.ts +++ b/tools/deployments/__tests__/changeset-version.test.ts @@ -182,28 +182,30 @@ it.for( } ); -it("versions Vite plugin v2 betas after its SHA prereleases", ({ expect }) => { +it("versions Vite plugin v2 release candidates after its betas", ({ + expect, +}) => { const config = getNpmPrereleaseConfig({ name: "@cloudflare/vite-plugin", - version: "1.63.1", + version: "2.0.0-beta.v.17", "workers-sdk": { - npmPrerelease: { tag: "beta", numbered: true }, + npmPrerelease: { tag: "rc", numbered: true }, }, }); assert(config !== undefined); const firstVersion = getNextNpmPrereleaseVersion({ - previousVersion: "1.63.1", + previousVersion: "2.0.0-beta.v.17", versionAfterChangesets: "2.0.0", config, }); - expect(firstVersion).toBe("2.0.0-beta.v.0"); - expect(gt(firstVersion, "2.0.0-beta.sha-fffffffff")).toBe(true); + expect(firstVersion).toBe("2.0.0-rc.0"); + expect(gt(firstVersion, "2.0.0-beta.v.17")).toBe(true); expect( getNextNpmPrereleaseVersion({ previousVersion: firstVersion, versionAfterChangesets: "2.0.0", config, }) - ).toBe("2.0.0-beta.v.1"); + ).toBe("2.0.0-rc.1"); }); diff --git a/tools/deployments/changeset-version.ts b/tools/deployments/changeset-version.ts index aeaefa2b43..315e05f824 100644 --- a/tools/deployments/changeset-version.ts +++ b/tools/deployments/changeset-version.ts @@ -20,7 +20,6 @@ const DEPENDENCY_FIELDS = [ interface NpmPrereleaseConfig { tag: string; numbered: boolean; - numberPrefix?: "v"; } interface PackageJSON { @@ -96,18 +95,7 @@ export function getNpmPrereleaseConfig( typeof numbered === "boolean", `Invalid ${pkg.name} npmPrerelease numbered value` ); - // Vite plugin v2 betas were previously published as `2.0.0-beta.sha-*`. - // Temporarily start its Changesets releases at `2.0.0-beta.v.0`; `v` sorts - // after `sha-*`. Remove this special case once v2 is stable. - const numberPrefix = - pkg.name === "@cloudflare/vite-plugin" && tag === "beta" && numbered - ? "v" - : undefined; - return { - tag, - numbered, - ...(numberPrefix === undefined ? {} : { numberPrefix }), - }; + return { tag, numbered }; } function appendPrerelease( @@ -115,9 +103,7 @@ function appendPrerelease( config: NpmPrereleaseConfig, number: number ): string { - const prefix = - config.numberPrefix === undefined ? "" : `.${config.numberPrefix}`; - const suffix = config.numbered ? `${prefix}.${number}` : ""; + const suffix = config.numbered ? `.${number}` : ""; return `${coreVersion}-${config.tag}${suffix}`; } @@ -127,8 +113,7 @@ function appendPrerelease( * but it does not preserve either of the prerelease policies we support: * * - Numbered prereleases keep their original core version and increment the - * suffix: `2.0.0-beta.0` -> `2.0.0-beta.1`. Vite plugin v2 temporarily uses - * `2.0.0-beta.v.0` -> `2.0.0-beta.v.1` instead. + * suffix: `2.0.0-beta.0` -> `2.0.0-beta.1`. * - Unnumbered prereleases increment the patch instead: * `5.20261006.1-beta` -> `5.20261006.2-beta`. * diff --git a/tools/e2e/__tests__/common.test.ts b/tools/e2e/__tests__/common.test.ts index 0b8c17d796..3d7dc2ecef 100644 --- a/tools/e2e/__tests__/common.test.ts +++ b/tools/e2e/__tests__/common.test.ts @@ -193,6 +193,59 @@ describe("listTmpKVNamespaces()", () => { expect(result.map((p) => p.id)).toMatchInlineSnapshot(`[]`); }); + + it("keeps temp kv namespaces whose encoded creation time is under an hour old", async ({ + expect, + }) => { + const recent = Date.now() - 1000 * 60 * 10; + const old = Date.now() - 1000 * 60 * 100; + agent + .get("https://api.cloudflare.com") + .intercept({ + path: `/client/v4/accounts/${MOCK_CLOUDFLARE_ACCOUNT_ID}/storage/kv/namespaces`, + method: "GET", + query: { + page: 1, + }, + }) + .reply( + 200, + JSON.stringify({ + result: [ + // Wrangler E2E format: `generateResourceName("kv" + Date.now())` with `_` + { id: "wrangler-recent", title: `tmp_e2e_kv${recent}_0a1b2c3d` }, + { id: "wrangler-old", title: `tmp_e2e_kv${old}_0a1b2c3d` }, + // Fixture format + { + id: "fixture-recent", + title: `tmp-e2e-kv${recent}-test-remote-bindings-0a1b2c3d`, + }, + { + id: "fixture-old", + title: `tmp-e2e-kv${old}-test-remote-bindings-0a1b2c3d`, + }, + // No encoded creation time, so treated as old + { id: "undated", title: "tmp-e2e-kv-0a1b2c3d" }, + { id: "preserved", title: "preserve-e2e-get-platform-proxy-kv" }, + ], + result_info: { + page: 1, + per_page: 100, + count: 6, + total_count: 6, + total_pages: 1, + }, + }) + ); + + const result = await listTmpKVNamespaces(); + + expect(result.map((p) => p.id)).toEqual([ + "wrangler-old", + "fixture-old", + "undated", + ]); + }); }); describe("deleteKVNamespace()", () => { diff --git a/tools/e2e/common.ts b/tools/e2e/common.ts index 35d0aaa132..9aa5a74b6c 100644 --- a/tools/e2e/common.ts +++ b/tools/e2e/common.ts @@ -293,9 +293,10 @@ export const listTmpKVNamespaces = async () => { (kv) => { const isTempE2E = kv.title.includes("tmp-e2e") || kv.title.includes("tmp_e2e"); - // Since KV namespaces don't have creation date metadata, we encode the date-time in the title + // Since KV namespaces don't have creation date metadata, we encode the date-time in the title, + // e.g. `tmp_e2e_kv_` (Wrangler E2E) or `tmp-e2e-kv-` (fixtures) const creationDate = new Date( - Number(kv.title.match(/tmp[-_]e2e[-_]kv(\d+)-$/)?.[1] ?? 0) + Number(kv.title.match(/tmp[-_]e2e[-_]kv(\d+)[-_]/)?.[1] ?? 0) ); // Temp KV namespaces that are more than an hour old (or any age if no date is found) return isTempE2E && Date.now() - creationDate.valueOf() > 1000 * 60 * 60;