diff --git a/.changeset/config.json b/.changeset/config.json index 12248e5ede..74421ee795 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -2,12 +2,14 @@ "$schema": "https://unpkg.com/@changesets/config@1.6.2/schema.json", "changelog": [ "@changesets/changelog-github", - { "repo": "cloudflare/workers-sdk" } + { + "repo": "cloudflare/workers-sdk" + } ], "commit": false, "linked": [], "access": "public", - "baseBranch": "main", + "baseBranch": "vite-plugin-v1", "updateInternalDependencies": "patch", "bumpVersionsWithWorkspaceProtocolOnly": true, "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { diff --git a/.changeset/v1-artifacts-local-default.md b/.changeset/v1-artifacts-local-default.md new file mode 100644 index 0000000000..7f277d45dc --- /dev/null +++ b/.changeset/v1-artifacts-local-default.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": minor +--- + +Use the local simulator for Artifacts bindings that omit `remote` + +Artifacts now works locally without Cloudflare credentials by default. Set `remote: true` to use deployed repositories, or `remote: false` to silence the migration warning. The updated Miniflare runtime also supplies Browser Run quick actions and local Artifacts fixes. diff --git a/.changeset/v1-container-docker-hint.md b/.changeset/v1-container-docker-hint.md new file mode 100644 index 0000000000..a5d32f7b51 --- /dev/null +++ b/.changeset/v1-container-docker-hint.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": patch +--- + +Remove unsupported CLI flag advice from v1 Container Docker errors + +When Docker is unavailable, suggest disabling local Containers through `dev.enable_containers` in the Wrangler configuration. The Vite plugin does not accept the `--enable-containers` CLI flag. diff --git a/.changeset/v1-nov12-runtime.md b/.changeset/v1-nov12-runtime.md new file mode 100644 index 0000000000..3bd5316798 --- /dev/null +++ b/.changeset/v1-nov12-runtime.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": patch +--- + +Update the v1 development runtime to Miniflare 5.20261110.2-beta + +Update Wrangler to 4.161.0 to keep its public Miniflare types aligned with the runtime. Use the latest compatible runtime, including relative asset redirect normalization, while retaining Wrangler configuration through the Miniflare v4 compatibility adapter. diff --git a/.changeset/v1-relative-redirects.md b/.changeset/v1-relative-redirects.md new file mode 100644 index 0000000000..b70bd153a9 --- /dev/null +++ b/.changeset/v1-relative-redirects.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": patch +--- + +Normalize relative asset redirect pathnames without changing query values or fragments + +Keep repeated separators captured by redirect placeholders within the site's path. Preserve explicitly configured external targets, including scheme-less URLs, when serving assets during development. diff --git a/.changeset/v1-remote-proxy-retries.md b/.changeset/v1-remote-proxy-retries.md new file mode 100644 index 0000000000..1f2d004568 --- /dev/null +++ b/.changeset/v1-remote-proxy-retries.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": patch +--- + +Retry remote binding requests when a replacement preview is already ready + +A retriable request could remain queued if the old preview connection failed after a remote binding session update completed. Drain the retained remote binding proxy's retry queue immediately so requests finish without waiting for another request or reload. Requests that fail on the current preview now return the error instead of hanging. diff --git a/.changeset/v1-wrangler-remote-auth.md b/.changeset/v1-wrangler-remote-auth.md new file mode 100644 index 0000000000..4c5ee8d5bc --- /dev/null +++ b/.changeset/v1-wrangler-remote-auth.md @@ -0,0 +1,7 @@ +--- +"@cloudflare/vite-plugin": patch +--- + +Keep v1 remote bindings on Wrangler authentication + +Ignore the obsolete CLOUDFLARE_CF_AUTH environment flag so development and preview sessions continue using the project's Wrangler profile and configured account. diff --git a/.github/actions/check-remote-tests/action.yml b/.github/actions/check-remote-tests/action.yml index 363481ecf0..90a90ea517 100644 --- a/.github/actions/check-remote-tests/action.yml +++ b/.github/actions/check-remote-tests/action.yml @@ -22,7 +22,7 @@ runs: REPO: ${{ github.repository }} run: | if [ "$EVENT_NAME" = "merge_group" ] || \ - [ "$HEAD_REF" = "changeset-release/main" ]; then + [[ "$HEAD_REF" == changeset-release/vite-plugin-v1 ]]; then echo "run_remote=true" >> "$GITHUB_OUTPUT" elif [ "$EVENT_NAME" = "pull_request" ]; then HAS_LABEL=$(gh pr view "$PR_NUMBER" \ diff --git a/.github/actions/expose-actions-variables/action.yml b/.github/actions/expose-actions-variables/action.yml deleted file mode 100644 index a44eeb01d1..0000000000 --- a/.github/actions/expose-actions-variables/action.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: "Expose Actions Variables" -description: "Expose ACTIONS_RUNTIME_TOKEN and ACTIONS_RESULTS_URL on GITHUB_ENV" -runs: - using: "node20" - main: "index.mjs" diff --git a/.github/actions/expose-actions-variables/index.mjs b/.github/actions/expose-actions-variables/index.mjs deleted file mode 100644 index ea6b5254ed..0000000000 --- a/.github/actions/expose-actions-variables/index.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import fs from "node:fs"; - -fs.appendFileSync( - process.env.GITHUB_ENV, - `GITHUB_ACTIONS_RUNTIME_TOKEN=${process.env.ACTIONS_RUNTIME_TOKEN}\n` + - `GITHUB_ACTIONS_RESULTS_URL=${process.env.ACTIONS_RESULTS_URL}\n` -); diff --git a/.github/actions/install-dependencies/action.yml b/.github/actions/install-dependencies/action.yml index 35e90295f9..709fe07cd9 100644 --- a/.github/actions/install-dependencies/action.yml +++ b/.github/actions/install-dependencies/action.yml @@ -18,7 +18,7 @@ inputs: turbo-signature: description: the cache signature key for connecting to the turbo remote cache disable-cache: - description: when "true", skip the pnpm store cache on setup-node (defense in depth for release builds) + description: when "true", skip the pnpm store and Turbo remote caches (defense in depth for release builds) default: "false" runs: using: "composite" @@ -53,15 +53,29 @@ runs: shell: bash run: echo "NODE_VERSION=$(node --version)" >> "$GITHUB_ENV" - - name: "Configure turbo repo cache environment variables" - if: inputs.turbo-api + - name: Record CI context for Turbo cache keys shell: bash + env: + CACHE_BASE_REF: ${{ github.base_ref || github.event.merge_group.base_ref || github.ref_name }} + CACHE_RUNNER_OS: ${{ runner.os }} run: | - echo "TURBO_API=${{ inputs.turbo-api }}" >> $GITHUB_ENV - echo "TURBO_TEAM=${{ inputs.turbo-team }}" >> $GITHUB_ENV - echo "TURBO_TOKEN=${{ inputs.turbo-token }}" >> $GITHUB_ENV - echo "TURBO_REMOTE_CACHE_SIGNATURE_KEY=${{ inputs.turbo-signature }}" >> $GITHUB_ENV - echo "TURBO_ENV_MODE=loose" >> $GITHUB_ENV + echo "CI_BASE_BRANCH=${CACHE_BASE_REF#refs/heads/}" >> "$GITHUB_ENV" + echo "CI_OS=$CACHE_RUNNER_OS" >> "$GITHUB_ENV" + + - name: Configure Turbo remote cache + if: inputs.turbo-api != '' && inputs.disable-cache != 'true' + shell: bash + env: + TURBO_API: ${{ inputs.turbo-api }} + TURBO_TEAM: ${{ inputs.turbo-team }} + TURBO_TOKEN: ${{ inputs.turbo-token }} + TURBO_REMOTE_CACHE_SIGNATURE_KEY: ${{ inputs.turbo-signature }} + run: | + echo "TURBO_API=$TURBO_API" >> "$GITHUB_ENV" + echo "TURBO_TEAM=$TURBO_TEAM" >> "$GITHUB_ENV" + echo "TURBO_TOKEN=$TURBO_TOKEN" >> "$GITHUB_ENV" + echo "TURBO_REMOTE_CACHE_SIGNATURE_KEY=$TURBO_REMOTE_CACHE_SIGNATURE_KEY" >> "$GITHUB_ENV" + echo "TURBO_ENV_MODE=loose" >> "$GITHUB_ENV" - name: Install NPM Dependencies shell: bash diff --git a/.github/actions/install-python-uv/action.yml b/.github/actions/install-python-uv/action.yml deleted file mode 100644 index e070ef0a19..0000000000 --- a/.github/actions/install-python-uv/action.yml +++ /dev/null @@ -1,9 +0,0 @@ -name: "Install Python uv" -runs: - using: "composite" - steps: - - name: Install uv for Python - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6 - with: - version: "0.12.3" - enable-cache: false diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index b7a686b6bf..0000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,53 +0,0 @@ -version: 2 -updates: - # Automatically check for updates in framework CLIs for C3 - - package-ecosystem: "npm" - open-pull-requests-limit: 10 - directory: "/packages/create-cloudflare/src/frameworks" - schedule: - interval: "weekly" - # Don't run these at midday on Mondays, when we are busy trying to land PRs - day: "sunday" - time: "06:00" - versioning-strategy: increase - # Match the 24h minimumReleaseAge enforced by pnpm in pnpm-workspace.yaml - # so Dependabot doesn't open PRs that CI will then reject. - cooldown: - default-days: 1 - # the following is used to add the [C3] prefix to the PR title, - # we override the commit message but setting a prefix like this - # makes it so that also the PR title gets such prefix - commit-message: - prefix: "[C3] " - labels: - - "package:c3" - - "dependencies" - - "ci:skip-pr-description-validation" - - # Check for workerd & workers-types updates for Miniflare - - package-ecosystem: "npm" - # If you restrict the update to a directory that is not the root - # then it will not update the pnpm-lock.yaml. - directory: "/" - groups: - # We want to keep workerd and workers-types updates in lock-step - workerd-and-workers-types: - patterns: - - "workerd" - - "@cloudflare/workers-types" - schedule: - interval: "daily" - time: "06:00" - # These packages are published by Cloudflare and can be updated immediately. - cooldown: - exclude: - - "workerd" - - "@cloudflare/workers-types" - versioning-strategy: increase - labels: - - "package:miniflare" - - "dependencies" - - "ci:skip-pr-description-validation" - allow: - - dependency-name: "workerd" - - dependency-name: "@cloudflare/workers-types" diff --git a/.github/extract-pr-and-workflow-id.js b/.github/extract-pr-and-workflow-id.js deleted file mode 100644 index 55810e72c4..0000000000 --- a/.github/extract-pr-and-workflow-id.js +++ /dev/null @@ -1,21 +0,0 @@ -// This file is not used directly. -// Instead its contents are used in `.github/workflows/write-prerelease-comment.yml` -// Any changes here should be copied into the CI step there. -const allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({ - owner: context.repo.owner, - repo: context.repo.repo, - run_id: context.payload.workflow_run.id, -}); - -for (const artifact of allArtifacts.data.artifacts) { - // Extract the PR number from the artifact name - const match = /^npm-package-(.+)-(\d+)$/.exec(artifact.name); - if (match) { - const packageName = match[1].toUpperCase(); - require("fs").appendFileSync( - process.env.GITHUB_ENV, - `\nWORKFLOW_RUN_PR_FOR_${packageName}=${match[2]}` + - `\nWORKFLOW_RUN_ID_FOR_${packageName}=${context.payload.workflow_run.id}` - ); - } -} diff --git a/.github/get-c3-dependabot-bumped-framework.cjs b/.github/get-c3-dependabot-bumped-framework.cjs deleted file mode 100644 index 8bdde7f9e4..0000000000 --- a/.github/get-c3-dependabot-bumped-framework.cjs +++ /dev/null @@ -1,26 +0,0 @@ -const { execSync } = require("child_process"); - -module.exports = function () { - const diff = execSync( - `git diff origin/${process.env.GITHUB_BASE_REF} -- packages/create-cloudflare/src/frameworks/package.json` - ).toString(); - - const changedPackages = diff - .match(/-\s*".*?":\s".*?",?/g) - .map((match) => match.match(/-\s*"(.*)":/)?.[1]) - .filter(Boolean); - - if (changedPackages.length === 0) { - console.warn("No changes detected!"); - return null; - } else if (changedPackages.length > 1) { - console.warn( - `More then one package has changed (${changedPackages.join( - ", " - )}), that's not currently supported` - ); - throw new Error("More than one package bump detected"); - } else { - return changedPackages[0]; - } -}; diff --git a/.github/prereleases/upload.mjs b/.github/prereleases/upload.mjs index 1648821adf..7ae65378d6 100644 --- a/.github/prereleases/upload.mjs +++ b/.github/prereleases/upload.mjs @@ -28,12 +28,14 @@ function getPackages() { } export function getPackagesForPrerelease() { - return getPackages().filter((pkg) => pkg.json["workers-sdk"]?.prerelease); + return getPackages().filter( + (pkg) => !pkg.json.private && pkg.json["workers-sdk"]?.prerelease + ); } const pkgs = getPackagesForPrerelease(); -spawnSync( +const result = spawnSync( "pnpm", [ "dlx", @@ -48,3 +50,6 @@ spawnSync( stdio: "inherit", } ); + +if (result.error) throw result.error; +process.exitCode = result.status ?? 1; diff --git a/.github/version-script.js b/.github/version-script.js deleted file mode 100644 index fb13807022..0000000000 --- a/.github/version-script.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Update the package.json version property for the given package - * - * Usage: - * - * ``` - * node ./.github/version-script.js - * ``` - * - * `` defaults to `wrangler` if not provided. - */ - -const { readFileSync, writeFileSync } = require("fs"); -const { execSync } = require("child_process"); - -try { - const packageName = getArgs()[0] ?? "wrangler"; - const packageJsonPath = `./packages/${packageName}/package.json`; - const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8")); - const stdout = execSync("git rev-parse --short HEAD", { encoding: "utf8" }); - pkg.version = "0.0.0-" + stdout.trim(); - writeFileSync(packageJsonPath, JSON.stringify(pkg, null, "\t") + "\n"); -} catch (error) { - console.error(error); - process.exit(1); -} - -/** - * Get the command line args, stripping `node` and script filename, etc. - */ -function getArgs() { - const args = Array.from(process.argv); - while (args.shift() !== module.filename) {} - return args; -} diff --git a/.github/workflows/README.md b/.github/workflows/README.md index d1b9eb5e62..b5dc7db216 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -1,198 +1,16 @@ -# GitHub Actions +# Vite plugin v1 workflows -See below for a summary of this repo's Actions +- test-and-check.yml runs validation, plugin/private-package unit tests, and integration fixture tests. +- vite-plugin-playgrounds.yml runs dev and build/preview browser tests on Vite 6, 7, and 8; Vite 8 also runs on macOS and Windows. +- e2e-vite.yml tests installation through supported package managers. Remote tests require the ci:run-remote-tests PR label or the merge queue; fork PRs never receive credentials. +- prerelease.yml builds and preview-publishes only the plugin through pkg.pr.new. +- changesets.yml versions and releases only the plugin from vite-plugin-v1, using npm's v1 dist-tag. +- codeowners.yml and the rerun-codeowners workflow pair preserve required ownership approvals and re-evaluate them after reviews. Changeset release branches are skipped. +- bonk-pr-review.yml reviews new same-repository PRs from Cloudflare org members, excluding changeset release PRs. +- validate-pr-description.yml keeps PR test, changeset, and documentation declarations consistent. -- _Actions marked with "⚠️" are expected to sometimes fail._ +CI, playground, and E2E jobs use the signed Turbo remote cache. Cache keys include the target base branch, operating system, and Node version. PRs, branch pushes, and merge-queue runs normalize the base branch to the same name. Playground keys also include the selected Vite major, the plugin build hash captured before compatibility downgrades, and shared test configuration/helpers. Checks run lint, types, and formatting through Turbo. -## Security auditing +Dependency installation uses a frozen lockfile. Release builds skip shared caches and omit package source maps. Every external GitHub Action remains pinned to a full commit SHA. -We use [`zizmor`](https://docs.zizmor.sh/) to audit GitHub Actions workflow definitions and keep CI workflows as safe as possible. When changing files in this directory, run: - -```sh -zizmor .github/workflows/*.yml -``` - -Workflow changes should avoid unsuppressed `zizmor` findings. In particular: - -- Pin external actions to immutable commit SHAs, not tags. -- Use `actions/checkout` v6 or newer so persisted credentials are stored under `$RUNNER_TEMP`; set `persist-credentials: false` when a job does not need follow-up authenticated Git operations. -- Pass GitHub expression values into shell steps through `env` instead of expanding `${{ ... }}` directly inside `run` blocks. -- Treat privileged triggers such as `pull_request_target` and `workflow_run` as security-sensitive. If a privileged trigger is required, document the safety model and add a targeted `zizmor` ignore with a reason. - -## PR related actions - -### Vouch (vouch.yml) - -- Triggers - - A new PR is opened on the Cloudflare repository. - - Reopening a PR does not trigger the check, so maintainers can reopen one after triage. -- Actions - - Allows bots, collaborators with write access, and authors listed in [`.github/VOUCHED.td`](../VOUCHED.td). - - Posts [the Workers SDK response](../vouch-pr-response.md) and closes PRs from unregistered collaborators. -- Safety model - - Uses `pull_request_target` so the token can comment on and close fork PRs. - - Checks out the current head of the repository's default branch (`main`) to read the response template, including for PRs targeting older branches. The Vouch action also reads the contributor list from the default branch. - - Does not check out or execute PR head code. Checkout credentials are not persisted, and token permissions are limited to reading contents and writing PRs. -- Maintaining the list - - Add or remove GitHub usernames in `.github/VOUCHED.td` through a reviewed PR. Write-access collaborators and bots do not need list entries. - -### Tests + Checks (test-and-check.yml) - -- Triggers - - Updates to PRs. - - PRs in the merge queue. -- Actions - - Builds all the packages. - - Runs formatting, linting and type checks. - - Runs fixture tests, Wrangler unit tests, C3 unit tests, Miniflare unit tests, and Oxlint + Oxfmt checks. - - Adds the PR to a GitHub project - - Makes sure that Wrangler's warning for old Node.js versions works. -- Test scheduling - - Each OS starts Vite/Vitest integrations independently of the other packages, fixtures in two package shards, and dev-registry in a dedicated partition. Wrangler and Miniflare use three complete Vitest file shards on Windows and two on Linux/macOS. Tools and release source map tests run on Linux. All existing platform coverage is retained. - - Fixture shards execute whole packages, preserving custom test commands and multi-project suites. New fixtures with a `test:ci` script are assigned automatically. dev-registry starts independently so it cannot queue behind other fixtures. The remaining fixtures are balanced using duration estimates in `tools/test/run-fixture-shard.ts`. - - The six existing `Tests (OS, suite)` checks remain as branch-protection gates. Each waits for all test partitions and fails if any partition fails, is cancelled, or is skipped. Individual partition checks and Turbo summaries identify the failing workload. - - Run the CI fixture groups locally with `pnpm run test:ci:fixtures --group=remaining --shard=1/2` and `pnpm run test:ci:fixtures --group=dev-registry --shard=1/1`. Omitting `--group` includes every fixture, as before. Run a runtime shard with `CI_TEST_SHARD=1/3 pnpm test:ci --filter=wrangler --filter=miniflare` (use `/2` for Linux/macOS). The runtime test tasks hash the shard environment variable without changing build cache keys. -- Uncached benchmarks - - Add `ci:no-turbo-cache` before pushing a commit to disable both local and remote Turbo cache reads and writes, including dependent builds and repository checks. Remove the label afterwards to restore normal caching. Adding or removing the label alone does not start this workflow; reruns retain the label state from the original event. - - pnpm's dependency download cache and the Chrome binary cache remain enabled. These do not cache test execution. Every Turbo invocation emits a run summary so cache status and task duration can be verified in the artifacts. - - A rebase does not force tests to run: Turbo hashes file contents, dependency tasks, configuration, and declared environment inputs. Commit SHAs are passed through without being hashed, so unchanged tasks can reuse results across commits and branches. -- Retry diagnostics - - Each test partition writes a GitHub job summary and `test-retries.json` in its Turbo artifact. It lists visible successful and exhausted Vitest retries, their test file, retry count, and combined attempt duration. Cached log replays are excluded. Streamed test output is captured independently in `.turbo/ci-logs`, so retry reports still work when Turbo cache writes are disabled. The capture helper preserves the pnpm exit code and releases pipes left open by orphaned processes after command exit, preventing a Windows failure from hanging the job. The default reporter can omit fast successful retries; missing or cancelled logs can also make the report incomplete. - - The Workflows timer-quota regressions retain all 5,100 real steps, timers, and storage operations. Each attempt uses a fresh instance and verifies 5,100 callback executions, preventing retries from replaying persisted steps. They fetch only terminal log events and assert the completed count. Each attempt logs its progress, phase, time, and errors, keeping an initial failure visible even if a retry passes. Their five-minute timeout accommodates full execution on Windows; it does not reduce the step count or replace real storage/RPC/timers. - - Interactive container tests wait for HTTP readiness independently of process state, keeping their assertions, 90-second test deadline, and zero whole-test retries. Fixture cleanup waits until its containers are gone, tolerating concurrent removal by Wrangler. - - The workflow attempt number identifies job-level reruns. Assertion polling (`vi.waitFor`, `expect.poll`) and retries inside custom test commands are separate mechanisms and are not counted by this report. Wrangler's E2E file retry loop runs in `e2e-wrangler.yml`, outside this workflow. - - Run `node -r esbuild-register tools/test/report-test-retries.ts` after a local Turbo test run with `--summarize` to inspect retry results. - -### Wrangler E2E tests (e2e-wrangler.yml) - -- Triggers - - Updates to PRs on the Cloudflare fork. - - PRs in the merge queue. -- Actions - - Runs the E2E tests for Wrangler. - - Cloudflare API credentials are only passed on Version Packages PRs (`changeset-release/main`), in the merge queue, or when the `ci:run-remote-tests` label is applied. Other PRs run the E2E suite without remote tests. - -### Vite Plugin E2E tests (e2e-vite.yml) - -- Triggers - - Updates to PRs on the Cloudflare fork. - - PRs in the merge queue. -- Actions - - Runs the E2E tests for the Vite plugin. - - Cloudflare API credentials are only passed on Version Packages PRs (`changeset-release/main`), in the merge queue, or when the `ci:run-remote-tests` label is applied. Other PRs run the E2E suite without remote tests. - -## Deploy Pages Previews (deploy-pages-preview.yml) - -- Triggers - - Updates to PRs that have one of the `preview:...` labels. -- Actions - - Deploy a preview of the matching Pages project to Cloudflare. - -## Deploy (to testing) and Test Playground Preview Worker (worker-playground-preview-testing-env-deploy-and-test.yml) - -- Triggers - - Commits merged to the `main` branch, on the Cloudflare fork, which touch files in the `packages/playground-preview-worker` directory. - - Updates to PRs, on the Cloudflare fork, with the `playground-worker` label applied. -- Actions - - Runs integrations tests to ensure the behaviour of the Worker powering the Workers Playground. - -## Create Pull Request Prerelease (prerelease.yml) - -- Triggers - - Updates to PRs. -- Actions - - Creates an installable pre-release of any package containing `{ "workers-sdk": { "prerelease": true } }` in its `package.json` (e.g. Wrangler, C3, and Miniflare) on every PR. - - Adds a comment to the PR with links to the pre-releases. - -## Housekeeping actions - -### Add issues to DevProd project (issues.yml) - -- Triggers - - Updates to issues. -- Actions - - Add the issue to a GitHub project. - -### Triage Issue (triage-issue.yml) - -- Triggers - - A new issue is opened (skips PRs and bot-authored issues). - - A new comment is created on an issue — re-triages with the latest context. Skips PRs, bot comments, and the triage bot's own report comment (matched by a marker) to avoid re-triage loops. - - Manual `workflow_dispatch` with an `issue-number` input. -- Actions - - Runs an OpenCode agent with the `.github/skills/issue-review.md` skill against the pre-fetched issue data (including existing comments) to produce a markdown triage report (`report.md`) and a structured JSON summary (`summary.json`). - - Uploads the report to the triage dashboard. - - Posts the report and structured summary as a maintainer-facing comment on the issue and applies the suggested labels (validated against existing repo labels). The comment carries a hidden marker so that re-triage updates the existing comment (via `gh`) rather than posting a duplicate. Comments and labels are attributed to the workers-devprod bot via `GH_ACCESS_TOKEN`. - - The AI agent itself runs sandboxed (no shell or network access); all GitHub writes happen in workflow steps from the generated files. - -### Generate changesets for dependabot PRs (c3-dependabot-versioning-prs.yml and miniflare-dependabot-versioning-prs.yml) - -- Triggers - - Updates to PRs, by the dependabot user, which update one of: - - frameworks dependencies in C3, - - miniflare. -- Actions - - Generates changesets for the affected package. - -### E2E Project Cleanup (e2e-project-cleanup.yml) - -- Triggers - - Scheduled to run at 3am each day. -- Actions - - Deletes any Workers and Pages projects that were not properly cleaned up by the E2E tests. - -## Main branch actions - -### Handle Changesets (changesets.yml) - -- Triggers - - Commits merged to the `main` branch, on the Cloudflare fork. -- Actions - - If there are changeset in the working directory, create or update a "Version Packages" PR to prep for a release. - - If there are no changesets, release any packages that have a bump to their version in this change. - - Public packages are deployed to npm - - Private packages will run their `deploy` script, if they have one. -- Tiered publishing - - Instead of `changeset publish`, the `publish` step runs `tools/deployments/publish-packages.ts`. - - Each package is published under a dist-tag derived from its version: stable versions use `latest`, while prereleases use their first prerelease identifier (for example, both `5.0.0-beta` and `5.0.0-beta.1` use `beta`). - - Packages pin their workspace siblings at an exact version (`workspace:*` is rewritten to the sibling's version at pack time). If a dependent lands on npm before its dependency has propagated, `npm install` of the dependent fails for the window in between — the release is published but broken. - - The orchestrator therefore groups packages into dependency tiers (currently three: `miniflare` and friends, then `wrangler`, then `@cloudflare/vite-plugin` / `@cloudflare/vitest-plugin`) and publishes tier by tier. Packages within a tier publish in parallel, bounded by `PUBLISH_CONCURRENCY`. - - Between tiers it polls the registry until every version just published is resolvable _and_ its tarball is fetchable, then waits a further `PUBLISH_PROPAGATION_MIN_SECONDS` — a successful read only proves the release runner's own CDN edge is up to date. That settle time is unconditional rather than a floor on the total gate duration: other edges can only serve a version once it is retrievable from the origin, and the first successful read is the best available proxy for when that happened. If a version never appears within `PUBLISH_PROPAGATION_TIMEOUT_SECONDS`, the release fails instead of publishing a broken dependent. - - Only `dependencies`/`peerDependencies`/`optionalDependencies` create ordering. `devDependencies` are excluded: consumers never install them, and including them would create cycles because packages like `wrangler` dev-depend on their own dependents. - - Packages whose exact version is already on npm are skipped, so re-running a partially failed release picks up only what is still missing. That "is it already published?" check runs once per tier _during_ the release, so its reads are retried (`PUBLISH_READ_RETRY_ATTEMPTS`, with exponential backoff) — otherwise one transient 5xx while checking a later tier would abort a run that had already published earlier tiers. A 404 is not retried, since it legitimately means "not published yet". - - If any package in a tier fails, later tiers are not attempted and **no git tags are created**, so a re-run retries cleanly. Tags are created at the very end by `changeset tag`, which also emits the `New tag:` lines that `changesets/action` parses into its `publishedPackages` output (consumed by the non-npm deployment step). - - Run `node -r esbuild-register tools/deployments/publish-packages.ts --dry-run` to print the computed tiers without publishing. - -## C3 related actions - -### C3 E2E Tests (c3-e2e.yml) - -- Triggers - - Updates to PRs. - - PRs in the merge queue. -- Actions - - Runs C3 E2E tests without Cloudflare API credentials. - - Runs framework tests when C3 changes, on release PRs, in the merge queue, or with `run-c3-frameworks-tests`. - - Runs framework cases in parallel shards. Required framework checks wait for all shards to succeed. - - Framework tests default to one retry. - - Uploads test logs, Vitest results, Turbo summaries, and retry reports. - - `ci:no-turbo-cache` disables Turbo caching for tests and builds; apply it before pushing. - -See [C3 E2E instructions](../../packages/create-cloudflare/e2e/README.md) for local testing and configuration. - -### Rerun Code Owners (rerun-codeowners.yml + rerun-codeowners-privileged.yml) - -- Triggers - - A review is submitted or dismissed on a PR. -- Actions - - Re-runs the "Run Codeowners Plus" check so it re-evaluates approval status after the review change. - - Uses the `workflow_run` pattern: the trigger workflow exists solely to fire a `workflow_run` event; the privileged companion workflow (which has full permissions) reads the PR head SHA from `github.event.workflow_run.head_sha` and performs the re-run. This is necessary because `pull_request_review` gives a read-only token for fork PRs and has no `_target` variant. - -### Rerun Remote Tests (rerun-remote-tests.yml) - -- Triggers - - The `ci:run-remote-tests` or `run-c3-frameworks-tests` label is added to or removed from a PR. -- Actions - - `ci:run-remote-tests` re-runs the Wrangler and Vite E2E workflows so they pick up the label change and pass (or withhold) API credentials to the test steps. - - `run-c3-frameworks-tests` re-runs only the C3 E2E workflow. - - Uses `pull_request_target` to get a privileged token even for fork PRs (safe because no untrusted code is checked out). +Test job names preserve the status contexts required by the repository rules for vite-plugin-v1. diff --git a/.github/workflows/bonk-pr-review.yml b/.github/workflows/bonk-pr-review.yml index 9771e83362..07dea9fb6b 100644 --- a/.github/workflows/bonk-pr-review.yml +++ b/.github/workflows/bonk-pr-review.yml @@ -2,6 +2,7 @@ name: New PR Review on: pull_request: + branches: [vite-plugin-v1] types: [opened] jobs: @@ -9,7 +10,7 @@ jobs: # Skip Version Packages PRs (auto-generated by the changesets action) since they don't need a Bonk review if: | github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name && - !(github.event.pull_request.base.repo.owner.login == 'cloudflare' && github.event.pull_request.head.ref == 'changeset-release/main') + !(github.event.pull_request.base.repo.owner.login == 'cloudflare' && startsWith(github.event.pull_request.head.ref, 'changeset-release/')) runs-on: ubuntu-latest timeout-minutes: 30 concurrency: diff --git a/.github/workflows/bonk.yml b/.github/workflows/bonk.yml deleted file mode 100644 index db3e9f8fa8..0000000000 --- a/.github/workflows/bonk.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: Bonk - -on: - issue_comment: - types: [created] - pull_request_review_comment: - types: [created] - -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.issue.number || github.ref }} - cancel-in-progress: false - -jobs: - bonk: - if: github.event.sender.type != 'Bot' && (contains(github.event.comment.body, '/bonk') || contains(github.event.comment.body, '@ask-bonk')) - runs-on: ubuntu-latest - timeout-minutes: 60 - permissions: - id-token: write - contents: write - issues: write - pull-requests: write - steps: - - name: Check if comment author is Cloudflare org member - run: | - STATUS=$(gh api \ - -H "Accept: application/vnd.github+json" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - "/orgs/cloudflare/members/${COMMENT_AUTHOR}" \ - --silent -i 2>/dev/null | head -1 | awk '{print $2}') || true - if [ "$STATUS" != "204" ]; then - echo "User ${COMMENT_AUTHOR} is not a member of the Cloudflare organization" - exit 1 - fi - echo "User ${COMMENT_AUTHOR} is a Cloudflare org member" - env: - GH_TOKEN: ${{ secrets.READ_ONLY_ORG_GITHUB_TOKEN }} - COMMENT_AUTHOR: ${{ github.event.comment.user.login }} - - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Build prompt with triggering comment - id: prompt - run: | - { - DELIMITER=$(openssl rand -hex 16) - echo "value<<$DELIMITER" - echo "You were invoked by @${COMMENT_AUTHOR} on ${COMMENT_URL}" - echo "" - echo "Their comment:" - echo '```' - echo "$COMMENT_BODY" - echo '```' - echo "" - echo "This is your task. Read it carefully and act on it." - echo "$DELIMITER" - } >> "$GITHUB_OUTPUT" - env: - COMMENT_AUTHOR: ${{ github.event.comment.user.login }} - COMMENT_BODY: ${{ github.event.comment.body }} - COMMENT_URL: ${{ github.event.comment.html_url }} - - - name: Run Bonk - uses: ask-bonk/ask-bonk/github@d00cbcf581a5463f7adc2d81e470234b1727f8dd # main - env: - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CF_AI_GATEWAY_ACCOUNT_ID }} - CLOUDFLARE_GATEWAY_ID: ${{ secrets.CF_AI_GATEWAY_NAME }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CF_AI_GATEWAY_TOKEN }} - OPENCODE_CONFIG_CONTENT: '{"permission":{"external_directory":{"/home/runner/work/**":"allow"},"question":"deny","doom_loop":"deny"}}' - with: - oidc_base_url: https://ask-bonk.cloudflare-exponent.workers.dev/auth - model: "cloudflare-ai-gateway/openai/gpt-5.6-terra" - variant: "high" - mentions: "/bonk,@ask-bonk" - permissions: write - agent: bonk - opencode_dev: true - opencode_version: "latest" - prompt: ${{ steps.prompt.outputs.value }} diff --git a/.github/workflows/c3-dependabot-versioning-prs.yml b/.github/workflows/c3-dependabot-versioning-prs.yml deleted file mode 100644 index 9e1964abe3..0000000000 --- a/.github/workflows/c3-dependabot-versioning-prs.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: "C3 - Generate changesets for dependabot PRs" -on: - pull_request_target: # zizmor: ignore[dangerous-triggers] dependabot-only job requires write access to push generated changesets; checkout v6 persists credentials under RUNNER_TEMP - paths: - - "packages/create-cloudflare/src/frameworks/package.json" - -permissions: - # content:write permission needed to update add changesets to dependabot PRs - # (see tools/dependabot/generate-dependabot-pr-changesets.ts) - contents: write - -jobs: - generate-changeset: - runs-on: ubuntu-slim - if: | - github.event.pull_request.user.login == 'dependabot[bot]' && - github.event.pull_request.head.repo.full_name == github.repository - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 2 - persist-credentials: true - ref: ${{ github.head_ref }} - token: ${{ secrets.GH_ACCESS_TOKEN }} - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Configure Git - run: | - git config --global user.email wrangler@cloudflare.com - git config --global user.name 'Wrangler automated PR updater' - - - name: Generate C3 changesets - # Keep the final param (the changeset prefix: `c3-frameworks-update`) in sync with the filter in the `.github/workflows/c3-e2e-dependabot.yml` workflow. - run: node -r esbuild-register tools/dependabot/generate-dependabot-pr-changesets.ts "$PR_NUMBER" create-cloudflare packages/create-cloudflare/src/frameworks/package.json c3-frameworks-update - env: - PR_NUMBER: ${{ github.event.number }} diff --git a/.github/workflows/c3-e2e.yml b/.github/workflows/c3-e2e.yml deleted file mode 100644 index c41ccaeee6..0000000000 --- a/.github/workflows/c3-e2e.yml +++ /dev/null @@ -1,387 +0,0 @@ -name: C3 E2E -on: - merge_group: - pull_request: - -permissions: - contents: read - pull-requests: read - -# pnpm 11-specific settings - recognised by pnpm 11+ and -# silently ignored by pnpm 10. -# -# - pmOnFail=ignore: pnpm 11's default `download` would silently re-exec as -# the monorepo's pinned pnpm 10.33.0, defeating the matrix override. -# - verifyDepsBeforeRun=false: pnpm 11's default `install` would re-run -# `pnpm install` at the monorepo root before invoking the script, which -# then trips on engines.pnpm. -env: - # Match the test/check workflow's opt-in benchmarks, including nested builds. - TURBO_CACHE: ${{ contains(github.event.pull_request.labels.*.name, 'ci:no-turbo-cache') && 'local:,remote:' || 'local:rw,remote:rw' }} - TURBO_RUN_SUMMARY: "true" - pnpm_config_pm_on_fail: ignore - pnpm_config_verify_deps_before_run: "false" - -jobs: - e2e: - # Runs the non-frameworks C3 E2E tests on all supported operating systems - # and package managers. - timeout-minutes: 45 - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os.name }}-${{ matrix.pm.name }}-${{ matrix.pm.version }}${{ matrix.experimental && '-experimental' || '' }}-${{ matrix.filter }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - # `matrix.pm.label` is the display name in job/artifact names. Default - # pm entries use the plain name (e.g. `pnpm`) to keep historical required- - # check names stable; non-default entries (e.g. pnpm 11) suffix the version. - name: ${{ format('C3 E2E ({0}, {1}{2}) - {3}', matrix.pm.label, matrix.os.description, matrix.experimental && ', experimental' || '', matrix.filter) }} - strategy: - fail-fast: false - matrix: - experimental: [false] - filter: ["cli", "workers"] - os: [{ name: ubuntu-latest, description: Linux }] - pm: - - { name: pnpm, version: "10.33.0", label: "pnpm" } - - { name: pnpm, version: "11.5.1", label: "pnpm@11.5.1" } - - { name: npm, version: "11.7.0", label: "npm" } - # The yarn tests keep failing on Linux with out of space errors, with no clear reason why. Disabling for now. - # - { name: yarn, version: "1.0.0", label: "yarn" } - include: - # Windows and experimental entries stay on the default pnpm to - # preserve historical required-check names. pnpm 11 coverage comes - # from the Linux base entries above. - - os: { name: windows-latest, description: Windows } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - filter: "cli" - - os: { name: windows-latest, description: Windows } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - filter: "workers" - - os: { name: ubuntu-latest, description: Linux } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - experimental: true - filter: "cli" - - os: { name: ubuntu-latest, description: Linux } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - experimental: true - filter: "workers" - runs-on: ${{ matrix.os.name }} - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - - name: Install Dependencies - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies - with: - turbo-api: ${{ secrets.TURBO_API }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - - name: Install Python uv - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-python-uv - - # Needed because gatsby requires git - - name: Configure Git - shell: bash - run: | - git config --global user.email wrangler@cloudflare.com - git config --global user.name 'Wrangler Tester' - - # Put the matrix pnpm version on PATH so scaffolded-project installs - # run it (not the monorepo's pinned pnpm 10.33.0). Without this, the - # matrix only relabels C3's `npm_config_user_agent` and pnpm 11 - # regressions go undetected. - # - # `pnpm/action-setup` refuses when both `version` input and the root - # `package.json#packageManager` are set, so we point it at a stub - # `package.json`. We also loosen `engines.pnpm` to avoid pnpm 11 - # bailing with ERR_PNPM_UNSUPPORTED_ENGINE at the monorepo root. - - name: Prepare workspace for matrix pnpm install - if: matrix.pm.name == 'pnpm' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - mkdir -p .ci-pnpm-setup-stub - printf '{"name":"ci-stub","private":true}\n' > .ci-pnpm-setup-stub/package.json - node -e " - const fs = require('node:fs'); - const pkg = JSON.parse(fs.readFileSync('package.json','utf8')); - if (pkg.engines && pkg.engines.pnpm) pkg.engines.pnpm = '*'; - fs.writeFileSync('package.json', JSON.stringify(pkg, null, '\t') + '\n'); - " - - name: Install matrix pnpm version for scaffolded installs - if: matrix.pm.name == 'pnpm' && steps.changes.outputs.everything_but_markdown == 'true' - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9 - with: - version: ${{ matrix.pm.version }} - package_json_file: .ci-pnpm-setup-stub/package.json - # Distinct dest so `addPath` prepends ahead of the monorepo's - # pinned pnpm 10.x from the earlier `~/setup-pnpm`. - dest: ~/matrix-pnpm - - name: Verify pnpm on PATH matches matrix version - if: matrix.pm.name == 'pnpm' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - got="$(pnpm --version)" - want="${{ matrix.pm.version }}" - echo "pnpm on PATH: $got (expected $want)" - [ "$got" = "$want" ] || { echo "ERROR: PATH pnpm is $got, not $want — scaffolded installs would silently run the wrong version."; exit 1; } - - - name: Install matrix npm version for scaffolded installs - if: matrix.pm.name == 'npm' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - npm install --global npm@${{ matrix.pm.version }} - got="$(npm --version)" - want="${{ matrix.pm.version }}" - echo "npm on PATH: $got (expected $want)" - [ "$got" = "$want" ] || { echo "ERROR: PATH npm is $got, not $want."; exit 1; } - - - id: run-e2e - if: steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: pnpm run test:ci:logged .turbo/ci-logs/c3.log run test:e2e:c3 - env: - NODE_VERSION: ${{ env.NODE_VERSION }} - E2E_EXPERIMENTAL: ${{ matrix.experimental }} - E2E_TEST_PM: ${{ matrix.pm.name }} - E2E_TEST_PM_VERSION: ${{ matrix.pm.version }} - E2E_TEST_FILTER: ${{ matrix.filter }} - CI_OS: ${{ runner.os }} - GITHUB_TOKEN: ${{ github.token }} # Needed for begit to clone the repo in the e2e tests for solid-start - - - name: Report test retries - if: ${{ !cancelled() && steps.changes.outputs.everything_but_markdown == 'true' }} - run: node -r esbuild-register tools/test/report-test-retries.ts - - - name: Upload Logs - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - if: ${{ !cancelled() && steps.changes.outputs.everything_but_markdown == 'true' }} - with: - name: ${{ format('e2e-logs-{0}-{1}-{2}-{3}', matrix.pm.label, matrix.os.description, matrix.experimental && 'experimental' || 'normal', matrix.filter) }} - path: packages/create-cloudflare/.e2e-logs${{ matrix.experimental && '-experimental' || '' }}/${{ matrix.pm.name }} - include-hidden-files: true - - - name: Upload Turbo Summary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - if: ${{ !cancelled() && steps.changes.outputs.everything_but_markdown == 'true' }} - with: - name: ${{ format('turbo-runs-{0}-{1}-{2}-{3}', matrix.pm.label, matrix.os.description, matrix.experimental && 'experimental' || 'normal', matrix.filter) }} - path: | - .turbo/runs - .turbo/test-retries.json - .turbo/ci-logs - include-hidden-files: true - - frameworks-e2e-shards: - # Runs the C3 frameworks E2E tests only in the merge queue, on the release branch, if create-cloudflare has changed, or when explicitly requested via label. - # - # Frameworks that delegate install to their own generator (e.g. `hono`) - # don't route through C3's `ERR_PNPM_IGNORED_BUILDS` recovery path; those - # tests opt out of pnpm 11 via `unsupportedPmRanges` in the test config. - # Case shards retain the five concurrent tests per runner used by Vitest. - timeout-minutes: 45 - concurrency: - group: ${{ github.workflow }}-frameworks${{ matrix.experimental && '-experimental' || '' }}-${{ github.ref }}-${{ matrix.os.name }}-${{ matrix.pm.name }}-${{ matrix.pm.version }}-${{ matrix.shard }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - name: ${{ format('C3 E2E ({0}, {1}{2}) - frameworks {3}/{4}', matrix.pm.label, matrix.os.description, matrix.experimental && ', experimental' || '', matrix.shard, matrix.shards) }} - strategy: - fail-fast: false - matrix: - experimental: [false] - shard: [1, 2, 3] - shards: [3] - os: - - { name: ubuntu-latest, description: Linux } - pm: - - { name: pnpm, version: "10.33.0", label: "pnpm" } - - { name: pnpm, version: "11.5.1", label: "pnpm@11.5.1" } - - { name: npm, version: "11.7.0", label: "npm" } - include: - # The smaller experimental suite uses two shards on the default pnpm. - - os: { name: ubuntu-latest, description: Linux } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - experimental: true - shard: 1 - shards: 2 - - os: { name: ubuntu-latest, description: Linux } - pm: { name: pnpm, version: "10.33.0", label: "pnpm" } - experimental: true - shard: 2 - shards: 2 - runs-on: ${{ matrix.os.name }} - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - framework_deps: - - 'packages/create-cloudflare/**' - - - name: Check if frameworks tests should run - id: check-frameworks - shell: bash - env: - GH_TOKEN: ${{ github.token }} - EVENT_NAME: ${{ github.event_name }} - HEAD_REF: ${{ github.head_ref }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REPO: ${{ github.repository }} - FRAMEWORK_DEPS_CHANGED: ${{ steps.changes.outputs.framework_deps }} - run: | - if [ "$EVENT_NAME" = "merge_group" ] || \ - [ "$HEAD_REF" = "changeset-release/main" ] || \ - [ "$FRAMEWORK_DEPS_CHANGED" = "true" ]; then - echo "run_frameworks=true" >> "$GITHUB_OUTPUT" - elif [ "$EVENT_NAME" = "pull_request" ]; then - HAS_LABEL=$(gh pr view "$PR_NUMBER" \ - --repo "$REPO" --json labels \ - --jq '[.labels[].name] | any(. == "run-c3-frameworks-tests")') - echo "run_frameworks=${HAS_LABEL}" >> "$GITHUB_OUTPUT" - else - echo "run_frameworks=false" >> "$GITHUB_OUTPUT" - fi - - - name: Install Dependencies - if: steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies - with: - turbo-api: ${{ secrets.TURBO_API }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - - name: Install Python uv - if: steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-python-uv - - - name: Configure Git - if: steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - git config --global user.email wrangler@cloudflare.com - git config --global user.name 'Wrangler Tester' - - # See the equivalent step in the `e2e` job above for context. - - name: Prepare workspace for matrix pnpm install - if: matrix.pm.name == 'pnpm' && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - mkdir -p .ci-pnpm-setup-stub - printf '{"name":"ci-stub","private":true}\n' > .ci-pnpm-setup-stub/package.json - node -e " - const fs = require('node:fs'); - const pkg = JSON.parse(fs.readFileSync('package.json','utf8')); - if (pkg.engines && pkg.engines.pnpm) pkg.engines.pnpm = '*'; - fs.writeFileSync('package.json', JSON.stringify(pkg, null, '\t') + '\n'); - " - - name: Install matrix pnpm version for scaffolded installs - if: matrix.pm.name == 'pnpm' && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - uses: pnpm/action-setup@0ebf47130e4866e96fce0953f49152a61190b271 # v6.0.9 - with: - version: ${{ matrix.pm.version }} - package_json_file: .ci-pnpm-setup-stub/package.json - dest: ~/matrix-pnpm - - name: Verify pnpm on PATH matches matrix version - if: matrix.pm.name == 'pnpm' && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - got="$(pnpm --version)" - want="${{ matrix.pm.version }}" - echo "pnpm on PATH: $got (expected $want)" - [ "$got" = "$want" ] || { echo "ERROR: PATH pnpm is $got, not $want — scaffolded installs would silently run the wrong version."; exit 1; } - - - name: Install matrix npm version for scaffolded installs - if: matrix.pm.name == 'npm' && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: | - npm install --global npm@${{ matrix.pm.version }} - got="$(npm --version)" - want="${{ matrix.pm.version }}" - echo "npm on PATH: $got (expected $want)" - [ "$got" = "$want" ] || { echo "ERROR: PATH npm is $got, not $want."; exit 1; } - - - id: run-e2e - if: steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' - shell: bash - run: pnpm run test:ci:logged .turbo/ci-logs/c3.log run test:e2e:c3 - env: - NODE_VERSION: ${{ env.NODE_VERSION }} - # Some framework generators write a different pnpm version to `packageManager`. - # By default pnpm downloads and runs it. Concurrent tests can then provision - # that version in the same pnpm tool store, causing recursive installs. - pnpm_config_manage_package_manager_versions: "false" - E2E_EXPERIMENTAL: ${{ matrix.experimental }} - E2E_TEST_PM: ${{ matrix.pm.name }} - E2E_TEST_PM_VERSION: ${{ matrix.pm.version }} - E2E_TEST_FILTER: frameworks - E2E_FRAMEWORK_SHARD: ${{ format('{0}/{1}', matrix.shard, matrix.shards) }} - CI_OS: ${{ runner.os }} - GITHUB_TOKEN: ${{ github.token }} - - - name: Report test retries - if: ${{ !cancelled() && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' }} - run: node -r esbuild-register tools/test/report-test-retries.ts - - - name: Upload Logs - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - if: ${{ !cancelled() && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' }} - with: - name: ${{ format('e2e-logs-{0}-{1}-{2}-frameworks-{3}', matrix.pm.label, matrix.os.description, matrix.experimental && 'experimental' || 'normal', matrix.shard) }} - path: packages/create-cloudflare/.e2e-logs${{ matrix.experimental && '-experimental' || '' }}/${{ matrix.pm.name }} - include-hidden-files: true - - - name: Upload Turbo Summary - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - if: ${{ !cancelled() && steps.check-frameworks.outputs.run_frameworks == 'true' && steps.changes.outputs.everything_but_markdown == 'true' }} - with: - name: ${{ format('turbo-runs-{0}-{1}-{2}-frameworks-{3}', matrix.pm.label, matrix.os.description, matrix.experimental && 'experimental' || 'normal', matrix.shard) }} - path: | - .turbo/runs - .turbo/test-retries.json - .turbo/ci-logs - include-hidden-files: true - - # Preserve required check names and require every framework shard to succeed. - frameworks-e2e: - needs: frameworks-e2e-shards - if: always() - timeout-minutes: 5 - name: ${{ format('C3 E2E ({0}, Linux{1}) - frameworks', matrix.pm, matrix.experimental && ', experimental' || '') }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - experimental: [false] - pm: [pnpm, pnpm@11.5.1, npm] - include: - - pm: pnpm - experimental: true - steps: - - name: Require all framework shards to pass - env: - FRAMEWORK_RESULT: ${{ needs.frameworks-e2e-shards.result }} - run: | - if [ "$FRAMEWORK_RESULT" != "success" ]; then - echo "Framework shards did not all pass: $FRAMEWORK_RESULT" - exit 1 - fi diff --git a/.github/workflows/changesets.yml b/.github/workflows/changesets.yml index 676a6b0a2b..b15529c289 100644 --- a/.github/workflows/changesets.yml +++ b/.github/workflows/changesets.yml @@ -1,122 +1,44 @@ -name: Handle Changesets +name: Release Vite plugin v1 on: push: - branches: - - main + branches: [vite-plugin-v1] permissions: - id-token: write contents: read - # note: no write permissions are needed since the workflow uses GH_ACCESS_TOKEN instead of GITHUB_TOKEN + id-token: write + +concurrency: + group: vite-plugin-v1-release + cancel-in-progress: false env: - # This workflow only builds and publishes — it never runs Playwright tests. - # Skip the browser download to avoid the postinstall script hanging in CI. PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" jobs: release: - if: ${{ github.repository_owner == 'cloudflare' }} - name: Handle Changesets - runs-on: macos-latest-large + if: github.repository_owner == 'cloudflare' + runs-on: ubuntu-latest + timeout-minutes: 30 steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: - # See https://github.com/changesets/action/issues/187 token: ${{ secrets.GH_ACCESS_TOKEN }} persist-credentials: true - # Pull in more history to cover the changeset commits - fetch-depth: 500 - - - name: Install Dependencies - # Defense in depth: do not pass Turbo remote cache credentials and - # disable the pnpm store cache so release builds always resolve - # packages from the registry and rebuild every task from source, - # rather than restoring from a (potentially poisoned) cache. - uses: ./.github/actions/install-dependencies + fetch-depth: 0 + - uses: ./.github/actions/install-dependencies with: - # Pinned to 24.18.0 (rather than floating `24`) until it's safe to - # float back: Node 24.17.0 regressed node-fetch@2 keep-alive responses - # with ERR_STREAM_PREMATURE_CLOSE (nodejs/node#63989, fixed in 24.18.0). node-version: 24.18.0 disable-cache: "true" - - - name: Check npm version - run: node -r esbuild-register tools/deployments/check-npm-version.ts - - - name: Check the changesets - run: node -r esbuild-register tools/deployments/validate-changesets.ts - - - name: Build all packages - run: pnpm run build + - run: node -r esbuild-register tools/deployments/check-npm-version.ts + - run: pnpm check:changesets + - run: pnpm build env: - CI_OS: ${{ runner.os }} SOURCEMAPS: "false" - ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} - ALGOLIA_PUBLIC_KEY: ${{ secrets.ALGOLIA_PUBLIC_KEY }} - SENTRY_DSN: "https://9edbb8417b284aa2bbead9b4c318918b@sentry10.cfdata.org/583" - NODE_ENV: "production" - # This is the "production" key for sparrow analytics. - # Include this here because this step will rebuild Wrangler and needs to have this available - SPARROW_SOURCE_KEY: "50598e014ed44c739ec8074fdc16057c" - - - name: Create Version PR or Publish to NPM - id: changesets - uses: changesets/action@a45c4d594aa4e2c509dc14a9f2b3b67ba3780d0d # v1.9.0 + - uses: changesets/action@a45c4d594aa4e2c509dc14a9f2b3b67ba3780d0d # v1.9.0 with: - version: node -r esbuild-register tools/deployments/changeset-version.ts - # Replaces `changeset publish` with an orchestrator that publishes in - # dependency-tier order and waits for each tier to become resolvable - # on the registry before starting the next one. Packages pin their - # siblings at an exact version, so publishing a dependent before its - # dependency has propagated produces an installable-but-broken - # release. It still ends with `changeset tag`, so the `New tag:` lines - # this action parses into `publishedPackages` are unchanged. - publish: node -r esbuild-register tools/deployments/publish-packages.ts + title: "[vite-plugin] Version v1 maintenance release" + version: pnpm version-packages + publish: pnpm release env: GITHUB_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} - # Once every version in a tier reads back OK, wait this long before - # starting the next tier. A successful read only proves this runner's - # CDN edge is up to date, not everyone else's. - PUBLISH_PROPAGATION_MIN_SECONDS: "60" - # Fail the release rather than publish a broken dependent if a version - # never becomes resolvable. - PUBLISH_PROPAGATION_TIMEOUT_SECONDS: "600" - - # Switch to Node 22 for non-npm package deployments because quick-edit - # builds native modules (tree-sitter) that are not compatible with - # Node 24's C++20 requirement for V8 headers. - - name: Switch to Node 22 for non-npm package deployments - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - # Pinned to 22.23.1 (rather than floating `22`) until it's safe to - # float back: Node 22.23.0 regressed node-fetch@2 keep-alive responses - # with ERR_STREAM_PREMATURE_CLOSE (nodejs/node#63989, fixed in 22.23.1). - node-version: 22.23.1 - - - name: Deploy non-NPM Packages - id: deploy - run: | - node -r esbuild-register tools/deployments/deploy-non-npm-packages.ts - echo "status=$(cat deployment-status.json)" >> $GITHUB_OUTPUT; - env: - PUBLISHED_PACKAGES: ${{ steps.changesets.outputs.publishedPackages }} - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - WORKERS_NEW_CLOUDFLARE_ACCOUNT_ID: ${{ secrets.WORKERS_NEW_CLOUDFLARE_ACCOUNT_ID }} - WORKERS_NEW_CLOUDFLARE_API_TOKEN: ${{ secrets.WORKERS_NEW_CLOUDFLARE_API_TOKEN }} - WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN: ${{ secrets.WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN }} - WORKERS_SHARED_SENTRY_ACCESS_ID: ${{ secrets.WORKERS_SHARED_SENTRY_ACCESS_ID }} - WORKERS_SHARED_SENTRY_ACCESS_SECRET: ${{ secrets.WORKERS_SHARED_SENTRY_ACCESS_SECRET }} - WORKERS_SHARED_SENTRY_AUTH_TOKEN: ${{ secrets.WORKERS_SHARED_SENTRY_AUTH_TOKEN }} - - - name: Send Alert - if: always() - run: node -r esbuild-register tools/deployments/alert-on-error.ts - env: - PUBLISH_STATUS: ${{ steps.changesets.outcome }} - HAS_CHANGESETS: ${{ steps.changesets.outputs.hasChangesets }} - DEPLOYMENT_STATUS: ${{ steps.deploy.outputs.status }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - TOKEN: ${{ secrets.STATUS_BOT_SECRET }} diff --git a/.github/workflows/codeowners.yml b/.github/workflows/codeowners.yml index e3d49a123c..86bd7ce8d3 100644 --- a/.github/workflows/codeowners.yml +++ b/.github/workflows/codeowners.yml @@ -5,11 +5,12 @@ name: "Code Owners" # re-runs this check (rather than creating a second check context). # Using pull_request_target (not pull_request) so the workflow has access to secrets # for fork PRs. This is safe because: -# - GitHub runs the workflow from the base repository's default branch +# - Only trusted base repository workflow code is executed # - PR head commits are fetched as git objects only (never checked out or executed) # - The action reads ownership rules from the PR base commit and calls the GitHub API on: pull_request_target: # zizmor: ignore[dangerous-triggers] checks base branch ownership rules and fetches PR head for diff computation without executing PR code + branches: [vite-plugin-v1] types: [ opened, @@ -23,7 +24,7 @@ on: concurrency: group: codeowners-${{ github.event.pull_request.number }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} + cancel-in-progress: ${{ !startsWith(github.head_ref, 'changeset-release/') }} permissions: contents: read @@ -38,20 +39,21 @@ jobs: # every other PR supports stacks regardless of parent PR creation order. steps: - name: "Checkout Base Branch" - if: github.event.pull_request.head.ref != 'changeset-release/main' + if: ${{ !startsWith(github.event.pull_request.head.ref, 'changeset-release/') }} uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: + ref: ${{ github.event.pull_request.base.sha }} fetch-depth: 0 persist-credentials: false - name: "Fetch PR Head (for diff computation)" - if: github.event.pull_request.head.ref != 'changeset-release/main' + if: ${{ !startsWith(github.event.pull_request.head.ref, 'changeset-release/') }} run: git fetch origin +refs/pull/${{ github.event.pull_request.number }}/head env: GITHUB_TOKEN: "${{ secrets.CODEOWNERS_GITHUB_PAT }}" - name: "Codeowners Plus" - if: github.event.pull_request.head.ref != 'changeset-release/main' + if: ${{ !startsWith(github.event.pull_request.head.ref, 'changeset-release/') }} uses: multimediallc/codeowners-plus@ff02aa993a92e8efe01642916d0877beb9439e9f # v1.9.0 with: github-token: "${{ secrets.CODEOWNERS_GITHUB_PAT }}" diff --git a/.github/workflows/deploy-previews.yml b/.github/workflows/deploy-previews.yml deleted file mode 100644 index e33d37997c..0000000000 --- a/.github/workflows/deploy-previews.yml +++ /dev/null @@ -1,90 +0,0 @@ -name: Deploy Previews - -# This workflow is designed to deploy a "preview" version of a project based on PR labels. - -# Triggers: -# - update to a PR that has one of the `preview:...` labels -# -# Actions: -# - deploy the matching project to Cloudflare. -# -# PR Label | Project -# --------------------------------------------------------- -# preview:chrome-devtools-patches | packages/chrome-devtools-patches -# preview:quick-edit | packages/quick-edit -# -# Note: this workflow does not run tests against these packages, only deploys previews. - -on: - pull_request: - types: [synchronize, opened, reopened, labeled, unlabeled] - -permissions: - contents: read - # pull-request:write permission needed so that the workflow can comment on PRs - pull-requests: write - -jobs: - deploy-projects: - # Only run this on PRs that are for the "cloudflare" org and not "from" `main` - # - non-Cloudflare PRs will not have the secrets needed - # - PRs "from" main would accidentally do a production deployment - if: github.repository_owner == 'cloudflare' && github.head_ref != 'main' && (contains(github.event.*.labels.*.name, 'preview:chrome-devtools-patches') || contains(github.event.*.labels.*.name, 'preview:quick-edit')) - timeout-minutes: 60 - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-app-previews - runs-on: macos-latest-large - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Build tools and libraries - run: pnpm run build - env: - NODE_ENV: "production" - CI_OS: ${{ runner.os }} - - - name: Deploy Wrangler DevTools preview - if: contains(github.event.*.labels.*.name, 'preview:chrome-devtools-patches') - run: | - output=$(pnpm --filter @cloudflare/chrome-devtools-patches run deploy:preview) - echo "Command output: $output" - echo "Extracting deployed URL from command output" - url=$(echo "$output" | sed -nE "s/.*Version Preview URL: ([^[:space:]]+).*/\1/p") - echo "Extracted URL: $url" - echo "VITE_DEVTOOLS_PREVIEW_URL=$url" >> $GITHUB_ENV - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - - - name: Build and Deploy Quick Edit preview - if: contains(github.event.*.labels.*.name, 'preview:quick-edit') - run: pnpm --filter quick-edit run preview - env: - DEBIAN_FRONTEND: noninteractive - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - NODE_OPTIONS: "--max_old_space_size=30000" - - - name: "Comment on PR with Devtools Link" - if: contains(github.event.*.labels.*.name, 'preview:chrome-devtools-patches') - uses: marocchino/sticky-pull-request-comment@d4d6b0936434b21bc8345ad45a440c5f7d2c40ff # v3.0.3 - with: - header: chrome-devtools-preview - message: | - The Wrangler DevTools preview is now live. You can access it directly at: ${{ env.VITE_DEVTOOLS_PREVIEW_URL }}/js_app - - In order to test the DevTools preview in `wrangler`: - - 1. `npx wrangler dev`. - 2. Hit `d` to open the DevTools in a fresh browser window. - 3. Paste the DevTools preview URL into the address bar (keeping all existing query parameters), e.g: - - ``` - - https://devtools.devprod.cloudflare.dev/js_app?theme=systemPreferred&ws=127.0.0.1%3A9229%2Fws&domain=tester&debugger=true - + ${{ env.VITE_DEVTOOLS_PREVIEW_URL }}/js_app?theme=systemPreferred&ws=127.0.0.1%3A9229%2Fws&domain=tester&debugger=true - ``` diff --git a/.github/workflows/e2e-local-explorer-ui.yml b/.github/workflows/e2e-local-explorer-ui.yml deleted file mode 100644 index bb5657c384..0000000000 --- a/.github/workflows/e2e-local-explorer-ui.yml +++ /dev/null @@ -1,69 +0,0 @@ -name: Local Explorer UI E2E - -on: - merge_group: - pull_request: - -permissions: - contents: read - -env: - # We run `playwright install` manually instead - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" - -jobs: - test: - name: Local Explorer UI E2E - concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - timeout-minutes: 30 - runs-on: ubuntu-latest - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - relevant: - - 'packages/local-explorer-ui/**' - - 'packages/miniflare/src/workers/local-explorer/**' - - 'fixtures/worker-with-resources/**' - - 'fixtures/shared/**' - - - name: Install Dependencies - if: steps.changes.outputs.relevant == 'true' - uses: ./.github/actions/install-dependencies - with: - turbo-api: ${{ secrets.TURBO_API }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - - - name: Install Playwright - if: steps.changes.outputs.relevant == 'true' - run: pnpm --filter @cloudflare/local-explorer-ui playwright:install - - - name: Build wrangler - if: steps.changes.outputs.relevant == 'true' - run: pnpm turbo build --filter wrangler - - - name: Run Local Explorer UI E2E tests - if: steps.changes.outputs.relevant == 'true' - run: pnpm test:e2e -F @cloudflare/local-explorer-ui --log-order=stream - timeout-minutes: 30 - env: - CI_OS: Linux - NODE_OPTIONS: "--max_old_space_size=8192" - - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: turbo-runs - path: .turbo/runs diff --git a/.github/workflows/e2e-project-cleanup.yml b/.github/workflows/e2e-project-cleanup.yml deleted file mode 100644 index e5d6306b3d..0000000000 --- a/.github/workflows/e2e-project-cleanup.yml +++ /dev/null @@ -1,33 +0,0 @@ -# This workflow cleans up any leftover projects created by e2e runs. - -name: E2E Project Cleanup - -on: - workflow_dispatch: - schedule: - - cron: "0 */2 * * *" # Run every 2 hours - -permissions: - contents: read - -jobs: - cleanup: - timeout-minutes: 30 - name: "Cleanup Test Projects" - if: ${{ github.repository_owner == 'cloudflare' }} - runs-on: ubuntu-slim - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Cleanup E2E test projects - run: node -r esbuild-register tools/e2e/e2eCleanup.ts - env: - CLOUDFLARE_API_TOKEN: ${{ secrets.TEST_CLOUDFLARE_API_TOKEN }} - CLOUDFLARE_ACCOUNT_ID: ${{ secrets.TEST_CLOUDFLARE_ACCOUNT_ID }} diff --git a/.github/workflows/e2e-vite.yml b/.github/workflows/e2e-vite.yml index 90fcbf7058..9a43005e68 100644 --- a/.github/workflows/e2e-vite.yml +++ b/.github/workflows/e2e-vite.yml @@ -1,73 +1,58 @@ -name: Vite Plugin E2E +name: Vite plugin v1 E2E on: - merge_group: pull_request: + branches: [vite-plugin-v1] + push: + branches: [vite-plugin-v1] + merge_group: + workflow_dispatch: permissions: contents: read pull-requests: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" + jobs: - e2e-vite-plugin-test: - name: ${{ format('Vite Plugin E2E ({0})', matrix.description) }} - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} + test: + name: Vite Plugin E2E (${{ matrix.description }}) + runs-on: ${{ matrix.os }} timeout-minutes: 60 strategy: fail-fast: false matrix: include: + - os: ubuntu-latest + description: Linux - os: macos-latest description: macOS - os: windows-latest description: Windows - - os: ubuntu-latest - description: Linux - runs-on: ${{ matrix.os }} steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: - fetch-depth: 0 persist-credentials: false - - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - - name: Check if remote tests should run - id: check-remote - uses: ./.github/actions/check-remote-tests - - - name: Install Dependencies - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies + - uses: ./.github/actions/install-dependencies with: turbo-api: ${{ secrets.TURBO_API }} turbo-team: ${{ secrets.TURBO_TEAM }} turbo-token: ${{ secrets.TURBO_TOKEN }} turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - - name: Run Vite plugin E2E tests - if: steps.changes.outputs.everything_but_markdown == 'true' - run: pnpm test:e2e -F @cloudflare/vite-plugin --log-order=stream - timeout-minutes: 20 + - uses: ./.github/actions/check-remote-tests + id: remote + - run: pnpm test:e2e env: - NODE_DEBUG: "vite-plugin:test" - # The remote-binding tests need to connect to Cloudflare - CLOUDFLARE_API_TOKEN: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_API_TOKEN || '' }} - CLOUDFLARE_ACCOUNT_ID: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_ACCOUNT_ID || '' }} - NODE_OPTIONS: "--max_old_space_size=8192" - CI_OS: ${{ matrix.os }} - - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + NODE_DEBUG: vite-plugin:test + CLOUDFLARE_API_TOKEN: ${{ steps.remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_API_TOKEN || '' }} + CLOUDFLARE_ACCOUNT_ID: ${{ steps.remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_ACCOUNT_ID || '' }} + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: failure() with: - name: turbo-runs-${{ matrix.os }} + name: e2e-logs-${{ matrix.os }} path: .turbo/runs diff --git a/.github/workflows/e2e-wrangler.yml b/.github/workflows/e2e-wrangler.yml deleted file mode 100644 index 8a1a88a288..0000000000 --- a/.github/workflows/e2e-wrangler.yml +++ /dev/null @@ -1,88 +0,0 @@ -name: Wrangler E2E - -on: - merge_group: - pull_request: - -permissions: - contents: read - pull-requests: read - -jobs: - e2e-wrangler-test: - name: ${{ format('Wrangler E2E ({0}, shard {1}/4)', matrix.description, matrix.shard) }} - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }}-${{ matrix.shard }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - timeout-minutes: 30 - strategy: - fail-fast: false - matrix: - os: [macos-latest, windows-latest, ubuntu-latest] - shard: [1, 2, 3, 4] - include: - - os: macos-latest - description: macOS - - os: windows-latest - description: Windows - - os: ubuntu-latest - description: Linux - - runs-on: ${{ matrix.os }} - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - - name: Check if remote tests should run - id: check-remote - uses: ./.github/actions/check-remote-tests - - - name: Install Dependencies - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies - with: - turbo-api: ${{ secrets.TURBO_API }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - - name: Run Wrangler E2E tests - if: steps.changes.outputs.everything_but_markdown == 'true' - run: pnpm run test:e2e:wrangler - env: - CLOUDFLARE_API_TOKEN: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_API_TOKEN || '' }} - CLOUDFLARE_ACCOUNT_ID: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_ACCOUNT_ID || '' }} - HYPERDRIVE_DATABASE_URL: ${{ secrets.TEST_HYPERDRIVE_DATABASE_URL}} - HYPERDRIVE_MYSQL_DATABASE_URL: ${{ secrets.TEST_HYPERDRIVE_MYSQL_DATABASE_URL}} - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/index.html - CI_OS: ${{ matrix.os }} - E2E_SHARD: ${{ matrix.shard }} - E2E_SHARD_COUNT: "4" - - - name: Run getPlatformProxy() remote-bindings e2e tests - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.shard == 1 - run: pnpm run test:e2e -F @fixture/get-platform-proxy-remote-bindings - env: - TEST_CLOUDFLARE_API_TOKEN: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_API_TOKEN || '' }} - TEST_CLOUDFLARE_ACCOUNT_ID: ${{ steps.check-remote.outputs.run-remote == 'true' && secrets.TEST_CLOUDFLARE_ACCOUNT_ID || '' }} - NODE_OPTIONS: "--max_old_space_size=8192" - CI_OS: ${{ matrix.os }} - - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: turbo-runs-${{ matrix.os }}-shard-${{ matrix.shard }} - path: .turbo/runs diff --git a/.github/workflows/hotfix-release.yml b/.github/workflows/hotfix-release.yml deleted file mode 100644 index c80c6511ad..0000000000 --- a/.github/workflows/hotfix-release.yml +++ /dev/null @@ -1,82 +0,0 @@ -name: Release a hotfix - -on: - workflow_dispatch: - inputs: - pr-number: - description: "Which PR should be released?" - required: true - confirm: - description: "Confirm that the PR is up to date with the last published release, with the specific additional changes that should be released as part of this hotfix and the relevant package patch versions bumped" - type: boolean - required: true - label: - description: "Which dist-tag should this release have?" - type: string - default: hotfix - required: true - -permissions: - contents: read - id-token: write - -jobs: - hotfix-release: - name: Hotfix Release - if: ${{ inputs.confirm == true }} - runs-on: ubuntu-latest - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: false - - - name: Check user for team affiliation - uses: tspascoal/get-user-teams-membership@ba78054988f58bea69b7c6136d563236f8ed2fc0 # v2 - id: teamAffiliation - with: - GITHUB_TOKEN: ${{ secrets.READ_ONLY_ORG_GITHUB_TOKEN }} - username: ${{ github.actor }} - team: wrangler - - - name: Stop workflow if user is not a wrangler team member - if: ${{ steps.teamAffiliation.outputs.isTeamMember == false }} - run: | - echo "You must be on the "wrangler" team to trigger this job." - exit 1 - - - name: "Checkout PR" - run: | - if ! [[ "$PR_NUMBER" =~ ^[0-9]+$ ]]; then - echo "::error::PR number must be numeric" - exit 1 - fi - gh pr checkout "$PR_NUMBER" - env: - GH_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} - PR_NUMBER: ${{ inputs.pr-number }} - - - name: Install Dependencies - # Defense in depth: do not pass Turbo remote cache credentials and - # disable the pnpm store cache so release builds always resolve - # packages from the registry and rebuild every task from source, - # rather than restoring from a (potentially poisoned) cache. - uses: ./.github/actions/install-dependencies - with: - disable-cache: "true" - - - name: Build all packages - run: pnpm run build - env: - CI_OS: ${{ runner.os }} - - - name: Publish packages - run: | - if ! [[ "$NPM_TAG" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then - echo "::error::npm dist-tag contains unsupported characters" - exit 1 - fi - pnpm publish -r --tag "$NPM_TAG" --filter wrangler --filter miniflare --filter create-cloudflare - env: - NPM_TAG: ${{ inputs.label }} diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml deleted file mode 100644 index a0e24aa2b4..0000000000 --- a/.github/workflows/issues.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: Add issues to DevProd project - -on: - issues: - types: [opened, transferred] - -permissions: - # issues:write permission needed so that the workflow can manage issues - issues: write - -jobs: - add-to-project: - name: Add issue to project - runs-on: ubuntu-slim - steps: - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 - with: - project-url: https://github.com/orgs/cloudflare/projects/1 - github-token: ${{ secrets.GH_ACCESS_TOKEN }} - labeled: bug, enhancement - label-operator: OR - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 - with: - project-url: https://github.com/orgs/cloudflare/projects/2 - github-token: ${{ secrets.GH_ACCESS_TOKEN }} - labeled: product:pages - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 - with: - project-url: https://github.com/orgs/cloudflare/projects/6 - github-token: ${{ secrets.GH_ACCESS_TOKEN }} - labeled: product:d1 - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 - with: - project-url: https://github.com/orgs/cloudflare/projects/12 - github-token: ${{ secrets.GH_ACCESS_TOKEN }} - labeled: package:c3 - - uses: actions/add-to-project@244f685bbc3b7adfa8466e08b698b5577571133e # v1.0.2 - with: - project-url: https://github.com/orgs/cloudflare/projects/8 - github-token: ${{ secrets.GH_ACCESS_TOKEN }} - labeled: product:queues diff --git a/.github/workflows/miniflare-dependabot-versioning-prs.yml b/.github/workflows/miniflare-dependabot-versioning-prs.yml deleted file mode 100644 index b3ce9ec166..0000000000 --- a/.github/workflows/miniflare-dependabot-versioning-prs.yml +++ /dev/null @@ -1,56 +0,0 @@ -name: "Miniflare - Generate changesets for dependabot PRs" - -on: - pull_request_target: # zizmor: ignore[dangerous-triggers] dependabot-only job requires write access to push generated changesets; checkout v6 persists credentials under RUNNER_TEMP - paths: - - "packages/miniflare/package.json" - - "pnpm-workspace.yaml" - -permissions: - # content:write permission needed to update add changesets to dependabot PRs, - # and to refresh the default compatibility date on workerd bumps - # (see tools/dependabot/generate-dependabot-pr-changesets.ts) - contents: write - -jobs: - generate-changeset: - runs-on: ubuntu-slim - if: | - github.actor == 'dependabot[bot]' && - github.event.pull_request.user.login == 'dependabot[bot]' && - github.event.pull_request.head.repo.full_name == github.repository - steps: - - name: Checkout - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 2 - persist-credentials: true - ref: ${{ github.head_ref }} - token: ${{ secrets.GH_ACCESS_TOKEN }} - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Configure Git - run: | - git config --global user.email wrangler@cloudflare.com - git config --global user.name 'Wrangler automated PR updater' - - - name: Generate Miniflare changesets - # Also refreshes DEFAULT_COMPAT_DATE when this PR bumps workerd, since - # the default compatibility date is derived from the pinned workerd - # release and `pnpm check:compat-date` enforces that they match. - # - # The paremeters to the script are: - # - PR: The number of the current Dependabot PR - # - Packages: Coma-separated names of the workers-sdk packages whose dependencies are being updated - # - PackageJSON: The path to the package JSON being updated by Dependabot - # - Changeset prefix: The prefix to go on the front of the filename of the generated changeset - run: >- - node -r esbuild-register tools/dependabot/generate-dependabot-pr-changesets.ts - "$PR_NUMBER" - miniflare,wrangler - packages/miniflare/package.json - dependabot-update - env: - PR_NUMBER: ${{ github.event.number }} diff --git a/.github/workflows/opencode-issue-solver.yml b/.github/workflows/opencode-issue-solver.yml deleted file mode 100644 index 8bae74860a..0000000000 --- a/.github/workflows/opencode-issue-solver.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: OpenCode Issue Solver - -on: - workflow_dispatch: - inputs: - issue-number: - description: "Issue number to attempt to fix" - required: true - type: number - -jobs: - assess-issue: - runs-on: ubuntu-latest - permissions: {} - - steps: - - name: Exit - run: | - exit 1 diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 1a02cc1ea0..0621e8e07f 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -1,53 +1,32 @@ -name: Prerelease +name: Vite plugin v1 preview package on: pull_request: + branches: [vite-plugin-v1] push: - branches: - - main - - d1 - - workflows - - next - - v3-maintenance + branches: [vite-plugin-v1] + merge_group: + workflow_dispatch: permissions: contents: read +env: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" + jobs: build: - if: ${{ github.repository_owner == 'cloudflare' }} + if: github.repository_owner == 'cloudflare' runs-on: ubuntu-latest - concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} timeout-minutes: 30 steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: - fetch-depth: 1 persist-credentials: false - - - name: Install Dependencies - # Defense in depth: do not pass Turbo remote cache credentials and - # disable the pnpm store cache so release builds always resolve - # packages from the registry and rebuild every task from source, - # rather than restoring from a (potentially poisoned) cache. - uses: ./.github/actions/install-dependencies + - uses: ./.github/actions/install-dependencies with: disable-cache: "true" - - - name: Build - run: pnpm build --filter="./packages/*" + - run: pnpm build env: - NODE_ENV: "production" - CI_OS: ${{ runner.os }} - # this is the "test/staging" key for sparrow analytics - SPARROW_SOURCE_KEY: "5adf183f94b3436ba78d67f506965998" - ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} - SENTRY_DSN: "https://9edbb8417b284aa2bbead9b4c318918b@sentry10.cfdata.org/583" - ALGOLIA_PUBLIC_KEY: ${{ secrets.ALGOLIA_PUBLIC_KEY }} - WRANGLER_PRERELEASE_LABEL: ${{ github.head_ref || github.ref_name }} - - - name: Upload packages - run: node -r esbuild-register .github/prereleases/upload.mjs + SOURCEMAPS: "false" + - run: node .github/prereleases/upload.mjs diff --git a/.github/workflows/rerun-remote-tests.yml b/.github/workflows/rerun-remote-tests.yml deleted file mode 100644 index 030290e615..0000000000 --- a/.github/workflows/rerun-remote-tests.yml +++ /dev/null @@ -1,87 +0,0 @@ -name: "Rerun Remote Tests" - -# Trigger: the "run-remote-tests" or "run-c3-frameworks-tests" label is added -# to or removed from a pull request. -# -# Goal: re-run the Wrangler and Vite E2E workflows when the remote-tests label -# changes so they pick up the label change and either pass or withhold the -# Cloudflare API token to the test steps. Re-run the C3 E2E workflow when the -# C3-frameworks label changes. This avoids adding "labeled" as a trigger type -# to every E2E workflow (which would cause wasteful re-runs on unrelated label -# changes). -# -# Using pull_request_target (not pull_request) so the workflow has access to a -# privileged GITHUB_TOKEN even for fork PRs. This is safe because the workflow -# runs code from the default branch — fork authors cannot modify it — and only -# calls the Actions API (no checkout of untrusted code). -on: - pull_request_target: # zizmor: ignore[dangerous-triggers] label-driven rerun workflow needs actions:write and does not check out or execute PR code - types: [labeled, unlabeled] - -permissions: {} - -jobs: - rerun-e2e: - name: "Rerun E2E Tests" - if: github.event.label.name == 'ci:run-remote-tests' || github.event.label.name == 'run-c3-frameworks-tests' - runs-on: ubuntu-latest - permissions: - actions: write - steps: - - name: "Re-run E2E workflows" - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} - LABEL_NAME: ${{ github.event.label.name }} - REPO: ${{ github.repository }} - run: | - # Determine which workflows to re-run based on the label. - if [ "$LABEL_NAME" = "ci:run-remote-tests" ]; then - WORKFLOWS="e2e-wrangler.yml e2e-vite.yml" - else - WORKFLOWS="c3-e2e.yml" - fi - - for workflow in ${WORKFLOWS}; do - # Find the most recent run of this workflow at the PR head SHA. - run_info=$(gh api "repos/${REPO}/actions/workflows/${workflow}/runs?head_sha=${HEAD_SHA}&per_page=1" \ - --jq '.workflow_runs[0] | "\(.id) \(.status)"' || true) - - run_id=$(echo "$run_info" | awk '{print $1}') - status=$(echo "$run_info" | awk '{print $2}') - - if [ -z "$run_id" ] || [ "$run_id" = "null" ]; then - echo "::warning::No run found for ${workflow} at SHA ${HEAD_SHA}" - continue - fi - - # Runs that haven't started yet will see the newly-added label - # when they begin — no need to cancel and re-run them. - if [ "$status" != "completed" ] && [ "$status" != "in_progress" ]; then - echo "${workflow} run ${run_id} is ${status} — not yet started, skipping." - continue - fi - - # If the run is actively executing, the label check has already - # evaluated (likely to the old value). Cancel it first — the - # rerun endpoint only works on completed runs. - if [ "$status" = "in_progress" ]; then - echo "Cancelling in-progress ${workflow} run ${run_id}..." - gh api "repos/${REPO}/actions/runs/${run_id}/cancel" --method POST || true - - # Cancellation is async; poll until the run reaches "completed". - for i in $(seq 1 30); do - current=$(gh api "repos/${REPO}/actions/runs/${run_id}" --jq '.status') - if [ "$current" = "completed" ]; then - echo "Run ${run_id} is now completed (cancelled)." - break - fi - echo " Waiting for cancellation to finish (${i}/30, status: ${current})..." - sleep 2 - done - fi - - gh api "repos/${REPO}/actions/runs/${run_id}/rerun" --method POST \ - && echo "Re-triggered ${workflow} (run ${run_id})" \ - || echo "::warning::Failed to re-run ${workflow} (run ${run_id})" - done diff --git a/.github/workflows/run-ci-for-external-forks.yml b/.github/workflows/run-ci-for-external-forks.yml deleted file mode 100644 index 6ee021c164..0000000000 --- a/.github/workflows/run-ci-for-external-forks.yml +++ /dev/null @@ -1,100 +0,0 @@ -name: Run CI on behalf of External Forks - -on: - workflow_dispatch: - inputs: - pr-number: - description: "The PR number to run CI on behalf of" - required: true - commit-sha: - description: "The specific commit SHA from the PR branch to run CI on" - required: true - reviewed: - description: "Confirm that the PR has been reviewed for use/leakage of secrets" - type: boolean - required: true - -permissions: - contents: read # no write permissions are needed since the workflow uses GH_ACCESS_TOKEN instead of GITHUB_TOKEN - pull-requests: write # Required for creating or updating the draft PR on behalf of the user - -jobs: - create-draft-pr: - name: Create or Update Draft PR - if: ${{ inputs.reviewed == true }} - runs-on: ubuntu-slim - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 0 - persist-credentials: true - token: ${{ secrets.GH_ACCESS_TOKEN }} - - - name: Check user for team affiliation - uses: tspascoal/get-user-teams-membership@ba78054988f58bea69b7c6136d563236f8ed2fc0 - id: teamAffiliation - with: - GITHUB_TOKEN: ${{ secrets.READ_ONLY_ORG_GITHUB_TOKEN }} - username: ${{ github.actor }} - team: wrangler - - - name: Stop workflow if user is not a team member - if: ${{ steps.teamAffiliation.outputs.isTeamMember != 'true' }} - run: | - echo "You must be on the \"wrangler\" team to trigger this job." - exit 1 - - - name: "Checkout PR" - run: | - gh pr checkout "$PR_NUM" --branch "run-ci-on-behalf-of-$PR_NUM" - git reset --hard "$COMMIT_SHA" - env: - # We need a PAT to checkout the fork - GH_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} - PR_NUM: ${{ inputs.pr-number }} - COMMIT_SHA: ${{ inputs.commit-sha }} - - - name: Push Branch - run: | - git config user.email "github-actions[bot]@users.noreply.github.com" - git config user.name "github-actions[bot]" - git push origin HEAD --force - - - name: "Create or Update Draft PR" - run: | - existing_pr=$(gh pr list \ - --head "run-ci-on-behalf-of-$PR_NUM" \ - --state open \ - --json number \ - --jq 'first(.[].number) // ""') - - if [ -n "$existing_pr" ]; then - gh pr edit "$existing_pr" \ - --add-label "ci:e2e" \ - --add-label "ci:run-remote-tests" \ - --title "$TITLE" \ - --body "$BODY" - else - gh pr create \ - --head "run-ci-on-behalf-of-$PR_NUM" \ - --draft \ - --label "ci:e2e" \ - --label "ci:run-remote-tests" \ - --title "$TITLE" \ - --body "$BODY" - fi - env: - GH_TOKEN: ${{ github.token }} - PR_NUM: ${{ inputs.pr-number }} - TITLE: "Run CI on behalf of #${{ inputs.pr-number }} @${{ inputs.commit-sha }}" - BODY: "This PR runs CI on behalf of #${{ inputs.pr-number }} at commit ${{ inputs.commit-sha }}. It can be closed after the CI run is complete." - - - name: "Trigger CI" - run: | - # Push an empty commit to trigger CI workflows - # This ensures CI runs because the PR already exists when this push happens - git commit --allow-empty -m "Trigger CI for #$PR_NUM" - git push origin HEAD - env: - PR_NUM: ${{ inputs.pr-number }} diff --git a/.github/workflows/semgrep.yml b/.github/workflows/semgrep.yml deleted file mode 100644 index 2e5e914b7c..0000000000 --- a/.github/workflows/semgrep.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Semgrep OSS scan -on: - pull_request: {} - push: - branches: [main] - workflow_dispatch: {} - schedule: - - cron: "0 0 15 * *" -concurrency: - group: semgrep-${{ github.event_name }}-${{ github.head_ref || github.run_id }} - cancel-in-progress: true -permissions: - contents: read -jobs: - semgrep: - name: semgrep-oss - runs-on: ubuntu-slim - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - id: cache-semgrep - uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5 - with: - path: ~/.local - key: semgrep-1.160.0-${{ runner.os }} - - if: steps.cache-semgrep.outputs.cache-hit != 'true' - run: pip install --user semgrep==1.160.0 - - run: echo "$HOME/.local/bin" >> "$GITHUB_PATH" - - run: semgrep scan --config=auto || true diff --git a/.github/workflows/test-and-check-other-node.yml b/.github/workflows/test-and-check-other-node.yml deleted file mode 100644 index 9f6eef9194..0000000000 --- a/.github/workflows/test-and-check-other-node.yml +++ /dev/null @@ -1,125 +0,0 @@ -name: CI (Other Node Versions) -description: Run primary tests on other supported Node.js versions - -on: - merge_group: - pull_request: - types: [synchronize, opened, reopened, labeled, unlabeled] - -permissions: - contents: read - -jobs: - test-other-node-versions: - timeout-minutes: 45 - runs-on: ubuntu-latest - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.node_version }}-test-other-node-versions - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - name: ${{ format('Tests ({0})', matrix.description) }} - strategy: - fail-fast: false - matrix: - # expected_to_fail: if true, tests may fail on this Node version. - # These versions are skipped on normal PRs but run on Version Packages PRs - # (changeset-release/main) or when the 'ci:test-all-node-versions' label is added. - # - # Node 24 is pinned to 24.18.0 (rather than floating `24`): Node 24.17.0 - # regressed node-fetch@2 keep-alive responses with ERR_STREAM_PREMATURE_CLOSE - # (nodejs/node#63989, fixed in 24.18.0). `description` stays "Node 24" to - # keep the job/check name stable. - include: - - { - node_version: 24.18.0, - description: "Node 24", - expected_to_fail: true, - } - - { node_version: 25, description: "Node 25", expected_to_fail: true } - - steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Filter changed paths - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - - name: Check if should run tests - id: should_run - env: - CHANGES_EVERYTHING_BUT_MARKDOWN: ${{ steps.changes.outputs.everything_but_markdown }} - EXPECTED_TO_FAIL: ${{ matrix.expected_to_fail }} - HAS_TEST_ALL_NODE_VERSIONS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'ci:test-all-node-versions') }} - HEAD_REF: ${{ github.event.pull_request.head.ref }} - run: | - if [[ "$CHANGES_EVERYTHING_BUT_MARKDOWN" == "true" ]] && \ - [[ "$EXPECTED_TO_FAIL" != "true" || \ - "$HEAD_REF" == "changeset-release/main" || \ - "$HAS_TEST_ALL_NODE_VERSIONS_LABEL" == "true" ]]; then - echo "result=true" >> $GITHUB_OUTPUT - else - echo "result=false" >> $GITHUB_OUTPUT - fi - - - name: Install Dependencies - if: steps.should_run.outputs.result == 'true' - uses: ./.github/actions/install-dependencies - with: - node-version: ${{ matrix.node_version }} - turbo-api: ${{ secrets.TURBO_API }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - # The miniflare browser-rendering tests download Chrome (~150 MB) via - # @puppeteer/browsers at runtime. Caching the binary avoids repeat - # downloads and reduces the chance of tests hanging while waiting for - # the download to finish within their timeout window. - # - # Restore only, deliberately. This shares its key with `test-and-check.yml`, - # which saves the cache only once a `.miniflare-install-complete` marker - # proves Chrome actually launched from the install. Cache keys are - # write-once, so saving here too would let this workflow publish an - # unvalidated — possibly half-extracted — Chrome that the validated save - # could then never replace. - - name: Restore Chrome browser cache (Browser Run) - if: steps.should_run.outputs.result == 'true' - uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 - with: - key: chrome-${{ runner.os }}-${{ hashFiles('packages/miniflare/src/plugins/browser-rendering/browser-version.ts') }} - path: | - ~/.cache/.wrangler/chrome - - - name: Run tests (packages) - # We are running the package tests first be able to get early feedback on changes. - # There is no point in running the fixtures if a package is broken. - if: steps.should_run.outputs.result == 'true' - run: pnpm run test:ci --log-order=stream --concurrency=1 --filter="./packages/*" - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/packages/index.html - CI_OS: ${{ matrix.description }} - - - name: Run e2e tests (unenv-preset) - if: steps.should_run.outputs.result == 'true' - run: pnpm test:e2e --filter wrangler -- unenv-preset - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - CI_OS: ${{ matrix.description }} - - - name: Run tests (vite-plugin) - if: steps.should_run.outputs.result == 'true' - run: pnpm test:ci --filter @cloudflare/vite-plugin - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - CI_OS: ${{ matrix.description }} diff --git a/.github/workflows/test-and-check.yml b/.github/workflows/test-and-check.yml index d14bddda6c..e2e5fbdec0 100644 --- a/.github/workflows/test-and-check.yml +++ b/.github/workflows/test-and-check.yml @@ -1,366 +1,71 @@ -name: CI +name: Vite plugin v1 CI on: - merge_group: pull_request: + branches: [vite-plugin-v1] + push: + branches: [vite-plugin-v1] + merge_group: + workflow_dispatch: permissions: contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ !startsWith(github.head_ref, 'changeset-release/') }} + env: - # We run `playwright install` manually instead PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" - # Use the PR label for deliberate benchmarks, including nested Turbo builds. - # Dependency and browser downloads retain their separate caches. - TURBO_CACHE: ${{ contains(github.event.pull_request.labels.*.name, 'ci:no-turbo-cache') && 'local:,remote:' || 'local:rw,remote:rw' }} - TURBO_RUN_SUMMARY: "true" jobs: - add-to-project: - if: github.head_ref != 'changeset-release/main' - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-add-pr - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - timeout-minutes: 30 - name: Add PR to project - runs-on: ubuntu-latest - steps: - - run: curl -X POST https://devprod-status-bot.devprod.workers.dev/pr-project/workers-sdk/${{ github.event.number }} - check: - timeout-minutes: 30 - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-checks - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - - name: "Checks" + name: Checks runs-on: ubuntu-latest + timeout-minutes: 30 steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: - fetch-depth: 0 persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies + - uses: ./.github/actions/install-dependencies with: turbo-api: ${{ secrets.TURBO_API }} turbo-team: ${{ secrets.TURBO_TEAM }} turbo-token: ${{ secrets.TURBO_TOKEN }} turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - - name: Check the changesets - run: node -r esbuild-register tools/deployments/validate-changesets.ts - - - name: Check for errors - run: pnpm run check --summarize + - run: pnpm check env: - CI_OS: ${{ runner.os }} - NODE_OPTIONS: "--max_old_space_size=8192" - - - name: Filter changed paths - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - miniflare_openapi: - - 'packages/miniflare/src/workers/local-explorer/openapi.local.json' - - 'packages/miniflare/src/workers/local-explorer/generated/**' - - 'packages/miniflare/scripts/openapi-filter-config.ts' - - 'packages/miniflare/scripts/filter-openapi.ts' - - 'packages/miniflare/scripts/check-generate-api.ts' - - 'packages/miniflare/openapi-ts.config.ts' - - - name: Check generated OpenAPI types are up to date - if: steps.changes.outputs.miniflare_openapi == 'true' - run: pnpm -F miniflare check:generate-api - - # Check for old Node.js version warnings and errors - - name: Use Node.js v20 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 - with: - node-version: 20 - - - name: Check for error message on Node.js < v22 - run: node packages/wrangler/src/__tests__/test-old-node-version.js error - - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: turbo-runs-checks - path: .turbo/runs - - test-partitions: - timeout-minutes: 30 - concurrency: - group: ${{ github.workflow }}-${{ github.ref }}-${{ matrix.os }}-${{ matrix.suite }}-${{ matrix.shard }}-test - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} - - name: ${{ format('Test partition ({0}, {1}, {2})', matrix.description, matrix.suite, matrix.shard) }} + NODE_OPTIONS: --max_old_space_size=8192 + test: + name: Tests (${{ matrix.description }}, ${{ matrix.suite }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 strategy: fail-fast: false matrix: - os: - - macos-latest - - ubuntu-latest - - windows-latest - suite: - - packages-and-tools - - integrations - - runtime - - fixtures - - dev-registry - shard: [1, 2] - exclude: - # The other packages run once per OS; tools and release source maps - # are tested on Linux only. - # dev-registry starts independently to avoid a long tail of fixtures. - - suite: packages-and-tools - shard: 2 - - suite: integrations - shard: 2 - - suite: dev-registry - shard: 2 + os: [ubuntu-latest, macos-latest, windows-latest] + suite: [packages-and-tools, fixtures] include: - - os: macos-latest - description: macOS - runtime-shards: 2 - os: ubuntu-latest description: Linux - runtime-shards: 2 + - os: macos-latest + description: macOS - os: windows-latest description: Windows - runtime-shards: 3 - # The Windows runtime partitions take longer than the other OSes. - - os: windows-latest - description: Windows - suite: runtime - shard: 3 - runtime-shards: 3 - - runs-on: ${{ matrix.os }} steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: - fetch-depth: 0 persist-credentials: false - - - name: Filter changed paths - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - - name: Install Dependencies - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies + - uses: ./.github/actions/install-dependencies with: turbo-api: ${{ secrets.TURBO_API }} turbo-team: ${{ secrets.TURBO_TEAM }} turbo-token: ${{ secrets.TURBO_TOKEN }} turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - # Browser Run tests in `packages/miniflare/test/plugins/browser/index.spec.ts` - # and the `fixtures/browser-run` fixture use `@puppeteer/browsers` to - # download Chrome into the global Wrangler cache. Caching that binary - # across CI runs avoids ~150 MB of repeat downloads per run. - # - # Note this is `cache/restore` paired with an explicit `cache/save` - # below, not plain `cache`: `actions/cache` saves from a post step - # declaring `post-if: success()`, so a job that fails for *any* reason - # never saves. Combined with this workflow only running on - # `pull_request`/`merge_group` — so nothing is ever written to - # `refs/heads/main`, the one ref every PR can restore from — that left - # Windows re-downloading Chrome on every single run. - # - # The Browser Run fixture is skipped on Ubuntu (AppArmor), but the - # miniflare browser spec runs everywhere, so the cache is needed on all - # three OSes for `runtime` and on Windows + macOS for - # `fixtures`. - - name: Restore Chrome browser cache (Browser Run) - id: chrome-cache - if: steps.changes.outputs.everything_but_markdown == 'true' && (matrix.suite == 'runtime' || (matrix.suite == 'fixtures' && matrix.os != 'ubuntu-latest')) - uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 - with: - # The Chrome version lives in - # `packages/miniflare/src/plugins/browser-rendering/browser-version.ts`. - # Bumping that constant invalidates this cache automatically via - # `hashFiles()` — a cache miss only triggers a fresh download, no - # functional impact. - key: chrome-${{ runner.os }}-${{ hashFiles('packages/miniflare/src/plugins/browser-rendering/browser-version.ts') }} - path: | - ~/.cache/.wrangler/chrome - ~/Library/Caches/.wrangler/chrome - ~/AppData/Local/xdg.cache/.wrangler/chrome - - - name: Run tests (tools only) - # tools _only_ needs to be tested on Linux because they're only intended to run in CI - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'packages-and-tools' && matrix.os == 'ubuntu-latest' - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/tools.log run test:ci --log-order=stream --filter="@cloudflare/tools" - shell: bash - env: - NODE_OPTIONS: "--max_old_space_size=8192" - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/tools/index.html - CI_OS: ${{ matrix.description }} - - - name: Run tests (packages) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'packages-and-tools' - # Wrangler and Miniflare run in the runtime partitions below. Keep the - # broad filter so new packages automatically retain CI coverage. - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/packages.log run test:ci --summarize --log-order=stream --concurrency=3 --filter="./packages/*" --filter="!wrangler" --filter="!miniflare" --filter="!@cloudflare/vite-plugin" --filter="!@cloudflare/vitest-plugin" - shell: bash - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/packages/index.html - CI_OS: ${{ matrix.description }} - - - name: Run tests (Vite and Vitest integrations) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'integrations' - # Start the integration packages without queuing behind the other packages. - # Preserve the existing Windows exclusion for flaky Vitest plugin watch - # tests; the comprehensive vitest-plugin-examples fixture still runs. - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/integrations.log run test:ci --summarize --log-order=stream --concurrency=2 --filter="@cloudflare/vite-plugin" ${{ matrix.os != 'windows-latest' && '--filter="@cloudflare/vitest-plugin"' || '' }} - shell: bash - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/packages/index.html - CI_OS: ${{ matrix.description }} - - - name: Run tests (Wrangler and Miniflare shard) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'runtime' - # Use Vitest's complete file partition: three shards on Windows, two elsewhere. - # Keep Miniflare's single worker and Wrangler's per-file isolation. - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/runtime.log run test:ci --summarize --log-order=stream --concurrency=2 --filter=wrangler --filter=miniflare - shell: bash - env: - CI_TEST_SHARD: ${{ format('{0}/{1}', matrix.shard, matrix.runtime-shards) }} - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/packages/index.html - CI_OS: ${{ matrix.description }} - - - name: Test release source maps (Miniflare and Vite plugin) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'packages-and-tools' && matrix.os == 'ubuntu-latest' - run: | - rm -rf packages/miniflare/dist packages/vite-plugin-cloudflare/dist - pnpm run build --filter=miniflare --filter=@cloudflare/vite-plugin - pnpm --filter miniflare exec vitest run test/sourcemap.spec.ts test/plugins/core/errors/index.spec.ts - pnpm --filter @cloudflare/vite-plugin exec vitest run src/__tests__/package-sourcemaps.spec.ts - env: - SOURCEMAPS: "false" - CI_OS: ${{ matrix.description }} - - - name: Run tests (fixtures) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'fixtures' - # Browser Run fixture is disabled on Ubuntu because of https://pptr.dev/troubleshooting#issues-with-apparmor-on-ubuntu - # Partition whole packages so their custom test scripts still run in full. - # Each runner keeps concurrency=2 to limit workerd resource contention. - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/fixtures.log run test:ci:fixtures --group=remaining --shard="$TEST_SHARD/2" - shell: bash - env: - TEST_SHARD: ${{ matrix.shard }} - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/index.html - CI_OS: ${{ matrix.description }} - - - name: Run tests (dev-registry) - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.suite == 'dev-registry' - # Start this long fixture without queuing behind the remaining packages. - run: | - mkdir -p .turbo/ci-logs - pnpm run test:ci:logged .turbo/ci-logs/dev-registry.log run test:ci:fixtures --group=dev-registry --shard=1/1 - shell: bash - env: - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/index.html - CI_OS: ${{ matrix.description }} - - # Only cache an install that Miniflare marked as complete. Without this - # check a job interrupted mid-download would publish a half-extracted - # Chrome under the cache key, which — because `@puppeteer/browsers` - # considers an install present as soon as the executable exists — every - # later run would restore and fail to launch. - - name: Check for a complete Chrome install - id: chrome-complete - if: always() && steps.chrome-cache.outcome == 'success' && steps.chrome-cache.outputs.cache-hit != 'true' - shell: bash - run: | - for dir in "$HOME/.cache/.wrangler/chrome" \ - "$HOME/Library/Caches/.wrangler/chrome" \ - "$HOME/AppData/Local/xdg.cache/.wrangler/chrome"; do - if [ -d "$dir" ] && [ -n "$(find "$dir" -name .miniflare-install-complete -print -quit)" ]; then - echo "Found a complete Chrome install under $dir" - echo "complete=true" >> "$GITHUB_OUTPUT" - exit 0 - fi - done - echo "No complete Chrome install found; skipping cache save" - echo "complete=false" >> "$GITHUB_OUTPUT" - - # Saved here rather than in a post step so that an unrelated test failure - # elsewhere in the job doesn't stop Chrome from being cached. - - name: Save Chrome browser cache (Browser Run) - if: always() && steps.chrome-complete.outputs.complete == 'true' - uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 - with: - key: chrome-${{ runner.os }}-${{ hashFiles('packages/miniflare/src/plugins/browser-rendering/browser-version.ts') }} - path: | - ~/.cache/.wrangler/chrome - ~/Library/Caches/.wrangler/chrome - ~/AppData/Local/xdg.cache/.wrangler/chrome - - - name: Report test retries - if: always() && steps.changes.outputs.everything_but_markdown == 'true' - run: node -r esbuild-register tools/test/report-test-retries.ts - - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: turbo-runs-${{ matrix.os }}-${{ matrix.suite }}-${{ matrix.shard }} - path: | - .turbo/runs - .turbo/test-retries.json - .turbo/ci-logs - - # These names are required by branch protection. Every partition must succeed - # before any required test check passes, including when a partition is cancelled. - test: - needs: test-partitions - if: always() - timeout-minutes: 5 - name: ${{ format('Tests ({0}, {1})', matrix.description, matrix.suite) }} - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - description: [macOS, Linux, Windows] - suite: [packages-and-tools, fixtures] - steps: - - name: Require all test partitions to pass - env: - TEST_RESULT: ${{ needs.test-partitions.result }} - run: | - if [ "$TEST_RESULT" != "success" ]; then - echo "Test partitions did not all pass: $TEST_RESULT" - exit 1 - fi + - run: pnpm build + - run: pnpm test:ci + if: matrix.suite == 'packages-and-tools' + - run: pnpm --filter @fixture/create-test-harness-example playwright:install + if: matrix.suite == 'fixtures' + - run: pnpm test:fixtures + if: matrix.suite == 'fixtures' diff --git a/.github/workflows/validate-pr-description.yml b/.github/workflows/validate-pr-description.yml index 4b16334470..3e9ad4a752 100644 --- a/.github/workflows/validate-pr-description.yml +++ b/.github/workflows/validate-pr-description.yml @@ -3,6 +3,7 @@ name: Validate PR Description on: merge_group: pull_request: + branches: [vite-plugin-v1] types: [ opened, @@ -21,10 +22,10 @@ permissions: jobs: check: # Don't check the Version Packages PR or merge queue jobs - if: github.event_name != 'merge_group' && github.head_ref != 'changeset-release/main' + if: github.event_name != 'merge_group' && !startsWith(github.head_ref, 'changeset-release/') concurrency: group: ${{ github.workflow }}-${{ github.ref }}-add-pr - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} + cancel-in-progress: ${{ !startsWith(github.head_ref, 'changeset-release/') }} timeout-minutes: 30 name: Check runs-on: ubuntu-slim @@ -45,11 +46,6 @@ jobs: - name: Install Dependencies if: steps.changes.outputs.everything_but_markdown == 'true' uses: ./.github/actions/install-dependencies - with: - turbo-api: ${{ secrets.TURBO_API }} - turbo-team: ${{ secrets.TURBO_TEAM }} - turbo-token: ${{ secrets.TURBO_TOKEN }} - turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - name: List changed files if: steps.changes.outputs.everything_but_markdown == 'true' diff --git a/.github/workflows/vite-plugin-playgrounds.yml b/.github/workflows/vite-plugin-playgrounds.yml index 1f68b437d6..e56f90d1bf 100644 --- a/.github/workflows/vite-plugin-playgrounds.yml +++ b/.github/workflows/vite-plugin-playgrounds.yml @@ -1,89 +1,56 @@ -name: Vite plugin playgrounds +name: Vite plugin v1 playgrounds on: - merge_group: pull_request: + branches: [vite-plugin-v1] + push: + branches: [vite-plugin-v1] + merge_group: + workflow_dispatch: permissions: contents: read concurrency: - group: ${{ github.workflow }}-${{ github.event.number || github.sha }} - cancel-in-progress: ${{ github.head_ref != 'changeset-release/main' }} + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true env: - # We run `playwright install` manually instead PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" jobs: test: - # Windows jobs that miss the turbo cache already take 15-25 minutes, and the - # timeouts/retries in `playground/vitest.config.e2e.ts` give slow tests more - # room to finish, so leave headroom before the hard job kill. - timeout-minutes: 45 - name: ${{ format('Vite Plugin Playground ({0}, {1})', matrix.os, matrix.vite) }} + name: Vite Plugin Playground (${{ matrix.os }}, vite-${{ matrix.vite }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 60 strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] - vite: ["vite-8"] + vite: [8] include: - os: ubuntu-latest - vite: "vite-6" + vite: 6 - os: ubuntu-latest - vite: "vite-7" - runs-on: ${{ matrix.os }} - env: - # Miniflare build outputs contain platform-specific paths. Include the OS - # in both the build cache key and the exported plugin build hash. - CI_OS: ${{ matrix.os }} + vite: 7 steps: - - name: Checkout Repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: persist-credentials: false - - name: Filter changed paths - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 - id: changes - with: - filters: | - everything_but_markdown: - - '!**/*.md' - - name: Install Dependencies - if: steps.changes.outputs.everything_but_markdown == 'true' - uses: ./.github/actions/install-dependencies + - uses: ./.github/actions/install-dependencies with: turbo-api: ${{ secrets.TURBO_API }} turbo-team: ${{ secrets.TURBO_TEAM }} turbo-token: ${{ secrets.TURBO_TOKEN }} turbo-signature: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} - - name: Install playwright - if: steps.changes.outputs.everything_but_markdown == 'true' - run: | - pnpm --filter @vite-plugin-cloudflare/playground playwright:install - - name: Build plugin with initial Vite version - if: steps.changes.outputs.everything_but_markdown == 'true' - run: | - pnpm dotenv -- pnpm turbo build --filter @cloudflare/vite-plugin - env: - NODE_OPTIONS: "--max_old_space_size=8192" - # The test steps below pass `--only`, which does not merely skip *running* - # dependencies — it strips them from the cache key as well. Left alone, - # the playground tests are cached on a key that ignores - # `@cloudflare/vite-plugin`, `wrangler`, `miniflare` and `workerd`, so - # they replay from cache and never actually run on internal PRs (#14967). - # - # The turbo hash for `@cloudflare/vite-plugin#build` covers that whole - # dependency graph, so exporting it here and declaring it as a task `env` - # in `playground/turbo.json` restores the invalidation `--only` removed. - # - # This must run before the Vite downgrade steps so that the hash - # describes the plugin that was actually built and tested. + - run: pnpm build + # --only avoids rebuilding the plugin after selecting Vite 6 or 7, but + # also removes its dependency hashes from the test cache key. Capture the + # actual build hash before the downgrade to restore that invalidation. - name: Export plugin build hash for the playground cache key - if: steps.changes.outputs.everything_but_markdown == 'true' shell: bash run: | - pnpm dotenv -- pnpm turbo build --filter @cloudflare/vite-plugin --dry=json | + pnpm dotenv -- turbo build --filter @cloudflare/vite-plugin --dry=json | node --input-type=module -e ' import { readFileSync } from "node:fs"; const { tasks } = JSON.parse(readFileSync(0, "utf8")); @@ -93,47 +60,20 @@ jobs: } console.log(`VITE_PLUGIN_BUILD_HASH=${task.hash}`); ' >> "$GITHUB_ENV" - # The exact Vite 8 workspace patch is intentionally unused after these - # compatibility-job downgrades. - - name: Downgrade to Vite 6 - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.vite == 'vite-6' - run: | - pnpm --config.allow-unused-patches=true update -r --no-save vite@^6.1.0 - - name: Downgrade to Vite 7 - if: steps.changes.outputs.everything_but_markdown == 'true' && matrix.vite == 'vite-7' - run: | - pnpm --config.allow-unused-patches=true update -r --no-save vite@^7.0.0 - - name: Run dev playground tests - if: steps.changes.outputs.everything_but_markdown == 'true' - # We use `--only` to prevent TurboRepo from rebuilding dependencies - # This ensures the Vite plugin is not rebuilt using a different Vite version - # `VITE_PLUGIN_BUILD_HASH` puts the stripped dependency hashes back into - # the cache key — see "Export plugin build hash" above - run: | - pnpm dotenv -- pnpm turbo test:ci:serve --filter @vite-plugin-cloudflare/playground --only + - name: Select compatibility Vite version + if: matrix.vite != 8 env: - VITE_VERSION: ${{ matrix.vite }} - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/index.html - NODE_DEBUG: "@cloudflare:vite-plugin" - - name: Run build/preview playground tests - if: steps.changes.outputs.everything_but_markdown == 'true' - # We use `--only` to prevent TurboRepo from rebuilding dependencies - # This ensures the Vite plugin is not rebuilt using a different Vite version - # `VITE_PLUGIN_BUILD_HASH` puts the stripped dependency hashes back into - # the cache key — see "Export plugin build hash" above - run: | - pnpm dotenv -- pnpm turbo test:ci:build --filter @vite-plugin-cloudflare/playground --only + VITE_MAJOR: ${{ matrix.vite }} + shell: bash + run: pnpm update -r --no-save "vite@^${VITE_MAJOR}.0.0" + - run: pnpm --filter @vite-plugin-cloudflare/playground playwright:install + - run: pnpm dotenv -- turbo test:ci:serve --filter @vite-plugin-cloudflare/playground --only --summarize env: - VITE_VERSION: ${{ matrix.vite }} - NODE_OPTIONS: "--max_old_space_size=8192" - WRANGLER_LOG_PATH: ${{ runner.temp }}/wrangler-debug-logs/ - TEST_REPORT_PATH: ${{ runner.temp }}/test-report/index.html + VITE_VERSION: vite-${{ matrix.vite }} + NODE_OPTIONS: --max_old_space_size=8192 + NODE_DEBUG: "@cloudflare:vite-plugin" + - run: pnpm dotenv -- turbo test:ci:build --filter @vite-plugin-cloudflare/playground --only --summarize + env: + VITE_VERSION: vite-${{ matrix.vite }} + NODE_OPTIONS: --max_old_space_size=8192 NODE_DEBUG: "@cloudflare:vite-plugin" - - name: Upload turbo logs - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: turbo-runs-${{ matrix.os }}-${{ matrix.vite }} - path: .turbo/runs diff --git a/.github/workflows/vouch.yml b/.github/workflows/vouch.yml deleted file mode 100644 index 81184c29b5..0000000000 --- a/.github/workflows/vouch.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Vouch - -on: - # Only check new PRs so maintainers can reopen one after triage. - pull_request_target: # zizmor: ignore[dangerous-triggers] reads trusted default-branch files and PR metadata without checking out or executing PR code - types: [opened] - -permissions: - contents: read - pull-requests: write - -jobs: - check: - if: ${{ github.repository_owner == 'cloudflare' }} - runs-on: ubuntu-latest - timeout-minutes: 5 - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - # Use the current policy even for PRs targeting older branches. - ref: ${{ github.event.repository.default_branch }} - fetch-depth: 1 - persist-credentials: false - - - name: Check pull request author - uses: mitchellh/vouch/action/check-pr@d66fa29a64600490892131ad87597c30c91fcac4 # v1 - with: - pr-number: ${{ github.event.pull_request.number }} - auto-close: true - template-file: .github/vouch-pr-response.md - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/worker-playground-preview-testing-env-deploy-and-test.yml b/.github/workflows/worker-playground-preview-testing-env-deploy-and-test.yml deleted file mode 100644 index 9ea49394e3..0000000000 --- a/.github/workflows/worker-playground-preview-testing-env-deploy-and-test.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: Deploy (to testing) and Test Playground Preview Worker - -# This workflow is designed to deploy a "testing" version of the Playground Preview Worker -# and test it via integration tests. - -# Triggers: -# - push to `main`, on Cloudflare, where there are changes to the files in this worker's package -# - update to a PR, on Cloudflare, labelled as `playground-worker` -# -# Actions: -# - deploy to testing environment -# - run the end-to-end tests against testing deployment -on: - push: - branches: - - main - paths: - - "packages/playground-preview-worker/**" - pull_request: - types: [synchronize, opened, reopened, labeled, unlabeled] - -permissions: - contents: read - -jobs: - e2e-test: - if: github.repository_owner == 'cloudflare' && (github.event_name != 'pull_request' || contains(github.event.*.labels.*.name, 'feature:playground-worker')) - name: "Deploy Playground Preview Worker (testing)" - runs-on: ubuntu-latest - - steps: - - name: Checkout repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Build tools and libraries - run: pnpm run build - env: - NODE_ENV: "production" - CI_OS: ${{ runner.os }} - - - name: Build & deploy Worker - run: pnpm run deploy:testing - env: - NODE_ENV: "production" - CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - working-directory: packages/playground-preview-worker - - - name: Run tests - run: pnpm run test:e2e - env: - TMP_CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - TMP_CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - NODE_OPTIONS: "--max_old_space_size=8192" - working-directory: packages/playground-preview-worker diff --git a/.github/workflows/workers-shared-deploy-production.yml b/.github/workflows/workers-shared-deploy-production.yml deleted file mode 100644 index 0eeb6ddd15..0000000000 --- a/.github/workflows/workers-shared-deploy-production.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Deploy Workers Shared Production - -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - deploy-workers: - name: Deploy Workers Shared Production - runs-on: ubuntu-latest - steps: - - name: Checkout repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Deploy - run: pnpm run deploy - working-directory: packages/workers-shared - env: - WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN: ${{ secrets.WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN }} - WORKERS_SHARED_SENTRY_ACCESS_ID: ${{ secrets.WORKERS_SHARED_SENTRY_ACCESS_ID }} - WORKERS_SHARED_SENTRY_ACCESS_SECRET: ${{ secrets.WORKERS_SHARED_SENTRY_ACCESS_SECRET }} - WORKERS_SHARED_SENTRY_AUTH_TOKEN: ${{ secrets.WORKERS_SHARED_SENTRY_AUTH_TOKEN }} - - - name: Publish deployment summary - run: echo -e "# Deployment summary\n\n| Service | Version | Release link |\n| --- | --- | --- |\n| Asset Worker | \`aw-$(node -r esbuild-register ./scripts/get-version-tag.ts)\` | https://cflare.co/release-asset-worker |\n| Router Worker | \`rw-$(node -r esbuild-register ./scripts/get-version-tag.ts)\` | https://cflare.co/release-router-worker |\n" >> $GITHUB_STEP_SUMMARY - working-directory: packages/workers-shared diff --git a/.github/workflows/workers-shared-deploy-staging.yml b/.github/workflows/workers-shared-deploy-staging.yml deleted file mode 100644 index f344541782..0000000000 --- a/.github/workflows/workers-shared-deploy-staging.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Deploy Workers Shared Staging - -on: - push: - branches: - - main - paths: - - "packages/workers-shared/**" - -permissions: - contents: read - -jobs: - deploy-workers: - name: "Deploy Workers Shared Staging" - runs-on: ubuntu-latest - steps: - - name: "Checkout repo" - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 - with: - fetch-depth: 1 - persist-credentials: false - - - name: Install Dependencies - uses: ./.github/actions/install-dependencies - - - name: Deploy - run: pnpm deploy:staging - working-directory: packages/workers-shared - env: - WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN: ${{ secrets.WORKERS_DEPLOY_AND_CONFIG_CLOUDFLARE_API_TOKEN }} diff --git a/.oxfmtrc.jsonc b/.oxfmtrc.jsonc index 77143a2f11..f382d54687 100644 --- a/.oxfmtrc.jsonc +++ b/.oxfmtrc.jsonc @@ -24,44 +24,17 @@ "proseWrap": "never", }, }, - { - "files": ["packages/local-explorer-ui/**/*.{js,jsx,ts,tsx}"], - "options": { - "sortTailwindcss": { - "stylesheet": "./packages/local-explorer-ui/src/styles/tailwind.css", - "functions": ["cn"], - }, - }, - }, ], "ignorePatterns": [ "CHANGELOG.md", - // tsup deletes these generated config bundles while checks run concurrently. - "**/tsup.config.bundled_*.{mjs,cjs}", - // In the C3 templates, in particular framework templates, we want to be able to - // use any format that the framework authors prefer/use in their own templates, - // so let's ignore all the c3 template files, exlcuding the c3.ts ones, and tests - "packages/create-cloudflare/templates*/**/*.*", - "!packages/create-cloudflare/templates*/**/c3.ts", - "!packages/create-cloudflare/templates*/**/test/**/*.ts", - "!packages/create-cloudflare/templates*/**/test/**/*.js", - // Format the hello-world template (negate previous exclusion above) for best practices, since we control these - // but still exclude the worker-configuration.d.ts file, since it's generated - "!packages/create-cloudflare/templates*/hello-world/**/*.*", - "packages/create-cloudflare/templates*/hello-world/**/worker-configuration.d.ts", - - "packages/vitest-plugin/scripts/rtti/rtti.js", "packages/vite-plugin-cloudflare/playground/prisma/src/generated", "dist-functions", "vscode.d.ts", "vscode.*.d.ts", ".e2e-logs*", ".github/pull_request_template.md", - "fixtures/interactive-dev-tests/src/startup-error.ts", "packages/vite-plugin-cloudflare/playground/**/*.d.ts", "fixtures/**/worker-configuration.d.ts", "packages/**/worker-configuration.d.ts", - "packages/local-explorer-ui/src/routeTree.gen.ts", - "packages/local-explorer-ui/src/api/generated", ], } diff --git a/.oxlintrc.jsonc b/.oxlintrc.jsonc index ed0f598e08..362d5f3508 100644 --- a/.oxlintrc.jsonc +++ b/.oxlintrc.jsonc @@ -34,7 +34,9 @@ "prefer-spread": "error", "@typescript-eslint/consistent-type-imports": [ "error", - { "disallowTypeAnnotations": false }, + { + "disallowTypeAnnotations": false, + }, ], "no-var": "error", "no-regex-spaces": "error", @@ -42,7 +44,12 @@ "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-require-imports": "error", - "no-shadow": ["error", { "allow": ["expect"] }], + "no-shadow": [ + "error", + { + "allow": ["expect"], + }, + ], "no-unexpected-multiline": "error", "@typescript-eslint/no-unnecessary-type-constraint": "error", "unicorn/prefer-node-protocol": "error", @@ -53,14 +60,15 @@ "workers-sdk/no-direct-recursive-rm": "error", "workers-sdk/require-description-when-disabling": "error", "@typescript-eslint/no-deprecated": "error", - "no-unused-vars": [ "error", { "argsIgnorePattern": "^_", "varsIgnorePattern": "^_", "ignoreRestSiblings": true, - "fix": { "imports": "fix" }, + "fix": { + "imports": "fix", + }, }, ], "no-restricted-imports": [ @@ -91,23 +99,7 @@ }, ], }, - "ignorePatterns": [ - "**/*.js", - "**/*.cjs", - "**/*.mjs", - "fixtures/**", - "packages/create-cloudflare/**/templates/**/*.*", - "!packages/create-cloudflare/**/templates*/**/c3.ts", - // TODO: we really should be linting this folder - "packages/wrangler/templates/**", - // Ignore generated files - "packages/containers-shared/src/client/**", - "packages/local-explorer-ui/src/api/generated/**", - "packages/local-explorer-ui/src/routeTree.gen.ts", - "packages/miniflare/src/runtime/config/workerd.*", - "packages/quick-edit-extension/vscode.d.ts", - "packages/quick-edit-extension/vscode.proposed.*.d.ts", - ], + "ignorePatterns": ["**/*.js", "**/*.cjs", "**/*.mjs", "fixtures/**"], "jsPlugins": [ "eslint-plugin-turbo", { @@ -116,107 +108,14 @@ }, ], "overrides": [ - // Published packages which all have their own "logger" class that should be used instead. { - "files": [ - "packages/cli/**", - "packages/create-cloudflare/**", - "packages/miniflare/**", - "packages/wrangler/**", - "packages/workers-utils/**", - ], - "rules": { - "no-console": "error", - }, - }, - // TODO: remove these overrides. This is a legacy of Miniflare's history, not intentional - { - "files": ["packages/miniflare/**"], - "rules": { - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/ban-ts-comment": "off", - "@typescript-eslint/no-floating-promises": "off", - "no-shadow": "off", - "no-useless-escape": "off", - "no-unsafe-optional-chaining": "off", - "no-control-regex": "off", - "no-case-declarations": "off", - "turbo/no-undeclared-env-vars": "off", - }, - }, - { - "files": ["packages/wrangler/src/**", "packages/workers-utils/src/**"], - "rules": { - "no-restricted-globals": [ - "error", - { - "name": "__dirname", - "message": "Use `getBasePath()` instead.", - }, - { - "name": "__filename", - "message": "Use `getBasePath()` instead.", - }, - { - "name": "fetch", - "message": "Use undici's fetch instead", - }, - ], - }, - }, - // Although in _general_ Miniflare shouldn't use console.log(), it's Workers can and should - { - "files": ["packages/miniflare/src/workers/**/*.ts"], - "rules": { - "no-console": "off", - "no-restricted-imports": [ - "error", - { - "paths": [ - { - "name": "zod", - "allowTypeImports": true, - "message": "Import runtime values from `miniflare:zod` instead.", - }, - ], - }, - ], - }, - }, - { - "files": ["packages/miniflare/src/workers/shared/zod.worker.ts"], - "rules": { - "no-restricted-imports": "off", - }, - }, - // Relax some rules for test & script files - { - "files": [ - "packages/wrangler/src/__tests__/**", - "packages/wrangler/e2e/**", - "packages/wrangler/scripts/**", - "packages/miniflare/scripts/**", - "packages/cli/src/__tests__/**", - "packages/create-cloudflare/scripts/**", - "packages/create-cloudflare/src/__tests__/**", - "packages/workers-utils/tests/**", - "packages/vite-plugin-cloudflare/e2e/**", - ], + "files": ["packages/vite-plugin-cloudflare/e2e/**"], "rules": { "no-console": "off", "no-restricted-globals": "off", "workers-sdk/no-unsafe-command-execution": "off", }, }, - // Local Explorer UI e2e tests use Playwright helpers (waitForText, waitForTableRows, etc.) - // as assertions, which the vitest/expect-expect rule doesn't recognise. - { - "files": ["packages/local-explorer-ui/src/__e2e__/**"], - "rules": { - "vitest/expect-expect": "off", - }, - }, - // Make sure Wrangler's version checking logic in vite-plugin-cloudflare can run properly { "files": ["packages/vite-plugin-cloudflare/**"], "rules": { diff --git a/AGENTS.md b/AGENTS.md index 56edba193b..7802b95bdc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,157 +1,14 @@ # AGENTS.md -This file helps AI coding agents work effectively in the Cloudflare Workers SDK -monorepo. Prefer authoritative configuration and documentation over copying -details into this file: copied versions, rule lists, and counts become stale. +This is the maintenance branch for Cloudflare Vite plugin v1. Read packages/vite-plugin-cloudflare/AGENTS.md before changing the plugin. -## Start Here - -- Use `pnpm`, not npm or yarn. -- Use the Node.js and pnpm versions declared in `package.json`. -- Install dependencies with `pnpm install`. -- Run commands from the workspace root unless package documentation says - otherwise. -- Before changing a package, read its `AGENTS.md` if it has one. -- Do not edit generated files directly. Change their source or generator and - regenerate them. - -## Common Commands - -The root `package.json` is authoritative for available scripts. - -- `pnpm build` — build the workspace with Turbo. -- `pnpm test:ci` — run tests in CI mode. -- `pnpm test:e2e` — run end-to-end tests; many require Cloudflare credentials. -- `pnpm check` — run the repository's validation, lint, type, and format checks. -- `pnpm fix` — apply supported lint and formatting fixes. -- `pnpm prettify` — format files with oxfmt. -- `pnpm run - - - - - - - diff --git a/fixtures/workers-with-assets-spa/public/shadowed-by-asset.txt b/fixtures/workers-with-assets-spa/public/shadowed-by-asset.txt deleted file mode 100644 index 1190b77f29..0000000000 --- a/fixtures/workers-with-assets-spa/public/shadowed-by-asset.txt +++ /dev/null @@ -1 +0,0 @@ -i'm some text! \ No newline at end of file diff --git a/fixtures/workers-with-assets-spa/src/index.ts b/fixtures/workers-with-assets-spa/src/index.ts deleted file mode 100644 index f1cf871969..0000000000 --- a/fixtures/workers-with-assets-spa/src/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -export default { - async fetch(request: Request): Promise { - const url = new URL(request.url); - if (url.pathname === "/api/math") { - return new Response(`1 + 1 = ${1 + 1}`); - } - if (url.pathname === "/api/json") { - return Response.json({ hello: "world" }); - } - if (url.pathname === "/api/html") { - return new Response("

Hello, world!

", { - headers: { "Content-Type": "text/html" }, - }); - } - if (url.pathname === "/shadowed-by-spa") { - return new Response("nope"); - } - if (url.pathname === "/shadowed-by-asset.txt") { - return new Response("nope"); - } - - return new Response("nope", { status: 404 }); - }, -}; diff --git a/fixtures/workers-with-assets-spa/tests/__image_snapshots__/index-test-ts-workers-assets-spa-renders-the-homepage-in-a-browser-correctly-1-snap.png b/fixtures/workers-with-assets-spa/tests/__image_snapshots__/index-test-ts-workers-assets-spa-renders-the-homepage-in-a-browser-correctly-1-snap.png deleted file mode 100644 index d1b8b3d49f..0000000000 Binary files a/fixtures/workers-with-assets-spa/tests/__image_snapshots__/index-test-ts-workers-assets-spa-renders-the-homepage-in-a-browser-correctly-1-snap.png and /dev/null differ diff --git a/fixtures/workers-with-assets-spa/tests/index.test.ts b/fixtures/workers-with-assets-spa/tests/index.test.ts deleted file mode 100644 index a559c06522..0000000000 --- a/fixtures/workers-with-assets-spa/tests/index.test.ts +++ /dev/null @@ -1,267 +0,0 @@ -import { resolve } from "node:path"; -import { toMatchImageSnapshot } from "jest-image-snapshot"; -import { Browser, chromium } from "playwright-chromium"; -import { afterAll, beforeAll, describe, it } from "vitest"; -import { runWranglerDev } from "../../shared/src/run-wrangler-long-lived"; - -describe("Workers + Assets + SPA", () => { - let ip: string, - port: number, - stop: (() => Promise) | undefined, - getOutput: () => string; - let browser: Browser | undefined; - - beforeAll(async () => { - ({ ip, port, stop, getOutput } = await runWranglerDev( - resolve(__dirname, ".."), - ["--port=0", "--inspector-port=0"] - )); - - browser = await chromium.launch({ - headless: !process.env.VITE_DEBUG_SERVE, - args: process.env.CI - ? ["--no-sandbox", "--disable-setuid-sandbox"] - : undefined, - }); - }); - - afterAll(async () => { - await stop?.(); - await browser?.close(); - }); - - it("renders the homepage in a browser correctly", async ({ expect }) => { - expect.extend({ toMatchImageSnapshot }); - - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/"); - if (process.platform === "darwin") { - // different platforms render the page differently (fonts?) - expect(await page.screenshot()).toMatchImageSnapshot({ - failureThreshold: 0.02, - failureThresholdType: "percent", - }); - } - - const mathResultLocator = page.getByText("1 + 1 = 2"); - await mathResultLocator.waitFor({ state: "attached" }); - expect(await mathResultLocator.getAttribute("id")).toBe(`math-result`); - - const jsonResultLocator = page.getByText( - JSON.stringify({ hello: "world" }, null, 2) - ); - await jsonResultLocator.waitFor({ state: "attached" }); - expect(await jsonResultLocator.getAttribute("id")).toBe(`json-result`); - - const htmlResultLocator = page.getByText("Hello, world!"); - await htmlResultLocator.waitFor({ state: "attached" }); - const parentHtmlResultLocator = htmlResultLocator.locator(".."); - expect(await parentHtmlResultLocator.getAttribute("id")).toBe( - "html-result" - ); - }); - - it("navigates soft page navigations correctly", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/"); - - const homepageLink = page.getByText("/ HARD SOFT").getByText("SOFT"); - expect(await homepageLink.getAttribute("href")).toBe("/"); - await homepageLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/`); - const homepageHeader = page.getByRole("heading", { name: "Homepage" }); - await homepageHeader.waitFor({ state: "attached" }); - - const blogLink = page.getByText("/blog HARD SOFT").getByText("SOFT"); - expect(await blogLink.getAttribute("href")).toBe("/blog"); - await blogLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/blog`); - const blogTitleLocator = page.getByRole("heading", { name: "Blog" }); - await blogTitleLocator.waitFor({ state: "attached" }); - - const blogSlugInput = page.getByRole("textbox"); - blogSlugInput.fill("/blog/some-slug-here"); - - const blogSlugLink = page.getByRole("button", { name: "SOFT load" }); - await blogSlugLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/blog/some-slug-here`); - const blogSlugTitleLocator = page.getByRole("heading", { - name: "Blog | some-slug-here", - }); - await blogSlugTitleLocator.waitFor({ state: "attached" }); - - const blogRandomLink = page - .getByText("/blog/random HARD SOFT") - .getByText("SOFT"); - expect(await blogRandomLink.getAttribute("href")).toBe("/blog/random"); - await blogRandomLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/blog/random`); - const blogRandomTitleLocator = page.getByRole("heading", { - name: "Blog | random", - }); - await blogRandomTitleLocator.waitFor({ state: "attached" }); - - const shadowedByAssetLink = page - .getByText("/shadowed-by-asset.txt HARD SOFT") - .getByText("SOFT"); - expect(await shadowedByAssetLink.getAttribute("href")).toBe( - "/shadowed-by-asset.txt" - ); - await shadowedByAssetLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/shadowed-by-asset.txt`); - const shadowedByAssetHeader = page.getByRole("heading", { - name: "404 page!", - }); - await shadowedByAssetHeader.waitFor({ state: "attached" }); - - const shadowedBySpaLink = page - .getByText("/shadowed-by-spa HARD SOFT") - .getByText("SOFT"); - expect(await shadowedBySpaLink.getAttribute("href")).toBe( - "/shadowed-by-spa" - ); - await shadowedBySpaLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/shadowed-by-spa`); - const shadowedBySpaHeader = page.getByRole("heading", { - name: "Shadowed by SPA!", - }); - await shadowedBySpaHeader.waitFor({ state: "attached" }); - - const mathLink = page.getByText("/api/math HARD SOFT").getByText("SOFT"); - expect(await mathLink.getAttribute("href")).toBe("/api/math"); - await mathLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/api/math`); - const mathHeader = page.getByRole("heading", { - name: "404 page!", - }); - await mathHeader.waitFor({ state: "attached" }); - }); - - it("navigates hard navigations correctly", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/"); - - const homepageLink = page.getByText("/ HARD SOFT").getByText("HARD"); - expect(await homepageLink.getAttribute("href")).toBe("/"); - await homepageLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/`); - const homepageHeader = page.getByRole("heading", { name: "Homepage" }); - await homepageHeader.waitFor({ state: "attached" }); - - const blogLink = page.getByText("/blog HARD SOFT").getByText("HARD"); - expect(await blogLink.getAttribute("href")).toBe("/blog"); - await blogLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/blog`); - const blogTitleLocator = page.getByRole("heading", { name: "Blog" }); - await blogTitleLocator.waitFor({ state: "attached" }); - - expect( - getOutput().match( - /GET \/blog 200 OK \(.*\) `Sec-Fetch-Mode: navigate` header present - using `not_found_handling` behavior/ - ) - ).toBeTruthy(); - - const blogSlugInput = page.getByRole("textbox"); - blogSlugInput.fill("/blog/some-slug-here"); - - const blogSlugLink = page.getByRole("link", { name: "HARD load" }); - await blogSlugLink.click(); - expect(page.url()).toBe(`http://${ip}:${port}/blog/some-slug-here`); - const blogSlugTitleLocator = page.getByRole("heading", { - name: "Blog | some-slug-here", - }); - await blogSlugTitleLocator.waitFor({ state: "attached" }); - - const blogRandomLink = page - .getByText("/blog/random HARD SOFT") - .getByText("HARD"); - expect(await blogRandomLink.getAttribute("href")).toBe("/blog/random"); - await blogRandomLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/blog/random`); - const blogRandomTitleLocator = page.getByRole("heading", { - name: "Blog | random", - }); - await blogRandomTitleLocator.waitFor({ state: "attached" }); - - const shadowedByAssetLink = page - .getByText("/shadowed-by-asset.txt HARD SOFT") - .getByText("HARD"); - expect(await shadowedByAssetLink.getAttribute("href")).toBe( - "/shadowed-by-asset.txt" - ); - await shadowedByAssetLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/shadowed-by-asset.txt`); - expect(await page.content()).toContain("i'm some text!"); - - await page.goBack(); - - const shadowedBySpaLink = page - .getByText("/shadowed-by-spa HARD SOFT") - .getByText("HARD"); - expect(await shadowedBySpaLink.getAttribute("href")).toBe( - "/shadowed-by-spa" - ); - await shadowedBySpaLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/shadowed-by-spa`); - const shadowedBySpaHeader = page.getByRole("heading", { - name: "Shadowed by SPA!", - }); - await shadowedBySpaHeader.waitFor({ state: "attached" }); - - const mathLink = page.getByText("/api/math HARD SOFT").getByText("HARD"); - expect(await mathLink.getAttribute("href")).toBe("/api/math"); - await mathLink.click(); - - expect(page.url()).toBe(`http://${ip}:${port}/api/math`); - const mathHeader = page.getByRole("heading", { - name: "404 page!", - }); - await mathHeader.waitFor({ state: "attached" }); - }); - - it("direct fetches don't look like SPA requests", async ({ expect }) => { - const homepageResponse = await fetch(`http://${ip}:${port}/`); - expect(await homepageResponse.text()).toContain("Homepage"); - - const blogResponse = await fetch(`http://${ip}:${port}/blog`); - expect(await blogResponse.text()).toBe("nope"); - - const shadowedByAssetResponse = await fetch( - `http://${ip}:${port}/shadowed-by-asset.txt` - ); - expect(await shadowedByAssetResponse.text()).toBe("i'm some text!"); - - const mathResponse = await fetch(`http://${ip}:${port}/api/math`); - expect(await mathResponse.text()).toBe("1 + 1 = 2"); - }); -}); diff --git a/fixtures/workers-with-assets-spa/tests/tsconfig.json b/fixtures/workers-with-assets-spa/tests/tsconfig.json deleted file mode 100644 index be0dabdb19..0000000000 --- a/fixtures/workers-with-assets-spa/tests/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["**/*.ts"] -} diff --git a/fixtures/workers-with-assets-spa/tsconfig.json b/fixtures/workers-with-assets-spa/tsconfig.json deleted file mode 100644 index 6112e71504..0000000000 --- a/fixtures/workers-with-assets-spa/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "preserve", - "lib": ["ES2020"], - "types": ["@cloudflare/workers-types"], - "moduleResolution": "node", - "noEmit": true, - "skipLibCheck": true - }, - "include": ["**/*.ts"], - "exclude": ["tests"] -} diff --git a/fixtures/workers-with-assets-spa/vitest.config.mts b/fixtures/workers-with-assets-spa/vitest.config.mts deleted file mode 100644 index 472d8fe92e..0000000000 --- a/fixtures/workers-with-assets-spa/vitest.config.mts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineProject, mergeConfig } from "vitest/config"; -import configShared from "../../vitest.shared"; - -export default mergeConfig( - configShared, - defineProject({ - test: { - // The `runWranglerDev` helper will wait up to 50 secs for Wrangler to boot up - // The `chromium.launch` helper will wait up to 30 secs for the browser to boot up. - hookTimeout: 50_000, - testTimeout: 50_000, - }, - }) -); diff --git a/fixtures/workers-with-assets-spa/wrangler.jsonc b/fixtures/workers-with-assets-spa/wrangler.jsonc deleted file mode 100644 index d949bcb6e1..0000000000 --- a/fixtures/workers-with-assets-spa/wrangler.jsonc +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "worker-with-assets-spa", - "main": "./src/index.ts", - "compatibility_date": "2025-03-11", - "compatibility_flags": ["assets_navigation_prefers_asset_serving"], - "assets": { - "directory": "./public/", - "binding": "ASSETS", - "not_found_handling": "single-page-application", - "run_worker_first": false, - }, - "routes": ["example.com"], -} diff --git a/fixtures/workers-with-assets-static-routing/package.json b/fixtures/workers-with-assets-static-routing/package.json deleted file mode 100644 index 965c116b96..0000000000 --- a/fixtures/workers-with-assets-static-routing/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "@fixture/workers-with-assets-static-routing", - "private": true, - "scripts": { - "check:type": "tsc", - "dev": "wrangler dev", - "dev:spa": "wrangler dev -c spa.wrangler.jsonc", - "pretest:ci": "pnpm playwright install chromium", - "test:ci": "vitest run", - "test:watch": "vitest", - "type:tests": "tsc -p ./test/tsconfig.json" - }, - "devDependencies": { - "@cloudflare/workers-tsconfig": "workspace:*", - "@cloudflare/workers-types": "catalog:default", - "@types/node": "catalog:default", - "playwright-chromium": "catalog:default", - "typescript": "catalog:default", - "undici": "catalog:default", - "vitest": "catalog:default", - "wrangler": "workspace:*" - } -} diff --git a/fixtures/workers-with-assets-static-routing/public/static/page.html b/fixtures/workers-with-assets-static-routing/public/static/page.html deleted file mode 100644 index c61edebd1b..0000000000 --- a/fixtures/workers-with-assets-static-routing/public/static/page.html +++ /dev/null @@ -1 +0,0 @@ -

A normal asset

diff --git a/fixtures/workers-with-assets-static-routing/public/worker/asset.html b/fixtures/workers-with-assets-static-routing/public/worker/asset.html deleted file mode 100644 index 1052ed12b5..0000000000 --- a/fixtures/workers-with-assets-static-routing/public/worker/asset.html +++ /dev/null @@ -1 +0,0 @@ -

Hello, I'm an asset!

diff --git a/fixtures/workers-with-assets-static-routing/public/worker/worker-runs.html b/fixtures/workers-with-assets-static-routing/public/worker/worker-runs.html deleted file mode 100644 index 57c660beaf..0000000000 --- a/fixtures/workers-with-assets-static-routing/public/worker/worker-runs.html +++ /dev/null @@ -1 +0,0 @@ -

Hello, I'm an asset at /worker/worker-runs.html!

diff --git a/fixtures/workers-with-assets-static-routing/spa-assets/index.html b/fixtures/workers-with-assets-static-routing/spa-assets/index.html deleted file mode 100644 index b696b5e4cd..0000000000 --- a/fixtures/workers-with-assets-static-routing/spa-assets/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - I'm an index.html for a SPA - - -

Here I am, at /!

- - - diff --git a/fixtures/workers-with-assets-static-routing/spa.wrangler.jsonc b/fixtures/workers-with-assets-static-routing/spa.wrangler.jsonc deleted file mode 100644 index f1472a236f..0000000000 --- a/fixtures/workers-with-assets-static-routing/spa.wrangler.jsonc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "workers-with-assets-static-routing", - "main": "src/index.ts", - "compatibility_date": "2025-05-20", - "assets": { - "binding": "ASSETS", - "directory": "./spa-assets", - "not_found_handling": "single-page-application", - "run_worker_first": ["/api/*", "!/api/asset"], - }, -} diff --git a/fixtures/workers-with-assets-static-routing/src/index.ts b/fixtures/workers-with-assets-static-routing/src/index.ts deleted file mode 100644 index 558007744c..0000000000 --- a/fixtures/workers-with-assets-static-routing/src/index.ts +++ /dev/null @@ -1,31 +0,0 @@ -export type Env = { - ASSETS: Fetcher; -}; - -export default { - async fetch(request, env, ctx): Promise { - const { pathname } = new URL(request.url); - - // api routes - if (pathname.startsWith("/api/")) { - return Response.json({ some: ["json", "response"] }); - } - - // asset middleware - const assetResp = await env.ASSETS.fetch(request); - if (assetResp.ok) { - let text = await assetResp.text(); - text = text.replace( - "I'm an asset", - "I'm an asset (and was intercepted by the User Worker)" - ); - return new Response(text, { - headers: assetResp.headers, - status: assetResp.status, - }); - } - - // default handling - return new Response("404 from the User Worker", { status: 404 }); - }, -} satisfies ExportedHandler; diff --git a/fixtures/workers-with-assets-static-routing/test/index.test.ts b/fixtures/workers-with-assets-static-routing/test/index.test.ts deleted file mode 100644 index 91a445cd75..0000000000 --- a/fixtures/workers-with-assets-static-routing/test/index.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { resolve } from "node:path"; -import { Browser, chromium } from "playwright-chromium"; -import { afterAll, beforeAll, describe, it } from "vitest"; -import { runWranglerDev } from "../../shared/src/run-wrangler-long-lived"; - -describe("[Workers + Assets] static routing", () => { - describe("static routing behavior", () => { - let ip: string, port: number, stop: (() => Promise) | undefined; - - beforeAll(async () => { - ({ ip, port, stop } = await runWranglerDev(resolve(__dirname, ".."), [ - "--port=0", - "--inspector-port=0", - ])); - }); - - afterAll(async () => { - await stop?.(); - }); - - it("should serve assets when they exist for a path", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/static/page`); - expect(response.status).toBe(200); - expect(await response.text()).toContain(`

A normal asset

`); - }); - - it("should run the worker when no assets exist for a path", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/`); - expect(response.status).toBe(404); - expect(await response.text()).toContain(`404 from the User Worker`); - }); - - it("should run the worker when a positive run_worker_first rule matches", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/worker/worker-runs`); - expect(response.status).toBe(200); - expect(await response.text()).toContain( - `

Hello, I'm an asset (and was intercepted by the User Worker) at /worker/worker-runs.html!

` - ); - }); - - it("should serve a 404 when a negative run_worker_first rule matches", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/missing-asset`); - expect(response.status).toBe(404); - expect(await response.text()).toEqual(""); - }); - - it("should serve an asset when both a positive and negative (asset) run_worker_first matches", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/worker/asset`); - expect(response.status).toBe(200); - expect(await response.text()).toContain(`

Hello, I'm an asset!

`); - }); - }); - - describe("static routing + SPA behavior", async () => { - let ip: string, port: number, stop: (() => Promise) | undefined; - - beforeAll(async () => { - ({ ip, port, stop } = await runWranglerDev(resolve(__dirname, ".."), [ - "-c=spa.wrangler.jsonc", - "--port=0", - "--inspector-port=0", - ])); - }); - - afterAll(async () => { - await stop?.(); - }); - - describe("browser navigation", () => { - let browser: Browser | undefined; - - beforeAll(async () => { - browser = await chromium.launch({ - headless: !process.env.VITE_DEBUG_SERVE, - args: process.env.CI - ? ["--no-sandbox", "--disable-setuid-sandbox"] - : undefined, - }); - }, 40_000); - - it("renders the root with index.html", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/"); - expect(await page.getByRole("heading").innerText()).toBe( - "Here I am, at /!" - ); - }); - - it("renders another path with index.html", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/some/page"); - expect(await page.getByRole("heading").innerText()).toBe( - "Here I am, at /some/page!" - ); - }); - - it("renders an include path with the User worker", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - const response = await page.goto("/api/route"); - expect(response?.headers()).toHaveProperty( - "content-type", - "application/json" - ); - expect(await page.content()).toContain(`{"some":["json","response"]}`); - }); - - it("renders an exclude path with index.html", async ({ expect }) => { - if (!browser) { - throw new Error("Browser couldn't be initialized"); - } - - const page = await browser.newPage({ - baseURL: `http://${ip}:${port}`, - }); - await page.goto("/api/asset"); - expect(await page.getByRole("heading").innerText()).toBe( - "Here I am, at /api/asset!" - ); - }); - }); - - describe("non-browser navigation", () => { - it("renders the root with index.html", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}`); - expect(response.status).toBe(200); - expect(await response.text()).toContain(`I'm an index.html for a SPA`); - }); - - it("renders another path with index.html", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/some/page`); - expect(response.status).toBe(200); - expect(await response.text()).toContain(`I'm an index.html for a SPA`); - }); - - it("renders an include path with the User worker", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/api/route`); - expect(response.status).toBe(200); - expect(response.headers.get("content-type")).toEqual( - "application/json" - ); - expect(await response.text()).toContain(`{"some":["json","response"]}`); - }); - - it("renders an exclude path with index.html", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/api/asset`); - expect(response.status).toBe(200); - expect(await response.text()).toContain(`I'm an index.html for a SPA`); - }); - }); - }); -}); diff --git a/fixtures/workers-with-assets-static-routing/test/tsconfig.json b/fixtures/workers-with-assets-static-routing/test/tsconfig.json deleted file mode 100644 index be0dabdb19..0000000000 --- a/fixtures/workers-with-assets-static-routing/test/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["**/*.ts"] -} diff --git a/fixtures/workers-with-assets-static-routing/tsconfig.json b/fixtures/workers-with-assets-static-routing/tsconfig.json deleted file mode 100644 index 6ec35310ea..0000000000 --- a/fixtures/workers-with-assets-static-routing/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "preserve", - "lib": ["ES2020"], - "types": ["@cloudflare/workers-types"], - "moduleResolution": "node", - "noEmit": true, - "skipLibCheck": true - }, - "include": ["**/*.ts"], - "exclude": ["test"] -} diff --git a/fixtures/workers-with-assets-static-routing/vitest.config.mts b/fixtures/workers-with-assets-static-routing/vitest.config.mts deleted file mode 100644 index 846cddc419..0000000000 --- a/fixtures/workers-with-assets-static-routing/vitest.config.mts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject, mergeConfig } from "vitest/config"; -import configShared from "../../vitest.shared"; - -export default mergeConfig( - configShared, - defineProject({ - test: {}, - }) -); diff --git a/fixtures/workers-with-assets-static-routing/wrangler.jsonc b/fixtures/workers-with-assets-static-routing/wrangler.jsonc deleted file mode 100644 index cc23155dfc..0000000000 --- a/fixtures/workers-with-assets-static-routing/wrangler.jsonc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "workers-with-assets-static-routing", - "main": "src/index.ts", - "compatibility_date": "2025-05-20", - "assets": { - "binding": "ASSETS", - "directory": "./public", - "run_worker_first": [ - // The `/oauth/callback` path and anything under `/worker` will be served by the Worker first - "/worker/*", - "/oauth/callback", - // The `/missing-asset` and `worker/asset` paths will not be served by the Worker first - "!/missing-asset", - "!/worker/asset", - ], - }, -} diff --git a/fixtures/workers-with-assets/.gitignore b/fixtures/workers-with-assets/.gitignore deleted file mode 100644 index 36c15628a9..0000000000 --- a/fixtures/workers-with-assets/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -./public/.assetsignore -./public/_redirects diff --git a/fixtures/workers-with-assets/README.md b/fixtures/workers-with-assets/README.md deleted file mode 100644 index 4a0d8f0767..0000000000 --- a/fixtures/workers-with-assets/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# workers-assets-with-user-worker - -`workers-assets-with-user-worker` is a test fixture that showcases Workers with Assets. This particular fixture sets up a User Worker, assets, and a binding from the user Worker to the assets. - -## dev - -To start a dev session you can run - -``` -wrangler dev -``` - -## Run tests - -``` -npm run test -``` diff --git a/fixtures/workers-with-assets/package.json b/fixtures/workers-with-assets/package.json deleted file mode 100644 index b675ff5623..0000000000 --- a/fixtures/workers-with-assets/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@fixture/workers-assets", - "private": true, - "scripts": { - "check:type": "tsc", - "dev": "wrangler dev", - "test:ci": "vitest run", - "test:watch": "vitest", - "type:tests": "tsc -p ./tests/tsconfig.json" - }, - "devDependencies": { - "@cloudflare/workers-tsconfig": "workspace:*", - "@cloudflare/workers-types": "catalog:default", - "typescript": "catalog:default", - "undici": "catalog:default", - "vitest": "catalog:default", - "wrangler": "workspace:*" - } -} diff --git a/fixtures/workers-with-assets/public/.assetsignore b/fixtures/workers-with-assets/public/.assetsignore deleted file mode 100644 index 554fc76b8d..0000000000 --- a/fixtures/workers-with-assets/public/.assetsignore +++ /dev/null @@ -1 +0,0 @@ -ignore-me.txt diff --git a/fixtures/workers-with-assets/public/.dot/index.html b/fixtures/workers-with-assets/public/.dot/index.html deleted file mode 100644 index 15f20472d8..0000000000 --- a/fixtures/workers-with-assets/public/.dot/index.html +++ /dev/null @@ -1 +0,0 @@ -hi from .dot/index.html diff --git a/fixtures/workers-with-assets/public/.dotfile.html b/fixtures/workers-with-assets/public/.dotfile.html deleted file mode 100644 index 23ee20b71f..0000000000 --- a/fixtures/workers-with-assets/public/.dotfile.html +++ /dev/null @@ -1 +0,0 @@ -hi from .dotfile.html diff --git a/fixtures/workers-with-assets/public/README.md b/fixtures/workers-with-assets/public/README.md deleted file mode 100644 index a78f2f04a1..0000000000 --- a/fixtures/workers-with-assets/public/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# Workers with Assets - -Welcome to Workers + Assets YAY! - -Please proceed with much excitement ^.^ - - ................. - .......-++**********:. - ..-+****++**********#: - ...-+***+++====+********##= - ....:=****+======+***********##+ - ....-****+======+*************###+ - .:==+*+======+***************####= - ....-===--=====++****************#####: - ....:====-:::-==+******************#####+. - ..-====:::::::+*******************#####*.. - ..-===-:::::::-==+*****************######=.. - ..-===-::::::-=======***************######*. - ...-===-::::::-==========+************######*:. - ...-===-::::::-==----========+*********#######:.. - .-===-::::::--::::::::::-======+******#######-. . - ..:====::::::-=:::-*####*-:::-=======+**#######-. - .:====-:::::-==:::*#########-::========+**#####- - ..====-:::::-===-::###########*:::======*******+.. - ..=+====:::::=====::-############:::====+*******=... - ....:=++====:::-======-::###########*:::===+*******-.. - ...........:-==+**+=++++=============-:::*#########-::===********:.. - ....--=+************====+++===============:::=*####*=:::-=+*******=.. - .:*************###*=====++++================::::::::::-==********:.. - ..*****#############=======++++==========================+*******+... - ...+****#############*==:::-===++++========================********-. - ...+****###############+=::::=====+++++====================********+... - .=****################*=-:::-======+++++=================+********:.. - ..-****##################===:-=========++++++=============+********:.. - .+***####################===========+***#++++++=========+********=.. - .*###################+-.-=======+****##*==+++++++====+********=... - ...-+#############*=...-++=====+****####+=====++++++*********+... - ....-*######+:.....++++===******####==========+*######**+.. - ...+=.....:::-+++++******#####=========+***######*.. - .......::::::=++******#####+========***********:... - ....::::::...+*****######=======+**********##*. - ..:::::....-*****######+=====+**********#####*. - ...:::::...:******#####*+++++*********#########+. - ..:::::...+*****######+++++++=.=###############:. - .:::::..-*****######-..-=++=..-##########***###.. - ....::::..=****######=....::::..:########******##*.. - ...::::..+***######-.....::::...*##***********###=.. - ..::::...-**####*:......::::...###************###-.. - ..:::......=##*:......:::::...+##*************###: - ...::::...............:::::....+##*************####. - ...::::::::::::::..:::::::......**************###-.. - .::::::::::::::::::::::..... ...:***********###+.... - ..::::.......::::::...... ..:********###*:... - ........ ...=******###=.. - .=***###+.. - ..*####:... - ........ diff --git a/fixtures/workers-with-assets/public/_headers b/fixtures/workers-with-assets/public/_headers deleted file mode 100644 index 572e15dbc6..0000000000 --- a/fixtures/workers-with-assets/public/_headers +++ /dev/null @@ -1,2 +0,0 @@ -/ - X-Header: Custom-Value \ No newline at end of file diff --git a/fixtures/workers-with-assets/public/_redirects b/fixtures/workers-with-assets/public/_redirects deleted file mode 100644 index 947c63866f..0000000000 --- a/fixtures/workers-with-assets/public/_redirects +++ /dev/null @@ -1,2 +0,0 @@ -/foo /bar -/pic /lava-lamps.jpg 200 diff --git a/fixtures/workers-with-assets/public/_worker.js b/fixtures/workers-with-assets/public/_worker.js deleted file mode 100644 index 7b5c6d1466..0000000000 --- a/fixtures/workers-with-assets/public/_worker.js +++ /dev/null @@ -1 +0,0 @@ -bang; diff --git a/fixtures/workers-with-assets/public/about/%5Bboop%5D.html b/fixtures/workers-with-assets/public/about/%5Bboop%5D.html deleted file mode 100644 index 7a0e3696b1..0000000000 --- a/fixtures/workers-with-assets/public/about/%5Bboop%5D.html +++ /dev/null @@ -1 +0,0 @@ -

%5Bboop%5D.html

diff --git a/fixtures/workers-with-assets/public/about/%5Bwomp%5D.html b/fixtures/workers-with-assets/public/about/%5Bwomp%5D.html deleted file mode 100644 index de76167b23..0000000000 --- a/fixtures/workers-with-assets/public/about/%5Bwomp%5D.html +++ /dev/null @@ -1 +0,0 @@ -

womp

diff --git a/fixtures/workers-with-assets/public/about/[boop].html b/fixtures/workers-with-assets/public/about/[boop].html deleted file mode 100644 index 37af005091..0000000000 --- a/fixtures/workers-with-assets/public/about/[boop].html +++ /dev/null @@ -1 +0,0 @@ -

[boop].html

diff --git a/fixtures/workers-with-assets/public/about/[fünky].txt b/fixtures/workers-with-assets/public/about/[fünky].txt deleted file mode 100644 index dbb84844bd..0000000000 --- a/fixtures/workers-with-assets/public/about/[fünky].txt +++ /dev/null @@ -1 +0,0 @@ -This should work. \ No newline at end of file diff --git a/fixtures/workers-with-assets/public/about/index.html b/fixtures/workers-with-assets/public/about/index.html deleted file mode 100644 index 14f9dffa9f..0000000000 --- a/fixtures/workers-with-assets/public/about/index.html +++ /dev/null @@ -1 +0,0 @@ -

Learn more about Workers with Assets soon!

diff --git a/fixtures/workers-with-assets/public/bar.html b/fixtures/workers-with-assets/public/bar.html deleted file mode 100644 index 5e46a9149b..0000000000 --- a/fixtures/workers-with-assets/public/bar.html +++ /dev/null @@ -1 +0,0 @@ -

Bar

diff --git a/fixtures/workers-with-assets/public/binding.html b/fixtures/workers-with-assets/public/binding.html deleted file mode 100644 index 8edcac24d5..0000000000 --- a/fixtures/workers-with-assets/public/binding.html +++ /dev/null @@ -1 +0,0 @@ -

✨This is from a user Worker binding✨

diff --git a/fixtures/workers-with-assets/public/foo.html b/fixtures/workers-with-assets/public/foo.html deleted file mode 100644 index 88dadda247..0000000000 --- a/fixtures/workers-with-assets/public/foo.html +++ /dev/null @@ -1 +0,0 @@ -

Foo

diff --git a/fixtures/workers-with-assets/public/ignore-me.txt b/fixtures/workers-with-assets/public/ignore-me.txt deleted file mode 100644 index 4e2646aedf..0000000000 --- a/fixtures/workers-with-assets/public/ignore-me.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS A SECRET \ No newline at end of file diff --git a/fixtures/workers-with-assets/public/index.html b/fixtures/workers-with-assets/public/index.html deleted file mode 100644 index b7351e6287..0000000000 --- a/fixtures/workers-with-assets/public/index.html +++ /dev/null @@ -1 +0,0 @@ -

Hello Workers + Assets World 🚀!

diff --git a/fixtures/workers-with-assets/public/lava-lamps.jpg b/fixtures/workers-with-assets/public/lava-lamps.jpg deleted file mode 100644 index fc66cad30f..0000000000 Binary files a/fixtures/workers-with-assets/public/lava-lamps.jpg and /dev/null differ diff --git a/fixtures/workers-with-assets/public/totallyinvalidextension.greg b/fixtures/workers-with-assets/public/totallyinvalidextension.greg deleted file mode 100644 index 0c0f38d8ff..0000000000 --- a/fixtures/workers-with-assets/public/totallyinvalidextension.greg +++ /dev/null @@ -1 +0,0 @@ -I'm a narcissist. \ No newline at end of file diff --git a/fixtures/workers-with-assets/public/yay.txt b/fixtures/workers-with-assets/public/yay.txt deleted file mode 100644 index b84f6bc7c6..0000000000 --- a/fixtures/workers-with-assets/public/yay.txt +++ /dev/null @@ -1,12 +0,0 @@ - - .----------------. .----------------. .----------------. -| .--------------. || .--------------. || .--------------. | -| | ____ ____ | || | __ | || | ____ ____ | | -| | |_ _||_ _| | || | / \ | || | |_ _||_ _| | | -| | \ \ / / | || | / /\ \ | || | \ \ / / | | -| | \ \/ / | || | / ____ \ | || | \ \/ / | | -| | _| |_ | || | _/ / \ \_ | || | _| |_ | | -| | |______| | || ||____| |____|| || | |______| | | -| | | || | | || | | | -| '--------------' || '--------------' || '--------------' | - '----------------' '----------------' '----------------' diff --git a/fixtures/workers-with-assets/src/index.ts b/fixtures/workers-with-assets/src/index.ts deleted file mode 100644 index a1ff32162e..0000000000 --- a/fixtures/workers-with-assets/src/index.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { WorkerEntrypoint } from "cloudflare:workers"; - -export interface Env { - // Example binding to a Service. Learn more at https://developers.cloudflare.com/workers/runtime-apis/service-bindings/ - ASSETS: Fetcher; - NAMED: Fetcher; -} - -export default { - async fetch(request: Request, env: Env): Promise { - const url = new URL(request.url); - if (url.pathname === "/assets-binding") { - return await env.ASSETS.fetch(new URL("binding.html", request.url)); - } - - if (url.pathname === "/named-entrypoint") { - const res = await env.NAMED.sayHello(); - return new Response(res); - } - // 404s from the Asset Worker will return this: - return new Response( - "There were no assets at this route! Hello from the user Worker instead!" + - `\n${new Date()}` - ); - }, -}; - -export class NamedEntrypoint extends WorkerEntrypoint { - async sayHello() { - return "hello from a named entrypoint"; - } -} diff --git a/fixtures/workers-with-assets/tests/index.test.ts b/fixtures/workers-with-assets/tests/index.test.ts deleted file mode 100644 index ff2b68f9c7..0000000000 --- a/fixtures/workers-with-assets/tests/index.test.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { readFileSync } from "node:fs"; -import { join, resolve } from "node:path"; -import { fetch } from "undici"; -import { afterAll, beforeAll, describe, it, onTestFinished } from "vitest"; -import { runWranglerDev } from "../../shared/src/run-wrangler-long-lived"; - -describe("[Workers + Assets] dynamic site", () => { - let ip: string, port: number, stop: (() => Promise) | undefined; - - beforeAll(async () => { - ({ ip, port, stop } = await runWranglerDev(resolve(__dirname, ".."), [ - "--port=0", - "--inspector-port=0", - ])); - }); - - afterAll(async () => { - await stop?.(); - }); - - it("should respond with static asset content", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/index.html`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(text).toContain(`

Hello Workers + Assets World 🚀!

`); - - response = await fetch(`http://${ip}:${port}/about/index.html`); - text = await response.text(); - expect(response.status).toBe(200); - expect(text).toContain(`

Learn more about Workers with Assets soon!

`); - }); - - it("should fallback to the user Worker if there are no assets at a given path ", async ({ - expect, - }) => { - // Requests should hit the Asset Worker *first*, then try the user Worker - const response = await fetch(`http://${ip}:${port}/no-assets-here`); - const text = await response.text(); - expect(text).toContain( - "There were no assets at this route! Hello from the user Worker instead!" - ); - }); - - // html_handling defaults to 'auto-trailing-slash' - it("should `/` resolve to `/index.html` ", async ({ expect }) => { - const response = await fetch(`http://${ip}:${port}/`); - const text = await response.text(); - expect(text).toContain("

Hello Workers + Assets World 🚀!

"); - }); - - it("should handle content types correctly on asset routes", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/index.html`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(response.headers.get("Content-Type")).toBe( - "text/html; charset=utf-8" - ); - - response = await fetch(`http://${ip}:${port}/README.md`); - text = await response.text(); - expect(response.status).toBe(200); - expect(response.headers.get("Content-Type")).toBe( - "text/markdown; charset=utf-8" - ); - expect(text).toContain(`Welcome to Workers + Assets YAY!`); - - response = await fetch(`http://${ip}:${port}/yay.txt`); - text = await response.text(); - expect(response.status).toBe(200); - expect(response.headers.get("Content-Type")).toBe( - "text/plain; charset=utf-8" - ); - expect(text).toContain(`.----------------.`); - - response = await fetch(`http://${ip}:${port}/lava-lamps.jpg`); - expect(response.status).toBe(200); - expect(response.headers.get("Content-Type")).toBe("image/jpeg"); - - response = await fetch(`http://${ip}:${port}/totallyinvalidextension.greg`); - expect(response.status).toBe(200); - expect(response.headers.has("Content-Type")).toBeFalsy(); - }); - - it("should return 405 for non-GET or HEAD requests on routes where assets exist", async ({ - expect, - }) => { - // these should return the error and NOT be forwarded onto the user Worker - // POST etc. request -> RW -> AW -> check manifest --405--> RW --405--> eyeball - - // methods as per https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods - // excl. TRACE and CONNECT which are not supported - - let response = await fetch(`http://${ip}:${port}/index.html`, { - method: "POST", - }); - expect(response.status).toBe(405); - expect(response.statusText).toBe("Method Not Allowed"); - - response = await fetch(`http://${ip}:${port}/index.html`, { - method: "PUT", - }); - expect(response.status).toBe(405); - expect(response.statusText).toBe("Method Not Allowed"); - - response = await fetch(`http://${ip}:${port}/index.html`, { - method: "DELETE", - }); - expect(response.status).toBe(405); - expect(response.statusText).toBe("Method Not Allowed"); - - response = await fetch(`http://${ip}:${port}/index.html`, { - method: "OPTIONS", - }); - expect(response.status).toBe(405); - expect(response.statusText).toBe("Method Not Allowed"); - - response = await fetch(`http://${ip}:${port}/index.html`, { - method: "PATCH", - }); - expect(response.status).toBe(405); - expect(response.statusText).toBe("Method Not Allowed"); - }); - - it("should work with encoded path names", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/about/[fünky].txt`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(response.url).toBe( - `http://${ip}:${port}/about/%5Bf%C3%BCnky%5D.txt` - ); - expect(text).toContain(`This should work.`); - - response = await fetch(`http://${ip}:${port}/about/[boop]`); - text = await response.text(); - expect(response.status).toBe(200); - expect(response.url).toBe(`http://${ip}:${port}/about/%5Bboop%5D`); - expect(text).toContain(`[boop].html`); - - response = await fetch(`http://${ip}:${port}/about/%5Bboop%5D`); - text = await response.text(); - expect(response.status).toBe(200); - expect(text).toContain(`[boop].html`); - - response = await fetch(`http://${ip}:${port}/about/%255Bboop%255D`); - text = await response.text(); - expect(response.status).toBe(200); - expect(text).toContain(`%5Bboop%5D.html`); - }); - - it("should forward all request types to the user Worker if there are *not* assets on that route", async ({ - expect, - }) => { - // Unlike above, if the AW does NOT find assets on a route, non-GET request should return 404s - // This is because all requests are first sent to the AW and only then to the UW - // and we don't want to 405 on a valid POST request intended for the UW - // POST etc. request -> RW -> AW -> checks manifest --404--> RW -> UW -> response - - let response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "GET", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "HEAD", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "POST", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "PUT", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "DELETE", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "OPTIONS", - }); - expect(response.status).toBe(200); - - response = await fetch(`http://${ip}:${port}/no-assets-here`, { - method: "PATCH", - }); - expect(response.status).toBe(200); - }); - - it("should be able to use an ASSETS binding", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/assets-binding`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(response.headers.get("Content-Type")).toBe( - "text/html; charset=utf-8" - ); - expect(text).toContain("

✨This is from a user Worker binding✨

"); - }); - - it("should be able to use a binding to a named entrypoint", async ({ - expect, - }) => { - let response = await fetch(`http://${ip}:${port}/named-entrypoint`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(text).toContain("hello from a named entrypoint"); - }); - - it("should apply custom redirects", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/foo`, { - redirect: "manual", - }); - expect(response.status).toBe(302); - expect(response.headers.get("Location")).toBe("/bar"); - - response = await fetch(`http://${ip}:${port}/pic`); - expect(response.status).toBe(200); - expect(await response.arrayBuffer()).toEqual( - readFileSync(join(__dirname, "../public/lava-lamps.jpg")).buffer - ); - }); - - it("should apply custom headers", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/`); - expect(response.status).toBe(200); - expect(response.headers.get("X-Header")).toBe("Custom-Value"); - }); - - it("should apply .assetsignore", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/.assetsignore`); - expect(await response.text()).not.toContain("ignore-me.txt"); - - response = await fetch(`http://${ip}:${port}/ignore-me.txt`); - expect(await response.text()).not.toContain("SECRET"); - - response = await fetch(`http://${ip}:${port}/_headers`); - expect(await response.text()).not.toContain("X-Header"); - }); - - it.todo("should warn of _worker.js", async () => { - // let response = await fetch(`http://${ip}:${port}/_worker.js`); - // expect(await response.text()).not.toContain("bang"); - }); - - it("should work with files which start with .", async ({ expect }) => { - let response = await fetch(`http://${ip}:${port}/.dot`); - let text = await response.text(); - expect(response.status).toBe(200); - expect(text).toMatchInlineSnapshot(` - "hi from .dot/index.html - " - `); - - response = await fetch(`http://${ip}:${port}/.dotfile.html`); - text = await response.text(); - expect(response.status).toBe(200); - expect(text).toMatchInlineSnapshot(` - "hi from .dotfile.html - " - `); - }); -}); - -describe("[Workers + Assets] logging", () => { - it("should log _headers and _redirects parsing", async ({ expect }) => { - const { ip, port, stop, getOutput } = await runWranglerDev( - resolve(__dirname, ".."), - ["--port=0", "--inspector-port=0"] - ); - - // Await a request to ensure the logs have been written - await fetch(`http://${ip}:${port}/`); - - expect(getOutput()).toContain( - `[wrangler:info] ✨ Parsed 2 valid redirect rules.` - ); - expect(getOutput()).toContain( - `[wrangler:info] ✨ Parsed 1 valid header rule.` - ); - onTestFinished(() => stop()); - }); - - it("should not log _headers and _redirects parsing when log level set to none", async ({ - expect, - }) => { - const { ip, port, stop, getOutput } = await runWranglerDev( - resolve(__dirname, ".."), - ["--port=0", "--inspector-port=0", "--log-level=none"] - ); - expect(getOutput()).toMatchInlineSnapshot(`""`); - onTestFinished(() => stop()); - }); -}); diff --git a/fixtures/workers-with-assets/tests/tsconfig.json b/fixtures/workers-with-assets/tests/tsconfig.json deleted file mode 100644 index be0dabdb19..0000000000 --- a/fixtures/workers-with-assets/tests/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["**/*.ts"] -} diff --git a/fixtures/workers-with-assets/tsconfig.json b/fixtures/workers-with-assets/tsconfig.json deleted file mode 100644 index 6112e71504..0000000000 --- a/fixtures/workers-with-assets/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "preserve", - "lib": ["ES2020"], - "types": ["@cloudflare/workers-types"], - "moduleResolution": "node", - "noEmit": true, - "skipLibCheck": true - }, - "include": ["**/*.ts"], - "exclude": ["tests"] -} diff --git a/fixtures/workers-with-assets/vitest.config.mts b/fixtures/workers-with-assets/vitest.config.mts deleted file mode 100644 index 846cddc419..0000000000 --- a/fixtures/workers-with-assets/vitest.config.mts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject, mergeConfig } from "vitest/config"; -import configShared from "../../vitest.shared"; - -export default mergeConfig( - configShared, - defineProject({ - test: {}, - }) -); diff --git a/fixtures/workers-with-assets/wrangler.jsonc b/fixtures/workers-with-assets/wrangler.jsonc deleted file mode 100644 index eca8be6c50..0000000000 --- a/fixtures/workers-with-assets/wrangler.jsonc +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "worker-with-assets", - "main": "src/index.ts", - "compatibility_date": "2024-12-12", - "assets": { - "directory": "./public", - "binding": "ASSETS", - "run_worker_first": false, - }, - "services": [ - { - "binding": "NAMED", - "service": "worker-with-assets", - "entrypoint": "NamedEntrypoint", - }, - ], -} diff --git a/fixtures/workflow-multiple/package.json b/fixtures/workflow-multiple/package.json deleted file mode 100644 index 2d7d6e5c7a..0000000000 --- a/fixtures/workflow-multiple/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "@fixture/workflow-multiple", - "private": true, - "scripts": { - "deploy": "wrangler deploy", - "start": "wrangler dev", - "test:ci": "vitest run" - }, - "devDependencies": { - "@cloudflare/workers-types": "catalog:default", - "typescript": "catalog:default", - "undici": "catalog:default", - "vitest": "catalog:default", - "wrangler": "workspace:*" - } -} diff --git a/fixtures/workflow-multiple/src/index.ts b/fixtures/workflow-multiple/src/index.ts deleted file mode 100644 index 93ed497540..0000000000 --- a/fixtures/workflow-multiple/src/index.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { - WorkerEntrypoint, - WorkflowEntrypoint, - WorkflowEvent, - WorkflowStep, -} from "cloudflare:workers"; - -type Params = { - name: string; -}; - -export class Demo extends WorkflowEntrypoint<{}, Params> { - async run(event: WorkflowEvent, step: WorkflowStep) { - const { timestamp, payload } = event; - - await step.sleep("Wait", "1 second"); - - const result = await step.do("First step", async function () { - return { - output: "First step result", - }; - }); - - await step.sleep("Wait", "1 second"); - - const result2 = await step.do("Second step", async function () { - return { - output: "workflow1", - }; - }); - - return "i'm workflow1"; - } -} - -export class Demo2 extends WorkflowEntrypoint<{}, Params> { - async run(event: WorkflowEvent, step: WorkflowStep) { - const { timestamp, payload } = event; - - await step.sleep("Wait", "1 second"); - - const result = await step.do("First step", async function () { - return { - output: "First step result", - }; - }); - - await step.sleep("Wait", "1 second"); - - const result2 = await step.do("Second step", async function () { - return { - output: "workflow2", - }; - }); - - return "i'm workflow2"; - } -} - -export class Demo3 extends WorkflowEntrypoint<{}, Params> { - async run(event: WorkflowEvent, step: WorkflowStep) { - const result = await step.do("First step", async function () { - return { - output: "First step result", - }; - }); - - await step.waitForEvent("wait for signal", { - type: "continue", - }); - - const result2 = await step.do("Second step", async function () { - return { - output: "workflow3", - }; - }); - - return "i'm workflow3"; - } -} - -type Env = { - WORKFLOW: Workflow; - WORKFLOW2: Workflow; - WORKFLOW3: Workflow; -}; - -// Deterministic ids are unique: create() throws once the instance exists, so -// read the existing instance instead. Any other failure is real and surfaces. -async function createOrGet( - workflow: Workflow, - options: WorkflowInstanceCreateOptions -): Promise { - try { - return await workflow.create(options); - } catch (e) { - if ( - options.id === undefined || - !(e instanceof Error) || - !e.message.includes("instance.already_exists") - ) { - throw e; - } - return workflow.get(options.id); - } -} - -export default class extends WorkerEntrypoint { - async fetch(req: Request) { - const url = new URL(req.url); - const id = url.searchParams.get("id"); - const workflowName = url.searchParams.get("workflowName"); - - if (url.pathname === "/favicon.ico") { - return new Response(null, { status: 404 }); - } - - let workflowToUse: Workflow; - if (workflowName === "3") { - workflowToUse = this.env.WORKFLOW3; - } else if (workflowName === "2") { - workflowToUse = this.env.WORKFLOW2; - } else { - workflowToUse = this.env.WORKFLOW; - } - - let handle: WorkflowInstance; - if (url.pathname === "/create") { - if (id === null) { - handle = await workflowToUse.create(); - } else { - handle = await createOrGet(workflowToUse, { id }); - } - } else if (url.pathname === "/pause") { - handle = await workflowToUse.get(id); - await handle.pause(); - } else if (url.pathname === "/resume") { - handle = await workflowToUse.get(id); - await handle.resume(); - } else if (url.pathname === "/restart") { - handle = await workflowToUse.get(id); - await handle.restart(); - } else if (url.pathname === "/terminate") { - handle = await workflowToUse.get(id); - await handle.terminate(); - } else if (url.pathname === "/sendEvent") { - handle = await workflowToUse.get(id); - await handle.sendEvent({ - type: "continue", - payload: await req.json(), - }); - return Response.json({ ok: true }); - } else { - handle = await workflowToUse.get(id); - } - - return Response.json({ status: await handle.status(), id: handle.id }); - } -} diff --git a/fixtures/workflow-multiple/tests/index.test.ts b/fixtures/workflow-multiple/tests/index.test.ts deleted file mode 100644 index 410d17dd6f..0000000000 --- a/fixtures/workflow-multiple/tests/index.test.ts +++ /dev/null @@ -1,244 +0,0 @@ -import { randomUUID } from "crypto"; -import { rm } from "fs/promises"; -import { resolve } from "path"; -import { fetch } from "undici"; -import { afterAll, beforeAll, describe, it, test, vi } from "vitest"; -import { runWranglerDev } from "../../shared/src/run-wrangler-long-lived"; - -describe("Workflows", () => { - let ip: string, - port: number, - stop: (() => Promise) | undefined, - getOutput: () => string; - - beforeAll(async () => { - // delete previous run contents because of persistence - await rm(resolve(__dirname, "..") + "/.wrangler", { - force: true, - recursive: true, - }); - ({ ip, port, stop, getOutput } = await runWranglerDev( - resolve(__dirname, ".."), - ["--port=0", "--inspector-port=0"] - )); - }); - - afterAll(async () => { - await stop?.(); - }); - - async function fetchJson(url: string, body?: unknown, method?: string) { - const response = await fetch(url, { - headers: { - "MF-Disable-Pretty-Error": "1", - }, - method: method ?? "GET", - body: body !== undefined ? JSON.stringify(body) : undefined, - }); - const text = await response.text(); - - try { - return JSON.parse(text); - } catch (err) { - throw new Error(`Couldn't parse JSON:\n\n${text}`); - } - } - - it("creates two instances with same id in two different workflows", async ({ - expect, - }) => { - // Create both workflow instances - // Note: We don't assert the intermediate "running" status because the workflow - // may complete before we can observe it, causing flaky tests on fast CI machines - await Promise.all([ - fetchJson(`http://${ip}:${port}/create?workflowName=1&id=test`), - fetchJson(`http://${ip}:${port}/create?workflowName=2&id=test`), - ]); - - // Wait for both workflows to complete with their final outputs - await Promise.all([ - vi.waitFor( - async () => { - await expect( - fetchJson(`http://${ip}:${port}/status?workflowName=1&id=test`) - ).resolves.toStrictEqual({ - id: "test", - status: { - status: "complete", - __LOCAL_DEV_STEP_OUTPUTS: [ - { output: "First step result" }, - { output: "workflow1" }, - ], - output: "i'm workflow1", - }, - }); - }, - { timeout: 10000 } - ), - vi.waitFor( - async () => { - await expect( - fetchJson(`http://${ip}:${port}/status?workflowName=2&id=test`) - ).resolves.toStrictEqual({ - id: "test", - status: { - status: "complete", - __LOCAL_DEV_STEP_OUTPUTS: [ - { output: "First step result" }, - { output: "workflow2" }, - ], - output: "i'm workflow2", - }, - }); - }, - { timeout: 10000 } - ), - ]); - }); - - describe("instance lifecycle methods (workflow3)", () => { - test("pause and resume a workflow", async ({ expect }) => { - const id = randomUUID(); - - await fetchJson(`http://${ip}:${port}/create?workflowName=3&id=${id}`); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { - status: { - __LOCAL_DEV_STEP_OUTPUTS: { output: string }[]; - }; - }; - expect(result.status.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Pause the instance - await fetchJson(`http://${ip}:${port}/pause?workflowName=3&id=${id}`); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { status: { status: string } }; - expect(result.status.status).toBe("paused"); - }, - { timeout: 5000 } - ); - - // Resume the instance - await fetchJson(`http://${ip}:${port}/resume?workflowName=3&id=${id}`); - - await fetchJson( - `http://${ip}:${port}/sendEvent?workflowName=3&id=${id}`, - { done: true }, - "POST" - ); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { status: { status: string; output: string } }; - expect(result.status.status).toBe("complete"); - expect(result.status.output).toBe("i'm workflow3"); - }, - { timeout: 5000 } - ); - }); - - test("terminate a running workflow", async ({ expect }) => { - const id = randomUUID(); - - await fetchJson(`http://${ip}:${port}/create?workflowName=3&id=${id}`); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { - status: { - __LOCAL_DEV_STEP_OUTPUTS: { output: string }[]; - }; - }; - expect(result.status.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Terminate - await fetchJson(`http://${ip}:${port}/terminate?workflowName=3&id=${id}`); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { status: { status: string } }; - expect(result.status.status).toBe("terminated"); - }, - { timeout: 5000 } - ); - }); - - test("restart a running workflow", async ({ expect }) => { - const id = randomUUID(); - - await fetchJson(`http://${ip}:${port}/create?workflowName=3&id=${id}`); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { - status: { - __LOCAL_DEV_STEP_OUTPUTS: { output: string }[]; - }; - }; - expect(result.status.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Restart the instance - await fetchJson(`http://${ip}:${port}/restart?workflowName=3&id=${id}`); - - // After restart, wait for it to be running again - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { status: { status: string } }; - expect(result.status.status).toBe("running"); - }, - { timeout: 5000 } - ); - - // Send event to complete the restarted workflow - await fetchJson( - `http://${ip}:${port}/sendEvent?workflowName=3&id=${id}`, - { done: true }, - "POST" - ); - - await vi.waitFor( - async () => { - const result = (await fetchJson( - `http://${ip}:${port}/status?workflowName=3&id=${id}` - )) as { status: { status: string; output: string } }; - expect(result.status.status).toBe("complete"); - expect(result.status.output).toBe("i'm workflow3"); - }, - { timeout: 5000 } - ); - }); - }); -}); diff --git a/fixtures/workflow-multiple/tests/tsconfig.json b/fixtures/workflow-multiple/tests/tsconfig.json deleted file mode 100644 index be0dabdb19..0000000000 --- a/fixtures/workflow-multiple/tests/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["**/*.ts"] -} diff --git a/fixtures/workflow-multiple/tsconfig.json b/fixtures/workflow-multiple/tsconfig.json deleted file mode 100644 index 6112e71504..0000000000 --- a/fixtures/workflow-multiple/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "preserve", - "lib": ["ES2020"], - "types": ["@cloudflare/workers-types"], - "moduleResolution": "node", - "noEmit": true, - "skipLibCheck": true - }, - "include": ["**/*.ts"], - "exclude": ["tests"] -} diff --git a/fixtures/workflow-multiple/vitest.config.mts b/fixtures/workflow-multiple/vitest.config.mts deleted file mode 100644 index 846cddc419..0000000000 --- a/fixtures/workflow-multiple/vitest.config.mts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject, mergeConfig } from "vitest/config"; -import configShared from "../../vitest.shared"; - -export default mergeConfig( - configShared, - defineProject({ - test: {}, - }) -); diff --git a/fixtures/workflow-multiple/wrangler.jsonc b/fixtures/workflow-multiple/wrangler.jsonc deleted file mode 100644 index 08061b67eb..0000000000 --- a/fixtures/workflow-multiple/wrangler.jsonc +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "my-workflow-demo", - "main": "src/index.ts", - "compatibility_date": "2024-10-22", - "workflows": [ - { - "binding": "WORKFLOW", - "name": "my-workflow", - "class_name": "Demo", - }, - { - "binding": "WORKFLOW2", - "name": "my-workflow-2", - "class_name": "Demo2", - }, - { - "binding": "WORKFLOW3", - "name": "my-workflow-3", - "class_name": "Demo3", - }, - ], -} diff --git a/fixtures/workflow/package.json b/fixtures/workflow/package.json deleted file mode 100644 index 316ad79898..0000000000 --- a/fixtures/workflow/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "@fixture/workflow-single", - "private": true, - "scripts": { - "deploy": "wrangler deploy", - "start": "wrangler dev", - "test:ci": "vitest run" - }, - "devDependencies": { - "@cloudflare/workers-tsconfig": "workspace:*", - "@cloudflare/workers-types": "catalog:default", - "typescript": "catalog:default", - "undici": "catalog:default", - "vitest": "catalog:default", - "wrangler": "workspace:*" - } -} diff --git a/fixtures/workflow/src/index.ts b/fixtures/workflow/src/index.ts deleted file mode 100644 index a58cd1b051..0000000000 --- a/fixtures/workflow/src/index.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { - WorkerEntrypoint, - WorkflowBackoff, - WorkflowEntrypoint, - WorkflowEvent, - WorkflowStep, -} from "cloudflare:workers"; -import { NonRetryableError } from "cloudflare:workflows"; - -type Params = { - name: string; -}; - -export class Demo extends WorkflowEntrypoint<{}, Params> { - async run(event: WorkflowEvent, step: WorkflowStep) { - const { timestamp, payload } = event; - - const result = await step.do("First step", async function () { - return { - output: "First step result", - }; - }); - - await step.sleep("Wait", "1 second"); - - const result2 = await step.do("Second step", async function () { - return { - output: "Second step result", - }; - }); - - return payload ?? "no-payload"; - } -} - -export class Demo2 extends WorkflowEntrypoint<{}, Params> { - async run(event: WorkflowEvent, step: WorkflowStep) { - const { timestamp, payload } = event; - - const result = await step.do("First step", async function () { - return { - output: "First step result", - }; - }); - - await step.waitForEvent("event-1 provider", { - type: "event-1", - }); - - const result2 = await step.do("Second step", async function () { - return { - output: "Second step result", - }; - }); - - return payload ?? "no-payload"; - } -} - -export class Demo3 extends WorkflowEntrypoint<{}, Params> { - async run( - event: WorkflowEvent, - step: WorkflowStep - ) { - let runs = -1; - try { - await step.do( - "First (and only step) step", - { - retries: { - limit: 3, - delay: 100, - }, - }, - async function () { - runs++; - if (event.payload.doRetry) { - throw new Error(event.payload.errorMessage); - } else { - throw new NonRetryableError(event.payload.errorMessage); - } - } - ); - } catch {} - - return `The step was retried ${runs} time${runs === 1 ? "" : "s"}`; - } -} - -type Env = { - WORKFLOW: Workflow; - WORKFLOW2: Workflow; - WORKFLOW3: Workflow<{ doRetry: boolean; errorMessage: string }>; -}; - -// Deterministic ids are unique: create() throws once the instance exists, so -// read the existing instance instead. Any other failure is real and surfaces. -async function createOrGet( - workflow: Workflow, - options: WorkflowInstanceCreateOptions -): Promise { - try { - return await workflow.create(options); - } catch (e) { - if ( - options.id === undefined || - !(e instanceof Error) || - !e.message.includes("instance.already_exists") - ) { - throw e; - } - return workflow.get(options.id); - } -} -export default class extends WorkerEntrypoint { - async fetch(req: Request) { - const url = new URL(req.url); - const id = url.searchParams.get("workflowName"); - const doRetry = url.searchParams.get("doRetry"); - const errorMessage = url.searchParams.get("errorMessage"); - - if (url.pathname === "/favicon.ico") { - return new Response(null, { status: 404 }); - } - - let handle: WorkflowInstance; - if (url.pathname === "/createBatch") { - // creates two instances; ids that already exist are skipped and - // excluded from createBatch's return, so read handles for the full - // set to keep this endpoint idempotent across repeat requests - const ids = ["batch-1", "batch-2"]; - await this.env.WORKFLOW.createBatch([ - { id: "batch-1", params: "1" }, - { id: "batch-2", params: "2" }, - ]); - const handles = await Promise.all( - ids.map((batchId) => this.env.WORKFLOW.get(batchId)) - ); - return Response.json(handles.map((instance) => instance.id)); - } else if (url.pathname === "/create") { - if (id === null) { - handle = await this.env.WORKFLOW.create(); - } else { - handle = await createOrGet(this.env.WORKFLOW, { id }); - } - } else if (url.pathname === "/createDemo2") { - if (id === null) { - handle = await this.env.WORKFLOW2.create(); - } else { - handle = await createOrGet(this.env.WORKFLOW2, { id }); - } - } else if (url.pathname === "/createDemo3") { - if (id === null) { - handle = await this.env.WORKFLOW3.create(); - } else { - handle = await createOrGet(this.env.WORKFLOW3, { - id, - params: { - doRetry: doRetry === "false" ? false : true, - errorMessage: errorMessage ?? "", - }, - }); - } - } else if (url.pathname === "/sendEvent") { - handle = await this.env.WORKFLOW2.get(id); - - await handle.sendEvent({ - type: "event-1", - payload: await req.json(), - }); - } else if (url.pathname === "/pause") { - handle = await this.env.WORKFLOW2.get(id); - await handle.pause(); - } else if (url.pathname === "/resume") { - handle = await this.env.WORKFLOW2.get(id); - await handle.resume(); - } else if (url.pathname === "/restart") { - handle = await this.env.WORKFLOW2.get(id); - await handle.restart(); - } else if (url.pathname === "/terminate") { - handle = await this.env.WORKFLOW2.get(id); - await handle.terminate(); - } else if (url.pathname === "/get2") { - handle = await this.env.WORKFLOW2.get(id); - } else if (url.pathname === "/get3") { - handle = await this.env.WORKFLOW3.get(id); - } else if (url.pathname === "/createWithRedirect") { - console.log("create with redirect called"); - handle = await this.env.WORKFLOW.create(); - - return Response.redirect( - new URL(`/status?workflowName=${handle.id}`, url).toString(), - 302 - ); - } else if (url.pathname === "/status") { - handle = await this.env.WORKFLOW.get(id); - } - - return Response.json(await handle.status()); - } -} diff --git a/fixtures/workflow/tests/index.test.ts b/fixtures/workflow/tests/index.test.ts deleted file mode 100644 index d3337fc5b9..0000000000 --- a/fixtures/workflow/tests/index.test.ts +++ /dev/null @@ -1,699 +0,0 @@ -import { randomUUID } from "crypto"; -import { rm } from "fs/promises"; -import { fork } from "node:child_process"; -import { resolve } from "path"; -import { fetch } from "undici"; -import { afterAll, beforeAll, describe, it, test, vi } from "vitest"; -import { - runWranglerDev, - wranglerEntryPath, -} from "../../shared/src/run-wrangler-long-lived"; - -describe("Workflows", () => { - let ip: string, - port: number, - stop: (() => Promise) | undefined, - getOutput: () => string; - - beforeAll(async () => { - // delete previous run contents because of persistence - await rm(resolve(__dirname, "..") + "/.wrangler", { - force: true, - recursive: true, - }); - ({ ip, port, stop, getOutput } = await runWranglerDev( - resolve(__dirname, ".."), - ["--port=0", "--inspector-port=0"] - )); - }); - - afterAll(async () => { - await stop?.(); - }); - - async function fetchJson(url: string, body?: unknown, method?: string) { - const response = await fetch(url, { - headers: { - "MF-Disable-Pretty-Error": "1", - }, - method: method ?? "GET", - body: body !== undefined ? JSON.stringify(body) : undefined, - }); - const text = await response.text(); - - try { - return JSON.parse(text); - } catch (err) { - throw new Error(`Couldn't parse JSON:\n\n${text}`); - } - } - - it("creates a workflow with id", async ({ expect }) => { - await expect(fetchJson(`http://${ip}:${port}/create?workflowName=test`)) - .resolves.toMatchInlineSnapshot(` - { - "__LOCAL_DEV_STEP_OUTPUTS": [ - { - "output": "First step result", - }, - ], - "output": null, - "status": "running", - } - `); - - await vi.waitFor( - async () => { - await expect(fetchJson(`http://${ip}:${port}/status?workflowName=test`)) - .resolves.toMatchInlineSnapshot(` - { - "__LOCAL_DEV_STEP_OUTPUTS": [ - { - "output": "First step result", - }, - ], - "output": null, - "status": "running", - } - `); - }, - { timeout: 5000 } - ); - }); - - it("creates a workflow without id", async ({ expect }) => { - await expect(fetchJson(`http://${ip}:${port}/create`)).resolves - .toMatchInlineSnapshot(` - { - "__LOCAL_DEV_STEP_OUTPUTS": [ - { - "output": "First step result", - }, - ], - "output": null, - "status": "running", - } - `); - }); - - it("fails getting a workflow without creating it first", async ({ - expect, - }) => { - await expect( - fetchJson(`http://${ip}:${port}/status?workflowName=anotherTest`) - ).resolves.toMatchObject({ - message: "instance.not_found", - name: "Error", - }); - }); - - test("batchCreate should create multiple instances and run them separately", async ({ - expect, - }) => { - await expect(fetchJson(`http://${ip}:${port}/createBatch`)).resolves - .toMatchInlineSnapshot(` - [ - "batch-1", - "batch-2", - ] - `); - - await Promise.all([ - vi.waitFor( - async () => { - await expect( - fetchJson(`http://${ip}:${port}/status?workflowName=batch-1`) - ).resolves.toStrictEqual({ - status: "complete", - __LOCAL_DEV_STEP_OUTPUTS: [ - { output: "First step result" }, - { output: "Second step result" }, - ], - output: "1", - }); - }, - { timeout: 5000 } - ), - vi.waitFor( - async () => { - await expect( - fetchJson(`http://${ip}:${port}/status?workflowName=batch-2`) - ).resolves.toStrictEqual({ - status: "complete", - __LOCAL_DEV_STEP_OUTPUTS: [ - { output: "First step result" }, - { output: "Second step result" }, - ], - output: "2", - }); - }, - { timeout: 5000 } - ), - ]); - }); - - describe("retrying a step", () => { - test("should retry a step if a generic Error (with a generic error message) is thrown", async ({ - expect, - }) => { - const name = randomUUID(); - await fetchJson( - `http://${ip}:${port}/createDemo3?workflowName=${name}&doRetry=true&errorMessage=generic_error_message` - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get3?workflowName=${name}` - ); - - expect(result["output"]).toEqual("The step was retried 3 times"); - }, - { timeout: 1500 } - ); - }); - - test("should retry a step if a generic Error (with an empty error message) is thrown", async ({ - expect, - }) => { - const name = randomUUID(); - await fetchJson( - `http://${ip}:${port}/createDemo3?workflowName=${name}&doRetry=true&errorMessage=` - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get3?workflowName=${name}` - ); - - expect(result["output"]).toEqual("The step was retried 3 times"); - }, - { timeout: 1500 } - ); - }); - - test("should not retry a step if a NonRetryableError (with a generic error message) is thrown", async ({ - expect, - }) => { - const name = randomUUID(); - await fetchJson( - `http://${ip}:${port}/createDemo3?workflowName=${name}&doRetry=false&errorMessage=generic_error_message` - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get3?workflowName=${name}` - ); - - expect(result["output"]).toEqual("The step was retried 0 times"); - }, - { timeout: 1500 } - ); - }); - - test("should not retry a step if a NonRetryableError (with an empty error message) is thrown", async ({ - expect, - }) => { - const name = randomUUID(); - await fetchJson( - `http://${ip}:${port}/createDemo3?workflowName=${name}&doRetry=false&errorMessage=` - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get3?workflowName=${name}` - ); - - expect(result["output"]).toEqual("The step was retried 0 times"); - }, - { timeout: 1500 } - ); - }); - }); - - test("waitForEvent should work", async ({ expect }) => { - await fetchJson(`http://${ip}:${port}/createDemo2?workflowName=something`); - - await fetchJson( - `http://${ip}:${port}/sendEvent?workflowName=something`, - { event: true }, - "POST" - ); - - await vi.waitFor( - async () => { - await expect( - fetchJson(`http://${ip}:${port}/get2?workflowName=something`) - ).resolves.toMatchInlineSnapshot(` - { - "__LOCAL_DEV_STEP_OUTPUTS": [ - { - "output": "First step result", - }, - { - "event": true, - }, - { - "output": "Second step result", - }, - ], - "output": {}, - "status": "complete", - } - `); - }, - { timeout: 5000 } - ); - }); - - describe("instance lifecycle methods", () => { - test("pause and resume a workflow", async ({ expect }) => { - const name = randomUUID(); - - await fetchJson(`http://${ip}:${port}/createDemo2?workflowName=${name}`); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 1500 } - ); - - // Pause the instance - await fetchJson(`http://${ip}:${port}/pause?workflowName=${name}`); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.status).toBe("paused"); - }, - { timeout: 1500 } - ); - - // Resume the instance - await fetchJson(`http://${ip}:${port}/resume?workflowName=${name}`); - - await fetchJson( - `http://${ip}:${port}/sendEvent?workflowName=${name}`, - { event: true }, - "POST" - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.status).toBe("complete"); - }, - { timeout: 5000 } - ); - }); - - test("terminate a running workflow", async ({ expect }) => { - const name = randomUUID(); - - await fetchJson(`http://${ip}:${port}/createDemo2?workflowName=${name}`); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 1500 } - ); - - // Terminate the instance - await fetchJson(`http://${ip}:${port}/terminate?workflowName=${name}`); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.status).toBe("terminated"); - }, - { timeout: 1500 } - ); - }); - - test("restart a running workflow", async ({ expect }) => { - const name = randomUUID(); - - await fetchJson(`http://${ip}:${port}/createDemo2?workflowName=${name}`); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Restart the instance - await fetchJson(`http://${ip}:${port}/restart?workflowName=${name}`); - - // After restart, wait for it to be running again - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.status).toBe("running"); - }, - { timeout: 1500 } - ); - - // Send event to complete the restarted workflow - await fetchJson( - `http://${ip}:${port}/sendEvent?workflowName=${name}`, - { event: true }, - "POST" - ); - - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=${name}` - ); - expect(result.status).toBe("complete"); - }, - { timeout: 5000 } - ); - }); - }); - - it("should create an instance after immediate redirect", async ({ - expect, - }) => { - await expect(fetchJson(`http://${ip}:${port}/createWithRedirect`)).resolves - .toMatchInlineSnapshot(` - { - "__LOCAL_DEV_STEP_OUTPUTS": [ - { - "output": "First step result", - }, - ], - "output": null, - "status": "running", - } - `); - }); - - // ========================================================================= - // Local CLI commands (wrangler workflows ... --local --port=) - // ========================================================================= - - /** - * Run a short-lived wrangler CLI command and return its combined output. - * Merges stdout + stderr into a single `output` string (wrangler routes - * log messages across both streams depending on the logger method). - */ - function runWranglerCommand( - args: string[] - ): Promise<{ output: string; exitCode: number | null }> { - return new Promise((resolve) => { - const chunks: Buffer[] = []; - - const child = fork(wranglerEntryPath, args, { - stdio: ["ignore", "pipe", "pipe", "ipc"], - cwd: __dirname, - }); - - child.stdout?.on("data", (chunk) => chunks.push(chunk)); - child.stderr?.on("data", (chunk) => chunks.push(chunk)); - - child.on("exit", (exitCode) => { - resolve({ - output: Buffer.concat(chunks).toString(), - exitCode, - }); - }); - }); - } - - describe("local CLI commands", () => { - it("workflows list --local", async ({ expect }) => { - const result = await runWranglerCommand([ - "workflows", - "list", - "--local", - `--port=${port}`, - ]); - - expect(result.exitCode).toBe(0); - expect(result.output).toContain( - "Showing 3 workflows from local dev session:" - ); - expect(result.output).toContain("my-workflow"); - expect(result.output).toContain("my-workflow2"); - expect(result.output).toContain("my-workflow3"); - expect(result.output).toContain("my-workflow-demo"); - expect(result.output).toContain("Demo"); - expect(result.output).toContain("Demo2"); - expect(result.output).toContain("Demo3"); - }); - - it("workflows describe --local", async ({ expect }) => { - const result = await runWranglerCommand([ - "workflows", - "describe", - "my-workflow", - "--local", - `--port=${port}`, - ]); - - expect(result.exitCode).toBe(0); - expect(result.output).toContain("my-workflow"); - expect(result.output).toContain("my-workflow-demo"); - expect(result.output).toContain("Demo"); - expect(result.output).toContain("Instance Status Counts:"); - }); - - it("workflows trigger --local and instances list --local", async ({ - expect, - }) => { - const result = await runWranglerCommand([ - "workflows", - "trigger", - "my-workflow", - "--local", - `--port=${port}`, - ]); - - expect(result.exitCode).toBe(0); - expect(result.output).toContain("has been triggered successfully"); - - // Wait for the instance to register - await vi.waitFor( - async () => { - const listResult = await runWranglerCommand([ - "workflows", - "instances", - "list", - "my-workflow", - "--local", - `--port=${port}`, - ]); - - expect(listResult.exitCode).toBe(0); - expect(listResult.output).toContain("from page 1:"); - }, - { timeout: 5000 } - ); - }); - - it("workflows instances describe --local", async ({ expect }) => { - // Trigger an instance first - const triggerResult = await runWranglerCommand([ - "workflows", - "trigger", - "my-workflow", - "--local", - `--port=${port}`, - ]); - expect(triggerResult.exitCode).toBe(0); - - // Describe latest - await vi.waitFor( - async () => { - const result = await runWranglerCommand([ - "workflows", - "instances", - "describe", - "my-workflow", - "latest", - "--local", - `--port=${port}`, - ]); - - expect(result.exitCode).toBe(0); - expect(result.output).toContain("Describing latest instance:"); - expect(result.output).toContain("my-workflow"); - expect(result.output).toContain("Steps:"); - }, - { timeout: 5000 } - ); - }); - - it("workflows instances pause and resume --local", async ({ expect }) => { - // Create a Demo2 instance (has waitForEvent so it stays running) - await fetchJson( - `http://${ip}:${port}/createDemo2?workflowName=pause-resume-test` - ); - - // Wait for it to be running - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=pause-resume-test` - ); - expect(result.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Pause via CLI - const pauseResult = await runWranglerCommand([ - "workflows", - "instances", - "pause", - "my-workflow2", - "pause-resume-test", - "--local", - `--port=${port}`, - ]); - expect(pauseResult.exitCode).toBe(0); - expect(pauseResult.output).toContain( - 'The instance "pause-resume-test" from my-workflow2 was paused successfully' - ); - - // Verify paused via binding - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=pause-resume-test` - ); - expect(result.status).toBe("paused"); - }, - { timeout: 5000 } - ); - - // Resume via CLI - const resumeResult = await runWranglerCommand([ - "workflows", - "instances", - "resume", - "my-workflow2", - "pause-resume-test", - "--local", - `--port=${port}`, - ]); - expect(resumeResult.exitCode).toBe(0); - expect(resumeResult.output).toContain( - 'The instance "pause-resume-test" from my-workflow2 was resumed successfully' - ); - }); - - it("workflows instances terminate --local", async ({ expect }) => { - // Create a Demo2 instance (has waitForEvent so it stays running) - await fetchJson( - `http://${ip}:${port}/createDemo2?workflowName=terminate-test` - ); - - // Wait for it to be running - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=terminate-test` - ); - expect(result.__LOCAL_DEV_STEP_OUTPUTS).toContainEqual({ - output: "First step result", - }); - }, - { timeout: 5000 } - ); - - // Terminate via CLI - const terminateResult = await runWranglerCommand([ - "workflows", - "instances", - "terminate", - "my-workflow2", - "terminate-test", - "--local", - `--port=${port}`, - ]); - expect(terminateResult.exitCode).toBe(0); - expect(terminateResult.output).toContain( - 'The instance "terminate-test" from my-workflow2 was terminated successfully' - ); - - // Verify terminated via binding - await vi.waitFor( - async () => { - const result = await fetchJson( - `http://${ip}:${port}/get2?workflowName=terminate-test` - ); - expect(result.status).toBe("terminated"); - }, - { timeout: 5000 } - ); - }); - - it("workflows delete --local", async ({ expect }) => { - const result = await runWranglerCommand([ - "workflows", - "delete", - "my-workflow3", - "--local", - `--port=${port}`, - ]); - - expect(result.exitCode).toBe(0); - expect(result.output).toContain( - 'Workflow "my-workflow3" instances removed successfully from local dev session.' - ); - }); - }); - - it("should persist instances across lifetimes", async ({ expect }) => { - await fetchJson(`http://${ip}:${port}/create?workflowName=something`); - - await stop?.(); - - const { port: portChild2, stop: stopChild2Process } = await runWranglerDev( - resolve(__dirname, ".."), - [`--port=0`, `--inspector-port=0`] - ); - - try { - const result = await fetchJson( - `http://${ip}:${portChild2}/status?workflowName=something` - ); - expect(result).not.toBeUndefined(); - } finally { - await stopChild2Process?.(); - } - }); -}); diff --git a/fixtures/workflow/tests/tsconfig.json b/fixtures/workflow/tests/tsconfig.json deleted file mode 100644 index be0dabdb19..0000000000 --- a/fixtures/workflow/tests/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "types": ["node"] - }, - "include": ["**/*.ts"] -} diff --git a/fixtures/workflow/tsconfig.json b/fixtures/workflow/tsconfig.json deleted file mode 100644 index 6112e71504..0000000000 --- a/fixtures/workflow/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "module": "preserve", - "lib": ["ES2020"], - "types": ["@cloudflare/workers-types"], - "moduleResolution": "node", - "noEmit": true, - "skipLibCheck": true - }, - "include": ["**/*.ts"], - "exclude": ["tests"] -} diff --git a/fixtures/workflow/vitest.config.mts b/fixtures/workflow/vitest.config.mts deleted file mode 100644 index 846cddc419..0000000000 --- a/fixtures/workflow/vitest.config.mts +++ /dev/null @@ -1,9 +0,0 @@ -import { defineProject, mergeConfig } from "vitest/config"; -import configShared from "../../vitest.shared"; - -export default mergeConfig( - configShared, - defineProject({ - test: {}, - }) -); diff --git a/fixtures/workflow/wrangler.jsonc b/fixtures/workflow/wrangler.jsonc deleted file mode 100644 index bee45e9564..0000000000 --- a/fixtures/workflow/wrangler.jsonc +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "my-workflow-demo", - "main": "src/index.ts", - "compatibility_date": "2024-10-22", - "workflows": [ - { - "binding": "WORKFLOW", - "name": "my-workflow", - "class_name": "Demo", - }, - { - "binding": "WORKFLOW2", - "name": "my-workflow2", - "class_name": "Demo2", - }, - { - "binding": "WORKFLOW3", - "name": "my-workflow3", - "class_name": "Demo3", - }, - ], -} diff --git a/package.json b/package.json index 31e7dcd0ae..d6d653f852 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "@cloudflare/workers-sdk", "version": "0.0.0", "private": true, - "description": "Monorepo for wrangler and associated packages", + "description": "Maintenance workspace for Cloudflare Vite plugin v1", "homepage": "https://github.com/cloudflare/workers-sdk#readme", "bugs": { "url": "https://github.com/cloudflare/workers-sdk/issues" @@ -10,41 +10,33 @@ "license": "MIT OR Apache-2.0", "author": "wrangler@cloudflare.com", "scripts": { - "build": "dotenv -- turbo build", - "check": "pnpm check:fixtures && pnpm check:private-packages && pnpm check:package-deps && pnpm check:catalog && pnpm check:pinned-deps && pnpm check:compat-date && pnpm check:deployments && pnpm check:workflows && node lint-turbo.mjs && dotenv -- turbo check:lint check:type check:format type:tests", - "check:catalog": "node -r esbuild-register tools/deployments/validate-catalog-usage.ts", - "check:compat-date": "node -r esbuild-register tools/deployments/update-default-compat-date.ts check", - "check:deployments": "node -r esbuild-register tools/deployments/deploy-non-npm-packages.ts check", - "check:fixtures": "node -r esbuild-register tools/deployments/validate-fixtures.ts", - "check:format": "oxfmt --check", - "check:lint": "oxlint --deny-warnings --type-aware", - "check:package-deps": "pnpm build && node -r esbuild-register tools/deployments/validate-package-dependencies.ts", - "check:pinned-deps": "node -r esbuild-register tools/deployments/validate-pinned-dependencies.ts", - "check:private-packages": "node -r esbuild-register tools/deployments/validate-private-packages.ts", - "check:type": "dotenv -- turbo check:type type:tests", - "check:workflows": "node -r esbuild-register tools/github-workflow-helpers/validate-action-pinning.ts", + "build": "dotenv -- turbo build --filter @cloudflare/vite-plugin...", "dev": "dotenv -- turbo dev", - "fix": "oxlint --fix --type-aware && pnpm run prettify", + "test": "pnpm test:ci", + "test:ci": "dotenv -- turbo test:ci --filter @cloudflare/vite-plugin... --filter @cloudflare/lint-config-shared", + "test:fixtures": "dotenv -- turbo test:ci --filter \"@fixture/*\"", + "test:playgrounds": "pnpm --filter @vite-plugin-cloudflare/playground test:ci", + "test:e2e": "dotenv -- turbo test:e2e --filter @cloudflare/vite-plugin", + "check": "pnpm check:changesets && pnpm check:workflows && pnpm check:pinned-deps && pnpm check:package-deps && node lint-turbo.mjs && dotenv -- turbo check:lint check:type check:format type:tests", + "check:changesets": "node -r esbuild-register tools/deployments/validate-changesets.ts", + "check:workflows": "node -r esbuild-register tools/github-workflow-helpers/validate-action-pinning.ts", + "check:pinned-deps": "node -r esbuild-register tools/deployments/validate-pinned-dependencies.ts", + "check:package-deps": "pnpm build && node -r esbuild-register tools/deployments/validate-package-dependencies.ts", + "check:lint": "oxlint --deny-warnings --type-aware", + "check:type": "dotenv -- turbo check:type type:tests", + "check:format": "oxfmt --check", + "fix": "oxlint --fix --type-aware && pnpm prettify", "prettify": "oxfmt", - "test": "dotenv -- turbo test", - "test:ci": "dotenv -- turbo test:ci", - "test:ci:fixtures": "node -r esbuild-register tools/test/run-fixture-shard.ts", - "test:ci:logged": "node tools/test/run-with-log.cjs", - "test:e2e": "dotenv -- turbo test:e2e", - "test:e2e:c3": "dotenv -- node -r esbuild-register packages/create-cloudflare/scripts/e2e/run-tests.ts", - "test:e2e:wrangler": "dotenv -- node -r esbuild-register tools/e2e/runIndividualE2EFiles.ts", - "test:watch": "turbo test:watch", - "type:tests": "dotenv -- turbo type:tests", - "update:compat-date": "node -r esbuild-register tools/deployments/update-default-compat-date.ts", - "deprecate-packages": "node -r esbuild-register tools/deployments/deprecate.ts" + "version-packages": "pnpm exec changeset version && pnpm install --lockfile-only --ignore-scripts && pnpm prettify", + "release": "pnpm exec changeset publish" }, "dependencies": { "@changesets/changelog-github": "^0.5.0", "@changesets/cli": "^2.29.7", "@changesets/parse": "^0.4.1", - "@manypkg/cli": "^0.23.0", + "@cloudflare/lint-config-shared": "workspace:*", "@types/node": "catalog:default", - "@vue/compiler-sfc": "^3.3.4", + "@types/semver": "7.8.0", "cross-env": "^7.0.3", "dotenv-cli": "^7.3.0", "esbuild": "catalog:default", @@ -54,13 +46,16 @@ "oxfmt": "^0.68.0", "oxlint": "^1.56.0", "oxlint-tsgolint": "^0.17.0", + "semver": "7.8.5", + "tinyglobby": "0.2.17", "tree-kill": "catalog:default", "turbo": "^2.7.2", "typescript": "catalog:default", + "vite": "catalog:default", "vitest": "catalog:default" }, "engines": { - "node": ">=22.0.0", + "node": ">=22.12.0", "pnpm": "^10.33.0" }, "volta": { diff --git a/packages/autoconfig/CHANGELOG.md b/packages/autoconfig/CHANGELOG.md deleted file mode 100644 index 125f545772..0000000000 --- a/packages/autoconfig/CHANGELOG.md +++ /dev/null @@ -1,477 +0,0 @@ -# @cloudflare/autoconfig - -## 0.7.9 - -### Patch Changes - -- Updated dependencies [[`f360829`](https://github.com/cloudflare/workers-sdk/commit/f3608290da40c11b248fff40101f30fc295652be)]: - - @cloudflare/config@0.26.0 - -## 0.7.8 - -### Patch Changes - -- Updated dependencies [[`dc3e4df`](https://github.com/cloudflare/workers-sdk/commit/dc3e4df999e9d774469c6292a7b92b1f427b3dd9), [`d8b1fca`](https://github.com/cloudflare/workers-sdk/commit/d8b1fca2ba2fec3d3945fa6ec719b8f6766ad610)]: - - @cloudflare/workers-utils@0.47.2 - - @cloudflare/config@0.25.0 - - @cloudflare/cli-shared-helpers@0.2.6 - -## 0.7.7 - -### Patch Changes - -- Updated dependencies [[`aaa6a88`](https://github.com/cloudflare/workers-sdk/commit/aaa6a880682fcc33a02366d7b193474f05e36717), [`ad7ff45`](https://github.com/cloudflare/workers-sdk/commit/ad7ff45076f762253268d03c28b5384f43889999), [`b606624`](https://github.com/cloudflare/workers-sdk/commit/b6066245aaccb0a6bb718ff063df4fa5a54e4215), [`93c1069`](https://github.com/cloudflare/workers-sdk/commit/93c10696930e50e310b8b49a8e792671bf371e82)]: - - @cloudflare/config@0.24.1 - - @cloudflare/workers-utils@0.47.1 - - @cloudflare/cli-shared-helpers@0.2.5 - -## 0.7.6 - -### Patch Changes - -- Updated dependencies [[`f025bbf`](https://github.com/cloudflare/workers-sdk/commit/f025bbfddcdab0193bffffc9fe5a9bf143f2fa65), [`b75421f`](https://github.com/cloudflare/workers-sdk/commit/b75421fcd5b2d8208cefb38882479773a7387df4), [`2b1a0ca`](https://github.com/cloudflare/workers-sdk/commit/2b1a0ca78c30403934ab9df9b6264185d473b3ef), [`aa2f9b7`](https://github.com/cloudflare/workers-sdk/commit/aa2f9b73ed1177bceb83fd730eb9e47cbabc8c7f)]: - - @cloudflare/config@0.24.0 - - @cloudflare/workers-utils@0.47.0 - - @cloudflare/cli-shared-helpers@0.2.4 - -## 0.7.5 - -### Patch Changes - -- Updated dependencies [[`7f57b1c`](https://github.com/cloudflare/workers-sdk/commit/7f57b1c60002ae3f077dd9c1e8cc482371065ef4)]: - - @cloudflare/config@0.23.0 - - @cloudflare/workers-utils@0.46.0 - - @cloudflare/cli-shared-helpers@0.2.3 - -## 0.7.4 - -### Patch Changes - -- Updated dependencies [[`aee2842`](https://github.com/cloudflare/workers-sdk/commit/aee2842bd1852b3187202f7746da5fd59ed36d44)]: - - @cloudflare/workers-utils@0.45.1 - - @cloudflare/cli-shared-helpers@0.2.2 - - @cloudflare/config@0.22.0 - -## 0.7.3 - -### Patch Changes - -- Updated dependencies [[`b9f1cdc`](https://github.com/cloudflare/workers-sdk/commit/b9f1cdc198533687f6b64ce72499a3ca04b2bf85), [`a0712e5`](https://github.com/cloudflare/workers-sdk/commit/a0712e578e45908ed5e46235828a434b49cf8f22), [`27bc20d`](https://github.com/cloudflare/workers-sdk/commit/27bc20d5b22e7156b59940275bd3d809e269d7ce)]: - - @cloudflare/config@0.22.0 - - @cloudflare/workers-utils@0.45.0 - - @cloudflare/cli-shared-helpers@0.2.1 - -## 0.7.2 - -### Patch Changes - -- Updated dependencies [[`2a15ae2`](https://github.com/cloudflare/workers-sdk/commit/2a15ae21d210fcd36e485e7492b75198c8d7856c)]: - - @cloudflare/config@0.21.0 - -## 0.7.1 - -### Patch Changes - -- [#15913](https://github.com/cloudflare/workers-sdk/pull/15913) [`3ea1365`](https://github.com/cloudflare/workers-sdk/commit/3ea1365509e64786471bac5dfee37ff60e5f75ff) Thanks [@NuroDev](https://github.com/NuroDev)! - Fix the type generation script added to TypeScript projects configured for `cf`. - - The `cf-typegen` script now runs `cf workers types` instead of the unsupported `cf types` command. Projects configured for Wrangler continue to use `wrangler types`. - -## 0.7.0 - -### Minor Changes - -- [#15805](https://github.com/cloudflare/workers-sdk/pull/15805) [`3572193`](https://github.com/cloudflare/workers-sdk/commit/35721935014b6740f39e5ed4cea1af717f26e252) Thanks [@edmundhung](https://github.com/edmundhung)! - Install the beta Cloudflare Vite plugin for cf - - When targeting cf, autoconfig now installs `@cloudflare/vite-plugin@beta` so supported projects use the Vite plugin v2 prerelease instead of the latest stable release. Wrangler autoconfiguration continues to install the latest stable release. - -- [#15805](https://github.com/cloudflare/workers-sdk/pull/15805) [`3572193`](https://github.com/cloudflare/workers-sdk/commit/35721935014b6740f39e5ed4cea1af717f26e252) Thanks [@edmundhung](https://github.com/edmundhung)! - Reject frameworks that cf cannot currently configure - - Autoconfig now directs Analog, Angular, Nuxt, Qwik, Solid Start, SvelteKit, Vike, and Waku projects to Wrangler when invoked by cf, before changing project files. Wrangler autoconfiguration remains supported for these frameworks. - -### Patch Changes - -- Updated dependencies [[`cde5d99`](https://github.com/cloudflare/workers-sdk/commit/cde5d99651678cde06da6721e194d2e6a21789ff), [`77e79b2`](https://github.com/cloudflare/workers-sdk/commit/77e79b2f5f1fa6a8f8ec2b04f8b288edac64bf9f)]: - - @cloudflare/config@0.20.0 - - @cloudflare/workers-utils@0.44.0 - -## 0.6.6 - -### Patch Changes - -- [#15870](https://github.com/cloudflare/workers-sdk/pull/15870) [`8c4b8a3`](https://github.com/cloudflare/workers-sdk/commit/8c4b8a3ee8d2f6cc6df96338ee819d25a10a7394) Thanks [@dario-piotrowicz](https://github.com/dario-piotrowicz)! - Keep Node.js ESM packages working when consumers rebundle them as CommonJS - - Node.js-targeted ESM bundles now provide a real `require` implementation for bundled CommonJS dependencies. This avoids downstream patches for dynamic require calls and keeps the packages usable when a consumer rebundles them to CommonJS. - -- Updated dependencies [[`a34edd4`](https://github.com/cloudflare/workers-sdk/commit/a34edd4939479a5ae58277803178b87d9bd44b33), [`8c4b8a3`](https://github.com/cloudflare/workers-sdk/commit/8c4b8a3ee8d2f6cc6df96338ee819d25a10a7394), [`8280086`](https://github.com/cloudflare/workers-sdk/commit/8280086df5571607ab614fa09684c2d78fcdd58b), [`74a520e`](https://github.com/cloudflare/workers-sdk/commit/74a520ea55c56e8f61764bfdcff1c5aceabcfefd)]: - - @cloudflare/config@0.19.0 - - @cloudflare/workers-utils@0.44.0 - - @cloudflare/cli-shared-helpers@0.2.0 - -## 0.6.5 - -### Patch Changes - -- Updated dependencies [[`8f7916c`](https://github.com/cloudflare/workers-sdk/commit/8f7916cd72cd0f6a3bcef80abc8ad4509b13026a)]: - - @cloudflare/workers-utils@0.43.0 - - @cloudflare/cli-shared-helpers@0.1.39 - - @cloudflare/config@0.18.0 - -## 0.6.4 - -### Patch Changes - -- Updated dependencies [[`479e1e8`](https://github.com/cloudflare/workers-sdk/commit/479e1e8eaf05764da7950c42c38cff2a98f00e3f), [`15799d4`](https://github.com/cloudflare/workers-sdk/commit/15799d4b61adc6317a506d700846ebaeeb558095), [`bdda4c3`](https://github.com/cloudflare/workers-sdk/commit/bdda4c3b3c028d3d4dab5ea4c5af8040ed7ed1d8), [`fc3cbaa`](https://github.com/cloudflare/workers-sdk/commit/fc3cbaa4150a3cf30502286452153806bf8800d2)]: - - @cloudflare/workers-utils@0.42.0 - - @cloudflare/config@0.18.0 - - @cloudflare/cli-shared-helpers@0.1.38 - -## 0.6.3 - -### Patch Changes - -- [#15812](https://github.com/cloudflare/workers-sdk/pull/15812) [`b37c5df`](https://github.com/cloudflare/workers-sdk/commit/b37c5df9b23fd2c06116d54bbeaf8da65014847c) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Prevent static-site detection from failing on inaccessible child directories - - Autoconfig now checks each candidate directory's `index.html` directly and ignores expected missing-file and permission errors. This allows commands such as `cf build` to run from directories containing protected folders, including a macOS home directory with `.Trash`. - -- Updated dependencies [[`8fade73`](https://github.com/cloudflare/workers-sdk/commit/8fade73f63289d3e4b64004669bca7e06d19c0e3)]: - - @cloudflare/workers-utils@0.41.2 - - @cloudflare/cli-shared-helpers@0.1.37 - - @cloudflare/config@0.17.0 - -## 0.6.2 - -### Patch Changes - -- Updated dependencies [[`59267fc`](https://github.com/cloudflare/workers-sdk/commit/59267fc79d1f7925a15369ca0125290df2404bfb)]: - - @cloudflare/workers-utils@0.41.1 - - @cloudflare/cli-shared-helpers@0.1.36 - - @cloudflare/config@0.17.0 - -## 0.6.1 - -### Patch Changes - -- Updated dependencies [[`ec5251a`](https://github.com/cloudflare/workers-sdk/commit/ec5251a92f561dbbba77694ac954d85298f44039)]: - - @cloudflare/config@0.17.0 - -## 0.6.0 - -### Minor Changes - -- [#15713](https://github.com/cloudflare/workers-sdk/pull/15713) [`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Define experimental Cloudflare configuration with a single default export - - Experimental `cloudflare.config.ts` files now define settings and resources together in a default-exported `defineConfig()` call. Add a Worker under `worker`, add Containers to the `containers` array, or omit both to provide settings only. - - ```ts - import * as entrypoint from "./src/index.ts" with { type: "cf-worker" }; - - export default defineConfig({ - accountId: "...", - complianceRegion: "public", - worker: { - name: "my-worker", - compatibilityDate: "2026-09-18", - entrypoint, - }, - }); - ``` - -### Patch Changes - -- Updated dependencies [[`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63), [`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63), [`45b3b81`](https://github.com/cloudflare/workers-sdk/commit/45b3b810809ee01cefbd53bea3a5ebc50bdb1c6c), [`95af41d`](https://github.com/cloudflare/workers-sdk/commit/95af41d564f7476cdda8c5923208c3b8a3ec2a11)]: - - @cloudflare/config@0.16.0 - - @cloudflare/workers-utils@0.41.0 - - @cloudflare/cli-shared-helpers@0.1.35 - -## 0.5.1 - -### Patch Changes - -- [#15694](https://github.com/cloudflare/workers-sdk/pull/15694) [`6e7c12e`](https://github.com/cloudflare/workers-sdk/commit/6e7c12eaf4cbd4545f9ba7144525198e9cf5f072) Thanks [@tpmmorris](https://github.com/tpmmorris)! - Defer configured unsupported frameworks to an installed Cloudflare dev server - - Configured `cf` projects whose detected framework is not supported by autoconfig no longer run inferred package scripts: `npm run build` as these may be invalid, e.g a build script `cf build` causes recursive calls `cf build -> npm run build -> cf build`. This allows `cf` to use its existing Cloudflare dev-server delegation instead. - -- Updated dependencies [[`1f070c8`](https://github.com/cloudflare/workers-sdk/commit/1f070c8a5a0b12247071551ed58d19444a427036), [`c4c9b75`](https://github.com/cloudflare/workers-sdk/commit/c4c9b75c54a095dc4b7ac82e44330f5650a2e4ac), [`643e5cc`](https://github.com/cloudflare/workers-sdk/commit/643e5ccb9e2ad7d85966af241e001465c0e1b1c6)]: - - @cloudflare/config@0.15.0 - - @cloudflare/workers-utils@0.40.1 - - @cloudflare/cli-shared-helpers@0.1.34 - -## 0.5.0 - -### Minor Changes - -- [#15593](https://github.com/cloudflare/workers-sdk/pull/15593) [`e24795b`](https://github.com/cloudflare/workers-sdk/commit/e24795bcd04fdf0d27a38f4f46b58009fde197ca) Thanks [@edmundhung](https://github.com/edmundhung)! - Expose mode support for autoconfigured framework commands - - Detected Astro and Vite frameworks now report that their build and development commands support `--mode`. Other frameworks remain unsupported by default. - -### Patch Changes - -- Updated dependencies [[`6874aa9`](https://github.com/cloudflare/workers-sdk/commit/6874aa978144469927831de59834e8cdc47a5114)]: - - @cloudflare/config@0.14.0 - - @cloudflare/workers-utils@0.40.0 - - @cloudflare/cli-shared-helpers@0.1.33 - -## 0.4.7 - -### Patch Changes - -- [#15651](https://github.com/cloudflare/workers-sdk/pull/15651) [`53c2189`](https://github.com/cloudflare/workers-sdk/commit/53c21892922f93a11b75d13d663acf327dad1695) Thanks [@edmundhung](https://github.com/edmundhung)! - Stop adding a `preview` script when configuring projects for `cf` - - Projects can continue using their existing development and preview scripts, or invoke `cf dev` directly. Wrangler-targeted autoconfiguration continues to add its existing `preview` script. - -- Updated dependencies [[`9515011`](https://github.com/cloudflare/workers-sdk/commit/9515011dc5ecdc5abf3a0c685d80f78e307fb513)]: - - @cloudflare/workers-utils@0.39.1 - - @cloudflare/cli-shared-helpers@0.1.32 - - @cloudflare/config@0.13.0 - -## 0.4.6 - -### Patch Changes - -- [#15491](https://github.com/cloudflare/workers-sdk/pull/15491) [`6c15da1`](https://github.com/cloudflare/workers-sdk/commit/6c15da10a6f486b0cf29cbbe30cabe50b16f4b4a) Thanks [@penalosa](https://github.com/penalosa)! - Recognize Astro 7 as officially supported by autoconfig - - Astro 7 projects no longer receive an unsupported-version warning during automatic configuration. Astro 7 uses the existing native `astro add cloudflare` configuration path introduced for Astro 6. - -- Updated dependencies [[`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78), [`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78), [`cb0955f`](https://github.com/cloudflare/workers-sdk/commit/cb0955f274102afb30b8502193edf66c0d3cb4d6), [`fa79b26`](https://github.com/cloudflare/workers-sdk/commit/fa79b26ef442303797013c70078c7acdd2c79247), [`ca71205`](https://github.com/cloudflare/workers-sdk/commit/ca71205bb45d9182e6c748e7097baed67739a891), [`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78)]: - - @cloudflare/workers-utils@0.39.0 - - @cloudflare/config@0.13.0 - - @cloudflare/cli-shared-helpers@0.1.31 - -## 0.4.5 - -### Patch Changes - -- Updated dependencies [[`3f42b10`](https://github.com/cloudflare/workers-sdk/commit/3f42b10a40d2b3aae1d8d5142ea0bc3ac58fa954), [`60d40f8`](https://github.com/cloudflare/workers-sdk/commit/60d40f88e6109ef31aa13a9feb15f5d64b3ffe1d)]: - - @cloudflare/config@0.12.0 - - @cloudflare/workers-utils@0.38.1 - - @cloudflare/cli-shared-helpers@0.1.30 - -## 0.4.4 - -### Patch Changes - -- [#15576](https://github.com/cloudflare/workers-sdk/pull/15576) [`5e0d6d3`](https://github.com/cloudflare/workers-sdk/commit/5e0d6d37194c0306a736a7d11995f5544b5715b3) Thanks [@edmundhung](https://github.com/edmundhung)! - Remove the unused Nitro Vite import when autoconfiguring TanStack Start for Cloudflare - - TanStack Start projects created for Node.js no longer retain an unused Nitro Vite import after Cloudflare autoconfiguration. - -- Updated dependencies [[`36aed7f`](https://github.com/cloudflare/workers-sdk/commit/36aed7f0f2db5056af9df917cf6c22a2be950b1e), [`bff525d`](https://github.com/cloudflare/workers-sdk/commit/bff525d66dd3785481148353d782dd33c3a644ed)]: - - @cloudflare/workers-utils@0.38.0 - - @cloudflare/cli-shared-helpers@0.1.29 - - @cloudflare/config@0.11.0 - -## 0.4.3 - -### Patch Changes - -- Updated dependencies [[`9c60d14`](https://github.com/cloudflare/workers-sdk/commit/9c60d14c0e4cd9306a58c830023f5b43fe6ed054), [`a849e0d`](https://github.com/cloudflare/workers-sdk/commit/a849e0d6d2253034fc158d5442c5124e77a39bd9)]: - - @cloudflare/config@0.11.0 - - @cloudflare/workers-utils@0.37.0 - - @cloudflare/cli-shared-helpers@0.1.28 - -## 0.4.2 - -### Patch Changes - -- Updated dependencies [[`fd17fc5`](https://github.com/cloudflare/workers-sdk/commit/fd17fc5c5fb86423e37ff5b142391e03cd7dbf59)]: - - @cloudflare/workers-utils@0.36.0 - - @cloudflare/cli-shared-helpers@0.1.27 - - @cloudflare/config@0.10.0 - -## 0.4.1 - -### Patch Changes - -- Updated dependencies [[`dbbb795`](https://github.com/cloudflare/workers-sdk/commit/dbbb795c47ff663857b605b484c63730e1e3ff45), [`b3f2628`](https://github.com/cloudflare/workers-sdk/commit/b3f26289a735279e463fb4802d4a4481cfaaac71), [`ea28cc3`](https://github.com/cloudflare/workers-sdk/commit/ea28cc33e5d39031e9bf512e17f3a57cccbd3f46), [`10d6bfb`](https://github.com/cloudflare/workers-sdk/commit/10d6bfbaf0ab7466892f4d97af1301494ca71e37)]: - - @cloudflare/workers-utils@0.35.0 - - @cloudflare/config@0.10.0 - - @cloudflare/cli-shared-helpers@0.1.26 - -## 0.4.0 - -### Minor Changes - -- [#15363](https://github.com/cloudflare/workers-sdk/pull/15363) [`baa7bd0`](https://github.com/cloudflare/workers-sdk/commit/baa7bd02af1dd9ad3b9ae8d175ca5b39c1b5fdd6) Thanks [@edmundhung](https://github.com/edmundhung)! - Resolve canonical framework build commands for the `cf` target - - Autoconfig now returns framework commands instead of package scripts for `cf`. Generated deploy scripts delegate build selection to `cf deploy`. Wrangler's existing package-script detection remains unchanged. - -### Patch Changes - -- Updated dependencies [[`3650d29`](https://github.com/cloudflare/workers-sdk/commit/3650d29f1cfcd6db103c25d22819e8fe41d592f3)]: - - @cloudflare/config@0.9.0 - -## 0.3.0 - -### Minor Changes - -- [#15246](https://github.com/cloudflare/workers-sdk/pull/15246) [`daefb3c`](https://github.com/cloudflare/workers-sdk/commit/daefb3cc0f0b884b8ce82b22ed9b67a9c43919be) Thanks [@edmundhung](https://github.com/edmundhung)! - Prepare autoconfig for multiple configuration targets - - Add target-specific configuration output and command detection while preserving Wrangler's existing setup and deployment behavior. - -### Patch Changes - -- Updated dependencies [[`ead8f69`](https://github.com/cloudflare/workers-sdk/commit/ead8f69e85efa758dd066b4d1cfc2fec406939dd), [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a), [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a), [`82d11fc`](https://github.com/cloudflare/workers-sdk/commit/82d11fca0c826ef54000e5fbe1dc87db73a5ef9c), [`7f66836`](https://github.com/cloudflare/workers-sdk/commit/7f668362bd5675afb95c1cb5128fad6aa092a430), [`acb14d0`](https://github.com/cloudflare/workers-sdk/commit/acb14d01d64f21f0f21c247da7c2fcb0557ebb3d)]: - - @cloudflare/config@0.8.0 - -## 0.2.9 - -### Patch Changes - -- Updated dependencies [[`59872c4`](https://github.com/cloudflare/workers-sdk/commit/59872c41d4417d9b8c2efddb4b35662453efcaae), [`c68f9cb`](https://github.com/cloudflare/workers-sdk/commit/c68f9cb866a2eae4416d20f584f733527189f18a), [`5c10e39`](https://github.com/cloudflare/workers-sdk/commit/5c10e398979c0a054f58dcf2751012cc99e977d2), [`39dcea6`](https://github.com/cloudflare/workers-sdk/commit/39dcea6c9362e2d651e3108fa769dbbc32db5a7b)]: - - @cloudflare/workers-utils@0.34.0 - - @cloudflare/cli-shared-helpers@0.1.25 - -## 0.2.8 - -### Patch Changes - -- Updated dependencies [[`fb6b51b`](https://github.com/cloudflare/workers-sdk/commit/fb6b51b87bf73edca9866bdf2d0810d7bf491108), [`1b73c87`](https://github.com/cloudflare/workers-sdk/commit/1b73c879c168dcc78b0f2657d04bc784b8af7da3)]: - - @cloudflare/workers-utils@0.33.1 - - @cloudflare/cli-shared-helpers@0.1.24 - -## 0.2.7 - -### Patch Changes - -- [#15123](https://github.com/cloudflare/workers-sdk/pull/15123) [`d0c976c`](https://github.com/cloudflare/workers-sdk/commit/d0c976c04ad890fcef56305ded11f1405e89273e) Thanks [@dependabot](https://github.com/apps/dependabot)! - Stop adding a redundant `nodejs_compat` flag to generated Wrangler configurations - - `create-cloudflare` and `wrangler setup` write today's date as the `compatibility_date`, and from `2026-08-04` that already enables `nodejs_compat`. Adding the flag as well made the generated project fail to start with "The compatibility flag nodejs_compat became the default as of 2026-08-04 so does not need to be specified anymore", so the flag is now only added for earlier compatibility dates. - - `create-cloudflare` also removes the flag when a template, or a framework's own scaffolder, already wrote it into a configuration that ends up using such a compatibility date, and still installs `@types/node` for these projects even though there is no longer a flag to detect them by. - - `wrangler setup` does the same for a `wrangler.json(c)` that is already in the project: it writes today's date over whatever date that configuration was written for, so a `nodejs_compat` it finds there is removed as part of writing the file. - -- Updated dependencies [[`d0c976c`](https://github.com/cloudflare/workers-sdk/commit/d0c976c04ad890fcef56305ded11f1405e89273e)]: - - @cloudflare/workers-utils@0.33.0 - - @cloudflare/cli-shared-helpers@0.1.23 - -## 0.2.6 - -### Patch Changes - -- Updated dependencies [[`0aa8fa5`](https://github.com/cloudflare/workers-sdk/commit/0aa8fa5e12bc64facb4e9fece321a762269d0357)]: - - @cloudflare/workers-utils@0.32.0 - - @cloudflare/cli-shared-helpers@0.1.22 - -## 0.2.5 - -### Patch Changes - -- Updated dependencies [[`8cf78c8`](https://github.com/cloudflare/workers-sdk/commit/8cf78c83cb4c64be8b458d7bd618b47e7c6e7d25), [`6946da1`](https://github.com/cloudflare/workers-sdk/commit/6946da1123f3c8484af80ec4f5426c5fe0bbdb34)]: - - @cloudflare/workers-utils@0.31.2 - - @cloudflare/cli-shared-helpers@0.1.21 - -## 0.2.4 - -### Patch Changes - -- Updated dependencies [[`b5c083b`](https://github.com/cloudflare/workers-sdk/commit/b5c083bf601d71bad82ccc044df55ba4584085e2)]: - - @cloudflare/workers-utils@0.31.1 - - @cloudflare/cli-shared-helpers@0.1.20 - -## 0.2.3 - -### Patch Changes - -- Updated dependencies [[`5a56dda`](https://github.com/cloudflare/workers-sdk/commit/5a56ddaf8548fe79787482506b3d5e0233c329c6)]: - - @cloudflare/workers-utils@0.31.0 - - @cloudflare/cli-shared-helpers@0.1.19 - -## 0.2.2 - -### Patch Changes - -- Updated dependencies [[`5e6556a`](https://github.com/cloudflare/workers-sdk/commit/5e6556a0c788679b6ac149ba3018a2cfd7cc73e9)]: - - @cloudflare/workers-utils@0.30.0 - - @cloudflare/cli-shared-helpers@0.1.18 - -## 0.2.1 - -### Patch Changes - -- Updated dependencies [[`552bcfc`](https://github.com/cloudflare/workers-sdk/commit/552bcfc8d44f8625b09dfd5d821c132b626cb7bb)]: - - @cloudflare/workers-utils@0.29.0 - - @cloudflare/cli-shared-helpers@0.1.17 - -## 0.2.0 - -### Minor Changes - -- [#14595](https://github.com/cloudflare/workers-sdk/pull/14595) [`2b390d7`](https://github.com/cloudflare/workers-sdk/commit/2b390d7831ff27aa13cdf05aa8e11e4c0086f924) Thanks [@colinhacks](https://github.com/colinhacks)! - Recognise nub as a package manager - - wrangler now detects nub — from its `npm_config_user_agent` and an installed `nub` binary — and autoconfig detects nub projects by their `nub.lock`, alongside npm, pnpm, yarn, and bun. - -### Patch Changes - -- [#14534](https://github.com/cloudflare/workers-sdk/pull/14534) [`a330170`](https://github.com/cloudflare/workers-sdk/commit/a330170e8dfbe481a99597b3e07c1438e20f5ebb) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Preserve existing Nuxt `modules` when configuring a project for Cloudflare - - Configuring an existing Nuxt project whose `nuxt.config.ts` already declares a `modules` array previously overwrote that array when adding `nitro-cloudflare-dev`, dropping modules such as `@nuxt/ui`. Existing entries are now retained and the Cloudflare module is appended instead. - -- Updated dependencies [[`2b390d7`](https://github.com/cloudflare/workers-sdk/commit/2b390d7831ff27aa13cdf05aa8e11e4c0086f924), [`a6c214f`](https://github.com/cloudflare/workers-sdk/commit/a6c214fb311215b1ed09b273171b7995033fb7d7)]: - - @cloudflare/workers-utils@0.28.0 - - @cloudflare/cli-shared-helpers@0.1.16 - -## 0.1.6 - -### Patch Changes - -- Updated dependencies [[`8cd805d`](https://github.com/cloudflare/workers-sdk/commit/8cd805db2f9901cba52d574b385577bafd595cb5)]: - - @cloudflare/cli-shared-helpers@0.1.15 - - @cloudflare/workers-utils@0.27.0 - -## 0.1.5 - -### Patch Changes - -- Updated dependencies [[`42df9bb`](https://github.com/cloudflare/workers-sdk/commit/42df9bbf07e37032a3e61027e33d504d74a25ccd)]: - - @cloudflare/workers-utils@0.27.0 - - @cloudflare/cli-shared-helpers@0.1.14 - -## 0.1.4 - -### Patch Changes - -- Updated dependencies [[`0283a1f`](https://github.com/cloudflare/workers-sdk/commit/0283a1fcdc635244f731010422e513e8b4ab0be3)]: - - @cloudflare/workers-utils@0.26.0 - - @cloudflare/cli-shared-helpers@0.1.13 - -## 0.1.3 - -### Patch Changes - -- [#14548](https://github.com/cloudflare/workers-sdk/pull/14548) [`383e679`](https://github.com/cloudflare/workers-sdk/commit/383e679b52e39dcb71cbbb66909218c008d9aac4) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Fix Vite version detection for vite+ projects during autoconfiguration - - vite+ installs `@voidzero-dev/vite-plus-core` under the `vite` npm alias, so the resolved `node_modules/vite/package.json` reports the wrapper's own version (e.g. `0.2.2`) rather than the underlying Vite version it bundles. This caused autoconfiguration to fail with an error claiming the Vite version was too old to be configured automatically. Autoconfiguration now detects the correct underlying Vite version for these projects. - -- Updated dependencies [[`aad35b7`](https://github.com/cloudflare/workers-sdk/commit/aad35b79d07df1bb764a4a5912d6b4328a34474b), [`1ac96a1`](https://github.com/cloudflare/workers-sdk/commit/1ac96a14b7fb022acada114ab8793fe8a4ba79a5), [`1ca8d8f`](https://github.com/cloudflare/workers-sdk/commit/1ca8d8f0bbd012a1d65cabadf7b6987b252775e9)]: - - @cloudflare/workers-utils@0.25.1 - - @cloudflare/cli-shared-helpers@0.1.12 - -## 0.1.2 - -### Patch Changes - -- Updated dependencies [[`aa5d580`](https://github.com/cloudflare/workers-sdk/commit/aa5d5801450b7e4417bfdbd477f86de3a4bc6933)]: - - @cloudflare/workers-utils@0.25.0 - - @cloudflare/cli-shared-helpers@0.1.11 - -## 0.1.1 - -### Patch Changes - -- [#14368](https://github.com/cloudflare/workers-sdk/pull/14368) [`a55b29a`](https://github.com/cloudflare/workers-sdk/commit/a55b29a4ba8a24f4d539538e2bf38e6a7e5b8e52) Thanks [@penalosa](https://github.com/penalosa)! - Add repository URL to `@cloudflare/autoconfig` - -## 0.1.0 - -### Minor Changes - -- [#14365](https://github.com/cloudflare/workers-sdk/pull/14365) [`f224ce2`](https://github.com/cloudflare/workers-sdk/commit/f224ce2009b6844a606eb53a71fb114434e8a7a0) Thanks [@dario-piotrowicz](https://github.com/dario-piotrowicz)! - Add experimental package for framework autoconfig detection and configuration - -- [#14365](https://github.com/cloudflare/workers-sdk/pull/14365) [`f224ce2`](https://github.com/cloudflare/workers-sdk/commit/f224ce2009b6844a606eb53a71fb114434e8a7a0) Thanks [@dario-piotrowicz](https://github.com/dario-piotrowicz)! - Add support for React Router >= 8.0.0 - - React Router v8 enables `viteEnvironmentApi` and `middleware` by default, so autoconfig no longer adds `future` flags to `react-router.config.ts` for v8+ projects and uses the middleware code pattern unconditionally. - -### Patch Changes - -- Updated dependencies [[`cfd6205`](https://github.com/cloudflare/workers-sdk/commit/cfd6205fe86f6afd74b5881f09524c93c83b8359), [`cfd6205`](https://github.com/cloudflare/workers-sdk/commit/cfd6205fe86f6afd74b5881f09524c93c83b8359)]: - - @cloudflare/workers-utils@0.24.0 - - @cloudflare/cli-shared-helpers@0.1.10 diff --git a/packages/autoconfig/package.json b/packages/autoconfig/package.json deleted file mode 100644 index 5475568896..0000000000 --- a/packages/autoconfig/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@cloudflare/autoconfig", - "version": "0.7.9", - "description": "Framework autoconfig detection and configuration for Cloudflare Workers", - "license": "MIT OR Apache-2.0", - "repository": { - "type": "git", - "url": "https://github.com/cloudflare/workers-sdk.git", - "directory": "packages/autoconfig" - }, - "files": [ - "dist" - ], - "type": "module", - "sideEffects": false, - "main": "dist/index.js", - "types": "dist/index.d.ts", - "exports": { - ".": { - "import": "./dist/index.js", - "types": "./dist/index.d.ts" - } - }, - "scripts": { - "build": "tsup", - "check:type": "tsc -p ./tsconfig.json", - "dev": "tsup --watch", - "test": "vitest", - "test:ci": "vitest run" - }, - "dependencies": { - "@cloudflare/cli-shared-helpers": "workspace:*", - "@cloudflare/config": "workspace:*", - "@cloudflare/workers-utils": "workspace:*" - }, - "devDependencies": { - "@cloudflare/shared-ast-primitives": "workspace:*", - "@cloudflare/workers-tsconfig": "workspace:*", - "@netlify/build-info": "10.5.1", - "@types/esprima": "^4.0.3", - "@types/node": "catalog:default", - "chalk": "catalog:default", - "empathic": "^2.0.0", - "esprima": "4.0.1", - "recast": "0.23.11", - "semiver": "^1.1.0", - "ts-dedent": "^2.2.0", - "tsup": "8.3.0", - "typescript": "catalog:default", - "vitest": "catalog:default" - }, - "volta": { - "extends": "../../package.json" - }, - "workers-sdk": { - "prerelease": true - } -} diff --git a/packages/autoconfig/scripts/deps.ts b/packages/autoconfig/scripts/deps.ts deleted file mode 100644 index 01728ca8c8..0000000000 --- a/packages/autoconfig/scripts/deps.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * Dependencies that _are not_ bundled along with @cloudflare/autoconfig. - * - * These must be explicitly documented with a reason why they cannot be bundled. - * This list is validated by `tools/deployments/validate-package-dependencies.ts`. - */ -export const EXTERNAL_DEPENDENCIES = [ - // Published workspace packages that consumers must install alongside autoconfig. - // They are kept external to share a single copy with wrangler and other SDK tools. - "@cloudflare/cli-shared-helpers", - // Its public types are exposed by autoconfig and must resolve for consumers. - "@cloudflare/config", - "@cloudflare/workers-utils", -]; diff --git a/packages/autoconfig/src/context.ts b/packages/autoconfig/src/context.ts deleted file mode 100644 index e7301a8a73..0000000000 --- a/packages/autoconfig/src/context.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Logger interface for autoconfig output. - * Callers provide their own implementation (e.g., wrapping `console` or a custom logger). - */ -export interface AutoConfigLogger { - /** Logs informational output. */ - log(...args: unknown[]): void; - /** Logs an informational message. */ - info(...args: unknown[]): void; - /** Logs a warning message. */ - warn(...args: unknown[]): void; - /** Logs a debug-level message (may be suppressed in production). */ - debug(...args: unknown[]): void; - /** Logs an error message. */ - error(...args: unknown[]): void; -} - -export type AutoConfigTarget = "cf" | "wrangler"; - -/** - * Dialog interface for interactive prompts. - * Callers provide their own implementation (e.g., using `prompts`, `inquirer`, or a custom UI). - */ -export interface AutoConfigDialogs { - /** - * Asks a yes/no confirmation question. - * - * @param text - The question to display - * @param options - Optional defaults and fallback behavior - * @returns `true` if confirmed, `false` otherwise - */ - confirm( - text: string, - options?: { defaultValue?: boolean; fallbackValue?: boolean } - ): Promise; - - /** - * Prompts the user for a text input. - * - * @param text - The prompt message - * @param options - Optional default value and validation function - * @returns The user-provided string - */ - prompt( - text: string, - options?: { - defaultValue?: string; - validate?: ( - value: string - ) => boolean | string | Promise; - } - ): Promise; - - /** - * Presents a selection list to the user. - * - * @param text - The prompt message - * @param options - Available choices and optional default selection - * @returns The selected value - */ - select( - text: string, - options: { - choices: Array<{ - title: string; - value: string; - description?: string; - }>; - defaultOption?: number; - } - ): Promise; -} - -/** - * Context object that provides external dependencies to the autoconfig system. - * - * Callers must provide implementations for `logger` and `dialogs`. - * All other fields are optional and allow callers to customize behavior - * (e.g., error reporting, command execution, CI detection). - */ -export interface AutoConfigContext { - /** Logger used for all autoconfig output. */ - logger: AutoConfigLogger; - /** Dialogs used for interactive prompts. */ - dialogs: AutoConfigDialogs; - /** - * Runs a shell command in the given directory. - * - * @param command - The shell command string to execute - * @param cwd - The working directory for the command - * @param label - A short label for logging (e.g., "[build]") - * @returns A promise that resolves when the command completes - */ - runCommand: (command: string, cwd: string, label: string) => Promise; - /** - * Returns `true` if running in a non-interactive or CI environment. - * Defaults to `() => false` if not provided. - * - * @returns Whether the current environment is non-interactive - */ - isNonInteractiveOrCI?: () => boolean; - /** - * Returns a cache folder path used for detecting cached project state, - * or `undefined` if not available. - * - * @returns The cache folder path, or `undefined` - */ - getCacheFolder?: () => string | undefined; -} diff --git a/packages/autoconfig/src/details/framework-detection.ts b/packages/autoconfig/src/details/framework-detection.ts deleted file mode 100644 index 7cf92de2e1..0000000000 --- a/packages/autoconfig/src/details/framework-detection.ts +++ /dev/null @@ -1,378 +0,0 @@ -import { existsSync, statSync } from "node:fs"; -import { join, resolve } from "node:path"; -import { - BunPackageManager, - FatalError, - NpmPackageManager, - NubPackageManager, - PnpmPackageManager, - UserError, - YarnPackageManager, -} from "@cloudflare/workers-utils"; -import { Project } from "@netlify/build-info"; -import { NodeFS } from "@netlify/build-info/node"; -import chalk from "chalk"; -import dedent from "ts-dedent"; -import { isFrameworkSupported, isKnownFramework } from "../frameworks"; -import { staticFramework } from "../frameworks/all-frameworks"; -import type { AutoConfigContext, AutoConfigTarget } from "../context"; -import type { PackageManager } from "@cloudflare/workers-utils"; -import type { Config, TelemetryMessage } from "@cloudflare/workers-utils"; -import type { Settings } from "@netlify/build-info"; - -/** - * Detects the framework used by the project at the given path. - * - * Uses `@netlify/build-info` to analyze build settings and identify the - * framework, then maps the detected package manager to wrangler's own type. - * - * If the project is identified as a Cloudflare Pages project the function - * returns early with a synthetic "Cloudflare Pages" framework entry. - * - * @param projectPath Path to the project root - * @param context Autoconfig context used for logging and user interaction - * @param options Detection options - * @returns An object containing: - * - `detectedFramework`: The matched framework, its build and development - * commands, and its output directory. - * - `packageManager`: The package manager detected in the project. - * - `isWorkspaceRoot`: `true` when the project path is the root of a - * monorepo workspace (only present when relevant). - * @throws {UserError} When called from a workspace root that does not itself - * contain the targeted project path. - * @throws {MultipleFrameworksCIError} (via `findDetectedFramework`) in CI / - * non-interactive environments when multiple known frameworks are detected - * and no clear winner can be determined. - */ -export async function detectFramework( - projectPath: string, - context: AutoConfigContext, - { - wranglerConfig, - target = "cf", - }: { - wranglerConfig?: Config; - target?: AutoConfigTarget; - } = {} -): Promise<{ - detectedFramework: DetectedFramework; - packageManager: PackageManager; - isWorkspaceRoot?: boolean; -}> { - const fs = new NodeFS(); - - fs.logger = context.logger; - - const project = new Project(fs, projectPath, projectPath) - .setEnvironment(process.env) - .setNodeVersion(process.version); - - const buildSettings = await project.getBuildSettings(); - - const isWorkspaceRoot = !!project.workspace?.isRoot; - - if (isWorkspaceRoot) { - const resolvedProjectPath = resolve(projectPath); - - const workspaceRootIncludesProject = project.workspace?.packages.some( - (pkg) => resolve(pkg.path) === resolvedProjectPath - ); - - if (!workspaceRootIncludesProject) { - throw new UserError( - "The Cloudflare application detection logic has been run in the root of a workspace instead of targeting a specific project. Change your working directory to one of the applications in the workspace and try again.", - { - telemetryMessage: "autoconfig detection workspace root unsupported", - } - ); - } - } - - // Convert the package manager detected by @netlify/build-info to our PackageManager type. - // This is populated after getBuildSettings() runs, which triggers the full detection chain. - const packageManager = convertDetectedPackageManager( - project.packageManager, - projectPath - ); - - const lockFileExists = packageManager.lockFiles.some((lockFile) => - existsSync(join(projectPath, lockFile)) - ); - - const maybeDetectedFramework = maybeFindDetectedFramework( - buildSettings, - context - ); - if (maybeDetectedFramework && target === "cf") { - const frameworkId = maybeDetectedFramework.framework.id; - const frameworkIsSupported = - isKnownFramework(frameworkId) && isFrameworkSupported(frameworkId); - - // @netlify/build-info prefers package.json scripts over the framework's - // built-in commands. cf needs direct commands for supported frameworks, but - // delegates unsupported frameworks to an installed Cloudflare dev server and - // must not execute their generic package scripts. - const detectedFrameworkSettings = frameworkIsSupported - ? project.frameworks - .get(maybeDetectedFramework.baseDirectory ?? "") - ?.find(({ id }) => id === frameworkId) - : undefined; - maybeDetectedFramework.devCommand = detectedFrameworkSettings?.dev?.command; - maybeDetectedFramework.buildCommand = - detectedFrameworkSettings?.build?.command; - } - - if ( - await isPagesProject( - projectPath, - context, - wranglerConfig, - maybeDetectedFramework - ) - ) { - return { - detectedFramework: { - framework: { - name: "Cloudflare Pages", - id: "cloudflare-pages", - }, - dist: wranglerConfig?.pages_build_output_dir, - }, - packageManager, - }; - } - - const detectedFramework = maybeDetectedFramework ?? { - framework: { - id: staticFramework.id, - name: staticFramework.name, - }, - }; - - if ( - !lockFileExists && - detectedFramework.framework.id !== staticFramework.id - ) { - context.logger.warn( - "No lock file has been detected in the current working directory." + - " This might indicate that the project is part of a workspace. Auto-configuration of " + - `projects inside workspaces is limited. See ${chalk.hex("#3B818D")( - "https://developers.cloudflare.com/workers/framework-guides/automatic-configuration/#workspaces" - )}` - ); - } - - return { - detectedFramework, - packageManager, - isWorkspaceRoot, - }; -} - -/** - * Converts the package manager detected by @netlify/build-info to our PackageManager type. - * Falls back to npm if no package manager was detected. - * - * @param pkgManager The package manager detected by @netlify/build-info (from project.packageManager) - * @param projectPath Path to the project root, used to detect nub via its lock file - * @returns A PackageManager object compatible with wrangler's package manager utilities - */ -function convertDetectedPackageManager( - pkgManager: { name: string } | null, - projectPath: string -): PackageManager { - // TODO: Remove this nub.lock check once netlify/build#7124 is merged and - // released, after which @netlify/build-info recognises nub directly. - // https://github.com/netlify/build/pull/7124 - if (existsSync(join(projectPath, "nub.lock"))) { - return NubPackageManager; - } - - if (!pkgManager) { - return NpmPackageManager; - } - - switch (pkgManager?.name) { - case "pnpm": - return PnpmPackageManager; - case "yarn": - return YarnPackageManager; - case "bun": - return BunPackageManager; - case "npm": - default: - return NpmPackageManager; - } -} - -class MultipleFrameworksCIError extends FatalError { - constructor( - frameworks: string[], - telemetryOptions: TelemetryMessage = { - telemetryMessage: "autoconfig detection multiple frameworks", - } - ) { - super( - dedent`Cloudflare's tooling was unable to automatically configure your project, since multiple frameworks were found: ${frameworks.join( - ", " - )}. - - To fix this issue either: - - check your project's configuration to make sure that the target framework - is the only configured one and try again - - run \`wrangler setup\` locally to get an interactive user experience where - you can specify what framework you want to target - - `, - { ...telemetryOptions, code: 1 } - ); - } -} - -function throwMultipleFrameworksNonInteractiveError( - settings: Settings[] -): never { - throw new MultipleFrameworksCIError( - settings.map((b) => b.name), - { - telemetryMessage: "autoconfig detection multiple frameworks", - } - ); -} - -type DetectedFramework = { - baseDirectory?: string; - framework: { - name: string; - id: string; - }; - devCommand?: string | undefined; - buildCommand?: string | undefined; - dist?: string; -}; - -async function isPagesProject( - projectPath: string, - context: AutoConfigContext, - wranglerConfig: Config | undefined, - detectedFramework?: DetectedFramework | undefined -): Promise { - if (wranglerConfig?.pages_build_output_dir) { - // The `pages_build_output_dir` is set only for Pages projects - return true; - } - - const cacheFolder = context.getCacheFolder?.(); - if (cacheFolder) { - const pagesConfigCache = join(cacheFolder, "pages.json"); - if (existsSync(pagesConfigCache)) { - // If there is a cached pages.json we can safely assume that the project - // is a Pages one - return true; - } - } - - if (detectedFramework === undefined) { - const functionsPath = join(projectPath, "functions"); - if (existsSync(functionsPath)) { - const functionsStat = statSync(functionsPath); - if (functionsStat.isDirectory()) { - const pagesConfirmed = await context.dialogs.confirm( - "We have identified a `functions` directory in this project, which might indicate you have an active Cloudflare Pages deployment. Is this correct?", - { - defaultValue: true, - // In CI we do want to fallback to `false` so that we can proceed with the autoconfig flow - fallbackValue: false, - } - ); - return pagesConfirmed; - } - } - } - - return false; -} - -/** - * Selects the most appropriate framework from a list of detected framework settings. - * - * When there is a good level of confidence that the selected framework is correct or - * the process is running locally (where the user can choose a different framework or - * abort the process) the framework is returned. If there is no such confidence and the - * process is running in non interactive mode (where the user doesn't have the option to - * change the detected framework) an error is instead thrown. - * - * @param settings The array of framework settings - * @returns The selected framework settings, or `undefined` if none provided - * @throws {MultipleFrameworksCIError} In CI environments when multiple known frameworks - * are detected and no clear winner can be determined - */ -function maybeFindDetectedFramework( - settings: Settings[], - context: AutoConfigContext -): DetectedFramework | undefined { - if (settings.length === 0) { - return undefined; - } - - if (settings.length === 1) { - return settings[0]; - } - - const settingsForOnlyKnownFrameworks = settings.filter(({ framework }) => - isKnownFramework(framework.id) - ); - - if (settingsForOnlyKnownFrameworks.length === 0) { - if (context.isNonInteractiveOrCI?.() ?? false) { - // If we're in a non interactive session (e.g. CI) let's throw to be on the safe side - throwMultipleFrameworksNonInteractiveError(settings); - } - // Locally we can just return the first one since the user can anyways choose a different - // framework or abort the process anyways - return settings[0]; - } - - if (settingsForOnlyKnownFrameworks.length === 1) { - // If there is a single known framework it's quite safe to assume that that's the - // one we care about - return settingsForOnlyKnownFrameworks[0]; - } - - if (settingsForOnlyKnownFrameworks.length === 2) { - const settingsForOnlyKnownFrameworksIds = new Set( - settingsForOnlyKnownFrameworks.map(({ framework }) => framework.id) - ); - - // Some frameworks (e.g. Vite, Hono) can serve as auxiliary tooling for a primary - // framework (e.g. Vite with React, Hono with Waku). When exactly two frameworks - // are detected and one is auxiliary, we discard it and return the primary one. - const idsOfAuxiliaryFrameworks = ["vite", "hono"]; - - for (const auxiliaryFrameworkId of idsOfAuxiliaryFrameworks) { - if (settingsForOnlyKnownFrameworksIds.has(auxiliaryFrameworkId)) { - const nonAuxiliaryFrameworkSettings = - settingsForOnlyKnownFrameworks.find( - ({ framework }) => framework.id !== auxiliaryFrameworkId - ); - - // Note: here nonAuxiliaryFrameworkSettings should always be defined, it could be undefined only if the - // same framework is actually detected twice (which shouldn't be possible). - if (nonAuxiliaryFrameworkSettings) { - return nonAuxiliaryFrameworkSettings; - } - } - } - } - - // If we've detected multiple frameworks, and we're in a non interactive session (e.g. CI) let's stay on the safe side and error - // (otherwise we just pick the first one as the user is always able to choose a different framework or terminate the process anyways) - if (context.isNonInteractiveOrCI?.() ?? false) { - throw new MultipleFrameworksCIError( - settingsForOnlyKnownFrameworks.map((b) => b.name), - { telemetryMessage: "autoconfig detection multiple frameworks" } - ); - } - - return settingsForOnlyKnownFrameworks[0]; -} diff --git a/packages/autoconfig/src/details/index.ts b/packages/autoconfig/src/details/index.ts deleted file mode 100644 index 49e0a16697..0000000000 --- a/packages/autoconfig/src/details/index.ts +++ /dev/null @@ -1,378 +0,0 @@ -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 { brandColor } from "@cloudflare/cli-shared-helpers/colors"; -import { - checkWorkerNameValidity, - getWorkerName, - NpmPackageManager, - parsePackageJSON, - readFileSync, -} from "@cloudflare/workers-utils"; -import { AutoConfigDetectionError } from "../errors"; -import { getFrameworkClassInstance } from "../frameworks"; -import { - allFrameworksInfos, - staticFramework, -} from "../frameworks/all-frameworks"; -import { detectFramework } from "./framework-detection"; -import type { AutoConfigContext, AutoConfigTarget } from "../context"; -import type { - AutoConfigDetails, - AutoConfigDetailsForNonConfiguredProject, -} from "../types"; -import type { PackageManager } from "@cloudflare/workers-utils"; -import type { Config, PackageJSON } from "@cloudflare/workers-utils"; - -const CLOUDFLARE_CONFIG_FILE = "cloudflare.config.ts"; - -/** - * Asserts that the current project being targeted for autoconfig is not already configured. - * - * @param details The details detected for the project. - */ -export function assertNonConfigured( - details: AutoConfigDetails -): asserts details is AutoConfigDetailsForNonConfiguredProject { - assert( - details.configured === false, - "Error: expected the current project not to be already configured" - ); -} - -function isExpectedFileSystemError(error: unknown): boolean { - return ( - typeof error === "object" && - error !== null && - "code" in error && - (error.code === "ENOENT" || - error.code === "ENOTDIR" || - error.code === "EACCES" || - error.code === "EPERM") - ); -} - -async function getPathStats(path: string): Promise { - try { - return await stat(path); - } catch (error) { - if (isExpectedFileSystemError(error)) { - return undefined; - } - throw error; - } -} - -async function hasIndexHtml(dir: string): Promise { - const stats = await getPathStats(join(dir, "index.html")); - if (!stats?.isFile()) { - return false; - } - - try { - return (await readdir(dir)).includes("index.html"); - } catch (error) { - if (isExpectedFileSystemError(error)) { - return false; - } - throw error; - } -} - -/** - * If we haven't detected a framework being used, or the project is a Pages one, we need to "guess" what output dir the - * user is intending to use. This is best-effort, and so will not be accurate all the time. The heuristic we use is the - * first child directory with an `index.html` file present. - */ -async function findAssetsDir(from: string): Promise { - if (await hasIndexHtml(from)) { - return "."; - } - const children = await readdir(from); - for (const child of children) { - const path = join(from, child); - const stats = await getPathStats(path); - if (stats?.isDirectory() && (await hasIndexHtml(path))) { - return relative(from, path); - } - } - return undefined; -} - -/** - * Detects project details needed for autoconfig: framework, package manager, - * output directory, worker name, commands, and whether the project is already configured. - * By default, the project is considered configured when `cloudflare.config.ts` - * exists. Passing `target: "wrangler"` opts into Wrangler configuration - * detection instead. - * - * @param options - Detection options including project path, wrangler config, and context. - * @returns The detected project details. - */ -export async function getDetailsForAutoConfig({ - projectPath = process.cwd(), - wranglerConfig, - target = "cf", - context, -}: { - /** The path to the project, defaults to cwd. */ - projectPath?: string; - /** The parsed wrangler configuration for the project (if any). */ - wranglerConfig?: Config; - /** The configuration target, defaults to cf. */ - target?: AutoConfigTarget; - /** The autoconfig context providing logger, dialogs, and other dependencies. */ - context: AutoConfigContext; -}): Promise { - const { logger } = context; - - logger.debug(`Running autoconfig detection in ${projectPath}...`); - - const hasCloudflareConfig = - target === "cf" && existsSync(resolve(projectPath, CLOUDFLARE_CONFIG_FILE)); - - if ( - target === "wrangler" && - // If a real Wrangler config has been found the project is already configured for Workers - wranglerConfig?.configPath && - // Unless `pages_build_output_dir` is set, since that indicates that the project is a Pages one instead - !wranglerConfig.pages_build_output_dir - ) { - return { - configured: true, - projectPath, - workerName: getWorkerName(wranglerConfig.name, projectPath), - // Fall back to npm when already configured since we don't need to run package manager commands - packageManager: NpmPackageManager, - }; - } - - const { detectedFramework, packageManager, isWorkspaceRoot } = - await detectFramework(projectPath, context, { wranglerConfig, target }); - - const framework = getFrameworkClassInstance(detectedFramework.framework.id); - const packageJsonPath = resolve(projectPath, "package.json"); - - let packageJson: PackageJSON | undefined; - - try { - packageJson = parsePackageJSON( - readFileSync(packageJsonPath), - packageJsonPath - ); - } catch { - logger.debug("No package.json found when running autoconfig"); - } - - const configured = - hasCloudflareConfig || framework.isConfigured(projectPath, { target }); - - const outputDir = - detectedFramework?.dist ?? (await findAssetsDir(projectPath)); - - const baseDetails = { - projectPath, - framework, - packageJson, - packageManager, - devCommand: getProjectCommand(detectedFramework.devCommand, packageManager), - buildCommand: getProjectCommand( - detectedFramework.buildCommand, - packageManager - ), - env: framework.env, - workerName: getWorkerName(packageJson?.name, projectPath), - }; - - if (configured) { - return { - ...baseDetails, - configured: true, - isWorkspaceRoot, - }; - } - - if (!outputDir) { - const errorMessage = - framework.id === "static" || framework.id === "cloudflare-pages" - ? "Could not detect a directory containing static files (e.g. html, css and js) for the project" - : "Failed to detect an output directory for the project"; - - throw new AutoConfigDetectionError(errorMessage, { - telemetryMessage: "autoconfig details output directory missing", - frameworkId: framework.id, - configured, - }); - } - - return { - ...baseDetails, - outputDir, - configured: false, - isWorkspaceRoot, - }; -} - -/** - * Converts a detected project command into one that can be run in the terminal - * (such as `npm run build` or `npx astro dev`). If no command is detected - * `undefined` is returned instead. - * - * @param command The detected project command - * @param packageManager The package manager to use for command prefixes - * @returns A runnable project command if detected, undefined otherwise - */ -function getProjectCommand( - command: string | undefined, - packageManager: PackageManager -): string | undefined { - if (!command) { - return undefined; - } - - const { type, dlx, npx } = packageManager; - - for (const packageManagerCommandPrefix of [type, dlx.join(" "), npx]) { - if (command.startsWith(packageManagerCommandPrefix)) { - // The command already includes a package-manager prefix. - return command; - } - } - - // Framework executables such as `astro build` need the appropriate package-manager prefix. - return `${npx} ${command}`; -} - -/** - * Displays the detected autoconfig details to the user via the context logger. - * - * @param autoConfigDetails - The detected project details to display. - * @param context - The autoconfig context providing the logger. - * @param displayOptions - Optional display customization. - */ -export function displayAutoConfigDetails( - autoConfigDetails: AutoConfigDetails, - context: AutoConfigContext, - displayOptions?: { heading?: string } -): void { - const { logger } = context; - logger.log(""); - - logger.log(displayOptions?.heading ?? "Detected Project Settings:"); - - logger.log(brandColor(" - Worker Name:"), autoConfigDetails.workerName); - if (autoConfigDetails.framework) { - logger.log(brandColor(" - Framework:"), autoConfigDetails.framework.name); - } - if (autoConfigDetails.buildCommand) { - logger.log(brandColor(" - Build Command:"), autoConfigDetails.buildCommand); - } - if (autoConfigDetails.outputDir) { - logger.log(brandColor(" - Output Directory:"), autoConfigDetails.outputDir); - } - - logger.log(""); -} - -/** - * Prompts the user to confirm or modify the detected autoconfig details. - * - * @param autoConfigDetails - The detected project details. - * @param context - The autoconfig context providing dialogs. - * @returns The (possibly updated) autoconfig details. - */ -export async function confirmAutoConfigDetails( - autoConfigDetails: AutoConfigDetails, - context: AutoConfigContext -): Promise { - const { dialogs } = context; - const modifySettings = await dialogs.confirm( - "Do you want to modify these settings?", - { defaultValue: false, fallbackValue: false } - ); - - if (!modifySettings) { - return autoConfigDetails; - } - - // Just spreading the object to shallow clone it to avoid some potential side effects - const { ...updatedAutoConfigDetails } = autoConfigDetails; - - const workerName = await dialogs.prompt( - "What do you want to name your Worker?", - { - defaultValue: autoConfigDetails.workerName ?? "", - validate: (value: string) => { - const validity = checkWorkerNameValidity(value); - if (validity.valid) { - return true; - } - return validity.cause; - }, - } - ); - - updatedAutoConfigDetails.workerName = workerName; - - const frameworkId = await dialogs.select( - "What framework is your application using?", - { - choices: allFrameworksInfos.map((f) => ({ - title: f.name, - value: f.id, - description: - f.id === staticFramework.id - ? "No framework at all, or a static framework such as Vite, React or Gatsby." - : `The ${f.name} JavaScript framework`, - })), - defaultOption: allFrameworksInfos.findIndex((framework) => { - if (!autoConfigDetails?.framework) { - // If there is no framework already detected let's default to the static one - // (note: there should always be a framework at this point) - return framework.id === staticFramework.id; - } - return autoConfigDetails.framework.id === framework.id; - }), - } - ); - - updatedAutoConfigDetails.framework = getFrameworkClassInstance(frameworkId); - - const outputDir = await dialogs.prompt( - "What directory contains your applications' output/asset files?", - { - defaultValue: autoConfigDetails.outputDir ?? "", - validate: async (value) => { - if (!value) { - return "Please provide a valid directory path"; - } - const valueStats = statSync(resolve(value), { throwIfNoEntry: false }); - if (!valueStats) { - // If the path doesn't point to anything that's fine since the directory will likely be - // generated by the build command anyways - return true; - } - if (valueStats?.isFile()) { - return "Please select a directory"; - } - return true; - }, - } - ); - - updatedAutoConfigDetails.outputDir = outputDir; - - if (autoConfigDetails.buildCommand || autoConfigDetails.packageJson) { - const buildCommand = await dialogs.prompt( - "What is your application's build command?", - { - defaultValue: autoConfigDetails.buildCommand ?? "", - } - ); - - updatedAutoConfigDetails.buildCommand = buildCommand; - } - - return updatedAutoConfigDetails; -} diff --git a/packages/autoconfig/src/errors.ts b/packages/autoconfig/src/errors.ts deleted file mode 100644 index 2bbb4cb3fb..0000000000 --- a/packages/autoconfig/src/errors.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { FatalError, UserError } from "@cloudflare/workers-utils"; -import type { TelemetryMessage } from "@cloudflare/workers-utils"; - -/** - * Base class for errors where something in a autoconfig frameworks' configuration goes - * something wrong. These are not reported to Sentry. - */ -export class AutoConfigFrameworkConfigurationError extends UserError {} - -/** - * Error thrown when autoconfig detection fails. - * Carries detection metadata (`frameworkId`, `configured`) so that callers can - * extract it for telemetry without the autoconfig library needing to know about - * the telemetry system. - */ -export class AutoConfigDetectionError extends FatalError { - /** The detected framework identifier (if detection got far enough to determine it). */ - readonly frameworkId: string | undefined; - /** Whether the project was already configured at the time of the error. */ - readonly configured: boolean; - - /** - * @param message - The human-readable error message. - * @param options - Error options including telemetry message, optional code, and detection metadata. - */ - constructor( - message: string, - options: TelemetryMessage & { - code?: number; - frameworkId?: string; - configured: boolean; - } - ) { - super(message, options); - Object.setPrototypeOf(this, new.target.prototype); - this.frameworkId = options.frameworkId; - this.configured = options.configured; - } -} diff --git a/packages/autoconfig/src/frameworks/all-frameworks.ts b/packages/autoconfig/src/frameworks/all-frameworks.ts deleted file mode 100644 index 5545847809..0000000000 --- a/packages/autoconfig/src/frameworks/all-frameworks.ts +++ /dev/null @@ -1,290 +0,0 @@ -import assert from "node:assert"; -import { Analog } from "./analog"; -import { Angular } from "./angular"; -import { Astro } from "./astro"; -import { NextJs } from "./next"; -import { Nuxt } from "./nuxt"; -import { Qwik } from "./qwik"; -import { ReactRouter } from "./react-router"; -import { SolidStart } from "./solid-start"; -import { Static } from "./static"; -import { SvelteKit } from "./sveltekit"; -import { TanstackStart } from "./tanstack"; -import { Vike } from "./vike"; -import { Vite } from "./vite"; -import { Waku } from "./waku"; -import type { AutoConfigFrameworkPackageInfo, FrameworkInfo } from "."; - -/** - * Information about all the known frameworks, including frameworks that we know about but we don't support. - * - * The "static" framework is not included in this list. - */ -export const allKnownFrameworks = [ - { - id: "analog", - name: "Analog", - class: Analog, - frameworkPackageInfo: { - name: "@analogjs/platform", - // Analog didn't work well before 2.0.0 with Cloudflare - // See: https://github.com/cloudflare/workers-sdk/issues/11470 - minimumVersion: "2.0.0", - maximumKnownMajorVersion: "2", - }, - supportsCf: false, - supported: true, - }, - { - id: "angular", - name: "Angular", - class: Angular, - frameworkPackageInfo: { - name: "@angular/core", - // Angular 19 introduced ssr.experimentalPlatform and AngularAppEngine - // which are required for Cloudflare Workers support - // See: https://github.com/angular/angular-cli/releases/tag/19.0.0 - // Angular 22 renamed experimentalPlatform to platform - // See: https://github.com/angular/angular-cli/commit/af2c7e9444fba81d3b1fd2d37dc4412f8305b5ed - minimumVersion: "19.0.0", - maximumKnownMajorVersion: "22", - }, - supportsCf: false, - supported: true, - }, - { - id: "astro", - name: "Astro", - class: Astro, - frameworkPackageInfo: { - name: "astro", - // Version 4 was the earliest version that we manually tested - // in https://github.com/cloudflare/workers-sdk/pull/12938 - // earlier versions might also be supported but we haven't checked them - minimumVersion: "4.0.0", - maximumKnownMajorVersion: "7", - }, - supportsCf: true, - supported: true, - }, - { - id: "hono", - name: "Hono", - supported: false, - }, - { - id: "next", - name: "Next.js", - class: NextJs, - frameworkPackageInfo: { - name: "next", - // 14.2.35 is the earliest version of Next.js officially supported by open-next - // see: https://github.com/cloudflare/workers-sdk/pull/11704#discussion_r2634519440 - minimumVersion: "14.2.35", - maximumKnownMajorVersion: "16", - }, - supportsCf: true, - supported: true, - }, - { - id: "nuxt", - name: "Nuxt", - class: Nuxt, - frameworkPackageInfo: { - name: "nuxt", - // 3.21.0 is the first Nuxt version with Nitro 2.11+ which supports - // cloudflare.deployConfig and cloudflare.nodeCompat options - // See: https://github.com/nuxt/nuxt/releases/tag/v3.21.0 - // See: https://github.com/nitrojs/nitro/releases/tag/v2.11.0 - minimumVersion: "3.21.0", - maximumKnownMajorVersion: "4", - }, - supportsCf: false, - supported: true, - }, - { - id: "qwik", - name: "Qwik", - class: Qwik, - frameworkPackageInfo: { - name: "@builder.io/qwik", - // 1.1.0 added the `platform` option in the qwikCity() Vite plugin - // which is required for getPlatformProxy integration - // See: https://github.com/QwikDev/qwik/pull/3604 - minimumVersion: "1.1.0", - maximumKnownMajorVersion: "1", - }, - supportsCf: false, - supported: true, - }, - { - id: "react-router", - name: "React Router", - class: ReactRouter, - frameworkPackageInfo: { - name: "react-router", - // React Router v7 introduced framework mode with Vite integration and - // react-router.config.ts which are required for Cloudflare Workers support - // See: https://remix.run/blog/react-router-v7 - minimumVersion: "7.0.0", - maximumKnownMajorVersion: "8", - }, - supportsCf: true, - supported: true, - }, - { - id: "solid-start", - name: "Solid Start", - class: SolidStart, - frameworkPackageInfo: { - name: "@solidjs/start", - // 1.0.0 is the first stable release with Nitro/Cloudflare Workers support - // See: https://github.com/solidjs/solid-start/releases/tag/v1.0.0 - minimumVersion: "1.0.0", - maximumKnownMajorVersion: "2", - }, - supportsCf: false, - supported: true, - }, - { - id: "svelte-kit", - name: "SvelteKit", - class: SvelteKit, - frameworkPackageInfo: { - name: "@sveltejs/kit", - // 2.20.3 is required by @sveltejs/adapter-cloudflare@7.0.0 which first - // added Workers Static Assets support (cfTarget:workers option) - // See: https://github.com/sveltejs/kit/releases/tag/%40sveltejs%2Fadapter-cloudflare%407.0.0 - minimumVersion: "2.20.3", - maximumKnownMajorVersion: "2", - }, - supportsCf: false, - supported: true, - }, - { - id: "tanstack-start", - name: "TanStack Start", - class: TanstackStart, - frameworkPackageInfo: { - name: "@tanstack/react-start", - // 1.132.0 is the first Release Candidate for TanStack Start that supports Cloudflare - // See: https://github.com/TanStack/router/releases/tag/v1.132.0 - minimumVersion: "1.132.0", - maximumKnownMajorVersion: "1", - }, - supportsCf: true, - supported: true, - }, - { - id: "vite", - name: "Vite", - class: Vite, - frameworkPackageInfo: { - name: "vite", - // Vite 6 introduced the Environment API which @cloudflare/vite-plugin requires - // See: https://vite.dev/blog/announcing-vite6#experimental-environment-api - // (6.1.0 is the minimum version supported by the vite plugin: - // https://github.com/cloudflare/workers-sdk/blob/b9b7e9d9fe/packages/vite-plugin-cloudflare/package.json#L80 - // we anyways allow for `6.0.x` versions since we bump them to `^6.1.0` in the autoconfig process) - minimumVersion: "6.0.0", - maximumKnownMajorVersion: "8", - }, - supportsCf: true, - supported: true, - }, - { - id: "vike", - name: "Vike", - class: Vike, - frameworkPackageInfo: { - name: "vike", - minimumVersion: "0.0.0", - maximumKnownMajorVersion: "0", - }, - supportsCf: false, - supported: true, - }, - { - id: "waku", - name: "Waku", - class: Waku, - frameworkPackageInfo: { - name: "waku", - // Autoconfig could support Waku before 1.0.0-alpha.4, but different autoconfig logic - // would need to be implemented for such versions, so we just decided to only support - // version 1.0.0-alpha.4 and up - // See: https://github.com/cloudflare/workers-sdk/pull/12657 - minimumVersion: "1.0.0-alpha.4", - maximumKnownMajorVersion: "1", - }, - supportsCf: false, - supported: true, - }, - { - id: "cloudflare-pages", - name: "Cloudflare Pages", - // Autoconfiguring a Pages project into a Workers one is not yet supported - supported: false, - }, - { - id: "hydrogen", - name: "Hydrogen", - supported: false, - }, -] as const satisfies FrameworkInfo[]; - -/** - * Type specific for the "static" framework. - * - * It is supported by autoconfig but, unlike all other frameworks, it doesn't have a package associated to it - */ -type StaticFrameworkInfo = Omit< - Extract, - "frameworkPackageInfo" ->; - -export const staticFramework = { - id: "static", - name: "Static", - class: Static, - supportsCf: true, - supported: true, -} as const satisfies StaticFrameworkInfo; - -/** Information for all the possible frameworks. This includes the "static" framework */ -export const allFrameworksInfos = [ - staticFramework, - ...allKnownFrameworks, -] as const satisfies (FrameworkInfo | StaticFrameworkInfo)[]; - -/** - * Gets the package information for a given framework, erroring if the framework - * could not be determined or is not supported. - * - * Returns `undefined` for the "static" framework, which has no associated package. - * - * @param frameworkId The id of the target framework - * @returns The framework's target package info, or undefined if the framework is "static" - */ -export function getFrameworkPackageInfo( - frameworkId: FrameworkInfo["id"] -): AutoConfigFrameworkPackageInfo | undefined { - if (frameworkId === staticFramework.id) { - // The "static" framework does not have an associated package - return undefined; - } - const targetedFramework = allKnownFrameworks.find( - (framework) => framework.id === frameworkId - ); - assert( - targetedFramework, - `Could not determine framework package info for ${JSON.stringify( - frameworkId - )}` - ); - assert( - targetedFramework.supported, - `Framework unexpectedly not supported ${JSON.stringify(frameworkId)}` - ); - return targetedFramework.frameworkPackageInfo; -} diff --git a/packages/autoconfig/src/frameworks/analog.ts b/packages/autoconfig/src/frameworks/analog.ts deleted file mode 100644 index ef55cd72b2..0000000000 --- a/packages/autoconfig/src/frameworks/analog.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { existsSync } from "node:fs"; -import { join } from "node:path"; -import { updateStatus } from "@cloudflare/cli-shared-helpers"; -import { blue } from "@cloudflare/cli-shared-helpers/colors"; -import { - mergeObjectProperties, - transformFile, -} from "@cloudflare/shared-ast-primitives"; -import { DEFAULT_COMPAT_DATE } from "@cloudflare/workers-utils"; -import * as recast from "recast"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class Analog extends Framework { - async configure({ - dryRun, - projectPath, - }: ConfigurationOptions): Promise { - if (!dryRun) { - await updateViteConfig(projectPath); - } - - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./dist/analog/server/index.mjs", - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: "./dist/analog/public" }, - }; - } -} - -async function updateViteConfig(projectPath: string) { - const viteConfigTsPAth = join(projectPath, "vite.config.ts"); - const viteConfigJsPath = join(projectPath, "vite.config.js"); - - let viteConfigPath: string; - - if (existsSync(viteConfigTsPAth)) { - viteConfigPath = viteConfigTsPAth; - } else if (existsSync(viteConfigJsPath)) { - viteConfigPath = viteConfigJsPath; - } else { - throw new Error("Could not find Vite config file to modify"); - } - - const compatDate = DEFAULT_COMPAT_DATE; - - updateStatus(`Updating configuration in ${blue(viteConfigPath)}`); - - transformFile(viteConfigPath, { - visitCallExpression: function (n) { - const callee = n.node.callee as recast.types.namedTypes.Identifier; - if (callee.name !== "analog") { - return this.traverse(n); - } - - const b = recast.types.builders; - const presetDef = [ - b.objectProperty( - b.identifier("nitro"), - b.objectExpression([ - // preset: "cloudflare_module" - b.objectProperty( - b.identifier("preset"), - b.stringLiteral("cloudflare_module") - ), - b.objectProperty( - b.identifier("compatibilityDate"), - b.stringLiteral(compatDate) - ), - ]) - ), - ]; - - if (n.node.arguments.length === 0) { - n.node.arguments.push(b.objectExpression(presetDef)); - } else { - mergeObjectProperties( - n.node.arguments[0] as recast.types.namedTypes.ObjectExpression, - presetDef - ); - } - - return false; - }, - }); -} diff --git a/packages/autoconfig/src/frameworks/angular.ts b/packages/autoconfig/src/frameworks/angular.ts deleted file mode 100644 index 8208267201..0000000000 --- a/packages/autoconfig/src/frameworks/angular.ts +++ /dev/null @@ -1,154 +0,0 @@ -import assert from "node:assert"; -import { readFile, writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import { brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { spinner } from "@cloudflare/cli-shared-helpers/interactive"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { parseJSONC } from "@cloudflare/workers-utils"; -import semiver from "semiver"; -import dedent from "ts-dedent"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { PackageManager } from "@cloudflare/workers-utils"; - -export class Angular extends Framework { - async configure({ - workerName, - outputDir, - dryRun, - packageManager, - isWorkspaceRoot, - }: ConfigurationOptions): Promise { - const angularJson = parseJSONC( - await readFile(resolve("angular.json"), "utf8") - ) as AngularJson; - - if (hasSsr(angularJson, workerName)) { - this.configurationDescription = "Configuring project for Angular"; - if (!dryRun) { - await updateAngularJson(workerName, angularJson, this.frameworkVersion); - await overrideServerFile(); - await installAdditionalDependencies(packageManager, isWorkspaceRoot); - } - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./dist/server/server.mjs", - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: `${outputDir}browser` }, - }; - } else { - this.configurationDescription = - "Configuring Angular SPA project (assets only)"; - return { - buildTool: "wrangler", - workerConfig: {}, - buildConfig: { assetsDirectory: outputDir }, - }; - } - } -} - -/** - * Checks whether the given Angular project has SSR configured. - * SSR is considered enabled when `architect.build.options.ssr` exists and is truthy. - */ -function hasSsr(angularJson: AngularJson, projectName: string): boolean { - const ssr = angularJson.projects[projectName]?.architect?.build?.options?.ssr; - return !!ssr; -} - -async function updateAngularJson( - projectName: string, - angularJson: AngularJson, - frameworkVersion: string -) { - const s = spinner(); - s.start(`Updating angular.json config`); - - // Update builder - const architectSection = angularJson.projects[projectName].architect; - architectSection.build.options.outputPath = "dist"; - architectSection.build.options.outputMode = "server"; - // ssr is guaranteed to be truthy here (checked by hasSsr before calling this). - // `ssr: true` is a valid Angular shorthand for SSR with defaults — normalise it - // to an object before setting properties on it. - assert(architectSection.build.options.ssr); - if (typeof architectSection.build.options.ssr === "boolean") { - architectSection.build.options.ssr = {}; - } - const platformKey = - semiver(frameworkVersion, "22.0.0") >= 0 - ? "platform" - : "experimentalPlatform"; - architectSection.build.options.ssr[platformKey] = "neutral"; - - await writeFile( - resolve("angular.json"), - JSON.stringify(angularJson, null, 2) - ); - - s.stop(`${brandColor(`updated`)} ${dim(`\`angular.json\``)}`); -} - -async function overrideServerFile() { - await writeFile( - resolve("src/server.ts"), - dedent` - import { AngularAppEngine, createRequestHandler } from '@angular/ssr'; - - const angularApp = new AngularAppEngine({ - // It is safe to set allow \`localhost\`, so that SSR can run in local development, - // as, in production, Cloudflare will ensure that \`localhost\` is not the host. - allowedHosts: ['localhost'], - }); - - /** - * This is a request handler used by the Angular CLI (dev-server and during build). - */ - export const reqHandler = createRequestHandler(async (req) => { - const res = await angularApp.handle(req); - - return res ?? new Response('Page not found.', { status: 404 }); - }); - - export default { fetch: reqHandler }; - ` - ); -} - -async function installAdditionalDependencies( - packageManager: PackageManager, - isWorkspaceRoot: boolean -) { - await installPackages(packageManager.type, ["xhr2"], { - dev: true, - startText: "Installing additional dependencies", - doneText: `${brandColor("installed")}`, - isWorkspaceRoot, - }); -} - -type AngularJson = { - projects: Record< - string, - { - architect: { - build: { - options: { - outputPath: string; - outputMode: string; - ssr?: Record | boolean | null; - assets: string[]; - }; - }; - }; - } - >; -}; diff --git a/packages/autoconfig/src/frameworks/astro.ts b/packages/autoconfig/src/frameworks/astro.ts deleted file mode 100644 index a685569d86..0000000000 --- a/packages/autoconfig/src/frameworks/astro.ts +++ /dev/null @@ -1,311 +0,0 @@ -import { - existsSync, - readFileSync as fsReadFileSync, - writeFileSync, -} from "node:fs"; -import { join } from "node:path"; -import { updateStatus } from "@cloudflare/cli-shared-helpers"; -import { blue, brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { runCommand } from "@cloudflare/cli-shared-helpers/command"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { - mergeObjectProperties, - transformFile, -} from "@cloudflare/shared-ast-primitives"; -import { parseJSONC } from "@cloudflare/workers-utils"; -import * as recast from "recast"; -import semiver from "semiver"; -import { Framework } from "./framework-class"; -import type { AutoConfigContext } from "../context"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { PackageManager } from "@cloudflare/workers-utils"; - -export class Astro extends Framework { - override readonly supportsMode = true; - - async configure({ - outputDir, - dryRun, - packageManager, - projectPath, - isWorkspaceRoot, - context, - }: ConfigurationOptions): Promise { - const astroVersion = this.frameworkVersion; - - const { npx } = packageManager; - if (!dryRun) { - if (semiver(astroVersion, "6.0.0") >= 0) { - // For Astro 6.0.0+ use the native `astro add cloudflare` command - await runCommand([npx, "astro", "add", "cloudflare", "-y"], { - silent: true, - startText: "Installing adapter", - doneText: `${brandColor("installed")} ${dim( - `via \`${npx} astro add cloudflare\`` - )}`, - }); - } else { - // For older versions of Astro we need to apply manual configuration since `astro add cloudflare` - // tries to install the latest version of the adapter causing conflicts - - // Note: here the Astro version can only be 5 or 4 because of the minimum version validation - const astroMajorVersion = semiver(astroVersion, "5.0.0") >= 0 ? 5 : 4; - await configureAstroLegacy( - projectPath, - isWorkspaceRoot, - packageManager, - astroMajorVersion, - context - ); - } - - writeFileSync("public/.assetsignore", "_worker.js\n_routes.json"); - } - - if (semiver(astroVersion, "6.0.0") < 0) { - // Before version 6 Astro required a wrangler config file - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: `${outputDir}/_worker.js/index.js`, - compatibilityFlags: ["global_fetch_strictly_public"], - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: outputDir }, - }; - } - - // From version 6 Astro doesn't need a wrangler config file but generates a redirected config on build - return { - workerConfig: null, - }; - } - - configurationDescription = - 'Configuring project for Astro with "astro add cloudflare"'; -} - -/** - * Finds the Astro config file in the project directory. - * Checks for astro.config.mjs, astro.config.ts, and astro.config.js in that order. - * - * @param projectPath The path of the project - * @returns The path to the Astro config file - * @throws Error if no config file is found - */ -function findAstroConfigFile(projectPath: string): string { - const extensions = ["mjs", "mts", "ts", "js"]; - for (const ext of extensions) { - const configPath = join(projectPath, `astro.config.${ext}`); - if (existsSync(configPath)) { - return configPath; - } - } - throw new Error( - "Could not find Astro config file (astro.config.mjs, astro.config.mts, astro.config.ts, or astro.config.js)" - ); -} - -/** - * Updates the Astro config file to add the Cloudflare adapter. - * This replicates the logic from `astro add cloudflare` for Astro versions < 6.0.0. - * - * @param projectPath The path of the project - * @param astroMajorVersion The major version of Astro (4 or 5) to determine the config options - */ -function updateAstroConfig( - projectPath: string, - astroMajorVersion: 4 | 5 -): void { - const configPath = findAstroConfigFile(projectPath); - - updateStatus(`Updating configuration in ${blue(configPath)}`); - - // Track the adapter identifier name (either from existing import or the one we add) - let adapterIdentifier = "cloudflare"; - - transformFile(configPath, { - // First pass: check for existing cloudflare import and add if missing - visitProgram(path) { - const body = path.node.body; - const b = recast.types.builders; - - // Check if cloudflare import already exists and capture the local identifier - let hasCloudflareImport = false; - for (const node of body) { - if ( - node.type === "ImportDeclaration" && - node.source.value === "@astrojs/cloudflare" - ) { - hasCloudflareImport = true; - // Find the default import specifier and capture its local name - for (const specifier of node.specifiers ?? []) { - if ( - specifier.type === "ImportDefaultSpecifier" && - specifier.local - ) { - // specifier.local is an Identifier node with a `name` property - const local = specifier.local as { name: string }; - adapterIdentifier = local.name; - break; - } - } - break; - } - } - - // Add the import if it doesn't exist - if (!hasCloudflareImport) { - const importDeclaration = b.importDeclaration( - [b.importDefaultSpecifier(b.identifier("cloudflare"))], - b.literal("@astrojs/cloudflare") - ); - - // Find the last import statement and insert after it - let lastImportIndex = -1; - for (let i = 0; i < body.length; i++) { - if (body[i].type === "ImportDeclaration") { - lastImportIndex = i; - } - } - - if (lastImportIndex >= 0) { - body.splice(lastImportIndex + 1, 0, importDeclaration); - } else { - // No imports found, add at the beginning - body.unshift(importDeclaration); - } - } - - this.traverse(path); - }, - - // Second pass: add adapter (and output for Astro 4) to defineConfig - visitCallExpression(path) { - const callee = path.node.callee; - - // Check if this is a defineConfig call - if (callee.type !== "Identifier" || callee.name !== "defineConfig") { - return this.traverse(path); - } - - const b = recast.types.builders; - - // Create the adapter property using the captured identifier name - const adapterProp = b.objectProperty( - b.identifier("adapter"), - b.callExpression(b.identifier(adapterIdentifier), []) - ); - - const propsToAdd: recast.types.namedTypes.ObjectProperty[] = []; - - if (astroMajorVersion === 4) { - // Astro 4 requires explicit output: "hybrid" for SSR - const outputProp = b.objectProperty( - b.identifier("output"), - b.literal("hybrid") - ); - propsToAdd.push(outputProp); - } - propsToAdd.push(adapterProp); - - // Get or create the config object argument - if (path.node.arguments.length === 0) { - path.node.arguments.push(b.objectExpression(propsToAdd)); - } else { - const configArg = path.node - .arguments[0] as recast.types.namedTypes.ObjectExpression; - if (configArg.type === "ObjectExpression") { - mergeObjectProperties(configArg, propsToAdd); - } - } - - return false; - }, - }); -} - -/** - * Updates the tsconfig.json to include worker-configuration.d.ts. - * This replicates part of the `astro add cloudflare` behavior. - * - * @param projectPath The path of the project - * @param context The autoconfig context providing logger and other dependencies - */ -function updateTsConfig(projectPath: string, context: AutoConfigContext) { - const tsconfigPath = join(projectPath, "tsconfig.json"); - if (!existsSync(tsconfigPath)) { - return; - } - - try { - const content = fsReadFileSync(tsconfigPath, "utf-8"); - const tsconfig = parseJSONC(content, tsconfigPath) as Record< - string, - unknown - >; - - const includeEntry = "./worker-configuration.d.ts"; - - if (!tsconfig.include) { - // If `include` is not defined, the tsconfig likely inherits it from a parent config (e.g., "extends": "astro/tsconfigs/base"). - // Adding an `include` field here would override the parent's includes, breaking type-checking. - // Instead, warn the user to add it manually. - context.logger.warn( - `Could not find an existing \`include\` field in tsconfig.json. You may need to manually add ${JSON.stringify( - includeEntry - )} to your tsconfig.json \`include\` array.` - ); - return; - } - - if (!(tsconfig.include as string[]).includes(includeEntry)) { - (tsconfig.include as string[]).push(includeEntry); - writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, "\t")); - updateStatus( - `Updated ${blue("tsconfig.json")} to include ${blue(includeEntry)}` - ); - } - } catch { - context.logger.warn( - `Could not update tsconfig.json to include worker-configuration.d.ts. You may need to add it manually.` - ); - } -} - -/** - * Configures an Astro project for Cloudflare deployment when running Astro < 6.0.0. - * This replicates the core logic from `astro add cloudflare` command since that command - * is not available or behaves differently in older Astro versions. - * - * @param projectPath The path of the project - * @param isWorkspaceRoot Whether the project is at the root of a workspace (affects package installation flags) - * @param packageManager The package manager to use for installing dependencies - * @param astroMajorVersion The major version of Astro (4 or 5) to determine the correct adapter version - */ -async function configureAstroLegacy( - projectPath: string, - isWorkspaceRoot: boolean, - packageManager: PackageManager, - astroMajorVersion: 4 | 5, - context: AutoConfigContext -): Promise { - const astroCloudflarePackageVersion = astroMajorVersion === 5 ? 12 : 11; - - await installPackages( - packageManager.type, - [`@astrojs/cloudflare@${astroCloudflarePackageVersion}`], - { - startText: `Installing @astrojs/cloudflare adapter (version ${astroCloudflarePackageVersion})`, - doneText: `${brandColor("installed")} ${dim("@astrojs/cloudflare")}`, - isWorkspaceRoot, - } - ); - updateAstroConfig(projectPath, astroMajorVersion); - updateTsConfig(projectPath, context); -} diff --git a/packages/autoconfig/src/frameworks/framework-class.ts b/packages/autoconfig/src/frameworks/framework-class.ts deleted file mode 100644 index 586576be83..0000000000 --- a/packages/autoconfig/src/frameworks/framework-class.ts +++ /dev/null @@ -1,138 +0,0 @@ -import assert from "node:assert"; -import semiver from "semiver"; -import { AutoConfigFrameworkConfigurationError } from "../errors"; -import { getInstalledPackageVersion } from "./utils/packages"; -import type { AutoConfigFrameworkPackageInfo, FrameworkInfo } from "."; -import type { AutoConfigContext, AutoConfigTarget } from "../context"; -import type { WorkerConfig } from "@cloudflare/config"; -import type { PackageManager } from "@cloudflare/workers-utils"; - -export abstract class Framework { - readonly id: FrameworkInfo["id"]; - readonly name: FrameworkInfo["name"]; - declare readonly env?: Readonly>; - /** Whether this framework's build and development commands accept `--mode`. */ - readonly supportsMode: boolean = false; - - #frameworkVersion: string | undefined; - get frameworkVersion(): string { - assert( - this.#frameworkVersion, - `The version for ${JSON.stringify(this.name)} is unexpectedly missing` - ); - return this.#frameworkVersion; - } - - constructor(frameworkInfo: Pick) { - this.id = frameworkInfo.id; - this.name = frameworkInfo.name; - } - - isConfigured( - _projectPath: string, - { - target: _target = "cf", - }: { - target?: AutoConfigTarget; - } = {} - ): boolean { - return false; - } - - abstract configure( - options: ConfigurationOptions - ): Promise | ConfigurationResults; - - configurationDescription?: string; - - /** - * Validates the installed framework version against the supported range and - * stores it for later access via the `frameworkVersion` getter. - * Warns via the context logger if the version exceeds `maximumKnownMajorVersion`. - * - * @param projectPath - Path to the project root used to resolve the installed version. - * @param frameworkPackageInfo - Package metadata including name and version bounds. - * @param context - The autoconfig context providing logger and other dependencies. - * @throws {AssertionError} If the installed version cannot be determined. - * @throws {AutoConfigFrameworkConfigurationError} If the version is below `minimumVersion`. - */ - validateFrameworkVersion( - projectPath: string, - frameworkPackageInfo: AutoConfigFrameworkPackageInfo, - context: AutoConfigContext - ) { - const frameworkVersion = getInstalledPackageVersion( - frameworkPackageInfo.name, - projectPath - ); - - assert( - frameworkVersion, - `Unable to detect the version of the \`${frameworkPackageInfo.name}\` package` - ); - - if (semiver(frameworkVersion, frameworkPackageInfo.minimumVersion) < 0) { - throw new AutoConfigFrameworkConfigurationError( - `The version of ${this.name} used in the project (${JSON.stringify( - frameworkVersion - )}) cannot be automatically configured. Please update the ${ - this.name - } version to at least ${JSON.stringify( - frameworkPackageInfo.minimumVersion - )} and try again.`, - { telemetryMessage: "autoconfig framework version unsupported" } - ); - } - - if ( - semiver(frameworkVersion, frameworkPackageInfo.maximumKnownMajorVersion) > - 0 - ) { - context.logger.warn( - `The version of ${this.name} used in the project (${JSON.stringify( - frameworkVersion - )}) is not officially supported, and may fail to correctly configure. Please report any issues to https://github.com/cloudflare/workers-sdk/issues` - ); - } - - this.#frameworkVersion = frameworkVersion; - } -} - -export type ConfigurationOptions = { - target: AutoConfigTarget; - outputDir: string; - projectPath: string; - workerName: string; - dryRun: boolean; - packageManager: PackageManager; - isWorkspaceRoot: boolean; - context: AutoConfigContext; -}; - -export type PackageJsonScriptsOverrides = { - preview?: string; // legacy Wrangler preview command, default is `npm run build && wrangler dev` - deploy?: string; // legacy Wrangler deploy command, default is `npm run build && wrangler deploy` - typegen?: string; // default is `wrangler types` -}; - -export type BuildConfig = { - assetsDirectory?: string; -}; - -export type ConfigurationResults = { - /** The tool that cf should delegate build and development commands to. */ - buildTool?: "vite" | "wrangler"; - /** Worker configuration generated by the framework. `null` if an external tool generates it. */ - workerConfig: Partial | null; - /** Build configuration that complements the Worker configuration. */ - buildConfig?: BuildConfig; - // Scripts to override in the package.json. Most frameworks should not need to do this, as their default detected build command will be sufficient - packageJsonScriptsOverrides?: PackageJsonScriptsOverrides; - // Build command to override the standard one (`npm run build` or framework's build command) - buildCommandOverride?: string; - // Deploy command to override the standard one (`npx wrangler deploy`) - deployCommandOverride?: string; - // Version command to override the standard one (`npx wrangler versions upload`) - versionCommandOverride?: string; -}; diff --git a/packages/autoconfig/src/frameworks/index.ts b/packages/autoconfig/src/frameworks/index.ts deleted file mode 100644 index 16d44d84b8..0000000000 --- a/packages/autoconfig/src/frameworks/index.ts +++ /dev/null @@ -1,114 +0,0 @@ -import assert from "node:assert"; -import { AutoConfigFrameworkConfigurationError } from "../errors"; -import { allFrameworksInfos, staticFramework } from "./all-frameworks"; -import { NoOpFramework } from "./no-op"; -import type { AutoConfigTarget } from "../context"; -import type { Framework } from "./framework-class"; - -export type { Framework, PackageJsonScriptsOverrides } from "./framework-class"; - -/** Set of the ids of all the possible frameworks, including the "static" framework */ -const allKnownFrameworksIds = new Set( - allFrameworksInfos.map(({ id }) => id) -); - -/** - * Identifies whether a given id maps to a known framework's id - * - * @param frameworkId The target id to check - * @returns true if the id is that of a known framework, false otherwise - */ -export function isKnownFramework(frameworkId: string): boolean { - return allKnownFrameworksIds.has(frameworkId); -} - -/** - * Gets a class instance for a framework based on its id - * - * @param frameworkId The target framework's id - * @returns The class for the framework, defaulting to the static framework is the id is not recognized - */ -export function getFrameworkClassInstance( - frameworkId: FrameworkInfo["id"] -): Framework { - const targetedFramework = allFrameworksInfos.find( - (framework) => framework.id === frameworkId - ); - const framework = targetedFramework ?? staticFramework; - const targetClass = - framework.supported === false ? NoOpFramework : framework.class; - - return new targetClass({ id: framework.id, name: framework.name }); -} - -/** - * Checks whether a framework is supported by autoconfig. - * - * @param frameworkId The target framework's id - * @returns a boolean indicating wether the framework is supported - */ -export function isFrameworkSupported( - frameworkId: FrameworkInfo["id"] -): boolean { - const targetedFramework = allFrameworksInfos.find( - (framework) => framework.id === frameworkId - ); - assert( - targetedFramework, - `Unexpected unknown framework id: ${JSON.stringify(frameworkId)}` - ); - return targetedFramework.supported; -} - -/** - * Validates that a framework supports the requested autoconfig target. - * - * @param framework - The detected framework. - * @param target - The requested autoconfig target. - * @throws {AutoConfigFrameworkConfigurationError} If a Wrangler-only framework is targeted by `cf`. - */ -export function validateFrameworkTargetSupport( - framework: Framework, - target: AutoConfigTarget -): void { - if (target !== "cf") { - return; - } - - const frameworkInfo = allFrameworksInfos.find( - ({ id }) => id === framework.id - ); - if (frameworkInfo?.supported !== true || frameworkInfo.supportsCf) { - return; - } - - throw new AutoConfigFrameworkConfigurationError( - `cf does not support ${framework.name} projects yet. You can still use Wrangler to develop and deploy this project.`, - { telemetryMessage: "autoconfig framework unsupported for cf" } - ); -} - -export type FrameworkInfo = { - id: string; - name: string; -} & ( - | { supported: false } - | { - supported: true; - supportsCf: boolean; - class: typeof Framework; - frameworkPackageInfo: AutoConfigFrameworkPackageInfo; - } -); - -/** - * AutoConfig information for a package that defines a framework. - */ -export type AutoConfigFrameworkPackageInfo = { - /** The package name (e.g. "astro" for the Astro framework and "@solidjs/start" for the SolidStart framework) */ - name: string; - /** The minimum version (if any) of the package/framework that autoconfig supports */ - minimumVersion: string; - /** The latest major version of the package/framework that autoconfig supports */ - maximumKnownMajorVersion: string; -}; diff --git a/packages/autoconfig/src/frameworks/next.ts b/packages/autoconfig/src/frameworks/next.ts deleted file mode 100644 index fb7a8a10d4..0000000000 --- a/packages/autoconfig/src/frameworks/next.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { runCommand } from "@cloudflare/cli-shared-helpers/command"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class NextJs extends Framework { - async configure({ - dryRun, - projectPath, - packageManager, - }: ConfigurationOptions): Promise { - const { npx, dlx } = packageManager; - - if (!dryRun) { - await runCommand( - [ - ...dlx, - "@opennextjs/cloudflare", - "migrate", - // Note: we force-install so that even if an incompatible version of - // Next.js is used this installation still succeeds, moving users - // (hopefully) in right direction (instead of failing at this step) - "--force-install", - ], - { - cwd: projectPath, - } - ); - } - - return { - // `@opennextjs/cloudflare migrate` creates the wrangler config file - workerConfig: {}, - packageJsonScriptsOverrides: { - preview: "opennextjs-cloudflare build && opennextjs-cloudflare preview", - deploy: "opennextjs-cloudflare build && opennextjs-cloudflare deploy", - }, - buildCommandOverride: `${npx} opennextjs-cloudflare build`, - deployCommandOverride: `${npx} opennextjs-cloudflare deploy`, - versionCommandOverride: `${npx} opennextjs-cloudflare upload`, - }; - } - - configurationDescription = - "Configuring project for Next.js with OpenNext by running `@opennextjs/cloudflare migrate`"; -} diff --git a/packages/autoconfig/src/frameworks/no-op.ts b/packages/autoconfig/src/frameworks/no-op.ts deleted file mode 100644 index 25155a9c8d..0000000000 --- a/packages/autoconfig/src/frameworks/no-op.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Framework } from "./framework-class"; -import type { ConfigurationResults } from "./framework-class"; - -export class NoOpFramework extends Framework { - async configure(): Promise { - return { - workerConfig: {}, - }; - } -} diff --git a/packages/autoconfig/src/frameworks/nuxt.ts b/packages/autoconfig/src/frameworks/nuxt.ts deleted file mode 100644 index 3d9d63b765..0000000000 --- a/packages/autoconfig/src/frameworks/nuxt.ts +++ /dev/null @@ -1,93 +0,0 @@ -import path from "node:path"; -import { brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { - mergeObjectProperties, - transformFile, -} from "@cloudflare/shared-ast-primitives"; -import * as recast from "recast"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -const updateNuxtConfig = (projectPath: string) => { - const configFile = path.join(projectPath, "nuxt.config.ts"); - - const b = recast.types.builders; - - const presetDef = b.objectProperty( - b.identifier("nitro"), - b.objectExpression([ - b.objectProperty( - b.identifier("preset"), - b.stringLiteral("cloudflare_module") - ), - b.objectProperty( - b.identifier("cloudflare"), - b.objectExpression([ - b.objectProperty( - b.identifier("deployConfig"), - b.booleanLiteral(true) - ), - b.objectProperty(b.identifier("nodeCompat"), b.booleanLiteral(true)), - ]) - ), - ]) - ); - - const moduleDef = b.objectProperty( - b.identifier("modules"), - b.arrayExpression([b.stringLiteral("nitro-cloudflare-dev")]) - ); - - transformFile(configFile, { - visitCallExpression: function (n) { - const callee = n.node.callee as recast.types.namedTypes.Identifier; - if (callee.name === "defineNuxtConfig") { - mergeObjectProperties( - n.node.arguments[0] as recast.types.namedTypes.ObjectExpression, - [presetDef, moduleDef] - ); - } - - return this.traverse(n); - }, - }); -}; - -export class Nuxt extends Framework { - async configure({ - dryRun, - projectPath, - packageManager, - isWorkspaceRoot, - }: ConfigurationOptions): Promise { - if (!dryRun) { - await installPackages(packageManager.type, ["nitro-cloudflare-dev"], { - dev: true, - startText: "Installing the Cloudflare dev module", - doneText: `${brandColor(`installed`)} ${dim("nitro-cloudflare-dev")}`, - isWorkspaceRoot, - }); - updateNuxtConfig(projectPath); - } - - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./.output/server/index.mjs", - env: { - ASSETS: { type: "assets" }, - }, - observability: { - enabled: true, - }, - }, - buildConfig: { assetsDirectory: "./.output/public/" }, - }; - } - - configurationDescription = "Configuring project for Nuxt"; -} diff --git a/packages/autoconfig/src/frameworks/qwik.ts b/packages/autoconfig/src/frameworks/qwik.ts deleted file mode 100644 index 88d0dd90de..0000000000 --- a/packages/autoconfig/src/frameworks/qwik.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { endSection } from "@cloudflare/cli-shared-helpers"; -import { brandColor } from "@cloudflare/cli-shared-helpers/colors"; -import { - quoteShellArgs, - runCommand, -} from "@cloudflare/cli-shared-helpers/command"; -import { spinner } from "@cloudflare/cli-shared-helpers/interactive"; -import { transformFile } from "@cloudflare/shared-ast-primitives"; -import * as recast from "recast"; -import * as typescriptParser from "recast/parsers/typescript"; -import { usesTypescript } from "../uses-typescript"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { Program } from "esprima"; - -export class Qwik extends Framework { - async configure({ - projectPath, - dryRun, - packageManager, - }: ConfigurationOptions): Promise { - if (!dryRun) { - // Add the workers integration - const cmd = [ - // For some reason `pnpx qwik add` fails for qwik so we use `pnpm qwik add` instead. - packageManager.type === "pnpm" - ? packageManager.type - : packageManager.npx, - "qwik", - "add", - "cloudflare-workers", - "--skipConfirmation=true", - ]; - endSection(`Running ${quoteShellArgs(cmd)}`); - await runCommand(cmd); - - addBindingsProxy(projectPath); - } - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./dist/_worker.js", - compatibilityFlags: ["global_fetch_strictly_public"], - env: { - ASSET: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: "./dist" }, - packageJsonScriptsOverrides: { - preview: `${packageManager.type} run build && wrangler dev`, - deploy: `${packageManager.type} run build && wrangler deploy`, - }, - }; - } - - configurationDescription = - 'Configuring project for Qwik with "qwik add cloudflare-workers"'; -} - -function addBindingsProxy(projectPath: string) { - // Qwik only has a typescript template atm. - // This check is an extra precaution - if (!usesTypescript(projectPath)) { - return; - } - - const s = spinner(); - s.start("Updating `vite.config.ts`"); - - const b = recast.types.builders; - - const getPlatformProxyTsAstNodes = ( - recast.parse( - ` - let platform = {}; - - if (process.env.NODE_ENV === 'development') { - const { getPlatformProxy } = await import('wrangler'); - platform = await getPlatformProxy(); - } - `, - { parser: typescriptParser } - ).program as Program - ).body; - - transformFile("vite.config.ts", { - // Insert the env declaration after the last import (but before the rest of the body) - visitProgram: function (n) { - const lastImportIndex = n.node.body.findLastIndex( - (t) => t.type === "ImportDeclaration" - ); - const lastImport = n.get("body", lastImportIndex); - lastImport.insertAfter(...getPlatformProxyTsAstNodes); - - return this.traverse(n); - }, - // Pass the `platform` object from the declaration to the `qwikCity` plugin - visitCallExpression: function (n) { - const callee = n.node.callee as recast.types.namedTypes.Identifier; - if (callee.name !== "qwikCity") { - return this.traverse(n); - } - - // The config object passed to `qwikCity` - const configArgument = n.node.arguments[0] as - | recast.types.namedTypes.ObjectExpression - | undefined; - - const platformPropery = b.objectProperty.from({ - key: b.identifier("platform"), - value: b.identifier("platform"), - shorthand: true, - }); - - if (!configArgument) { - n.node.arguments = [b.objectExpression([platformPropery])]; - - return false; - } - - if (configArgument.type !== "ObjectExpression") { - throw new Error("Failed to update `vite.config.ts`"); - } - - // Add the `platform` object to the object - configArgument.properties.push(platformPropery); - - return false; - }, - }); - - s.stop(`${brandColor("updated")} \`vite.config.ts\``); -} diff --git a/packages/autoconfig/src/frameworks/react-router.ts b/packages/autoconfig/src/frameworks/react-router.ts deleted file mode 100644 index 8b94254d14..0000000000 --- a/packages/autoconfig/src/frameworks/react-router.ts +++ /dev/null @@ -1,531 +0,0 @@ -import assert from "node:assert"; -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; -import path from "node:path"; -import { brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { parseFile, transformFile } from "@cloudflare/shared-ast-primitives"; -import * as recast from "recast"; -import semiver from "semiver"; -import dedent from "ts-dedent"; -import { Framework } from "./framework-class"; -import { transformViteConfig } from "./utils/vite-config"; -import { installCloudflareVitePlugin } from "./utils/vite-plugin"; -import type { AutoConfigContext } from "../context"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { Program } from "esprima"; - -const b = recast.types.builders; - -/** - * Resolves the path to the React Router config file (`react-router.config.ts` or `.js`) - * in the given project directory. - * - * @param projectPath - Absolute path to the project root. - * @returns The resolved config file path, or `null` if neither `.ts` nor `.js` variant exists. - */ -function getReactRouterConfigPath(projectPath: string): string | null { - const filePathTS = path.join(projectPath, "react-router.config.ts"); - const filePathJS = path.join(projectPath, "react-router.config.js"); - - if (existsSync(filePathTS)) { - return filePathTS; - } - - if (existsSync(filePathJS)) { - return filePathJS; - } - - return null; -} - -/** - * Checks whether the middleware pattern should be used for the given React Router project. - * - * For React Router >= 8.0.0, middleware is enabled by default - * (ref: https://github.com/remix-run/react-router/pull/15078), so this always returns `true`. - * - * For earlier versions, it parses the user's `react-router.config.ts` (or `.js`) to check - * whether `future.v8_middleware` is explicitly set to `true`. - * - * This determines which code pattern to generate: - * - With middleware: simplified fetch handler using `cloudflare:workers` env pattern - * - Without middleware: traditional `AppLoadContext` pattern with `env`/`ctx` params - * - * Parses the config file read-only (via `parseFile`) without writing anything to disk. - * Handles both TS `satisfies`/`as` expressions and plain object exports. - * - * @param projectPath - Absolute path to the project root containing the React Router config file. - * @param frameworkVersion - React Router semver version string. When provided and - * >= 8.0.0, returns `true` without parsing the config file (middleware is the default in v8). - * @returns `true` if middleware is enabled (either by default in v8+ or via `future.v8_middleware` - * in the config), `false` otherwise (including when the config file is missing or has no - * `future` block). - */ -export function hasV8MiddlewareFlag( - projectPath: string, - frameworkVersion?: string -): boolean { - // React Router >= 8.0.0 has middleware enabled by default - if (frameworkVersion && semiver(frameworkVersion, "8.0.0") >= 0) { - return true; - } - - const filePath = getReactRouterConfigPath(projectPath); - if (!filePath) { - return false; - } - - let ast: Program | null = null; - try { - ast = parseFile(filePath); - } catch {} - - if (!ast) { - return false; - } - - let found = false; - recast.visit(ast, { - visitExportDefaultDeclaration(n) { - let node: recast.types.namedTypes.ObjectExpression | null = null; - if ( - (n.node.declaration.type === "TSAsExpression" || - n.node.declaration.type === "TSSatisfiesExpression") && - n.node.declaration.expression.type === "ObjectExpression" - ) { - node = n.node.declaration.expression; - } else if (n.node.declaration.type === "ObjectExpression") { - node = n.node.declaration; - } - - if (node) { - const futureProp = node.properties.find( - (p) => - p.type === "ObjectProperty" && - p.key.type === "Identifier" && - p.key.name === "future" && - p.value.type === "ObjectExpression" - ); - if ( - futureProp?.type === "ObjectProperty" && - futureProp.value.type === "ObjectExpression" - ) { - found = futureProp.value.properties.some( - (p) => - p.type === "ObjectProperty" && - p.key.type === "Identifier" && - p.key.name === "v8_middleware" && - p.value.type === "BooleanLiteral" && - p.value.value === true - ); - } - } - return false; - }, - }); - - return found; -} - -/** - * Transforms the user's `react-router.config.ts` (or `.js`) to ensure the - * `future.unstable_viteEnvironmentApi` or `future.v8_viteEnvironmentApi` flag - * is set to `true`. If a `future` block already exists, the flag is added or - * updated in place; otherwise a new `future` block is created. - * - * Supports TS `as` and `satisfies` expressions wrapping the default export object. - * - * @param projectPath - Absolute path to the project root containing the React Router config file. - * @param viteEnvironmentKey - The config property name to set, either - * `"unstable_viteEnvironmentApi"` (React Router < 7.10.0) or `"v8_viteEnvironmentApi"`. - * @throws {Error} If no `react-router.config.ts` or `.js` file exists in the project. - * @throws {Error} If the default export cannot be parsed as an object expression. - */ -function transformReactRouterConfig( - projectPath: string, - viteEnvironmentKey: ReturnType -) { - const filePath = getReactRouterConfigPath(projectPath); - if (!filePath) { - throw new Error("Could not find React Router config file to modify"); - } - - transformFile(filePath, { - /** - * Visit an export default declaration of the form: - * - * export default { - * ... - * } - * - * and add or modify the `future` property to look like: - * - * future: { - * unstable_viteEnvironmentApi: true // v8_viteEnvironment depending on the React Router version - * } - * - * For some extra complexity, this also supports TS `as` and `satisfies` expressions - */ - visitExportDefaultDeclaration(n) { - let node: recast.types.namedTypes.ObjectExpression; - if ( - (n.node.declaration.type === "TSAsExpression" || - n.node.declaration.type === "TSSatisfiesExpression") && - n.node.declaration.expression.type === "ObjectExpression" - ) { - node = n.node.declaration.expression; - } else if (n.node.declaration.type === "ObjectExpression") { - node = n.node.declaration; - } else { - throw new Error( - `Could not parse React Router config file. Please add the following snippet manually:\n future: {\n ${viteEnvironmentKey}: true,\n }` - ); - } - - assert(node.type === "ObjectExpression"); - - // Is there an existing `future` key? If there is, we should modify it rather than creating a new one - const futureKey = node.properties.findIndex( - (p) => - p.type === "ObjectProperty" && - p.key.type === "Identifier" && - p.key.name === "future" && - p.value.type === "ObjectExpression" - ); - if (futureKey !== -1) { - const future = node.properties[futureKey]; - assert( - future.type === "ObjectProperty" && - future.value.type === "ObjectExpression" - ); - - // Does the `future` key already have a property called `unstable_viteEnvironmentApi`? - const viteEnvironment = future.value.properties.findIndex( - (p) => - p.type === "ObjectProperty" && - p.key.type === "Identifier" && - p.key.name === viteEnvironmentKey && - p.value.type === "BooleanLiteral" - ); - - // If there's already a unstable_viteEnvironmentApi key, set the value to true - if (viteEnvironment !== -1) { - const prop = future.value.properties[viteEnvironment]; - assert( - prop.type === "ObjectProperty" && - prop.value.type === "BooleanLiteral" - ); - prop.value.value = true; - } else { - const prop = b.objectProperty( - b.identifier(viteEnvironmentKey), - b.booleanLiteral(true) - ); - future.value.properties.push(prop); - } - } else { - node.properties.push( - b.objectProperty( - b.identifier("future"), - b.objectExpression([ - b.objectProperty( - b.identifier(viteEnvironmentKey), - b.booleanLiteral(true) - ), - ]) - ) - ); - } - - return false; - }, - }); -} - -/** - * Returns the correct future flag property name for enabling the Vite Environment API - * based on the installed React Router version. - * - * @param reactRouterVersion - The installed React Router semver version string (e.g. `"7.16.0"`). - * When empty, defaults to the stable `"v8_viteEnvironmentApi"` name. - * @returns `"unstable_viteEnvironmentApi"` for versions before 7.10.0, - * or `"v8_viteEnvironmentApi"` for 7.10.0 and later. - */ -function viteEnvApiConfigPropertyName(reactRouterVersion: string) { - if (!reactRouterVersion) { - return "v8_viteEnvironmentApi"; - } - - // version less than 7.10.0 - if (semiver(reactRouterVersion, "7.10.0") === -1) { - return "unstable_viteEnvironmentApi"; - } else { - return "v8_viteEnvironmentApi"; - } -} - -/** - * Determines whether the installed React Router version still requires the explicit - * `future` flag in `react-router.config.ts` for enabling the vite environment API. - * - * React Router >= 8.0.0 enables these features by default - * (ref: https://github.com/remix-run/react-router/pull/15077), so no future flags - * are needed (they also can't be included as they would cause errors at build time). - * - * @param reactRouterVersion - The installed React Router semver version string (e.g. `"7.16.0"`). - * @returns `true` if the future flag needs to be set (versions < 8.0.0), `false` otherwise. - */ -function needsViteEnvAPIFutureFlag(reactRouterVersion: string): boolean { - if (!reactRouterVersion) { - return false; - } - - return semiver(reactRouterVersion, "8.0.0") < 0; -} - -/** - * Writes the `workers/app.ts` Worker entry point. When `v8_middleware` is enabled, - * generates a simplified fetch handler that delegates directly to the request handler. - * Otherwise generates the traditional pattern with `AppLoadContext` module augmentation - * and explicit `env`/`ctx` forwarding. - * - * @param useMiddlewarePattern - Whether `v8_middleware` is enabled in the user's config. - */ -function writeAppTs(useMiddlewarePattern: boolean) { - if (useMiddlewarePattern) { - writeFileSync( - "workers/app.ts", - dedent /* javascript */ ` - import { createRequestHandler } from "react-router"; - - const requestHandler = createRequestHandler( - () => import("virtual:react-router/server-build"), - import.meta.env.MODE, - ); - - export default { - async fetch(request) { - return requestHandler(request); - }, - } satisfies ExportedHandler; - ` - ); - return; - } - - writeFileSync( - "workers/app.ts", - dedent /* javascript */ ` - import { createRequestHandler } from "react-router"; - - declare module "react-router" { - export interface AppLoadContext { - cloudflare: { - env: Env; - ctx: ExecutionContext; - }; - } - } - - const requestHandler = createRequestHandler( - () => import("virtual:react-router/server-build"), - import.meta.env.MODE - ); - - export default { - async fetch(request, env, ctx) { - return requestHandler(request, { - cloudflare: { env, ctx }, - }); - }, - } satisfies ExportedHandler; - ` - ); -} - -/** - * Writes `app/entry.server.tsx` if it does not already exist. When `v8_middleware` - * is enabled, the generated file omits the `AppLoadContext` import and `_loadContext` - * parameter. Otherwise uses the traditional signature that includes both. - * - * If the file already exists on disk it is left untouched and a warning is logged. - * - * @param useMiddlewarePattern - Whether `v8_middleware` is enabled in the user's config. - * @param context - The autoconfig context providing logger and other dependencies. - */ -function writeEntryServerTsx( - useMiddlewarePattern: boolean, - context: AutoConfigContext -) { - if (existsSync("app/entry.server.tsx")) { - context.logger.warn( - "The file `app/entry.server.tsx` already exists on disk, and so we're not modifying it. This may lead to deployment failures if `app/entry.server.tsx` is not set up correctly." - ); - return; - } - - if (useMiddlewarePattern) { - writeFileSync( - `app/entry.server.tsx`, - dedent /* javascript */ ` - import type { EntryContext } from "react-router"; - import { ServerRouter } from "react-router"; - import { isbot } from "isbot"; - import { renderToReadableStream } from "react-dom/server"; - - export default async function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - routerContext: EntryContext, - ) { - let shellRendered = false; - const userAgent = request.headers.get("user-agent"); - - const body = await renderToReadableStream( - , - { - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - }, - ); - shellRendered = true; - - // Ensure requests from bots and SPA Mode renders wait for all content to load before responding - // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation - if ((userAgent && isbot(userAgent)) || routerContext.isSpaMode) { - await body.allReady; - } - - responseHeaders.set("Content-Type", "text/html"); - return new Response(body, { - headers: responseHeaders, - status: responseStatusCode, - }); - } - ` - ); - return; - } - - writeFileSync( - `app/entry.server.tsx`, - dedent /* javascript */ ` - import type { AppLoadContext, EntryContext } from "react-router"; - import { ServerRouter } from "react-router"; - import { isbot } from "isbot"; - import { renderToReadableStream } from "react-dom/server"; - - export default async function handleRequest( - request: Request, - responseStatusCode: number, - responseHeaders: Headers, - routerContext: EntryContext, - _loadContext: AppLoadContext - ) { - let shellRendered = false; - const userAgent = request.headers.get("user-agent"); - - const body = await renderToReadableStream( - , - { - onError(error: unknown) { - responseStatusCode = 500; - // Log streaming rendering errors from inside the shell. Don't log - // errors encountered during initial shell rendering since they'll - // reject and get logged in handleDocumentRequest. - if (shellRendered) { - console.error(error); - } - }, - } - ); - shellRendered = true; - - // Ensure requests from bots and SPA Mode renders wait for all content to load before responding - // https://react.dev/reference/react-dom/server/renderToPipeableStream#waiting-for-all-content-to-load-for-crawlers-and-static-generation - if ((userAgent && isbot(userAgent)) || routerContext.isSpaMode) { - await body.allReady; - } - - responseHeaders.set("Content-Type", "text/html"); - return new Response(body, { - headers: responseHeaders, - status: responseStatusCode, - }); - } - ` - ); -} - -export class ReactRouter extends Framework { - readonly env = { - CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true", - } as const; - - async configure({ - dryRun, - projectPath, - packageManager, - isWorkspaceRoot, - context, - target, - }: ConfigurationOptions): Promise { - const useMiddlewarePattern = hasV8MiddlewareFlag( - projectPath, - this.frameworkVersion - ); - if (!dryRun) { - await installCloudflareVitePlugin({ - packageManager: packageManager.type, - projectPath, - isWorkspaceRoot, - version: target === "cf" ? "beta" : undefined, - }); - - mkdirSync("workers"); - - writeAppTs(useMiddlewarePattern); - - await installPackages(packageManager.type, ["isbot"], { - dev: true, - startText: "Installing the isbot package", - doneText: `${brandColor(`installed`)} ${dim("isbot")}`, - isWorkspaceRoot, - }); - - writeEntryServerTsx(useMiddlewarePattern, context); - - transformViteConfig(projectPath, { - viteEnvironmentName: "ssr", - incompatibleVitePlugins: ["netlifyReactRouter"], - }); - - if (needsViteEnvAPIFutureFlag(this.frameworkVersion)) { - const viteEnvironmentKey = viteEnvApiConfigPropertyName( - this.frameworkVersion - ); - transformReactRouterConfig(projectPath, viteEnvironmentKey); - } - } - - return { - buildTool: "vite", - workerConfig: { - entrypoint: "./workers/app.ts", - }, - }; - } - - configurationDescription = "Configuring project for React Router"; -} diff --git a/packages/autoconfig/src/frameworks/solid-start.ts b/packages/autoconfig/src/frameworks/solid-start.ts deleted file mode 100644 index 679c9f1ed0..0000000000 --- a/packages/autoconfig/src/frameworks/solid-start.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { updateStatus } from "@cloudflare/cli-shared-helpers"; -import { blue } from "@cloudflare/cli-shared-helpers/colors"; -import { - mergeObjectProperties, - transformFile, -} from "@cloudflare/shared-ast-primitives"; -import { DEFAULT_COMPAT_DATE } from "@cloudflare/workers-utils"; -import * as recast from "recast"; -import semiver from "semiver"; -import { usesTypescript } from "../uses-typescript"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class SolidStart extends Framework { - async configure({ - projectPath, - dryRun, - }: ConfigurationOptions): Promise { - if (!dryRun) { - const solidStartVersion = this.frameworkVersion; - - if (semiver(solidStartVersion, "2.0.0-alpha") < 0) { - updateAppConfigFile(projectPath); - } else { - updateViteConfigFile(projectPath); - } - } - - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./.output/server/index.mjs", - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: "./.output/public" }, - }; - } -} - -/** - * This functions updates the `vite.config.(js|ts)` files used by SolidStart applications - * to use the `cloudflare-module` preset to target Cloudflare Workers. - * - * Note: SolidStart projects prior to version `2.0.0-alpha` used to have an `app.config.(js|ts)` file instead - * - * @param projectPath The path of the project - */ -function updateViteConfigFile(projectPath: string): void { - const filePath = `vite.config.${usesTypescript(projectPath) ? "ts" : "js"}`; - - transformFile(filePath, { - visitCallExpression: function (n) { - const callee = n.node.callee as recast.types.namedTypes.Identifier; - if (callee.name !== "nitro") { - return this.traverse(n); - } - - const b = recast.types.builders; - const presetProp = b.objectProperty( - b.identifier("preset"), - b.stringLiteral("cloudflare-module") - ); - - if (n.node.arguments.length === 0) { - n.node.arguments.push(b.objectExpression([presetProp])); - } else { - mergeObjectProperties( - n.node.arguments[0] as recast.types.namedTypes.ObjectExpression, - [presetProp] - ); - } - - return false; - }, - }); -} - -/** - * SolidStart apps used to have an `app.config.(js|ts)` before version `2.0.0-alpha` - * (afterwards this has been replaced by `vite.config.(js|ts)`). - * Reference: https://github.com/solidjs/templates/commit/c4cd73e08bdc - * - * This functions updates the `app.config.(js|ts)` to use the `cloudflare_module` preset - * to target Cloudflare Workers. - * - * @param projectPath The path of the project - */ -function updateAppConfigFile(projectPath: string): void { - const filePath = `app.config.${usesTypescript(projectPath) ? "ts" : "js"}`; - - const compatDate = DEFAULT_COMPAT_DATE; - - updateStatus(`Updating configuration in ${blue(filePath)}`); - - transformFile(filePath, { - visitCallExpression: function (n) { - const callee = n.node.callee as recast.types.namedTypes.Identifier; - if (callee.name !== "defineConfig") { - return this.traverse(n); - } - - const b = recast.types.builders; - mergeObjectProperties( - n.node.arguments[0] as recast.types.namedTypes.ObjectExpression, - [ - b.objectProperty( - b.identifier("server"), - b.objectExpression([ - // preset: "cloudflare_module" - b.objectProperty( - b.identifier("preset"), - b.stringLiteral("cloudflare_module") - ), - b.objectProperty( - b.identifier("compatibilityDate"), - b.stringLiteral(compatDate) - ), - ]) - ), - ] - ); - - return false; - }, - }); -} diff --git a/packages/autoconfig/src/frameworks/static.ts b/packages/autoconfig/src/frameworks/static.ts deleted file mode 100644 index 2a106f960b..0000000000 --- a/packages/autoconfig/src/frameworks/static.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class Static extends Framework { - configure({ outputDir }: ConfigurationOptions): ConfigurationResults { - return { - buildTool: "wrangler", - workerConfig: {}, - buildConfig: { assetsDirectory: outputDir }, - }; - } -} diff --git a/packages/autoconfig/src/frameworks/sveltekit.ts b/packages/autoconfig/src/frameworks/sveltekit.ts deleted file mode 100644 index 636434c986..0000000000 --- a/packages/autoconfig/src/frameworks/sveltekit.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { writeFileSync } from "node:fs"; -import { brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { runCommand } from "@cloudflare/cli-shared-helpers/command"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { Framework } from "./framework-class"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class SvelteKit extends Framework { - async configure({ - dryRun, - packageManager, - isWorkspaceRoot, - }: ConfigurationOptions): Promise { - const { dlx } = packageManager; - if (!dryRun) { - await runCommand( - [ - ...dlx, - "sv", - "add", - "--no-install", - "--no-git-check", - "sveltekit-adapter=adapter:cloudflare+cfTarget:workers", - ], - { - silent: true, - startText: "Installing adapter", - doneText: `${brandColor("installed")} ${dim( - `via \`${dlx.join( - " " - )} sv add sveltekit-adapter=adapter:cloudflare+cfTarget:workers\`` - )}`, - } - ); - writeFileSync("static/.assetsignore", "_worker.js\n_routes.json"); - - await installPackages(packageManager.type, [], { - startText: "Installing packages", - doneText: `${brandColor("installed")}`, - isWorkspaceRoot, - }); - } - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: ".svelte-kit/cloudflare/_worker.js", - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: ".svelte-kit/cloudflare" }, - }; - } - - configurationDescription = 'Configuring project for SvelteKit with "sv add"'; -} diff --git a/packages/autoconfig/src/frameworks/tanstack.ts b/packages/autoconfig/src/frameworks/tanstack.ts deleted file mode 100644 index 504fb3c899..0000000000 --- a/packages/autoconfig/src/frameworks/tanstack.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { Framework } from "./framework-class"; -import { transformViteConfig } from "./utils/vite-config"; -import { installCloudflareVitePlugin } from "./utils/vite-plugin"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class TanstackStart extends Framework { - readonly env = { - CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true", - } as const; - - async configure({ - dryRun, - projectPath, - packageManager, - isWorkspaceRoot, - target, - }: ConfigurationOptions): Promise { - if (!dryRun) { - await installCloudflareVitePlugin({ - packageManager: packageManager.type, - isWorkspaceRoot, - projectPath, - version: target === "cf" ? "beta" : undefined, - }); - - transformViteConfig(projectPath, { viteEnvironmentName: "ssr" }); - } - - return { - buildTool: "vite", - workerConfig: { - entrypoint: "@tanstack/react-start/server-entry", - }, - }; - } - - configurationDescription = "Configuring project for Tanstack Start"; -} diff --git a/packages/autoconfig/src/frameworks/utils/packages.ts b/packages/autoconfig/src/frameworks/utils/packages.ts deleted file mode 100644 index 7d55577058..0000000000 --- a/packages/autoconfig/src/frameworks/utils/packages.ts +++ /dev/null @@ -1,4 +0,0 @@ -export { - isPackageInstalled, - getInstalledPackageVersion, -} from "@cloudflare/workers-utils"; diff --git a/packages/autoconfig/src/frameworks/utils/vite-config.ts b/packages/autoconfig/src/frameworks/utils/vite-config.ts deleted file mode 100644 index 29dc761785..0000000000 --- a/packages/autoconfig/src/frameworks/utils/vite-config.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { existsSync } from "node:fs"; -import path from "node:path"; -import { transformFile } from "@cloudflare/shared-ast-primitives"; -import { UserError } from "@cloudflare/workers-utils"; -import * as recast from "recast"; -import dedent from "ts-dedent"; -import type { AutoConfigContext } from "../../context"; -import type { types } from "recast"; - -const b = recast.types.builders; -const t = recast.types.namedTypes; - -/** - * Extracts the ObjectExpression from the first argument of defineConfig(). - * - * Handles: - * - defineConfig({ ... }) - * - defineConfig(() => ({ ... })) - * - defineConfig(({ isSsrBuild }) => ({ ... })) - * - defineConfig(() => { return { ... }; }) - * - defineConfig(function() { return { ... }; }) - */ -function extractConfigObject( - node: recast.types.ASTNode -): types.namedTypes.ObjectExpression | null { - // Direct object: defineConfig({ ... }) - if (t.ObjectExpression.check(node)) { - return node; - } - - // Arrow function: defineConfig(() => ({ ... })) or defineConfig(() => { return { ... }; }) - if (t.ArrowFunctionExpression.check(node)) { - if (t.ObjectExpression.check(node.body)) { - return node.body; - } - if (t.BlockStatement.check(node.body)) { - return extractFromBlockStatement(node.body); - } - } - - // Function expression: defineConfig(function() { return { ... }; }) - if (t.FunctionExpression.check(node)) { - return extractFromBlockStatement(node.body); - } - - return null; -} - -function extractFromBlockStatement( - block: types.namedTypes.BlockStatement -): types.namedTypes.ObjectExpression | null { - const returnStmt = block.body.find((s) => t.ReturnStatement.check(s)); - if ( - returnStmt && - t.ReturnStatement.check(returnStmt) && - returnStmt.argument && - t.ObjectExpression.check(returnStmt.argument) - ) { - return returnStmt.argument; - } - return null; -} - -export function checkIfViteConfigUsesCloudflarePlugin( - projectPath: string, - context?: AutoConfigContext -): boolean { - const filePath = getViteConfigPath(projectPath); - - let importsCloudflarePlugin = false; - let usesCloudflarePlugin = false; - - transformFile(filePath, { - visitProgram(n) { - if ( - n.node.body.some( - (s) => - s.type === "ImportDeclaration" && - s.source.value === "@cloudflare/vite-plugin" - ) - ) { - importsCloudflarePlugin = true; - return this.traverse(n); - } - - this.traverse(n); - }, - visitCallExpression: function (n) { - const callee = n.node.callee as types.namedTypes.Identifier; - if (callee.name !== "defineConfig") { - return this.traverse(n); - } - - const configObject = extractConfigObject(n.node.arguments[0]); - if (!configObject) { - context?.logger.debug( - `Vite config uses an unsupported expression type. Skipping Cloudflare plugin check.` - ); - return this.traverse(n); - } - - const pluginsProp = configObject.properties.find((prop) => - isPluginsProp(prop) - ); - if (!pluginsProp || !t.ArrayExpression.check(pluginsProp.value)) { - context?.logger.debug( - `Vite config does not have a valid plugins array. Skipping Cloudflare plugin check.` - ); - return this.traverse(n); - } - - if ( - pluginsProp.value.elements.some( - (el) => - el?.type === "CallExpression" && - el.callee.type === "Identifier" && - el.callee.name === "cloudflare" - ) - ) { - usesCloudflarePlugin = true; - return this.traverse(n); - } - - this.traverse(n); - }, - }); - - return importsCloudflarePlugin && usesCloudflarePlugin; -} - -/** - * Returns whether a Vite config file (`vite.config.ts` or `vite.config.js`) - * exists in the given project directory. - */ -export function hasViteConfig(projectPath: string): boolean { - return ( - existsSync(path.join(projectPath, "vite.config.ts")) || - existsSync(path.join(projectPath, "vite.config.js")) - ); -} - -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 { - throw new Error("Could not find Vite config file to modify"); - } - - return filePath; -} - -/** - * Name of vite plugins that we know are incompatible with the Cloudflare one - */ -const knownIncompatiblePlugins = ["nitro", "nitroV2Plugin", "netlify"]; - -function hasIdentifierOutsideImport( - program: types.namedTypes.Program, - identifierName: string -): boolean { - let hasIdentifier = false; - - recast.types.visit(program, { - visitIdentifier(n) { - const parent = n.parentPath.node; - if ( - n.node.name === identifierName && - !t.ImportSpecifier.check(parent) && - !t.ImportDefaultSpecifier.check(parent) && - !t.ImportNamespaceSpecifier.check(parent) - ) { - hasIdentifier = true; - return false; - } - - this.traverse(n); - }, - }); - - return hasIdentifier; -} - -export function transformViteConfig( - projectPath: string, - options: { - viteEnvironmentName?: string; - incompatibleVitePlugins?: string[]; - } = {} -) { - const filePath = getViteConfigPath(projectPath); - const removedIncompatiblePlugins = new Set(); - - transformFile(filePath, { - visitProgram(n) { - // Add an import of the @cloudflare/vite-plugin - // ``` - // import {cloudflare} from "@cloudflare/vite-plugin"; - // ``` - const lastImportIndex = n.node.body.findLastIndex( - (statement) => statement.type === "ImportDeclaration" - ); - const lastImport = n.get("body", lastImportIndex); - const importAst = b.importDeclaration( - [b.importSpecifier(b.identifier("cloudflare"))], - b.stringLiteral("@cloudflare/vite-plugin") - ); - - // Only import if not already imported - if ( - !n.node.body.some( - (s) => - s.type === "ImportDeclaration" && - s.source.value === "@cloudflare/vite-plugin" - ) - ) { - lastImport.insertAfter(importAst); - } - - this.traverse(n); - - // Remove imports that are now unused because their plugin was removed. - n.node.body = n.node.body.filter((statement) => { - if ( - !t.ImportDeclaration.check(statement) || - !statement.specifiers?.length - ) { - return true; - } - - statement.specifiers = statement.specifiers.filter( - (specifier) => - !t.Identifier.check(specifier.local) || - !removedIncompatiblePlugins.has(specifier.local.name) || - hasIdentifierOutsideImport(n.node, specifier.local.name) - ); - - return statement.specifiers.length > 0; - }); - - return false; - }, - visitCallExpression: function (n) { - // Add the imported plugin to the config - // ``` - // defineConfig({ - // plugins: [cloudflare({ viteEnvironment: { name: 'ssr' } })], - // }); - // ``` - // Also handles function-based configs like: - // ``` - // defineConfig(({ isSsrBuild }) => ({ - // plugins: [...] - // })); - // ``` - const callee = n.node.callee as types.namedTypes.Identifier; - if (callee.name !== "defineConfig") { - return this.traverse(n); - } - - const configObject = extractConfigObject(n.node.arguments[0]); - if (!configObject) { - const argType = n.node.arguments[0]?.type ?? "unknown"; - throw new UserError( - dedent` - Cannot modify Vite config: could not extract a config object (found ${argType}). - - The Cloudflare plugin can only be automatically added to Vite configs that use: - - A simple object: defineConfig({ plugins: [...] }) - - An arrow function returning an object: defineConfig(() => ({ plugins: [...] })) - - If your config uses a more complex pattern, please manually add the plugin: - - import { cloudflare } from "@cloudflare/vite-plugin"; - - export default defineConfig({ - plugins: [cloudflare()] - }); - `, - { - telemetryMessage: "autoconfig vite config object unsupported", - } - ); - } - - const pluginsProp = configObject.properties.find((prop) => - isPluginsProp(prop) - ); - if (!pluginsProp || !t.ArrayExpression.check(pluginsProp.value)) { - throw new UserError( - dedent` - Cannot modify Vite config: could not find a valid plugins array. - - Please ensure your Vite config has a plugins array: - - export default defineConfig({ - plugins: [] - }); - `, - { - telemetryMessage: "autoconfig vite plugins array missing", - } - ); - } - - // Only add the Cloudflare plugin if it's not already present - if ( - !pluginsProp.value.elements.some( - (el) => - el?.type === "CallExpression" && - el.callee.type === "Identifier" && - el.callee.name === "cloudflare" - ) - ) { - pluginsProp.value.elements.push( - b.callExpression(b.identifier("cloudflare"), [ - ...(options.viteEnvironmentName - ? [ - b.objectExpression([ - b.objectProperty( - b.identifier("viteEnvironment"), - b.objectExpression([ - b.objectProperty( - b.identifier("name"), - b.stringLiteral(options.viteEnvironmentName) - ), - ]) - ), - ]), - ] - : []), - ]) - ); - } - - const incompatibleVitePlugins = [ - ...knownIncompatiblePlugins, - ...(options.incompatibleVitePlugins ?? []), - ]; - - // Remove incompatible plugins - pluginsProp.value.elements = pluginsProp.value.elements.filter((el) => { - if ( - el?.type === "CallExpression" && - el.callee.type === "Identifier" && - incompatibleVitePlugins.includes(el.callee.name) - ) { - removedIncompatiblePlugins.add(el.callee.name); - return false; - } - return true; - }); - return false; - }, - }); -} - -function isPluginsProp( - prop: unknown -): prop is types.namedTypes.ObjectProperty | types.namedTypes.Property { - return ( - (t.Property.check(prop) || t.ObjectProperty.check(prop)) && - t.Identifier.check(prop.key) && - prop.key.name === "plugins" - ); -} diff --git a/packages/autoconfig/src/frameworks/utils/vite-plugin.ts b/packages/autoconfig/src/frameworks/utils/vite-plugin.ts deleted file mode 100644 index 0a32d695d5..0000000000 --- a/packages/autoconfig/src/frameworks/utils/vite-plugin.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { brandColor, dim } from "@cloudflare/cli-shared-helpers/colors"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import semiver from "semiver"; -import { getInstalledPackageVersion } from "./packages"; -import type { PackageManager } from "@cloudflare/workers-utils"; - -/** - * Installs the `@cloudflare/vite-plugin` package as a dev dependency - * - * If the project has Vite >= 6.0.0 but < 6.1.0 installed, it will first - * be updated to `^6.1.0` to ensure compatibility with the plugin. - * - * @param packageManager the type of package manager to use for installation - * @param projectPath the path of the project (used to check the installed Vite version) - * @param isWorkspaceRoot whether the current project is a workspace root - * @param version optional npm version or dist-tag; defaults to the latest release - */ -export async function installCloudflareVitePlugin({ - packageManager, - projectPath, - isWorkspaceRoot, - version, -}: { - packageManager: PackageManager["type"]; - projectPath: string; - isWorkspaceRoot: boolean; - version?: string; -}): Promise { - const packageSpecifier = `@cloudflare/vite-plugin${version ? `@${version}` : ""}`; - const viteVersion = getInstalledPackageVersion("vite", projectPath); - - if ( - viteVersion && - semiver(viteVersion, "6.0.0") >= 0 && - semiver(viteVersion, "6.1.0") < 0 - ) { - // If the vite version is between 6.0.0 and 6.1.0 lets bump it to - // the latest version of 6.x, in this way it will be compatible - // with the vite plugin (likely without causing any inconvenience) - await installPackages(packageManager, ["vite@^6.1.0"], { - dev: true, - startText: - "Updating the version of vite to be compatible with the Cloudflare Vite Plugin", - doneText: `${brandColor(`updated`)} ${dim("Vite")}`, - isWorkspaceRoot, - }); - } - - await installPackages(packageManager, [packageSpecifier], { - dev: true, - startText: "Installing the Cloudflare Vite plugin", - doneText: `${brandColor(`installed`)} ${dim(packageSpecifier)}`, - isWorkspaceRoot, - }); -} diff --git a/packages/autoconfig/src/frameworks/vike.ts b/packages/autoconfig/src/frameworks/vike.ts deleted file mode 100644 index aabb8a3df6..0000000000 --- a/packages/autoconfig/src/frameworks/vike.ts +++ /dev/null @@ -1,298 +0,0 @@ -import assert from "node:assert"; -import { existsSync } from "node:fs"; -import path from "node:path"; -import { brandColor } from "@cloudflare/cli-shared-helpers/colors"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { transformFile } from "@cloudflare/shared-ast-primitives"; -import * as recast from "recast"; -import { Framework } from "./framework-class"; -import { isPackageInstalled } from "./utils/packages"; -import { installCloudflareVitePlugin } from "./utils/vite-plugin"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { types } from "recast"; - -const b = recast.types.builders; -const t = recast.types.namedTypes; - -export class Vike extends Framework { - readonly env = { - CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true", - } as const; - - async configure({ - projectPath, - dryRun, - packageManager, - isWorkspaceRoot, - }: ConfigurationOptions): Promise { - const vikeServerIsInstalled = isPackageInstalled( - "vike-server", - projectPath - ); - if (vikeServerIsInstalled) { - // Note: if vike-server is used we just error, this is the simplest solution, alternatively we could - // migrate the project as described in https://vike.dev/migration/vike-photon, but that is probably - // not currently worth the effort (but something we might consider if/when needed) - throw new Error( - 'Aborting since the project is using the deprecated "vike-server" package, please remove the package from your project and try again.' - ); - } - - if (!dryRun) { - // note: the following installation steps follow the guide in: https://vike.dev/cloudflare#get-started - - await installPackages( - packageManager.type, - ["vike-photon", "@photonjs/cloudflare"], - { - startText: "Installing vike-photon and @photonjs/cloudflare", - doneText: `${brandColor(`installed`)} photon packages`, - isWorkspaceRoot, - } - ); - - await installCloudflareVitePlugin({ - packageManager: packageManager.type, - isWorkspaceRoot, - projectPath, - }); - - addVikePhotonToConfigFile(projectPath); - } - - return { - buildTool: "vite", - workerConfig: { - entrypoint: "virtual:photon:cloudflare:server-entry", - }, - packageJsonScriptsOverrides: { - preview: "vike build && vike preview", - deploy: "vike build && wrangler deploy", - }, - }; - } -} - -/** - * Modifies a vike config file present at `pages/+config.(js|ts)` to import and use `vikePhoton` - * - * @param projectPath The project's path - */ -function addVikePhotonToConfigFile(projectPath: string) { - const filePath = getConfigPath(projectPath); - let programNode: types.namedTypes.Program | undefined; - - transformFile(filePath, { - visitProgram(n) { - programNode = n.node; - addVikePhotonImportToConfigFile(n); - return this.traverse(n); - }, - visitExportDefaultDeclaration(n) { - addVikePhotonToVikeConfigExportObject(n, programNode); - return this.traverse(n); - }, - }); -} - -/** Name of the vike config property that needs to include vikePhoton */ -const vikeConfigExtendsPropName = "extends"; - -/** - * Given a recast visitor node path for the vike config export declaration it adds vikePhoton to the config extends property - * - * @param n node path for the vike config file's default export - */ -function addVikePhotonToVikeConfigExportObject( - n: Parameters>[0], - programNode?: types.namedTypes.Program -) { - const configObject = getVikeConfigObjectExpression(n, programNode); - - let configTargetProp = configObject.properties.find((prop) => - isExtendsProp(prop) - ); - if (!configTargetProp) { - configTargetProp = b.objectProperty( - b.identifier(vikeConfigExtendsPropName), - b.arrayExpression([]) - ); - configObject.properties.push(configTargetProp); - } - - assert(configTargetProp && t.ArrayExpression.check(configTargetProp.value)); - - // Determine the local import name for "vike-photon/config" (defaults to "vikePhoton"). - // This handles cases where the user already imported it under a different name. - const vikePhotonLocalName = - getVikePhotonImportLocalName(programNode) ?? "vikePhoton"; - - // Only add vikePhoton if it's not already present - if ( - !configTargetProp.value.elements.some( - (el) => el?.type === "Identifier" && el.name === vikePhotonLocalName - ) - ) { - configTargetProp.value.elements.push(b.identifier(vikePhotonLocalName)); - } -} - -/** - * Finds the local name used for the default import from "vike-photon/config". - * e.g. `import vikePhoton from "vike-photon/config"` returns "vikePhoton", - * `import photon from "vike-photon/config"` returns "photon". - */ -function getVikePhotonImportLocalName( - programNode?: types.namedTypes.Program -): string | undefined { - if (!programNode) { - return undefined; - } - for (const stmt of programNode.body) { - if ( - t.ImportDeclaration.check(stmt) && - stmt.source.value === "vike-photon/config" - ) { - const defaultSpec = stmt.specifiers?.find((s) => - t.ImportDefaultSpecifier.check(s) - ); - if (defaultSpec && t.Identifier.check(defaultSpec.local)) { - return defaultSpec.local.name; - } - } - } - return undefined; -} - -/** - * Given a recast visitor node path for the vike config export declaration it returns the object expression associated to it - * - * @param n node path for the vike config file's default export - */ -function getVikeConfigObjectExpression( - n: Parameters>[0], - programNode?: types.namedTypes.Program -): types.namedTypes.ObjectExpression { - if (n.node.declaration.type === "ObjectExpression") { - // The export is a simple object expression - return n.node.declaration; - } - - if ( - (n.node.declaration.type === "TSAsExpression" || - n.node.declaration.type === "TSSatisfiesExpression") && - n.node.declaration.expression.type === "ObjectExpression" - ) { - // The export is an `as Config` or `satisfies Config` expression, so we go a level - // deeper to get the object expression - return n.node.declaration.expression; - } - - if (n.node.declaration.type === "Identifier" && programNode) { - // The export is a variable reference, e.g., `const config: Config = { ... }; export default config;` - const objectExpression = resolveIdentifierToObjectExpression( - n.node.declaration.name, - programNode - ); - if (objectExpression) { - return objectExpression; - } - } - - throw new Error("Could not determine Vike default object export"); -} - -/** - * Resolves a variable name to its ObjectExpression initializer by searching the program body. - * Handles both plain object initializers and those wrapped in TSAsExpression/TSSatisfiesExpression. - */ -function resolveIdentifierToObjectExpression( - varName: string, - programNode: types.namedTypes.Program -): types.namedTypes.ObjectExpression | undefined { - for (const stmt of programNode.body) { - if (t.VariableDeclaration.check(stmt)) { - for (const declarator of stmt.declarations) { - if ( - t.VariableDeclarator.check(declarator) && - t.Identifier.check(declarator.id) && - declarator.id.name === varName && - declarator.init - ) { - if (t.ObjectExpression.check(declarator.init)) { - return declarator.init; - } - if ( - (t.TSAsExpression.check(declarator.init) || - t.TSSatisfiesExpression.check(declarator.init)) && - t.ObjectExpression.check(declarator.init.expression) - ) { - return declarator.init.expression; - } - } - } - } - } - return undefined; -} - -/** - * Given a recast visitor node path for the vike config file it adds the following vikePhoton import to the file (if not already present): - * ``` - * import vikePhoton from "vike-photon/config"; - * ``` - * @param n node path for the vike config file - */ -function addVikePhotonImportToConfigFile( - n: Parameters>[0] -): void { - const lastImportIndex = n.node.body.findLastIndex( - (statement) => statement.type === "ImportDeclaration" - ); - const lastImport = n.get("body", lastImportIndex); - const importAst = b.importDeclaration( - [b.importDefaultSpecifier(b.identifier("vikePhoton"))], - b.stringLiteral("vike-photon/config") - ); - - // Only import if not already imported - if ( - !n.node.body.some( - (s) => - s.type === "ImportDeclaration" && - s.source.value === "vike-photon/config" - ) - ) { - lastImport.insertAfter(importAst); - } -} - -function getConfigPath(projectPath: string): string { - const filePathTS = path.join(projectPath, "pages", "+config.ts"); - const filePathJS = path.join(projectPath, "pages", "+config.js"); - - let filePath: string; - - if (existsSync(filePathTS)) { - filePath = filePathTS; - } else if (existsSync(filePathJS)) { - filePath = filePathJS; - } else { - throw new Error("Could not find config file to modify"); - } - - return filePath; -} - -function isExtendsProp( - prop: unknown -): prop is types.namedTypes.ObjectProperty | types.namedTypes.Property { - return ( - (t.Property.check(prop) || t.ObjectProperty.check(prop)) && - t.Identifier.check(prop.key) && - prop.key.name === vikeConfigExtendsPropName - ); -} diff --git a/packages/autoconfig/src/frameworks/vite.ts b/packages/autoconfig/src/frameworks/vite.ts deleted file mode 100644 index 1689dabb8e..0000000000 --- a/packages/autoconfig/src/frameworks/vite.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { usesTypescript } from "../uses-typescript"; -import { Framework } from "./framework-class"; -import { - checkIfViteConfigUsesCloudflarePlugin, - hasViteConfig, - transformViteConfig, -} from "./utils/vite-config"; -import { installCloudflareVitePlugin } from "./utils/vite-plugin"; -import type { AutoConfigTarget } from "../context"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; - -export class Vite extends Framework { - override readonly supportsMode = true; - - readonly env = { - CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true", - } as const; - - isConfigured( - projectPath: string, - { target = "cf" }: { target?: AutoConfigTarget } = {} - ): boolean { - if (target !== "wrangler") { - return false; - } - if (!hasViteConfig(projectPath)) { - return false; - } - return checkIfViteConfigUsesCloudflarePlugin(projectPath); - } - - async configure({ - dryRun, - projectPath, - packageManager, - isWorkspaceRoot, - target, - }: ConfigurationOptions): Promise { - if (!dryRun) { - await installCloudflareVitePlugin({ - packageManager: packageManager.type, - isWorkspaceRoot, - projectPath, - version: target === "cf" ? "beta" : undefined, - }); - - if (hasViteConfig(projectPath)) { - transformViteConfig(projectPath); - } else { - createViteConfig(projectPath); - } - } - - return { - buildTool: "vite", - workerConfig: { - assets: { - notFoundHandling: "single-page-application", - }, - }, - }; - } -} - -/** - * Creates a minimal `vite.config` file with the Cloudflare plugin already - * configured. Used when a Vite project has no config file (e.g. projects - * scaffolded with `npm create vite@latest --template vanilla`). - * - * The file extension (`.ts` or `.js`) is chosen based on whether the project - * has a `tsconfig.json`. - */ -function createViteConfig(projectPath: string): void { - const ext = usesTypescript(projectPath) ? "ts" : "js"; - const filePath = join(projectPath, `vite.config.${ext}`); - const content = `import { cloudflare } from "@cloudflare/vite-plugin"; -import { defineConfig } from "vite"; - -export default defineConfig({ -\tplugins: [cloudflare()], -}); -`; - writeFileSync(filePath, content); -} diff --git a/packages/autoconfig/src/frameworks/waku.ts b/packages/autoconfig/src/frameworks/waku.ts deleted file mode 100644 index 9325265dde..0000000000 --- a/packages/autoconfig/src/frameworks/waku.ts +++ /dev/null @@ -1,213 +0,0 @@ -import assert from "node:assert"; -import { existsSync } from "node:fs"; -import { writeFile } from "node:fs/promises"; -import { join } from "node:path"; -import { updateStatus } from "@cloudflare/cli-shared-helpers"; -import { blue, brandColor } from "@cloudflare/cli-shared-helpers/colors"; -import { installPackages } from "@cloudflare/cli-shared-helpers/packages"; -import { transformFile } from "@cloudflare/shared-ast-primitives"; -import * as recast from "recast"; -import dedent from "ts-dedent"; -import { Framework } from "./framework-class"; -import { installCloudflareVitePlugin } from "./utils/vite-plugin"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "./framework-class"; -import type { types } from "recast"; - -const b = recast.types.builders; -const t = recast.types.namedTypes; - -export class Waku extends Framework { - async configure({ - dryRun, - projectPath, - packageManager, - isWorkspaceRoot, - }: ConfigurationOptions): Promise { - if (!dryRun) { - await installPackages(packageManager.type, ["hono"], { - dev: true, - startText: "Installing hono dependency", - doneText: `${brandColor("installed")}`, - isWorkspaceRoot, - }); - - await installCloudflareVitePlugin({ - packageManager: packageManager.type, - projectPath, - isWorkspaceRoot, - }); - - await createWakuServerFile(projectPath); - await updateWakuConfig(projectPath); - } - - return { - buildTool: "wrangler", - workerConfig: { - entrypoint: "./src/waku.server", - assets: { - htmlHandling: "drop-trailing-slash", - }, - env: { - ASSETS: { type: "assets" }, - }, - }, - buildConfig: { assetsDirectory: "./dist/public" }, - }; - } -} - -/** - * Created a waku.server.tsx file that uses the Cloudflare adapter - * - * @param projectPath Path to the project - */ -async function createWakuServerFile(projectPath: string) { - await writeFile( - `${projectPath}/src/waku.server.tsx`, - dedent` - import { fsRouter } from 'waku'; - import adapter from 'waku/adapters/cloudflare'; - - export default adapter( - fsRouter(import.meta.glob('./**/*.{tsx,ts}', { base: './pages' })), - { - handlers: { - // Define additional Cloudflare Workers handlers here - // https://developers.cloudflare.com/workers/runtime-apis/handlers/ - // async queue( - // batch: MessageBatch, - // _env: Env, - // _ctx: ExecutionContext, - // ): Promise { - // for (const message of batch.messages) { - // console.log('Received', message); - // } - // }, - }, - }, - ); - ` - ); -} - -/** - * Updated the waku.config.ts file to import and use the Cloudflare Vite plugin - * - * @param projectPath Path to the project - */ -async function updateWakuConfig(projectPath: string) { - const wakuConfigPath = join(projectPath, "waku.config.ts"); - - if (!existsSync(wakuConfigPath)) { - throw new Error("Could not find Waku config file to modify"); - } - - updateStatus(`Updating Waku configuration in ${blue(wakuConfigPath)}`); - - transformFile(wakuConfigPath, { - visitProgram(n) { - // Add an import of the @cloudflare/vite-plugin - // ``` - // import { cloudflare } from '@cloudflare/vite-plugin'; - // ``` - const lastImportIndex = n.node.body.findLastIndex( - (statement) => statement.type === "ImportDeclaration" - ); - const lastImport = n.get("body", lastImportIndex); - - // Only import if not already imported - if ( - !n.node.body.some( - (s) => - s.type === "ImportDeclaration" && - s.source.value === "@cloudflare/vite-plugin" - ) - ) { - const importAst = b.importDeclaration( - [b.importSpecifier(b.identifier("cloudflare"))], - b.stringLiteral("@cloudflare/vite-plugin") - ); - lastImport.insertAfter(importAst); - } - - return this.traverse(n); - }, - visitCallExpression: function (n) { - const callee = n.node.callee as types.namedTypes.Identifier; - if (callee.name !== "defineConfig") { - return this.traverse(n); - } - - const config = n.node.arguments[0]; - assert(t.ObjectExpression.check(config)); - const viteConfig = config.properties.find((prop) => - isViteProp(prop) - )?.value; - assert(t.ObjectExpression.check(viteConfig)); - const pluginsProp = viteConfig.properties.find((prop) => - isPluginsProp(prop) - ); - assert(pluginsProp && t.ArrayExpression.check(pluginsProp.value)); - - // Only add the Cloudflare loader plugin if it's not already present - if ( - !pluginsProp.value.elements.some( - (el) => - el?.type === "CallExpression" && - el.callee.type === "Identifier" && - el.callee.name === "cloudflare" - ) - ) { - pluginsProp.value.elements.push( - b.callExpression(b.identifier("cloudflare"), [ - b.objectExpression([ - b.objectProperty( - b.identifier("viteEnvironment"), - b.objectExpression([ - b.objectProperty( - b.identifier("name"), - b.stringLiteral("rsc") - ), - b.objectProperty( - b.identifier("childEnvironments"), - b.arrayExpression([b.stringLiteral("ssr")]) - ), - ]) - ), - b.objectProperty( - b.identifier("inspectorPort"), - b.booleanLiteral(false) - ), - ]), - ]) - ); - } - - this.traverse(n); - }, - }); -} - -function isViteProp( - prop: unknown -): prop is types.namedTypes.ObjectProperty | types.namedTypes.Property { - return ( - (t.Property.check(prop) || t.ObjectProperty.check(prop)) && - t.Identifier.check(prop.key) && - prop.key.name === "vite" - ); -} - -function isPluginsProp( - prop: unknown -): prop is types.namedTypes.ObjectProperty | types.namedTypes.Property { - return ( - (t.Property.check(prop) || t.ObjectProperty.check(prop)) && - t.Identifier.check(prop.key) && - prop.key.name === "plugins" - ); -} diff --git a/packages/autoconfig/src/index.ts b/packages/autoconfig/src/index.ts deleted file mode 100644 index d925f29d32..0000000000 --- a/packages/autoconfig/src/index.ts +++ /dev/null @@ -1,41 +0,0 @@ -export type { - AutoConfigContext, - AutoConfigTarget, - AutoConfigLogger, - AutoConfigDialogs, -} from "./context"; - -export { getDetailsForAutoConfig } from "./details"; -export { runAutoConfig, buildOperationsSummary } from "./run"; - -export { Framework } from "./frameworks/framework-class"; -export type { - BuildConfig, - ConfigurationOptions, - ConfigurationResults, - PackageJsonScriptsOverrides, -} from "./frameworks/framework-class"; - -export { isFrameworkSupported } from "./frameworks"; - -export type { - FrameworkInfo, - AutoConfigFrameworkPackageInfo, -} from "./frameworks"; - -export { displayAutoConfigDetails, confirmAutoConfigDetails } from "./details"; - -export type { - AutoConfigDetails, - AutoConfigDetailsForConfiguredProject, - AutoConfigDetailsForNonConfiguredProject, - AutoConfigOptions, - AutoConfigSummary, -} from "./types"; - -export { - AutoConfigDetectionError, - AutoConfigFrameworkConfigurationError, -} from "./errors"; - -export { getInstalledPackageVersion } from "@cloudflare/workers-utils"; diff --git a/packages/autoconfig/src/run.ts b/packages/autoconfig/src/run.ts deleted file mode 100644 index d73c508f7b..0000000000 --- a/packages/autoconfig/src/run.ts +++ /dev/null @@ -1,685 +0,0 @@ -import assert from "node:assert"; -import { existsSync } from "node:fs"; -import { readFile, writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import { - maybeAppendWranglerToGitIgnoreLikeFile, - maybeAppendWranglerToGitIgnore, -} from "@cloudflare/cli-shared-helpers/gitignore"; -import { - installPackages, - installWrangler, -} from "@cloudflare/cli-shared-helpers/packages"; -import { convertToWranglerConfig, InputConfigSchema } from "@cloudflare/config"; -import { - DEFAULT_COMPAT_DATE, - FatalError, - isNodejsCompatDefaultOn, - parseJSONC, -} from "@cloudflare/workers-utils"; -import { - assertNonConfigured, - confirmAutoConfigDetails, - displayAutoConfigDetails, -} from "./details"; -import { - isFrameworkSupported, - isKnownFramework, - type PackageJsonScriptsOverrides, - validateFrameworkTargetSupport, -} from "./frameworks"; -import { getFrameworkPackageInfo } from "./frameworks/all-frameworks"; -import { Static } from "./frameworks/static"; -import { usesTypescript } from "./uses-typescript"; -import type { AutoConfigContext, AutoConfigTarget } from "./context"; -import type { - BuildConfig, - ConfigurationResults, -} from "./frameworks/framework-class"; -import type { - AutoConfigDetails, - AutoConfigDetailsForNonConfiguredProject, - AutoConfigOptions, - AutoConfigSummary, -} from "./types"; -import type { WorkerConfig } from "@cloudflare/config"; -import type { PackageJSON, RawConfig } from "@cloudflare/workers-utils"; - -/** - * Runs the full autoconfig flow: displays detected settings, confirms with the user, - * validates the framework version, runs framework configuration, writes configuration, - * updates package.json scripts, and optionally runs the build command. - * - * @param autoConfigDetails - The detected project details from `getDetailsForAutoConfig()`. - * @param autoConfigOptions - Options controlling dry-run, confirmations, build, and context. - * @returns A summary of all operations performed. - */ -export async function runAutoConfig( - autoConfigDetails: AutoConfigDetails, - autoConfigOptions: AutoConfigOptions -): Promise { - const { context } = autoConfigOptions; - const target = autoConfigOptions.target ?? "cf"; - const { logger } = context; - const dryRun = autoConfigOptions.dryRun === true; - const runBuild = !dryRun && (autoConfigOptions.runBuild ?? true); - const skipConfirmations = - dryRun || autoConfigOptions.skipConfirmations === true; - const enableTargetCliInstallation = - autoConfigOptions.enableTargetCliInstallation ?? true; - - assertNonConfigured(autoConfigDetails); - - displayAutoConfigDetails(autoConfigDetails, context); - - const updatedAutoConfigDetails = skipConfirmations - ? autoConfigDetails - : await confirmAutoConfigDetails(autoConfigDetails, context); - - if (autoConfigDetails !== updatedAutoConfigDetails) { - displayAutoConfigDetails(updatedAutoConfigDetails, context, { - heading: "Updated Project Settings:", - }); - } - - autoConfigDetails = updatedAutoConfigDetails; - assertNonConfigured(autoConfigDetails); - validateFrameworkTargetSupport(autoConfigDetails.framework, target); - - if (isKnownFramework(autoConfigDetails.framework.id)) { - const frameworkIsSupported = isFrameworkSupported( - autoConfigDetails.framework.id - ); - if (!frameworkIsSupported) { - throw new FatalError( - autoConfigDetails.framework.id === "cloudflare-pages" - ? `The target project seems to be using Cloudflare Pages. Automatically migrating from a Pages project to Workers is not yet supported.` - : `The detected framework ("${autoConfigDetails.framework.name}") cannot be automatically configured.`, - { telemetryMessage: "autoconfig run framework unsupported" } - ); - } - } - - assert( - autoConfigDetails.outputDir, - "The Output Directory is unexpectedly missing" - ); - - const compatibilityDate = DEFAULT_COMPAT_DATE; - - const defaultWorkerConfig: WorkerConfig = { - name: autoConfigDetails.workerName, - compatibilityDate, - observability: { - enabled: true, - }, - }; - - const { packageManager } = autoConfigDetails; - const isWorkspaceRoot = autoConfigDetails.isWorkspaceRoot ?? false; - - const frameworkPackageInfo = getFrameworkPackageInfo( - autoConfigDetails.framework.id - ); - if (frameworkPackageInfo) { - autoConfigDetails.framework.validateFrameworkVersion( - autoConfigDetails.projectPath, - frameworkPackageInfo, - context - ); - } - - const dryRunConfigurationResults = - await autoConfigDetails.framework.configure({ - target, - outputDir: autoConfigDetails.outputDir, - projectPath: autoConfigDetails.projectPath, - workerName: autoConfigDetails.workerName, - isWorkspaceRoot, - dryRun: true, - packageManager, - context, - }); - const dryRunWorkerConfig = mergeWorkerConfig( - defaultWorkerConfig, - dryRunConfigurationResults.workerConfig - ); - if ( - target === "cf" && - dryRunConfigurationResults.buildTool === "wrangler" && - dryRunConfigurationResults.buildConfig && - existsSync(resolve(autoConfigDetails.projectPath, "wrangler.config.ts")) - ) { - throw new FatalError( - "Cannot generate wrangler.config.ts because the file already exists. Remove or rename the existing file, then run autoconfig again.", - { telemetryMessage: "autoconfig wrangler config conflict" } - ); - } - - const { npx } = packageManager; - const buildCommand = - dryRunConfigurationResults.buildCommandOverride ?? - autoConfigDetails.buildCommand; - - const autoConfigSummary = await buildOperationsSummary( - { ...autoConfigDetails, outputDir: autoConfigDetails.outputDir }, - dryRunWorkerConfig, - dryRunConfigurationResults, - { - build: buildCommand, - deploy: - dryRunConfigurationResults.deployCommandOverride ?? - `${npx} ${target} deploy`, - version: - dryRunConfigurationResults.versionCommandOverride ?? - `${npx} ${target} versions upload`, - }, - enableTargetCliInstallation, - target, - context, - dryRunConfigurationResults.packageJsonScriptsOverrides - ); - - if ( - !( - skipConfirmations || - (await context.dialogs.confirm("Proceed with setup?")) - ) - ) { - throw new FatalError("Setup cancelled", { - telemetryMessage: "autoconfig run setup cancelled", - }); - } - - if (dryRun) { - logger.log( - `✋ ${"Autoconfig process run in dry-run mode, existing now."}` - ); - logger.log(""); - - return autoConfigSummary; - } - - logger.debug( - `Running autoconfig with:\n${JSON.stringify(autoConfigDetails, null, 2)}...` - ); - - if (autoConfigDetails.packageJson && enableTargetCliInstallation) { - if (target === "cf") { - const hasCfDependency = - autoConfigDetails.packageJson.dependencies?.cf !== undefined || - autoConfigDetails.packageJson.devDependencies?.cf !== undefined; - if (!hasCfDependency) { - await installPackages(packageManager.type, ["cf@latest"], { - dev: true, - isWorkspaceRoot, - }); - } - } else { - await installWrangler(packageManager.type, isWorkspaceRoot); - } - } - - if ( - autoConfigDetails.packageJson && - target === "cf" && - dryRunConfigurationResults.buildTool === "wrangler" - ) { - await installWrangler(packageManager.type, isWorkspaceRoot); - } - - const configurationResults = await autoConfigDetails.framework.configure({ - target, - outputDir: autoConfigDetails.outputDir, - projectPath: autoConfigDetails.projectPath, - workerName: autoConfigDetails.workerName, - isWorkspaceRoot, - dryRun: false, - packageManager, - context, - }); - const workerConfig = mergeWorkerConfig( - defaultWorkerConfig, - configurationResults.workerConfig - ); - - if (autoConfigDetails.packageJson) { - const packageJsonPath = resolve( - autoConfigDetails.projectPath, - "package.json" - ); - const existingPackageJson = JSON.parse( - await readFile(packageJsonPath, "utf8") - ) as PackageJSON; - - await writeFile( - packageJsonPath, - JSON.stringify( - { - ...existingPackageJson, - scripts: { - ...existingPackageJson.scripts, - ...autoConfigSummary.scripts, - }, - } satisfies PackageJSON, - null, - 2 - ) + "\n" - ); - } - - if (target === "wrangler") { - const wranglerConfig = getWranglerConfig( - workerConfig, - configurationResults - ); - if (wranglerConfig !== null) { - // `saveWranglerJsonc()` reconciles the Node.js compatibility flags itself, - // once it has merged this with any config already on disk. - await saveWranglerJsonc(autoConfigDetails.projectPath, wranglerConfig); - } - } - - if (target === "cf") { - if (workerConfig !== null) { - await saveCloudflareConfig(autoConfigDetails.projectPath, workerConfig); - } - if ( - configurationResults.buildTool === "wrangler" && - configurationResults.buildConfig - ) { - await saveWranglerConfigTs( - autoConfigDetails.projectPath, - configurationResults.buildConfig - ); - } - } - - maybeAppendWranglerToGitIgnore(autoConfigDetails.projectPath); - - // If we're uploading the project path as the output directory, make sure we don't accidentally upload any sensitive Wrangler files - if (autoConfigDetails.outputDir === autoConfigDetails.projectPath) { - maybeAppendWranglerToGitIgnoreLikeFile( - `${autoConfigDetails.projectPath}/.assetsignore` - ); - } - - if (buildCommand && runBuild) { - await context.runCommand( - buildCommand, - autoConfigDetails.projectPath, - "[build]" - ); - } - - return autoConfigSummary; -} - -/** - * Applies the common Worker defaults to framework-provided configuration. - * - * @param defaultWorkerConfig The common Worker configuration defaults - * @param workerConfig The framework-provided Worker configuration - * @returns The merged Worker configuration, or `null` when an external tool owns it - */ -function mergeWorkerConfig( - defaultWorkerConfig: WorkerConfig, - workerConfig: Partial | null -): WorkerConfig | null { - return workerConfig === null - ? null - : { ...defaultWorkerConfig, ...workerConfig }; -} - -/** - * Converts framework configuration results into the legacy Wrangler format. - * - * @param workerConfig The resolved Worker configuration - * @param configurationResults The framework configuration results - * @returns The Wrangler configuration, or `null` when an external tool owns it - */ -function getWranglerConfig( - workerConfig: WorkerConfig | null, - configurationResults: ConfigurationResults -): RawConfig | null { - if (workerConfig === null) { - return null; - } - - const parsedConfig = InputConfigSchema.parse({ worker: workerConfig }); - const convertedWranglerConfig = convertToWranglerConfig(parsedConfig); - const wranglerConfig = ensureNodejsCompatIsEnabled({ - $schema: "node_modules/wrangler/config-schema.json", - ...convertedWranglerConfig, - ...(configurationResults.buildConfig?.assetsDirectory - ? { - assets: { - ...convertedWranglerConfig.assets, - directory: configurationResults.buildConfig.assetsDirectory, - }, - } - : {}), - }); - - return wranglerConfig; -} - -/** - * Given a wrangler config object this function makes sure that Node.js compatibility is enabled. - * - * From `NODEJS_COMPAT_DEFAULT_ON_DATE` the config's compatibility date is enough to enable it, and - * specifying `nodejs_compat` as well is a workerd validation error, so the flag is only added for - * earlier dates. - * - * Either way the function filters out any compatibility flag already present starting with - * `nodejs_` (e.g. `nodejs_als`), so that a framework-provided flag cannot conflict with this. - * - * @param wranglerConfig The target wrangler config object - * @returns A copy of the config object where Node.js compatibility is assured to be enabled - */ -function ensureNodejsCompatIsEnabled(wranglerConfig: RawConfig): RawConfig { - const flags = (wranglerConfig.compatibility_flags ?? []).filter( - (flag) => !flag.startsWith("nodejs_") - ); - - if (!isNodejsCompatDefaultOn(wranglerConfig.compatibility_date)) { - flags.push("nodejs_compat"); - } - - if (flags.length === 0) { - const { compatibility_flags: _removed, ...rest } = wranglerConfig; - return rest; - } - - return { ...wranglerConfig, compatibility_flags: flags }; -} - -/** - * Saves the a wrangler.jsonc file for the current project potentially combining new values to the potential - * pre-existing wrangler config file generated by the framework's CLI - * - * @param projectPath The project's path - * @param baseWranglerConfig The wrangler config to use - */ -export async function saveWranglerJsonc( - projectPath: string, - wranglerConfig: RawConfig -): Promise { - let existingWranglerConfig: RawConfig = {}; - - const wranglerConfigPath = getDirWranglerJsonConfigPath(projectPath); - if (wranglerConfigPath) { - const existingContent = await readFile(wranglerConfigPath, "utf8"); - existingWranglerConfig = parseJSONC( - existingContent, - wranglerConfigPath - ) as RawConfig; - } - - // Reconcile the flags against the config that actually gets written. The - // merge only overrides the keys we generate, so a `nodejs_compat` written by - // the framework's own scaffolder would otherwise survive next to the - // compatibility date we write over it — the combination workerd rejects. - const mergedWranglerConfig = ensureNodejsCompatIsEnabled({ - ...existingWranglerConfig, - ...wranglerConfig, - }); - - await writeFile( - resolve(projectPath, "wrangler.jsonc"), - JSON.stringify(mergedWranglerConfig, null, 2) + "\n" - ); -} - -/** - * Writes the Worker configuration used by `cf`. - * - * @param projectPath The project directory - * @param workerConfig The Worker configuration to write - */ -async function saveCloudflareConfig( - projectPath: string, - workerConfig: WorkerConfig -): Promise { - await writeFile( - resolve(projectPath, "cloudflare.config.ts"), - renderCloudflareConfig(workerConfig) - ); -} - -/** - * Writes the Wrangler build-tool configuration used by `cf`. - * - * @param projectPath The project directory - * @param buildConfig The build-tool configuration to write - */ -async function saveWranglerConfigTs( - projectPath: string, - buildConfig: BuildConfig -): Promise { - await writeFile( - resolve(projectPath, "wrangler.config.ts"), - renderWranglerConfigTs(buildConfig) - ); -} - -/** - * Renders a Worker configuration as a `cloudflare.config.ts` module. - * - * @param workerConfig The Worker configuration to render - * @returns The configuration module source - */ -function renderCloudflareConfig(workerConfig: WorkerConfig): string { - return `import { defineConfig } from "cf/config";\n\nexport default defineConfig({\n worker: ${JSON.stringify(workerConfig, null, 2).replaceAll("\n", "\n ")}\n});\n`; -} - -/** - * Renders build-tool configuration as a `wrangler.config.ts` module. - * - * @param buildConfig The build-tool configuration to render - * @returns The configuration module source - */ -function renderWranglerConfigTs(buildConfig: BuildConfig): string { - return `import { defineWranglerConfig } from "wrangler/experimental-config";\n\nexport default defineWranglerConfig(${JSON.stringify(buildConfig, null, 2)});\n`; -} - -/** - * Indents rendered file content for display in the operation summary. - * - * @param content The file content to indent - * @returns The indented content - */ -function indentFileContent(content: string): string { - return " " + content.trimEnd().replace(/\n/g, "\n "); -} - -/** - * Builds a summary of all operations that autoconfig will (or did) perform, - * including package installation, package.json script updates, configuration - * creation, and framework-specific configuration. - * - * @param autoConfigDetails - The detected project details. - * @param workerConfig - The resolved Worker configuration. - * @param configurationResults - The framework configuration results. - * @param projectCommands - The build, deploy, and version commands for the project. - * @param enableTargetCliInstallation - Whether to install the selected target CLI package. - * @param target - The configuration target. - * @param context - The autoconfig context providing logger and other dependencies. - * @param packageJsonScriptsOverrides - Optional overrides for package.json script entries. - * @returns A summary object describing all planned operations. - */ -export async function buildOperationsSummary( - autoConfigDetails: AutoConfigDetailsForNonConfiguredProject & { - outputDir: NonNullable; - }, - workerConfig: WorkerConfig | null, - configurationResults: ConfigurationResults, - projectCommands: { - build?: string; - deploy: string; - version?: string; - }, - enableTargetCliInstallation: boolean, - target: AutoConfigTarget, - context: AutoConfigContext, - packageJsonScriptsOverrides?: PackageJsonScriptsOverrides -): Promise { - const { logger } = context; - logger.log(""); - const wranglerConfig = - target === "wrangler" - ? getWranglerConfig(workerConfig, configurationResults) - : null; - - const summary: AutoConfigSummary = { - scripts: {}, - ...(target === "wrangler" - ? { wranglerConfig: wranglerConfig ?? undefined } - : { - workerConfig: workerConfig ?? undefined, - buildConfig: configurationResults.buildConfig, - }), - outputDir: autoConfigDetails.outputDir, - frameworkId: autoConfigDetails.framework.id, - buildCommand: projectCommands.build, - deployCommand: projectCommands.deploy, - versionCommand: projectCommands.version, - }; - - const packagesToInstall = new Set(); - if (autoConfigDetails.packageJson) { - if (enableTargetCliInstallation) { - packagesToInstall.add(target); - } - if (configurationResults.buildTool === "vite") { - packagesToInstall.add( - target === "cf" - ? "@cloudflare/vite-plugin@beta" - : "@cloudflare/vite-plugin" - ); - } else if ( - target === "cf" && - configurationResults.buildTool === "wrangler" - ) { - packagesToInstall.add("wrangler"); - } - } - - if (packagesToInstall.size > 0) { - logger.log("📦 Install packages:"); - for (const packageName of packagesToInstall) { - logger.log(` - ${packageName} (devDependency)`); - } - logger.log(""); - } - - if (autoConfigDetails.packageJson) { - const scriptOverrides = - target === "wrangler" ? packageJsonScriptsOverrides : undefined; - const buildCommandPrefix = - target === "wrangler" && autoConfigDetails.buildCommand - ? `${autoConfigDetails.buildCommand} && ` - : ""; - summary.scripts = { - deploy: - scriptOverrides?.deploy ?? `${buildCommandPrefix}${target} deploy`, - }; - if (target === "wrangler") { - summary.scripts.preview = - scriptOverrides?.preview ?? `${buildCommandPrefix}${target} dev`; - } - - const containsServerSideCode = - // If there is an entrypoint then we know that there is server side code - !!workerConfig?.entrypoint; - - if ( - // If there is no server side code, then there is no need to add the cf-typegen script - containsServerSideCode && - usesTypescript(autoConfigDetails.projectPath) && - !("cf-typegen" in (autoConfigDetails.packageJson.scripts ?? {})) - ) { - summary.scripts["cf-typegen"] = - scriptOverrides?.typegen ?? - (target === "cf" ? "cf workers types" : "wrangler types"); - } - - logger.log("📝 Update package.json scripts:"); - for (const [name, script] of Object.entries(summary.scripts)) { - logger.log(` - "${name}": "${script}"`); - } - logger.log(""); - } - - if (target === "cf" && workerConfig) { - logger.log("📄 Create cloudflare.config.ts:"); - logger.log(indentFileContent(renderCloudflareConfig(workerConfig))); - logger.log(""); - } - - if ( - target === "cf" && - configurationResults.buildTool === "wrangler" && - configurationResults.buildConfig - ) { - logger.log("📄 Create wrangler.config.ts:"); - logger.log( - indentFileContent( - renderWranglerConfigTs(configurationResults.buildConfig) - ) - ); - logger.log(""); - } - - if (target === "wrangler" && wranglerConfig) { - const wranglerConfigPath = resolve( - autoConfigDetails.projectPath, - "wrangler.jsonc" - ); - const configExists = existsSync(wranglerConfigPath); - logger.log( - configExists ? "📄 Update wrangler.jsonc:" : "📄 Create wrangler.jsonc:" - ); - logger.log( - " " + JSON.stringify(wranglerConfig, null, 2).replace(/\n/g, "\n ") - ); - logger.log(""); - } - - if ( - autoConfigDetails.framework && - !(autoConfigDetails.framework instanceof Static) && - !autoConfigDetails.framework.isConfigured(autoConfigDetails.projectPath, { - target, - }) - ) { - summary.frameworkConfiguration = - autoConfigDetails.framework.configurationDescription ?? - `Configuring project for ${autoConfigDetails.framework.name}`; - - logger.log(`🛠️ ${summary.frameworkConfiguration}`); - logger.log(""); - } - - return summary; -} - -/** - * Gets the path to the wrangler config file, in jsonc or json format, if present in a target directory. - * - * @param dir The target directory - * @returns The path to the wrangler config file if present, `undefined` otherwise - */ -function getDirWranglerJsonConfigPath(dir: string): string | undefined { - const filePathJsonC = resolve(dir, "wrangler.jsonc"); - if (existsSync(filePathJsonC)) { - return filePathJsonC; - } - - const filePathJson = resolve(dir, "wrangler.json"); - if (existsSync(filePathJson)) { - return filePathJson; - } - - return undefined; -} diff --git a/packages/autoconfig/src/types.ts b/packages/autoconfig/src/types.ts deleted file mode 100644 index 05fe65766f..0000000000 --- a/packages/autoconfig/src/types.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { AutoConfigContext, AutoConfigTarget } from "./context"; -import type { Framework } from "./frameworks/framework-class"; -import type { BuildConfig } from "./frameworks/framework-class"; -import type { WorkerConfig } from "@cloudflare/config"; -import type { PackageManager } from "@cloudflare/workers-utils"; -import type { PackageJSON, RawConfig } from "@cloudflare/workers-utils"; - -/** Makes the specified keys of T optional. */ -type Optional = Omit & Partial>; - -type AutoConfigDetailsBase = { - /** The name of the worker */ - workerName: string; - /** The path to the project (defaults to cwd) */ - projectPath: string; - /** The content of the project's package.json file (if any) */ - packageJson?: PackageJSON; - /** Whether the project is already configured (no autoconfig required) */ - configured: boolean; - /** Details about the detected framework. It can be a JS framework or 'Static' if no actual JS framework is used. */ - framework: Framework; - /** The dev command used to run the project locally (if any) */ - devCommand?: string; - /** The build command used to build the project (if any) */ - buildCommand?: 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) */ - outputDir: string; - /** The detected package manager for the project */ - packageManager: PackageManager; - /** Whether the current path is at the root of a workspace */ - isWorkspaceRoot?: boolean; -}; - -export type AutoConfigDetailsForConfiguredProject = Optional< - AutoConfigDetailsBase, - // If AutoConfig detects that the project is already configured it's unnecessary to check - // what framework is being used nor the output directory, so in this case thee fields are optional - "framework" | "outputDir" -> & { - configured: true; -}; - -export type AutoConfigDetailsForNonConfiguredProject = AutoConfigDetailsBase & { - configured: false; -}; - -export type AutoConfigDetails = - | AutoConfigDetailsForConfiguredProject - | AutoConfigDetailsForNonConfiguredProject; - -export type AutoConfigOptions = { - /** The configuration target, defaults to cf. */ - target?: AutoConfigTarget; - /** The autoconfig context providing logger, dialogs, and other dependencies. */ - context: AutoConfigContext; - /** Whether to run autoconfig without actually applying any filesystem modification (default: false) */ - dryRun?: boolean; - /** - * Whether the build command should be run (default: true) - * - * Note: When `dryRun` is `true` the build command is never run. - */ - runBuild?: boolean; - /** - * Whether the confirmation prompts should be skipped (default: false) - * - * Note: When `dryRun` is `true` the the confirmation prompts are always skipped. - */ - skipConfirmations?: boolean; - /** - * Whether to install the selected target CLI during autoconfig. - */ - enableTargetCliInstallation?: boolean; -}; - -export type AutoConfigSummary = { - scripts: Record; - workerConfig?: WorkerConfig; - buildConfig?: BuildConfig; - wranglerConfig?: RawConfig; - frameworkConfiguration?: string; - outputDir: string; - frameworkId?: string; - buildCommand?: string; - deployCommand?: string; - versionCommand?: string; -}; diff --git a/packages/autoconfig/src/uses-typescript.ts b/packages/autoconfig/src/uses-typescript.ts deleted file mode 100644 index 17b6feb46e..0000000000 --- a/packages/autoconfig/src/uses-typescript.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { existsSync } from "node:fs"; -import { join } from "node:path"; - -export function usesTypescript(projectPath: string) { - return existsSync(join(projectPath, `tsconfig.json`)); -} diff --git a/packages/autoconfig/tests/details/confirm-auto-config-details.test.ts b/packages/autoconfig/tests/details/confirm-auto-config-details.test.ts deleted file mode 100644 index b2a286f40a..0000000000 --- a/packages/autoconfig/tests/details/confirm-auto-config-details.test.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { describe, test, vi } from "vitest"; -import { confirmAutoConfigDetails } from "../../src/details"; -import { Astro } from "../../src/frameworks/astro"; -import { Static } from "../../src/frameworks/static"; -import { createMockContext } from "../helpers/mock-context"; - -describe("autoconfig details - confirmAutoConfigDetails()", () => { - describe("interactive mode", () => { - test("no modifications applied", async ({ expect }) => { - const noModifyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(false), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - const updatedAutoConfigDetails = await confirmAutoConfigDetails( - { - workerName: "worker-name", - buildCommand: "npm run build", - projectPath: "", - configured: false, - framework: new Static({ id: "static", name: "Static" }), - outputDir: "./public", - packageManager: NpmPackageManager, - }, - noModifyContext - ); - - expect(updatedAutoConfigDetails).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "configured": false, - "framework": Static { - "configurationDescription": undefined, - "id": "static", - "name": "Static", - "supportsMode": false, - }, - "outputDir": "./public", - "packageManager": { - "dlx": [ - "npx", - ], - "lockFiles": [ - "package-lock.json", - ], - "npx": "npx", - "type": "npm", - }, - "projectPath": "", - "workerName": "worker-name", - } - `); - }); - - test("settings can be updated in a plain static site without a framework nor a build script", async ({ - expect, - }) => { - const modifyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi - .fn() - .mockResolvedValueOnce("new-name") - .mockResolvedValueOnce("./_public_") - .mockResolvedValueOnce("npm run app:build"), - select: vi.fn().mockResolvedValue("static"), - }, - }); - - const updatedAutoConfigDetails = await confirmAutoConfigDetails( - { - workerName: "my-worker", - buildCommand: "npm run build", - outputDir: "", - projectPath: "", - configured: false, - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - modifyContext - ); - expect(updatedAutoConfigDetails).toMatchInlineSnapshot(` - { - "buildCommand": "npm run app:build", - "configured": false, - "framework": Static { - "configurationDescription": undefined, - "id": "static", - "name": "Static", - "supportsMode": false, - }, - "outputDir": "./_public_", - "packageManager": { - "dlx": [ - "npx", - ], - "lockFiles": [ - "package-lock.json", - ], - "npx": "npx", - "type": "npm", - }, - "projectPath": "", - "workerName": "new-name", - } - `); - }); - - test("settings can be updated in a static app using a framework", async ({ - expect, - }) => { - const modifyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi - .fn() - .mockResolvedValueOnce("my-astro-worker") - .mockResolvedValueOnce("") - .mockResolvedValueOnce("npm run build"), - select: vi.fn().mockResolvedValue("astro"), - }, - }); - - const updatedAutoConfigDetails = await confirmAutoConfigDetails( - { - workerName: "my-astro-site", - buildCommand: "astro build", - framework: new Astro({ id: "astro", name: "Astro" }), - outputDir: "", - projectPath: "", - configured: false, - packageManager: NpmPackageManager, - }, - modifyContext - ); - expect(updatedAutoConfigDetails).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "configured": false, - "framework": Astro { - "configurationDescription": "Configuring project for Astro with "astro add cloudflare"", - "id": "astro", - "name": "Astro", - "supportsMode": true, - }, - "outputDir": "", - "packageManager": { - "dlx": [ - "npx", - ], - "lockFiles": [ - "package-lock.json", - ], - "npx": "npx", - "type": "npm", - }, - "projectPath": "", - "workerName": "my-astro-worker", - } - `); - }); - - test("framework can be changed from a detected framework to another", async ({ - expect, - }) => { - const modifyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi - .fn() - .mockResolvedValueOnce("my-nuxt-worker") - .mockResolvedValueOnce("./dist") - .mockResolvedValueOnce("npm run build"), - select: vi.fn().mockResolvedValue("nuxt"), - }, - }); - - const updatedAutoConfigDetails = await confirmAutoConfigDetails( - { - workerName: "my-astro-site", - buildCommand: "astro build", - framework: new Astro({ id: "astro", name: "Astro" }), - outputDir: "", - projectPath: "", - configured: false, - packageManager: NpmPackageManager, - }, - modifyContext - ); - - expect(updatedAutoConfigDetails.framework?.id).toBe("nuxt"); - expect(updatedAutoConfigDetails.framework?.name).toBe("Nuxt"); - }); - }); - - describe("non-interactive mode", () => { - test("no modifications are applied in non-interactive", async ({ - expect, - }) => { - const nonInteractiveContext = createMockContext({ - isNonInteractiveOrCI: () => true, - dialogs: { - confirm: vi.fn().mockResolvedValue(false), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - - const updatedAutoConfigDetails = await confirmAutoConfigDetails( - { - workerName: "worker-name", - buildCommand: "npm run build", - projectPath: "", - configured: false, - framework: new Static({ id: "static", name: "Static" }), - outputDir: "./public", - packageManager: NpmPackageManager, - }, - nonInteractiveContext - ); - - expect(updatedAutoConfigDetails).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "configured": false, - "framework": Static { - "configurationDescription": undefined, - "id": "static", - "name": "Static", - "supportsMode": false, - }, - "outputDir": "./public", - "packageManager": { - "dlx": [ - "npx", - ], - "lockFiles": [ - "package-lock.json", - ], - "npx": "npx", - "type": "npm", - }, - "projectPath": "", - "workerName": "worker-name", - } - `); - }); - }); -}); diff --git a/packages/autoconfig/tests/details/display-auto-config-details.test.ts b/packages/autoconfig/tests/details/display-auto-config-details.test.ts deleted file mode 100644 index 25183b31ce..0000000000 --- a/packages/autoconfig/tests/details/display-auto-config-details.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { mockConsoleMethods } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { displayAutoConfigDetails } from "../../src/details"; -import { Static } from "../../src/frameworks/static"; -import { createMockContext } from "../helpers/mock-context"; -import type { Framework } from "../../src/frameworks"; - -describe("autoconfig details - displayAutoConfigDetails()", () => { - const std = mockConsoleMethods(); - const context = createMockContext(); - - it("should cleanly handle a case in which only the worker name has been detected", ({ - expect, - }) => { - displayAutoConfigDetails( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-project", - framework: new Static({ id: "static", name: "Static" }), - outputDir: "./public", - packageManager: NpmPackageManager, - }, - context - ); - expect(std.out).toMatchInlineSnapshot( - ` - " - Detected Project Settings: - - Worker Name: my-project - - Framework: Static - - Output Directory: ./public - " - ` - ); - }); - - it("should display all the project settings provided by the details object", ({ - expect, - }) => { - displayAutoConfigDetails( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-astro-app", - framework: { - name: "Astro", - id: "astro", - isConfigured: () => false, - configure: () => - ({ - workerConfig: {}, - }) satisfies ReturnType, - } as unknown as Framework, - buildCommand: "astro build", - outputDir: "dist", - packageManager: NpmPackageManager, - }, - context - ); - expect(std.out).toMatchInlineSnapshot(` - " - Detected Project Settings: - - Worker Name: my-astro-app - - Framework: Astro - - Build Command: astro build - - Output Directory: dist - " - `); - }); - - it("should omit the framework and build command entries when they are not part of the details object", ({ - expect, - }) => { - displayAutoConfigDetails( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-site", - outputDir: "dist", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - context - ); - expect(std.out).toMatchInlineSnapshot(` - " - Detected Project Settings: - - Worker Name: my-site - - Framework: Static - - Output Directory: dist - " - `); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/basic-framework-detection.test.ts b/packages/autoconfig/tests/details/framework-detection/basic-framework-detection.test.ts deleted file mode 100644 index 1b9615a2ad..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/basic-framework-detection.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { writeFile } from "node:fs/promises"; -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; - -describe("detectFramework() / basic framework detection", () => { - runInTempDir(); - const context = createMockContext(); - - it("defaults to the static framework when no framework is detected", async ({ - expect, - }) => { - await writeFile( - "package-lock.json", - JSON.stringify({ lockfileVersion: 3 }) - ); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework.framework.id).toBe("static"); - }); - - it("detects astro when astro is in dependencies", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.framework.id).toBe("astro"); - expect(result.detectedFramework?.framework.name).toBe("Astro"); - }); - - it("includes buildCommand in detectedFramework when available", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.buildCommand).toBeDefined(); - expect(result.detectedFramework?.buildCommand).toContain("astro build"); - }); - - it("clears commands for an unknown framework when targeting cf", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - scripts: { build: "cf build", dev: "cf dev" }, - dependencies: { gatsby: "5" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework).toMatchObject({ - framework: { id: "gatsby" }, - buildCommand: undefined, - devCommand: undefined, - }); - }); - - it("preserves command inference for an unsupported framework when targeting Wrangler", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - scripts: { build: "cf build", dev: "cf dev" }, - dependencies: { hono: "4", vite: "8" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context, { - target: "wrangler", - }); - - expect(result.detectedFramework).toMatchObject({ - framework: { id: "hono" }, - buildCommand: "npm run build", - devCommand: undefined, - }); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/lock-file-warning.test.ts b/packages/autoconfig/tests/details/framework-detection/lock-file-warning.test.ts deleted file mode 100644 index 15167c9da4..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/lock-file-warning.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { - mockConsoleMethods, - runInTempDir, - seed, -} from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; -const noLockFileWarning = - "No lock file has been detected in the current working directory. This might indicate that the project is part of a workspace."; - -describe("detectFramework() / lock file warning", () => { - runInTempDir(); - const std = mockConsoleMethods(); - const context = createMockContext(); - - it("warns when no lock file is detected", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - }); - - await detectFramework(process.cwd(), context); - - expect(std.warn).toContain(noLockFileWarning); - }); - - it("does not warn for static projects without a lock file", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({}), - }); - - await detectFramework(process.cwd(), context); - - expect(std.warn).not.toContain(noLockFileWarning); - }); - - it("does not warn when a lock file exists", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await detectFramework(process.cwd(), context); - - expect(std.warn).not.toContain(noLockFileWarning); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/multiple-frameworks-detected.test.ts b/packages/autoconfig/tests/details/framework-detection/multiple-frameworks-detected.test.ts deleted file mode 100644 index 3da13b85c9..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/multiple-frameworks-detected.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { afterEach, describe, it, vi } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; - -describe("detectFramework() / multiple frameworks detected", () => { - runInTempDir(); - const context = createMockContext(); - - afterEach(() => { - vi.unstubAllGlobals(); - }); - - describe("non-CI environment", () => { - it("returns the known framework when multiple are detected but only one is known", async ({ - expect, - }) => { - // gatsby is not in allKnownFrameworks, only astro is - await seed({ - "package.json": JSON.stringify({ - dependencies: { astro: "5", gatsby: "5" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.framework.id).toBe("astro"); - }); - - it("filters out Vite and returns the other known framework", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { next: "14", vite: "5" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.framework.id).toBe("next"); - }); - - it("returns Waku (not Hono) when both Waku and Hono are detected", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { waku: "0.21", hono: "4" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.framework.id).toBe("waku"); - }); - - it("returns Hydrogen (not React Router) when both Hydrogen and React Router are detected", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { - "@shopify/hydrogen": "2024", - "@react-router/dev": "7", - "react-router": "7", - }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.detectedFramework?.framework.id).toBe("hydrogen"); - }); - - it("returns first framework without throwing when multiple unknown frameworks are detected", async ({ - expect, - }) => { - // Both gatsby and gridsome are unknown to wrangler - await seed({ - "package.json": JSON.stringify({ - dependencies: { gatsby: "5", gridsome: "1" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - // Should not throw even with multiple unknowns in non-CI mode - await expect( - detectFramework(process.cwd(), context) - ).resolves.toBeDefined(); - }); - }); - - describe("CI environment", () => { - const ciContext = createMockContext({ - isNonInteractiveOrCI: () => true, - }); - - it("throws MultipleFrameworksCIError when multiple known frameworks are detected", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { astro: "5", nuxt: "3" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await expect( - detectFramework(process.cwd(), ciContext) - ).rejects.toThrowErrorMatchingInlineSnapshot( - ` - [Error: Cloudflare's tooling was unable to automatically configure your project, since multiple frameworks were found: Astro, Nuxt. - - To fix this issue either: - - check your project's configuration to make sure that the target framework - is the only configured one and try again - - run \`wrangler setup\` locally to get an interactive user experience where - you can specify what framework you want to target - ] - ` - ); - }); - - it("throws MultipleFrameworksCIError when multiple unknown frameworks are detected", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { gatsby: "5", gridsome: "1" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await expect(detectFramework(process.cwd(), ciContext)).rejects.toThrow( - /Cloudflare's tooling was unable to automatically configure your project, since multiple frameworks were found/ - ); - }); - - it("does not throw when Hydrogen and React Router are detected (Hydrogen is selected)", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { - "@shopify/hydrogen": "2024", - "@react-router/dev": "7", - "react-router": "7", - }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), ciContext); - - expect(result.detectedFramework?.framework.id).toBe("hydrogen"); - }); - - it("does not throw when Vite and another known framework are detected (Vite is filtered out)", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { astro: "5", vite: "5" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), ciContext); - - expect(result.detectedFramework?.framework.id).toBe("astro"); - }); - - it("does not throw when Hono and another known framework are detected (Hono is filtered out)", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - dependencies: { "@tanstack/react-start": "1.132.0", hono: "4" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), ciContext); - - expect(result.detectedFramework?.framework.id).toBe("tanstack-start"); - }); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/package-manager-detection.test.ts b/packages/autoconfig/tests/details/framework-detection/package-manager-detection.test.ts deleted file mode 100644 index dd6377b0aa..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/package-manager-detection.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { - BunPackageManager, - NpmPackageManager, - NubPackageManager, - PnpmPackageManager, - YarnPackageManager, -} from "@cloudflare/workers-utils"; -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; - -describe("detectFramework() / package manager detection", () => { - runInTempDir(); - const context = createMockContext(); - - it("detects npm when package-lock.json is present", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(NpmPackageManager); - }); - - it("detects pnpm when pnpm-lock.yaml is present", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "pnpm-lock.yaml": "lockfileVersion: '6.0'\n", - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(PnpmPackageManager); - }); - - it("detects yarn when yarn.lock is present", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "yarn.lock": "# yarn lockfile v1\n", - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(YarnPackageManager); - }); - - it("detects bun when bun.lock is present", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "bun.lock": "", - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(BunPackageManager); - }); - - it("detects nub when nub.lock is present", async ({ expect }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "nub.lock": "", - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(NubPackageManager); - }); - - it("falls back to npm when no package manager lock file is present", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.packageManager).toStrictEqual(NpmPackageManager); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/pages-project-detection.test.ts b/packages/autoconfig/tests/details/framework-detection/pages-project-detection.test.ts deleted file mode 100644 index dd36375835..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/pages-project-detection.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { join } from "node:path"; -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it, vi } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; -import type { Config } from "@cloudflare/workers-utils"; - -describe("detectFramework() / Pages project detection", () => { - runInTempDir(); - const context = createMockContext(); - - it("returns Cloudflare Pages framework when pages_build_output_dir is set in wrangler config", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({}), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context, { - wranglerConfig: { - pages_build_output_dir: "./dist", - } as Config, - }); - - expect(result.detectedFramework?.framework.id).toBe("cloudflare-pages"); - expect(result.detectedFramework?.framework.name).toBe("Cloudflare Pages"); - expect(result.detectedFramework?.dist).toBe("./dist"); - }); - - it("returns Cloudflare Pages framework when the pages cache file exists", async ({ - expect, - }) => { - const cacheFolder = join(process.cwd(), ".cache"); - await seed({ - "package.json": JSON.stringify({}), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - [join(cacheFolder, "pages.json")]: JSON.stringify({ - account_id: "test-account", - }), - }); - - const cacheContext = createMockContext({ - getCacheFolder: () => cacheFolder, - }); - - const result = await detectFramework(process.cwd(), cacheContext); - - expect(result.detectedFramework?.framework.id).toBe("cloudflare-pages"); - expect(result.detectedFramework?.framework.name).toBe("Cloudflare Pages"); - }); - - it("returns Cloudflare Pages when a functions/ directory exists, no framework is detected, and the user confirms", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({}), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - "functions/hello.js": `export function onRequest() { return new Response("hi"); }`, - }); - - const confirmContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - - const result = await detectFramework(process.cwd(), confirmContext); - - expect(result.detectedFramework?.framework.id).toBe("cloudflare-pages"); - expect(result.detectedFramework?.framework.name).toBe("Cloudflare Pages"); - }); - - it("does not return Cloudflare Pages when the user denies the functions/ directory prompt", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({}), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - "functions/hello.js": `export function onRequest() { return new Response("hi"); }`, - }); - - const denyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(false), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - - const result = await detectFramework(process.cwd(), denyContext); - - expect(result.detectedFramework?.framework.id).not.toBe("cloudflare-pages"); - }); - - it("does not return Cloudflare Pages when a functions/ directory exists alongside a detected framework", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { astro: "5" } }), - "functions/hello.js": `export function onRequest() { return new Response("hi"); }`, - }); - - const result = await detectFramework(process.cwd(), context); - - // Astro is detected, so Pages detection via functions/ is skipped - expect(result.detectedFramework?.framework.id).not.toBe("cloudflare-pages"); - expect(result.detectedFramework?.framework.id).toBe("astro"); - }); -}); diff --git a/packages/autoconfig/tests/details/framework-detection/workspace-root-handling.test.ts b/packages/autoconfig/tests/details/framework-detection/workspace-root-handling.test.ts deleted file mode 100644 index 7da594d646..0000000000 --- a/packages/autoconfig/tests/details/framework-detection/workspace-root-handling.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { detectFramework } from "../../../src/details/framework-detection"; -import { createMockContext } from "../../helpers/mock-context"; - -describe("detectFramework() / workspace root handling", () => { - runInTempDir(); - const context = createMockContext(); - - it("sets isWorkspaceRoot to false for regular (non-monorepo) projects", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ name: "my-app" }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.isWorkspaceRoot).toBe(false); - }); - - it("sets isWorkspaceRoot to true when the workspace root is itself a workspace package", async ({ - expect, - }) => { - await seed({ - "pnpm-workspace.yaml": "packages:\n - 'packages/*'\n - '.'\n", - "package.json": JSON.stringify({ - name: "my-workspace", - workspaces: ["packages/*", "."], - }), - "packages/my-app/package.json": JSON.stringify({ name: "my-app" }), - }); - - const result = await detectFramework(process.cwd(), context); - - expect(result.isWorkspaceRoot).toBe(true); - }); - - it("throws UserError when run from a workspace root that does not include the root as a package", async ({ - expect, - }) => { - await seed({ - "pnpm-workspace.yaml": "packages:\n - 'packages/*'\n", - "package.json": JSON.stringify({ - name: "my-workspace", - workspaces: ["packages/*"], - }), - "packages/my-app/package.json": JSON.stringify({ name: "my-app" }), - "packages/my-app/index.html": "

Hello World

", - }); - - await expect( - detectFramework(process.cwd(), context) - ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: The Cloudflare application detection logic has been run in the root of a workspace instead of targeting a specific project. Change your working directory to one of the applications in the workspace and try again.]` - ); - }); -}); diff --git a/packages/autoconfig/tests/details/get-details-for-auto-config.test.ts b/packages/autoconfig/tests/details/get-details-for-auto-config.test.ts deleted file mode 100644 index a585df1776..0000000000 --- a/packages/autoconfig/tests/details/get-details-for-auto-config.test.ts +++ /dev/null @@ -1,762 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { writeFile } from "node:fs/promises"; -import { join } from "node:path"; -import { - mockConsoleMethods, - runInTempDir, - seed, -} from "@cloudflare/workers-utils/test-helpers"; -import { afterEach, describe, it, vi } from "vitest"; -import * as details from "../../src/details"; -import { createMockContext } from "../helpers/mock-context"; -import type { Config } from "@cloudflare/workers-utils"; - -const fileSystemErrors = vi.hoisted(() => ({ - readdir: new Map(), - stat: new Map(), -})); -const statAliases = vi.hoisted(() => new Map()); - -vi.mock("node:fs/promises", async (importOriginal) => { - const original = await importOriginal(); - - function throwConfiguredError(errors: Map, path: unknown) { - const stringPath = String(path); - const code = errors.get(stringPath); - if (code !== undefined) { - throw Object.assign(new Error(`${code}: ${stringPath}`), { - code, - path: stringPath, - }); - } - } - - return { - ...original, - readdir: (...args: Parameters) => { - throwConfiguredError(fileSystemErrors.readdir, args[0]); - return Reflect.apply(original.readdir, undefined, args); - }, - stat: (...args: Parameters) => { - throwConfiguredError(fileSystemErrors.stat, args[0]); - const alias = statAliases.get(String(args[0])); - if (alias !== undefined) { - return Reflect.apply(original.stat, undefined, [ - alias, - ...args.slice(1), - ]); - } - return Reflect.apply(original.stat, undefined, args); - }, - }; -}); - -describe("autoconfig details - getDetailsForAutoConfig()", () => { - runInTempDir(); - const std = mockConsoleMethods(); - const context = createMockContext(); - - afterEach(() => { - fileSystemErrors.readdir.clear(); - fileSystemErrors.stat.clear(); - statAliases.clear(); - vi.unstubAllGlobals(); - }); - - it("should set configured: true if a configPath exists during legacy Wrangler detection", async ({ - expect, - }) => { - await expect( - details.getDetailsForAutoConfig({ - wranglerConfig: { configPath: "/tmp" } as Config, - target: "wrangler", - context, - }) - ).resolves.toMatchObject({ configured: true }); - }); - - it("should migrate an existing Wrangler project by default", async ({ - expect, - }) => { - await writeFile("index.html", "

Hello World

"); - - await expect( - details.getDetailsForAutoConfig({ - wranglerConfig: { configPath: "/tmp" } as Config, - context, - }) - ).resolves.toMatchObject({ configured: false }); - }); - - it("should detect commands without using the package dev script when a Cloudflare config exists", async ({ - expect, - }) => { - await seed({ - "cloudflare.config.ts": "export default {};", - "package.json": JSON.stringify({ - scripts: { build: "astro build", dev: "cf dev" }, - dependencies: { astro: "5" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - configured: true, - framework: { id: "astro", supportsMode: true }, - buildCommand: "npx astro build", - devCommand: "npx astro dev", - packageManager: { type: "npm" }, - }); - }); - - it("should defer a configured unsupported framework to a Cloudflare dev server", async ({ - expect, - }) => { - await seed({ - "cloudflare.config.ts": "export default {};", - "package.json": JSON.stringify({ - scripts: { build: "cf build", dev: "cf dev" }, - dependencies: { hono: "4", vite: "8" }, - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - configured: true, - framework: { id: "hono" }, - buildCommand: undefined, - devCommand: undefined, - packageManager: { type: "npm" }, - }); - }); - - // Check that Astro is detected. We don't want to duplicate the tests of @netlify/build-info - // by exhaustively checking every possible combination - it.for(["npm", "pnpm"] as const)( - "should perform basic framework detection (using %s)", - async (pm, { expect }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - astro: "5", - }, - }) - ); - - // Create the appropriate lockfile so @netlify/build-info detects the package manager - if (pm === "pnpm") { - await writeFile("pnpm-lock.yaml", "lockfileVersion: 6.0"); - } else { - await writeFile( - "package-lock.json", - JSON.stringify({ lockfileVersion: 3 }) - ); - } - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - buildCommand: pm === "pnpm" ? "pnpm astro build" : "npx astro build", - devCommand: pm === "pnpm" ? "pnpm astro dev" : "npx astro dev", - framework: { supportsMode: true }, - configured: false, - outputDir: "dist", - packageJson: { - dependencies: { - astro: "5", - }, - }, - }); - } - ); - - it("should select the known framework when multiple frameworks are detected but only one is known", async ({ - expect, - }) => { - // Gatsby is not in allKnownFrameworks, so only Astro should be considered - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - astro: "5", - gatsby: "5", - }, - }) - ); - - const result = await details.getDetailsForAutoConfig({ context }); - - // Should select Astro since it's the only known framework - expect(result.framework?.id).toBe("astro"); - expect(result.framework?.name).toBe("Astro"); - }); - - it("should bail when run in the root of a workspace", async ({ expect }) => { - await seed({ - "pnpm-workspace.yaml": "packages:\n - 'packages/*'\n", - "package.json": JSON.stringify({ - name: "my-workspace", - workspaces: ["packages/*"], - }), - "packages/my-app/package.json": JSON.stringify({ name: "my-app" }), - "packages/my-app/index.html": "

Hello World

", - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: The Cloudflare application detection logic has been run in the root of a workspace instead of targeting a specific project. Change your working directory to one of the applications in the workspace and try again.]` - ); - }); - - it("should not bail when run in the root of a workspace if the root is included as a workspace package", async ({ - expect, - }) => { - await seed({ - "pnpm-workspace.yaml": "packages:\n - 'packages/*'\n - '.'\n", - "package.json": JSON.stringify({ - name: "my-workspace", - workspaces: ["packages/*", "."], - }), - "index.html": "

Hello World

", - "packages/my-app/package.json": JSON.stringify({ name: "my-app" }), - "packages/my-app/index.html": "

Hello World

", - }); - - const result = await details.getDetailsForAutoConfig({ context }); - - expect(result.isWorkspaceRoot).toBe(true); - expect(result.framework?.id).toBe("static"); - }); - - it("should set isWorkspaceRoot to false for non-workspace projects", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ - name: "my-app", - }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - "index.html": "

Hello World

", - }); - - const result = await details.getDetailsForAutoConfig({ context }); - - expect(result.isWorkspaceRoot).toBe(false); - }); - - it("should warn when no lock file is detected (project may be inside a workspace)", async ({ - expect, - }) => { - // Create a project without a lock file - simulating a project inside a workspace - // where the lock file is at the workspace root - await seed({ - "package.json": JSON.stringify({ - name: "my-app", - dependencies: { astro: "6" }, - }), - "index.html": "

Hello World

", - }); - - await details.getDetailsForAutoConfig({ context }); - - expect(std.warn).toContain( - "No lock file has been detected in the current working directory." - ); - expect(std.warn).toContain("project is part of a workspace"); - }); - - it("should use the direct framework build instead of an npm script for cf", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - scripts: { - build: "echo build", - }, - dependencies: { - astro: "5", - }, - }) - ); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - buildCommand: "npx astro build", - }); - }); - - it("should preserve npm build script detection for Wrangler", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - scripts: { - build: "echo build", - }, - dependencies: { - astro: "5", - }, - }) - ); - - await expect( - details.getDetailsForAutoConfig({ target: "wrangler", context }) - ).resolves.toMatchObject({ - buildCommand: "npm run build", - }); - }); - - it("should include the Vite plugin command environment for cf", async ({ - expect, - }) => { - await seed({ - "package.json": JSON.stringify({ dependencies: { vite: "8" } }), - "package-lock.json": JSON.stringify({ lockfileVersion: 3 }), - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - framework: { id: "vite" }, - buildCommand: "npx vite build", - env: { - CLOUDFLARE_VITE_FORCE_BUILD_OUTPUT: "true", - }, - }); - }); - - it("an error should be thrown if no output dir can be detected", async ({ - expect, - }) => { - await expect( - details.getDetailsForAutoConfig({ context }) - ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: Could not detect a directory containing static files (e.g. html, css and js) for the project]` - ); - }); - - it("outputDir should be set to cwd if an index.html file exists", async ({ - expect, - }) => { - await writeFile("index.html", `

Hello World

`); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - outputDir: ".", - }); - }); - - it("outputDir should find first child directory with an index.html file", async ({ - expect, - }) => { - await seed({ - "public/index.html": `

Hello World

`, - "random/index.html": `

Hello World

`, - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - outputDir: "public", - }); - }); - - it("outputDir should require index.html to use exact casing", async ({ - expect, - }) => { - await seed({ - "public/INDEX.HTML": `

Hello World

`, - }); - statAliases.set( - join(process.cwd(), "public", "index.html"), - join(process.cwd(), "public", "INDEX.HTML") - ); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).rejects.toThrowErrorMatchingInlineSnapshot( - `[Error: Could not detect a directory containing static files (e.g. html, css and js) for the project]` - ); - }); - - it("outputDir should ignore inaccessible child directories", async ({ - expect, - }) => { - await seed({ - ".Trash/placeholder": "", - "public/index.html": `

Hello World

`, - }); - fileSystemErrors.readdir.set(join(process.cwd(), ".Trash"), "EPERM"); - fileSystemErrors.stat.set( - join(process.cwd(), ".Trash", "index.html"), - "EPERM" - ); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - outputDir: "public", - }); - }); - - it("outputDir should ignore child directories that cannot be statted", async ({ - expect, - }) => { - await seed({ - "0-cache/placeholder": "", - "public/index.html": `

Hello World

`, - }); - fileSystemErrors.stat.set(join(process.cwd(), "0-cache"), "EACCES"); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - outputDir: "public", - }); - }); - - it("outputDir should prioritize the project directory over its child directories", async ({ - expect, - }) => { - await seed({ - "index.html": `

Hello World

`, - "public/index.html": `

Hello World

`, - }); - - await expect( - details.getDetailsForAutoConfig({ context }) - ).resolves.toMatchObject({ - outputDir: ".", - }); - }); - - const workerNamesToTest = [ - { rawName: "my-project-1", normalizedName: "my-project-1" }, - { - rawName: "--my-other-project%1_", - normalizedName: "my-other-project-1", - }, - { - rawName: "x".repeat(100), - normalizedName: "x".repeat(63), - }, - ]; - - it.for(workerNamesToTest)( - "should use the directory name as the worker name for a plain static site, normalizing it if needed (%s)", - async ( - { rawName: dirname, normalizedName: expectedWorkerName }, - { expect } - ) => { - await seed({ - [`./${dirname}/index.html`]: "

Hello World

", - }); - await expect( - details.getDetailsForAutoConfig({ - projectPath: `./${dirname}`, - context, - }) - ).resolves.toMatchObject({ - workerName: expectedWorkerName, - }); - } - ); - - it.for(workerNamesToTest)( - "should use the project name from the package.json file when available as the worker name, normalizing it if needed (%s)", - async ( - { rawName: projectName, normalizedName: expectedWorkerName }, - { expect } - ) => { - const dirname = `project-${randomUUID()}`; - await seed({ - [`./${dirname}/package.json`]: JSON.stringify({ name: projectName }), - [`./${dirname}/index.html`]: "

Hello World

", - }); - await expect( - details.getDetailsForAutoConfig({ - projectPath: `./${dirname}`, - context, - }) - ).resolves.toMatchObject({ - workerName: expectedWorkerName, - }); - } - ); - - it("WRANGLER_CI_OVERRIDE_NAME, when set should override the worker name", async ({ - expect, - }) => { - vi.stubEnv("WRANGLER_CI_OVERRIDE_NAME", "overridden-worker-name"); - - await seed({ - "./my-project/index.html": "

Hello World

", - }); - await expect( - details.getDetailsForAutoConfig({ - projectPath: `./my-project`, - context, - }) - ).resolves.toMatchObject({ - workerName: "overridden-worker-name", - }); - }); - - describe("Pages project detection", () => { - it("should detect Pages project when pages_build_output_dir is set in wrangler config", async ({ - expect, - }) => { - await seed({ - "public/index.html": `

Hello World

`, - }); - - const result = await details.getDetailsForAutoConfig({ - wranglerConfig: { - configPath: "/tmp/wrangler.toml", - pages_build_output_dir: "./dist", - } as Config, - context, - }); - - expect(result.configured).toBe(false); - expect(result.framework?.id).toBe("cloudflare-pages"); - expect(result.framework?.name).toBe("Cloudflare Pages"); - }); - - it("should detect Pages project when pages.json cache file exists", async ({ - expect, - }) => { - const cacheFolder = join(process.cwd(), ".cache"); - await seed({ - "public/index.html": `

Hello World

`, - [join(cacheFolder, "pages.json")]: JSON.stringify({ - account_id: "test-account", - }), - }); - - const cacheContext = createMockContext({ - getCacheFolder: () => cacheFolder, - }); - - const result = await details.getDetailsForAutoConfig({ - context: cacheContext, - }); - - expect(result.framework?.id).toBe("cloudflare-pages"); - expect(result.framework?.name).toBe("Cloudflare Pages"); - }); - - it("should detect Pages project when functions directory exists, no framework is detected and the user confirms that it is", async ({ - expect, - }) => { - await seed({ - "public/index.html": `

Hello World

`, - "functions/hello.js": ` - export function onRequest(context) { - return new Response("Hello, world!"); - } - `, - }); - - const confirmContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - - const result = await details.getDetailsForAutoConfig({ - context: confirmContext, - }); - - expect(result.framework?.id).toBe("cloudflare-pages"); - expect(result.framework?.name).toBe("Cloudflare Pages"); - }); - - it("should not detect Pages project when the user denies that, even if the functions directory exists and no framework is detected", async ({ - expect, - }) => { - await seed({ - "public/index.html": `

Hello World

`, - "functions/hello.js": ` - export function onRequest(context) { - return new Response("Hello, world!"); - } - `, - }); - - const denyContext = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(false), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - }); - - const result = await details.getDetailsForAutoConfig({ - context: denyContext, - }); - - expect(result.framework?.id).toBe("static"); - expect(result.framework?.name).toBe("Static"); - }); - - it("should not detect Pages project when functions directory exists but a framework is detected", async ({ - expect, - }) => { - await seed({ - "functions/hello.js": - "export const myFun = () => { console.log('Hello!'); };", - "package.json": JSON.stringify({ - dependencies: { - astro: "5", - }, - }), - }); - - const result = await details.getDetailsForAutoConfig({ context }); - - // Should detect Astro, not Pages - expect(result.framework?.id).toBe("astro"); - }); - }); - - describe("multiple frameworks detected", () => { - describe("local environment (non-CI)", () => { - it("should return a single framework when multiple frameworks are detected", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - astro: "5", - "@angular/core": "18", - }, - }) - ); - - const result = await details.getDetailsForAutoConfig({ context }); - - // Should return a framework (either astro or angular) - expect(result.framework).toBeDefined(); - expect(["astro", "angular"]).toContain(result.framework?.id); - }); - }); - - describe("CI environment", () => { - const ciContext = createMockContext({ - isNonInteractiveOrCI: () => true, - }); - - it("should throw MultipleFrameworksCIError when multiple known frameworks are detected in CI", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - astro: "5", - nuxt: "3", - }, - }) - ); - - await expect( - details.getDetailsForAutoConfig({ context: ciContext }) - ).rejects.toThrow( - /Cloudflare's tooling was unable to automatically configure your project, since multiple frameworks were found/ - ); - }); - - it("should NOT throw when Vite and another known framework are detected in CI (Vite is filtered out)", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - astro: "5", - vite: "5", - }, - }) - ); - - const result = await details.getDetailsForAutoConfig({ - context: ciContext, - }); - expect(result.framework?.id).toBe("astro"); - }); - - it("should throw MultipleFrameworksCIError when multiple unknown frameworks are detected in CI", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - gatsby: "5", - gridsome: "1", - }, - }) - ); - - await expect( - details.getDetailsForAutoConfig({ context: ciContext }) - ).rejects.toThrowErrorMatchingInlineSnapshot( - ` - [Error: Cloudflare's tooling was unable to automatically configure your project, since multiple frameworks were found: Gatsby, Gridsome. - - To fix this issue either: - - check your project's configuration to make sure that the target framework - is the only configured one and try again - - run \`wrangler setup\` locally to get an interactive user experience where - you can specify what framework you want to target - ] - ` - ); - }); - }); - - it("should return non-Vite framework when Vite and another known framework are detected", async ({ - expect, - }) => { - await writeFile( - "package.json", - JSON.stringify({ - dependencies: { - next: "14", - vite: "5", - }, - }) - ); - - const result = await details.getDetailsForAutoConfig({ context }); - expect(result.framework?.id).toBe("next"); - }); - - it("should fallback to static framework when no frameworks detected", async ({ - expect, - }) => { - await seed({ - "index.html": "

Hello World

", - "package.json": JSON.stringify({}), - }); - - const result = await details.getDetailsForAutoConfig({ context }); - - expect(result.framework?.id).toBe("static"); - }); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/angular.test.ts b/packages/autoconfig/tests/frameworks/angular.test.ts deleted file mode 100644 index 65afb764a9..0000000000 --- a/packages/autoconfig/tests/frameworks/angular.test.ts +++ /dev/null @@ -1,451 +0,0 @@ -import { mkdir, writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { beforeEach, describe, it, vi } from "vitest"; -import { Angular } from "../../src/frameworks/angular"; -import { createMockContext } from "../helpers/mock-context"; -import type { AutoConfigFrameworkPackageInfo } from "../../src/frameworks"; -const context = createMockContext(); - -const BASE_OPTIONS = { - target: "wrangler" as const, - projectPath: process.cwd(), - workerName: "my-angular-app", - outputDir: "dist/my-angular-app/", - dryRun: false, - packageManager: NpmPackageManager, - isWorkspaceRoot: false, - context, -}; - -const ANGULAR_PACKAGE_INFO: AutoConfigFrameworkPackageInfo = { - name: "@angular/core", - minimumVersion: "19.0.0", - maximumKnownMajorVersion: "22", -}; - -async function mockAngularCoreVersion(version: string) { - const pkgDir = resolve("node_modules/@angular/core"); - await mkdir(pkgDir, { recursive: true }); - await writeFile( - resolve(pkgDir, "package.json"), - JSON.stringify({ name: "@angular/core", version }) - ); -} - -describe("Angular framework configure()", () => { - runInTempDir(); - - let installSpy: ReturnType; - - beforeEach(() => { - installSpy = vi - .spyOn(cliPackages, "installPackages") - .mockImplementation(async () => {}); - }); - - describe("non-SSR (SPA) project", () => { - beforeEach(async () => { - /** Minimal angular.json for a non-SSR (SPA) project — no `ssr` field */ - const NON_SSR_ANGULAR_JSON = { - projects: { - "my-angular-app": { - architect: { - build: { - options: { - browser: "src/main.ts", - tsConfig: "tsconfig.app.json", - assets: [{ glob: "**/*", input: "public" }], - styles: ["src/styles.css"], - }, - }, - }, - }, - }, - }; - - await writeFile( - resolve("angular.json"), - JSON.stringify(NON_SSR_ANGULAR_JSON, null, 2) - ); - await mkdir(resolve("src"), { recursive: true }); - }); - - it("returns assets-only configuration", async ({ expect }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - const result = await framework.configure(BASE_OPTIONS); - - expect(result.workerConfig).toEqual({}); - expect(result.buildConfig?.assetsDirectory).toBe("dist/my-angular-app/"); - expect(result.workerConfig).not.toHaveProperty("entrypoint"); - }); - - it("does not support Cloudflare modes", ({ expect }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - - expect(framework.supportsMode).toBe(false); - }); - - it("sets configurationDescription for SPA", async ({ expect }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - await framework.configure(BASE_OPTIONS); - - expect(framework.configurationDescription).toBe( - "Configuring Angular SPA project (assets only)" - ); - }); - - it("does not install additional dependencies", async ({ expect }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - await framework.configure(BASE_OPTIONS); - - expect(installSpy).not.toHaveBeenCalled(); - }); - - it("does not create src/server.ts", async ({ expect }) => { - const { existsSync } = await import("node:fs"); - const framework = new Angular({ id: "angular", name: "Angular" }); - await framework.configure(BASE_OPTIONS); - - expect(existsSync(resolve("src/server.ts"))).toBe(false); - }); - - it("does not modify angular.json", async ({ expect }) => { - const { readFileSync } = await import("node:fs"); - const framework = new Angular({ id: "angular", name: "Angular" }); - await framework.configure(BASE_OPTIONS); - - const angularJson = JSON.parse( - readFileSync(resolve("angular.json"), "utf8") - ); - // outputMode and outputPath should not have been set - expect( - angularJson.projects["my-angular-app"].architect.build.options - .outputMode - ).toBeUndefined(); - expect( - angularJson.projects["my-angular-app"].architect.build.options - .outputPath - ).toBeUndefined(); - }); - - it("skips side effects in dryRun mode", async ({ expect }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - const result = await framework.configure({ - ...BASE_OPTIONS, - dryRun: true, - }); - - expect(result.workerConfig).toEqual({}); - expect(result.buildConfig?.assetsDirectory).toBe("dist/my-angular-app/"); - expect(installSpy).not.toHaveBeenCalled(); - }); - }); - - describe("project with ssr: false", () => { - beforeEach(async () => { - /** angular.json for a project with SSR explicitly set to false */ - const SSR_FALSE_ANGULAR_JSON = { - projects: { - "my-angular-app": { - architect: { - build: { - options: { - browser: "src/main.ts", - tsConfig: "tsconfig.app.json", - assets: [], - styles: [], - ssr: false, - }, - }, - }, - }, - }, - }; - - await writeFile( - resolve("angular.json"), - JSON.stringify(SSR_FALSE_ANGULAR_JSON, null, 2) - ); - await mkdir(resolve("src"), { recursive: true }); - }); - - it("returns assets-only configuration when ssr is false", async ({ - expect, - }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - const result = await framework.configure(BASE_OPTIONS); - - expect(result.workerConfig).toEqual({}); - expect(result.buildConfig?.assetsDirectory).toBe("dist/my-angular-app/"); - expect(result.workerConfig).not.toHaveProperty("entrypoint"); - }); - - it("sets SPA configurationDescription when ssr is false", async ({ - expect, - }) => { - const framework = new Angular({ id: "angular", name: "Angular" }); - await framework.configure(BASE_OPTIONS); - - expect(framework.configurationDescription).toBe( - "Configuring Angular SPA project (assets only)" - ); - }); - }); - - describe("project with ssr: true (boolean shorthand)", () => { - beforeEach(async () => { - /** angular.json for a project with SSR enabled via the `true` boolean shorthand */ - const SSR_TRUE_ANGULAR_JSON = { - projects: { - "my-angular-app": { - architect: { - build: { - options: { - browser: "src/main.ts", - tsConfig: "tsconfig.app.json", - assets: [], - styles: [], - ssr: true, - }, - }, - }, - }, - }, - }; - - await writeFile( - resolve("angular.json"), - JSON.stringify(SSR_TRUE_ANGULAR_JSON, null, 2) - ); - await mkdir(resolve("src"), { recursive: true }); - }); - - it("returns SSR configuration without crashing", async ({ expect }) => { - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - const result = await framework.configure(BASE_OPTIONS); - - expect(result.workerConfig).toEqual({ - entrypoint: "./dist/server/server.mjs", - env: { - ASSETS: { type: "assets" }, - }, - }); - expect(result.buildConfig?.assetsDirectory).toBe( - "dist/my-angular-app/browser" - ); - }); - - it("sets experimentalPlatform in angular.json when ssr was true (Angular <22)", async ({ - expect, - }) => { - const { readFileSync } = await import("node:fs"); - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - const angularJson = JSON.parse( - readFileSync(resolve("angular.json"), "utf8") - ); - const options = - angularJson.projects["my-angular-app"].architect.build.options; - // The boolean `true` should have been promoted to an object - expect(typeof options.ssr).toBe("object"); - expect(options.ssr.experimentalPlatform).toBe("neutral"); - }); - - it("sets platform in angular.json when ssr was true (Angular >=22)", async ({ - expect, - }) => { - const { readFileSync } = await import("node:fs"); - await mockAngularCoreVersion("22.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - const angularJson = JSON.parse( - readFileSync(resolve("angular.json"), "utf8") - ); - const options = - angularJson.projects["my-angular-app"].architect.build.options; - expect(typeof options.ssr).toBe("object"); - expect(options.ssr.platform).toBe("neutral"); - }); - }); - - describe("SSR project", () => { - beforeEach(async () => { - /** angular.json for a project with SSR enabled (object value) */ - const SSR_ANGULAR_JSON = { - projects: { - "my-angular-app": { - architect: { - build: { - options: { - browser: "src/main.ts", - tsConfig: "tsconfig.app.json", - assets: [], - styles: [], - ssr: { - entry: "src/server.ts", - }, - }, - }, - }, - }, - }, - }; - - await writeFile( - resolve("angular.json"), - JSON.stringify(SSR_ANGULAR_JSON, null, 2) - ); - await mkdir(resolve("src"), { recursive: true }); - }); - - it("returns SSR configuration with an entrypoint and assets", async ({ - expect, - }) => { - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - const result = await framework.configure(BASE_OPTIONS); - - expect(result.workerConfig).toEqual({ - entrypoint: "./dist/server/server.mjs", - env: { - ASSETS: { type: "assets" }, - }, - }); - expect(result.buildConfig?.assetsDirectory).toBe( - "dist/my-angular-app/browser" - ); - }); - - it("sets SSR configurationDescription", async ({ expect }) => { - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - expect(framework.configurationDescription).toBe( - "Configuring project for Angular" - ); - }); - - it("sets experimentalPlatform in angular.json (Angular <22)", async ({ - expect, - }) => { - const { readFileSync } = await import("node:fs"); - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - const angularJson = JSON.parse( - readFileSync(resolve("angular.json"), "utf8") - ); - const options = - angularJson.projects["my-angular-app"].architect.build.options; - expect(options.outputMode).toBe("server"); - expect(options.outputPath).toBe("dist"); - expect(options.ssr.experimentalPlatform).toBe("neutral"); - }); - - it("sets platform in angular.json (Angular >=22)", async ({ expect }) => { - const { readFileSync } = await import("node:fs"); - await mockAngularCoreVersion("22.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - const angularJson = JSON.parse( - readFileSync(resolve("angular.json"), "utf8") - ); - const options = - angularJson.projects["my-angular-app"].architect.build.options; - expect(options.outputMode).toBe("server"); - expect(options.outputPath).toBe("dist"); - expect(options.ssr.platform).toBe("neutral"); - }); - - it("creates src/server.ts", async ({ expect }) => { - const { existsSync } = await import("node:fs"); - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - expect(existsSync(resolve("src/server.ts"))).toBe(true); - }); - - it("installs additional dependencies", async ({ expect }) => { - await mockAngularCoreVersion("21.0.0"); - const framework = new Angular({ id: "angular", name: "Angular" }); - framework.validateFrameworkVersion( - process.cwd(), - ANGULAR_PACKAGE_INFO, - context - ); - await framework.configure(BASE_OPTIONS); - - expect(installSpy).toHaveBeenCalledWith( - NpmPackageManager.type, - ["xhr2"], - expect.objectContaining({ dev: true }) - ); - }); - - it("skips side effects in dryRun mode", async ({ expect }) => { - const { existsSync } = await import("node:fs"); - const framework = new Angular({ id: "angular", name: "Angular" }); - const result = await framework.configure({ - ...BASE_OPTIONS, - dryRun: true, - }); - - // Config is still returned - expect(result.workerConfig).toHaveProperty("entrypoint"); - // But side effects are skipped - expect(existsSync(resolve("src/server.ts"))).toBe(false); - expect(installSpy).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/cf-configuration-support.test.ts b/packages/autoconfig/tests/frameworks/cf-configuration-support.test.ts deleted file mode 100644 index df474d8a77..0000000000 --- a/packages/autoconfig/tests/frameworks/cf-configuration-support.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, it } from "vitest"; -import { - getFrameworkClassInstance, - validateFrameworkTargetSupport, -} from "../../src/frameworks"; - -const WRANGLER_ONLY_FRAMEWORKS = [ - "analog", - "angular", - "nuxt", - "qwik", - "solid-start", - "svelte-kit", - "vike", - "waku", -] as const; - -describe("cf framework configuration support", () => { - it.for(WRANGLER_ONLY_FRAMEWORKS)( - "rejects %s projects with Wrangler guidance", - (id, { expect }) => { - const framework = getFrameworkClassInstance(id); - - expect(() => validateFrameworkTargetSupport(framework, "cf")).toThrow( - `cf does not support ${framework.name} projects yet. You can still use Wrangler to develop and deploy this project.` - ); - } - ); - - it.for(WRANGLER_ONLY_FRAMEWORKS)( - "allows %s projects when targeting Wrangler", - (id, { expect }) => { - const framework = getFrameworkClassInstance(id); - - expect(() => - validateFrameworkTargetSupport(framework, "wrangler") - ).not.toThrow(); - } - ); - - it.for([ - "astro", - "next", - "react-router", - "static", - "tanstack-start", - "vite", - ] as const)("allows %s projects when targeting cf", (id, { expect }) => { - const framework = getFrameworkClassInstance(id); - - expect(() => validateFrameworkTargetSupport(framework, "cf")).not.toThrow(); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-future-no-middleware.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-future-no-middleware.ts deleted file mode 100644 index 844e5078d1..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-future-no-middleware.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Config } from "@react-router/dev/config"; -export default { - ssr: true, - future: { - v8_splitRouteModules: true, - }, -} satisfies Config; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-and-split.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-and-split.ts deleted file mode 100644 index d4298c7391..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-and-split.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { Config } from "@react-router/dev/config"; -export default { - ssr: true, - future: { - v8_middleware: true, - v8_splitRouteModules: true, - }, -} satisfies Config; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-false.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-false.ts deleted file mode 100644 index 4696f3a73c..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-false.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Config } from "@react-router/dev/config"; -export default { - ssr: true, - future: { - v8_middleware: false, - }, -} satisfies Config; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-true.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-true.ts deleted file mode 100644 index dfc17a9fab..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-middleware-true.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { Config } from "@react-router/dev/config"; -export default { - ssr: true, - future: { - v8_middleware: true, - }, -} satisfies Config; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-no-future.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-no-future.ts deleted file mode 100644 index f6df07622c..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-no-future.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Config } from "@react-router/dev/config"; -export default { - ssr: true, -} satisfies Config; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-plain-object-middleware.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/config-plain-object-middleware.ts deleted file mode 100644 index 44a6ef49d8..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/config-plain-object-middleware.ts +++ /dev/null @@ -1,6 +0,0 @@ -export default { - ssr: true, - future: { - v8_middleware: true, - }, -}; diff --git a/packages/autoconfig/tests/frameworks/fixtures/react-router/vite-config-basic.ts b/packages/autoconfig/tests/frameworks/fixtures/react-router/vite-config-basic.ts deleted file mode 100644 index 9e2760ea80..0000000000 --- a/packages/autoconfig/tests/frameworks/fixtures/react-router/vite-config-basic.ts +++ /dev/null @@ -1,2 +0,0 @@ -import { defineConfig } from "vite"; -export default defineConfig({ plugins: [] }); diff --git a/packages/autoconfig/tests/frameworks/get-framework-class.test.ts b/packages/autoconfig/tests/frameworks/get-framework-class.test.ts deleted file mode 100644 index 773fdcc54c..0000000000 --- a/packages/autoconfig/tests/frameworks/get-framework-class.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { describe, it } from "vitest"; -import { getFrameworkClassInstance } from "../../src/frameworks"; -import { NextJs } from "../../src/frameworks/next"; -import { NoOpFramework } from "../../src/frameworks/no-op"; -import { Static } from "../../src/frameworks/static"; - -describe("getFrameworkClassInstance()", () => { - it("should return a Static framework when frameworkId is unknown", ({ - expect, - }) => { - const framework = getFrameworkClassInstance("unknown-framework"); - - expect(framework).toBeInstanceOf(Static); - expect(framework.id).toBe("static"); - expect(framework.name).toBe("Static"); - }); - - it("should return a target framework when frameworkId is known and supported", ({ - expect, - }) => { - const framework = getFrameworkClassInstance("next"); - - expect(framework).toBeInstanceOf(NextJs); - expect(framework.id).toBe("next"); - expect(framework.name).toBe("Next.js"); - }); - - it("should return a NoOpFramework for an unsupported framework (hono)", ({ - expect, - }) => { - const framework = getFrameworkClassInstance("hono"); - - expect(framework).toBeInstanceOf(NoOpFramework); - expect(framework.id).toBe("hono"); - expect(framework.name).toBe("Hono"); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/is-framework-supported.test.ts b/packages/autoconfig/tests/frameworks/is-framework-supported.test.ts deleted file mode 100644 index 6747cb99e0..0000000000 --- a/packages/autoconfig/tests/frameworks/is-framework-supported.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { describe, it } from "vitest"; -import { isFrameworkSupported } from "../../src/frameworks"; - -describe("isFrameworkSupported()", () => { - it("should return true for a supported framework id", ({ expect }) => { - expect(isFrameworkSupported("astro")).toBe(true); - }); - - it("should return false for a known but unsupported framework id", ({ - expect, - }) => { - expect(isFrameworkSupported("hono")).toBe(false); - }); - - it("should throw for an unknown framework id", ({ expect }) => { - expect(() => isFrameworkSupported("unknown-framework")).toThrow( - 'Unexpected unknown framework id: "unknown-framework"' - ); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/is-known-framework.test.ts b/packages/autoconfig/tests/frameworks/is-known-framework.test.ts deleted file mode 100644 index 97ffa2d739..0000000000 --- a/packages/autoconfig/tests/frameworks/is-known-framework.test.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { describe, it } from "vitest"; -import { isKnownFramework } from "../../src/frameworks"; - -describe("isKnownFramework()", () => { - it("should return true for a known supported framework id", ({ expect }) => { - expect(isKnownFramework("astro")).toBe(true); - }); - - it("should return true for a known but unsupported framework id", ({ - expect, - }) => { - expect(isKnownFramework("hono")).toBe(true); - }); - - it('should return true for the "static" framework id', ({ expect }) => { - expect(isKnownFramework("static")).toBe(true); - }); - - it("should return false for an unknown framework id", ({ expect }) => { - expect(isKnownFramework("unknown-framework")).toBe(false); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/react-router.test.ts b/packages/autoconfig/tests/frameworks/react-router.test.ts deleted file mode 100644 index 7f96ab764f..0000000000 --- a/packages/autoconfig/tests/frameworks/react-router.test.ts +++ /dev/null @@ -1,473 +0,0 @@ -import { existsSync, readFileSync } from "node:fs"; -import { mkdir, writeFile } from "node:fs/promises"; -import { join, resolve } from "node:path"; -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { beforeEach, describe, it, vi } from "vitest"; -import { - hasV8MiddlewareFlag, - ReactRouter, -} from "../../src/frameworks/react-router"; -import * as packagesUtils from "../../src/frameworks/utils/packages"; -import { createMockContext } from "../helpers/mock-context"; - -function fixture(name: string): string { - return readFileSync(join(__dirname, "fixtures/react-router", name), "utf-8"); -} - -vi.mock("../../src/frameworks/utils/vite-config", () => ({ - transformViteConfig: vi.fn(), -})); - -vi.mock("../../src/frameworks/utils/vite-plugin", () => ({ - installCloudflareVitePlugin: vi.fn(), -})); - -vi.mock("../../src/frameworks/utils/packages", () => ({ - getInstalledPackageVersion: vi.fn(), - isPackageInstalled: vi.fn(() => true), -})); - -const context = createMockContext(); - -function getBaseOptions() { - return { - target: "cf" as const, - projectPath: process.cwd(), - outputDir: "build/", - workerName: "my-react-router-app", - dryRun: false, - packageManager: NpmPackageManager, - isWorkspaceRoot: false, - context, - }; -} - -function createFramework(version: string): ReactRouter { - vi.mocked(packagesUtils.getInstalledPackageVersion).mockReturnValue(version); - - const framework = new ReactRouter({ - id: "react-router", - name: "React Router", - }); - - framework.validateFrameworkVersion( - ".", - { - name: "react-router", - minimumVersion: "7.0.0", - maximumKnownMajorVersion: "8", - }, - context - ); - - return framework; -} - -describe("hasV8MiddlewareFlag()", () => { - runInTempDir(); - - it("returns false when no config file exists", ({ expect }) => { - expect(hasV8MiddlewareFlag(process.cwd())).toBe(false); - }); - - it("returns false when config has no future block", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(false); - }); - - it("returns false when future block does not contain v8_middleware", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-future-no-middleware.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(false); - }); - - it("returns true when v8_middleware is set to true", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-true.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(true); - }); - - it("returns false when v8_middleware is set to false", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-false.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(false); - }); - - it("handles plain object export without satisfies", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-plain-object-middleware.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(true); - }); - - it("returns false when config file has syntax errors", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - "export default { this is not valid syntax" - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(false); - }); - - it("detects v8_middleware inside a `satisfies Config` expression", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-and-split.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd())).toBe(true); - }); -}); - -describe("React Router framework configure()", () => { - runInTempDir(); - - beforeEach(async () => { - vi.spyOn(cliPackages, "installPackages").mockImplementation(async () => {}); - - await mkdir(resolve("app"), { recursive: true }); - await writeFile(resolve("vite.config.ts"), fixture("vite-config-basic.ts")); - }); - - describe("workers/app.ts generation — without v8_middleware", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - }); - - it("creates workers/app.ts with AppLoadContext augmentation", async ({ - expect, - }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("workers/app.ts"), "utf-8"); - expect(content).toContain("AppLoadContext"); - expect(content).toContain("declare module"); - expect(content).toContain("cloudflare: { env, ctx }"); - expect(content).toContain("async fetch(request, env, ctx)"); - expect(content).toContain("satisfies ExportedHandler"); - }); - }); - - describe("workers/app.ts generation — with v8_middleware", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-true.ts") - ); - }); - - it("creates workers/app.ts without AppLoadContext augmentation", async ({ - expect, - }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("workers/app.ts"), "utf-8"); - expect(content).not.toContain("AppLoadContext"); - expect(content).not.toContain("declare module"); - expect(content).toContain( - 'import { createRequestHandler } from "react-router"' - ); - expect(content).toContain("requestHandler(request)"); - expect(content).toContain("satisfies ExportedHandler"); - }); - - it("creates workers/app.ts with a simple fetch handler", async ({ - expect, - }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("workers/app.ts"), "utf-8"); - expect(content).toContain("async fetch(request)"); - expect(content).not.toContain("env, ctx"); - expect(content).not.toContain("cloudflare: { env, ctx }"); - }); - }); - - describe("entry.server.tsx generation — without v8_middleware", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - }); - - it("creates entry.server.tsx with AppLoadContext", async ({ expect }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("app/entry.server.tsx"), "utf-8"); - expect(content).toContain("AppLoadContext"); - expect(content).toContain("_loadContext: AppLoadContext"); - expect(content).toContain( - 'import type { AppLoadContext, EntryContext } from "react-router"' - ); - }); - }); - - describe("entry.server.tsx generation — with v8_middleware", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-true.ts") - ); - }); - - it("creates entry.server.tsx without AppLoadContext", async ({ - expect, - }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("app/entry.server.tsx"), "utf-8"); - expect(content).not.toContain("AppLoadContext"); - expect(content).not.toContain("_loadContext"); - expect(content).toContain( - 'import type { EntryContext } from "react-router"' - ); - expect(content).toContain("ServerRouter"); - expect(content).toContain("renderToReadableStream"); - }); - }); - - describe("entry.server.tsx — existing file not overwritten", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-true.ts") - ); - }); - - it("does not overwrite existing entry.server.tsx", async ({ expect }) => { - const existingContent = "// existing entry server"; - await mkdir(resolve("app"), { recursive: true }); - await writeFile(resolve("app/entry.server.tsx"), existingContent); - - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("app/entry.server.tsx"), "utf-8"); - expect(content).toBe(existingContent); - }); - }); - - describe("react-router.config.ts transformation", () => { - it("adds v8_viteEnvironmentApi for React Router >= 7.10.0", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("react-router.config.ts"), "utf-8"); - expect(content).toContain("v8_viteEnvironmentApi: true"); - // Should NOT add other v8 flags - expect(content).not.toContain("v8_middleware"); - expect(content).not.toContain("v8_splitRouteModules"); - expect(content).not.toContain("v8_passThroughRequests"); - expect(content).not.toContain("v8_trailingSlashAwareDataRequests"); - }); - - it("uses unstable_viteEnvironmentApi for React Router < 7.10.0", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - - const framework = createFramework("7.9.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("react-router.config.ts"), "utf-8"); - expect(content).toContain("unstable_viteEnvironmentApi: true"); - expect(content).not.toContain("v8_viteEnvironmentApi"); - }); - - it("preserves existing future flags when adding viteEnvironmentApi", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-middleware-true.ts") - ); - - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("react-router.config.ts"), "utf-8"); - // Existing flag preserved - expect(content).toContain("v8_middleware: true"); - // New flag added - expect(content).toContain("v8_viteEnvironmentApi: true"); - }); - }); - - describe("React Router >= 8.0.0", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - }); - - it("does not add future flags to react-router.config.ts", async ({ - expect, - }) => { - const original = readFileSync(resolve("react-router.config.ts"), "utf-8"); - - const framework = createFramework("8.0.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("react-router.config.ts"), "utf-8"); - expect(content).not.toContain("v8_viteEnvironmentApi"); - expect(content).not.toContain("unstable_viteEnvironmentApi"); - expect(content).toBe(original); - }); - - it("does not add future flags for React Router 8.x", async ({ expect }) => { - const original = readFileSync(resolve("react-router.config.ts"), "utf-8"); - - const framework = createFramework("8.2.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("react-router.config.ts"), "utf-8"); - expect(content).not.toContain("v8_viteEnvironmentApi"); - expect(content).not.toContain("unstable_viteEnvironmentApi"); - expect(content).toBe(original); - }); - - it("uses middleware pattern by default for workers/app.ts", async ({ - expect, - }) => { - const framework = createFramework("8.0.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("workers/app.ts"), "utf-8"); - expect(content).not.toContain("AppLoadContext"); - expect(content).not.toContain("declare module"); - expect(content).toContain("async fetch(request)"); - expect(content).not.toContain("env, ctx"); - expect(content).toContain("requestHandler(request)"); - }); - - it("uses middleware pattern by default for entry.server.tsx", async ({ - expect, - }) => { - const framework = createFramework("8.0.0"); - await framework.configure(getBaseOptions()); - - const content = readFileSync(resolve("app/entry.server.tsx"), "utf-8"); - expect(content).not.toContain("AppLoadContext"); - expect(content).not.toContain("_loadContext"); - expect(content).toContain( - 'import type { EntryContext } from "react-router"' - ); - }); - }); - - describe("hasV8MiddlewareFlag with version >= 8.0.0", () => { - it("returns true without config file when version >= 8.0.0", ({ - expect, - }) => { - expect(hasV8MiddlewareFlag(process.cwd(), "8.0.0")).toBe(true); - }); - - it("returns true regardless of config content when version >= 8.0.0", async ({ - expect, - }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd(), "8.0.0")).toBe(true); - }); - - it("still parses config for versions < 8.0.0", async ({ expect }) => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - expect(hasV8MiddlewareFlag(process.cwd(), "7.16.0")).toBe(false); - }); - }); - - describe("dry run", () => { - it("does not create files in dry run mode", async ({ expect }) => { - const framework = createFramework("7.16.0"); - const result = await framework.configure({ - ...getBaseOptions(), - dryRun: true, - }); - - expect(result.workerConfig).toEqual({ - entrypoint: "./workers/app.ts", - }); - expect(existsSync(resolve("workers/app.ts"))).toBe(false); - expect(existsSync(resolve("app/entry.server.tsx"))).toBe(false); - }); - }); - - describe("wrangler config", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - }); - - it("returns wrangler config with main pointing to workers/app.ts", async ({ - expect, - }) => { - const framework = createFramework("7.16.0"); - const result = await framework.configure(getBaseOptions()); - - expect(result.workerConfig).toEqual({ - entrypoint: "./workers/app.ts", - }); - }); - }); - - describe("package installation", () => { - beforeEach(async () => { - await writeFile( - resolve("react-router.config.ts"), - fixture("config-no-future.ts") - ); - }); - - it("installs isbot as a dev dependency", async ({ expect }) => { - const framework = createFramework("7.16.0"); - await framework.configure(getBaseOptions()); - - expect(cliPackages.installPackages).toHaveBeenCalledWith( - NpmPackageManager.type, - ["isbot"], - expect.objectContaining({ dev: true }) - ); - }); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/utils/vite-plugin.test.ts b/packages/autoconfig/tests/frameworks/utils/vite-plugin.test.ts deleted file mode 100644 index 81728d5278..0000000000 --- a/packages/autoconfig/tests/frameworks/utils/vite-plugin.test.ts +++ /dev/null @@ -1,306 +0,0 @@ -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { beforeEach, describe, it, vi } from "vitest"; -import { getInstalledPackageVersion } from "../../../src/frameworks/utils/packages"; -import { installCloudflareVitePlugin } from "../../../src/frameworks/utils/vite-plugin"; -import type { MockInstance } from "vitest"; - -vi.mock("../../../src/frameworks/utils/packages", () => ({ - getInstalledPackageVersion: vi.fn(), -})); - -describe("installCloudflareVitePlugin", () => { - let installSpy: MockInstance; - - beforeEach(() => { - installSpy = vi - .spyOn(cliPackages, "installPackages") - .mockImplementation(async () => {}); - }); - - describe("when Vite is not installed/detected", () => { - beforeEach(() => { - vi.mocked(getInstalledPackageVersion).mockReturnValue(undefined); - }); - - it("installs only @cloudflare/vite-plugin", async ({ expect }) => { - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin"], - expect.objectContaining({ dev: true }) - ); - }); - - it("installs a requested plugin version or tag", async ({ expect }) => { - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - version: "beta", - }); - - expect(installSpy).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin@beta"], - expect.objectContaining({ - dev: true, - doneText: expect.stringContaining("@cloudflare/vite-plugin@beta"), - }) - ); - }); - - it("does not attempt to upgrade Vite", async ({ expect }) => { - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).not.toHaveBeenCalledWith( - expect.anything(), - ["vite@^6.1.0"], - expect.anything() - ); - }); - }); - - describe("when Vite version is in [6.0.0, 6.1.0) range", () => { - it("upgrades Vite before installing the plugin for version 6.0.0", async ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("6.0.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(2); - expect(installSpy).toHaveBeenNthCalledWith( - 1, - "npm", - ["vite@^6.1.0"], - expect.objectContaining({ dev: true }) - ); - expect(installSpy).toHaveBeenNthCalledWith( - 2, - "npm", - ["@cloudflare/vite-plugin"], - expect.objectContaining({ dev: true }) - ); - }); - - it("upgrades Vite before installing the plugin for version 6.0.5", async ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("6.0.5"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(2); - expect(installSpy).toHaveBeenNthCalledWith( - 1, - "npm", - ["vite@^6.1.0"], - expect.objectContaining({ dev: true }) - ); - expect(installSpy).toHaveBeenNthCalledWith( - 2, - "npm", - ["@cloudflare/vite-plugin"], - expect.objectContaining({ dev: true }) - ); - }); - }); - - describe("when Vite version is >= 6.1.0", () => { - it("does not upgrade Vite for version 6.1.0", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("6.1.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin"], - expect.objectContaining({ dev: true }) - ); - }); - - it("does not upgrade Vite for version 6.2.0", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("6.2.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).not.toHaveBeenCalledWith( - expect.anything(), - ["vite@^6.1.0"], - expect.anything() - ); - }); - - it("does not upgrade Vite for version 7.0.0", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("7.0.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).not.toHaveBeenCalledWith( - expect.anything(), - ["vite@^6.1.0"], - expect.anything() - ); - }); - }); - - describe("when Vite version is < 6.0.0", () => { - it("does not upgrade Vite for version 5.4.0", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("5.4.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).not.toHaveBeenCalledWith( - expect.anything(), - ["vite@^6.1.0"], - expect.anything() - ); - }); - - it("does not upgrade Vite for version 4.0.0", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("4.0.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledTimes(1); - expect(installSpy).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin"], - expect.objectContaining({ dev: true }) - ); - }); - }); - - describe("parameter forwarding", () => { - beforeEach(() => { - vi.mocked(getInstalledPackageVersion).mockReturnValue(undefined); - }); - - it("forwards isWorkspaceRoot to installPackages", async ({ expect }) => { - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: true, - }); - - expect(installSpy).toHaveBeenCalledWith( - expect.anything(), - expect.anything(), - expect.objectContaining({ isWorkspaceRoot: true }) - ); - }); - - it("forwards isWorkspaceRoot when upgrading Vite", async ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("6.0.0"); - - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/test/project", - isWorkspaceRoot: true, - }); - - // Both the Vite upgrade and plugin install should have isWorkspaceRoot: true - expect(installSpy).toHaveBeenNthCalledWith( - 1, - expect.anything(), - ["vite@^6.1.0"], - expect.objectContaining({ isWorkspaceRoot: true }) - ); - expect(installSpy).toHaveBeenNthCalledWith( - 2, - expect.anything(), - ["@cloudflare/vite-plugin"], - expect.objectContaining({ isWorkspaceRoot: true }) - ); - }); - - it("forwards packageManager to installPackages", async ({ expect }) => { - await installCloudflareVitePlugin({ - packageManager: "pnpm", - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledWith( - "pnpm", - expect.anything(), - expect.anything() - ); - }); - - it("forwards different package managers correctly", async ({ expect }) => { - for (const pm of ["npm", "yarn", "pnpm", "bun"] as const) { - installSpy.mockClear(); - - await installCloudflareVitePlugin({ - packageManager: pm, - projectPath: "/test/project", - isWorkspaceRoot: false, - }); - - expect(installSpy).toHaveBeenCalledWith( - pm, - expect.anything(), - expect.anything() - ); - } - }); - - it("passes projectPath to getInstalledPackageVersion", async ({ - expect, - }) => { - await installCloudflareVitePlugin({ - packageManager: "npm", - projectPath: "/custom/path", - isWorkspaceRoot: false, - }); - - expect(getInstalledPackageVersion).toHaveBeenCalledWith( - "vite", - "/custom/path" - ); - }); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/validate-framework-version.test.ts b/packages/autoconfig/tests/frameworks/validate-framework-version.test.ts deleted file mode 100644 index c2325117ca..0000000000 --- a/packages/autoconfig/tests/frameworks/validate-framework-version.test.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { mockConsoleMethods } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it, vi } from "vitest"; -import { AutoConfigFrameworkConfigurationError } from "../../src/errors"; -import { getFrameworkPackageInfo } from "../../src/frameworks/all-frameworks"; -import { Framework } from "../../src/frameworks/framework-class"; -import { getInstalledPackageVersion } from "../../src/frameworks/utils/packages"; -import { createMockContext } from "../helpers/mock-context"; -import type { AutoConfigFrameworkPackageInfo } from "../../src/frameworks"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "../../src/frameworks/framework-class"; - -vi.mock("../../src/frameworks/utils/packages"); - -/** Minimal concrete subclass so we can instantiate the abstract Framework */ -class TestFramework extends Framework { - configure(_options: ConfigurationOptions): ConfigurationResults { - return { workerConfig: null }; - } -} - -const PACKAGE_INFO: AutoConfigFrameworkPackageInfo = { - name: "some-pkg", - minimumVersion: "2.0.0", - maximumKnownMajorVersion: "4", -}; - -describe("Framework.validateFrameworkVersion()", () => { - const std = mockConsoleMethods(); - const context = createMockContext(); - - it("throws an AssertionError when the package version cannot be determined", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue(undefined); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).toThrow("Unable to detect the version of the `some-pkg` package"); - }); - - it("throws AutoConfigFrameworkConfigurationError when installed version is below minimum", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("1.0.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).toThrow(AutoConfigFrameworkConfigurationError); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).toThrowErrorMatchingInlineSnapshot( - `[Error: The version of Test used in the project ("1.0.0") cannot be automatically configured. Please update the Test version to at least "2.0.0" and try again.]` - ); - }); - - it("does not throw and sets frameworkVersion when installed version equals minimumVersion", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("2.0.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("2.0.0"); - expect(std.warn).toBe(""); - }); - - it("does not throw and sets frameworkVersion when installed version is within known range", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("3.0.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("3.0.0"); - expect(std.warn).toBe(""); - }); - - it("does not throw and does not warn when installed version equals maximumKnownMajorVersion", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("4.0.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("4.0.0"); - expect(std.warn).toBe(""); - }); - - it("does not throw and does not warn when installed version is a minor/patch update within the known major", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("4.5.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("4.5.0"); - expect(std.warn).toBe(""); - }); - - it("does not throw nor warn when the installed version is an update within the known major", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("4.3.2"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("4.3.2"); - expect(std.warn).toBe(""); - }); - - it("does not throw but warns when installed version exceeds maximumKnownMajorVersion", ({ - expect, - }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("5.0.0"); - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => - framework.validateFrameworkVersion("/project", PACKAGE_INFO, context) - ).not.toThrow(); - expect(framework.frameworkVersion).toBe("5.0.0"); - expect(std.warn).toContain('"5.0.0"'); - expect(std.warn).toContain("Test"); - expect(std.warn).toContain("is not officially supported"); - }); - - it("does not warn for Astro 7", ({ expect }) => { - vi.mocked(getInstalledPackageVersion).mockReturnValue("7.3.0"); - const framework = new TestFramework({ id: "astro", name: "Astro" }); - const packageInfo = getFrameworkPackageInfo("astro"); - - expect(packageInfo).toBeDefined(); - if (packageInfo === undefined) { - throw new Error("Expected Astro to have package information"); - } - framework.validateFrameworkVersion("/project", packageInfo, context); - - expect(framework.frameworkVersion).toBe("7.3.0"); - expect(std.warn).toBe(""); - }); - - it("throws an AssertionError when frameworkVersion getter is accessed before validateFrameworkVersion is called", ({ - expect, - }) => { - const framework = new TestFramework({ id: "test", name: "Test" }); - - expect(() => framework.frameworkVersion).toThrow( - 'The version for "Test" is unexpectedly missing' - ); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/vike.test.ts b/packages/autoconfig/tests/frameworks/vike.test.ts deleted file mode 100644 index 86ba026787..0000000000 --- a/packages/autoconfig/tests/frameworks/vike.test.ts +++ /dev/null @@ -1,327 +0,0 @@ -import { mkdir, readFile, writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { beforeEach, describe, it, vi } from "vitest"; -import { Vike } from "../../src/frameworks/vike"; -import { createMockContext } from "../helpers/mock-context"; - -vi.mock("../../src/frameworks/utils/packages", () => ({ - isPackageInstalled: () => false, -})); - -vi.mock("../../src/frameworks/utils/vite-plugin", () => ({ - installCloudflareVitePlugin: async () => {}, -})); - -const context = createMockContext(); - -function getBaseOptions() { - return { - target: "wrangler" as const, - projectPath: process.cwd(), - workerName: "my-vike-app", - outputDir: "", - dryRun: false, - packageManager: NpmPackageManager, - isWorkspaceRoot: false, - context, - }; -} - -describe("Vike framework configure()", () => { - runInTempDir(); - - beforeEach(() => { - vi.spyOn(cliPackages, "installPackages").mockImplementation(async () => {}); - }); - - describe("config file transformation", () => { - it("handles the old format: `export default { ... } satisfies Config`", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import type { Config } from "vike/types"; -import vikeReact from "vike-react/config"; - -// Default config (can be overridden by pages) -// https://vike.dev/config - -export default { - // https://vike.dev/head-tags - title: "My Vike App", - description: "Demo showcasing Vike", - - extends: [vikeReact], -} satisfies Config; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - - it("handles the new format: `const config: Config = { ... }; export default config;`", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import type { Config } from "vike/types"; -import vikeReact from "vike-react/config"; - -// Default config (can be overridden by pages) -// https://vike.dev/config - -const config: Config = { - // https://vike.dev/head-tags - title: "My Vike App", - description: "Demo showcasing Vike", - - extends: [vikeReact], -}; - -export default config; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - - it("handles plain format: `export default { ... }`", async ({ expect }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import vikeReact from "vike-react/config"; - -export default { - title: "My Vike App", - extends: [vikeReact], -}; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - - it("handles `export default { ... } as Config` format", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import type { Config } from "vike/types"; -import vikeReact from "vike-react/config"; - -export default { - title: "My Vike App", - extends: [vikeReact], -} as Config; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - - it("creates extends array if not present", async ({ expect }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import vikeReact from "vike-react/config"; - -export default { - title: "My Vike App", -}; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikePhoton]"); - }); - - it("creates extends array on variable-referenced config if not present", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import type { Config } from "vike/types"; - -const config: Config = { - title: "My Vike App", -}; - -export default config; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikePhoton]"); - }); - - it("does not duplicate import or extends entry on repeated calls", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import vikeReact from "vike-react/config"; -import vikePhoton from "vike-photon/config"; - -export default { - title: "My Vike App", - extends: [vikeReact, vikePhoton], -}; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - - const importCount = ( - result.match(/import vikePhoton from "vike-photon\/config"/g) || [] - ).length; - expect(importCount).toBe(1); - - // Verify the extends array wasn't duplicated either - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - - it("does not duplicate extends entry when vike-photon is imported under a different name", async ({ - expect, - }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import vikeReact from "vike-react/config"; -import photon from "vike-photon/config"; - -export default { - title: "My Vike App", - extends: [vikeReact, photon], -}; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - - // Should not add a second import - const importCount = (result.match(/from "vike-photon\/config"/g) || []) - .length; - expect(importCount).toBe(1); - - // Should not duplicate the extends entry under any name - expect(result).toContain("extends: [vikeReact, photon]"); - expect(result).not.toContain("vikePhoton"); - }); - - it("uses .js config file as fallback", async ({ expect }) => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.js"), - `import vikeReact from "vike-react/config"; - -export default { - title: "My Vike App", - extends: [vikeReact], -}; -` - ); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure(getBaseOptions()); - - const result = await readFile(resolve("pages/+config.js"), "utf8"); - expect(result).toContain('import vikePhoton from "vike-photon/config";'); - expect(result).toContain("extends: [vikeReact, vikePhoton]"); - }); - }); - - describe("configure() return value", () => { - beforeEach(async () => { - await mkdir(resolve("pages"), { recursive: true }); - await writeFile( - resolve("pages/+config.ts"), - `import vikeReact from "vike-react/config"; - -export default { - extends: [vikeReact], -}; -` - ); - }); - - it("returns the Worker config", async ({ expect }) => { - const framework = new Vike({ id: "vike", name: "Vike" }); - const result = await framework.configure(getBaseOptions()); - - expect(result.workerConfig).toEqual({ - entrypoint: "virtual:photon:cloudflare:server-entry", - }); - }); - - it("returns correct packageJsonScriptsOverrides", async ({ expect }) => { - const framework = new Vike({ id: "vike", name: "Vike" }); - const result = await framework.configure(getBaseOptions()); - - expect(result.packageJsonScriptsOverrides).toEqual({ - preview: "vike build && vike preview", - deploy: "vike build && wrangler deploy", - }); - }); - }); - - describe("dryRun mode", () => { - it("does not modify config file in dryRun mode", async ({ expect }) => { - await mkdir(resolve("pages"), { recursive: true }); - const originalContent = `import vikeReact from "vike-react/config"; - -export default { - extends: [vikeReact], -}; -`; - await writeFile(resolve("pages/+config.ts"), originalContent); - - const framework = new Vike({ id: "vike", name: "Vike" }); - await framework.configure({ ...getBaseOptions(), dryRun: true }); - - const result = await readFile(resolve("pages/+config.ts"), "utf8"); - expect(result).toBe(originalContent); - }); - }); -}); diff --git a/packages/autoconfig/tests/frameworks/vite.test.ts b/packages/autoconfig/tests/frameworks/vite.test.ts deleted file mode 100644 index a934d13ca1..0000000000 --- a/packages/autoconfig/tests/frameworks/vite.test.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { existsSync, readFileSync } from "node:fs"; -import { writeFile } from "node:fs/promises"; -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { beforeEach, describe, it, vi } from "vitest"; -import { Vite } from "../../src/frameworks/vite"; -import { createMockContext } from "../helpers/mock-context"; - -const context = createMockContext(); - -const BASE_OPTIONS = { - target: "cf" as const, - projectPath: ".", - workerName: "my-vite-app", - outputDir: "dist", - dryRun: false, - packageManager: NpmPackageManager, - isWorkspaceRoot: false, - context, -}; - -describe("Vite framework", () => { - runInTempDir(); - - beforeEach(() => { - vi.spyOn(cliPackages, "installPackages").mockImplementation(async () => {}); - }); - - it("accepts Cloudflare modes", ({ expect }) => { - const framework = new Vite({ id: "vite", name: "Vite" }); - - expect(framework.supportsMode).toBe(true); - }); - - describe("isConfigured()", () => { - it("returns false when no vite config file exists", ({ expect }) => { - const framework = new Vite({ id: "vite", name: "Vite" }); - expect(framework.isConfigured(".")).toBe(false); - }); - - it("only treats the Cloudflare plugin as configured in legacy Wrangler mode", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - `import { cloudflare } from "@cloudflare/vite-plugin"; - import { defineConfig } from "vite"; - export default defineConfig({ plugins: [cloudflare()] });` - ); - const framework = new Vite({ id: "vite", name: "Vite" }); - - expect(framework.isConfigured(".")).toBe(false); - expect(framework.isConfigured(".", { target: "wrangler" })).toBe(true); - }); - }); - - describe("configure()", () => { - it("creates a vite config with the cloudflare plugin when no config file exists", async ({ - expect, - }) => { - const framework = new Vite({ id: "vite", name: "Vite" }); - const result = await framework.configure(BASE_OPTIONS); - expect(cliPackages.installPackages).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin@beta"], - expect.anything() - ); - - expect(existsSync("vite.config.js")).toBe(true); - const content = readFileSync("vite.config.js", "utf-8"); - expect(content).toContain( - 'import { cloudflare } from "@cloudflare/vite-plugin"' - ); - expect(content).toContain("plugins: [cloudflare()]"); - - expect(result.workerConfig).toEqual({ - assets: { - notFoundHandling: "single-page-application", - }, - }); - expect(result.buildTool).toBe("vite"); - }); - - it("installs the stable plugin for Wrangler", async ({ expect }) => { - const framework = new Vite({ id: "vite", name: "Vite" }); - await framework.configure({ ...BASE_OPTIONS, target: "wrangler" }); - - expect(cliPackages.installPackages).toHaveBeenCalledWith( - "npm", - ["@cloudflare/vite-plugin"], - expect.anything() - ); - }); - - it("uses .ts extension when the project has a tsconfig.json", async ({ - expect, - }) => { - await writeFile("tsconfig.json", "{}"); - - const framework = new Vite({ id: "vite", name: "Vite" }); - await framework.configure(BASE_OPTIONS); - - expect(existsSync("vite.config.ts")).toBe(true); - expect(existsSync("vite.config.js")).toBe(false); - }); - - it("transforms existing vite config instead of creating a new one", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; -import react from '@vitejs/plugin-react'; - -export default defineConfig({ - plugins: [react()] -}); -` - ); - - const framework = new Vite({ id: "vite", name: "Vite" }); - await framework.configure(BASE_OPTIONS); - - const content = readFileSync("vite.config.ts", "utf-8"); - expect(content).toContain("cloudflare()"); - // Existing plugins should be preserved - expect(content).toContain("react()"); - }); - - it("does not create or modify files in dry-run mode", async ({ - expect, - }) => { - const framework = new Vite({ id: "vite", name: "Vite" }); - const result = await framework.configure({ - ...BASE_OPTIONS, - dryRun: true, - }); - - expect(existsSync("vite.config.ts")).toBe(false); - expect(existsSync("vite.config.js")).toBe(false); - expect(result.workerConfig).toEqual({ - assets: { - notFoundHandling: "single-page-application", - }, - }); - }); - }); -}); diff --git a/packages/autoconfig/tests/get-installed-package-version.test.ts b/packages/autoconfig/tests/get-installed-package-version.test.ts deleted file mode 100644 index 533374d790..0000000000 --- a/packages/autoconfig/tests/get-installed-package-version.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, test } from "vitest"; -import { getInstalledPackageVersion } from "../src/frameworks/utils/packages"; - -describe("getInstalledPackageVersion()", () => { - runInTempDir(); - test("happy path", async ({ expect }) => { - await seed({ - "node_modules/react-router/package.json": JSON.stringify({ - name: "react-router", - version: "1.2.3", - main: "index.js", - }), - "node_modules/react-router/index.js": "console.log(1)", - }); - expect(getInstalledPackageVersion("react-router", process.cwd())).toBe( - "1.2.3" - ); - }); - - test("no node_modules", async ({ expect }) => { - expect( - getInstalledPackageVersion("react-router", process.cwd()) - ).toBeUndefined(); - }); - - test("aliased package returns the bundled version of the requested package", async ({ - expect, - }) => { - // vite+ installs `@voidzero-dev/vite-plus-core` under the `vite` alias, so - // the resolved package.json has a different `name` and its own `version`. - await seed({ - "node_modules/vite/package.json": JSON.stringify({ - name: "@voidzero-dev/vite-plus-core", - version: "0.2.2", - bundledVersions: { - vite: "8.1.2", - rolldown: "1.0.0", - tsdown: "0.15.0", - }, - main: "index.js", - }), - "node_modules/vite/index.js": "console.log(1)", - }); - expect(getInstalledPackageVersion("vite", process.cwd())).toBe("8.1.2"); - }); - - test("aliased package without a matching bundled version falls back to its own version", async ({ - expect, - }) => { - await seed({ - "node_modules/vite/package.json": JSON.stringify({ - name: "@voidzero-dev/vite-plus-core", - version: "0.2.2", - bundledVersions: { - rolldown: "1.0.0", - }, - main: "index.js", - }), - "node_modules/vite/index.js": "console.log(1)", - }); - expect(getInstalledPackageVersion("vite", process.cwd())).toBe("0.2.2"); - }); - - test("package whose name matches ignores bundledVersions and returns its own version", async ({ - expect, - }) => { - await seed({ - "node_modules/vite/package.json": JSON.stringify({ - name: "vite", - version: "6.3.0", - bundledVersions: { - vite: "8.1.2", - }, - main: "index.js", - }), - "node_modules/vite/index.js": "console.log(1)", - }); - expect(getInstalledPackageVersion("vite", process.cwd())).toBe("6.3.0"); - }); -}); diff --git a/packages/autoconfig/tests/helpers/mock-context.ts b/packages/autoconfig/tests/helpers/mock-context.ts deleted file mode 100644 index 98d8d3fd74..0000000000 --- a/packages/autoconfig/tests/helpers/mock-context.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { vi } from "vitest"; -import type { AutoConfigContext } from "../../src/context"; - -/** - * Creates a mock `AutoConfigContext` suitable for testing. - * All dialog methods default to returning sensible values. - * The logger delegates to `console` so that `mockConsoleMethods()` captures - * the output and tests can assert on `std.out`, `std.warn`, etc. - * - * @param overrides - Partial overrides to customize the context. - * @returns A fully mocked `AutoConfigContext`. - */ -export function createMockContext( - overrides?: Partial -): AutoConfigContext { - return { - logger: { - log: vi.fn((...args: unknown[]) => console.log(...args)), - info: vi.fn((...args: unknown[]) => console.info(...args)), - warn: vi.fn((...args: unknown[]) => console.warn(...args)), - debug: vi.fn((...args: unknown[]) => console.debug(...args)), - error: vi.fn((...args: unknown[]) => console.error(...args)), - }, - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi.fn().mockResolvedValue(""), - select: vi.fn().mockResolvedValue(""), - }, - runCommand: vi.fn(), - isNonInteractiveOrCI: () => false, - getCacheFolder: () => undefined, - ...overrides, - }; -} diff --git a/packages/autoconfig/tests/run-summary.test.ts b/packages/autoconfig/tests/run-summary.test.ts deleted file mode 100644 index 9b3fb69cf4..0000000000 --- a/packages/autoconfig/tests/run-summary.test.ts +++ /dev/null @@ -1,341 +0,0 @@ -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { mockConsoleMethods } from "@cloudflare/workers-utils/test-helpers"; -import { dedent } from "ts-dedent"; -import { describe, test } from "vitest"; -import { Astro } from "../src/frameworks/astro"; -import { Static } from "../src/frameworks/static"; -import { buildOperationsSummary } from "../src/run"; -import { createMockContext } from "./helpers/mock-context"; -import type { WorkerConfig } from "@cloudflare/config"; - -const testWorkerConfig: WorkerConfig = { - name: "worker-name", - compatibilityDate: "2026-08-04", - observability: { - enabled: true, - }, -}; - -describe("autoconfig run - buildOperationsSummary()", () => { - const std = mockConsoleMethods(); - const context = createMockContext(); - - describe("interactive mode", () => { - test("presents a summary for a simple project where only a wrangler.jsonc file needs to be created", async ({ - expect, - }) => { - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - configured: false, - outputDir: "public", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { workerConfig: testWorkerConfig }, - { - build: "npm run build", - deploy: "npx wrangler deploy", - version: "npx wrangler versions upload", - }, - false, - "wrangler", - context - ); - - expect(std.out).toMatchInlineSnapshot(` - " - 📄 Create wrangler.jsonc: - { - "$schema": "node_modules/wrangler/config-schema.json", - "name": "worker-name", - "compatibility_date": "2026-08-04", - "observability": { - "enabled": true - } - } - " - `); - - expect(summary).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "deployCommand": "npx wrangler deploy", - "frameworkId": "static", - "outputDir": "public", - "scripts": {}, - "versionCommand": "npx wrangler versions upload", - "wranglerConfig": { - "$schema": "node_modules/wrangler/config-schema.json", - "compatibility_date": "2026-08-04", - "name": "worker-name", - "observability": { - "enabled": true, - }, - }, - } - `); - }); - - test("shows that wrangler will be added as a devDependency when not already installed as such", async ({ - expect, - }) => { - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - packageJson: { - name: "my-project", - devDependencies: {}, - }, - configured: false, - outputDir: "dist", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { workerConfig: testWorkerConfig }, - { - build: "npm run build", - deploy: "npx wrangler deploy", - version: "npx wrangler versions upload", - }, - true, - "wrangler", - context - ); - - expect(std.out).toContain( - dedent` - 📦 Install packages: - - wrangler (devDependency) - ` - ); - - expect(summary).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "deployCommand": "npx wrangler deploy", - "frameworkId": "static", - "outputDir": "dist", - "scripts": { - "deploy": "wrangler deploy", - "preview": "wrangler dev", - }, - "versionCommand": "npx wrangler versions upload", - "wranglerConfig": { - "$schema": "node_modules/wrangler/config-schema.json", - "compatibility_date": "2026-08-04", - "name": "worker-name", - "observability": { - "enabled": true, - }, - }, - } - `); - }); - - test("when a package.json is present wrangler@latest will be unconditionally installed (even if already present)", async ({ - expect, - }) => { - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - packageJson: { - name: "my-project", - devDependencies: { - wrangler: "^4.0.0", - }, - }, - configured: false, - outputDir: "out", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { workerConfig: testWorkerConfig }, - { - build: "npm run build", - deploy: "npx wrangler deploy", - version: "npx wrangler versions upload", - }, - true, - "wrangler", - context - ); - - expect(std.out).toContain( - dedent` - 📦 Install packages: - - wrangler (devDependency) - ` - ); - - expect(summary).toMatchInlineSnapshot(` - { - "buildCommand": "npm run build", - "deployCommand": "npx wrangler deploy", - "frameworkId": "static", - "outputDir": "out", - "scripts": { - "deploy": "wrangler deploy", - "preview": "wrangler dev", - }, - "versionCommand": "npx wrangler versions upload", - "wranglerConfig": { - "$schema": "node_modules/wrangler/config-schema.json", - "compatibility_date": "2026-08-04", - "name": "worker-name", - "observability": { - "enabled": true, - }, - }, - } - `); - }); - - test("uses cf scripts and previews package installation and generated config files", async ({ - expect, - }) => { - const buildConfig = { assetsDirectory: "dist" }; - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - packageJson: { name: "my-project" }, - configured: false, - outputDir: "dist", - buildCommand: "npm run build", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { - buildTool: "wrangler", - workerConfig: testWorkerConfig, - buildConfig, - }, - { - build: "npm run build", - deploy: "cf deploy", - }, - true, - "cf", - context, - { - deploy: "wrangler deploy", - preview: "wrangler dev", - } - ); - - expect(summary.scripts).toEqual({ - deploy: "cf deploy", - }); - expect(std.out).toContain( - dedent` - 📦 Install packages: - - cf (devDependency) - - wrangler (devDependency) - ` - ); - expect(std.out).toContain(' import { defineConfig } from "cf/config";'); - expect(std.out).toContain(" export default defineConfig({"); - expect(std.out).toContain( - ' import { defineWranglerConfig } from "wrangler/experimental-config";' - ); - expect(std.out).toContain(" export default defineWranglerConfig({"); - }); - - test.for([ - { target: "cf", plugin: "@cloudflare/vite-plugin@beta" }, - { target: "wrangler", plugin: "@cloudflare/vite-plugin" }, - ] as const)( - "shows that $plugin will be installed for $target", - async ({ target, plugin }, { expect }) => { - await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - packageJson: { name: "my-project" }, - configured: false, - outputDir: "dist", - framework: new Static({ id: "static", name: "Static" }), - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { buildTool: "vite", workerConfig: testWorkerConfig }, - { build: "npm run build", deploy: `${target} deploy` }, - false, - target, - context - ); - - expect(std.out).toContain(` - ${plugin} (devDependency)`); - } - ); - - test("shows that when needed a framework specific configuration will be run", async ({ - expect, - }) => { - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - framework: new Astro({ id: "astro", name: "Astro" }), - configured: false, - outputDir: "dist", - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { workerConfig: testWorkerConfig }, - { - build: "npm run build", - deploy: "npx wrangler deploy", - }, - false, - "wrangler", - context - ); - - expect(std.out).toContain( - '🛠️ Configuring project for Astro with "astro add cloudflare"' - ); - - expect(summary.frameworkConfiguration).toBe( - 'Configuring project for Astro with "astro add cloudflare"' - ); - - expect(summary.frameworkId).toBe("astro"); - }); - - test("doesn't show the framework specific configuration step for the Static framework", async ({ - expect, - }) => { - const summary = await buildOperationsSummary( - { - workerName: "worker-name", - projectPath: "", - framework: new Static({ id: "static", name: "Static" }), - configured: false, - outputDir: "public", - packageManager: NpmPackageManager, - }, - testWorkerConfig, - { workerConfig: testWorkerConfig }, - { - build: "npm run build", - deploy: "npx wrangler deploy", - }, - false, - "wrangler", - context - ); - - expect(std.out).not.toContain("🛠️ Configuring project for"); - expect(summary.frameworkConfiguration).toBeUndefined(); - }); - }); -}); diff --git a/packages/autoconfig/tests/run.test.ts b/packages/autoconfig/tests/run.test.ts deleted file mode 100644 index 60356e151d..0000000000 --- a/packages/autoconfig/tests/run.test.ts +++ /dev/null @@ -1,425 +0,0 @@ -import { existsSync, readFileSync } from "node:fs"; -import * as cliPackages from "@cloudflare/cli-shared-helpers/packages"; -import { NpmPackageManager } from "@cloudflare/workers-utils"; -import { - mockConsoleMethods, - runInTempDir, - seed, -} from "@cloudflare/workers-utils/test-helpers"; -import { describe, it, vi } from "vitest"; -import { getFrameworkClassInstance } from "../src/frameworks"; -import { Framework } from "../src/frameworks/framework-class"; -import { Static } from "../src/frameworks/static"; -import { runAutoConfig } from "../src/run"; -import { createMockContext } from "./helpers/mock-context"; -import type { - ConfigurationOptions, - ConfigurationResults, -} from "../src/frameworks/framework-class"; - -class ExternalWorkerConfigFramework extends Framework { - configure(): ConfigurationResults { - return { - buildTool: "wrangler", - workerConfig: null, - buildConfig: { assetsDirectory: "dist" }, - }; - } -} - -class ViteBuildToolFramework extends Framework { - configure(): ConfigurationResults { - return { - buildTool: "vite", - workerConfig: { entrypoint: "src/index.ts" }, - }; - } -} - -class BuildCommandOverrideFramework extends Static { - configure(options: ConfigurationOptions): ConfigurationResults { - return { - ...super.configure(options), - buildCommandOverride: "npx framework build", - }; - } -} - -describe("runAutoConfig()", () => { - runInTempDir(); - mockConsoleMethods(); - - it("rejects autoconfiguration for an unsupported framework", async ({ - expect, - }) => { - await expect( - runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "hono-app", - framework: getFrameworkClassInstance("hono"), - outputDir: "dist", - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ) - ).rejects.toThrow( - 'The detected framework ("Hono") cannot be automatically configured.' - ); - }); - - it("rejects a Wrangler-only framework when passed preconstructed cf details", async ({ - expect, - }) => { - await expect( - runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "qwik-app", - framework: getFrameworkClassInstance("qwik"), - outputDir: "dist", - packageManager: NpmPackageManager, - }, - { - target: "cf", - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ) - ).rejects.toThrow( - "cf does not support Qwik projects yet. You can still use Wrangler to develop and deploy this project." - ); - }); - - it("allows selecting a cf-supported framework during confirmation", async ({ - expect, - }) => { - vi.spyOn(cliPackages, "installWrangler").mockResolvedValue(); - const context = createMockContext({ - dialogs: { - confirm: vi.fn().mockResolvedValue(true), - prompt: vi - .fn() - .mockResolvedValueOnce("static-app") - .mockResolvedValueOnce("dist"), - select: vi.fn().mockResolvedValue("static"), - }, - }); - - const summary = await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "qwik-app", - framework: getFrameworkClassInstance("qwik"), - outputDir: "dist", - packageManager: NpmPackageManager, - }, - { - target: "cf", - context, - runBuild: false, - enableTargetCliInstallation: false, - } - ); - - expect(summary.frameworkId).toBe("static"); - }); - - it("creates new configuration and cf scripts by default", async ({ - expect, - }) => { - const installWrangler = vi - .spyOn(cliPackages, "installWrangler") - .mockResolvedValue(); - const packageJson = { - name: "my-static-app", - scripts: { - build: "generate && vite build", - preview: "vite preview", - }, - }; - await seed({ - "package.json": JSON.stringify(packageJson), - "public/index.html": "

Hello World

", - }); - const context = createMockContext(); - - const summary = await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-static-app", - framework: new BuildCommandOverrideFramework({ - id: "static", - name: "Static", - }), - buildCommand: "npm run build", - outputDir: "public", - packageJson, - packageManager: NpmPackageManager, - }, - { - context, - skipConfirmations: true, - enableTargetCliInstallation: false, - } - ); - - expect(summary.workerConfig).toMatchObject({ - name: "my-static-app", - observability: { enabled: true }, - }); - expect(summary.buildConfig).toEqual({ assetsDirectory: "public" }); - expect(summary.buildCommand).toBe("npx framework build"); - expect(summary.deployCommand).toBe("npx cf deploy"); - expect(summary.versionCommand).toBe("npx cf versions upload"); - expect(readFileSync("cloudflare.config.ts", "utf8")).toContain( - 'import { defineConfig } from "cf/config";\n\nexport default defineConfig({\n worker: {\n "name": "my-static-app"' - ); - expect(readFileSync("wrangler.config.ts", "utf8")).toContain( - 'import { defineWranglerConfig } from "wrangler/experimental-config";\n\nexport default defineWranglerConfig({\n "assetsDirectory": "public"' - ); - expect(existsSync("wrangler.jsonc")).toBe(false); - expect(installWrangler).toHaveBeenCalledWith("npm", false); - expect(context.runCommand).toHaveBeenCalledWith( - "npx framework build", - process.cwd(), - "[build]" - ); - expect(JSON.parse(readFileSync("package.json", "utf8"))).toMatchObject({ - scripts: { - build: "generate && vite build", - deploy: "cf deploy", - preview: "vite preview", - }, - }); - }); - - it("installs cf and Wrangler for cf projects", async ({ expect }) => { - const installPackages = vi - .spyOn(cliPackages, "installPackages") - .mockResolvedValue(); - const installWrangler = vi - .spyOn(cliPackages, "installWrangler") - .mockResolvedValue(); - const packageJson = { name: "my-static-app" }; - await seed({ - "package.json": JSON.stringify(packageJson), - "public/index.html": "

Hello World

", - }); - - await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-static-app", - framework: new Static({ id: "static", name: "Static" }), - outputDir: "public", - packageJson, - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ); - - expect(installPackages).toHaveBeenCalledWith("npm", ["cf@latest"], { - dev: true, - isWorkspaceRoot: false, - }); - expect(installWrangler).toHaveBeenCalledWith("npm", false); - }); - - it("does not reinstall an existing cf dependency", async ({ expect }) => { - const installPackages = vi - .spyOn(cliPackages, "installPackages") - .mockResolvedValue(); - vi.spyOn(cliPackages, "installWrangler").mockResolvedValue(); - const packageJson = { - name: "my-static-app", - devDependencies: { cf: "^0.8.0" }, - }; - await seed({ - "package.json": JSON.stringify(packageJson), - "public/index.html": "

Hello World

", - }); - - await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-static-app", - framework: new Static({ id: "static", name: "Static" }), - outputDir: "public", - packageJson, - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ); - - expect(installPackages).not.toHaveBeenCalled(); - }); - - it("does not install Wrangler when cf delegates to Vite", async ({ - expect, - }) => { - const installPackages = vi - .spyOn(cliPackages, "installPackages") - .mockResolvedValue(); - const installWrangler = vi - .spyOn(cliPackages, "installWrangler") - .mockResolvedValue(); - const packageJson = { name: "my-vite-app" }; - await seed({ - "package.json": JSON.stringify(packageJson), - "dist/index.html": "

Hello World

", - "tsconfig.json": "{}", - }); - - await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-vite-app", - framework: new ViteBuildToolFramework({ - id: "static", - name: "Static", - }), - outputDir: "dist", - packageJson, - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ); - - expect(installPackages).toHaveBeenCalledWith("npm", ["cf@latest"], { - dev: true, - isWorkspaceRoot: false, - }); - expect(installWrangler).not.toHaveBeenCalled(); - expect(JSON.parse(readFileSync("package.json", "utf8"))).toMatchObject({ - scripts: { - "cf-typegen": "cf workers types", - }, - }); - }); - - it("keeps the Wrangler typegen command for Wrangler projects", async ({ - expect, - }) => { - const packageJson = { name: "my-vite-app" }; - await seed({ - "package.json": JSON.stringify(packageJson), - "tsconfig.json": "{}", - }); - - await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "my-vite-app", - framework: new ViteBuildToolFramework({ - id: "static", - name: "Static", - }), - outputDir: "dist", - packageJson, - packageManager: NpmPackageManager, - }, - { - target: "wrangler", - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - enableTargetCliInstallation: false, - } - ); - - expect(JSON.parse(readFileSync("package.json", "utf8"))).toMatchObject({ - scripts: { - "cf-typegen": "wrangler types", - }, - }); - }); - - it("writes build configuration when an external tool owns the Worker configuration", async ({ - expect, - }) => { - await runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "external-config-app", - framework: new ExternalWorkerConfigFramework({ - id: "static", - name: "Static", - }), - outputDir: "dist", - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ); - - expect(existsSync("cloudflare.config.ts")).toBe(false); - expect(readFileSync("wrangler.config.ts", "utf8")).toContain( - '"assetsDirectory": "dist"' - ); - }); - - it("fails rather than overwriting existing Wrangler build configuration", async ({ - expect, - }) => { - const existingBuildConfig = "export default { minify: true };\n"; - await seed({ - "wrangler.config.ts": existingBuildConfig, - }); - - await expect( - runAutoConfig( - { - configured: false, - projectPath: process.cwd(), - workerName: "external-config-app", - framework: new ExternalWorkerConfigFramework({ - id: "static", - name: "Static", - }), - outputDir: "dist", - packageManager: NpmPackageManager, - }, - { - context: createMockContext(), - skipConfirmations: true, - runBuild: false, - } - ) - ).rejects.toThrow( - "Cannot generate wrangler.config.ts because the file already exists" - ); - expect(readFileSync("wrangler.config.ts", "utf8")).toBe( - existingBuildConfig - ); - }); -}); diff --git a/packages/autoconfig/tests/save-wrangler-jsonc.test.ts b/packages/autoconfig/tests/save-wrangler-jsonc.test.ts deleted file mode 100644 index 21f91f4c99..0000000000 --- a/packages/autoconfig/tests/save-wrangler-jsonc.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { readFileSync } from "node:fs"; -import { NODEJS_COMPAT_DEFAULT_ON_DATE } from "@cloudflare/workers-utils"; -import { runInTempDir, seed } from "@cloudflare/workers-utils/test-helpers"; -import { describe, test } from "vitest"; -import { saveWranglerJsonc } from "../src/run"; -import type { RawConfig } from "@cloudflare/workers-utils"; - -/** A date before `nodejs_compat` is enabled by the compatibility date alone. */ -const DATE_BEFORE_DEFAULT_ON = "2025-01-01"; - -function readWrittenConfig(): RawConfig { - return JSON.parse( - readFileSync(`${process.cwd()}/wrangler.jsonc`, "utf8") - ) as RawConfig; -} - -describe("autoconfig run - saveWranglerJsonc()", () => { - runInTempDir(); - - test("drops a nodejs_compat left behind by the framework's own scaffolder", async ({ - expect, - }) => { - await seed({ - "wrangler.jsonc": JSON.stringify({ - name: "worker-name", - compatibility_date: DATE_BEFORE_DEFAULT_ON, - compatibility_flags: ["nodejs_compat"], - }), - }); - - await saveWranglerJsonc(process.cwd(), { - name: "worker-name", - compatibility_date: NODEJS_COMPAT_DEFAULT_ON_DATE, - }); - - // The date we write already enables it, so specifying it as well would be - // a workerd validation error. - expect(readWrittenConfig()).toStrictEqual({ - name: "worker-name", - compatibility_date: NODEJS_COMPAT_DEFAULT_ON_DATE, - }); - }); - - test("keeps unrelated flags from the existing config while dropping the redundant one", async ({ - expect, - }) => { - await seed({ - "wrangler.jsonc": JSON.stringify({ - name: "worker-name", - compatibility_date: DATE_BEFORE_DEFAULT_ON, - compatibility_flags: ["nodejs_compat", "no_global_navigator"], - }), - }); - - await saveWranglerJsonc(process.cwd(), { - compatibility_date: NODEJS_COMPAT_DEFAULT_ON_DATE, - }); - - expect(readWrittenConfig().compatibility_flags).toStrictEqual([ - "no_global_navigator", - ]); - }); - - test("still adds nodejs_compat for a date that does not enable it", async ({ - expect, - }) => { - await seed({ - "wrangler.jsonc": JSON.stringify({ - name: "worker-name", - }), - }); - - await saveWranglerJsonc(process.cwd(), { - compatibility_date: DATE_BEFORE_DEFAULT_ON, - }); - - expect(readWrittenConfig().compatibility_flags).toStrictEqual([ - "nodejs_compat", - ]); - }); - - test("writes the config when the project has none yet", async ({ - expect, - }) => { - await saveWranglerJsonc(process.cwd(), { - name: "worker-name", - compatibility_date: NODEJS_COMPAT_DEFAULT_ON_DATE, - }); - - expect(readWrittenConfig()).toStrictEqual({ - name: "worker-name", - compatibility_date: NODEJS_COMPAT_DEFAULT_ON_DATE, - }); - }); -}); diff --git a/packages/autoconfig/tests/tsconfig.json b/packages/autoconfig/tests/tsconfig.json deleted file mode 100644 index ca97bed2d3..0000000000 --- a/packages/autoconfig/tests/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "module": "preserve", - "types": ["node"] - }, - "include": ["../*.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"] -} diff --git a/packages/autoconfig/tests/vite-config.test.ts b/packages/autoconfig/tests/vite-config.test.ts deleted file mode 100644 index 0f0dbb9124..0000000000 --- a/packages/autoconfig/tests/vite-config.test.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { readFileSync } from "node:fs"; -import { writeFile } from "node:fs/promises"; -import { - mockConsoleMethods, - runInTempDir, -} from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { - checkIfViteConfigUsesCloudflarePlugin, - transformViteConfig, -} from "../src/frameworks/utils/vite-config"; -import { createMockContext } from "./helpers/mock-context"; - -describe("vite-config utils", () => { - runInTempDir(); - const std = mockConsoleMethods(); - const context = createMockContext(); - - describe("checkIfViteConfigUsesCloudflarePlugin", () => { - it("should detect cloudflare plugin in function-based defineConfig", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; -import { cloudflare } from '@cloudflare/vite-plugin'; - -export default defineConfig(() => ({ - plugins: [cloudflare()] -})); -` - ); - - const result = checkIfViteConfigUsesCloudflarePlugin(".", context); - expect(result).toBe(true); - }); - - it("should return false for function-based defineConfig without cloudflare plugin", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(() => ({ - plugins: [] -})); -` - ); - - const result = checkIfViteConfigUsesCloudflarePlugin(".", context); - expect(result).toBe(false); - }); - - it("should handle vite config without plugins array", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig({ - server: { port: 3000 } -}); -` - ); - - const result = checkIfViteConfigUsesCloudflarePlugin(".", context); - expect(result).toBe(false); - expect(std.debug).toContain( - "Vite config does not have a valid plugins array" - ); - }); - - it("should detect cloudflare plugin correctly", async ({ expect }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; -import { cloudflare } from '@cloudflare/vite-plugin'; - -export default defineConfig({ - plugins: [cloudflare()] -}); -` - ); - - const result = checkIfViteConfigUsesCloudflarePlugin(".", context); - expect(result).toBe(true); - }); - }); - - describe("transformViteConfig", () => { - it("should successfully transform function-based defineConfig with arrow expression body", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(() => ({ - plugins: [] -})); -` - ); - - expect(() => transformViteConfig(".")).not.toThrow(); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).toContain( - 'import { cloudflare } from "@cloudflare/vite-plugin"' - ); - expect(result).toContain("cloudflare()"); - }); - - it("should successfully transform function-based defineConfig with destructured params", async ({ - expect, - }) => { - // This is the exact pattern from the React Router node-postgres template - await writeFile( - "vite.config.ts", - ` -import { reactRouter } from "@react-router/dev/vite"; -import tailwindcss from "@tailwindcss/vite"; -import { defineConfig } from "vite"; -import tsconfigPaths from "vite-tsconfig-paths"; - -export default defineConfig(({ isSsrBuild }) => ({ - build: { - rollupOptions: isSsrBuild - ? { - input: "./server/app.ts", - } - : undefined, - }, - plugins: [tailwindcss(), reactRouter(), tsconfigPaths()], -})); -` - ); - - expect(() => transformViteConfig(".")).not.toThrow(); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).toContain( - 'import { cloudflare } from "@cloudflare/vite-plugin"' - ); - expect(result).toContain("cloudflare()"); - // The existing plugins should be preserved - expect(result).toContain("tailwindcss()"); - expect(result).toContain("reactRouter()"); - expect(result).toContain("tsconfigPaths()"); - // The function structure should be preserved - expect(result).toContain("isSsrBuild"); - }); - - it("should successfully transform function-based defineConfig with block body", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(() => { - return { - plugins: [] - }; -}); -` - ); - - expect(() => transformViteConfig(".")).not.toThrow(); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).toContain( - 'import { cloudflare } from "@cloudflare/vite-plugin"' - ); - expect(result).toContain("cloudflare()"); - }); - - it("should successfully transform function expression defineConfig", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(function() { - return { - plugins: [] - }; -}); -` - ); - - expect(() => transformViteConfig(".")).not.toThrow(); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).toContain( - 'import { cloudflare } from "@cloudflare/vite-plugin"' - ); - expect(result).toContain("cloudflare()"); - }); - - it("should pass viteEnvironmentName option with function-based config", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(() => ({ - plugins: [] -})); -` - ); - - expect(() => - transformViteConfig(".", { viteEnvironmentName: "ssr" }) - ).not.toThrow(); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).toContain("viteEnvironment"); - expect(result).toContain('"ssr"'); - }); - - it("should remove incompatible plugins from function-based config", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; -import { nitro, keepMe } from 'nitro/vite'; - -export default defineConfig(() => ({ - plugins: [nitro(), keepMe(), someOther()] -})); -` - ); - - transformViteConfig("."); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result).not.toContain("nitro()"); - expect(result).toContain("import { keepMe } from 'nitro/vite'"); - expect(result).toContain("keepMe()"); - expect(result).toContain("someOther()"); - expect(result).toContain("cloudflare()"); - }); - - it("should preserve incompatible plugin imports that are still referenced", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; -import { nitro, nitro as nitroPlugin } from 'nitro/vite'; - -export default defineConfig({ - nitroOptions: nitro, - plugins: [nitro(), enabled ? nitro() : undefined, nitroPlugin()] -}); -` - ); - - transformViteConfig("."); - const result = readFileSync("vite.config.ts", "utf-8"); - expect(result.match(/nitro\(\)/g)).toHaveLength(1); - expect(result).toContain("enabled ? nitro() : undefined"); - expect(result).toContain("nitroPlugin()"); - expect(result).toContain("from 'nitro/vite'"); - expect(result).toContain("nitroOptions: nitro"); - }); - - it("should throw UserError when plugins array is missing", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig({ - server: { port: 3000 } -}); -` - ); - - expect(() => transformViteConfig(".")).toThrow( - /Cannot modify Vite config: could not find a valid plugins array/ - ); - }); - - it("should throw UserError when plugins array is missing in function-based config", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig(() => ({ - server: { port: 3000 } -})); -` - ); - - expect(() => transformViteConfig(".")).toThrow( - /Cannot modify Vite config: could not find a valid plugins array/ - ); - }); - - it("should successfully transform valid vite config", async ({ - expect, - }) => { - await writeFile( - "vite.config.ts", - ` -import { defineConfig } from 'vite'; - -export default defineConfig({ - plugins: [] -}); -` - ); - - expect(() => transformViteConfig(".")).not.toThrow(); - }); - }); -}); diff --git a/packages/autoconfig/tsconfig.json b/packages/autoconfig/tsconfig.json deleted file mode 100644 index 533933f8b7..0000000000 --- a/packages/autoconfig/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/tsconfig.json", - "compilerOptions": { - "module": "esnext", - "types": ["node"], - "tsBuildInfoFile": ".tsbuildinfo" - }, - "include": ["**/*.ts", "**/*.js"], - "exclude": ["dist", "node_modules", "**/__tests__", "**/*.test.ts", "tests"] -} diff --git a/packages/autoconfig/tsup.config.ts b/packages/autoconfig/tsup.config.ts deleted file mode 100644 index 1ad9bdc97b..0000000000 --- a/packages/autoconfig/tsup.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { defineConfig } from "tsup"; -import { EXTERNAL_DEPENDENCIES } from "./scripts/deps"; - -export default defineConfig(() => [ - { - treeshake: true, - keepNames: true, - entry: ["src/index.ts"], - platform: "node", - // Provide require for bundled CommonJS dependencies. The __filename - // fallback keeps the output working when it is rebundled to CommonJS. - banner: { - js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url || (typeof __filename === "string" ? __filename : "/"));', - }, - format: "esm", - dts: true, - outDir: "dist", - tsconfig: "tsconfig.json", - metafile: true, - sourcemap: process.env.SOURCEMAPS !== "false", - define: { - "process.env.NODE_ENV": `'${"production"}'`, - }, - external: EXTERNAL_DEPENDENCIES, - }, -]); diff --git a/packages/autoconfig/turbo.json b/packages/autoconfig/turbo.json deleted file mode 100644 index 691f611507..0000000000 --- a/packages/autoconfig/turbo.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$schema": "http://turbo.build/schema.json", - "extends": ["//"], - "tasks": { - "build": { - "inputs": ["$TURBO_DEFAULT$", "!**/tests/**"], - "outputs": ["dist/**"], - "env": ["SOURCEMAPS"], - "passThroughEnv": ["PWD"] - }, - "test:ci": { - "dependsOn": ["build"], - "env": ["LC_ALL", "TZ"] - } - } -} diff --git a/packages/autoconfig/vitest.config.mts b/packages/autoconfig/vitest.config.mts deleted file mode 100644 index 407d414c58..0000000000 --- a/packages/autoconfig/vitest.config.mts +++ /dev/null @@ -1,12 +0,0 @@ -import { defineConfig } from "vitest/config"; - -export default defineConfig({ - test: { - testTimeout: 15_000, - pool: "forks", - include: ["**/tests/**/*.test.ts"], - reporters: ["default"], - unstubEnvs: true, - mockReset: true, - }, -}); diff --git a/packages/build-output-utils/CHANGELOG.md b/packages/build-output-utils/CHANGELOG.md deleted file mode 100644 index e195ff71d4..0000000000 --- a/packages/build-output-utils/CHANGELOG.md +++ /dev/null @@ -1,235 +0,0 @@ -# @cloudflare/build-output-utils - -## 0.9.2 - -### Patch Changes - -- Updated dependencies [[`f360829`](https://github.com/cloudflare/workers-sdk/commit/f3608290da40c11b248fff40101f30fc295652be)]: - - @cloudflare/config@0.26.0 - -## 0.9.1 - -### Patch Changes - -- Updated dependencies [[`d8b1fca`](https://github.com/cloudflare/workers-sdk/commit/d8b1fca2ba2fec3d3945fa6ec719b8f6766ad610)]: - - @cloudflare/config@0.25.0 - -## 0.9.0 - -### Minor Changes - -- [#15981](https://github.com/cloudflare/workers-sdk/pull/15981) [`0d1bd50`](https://github.com/cloudflare/workers-sdk/commit/0d1bd50d6453e286160e78bee5143c7f7ce221fe) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Reject symlinks when reading experimental Build Output directories - - Build Output directories must be portable and self-contained. The shared reader now rejects symlinks anywhere in the output tree, including links to files within it, and reports the offending path in a Build Output error before reading configs. - -### Patch Changes - -- [#16154](https://github.com/cloudflare/workers-sdk/pull/16154) [`7557322`](https://github.com/cloudflare/workers-sdk/commit/75573221a3e0f2cf0ea8b3d413797a9f1d1a6984) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Keep experimental Build Output portable when source assets are symlinks - - Asset links are now copied as regular files and directories so Wrangler produces portable, self-contained Build Output that can be read successfully. - -- Updated dependencies [[`aaa6a88`](https://github.com/cloudflare/workers-sdk/commit/aaa6a880682fcc33a02366d7b193474f05e36717), [`b606624`](https://github.com/cloudflare/workers-sdk/commit/b6066245aaccb0a6bb718ff063df4fa5a54e4215)]: - - @cloudflare/config@0.24.1 - -## 0.8.6 - -### Patch Changes - -- Updated dependencies [[`f025bbf`](https://github.com/cloudflare/workers-sdk/commit/f025bbfddcdab0193bffffc9fe5a9bf143f2fa65), [`b75421f`](https://github.com/cloudflare/workers-sdk/commit/b75421fcd5b2d8208cefb38882479773a7387df4)]: - - @cloudflare/config@0.24.0 - -## 0.8.5 - -### Patch Changes - -- Updated dependencies [[`7f57b1c`](https://github.com/cloudflare/workers-sdk/commit/7f57b1c60002ae3f077dd9c1e8cc482371065ef4)]: - - @cloudflare/config@0.23.0 - -## 0.8.4 - -### Patch Changes - -- Updated dependencies [[`b9f1cdc`](https://github.com/cloudflare/workers-sdk/commit/b9f1cdc198533687f6b64ce72499a3ca04b2bf85), [`a0712e5`](https://github.com/cloudflare/workers-sdk/commit/a0712e578e45908ed5e46235828a434b49cf8f22), [`27bc20d`](https://github.com/cloudflare/workers-sdk/commit/27bc20d5b22e7156b59940275bd3d809e269d7ce)]: - - @cloudflare/config@0.22.0 - -## 0.8.3 - -### Patch Changes - -- Updated dependencies [[`2a15ae2`](https://github.com/cloudflare/workers-sdk/commit/2a15ae21d210fcd36e485e7492b75198c8d7856c)]: - - @cloudflare/config@0.21.0 - -## 0.8.2 - -### Patch Changes - -- Updated dependencies [[`cde5d99`](https://github.com/cloudflare/workers-sdk/commit/cde5d99651678cde06da6721e194d2e6a21789ff), [`77e79b2`](https://github.com/cloudflare/workers-sdk/commit/77e79b2f5f1fa6a8f8ec2b04f8b288edac64bf9f)]: - - @cloudflare/config@0.20.0 - -## 0.8.1 - -### Patch Changes - -- Updated dependencies [[`a34edd4`](https://github.com/cloudflare/workers-sdk/commit/a34edd4939479a5ae58277803178b87d9bd44b33)]: - - @cloudflare/config@0.19.0 - -## 0.8.0 - -### Minor Changes - -- [#15844](https://github.com/cloudflare/workers-sdk/pull/15844) [`43f7ffb`](https://github.com/cloudflare/workers-sdk/commit/43f7ffbcbe020bc4c30809c6bd408059a6eeac87) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Allow frameworks to remove Worker bundles after prerendering - - Build Output readers now ignore stale manifests when only static assets remain and omit non-default Workers that have neither a bundle nor assets. A default Worker must still contain deployable output. - -### Patch Changes - -- Updated dependencies [[`bdda4c3`](https://github.com/cloudflare/workers-sdk/commit/bdda4c3b3c028d3d4dab5ea4c5af8040ed7ed1d8), [`fc3cbaa`](https://github.com/cloudflare/workers-sdk/commit/fc3cbaa4150a3cf30502286452153806bf8800d2)]: - - @cloudflare/config@0.18.0 - -## 0.7.1 - -### Patch Changes - -- Updated dependencies [[`ec5251a`](https://github.com/cloudflare/workers-sdk/commit/ec5251a92f561dbbba77694ac954d85298f44039)]: - - @cloudflare/config@0.17.0 - -## 0.7.0 - -### Minor Changes - -- [#15713](https://github.com/cloudflare/workers-sdk/pull/15713) [`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Identify experimental Build Output resource configs by filename and location - - The root remains `config.json`, Worker configs are now `worker.config.json`, and Container configs are now `container.config.json`. Resource configs no longer contain top-level `type` discriminators, while settings and build context are stored together in the root config. - -- [#15471](https://github.com/cloudflare/workers-sdk/pull/15471) [`0751490`](https://github.com/cloudflare/workers-sdk/commit/0751490b357fc85022dbc9ff5e6642c0f33a2f0a) Thanks [@edmundhung](https://github.com/edmundhung)! - Fix cf builds for static projects that serve assets from the project root - - The experimental Build Output path now omits the reserved `.cloudflare` directory when the project root is used for static assets. This prevents recursive output copying in Wrangler while preserving the existing behaviour for other asset directories. - -### Patch Changes - -- Updated dependencies [[`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63), [`3c75cad`](https://github.com/cloudflare/workers-sdk/commit/3c75cad95ce8dc80973d4aba33a59a406f791e63)]: - - @cloudflare/config@0.16.0 - -## 0.6.0 - -### Minor Changes - -- [#15701](https://github.com/cloudflare/workers-sdk/pull/15701) [`643e5cc`](https://github.com/cloudflare/workers-sdk/commit/643e5ccb9e2ad7d85966af241e001465c0e1b1c6) Thanks [@WillTaylorDev](https://github.com/WillTaylorDev)! - Pass Preview intent to `defineWorker` and upload its resolved configuration - - Preview builds now evaluate programmatic Worker configuration with `ctx.isPreview` set to `true` and record that intent in Build Output. The shared Preview uploader deploys the resolved bindings and settings while preserving configured Preview base values when it creates a Preview. - -### Patch Changes - -- Updated dependencies [[`1f070c8`](https://github.com/cloudflare/workers-sdk/commit/1f070c8a5a0b12247071551ed58d19444a427036), [`643e5cc`](https://github.com/cloudflare/workers-sdk/commit/643e5ccb9e2ad7d85966af241e001465c0e1b1c6)]: - - @cloudflare/config@0.15.0 - -## 0.5.2 - -### Patch Changes - -- Updated dependencies [[`6874aa9`](https://github.com/cloudflare/workers-sdk/commit/6874aa978144469927831de59834e8cdc47a5114)]: - - @cloudflare/config@0.14.0 - -## 0.5.1 - -### Patch Changes - -- Updated dependencies [[`ca71205`](https://github.com/cloudflare/workers-sdk/commit/ca71205bb45d9182e6c748e7097baed67739a891)]: - - @cloudflare/config@0.13.0 - -## 0.5.0 - -### Minor Changes - -- [#15605](https://github.com/cloudflare/workers-sdk/pull/15605) [`c846bd8`](https://github.com/cloudflare/workers-sdk/commit/c846bd8f0f27da59a77406c516fab0431c38740e) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Add support for reading and writing Container configs in build output - - Container configs can now be written to and read from the Build Output Specification. - -### Patch Changes - -- Updated dependencies [[`3f42b10`](https://github.com/cloudflare/workers-sdk/commit/3f42b10a40d2b3aae1d8d5142ea0bc3ac58fa954)]: - - @cloudflare/config@0.12.0 - -## 0.4.1 - -### Patch Changes - -- Updated dependencies [[`9c60d14`](https://github.com/cloudflare/workers-sdk/commit/9c60d14c0e4cd9306a58c830023f5b43fe6ed054)]: - - @cloudflare/config@0.11.0 - -## 0.4.0 - -### Minor Changes - -- [#15388](https://github.com/cloudflare/workers-sdk/pull/15388) [`10d6bfb`](https://github.com/cloudflare/workers-sdk/commit/10d6bfbaf0ab7466892f4d97af1301494ca71e37) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Support partial manifests in the experimental Build Output Specification - - Build output producers now declare whether their module inventory is complete. `readBuildOutput()` resolves partial manifests by discovering `.js`, `.mjs`, and `.map` files while preserving explicit module type overrides. - -### Patch Changes - -- Updated dependencies [[`ea28cc3`](https://github.com/cloudflare/workers-sdk/commit/ea28cc33e5d39031e9bf512e17f3a57cccbd3f46), [`10d6bfb`](https://github.com/cloudflare/workers-sdk/commit/10d6bfbaf0ab7466892f4d97af1301494ca71e37)]: - - @cloudflare/config@0.10.0 - -## 0.3.1 - -### Patch Changes - -- Updated dependencies [[`3650d29`](https://github.com/cloudflare/workers-sdk/commit/3650d29f1cfcd6db103c25d22819e8fe41d592f3)]: - - @cloudflare/config@0.9.0 - -## 0.3.0 - -### Minor Changes - -- [#15371](https://github.com/cloudflare/workers-sdk/pull/15371) [`e9df120`](https://github.com/cloudflare/workers-sdk/commit/e9df1204238ba26ed0e065b5bf441cfa4b4e683a) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Support multiple named Workers in the experimental Build Output utilities - - Build Output paths and config writing can now target any named Worker directory, and reading Build Output returns every Worker keyed by its directory name. `writeWorkerConfig` now accepts a single options object. - -## 0.2.0 - -### Minor Changes - -- [#15326](https://github.com/cloudflare/workers-sdk/pull/15326) [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Record the selected mode in the Build Output Specification top-level `config.json` - - The mode a build was produced in is now written to `.cloudflare/output/v0/config.json` as a `mode` field, alongside the account and compliance settings. - -- [#15326](https://github.com/cloudflare/workers-sdk/pull/15326) [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Rename the top-level config accessors after the config they operate on - - `getRootConfigPath` and `writeRootConfig` are now `getSettingsConfigPath` and `writeSettingsConfig`, and the corresponding validation error reads `invalid settings config` rather than `invalid root config`. - -### Patch Changes - -- Updated dependencies [[`ead8f69`](https://github.com/cloudflare/workers-sdk/commit/ead8f69e85efa758dd066b4d1cfc2fec406939dd), [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a), [`9fcb1c9`](https://github.com/cloudflare/workers-sdk/commit/9fcb1c9c0a8a0edee04675c4446cd88b34c85b8a), [`82d11fc`](https://github.com/cloudflare/workers-sdk/commit/82d11fca0c826ef54000e5fbe1dc87db73a5ef9c), [`7f66836`](https://github.com/cloudflare/workers-sdk/commit/7f668362bd5675afb95c1cb5128fad6aa092a430), [`acb14d0`](https://github.com/cloudflare/workers-sdk/commit/acb14d01d64f21f0f21c247da7c2fcb0557ebb3d)]: - - @cloudflare/config@0.8.0 - -## 0.1.3 - -### Patch Changes - -- Updated dependencies [[`59872c4`](https://github.com/cloudflare/workers-sdk/commit/59872c41d4417d9b8c2efddb4b35662453efcaae), [`99a1f49`](https://github.com/cloudflare/workers-sdk/commit/99a1f49d7c037a25d4a19a3fe3054337e7201864), [`99a1f49`](https://github.com/cloudflare/workers-sdk/commit/99a1f49d7c037a25d4a19a3fe3054337e7201864), [`99a1f49`](https://github.com/cloudflare/workers-sdk/commit/99a1f49d7c037a25d4a19a3fe3054337e7201864)]: - - @cloudflare/config@0.7.0 - -## 0.1.2 - -### Patch Changes - -- Updated dependencies [[`6529f0c`](https://github.com/cloudflare/workers-sdk/commit/6529f0ca5ecda93f67efbaa72a7f9a9f8fd814bf)]: - - @cloudflare/config@0.6.0 - -## 0.1.1 - -### Patch Changes - -- Updated dependencies [[`2194f88`](https://github.com/cloudflare/workers-sdk/commit/2194f888e53a987ee12c75f1f58f5af287e3c8a3)]: - - @cloudflare/config@0.5.0 - -## 0.1.0 - -### Minor Changes - -- [#14905](https://github.com/cloudflare/workers-sdk/pull/14905) [`b21eac2`](https://github.com/cloudflare/workers-sdk/commit/b21eac24878f060296915f198fae910268c465ef) Thanks [@jamesopstad](https://github.com/jamesopstad)! - Move build output utils to new `@cloudflare/build-output-utils` package - -### Patch Changes - -- Updated dependencies [[`b21eac2`](https://github.com/cloudflare/workers-sdk/commit/b21eac24878f060296915f198fae910268c465ef)]: - - @cloudflare/config@0.4.0 diff --git a/packages/build-output-utils/README.md b/packages/build-output-utils/README.md deleted file mode 100644 index ac44889974..0000000000 --- a/packages/build-output-utils/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `@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 deleted file mode 100644 index 5dc40e21ff..0000000000 --- a/packages/build-output-utils/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "@cloudflare/build-output-utils", - "version": "0.9.2", - "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.", - "homepage": "https://github.com/cloudflare/workers-sdk/tree/main/packages/build-output-utils#readme", - "bugs": { - "url": "https://github.com/cloudflare/workers-sdk/issues" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/cloudflare/workers-sdk.git", - "directory": "packages/build-output-utils" - }, - "files": [ - "dist" - ], - "type": "module", - "sideEffects": false, - "exports": { - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - } - }, - "scripts": { - "build": "tsdown", - "check:type": "tsc", - "dev": "tsdown --watch", - "test:ci": "vitest run", - "test:watch": "vitest" - }, - "dependencies": { - "@cloudflare/config": "workspace:*" - }, - "devDependencies": { - "@cloudflare/workers-tsconfig": "workspace:*", - "@cloudflare/workers-types": "catalog:default", - "@cloudflare/workers-utils": "workspace:*", - "tsdown": "0.16.3", - "typescript": "catalog:default", - "vitest": "catalog:default" - }, - "workers-sdk": { - "prerelease": true - } -} diff --git a/packages/build-output-utils/src/__tests__/paths.test.ts b/packages/build-output-utils/src/__tests__/paths.test.ts deleted file mode 100644 index ff79cce6f1..0000000000 --- a/packages/build-output-utils/src/__tests__/paths.test.ts +++ /dev/null @@ -1,121 +0,0 @@ -import * as path from "node:path"; -import { describe, it } from "vitest"; -import { - BUILD_OUTPUT_ROOT, - BUILD_OUTPUT_VERSION, - CONTAINER_CONFIG_FILENAME, - DEFAULT_WORKER_DIRECTORY_NAME, - getContainerConfigPath, - getContainerDir, - getContainersDir, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerBundleDir, - getWorkerConfigPath, - getWorkersDir, - normalizeDirectoryName, - ROOT_CONFIG_FILENAME, - WORKER_CONFIG_FILENAME, -} from "../paths"; - -describe("path constants", () => { - it("expose the spec's version and root", ({ expect }) => { - expect(BUILD_OUTPUT_VERSION).toBe("v0"); - expect(BUILD_OUTPUT_ROOT).toBe(".cloudflare/output"); - expect(ROOT_CONFIG_FILENAME).toBe("config.json"); - expect(WORKER_CONFIG_FILENAME).toBe("worker.config.json"); - expect(CONTAINER_CONFIG_FILENAME).toBe("container.config.json"); - expect(DEFAULT_WORKER_DIRECTORY_NAME).toBe("default"); - }); -}); - -describe("path resolvers", () => { - const root = path.resolve("/project"); - const outputDir = path.join(root, ".cloudflare", "output", "v0"); - - it("resolves the root config path", ({ expect }) => { - expect(getRootConfigPath(root)).toBe(path.join(outputDir, "config.json")); - }); - - it("resolves the workers directory", ({ expect }) => { - expect(getWorkersDir(root)).toBe(path.join(outputDir, "workers")); - }); - - it("resolves Container paths", ({ expect }) => { - const containersDir = path.join(outputDir, "containers"); - const containerDir = path.join(containersDir, "api-container"); - expect(getContainersDir(root)).toBe(containersDir); - expect(getContainerDir(root, "api-container")).toBe(containerDir); - expect(getContainerConfigPath(root, "api-container")).toBe( - path.join(containerDir, "container.config.json") - ); - }); - - it("resolves the Worker's config, bundle, and assets paths", ({ expect }) => { - const workerDir = path.join(outputDir, "workers", "default"); - expect(getWorkerConfigPath(root)).toBe( - path.join(workerDir, "worker.config.json") - ); - expect(getWorkerBundleDir(root)).toBe(path.join(workerDir, "bundle")); - expect(getWorkerAssetsDir(root)).toBe(path.join(workerDir, "assets")); - }); - - it("rejects invalid Worker directory names", ({ expect }) => { - for (const name of [ - "", - ".", - "..", - "nested/worker", - "nested\\worker", - "worker\0name", - ]) { - expect(() => getWorkerConfigPath(root, name)).toThrow( - `Worker directory names must be non-empty, single path segments. Received ${JSON.stringify(name)}.` - ); - } - }); - - it("rejects invalid Container directory names", ({ expect }) => { - for (const name of [ - "", - ".", - "..", - "nested/container", - "nested\\container", - "container\0name", - ]) { - expect(() => getContainerConfigPath(root, name)).toThrow( - `Container directory names must be non-empty, single path segments. Received ${JSON.stringify(name)}.` - ); - } - }); -}); - -describe("resource directory names", () => { - it("normalizes resource names to portable directory names", ({ expect }) => { - expect(normalizeDirectoryName("My_Container")).toBe("my_container"); - expect(normalizeDirectoryName("my-worker")).toBe("my-worker"); - expect(normalizeDirectoryName("My Container\tName")).toBe( - "my-container-name" - ); - expect(normalizeDirectoryName('API:prod?*<>"|')).toBe("api-prod-"); - expect(normalizeDirectoryName("api/prod\\v1")).toBe("api-prod-v1"); - expect(normalizeDirectoryName("api\u0007prod")).toBe("api-prod"); - expect(normalizeDirectoryName("trailing-dots...")).toBe("trailing-dots-"); - expect(normalizeDirectoryName("CON")).toBe("_con"); - expect(normalizeDirectoryName("CON.json")).toBe("_con.json"); - expect(normalizeDirectoryName("LPT².txt")).toBe("_lpt².txt"); - }); - - it("truncates resource directory names", ({ expect }) => { - expect(normalizeDirectoryName("a".repeat(300))).toBe("a".repeat(254)); - expect(normalizeDirectoryName("界".repeat(300))).toBe("界".repeat(84)); - expect(normalizeDirectoryName("😀".repeat(300))).toBe("😀".repeat(63)); - - const boundaryPrefix = "a".repeat(251); - expect(normalizeDirectoryName(`${boundaryPrefix}😀`)).toBe(boundaryPrefix); - expect(normalizeDirectoryName(`${boundaryPrefix}�`)).toBe( - `${boundaryPrefix}�` - ); - }); -}); diff --git a/packages/build-output-utils/src/__tests__/read.test.ts b/packages/build-output-utils/src/__tests__/read.test.ts deleted file mode 100644 index 0c582a7a47..0000000000 --- a/packages/build-output-utils/src/__tests__/read.test.ts +++ /dev/null @@ -1,635 +0,0 @@ -import * as fsp from "node:fs/promises"; -import * as path from "node:path"; -import { - InputSettingsSchema, - InputWorkerSchema, - OutputContainerSchema, -} from "@cloudflare/config"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { beforeEach, describe, it } from "vitest"; -import { BuildOutputError } from "../errors"; -import { - DEFAULT_WORKER_DIRECTORY_NAME, - getContainerConfigPath, - getContainerDir, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerBundleDir, - getWorkerConfigPath, - getWorkerDir, -} from "../paths"; -import { readBuildOutput } from "../read"; -import { - writeContainerConfig, - writeRootConfig, - writeWorkerConfig, -} from "../write"; -import type { BuildOutputWorker, BuildOutputWorkers } from "../read"; -import type { ParsedOutputWorkerConfig } from "@cloudflare/config"; - -const completeManifest: ParsedOutputWorkerConfig["manifest"] = { - type: "complete", - mainModule: "index.js", - modules: { "index.js": { type: "esm" } }, -}; - -const parsedSettingsConfig = InputSettingsSchema.parse({ - accountId: "1234567890", - complianceRegion: "public", -}); - -const parsedStandardContainerConfig = OutputContainerSchema.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" }, - }, -}); - -function inputWorkerConfig(name: string) { - return InputWorkerSchema.parse({ - name, - compatibilityDate: "2026-06-01", - entrypoint: "index.js", - }); -} - -function getWorker( - workers: BuildOutputWorkers, - directoryName: string -): BuildOutputWorker { - const worker = workers[directoryName]; - if (worker === undefined) { - throw new Error(`Expected Worker ${JSON.stringify(directoryName)}.`); - } - return worker; -} - -async function writeBundleFiles( - root: string, - files: Record -): Promise { - const bundleDir = getWorkerBundleDir(root); - for (const [fileName, contents] of Object.entries(files)) { - const filePath = path.join(bundleDir, fileName); - await fsp.mkdir(path.dirname(filePath), { recursive: true }); - await fsp.writeFile(filePath, contents); - } -} - -/** - * Seed a Worker into the Build Output Specification tree, optionally creating - * the `bundle/` and `assets/` directories on disk. - * - * `hasBundle` controls whether the config is written with a manifest and - * whether the `bundle/` directory is created. `bundleDir` can override just the - * directory creation (defaulting to `hasBundle`), which is useful for - * exercising stale manifests after a framework removes a bundle. - */ -async function seedWorker( - root: string, - { - directoryName = DEFAULT_WORKER_DIRECTORY_NAME, - name = "my-worker", - hasBundle = true, - bundleDir = hasBundle, - assets = false, - }: { - directoryName?: string; - name?: string; - hasBundle?: boolean; - bundleDir?: boolean; - assets?: boolean; - } = {} -) { - await writeWorkerConfig({ - root, - config: inputWorkerConfig(name), - manifest: hasBundle ? completeManifest : undefined, - directoryName, - }); - if (bundleDir) { - await fsp.mkdir(getWorkerBundleDir(root, directoryName), { - recursive: true, - }); - } - if (assets) { - await fsp.mkdir(getWorkerAssetsDir(root, directoryName), { - recursive: true, - }); - } -} - -describe("readBuildOutput", () => { - runInTempDir(); - beforeEach(async () => { - await writeRootConfig(process.cwd(), parsedSettingsConfig, { - 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"], - ] as const)( - "rejects a symlink at %s", - async ([relativePath, type], { expect }) => { - const root = process.cwd(); - await seedWorker(root, { assets: true }); - await writeBundleFiles(root, { - "chunks/module.js": "export default {};", - }); - await fsp.mkdir(path.join(getWorkerAssetsDir(root), "nested")); - - const symlinkPath = path.join(root, relativePath); - const targetPath = path.join(root, "symlink-target"); - await fsp.rename(symlinkPath, targetPath); - await fsp.symlink(targetPath, symlinkPath, type); - - await expect(readBuildOutput(root)).rejects.toThrow( - new BuildOutputError( - `symlink found at ${symlinkPath}. Symlinks are not permitted because the build output must be portable and self-contained.` - ) - ); - } - ); - - it("allows symlinks outside the build output directory", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - const linkedRoot = path.join(root, "linked-project"); - await fsp.symlink(root, linkedRoot, "dir"); - await fsp.symlink( - "does-not-exist", - path.join(root, ".cloudflare/cache"), - "dir" - ); - - const output = await readBuildOutput(linkedRoot); - - expect(output.root).toBe(linkedRoot); - 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", - async (relativePath, { expect }) => { - const root = process.cwd(); - await fsp.rename( - path.join(root, relativePath), - path.join(root, "old-output") - ); - - await expect(readBuildOutput(root)).rejects.toThrow( - /no root config found/ - ); - } - ); - - it.for([".cloudflare", ".cloudflare/output"])( - "reports a missing root config 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/ - ); - } - ); - - it("reads the default Worker, keeping the manifest", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - - const output = await readBuildOutput(root); - const worker = output.workers.default; - - expect(output.version).toBe("v0"); - expect(output.root).toBe(root); - expect(worker.configPath).toBe(getWorkerConfigPath(root)); - expect(worker.bundleDir).toBe(getWorkerBundleDir(root)); - expect(worker.assetsDir).toBeUndefined(); - - expect(worker.config.name).toBe("my-worker"); - expect(worker.config.manifest).toEqual(completeManifest); - expect(worker.config).not.toHaveProperty("entrypoint"); - }); - - it("returns an absolute project root", async ({ expect }) => { - await seedWorker(process.cwd()); - - const output = await readBuildOutput("."); - - expect(output.root).toBe(process.cwd()); - }); - - it("reads additional Workers keyed by directory name", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root, { - directoryName: "additional-worker", - name: "additional-worker", - }); - await seedWorker(root); - - const { workers } = await readBuildOutput(root); - const additionalWorker = getWorker(workers, "additional-worker"); - - expect(Object.keys(workers)).toHaveLength(2); - expect(Object.keys(workers)).toEqual( - expect.arrayContaining(["default", "additional-worker"]) - ); - expect(additionalWorker.config.name).toBe("additional-worker"); - expect(additionalWorker.bundleDir).toBe( - getWorkerBundleDir(root, "additional-worker") - ); - }); - - it("reads Containers", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await writeContainerConfig({ - root, - config: parsedDurableObjectContainerConfig, - directoryName: parsedDurableObjectContainerConfig.name, - }); - await writeContainerConfig({ - root, - config: parsedStandardContainerConfig, - directoryName: parsedStandardContainerConfig.name, - }); - - const { containers } = await readBuildOutput(root); - - expect(containers).toHaveLength(2); - expect(containers).toEqual( - expect.arrayContaining([ - { - configPath: getContainerConfigPath(root, "api-container"), - config: parsedStandardContainerConfig, - }, - { - configPath: getContainerConfigPath(root, "session-container"), - config: parsedDurableObjectContainerConfig, - }, - ]) - ); - }); - - it("returns no Containers when the Containers directory is absent", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - - const { containers } = await readBuildOutput(root); - - expect(containers).toEqual([]); - }); - - it("requires the default Worker when Containers are present", async ({ - expect, - }) => { - const root = process.cwd(); - await writeContainerConfig({ - root, - config: parsedStandardContainerConfig, - directoryName: parsedStandardContainerConfig.name, - }); - - await expect(readBuildOutput(root)).rejects.toThrow( - /no Worker config found/ - ); - }); - - it("throws when a Container config is missing", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.mkdir(getContainerDir(root, "api"), { recursive: true }); - - await expect(readBuildOutput(root)).rejects.toThrow(BuildOutputError); - await expect(readBuildOutput(root)).rejects.toThrow( - /no Container config found/ - ); - }); - - it("throws when a Container config is not valid JSON", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.mkdir(getContainerDir(root, "api"), { recursive: true }); - await fsp.writeFile(getContainerConfigPath(root, "api"), "{ not json"); - - await expect(readBuildOutput(root)).rejects.toThrow(/could not parse JSON/); - }); - - it("throws when a Container config does not match its schema", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.mkdir(getContainerDir(root, "api"), { recursive: true }); - await fsp.writeFile( - getContainerConfigPath(root, "api"), - JSON.stringify({ name: "api" }) - ); - - await expect(readBuildOutput(root)).rejects.toThrow( - /invalid Container config/ - ); - }); - - it("resolves a partial manifest from bundle files and explicit overrides", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeWorkerConfig({ - root, - config: inputWorkerConfig("my-worker"), - manifest: { - type: "partial", - mainModule: "index.js", - modules: { - "chunks/worker.mjs": { type: "cjs" }, - "data.txt": { type: "text" }, - }, - }, - }); - await writeBundleFiles(root, { - "index.js": "module.exports = {};", - "chunks/worker.mjs": "export default {};", - "chunks/worker.mjs.map": "{}", - "data.txt": "data", - "ignored.json": "{}", - }); - - const { workers } = await readBuildOutput(root); - const { manifest: resolvedManifest } = workers.default.config; - - expect(resolvedManifest).toEqual({ - type: "complete", - mainModule: "index.js", - modules: { - "chunks/worker.mjs": { type: "cjs" }, - "chunks/worker.mjs.map": { type: "sourcemap" }, - "data.txt": { type: "text" }, - "index.js": { type: "esm" }, - }, - }); - }); - - it("does not scan bundle files for a complete manifest", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeBundleFiles(root, { - "index.js": "export default {};", - "unlisted.js": "export default {};", - }); - - const { workers } = await readBuildOutput(root); - const { manifest: resolvedManifest } = workers.default.config; - - expect(resolvedManifest).toEqual(completeManifest); - }); - - it("throws when a partial manifest's main module cannot be resolved", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeWorkerConfig({ - root, - config: inputWorkerConfig("my-worker"), - manifest: { - type: "partial", - mainModule: "missing.js", - modules: {}, - }, - }); - - await expect(readBuildOutput(root)).rejects.toThrow( - /partial manifest .* has main module "missing\.js", but it was not found as an ES module/ - ); - }); - - it("throws when a partial manifest's main module is a source map", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeWorkerConfig({ - root, - config: inputWorkerConfig("my-worker"), - manifest: { - type: "partial", - mainModule: "index.js.map", - modules: {}, - }, - }); - await writeBundleFiles(root, { "index.js.map": "{}" }); - - await expect(readBuildOutput(root)).rejects.toThrow( - /partial manifest .* has main module "index\.js\.map", but it was not found as an ES module/ - ); - }); - - it("resolves the assets directory when present and leaves bundle undefined for assets-only Workers", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root, { hasBundle: false, assets: true }); - - const { workers } = await readBuildOutput(root); - const worker = workers.default; - - expect(worker.bundleDir).toBeUndefined(); - expect(worker.assetsDir).toBe(getWorkerAssetsDir(root)); - }); - - it("ignores a stale manifest for an assets-only Worker", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root, { - hasBundle: true, - bundleDir: false, - assets: true, - }); - - const { workers } = await readBuildOutput(root); - const worker = workers.default; - - expect(worker.config.manifest).toBeUndefined(); - expect(worker.bundleDir).toBeUndefined(); - expect(worker.assetsDir).toBe(getWorkerAssetsDir(root)); - }); - - it("omits an additional Worker with no deployable output", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await seedWorker(root, { - directoryName: "prerender", - name: "prerender-worker", - hasBundle: true, - bundleDir: false, - }); - - const { workers } = await readBuildOutput(root); - - expect(workers).not.toHaveProperty("prerender"); - }); - - it("throws when the default Worker has no deployable output", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root, { - hasBundle: true, - bundleDir: false, - assets: false, - }); - - await expect(readBuildOutput(root)).rejects.toThrow(BuildOutputError); - await expect(readBuildOutput(root)).rejects.toThrow( - `Default Worker at ${getWorkerDir(root)} has neither a bundle directory (${getWorkerBundleDir(root)}) nor an assets directory (${getWorkerAssetsDir(root)}).` - ); - }); - - it("throws when the Worker config is missing", async ({ expect }) => { - const root = process.cwd(); - await fsp.mkdir(getWorkerDir(root), { recursive: true }); - - await expect(readBuildOutput(root)).rejects.toThrow(BuildOutputError); - await expect(readBuildOutput(root)).rejects.toThrow( - /no Worker config found/ - ); - }); - - it("throws when the config is not valid JSON", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.writeFile(getWorkerConfigPath(root), "{ not json"); - - await expect(readBuildOutput(root)).rejects.toThrow(/could not parse JSON/); - }); - - it("throws when the Worker config does not match its schema", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.writeFile(getWorkerConfigPath(root), JSON.stringify({})); - - await expect(readBuildOutput(root)).rejects.toThrow( - /invalid Worker config/ - ); - }); - - it("returns the root config", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, - }); - - const { rootConfig } = await readBuildOutput(root); - - expect(rootConfig).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: false }, - }); - }); - - it("throws when the root config is absent", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - await fsp.rm(getRootConfigPath(root)); - - await expect(readBuildOutput(root)).rejects.toThrow(/no root config found/); - }); - - it("returns the build context recorded in the root config", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: true, - mode: "staging", - }); - - const { rootConfig } = await readBuildOutput(root); - - expect(rootConfig).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: true, mode: "staging" }, - }); - }); - - it("returns the build context when no mode was selected", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, - }); - - const { rootConfig } = await readBuildOutput(root); - - expect(rootConfig.buildContext).toEqual({ isPreview: false }); - }); - - it("throws when the recorded mode is not a string", async ({ expect }) => { - const root = process.cwd(); - await seedWorker(root); - const configPath = getRootConfigPath(root); - await fsp.mkdir(path.dirname(configPath), { recursive: true }); - await fsp.writeFile( - configPath, - JSON.stringify({ buildContext: { isPreview: false, mode: 123 } }) - ); - - await expect(readBuildOutput(root)).rejects.toThrow(/invalid root config/); - }); - - it("throws when the root config does not match its schema", async ({ - expect, - }) => { - const root = process.cwd(); - await seedWorker(root); - const configPath = getRootConfigPath(root); - await fsp.mkdir(path.dirname(configPath), { recursive: true }); - await fsp.writeFile(configPath, JSON.stringify({ nope: 1 })); - - await expect(readBuildOutput(root)).rejects.toThrow(/invalid root config/); - }); - - it("reads the root config before Worker configs", async ({ expect }) => { - const root = process.cwd(); - await fsp.mkdir(getWorkerDir(root), { recursive: true }); - await fsp.writeFile(getWorkerConfigPath(root), "{ not json"); - const configPath = getRootConfigPath(root); - await fsp.writeFile(configPath, JSON.stringify({ nope: 1 })); - - await expect(readBuildOutput(root)).rejects.toThrow(/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 deleted file mode 100644 index b0fbcf91f9..0000000000 --- a/packages/build-output-utils/src/__tests__/write.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import * as fs from "node:fs"; -import * as path from "node:path"; -import { - InputSettingsSchema, - InputWorkerSchema, - OutputContainerSchema, - OutputWorkerSchema, -} from "@cloudflare/config"; -import { runInTempDir } from "@cloudflare/workers-utils/test-helpers"; -import { describe, it } from "vitest"; -import { - BUILD_OUTPUT_ROOT, - getContainerConfigPath, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerConfigPath, -} from "../paths"; -import { readBuildOutput } from "../read"; -import { - cleanBuildOutputDir, - writeContainerConfig, - writeAssets, - writeRootConfig, - writeWorkerConfig, -} from "../write"; - -const parsedWorkerConfig = InputWorkerSchema.parse({ - name: "my-worker", - compatibilityDate: "2026-06-01", - entrypoint: "index.js", -}); - -const parsedSettingsConfig = InputSettingsSchema.parse({ - accountId: "1234567890", - complianceRegion: "public", -}); - -const parsedStandardContainerConfig = OutputContainerSchema.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" }, - }, -}); - -describe("writeRootConfig", () => { - runInTempDir(); - - it("writes the root config.json with the shared settings", async ({ - expect, - }) => { - const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, - }); - - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: false }, - }); - }); - - it("records build context alongside the shared settings", async ({ - expect, - }) => { - const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: "staging", - }); - - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ - ...parsedSettingsConfig, - buildContext: { isPreview: false, mode: "staging" }, - }); - }); - - it("writes only build context when there are no settings or mode", async ({ - expect, - }) => { - const root = process.cwd(); - await writeRootConfig(root, undefined, { - isPreview: false, - mode: undefined, - }); - - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ buildContext: { isPreview: false } }); - }); - - it("writes build context when there are no settings", async ({ expect }) => { - const root = process.cwd(); - await writeRootConfig(root, undefined, { - isPreview: true, - mode: "production", - }); - - const contents = JSON.parse( - fs.readFileSync(getRootConfigPath(root), "utf-8") - ); - expect(contents).toEqual({ - buildContext: { isPreview: true, mode: "production" }, - }); - }); -}); - -describe("writeWorkerConfig", () => { - runInTempDir(); - - it("writes worker.config.json under default, stripping entrypoint and keeping the manifest", async ({ - expect, - }) => { - const root = process.cwd(); - const manifest = { - type: "complete", - mainModule: "index.js", - modules: { "index.js": { type: "esm" } }, - } as const; - - await writeWorkerConfig({ root, config: parsedWorkerConfig, manifest }); - - const contents = JSON.parse( - fs.readFileSync(getWorkerConfigPath(root), "utf-8") - ); - 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); - }); - - it("omits the manifest field when no manifest is provided", async ({ - expect, - }) => { - const root = process.cwd(); - await writeWorkerConfig({ root, config: parsedWorkerConfig }); - - const contents = JSON.parse( - fs.readFileSync(getWorkerConfigPath(root), "utf-8") - ); - expect(contents).not.toHaveProperty("manifest"); - }); - - it("writes worker.config.json for a named Worker directory", async ({ - expect, - }) => { - const root = process.cwd(); - await writeWorkerConfig({ - root, - config: parsedWorkerConfig, - directoryName: "additional", - }); - - const contents = JSON.parse( - fs.readFileSync(getWorkerConfigPath(root, "additional"), "utf-8") - ); - expect(contents.name).toBe("my-worker"); - }); -}); - -describe("writeContainerConfig", () => { - runInTempDir(); - - it("writes a standard Container config with a remote image reference", async ({ - expect, - }) => { - const root = process.cwd(); - await writeContainerConfig({ - root, - config: parsedStandardContainerConfig, - directoryName: parsedStandardContainerConfig.name, - }); - - const contents = JSON.parse( - fs.readFileSync(getContainerConfigPath(root, "api-container"), "utf-8") - ); - expect(contents).toEqual(parsedStandardContainerConfig); - expect(OutputContainerSchema.parse(contents)).toEqual(contents); - }); - - it("writes a Durable Object Container config with a local image reference", async ({ - expect, - }) => { - const root = process.cwd(); - await writeContainerConfig({ - root, - config: parsedDurableObjectContainerConfig, - directoryName: parsedDurableObjectContainerConfig.name, - }); - - const contents = JSON.parse( - fs.readFileSync( - getContainerConfigPath(root, "session-container"), - "utf-8" - ) - ); - expect(contents).toEqual(parsedDurableObjectContainerConfig); - expect(OutputContainerSchema.parse(contents)).toEqual(contents); - }); -}); - -describe("cleanBuildOutputDir", () => { - runInTempDir(); - - it("removes the build output directory", async ({ expect }) => { - const root = process.cwd(); - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, - }); - const outputDir = path.join(root, BUILD_OUTPUT_ROOT); - expect(fs.existsSync(outputDir)).toBe(true); - - await cleanBuildOutputDir(root); - expect(fs.existsSync(outputDir)).toBe(false); - }); -}); - -describe("writeAssets", () => { - runInTempDir(); - - it("copies an asset directory into the build output", async ({ expect }) => { - const root = process.cwd(); - const sourceDirectory = path.join(root, "public"); - fs.mkdirSync(sourceDirectory); - fs.writeFileSync(path.join(sourceDirectory, "index.html"), "hello"); - - await writeAssets({ root, sourceDirectory }); - - expect( - fs.readFileSync(path.join(getWorkerAssetsDir(root), "index.html"), "utf8") - ).toBe("hello"); - }); - - it("dereferences symlinked files and directories", async ({ expect }) => { - const root = process.cwd(); - const sourceDirectory = path.join(root, "public"); - const sourceNestedDirectory = path.join(sourceDirectory, "nested"); - fs.mkdirSync(sourceNestedDirectory, { recursive: true }); - fs.writeFileSync(path.join(sourceNestedDirectory, "index.html"), "hello"); - fs.symlinkSync( - "nested/index.html", - path.join(sourceDirectory, "index.html") - ); - fs.symlinkSync("nested", path.join(sourceDirectory, "linked"), "dir"); - - await writeRootConfig(root, parsedSettingsConfig, { - isPreview: false, - mode: undefined, - }); - await writeWorkerConfig({ root, config: parsedWorkerConfig }); - await writeAssets({ root, sourceDirectory }); - - const output = await readBuildOutput(root); - const assetsDir = getWorkerAssetsDir(root); - expect(output.workers.default.assetsDir).toBe(assetsDir); - expect(fs.lstatSync(path.join(assetsDir, "index.html")).isFile()).toBe( - true - ); - expect(fs.lstatSync(path.join(assetsDir, "linked")).isDirectory()).toBe( - true - ); - expect( - fs.readFileSync(path.join(assetsDir, "linked/index.html"), "utf8") - ).toBe("hello"); - }); - - it("omits .cloudflare when the project root contains the assets", async ({ - expect, - }) => { - const root = process.cwd(); - fs.writeFileSync(path.join(root, "index.html"), "hello"); - 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 writeAssets({ root, sourceDirectory: root }); - - const assetsDir = getWorkerAssetsDir(root); - expect(fs.readFileSync(path.join(assetsDir, "index.html"), "utf8")).toBe( - "hello" - ); - expect(fs.lstatSync(path.join(assetsDir, "linked")).isDirectory()).toBe( - true - ); - expect( - fs.readFileSync(path.join(assetsDir, "linked/linked.html"), "utf8") - ).toBe("linked"); - expect(fs.existsSync(path.join(assetsDir, ".cloudflare"))).toBe(false); - }); - - it("preserves files already generated in the build output", async ({ - expect, - }) => { - const root = process.cwd(); - fs.writeFileSync(path.join(root, "index.html"), "source"); - const assetsDir = getWorkerAssetsDir(root); - fs.mkdirSync(assetsDir, { recursive: true }); - fs.writeFileSync(path.join(assetsDir, "index.html"), "generated"); - - await writeAssets({ root, sourceDirectory: root }); - - expect(fs.readFileSync(path.join(assetsDir, "index.html"), "utf8")).toBe( - "generated" - ); - }); -}); diff --git a/packages/build-output-utils/src/errors.ts b/packages/build-output-utils/src/errors.ts deleted file mode 100644 index 590d397435..0000000000 --- a/packages/build-output-utils/src/errors.ts +++ /dev/null @@ -1,12 +0,0 @@ -const BUILD_OUTPUT_ERROR_PREFIX = "Build Output Specification: "; - -/** - * Thrown when the Build Output Specification tree is missing, malformed, or - * internally inconsistent. - */ -export class BuildOutputError extends Error { - constructor(message: string) { - super(`${BUILD_OUTPUT_ERROR_PREFIX}${message}`); - this.name = "BuildOutputError"; - } -} diff --git a/packages/build-output-utils/src/index.ts b/packages/build-output-utils/src/index.ts deleted file mode 100644 index 53b048ed4d..0000000000 --- a/packages/build-output-utils/src/index.ts +++ /dev/null @@ -1,40 +0,0 @@ -export { - BUILD_OUTPUT_ROOT, - BUILD_OUTPUT_VERSION, - CONTAINER_CONFIG_FILENAME, - DEFAULT_WORKER_DIRECTORY_NAME, - getContainerConfigPath, - getContainerDir, - getContainersDir, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerBundleDir, - getWorkerConfigPath, - getWorkerDir, - getWorkersDir, - normalizeDirectoryName, - ROOT_CONFIG_FILENAME, - WORKER_CONFIG_FILENAME, -} from "./paths"; -export { - cleanBuildOutputDir, - writeContainerConfig, - writeAssets, - writeRootConfig, - writeWorkerConfig, -} from "./write"; -export type { - WriteAssetsOptions, - WriteContainerConfigOptions, - WriteWorkerConfigOptions, -} from "./write"; -export { BuildOutputError } from "./errors"; -export { readBuildOutput } from "./read"; -export type { - BuildOutput, - BuildOutputContainer, - BuildOutputContainers, - BuildOutputWorker, - BuildOutputWorkers, - ResolvedOutputWorkerConfig, -} from "./read"; diff --git a/packages/build-output-utils/src/paths.ts b/packages/build-output-utils/src/paths.ts deleted file mode 100644 index 872392c621..0000000000 --- a/packages/build-output-utils/src/paths.ts +++ /dev/null @@ -1,175 +0,0 @@ -import * as path from "node:path"; - -/** - * Initial draft version of the Build Output Specification. - * - * Will move to `v1` when the spec stabilises. - */ -export const BUILD_OUTPUT_VERSION = "v0"; - -/** Build output directory relative to the project root. */ -export const BUILD_OUTPUT_ROOT = ".cloudflare/output"; - -/** Filename of the root config in the Build Output Specification. */ -export const ROOT_CONFIG_FILENAME = "config.json"; - -/** Filename of each Worker config in the Build Output Specification. */ -export const WORKER_CONFIG_FILENAME = "worker.config.json"; - -/** Filename of each Container config in the Build Output Specification. */ -export const CONTAINER_CONFIG_FILENAME = "container.config.json"; - -/** Name of the directory containing the default Worker. */ -export const DEFAULT_WORKER_DIRECTORY_NAME = "default"; - -// oxlint-disable-next-line no-control-regex -- Windows forbids control characters in file names. -const INVALID_DIRECTORY_NAME_CHARACTERS = /[\s<>:"/\\|?*\u0000-\u001f]+|\.+$/g; -const WINDOWS_RESERVED_NAME = - /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/; -// Leave room for the prefix added to Windows reserved names. -const MAX_DIRECTORY_NAME_BYTES = 254; - -/** Absolute path to the Build Output Specification directory. */ -export function getBuildOutputDir(root: string): string { - return path.resolve(root, BUILD_OUTPUT_ROOT); -} - -/** - * Absolute path to the root `config.json`. - * - * Holds the settings declared at the top level of `cloudflare.config.ts` and - * build context. - */ -export function getRootConfigPath(root: string): string { - return path.join( - getBuildOutputDir(root), - BUILD_OUTPUT_VERSION, - ROOT_CONFIG_FILENAME - ); -} - -/** - * Absolute path to the Workers output directory. - */ -export function getWorkersDir(root: string): string { - return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, "workers"); -} - -/** - * Absolute path to the Containers output directory. - */ -export function getContainersDir(root: string): string { - return path.join(getBuildOutputDir(root), BUILD_OUTPUT_VERSION, "containers"); -} - -/** - * Convert a Cloudflare resource name into a portable, case-insensitive - * directory name. - * - * The original resource name remains in its config file. Callers must reject - * collisions when multiple resource names normalise to the same directory. - */ -export function normalizeDirectoryName(name: string): string { - const directoryName = truncateUtf8( - name.toLowerCase(), - MAX_DIRECTORY_NAME_BYTES - ).replace(INVALID_DIRECTORY_NAME_CHARACTERS, "-"); - - return WINDOWS_RESERVED_NAME.test(directoryName) - ? `_${directoryName}` - : directoryName; -} - -function truncateUtf8(value: string, maxBytes: number): string { - let result = ""; - let byteLength = 0; - for (const character of value) { - const characterByteLength = Buffer.byteLength(character); - if (byteLength + characterByteLength > maxBytes) { - break; - } - - result += character; - byteLength += characterByteLength; - } - return result; -} - -function validateDirectoryName(name: string, resourceType: string): void { - if ( - name.length === 0 || - name === "." || - name === ".." || - name.includes("/") || - name.includes("\\") || - name.includes("\0") - ) { - throw new Error( - `${resourceType} directory names must be non-empty, single path segments. Received ${JSON.stringify(name)}.` - ); - } -} - -/** - * Absolute path to a Worker's directory (`workers/`). - */ -export function getWorkerDir( - root: string, - directoryName = DEFAULT_WORKER_DIRECTORY_NAME -): string { - validateDirectoryName(directoryName, "Worker"); - - return path.join(getWorkersDir(root), directoryName); -} - -/** - * Absolute path to a Container's directory (`containers/`). - */ -export function getContainerDir(root: string, directoryName: string): string { - validateDirectoryName(directoryName, "Container"); - - return path.join(getContainersDir(root), directoryName); -} - -/** - * Absolute path to the Container's config file. - */ -export function getContainerConfigPath( - root: string, - directoryName: string -): string { - return path.join( - getContainerDir(root, directoryName), - CONTAINER_CONFIG_FILENAME - ); -} - -/** - * Absolute path to the Worker's config file. - */ -export function getWorkerConfigPath( - root: string, - directoryName = DEFAULT_WORKER_DIRECTORY_NAME -): string { - return path.join(getWorkerDir(root, directoryName), WORKER_CONFIG_FILENAME); -} - -/** - * Absolute path to the Worker's bundle directory. - */ -export function getWorkerBundleDir( - root: string, - directoryName = DEFAULT_WORKER_DIRECTORY_NAME -): string { - return path.join(getWorkerDir(root, directoryName), "bundle"); -} - -/** - * Absolute path to the Worker's assets directory. - */ -export function getWorkerAssetsDir( - root: string, - directoryName = DEFAULT_WORKER_DIRECTORY_NAME -): string { - return path.join(getWorkerDir(root, directoryName), "assets"); -} diff --git a/packages/build-output-utils/src/read.ts b/packages/build-output-utils/src/read.ts deleted file mode 100644 index efce044d4c..0000000000 --- a/packages/build-output-utils/src/read.ts +++ /dev/null @@ -1,434 +0,0 @@ -import * as fs from "node:fs"; -import * as fsp from "node:fs/promises"; -import * as path from "node:path"; -import { - OutputContainerSchema, - OutputRootConfigSchema, - OutputWorkerSchema, -} from "@cloudflare/config"; -import { BuildOutputError } from "./errors"; -import { - BUILD_OUTPUT_VERSION, - DEFAULT_WORKER_DIRECTORY_NAME, - getBuildOutputDir, - getContainerConfigPath, - getContainersDir, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerBundleDir, - getWorkerConfigPath, - getWorkerDir, - getWorkersDir, -} from "./paths"; -import type { - ModuleType, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, -} from "@cloudflare/config"; - -type ManifestModules = NonNullable< - ParsedOutputWorkerConfig["manifest"] ->["modules"]; - -type CompleteManifest = Omit< - NonNullable, - "type" -> & { type: "complete" }; - -/** A parsed Worker config whose manifest has been fully resolved. */ -export type ResolvedOutputWorkerConfig = Omit< - ParsedOutputWorkerConfig, - "manifest" -> & { - manifest?: CompleteManifest; -}; - -interface BuildOutputWorkerBase { - /** Absolute path to the Worker's `worker.config.json`. */ - configPath: string; - /** The parsed Worker config, including its fully resolved `manifest`. */ - config: ResolvedOutputWorkerConfig; -} - -/** - * The Worker found in the Build Output Specification tree. - * - * `bundleDir` / `assetsDir` are resolved to `undefined` when the corresponding - * directory is absent on disk, so consumers don't need their own existence - * checks. A Worker always has at least one of them: the type is a union so - * that a Worker with neither a `bundle/` nor an `assets/` directory is - * unrepresentable. - */ -export type BuildOutputWorker = BuildOutputWorkerBase & - ( - | { - /** Absolute path to the Worker's `bundle/` directory. */ - bundleDir: string; - /** Absolute path to the Worker's `assets/` directory, if present. */ - assetsDir: string | undefined; - } - | { - /** Absolute path to the Worker's `bundle/` directory, if present. */ - bundleDir: string | undefined; - /** Absolute path to the Worker's `assets/` directory. */ - assetsDir: string; - } - ); - -export type BuildOutputWorkers = Record & { - /** The default Worker. */ - default: BuildOutputWorker; -}; - -/** A Container found in the Build Output Specification tree. */ -export interface BuildOutputContainer { - /** Absolute path to the Container's `container.config.json`. */ - configPath: string; - /** The parsed Container config. */ - config: ParsedOutputContainerConfig; -} - -/** Containers found in the Build Output Specification tree. */ -export type BuildOutputContainers = BuildOutputContainer[]; - -/** - * The result of reading a Build Output Specification tree. - */ -export interface BuildOutput { - /** Absolute project root from which the output was read. */ - root: string; - /** Version of the spec the tree conforms to. */ - version: string; - /** - * The parsed root `config.json`. - */ - rootConfig: ParsedOutputRootConfig; - /** - * The deployable Workers found under - * `/.cloudflare/output/v0/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 - * meaning. - */ - containers: BuildOutputContainers; -} - -/** - * Read and parse the Build Output Specification tree at - * `/.cloudflare/output/v0/`. - * - * 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/`. - * - * @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. - */ -export async function readBuildOutput(root: string): Promise { - const absoluteRoot = path.resolve(root); - await validateBuildOutputDirectory(absoluteRoot); - const rootConfig = await readRootConfig(absoluteRoot); - const [workers, containers] = await Promise.all([ - readWorkers(absoluteRoot), - readContainers(absoluteRoot), - ]); - - return { - root: absoluteRoot, - version: BUILD_OUTPUT_VERSION, - rootConfig, - workers, - containers, - }; -} - -/** Reject symlinks so build output remains portable and self-contained. */ -async function validateBuildOutputDirectory(root: string): Promise { - const buildOutputDir = getBuildOutputDir(root); - - // Check the output path itself before scanning to avoid following a linked - // `.cloudflare` or `output` directory. - for (const directory of [path.dirname(buildOutputDir), buildOutputDir]) { - const entry = fs.lstatSync(directory, { throwIfNoEntry: false }); - if (entry === undefined) { - return; - } - assertNotSymlink(directory, entry); - if (!entry.isDirectory()) { - return; - } - } - - const entries = await fsp.readdir(buildOutputDir, { - recursive: true, - withFileTypes: true, - }); - for (const entry of entries) { - assertNotSymlink(path.join(entry.parentPath, entry.name), entry); - } -} - -function assertNotSymlink(filePath: string, entry: fs.Stats | fs.Dirent): void { - if (entry.isSymbolicLink()) { - throw new BuildOutputError( - `symlink found at ${filePath}. Symlinks are not permitted because the build output must be portable and self-contained.` - ); - } -} - -/** Read and parse the default Worker and any additional Worker configs. */ -async function readWorkers(root: string): Promise { - const workersDir = getWorkersDir(root); - const defaultWorker = await readWorker(root, DEFAULT_WORKER_DIRECTORY_NAME); - 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}).` - ); - } - const additionalWorkerDirectoryNames = ( - await fsp.readdir(workersDir, { withFileTypes: true }) - ) - .filter( - (entry) => - entry.isDirectory() && entry.name !== DEFAULT_WORKER_DIRECTORY_NAME - ) - .map((entry) => entry.name); - const additionalWorkers = await Promise.all( - additionalWorkerDirectoryNames.map(async (workerDirectoryName) => { - const worker = await readWorker(root, workerDirectoryName); - return worker === undefined - ? undefined - : ([workerDirectoryName, worker] as const); - }) - ); - - return { - default: defaultWorker, - ...Object.fromEntries( - additionalWorkers.filter( - (entry): entry is readonly [string, BuildOutputWorker] => - entry !== undefined - ) - ), - }; -} - -/** Read and parse all Container configs, if any. */ -async function readContainers(root: string): Promise { - const containersDir = getContainersDir(root); - if (!fs.existsSync(containersDir)) { - return []; - } - - const containerDirectoryNames = ( - await fsp.readdir(containersDir, { withFileTypes: true }) - ) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name); - - return Promise.all( - containerDirectoryNames.map((containerDirectoryName) => - readContainer(root, containerDirectoryName) - ) - ); -} - -/** Read and parse one Container config. */ -async function readContainer( - root: string, - containerDirectoryName: string -): Promise { - const configPath = getContainerConfigPath(root, containerDirectoryName); - - if (!fs.existsSync(configPath)) { - throw new BuildOutputError(`no Container config found at ${configPath}.`); - } - - const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputContainerSchema.safeParse( - parseJson(contents, configPath) - ); - if (!result.success) { - throw new BuildOutputError( - `invalid Container config at ${configPath}.\n${result.error.message}` - ); - } - - return { configPath, config: result.data }; -} - -/** - * Read and parse the Worker's `worker.config.json` and resolve its - * `bundle/` / `assets/` directories. - * - * @returns the Worker, with whichever of its directories exist resolved, or - * `undefined` when it has no deployable output. - * @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); - - if (!fs.existsSync(configPath)) { - throw new BuildOutputError(`no Worker config found at ${configPath}.`); - } - - const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputWorkerSchema.safeParse(parseJson(contents, configPath)); - if (!result.success) { - throw new BuildOutputError( - `invalid Worker config at ${configPath}.\n${result.error.message}` - ); - } - - const bundleDir = getWorkerBundleDir(root, workerDirectoryName); - const assetsDir = getWorkerAssetsDir(root, workerDirectoryName); - const hasBundleDir = fs.existsSync(bundleDir); - const hasAssetsDir = fs.existsSync(assetsDir); - - if (hasBundleDir) { - const config = await resolveManifest(result.data, configPath, bundleDir); - return { - configPath, - config, - bundleDir, - assetsDir: hasAssetsDir ? assetsDir : undefined, - }; - } - - if (hasAssetsDir) { - const { manifest: _manifest, ...config } = result.data; - return { - configPath, - config, - bundleDir: undefined, - assetsDir, - }; - } - - return undefined; -} - -/** Resolve the manifest against the bundle contents. */ -async function resolveManifest( - config: ParsedOutputWorkerConfig, - configPath: string, - bundleDir: string -): Promise { - const { manifest, ...workerConfig } = config; - if (manifest === undefined) { - return workerConfig; - } - if (manifest.type === "complete") { - return { - ...workerConfig, - manifest: { ...manifest, type: "complete" }, - }; - } - - 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.` - ); - } - - const modules = { - ...inferredModules, - ...manifest.modules, - }; - - return { - ...workerConfig, - manifest: { - type: "complete", - mainModule: manifest.mainModule, - modules, - }, - }; -} - -/** Infer JavaScript modules and source maps from a bundle directory. */ -async function scanModules(bundleDir: string): Promise { - const modules: ManifestModules = {}; - const entries = await fsp.readdir(bundleDir, { - recursive: true, - withFileTypes: true, - }); - - for (const entry of entries) { - const type = entry.isFile() ? inferModuleType(entry.name) : undefined; - if (type !== undefined) { - const modulePath = path - .relative(bundleDir, path.join(entry.parentPath, entry.name)) - .split(path.sep) - .join("/"); - modules[modulePath] = { type }; - } - } - - return modules; -} - -/** Infer the module type for extensions supported by partial manifests. */ -function inferModuleType(modulePath: string): ModuleType | undefined { - switch (path.extname(modulePath)) { - case ".js": - case ".mjs": - return "esm"; - case ".map": - return "sourcemap"; - } -} - -/** - * Read and parse the root `config.json`. - * - * @returns the parsed root config. - * @throws {BuildOutputError} if the file is missing, is not valid JSON, or - * does not match its schema. - */ -async function readRootConfig(root: string): Promise { - const configPath = getRootConfigPath(root); - - if (!fs.existsSync(configPath)) { - throw new BuildOutputError(`no root config found at ${configPath}.`); - } - - const contents = await fsp.readFile(configPath, "utf-8"); - const result = OutputRootConfigSchema.safeParse( - parseJson(contents, configPath) - ); - if (!result.success) { - throw new BuildOutputError( - `invalid root config at ${configPath}.\n${result.error.message}` - ); - } - - return result.data; -} - -function parseJson(contents: string, configPath: string): 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}` - ); - } -} diff --git a/packages/build-output-utils/src/write.ts b/packages/build-output-utils/src/write.ts deleted file mode 100644 index 1346127947..0000000000 --- a/packages/build-output-utils/src/write.ts +++ /dev/null @@ -1,149 +0,0 @@ -import * as fsp from "node:fs/promises"; -import * as path from "node:path"; -import { removeDir } from "@cloudflare/workers-utils"; -import { - BUILD_OUTPUT_ROOT, - DEFAULT_WORKER_DIRECTORY_NAME, - getBuildOutputDir, - getContainerConfigPath, - getContainerDir, - getRootConfigPath, - getWorkerAssetsDir, - getWorkerConfigPath, - getWorkerDir, -} from "./paths"; -import type { - ParsedInputSettingsConfig, - ParsedInputWorkerConfig, - ParsedOutputContainerConfig, - ParsedOutputRootConfig, - ParsedOutputWorkerConfig, - ConfigContext, -} from "@cloudflare/config"; - -/** - * Clean the build output directory. - */ -export async function cleanBuildOutputDir(root: string): Promise { - await removeDir(getBuildOutputDir(root)); -} - -export interface WriteAssetsOptions { - root: string; - sourceDirectory: string; -} - -/** - * Copy static assets into the Build Output Specification tree. - * - * Symlinks are dereferenced so the output remains portable and self-contained. - * - * When the project root is itself the asset source, the reserved - * `.cloudflare` directory is omitted so the nested output is not copied into - * itself. - */ -export async function writeAssets({ - root, - sourceDirectory, -}: WriteAssetsOptions): Promise { - const assetsDir = getWorkerAssetsDir(root); - await fsp.mkdir(assetsDir, { recursive: true }); - - if (path.resolve(sourceDirectory) !== path.resolve(root)) { - await fsp.cp(sourceDirectory, assetsDir, { - recursive: true, - force: false, - dereference: true, - }); - return; - } - - const entries = await fsp.readdir(sourceDirectory); - await Promise.all( - entries - .filter((entry) => entry !== path.dirname(BUILD_OUTPUT_ROOT)) - .map((entry) => - fsp.cp(path.join(sourceDirectory, entry), path.join(assetsDir, entry), { - recursive: true, - force: false, - dereference: true, - }) - ) - ); -} - -export interface WriteWorkerConfigOptions { - root: string; - config: ParsedInputWorkerConfig; - manifest?: ParsedOutputWorkerConfig["manifest"]; - directoryName?: string; -} - -/** - * Write an output Worker `worker.config.json` to the Build Output Specification - * tree. - * - * - Workers mode: `manifest` is provided (bundle/ present on disk). - * - Assets-only mode: `manifest` is omitted (no bundle/ directory). - */ -export async function writeWorkerConfig({ - root, - config, - manifest, - directoryName = DEFAULT_WORKER_DIRECTORY_NAME, -}: WriteWorkerConfigOptions): Promise { - const { entrypoint: _entrypoint, ...rest } = config; - const outputConfig: ParsedOutputWorkerConfig = { ...rest, manifest }; - await fsp.mkdir(getWorkerDir(root, directoryName), { recursive: true }); - await fsp.writeFile( - getWorkerConfigPath(root, directoryName), - JSON.stringify(outputConfig) - ); -} - -export interface WriteContainerConfigOptions { - root: string; - config: ParsedOutputContainerConfig; - directoryName: string; -} - -/** - * Write an output Container `container.config.json` to the Build Output - * Specification tree. - * - * Local Dockerfiles must already have been built and represented by a - * `localReference` in the output config. - */ -export async function writeContainerConfig({ - root, - config, - directoryName, -}: WriteContainerConfigOptions): Promise { - await fsp.mkdir(getContainerDir(root, directoryName), { - recursive: true, - }); - await fsp.writeFile( - getContainerConfigPath(root, directoryName), - JSON.stringify(config) - ); -} - -/** - * 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. - */ -export async function writeRootConfig( - root: string, - settings: ParsedInputSettingsConfig | undefined, - buildContext: ConfigContext -): Promise { - const outputConfig: ParsedOutputRootConfig = { - ...settings, - buildContext, - }; - const configPath = getRootConfigPath(root); - await fsp.mkdir(path.dirname(configPath), { recursive: true }); - await fsp.writeFile(configPath, JSON.stringify(outputConfig)); -} diff --git a/packages/build-output-utils/tsconfig.json b/packages/build-output-utils/tsconfig.json deleted file mode 100644 index 84e3fdf220..0000000000 --- a/packages/build-output-utils/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "@cloudflare/workers-tsconfig/base.json", - "compilerOptions": { - "types": ["@cloudflare/workers-types/experimental", "@types/node"] - }, - "include": ["src"] -} diff --git a/packages/build-output-utils/tsdown.config.ts b/packages/build-output-utils/tsdown.config.ts deleted file mode 100644 index 0c9545f089..0000000000 --- a/packages/build-output-utils/tsdown.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { defineConfig } from "tsdown"; - -export default defineConfig({ - entry: { - index: "src/index.ts", - }, - platform: "node", - outDir: "dist", - dts: true, - tsconfig: "tsconfig.json", -}); diff --git a/packages/build-output-utils/turbo.json b/packages/build-output-utils/turbo.json deleted file mode 100644 index 6556dcf3e5..0000000000 --- a/packages/build-output-utils/turbo.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "$schema": "http://turbo.build/schema.json", - "extends": ["//"], - "tasks": { - "build": { - "outputs": ["dist/**"] - } - } -} diff --git a/packages/build-output-utils/vitest.config.ts b/packages/build-output-utils/vitest.config.ts deleted file mode 100644 index 0c9f1f8e04..0000000000 --- a/packages/build-output-utils/vitest.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from "vitest/config"; - -export default defineConfig({ - test: { - include: ["**/__tests__/**/*.test.ts"], - reporters: ["default"], - }, -}); diff --git a/packages/chrome-devtools-patches/CHANGELOG.md b/packages/chrome-devtools-patches/CHANGELOG.md deleted file mode 100644 index 2dfddb4852..0000000000 --- a/packages/chrome-devtools-patches/CHANGELOG.md +++ /dev/null @@ -1,50 +0,0 @@ -# @cloudflare/chrome-devtools-patches - -## 0.1.5 - -### Patch Changes - -- [#12928](https://github.com/cloudflare/workers-sdk/pull/12928) [`81ee98e`](https://github.com/cloudflare/workers-sdk/commit/81ee98e6a0c6be879757289ef6e34e1559d6ee2a) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - Migrate chrome-devtools-patches deployment from Cloudflare Pages to Workers + Assets - - The DevTools frontend is now deployed as a Cloudflare Workers + Assets project instead of a Cloudflare Pages project. This uses `wrangler deploy` for production deployments and `wrangler versions upload` for PR preview deployments. - - The inspector proxy origin allowlists in both wrangler and miniflare have been updated to accept connections from the new `workers.dev` domain patterns, while retaining the legacy `pages.dev` patterns for backward compatibility. - -## 0.1.4 - -### Patch Changes - -- [#9649](https://github.com/cloudflare/workers-sdk/pull/9649) [`ec9b417`](https://github.com/cloudflare/workers-sdk/commit/ec9b417f8ed711e7b5044410e83d781f123a6a62) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - patch release to trigger a test release - -## 0.1.3 - -### Patch Changes - -- [#9551](https://github.com/cloudflare/workers-sdk/pull/9551) [`b0b59e0`](https://github.com/cloudflare/workers-sdk/commit/b0b59e071393e13e3770fd59fb0cb26136e88272) Thanks [@penalosa](https://github.com/penalosa)! - Update Devtools Patches - -## 0.1.2 - -### Patch Changes - -- [#7693](https://github.com/cloudflare/workers-sdk/pull/7693) [`65a3e35`](https://github.com/cloudflare/workers-sdk/commit/65a3e3590aff2f287c669172856512d6b29bd37f) Thanks [@emily-shen](https://github.com/emily-shen)! - chore: rebases patches on latest devtools head - -## 0.1.1 - -### Patch Changes - -- [#7258](https://github.com/cloudflare/workers-sdk/pull/7258) [`f1f508e`](https://github.com/cloudflare/workers-sdk/commit/f1f508ec1acefd7b409b77ae1070029953cca061) Thanks [@andyjessop](https://github.com/andyjessop)! - change package name from @cloudflare/wrangler-devtools to @cloudflare/chrome-devtools-patches - -## 0.1.0 - -### Minor Changes - -- [#7137](https://github.com/cloudflare/workers-sdk/pull/7137) [`1b195bd`](https://github.com/cloudflare/workers-sdk/commit/1b195bd09aef282a8a205d341579cdb7e3755d89) Thanks [@andyjessop](https://github.com/andyjessop)! - feat: update devtools patches for release - - rebases patches on top of latest devtools head - - removes CPU profiling tab - - adds performance tab - -## 0.0.1 - -### Patch Changes - -- [#4738](https://github.com/cloudflare/workers-sdk/pull/4738) [`a9f36ef`](https://github.com/cloudflare/workers-sdk/commit/a9f36ef01c6080352934cfd31c4987c5e197f8b5) Thanks [@neilsh](https://github.com/neilsh)! - fix: Fix typo in CSP diff --git a/packages/chrome-devtools-patches/Makefile b/packages/chrome-devtools-patches/Makefile deleted file mode 100644 index 95d3741940..0000000000 --- a/packages/chrome-devtools-patches/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -ROOT = $(realpath .) -PATH_WITH_DEPOT = $(PATH):$(ROOT)/depot/ -# The upstream devtools commit upon which our patches are based -HEAD = b66ecf5bef3ae6c769dbc6d904ce1c54d3771227 -PATCHES = $(shell ls ${PWD}/patches/*.patch) -depot: - git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git depot - -devtools-frontend: depot - git clone https://chromium.googlesource.com/devtools/devtools-frontend - # Ensure other depot_tools can be called from gclient config - PATH="$(PATH_WITH_DEPOT)" $(ROOT)/depot/gclient config https://chromium.googlesource.com/devtools/devtools-frontend --unmanaged - git -C devtools-frontend checkout $(HEAD) - git -C devtools-frontend config user.email "workers-devprod@cloudflare.com" - git -C devtools-frontend config user.name "Workers DevProd" - git -C devtools-frontend am $(PATCHES) - -devtools-frontend/out/Default/gen/front_end: devtools-frontend - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" $(ROOT)/depot/gclient sync - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" $(ROOT)/depot/gn gen out/Default - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" $(ROOT)/depot/autoninja -C out/Default - -publish: cleanup devtools-frontend/out/Default/gen/front_end - npx wrangler deploy - -publish-preview: cleanup devtools-frontend/out/Default/gen/front_end - npx wrangler versions upload - -cleanup: - rm -rf devtools-frontend .gclient* .cipd node_modules depot - -test: - git -C devtools-frontend am $(PATCHES) - -dev: - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" npm run install-deps - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" gn gen out/Default --args="devtools_skip_typecheck=true" - cd devtools-frontend && PATH="$(PATH_WITH_DEPOT)" npm run watch diff --git a/packages/chrome-devtools-patches/README.md b/packages/chrome-devtools-patches/README.md deleted file mode 100644 index 6f12095d98..0000000000 --- a/packages/chrome-devtools-patches/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Workers Devtools - -This package contains a Workers specific version of Chrome Devtools that is used by the Wrangler dev command and other applications. It is a customized fork of Chrome DevTools specifically tailored for debugging Cloudflare Workers. This package provides Worker-specific functionality through carefully maintained patches on top of Chrome DevTools. - -## Overview - -This package is used across multiple Cloudflare products: - -- Workers Playground (`workers-playground`) -- Quick Editor (`@cloudflare/quick-edit`) -- Wrangler CLI via the `InspectorProxy` - -## Features - -Our customized DevTools implementation provides: - -- Source code viewing and live updates -- Network request inspection -- Worker-specific UI optimizations - -## Development - -We maintain this fork by applying patches on top of Chrome DevTools. These patches need to be periodically rebased as Chrome DevTools evolves. - -**Key Development Tasks:** - -- Generating patches from our customizations -- Rebasing patches onto new Chrome DevTools versions -- Testing functionality across all integration points - -## Updating DevTools - -We perform quarterly updates to stay current with upstream Chrome DevTools. The update process involves: - -1. Cloning the devtools-frontend repo -2. Applying our existing patches -3. Rebasing onto the latest Chrome DevTools -4. Regenerating patches -5. Thorough testing across all integration points - -**For detailed instructions on updating DevTools, please refer to our internal documentation on keeping devtools up-to-date.** - -## Testing - -Two methods are available for testing updates: - -**Local Development:** - -- Build and serve DevTools locally -- Test against local Playground instance -- Make targeted fixes as needed - -**Preview Builds:** - -On any pull request to the repo on GitHub, you can add the `preview:chrome-devtools-patches` label to trigger a preview build of the DevTools frontend. This is useful because it will allow you to manually test your changes in a live environment, and with one-click. - -Once the preview is built, you will see a comment on the PR with a link to the live URL. - -## Acceptance Criteria - -Our DevTools implementation must maintain full functionality across: - -- Console operations (logging, errors, filters) -- Source code viewing and debugging -- Network request inspection -- Worker-specific UI customizations - -## Contributing - -When making changes: - -- Keep patches minimal and targeted -- Prefer CSS-based UI modifications -- Test thoroughly across all integration points -- Document any new patches or modifications - -## Deployment - -This package is deployed as a Cloudflare Workers + Assets project. The static DevTools frontend is served directly from Workers Assets, configured via `wrangler.jsonc`. - -Deployments are managed by GitHub Actions: - -- deploy-previews.yml: - - Runs on any PR that has the `preview:chrome-devtools-patches` label. - - Uploads a preview version (without activating it in production) via `wrangler versions upload`. - - The preview URL is posted as a comment on the PR. -- changesets.yml: - - Runs when a "Version Packages" PR, containing a changeset that touches this package, is merged to `main`. - - Deploys this package to production via `wrangler deploy`. - - Production is accessible via the custom domain [https://devtools.devprod.cloudflare.dev/]. diff --git a/packages/chrome-devtools-patches/package.json b/packages/chrome-devtools-patches/package.json deleted file mode 100644 index ee54c86795..0000000000 --- a/packages/chrome-devtools-patches/package.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "name": "@cloudflare/chrome-devtools-patches", - "version": "0.1.5", - "private": true, - "description": "Chrome Devtools hosted for easy use with Workers tooling and applications (Wrangler, Playground, Quick Editor).", - "homepage": "https://github.com/cloudflare/workers-sdk#readme", - "bugs": { - "url": "https://github.com/cloudflare/workers-sdk/issues" - }, - "license": "BSD-3-Clause", - "author": "workers-devprod@cloudflare.com", - "scripts": { - "deploy": "CLOUDFLARE_ACCOUNT_ID=e35fd947284363a46fd7061634477114 make publish", - "deploy:preview": "CLOUDFLARE_ACCOUNT_ID=e35fd947284363a46fd7061634477114 make publish-preview", - "testenv": "make testenv" - }, - "devDependencies": { - "wrangler": "workspace:*" - }, - "volta": { - "extends": "../../package.json" - }, - "workers-sdk": { - "deploy": true - } -} diff --git a/packages/chrome-devtools-patches/patches/0001-Expand-Browser-support-make-it-work-in-Firefox-Safar.patch b/packages/chrome-devtools-patches/patches/0001-Expand-Browser-support-make-it-work-in-Firefox-Safar.patch deleted file mode 100644 index 14e0ecccbf..0000000000 --- a/packages/chrome-devtools-patches/patches/0001-Expand-Browser-support-make-it-work-in-Firefox-Safar.patch +++ /dev/null @@ -1,128 +0,0 @@ -From 261ba678389218354cb8f9dce78483cf4f09716f Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 14:15:43 +0100 -Subject: [PATCH 1/8] Expand Browser support (make it work in Firefox & Safari) - -* Basic support for text colour in dark mode in browsers - that don't implement :host-context - -* A few firefox-specific patches (with detailed inline comments) - -* A (vendored) custom elements polyfill for Safari - -Acceptance criteria: -If updating the commit of devtools upon which these patches are based, make sure this patch: -* Displays console.log() output with sufficient contrast in dark mode -* Allows devtools to load in Safari (loading with _any_ UI is sufficent to check whether this has worked) -* Supports viewing a list of requests in the network panel in Firefox (without the patches here this goes very obviously wrong) ---- - front_end/core/dom_extension/DOMExtension.ts | 2 +- - front_end/entrypoint_template.html | 38 ++++++++++++++++++- - front_end/entrypoints/js_app/js_app.ts | 3 ++ - .../legacy/components/data_grid/DataGrid.ts | 5 +++ - 4 files changed, 46 insertions(+), 2 deletions(-) - -diff --git a/front_end/core/dom_extension/DOMExtension.ts b/front_end/core/dom_extension/DOMExtension.ts -index 202c680a30..a639437998 100644 ---- a/front_end/core/dom_extension/DOMExtension.ts -+++ b/front_end/core/dom_extension/DOMExtension.ts -@@ -133,7 +133,7 @@ Node.prototype.getComponentSelection = function(): Selection|null { - while (parent && parent.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { - parent = parent.parentNode; - } -- return parent instanceof ShadowRoot ? parent.getSelection() : this.window().getSelection(); -+ return parent instanceof ShadowRoot ? (parent?.getSelection?.() ?? this.window().getSelection()) : this.window().getSelection(); - }; - - Node.prototype.hasSelection = function(): boolean { -diff --git a/front_end/entrypoint_template.html b/front_end/entrypoint_template.html -index 64d55d4c14..07972be81f 100644 ---- a/front_end/entrypoint_template.html -+++ b/front_end/entrypoint_template.html -@@ -13,9 +13,45 @@ - background-color: rgb(41 42 45); - } - } -+ -+ .platform-mac { -+ --monospace-font-size: 11px; -+ --monospace-font-family: menlo, monospace; -+ --source-code-font-size: 11px; -+ --source-code-font-family: menlo, monospace; -+ } -+ -+ .platform-windows { -+ --monospace-font-size: 12px; -+ --monospace-font-family: consolas, lucida console, courier new, monospace; -+ --source-code-font-size: 12px; -+ --source-code-font-family: consolas, lucida console, courier new, monospace; -+ } -+ -+ .platform-linux { -+ --monospace-font-size: 11px; -+ --monospace-font-family: dejavu sans mono, monospace; -+ --source-code-font-size: 11px; -+ --source-code-font-family: dejavu sans mono, monospace; -+ } -+ -+ .-theme-with-dark-background .platform-linux, -+ .-theme-with-dark-background .platform-mac { -+ --override-text-color: rgb(189 198 207); -+ } -+ -+ .cm-editor + .cm-editor { -+ display: 'none', -+ } - -- -+ - -+ - - - -diff --git a/front_end/entrypoints/js_app/js_app.ts b/front_end/entrypoints/js_app/js_app.ts -index a7f4827d68..2dbb4eca42 100644 ---- a/front_end/entrypoints/js_app/js_app.ts -+++ b/front_end/entrypoints/js_app/js_app.ts -@@ -44,6 +44,9 @@ async function loadSourcesModule(): Promise { - } - return loadedSourcesModule; - } -+ -+// This is not supported in Firefox: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView -+Element.prototype.scrollIntoViewIfNeeded = Element.prototype.scrollIntoView; - export class JsMainImpl implements Common.Runnable.Runnable { - static instance(opts: {forceNew: boolean|null} = {forceNew: null}): JsMainImpl { - const {forceNew} = opts; -diff --git a/front_end/ui/legacy/components/data_grid/DataGrid.ts b/front_end/ui/legacy/components/data_grid/DataGrid.ts -index 70820e38a1..5c9e25c522 100644 ---- a/front_end/ui/legacy/components/data_grid/DataGrid.ts -+++ b/front_end/ui/legacy/components/data_grid/DataGrid.ts -@@ -223,6 +223,8 @@ export class DataGridImpl extends Common.ObjectWrapper.ObjectWrapper *under* the -+ (this.dataTableBody as HTMLElement).style.height = 'calc(100% - 27px)'; - this.topFillerRow = this.dataTableBody.createChild('tr', 'data-grid-filler-row revealed'); - UI.ARIAUtils.setHidden(this.topFillerRow, true); - this.bottomFillerRow = this.dataTableBody.createChild('tr', 'data-grid-filler-row revealed'); -@@ -535,6 +537,9 @@ export class DataGridImpl extends Common.ObjectWrapper.ObjectWrapper -Date: Fri, 25 Oct 2024 16:06:06 +0100 -Subject: [PATCH 2/8] Setup Cloudflare devtools target type - ---- - front_end/core/sdk/Target.ts | 5 +++++ - front_end/entrypoints/js_app/js_app.ts | 2 +- - 2 files changed, 6 insertions(+), 1 deletion(-) - -diff --git a/front_end/core/sdk/Target.ts b/front_end/core/sdk/Target.ts -index 2437d6aac1..e9a3318268 100644 ---- a/front_end/core/sdk/Target.ts -+++ b/front_end/core/sdk/Target.ts -@@ -98,6 +98,10 @@ export class Target extends ProtocolClient.InspectorBackend.TargetBase { - break; - case Type.NODE_WORKER: - this.#capabilitiesMask = Capability.JS | Capability.NETWORK | Capability.TARGET; -+ break; -+ case Type.CLOUDFLARE: -+ this.#capabilitiesMask = Capability.JS | Capability.NETWORK; -+ break; - } - this.#typeInternal = type; - this.#parentTargetInternal = parentTarget; -@@ -298,6 +302,7 @@ export enum Type { - AUCTION_WORKLET = 'auction-worklet', - WORKLET = 'worklet', - TAB = 'tab', -+ CLOUDFLARE = 'cloudflare', - NODE_WORKER = 'node-worker', - } - -diff --git a/front_end/entrypoints/js_app/js_app.ts b/front_end/entrypoints/js_app/js_app.ts -index 2dbb4eca42..814bc1fc70 100644 ---- a/front_end/entrypoints/js_app/js_app.ts -+++ b/front_end/entrypoints/js_app/js_app.ts -@@ -61,7 +61,7 @@ export class JsMainImpl implements Common.Runnable.Runnable { - Host.userMetrics.actionTaken(Host.UserMetrics.Action.ConnectToNodeJSDirectly); - void SDK.Connections.initMainConnection(async () => { - const target = SDK.TargetManager.TargetManager.instance().createTarget( -- 'main', i18nString(UIStrings.main), SDK.Target.Type.NODE, null); -+ 'main', i18nString(UIStrings.main), SDK.Target.Type.CLOUDFLARE, null); - void target.runtimeAgent().invoke_runIfWaitingForDebugger(); - }, Components.TargetDetachedDialog.TargetDetachedDialog.connectionLost); - } --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/patches/0003-Add-ping-to-improve-connection-stability.-Without-th.patch b/packages/chrome-devtools-patches/patches/0003-Add-ping-to-improve-connection-stability.-Without-th.patch deleted file mode 100644 index 22f8e743b3..0000000000 --- a/packages/chrome-devtools-patches/patches/0003-Add-ping-to-improve-connection-stability.-Without-th.patch +++ /dev/null @@ -1,45 +0,0 @@ -From bcba740e8dd373acf74a8d7f82d93107e2bf4a08 Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 15:04:17 +0100 -Subject: [PATCH 3/8] Add ping to improve connection stability. Without this, - we see frequent "Devtools disconnected" messages in the dash and Workers - Playground - ---- - front_end/core/protocol_client/InspectorBackend.ts | 8 ++++++++ - 1 file changed, 8 insertions(+) - -diff --git a/front_end/core/protocol_client/InspectorBackend.ts b/front_end/core/protocol_client/InspectorBackend.ts -index 32948c2dbd..27dfa1abe3 100644 ---- a/front_end/core/protocol_client/InspectorBackend.ts -+++ b/front_end/core/protocol_client/InspectorBackend.ts -@@ -256,6 +256,7 @@ export class SessionRouter { - proxyConnection: ((Connection | undefined)|null), - }>(); - #pendingScripts: Array<() => void> = []; -+ #pingInterval: ReturnType; - - constructor(connection: Connection) { - this.#connectionInternal = connection; -@@ -266,11 +267,18 @@ export class SessionRouter { - this.#connectionInternal.setOnMessage(this.onMessage.bind(this)); - - this.#connectionInternal.setOnDisconnect(reason => { -+ clearInterval(this.#pingInterval); - const session = this.#sessions.get(''); - if (session) { - session.target.dispose(reason); - } - }); -+ this.#pingInterval = setInterval(() => { -+ this.#connectionInternal.sendRawMessage(JSON.stringify({ -+ method: 'Runtime.getIsolateId', -+ id: this.nextMessageId(), -+ })); -+ }, 10_000); - } - - registerSession(target: TargetBase, sessionId: string, proxyConnection?: Connection|null): void { --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/patches/0004-Support-viewing-source-files-over-the-network.-This-.patch b/packages/chrome-devtools-patches/patches/0004-Support-viewing-source-files-over-the-network.-This-.patch deleted file mode 100644 index 3abadff27d..0000000000 --- a/packages/chrome-devtools-patches/patches/0004-Support-viewing-source-files-over-the-network.-This-.patch +++ /dev/null @@ -1,158 +0,0 @@ -From b1f97bf51177076f6abb501cf8fe57a77640792e Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 15:26:38 +0100 -Subject: [PATCH 4/8] Support viewing source files over the network. This - consists of: - -* Replacing the default file viewers (Workspace & Snippets), with a network based one called "Cloudflare" (see sources-meta.ts & js_app.ts) - -* Supporting a `?domain=` query param to customise the network name. Without this, the protocol is used (i.e. `file://`), which isn't super friendly (see NavigatorView.ts) - -* Enable JUST_MY_CODE to hide Wrangler's injected middleware (see MainImpl.ts) - -* Enable AUTHORED_DEPLOYED_GROUPING for a better grouping between source-mapped and compiled code (see MainImpl.ts) - -* Support the mechanism by which Wrangler provides sourcemaps, the wrangler-file:// protocol (see PageResourceLoader.ts & ParsedURL.ts) ---- - front_end/core/common/ParsedURL.ts | 2 +- - front_end/core/sdk/PageResourceLoader.ts | 4 +++- - front_end/entrypoints/js_app/js_app.ts | 16 ++++++-------- - front_end/entrypoints/main/MainImpl.ts | 2 ++ - front_end/panels/sources/NavigatorView.ts | 5 +++-- - front_end/panels/sources/sources-meta.ts | 26 ----------------------- - 6 files changed, 15 insertions(+), 40 deletions(-) - -diff --git a/front_end/core/common/ParsedURL.ts b/front_end/core/common/ParsedURL.ts -index d01ab1856d..e29c0eab46 100644 ---- a/front_end/core/common/ParsedURL.ts -+++ b/front_end/core/common/ParsedURL.ts -@@ -365,7 +365,7 @@ export class ParsedURL { - static completeURL(baseURL: Platform.DevToolsPath.UrlString, href: string): Platform.DevToolsPath.UrlString|null { - // Return special URLs as-is. - if (href.startsWith('data:') || href.startsWith('blob:') || href.startsWith('javascript:') || -- href.startsWith('mailto:')) { -+ href.startsWith('mailto:') || href.startsWith('wrangler:')) { - return href as Platform.DevToolsPath.UrlString; - } - -diff --git a/front_end/core/sdk/PageResourceLoader.ts b/front_end/core/sdk/PageResourceLoader.ts -index 722bf5f80a..cede6fbc20 100644 ---- a/front_end/core/sdk/PageResourceLoader.ts -+++ b/front_end/core/sdk/PageResourceLoader.ts -@@ -381,7 +381,9 @@ export class PageResourceLoader extends Common.ObjectWrapper.ObjectWrapper -Date: Fri, 25 Oct 2024 15:05:56 +0100 -Subject: [PATCH 5/8] Support forcing the devtools theme via a query parameter, - to enable it to fit in with the Cloudflare dashboard when embedded. - -To test, make sure that `?theme=dark`, `?theme=default`, and `?theme=systemPreferred` all correctly force the theme of devtools ---- - front_end/ui/legacy/theme_support/ThemeSupport.ts | 11 ++++++++--- - 1 file changed, 8 insertions(+), 3 deletions(-) - -diff --git a/front_end/ui/legacy/theme_support/ThemeSupport.ts b/front_end/ui/legacy/theme_support/ThemeSupport.ts -index 298ba78952..43ee9341ec 100644 ---- a/front_end/ui/legacy/theme_support/ThemeSupport.ts -+++ b/front_end/ui/legacy/theme_support/ThemeSupport.ts -@@ -152,14 +152,19 @@ export class ThemeSupport extends EventTarget { - } - - #applyThemeToDocument(document: Document): void { -+ // Get theme from url, to allow for theme inheritance from the Cloudflare dashboard -+ const urlParams = new URLSearchParams(document.location.search); -+ const theme = urlParams.get('theme') ?? 'systemPreferred'; -+ - const isForcedColorsMode = window.matchMedia('(forced-colors: active)').matches; - const systemPreferredTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default'; - -- const useSystemPreferred = this.setting.get() === 'systemPreferred' || isForcedColorsMode; -- this.themeNameInternal = useSystemPreferred ? systemPreferredTheme : this.setting.get(); -+ const useSystemPreferred = theme === 'systemPreferred' || isForcedColorsMode; -+ this.themeNameInternal = useSystemPreferred ? systemPreferredTheme : theme; - document.documentElement.classList.toggle('theme-with-dark-background', this.themeNameInternal === 'dark'); - -- const useChromeTheme = Common.Settings.moduleSetting('chrome-theme-colors').get(); -+ // Disable this—it adds blue headers which are out of keeping with Cloudflare styling -+ const useChromeTheme = false; - const isIncognito = Root.Runtime.hostConfig.isOffTheRecord === true; - // Baseline is the name of Chrome's default color theme and there are two of these: default and grayscale. - // The collective name for the rest of the color themes is dynamic. --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/patches/0006-All-about-the-network-tab.patch b/packages/chrome-devtools-patches/patches/0006-All-about-the-network-tab.patch deleted file mode 100644 index 316478818d..0000000000 --- a/packages/chrome-devtools-patches/patches/0006-All-about-the-network-tab.patch +++ /dev/null @@ -1,116 +0,0 @@ -From 1729d533ea8866ee71a5e2170253f7cd6f850e0c Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 16:05:12 +0100 -Subject: [PATCH 6/8] All about the network tab! - -* Display the _content_ of responses (using cfResponse.body, a Cloudflare-specific extension) - -* Enable the network tab for the js_app type - -* Hide unsupported UI (cache disabling & network throttling) ---- - front_end/core/sdk/NetworkManager.ts | 8 ++++++- - front_end/entrypoints/js_app/js_app.ts | 1 + - front_end/panels/network/NetworkPanel.ts | 27 ------------------------ - 3 files changed, 8 insertions(+), 28 deletions(-) - -diff --git a/front_end/core/sdk/NetworkManager.ts b/front_end/core/sdk/NetworkManager.ts -index 1e50c6329f..756679235b 100644 ---- a/front_end/core/sdk/NetworkManager.ts -+++ b/front_end/core/sdk/NetworkManager.ts -@@ -34,6 +34,7 @@ - - import type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js'; - import * as Protocol from '../../generated/protocol.js'; -+import { ContentData } from '../../models/text_utils/ContentData.js'; - import * as TextUtils from '../../models/text_utils/text_utils.js'; - import * as Common from '../common/common.js'; - import type {Serializer} from '../common/Settings.js'; -@@ -846,7 +847,7 @@ export class NetworkDispatcher implements ProtocolProxyApi.NetworkDispatcher { - this.updateNetworkRequest(networkRequest); - } - -- loadingFinished({requestId, timestamp: finishTime, encodedDataLength}: Protocol.Network.LoadingFinishedEvent): void { -+ loadingFinished({requestId, timestamp: finishTime, encodedDataLength, cfResponse}: Protocol.Network.LoadingFinishedEvent & { cfResponse?: Omit }): void { - let networkRequest: NetworkRequest|null|undefined = this.#requestsById.get(requestId); - if (!networkRequest) { - networkRequest = this.maybeAdoptMainResourceRequest(requestId); -@@ -855,6 +856,11 @@ export class NetworkDispatcher implements ProtocolProxyApi.NetworkDispatcher { - return; - } - this.getExtraInfoBuilder(requestId).finished(); -+ if (cfResponse !== undefined) { -+ networkRequest.setContentDataProvider(async () => { -+ return new ContentData(cfResponse.body, cfResponse.base64Encoded, networkRequest.mimeType); -+ }); -+ } - this.finishNetworkRequest(networkRequest, finishTime, encodedDataLength); - this.#manager.dispatchEventToListeners(Events.LoadingFinished, networkRequest); - } -diff --git a/front_end/entrypoints/js_app/js_app.ts b/front_end/entrypoints/js_app/js_app.ts -index 893ac3533f..937e646ab5 100644 ---- a/front_end/entrypoints/js_app/js_app.ts -+++ b/front_end/entrypoints/js_app/js_app.ts -@@ -4,6 +4,7 @@ - - import '../shell/shell.js'; - import '../../panels/js_timeline/js_timeline-meta.js'; -+import '../../panels/network/network-meta.js'; - import '../../panels/mobile_throttling/mobile_throttling-meta.js'; - import '../../panels/network/network-meta.js'; - -diff --git a/front_end/panels/network/NetworkPanel.ts b/front_end/panels/network/NetworkPanel.ts -index f70065800e..ac1316662b 100644 ---- a/front_end/panels/network/NetworkPanel.ts -+++ b/front_end/panels/network/NetworkPanel.ts -@@ -76,14 +76,6 @@ const UIStrings = { - *@description Text to preserve the log after refreshing - */ - preserveLog: 'Preserve log', -- /** -- *@description Text to disable cache while DevTools is open -- */ -- disableCacheWhileDevtoolsIsOpen: 'Disable cache while DevTools is open', -- /** -- *@description Text in Network Config View of the Network panel -- */ -- disableCache: 'Disable cache', - /** - *@description Tooltip text that appears when hovering over the largeicon settings gear in show settings pane setting in network panel of the network panel - */ -@@ -181,10 +173,6 @@ const UIStrings = { - *@description Text in Network Panel that is displayed when frames are being fetched. - */ - fetchingFrames: 'Fetching frames…', -- /** -- * @description Text of a button in the Network panel's toolbar that open Network Conditions panel in the drawer. -- */ -- moreNetworkConditions: 'More network conditions…', - } as const; - const str_ = i18n.i18n.registerUIStrings('panels/network/NetworkPanel.ts', UIStrings); - const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); -@@ -456,21 +444,6 @@ export class NetworkPanel extends UI.Panel.Panel implements - this.panelToolbar.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox( - this.preserveLogSetting, i18nString(UIStrings.doNotClearLogOnPageReload), i18nString(UIStrings.preserveLog))); - -- this.panelToolbar.appendSeparator(); -- const disableCacheCheckbox = new UI.Toolbar.ToolbarSettingCheckbox( -- Common.Settings.Settings.instance().moduleSetting('cache-disabled'), -- i18nString(UIStrings.disableCacheWhileDevtoolsIsOpen), i18nString(UIStrings.disableCache)); -- this.panelToolbar.appendToolbarItem(disableCacheCheckbox); -- -- this.panelToolbar.appendToolbarItem(this.throttlingSelect); -- -- const networkConditionsButton = new UI.Toolbar.ToolbarButton( -- i18nString(UIStrings.moreNetworkConditions), 'network-settings', undefined, 'network-conditions'); -- networkConditionsButton.addEventListener(UI.Toolbar.ToolbarButton.Events.CLICK, () => { -- void UI.ViewManager.ViewManager.instance().showView('network.config'); -- }, this); -- this.panelToolbar.appendToolbarItem(networkConditionsButton); -- - this.rightToolbar.appendToolbarItem(new UI.Toolbar.ToolbarItem(this.progressBarContainer)); - this.rightToolbar.appendSeparator(); - this.rightToolbar.appendToolbarItem(new UI.Toolbar.ToolbarSettingToggle( --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/patches/0007-Limit-heap-profiling-modes-available.patch b/packages/chrome-devtools-patches/patches/0007-Limit-heap-profiling-modes-available.patch deleted file mode 100644 index dcde323350..0000000000 --- a/packages/chrome-devtools-patches/patches/0007-Limit-heap-profiling-modes-available.patch +++ /dev/null @@ -1,31 +0,0 @@ -From c43fb074f72c73e4c7ad9dd02c061870298a4347 Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 16:07:24 +0100 -Subject: [PATCH 7/8] Limit heap profiling modes available - ---- - front_end/panels/profiler/HeapProfilerPanel.ts | 8 ++------ - 1 file changed, 2 insertions(+), 6 deletions(-) - -diff --git a/front_end/panels/profiler/HeapProfilerPanel.ts b/front_end/panels/profiler/HeapProfilerPanel.ts -index b25d9e65fc..9a19052de2 100644 ---- a/front_end/panels/profiler/HeapProfilerPanel.ts -+++ b/front_end/panels/profiler/HeapProfilerPanel.ts -@@ -25,12 +25,8 @@ export class HeapProfilerPanel extends ProfilesPanel implements UI.ContextMenu.P - UI.ActionRegistration.ActionDelegate { - constructor() { - const registry = instance; -- const profileTypes = [ -- registry.heapSnapshotProfileType, -- registry.trackingHeapSnapshotProfileType, -- registry.samplingHeapProfileType, -- registry.detachedElementProfileType, -- ]; -+ const profileTypes = -+ [registry.heapSnapshotProfileType]; - super('heap-profiler', profileTypes as ProfileType[], 'profiler.heap-toggle-recording'); - } - --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/patches/0008-Use-the-worker-name-as-the-title-for-the-Javascript-.patch b/packages/chrome-devtools-patches/patches/0008-Use-the-worker-name-as-the-title-for-the-Javascript-.patch deleted file mode 100644 index d0e393fc49..0000000000 --- a/packages/chrome-devtools-patches/patches/0008-Use-the-worker-name-as-the-title-for-the-Javascript-.patch +++ /dev/null @@ -1,31 +0,0 @@ -From 641e6a0eb3f7cf138168185f8a51cd93b1d0db74 Mon Sep 17 00:00:00 2001 -From: Workers DevProd -Date: Fri, 25 Oct 2024 16:11:10 +0100 -Subject: [PATCH 8/8] Use the worker name as the title for the Javascript - Isolate name in the Performance tab - ---- - front_end/panels/timeline/IsolateSelector.ts | 6 +++++- - 1 file changed, 5 insertions(+), 1 deletion(-) - -diff --git a/front_end/panels/timeline/IsolateSelector.ts b/front_end/panels/timeline/IsolateSelector.ts -index eea81e20dd..9d19e75d79 100644 ---- a/front_end/panels/timeline/IsolateSelector.ts -+++ b/front_end/panels/timeline/IsolateSelector.ts -@@ -52,8 +52,12 @@ export class IsolateSelector extends UI.Toolbar.ToolbarItem implements SDK.Isola - const name = SDK.TargetManager.TargetManager.instance().rootTarget() !== target ? target.name() : ''; - const parsedURL = new Common.ParsedURL.ParsedURL(target.inspectedURL()); - const domain = parsedURL.isValid ? parsedURL.domain() : ''; -+ -+ const query = new URLSearchParams(location.search); -+ const workerName = query.get('domain'); -+ - const title = -- target.decorateLabel(domain && name ? `${domain}: ${name}` : name || domain || i18nString(UIStrings.empty)); -+ target.decorateLabel(domain && name ? `${domain}: ${name}` : name || domain || workerName || i18nString(UIStrings.empty)); - modelCountByName.set(title, (modelCountByName.get(title) || 0) + 1); - } - itemForIsolate.removeChildren(); --- -2.39.5 (Apple Git-154) - diff --git a/packages/chrome-devtools-patches/wrangler.jsonc b/packages/chrome-devtools-patches/wrangler.jsonc deleted file mode 100644 index 68f024d3dc..0000000000 --- a/packages/chrome-devtools-patches/wrangler.jsonc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "$schema": "./node_modules/wrangler/config-schema.json", - "name": "cloudflare-devtools", - "compatibility_date": "2025-07-01", - "assets": { - "directory": "devtools-frontend/out/Default/gen/front_end", - }, - "preview_urls": true, - "workers_dev": true, -} diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md deleted file mode 100644 index 9f23adee47..0000000000 --- a/packages/cli/CHANGELOG.md +++ /dev/null @@ -1,442 +0,0 @@ -# @cloudflare/cli - -## 0.2.6 - -### Patch Changes - -- Updated dependencies [[`dc3e4df`](https://github.com/cloudflare/workers-sdk/commit/dc3e4df999e9d774469c6292a7b92b1f427b3dd9)]: - - @cloudflare/workers-utils@0.47.2 - -## 0.2.5 - -### Patch Changes - -- Updated dependencies [[`ad7ff45`](https://github.com/cloudflare/workers-sdk/commit/ad7ff45076f762253268d03c28b5384f43889999), [`93c1069`](https://github.com/cloudflare/workers-sdk/commit/93c10696930e50e310b8b49a8e792671bf371e82)]: - - @cloudflare/workers-utils@0.47.1 - -## 0.2.4 - -### Patch Changes - -- Updated dependencies [[`b75421f`](https://github.com/cloudflare/workers-sdk/commit/b75421fcd5b2d8208cefb38882479773a7387df4), [`2b1a0ca`](https://github.com/cloudflare/workers-sdk/commit/2b1a0ca78c30403934ab9df9b6264185d473b3ef), [`aa2f9b7`](https://github.com/cloudflare/workers-sdk/commit/aa2f9b73ed1177bceb83fd730eb9e47cbabc8c7f)]: - - @cloudflare/workers-utils@0.47.0 - -## 0.2.3 - -### Patch Changes - -- Updated dependencies [[`7f57b1c`](https://github.com/cloudflare/workers-sdk/commit/7f57b1c60002ae3f077dd9c1e8cc482371065ef4)]: - - @cloudflare/workers-utils@0.46.0 - -## 0.2.2 - -### Patch Changes - -- Updated dependencies [[`aee2842`](https://github.com/cloudflare/workers-sdk/commit/aee2842bd1852b3187202f7746da5fd59ed36d44)]: - - @cloudflare/workers-utils@0.45.1 - -## 0.2.1 - -### Patch Changes - -- Updated dependencies [[`b9f1cdc`](https://github.com/cloudflare/workers-sdk/commit/b9f1cdc198533687f6b64ce72499a3ca04b2bf85), [`a0712e5`](https://github.com/cloudflare/workers-sdk/commit/a0712e578e45908ed5e46235828a434b49cf8f22)]: - - @cloudflare/workers-utils@0.45.0 - -## 0.2.0 - -### Minor Changes - -- [#15851](https://github.com/cloudflare/workers-sdk/pull/15851) [`74a520e`](https://github.com/cloudflare/workers-sdk/commit/74a520ea55c56e8f61764bfdcff1c5aceabcfefd) Thanks [@NuroDev](https://github.com/NuroDev)! - Add a `cwd` option to package installation helpers - - Package installations can now run in a specified working directory. npm package manifest updates also use that directory. - -### Patch Changes - -- Updated dependencies [[`8c4b8a3`](https://github.com/cloudflare/workers-sdk/commit/8c4b8a3ee8d2f6cc6df96338ee819d25a10a7394), [`8280086`](https://github.com/cloudflare/workers-sdk/commit/8280086df5571607ab614fa09684c2d78fcdd58b)]: - - @cloudflare/workers-utils@0.44.0 - -## 0.1.39 - -### Patch Changes - -- Updated dependencies [[`8f7916c`](https://github.com/cloudflare/workers-sdk/commit/8f7916cd72cd0f6a3bcef80abc8ad4509b13026a)]: - - @cloudflare/workers-utils@0.43.0 - -## 0.1.38 - -### Patch Changes - -- Updated dependencies [[`479e1e8`](https://github.com/cloudflare/workers-sdk/commit/479e1e8eaf05764da7950c42c38cff2a98f00e3f), [`15799d4`](https://github.com/cloudflare/workers-sdk/commit/15799d4b61adc6317a506d700846ebaeeb558095), [`bdda4c3`](https://github.com/cloudflare/workers-sdk/commit/bdda4c3b3c028d3d4dab5ea4c5af8040ed7ed1d8), [`fc3cbaa`](https://github.com/cloudflare/workers-sdk/commit/fc3cbaa4150a3cf30502286452153806bf8800d2)]: - - @cloudflare/workers-utils@0.42.0 - -## 0.1.37 - -### Patch Changes - -- Updated dependencies [[`8fade73`](https://github.com/cloudflare/workers-sdk/commit/8fade73f63289d3e4b64004669bca7e06d19c0e3)]: - - @cloudflare/workers-utils@0.41.2 - -## 0.1.36 - -### Patch Changes - -- Updated dependencies [[`59267fc`](https://github.com/cloudflare/workers-sdk/commit/59267fc79d1f7925a15369ca0125290df2404bfb)]: - - @cloudflare/workers-utils@0.41.1 - -## 0.1.35 - -### Patch Changes - -- Updated dependencies [[`45b3b81`](https://github.com/cloudflare/workers-sdk/commit/45b3b810809ee01cefbd53bea3a5ebc50bdb1c6c), [`95af41d`](https://github.com/cloudflare/workers-sdk/commit/95af41d564f7476cdda8c5923208c3b8a3ec2a11)]: - - @cloudflare/workers-utils@0.41.0 - -## 0.1.34 - -### Patch Changes - -- Updated dependencies [[`c4c9b75`](https://github.com/cloudflare/workers-sdk/commit/c4c9b75c54a095dc4b7ac82e44330f5650a2e4ac)]: - - @cloudflare/workers-utils@0.40.1 - -## 0.1.33 - -### Patch Changes - -- Updated dependencies [[`6874aa9`](https://github.com/cloudflare/workers-sdk/commit/6874aa978144469927831de59834e8cdc47a5114)]: - - @cloudflare/workers-utils@0.40.0 - -## 0.1.32 - -### Patch Changes - -- Updated dependencies [[`9515011`](https://github.com/cloudflare/workers-sdk/commit/9515011dc5ecdc5abf3a0c685d80f78e307fb513)]: - - @cloudflare/workers-utils@0.39.1 - -## 0.1.31 - -### Patch Changes - -- Updated dependencies [[`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78), [`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78), [`cb0955f`](https://github.com/cloudflare/workers-sdk/commit/cb0955f274102afb30b8502193edf66c0d3cb4d6), [`fa79b26`](https://github.com/cloudflare/workers-sdk/commit/fa79b26ef442303797013c70078c7acdd2c79247), [`ca71205`](https://github.com/cloudflare/workers-sdk/commit/ca71205bb45d9182e6c748e7097baed67739a891), [`a83d7ac`](https://github.com/cloudflare/workers-sdk/commit/a83d7ac4d4d52811e11b61753aa60c10ca5c8c78)]: - - @cloudflare/workers-utils@0.39.0 - -## 0.1.30 - -### Patch Changes - -- Updated dependencies [[`60d40f8`](https://github.com/cloudflare/workers-sdk/commit/60d40f88e6109ef31aa13a9feb15f5d64b3ffe1d)]: - - @cloudflare/workers-utils@0.38.1 - -## 0.1.29 - -### Patch Changes - -- Updated dependencies [[`36aed7f`](https://github.com/cloudflare/workers-sdk/commit/36aed7f0f2db5056af9df917cf6c22a2be950b1e), [`bff525d`](https://github.com/cloudflare/workers-sdk/commit/bff525d66dd3785481148353d782dd33c3a644ed)]: - - @cloudflare/workers-utils@0.38.0 - -## 0.1.28 - -### Patch Changes - -- Updated dependencies [[`a849e0d`](https://github.com/cloudflare/workers-sdk/commit/a849e0d6d2253034fc158d5442c5124e77a39bd9)]: - - @cloudflare/workers-utils@0.37.0 - -## 0.1.27 - -### Patch Changes - -- Updated dependencies [[`fd17fc5`](https://github.com/cloudflare/workers-sdk/commit/fd17fc5c5fb86423e37ff5b142391e03cd7dbf59)]: - - @cloudflare/workers-utils@0.36.0 - -## 0.1.26 - -### Patch Changes - -- Updated dependencies [[`dbbb795`](https://github.com/cloudflare/workers-sdk/commit/dbbb795c47ff663857b605b484c63730e1e3ff45), [`b3f2628`](https://github.com/cloudflare/workers-sdk/commit/b3f26289a735279e463fb4802d4a4481cfaaac71), [`ea28cc3`](https://github.com/cloudflare/workers-sdk/commit/ea28cc33e5d39031e9bf512e17f3a57cccbd3f46)]: - - @cloudflare/workers-utils@0.35.0 - -## 0.1.25 - -### Patch Changes - -- Updated dependencies [[`59872c4`](https://github.com/cloudflare/workers-sdk/commit/59872c41d4417d9b8c2efddb4b35662453efcaae), [`c68f9cb`](https://github.com/cloudflare/workers-sdk/commit/c68f9cb866a2eae4416d20f584f733527189f18a), [`5c10e39`](https://github.com/cloudflare/workers-sdk/commit/5c10e398979c0a054f58dcf2751012cc99e977d2), [`39dcea6`](https://github.com/cloudflare/workers-sdk/commit/39dcea6c9362e2d651e3108fa769dbbc32db5a7b)]: - - @cloudflare/workers-utils@0.34.0 - -## 0.1.24 - -### Patch Changes - -- Updated dependencies [[`fb6b51b`](https://github.com/cloudflare/workers-sdk/commit/fb6b51b87bf73edca9866bdf2d0810d7bf491108), [`1b73c87`](https://github.com/cloudflare/workers-sdk/commit/1b73c879c168dcc78b0f2657d04bc784b8af7da3)]: - - @cloudflare/workers-utils@0.33.1 - -## 0.1.23 - -### Patch Changes - -- Updated dependencies [[`d0c976c`](https://github.com/cloudflare/workers-sdk/commit/d0c976c04ad890fcef56305ded11f1405e89273e)]: - - @cloudflare/workers-utils@0.33.0 - -## 0.1.22 - -### Patch Changes - -- Updated dependencies [[`0aa8fa5`](https://github.com/cloudflare/workers-sdk/commit/0aa8fa5e12bc64facb4e9fece321a762269d0357)]: - - @cloudflare/workers-utils@0.32.0 - -## 0.1.21 - -### Patch Changes - -- Updated dependencies [[`8cf78c8`](https://github.com/cloudflare/workers-sdk/commit/8cf78c83cb4c64be8b458d7bd618b47e7c6e7d25), [`6946da1`](https://github.com/cloudflare/workers-sdk/commit/6946da1123f3c8484af80ec4f5426c5fe0bbdb34)]: - - @cloudflare/workers-utils@0.31.2 - -## 0.1.20 - -### Patch Changes - -- Updated dependencies [[`b5c083b`](https://github.com/cloudflare/workers-sdk/commit/b5c083bf601d71bad82ccc044df55ba4584085e2)]: - - @cloudflare/workers-utils@0.31.1 - -## 0.1.19 - -### Patch Changes - -- Updated dependencies [[`5a56dda`](https://github.com/cloudflare/workers-sdk/commit/5a56ddaf8548fe79787482506b3d5e0233c329c6)]: - - @cloudflare/workers-utils@0.31.0 - -## 0.1.18 - -### Patch Changes - -- Updated dependencies [[`5e6556a`](https://github.com/cloudflare/workers-sdk/commit/5e6556a0c788679b6ac149ba3018a2cfd7cc73e9)]: - - @cloudflare/workers-utils@0.30.0 - -## 0.1.17 - -### Patch Changes - -- Updated dependencies [[`552bcfc`](https://github.com/cloudflare/workers-sdk/commit/552bcfc8d44f8625b09dfd5d821c132b626cb7bb)]: - - @cloudflare/workers-utils@0.29.0 - -## 0.1.16 - -### Patch Changes - -- Updated dependencies [[`2b390d7`](https://github.com/cloudflare/workers-sdk/commit/2b390d7831ff27aa13cdf05aa8e11e4c0086f924), [`a6c214f`](https://github.com/cloudflare/workers-sdk/commit/a6c214fb311215b1ed09b273171b7995033fb7d7)]: - - @cloudflare/workers-utils@0.28.0 - -## 0.1.15 - -### Patch Changes - -- [#14499](https://github.com/cloudflare/workers-sdk/pull/14499) [`8cd805d`](https://github.com/cloudflare/workers-sdk/commit/8cd805db2f9901cba52d574b385577bafd595cb5) Thanks [@colinhacks](https://github.com/colinhacks)! - Detect the `nub` package manager - - C3 resolves the invoking package manager with `which-pm-runs`, which already returns `nub`, but `detectPackageManager` had no `nub` case in its switch, so it fell through to the npm default and produced npm commands. `detectPackageManager` now maps `nub` to its `nub`/`nubx` executables, and `@cloudflare/cli-shared-helpers`'s package-install helpers accept `nub` as a package manager. - -- Updated dependencies []: - - @cloudflare/workers-utils@0.27.0 - -## 0.1.14 - -### Patch Changes - -- Updated dependencies [[`42df9bb`](https://github.com/cloudflare/workers-sdk/commit/42df9bbf07e37032a3e61027e33d504d74a25ccd)]: - - @cloudflare/workers-utils@0.27.0 - -## 0.1.13 - -### Patch Changes - -- Updated dependencies [[`0283a1f`](https://github.com/cloudflare/workers-sdk/commit/0283a1fcdc635244f731010422e513e8b4ab0be3)]: - - @cloudflare/workers-utils@0.26.0 - -## 0.1.12 - -### Patch Changes - -- Updated dependencies [[`aad35b7`](https://github.com/cloudflare/workers-sdk/commit/aad35b79d07df1bb764a4a5912d6b4328a34474b), [`1ac96a1`](https://github.com/cloudflare/workers-sdk/commit/1ac96a14b7fb022acada114ab8793fe8a4ba79a5), [`1ca8d8f`](https://github.com/cloudflare/workers-sdk/commit/1ca8d8f0bbd012a1d65cabadf7b6987b252775e9)]: - - @cloudflare/workers-utils@0.25.1 - -## 0.1.11 - -### Patch Changes - -- Updated dependencies [[`aa5d580`](https://github.com/cloudflare/workers-sdk/commit/aa5d5801450b7e4417bfdbd477f86de3a4bc6933)]: - - @cloudflare/workers-utils@0.25.0 - -## 0.1.10 - -### Patch Changes - -- Updated dependencies [[`cfd6205`](https://github.com/cloudflare/workers-sdk/commit/cfd6205fe86f6afd74b5881f09524c93c83b8359), [`cfd6205`](https://github.com/cloudflare/workers-sdk/commit/cfd6205fe86f6afd74b5881f09524c93c83b8359)]: - - @cloudflare/workers-utils@0.24.0 - -## 0.1.9 - -### Patch Changes - -- Updated dependencies [[`673b09e`](https://github.com/cloudflare/workers-sdk/commit/673b09e0fa26368125fb527596a8eb5d31c27302), [`5dfb788`](https://github.com/cloudflare/workers-sdk/commit/5dfb788595a2104b4b0922cfce3d69a2f1d881eb)]: - - @cloudflare/workers-utils@0.23.2 - -## 0.1.8 - -### Patch Changes - -- Updated dependencies [[`ecfdd5a`](https://github.com/cloudflare/workers-sdk/commit/ecfdd5a6c60b9c6f99c28f9294da656933c2a5fd)]: - - @cloudflare/workers-utils@0.23.1 - -## 0.1.7 - -### Patch Changes - -- Updated dependencies [[`c6c61b5`](https://github.com/cloudflare/workers-sdk/commit/c6c61b59431443b2bcda25f3af7624dd2ce19b9b), [`b502d54`](https://github.com/cloudflare/workers-sdk/commit/b502d5445b9e9e030020a3d65c0334507393aa64), [`c4f45e8`](https://github.com/cloudflare/workers-sdk/commit/c4f45e8b8694c60fb1808f7fbb130e4b4893d20c)]: - - @cloudflare/workers-utils@0.23.0 - -## 0.1.6 - -### Patch Changes - -- [#14112](https://github.com/cloudflare/workers-sdk/pull/14112) [`3a746ac`](https://github.com/cloudflare/workers-sdk/commit/3a746ac56a40b805e38f26ef5328e44917b543e6) Thanks [@penalosa](https://github.com/penalosa)! - Pin non-bundled runtime dependencies to exact versions - - Dependencies that are not bundled into a package's published output are installed directly into consumers' dependency trees, so they are now pinned to exact versions instead of semver ranges. This closes a supply-chain gap where an unpinned external dependency could resolve to a compromised upstream release on a fresh install. A new `pnpm check:pinned-deps` lint enforces this for all published packages (and for the shared pnpm catalog) going forward. - -- Updated dependencies [[`e86489a`](https://github.com/cloudflare/workers-sdk/commit/e86489a5743ff9bad7bcb5b444ad3d952d5b0164), [`337e912`](https://github.com/cloudflare/workers-sdk/commit/337e9124cfa461a99ce7ffb800dcc341f7b2f026), [`65b5f9e`](https://github.com/cloudflare/workers-sdk/commit/65b5f9e1855651c2df2c1bdfc8930141e36413d5)]: - - @cloudflare/workers-utils@0.22.1 - -## 0.1.5 - -### Patch Changes - -- Updated dependencies [[`e3c862a`](https://github.com/cloudflare/workers-sdk/commit/e3c862a99f9b633ca288306eae8a8c3a900590ee), [`599b27a`](https://github.com/cloudflare/workers-sdk/commit/599b27aafb9bc432524a35eb4e5a414de21bef41), [`e3c862a`](https://github.com/cloudflare/workers-sdk/commit/e3c862a99f9b633ca288306eae8a8c3a900590ee), [`e3c862a`](https://github.com/cloudflare/workers-sdk/commit/e3c862a99f9b633ca288306eae8a8c3a900590ee)]: - - @cloudflare/workers-utils@0.22.0 - -## 0.1.4 - -### Patch Changes - -- Updated dependencies [[`90092c0`](https://github.com/cloudflare/workers-sdk/commit/90092c0bca526e2e08a25fe7969534426eb6fd9f)]: - - @cloudflare/workers-utils@0.21.1 - -## 0.1.3 - -### Patch Changes - -- Updated dependencies [[`248bc08`](https://github.com/cloudflare/workers-sdk/commit/248bc08152cf9f792d98c8c78f8fb1417b1bb3b3)]: - - @cloudflare/workers-utils@0.21.0 - -## 0.1.2 - -### Patch Changes - -- Updated dependencies [[`f3fed88`](https://github.com/cloudflare/workers-sdk/commit/f3fed8859b612d424388fe45a1d638cf6b1c42c7)]: - - @cloudflare/workers-utils@0.20.0 - -## 0.1.1 - -### Patch Changes - -- Updated dependencies [[`2b8c0cc`](https://github.com/cloudflare/workers-sdk/commit/2b8c0ccb9ede7487bd96cfc51b3262a717bb532c)]: - - @cloudflare/workers-utils@0.19.0 - -## 0.1.0 - -### Minor Changes - -- [#13651](https://github.com/cloudflare/workers-sdk/pull/13651) [`47ac63f`](https://github.com/cloudflare/workers-sdk/commit/47ac63f05ca86d781110490ff21ff88f2828fbbf) Thanks [@penalosa](https://github.com/penalosa)! - Publish `@cloudflare/cli-shared-helpers` and `@cloudflare/workers-utils` to npm - -### Patch Changes - -- Updated dependencies [[`5680287`](https://github.com/cloudflare/workers-sdk/commit/56802879641c123ee11160d77ecaf104915cd826), [`47ac63f`](https://github.com/cloudflare/workers-sdk/commit/47ac63f05ca86d781110490ff21ff88f2828fbbf)]: - - @cloudflare/workers-utils@0.18.0 - -## 1.4.0 - -### Minor Changes - -- [#13144](https://github.com/cloudflare/workers-sdk/pull/13144) [`db60b94`](https://github.com/cloudflare/workers-sdk/commit/db60b94d9620e7608df3e98876d5df4fde952ecf) Thanks [@dario-piotrowicz](https://github.com/dario-piotrowicz)! - Add gitignore helpers for appending Wrangler-related entries - - New `maybeAppendWranglerToGitIgnore` and `maybeAppendWranglerToGitIgnoreLikeFile` functions that automatically append Wrangler-related entries (`.wrangler`, `.dev.vars*`, `.env*`, and their negated example patterns) to `.gitignore` or similar ignore files. Existing entries are detected and skipped to avoid duplicates. - -## 1.3.0 - -### Minor Changes - -- [#13068](https://github.com/cloudflare/workers-sdk/pull/13068) [`e631a94`](https://github.com/cloudflare/workers-sdk/commit/e631a946466ded834763497d094da9e93d3d3721) Thanks [@dario-piotrowicz](https://github.com/dario-piotrowicz)! - Add `runCommand` and `quoteShellArgs`, `installPackages` and `installWrangler` utilities to `@cloudflare/cli/command` - - These utilities are now available from `@cloudflare/cli` as dedicated sub-path exports: `runCommand` and `quoteShellArgs` via `@cloudflare/cli/command`, and `installPackages` and `installWrangler` via `@cloudflare/cli/packages`. This makes them reusable across packages in the SDK without duplication. - -## 1.2.1 - -### Patch Changes - -- [#11940](https://github.com/cloudflare/workers-sdk/pull/11940) [`69ff962`](https://github.com/cloudflare/workers-sdk/commit/69ff9620487a6ae979f369eb1dbac887ce46e246) Thanks [@penalosa](https://github.com/penalosa)! - Mark macOS version compatibility errors as user errors - - When checking macOS version compatibility, the CLI now throws `UserError` instead of generic `Error`. This ensures that version incompatibility issues are properly classified as user-facing errors that shouldn't be reported to Sentry. - -- [#11967](https://github.com/cloudflare/workers-sdk/pull/11967) [`202c59e`](https://github.com/cloudflare/workers-sdk/commit/202c59e4f4f28419fb6ac0aa8c7dc3960a0c8d3e) Thanks [@emily-shen](https://github.com/emily-shen)! - chore: update undici - - The following dependency versions have been updated: - - | Dependency | From | To | - | ---------- | ------ | ------ | - | undici | 7.14.0 | 7.18.2 | - -## 1.2.0 - -### Minor Changes - -- [#11578](https://github.com/cloudflare/workers-sdk/pull/11578) [`4201472`](https://github.com/cloudflare/workers-sdk/commit/4201472291fa1c864dbcca40c173a76e5b571a04) Thanks [@gpanders](https://github.com/gpanders)! - Add showCursor helper function to show or hide the cursor in the terminal - -## 1.1.4 - -### Patch Changes - -- [#11448](https://github.com/cloudflare/workers-sdk/pull/11448) [`2b4813b`](https://github.com/cloudflare/workers-sdk/commit/2b4813b18076817bb739491246313c32b403651f) Thanks [@edmundhung](https://github.com/edmundhung)! - Builds package with esbuild `v0.27.0` - -## 1.1.3 - -### Patch Changes - -- [#10764](https://github.com/cloudflare/workers-sdk/pull/10764) [`79a6b7d`](https://github.com/cloudflare/workers-sdk/commit/79a6b7dd811fea5a413b084fcd281915a418a85a) Thanks [@emily-shen](https://github.com/emily-shen)! - fix: respect the log level set by wrangler when logging using @cloudflare/cli - -## 1.1.2 - -### Patch Changes - -- [#10492](https://github.com/cloudflare/workers-sdk/pull/10492) [`8ae9323`](https://github.com/cloudflare/workers-sdk/commit/8ae9323a5c45f3efe3685e36b1536cc25d39fbfb) Thanks [@gpanders](https://github.com/gpanders)! - Include cursor in text prompts - -## 1.1.1 - -### Patch Changes - -- [#4768](https://github.com/cloudflare/workers-sdk/pull/4768) [`c3e410c2`](https://github.com/cloudflare/workers-sdk/commit/c3e410c2797f5c59b9ea0f63c20feef643366df2) Thanks [@petebacondarwin](https://github.com/petebacondarwin)! - ci: bump undici versions to 5.28.2 - -## 1.1.0 - -### Minor Changes - -- [#4779](https://github.com/cloudflare/workers-sdk/pull/4779) [`06bb99e1`](https://github.com/cloudflare/workers-sdk/commit/06bb99e1c91ffe5305343a17353912e734f5bd0c) Thanks [@1000hz](https://github.com/1000hz)! - Added a new `SelectRefreshablePrompt` component - - This component supports infinite scrolling, and the ability to refresh the items on 'R' keypress. See [#4310](https://github.com/cloudflare/workers-sdk/pull/4310) for more details. - -* [#4779](https://github.com/cloudflare/workers-sdk/pull/4779) [`06bb99e1`](https://github.com/cloudflare/workers-sdk/commit/06bb99e1c91ffe5305343a17353912e734f5bd0c) Thanks [@1000hz](https://github.com/1000hz)! - Added `@clack/core`'s `MultiSelectPrompt` component - - See [#4310](https://github.com/cloudflare/workers-sdk/pull/4310) for more details. - -- [#4779](https://github.com/cloudflare/workers-sdk/pull/4779) [`06bb99e1`](https://github.com/cloudflare/workers-sdk/commit/06bb99e1c91ffe5305343a17353912e734f5bd0c) Thanks [@1000hz](https://github.com/1000hz)! - Added `processArguments` helper function - - See [#4310](https://github.com/cloudflare/workers-sdk/pull/4310) for more details. - -### Patch Changes - -- [#4779](https://github.com/cloudflare/workers-sdk/pull/4779) [`06bb99e1`](https://github.com/cloudflare/workers-sdk/commit/06bb99e1c91ffe5305343a17353912e734f5bd0c) Thanks [@1000hz](https://github.com/1000hz)! - Downgraded `chalk` dependency from `^5.2.0` to `^2.4.2` - - This was done for compatibility reasons with the version used in the `wrangler` package. See [#4310](https://github.com/cloudflare/workers-sdk/pull/4310) for more details. - -## 1.0.0 - -### Major Changes - -- [#4189](https://github.com/cloudflare/workers-sdk/pull/4189) [`05798038`](https://github.com/cloudflare/workers-sdk/commit/05798038c85a83afb2c0e8ea9533c31a6fbe3e91) Thanks [@gabivlj](https://github.com/gabivlj)! - Move helper cli files of C3 into @cloudflare/cli and make Wrangler and C3 depend on it - -### Patch Changes - -- [#4271](https://github.com/cloudflare/workers-sdk/pull/4271) [`70016b2b`](https://github.com/cloudflare/workers-sdk/commit/70016b2bb514ea95f1ce0db3582e194c31df4c14) Thanks [@gabivlj](https://github.com/gabivlj)! - change backgrounds of statuses from red to more appropriate ones diff --git a/packages/cli/README.md b/packages/cli/README.md deleted file mode 100644 index 5398f1771c..0000000000 --- a/packages/cli/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Cloudflare CLI - -> Internal utility package for workers-sdk. Not intended for external use — APIs may change without notice. - -All things related to rendering the CLI for workers-sdk. diff --git a/packages/cli/__tests__/check-macos-version.test.ts b/packages/cli/__tests__/check-macos-version.test.ts deleted file mode 100644 index 6cd77a703b..0000000000 --- a/packages/cli/__tests__/check-macos-version.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -import os from "node:os"; -import ci from "ci-info"; -import { beforeEach, describe, it, vi } from "vitest"; -import { checkMacOSVersion } from "../check-macos-version"; - -vi.mock("node:os"); -vi.mock("ci-info", () => ({ - default: { isCI: false }, - isCI: false, -})); - -const mockOs = vi.mocked(os); - -describe("checkMacOSVersion", () => { - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(ci).isCI = false; - }); - - it("should not throw on non-macOS platforms", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("linux"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should not throw on macOS 13.5.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("22.6.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should not throw on macOS 14.0.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("23.0.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should not throw on macOS 13.6.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("22.7.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should throw error on macOS 12.7.6", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("21.6.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).toThrow( - "Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (12.6.0)" - ); - }); - - it("should throw error on macOS 13.4.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("22.4.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).toThrow( - "Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (13.4.0)" - ); - }); - - it("should handle invalid Darwin version format gracefully", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("invalid-version"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should handle very old Darwin versions gracefully", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("19.6.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); - - it("should not throw when running in CI", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - vi.mocked(ci).isCI = true; - mockOs.release.mockReturnValue("21.6.0"); - - expect(() => checkMacOSVersion({ shouldThrow: true })).not.toThrow(); - }); -}); - -describe("checkMacOSVersion with shouldThrow=false", () => { - beforeEach(() => { - vi.clearAllMocks(); - vi.mocked(ci).isCI = false; - }); - - it("should not warn on non-macOS platforms", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("linux"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).not.toHaveBeenCalled(); - }); - - it("should not warn on macOS 13.5.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("22.6.0"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).not.toHaveBeenCalled(); - }); - - it("should warn on macOS 12.7.6", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("21.6.0"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining( - "⚠️ Warning: Unsupported macOS version detected (12.6.0)" - ) - ); - }); - - it("should warn on macOS 13.4.0", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("22.4.0"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).toHaveBeenCalledWith( - expect.stringContaining( - "⚠️ Warning: Unsupported macOS version detected (13.4.0)" - ) - ); - }); - - it("should not warn when running in CI", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - vi.mocked(ci).isCI = true; - mockOs.release.mockReturnValue("21.6.0"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).not.toHaveBeenCalled(); - }); - - it("should not warn on invalid Darwin version format", ({ expect }) => { - vi.spyOn(process, "platform", "get").mockReturnValue("darwin"); - mockOs.release.mockReturnValue("invalid-version"); - const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); - - checkMacOSVersion({ shouldThrow: false }); - - expect(warnSpy).not.toHaveBeenCalled(); - }); -}); diff --git a/packages/cli/__tests__/cli.test.ts b/packages/cli/__tests__/cli.test.ts deleted file mode 100644 index ea3e3a272b..0000000000 --- a/packages/cli/__tests__/cli.test.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { describe, test } from "vitest"; -import { space } from ".."; - -describe("cli", () => { - test("test spaces", ({ expect }) => { - expect(space(300)).toMatchInlineSnapshot( - '"                                                                                                                                                                                                                                                                                                            "' - ); - }); -}); diff --git a/packages/cli/__tests__/command.test.ts b/packages/cli/__tests__/command.test.ts deleted file mode 100644 index 5491069479..0000000000 --- a/packages/cli/__tests__/command.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { spawn } from "cross-spawn"; -import { afterEach, beforeEach, describe, test, vi } from "vitest"; -import { quoteShellArgs, runCommand } from "../command"; -import type { ChildProcess } from "node:child_process"; - -// We can change how the mock spawn works by setting these variables -let spawnResultCode = 0; -let spawnStdout: string | undefined = undefined; -let spawnStderr: string | undefined = undefined; - -vi.mock("cross-spawn"); - -describe("Command Helpers", () => { - afterEach(() => { - spawnResultCode = 0; - spawnStdout = undefined; - spawnStderr = undefined; - }); - - beforeEach(() => { - vi.mocked(spawn).mockImplementation(() => { - return { - on: vi.fn().mockImplementation((event, cb) => { - if (event === "close") { - cb(spawnResultCode); - } - }), - stdout: { - on(_event: "data", cb: (data: string) => void) { - if (spawnStdout !== undefined) { - cb(spawnStdout); - } - }, - }, - stderr: { - on(_event: "data", cb: (data: string) => void) { - if (spawnStderr !== undefined) { - cb(spawnStderr); - } - }, - }, - } as unknown as ChildProcess; - }); - }); - - test("runCommand", async ({ expect }) => { - await runCommand(["ls", "-l"]); - expect(spawn).toHaveBeenCalledWith("ls", ["-l"], { - stdio: "inherit", - env: process.env, - signal: expect.any(AbortSignal), - }); - }); - - describe("quoteShellArgs", () => { - test.runIf(process.platform !== "win32")("mac", async ({ expect }) => { - expect(quoteShellArgs([`pages:dev`])).toEqual("pages:dev"); - expect(quoteShellArgs([`24.02 foo-bar`])).toEqual(`'24.02 foo-bar'`); - expect(quoteShellArgs([`foo/10 bar/20-baz/`])).toEqual( - `'foo/10 bar/20-baz/'` - ); - }); - - test.runIf(process.platform === "win32")("windows", async ({ expect }) => { - expect(quoteShellArgs([`pages:dev`])).toEqual("pages:dev"); - expect(quoteShellArgs([`24.02 foo-bar`])).toEqual(`"24.02 foo-bar"`); - expect(quoteShellArgs([`foo/10 bar/20-baz/`])).toEqual( - `"foo/10 bar/20-baz/"` - ); - }); - }); -}); diff --git a/packages/cli/__tests__/gitignore.test.ts b/packages/cli/__tests__/gitignore.test.ts deleted file mode 100644 index 90aa28e84f..0000000000 --- a/packages/cli/__tests__/gitignore.test.ts +++ /dev/null @@ -1,445 +0,0 @@ -import { appendFileSync, existsSync, statSync, writeFileSync } from "node:fs"; -import { readFileSync } from "@cloudflare/workers-utils"; -import { beforeEach, describe, test, vi } from "vitest"; -import { - maybeAppendWranglerToGitIgnore, - maybeAppendWranglerToGitIgnoreLikeFile, -} from "../gitignore"; -import type { PathLike } from "node:fs"; -import type { Mock } from "vitest"; - -vi.mock("node:fs"); -vi.mock("@cloudflare/workers-utils"); -vi.mock("../interactive", () => ({ - spinner: () => ({ - start: vi.fn(), - stop: vi.fn(), - update: vi.fn(), - }), -})); - -describe("maybeAppendWranglerToGitIgnoreLikeFile", () => { - let writeFileSyncMock: Mock; - let appendFileSyncMock: Mock; - - beforeEach(() => { - vi.resetAllMocks(); - - writeFileSyncMock = vi.mocked(writeFileSync); - appendFileSyncMock = vi.mocked(appendFileSync); - }); - - test("should append the wrangler section to a standard gitignore file", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .vscode` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - - # wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should not touch the file if it already contains all wrangler files", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .dev.vars* - !.dev.vars.example - .env* - !.env.example - .vscode - .wrangler - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock).not.toHaveBeenCalled(); - }); - - test("should not touch the file if it contains all wrangler files (and can cope with comments)", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .wrangler # This is for wrangler - .dev.vars* # this is for wrangler and getPlatformProxy - !.dev.vars.example # more comments - .env* # even more - !.env.example # and a final one - .vscode - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock).not.toHaveBeenCalled(); - }); - - test("should append to the file the missing wrangler files when some are already present (should add the section heading if including .wrangler and some others)", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .dev.vars* - .vscode` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - - # wrangler files - .wrangler - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should append to the file the missing wrangler files when some are already present (should not add the section heading if .wrangler already exists)", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .wrangler - .dev.vars* - .vscode` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should append to the file the missing wrangler files when some are already present (should not add the section heading if only adding .wrangler)", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .dev.vars* - !.dev.vars.example - .env* - !.env.example - .vscode` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - - .wrangler - ", - ], - ] - `); - }); - - test("when it appends to the file it doesn't include an empty line only if there was one already", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .dev.vars* - !.dev.vars.example - .env* - !.env.example - .vscode - - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - .wrangler - ", - ], - ] - `); - }); - - test("should create the file if it didn't exist already", ({ expect }) => { - mockIgnoreFile("my-project/.gitignore", ""); - // pretend that the file doesn't exist - vi.mocked(existsSync).mockImplementation(() => false); - - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - // writeFile wrote the (empty) file - expect(writeFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - "", - ], - ] - `); - - // and the correct lines were then added to it - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - "# wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should add the wildcard .dev.vars* entry even if a .dev.vars is already included", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .dev.vars - .vscode - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - # wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should not add the .env entries if some form of .env entries are already included", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - .env - .env.* - !.env.example - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - # wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - ", - ], - ] - `); - }); - - test("should not add the .wrangler entry if a .wrangler/ is already included", ({ - expect, - }) => { - mockIgnoreFile( - "my-project/.gitignore", - ` - node_modules - .wrangler/ # This is for wrangler - .vscode - ` - ); - maybeAppendWranglerToGitIgnoreLikeFile("my-project/.gitignore"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - function mockIgnoreFile(path: string, content: string) { - vi.mocked(existsSync).mockImplementation( - (filePath: PathLike) => filePath === path - ); - vi.mocked(readFileSync).mockImplementation((filePath: string) => - filePath === path ? content.replace(/\n\s*/g, "\n") : "" - ); - } -}); - -describe("maybeAppendWranglerToGitIgnore", () => { - let appendFileSyncMock: Mock; - - beforeEach(() => { - vi.resetAllMocks(); - - appendFileSyncMock = vi.mocked(appendFileSync); - - vi.mocked(statSync).mockImplementation(((path: string) => ({ - isDirectory() { - return path.endsWith(".git"); - }, - })) as typeof statSync); - }); - - test("should not create the gitignore file if neither the .git directory not the .gitingore file exist", ({ - expect, - }) => { - // no .gitignore file exists - vi.mocked(existsSync).mockImplementation(() => false); - // neither a .git directory does - vi.mocked(statSync).mockImplementation(() => { - throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); - }); - - maybeAppendWranglerToGitIgnore("my-project"); - - expect(vi.mocked(writeFileSync)).not.toHaveBeenCalled(); - expect(appendFileSyncMock).not.toHaveBeenCalled(); - }); - - test("should create a .gitignore file when .git directory exists", ({ - expect, - }) => { - // no .gitignore file exists - vi.mocked(existsSync).mockImplementation(() => false); - vi.mocked(readFileSync).mockImplementation(() => ""); - - maybeAppendWranglerToGitIgnore("my-project"); - - // writeFileSync created the (empty) file - expect(vi.mocked(writeFileSync).mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - "", - ], - ] - `); - - // and the correct wrangler lines were appended to it - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - "# wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); - - test("should append wrangler entries when the .gitignore file exists but the .git directory does not", ({ - expect, - }) => { - // .gitignore exists - vi.mocked(existsSync).mockImplementation( - (filePath: PathLike) => filePath === "my-project/.gitignore" - ); - vi.mocked(readFileSync).mockImplementation((filePath: string) => - filePath === "my-project/.gitignore" ? "\nnode_modules\n.vscode\n" : "" - ); - // .git directory does NOT exist - vi.mocked(statSync).mockImplementation(() => { - throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); - }); - - maybeAppendWranglerToGitIgnore("my-project"); - - expect(appendFileSyncMock.mock.calls).toMatchInlineSnapshot(` - [ - [ - "my-project/.gitignore", - " - # wrangler files - .wrangler - .dev.vars* - !.dev.vars.example - .env* - !.env.example - ", - ], - ] - `); - }); -}); diff --git a/packages/cli/__tests__/packages.test.ts b/packages/cli/__tests__/packages.test.ts deleted file mode 100644 index a1e9808198..0000000000 --- a/packages/cli/__tests__/packages.test.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { writeFile } from "node:fs/promises"; -import { resolve } from "node:path"; -import { parsePackageJSON, readFileSync } from "@cloudflare/workers-utils"; -import { afterEach, describe, test, vi } from "vitest"; -import { runCommand } from "../command"; -import { installPackages, installWrangler } from "../packages"; - -vi.mock("../command"); -vi.mock("@cloudflare/workers-utils", () => ({ - readFileSync: vi.fn(), - parsePackageJSON: vi.fn(), -})); -vi.mock("node:fs/promises", () => ({ - writeFile: vi.fn(), -})); - -describe("Package Helpers", () => { - afterEach(() => { - vi.clearAllMocks(); - }); - - describe("installPackages", async () => { - type TestCase = { - pm: "npm" | "pnpm" | "yarn" | "bun"; - initialArgs: string[]; - additionalArgs?: string[]; - }; - - const cases: TestCase[] = [ - { pm: "npm", initialArgs: ["npm", "install"] }, - { pm: "pnpm", initialArgs: ["pnpm", "install"] }, - { pm: "bun", initialArgs: ["bun", "add"] }, - { pm: "yarn", initialArgs: ["yarn", "add"] }, - ]; - - test.for(cases)( - "with $pm", - async ({ pm, initialArgs, additionalArgs }, { expect }) => { - const mockPkgJson = { - dependencies: { - foo: "^1.0.0", - bar: "^2.0.0", - baz: "^1.2.3", - }, - }; - vi.mocked(readFileSync).mockReturnValue(JSON.stringify(mockPkgJson)); - vi.mocked(parsePackageJSON).mockReturnValue(mockPkgJson); - - const packages = ["foo", "bar@latest", "baz@1.2.3"]; - await installPackages(pm, packages); - - expect(vi.mocked(runCommand)).toHaveBeenCalledWith( - [...initialArgs, ...packages, ...(additionalArgs ?? [])], - expect.anything() - ); - - if (pm === "npm") { - const writeFileCall = vi.mocked(writeFile).mock.calls[0]; - expect(writeFileCall[0]).toBe(resolve(process.cwd(), "package.json")); - expect(JSON.parse(writeFileCall[1] as string)).toMatchObject({ - dependencies: { - foo: "^1.0.0", - bar: "^2.0.0", - baz: "1.2.3", - }, - }); - } - } - ); - - const devCases: TestCase[] = [ - { pm: "npm", initialArgs: ["npm", "install", "--save-dev"] }, - { pm: "pnpm", initialArgs: ["pnpm", "install", "--save-dev"] }, - { pm: "bun", initialArgs: ["bun", "add", "-d"] }, - { pm: "yarn", initialArgs: ["yarn", "add", "-D"] }, - ]; - - test.for(devCases)( - "with $pm (dev = true)", - async ({ pm, initialArgs, additionalArgs }, { expect }) => { - const mockPkgJson = { - devDependencies: { - foo: "^1.0.0", - bar: "^2.0.0", - baz: "^1.2.3", - }, - }; - vi.mocked(readFileSync).mockReturnValue(JSON.stringify(mockPkgJson)); - vi.mocked(parsePackageJSON).mockReturnValue(mockPkgJson); - - const packages = ["foo", "bar@latest", "baz@1.2.3"]; - await installPackages(pm, packages, { dev: true }); - - expect(vi.mocked(runCommand)).toHaveBeenCalledWith( - [...initialArgs, ...packages, ...(additionalArgs ?? [])], - expect.anything() - ); - - if (pm === "npm") { - const writeFileCall = vi.mocked(writeFile).mock.calls[0]; - expect(writeFileCall[0]).toBe(resolve(process.cwd(), "package.json")); - expect(JSON.parse(writeFileCall[1] as string)).toMatchObject({ - devDependencies: { - foo: "^1.0.0", - bar: "^2.0.0", - baz: "1.2.3", - }, - }); - } - } - ); - - test("runs in the requested directory", async ({ expect }) => { - const cwd = resolve("project"); - const mockPkgJson = { - devDependencies: { - cf: "latest", - }, - }; - vi.mocked(readFileSync).mockReturnValue(JSON.stringify(mockPkgJson)); - vi.mocked(parsePackageJSON).mockReturnValue(mockPkgJson); - - await installPackages("npm", ["cf@latest"], { cwd, dev: true }); - - expect(vi.mocked(runCommand)).toHaveBeenCalledWith( - ["npm", "install", "--save-dev", "cf@latest"], - expect.objectContaining({ cwd }) - ); - expect(vi.mocked(writeFile)).toHaveBeenCalledWith( - resolve(cwd, "package.json"), - expect.any(String) - ); - }); - }); - - test("installWrangler", async ({ expect }) => { - const mockPkgJson = { - devDependencies: { - wrangler: "^4.0.0", - }, - }; - vi.mocked(readFileSync).mockReturnValue(JSON.stringify(mockPkgJson)); - vi.mocked(parsePackageJSON).mockReturnValue(mockPkgJson); - - await installWrangler("npm", false); - - expect(vi.mocked(runCommand)).toHaveBeenCalledWith( - ["npm", "install", "--save-dev", "wrangler@latest"], - expect.anything() - ); - }); - - test("installWrangler updates existing workers-types", async ({ expect }) => { - const mockPkgJson = { - devDependencies: { - "@cloudflare/workers-types": "^4.20241011.0", - wrangler: "^3.60.3", - }, - }; - vi.mocked(readFileSync).mockReturnValue(JSON.stringify(mockPkgJson)); - vi.mocked(parsePackageJSON).mockReturnValue(mockPkgJson); - - await installWrangler("npm", false); - - expect(vi.mocked(runCommand)).toHaveBeenCalledWith( - [ - "npm", - "install", - "--save-dev", - "wrangler@latest", - "@cloudflare/workers-types@latest", - ], - expect.anything() - ); - }); -}); diff --git a/packages/cli/args.ts b/packages/cli/args.ts deleted file mode 100644 index 2e1cf3a4be..0000000000 --- a/packages/cli/args.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { inputPrompt } from "./interactive"; -import type { Arg, PromptConfig } from "./interactive"; - -export const processArgument = async ( - args: Record, - name: string, - promptConfig: PromptConfig -) => { - const value = args[name]; - const result = await inputPrompt({ - ...promptConfig, - // Accept the default value if the arg is already set - acceptDefault: promptConfig.acceptDefault ?? value !== undefined, - defaultValue: value ?? promptConfig.defaultValue, - }); - - // Update value in args before returning the result - args[name] = result as Arg; - - return result; -}; diff --git a/packages/cli/check-macos-version.ts b/packages/cli/check-macos-version.ts deleted file mode 100644 index 41aa1866f8..0000000000 --- a/packages/cli/check-macos-version.ts +++ /dev/null @@ -1,109 +0,0 @@ -import os from "node:os"; -import { UserError } from "@cloudflare/workers-utils/errors"; -import ci from "ci-info"; - -/** - * Minimum macOS version required for workerd compatibility. - */ -const MINIMUM_MACOS_VERSION = "13.5.0"; - -/** - * Checks the current macOS version for workerd compatibility. - * - * This function is a no-op on non-Darwin platforms and in CI environments. - * - * @param options - Configuration object - * @param options.shouldThrow - If true, throws an error on unsupported versions. If false, logs a warning. - */ -export function checkMacOSVersion(options: { shouldThrow: boolean }): void { - if (process.platform !== "darwin") { - return; - } - - if (ci.isCI) { - return; - } - - const release = os.release(); - const macOSVersion = darwinVersionToMacOSVersion(release); - - if (macOSVersion && isVersionLessThan(macOSVersion, MINIMUM_MACOS_VERSION)) { - if (options.shouldThrow) { - throw new UserError( - `Unsupported macOS version: The Cloudflare Workers runtime cannot run on the current version of macOS (${macOSVersion}). ` + - `The minimum requirement is macOS ${MINIMUM_MACOS_VERSION}+. See https://github.com/cloudflare/workerd?tab=readme-ov-file#running-workerd ` + - `If you cannot upgrade your version of macOS, you could try running in a DevContainer setup with a supported version of Linux (glibc 2.35+ required).`, - { telemetryMessage: false } - ); - } else { - /* eslint-disable-next-line no-console -- this package has no logger to use - (TODO: disable the `no-console` rule on packages that do not use a logger) */ - console.warn( - `⚠️ Warning: Unsupported macOS version detected (${macOSVersion}). ` + - `The Cloudflare Workers runtime may not work correctly on macOS versions below ${MINIMUM_MACOS_VERSION}. ` + - `Consider upgrading to macOS ${MINIMUM_MACOS_VERSION}+ or using a DevContainer setup with a supported version of Linux (glibc 2.35+ required).` - ); - } - } -} - -/** - * Converts Darwin kernel version to macOS version. - * Darwin 21.x.x = macOS 12.x (Monterey) - * Darwin 22.x.x = macOS 13.x (Ventura) - * Darwin 23.x.x = macOS 14.x (Sonoma) - * etc. - */ -function darwinVersionToMacOSVersion(darwinVersion: string): string | null { - const match = darwinVersion.match(/^(\d+)\.(\d+)\.(\d+)/); - if (!match) { - return null; - } - - const major = parseInt(match[1], 10); - - if (major >= 20) { - const macOSMajor = major - 9; - const minor = parseInt(match[2], 10); - const patch = parseInt(match[3], 10); - return `${macOSMajor}.${minor}.${patch}`; - } - - return null; -} - -/** - * Simple semver comparison for major.minor.patch versions. - * Validates that both versions follow the M.m.p format before comparison. - */ -function isVersionLessThan(version1: string, version2: string): boolean { - const versionRegex = /^(\d+)\.(\d+)\.(\d+)$/; - - const match1 = version1.match(versionRegex); - const match2 = version2.match(versionRegex); - - if (!match1 || !match2) { - throw new Error( - `Invalid version format. Expected M.m.p format, got: ${version1}, ${version2}` - ); - } - - const [major1, minor1, patch1] = [ - parseInt(match1[1], 10), - parseInt(match1[2], 10), - parseInt(match1[3], 10), - ]; - const [major2, minor2, patch2] = [ - parseInt(match2[1], 10), - parseInt(match2[2], 10), - parseInt(match2[3], 10), - ]; - - if (major1 !== major2) { - return major1 < major2; - } - if (minor1 !== minor2) { - return minor1 < minor2; - } - return patch1 < patch2; -} diff --git a/packages/cli/colors.ts b/packages/cli/colors.ts deleted file mode 100644 index bd172dfc00..0000000000 --- a/packages/cli/colors.ts +++ /dev/null @@ -1,34 +0,0 @@ -import chalk from "chalk"; - -const { white, gray, dim, hidden, bold, cyanBright, bgCyan } = chalk; - -const brandColor = chalk.hex("#BD5B08"); - -const black = chalk.hex("#111"); -const blue = chalk.hex("#0E838F"); -const bgBlue = black.bgHex("#0E838F"); -const red = chalk.hex("#AB2526"); -const bgRed = black.bgHex("#AB2526"); -const green = chalk.hex("#218529"); -const bgGreen = black.bgHex("#218529"); -const yellow = chalk.hex("#7F7322"); -const bgYellow = black.bgHex("#7F7322"); - -export { - blue, - bgBlue, - green, - bgGreen, - red, - bgRed, - yellow, - bgYellow, - cyanBright, - bgCyan, - brandColor, - dim, - white, - gray, - hidden, - bold, -}; diff --git a/packages/cli/command.ts b/packages/cli/command.ts deleted file mode 100644 index e882dac00a..0000000000 --- a/packages/cli/command.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { spawn } from "cross-spawn"; -import { CancelError } from "./error"; -import { isInteractive, spinner } from "./interactive"; -import { stripAnsi } from "."; - -/** - * Command is a string array, like ['git', 'commit', '-m', '"Initial commit"'] - */ -type Command = string[]; - -export type RunOptions = { - startText?: string; - doneText?: string | ((output: string) => string); - silent?: boolean; - captureOutput?: boolean; - useSpinner?: boolean; - env?: NodeJS.ProcessEnv; - cwd?: string; - /** If defined this function is called to all you to transform the output from the command into a new string. */ - transformOutput?: (output: string) => string; -}; - -type PrintOptions = { - promise: Promise | (() => Promise); - useSpinner?: boolean; - startText: string; - doneText?: string | ((output: T) => string); -}; - -/** - * An awaitable wrapper around `spawn` that optionally displays progress to user and processes/captures the command's output - * - * @param command - The command to run as an array of strings - * @param opts.silent - Should the command's stdout and stderr be dispalyed to the user - * @param opts.captureOutput - Should the output of the command the returned as a string. - * @param opts.env - An object of environment variables to be injected when running the command - * @param opts.cwd - The directory in which the command should be run - * @param opts.useSpinner - Should a spinner be shown when running the command - * @param opts.startText - Spinner start text - * @param opts.endText - Spinner end text - * @param opts.transformOutput - A transformer to be run on command output before returning - * - * @returns Output collected from the stdout of the command, if `captureOutput` was set to true. Otherwise `null`. - */ -export const runCommand = async ( - command: Command, - opts: RunOptions = {} -): Promise => { - return printAsyncStatus({ - useSpinner: opts.useSpinner ?? opts.silent, - startText: opts.startText || quoteShellArgs(command), - doneText: opts.doneText, - promise() { - const [executable, ...args] = command; - const abortController = new AbortController(); - const cmd = spawn(executable, [...args], { - // TODO: ideally inherit stderr, but npm install uses this for warnings - // stdio: [ioMode, ioMode, "inherit"], - stdio: opts.silent ? "pipe" : "inherit", - env: { - ...process.env, - ...opts.env, - }, - cwd: opts.cwd, - signal: abortController.signal, - }); - - let output = ``; - - if (opts.captureOutput ?? opts.silent) { - cmd.stdout?.on("data", (data) => { - output += data; - }); - cmd.stderr?.on("data", (data) => { - output += data; - }); - } - - let cleanup: (() => void) | null = null; - - return new Promise((resolvePromise, reject) => { - const cancel = (signal?: NodeJS.Signals) => { - reject(new CancelError(`Command cancelled`, signal)); - abortController.abort(signal ? `${signal} received` : null); - }; - - process.on("SIGTERM", cancel).on("SIGINT", cancel); - - // To cleanup the signal listeners when the promise settles - cleanup = () => { - process.off("SIGTERM", cancel).off("SIGINT", cancel); - }; - - cmd.on("close", (code) => { - try { - if (code !== 0) { - throw new Error(output, { cause: code }); - } - - // Process any captured output - const transformOutput = - opts.transformOutput ?? ((result: string) => result); - const processedOutput = transformOutput(stripAnsi(output)); - - // Send the captured (and processed) output back to the caller - resolvePromise(processedOutput); - } catch (e) { - // Something went wrong. - // Perhaps the command or the transform failed. - reject(new Error(output, { cause: e })); - } - }); - - cmd.on("error", (error) => { - reject(error); - }); - }).finally(() => { - cleanup?.(); - }); - }, - }); -}; - -const printAsyncStatus = async ({ - promise, - ...opts -}: PrintOptions): Promise => { - let s: ReturnType | undefined; - - if (opts.useSpinner && isInteractive()) { - s = spinner(); - } - - s?.start(opts?.startText); - - if (typeof promise === "function") { - promise = promise(); - } - - try { - const output = await promise; - - const doneText = - typeof opts.doneText === "function" - ? opts.doneText(output) - : opts.doneText; - s?.stop(doneText); - } catch (err) { - s?.stop((err as Error).message); - } finally { - s?.stop(); - } - - return promise; -}; - -/** - * Formats an array of command line arguments to be displayed to the user - * in a platform safe way. Args used in conjunction with `runCommand` are safe - * since we use `cross-spawn` to handle multi-platform support. - * - * However, when we output commands to the user, we have to make sure that they - * are compatible with the platform they are using. - * - * @param args - The arguments to format to the user - */ -export function quoteShellArgs(args: string[]): string { - if (process.platform === "win32") { - // Simple Windows command prompt quoting if there are special characters. - const specialCharsMatcher = /[&<>[\]|{}^=;!'+,`~\s]/; - return args - .map((arg) => - arg.match(specialCharsMatcher) ? `"${arg.replaceAll(`"`, `""`)}"` : arg - ) - .join(" "); - } else { - return args - .map((s) => { - if (/["\s]/.test(s) && !/'/.test(s)) { - return "'" + s.replace(/(['\\])/g, "\\$1") + "'"; - } - if (/["'\s]/.test(s)) { - return '"' + s.replace(/(["\\$`!])/g, "\\$1") + '"'; - } - return s; - }) - .join(" "); - } -} diff --git a/packages/cli/cursor.ts b/packages/cli/cursor.ts deleted file mode 100644 index dd3f29b246..0000000000 --- a/packages/cli/cursor.ts +++ /dev/null @@ -1,13 +0,0 @@ -import process from "node:process"; - -export function showCursor(show: boolean, stream = process.stderr) { - if (!stream.isTTY) { - return; - } - - if (show) { - stream.write("\x1b[?25h"); - } else { - stream.write("\x1b[?25l"); - } -} diff --git a/packages/cli/error.ts b/packages/cli/error.ts deleted file mode 100644 index d405afc03d..0000000000 --- a/packages/cli/error.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Error thrown when an operation is cancelled - */ -export class CancelError extends Error { - constructor( - message?: string, - readonly signal?: NodeJS.Signals - ) { - super(message); - } -} diff --git a/packages/cli/gitignore.ts b/packages/cli/gitignore.ts deleted file mode 100644 index 65c67da15c..0000000000 --- a/packages/cli/gitignore.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { appendFileSync, existsSync, statSync, writeFileSync } from "node:fs"; -import { basename } from "node:path"; -import { readFileSync } from "@cloudflare/workers-utils"; -import { brandColor, dim } from "./colors"; -import { spinner } from "./interactive"; - -/** - * Appends to a file that follows a .gitignore-like structure any missing - * Wrangler-related entries (`.wrangler`, `.dev.vars*`, `.env*`, and their - * negated example patterns). - * - * Creates the file if it does not already exist. - * - * @param filePath Absolute or relative path to the ignore file to update. - */ -export function maybeAppendWranglerToGitIgnoreLikeFile(filePath: string): void { - const filePreExisted = existsSync(filePath); - - if (!filePreExisted) { - writeFileSync(filePath, ""); - } - - const existingGitIgnoreContent = readFileSync(filePath); - const wranglerGitIgnoreFilesToAdd: string[] = []; - - const hasDotWrangler = existingGitIgnoreContent.match( - /^\/?\.wrangler(\/|\s|$)/m - ); - if (!hasDotWrangler) { - wranglerGitIgnoreFilesToAdd.push(".wrangler"); - } - - const hasDotDevDotVars = existingGitIgnoreContent.match( - /^\/?\.dev\.vars\*(\s|$)/m - ); - if (!hasDotDevDotVars) { - wranglerGitIgnoreFilesToAdd.push(".dev.vars*"); - } - - const hasDotDevVarsExample = existingGitIgnoreContent.match( - /^!\/?\.dev\.vars\.example(\s|$)/m - ); - if (!hasDotDevVarsExample) { - wranglerGitIgnoreFilesToAdd.push("!.dev.vars.example"); - } - - /** - * We check for the following type of occurrences: - * - * ``` - * .env - * .env* - * .env. - * .env*. - * ``` - * - * Any of these may alone on a line or be followed by a space and a trailing comment: - * - * ``` - * .env. # some trailing comment - * ``` - */ - const hasDotEnv = existingGitIgnoreContent.match( - /^\/?\.env\*?(\..*?)?(\s|$)/m - ); - if (!hasDotEnv) { - wranglerGitIgnoreFilesToAdd.push(".env*"); - } - - const hasDotEnvExample = existingGitIgnoreContent.match( - /^!\/?\.env\.example(\s|$)/m - ); - if (!hasDotEnvExample) { - wranglerGitIgnoreFilesToAdd.push("!.env.example"); - } - - if (wranglerGitIgnoreFilesToAdd.length === 0) { - return; - } - - const s = spinner(); - s.start(`Adding Wrangler files to the ${basename(filePath)} file`); - - const linesToAppend = [ - ...(filePreExisted - ? ["", ...(!existingGitIgnoreContent.match(/\n\s*$/) ? [""] : [])] - : []), - ]; - - if (!hasDotWrangler && wranglerGitIgnoreFilesToAdd.length > 1) { - linesToAppend.push("# wrangler files"); - } - - wranglerGitIgnoreFilesToAdd.forEach((line) => linesToAppend.push(line)); - - linesToAppend.push(""); - - appendFileSync(filePath, linesToAppend.join("\n")); - - const fileName = basename(filePath); - - s.stop( - `${brandColor(filePreExisted ? "updated" : "created")} ${dim( - `${fileName} file` - )}` - ); -} - -/** - * Appends any missing Wrangler-related entries to the project's `.gitignore` file. - * - * Bails out only when *neither* a `.gitignore` file nor a `.git` directory exists, - * which indicates the project is likely not targeting/using git. If either one is - * present the entries are appended (creating `.gitignore` if needed). - * - * @param projectPath Root directory of the project. - */ -export function maybeAppendWranglerToGitIgnore(projectPath: string): void { - const gitIgnorePath = `${projectPath}/.gitignore`; - const gitIgnorePreExisted = existsSync(gitIgnorePath); - const gitDirExists = directoryExists(`${projectPath}/.git`); - - if (!gitIgnorePreExisted && !gitDirExists) { - // if there is no .gitignore file and neither a .git directory - // then bail as the project is likely not targeting/using git - return; - } - - maybeAppendWranglerToGitIgnoreLikeFile(gitIgnorePath); -} - -/** - * Checks whether a directory exists at the given path. - * - * Returns `false` when the path does not exist (`ENOENT`). Re-throws any - * other filesystem error. - * - * @param path Path to check - * @returns `true` if a directory exists at `path`, `false` otherwise - */ -function directoryExists(path: string): boolean { - try { - const stat = statSync(path); - return stat.isDirectory(); - } catch (error) { - if ((error as { code: string }).code === "ENOENT") { - return false; - } - throw new Error(error as string); - } -} diff --git a/packages/cli/index.ts b/packages/cli/index.ts deleted file mode 100644 index 4c8b63d9b5..0000000000 --- a/packages/cli/index.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { exit } from "node:process"; -import { - bgBlue, - bgGreen, - bgRed, - bgYellow, - brandColor, - dim, - gray, - hidden, - white, -} from "./colors"; -import { stderr, stdout } from "./streams"; - -export const shapes = { - diamond: "◇", - dash: "─", - radioInactive: "○", - radioActive: "●", - - backActive: "◀", - backInactive: "◁", - - bar: "│", - leftT: "├", - rigthT: "┤", - - arrows: { - left: "‹", - right: "›", - }, - - corners: { - tl: "╭", - bl: "╰", - tr: "╮", - br: "╯", - }, -}; - -export const status = { - error: bgRed(` ERROR `), - warning: bgYellow(` WARNING `), - info: bgBlue(` INFO `), - success: bgGreen(` SUCCESS `), - cancel: white.bgRed(` X `), -}; - -// Returns a string containing n non-trimmable spaces -// This is useful for places where clack trims lines of output -// but we need leading spaces -export const space = (n = 1) => { - return hidden("\u200A".repeat(n)); -}; - -const LOGGER_LEVELS = { - none: -1, - error: 0, - warn: 1, - info: 2, - log: 3, - debug: 4, -} as const; - -export type LoggerLevel = keyof typeof LOGGER_LEVELS; - -// Global log level that can be set by consuming packages -let currentLogLevel: LoggerLevel = "log"; - -export function setLogLevel(level: LoggerLevel) { - currentLogLevel = level; -} - -export function getLogLevel(): LoggerLevel { - return currentLogLevel; -} - -// Primitive for printing to stdout. Use this instead of -// console.log or printing to stdout directly -export const logRaw = (msg: string) => { - // treat all log calls as 'log' level logs - const currentLevel = getLogLevel(); - - // Only output if current log level allows 'log' level messages - if (LOGGER_LEVELS[currentLevel] >= LOGGER_LEVELS.log) { - stdout.write(`${msg}\n`); - } -}; - -// A simple stylized log for use within a prompt -export const log = (msg: string) => { - const lines = msg - .split("\n") - .map((ln) => `${gray(shapes.bar)}${ln.length > 0 ? " " + white(ln) : ""}`); - - logRaw(lines.join("\n")); -}; - -export const newline = () => { - log(""); -}; - -type FormatOptions = { - linePrefix?: string; - firstLinePrefix?: string; - newlineBefore?: boolean; - newlineAfter?: boolean; - formatLine?: (line: string) => string; - multiline?: boolean; -}; -export const format = ( - msg: string, - { - linePrefix = gray(shapes.bar), - firstLinePrefix = linePrefix, - newlineBefore = false, - newlineAfter = false, - formatLine = (line: string) => white(line), - multiline = true, - }: FormatOptions = {} -) => { - const lines = multiline ? msg.split("\n") : [msg]; - const formattedLines = lines.map( - (line, i) => - (i === 0 ? firstLinePrefix : linePrefix) + space() + formatLine(line) - ); - - if (newlineBefore) { - formattedLines.unshift(linePrefix); - } - if (newlineAfter) { - formattedLines.push(linePrefix); - } - - return formattedLines.join("\n"); -}; - -// Log a simple status update with a style similar to the clack spinner -export const updateStatus = (msg: string, printNewLine = true) => { - logRaw( - format(msg, { - firstLinePrefix: gray(shapes.leftT), - linePrefix: gray(shapes.bar), - newlineAfter: printNewLine, - }) - ); -}; - -export const startSection = ( - heading: string, - subheading?: string, - printNewLine = true -) => { - logRaw( - `${gray(shapes.corners.tl)} ${brandColor(heading)} ${ - subheading ? dim(subheading) : "" - }` - ); - if (printNewLine) { - newline(); - } -}; - -export const endSection = (heading: string, subheading?: string) => { - logRaw( - `${gray(shapes.corners.bl)} ${brandColor(heading)} ${ - subheading ? dim(subheading) : "" - }\n` - ); -}; - -export const cancel = ( - msg: string, - { - // current default is backcompat and makes sense going forward too - shape = shapes.corners.bl, - // current default for backcompat -- TODO: change default to true once all callees have been updated - multiline = false, - } = {} -) => { - logRaw( - format(msg, { - firstLinePrefix: `${gray(shape)} ${status.cancel}`, - linePrefix: gray(shapes.bar), - newlineBefore: true, - formatLine: (line) => dim(line), // for backcompat but it's not ideal for this to be "dim" - multiline, - }) - ); -}; - -export const warn = ( - msg: string, - { - // current default for backcompat -- TODO: change default to shapes.bar once all callees have been updated - shape = shapes.corners.bl, - // current default for backcompat -- TODO: change default to true once all callees have been updated - multiline = false, - newlineBefore = true, - } = {} -) => { - logRaw( - format(msg, { - firstLinePrefix: gray(shape) + space() + status.warning, - linePrefix: gray(shapes.bar), - formatLine: (line) => dim(line), // for backcompat but it's not ideal for this to be "dim" - multiline, - newlineBefore, - }) - ); -}; - -export const success = ( - msg: string, - { - // current default for backcompat -- TODO: change default to shapes.bar once all callees have been updated - shape = shapes.corners.bl, - // current default for backcompat -- TODO: change default to true once all callees have been updated - multiline = false, - } = {} -) => { - logRaw( - format(msg, { - firstLinePrefix: gray(shape) + space() + status.success, - linePrefix: gray(shapes.bar), - newlineBefore: true, - formatLine: (line) => dim(line), // for backcompat but it's not ideal for this to be "dim" - multiline, - }) - ); -}; - -// Strip the ansi color characters out of the line when calculating -// line length, otherwise the padding will be thrown off -// Used from https://github.com/natemoo-re/clack/blob/main/packages/prompts/src/index.ts -export const stripAnsi = (str: string) => { - const pattern = [ - "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", - "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))", - ].join("|"); - const regex = RegExp(pattern, "g"); - - return str.replace(linkRegex, "$2").replace(regex, ""); -}; - -// Regular Expression that matches a hyperlink -// e.g. `\u001B]8;;http://example.com/\u001B\\This is a link\u001B]8;;\u001B\` -export const linkRegex = - // eslint-disable-next-line no-control-regex -- regex intentionally matches ANSI escape sequences for hyperlink parsing - /\u001B\]8;;(?.+)\u001B\\(?