From ebe4f348c183ddc962e65b21479b5b55c025835f Mon Sep 17 00:00:00 2001 From: Mathieu Laurent Date: Sat, 14 Nov 2026 23:07:51 +0100 Subject: [PATCH 01/12] feat(cloudflare): per-pull-request previews with void deploy --preview Add `void deploy --platform cloudflare --preview [--json]` and `void preview delete `, built on Cloudflare Workers Previews. A Preview is a named, isolated environment of the same Worker with a stable `-..workers.dev` URL. Deploying the same name again updates it; production traffic, the active deployment, routes and schedules are never touched, and a Preview gets no production secrets. - @void/deploy-cloudflare: `previews.deploy` / `previews.delete` operations, `deployCloudflarePreview` (sends only `previews.deploy`), `deleteCloudflarePreview` (a missing Preview, 10025, counts as deleted) and name validation. - void: the static deploy prepares its Build Output as a Preview build and publishes it through `cf previews deploy --prebuilt` instead of activating a version. Apps that need a Worker, an existing-Worker handoff, and --atomic/--provision/--require-email are refused before anything is built or uploaded. A preview never saves an account for the project. - --json prints one record on stdout (workerName, previewName, previewUrl, deploymentId, deploymentUrl); progress goes to stderr through an explicit progress stream in output.ts. - When the Worker has Preview URLs turned off, the deploy fails and points at `cloudflare.preview_urls` in void.config.ts. - Help, interactive hints, CLI reference, a pull request workflow in the Cloudflare integration guide, and the skill. Refs #467, #471. --- docs/integrations/cloudflare.md | 71 +++++++ docs/reference/cli.md | 4 +- docs/reference/cli/deploy.md | 43 +++++ packages/deploy-cloudflare/src/diagnostics.ts | 6 + packages/deploy-cloudflare/src/index.ts | 8 + packages/deploy-cloudflare/src/operations.ts | 19 ++ packages/deploy-cloudflare/src/preview.ts | 179 ++++++++++++++++++ packages/deploy-cloudflare/src/version.ts | 7 +- .../test/operation-fixture.ts | 4 + .../test/unit/preview.test.ts | 140 ++++++++++++++ packages/void/skills/void/SKILL.md | 2 + packages/void/src/cli/args.ts | 31 +++ packages/void/src/cli/cf-build-output.ts | 12 +- packages/void/src/cli/cf-command-values.ts | 44 +++++ packages/void/src/cli/cf-version-runner.ts | 20 ++ packages/void/src/cli/cli-main.ts | 16 +- .../src/cli/cloudflare-operation-process.ts | 16 ++ .../void/src/cli/deploy-cloudflare-helpers.ts | 8 +- .../void/src/cli/deploy-cloudflare-static.ts | 130 +++++++++++-- packages/void/src/cli/deploy-cloudflare.ts | 16 ++ packages/void/src/cli/deploy-helpers.ts | 27 ++- packages/void/src/cli/deploy-summary.ts | 3 +- packages/void/src/cli/deploy-types.ts | 7 + packages/void/src/cli/deploy.ts | 11 +- packages/void/src/cli/help.ts | 32 ++++ packages/void/src/cli/output.ts | 41 +++- packages/void/src/cli/preview-args.ts | 25 +++ packages/void/src/cli/preview-cmd.ts | 91 +++++++++ .../void/test/unit/cf-build-output.test.ts | 16 ++ .../void/test/unit/cf-version-runner.test.ts | 61 ++++++ .../void/test/unit/cloudflare-deploy.test.ts | 155 +++++++++++++++ packages/void/test/unit/deploy-args.test.ts | 35 ++++ packages/void/test/unit/preview-args.test.ts | 16 ++ 33 files changed, 1262 insertions(+), 34 deletions(-) create mode 100644 packages/deploy-cloudflare/src/preview.ts create mode 100644 packages/deploy-cloudflare/test/unit/preview.test.ts create mode 100644 packages/void/src/cli/preview-args.ts create mode 100644 packages/void/src/cli/preview-cmd.ts create mode 100644 packages/void/test/unit/preview-args.test.ts diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index a8ab0039c..f55236589 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -145,6 +145,77 @@ Set these CI secrets and variables as needed: For email, run `void email setup --platform cloudflare` locally, commit `void.lock.json`, and pass `--require-email` in CI. The token also needs Email Routing Edit and Email Sending Edit. +### Pull request previews + +Give each pull request its own URL with [Cloudflare Previews](https://developers.cloudflare.com/workers/previews/). A Preview belongs to the same Worker but never receives production traffic. Previews are available for static sites, SPAs and supported SSGs. + +```sh +void deploy --platform cloudflare --preview pr-64 --json # create or update +void preview delete pr-64 # remove +``` + +The CI job needs only `CLOUDFLARE_API_TOKEN` (Workers Scripts: Edit) and, when the token can access several accounts, `CLOUDFLARE_ACCOUNT_ID`. This workflow deploys a preview on every push to a pull request, comments its URL, and deletes it when the pull request closes: + +```yaml +name: Preview + +on: + pull_request: + types: [opened, synchronize, reopened, closed] + +permissions: + contents: read + pull-requests: write + +concurrency: + group: preview-${{ github.event.pull_request.number }} + +jobs: + preview: + # Repository secrets are not available to pull requests from forks. + if: github.event.action != 'closed' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + check-latest: true + cache: pnpm + - run: pnpm install --frozen-lockfile + - id: preview + run: | + set -o pipefail + url="$(pnpm exec void deploy --platform cloudflare --preview "pr-${{ github.event.pull_request.number }}" --json | jq -er '.previewUrl')" + echo "url=$url" >> "$GITHUB_OUTPUT" + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + - run: gh pr comment "${{ github.event.pull_request.number }}" --edit-last --create-if-none --body "Preview: ${{ steps.preview.outputs.url }}" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + cleanup: + if: github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + check-latest: true + cache: pnpm + - run: pnpm install --frozen-lockfile + - run: pnpm exec void preview delete "pr-${{ github.event.pull_request.number }}" + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} +``` + +If the build runs in an earlier job, download its output and add `--skip-build`. Preview URLs are public; protect them with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/) when needed. See [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output and naming rules. + #### Cloudflare Access For local deployment to an Access-protected Worker, you can use a short-lived user session: diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 129582f0f..5e043940c 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -23,7 +23,7 @@ Use this page as a command reference. If you are setting up a project for the fi | `init`, `prepare`, `info`, `migrate` | [Project setup](./cli/setup.md) | | `connect`, `auth`, `account`, `cloudflare` | [Connections and authentication](./cli/auth.md) | | `project` | [Projects, teams, logs, and rollback](./cli/project.md) | -| `deploy` | [Deployment](./cli/deploy.md) | +| `deploy`, `preview` | [Deployment](./cli/deploy.md) | | `db` | [Database](./cli/database.md) | | `gen` | [Code generation](./cli/generate.md) | | `secret`, `env` | [Secrets and environment](./cli/secrets.md) | @@ -40,6 +40,8 @@ Platform administrators can also choose AI Gateway logging [per project](./cli/p | --------------------------------- | ----------------------------------------------------------------------------- | | `void deploy` | Build and deploy to the configured platform | | `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | +| `void deploy --preview ` | Deploy a Cloudflare Preview with its own URL; production is unchanged | +| `void preview delete ` | Delete a Cloudflare Preview | | `void prepare` | Generate `.void` artifacts without starting Vite | | `void info [--json]` | Inspect persistent resource names before moving their code | | `void gen model [cols...]` | Scaffold a Drizzle table and API routes | diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 609481a14..bcd6cbca3 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -12,6 +12,7 @@ void deploy [--project ] [--dir ] [--spa] [--skip-build] [--skip-mig void deploy [--platform ] [--require-email] void deploy --platform cloudflare --atomic void deploy --platform cloudflare --provision +void deploy --platform cloudflare --preview [--json] ``` Auto-detects your project type and chooses the right pipeline. See [Supported App Types](../../guide/app-types.md) and [Deployment](../../guide/deployment.md) for details. @@ -39,6 +40,8 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m | `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` | | `--provision` | Run resource provisioning again even when every resource exists, for example to enable D1 read replication on an existing database; requires `--platform cloudflare` | | `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | +| `--preview ` | Create or update a Cloudflare Preview instead of production; see [Previews](#void-deploy-preview) | +| `--json` | With `--preview`, print the result as one JSON record on stdout; progress goes to stderr | | `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | `--atomic` applies to one deployment. For an existing Durable Object Worker that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. @@ -115,3 +118,43 @@ Sandbox requires [Workers Paid](https://dash.cloudflare.com/?to=/:account/worker For email, set `email.from` and run `void email setup --platform cloudflare` locally. Commit the lock file and pass `--require-email` in CI. See [Email setup](../../guide/email/domains.md#your-own-cloudflare-account). For Access credentials, Hyperdrive permissions, readiness, and rollback, see [Cloudflare deployment](../../integrations/cloudflare.md#deploy-to-your-own-cloudflare-account). + +## `void deploy --platform cloudflare --preview ` {#void-deploy-preview} + +Deploy the build to a named [Cloudflare Preview](https://developers.cloudflare.com/workers/previews/) of the same Worker: + +```sh +void deploy --platform cloudflare --skip-build --preview pr-64 --json +``` + +A Preview has its own stable URL, `https://-..workers.dev`, which always serves its latest deployment. Deploying the same name again updates that URL. Production traffic, the active deployment, routes and schedules are unchanged. + +Previews are available for static sites, SPAs and supported SSGs. Apps that need a Worker, such as server routes, bindings, migrations or secrets, are refused before anything is built or uploaded. A Preview does not inherit production secrets. + +The name uses lowercase letters, digits and hyphens. `-` must fit in 63 characters. Use a name derived from the pull request, such as `pr-64`, rather than a branch name. + +With `--json`, stdout carries one line: + +```json +{ + "workerName": "my-app", + "previewName": "pr-64", + "previewUrl": "https://pr-64-my-app.my-team.workers.dev", + "deploymentId": "…", + "deploymentUrl": "https://…-my-app.my-team.workers.dev" +} +``` + +`previewUrl` always serves the latest deployment of this Preview. `deploymentUrl` serves only this deployment. + +The Worker must allow Preview URLs. Void's production deploy turns them on when workers.dev is on. If you set `cloudflare.preview_urls` to `false` in `void.config.ts`, a preview deploy fails and says how to turn it back on. Workers Free allows 100 Previews per Worker; Cloudflare removes the least recently deployed one beyond that. + +See [Pull request previews](../../integrations/cloudflare.md#pull-request-previews) for a GitHub Actions workflow. + +## `void preview delete ` {#void-preview-delete} + +```sh +void preview delete pr-64 +``` + +Delete a Preview and all its deployments. Production is unchanged. Deleting a Preview that does not exist succeeds, so a cleanup job can run more than once. It uses the same account and Worker as `void deploy --platform cloudflare`. diff --git a/packages/deploy-cloudflare/src/diagnostics.ts b/packages/deploy-cloudflare/src/diagnostics.ts index d6804342b..684b0f749 100644 --- a/packages/deploy-cloudflare/src/diagnostics.ts +++ b/packages/deploy-cloudflare/src/diagnostics.ts @@ -82,3 +82,9 @@ export function cloudflareCommandDiagnostic(result: CloudflareCommandResult): st .slice(0, MAX_DIAGNOSTIC_LENGTH); return bounded.length < message.length ? `${bounded}\n[diagnostic truncated]` : bounded; } + +/** The uploader's diagnostic as an optional result field. */ +export function commandDiagnosticFields(result: CloudflareCommandResult): { diagnostic?: string } { + const diagnostic = cloudflareCommandDiagnostic(result); + return diagnostic ? { diagnostic } : {}; +} diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 3d5507cd8..1e02de015 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -53,12 +53,20 @@ export { type CloudflareVersionMetadata, type CloudflareWorkersDevSubdomainLookup, } from './version.ts'; +export { + deleteCloudflarePreview, + deployCloudflarePreview, + validateCloudflarePreviewName, + type CloudflarePreviewDeleteResult, + type CloudflarePreviewDeployResult, +} from './preview.ts'; export { createCloudflareMetadataRunner } from './metadata.ts'; export { cloudflareCommandDiagnostic } from './diagnostics.ts'; export { VOID_SECRET_DRAFT_MESSAGE, VOID_SECRET_DRAFT_SOURCE } from './secret-draft.ts'; export type { CloudflareOperation, + CloudflarePreviewUploadResult, CloudflareUploadResult, CloudflareProviderError, } from './operations.ts'; diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index a590181a2..a7cff1e5a 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -56,6 +56,15 @@ export type CloudflareOperation = */ interactive?: boolean; } & WorkerTarget) + | ({ + /** + * Create or update a named Workers Preview from the prebuilt output. A Preview has its own + * URL and settings and never receives production traffic. + */ + type: 'previews.deploy'; + previewName: string; + } & WorkerTarget) + | ({ type: 'previews.delete'; previewName: string } & WorkerTarget) | ({ type: 'triggers.deploy'; assets?: boolean } & WorkerTarget) | ({ type: 'triggers.clear-crons' | 'triggers.clear-domains' } & WorkerTarget) | ({ type: 'tail'; search?: string; versionId?: string; status?: 'error' } & WorkerTarget); @@ -66,6 +75,16 @@ export type CloudflareUploadResult = { workersDevUrl?: string; }; +/** Structured `previews.deploy` data, decoded by the runner from the provider's response. */ +export type CloudflarePreviewUploadResult = { + previewId: string; + previewName: string; + deploymentId: string; + /** Absent when the Worker has Preview URLs turned off. */ + previewUrl?: string; + deploymentUrl?: string; +}; + export type CloudflareProviderError = { code?: number; message: string; diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts new file mode 100644 index 000000000..bf9cabaef --- /dev/null +++ b/packages/deploy-cloudflare/src/preview.ts @@ -0,0 +1,179 @@ +import { isRecord } from '@void/deploy-core'; +import { commandDiagnosticFields } from './diagnostics.ts'; +import { + isCleanCommandExit, + isCompletedCommand, + isWorkerNotFound, + type CloudflareCommandRunner, +} from './execute.ts'; +import type { CloudflarePreviewUploadResult } from './operations.ts'; + +/** + * A Preview name becomes the first label of `-..workers.dev`. Accept only + * names Cloudflare uses unchanged, so the URL Void prints is the one CI expects. + */ +const PREVIEW_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; +/** A DNS label holds at most 63 characters. */ +const MAX_HOST_LABEL = 63; +/** Cloudflare's "Preview not found" API error. */ +const PREVIEW_NOT_FOUND = 10025; + +/** Return why `name` cannot name a Preview of `workerName`, or null when it can. */ +export function validateCloudflarePreviewName(name: string, workerName?: string): string | null { + if (!PREVIEW_NAME.test(name)) { + return `"${name}" is not a valid preview name. Use lowercase letters, digits and hyphens, starting and ending with a letter or digit (for example "pr-64").`; + } + if (workerName !== undefined && name.length + 1 + workerName.length > MAX_HOST_LABEL) { + return `The preview name "${name}" is too long for the Worker "${workerName}": "${name}-${workerName}" must fit in ${MAX_HOST_LABEL} characters to be a workers.dev hostname.`; + } + return null; +} + +export type CloudflarePreviewDeployResult = + | { + ok: true; + previewId: string; + deploymentId: string; + /** The stable URL that always serves this Preview's latest deployment. */ + previewUrl: string; + /** The URL of this deployment only. */ + deploymentUrl: string | undefined; + } + | { + ok: false; + reason: 'uploader-changed' | 'invalid-name' | 'output-invalid'; + diagnostic?: string; + } + | { ok: false; reason: 'deploy-failed'; status: number; diagnostic?: string } + /** Cloudflare created the deployment but returned no Preview URL: `preview_urls` is off. */ + | { ok: false; reason: 'preview-urls-disabled' }; + +/** + * Create or update a named Workers Preview from the prepared output. This only ever sends + * `previews.deploy`: production versions, deployments, traffic and triggers are not read or + * changed, and no migration, provisioning or secret operation runs. + */ +export async function deployCloudflarePreview(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + previewName: string; + verifyUploader: () => boolean; + configPath?: string; +}): Promise { + const invalid = validateCloudflarePreviewName(options.previewName, options.workerName); + if (invalid) { + return { ok: false, reason: 'invalid-name', diagnostic: invalid }; + } + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + const result = await options.runWrangler( + { + type: 'previews.deploy', + workerName: options.workerName, + previewName: options.previewName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }, + { capture: true }, + ); + if (!isCleanCommandExit(result)) { + return { + ok: false, + reason: 'deploy-failed', + status: result.status, + ...commandDiagnosticFields(result), + }; + } + const uploaded = readPreviewUploadResult(result.data); + if (!uploaded || uploaded.previewName !== options.previewName) { + return { ok: false, reason: 'output-invalid' }; + } + if (!uploaded.previewUrl) { + return { ok: false, reason: 'preview-urls-disabled' }; + } + return { + ok: true, + previewId: uploaded.previewId, + deploymentId: uploaded.deploymentId, + previewUrl: uploaded.previewUrl, + deploymentUrl: uploaded.deploymentUrl, + }; +} + +export type CloudflarePreviewDeleteResult = + | { ok: true; deleted: boolean } + | { ok: false; reason: 'uploader-changed' | 'invalid-name'; diagnostic?: string } + | { ok: false; reason: 'delete-failed'; status: number; diagnostic?: string }; + +/** + * Delete a named Preview and all its deployments. A Preview that does not exist is reported as + * `deleted: false`, so a pull-request cleanup job can run more than once. + */ +export async function deleteCloudflarePreview(options: { + runWrangler: CloudflareCommandRunner; + workerName: string; + previewName: string; + verifyUploader: () => boolean; + configPath?: string; +}): Promise { + const invalid = validateCloudflarePreviewName(options.previewName); + if (invalid) { + return { ok: false, reason: 'invalid-name', diagnostic: invalid }; + } + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + const result = await options.runWrangler( + { + type: 'previews.delete', + workerName: options.workerName, + previewName: options.previewName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }, + { capture: true }, + ); + if (isCleanCommandExit(result)) { + return { ok: true, deleted: true }; + } + // Neither the Preview nor, with 10007, its Worker exists: there is nothing left to delete. + if ( + isWorkerNotFound(result) || + (isCompletedCommand(result) && result.errorCode === PREVIEW_NOT_FOUND) + ) { + return { ok: true, deleted: false }; + } + return { + ok: false, + reason: 'delete-failed', + status: result.status, + ...commandDiagnosticFields(result), + }; +} + +/** Validate the structured result the runner decoded from the provider's Preview record. */ +function readPreviewUploadResult(value: unknown): CloudflarePreviewUploadResult | null { + if (!isRecord(value)) { + return null; + } + const { previewId, previewName, deploymentId, previewUrl, deploymentUrl } = value; + const optionalUrl = (url: unknown) => + url === undefined || (typeof url === 'string' && url.startsWith('https://')); + if ( + typeof previewId !== 'string' || + !previewId || + typeof previewName !== 'string' || + typeof deploymentId !== 'string' || + !deploymentId || + !optionalUrl(previewUrl) || + !optionalUrl(deploymentUrl) + ) { + return null; + } + return { + previewId, + previewName, + deploymentId, + ...(previewUrl ? { previewUrl: previewUrl as string } : {}), + ...(deploymentUrl ? { deploymentUrl: deploymentUrl as string } : {}), + }; +} diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 5235a338f..ebb571c79 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -6,7 +6,7 @@ import { isDeepStrictEqual } from 'node:util'; import { canonicalJson, isRecord } from '@void/deploy-core'; import { join } from 'pathslash'; import { parseRootWranglerConfig } from './config.ts'; -import { cloudflareCommandDiagnostic } from './diagnostics.ts'; +import { commandDiagnosticFields } from './diagnostics.ts'; import { isCleanCommandExit, isCompletedCommand, @@ -2522,11 +2522,6 @@ function versionPercentages( }); } -function commandDiagnosticFields(result: CloudflareCommandResult): { diagnostic?: string } { - const diagnostic = cloudflareCommandDiagnostic(result); - return diagnostic ? { diagnostic } : {}; -} - function isContainersUnavailable(result: CloudflareCommandResult): boolean { return ( result.failure === 'containers-unavailable' || diff --git a/packages/deploy-cloudflare/test/operation-fixture.ts b/packages/deploy-cloudflare/test/operation-fixture.ts index cbc52bf49..3987da99c 100644 --- a/packages/deploy-cloudflare/test/operation-fixture.ts +++ b/packages/deploy-cloudflare/test/operation-fixture.ts @@ -193,6 +193,10 @@ export function operationFixtureArgs(operation: CloudflareOperation): Array) { + const calls: Array = []; + const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { + calls.push(operation); + return { status: 0, stdout: '', stderr: '', ...answer }; + }); + return { calls, runWrangler }; +} + +const target = { workerName: 'site', previewName: 'pr-64', verifyUploader: () => true }; + +describe('validateCloudflarePreviewName', () => { + it.each(['pr-64', 'a', 'feature-login', '0'])('accepts %s', (name) => { + expect(validateCloudflarePreviewName(name, 'site')).toBeNull(); + }); + + it.each(['', 'PR-64', 'pr_64', 'feature/login', '-pr', 'pr-', '--flag', 'pr 64'])( + 'rejects %j', + (name) => { + expect(validateCloudflarePreviewName(name, 'site')).toContain('not a valid preview name'); + }, + ); + + it('rejects a name whose workers.dev label would exceed 63 characters', () => { + expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(58))).toContain('63 characters'); + expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(57))).toBeNull(); + }); +}); + +describe('deployCloudflarePreview', () => { + it('sends only previews.deploy and returns the stable Preview URL', async () => { + const { calls, runWrangler } = runner({ data: uploaded }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, configPath: '/app/wrangler.json' }), + ).toEqual({ + ok: true, + previewId: 'prv_1', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-site.team.workers.dev', + deploymentUrl: 'https://dep1-site.team.workers.dev', + }); + // Production is never read or changed: no versions, deployments, traffic or triggers. + expect(calls).toEqual([ + { + type: 'previews.deploy', + workerName: 'site', + previewName: 'pr-64', + configPath: '/app/wrangler.json', + }, + ]); + }); + + it('rejects an invalid name or a changed uploader before running anything', async () => { + const { calls, runWrangler } = runner({ data: uploaded }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, previewName: '--force' }), + ).toMatchObject({ ok: false, reason: 'invalid-name' }); + expect( + await deployCloudflarePreview({ ...target, runWrangler, verifyUploader: () => false }), + ).toEqual({ ok: false, reason: 'uploader-changed' }); + expect(calls).toEqual([]); + }); + + it('reports a failed deploy', async () => { + const { runWrangler } = runner({ status: 1, errors: [{ message: 'Authentication error' }] }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: false, + reason: 'deploy-failed', + status: 1, + }); + }); + + it('reports disabled Preview URLs when Cloudflare returns none', async () => { + const { previewUrl: _, ...withoutUrl } = uploaded; + const { runWrangler } = runner({ data: withoutUrl }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'preview-urls-disabled', + }); + }); + + it.each([ + { ...uploaded, previewName: 'pr-65' }, + { ...uploaded, previewUrl: 'http://pr-64-site.team.workers.dev' }, + { ...uploaded, deploymentId: '' }, + undefined, + ])('rejects an unreadable or foreign Preview record %#', async (data) => { + const { runWrangler } = runner({ data }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: false, + reason: 'output-invalid', + }); + }); +}); + +describe('deleteCloudflarePreview', () => { + it('deletes the named Preview of the Worker', async () => { + const { calls, runWrangler } = runner({}); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: true, + deleted: true, + }); + expect(calls).toEqual([{ type: 'previews.delete', workerName: 'site', previewName: 'pr-64' }]); + }); + + // 10025: "Preview not found", as Cloudflare answered in a live run. 10007: no such Worker. + it.each([10025, 10007])('treats error %i as already deleted', async (errorCode) => { + const { runWrangler } = runner({ status: 1, errorCode }); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ + ok: true, + deleted: false, + }); + }); + + it('reports other failures', async () => { + const { runWrangler } = runner({ status: 1, errorCode: 10000 }); + expect(await deleteCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: false, + reason: 'delete-failed', + status: 1, + }); + }); +}); diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index 24550f2c0..0f6400591 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -32,6 +32,8 @@ For a one-time deployment elsewhere, connect to that platform, then set `VOID_API_URL` for the deploy command and pass `--project `. This preserves the app's existing saved destination, including when the target project is new. +For a per-pull-request Cloudflare preview of a static site or SPA, use `void deploy --platform cloudflare --preview pr- --json` and `void preview delete pr-` on close; see `docs/reference/cli/deploy.md`. + Use `void deploy --skip-migrations` when database migrations run separately; it skips application and authentication SQL for that invocation. Ensure the code supports the current database schema and follow `docs/guide/deployment.md` for the release workflow. ## Task Routing diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index b61d5edcd..1e8557662 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -19,6 +19,8 @@ export function parseDeployArgs( provision: { type: 'boolean' }, 'require-email': { type: 'boolean' }, atomic: { type: 'boolean' }, + preview: { type: 'string' }, + json: { type: 'boolean' }, }, allowPositionals: true, strict: true, @@ -32,6 +34,9 @@ export function parseDeployArgs( if (optionMatch?.[1] === '--platform') { throw new Error("deploy: --platform requires a value ('cloudflare' or 'void')."); } + if (optionMatch?.[1] === '--preview') { + throw new Error('deploy: --preview requires a name (for example --preview pr-64).'); + } throw new Error('deploy: --project requires a slug.'); } @@ -106,7 +111,33 @@ export function parseDeployArgs( } } + if (tokens.filter((token) => token.kind === 'option' && token.name === 'preview').length > 1) { + throw new Error('deploy: --preview can only be specified once.'); + } + const preview = typeof parsed.values.preview === 'string' ? parsed.values.preview : undefined; + const json = parsed.values.json === true ? true : undefined; + if (preview !== undefined) { + if (platform !== 'cloudflare') { + throw new Error('deploy: --preview requires --platform cloudflare.'); + } + // The name itself is checked against the Worker name before the build. + for (const [flag, set] of [ + ['--atomic', atomic], + ['--provision', provision], + ['--require-email', requireEmail], + ] as const) { + if (set) { + throw new Error(`deploy: ${flag} cannot be combined with --preview.`); + } + } + } + if (json && preview === undefined) { + throw new Error('deploy: --json is available only with --preview.'); + } + return { + preview, + json, projectSlug, dir, spa, diff --git a/packages/void/src/cli/cf-build-output.ts b/packages/void/src/cli/cf-build-output.ts index 594aefaf2..3a8d6a897 100644 --- a/packages/void/src/cli/cf-build-output.ts +++ b/packages/void/src/cli/cf-build-output.ts @@ -156,6 +156,8 @@ export async function prepareCfBuildOutput( accountId?: string, mode?: string, projectRoot: string = workerDirectory, + /** Mark the output as a Preview build, which `cf previews deploy` requires. */ + options: { isPreview?: boolean } = {}, ): Promise { const source = resolve(workerDirectory); if (existsSync(getRootConfigPath(source))) { @@ -281,7 +283,7 @@ export async function prepareCfBuildOutput( await writeRootConfig( directory, typeof configuredAccountId === 'string' ? { accountId: configuredAccountId } : {}, - { isPreview: false, mode: mode ?? 'production' }, + { isPreview: options.isPreview === true, mode: mode ?? 'production' }, ); await writeWorkerConfig({ root: directory, @@ -546,6 +548,7 @@ async function prepareBundledBuildOutput(options: { assets: Record; accountId: string; external?: Array; + isPreview?: boolean; }): Promise { const scratch = mkdtempSync(join(tmpdir(), options.scratchPrefix)); try { @@ -576,7 +579,9 @@ async function prepareBundledBuildOutput(options: { JSON.stringify({ ...options.config, main: 'index.js', assets: options.assets }), { mode: 0o600 }, ); - return await prepareCfBuildOutput(scratch, options.accountId, undefined, options.projectRoot); + return await prepareCfBuildOutput(scratch, options.accountId, undefined, options.projectRoot, { + isPreview: options.isPreview, + }); } finally { rmSync(scratch, { recursive: true, force: true }); } @@ -588,6 +593,8 @@ export async function prepareCfStaticBuildOutput(options: { configPath: string; assetsDirectory: string; accountId: string; + /** Prepare the output for `cf previews deploy` instead of a production version. */ + isPreview?: boolean; }): Promise { const raw = record(JSON.parse(readFileSync(options.configPath, 'utf8'))); if (!raw || typeof raw.main !== 'string' || basename(raw.main) !== raw.main) { @@ -604,6 +611,7 @@ export async function prepareCfStaticBuildOutput(options: { config: raw, assets: { ...record(raw.assets), directory: resolve(options.assetsDirectory) }, accountId: options.accountId, + isPreview: options.isPreview, }); } diff --git a/packages/void/src/cli/cf-command-values.ts b/packages/void/src/cli/cf-command-values.ts index f14c5d240..92f649f9b 100644 --- a/packages/void/src/cli/cf-command-values.ts +++ b/packages/void/src/cli/cf-command-values.ts @@ -1,3 +1,5 @@ +import type { CloudflarePreviewUploadResult } from '@void/deploy-cloudflare'; +import { isRecord } from '@void/deploy-core'; // Leave room for a 64 MiB Worker, base64 expansion, and JSON metadata. export const CF_VERSION_SOURCE_MAX_OUTPUT_BYTES: number = 128 * 1024 * 1024; @@ -34,3 +36,45 @@ export function readCfUploadOutput(result: { workersDevUrl: output.match(/(https:\/\/[a-z0-9.-]+\.workers\.dev(?:\/[^\s]*)?)/i)?.[1], }; } + +/** + * Decode the Preview record `cf previews deploy` prints as JSON: the stable Preview URL and the + * URL of this deployment. Earlier provider lines may precede the record, so read the last line that + * starts a JSON object together with everything after it. + */ +export function readCfPreviewDeployOutput( + stdout: string, +): CloudflarePreviewUploadResult | undefined { + const lines = stdout.trim().split('\n'); + for (let index = lines.length - 1; index >= 0; index--) { + if (!lines[index]!.startsWith('{')) { + continue; + } + let record: unknown; + try { + record = JSON.parse(lines.slice(index).join('\n')); + } catch { + continue; + } + if (!isRecord(record)) { + return undefined; + } + const value = record; + const first = (urls: unknown) => + Array.isArray(urls) && typeof urls[0] === 'string' ? urls[0].replace(/\/$/, '') : undefined; + const previewUrl = first(value.preview_urls); + const deploymentUrl = first(value.deployment_urls); + return typeof value.preview_id === 'string' && + typeof value.preview_name === 'string' && + typeof value.deployment_id === 'string' + ? { + previewId: value.preview_id, + previewName: value.preview_name, + deploymentId: value.deployment_id, + ...(previewUrl ? { previewUrl } : {}), + ...(deploymentUrl ? { deploymentUrl } : {}), + } + : undefined; + } + return undefined; +} diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index bf1fb35b3..3a36f0197 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -15,6 +15,7 @@ import { dirname, join } from 'pathslash'; import type { CfBuildOutput } from './cf-build-output.ts'; import { CF_VERSION_SOURCE_MAX_OUTPUT_BYTES, + readCfPreviewDeployOutput, readCfUploadOutput, safePositional, } from './cf-command-values.ts'; @@ -727,6 +728,25 @@ export function createCfVersionRunner(options: { ); } + if (operation.type === 'previews.deploy') { + if (operation.workerName !== workerName) { + return failed('The Cloudflare preview target changed.'); + } + const verified = await verifyResources(output.directory); + if (!isCleanCloudflareExit(verified)) { + return verified; + } + // One argv item, so a name that starts with "-" is never read as a flag. + const deployed = await runCf( + ['previews', 'deploy', '--prebuilt', `--preview-name=${operation.previewName}`], + { cwd: output.directory, capture: command.capture }, + ); + if (!isCleanCloudflareExit(deployed)) { + return deployed; + } + return { ...deployed, data: readCfPreviewDeployOutput(deployed.stdout) }; + } + if (operation.type === 'versions.deploy') { if (operation.workerName !== workerName) { return failed('The Cloudflare deployment target changed.'); diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 33b863b05..3e99fbbaf 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -22,6 +22,7 @@ import { OperatorClientError } from './operator-client.ts'; import { formatUrl, pc } from './output.ts'; import { parsePlatformArgs, platformSubcommands } from './platform-args.ts'; import { parsePrepareArgs } from './prepare-args.ts'; +import { parsePreviewArgs, previewSubcommands } from './preview-args.ts'; import { projectSubcommands, parseProjectArgs } from './project-args.ts'; import { secretSubcommands, parseSecretArgs } from './secret-args.ts'; import type { SubcommandDef, SubcommandResult } from './subcommand-prompt.ts'; @@ -135,6 +136,10 @@ const subcommandGroups: Record Promise> = { runCloudflareCommand(root, parsed), ), ), + preview: () => + runSubcommandGroup('preview', previewSubcommands, parsePreviewArgs, (root, parsed) => + import('./preview-cmd.ts').then(({ runPreviewCommand }) => runPreviewCommand(root, parsed)), + ), project: () => runSubcommandGroup('project', projectSubcommands, parseProjectArgs, (root, parsed) => import('./project-cmd.ts').then(({ runProjectCommand }) => runProjectCommand(root, parsed)), @@ -286,7 +291,16 @@ if (helpPath) { description: 'Inspect persistent resource names in this project', }, { name: 'connect', description: 'Connect to Cloudflare or a Void platform' }, - { name: 'deploy', description: 'Build and deploy, or link an existing Cloudflare Worker' }, + { + name: 'deploy', + hint: '--platform cloudflare --preview ', + description: 'Build and deploy, or link an existing Cloudflare Worker', + }, + { + name: 'preview', + hint: 'delete', + description: 'Delete a Cloudflare Preview created with void deploy --preview', + }, { name: 'auth', hint: 'login | status | logout', diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index e8be9ca40..88709660c 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -1494,6 +1494,22 @@ async function main(): Promise { if (operation.type.startsWith('email.')) { return email(); } + if (operation.type === 'previews.delete') { + // cf does not read a positional after "--", so refuse a name it could read as a flag. + if (!safePositional(operation.previewName)) { + throw new Error('Cloudflare Preview name is invalid.'); + } + return runCf([ + 'previews', + 'delete', + operation.previewName, + `--worker=${workerName()}`, + '--force', + ]); + } + if (operation.type === 'previews.deploy') { + throw new Error('Cloudflare Previews deploy only from the prepared Build Output.'); + } if ( operation.type.startsWith('deployments.') || (operation.type.startsWith('versions.') && operation.type !== 'versions.upload') diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 895d7e56e..3e783bef1 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -97,12 +97,14 @@ export function discoverRootWranglerConfig(root: string): string { function createCloudflareUploaderPins( root: string, deps: CloudflareDeployDeps, + /** False for commands that never upload through the prebuilt cf uploader. */ + usesPrebuiltUploader = true, ): { usesCf: boolean; cfUploaderIsPinned: () => boolean; assertUploaderStillPinned: () => boolean; } { - const usesCf = !deps.activateVersion && !deps.runWrangler; + const usesCf = usesPrebuiltUploader && !deps.activateVersion && !deps.runWrangler; const hashUploader = deps.hashWranglerUploader ?? hashWranglerUploader; const wranglerUploaderHashBefore = hashUploader(root); const cfUploaderHashBefore = usesCf ? hashCfUploader() : undefined; @@ -170,6 +172,8 @@ export async function connectCloudflareDeployAccount(options: { readinessAccessOrigin: string | null | undefined; /** Scrubs and logs every child this connection runs. */ reporter: CloudflareChildReporter; + /** False skips pinning the prebuilt cf uploader, for commands that only call the API. */ + usesPrebuiltUploader?: boolean; }): Promise { const { root, configPath, deps, reporter } = options; let { rootConfig } = options; @@ -186,7 +190,7 @@ export async function connectCloudflareDeployAccount(options: { readWranglerTopLevelString(rootConfig, 'compliance_region'), ); // Pin the uploaders before the first authenticated command, including account discovery. - const pins = createCloudflareUploaderPins(root, deps); + const pins = createCloudflareUploaderPins(root, deps, options.usesPrebuiltUploader); let accountId = readWranglerTopLevelString(rootConfig, 'account_id') ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index ca2ed3674..b09d00246 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -2,6 +2,7 @@ import { execSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { activateCloudflareVersion, + deployCloudflarePreview, encodeCloudflareVersionMessage, parseRootWranglerConfig, readCloudflareTriggerConfig, @@ -11,6 +12,8 @@ import { writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig, assertExistingCloudflareConfig, + validateCloudflarePreviewName, + type CloudflarePreviewDeployResult, } from '@void/deploy-cloudflare'; import { dirname, join, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; @@ -62,7 +65,7 @@ import { import { type RunDeployOptions, type CloudflareDeployDeps } from './deploy-types.ts'; import { readGeneratedAssetHeadersFile } from './headers.ts'; import { type CliLogger } from './log-file.ts'; -import { getErrorMessage, note } from './output.ts'; +import { getErrorMessage, note, printJsonRecord, printSuccess, progressOutput } from './output.ts'; import { buildStaticManifest, readWranglerHtmlHandling } from './package.ts'; import { detectPreset, type StaticPreset, type FrameworkPreset } from './preset.ts'; import { deleteEnvVarCaseAware } from './provision.ts'; @@ -337,7 +340,9 @@ export async function runCloudflareStaticDeploy( configPath, rootConfig: parseRootWranglerConfig(configPath), deps, - persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), + // A preview never saves an account for the project, as `void preview delete` does not. + persistAccount: + options.preview === undefined && !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, }); @@ -374,7 +379,17 @@ export async function runCloudflareStaticDeploy( } const rootConfig = parseRootWranglerConfig(configPath); const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); - printDeployContext(workerName, 'Cloudflare'); + printDeployContext( + workerName, + options.preview === undefined ? 'Cloudflare' : `Cloudflare Preview ${options.preview}`, + ); + if (options.preview !== undefined) { + const invalid = validateCloudflarePreviewName(options.preview, workerName); + if (invalid) { + log.error(`deploy: ${invalid}`); + return exit(1); + } + } const rootConfigBeforeBuild = existsSync(configPath) ? readFileSync(configPath, 'utf-8') : null; if (preset.buildCommand && !options.skipBuild) { log.step('Building...'); @@ -386,7 +401,12 @@ export async function runCloudflareStaticDeploy( const runStaticBuild = deps.runStaticBuild ?? ((command: string, env: NodeJS.ProcessEnv) => { - execSync(command, { cwd: root, stdio: 'inherit', env }); + // With --json, stdout carries only the result record. + execSync(command, { + cwd: root, + stdio: ['inherit', progressOutput(), 'inherit'], + env, + }); }); try { runStaticBuild(preset.buildCommand, buildChildEnv); @@ -472,7 +492,6 @@ export async function runCloudflareStaticDeploy( headers: edgeRouting.assetHeaders, }); - const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); assertCloudflareDeployTargetUnchanged({ root, existingWorker, @@ -490,6 +509,7 @@ export async function runCloudflareStaticDeploy( configPath: staticConfigPath, assetsDirectory: stagedAssetsDirectory, accountId, + isPreview: options.preview !== undefined, }) : null; if (!cfOutput && usesCf) { @@ -507,6 +527,27 @@ export async function runCloudflareStaticDeploy( verifyCompatibilityRunner: assertUploaderStillPinned, reporter, }); + const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; + if (options.preview !== undefined) { + log.step(`Deploying Preview ${options.preview}...`); + const result = await deployCloudflarePreview({ + runWrangler: activationRunner, + workerName, + previewName: options.preview, + verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, + configPath: staticConfigPath, + }).finally(() => cfOutput?.dispose()); + return reportCloudflareStaticPreview(result, { + previewName: options.preview, + workerName, + typeLabel, + json: options.json === true, + reporter, + cliLog, + exit, + }); + } + const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); const execution = await activateCloudflareVersionWithProgress( deps.activateVersion ?? activateCloudflareVersion, { @@ -559,12 +600,79 @@ export async function runCloudflareStaticDeploy( execution, cliLog, }); - note( - formatDeploySummary({ + note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); + printDeploySuccess(); +} + +/** Print a preview deploy's result: the URL, or a JSON record with `--json`, or the failure. */ +function reportCloudflareStaticPreview( + result: CloudflarePreviewDeployResult, + options: { + previewName: string; + workerName: string; + typeLabel: string; + json: boolean; + reporter: CloudflareChildReporter; + cliLog: CliLogger; + exit: (code: number) => never; + }, +): void { + const { previewName, workerName } = options; + if (!result.ok) { + const message = options.reporter.redactor.redact( + formatCloudflarePreviewError(result, workerName), + ); + options.cliLog.error('cloudflare_preview_failed', new Error(message), { + reason: result.reason, + }); + log.error(message); + return options.exit(1); + } + options.cliLog.info('cloudflare_preview_deployed', { + previewName, + previewId: result.previewId, + deploymentId: result.deploymentId, + }); + if (options.json) { + printJsonRecord({ workerName, - typeLabel: preset.appType === 'spa' ? 'Static SPA' : 'Static Site', - }), - execution.previewUrl, + previewName, + previewUrl: result.previewUrl, + deploymentId: result.deploymentId, + deploymentUrl: result.deploymentUrl ?? null, + }); + } + note( + [ + formatDeploySummary({ workerName, typeLabel: options.typeLabel }), + `Preview: ${previewName}`, + ...(result.deploymentUrl ? [`This deployment: ${result.deploymentUrl}`] : []), + ].join('\n'), + result.previewUrl, ); - printDeploySuccess(); + printSuccess(`Preview ${previewName} deployed. Production is unchanged.`); +} + +function formatCloudflarePreviewError( + result: Extract, + workerName: string, +): string { + switch (result.reason) { + case 'invalid-name': + return `deploy: ${result.diagnostic}`; + case 'uploader-changed': + return 'deploy: the Cloudflare uploader changed during the preview deploy. Nothing was deployed.'; + case 'output-invalid': + return 'deploy: Cloudflare accepted the preview but did not return a readable Preview record. Check the Worker in the Cloudflare dashboard before retrying.'; + case 'preview-urls-disabled': + return [ + `deploy: the preview was deployed, but Preview URLs are turned off for the Worker "${workerName}", so it has no URL.`, + 'Set preview_urls: true in the cloudflare field of void.config.ts and run a production deploy (void deploy --platform cloudflare), or turn on Preview under Domains for the Worker in the Cloudflare dashboard. Then deploy the preview again.', + ].join('\n'); + case 'deploy-failed': + return [ + 'deploy: Cloudflare could not deploy the preview. Production is unchanged.', + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } } diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 84fde0d03..ee702e796 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -63,6 +63,12 @@ export async function runCloudflareDeploy( ); return exit(1); } + if (options.preview !== undefined && (options.reuseExistingWorker || initialCloudflareLink)) { + log.error( + 'deploy: previews are unavailable during the existing Worker handoff. Complete the handoff with a production deploy first.', + ); + return exit(1); + } const detectedFramework = detectFramework(root); const frameworkPreset = detectedFramework ? FRAMEWORK_PRESETS[detectedFramework.name] : undefined; cliLog.info('cloudflare_deploy_start', { @@ -114,6 +120,16 @@ export async function runCloudflareDeploy( ); } + if (options.preview !== undefined) { + log.error( + [ + 'deploy: --preview currently supports static sites and single-page apps only.', + 'This app needs a Worker (server routes, bindings, migrations or secrets), and a Preview would share or skip them. Deploy it without --preview.', + ].join('\n'), + ); + return exit(1); + } + // After the static branch: a static framework build is served by the thin // edge Worker, which applies the redirect itself. if (detectedFramework && voidConfig.routing?.alwaysUseHttps === true) { diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 81b9df40b..3a39850fe 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -1,5 +1,6 @@ import { execSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; +import type { Writable } from 'node:stream'; import { isCancel, log as clackLog, text } from '@voidzero-dev/vite-plus-prompts'; import { join, resolve } from 'pathslash'; import { findEnvFile } from '../codegen/env-types.ts'; @@ -23,7 +24,7 @@ import { } from './deploy-types.ts'; import { fetchRemoteSecretNames, formatEnvReport, validateProdEnv } from './env-validation.ts'; import { type CliLogger } from './log-file.ts'; -import { formatCount, getErrorMessage, pc } from './output.ts'; +import { formatCount, getErrorMessage, pc, progressOptions } from './output.ts'; import { detectPreset, formatProjectCommand, @@ -50,15 +51,29 @@ import { import type { WrapperFeatures } from './wrapper.ts'; import { needsWrapper, generateWrapper } from './wrapper.ts'; +/** Format a Cloudflare message and send it to the progress stream a `--json` command chose. */ +function progressLog( + write: (message: string, options?: { output?: Writable }) => void, + message: string, +): void { + const formatted = formatCloudflareUserMessage(message); + const options = progressOptions(); + if (options.output) { + write(formatted, options); + } else { + write(formatted); + } +} + export const log: Record< 'error' | 'info' | 'message' | 'step' | 'warn', (message: string) => void > = { - error: (message: string) => clackLog.error(formatCloudflareUserMessage(message)), - info: (message: string) => clackLog.info(formatCloudflareUserMessage(message)), - message: (message: string) => clackLog.message(formatCloudflareUserMessage(message)), - step: (message: string) => clackLog.step(formatCloudflareUserMessage(message)), - warn: (message: string) => clackLog.warn(formatCloudflareUserMessage(message)), + error: (message: string) => progressLog(clackLog.error, message), + info: (message: string) => progressLog(clackLog.info, message), + message: (message: string) => progressLog(clackLog.message, message), + step: (message: string) => progressLog(clackLog.step, message), + warn: (message: string) => progressLog(clackLog.warn, message), }; export class DeployEventError extends Error {} diff --git a/packages/void/src/cli/deploy-summary.ts b/packages/void/src/cli/deploy-summary.ts index 9a328e90e..4c8397bd9 100644 --- a/packages/void/src/cli/deploy-summary.ts +++ b/packages/void/src/cli/deploy-summary.ts @@ -1,9 +1,10 @@ import { intro } from '@voidzero-dev/vite-plus-prompts'; -import { formatCount, pc, printSuccess, sanitizeTerminalText } from './output.ts'; +import { formatCount, pc, printSuccess, progressOptions, sanitizeTerminalText } from './output.ts'; export function printDeployContext(project: string, destination: string): void { intro( `${pc.dim(sanitizeTerminalText(project))} ${pc.dim('→')} ${pc.blue(sanitizeTerminalText(destination))}`, + progressOptions(), ); } diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index a7fd077ff..d65072a0d 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -49,6 +49,13 @@ export type RunDeployOptions = { requireEmail?: boolean; /** Publish an existing Durable Object Worker atomically after explicit operator choice. */ atomic?: boolean; + /** + * Create or update this named Cloudflare Preview instead of deploying production. + * `--platform cloudflare` only; production traffic is never changed. + */ + preview?: string; + /** Print the deployment result as one JSON record on stdout; logs go to stderr. */ + json?: boolean; /** * `CF_ACCESS_READINESS_ORIGIN` as recorded before project code ran (`null` when unset). * `--platform cloudflare` only. diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 282ae7f08..336bfb6a2 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -35,6 +35,7 @@ import { openDeployLog, type CliLogger } from './log-file.ts'; import { buildDeployLogSummary } from './log-summary.ts'; import { promptForLoginToken } from './login.ts'; import { migrateLegacyVoidConfig } from './migrate.ts'; +import { setProgressOutput } from './output.ts'; import { listPlatformConnections } from './platform-registry.ts'; import { detectPreset, FRAMEWORK_PRESETS } from './preset.ts'; import { @@ -58,7 +59,14 @@ export function resolveDeploymentPlatform( export async function runDeploy(root: string, options?: RunDeployOptions): Promise { // The Cloudflare link check can evaluate void.config.ts, so record operator input first. options = withRecordedReadinessAccessOrigin(options ?? {}); - console.log(); + if (options.json) { + // stdout carries only the result record. Kept for the rest of the process, so the CLI's own + // report of a thrown error also goes to stderr. + setProgressOutput(process.stderr); + process.stderr.write('\n'); + } else { + console.log(); + } const cliLog = openDeployLog({ mirrorToStderr: options?.debug === true || process.env.VOID_DEPLOY_DEBUG === '1', @@ -70,6 +78,7 @@ export async function runDeploy(root: string, options?: RunDeployOptions): Promi spa: options?.spa === true ? true : undefined, skipBuild: options?.skipBuild === true ? true : undefined, skipMigrations: options?.skipMigrations === true ? true : undefined, + preview: options?.preview, nodeVersion: process.version, platform: process.platform, arch: process.arch, diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index a69948db2..1a3497b76 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -190,6 +190,15 @@ const HELP_TREE: HelpTree = { description: 'Publish a Durable Object Worker without pre-traffic staging (Cloudflare only)', }, + { + command: '--preview ', + description: + 'Create or update a Cloudflare Preview with its own URL; production is unchanged (static sites and SPAs, with --platform cloudflare)', + }, + { + command: '--json', + description: 'Print the preview result as JSON on stdout (with --preview)', + }, { command: '--debug', description: 'Mirror the deploy log to stderr (always written to ~/.void/logs)', @@ -203,6 +212,27 @@ const HELP_TREE: HelpTree = { command: 'void deploy --platform cloudflare', description: 'Deploy to your own Cloudflare account', }, + { + command: 'void deploy --platform cloudflare --preview pr-64 --json', + description: 'Deploy a pull request preview and print its URL as JSON', + }, + ], + }, + preview: { + summary: + 'Manage Cloudflare Previews created with `void deploy --platform cloudflare --preview`.', + usage: ['void preview delete '], + commands: [ + { command: 'delete ', description: 'Delete a Preview and all its deployments' }, + ], + children: { + delete: basicSubcommand( + 'Delete a Preview and all its deployments. Production is unchanged; a Preview that does not exist is not an error.', + 'void preview delete ', + ), + }, + examples: [ + { command: 'void preview delete pr-64', description: 'Remove a pull request preview' }, ], }, auth: { @@ -1565,6 +1595,8 @@ export function printGlobalHelp(): void { globalCommandLine(['deploy'], 'void deploy'), ...globalOptionLines(['deploy']), '', + ...globalCommandGroup('preview'), + '', ...globalCommandGroup('auth'), '', ...globalCommandGroup('account'), diff --git a/packages/void/src/cli/output.ts b/packages/void/src/cli/output.ts index 5dc9bb7e2..2871fc08b 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -28,10 +28,41 @@ export function formatUrl(url: string): string { return formatLink(text, text); } +let progressStream: Writable | undefined; + +/** + * Choose where Void's progress output goes. `--json` commands send it to stderr so stdout carries + * only their result record. Pass undefined to restore stdout. + */ +export function setProgressOutput(stream: Writable | undefined): void { + progressStream = stream; +} + +/** The stream Void's progress renderers write to: stdout unless a `--json` command chose stderr. */ +export function progressOutput(): Writable { + return progressStream ?? process.stdout; +} + +/** + * Renderer options that route output to the chosen progress stream. Empty unless a `--json` + * command chose one, so ordinary runs call the renderers exactly as before. + */ +export function progressOptions(): { output?: Writable } { + return progressStream ? { output: progressStream } : {}; +} + +/** Print one machine-readable JSON record on stdout. */ +export function printJsonRecord(record: unknown): void { + process.stdout.write(`${JSON.stringify(record)}\n`); +} + /** Complete an action with the same spacing, checkmark, and color on every target. */ export function printSuccess(message: string): void { // Remove nested styles so a blue URL or dim hint cannot override the success color. - outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { withGuide: false }); + outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { + withGuide: false, + ...progressOptions(), + }); } export function formatCount(count: number, singular: string, plural = `${singular}s`): string { @@ -127,11 +158,15 @@ export function note(...args: Parameters): void { const urlTitle = plainTitle && /^https?:\/\/\S+$/.test(plainTitle) ? plainTitle : undefined; // Native macOS Terminal recognizes URLs by whitespace boundaries. const boxedTitle = urlTitle ? ` ${urlTitle} ` : title; - const output = opts?.output ?? process.stdout; + const output = opts?.output ?? progressOutput(); const columns = (output as { columns?: unknown }).columns; const needsWidthFallback = typeof columns === 'number' && columns < MIN_NOTE_COLUMNS; if (!urlTitle && !needsWidthFallback) { - promptsNote(...args); + if (opts?.output || !progressStream) { + promptsNote(...args); + } else { + promptsNote(message, title, { ...opts, output }); + } return; } // The box renderer only reads `columns` and calls `write()`. diff --git a/packages/void/src/cli/preview-args.ts b/packages/void/src/cli/preview-args.ts new file mode 100644 index 000000000..5811b6f3b --- /dev/null +++ b/packages/void/src/cli/preview-args.ts @@ -0,0 +1,25 @@ +import type { SubcommandDef } from './subcommand-prompt.ts'; + +export const previewSubcommands: Array = [ + { + name: 'delete', + hint: '', + description: 'Delete a Cloudflare Preview and all its deployments', + }, +]; + +export type PreviewArgs = { subcommand: 'delete'; name: string }; + +export function parsePreviewArgs(args: Array): PreviewArgs { + const [subcommand, name, extra] = args; + if (subcommand !== 'delete') { + throw new Error('preview: Usage: void preview delete .'); + } + if (!name || name.startsWith('-')) { + throw new Error('preview: delete requires a preview name (for example pr-64).'); + } + if (extra) { + throw new Error(`preview: Unexpected argument '${extra}'.`); + } + return { subcommand, name }; +} diff --git a/packages/void/src/cli/preview-cmd.ts b/packages/void/src/cli/preview-cmd.ts new file mode 100644 index 000000000..2f6e8c04c --- /dev/null +++ b/packages/void/src/cli/preview-cmd.ts @@ -0,0 +1,91 @@ +import { + deleteCloudflarePreview, + parseRootWranglerConfig, + readWranglerTopLevelString, + type CloudflarePreviewDeleteResult, +} from '@void/deploy-cloudflare'; +import { createCloudflareChildReporter } from './cloudflare-child-report.ts'; +import { + confirmCloudflareDeployAuthentication, + connectCloudflareDeployAccount, + discoverRootWranglerConfig, +} from './deploy-cloudflare-helpers.ts'; +import { log } from './deploy-helpers.ts'; +import { deriveWorkerName } from './deploy-resources.ts'; +import type { CloudflareDeployDeps } from './deploy-types.ts'; +import { openDeployLog } from './log-file.ts'; +import { printSuccess } from './output.ts'; +import type { PreviewArgs } from './preview-args.ts'; + +/** + * Delete a Preview of this project's Cloudflare Worker. Production is not read or changed. A + * Preview that no longer exists is not an error, so a pull-request cleanup job can rerun. + */ +export async function runPreviewCommand( + root: string, + args: PreviewArgs, + deps: CloudflareDeployDeps = {}, +): Promise { + const cliLog = openDeployLog(); + try { + const reporter = createCloudflareChildReporter(cliLog); + const configPath = discoverRootWranglerConfig(root); + const connection = await connectCloudflareDeployAccount({ + root, + configPath, + rootConfig: parseRootWranglerConfig(configPath), + deps, + // Deleting a Preview never chooses or saves an account for the project. + persistAccount: false, + readinessAccessOrigin: undefined, + reporter, + // Deleting is one API call: there is no prebuilt upload to pin. + usesPrebuiltUploader: false, + }); + if (!connection || !(await confirmCloudflareDeployAuthentication(connection, configPath))) { + throw new Error('preview: could not connect to Cloudflare.'); + } + const workerName = + readWranglerTopLevelString(connection.rootConfig, 'name') ?? deriveWorkerName(root); + const result = await deleteCloudflarePreview({ + runWrangler: connection.runWrangler, + workerName, + previewName: args.name, + verifyUploader: connection.assertUploaderStillPinned, + configPath, + }); + if (!result.ok) { + const message = reporter.redactor.redact(formatDeleteError(result, args.name, workerName)); + cliLog.error('cloudflare_preview_delete_failed', new Error(message), { + reason: result.reason, + }); + throw new Error(message); + } + cliLog.info('cloudflare_preview_deleted', { previewName: args.name, deleted: result.deleted }); + if (result.deleted) { + printSuccess(`Deleted the preview ${args.name} of ${workerName}.`); + } else { + log.info(`The preview ${args.name} of ${workerName} does not exist. Nothing to delete.`); + } + } finally { + await cliLog.close().catch(() => {}); + } +} + +function formatDeleteError( + result: Extract, + name: string, + workerName: string, +): string { + switch (result.reason) { + case 'invalid-name': + return `preview: ${result.diagnostic}`; + case 'uploader-changed': + return 'preview: the Cloudflare uploader changed. Nothing was deleted.'; + case 'delete-failed': + return [ + `preview: Cloudflare could not delete the preview "${name}" of the Worker "${workerName}".`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } +} diff --git a/packages/void/test/unit/cf-build-output.test.ts b/packages/void/test/unit/cf-build-output.test.ts index 0a499d846..b44c4266a 100644 --- a/packages/void/test/unit/cf-build-output.test.ts +++ b/packages/void/test/unit/cf-build-output.test.ts @@ -1171,9 +1171,25 @@ it('bundles a generated static Worker and staged assets into prebuilt cf output' expect(built.workers.default.config.manifest?.mainModule).toBe('index.js'); expect(built.workers.default.assetsDir).toBeDefined(); expect(prepared.assetsDirectory).toBe(toSlash(assets)); + expect(built.rootConfig.buildContext.isPreview).toBe(false); expectCfDryRun(prepared.directory, ['deploy']); }, ); + // `cf previews deploy` accepts only output marked as a Preview build. + await withPrepared( + prepareCfStaticBuildOutput({ + projectRoot: root, + configPath, + assetsDirectory: assets, + accountId: 'account-id', + isPreview: true, + }), + async (prepared) => { + const built = await readBuildOutput(prepared.directory); + expect(built.rootConfig.buildContext.isPreview).toBe(true); + expectCfDryRun(prepared.directory, ['previews', 'deploy', '--preview-name=pr-1']); + }, + ); }); /** The comment line `void domain add` writes, in the format of writeWranglerPublishedTrafficSnapshot. */ diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index 558f71af1..7054c71f9 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -3327,3 +3327,64 @@ describe('settings credential before activation', () => { } }); }); + +it('deploys a named Preview from the prebuilt output without touching versions or traffic', async () => { + const prepared = await output(); + try { + const calls: Array<{ args: Array; cwd: string | undefined }> = []; + const verified: Array = []; + const preview = { + type: 'preview', + preview_id: 'prv_1', + preview_name: 'pr-64', + preview_urls: ['https://pr-64-void-test.team.workers.dev'], + deployment_id: 'dep_1', + deployment_urls: ['https://dep1-void-test.team.workers.dev'], + }; + const runner = createCfVersionRunner({ + output: prepared, + workerName: 'void-test', + verifyResources: async (directory) => { + verified.push(directory); + return { status: 0, stdout: '', stderr: '' }; + }, + runCf: (args, run) => { + calls.push({ args, cwd: run.cwd }); + return { + status: 0, + // Provider lines may precede the JSON record. + stdout: `Uploading assets\n${JSON.stringify(preview, null, 2)}\n`, + stderr: '', + }; + }, + }); + const result = await runner( + { type: 'previews.deploy', workerName: 'void-test', previewName: 'pr-64' }, + { capture: true }, + ); + expect(result.status).toBe(0); + expect(result.data).toEqual({ + previewId: 'prv_1', + previewName: 'pr-64', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-void-test.team.workers.dev', + deploymentUrl: 'https://dep1-void-test.team.workers.dev', + }); + expect(verified).toEqual([prepared.directory]); + expect(calls).toEqual([ + { + args: ['previews', 'deploy', '--prebuilt', '--preview-name=pr-64'], + cwd: prepared.directory, + }, + ]); + + const moved = await runner( + { type: 'previews.deploy', workerName: 'other-worker', previewName: 'pr-64' }, + { capture: true }, + ); + expect(moved.status).not.toBe(0); + expect(calls).toHaveLength(1); + } finally { + prepared.dispose(); + } +}); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 3f3017be8..82976f321 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12410,3 +12410,158 @@ describe('runCloudflareDeploy — `addresses` is whole-object pinned across the expect(dropped.reason).toMatch(/addresses/); }); }); + +describe('runCloudflareDeploy — previews', () => { + // What the cf runner decodes from `cf previews deploy`. + const previewRecord: Record = { + previewId: 'prv_1', + previewName: 'pr-64', + deploymentId: 'dep_1', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }; + + function previewHarness(record: unknown = previewRecord) { + const base = harness(); + const wranglerArgs: Array> = []; + const activateVersion = vi.fn(base.deps.activateVersion!); + const runWrangler = operationFixture((args) => { + wranglerArgs.push(args); + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + if (args[0] === 'preview') { + return { ...cleanExit, stdout: JSON.stringify(record) }; + } + return cleanExit; + }); + return { + deps: { ...base.deps, runWrangler, activateVersion } satisfies CloudflareDeployDeps, + exitCalls: base.exitCalls, + wranglerArgs, + activateVersion, + }; + } + + const spa = () => + makeProject({ + 'package.json': JSON.stringify({ name: 'spaapp' }), + 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'dist/index.html': '
', + }); + + it('deploys a named Preview without activating, moving traffic or recording production state', async () => { + const root = spa(); + const { deps, exitCalls, wranglerArgs, activateVersion } = previewHarness(); + const output = await captureDeployOutput(() => + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ); + + expect(exitCalls).toEqual([]); + expect(activateVersion).not.toHaveBeenCalled(); + // Only the session check and the Preview deploy reach Cloudflare: no version upload, + // deployment, traffic split, trigger or secret operation. + expect(wranglerArgs.map((args) => args.slice(0, 1))).toEqual([['whoami'], ['preview']]); + expect(wranglerArgs[1]).toEqual( + expect.arrayContaining(['--preview-name', 'pr-64', '--name', 'spaapp']), + ); + expect(existsSync(join(root, '.void/cloudflare-candidate.json'))).toBe(false); + expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toEqual({ + account_id: 'acc123', + }); + expect(output).toContain('spaapp → Cloudflare Preview pr-64'); + expect(output).toContain('https://pr-64-spaapp.team.workers.dev'); + expect(output).toContain('Preview pr-64 deployed. Production is unchanged.'); + }); + + it('prints one JSON record on stdout and keeps the logs on stderr', async () => { + const root = spa(); + const { deps, exitCalls } = previewHarness(); + const stdout: Array = []; + const stderr: Array = []; + const out = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { + stdout.push(String(chunk)); + return true; + }); + const err = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { + stderr.push(String(chunk)); + return true; + }); + const { setProgressOutput } = await import('../../src/cli/output.ts'); + try { + // As runDeploy does for --json. + setProgressOutput(process.stderr); + await runCloudflareDeploy( + root, + { platform: 'cloudflare', preview: 'pr-64', json: true }, + silentCliLog, + deps, + ); + } finally { + setProgressOutput(undefined); + out.mockRestore(); + err.mockRestore(); + } + + expect(exitCalls).toEqual([]); + expect(stdout).toHaveLength(1); + expect(JSON.parse(stdout[0]!)).toEqual({ + workerName: 'spaapp', + previewName: 'pr-64', + previewUrl: 'https://pr-64-spaapp.team.workers.dev', + deploymentId: 'dep_1', + deploymentUrl: 'https://dep1-spaapp.team.workers.dev', + }); + expect(stripVTControlCharacters(stderr.join(''))).toContain('Production is unchanged'); + }); + + it('fails clearly when the Worker has Preview URLs turned off', async () => { + const root = spa(); + const { previewUrl: _, ...withoutUrl } = previewRecord; + const { deps, exitCalls } = previewHarness(withoutUrl); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('Preview URLs are turned off'); + expect(output).toContain('preview_urls: true in the cloudflare field of void.config.ts'); + }); + + it('rejects a name too long for the Worker before building or uploading', async () => { + const root = spa(); + const { deps, exitCalls, wranglerArgs } = previewHarness(); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy( + root, + { platform: 'cloudflare', preview: `pr-${'1'.repeat(60)}` }, + silentCliLog, + deps, + ), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('63 characters'); + expect(wranglerArgs.some((args) => args[0] === 'preview')).toBe(false); + }); + + it('refuses an app that needs a Worker before any Cloudflare operation', async () => { + const root = makeProject({ + 'package.json': JSON.stringify({ name: 'workerapp' }), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'routes/index.ts': 'export const GET = () => "hi";\n', + }); + const { deps, exitCalls, wranglerArgs } = previewHarness(); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ).rejects.toThrow(ExitError), + ); + expect(exitCalls).toEqual([1]); + expect(output).toContain('--preview currently supports static sites and single-page apps'); + expect(wranglerArgs).toEqual([]); + }); +}); diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 4d8a5dc63..7fbfa32a8 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -157,3 +157,38 @@ describe('parseDeployArgs', () => { }); }); }); + +describe('parseDeployArgs --preview', () => { + it('parses a Cloudflare preview with JSON output', () => { + expect( + parseDeployArgs(['--platform', 'cloudflare', '--skip-build', '--preview', 'pr-64', '--json']), + ).toMatchObject({ platform: 'cloudflare', skipBuild: true, preview: 'pr-64', json: true }); + }); + + it('requires --platform cloudflare and a name', () => { + expect(() => parseDeployArgs(['--preview', 'pr-64'])).toThrow( + '--preview requires --platform cloudflare', + ); + expect(() => parseDeployArgs(['--platform', 'void', '--preview', 'pr-64'])).toThrow( + '--preview requires --platform cloudflare', + ); + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview'])).toThrow( + '--preview requires a name', + ); + expect(() => + parseDeployArgs(['--platform', 'cloudflare', '--preview', 'a', '--preview', 'b']), + ).toThrow('only be specified once'); + }); + + it.each(['--atomic', '--provision', '--require-email'])('rejects %s with --preview', (flag) => { + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview', 'pr-64', flag])).toThrow( + `${flag} cannot be combined with --preview`, + ); + }); + + it('accepts --json only with --preview', () => { + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--json'])).toThrow( + '--json is available only with --preview', + ); + }); +}); diff --git a/packages/void/test/unit/preview-args.test.ts b/packages/void/test/unit/preview-args.test.ts new file mode 100644 index 000000000..9300ba6ac --- /dev/null +++ b/packages/void/test/unit/preview-args.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from 'vite-plus/test'; +import { parsePreviewArgs } from '../../src/cli/preview-args.ts'; + +describe('parsePreviewArgs', () => { + it('parses delete with a name', () => { + expect(parsePreviewArgs(['delete', 'pr-64'])).toEqual({ subcommand: 'delete', name: 'pr-64' }); + }); + + it('rejects missing, unknown and extra arguments', () => { + expect(() => parsePreviewArgs([])).toThrow('void preview delete '); + expect(() => parsePreviewArgs(['list'])).toThrow('void preview delete '); + expect(() => parsePreviewArgs(['delete'])).toThrow('requires a preview name'); + expect(() => parsePreviewArgs(['delete', '--force'])).toThrow('requires a preview name'); + expect(() => parsePreviewArgs(['delete', 'pr-64', 'pr-65'])).toThrow('Unexpected argument'); + }); +}); From cd7f22018749dd7d35ced37e6d3eb6aab204a2c7 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 17:21:46 +0800 Subject: [PATCH 02/12] fix: lint after merging main Use top-level type imports, numeric separators, type guards instead of casts, and no non-null assertions or trailing-slash regex in the preview code that came in with the merge. Co-Authored-By: Claude Opus 5.5 --- packages/deploy-cloudflare/src/preview.ts | 24 ++++++++++--------- .../test/unit/preview.test.ts | 4 ++-- packages/void/src/cli/cf-command-values.ts | 17 +++++++++---- .../void/src/cli/deploy-cloudflare-static.ts | 2 +- packages/void/src/cli/preview-cmd.ts | 2 +- .../void/test/unit/cf-version-runner.test.ts | 2 +- .../void/test/unit/cloudflare-deploy.test.ts | 4 ++-- 7 files changed, 32 insertions(+), 23 deletions(-) diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts index bf9cabaef..fdbff2080 100644 --- a/packages/deploy-cloudflare/src/preview.ts +++ b/packages/deploy-cloudflare/src/preview.ts @@ -1,11 +1,7 @@ import { isRecord } from '@void/deploy-core'; import { commandDiagnosticFields } from './diagnostics.ts'; -import { - isCleanCommandExit, - isCompletedCommand, - isWorkerNotFound, - type CloudflareCommandRunner, -} from './execute.ts'; +import { isCleanCommandExit, isCompletedCommand, isWorkerNotFound } from './execute.ts'; +import type { CloudflareCommandRunner } from './execute.ts'; import type { CloudflarePreviewUploadResult } from './operations.ts'; /** @@ -16,7 +12,7 @@ const PREVIEW_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; /** A DNS label holds at most 63 characters. */ const MAX_HOST_LABEL = 63; /** Cloudflare's "Preview not found" API error. */ -const PREVIEW_NOT_FOUND = 10025; +const PREVIEW_NOT_FOUND = 10_025; /** Return why `name` cannot name a Preview of `workerName`, or null when it can. */ export function validateCloudflarePreviewName(name: string, workerName?: string): string | null { @@ -156,8 +152,6 @@ function readPreviewUploadResult(value: unknown): CloudflarePreviewUploadResult return null; } const { previewId, previewName, deploymentId, previewUrl, deploymentUrl } = value; - const optionalUrl = (url: unknown) => - url === undefined || (typeof url === 'string' && url.startsWith('https://')); if ( typeof previewId !== 'string' || !previewId || @@ -173,7 +167,15 @@ function readPreviewUploadResult(value: unknown): CloudflarePreviewUploadResult previewId, previewName, deploymentId, - ...(previewUrl ? { previewUrl: previewUrl as string } : {}), - ...(deploymentUrl ? { deploymentUrl: deploymentUrl as string } : {}), + ...(isHttpsUrl(previewUrl) ? { previewUrl } : {}), + ...(isHttpsUrl(deploymentUrl) ? { deploymentUrl } : {}), }; } + +function isHttpsUrl(url: unknown): url is string { + return typeof url === 'string' && url.startsWith('https://'); +} + +function optionalUrl(url: unknown): boolean { + return url === undefined || isHttpsUrl(url); +} diff --git a/packages/deploy-cloudflare/test/unit/preview.test.ts b/packages/deploy-cloudflare/test/unit/preview.test.ts index 23c455d02..3c0dc3e0a 100644 --- a/packages/deploy-cloudflare/test/unit/preview.test.ts +++ b/packages/deploy-cloudflare/test/unit/preview.test.ts @@ -121,7 +121,7 @@ describe('deleteCloudflarePreview', () => { }); // 10025: "Preview not found", as Cloudflare answered in a live run. 10007: no such Worker. - it.each([10025, 10007])('treats error %i as already deleted', async (errorCode) => { + it.each([10_025, 10_007])('treats error %i as already deleted', async (errorCode) => { const { runWrangler } = runner({ status: 1, errorCode }); expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ ok: true, @@ -130,7 +130,7 @@ describe('deleteCloudflarePreview', () => { }); it('reports other failures', async () => { - const { runWrangler } = runner({ status: 1, errorCode: 10000 }); + const { runWrangler } = runner({ status: 1, errorCode: 10_000 }); expect(await deleteCloudflarePreview({ ...target, runWrangler })).toMatchObject({ ok: false, reason: 'delete-failed', diff --git a/packages/void/src/cli/cf-command-values.ts b/packages/void/src/cli/cf-command-values.ts index 9c914cd28..11ee4119e 100644 --- a/packages/void/src/cli/cf-command-values.ts +++ b/packages/void/src/cli/cf-command-values.ts @@ -47,7 +47,7 @@ export function readCfPreviewDeployOutput( ): CloudflarePreviewUploadResult | undefined { const lines = stdout.trim().split('\n'); for (let index = lines.length - 1; index >= 0; index--) { - if (!lines[index]!.startsWith('{')) { + if (lines[index]?.startsWith('{') !== true) { continue; } let record: unknown; @@ -60,10 +60,8 @@ export function readCfPreviewDeployOutput( return undefined; } const value = record; - const first = (urls: unknown) => - Array.isArray(urls) && typeof urls[0] === 'string' ? urls[0].replace(/\/$/, '') : undefined; - const previewUrl = first(value.preview_urls); - const deploymentUrl = first(value.deployment_urls); + const previewUrl = firstUrl(value.preview_urls); + const deploymentUrl = firstUrl(value.deployment_urls); return typeof value.preview_id === 'string' && typeof value.preview_name === 'string' && typeof value.deployment_id === 'string' @@ -78,3 +76,12 @@ export function readCfPreviewDeployOutput( } return undefined; } + +/** The first URL of a cf URL list, without a trailing slash. */ +function firstUrl(urls: unknown): string | undefined { + const url: unknown = Array.isArray(urls) ? urls[0] : undefined; + if (typeof url !== 'string') { + return undefined; + } + return url.endsWith('/') ? url.slice(0, -1) : url; +} diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 1abc97b3c..8550ef6ec 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -13,8 +13,8 @@ import { writeCloudflareStaticDeployConfig, assertExistingCloudflareConfig, validateCloudflarePreviewName, - type CloudflarePreviewDeployResult, } from '@void/deploy-cloudflare'; +import type { CloudflarePreviewDeployResult } from '@void/deploy-cloudflare'; import { dirname, join, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; import { analyzeApplication } from '../application-routing.ts'; diff --git a/packages/void/src/cli/preview-cmd.ts b/packages/void/src/cli/preview-cmd.ts index 2f6e8c04c..a59d547c6 100644 --- a/packages/void/src/cli/preview-cmd.ts +++ b/packages/void/src/cli/preview-cmd.ts @@ -2,8 +2,8 @@ import { deleteCloudflarePreview, parseRootWranglerConfig, readWranglerTopLevelString, - type CloudflarePreviewDeleteResult, } from '@void/deploy-cloudflare'; +import type { CloudflarePreviewDeleteResult } from '@void/deploy-cloudflare'; import { createCloudflareChildReporter } from './cloudflare-child-report.ts'; import { confirmCloudflareDeployAuthentication, diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index 83e2eca9a..cb21440a4 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -3438,6 +3438,6 @@ it('deploys a named Preview from the prebuilt output without touching versions o expect(moved.status).not.toBe(0); expect(calls).toHaveLength(1); } finally { - prepared.dispose(); + await prepared.dispose(); } }); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 017890f60..74ce21866 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12782,7 +12782,7 @@ describe('runCloudflareDeploy — previews', () => { function previewHarness(record: unknown = previewRecord) { const base = harness(); const wranglerArgs: Array> = []; - const activateVersion = vi.fn(base.deps.activateVersion!); + const activateVersion = vi.fn(base.deps.activateVersion); const runWrangler = operationFixture((args) => { wranglerArgs.push(args); if (args[0] === 'whoami') { @@ -12864,7 +12864,7 @@ describe('runCloudflareDeploy — previews', () => { expect(exitCalls).toEqual([]); expect(stdout).toHaveLength(1); - expect(JSON.parse(stdout[0]!)).toEqual({ + expect(JSON.parse(stdout[0] ?? '')).toEqual({ workerName: 'spaapp', previewName: 'pr-64', previewUrl: 'https://pr-64-spaapp.team.workers.dev', From 9c4352a7090bc12044a0388c6c7e202f6d7d6bfd Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 17:24:27 +0800 Subject: [PATCH 03/12] refactor(cli): run deploy --json in a child process `void deploy --preview --json` now runs like `void db execute --json`: the deploy runs in a child whose stdout is our stderr, and only the result the child writes to fd 3 reaches stdout. Errors, parse errors and output from void.config.ts no longer mix with the record. The shared runner is renamed to json-command-process.ts, and the progress-stream plumbing in output.ts, deploy-helpers.ts and deploy-summary.ts is dropped. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/args.ts | 2 +- packages/void/src/cli/cli-main.ts | 24 +++++--- .../void/src/cli/deploy-cloudflare-static.ts | 31 ++++------ packages/void/src/cli/deploy-helpers.ts | 27 ++------- packages/void/src/cli/deploy-summary.ts | 3 +- packages/void/src/cli/deploy-types.ts | 5 ++ packages/void/src/cli/deploy.ts | 10 +--- ...ute-process.ts => json-command-process.ts} | 26 +++++--- packages/void/src/cli/output.ts | 41 +------------ .../void/test/unit/cloudflare-deploy.test.ts | 42 +++++-------- .../void/test/unit/deploy-json-stdout.test.ts | 60 +++++++++++++++++++ packages/void/vite.config.ts | 3 +- 12 files changed, 143 insertions(+), 131 deletions(-) rename packages/void/src/cli/{db-execute-process.ts => json-command-process.ts} (63%) create mode 100644 packages/void/test/unit/deploy-json-stdout.test.ts diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index af27eb316..b641ec626 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -3,7 +3,7 @@ import type { RunDeployOptions } from './deploy-types.ts'; export function parseDeployArgs( args: Array, -): Omit { +): Omit { let parsed: ReturnType; try { parsed = parseArgs({ diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index ca85619ce..0e9d94088 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -198,8 +198,8 @@ const subcommandGroups = { db: () => runSubcommandGroup('db', dbSubcommands, parseDbArgs, async (root, parsed) => { if (parsed.action === 'execute' && parsed.json) { - const { runDbExecuteProcess } = await import('./db-execute-process.ts'); - await runDbExecuteProcess(root, args); + const { runJsonCommandProcess } = await import('./json-command-process.ts'); + await runJsonCommandProcess(root, args); } else { const { runDbCommand } = await import('./db.ts'); await runDbCommand(root, parsed); @@ -240,15 +240,23 @@ if (helpPath) { try { deployArgs = parseDeployArgs(args.slice(1)); } catch (err) { - log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); + log.error( + formatCloudflareUserMessage(err instanceof Error ? err.message : String(err)), + args.includes('--json') ? { output: process.stderr } : undefined, + ); process.exit(1); } - const { runDeploy } = await import('./deploy.ts'); - await runDeploy(root, deployArgs).catch((err: unknown) => { - log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); - process.exit(1); - }); + if (deployArgs.json) { + const { runJsonCommandProcess } = await import('./json-command-process.ts'); + await runJsonCommandProcess(root, args); + } else { + const { runDeploy } = await import('./deploy.ts'); + await runDeploy(root, deployArgs).catch((err: unknown) => { + log.error(formatCloudflareUserMessage(err instanceof Error ? err.message : String(err))); + process.exit(1); + }); + } } else if (command === 'connect') { await (async () => { const parsed = parseConnectArgs(args.slice(1)); diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 8550ef6ec..fa516598a 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -68,7 +68,7 @@ import { import type { RunDeployOptions, CloudflareDeployDeps } from './deploy-types.ts'; import { readGeneratedAssetHeadersFile } from './headers.ts'; import type { CliLogger } from './log-file.ts'; -import { getErrorMessage, note, printJsonRecord, printSuccess, progressOutput } from './output.ts'; +import { getErrorMessage, note, printSuccess } from './output.ts'; import { buildStaticManifest, readWranglerHtmlHandling } from './package.ts'; import { detectPreset } from './preset.ts'; import type { StaticPreset, FrameworkPreset } from './preset.ts'; @@ -407,12 +407,7 @@ export async function runCloudflareStaticDeploy( const runStaticBuild = deps.runStaticBuild ?? ((command: string, env: NodeJS.ProcessEnv) => { - // With --json, stdout carries only the result record. - execSync(command, { - cwd: root, - stdio: ['inherit', progressOutput(), 'inherit'], - env, - }); + execSync(command, { cwd: root, stdio: 'inherit', env }); }); try { runStaticBuild(preset.buildCommand, buildChildEnv); @@ -547,7 +542,7 @@ export async function runCloudflareStaticDeploy( previewName: options.preview, workerName, typeLabel, - json: options.json === true, + writeResult: options.writeResult, reporter, cliLog, exit, @@ -617,7 +612,7 @@ function reportCloudflareStaticPreview( previewName: string; workerName: string; typeLabel: string; - json: boolean; + writeResult: RunDeployOptions['writeResult']; reporter: CloudflareChildReporter; cliLog: CliLogger; exit: (code: number) => never; @@ -639,15 +634,15 @@ function reportCloudflareStaticPreview( previewId: result.previewId, deploymentId: result.deploymentId, }); - if (options.json) { - printJsonRecord({ - workerName, - previewName, - previewUrl: result.previewUrl, - deploymentId: result.deploymentId, - deploymentUrl: result.deploymentUrl ?? null, - }); - } + const record = { + type: 'preview', + workerName, + previewName, + previewUrl: result.previewUrl, + deploymentId: result.deploymentId, + deploymentUrl: result.deploymentUrl ?? null, + }; + options.writeResult?.(`${JSON.stringify(record)}\n`); note( [ formatDeploySummary({ workerName, typeLabel: options.typeLabel }), diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index dd118c3ea..7a00f3130 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -1,6 +1,5 @@ import { execSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; -import type { Writable } from 'node:stream'; import { isCancel, log as clackLog, text } from '@voidzero-dev/vite-plus-prompts'; import { join, resolve } from 'pathslash'; import { findEnvFile } from '../codegen/env-types.ts'; @@ -23,7 +22,7 @@ import type { } from './deploy-types.ts'; import { fetchRemoteSecretNames, formatEnvReport, validateProdEnv } from './env-validation.ts'; import type { CliLogger } from './log-file.ts'; -import { formatCount, getErrorMessage, pc, progressOptions } from './output.ts'; +import { formatCount, getErrorMessage, pc } from './output.ts'; import { detectPreset, formatProjectCommand, resolveProjectCommand } from './preset.ts'; import type { StaticPreset } from './preset.ts'; import { attachSelectedPlatform, shouldLinkDeployProject, writeProjectConfig } from './project.ts'; @@ -41,29 +40,15 @@ import type { LiveBindingConfig, WranglerCompat } from './wrangler.ts'; import type { WrapperFeatures } from './wrapper.ts'; import { needsWrapper, generateWrapper } from './wrapper.ts'; -/** Format a Cloudflare message and send it to the progress stream a `--json` command chose. */ -function progressLog( - write: (message: string, options?: { output?: Writable }) => void, - message: string, -): void { - const formatted = formatCloudflareUserMessage(message); - const options = progressOptions(); - if (options.output) { - write(formatted, options); - } else { - write(formatted); - } -} - export const log: Record< 'error' | 'info' | 'message' | 'step' | 'warn', (message: string) => void > = { - error: (message: string) => progressLog(clackLog.error, message), - info: (message: string) => progressLog(clackLog.info, message), - message: (message: string) => progressLog(clackLog.message, message), - step: (message: string) => progressLog(clackLog.step, message), - warn: (message: string) => progressLog(clackLog.warn, message), + error: (message: string) => clackLog.error(formatCloudflareUserMessage(message)), + info: (message: string) => clackLog.info(formatCloudflareUserMessage(message)), + message: (message: string) => clackLog.message(formatCloudflareUserMessage(message)), + step: (message: string) => clackLog.step(formatCloudflareUserMessage(message)), + warn: (message: string) => clackLog.warn(formatCloudflareUserMessage(message)), }; export class DeployEventError extends Error {} diff --git a/packages/void/src/cli/deploy-summary.ts b/packages/void/src/cli/deploy-summary.ts index 4c8397bd9..9a328e90e 100644 --- a/packages/void/src/cli/deploy-summary.ts +++ b/packages/void/src/cli/deploy-summary.ts @@ -1,10 +1,9 @@ import { intro } from '@voidzero-dev/vite-plus-prompts'; -import { formatCount, pc, printSuccess, progressOptions, sanitizeTerminalText } from './output.ts'; +import { formatCount, pc, printSuccess, sanitizeTerminalText } from './output.ts'; export function printDeployContext(project: string, destination: string): void { intro( `${pc.dim(sanitizeTerminalText(project))} ${pc.dim('→')} ${pc.blue(sanitizeTerminalText(destination))}`, - progressOptions(), ); } diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index 6f40a01b3..fec9064c7 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -59,6 +59,11 @@ export type RunDeployOptions = { preview?: string; /** Print the deployment result as one JSON record on stdout; logs go to stderr. */ json?: boolean; + /** + * Internal: receives the `--json` result record. Only the `--json` child process sets it; its + * stdout is the parent's stderr. + */ + writeResult?: (text: string) => void; /** * `CF_ACCESS_READINESS_ORIGIN` as recorded before project code ran (`null` when unset). * `--platform cloudflare` only. diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 9df928cc6..5ff6d329f 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -37,7 +37,6 @@ import type { CliLogger } from './log-file.ts'; import { buildDeployLogSummary } from './log-summary.ts'; import { promptForLoginToken } from './login.ts'; import { migrateLegacyVoidConfig } from './migrate.ts'; -import { setProgressOutput } from './output.ts'; import { listPlatformConnections } from './platform-registry.ts'; import { detectPreset, FRAMEWORK_PRESETS } from './preset.ts'; import type { FrameworkPreset } from './preset.ts'; @@ -58,14 +57,7 @@ export function resolveDeploymentPlatform( export async function runDeploy(root: string, options?: RunDeployOptions): Promise { // The Cloudflare link check can evaluate void.config.ts, so record operator input first. options = withRecordedReadinessAccessOrigin(options ?? {}); - if (options.json) { - // stdout carries only the result record. Kept for the rest of the process, so the CLI's own - // report of a thrown error also goes to stderr. - setProgressOutput(process.stderr); - process.stderr.write('\n'); - } else { - console.log(); - } + console.log(); const cliLog = openDeployLog({ mirrorToStderr: options?.debug === true || process.env.VOID_DEPLOY_DEBUG === '1', diff --git a/packages/void/src/cli/db-execute-process.ts b/packages/void/src/cli/json-command-process.ts similarity index 63% rename from packages/void/src/cli/db-execute-process.ts rename to packages/void/src/cli/json-command-process.ts index d08b26c97..b2442ba80 100644 --- a/packages/void/src/cli/db-execute-process.ts +++ b/packages/void/src/cli/json-command-process.ts @@ -5,11 +5,15 @@ import { log } from '@voidzero-dev/vite-plus-prompts'; import { formatCloudflareUserMessage } from './cloudflare-user-output.ts'; import { Buffer } from './node-buffer.ts'; -const CHILD_COMMAND = '__void-db-execute-json__'; +const CHILD_COMMAND = '__void-json-command__'; const RESULT_FD = 3; -/** Keep config output on stderr, including writes to fd 1 and output from its children. */ -export async function runDbExecuteProcess( +/** + * Run a `--json` command (`db execute` or `deploy`) in a child process whose stdout is our + * stderr, so config output, including writes to fd 1 and output from its children, never reaches + * stdout. Only the result the child writes to fd 3 is printed, and only on success. + */ +export async function runJsonCommandProcess( root: string, args: ReadonlyArray, ): Promise { @@ -51,10 +55,18 @@ if (process.argv[2] === CHILD_COMMAND) { try { // Keep the CLI arguments visible to project config evaluated by this process. process.argv.splice(1, 2); - const { parseDbArgs } = await import('./db-args.ts'); - const args = parseDbArgs(process.argv.slice(3)); - const { runDbCommand } = await import('./db.ts'); - await runDbCommand(process.cwd(), args, (text) => writeFileSync(RESULT_FD, text)); + const writeResult = (text: string) => writeFileSync(RESULT_FD, text); + // `.at()`, as TypeScript still narrows `argv[2]` to the marker after the splice. + if (process.argv.at(2) === 'deploy') { + const { parseDeployArgs } = await import('./args.ts'); + const { runDeploy } = await import('./deploy.ts'); + await runDeploy(process.cwd(), { ...parseDeployArgs(process.argv.slice(3)), writeResult }); + } else { + const { parseDbArgs } = await import('./db-args.ts'); + const args = parseDbArgs(process.argv.slice(3)); + const { runDbCommand } = await import('./db.ts'); + await runDbCommand(process.cwd(), args, writeResult); + } } catch (error) { log.error(formatCloudflareUserMessage(error instanceof Error ? error.message : String(error)), { output: process.stderr, diff --git a/packages/void/src/cli/output.ts b/packages/void/src/cli/output.ts index a832a97c7..d8cc5c81b 100644 --- a/packages/void/src/cli/output.ts +++ b/packages/void/src/cli/output.ts @@ -28,41 +28,10 @@ export function formatUrl(url: string): string { return formatLink(text, text); } -let progressStream: Writable | undefined; - -/** - * Choose where Void's progress output goes. `--json` commands send it to stderr so stdout carries - * only their result record. Pass undefined to restore stdout. - */ -export function setProgressOutput(stream: Writable | undefined): void { - progressStream = stream; -} - -/** The stream Void's progress renderers write to: stdout unless a `--json` command chose stderr. */ -export function progressOutput(): Writable { - return progressStream ?? process.stdout; -} - -/** - * Renderer options that route output to the chosen progress stream. Empty unless a `--json` - * command chose one, so ordinary runs call the renderers exactly as before. - */ -export function progressOptions(): { output?: Writable } { - return progressStream ? { output: progressStream } : {}; -} - -/** Print one machine-readable JSON record on stdout. */ -export function printJsonRecord(record: unknown): void { - process.stdout.write(`${JSON.stringify(record)}\n`); -} - /** Complete an action with the same spacing, checkmark, and color on every target. */ export function printSuccess(message: string): void { // Remove nested styles so a blue URL or dim hint cannot override the success color. - outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { - withGuide: false, - ...progressOptions(), - }); + outro(`\n${pc.green(`✓ ${stripVTControlCharacters(message)}`)}`, { withGuide: false }); } /** @@ -191,15 +160,11 @@ export function note(...args: Parameters): void { const urlTitle = plainTitle && /^https?:\/\/\S+$/.test(plainTitle) ? plainTitle : undefined; // Native macOS Terminal recognizes URLs by whitespace boundaries. const boxedTitle = urlTitle ? ` ${urlTitle} ` : title; - const output = opts?.output ?? progressOutput(); + const output = opts?.output ?? process.stdout; const columns = (output as { columns?: unknown }).columns; const needsWidthFallback = typeof columns === 'number' && columns < MIN_NOTE_COLUMNS; if (!urlTitle && !needsWidthFallback) { - if (opts?.output || !progressStream) { - promptsNote(...args); - } else { - promptsNote(message, title, { ...opts, output }); - } + promptsNote(...args); return; } // The box renderer only reads `columns` and calls `write()`. diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 74ce21866..ac18c9307 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12833,45 +12833,35 @@ describe('runCloudflareDeploy — previews', () => { expect(output).toContain('Preview pr-64 deployed. Production is unchanged.'); }); - it('prints one JSON record on stdout and keeps the logs on stderr', async () => { + it('gives writeResult exactly one preview record', async () => { const root = spa(); const { deps, exitCalls } = previewHarness(); - const stdout: Array = []; - const stderr: Array = []; - const out = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => { - stdout.push(String(chunk)); - return true; - }); - const err = vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => { - stderr.push(String(chunk)); - return true; - }); - const { setProgressOutput } = await import('../../src/cli/output.ts'); - try { - // As runDeploy does for --json. - setProgressOutput(process.stderr); - await runCloudflareDeploy( + const results: Array = []; + await captureDeployOutput(() => + runCloudflareDeploy( root, - { platform: 'cloudflare', preview: 'pr-64', json: true }, + { + platform: 'cloudflare', + preview: 'pr-64', + json: true, + writeResult: (text) => results.push(text), + }, silentCliLog, deps, - ); - } finally { - setProgressOutput(undefined); - out.mockRestore(); - err.mockRestore(); - } + ), + ); expect(exitCalls).toEqual([]); - expect(stdout).toHaveLength(1); - expect(JSON.parse(stdout[0] ?? '')).toEqual({ + expect(results).toHaveLength(1); + expect(results[0]?.endsWith('}\n')).toBe(true); + expect(JSON.parse(results[0] ?? '')).toEqual({ + type: 'preview', workerName: 'spaapp', previewName: 'pr-64', previewUrl: 'https://pr-64-spaapp.team.workers.dev', deploymentId: 'dep_1', deploymentUrl: 'https://dep1-spaapp.team.workers.dev', }); - expect(stripVTControlCharacters(stderr.join(''))).toContain('Production is unchanged'); }); it('fails clearly when the Worker has Preview URLs turned off', async () => { diff --git a/packages/void/test/unit/deploy-json-stdout.test.ts b/packages/void/test/unit/deploy-json-stdout.test.ts new file mode 100644 index 000000000..1b4ff3d21 --- /dev/null +++ b/packages/void/test/unit/deploy-json-stdout.test.ts @@ -0,0 +1,60 @@ +import { spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, expect, it } from 'vite-plus/test'; + +const roots: Array = []; +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +const cli = fileURLToPath(new URL('../../dist/cli/cli.mjs', import.meta.url)); + +function runVoid(root: string, args: Array) { + return spawnSync(process.execPath, [cli, ...args], { + cwd: root, + encoding: 'utf8', + timeout: 30_000, + env: { ...process.env, CI: '1', NO_COLOR: '1' }, + }); +} + +it('keeps config output and failures off `void deploy --json` stdout', () => { + const root = mkdtempSync(join(tmpdir(), 'void-deploy-json-stdout-')); + roots.push(root); + writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'workerapp' })); + writeFileSync( + join(root, 'void.config.ts'), + `import { writeSync } from 'node:fs'; +console.log('config log'); +writeSync(1, 'config fd\\n'); +export default {}; +`, + ); + mkdirSync(join(root, 'routes')); + writeFileSync(join(root, 'routes/index.ts'), 'export const GET = () => "hi";\n'); + + // A Worker app is refused before any Cloudflare call, after void.config.ts ran. + const refused = runVoid(root, [ + 'deploy', + '--platform', + 'cloudflare', + '--preview', + 'pr-1', + '--json', + ]); + expect(refused.status).toBe(1); + expect(refused.stdout).toBe(''); + expect(refused.stderr).toContain('config log'); + expect(refused.stderr).toContain('config fd'); + expect(refused.stderr).toContain('--preview currently supports static sites'); + + const parseError = runVoid(root, ['deploy', '--json']); + expect(parseError.status).toBe(1); + expect(parseError.stdout).toBe(''); + expect(parseError.stderr).toContain('--json is available only with --preview'); +}); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index cf90d1b51..364144c08 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -140,7 +140,8 @@ export default defineConfig({ 'src/pages/serialize.ts', 'src/pages/islands-plugin.ts', 'src/cli/cli.ts', - 'src/cli/db-execute-process.ts', + // Runs `db execute --json` and `deploy --json` with stdout kept for the result. + 'src/cli/json-command-process.ts', // Stable entry that deploy spawns as an isolated child. 'src/cli/env-schema-probe.ts', // Private typed Cloudflare transport, spawned by deployment orchestrators. From 3de6440e91ec82d711a4f952be2352ce10b2cf81 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 17:29:53 +0800 Subject: [PATCH 04/12] feat(cli): void project preview delete Move preview cleanup next to rollback as `void project preview delete [--platform cloudflare]`, so it does not clash with `vp preview`. It uses the same Worker and account as rollback and logs. A Preview that does not exist is not an error; a missing Worker or any other failure exits 1. The name is checked before any config is read. The top-level `void preview` command, its help and the uploader opt-out in the deploy helpers are removed. Co-Authored-By: Claude Opus 5.5 --- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/preview.ts | 56 +++++++++--- .../test/operation-fixture.ts | 8 +- .../test/unit/preview.test.ts | 61 +++++++++---- packages/void/src/cli/cli-main.ts | 18 +--- packages/void/src/cli/cloudflare-preview.ts | 48 ++++++++++ .../void/src/cli/deploy-cloudflare-helpers.ts | 13 +-- packages/void/src/cli/help.ts | 40 ++++---- packages/void/src/cli/preview-args.ts | 25 ----- packages/void/src/cli/preview-cmd.ts | 91 ------------------- packages/void/src/cli/project-args.ts | 39 +++++++- packages/void/src/cli/project-cmd.ts | 10 ++ .../unit/cloudflare-operation-process.test.ts | 35 +++++++ packages/void/test/unit/preview-args.test.ts | 16 ---- packages/void/test/unit/project-args.test.ts | 28 ++++++ .../void/test/unit/project-preview.test.ts | 83 +++++++++++++++++ 16 files changed, 361 insertions(+), 211 deletions(-) create mode 100644 packages/void/src/cli/cloudflare-preview.ts delete mode 100644 packages/void/src/cli/preview-args.ts delete mode 100644 packages/void/src/cli/preview-cmd.ts delete mode 100644 packages/void/test/unit/preview-args.test.ts create mode 100644 packages/void/test/unit/project-preview.test.ts diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index b495c5cab..82975c9a1 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -56,6 +56,7 @@ export { } from './version.ts'; export { deleteCloudflarePreview, + cloudflarePreviewNameProblem, deployCloudflarePreview, validateCloudflarePreviewName, type CloudflarePreviewDeleteResult, diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts index fdbff2080..09af279ef 100644 --- a/packages/deploy-cloudflare/src/preview.ts +++ b/packages/deploy-cloudflare/src/preview.ts @@ -14,6 +14,39 @@ const MAX_HOST_LABEL = 63; /** Cloudflare's "Preview not found" API error. */ const PREVIEW_NOT_FOUND = 10_025; +/** + * Return why `name` cannot name a Preview, or undefined when it can. Cloudflare uses the name + * unchanged as the start of a hostname label, so the URL Void prints is the one CI expects. + */ +export function cloudflarePreviewNameProblem(name: string): string | undefined { + if (name.length === 0 || name.length > MAX_HOST_LABEL) { + return `must be 1 to ${MAX_HOST_LABEL} characters`; + } + if (!isLowercaseLetter(name[0])) { + return 'must start with a lowercase letter'; + } + for (const character of name) { + if (!isLowercaseLetter(character) && !isDigit(character) && character !== '-') { + return 'may use only lowercase letters, digits and hyphens'; + } + } + if (name.endsWith('-')) { + return 'must end with a letter or digit'; + } + if (name.includes('--')) { + return 'cannot have two hyphens in a row'; + } + return undefined; +} + +function isLowercaseLetter(character: string | undefined): boolean { + return character !== undefined && character >= 'a' && character <= 'z'; +} + +function isDigit(character: string): boolean { + return character >= '0' && character <= '9'; +} + /** Return why `name` cannot name a Preview of `workerName`, or null when it can. */ export function validateCloudflarePreviewName(name: string, workerName?: string): string | null { if (!PREVIEW_NAME.test(name)) { @@ -98,27 +131,20 @@ export async function deployCloudflarePreview(options: { export type CloudflarePreviewDeleteResult = | { ok: true; deleted: boolean } - | { ok: false; reason: 'uploader-changed' | 'invalid-name'; diagnostic?: string } + | { ok: false; reason: 'worker-not-found' } | { ok: false; reason: 'delete-failed'; status: number; diagnostic?: string }; /** * Delete a named Preview and all its deployments. A Preview that does not exist is reported as - * `deleted: false`, so a pull-request cleanup job can run more than once. + * `deleted: false`, so a pull-request cleanup job can run more than once. A missing Worker is an + * error: the name or account most likely points somewhere else. */ export async function deleteCloudflarePreview(options: { runWrangler: CloudflareCommandRunner; workerName: string; previewName: string; - verifyUploader: () => boolean; configPath?: string; }): Promise { - const invalid = validateCloudflarePreviewName(options.previewName); - if (invalid) { - return { ok: false, reason: 'invalid-name', diagnostic: invalid }; - } - if (!options.verifyUploader()) { - return { ok: false, reason: 'uploader-changed' }; - } const result = await options.runWrangler( { type: 'previews.delete', @@ -131,13 +157,13 @@ export async function deleteCloudflarePreview(options: { if (isCleanCommandExit(result)) { return { ok: true, deleted: true }; } - // Neither the Preview nor, with 10007, its Worker exists: there is nothing left to delete. - if ( - isWorkerNotFound(result) || - (isCompletedCommand(result) && result.errorCode === PREVIEW_NOT_FOUND) - ) { + // Checked first: "Preview not found" must never read as a missing Worker. + if (isCompletedCommand(result) && result.errorCode === PREVIEW_NOT_FOUND) { return { ok: true, deleted: false }; } + if (isWorkerNotFound(result)) { + return { ok: false, reason: 'worker-not-found' }; + } return { ok: false, reason: 'delete-failed', diff --git a/packages/deploy-cloudflare/test/operation-fixture.ts b/packages/deploy-cloudflare/test/operation-fixture.ts index d31203816..e69f84284 100644 --- a/packages/deploy-cloudflare/test/operation-fixture.ts +++ b/packages/deploy-cloudflare/test/operation-fixture.ts @@ -197,7 +197,13 @@ export function operationFixtureArgs(operation: CloudflareOperation): Array) { const target = { workerName: 'site', previewName: 'pr-64', verifyUploader: () => true }; +describe('cloudflarePreviewNameProblem', () => { + it.each(['pr-64', 'a', 'feature-login', 'a'.repeat(63)])('accepts %s', (name) => { + expect(cloudflarePreviewNameProblem(name)).toBeUndefined(); + }); + + it.each([ + ['', 'must be 1 to 63 characters'], + ['a'.repeat(64), 'must be 1 to 63 characters'], + ['1a', 'must start with a lowercase letter'], + ['-a', 'must start with a lowercase letter'], + ['A', 'must start with a lowercase letter'], + ['a_b', 'may use only lowercase letters, digits and hyphens'], + ['a-', 'must end with a letter or digit'], + ['a--b', 'cannot have two hyphens in a row'], + ])('refuses %j', (name, problem) => { + expect(cloudflarePreviewNameProblem(name)).toBe(problem); + }); +}); + describe('validateCloudflarePreviewName', () => { it.each(['pr-64', 'a', 'feature-login', '0'])('accepts %s', (name) => { expect(validateCloudflarePreviewName(name, 'site')).toBeNull(); @@ -111,30 +131,37 @@ describe('deployCloudflarePreview', () => { }); describe('deleteCloudflarePreview', () => { + const deleteTarget = { workerName: 'site', previewName: 'pr-64' }; + it('deletes the named Preview of the Worker', async () => { const { calls, runWrangler } = runner({}); - expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ + expect(await deleteCloudflarePreview({ ...deleteTarget, runWrangler })).toEqual({ ok: true, deleted: true, }); expect(calls).toEqual([{ type: 'previews.delete', workerName: 'site', previewName: 'pr-64' }]); }); - // 10025: "Preview not found", as Cloudflare answered in a live run. 10007: no such Worker. - it.each([10_025, 10_007])('treats error %i as already deleted', async (errorCode) => { - const { runWrangler } = runner({ status: 1, errorCode }); - expect(await deleteCloudflarePreview({ ...target, runWrangler })).toEqual({ - ok: true, - deleted: false, - }); - }); - - it('reports other failures', async () => { - const { runWrangler } = runner({ status: 1, errorCode: 10_000 }); - expect(await deleteCloudflarePreview({ ...target, runWrangler })).toMatchObject({ - ok: false, - reason: 'delete-failed', - status: 1, - }); + // 10025 is "Preview not found"; 10007 and not-found mean the Worker itself is missing. + it.each([ + [ + { status: 1, errorCode: 10_025 }, + { ok: true, deleted: false }, + ], + [ + { status: 1, errorCode: 10_007 }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, failure: 'not-found' as const }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, errorCode: 10_000, stderr: 'Authentication error' }, + { ok: false, reason: 'delete-failed', status: 1, diagnostic: 'Authentication error' }, + ], + ])('maps %j', async (answer, expected) => { + const { runWrangler } = runner(answer); + expect(await deleteCloudflarePreview({ ...deleteTarget, runWrangler })).toEqual(expected); }); }); diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 0e9d94088..4795f2527 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -23,7 +23,6 @@ import { OperatorClientError } from './operator-client.ts'; import { formatUrl, pc } from './output.ts'; import { parsePlatformArgs, platformSubcommands } from './platform-args.ts'; import { parsePrepareArgs } from './prepare-args.ts'; -import { parsePreviewArgs, previewSubcommands } from './preview-args.ts'; import { projectSubcommands, parseProjectArgs } from './project-args.ts'; import { secretSubcommands, parseSecretArgs } from './secret-args.ts'; import type { SubcommandDef, SubcommandResult } from './subcommand-prompt.ts'; @@ -175,10 +174,6 @@ const subcommandGroups = { runCloudflareCommand(root, parsed), ), ), - preview: () => - runSubcommandGroup('preview', previewSubcommands, parsePreviewArgs, (root, parsed) => - import('./preview-cmd.ts').then(({ runPreviewCommand }) => runPreviewCommand(root, parsed)), - ), project: () => runSubcommandGroup('project', projectSubcommands, parseProjectArgs, (root, parsed) => import('./project-cmd.ts').then(({ runProjectCommand }) => runProjectCommand(root, parsed)), @@ -341,16 +336,7 @@ if (helpPath) { description: 'Inspect persistent resource names in this project', }, { name: 'connect', description: 'Connect to Cloudflare or a Void platform' }, - { - name: 'deploy', - hint: '--platform cloudflare --preview ', - description: 'Build and deploy, or link an existing Cloudflare Worker', - }, - { - name: 'preview', - hint: 'delete', - description: 'Delete a Cloudflare Preview created with void deploy --preview', - }, + { name: 'deploy', description: 'Build and deploy, or link an existing Cloudflare Worker' }, { name: 'auth', hint: 'login | status | logout', @@ -374,7 +360,7 @@ if (helpPath) { }, { name: 'project', - hint: 'status | link | list | team | token | zero-trust | security | logs | requests | rollback | cancel | delete | purge-cache', + hint: 'status | link | list | team | token | zero-trust | security | logs | requests | rollback | preview | cancel | delete | purge-cache', description: 'Manage projects, teams, deployments, and scoped CI credentials', }, { name: 'secret', hint: 'list | put | delete | sync', description: 'Manage project secrets' }, diff --git a/packages/void/src/cli/cloudflare-preview.ts b/packages/void/src/cli/cloudflare-preview.ts new file mode 100644 index 000000000..451e7a743 --- /dev/null +++ b/packages/void/src/cli/cloudflare-preview.ts @@ -0,0 +1,48 @@ +import { cloudflarePreviewNameProblem, deleteCloudflarePreview } from '@void/deploy-cloudflare'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import type { CloudflareOperationRunner } from './cloudflare-operations.ts'; +import { printSuccess } from './output.ts'; + +/** + * `void project preview delete `: delete a Preview of this project's Worker. Production is + * not read or changed. A Preview that does not exist is not an error, so a cleanup job can rerun. + */ +export async function runCloudflarePreviewDelete( + root: string, + { name }: { name: string }, + runner?: CloudflareOperationRunner, +): Promise { + const problem = cloudflarePreviewNameProblem(name); + if (problem) { + throw new Error(`project: "${name}" is not a valid preview name: ${problem}.`); + } + // The same Worker and account as rollback, logs and deploy --preview. + const { resolveCloudflareOperationContext } = await import('./cloudflare-operations.ts'); + const context = resolveCloudflareOperationContext(root, runner); + const { workerName } = context; + const result = await deleteCloudflarePreview({ + runWrangler: context.runWrangler, + workerName, + previewName: name, + configPath: context.configPath, + }); + if (result.ok) { + if (result.deleted) { + printSuccess(`Deleted preview ${name} of Worker ${workerName}. Production is unchanged.`); + } else { + log.info(`Preview ${name} does not exist on Worker ${workerName}. Nothing to delete.`); + } + return; + } + if (result.reason === 'worker-not-found') { + throw new Error( + `project: Worker "${workerName}" was not found in Cloudflare account ${context.accountId}. Nothing was deleted. Check cloudflare.name and CLOUDFLARE_ACCOUNT_ID.`, + ); + } + throw new Error( + [ + `project: Cloudflare could not delete preview "${name}" of Worker "${workerName}".`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'), + ); +} diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index a874db3c4..74188d610 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -94,13 +94,8 @@ export function discoverRootWranglerConfig(root: string): string { * checks the same baseline, so project code can never swap the executable under the session. * Injected test runners (`activateVersion` / `runWrangler`) bypass the pinned cf uploader. */ -function createCloudflareUploaderPins( - root: string, - deps: CloudflareDeployDeps, - /** False for commands that never upload through the prebuilt cf uploader. */ - usesPrebuiltUploader = true, -) { - const usesCf = usesPrebuiltUploader && !deps.activateVersion && !deps.runWrangler; +function createCloudflareUploaderPins(root: string, deps: CloudflareDeployDeps) { + const usesCf = !deps.activateVersion && !deps.runWrangler; const hashUploader = deps.hashWranglerUploader ?? hashWranglerUploader; const wranglerUploaderHashBefore = hashUploader(root); const cfUploaderHashBefore = usesCf ? hashCfUploader() : undefined; @@ -168,8 +163,6 @@ export async function connectCloudflareDeployAccount(options: { readinessAccessOrigin: string | null | undefined; /** Scrubs and logs every child this connection runs. */ reporter: CloudflareChildReporter; - /** False skips pinning the prebuilt cf uploader, for commands that only call the API. */ - usesPrebuiltUploader?: boolean; }): Promise { const { root, configPath, deps, reporter } = options; let { rootConfig } = options; @@ -186,7 +179,7 @@ export async function connectCloudflareDeployAccount(options: { readWranglerTopLevelString(rootConfig, 'compliance_region'), ); // Pin the uploaders before the first authenticated command, including account discovery. - const pins = createCloudflareUploaderPins(root, deps, options.usesPrebuiltUploader); + const pins = createCloudflareUploaderPins(root, deps); let accountId = readWranglerTopLevelString(rootConfig, 'account_id') ?? (process.env.CLOUDFLARE_ACCOUNT_ID?.trim() || undefined); diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index cce2adfa6..658ce2be7 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -221,23 +221,6 @@ const HELP_TREE = { }, ], }, - preview: { - summary: - 'Manage Cloudflare Previews created with `void deploy --platform cloudflare --preview`.', - usage: ['void preview delete '], - commands: [ - { command: 'delete ', description: 'Delete a Preview and all its deployments' }, - ], - children: { - delete: basicSubcommand( - 'Delete a Preview and all its deployments. Production is unchanged; a Preview that does not exist is not an error.', - 'void preview delete ', - ), - }, - examples: [ - { command: 'void preview delete pr-64', description: 'Remove a pull request preview' }, - ], - }, auth: { summary: 'Authenticate with this project’s saved Cloudflare or Void destination. Without one, choose interactively or pass --platform.', @@ -687,6 +670,10 @@ const HELP_TREE = { { command: 'logs', description: 'Show runtime logs from the deployed project' }, { command: 'requests', description: 'Show request-level traffic (status, method, timing)' }, { command: 'rollback [deployId]', description: 'Roll back to a previous deployment' }, + { + command: 'preview delete ', + description: 'Delete a Cloudflare Preview made with void deploy --preview', + }, { command: 'cancel [deployId]', description: 'Cancel an active deployment' }, { command: 'delete [name]', description: 'Delete a project and all its resources' }, { command: 'purge-cache', description: 'Purge all cached pages (Void platform)' }, @@ -945,6 +932,23 @@ const HELP_TREE = { }, ], }, + preview: { + summary: + 'Delete a Cloudflare Preview made with void deploy --preview, and all its deployments. Production is unchanged.', + usage: ['void project preview delete [--platform cloudflare]'], + options: [ + { + command: '--platform cloudflare', + description: 'Delete it after a one-off Cloudflare deploy', + }, + ], + examples: [ + { + command: 'void project preview delete pr-64 --platform cloudflare', + description: 'Remove a pull request preview', + }, + ], + }, cancel: basicSubcommand('Cancel an active deployment.', 'void project cancel [deployId]'), delete: { summary: 'Delete a project and all its resources.', @@ -1726,8 +1730,6 @@ export function printGlobalHelp(): void { globalCommandLine(['deploy'], 'void deploy'), ...globalOptionLines(['deploy']), '', - ...globalCommandGroup('preview'), - '', ...globalCommandGroup('auth'), '', ...globalCommandGroup('account'), diff --git a/packages/void/src/cli/preview-args.ts b/packages/void/src/cli/preview-args.ts deleted file mode 100644 index 5811b6f3b..000000000 --- a/packages/void/src/cli/preview-args.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { SubcommandDef } from './subcommand-prompt.ts'; - -export const previewSubcommands: Array = [ - { - name: 'delete', - hint: '', - description: 'Delete a Cloudflare Preview and all its deployments', - }, -]; - -export type PreviewArgs = { subcommand: 'delete'; name: string }; - -export function parsePreviewArgs(args: Array): PreviewArgs { - const [subcommand, name, extra] = args; - if (subcommand !== 'delete') { - throw new Error('preview: Usage: void preview delete .'); - } - if (!name || name.startsWith('-')) { - throw new Error('preview: delete requires a preview name (for example pr-64).'); - } - if (extra) { - throw new Error(`preview: Unexpected argument '${extra}'.`); - } - return { subcommand, name }; -} diff --git a/packages/void/src/cli/preview-cmd.ts b/packages/void/src/cli/preview-cmd.ts deleted file mode 100644 index a59d547c6..000000000 --- a/packages/void/src/cli/preview-cmd.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { - deleteCloudflarePreview, - parseRootWranglerConfig, - readWranglerTopLevelString, -} from '@void/deploy-cloudflare'; -import type { CloudflarePreviewDeleteResult } from '@void/deploy-cloudflare'; -import { createCloudflareChildReporter } from './cloudflare-child-report.ts'; -import { - confirmCloudflareDeployAuthentication, - connectCloudflareDeployAccount, - discoverRootWranglerConfig, -} from './deploy-cloudflare-helpers.ts'; -import { log } from './deploy-helpers.ts'; -import { deriveWorkerName } from './deploy-resources.ts'; -import type { CloudflareDeployDeps } from './deploy-types.ts'; -import { openDeployLog } from './log-file.ts'; -import { printSuccess } from './output.ts'; -import type { PreviewArgs } from './preview-args.ts'; - -/** - * Delete a Preview of this project's Cloudflare Worker. Production is not read or changed. A - * Preview that no longer exists is not an error, so a pull-request cleanup job can rerun. - */ -export async function runPreviewCommand( - root: string, - args: PreviewArgs, - deps: CloudflareDeployDeps = {}, -): Promise { - const cliLog = openDeployLog(); - try { - const reporter = createCloudflareChildReporter(cliLog); - const configPath = discoverRootWranglerConfig(root); - const connection = await connectCloudflareDeployAccount({ - root, - configPath, - rootConfig: parseRootWranglerConfig(configPath), - deps, - // Deleting a Preview never chooses or saves an account for the project. - persistAccount: false, - readinessAccessOrigin: undefined, - reporter, - // Deleting is one API call: there is no prebuilt upload to pin. - usesPrebuiltUploader: false, - }); - if (!connection || !(await confirmCloudflareDeployAuthentication(connection, configPath))) { - throw new Error('preview: could not connect to Cloudflare.'); - } - const workerName = - readWranglerTopLevelString(connection.rootConfig, 'name') ?? deriveWorkerName(root); - const result = await deleteCloudflarePreview({ - runWrangler: connection.runWrangler, - workerName, - previewName: args.name, - verifyUploader: connection.assertUploaderStillPinned, - configPath, - }); - if (!result.ok) { - const message = reporter.redactor.redact(formatDeleteError(result, args.name, workerName)); - cliLog.error('cloudflare_preview_delete_failed', new Error(message), { - reason: result.reason, - }); - throw new Error(message); - } - cliLog.info('cloudflare_preview_deleted', { previewName: args.name, deleted: result.deleted }); - if (result.deleted) { - printSuccess(`Deleted the preview ${args.name} of ${workerName}.`); - } else { - log.info(`The preview ${args.name} of ${workerName} does not exist. Nothing to delete.`); - } - } finally { - await cliLog.close().catch(() => {}); - } -} - -function formatDeleteError( - result: Extract, - name: string, - workerName: string, -): string { - switch (result.reason) { - case 'invalid-name': - return `preview: ${result.diagnostic}`; - case 'uploader-changed': - return 'preview: the Cloudflare uploader changed. Nothing was deleted.'; - case 'delete-failed': - return [ - `preview: Cloudflare could not delete the preview "${name}" of the Worker "${workerName}".`, - ...(result.diagnostic ? [result.diagnostic] : []), - ].join('\n'); - } -} diff --git a/packages/void/src/cli/project-args.ts b/packages/void/src/cli/project-args.ts index 488db82c6..40e7320eb 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -49,6 +49,18 @@ export const projectSubcommands: Array = [ }, ], }, + { + name: 'preview', + arg: 'delete ', + description: 'Delete a Cloudflare Preview made by deploy --preview', + flags: [ + { + name: '--platform', + arg: 'cloudflare', + description: 'Delete it after a one-off deploy with --platform cloudflare', + }, + ], + }, { name: 'cancel', arg: '[deployId]', description: 'Cancel an active deployment' }, { name: 'delete', @@ -205,6 +217,7 @@ export type ProjectArgs = } | { subcommand: 'requests'; status: string; range: string } | { subcommand: 'rollback'; deployId: string; platform?: 'cloudflare' } + | { subcommand: 'preview'; action: 'delete'; name: string; platform?: 'cloudflare' } | { subcommand: 'cancel'; deployId: string } | { subcommand: 'delete'; name: string; force: boolean } | { subcommand: 'purge-cache'; projectSlug: string }; @@ -359,6 +372,30 @@ export function parseProjectArgs(args: Array): ProjectArgs { }; } + if (subcommand === 'preview') { + const usage = 'project: Usage: void project preview delete [--platform cloudflare].'; + let platform: 'cloudflare' | undefined; + const positional: Array = []; + for (let i = 0; i < rest.length; i++) { + const arg = rest[i]; + if (arg === '--platform' || arg.startsWith('--platform=')) { + const value = arg === '--platform' ? rest[++i] : arg.slice('--platform='.length); + if (value !== 'cloudflare') { + throw new Error(usage); + } + platform = 'cloudflare'; + } else { + // The interactive menu passes the typed "delete " as one argument. + positional.push(...arg.split(' ').filter(Boolean)); + } + } + const [action, name] = positional; + if (positional.length !== 2 || action !== 'delete' || !name || name.startsWith('-')) { + throw new Error(usage); + } + return { subcommand, action, name, ...(platform ? { platform } : {}) }; + } + if (subcommand === 'cancel') { return { subcommand, deployId: parseOptionalPositional(rest) }; } @@ -393,7 +430,7 @@ export function parseProjectArgs(args: Array): ProjectArgs { } throw new Error( - 'project: Usage: void project .', + 'project: Usage: void project .', ); } diff --git a/packages/void/src/cli/project-cmd.ts b/packages/void/src/cli/project-cmd.ts index 9ab0464e1..4538c1f8e 100644 --- a/packages/void/src/cli/project-cmd.ts +++ b/packages/void/src/cli/project-cmd.ts @@ -100,6 +100,16 @@ export async function runProjectCommand(root: string, args: ProjectArgs): Promis const { runRollbackCommand } = await import('./rollback.ts'); return runRollbackCommand(root, args.deployId || undefined, args.platform); } + if (args.subcommand === 'preview') { + // A one-off `deploy --platform cloudflare` keeps the saved platform, as for rollback. + if (args.platform !== 'cloudflare' && !cloudflare) { + throw new Error( + 'project: Previews from `void deploy --preview` exist only for direct Cloudflare deploys. Add --platform cloudflare.', + ); + } + const { runCloudflarePreviewDelete } = await import('./cloudflare-preview.ts'); + return runCloudflarePreviewDelete(root, { name: args.name }); + } if (args.subcommand === 'cancel') { if (cloudflare) { throw new Error( diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index b2becab26..6f65f6308 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -1861,3 +1861,38 @@ it.each([ expect(redirected).toBe(false); expect(output.stdout + output.stderr).not.toContain('synthetic-token'); }); + +it('deletes a Preview through the pinned cf and reads its error code', async () => { + const directory = temporaryDirectory('void-cf-preview-delete-'); + const preload = join(directory, 'mock-cf.mjs'); + const callsPath = join(directory, 'calls.json'); + const configPath = join(directory, 'wrangler.json'); + writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); + writeFileSync( + preload, + `import child from 'node:child_process'; +import { syncBuiltinESMExports } from 'node:module'; +import { writeFileSync } from 'node:fs'; +child.spawnSync = (_executable, args) => { + writeFileSync(${JSON.stringify(callsPath)}, JSON.stringify(args.slice(1))); + return { status: 1, stdout: '', stderr: 'Preview not found [code: 10025]' }; +}; +syncBuiltinESMExports(); +`, + ); + const output = await runOperation( + directory, + { type: 'previews.delete', configPath, workerName: 'test-worker', previewName: 'pr-64' }, + { ...systemEnv, CI: 'true', CLOUDFLARE_AUTH_USE_KEYRING: 'false' }, + preload, + ); + expect(output.status).toBe(1); + expect(JSON.parse(output.stdout)).toMatchObject({ errorCode: 10_025 }); + expect(JSON.parse(readFileSync(callsPath, 'utf8'))).toEqual([ + 'previews', + 'delete', + 'pr-64', + '--worker=test-worker', + '--force', + ]); +}); diff --git a/packages/void/test/unit/preview-args.test.ts b/packages/void/test/unit/preview-args.test.ts deleted file mode 100644 index 9300ba6ac..000000000 --- a/packages/void/test/unit/preview-args.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from 'vite-plus/test'; -import { parsePreviewArgs } from '../../src/cli/preview-args.ts'; - -describe('parsePreviewArgs', () => { - it('parses delete with a name', () => { - expect(parsePreviewArgs(['delete', 'pr-64'])).toEqual({ subcommand: 'delete', name: 'pr-64' }); - }); - - it('rejects missing, unknown and extra arguments', () => { - expect(() => parsePreviewArgs([])).toThrow('void preview delete '); - expect(() => parsePreviewArgs(['list'])).toThrow('void preview delete '); - expect(() => parsePreviewArgs(['delete'])).toThrow('requires a preview name'); - expect(() => parsePreviewArgs(['delete', '--force'])).toThrow('requires a preview name'); - expect(() => parsePreviewArgs(['delete', 'pr-64', 'pr-65'])).toThrow('Unexpected argument'); - }); -}); diff --git a/packages/void/test/unit/project-args.test.ts b/packages/void/test/unit/project-args.test.ts index b1fa04144..2698cd05b 100644 --- a/packages/void/test/unit/project-args.test.ts +++ b/packages/void/test/unit/project-args.test.ts @@ -405,3 +405,31 @@ describe('security', () => { ); }); }); + +describe('parseProjectArgs preview', () => { + it('parses preview delete with an optional platform', () => { + expect(parseProjectArgs(['preview', 'delete', 'pr-64'])).toEqual({ + subcommand: 'preview', + action: 'delete', + name: 'pr-64', + }); + expect(parseProjectArgs(['preview', '--platform=cloudflare', 'delete', 'pr-64'])).toEqual({ + subcommand: 'preview', + action: 'delete', + name: 'pr-64', + platform: 'cloudflare', + }); + }); + + it.each([ + [['preview', 'delete']], + [['preview', 'delete', '-x']], + [['preview', 'delete', 'pr-64', 'pr-65']], + [['preview', 'list']], + [['preview', 'delete', 'pr-64', '--platform', 'aws']], + ])('refuses %j', (args) => { + expect(() => parseProjectArgs(args)).toThrow( + 'project: Usage: void project preview delete [--platform cloudflare].', + ); + }); +}); diff --git a/packages/void/test/unit/project-preview.test.ts b/packages/void/test/unit/project-preview.test.ts new file mode 100644 index 000000000..7ff941ed1 --- /dev/null +++ b/packages/void/test/unit/project-preview.test.ts @@ -0,0 +1,83 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { CloudflareCommandResult, CloudflareOperation } from '@void/deploy-cloudflare'; +import { log } from '@voidzero-dev/vite-plus-prompts'; +import { afterEach, beforeEach, expect, it, vi } from 'vite-plus/test'; +import { runCloudflarePreviewDelete } from '../../src/cli/cloudflare-preview.ts'; +import { runProjectCommand } from '../../src/cli/project-cmd.ts'; + +const output = await import('../../src/cli/output.ts'); + +let root: string; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'void-project-preview-')); + writeFileSync( + join(root, 'wrangler.json'), + JSON.stringify({ name: 'my-app', account_id: 'acc123' }), + ); +}); +afterEach(() => { + rmSync(root, { recursive: true, force: true }); + vi.restoreAllMocks(); +}); + +function runner(answer: Partial) { + const calls: Array = []; + const run = (operation: CloudflareOperation) => { + calls.push(operation); + return { status: 0, stdout: '', stderr: '', ...answer }; + }; + return { calls, run }; +} + +it('deletes the preview of the configured Worker', async () => { + const success = vi.spyOn(output, 'printSuccess').mockImplementation(() => {}); + const { calls, run } = runner({}); + await runCloudflarePreviewDelete(root, { name: 'pr-64' }, run); + expect(calls).toMatchObject([ + { type: 'previews.delete', workerName: 'my-app', previewName: 'pr-64' }, + ]); + expect(success).toHaveBeenCalledWith( + 'Deleted preview pr-64 of Worker my-app. Production is unchanged.', + ); +}); + +it('succeeds when the preview does not exist', async () => { + const info = vi.spyOn(log, 'info').mockImplementation(() => {}); + const { run } = runner({ status: 1, errorCode: 10_025, stderr: 'Not found [code: 10025]' }); + await runCloudflarePreviewDelete(root, { name: 'pr-64' }, run); + expect(info).toHaveBeenCalledWith( + 'Preview pr-64 does not exist on Worker my-app. Nothing to delete.', + ); +}); + +it.each([ + [ + { status: 1, errorCode: 10_007 }, + 'project: Worker "my-app" was not found in Cloudflare account acc123. Nothing was deleted.', + ], + [ + { status: 1, errorCode: 10_000, stderr: 'Authentication error' }, + 'project: Cloudflare could not delete preview "pr-64" of Worker "my-app".\nAuthentication error', + ], +])('fails on %j', async (answer, message) => { + const { run } = runner(answer); + await expect(runCloudflarePreviewDelete(root, { name: 'pr-64' }, run)).rejects.toThrow(message); +}); + +it('refuses an invalid name before reading the config', async () => { + const { calls, run } = runner({}); + await expect(runCloudflarePreviewDelete(root, { name: 'PR_64' }, run)).rejects.toThrow( + 'project: "PR_64" is not a valid preview name: must start with a lowercase letter.', + ); + expect(calls).toEqual([]); +}); + +it('refuses a project that is not deployed to Cloudflare without --platform cloudflare', async () => { + await expect( + runProjectCommand(root, { subcommand: 'preview', action: 'delete', name: 'pr-64' }), + ).rejects.toThrow( + 'project: Previews from `void deploy --preview` exist only for direct Cloudflare deploys. Add --platform cloudflare.', + ); +}); From 196cbf853c465e809fd3790d44e5d2900d2b4bdc Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 17:36:31 +0800 Subject: [PATCH 05/12] fix(deploy): check the preview target and strip bindings Before connecting, `deploy --preview` now checks the name with a small parser (no regex), and needs `cloudflare.name` and a pinned account, so the deploy and `void project preview delete` reach the same Worker. The workers.dev length rule is checked against that name. The upload first reads the Worker's deployment status: cf would create a missing Worker without asking, so a Worker with no production deployment stops with nothing uploaded. The staged config keeps only an allow-list of keys, so a preview gets none of the Worker's bindings, vars or migrations. A deploy with Preview URLs off reports the deployment it made and how to turn them on. The cf runner decodes the Preview record from its parsed stdout JSON. The preview tail moves to cloudflare-preview.ts. The account save and queue-cleanup read go back to main's code. Co-Authored-By: Claude Opus 5.5 --- packages/deploy-cloudflare/src/index.ts | 2 +- packages/deploy-cloudflare/src/preview.ts | 84 ++++++---- .../test/operation-fixture.ts | 2 +- .../test/unit/preview.test.ts | 111 +++++++++---- packages/void/src/cli/args.ts | 5 +- packages/void/src/cli/cf-command-values.ts | 52 +++--- packages/void/src/cli/cf-version-runner.ts | 6 +- packages/void/src/cli/cloudflare-preview.ts | 157 +++++++++++++++++- .../void/src/cli/deploy-cloudflare-static.ts | 123 +++----------- .../void/test/unit/cf-version-runner.test.ts | 6 +- .../void/test/unit/cloudflare-deploy.test.ts | 118 ++++++++++--- packages/void/test/unit/deploy-args.test.ts | 3 + 12 files changed, 448 insertions(+), 221 deletions(-) diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 82975c9a1..58ac26f7f 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -58,7 +58,7 @@ export { deleteCloudflarePreview, cloudflarePreviewNameProblem, deployCloudflarePreview, - validateCloudflarePreviewName, + previewStaticWorkerConfig, type CloudflarePreviewDeleteResult, type CloudflarePreviewDeployResult, } from './preview.ts'; diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts index 09af279ef..0457a80f6 100644 --- a/packages/deploy-cloudflare/src/preview.ts +++ b/packages/deploy-cloudflare/src/preview.ts @@ -4,11 +4,6 @@ import { isCleanCommandExit, isCompletedCommand, isWorkerNotFound } from './exec import type { CloudflareCommandRunner } from './execute.ts'; import type { CloudflarePreviewUploadResult } from './operations.ts'; -/** - * A Preview name becomes the first label of `-..workers.dev`. Accept only - * names Cloudflare uses unchanged, so the URL Void prints is the one CI expects. - */ -const PREVIEW_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; /** A DNS label holds at most 63 characters. */ const MAX_HOST_LABEL = 63; /** Cloudflare's "Preview not found" API error. */ @@ -47,15 +42,28 @@ function isDigit(character: string): boolean { return character >= '0' && character <= '9'; } -/** Return why `name` cannot name a Preview of `workerName`, or null when it can. */ -export function validateCloudflarePreviewName(name: string, workerName?: string): string | null { - if (!PREVIEW_NAME.test(name)) { - return `"${name}" is not a valid preview name. Use lowercase letters, digits and hyphens, starting and ending with a letter or digit (for example "pr-64").`; - } - if (workerName !== undefined && name.length + 1 + workerName.length > MAX_HOST_LABEL) { - return `The preview name "${name}" is too long for the Worker "${workerName}": "${name}-${workerName}" must fit in ${MAX_HOST_LABEL} characters to be a workers.dev hostname.`; - } - return null; +/** Root config keys a static Preview keeps. Bindings, vars, migrations and triggers are dropped. */ +const PREVIEW_CONFIG_KEYS = [ + 'name', + 'account_id', + 'compliance_region', + 'compatibility_date', + 'compatibility_flags', + 'assets', + 'observability', + 'version_metadata', +]; + +/** + * The config a static site Preview is staged from. cf sends every binding in the Build Output to + * the Preview, so this copies only an allow-list: a binding kind added later never reaches it. + */ +export function previewStaticWorkerConfig( + config: Record, +): Record { + return Object.fromEntries( + PREVIEW_CONFIG_KEYS.flatMap((key) => (config[key] === undefined ? [] : [[key, config[key]]])), + ); } export type CloudflarePreviewDeployResult = @@ -66,21 +74,23 @@ export type CloudflarePreviewDeployResult = /** The stable URL that always serves this Preview's latest deployment. */ previewUrl: string; /** The URL of this deployment only. */ - deploymentUrl: string | undefined; + deploymentUrl: string | null; } + | { ok: false; reason: 'worker-not-found' | 'uploader-changed' | 'output-invalid' } | { ok: false; - reason: 'uploader-changed' | 'invalid-name' | 'output-invalid'; + reason: 'worker-check-failed' | 'deploy-failed'; + status: number; diagnostic?: string; } - | { ok: false; reason: 'deploy-failed'; status: number; diagnostic?: string } /** Cloudflare created the deployment but returned no Preview URL: `preview_urls` is off. */ - | { ok: false; reason: 'preview-urls-disabled' }; + | { ok: false; reason: 'preview-urls-disabled'; deploymentId: string }; /** - * Create or update a named Workers Preview from the prepared output. This only ever sends - * `previews.deploy`: production versions, deployments, traffic and triggers are not read or - * changed, and no migration, provisioning or secret operation runs. + * Create or update a named Workers Preview from the prepared output. It reads the Worker's + * deployment status first, because cf would create a missing Worker without asking. Production + * versions, deployments, traffic and triggers are not changed, and no migration, provisioning or + * secret operation runs. */ export async function deployCloudflarePreview(options: { runWrangler: CloudflareCommandRunner; @@ -89,20 +99,30 @@ export async function deployCloudflarePreview(options: { verifyUploader: () => boolean; configPath?: string; }): Promise { - const invalid = validateCloudflarePreviewName(options.previewName, options.workerName); - if (invalid) { - return { ok: false, reason: 'invalid-name', diagnostic: invalid }; + const target = { + workerName: options.workerName, + ...(options.configPath ? { configPath: options.configPath } : {}), + }; + const status = await options.runWrangler( + { type: 'deployments.status', ...target }, + { capture: true }, + ); + if (isWorkerNotFound(status)) { + return { ok: false, reason: 'worker-not-found' }; + } + if (!isCleanCommandExit(status)) { + return { + ok: false, + reason: 'worker-check-failed', + status: status.status, + ...commandDiagnosticFields(status), + }; } if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } const result = await options.runWrangler( - { - type: 'previews.deploy', - workerName: options.workerName, - previewName: options.previewName, - ...(options.configPath ? { configPath: options.configPath } : {}), - }, + { type: 'previews.deploy', previewName: options.previewName, ...target }, { capture: true }, ); if (!isCleanCommandExit(result)) { @@ -118,14 +138,14 @@ export async function deployCloudflarePreview(options: { return { ok: false, reason: 'output-invalid' }; } if (!uploaded.previewUrl) { - return { ok: false, reason: 'preview-urls-disabled' }; + return { ok: false, reason: 'preview-urls-disabled', deploymentId: uploaded.deploymentId }; } return { ok: true, previewId: uploaded.previewId, deploymentId: uploaded.deploymentId, previewUrl: uploaded.previewUrl, - deploymentUrl: uploaded.deploymentUrl, + deploymentUrl: uploaded.deploymentUrl ?? null, }; } diff --git a/packages/deploy-cloudflare/test/operation-fixture.ts b/packages/deploy-cloudflare/test/operation-fixture.ts index e69f84284..ef5cd2d05 100644 --- a/packages/deploy-cloudflare/test/operation-fixture.ts +++ b/packages/deploy-cloudflare/test/operation-fixture.ts @@ -195,7 +195,7 @@ export function operationFixtureArgs(operation: CloudflareOperation): Array) { +/** Answer each operation type on its own; the Worker exists unless `status` says otherwise. */ +function runner( + answer: Partial, + status: Partial = {}, +) { const calls: Array = []; const runWrangler: CloudflareCommandRunner = vi.fn((operation: CloudflareOperation) => { calls.push(operation); - return { status: 0, stdout: '', stderr: '', ...answer }; + return { + status: 0, + stdout: '', + stderr: '', + ...(operation.type === 'deployments.status' ? status : answer), + }; }); return { calls, runWrangler }; } @@ -46,26 +55,39 @@ describe('cloudflarePreviewNameProblem', () => { }); }); -describe('validateCloudflarePreviewName', () => { - it.each(['pr-64', 'a', 'feature-login', '0'])('accepts %s', (name) => { - expect(validateCloudflarePreviewName(name, 'site')).toBeNull(); - }); - - it.each(['', 'PR-64', 'pr_64', 'feature/login', '-pr', 'pr-', '--flag', 'pr 64'])( - 'rejects %j', - (name) => { - expect(validateCloudflarePreviewName(name, 'site')).toContain('not a valid preview name'); - }, - ); - - it('rejects a name whose workers.dev label would exceed 63 characters', () => { - expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(58))).toContain('63 characters'); - expect(validateCloudflarePreviewName('pr-64', 'w'.repeat(57))).toBeNull(); +describe('previewStaticWorkerConfig', () => { + it('keeps only the allow-listed keys', () => { + expect( + previewStaticWorkerConfig({ + name: 'site', + account_id: 'acc', + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + assets: { html_handling: 'auto-trailing-slash' }, + observability: { enabled: true }, + version_metadata: { binding: 'CF_VERSION_METADATA' }, + kv_namespaces: [{ binding: 'KV', id: 'kv' }], + d1_databases: [{ binding: 'DB', database_id: 'db' }], + vars: { SECRET_LOOKING: 'x' }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + triggers: { crons: ['* * * * *'] }, + routes: ['example.com/*'], + preview_urls: true, + }), + ).toEqual({ + name: 'site', + account_id: 'acc', + compatibility_date: '2026-01-01', + compatibility_flags: ['nodejs_compat'], + assets: { html_handling: 'auto-trailing-slash' }, + observability: { enabled: true }, + version_metadata: { binding: 'CF_VERSION_METADATA' }, + }); }); }); describe('deployCloudflarePreview', () => { - it('sends only previews.deploy and returns the stable Preview URL', async () => { + it('checks the Worker, then deploys the Preview and returns its URL', async () => { const { calls, runWrangler } = runner({ data: uploaded }); expect( await deployCloudflarePreview({ ...target, runWrangler, configPath: '/app/wrangler.json' }), @@ -76,8 +98,9 @@ describe('deployCloudflarePreview', () => { previewUrl: 'https://pr-64-site.team.workers.dev', deploymentUrl: 'https://dep1-site.team.workers.dev', }); - // Production is never read or changed: no versions, deployments, traffic or triggers. + // Production is never changed: no versions, traffic or triggers. expect(calls).toEqual([ + { type: 'deployments.status', workerName: 'site', configPath: '/app/wrangler.json' }, { type: 'previews.deploy', workerName: 'site', @@ -87,32 +110,64 @@ describe('deployCloudflarePreview', () => { ]); }); - it('rejects an invalid name or a changed uploader before running anything', async () => { + it.each([ + [ + { status: 1, errorCode: 10_007 }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, failure: 'not-found' as const }, + { ok: false, reason: 'worker-not-found' }, + ], + [ + { status: 1, stderr: 'Authentication error' }, + { + ok: false, + reason: 'worker-check-failed', + status: 1, + diagnostic: 'Authentication error', + }, + ], + ])('uploads nothing when the Worker check gives %j', async (status, expected) => { + const { calls, runWrangler } = runner({ data: uploaded }, status); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual(expected); + expect(calls.map((call) => call.type)).toEqual(['deployments.status']); + }); + + it('uploads nothing when the uploader changed', async () => { const { calls, runWrangler } = runner({ data: uploaded }); - expect( - await deployCloudflarePreview({ ...target, runWrangler, previewName: '--force' }), - ).toMatchObject({ ok: false, reason: 'invalid-name' }); expect( await deployCloudflarePreview({ ...target, runWrangler, verifyUploader: () => false }), ).toEqual({ ok: false, reason: 'uploader-changed' }); - expect(calls).toEqual([]); + expect(calls.map((call) => call.type)).toEqual(['deployments.status']); }); it('reports a failed deploy', async () => { - const { runWrangler } = runner({ status: 1, errors: [{ message: 'Authentication error' }] }); - expect(await deployCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + const { runWrangler } = runner({ status: 1, stderr: 'Authentication error' }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ ok: false, reason: 'deploy-failed', status: 1, + diagnostic: 'Authentication error', }); }); - it('reports disabled Preview URLs when Cloudflare returns none', async () => { + it('reports disabled Preview URLs with the deployment Cloudflare created', async () => { const { previewUrl: _, ...withoutUrl } = uploaded; const { runWrangler } = runner({ data: withoutUrl }); expect(await deployCloudflarePreview({ ...target, runWrangler })).toEqual({ ok: false, reason: 'preview-urls-disabled', + deploymentId: 'dep_1', + }); + }); + + it('returns a null deployment URL when Cloudflare gives none', async () => { + const { deploymentUrl: _, ...withoutUrl } = uploaded; + const { runWrangler } = runner({ data: withoutUrl }); + expect(await deployCloudflarePreview({ ...target, runWrangler })).toMatchObject({ + ok: true, + deploymentUrl: null, }); }); diff --git a/packages/void/src/cli/args.ts b/packages/void/src/cli/args.ts index b641ec626..d5f706dda 100644 --- a/packages/void/src/cli/args.ts +++ b/packages/void/src/cli/args.ts @@ -121,10 +121,13 @@ export function parseDeployArgs( const preview = typeof parsed.values.preview === 'string' ? parsed.values.preview : undefined; const json = parsed.values.json === true ? true : undefined; if (preview !== undefined) { + if (preview === '') { + throw new Error('deploy: --preview requires a name (for example --preview pr-64).'); + } if (platform !== 'cloudflare') { throw new Error('deploy: --preview requires --platform cloudflare.'); } - // The name itself is checked against the Worker name before the build. + // The name and the Worker it targets are checked before connecting to Cloudflare. for (const [flag, set] of [ ['--atomic', atomic], ['--provision', provision], diff --git a/packages/void/src/cli/cf-command-values.ts b/packages/void/src/cli/cf-command-values.ts index 11ee4119e..fa10033d7 100644 --- a/packages/void/src/cli/cf-command-values.ts +++ b/packages/void/src/cli/cf-command-values.ts @@ -38,43 +38,29 @@ export function readCfUploadOutput(result: { } /** - * Decode the Preview record `cf previews deploy` prints as JSON: the stable Preview URL and the - * URL of this deployment. Earlier provider lines may precede the record, so read the last line that - * starts a JSON object together with everything after it. + * Map the Preview record `cf previews deploy` prints as JSON on stdout to the stable Preview URL + * and the URL of this deployment. Anything unreadable gives undefined, so the deploy fails closed. */ export function readCfPreviewDeployOutput( - stdout: string, + data: unknown, ): CloudflarePreviewUploadResult | undefined { - const lines = stdout.trim().split('\n'); - for (let index = lines.length - 1; index >= 0; index--) { - if (lines[index]?.startsWith('{') !== true) { - continue; - } - let record: unknown; - try { - record = JSON.parse(lines.slice(index).join('\n')); - } catch { - continue; - } - if (!isRecord(record)) { - return undefined; - } - const value = record; - const previewUrl = firstUrl(value.preview_urls); - const deploymentUrl = firstUrl(value.deployment_urls); - return typeof value.preview_id === 'string' && - typeof value.preview_name === 'string' && - typeof value.deployment_id === 'string' - ? { - previewId: value.preview_id, - previewName: value.preview_name, - deploymentId: value.deployment_id, - ...(previewUrl ? { previewUrl } : {}), - ...(deploymentUrl ? { deploymentUrl } : {}), - } - : undefined; + if ( + !isRecord(data) || + typeof data.preview_id !== 'string' || + typeof data.preview_name !== 'string' || + typeof data.deployment_id !== 'string' + ) { + return undefined; } - return undefined; + const previewUrl = firstUrl(data.preview_urls); + const deploymentUrl = firstUrl(data.deployment_urls); + return { + previewId: data.preview_id, + previewName: data.preview_name, + deploymentId: data.deployment_id, + ...(previewUrl ? { previewUrl } : {}), + ...(deploymentUrl ? { deploymentUrl } : {}), + }; } /** The first URL of a cf URL list, without a trailing slash. */ diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index 5b2765e39..72982c92e 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -745,14 +745,14 @@ export function createCfVersionRunner(options: { return verified; } // One argv item, so a name that starts with "-" is never read as a flag. - const deployed = await runCf( + const deployed = await run( ['previews', 'deploy', '--prebuilt', `--preview-name=${operation.previewName}`], - { cwd: output.directory, capture: command.capture }, + command.capture, ); if (!isCleanCloudflareExit(deployed)) { return deployed; } - return { ...deployed, data: readCfPreviewDeployOutput(deployed.stdout) }; + return { ...deployed, data: readCfPreviewDeployOutput(deployed.data) }; } if (operation.type === 'versions.deploy') { diff --git a/packages/void/src/cli/cloudflare-preview.ts b/packages/void/src/cli/cloudflare-preview.ts index 451e7a743..ea0e71b66 100644 --- a/packages/void/src/cli/cloudflare-preview.ts +++ b/packages/void/src/cli/cloudflare-preview.ts @@ -1,7 +1,160 @@ -import { cloudflarePreviewNameProblem, deleteCloudflarePreview } from '@void/deploy-cloudflare'; +import { + cloudflarePreviewNameProblem, + deleteCloudflarePreview, + deployCloudflarePreview, + readWranglerTopLevelString, +} from '@void/deploy-cloudflare'; +import type { + CloudflareCommandRunner, + CloudflarePreviewDeployResult, +} from '@void/deploy-cloudflare'; import { log } from '@voidzero-dev/vite-plus-prompts'; +import { basename } from 'pathslash'; +import type { CfBuildOutput } from './cf-build-output.ts'; +import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import type { CloudflareOperationRunner } from './cloudflare-operations.ts'; -import { printSuccess } from './output.ts'; +import { log as deployLog } from './deploy-helpers.ts'; +import { formatDeploySummary } from './deploy-summary.ts'; +import type { RunDeployOptions } from './deploy-types.ts'; +import type { CliLogger } from './log-file.ts'; +import { note, printSuccess } from './output.ts'; + +/** A workers.dev hostname label holds at most 63 characters. */ +const MAX_HOST_LABEL = 63; + +/** Where the user sets a top-level Cloudflare config key, for messages. */ +export function cloudflareConfigKey(configPath: string, key: string): string { + const file = basename(configPath); + return file === 'wrangler.jsonc' || file === 'wrangler.json' + ? `${key} in ${file}` + : `cloudflare.${key} in void.config.ts`; +} + +/** + * Check a `deploy --preview` request before connecting to Cloudflare. A Worker name and a pinned + * account make the deploy and `void project preview delete` reach the same Worker. + */ +export function checkCloudflarePreviewRequest(options: { + previewName: string; + rootConfig: Record; + configPath: string; +}): string | undefined { + const { previewName, rootConfig, configPath } = options; + const problem = cloudflarePreviewNameProblem(previewName); + if (problem) { + return `deploy: "${previewName}" is not a valid preview name: ${problem}. For example: pr-64.`; + } + const workerName = readWranglerTopLevelString(rootConfig, 'name'); + if (!workerName) { + return `deploy: --preview needs the Worker name (${cloudflareConfigKey(configPath, 'name')}), so the preview and its cleanup reach the same Worker.`; + } + if ( + !readWranglerTopLevelString(rootConfig, 'account_id') && + !process.env.CLOUDFLARE_ACCOUNT_ID?.trim() + ) { + return 'deploy: --preview needs a pinned Cloudflare account. Set cloudflare.account_id in void.config.ts or CLOUDFLARE_ACCOUNT_ID.'; + } + // Stricter than a Preview that serves only a custom domain needs, but CI reads the workers.dev + // URL. + if (previewName.length + 1 + workerName.length > MAX_HOST_LABEL) { + return `deploy: preview name "${previewName}" is too long for Worker "${workerName}". On workers.dev, "${previewName}-${workerName}" must be at most ${MAX_HOST_LABEL} characters, so use at most ${MAX_HOST_LABEL - 1 - workerName.length}.`; + } + return undefined; +} + +/** Deploy a static Preview from the prepared output and report it. Production is unchanged. */ +export async function runCloudflareStaticPreview(options: { + runWrangler: CloudflareCommandRunner; + cfOutput: CfBuildOutput | null; + workerName: string; + previewName: string; + accountId: string; + configPath: string; + staticConfigPath: string; + verifyUploader: () => boolean; + typeLabel: string; + writeResult: RunDeployOptions['writeResult']; + reporter: CloudflareChildReporter; + cliLog: CliLogger; + exit: (code: number) => never; +}): Promise { + const { previewName, workerName, cliLog } = options; + deployLog.step(`Deploying Preview ${previewName}...`); + let result: CloudflarePreviewDeployResult; + try { + result = await deployCloudflarePreview({ + runWrangler: options.runWrangler, + workerName, + previewName, + verifyUploader: options.verifyUploader, + configPath: options.staticConfigPath, + }); + } finally { + await options.cfOutput?.dispose(); + } + if (!result.ok) { + const message = options.reporter.redactor.redact(formatCloudflarePreviewError(result, options)); + cliLog.error('cloudflare_preview_failed', new Error(message), { reason: result.reason }); + deployLog.error(message); + return options.exit(1); + } + cliLog.info('cloudflare_preview_deployed', { + previewName, + previewId: result.previewId, + deploymentId: result.deploymentId, + }); + const record = { + type: 'preview', + workerName, + previewName, + previewUrl: result.previewUrl, + deploymentId: result.deploymentId, + deploymentUrl: result.deploymentUrl, + }; + options.writeResult?.(`${JSON.stringify(record)}\n`); + note( + [ + formatDeploySummary({ workerName, typeLabel: options.typeLabel }), + `Preview: ${previewName}`, + ...(result.deploymentUrl ? [`This deployment: ${result.deploymentUrl}`] : []), + ].join('\n'), + result.previewUrl, + ); + printSuccess(`Preview ${previewName} deployed. Production is unchanged.`); +} + +function formatCloudflarePreviewError( + result: Extract, + options: { previewName: string; workerName: string; accountId: string; configPath: string }, +): string { + const { previewName, workerName } = options; + switch (result.reason) { + case 'worker-not-found': + return [ + `deploy: Worker "${workerName}" has no production deployment in Cloudflare account ${options.accountId}. Nothing was uploaded.`, + 'Deploy production first: void deploy --platform cloudflare', + ].join('\n'); + case 'worker-check-failed': + return [ + `deploy: could not check Worker "${workerName}" on Cloudflare. Nothing was uploaded.`, + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + case 'uploader-changed': + return 'deploy: the Cloudflare uploader changed during the preview deploy. Nothing was deployed.'; + case 'output-invalid': + return 'deploy: Cloudflare accepted the preview but did not return a readable Preview record. Check the Worker in the Cloudflare dashboard before retrying.'; + case 'preview-urls-disabled': + return [ + `deploy: Cloudflare created deployment ${result.deploymentId} for preview "${previewName}", but Preview URLs are off for Worker "${workerName}", so it has no URL.`, + `Set preview_urls: true (${cloudflareConfigKey(options.configPath, 'preview_urls')}), run void deploy --platform cloudflare once, then deploy the preview again. This also turns on version URLs for production versions.`, + ].join('\n'); + case 'deploy-failed': + return [ + 'deploy: Cloudflare could not deploy the preview. Production is unchanged.', + ...(result.diagnostic ? [result.diagnostic] : []), + ].join('\n'); + } +} /** * `void project preview delete `: delete a Preview of this project's Worker. Production is diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index fa516598a..0802faf3b 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -2,7 +2,6 @@ import { execSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { activateCloudflareVersion, - deployCloudflarePreview, encodeCloudflareVersionMessage, parseRootWranglerConfig, readCloudflareTriggerConfig, @@ -12,9 +11,8 @@ import { writeCloudflareFrameworkDeployConfig, writeCloudflareStaticDeployConfig, assertExistingCloudflareConfig, - validateCloudflarePreviewName, + previewStaticWorkerConfig, } from '@void/deploy-cloudflare'; -import type { CloudflarePreviewDeployResult } from '@void/deploy-cloudflare'; import { dirname, join, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; import { analyzeApplication } from '../application-routing.ts'; @@ -33,6 +31,7 @@ import type { CloudflareCandidateReceipt } from './cloudflare-candidate.ts'; import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import { readCloudflareLink } from './cloudflare-link.ts'; import type { CloudflareLink } from './cloudflare-link.ts'; +import { checkCloudflarePreviewRequest, runCloudflareStaticPreview } from './cloudflare-preview.ts'; import { deduplicateGeneratedCompatibilityFlags } from './deploy-artifact-validation.ts'; import { deployPointerPath } from './deploy-binding-snapshot.ts'; import { prepareExistingCloudflareDeployWithAuth } from './deploy-cloudflare-auth.ts'; @@ -68,7 +67,7 @@ import { import type { RunDeployOptions, CloudflareDeployDeps } from './deploy-types.ts'; import { readGeneratedAssetHeadersFile } from './headers.ts'; import type { CliLogger } from './log-file.ts'; -import { getErrorMessage, note, printSuccess } from './output.ts'; +import { getErrorMessage, note } from './output.ts'; import { buildStaticManifest, readWranglerHtmlHandling } from './package.ts'; import { detectPreset } from './preset.ts'; import type { StaticPreset, FrameworkPreset } from './preset.ts'; @@ -341,14 +340,23 @@ export async function runCloudflareStaticDeploy( ): Promise { const exit = deps.exit ?? ((code: number): never => process.exit(code)); const configPath = discoverRootWranglerConfig(root); + if (options.preview !== undefined) { + const problem = checkCloudflarePreviewRequest({ + previewName: options.preview, + rootConfig: parseRootWranglerConfig(configPath), + configPath, + }); + if (problem) { + log.error(problem); + return exit(1); + } + } const connection = await connectCloudflareDeployAccount({ root, configPath, rootConfig: parseRootWranglerConfig(configPath), deps, - // A preview never saves an account for the project, as `void preview delete` does not. - persistAccount: - options.preview === undefined && !(options.reuseExistingWorker || initialCloudflareLink), + persistAccount: !(options.reuseExistingWorker || initialCloudflareLink), readinessAccessOrigin: options.readinessAccessOrigin, reporter, }); @@ -389,13 +397,6 @@ export async function runCloudflareStaticDeploy( workerName, options.preview === undefined ? 'Cloudflare' : `Cloudflare Preview ${options.preview}`, ); - if (options.preview !== undefined) { - const invalid = validateCloudflarePreviewName(options.preview, workerName); - if (invalid) { - log.error(`deploy: ${invalid}`); - return exit(1); - } - } const rootConfigBeforeBuild = existsSync(configPath) ? readFileSync(configPath, 'utf8') : null; if (preset.buildCommand && !options.skipBuild) { log.step('Building...'); @@ -447,7 +448,12 @@ export async function runCloudflareStaticDeploy( // Write the static config separately so the root config, with its Worker-only bindings and // comments, stays untouched for a later switch back to a Worker app. const staticConfigPath = join(dirname(entryPath), 'wrangler-static.json'); - writeFileSync(staticConfigPath, `${JSON.stringify(rootConfig, null, 2)}\n`, { mode: 0o600 }); + // A preview gets none of the Worker's bindings, vars or migrations. + writeFileSync( + staticConfigPath, + `${JSON.stringify(options.preview === undefined ? rootConfig : previewStaticWorkerConfig(rootConfig), null, 2)}\n`, + { mode: 0o600 }, + ); writeCloudflareStaticDeployConfig({ configPath: staticConfigPath, name: workerName, @@ -493,6 +499,7 @@ export async function runCloudflareStaticDeploy( headers: edgeRouting.assetHeaders, }); + const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); assertCloudflareDeployTargetUnchanged({ root, existingWorker, @@ -530,17 +537,15 @@ export async function runCloudflareStaticDeploy( }); const typeLabel = preset.appType === 'spa' ? 'Static SPA' : 'Static Site'; if (options.preview !== undefined) { - log.step(`Deploying Preview ${options.preview}...`); - const result = await deployCloudflarePreview({ + return runCloudflareStaticPreview({ runWrangler: activationRunner, + cfOutput, workerName, previewName: options.preview, + accountId, + configPath, + staticConfigPath, verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, - configPath: staticConfigPath, - }).finally(() => cfOutput?.dispose()); - return reportCloudflareStaticPreview(result, { - previewName: options.preview, - workerName, typeLabel, writeResult: options.writeResult, reporter, @@ -548,7 +553,6 @@ export async function runCloudflareStaticDeploy( exit, }); } - const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); const execution = await activateCloudflareVersionWithProgress( deps.activateVersion ?? activateCloudflareVersion, { @@ -604,76 +608,3 @@ export async function runCloudflareStaticDeploy( note(formatDeploySummary({ workerName, typeLabel }), execution.previewUrl); printDeploySuccess(); } - -/** Print a preview deploy's result: the URL, or a JSON record with `--json`, or the failure. */ -function reportCloudflareStaticPreview( - result: CloudflarePreviewDeployResult, - options: { - previewName: string; - workerName: string; - typeLabel: string; - writeResult: RunDeployOptions['writeResult']; - reporter: CloudflareChildReporter; - cliLog: CliLogger; - exit: (code: number) => never; - }, -): void { - const { previewName, workerName } = options; - if (!result.ok) { - const message = options.reporter.redactor.redact( - formatCloudflarePreviewError(result, workerName), - ); - options.cliLog.error('cloudflare_preview_failed', new Error(message), { - reason: result.reason, - }); - log.error(message); - return options.exit(1); - } - options.cliLog.info('cloudflare_preview_deployed', { - previewName, - previewId: result.previewId, - deploymentId: result.deploymentId, - }); - const record = { - type: 'preview', - workerName, - previewName, - previewUrl: result.previewUrl, - deploymentId: result.deploymentId, - deploymentUrl: result.deploymentUrl ?? null, - }; - options.writeResult?.(`${JSON.stringify(record)}\n`); - note( - [ - formatDeploySummary({ workerName, typeLabel: options.typeLabel }), - `Preview: ${previewName}`, - ...(result.deploymentUrl ? [`This deployment: ${result.deploymentUrl}`] : []), - ].join('\n'), - result.previewUrl, - ); - printSuccess(`Preview ${previewName} deployed. Production is unchanged.`); -} - -function formatCloudflarePreviewError( - result: Extract, - workerName: string, -): string { - switch (result.reason) { - case 'invalid-name': - return `deploy: ${result.diagnostic}`; - case 'uploader-changed': - return 'deploy: the Cloudflare uploader changed during the preview deploy. Nothing was deployed.'; - case 'output-invalid': - return 'deploy: Cloudflare accepted the preview but did not return a readable Preview record. Check the Worker in the Cloudflare dashboard before retrying.'; - case 'preview-urls-disabled': - return [ - `deploy: the preview was deployed, but Preview URLs are turned off for the Worker "${workerName}", so it has no URL.`, - 'Set preview_urls: true in the cloudflare field of void.config.ts and run a production deploy (void deploy --platform cloudflare), or turn on Preview under Domains for the Worker in the Cloudflare dashboard. Then deploy the preview again.', - ].join('\n'); - case 'deploy-failed': - return [ - 'deploy: Cloudflare could not deploy the preview. Production is unchanged.', - ...(result.diagnostic ? [result.diagnostic] : []), - ].join('\n'); - } -} diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index cb21440a4..3312ef5a5 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -3405,9 +3405,9 @@ it('deploys a named Preview from the prebuilt output without touching versions o calls.push({ args, cwd: run.cwd }); return { status: 0, - // Provider lines may precede the JSON record. - stdout: `Uploading assets\n${JSON.stringify(preview, null, 2)}\n`, - stderr: '', + // cf prints the record as JSON on stdout and its progress on stderr. + stdout: `${JSON.stringify(preview, null, 2)}\n`, + stderr: 'Uploading assets\n', }; }, }); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index ac18c9307..b03f81b2f 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12770,6 +12770,13 @@ describe('runCloudflareDeploy — `addresses` is whole-object pinned across the }); describe('runCloudflareDeploy — previews', () => { + /** Join the lines the terminal renderer wrapped, so long messages can be matched whole. */ + const unwrap = (text: string) => + text + .split('\n') + .map((line) => line.trim()) + .join(' '); + // What the cf runner decodes from `cf previews deploy`. const previewRecord: Record = { previewId: 'prv_1', @@ -12788,7 +12795,7 @@ describe('runCloudflareDeploy — previews', () => { if (args[0] === 'whoami') { return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; } - if (args[0] === 'preview') { + if (args[0] === 'previews') { return { ...cleanExit, stdout: JSON.stringify(record) }; } return cleanExit; @@ -12801,11 +12808,11 @@ describe('runCloudflareDeploy — previews', () => { }; } - const spa = () => + const spa = (config: Record = { name: 'spaapp', account_id: 'acc123' }) => makeProject({ 'package.json': JSON.stringify({ name: 'spaapp' }), 'void.json': JSON.stringify({ inference: { appType: 'spa' } }), - 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123' }), + 'wrangler.jsonc': JSON.stringify(config), 'dist/index.html': '
', }); @@ -12818,14 +12825,17 @@ describe('runCloudflareDeploy — previews', () => { expect(exitCalls).toEqual([]); expect(activateVersion).not.toHaveBeenCalled(); - // Only the session check and the Preview deploy reach Cloudflare: no version upload, - // deployment, traffic split, trigger or secret operation. - expect(wranglerArgs.map((args) => args.slice(0, 1))).toEqual([['whoami'], ['preview']]); - expect(wranglerArgs[1]).toEqual( - expect.arrayContaining(['--preview-name', 'pr-64', '--name', 'spaapp']), - ); + // Only the session check, the Worker check and the Preview deploy reach Cloudflare: no + // version upload, traffic split, trigger or secret operation. + expect(wranglerArgs.map((args) => args.slice(0, 2))).toEqual([ + ['whoami', '--json'], + ['deployments', 'status'], + ['previews', 'deploy'], + ]); + expect(wranglerArgs[2]).toEqual(['previews', 'deploy', '--prebuilt', '--preview-name=pr-64']); expect(existsSync(join(root, '.void/cloudflare-candidate.json'))).toBe(false); expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toEqual({ + name: 'spaapp', account_id: 'acc123', }); expect(output).toContain('spaapp → Cloudflare Preview pr-64'); @@ -12864,6 +12874,54 @@ describe('runCloudflareDeploy — previews', () => { }); }); + it('stages a config without the Worker bindings, vars or migrations', async () => { + const root = spa({ + name: 'spaapp', + account_id: 'acc123', + kv_namespaces: [{ binding: 'KV', id: 'kv' }], + d1_databases: [{ binding: 'DB', database_name: 'db', database_id: 'db' }], + vars: { MODE: 'production' }, + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + }); + const { deps, exitCalls } = previewHarness(); + await captureDeployOutput(() => + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, deps), + ); + expect(exitCalls).toEqual([]); + const staged = parseRootWranglerConfig( + join(root, '.void/deploy/cloudflare/wrangler-static.json'), + ); + expect(staged).toMatchObject({ name: 'spaapp', account_id: 'acc123' }); + for (const key of ['kv_namespaces', 'd1_databases', 'vars', 'migrations']) { + expect(staged).not.toHaveProperty(key); + } + }); + + it('stops before uploading when the Worker has no production deployment', async () => { + const root = spa(); + const base = previewHarness(); + const runWrangler = operationFixture((args) => { + base.wranglerArgs.push(args); + if (args[0] === 'whoami') { + return { ...cleanExit, stdout: '{"loggedIn":true,"accounts":[]}' }; + } + return args[0] === 'deployments' ? { ...cleanExit, status: 1, errorCode: 10_007 } : cleanExit; + }); + const output = await captureDeployOutput(() => + expect( + runCloudflareDeploy(root, { platform: 'cloudflare', preview: 'pr-64' }, silentCliLog, { + ...base.deps, + runWrangler, + }), + ).rejects.toThrow(ExitError), + ); + expect(base.exitCalls).toEqual([1]); + expect(unwrap(output)).toContain( + 'deploy: Worker "spaapp" has no production deployment in Cloudflare account acc123. Nothing was uploaded.', + ); + expect(base.wranglerArgs.some((args) => args[0] === 'previews')).toBe(false); + }); + it('fails clearly when the Worker has Preview URLs turned off', async () => { const root = spa(); const { previewUrl: _, ...withoutUrl } = previewRecord; @@ -12874,26 +12932,44 @@ describe('runCloudflareDeploy — previews', () => { ).rejects.toThrow(ExitError), ); expect(exitCalls).toEqual([1]); - expect(output).toContain('Preview URLs are turned off'); - expect(output).toContain('preview_urls: true in the cloudflare field of void.config.ts'); + expect(unwrap(output)).toContain( + 'Cloudflare created deployment dep_1 for preview "pr-64", but Preview URLs are off for Worker "spaapp", so it has no URL.', + ); + expect(unwrap(output)).toContain('Set preview_urls: true (preview_urls in wrangler.jsonc)'); }); - it('rejects a name too long for the Worker before building or uploading', async () => { - const root = spa(); + it.each([ + ['a bad name', 'PR_64', undefined, '"PR_64" is not a valid preview name'], + [ + 'no Worker name', + 'pr-64', + { account_id: 'acc123' }, + '--preview needs the Worker name (name in wrangler.jsonc)', + ], + [ + 'no pinned account', + 'pr-64', + { name: 'spaapp' }, + '--preview needs a pinned Cloudflare account', + ], + [ + 'a name too long for the Worker', + `pr-${'1'.repeat(60)}`, + undefined, + 'must be at most 63 characters, so use at most 56', + ], + ])('refuses %s before any Cloudflare call', async (_case, preview, config, message) => { + vi.stubEnv('CLOUDFLARE_ACCOUNT_ID', undefined); + const root = spa(config); const { deps, exitCalls, wranglerArgs } = previewHarness(); const output = await captureDeployOutput(() => expect( - runCloudflareDeploy( - root, - { platform: 'cloudflare', preview: `pr-${'1'.repeat(60)}` }, - silentCliLog, - deps, - ), + runCloudflareDeploy(root, { platform: 'cloudflare', preview }, silentCliLog, deps), ).rejects.toThrow(ExitError), ); expect(exitCalls).toEqual([1]); - expect(output).toContain('63 characters'); - expect(wranglerArgs.some((args) => args[0] === 'preview')).toBe(false); + expect(unwrap(output)).toContain(message); + expect(wranglerArgs).toEqual([]); }); it('refuses an app that needs a Worker before any Cloudflare operation', async () => { diff --git a/packages/void/test/unit/deploy-args.test.ts b/packages/void/test/unit/deploy-args.test.ts index 7fbfa32a8..6973985ed 100644 --- a/packages/void/test/unit/deploy-args.test.ts +++ b/packages/void/test/unit/deploy-args.test.ts @@ -175,6 +175,9 @@ describe('parseDeployArgs --preview', () => { expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview'])).toThrow( '--preview requires a name', ); + expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview='])).toThrow( + '--preview requires a name', + ); expect(() => parseDeployArgs(['--platform', 'cloudflare', '--preview', 'a', '--preview', 'b']), ).toThrow('only be specified once'); From 556f9e230eb82ed6f2038d38e5b28b3752a50db0 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 17:38:44 +0800 Subject: [PATCH 06/12] docs: pull request previews Document `void deploy --preview` and `void project preview delete`: the requirements (production first, `cloudflare.name`, a pinned account), the JSON record, failure output and naming rules. The GitHub Actions example now passes values through `env:`, skips fork and Dependabot pull requests, comments once and cleans up from the base branch. Update the deploy help rows, the skill and the package notes. Co-Authored-By: Claude Opus 5.5 --- docs/integrations/cloudflare.md | 122 ++++++++++++++++------------- docs/reference/cli.md | 100 +++++++++++------------ docs/reference/cli/deploy.md | 45 +++++++---- docs/reference/cli/project.md | 13 +++ packages/void/AGENTS.md | 2 + packages/void/skills/void/SKILL.md | 2 +- packages/void/src/cli/help.ts | 9 ++- 7 files changed, 165 insertions(+), 128 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 73cc92d51..68fea12e2 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -147,94 +147,103 @@ Grant **Workers → Admin** for the account when Void creates the Worker. For su For email, run `void email setup --platform cloudflare` locally, commit `void.lock.json`, and pass `--require-email` in CI. The token also needs Zone Read and Email Sending Edit, plus Email Routing Edit for apps with `email/` handlers. +#### Cloudflare Access + +For local deployment to an Access-protected Worker, you can use a short-lived user session: + +```sh +export CF_ACCESS_TOKEN="$(cloudflared access token --app=https://..workers.dev)" +``` + +Void uses Access credentials for readiness checks without saving them. If checks are denied, the deployment fails. A first-deploy bootstrap can already be active behind Access when this happens. + +By default, Void sends Access credentials only to `workers.dev` URLs. If `workers_dev` is `false`, Void can check readiness through your first route or Custom Domain. To send the credentials there, set `CF_ACCESS_READINESS_ORIGIN` to that hostname's origin: + +```sh +export CF_ACCESS_READINESS_ORIGIN="https://app.example.com" +``` + +Set this variable in the shell or CI environment running `void deploy`. Use an exact HTTPS origin for a hostname you control that serves this Worker; Void sends your Access credentials there. + ### Pull request previews -Give each pull request its own URL with [Cloudflare Previews](https://developers.cloudflare.com/workers/previews/). A Preview belongs to the same Worker but never receives production traffic. Previews are available for static sites, SPAs and supported SSGs. +Give each pull request its own URL with [Cloudflare Previews](https://developers.cloudflare.com/workers/previews/). A preview belongs to the same Worker but never receives production traffic. ```sh -void deploy --platform cloudflare --preview pr-64 --json # create or update -void preview delete pr-64 # remove +void deploy --platform cloudflare --preview pr-64 --json # create or update +void project preview delete pr-64 --platform cloudflare # remove ``` -The CI job needs only `CLOUDFLARE_API_TOKEN` (Workers Scripts: Edit) and, when the token can access several accounts, `CLOUDFLARE_ACCOUNT_ID`. This workflow deploys a preview on every push to a pull request, comments its URL, and deletes it when the pull request closes: +Deploy production once first and set `cloudflare.name`. The token needs **Workers → Editor**, since the Worker already exists, and `CLOUDFLARE_ACCOUNT_ID` pins the account. The preview job runs the pull request's code with this token, which can also deploy production. Pull requests from forks and Dependabot get no preview. + +This workflow deploys a preview on every push, comments its URL once, and deletes it when the pull request closes: ```yaml name: Preview - on: pull_request: types: [opened, synchronize, reopened, closed] - permissions: contents: read pull-requests: write - concurrency: - group: preview-${{ github.event.pull_request.number }} - + group: ${{ github.workflow }}-pr-${{ github.event.pull_request.number }} + # A new push cancels an older preview deploy; cleanup waits for it instead. + cancel-in-progress: ${{ github.event.action != 'closed' }} jobs: - preview: - # Repository secrets are not available to pull requests from forks. - if: github.event.action != 'closed' && github.event.pull_request.head.repo.full_name == github.repository + deploy: + # Fork and Dependabot pull requests get no repository secrets. + if: >- + github.event.action != 'closed' && + github.event.pull_request.head.repo.full_name == github.repository && + github.actor != 'dependabot[bot]' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 - with: - node-version: lts/* - check-latest: true - cache: pnpm + - uses: actions/checkout@v6 + - uses: pnpm/action-setup@v5 + - uses: actions/setup-node@v6 + with: { node-version: lts/*, check-latest: true, cache: pnpm } - run: pnpm install --frozen-lockfile - id: preview - run: | - set -o pipefail - url="$(pnpm exec void deploy --platform cloudflare --preview "pr-${{ github.event.pull_request.number }}" --json | jq -er '.previewUrl')" - echo "url=$url" >> "$GITHUB_OUTPUT" env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} - - run: gh pr comment "${{ github.event.pull_request.number }}" --edit-last --create-if-none --body "Preview: ${{ steps.preview.outputs.url }}" - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - + PREVIEW: pr-${{ github.event.pull_request.number }} + run: | + pnpm exec void deploy --platform cloudflare --preview "$PREVIEW" --json > preview.json + echo "url=$(jq -er .previewUrl preview.json)" >> "$GITHUB_OUTPUT" + # The preview URL never changes for a pull request, so comment once. + - env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + URL: ${{ steps.preview.outputs.url }} + run: | + if ! gh pr view "$PR" --json comments --jq '.comments[].body' | grep -qF "$URL"; then + gh pr comment "$PR" --body "Preview: $URL" + fi cleanup: - if: github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository + if: >- + github.event.action == 'closed' && + github.event.pull_request.head.repo.full_name == github.repository && + github.actor != 'dependabot[bot]' runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + # Trusted base-branch code; it still exists after the pull request closes. + - uses: actions/checkout@v6 with: - node-version: lts/* - check-latest: true - cache: pnpm + ref: ${{ github.event.pull_request.base.ref }} + - uses: pnpm/action-setup@v5 + - uses: actions/setup-node@v6 + with: { node-version: lts/*, check-latest: true, cache: pnpm } - run: pnpm install --frozen-lockfile - - run: pnpm exec void preview delete "pr-${{ github.event.pull_request.number }}" - env: + - env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + PREVIEW: pr-${{ github.event.pull_request.number }} + run: pnpm exec void project preview delete "$PREVIEW" --platform cloudflare ``` -If the build runs in an earlier job, download its output and add `--skip-build`. Preview URLs are public; protect them with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/) when needed. See [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output and naming rules. - -#### Cloudflare Access - -For local deployment to an Access-protected Worker, you can use a short-lived user session: - -```sh -export CF_ACCESS_TOKEN="$(cloudflared access token --app=https://..workers.dev)" -``` - -Void uses Access credentials for readiness checks without saving them. If checks are denied, the deployment fails. A first-deploy bootstrap can already be active behind Access when this happens. - -By default, Void sends Access credentials only to `workers.dev` URLs. If `workers_dev` is `false`, Void can check readiness through your first route or Custom Domain. To send the credentials there, set `CF_ACCESS_READINESS_ORIGIN` to that hostname's origin: - -```sh -export CF_ACCESS_READINESS_ORIGIN="https://app.example.com" -``` - -Set this variable in the shell or CI environment running `void deploy`. Use an exact HTTPS origin for a hostname you control that serves this Worker; Void sends your Access credentials there. +Using npm, Yarn or Bun? Use the setup steps that `void init --github` writes. If an earlier job builds the site, download its output and add `--skip-build`. Preview URLs are public; see [`void deploy --preview`](../reference/cli/deploy.md#void-deploy-preview) for the JSON output, naming rules and limits. ### Databases and secrets @@ -279,6 +288,7 @@ Void deploys native apps, static sites, SPAs, supported SSGs, and Cloudflare bui - Native apps support Void routing rules. Framework apps on the direct target must configure redirects, rewrites, fallbacks, and headers through their framework or Worker. - `--skip-build` works for existing static output. Worker apps require a fresh build. +- `--preview` works for static sites and SPAs only. - Named Cloudflare environments aren't supported. Use a separate Void project config for each target. - Sandbox requires Workers Paid and Docker. See [Sandbox requirements](../guide/sandboxes.md#deployment) for plan and token permissions. - Email to arbitrary recipients, and all sending from apps without `email/` handlers, requires Workers Paid. Apps with handlers keep inbound mail and verified recipients on Workers Free. See [Email](../guide/email/domains.md#your-own-cloudflare-account). @@ -288,7 +298,7 @@ Commit Durable Object migration history in `void.lock.json`. Do not delete or re ### Managing the deployed app -`void secret`, `void domain`, `void project status|list|logs|rollback`, and remote `void db` commands use the selected account and Worker. Logs are a live tail. +`void secret`, `void domain`, `void project status|list|logs|rollback`, `void project preview delete`, and remote `void db` commands use the selected account and Worker. Logs are a live tail. Custom domain commands update routes immediately. If a first deployment times out while DNS or TLS is propagating, check the domain in Cloudflare and retry once `/__void/ready` is reachable. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 371c9a1b5..fc140bf9a 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -23,7 +23,7 @@ Use this page as a command reference. If you are setting up a project for the fi | `init`, `prepare`, `info`, `migrate` | [Project setup](./cli/setup.md) | | `connect`, `auth`, `account`, `cloudflare` | [Connections and authentication](./cli/auth.md) | | `project` | [Projects, teams, logs, and rollback](./cli/project.md) | -| `deploy`, `preview` | [Deployment](./cli/deploy.md) | +| `deploy` | [Deployment](./cli/deploy.md) | | `db` | [Database](./cli/database.md) | | `gen` | [Code generation](./cli/generate.md) | | `secret`, `env` | [Secrets and environment](./cli/secrets.md) | @@ -34,55 +34,55 @@ Use this page as a command reference. If you are setting up a project for the fi ## Cheat Sheet {#cheat-sheet} -| Command | Purpose | -| --------------------------------- | ----------------------------------------------------------------------------- | -| `void deploy` | Build and deploy to the configured platform | -| `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | -| `void deploy --preview ` | Deploy a Cloudflare Preview with its own URL; production is unchanged | -| `void preview delete ` | Delete a Cloudflare Preview | -| `void prepare` | Generate `.void` artifacts without starting Vite | -| `void info [--json]` | Inspect persistent resource names before moving their code | -| `void gen model [cols...]` | Scaffold a Drizzle table and API routes | -| `void gen route ` | Create an API route | -| `void db push` | Apply schema directly without migration files | -| `void db generate` | Generate SQL migrations from schema changes | -| `void db status` | Show local/remote migration status | -| `void db reset` | Drop and re-apply all migrations | -| `void db seed` | Reset + seed local database | -| `void db execute ` | Run SQL against the database (--remote for deployed) | -| `void db studio` | Open Drizzle Studio (--remote for a deployed external database) | -| `void db restore --bookmark ` | Restore the deployed D1 database to a restore point (direct Cloudflare) | -| `void secret put ` | Set a production secret | -| `void secret list` | List production secrets | -| `void secret sync ` | Bulk upload secrets from dotenv file | -| `void env check [--remote]` | Validate env.ts schema | -| `void env types` | Regenerate .void/env.d.ts from env.ts | -| `void auth login` | Authenticate with the project’s saved destination, or choose one | -| `void account login` | Authenticate with a Void platform | -| `void cloudflare login` | Authenticate with Cloudflare through Void | -| `void platform install` | Install a company Void platform in Cloudflare | -| `void platform security` | Administer security audits: scan mode, models, caps, findings, and alerts | -| `void connect ` | Connect the CLI to a Void platform; hostnames default to HTTPS | -| `void project link` | Link directory to a project | -| `void project logs` | Show runtime logs from deployed project | -| `void project requests` | Show request-level traffic (status, method, timing) | -| `void project rollback` | Roll back to a previous deployment | -| `void project cancel` | Cancel an active deployment | -| `void project zero-trust` | Inspect or override project Zero Trust protection, or bypass a security scan | -| `void project security` | Review findings and scans, set model and budget, scan, check code pre-deploy | -| `void project purge-cache` | Purge all cached pages (Void platform) | -| `void build logs` | Stream, tail, or download build logs | -| `void email status` | Show email readiness on your own Cloudflare account (`--platform cloudflare`) | -| `void email setup` | Set email up on your own Cloudflare account, without deploying | -| `void email usage` | Show monthly recipient attempts, inbound receipts, and quota | -| `void email logs` | Show recent email delivery activity | -| `void email destinations` | List verified recipient addresses | -| `void email allow
` | Add a recipient and send a verification email | -| `void email disallow
` | Remove a recipient from the allowlist | -| `void email alias [name]` | Show the shared mail address, or give it a shorter permanent name | -| `void email domain` | Send and receive at your own domain on a Cloudflare zone | -| `void init` | Set up a new or existing project, including coding agents | -| `void migrate` | Update project configuration | +| Command | Purpose | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------- | +| `void deploy` | Build and deploy to the configured platform | +| `void deploy --skip-migrations` | Deploy code without applying application or authentication SQL migrations | +| `void deploy --platform cloudflare --preview ` | Deploy a static site to a Cloudflare Preview; production is unchanged | +| `void project preview delete --platform cloudflare` | Delete a Cloudflare Preview | +| `void prepare` | Generate `.void` artifacts without starting Vite | +| `void info [--json]` | Inspect persistent resource names before moving their code | +| `void gen model [cols...]` | Scaffold a Drizzle table and API routes | +| `void gen route ` | Create an API route | +| `void db push` | Apply schema directly without migration files | +| `void db generate` | Generate SQL migrations from schema changes | +| `void db status` | Show local/remote migration status | +| `void db reset` | Drop and re-apply all migrations | +| `void db seed` | Reset + seed local database | +| `void db execute ` | Run SQL against the database (--remote for deployed) | +| `void db studio` | Open Drizzle Studio (--remote for a deployed external database) | +| `void db restore --bookmark ` | Restore the deployed D1 database to a restore point (direct Cloudflare) | +| `void secret put ` | Set a production secret | +| `void secret list` | List production secrets | +| `void secret sync ` | Bulk upload secrets from dotenv file | +| `void env check [--remote]` | Validate env.ts schema | +| `void env types` | Regenerate .void/env.d.ts from env.ts | +| `void auth login` | Authenticate with the project’s saved destination, or choose one | +| `void account login` | Authenticate with a Void platform | +| `void cloudflare login` | Authenticate with Cloudflare through Void | +| `void platform install` | Install a company Void platform in Cloudflare | +| `void platform security` | Administer security audits: scan mode, models, caps, findings, and alerts | +| `void connect ` | Connect the CLI to a Void platform; hostnames default to HTTPS | +| `void project link` | Link directory to a project | +| `void project logs` | Show runtime logs from deployed project | +| `void project requests` | Show request-level traffic (status, method, timing) | +| `void project rollback` | Roll back to a previous deployment | +| `void project cancel` | Cancel an active deployment | +| `void project zero-trust` | Inspect or override project Zero Trust protection, or bypass a security scan | +| `void project security` | Review findings and scans, set model and budget, scan, check code pre-deploy | +| `void project purge-cache` | Purge all cached pages (Void platform) | +| `void build logs` | Stream, tail, or download build logs | +| `void email status` | Show email readiness on your own Cloudflare account (`--platform cloudflare`) | +| `void email setup` | Set email up on your own Cloudflare account, without deploying | +| `void email usage` | Show monthly recipient attempts, inbound receipts, and quota | +| `void email logs` | Show recent email delivery activity | +| `void email destinations` | List verified recipient addresses | +| `void email allow
` | Add a recipient and send a verification email | +| `void email disallow
` | Remove a recipient from the allowlist | +| `void email alias [name]` | Show the shared mail address, or give it a shorter permanent name | +| `void email domain` | Send and receive at your own domain on a Cloudflare zone | +| `void init` | Set up a new or existing project, including coding agents | +| `void migrate` | Update project configuration | For platform administration, see [plans and account limits](../guide/platform/administration/plans.md), [users and projects](./cli/platform-users.md), and [AI logging](./cli/platform-users.md#ai-gateway-logging). diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 21eebd2c8..3f611807b 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -40,8 +40,8 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m | `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` | | `--provision` | Run resource provisioning again even when every resource exists; requires `--platform cloudflare` | | `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | -| `--preview ` | Create or update a Cloudflare Preview instead of production; see [Previews](#void-deploy-preview) | -| `--json` | With `--preview`, print the result as one JSON record on stdout; progress goes to stderr | +| `--preview ` | Deploy a static site or SPA to a Cloudflare Preview; production is unchanged ([more](#void-deploy-preview)) | +| `--json` | With `--preview`, print one JSON object on stdout; everything else goes to stderr | | `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | `--atomic` applies to one deployment. For an existing Durable Object Worker that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. @@ -125,22 +125,32 @@ For Access credentials, Hyperdrive permissions, readiness, and rollback, see [Cl ## `void deploy --platform cloudflare --preview ` {#void-deploy-preview} -Deploy the build to a named [Cloudflare Preview](https://developers.cloudflare.com/workers/previews/) of the same Worker: +Deploy a static site or SPA to a named [Cloudflare Preview](https://developers.cloudflare.com/workers/previews/) of the same Worker. Production traffic, routes and schedules are unchanged. ```sh -void deploy --platform cloudflare --skip-build --preview pr-64 --json +void deploy --platform cloudflare --preview pr-64 ``` -A Preview has its own stable URL, `https://-..workers.dev`, which always serves its latest deployment. Deploying the same name again updates that URL. Production traffic, the active deployment, routes and schedules are unchanged. +Add `--skip-build` or `--dir` to reuse an earlier build. -Previews are available for static sites, SPAs and supported SSGs. Apps that need a Worker, such as server routes, bindings, migrations or secrets, are refused before anything is built or uploaded. A Preview does not inherit production secrets. +A Preview keeps its URL across deploys: `https://-..workers.dev`, or `.` on a custom domain. -The name uses lowercase letters, digits and hyphens. `-` must fit in 63 characters. Use a name derived from the pull request, such as `pr-64`, rather than a branch name. +Before the first preview: + +- Deploy the Worker to production once with `void deploy --platform cloudflare`. A preview never creates the Worker. +- Set `cloudflare.name` in `void.config.ts`. +- Pin the account with `cloudflare.account_id` or `CLOUDFLARE_ACCOUNT_ID`. +- Workers that serve only routes or custom domains need `preview_urls: true`. + +Only static sites and SPAs can deploy a preview. A static preview gets none of the Worker's bindings, vars or secrets. + +Use lowercase letters, digits and single hyphens, starting with a letter. On workers.dev, `-` must fit in 63 characters. Name previews after the pull request, such as `pr-64`. With `--json`, stdout carries one line: ```json { + "type": "preview", "workerName": "my-app", "previewName": "pr-64", "previewUrl": "https://pr-64-my-app.my-team.workers.dev", @@ -149,16 +159,17 @@ With `--json`, stdout carries one line: } ``` -`previewUrl` always serves the latest deployment of this Preview. `deploymentUrl` serves only this deployment. - -The Worker must allow Preview URLs. Void's production deploy turns them on when workers.dev is on. If you set `cloudflare.preview_urls` to `false` in `void.config.ts`, a preview deploy fails and says how to turn it back on. Workers Free allows 100 Previews per Worker; Cloudflare removes the least recently deployed one beyond that. +| Field | Type | Meaning | +| --------------- | ---------------- | ----------------------------------------------- | +| `type` | `"preview"` | Record type | +| `workerName` | `string` | The Worker the preview belongs to | +| `previewName` | `string` | The name passed to `--preview` | +| `previewUrl` | `string` | Always serves the latest deploy of this preview | +| `deploymentId` | `string` | This deployment | +| `deploymentUrl` | `string \| null` | Serves only this deployment | -See [Pull request previews](../../integrations/cloudflare.md#pull-request-previews) for a GitHub Actions workflow. +On failure, stdout is empty and the exit code is not 0; read stderr. -## `void preview delete ` {#void-preview-delete} - -```sh -void preview delete pr-64 -``` +Preview URLs are public. Protect them with [Cloudflare Access](https://developers.cloudflare.com/workers/configuration/cloudflare-access/) when needed. Workers Free allows 100 previews per Worker; Cloudflare removes the oldest one beyond that. -Delete a Preview and all its deployments. Production is unchanged. Deleting a Preview that does not exist succeeds, so a cleanup job can run more than once. It uses the same account and Worker as `void deploy --platform cloudflare`. +Remove a preview with [`void project preview delete`](./project.md#void-project-preview-delete-name). See [Pull request previews](../../integrations/cloudflare.md#pull-request-previews) for a GitHub Actions workflow. diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index 7436ddea0..adb30dea7 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -241,6 +241,19 @@ Pass `--platform cloudflare` to roll back a one-off Cloudflare deployment. Database recovery is separate from code rollback. Void asks for confirmation when the earlier code may be incompatible with the current schema. For D1 on Cloudflare, use [`void db restore`](./database.md#void-db-restore) with the restore point printed during deployment. +## `void project preview delete ` {#void-project-preview-delete-name} + +``` +void project preview delete [--platform cloudflare] +``` + +Delete a Cloudflare Preview made with [`void deploy --preview`](./deploy.md#void-deploy-preview), and all its deployments. Production is unchanged. It needs `cloudflare.name` and a pinned account (`cloudflare.account_id` or `CLOUDFLARE_ACCOUNT_ID`), the same ones the preview deploy used. + +- Exit code 0: the preview was deleted, or it did not exist. A cleanup job can run more than once. +- Exit code 1: the Worker was not found in the account, or Cloudflare returned another error. + +Pass `--platform cloudflare` when the project's saved platform is not Cloudflare. + ## `void project cancel [deployId]` {#void-project-cancel-deployid} ``` diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b68..47418ac02 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -25,6 +25,8 @@ Unlinked projects with a root `wrangler.jsonc` or `wrangler.json` get a link-and Assets-only Workers report null or empty handlers alongside `script_runtime.assets`. Accept that shape during handoff; only the static adapter may add its `ASSETS` binding and sole `fetch` handler. Preserve every existing binding and reject name collisions. Missing handler metadata without verified assets must not bypass the handler checks. +Static previews (`deploy --preview`) send `deployments.status` then `previews.deploy` from a Build Output with `isPreview: true` and an allow-listed config (`previewStaticWorkerConfig`); they never create a Worker. + Handoff asks for an explicit ISR cache choice when the app requests caching and the verified Worker has no cache. Persist `routing.isr` in `void.config.ts` before provisioning: true allows only the new cache during this deployment; false disables ISR in native output and managed manifests until explicitly changed. Existing bindings and handlers remain protected; generated and uploaded cache IDs must match the approved pre-build identity, and the cache cannot alias an existing application namespace. Retrying may reuse the ID already recorded in `void.lock.json`. Never defer cache enablement implicitly to the next deploy. Existing D1 migration settings remain untouched during handoff, which applies no migrations. The main export `voidPlugin()` returns an array of Vite plugins. For the default Cloudflare target, this includes the `cloudflare()` plugin. For non-CF targets (`node`, `bun`, `deno`), it replaces `cloudflare()` with `nodeTargetPlugin()`: diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index 4192a268c..f35504e9d 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -32,7 +32,7 @@ For a one-time deployment elsewhere, connect to that platform, then set `VOID_API_URL` for the deploy command and pass `--project `. This preserves the app's existing saved destination, including when the target project is new. -For a per-pull-request Cloudflare preview of a static site or SPA, use `void deploy --platform cloudflare --preview pr- --json` and `void preview delete pr-` on close; see `docs/reference/cli/deploy.md`. +Static PR previews: `void deploy --platform cloudflare --preview pr- --json` (deploy production first); remove with `void project preview delete pr- --platform cloudflare`. Use `void deploy --skip-migrations` when database migrations run separately; it skips application and authentication SQL for that invocation. Ensure the code supports the current database schema and follow `docs/guide/deployment.md` for the release workflow. diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 658ce2be7..804c65aaa 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -196,11 +196,12 @@ const HELP_TREE = { { command: '--preview ', description: - 'Create or update a Cloudflare Preview with its own URL; production is unchanged (static sites and SPAs, with --platform cloudflare)', + 'Deploy a static site or SPA to a Cloudflare Preview with its own URL; production is unchanged (needs --platform cloudflare)', }, { command: '--json', - description: 'Print the preview result as JSON on stdout (with --preview)', + description: + 'With --preview, print one JSON object on stdout; everything else goes to stderr', }, { command: '--debug', @@ -216,8 +217,8 @@ const HELP_TREE = { description: 'Deploy to your own Cloudflare account', }, { - command: 'void deploy --platform cloudflare --preview pr-64 --json', - description: 'Deploy a pull request preview and print its URL as JSON', + command: 'void deploy --platform cloudflare --preview pr-64', + description: 'Deploy a pull request preview; production is unchanged', }, ], }, From c2db775bd366516b7e4d0d4eb7d2d2c74f738bb0 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:00:38 +0800 Subject: [PATCH 07/12] fix(cli): require the preview name in the project menu A menu hint with a <...> part now needs input, so Enter on an empty "delete " no longer runs into a usage error. The menu splits a hint of several words into separate arguments, so parseProjectArgs stays strict. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/cli-main.ts | 11 ++++++++--- packages/void/src/cli/project-args.ts | 3 +-- packages/void/src/cli/subcommand-prompt.ts | 8 +++++--- packages/void/test/unit/project-args.test.ts | 1 + packages/void/test/unit/subcommand-prompt.test.ts | 12 ++++++++++++ 5 files changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 4795f2527..1e47301e0 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -27,10 +27,15 @@ import { projectSubcommands, parseProjectArgs } from './project-args.ts'; import { secretSubcommands, parseSecretArgs } from './secret-args.ts'; import type { SubcommandDef, SubcommandResult } from './subcommand-prompt.ts'; -function buildArgs(result: SubcommandResult, trailingArgs: Array): Array { +function buildArgs( + result: SubcommandResult, + trailingArgs: Array, + subcommands: Array, +): Array { const out = [result.subcommand]; if (result.arg) { - out.push(result.arg); + const hint = subcommands.find(({ name }) => name === result.subcommand)?.arg; + out.push(...(hint?.includes(' ') ? result.arg.split(' ').filter(Boolean) : [result.arg])); } if (result.extraArgs) { out.push(...result.extraArgs); @@ -81,7 +86,7 @@ async function runSubcommandGroup( if (!result) { process.exit(0); } - const parsed = parse(buildArgs(result, args.slice(1))); + const parsed = parse(buildArgs(result, args.slice(1), subcommands)); await run(root, parsed); } else { const parsed = parse(args.slice(1)); diff --git a/packages/void/src/cli/project-args.ts b/packages/void/src/cli/project-args.ts index 40e7320eb..d0334d9c1 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -385,8 +385,7 @@ export function parseProjectArgs(args: Array): ProjectArgs { } platform = 'cloudflare'; } else { - // The interactive menu passes the typed "delete " as one argument. - positional.push(...arg.split(' ').filter(Boolean)); + positional.push(arg); } } const [action, name] = positional; diff --git a/packages/void/src/cli/subcommand-prompt.ts b/packages/void/src/cli/subcommand-prompt.ts index 8bb663094..3a26f8b76 100644 --- a/packages/void/src/cli/subcommand-prompt.ts +++ b/packages/void/src/cli/subcommand-prompt.ts @@ -37,7 +37,9 @@ export type FollowUpDef = export type SubcommandDef = { name: string; description: string; - arg?: string; // e.g. "" — shown as dim hint, enables inline text input + // e.g. "": a dim hint that enables text input. A "<...>" part makes the input required, and + // a hint of several words, such as "delete ", is passed as that many arguments. + arg?: string; hint?: string; // e.g. "login | logout | whoami" — shown dim after name flags?: Array; followUp?: FollowUpDef; @@ -226,7 +228,7 @@ export function promptSubcommand( ...instructions(SELECT_INSTRUCTIONS), ]; if (focused.arg) { - if (focused.arg.startsWith('<')) { + if (focused.arg.includes('<')) { footer.push(`${guidePrefix()}${pc.dim(`Type ${focused.arg}, then press Enter`)}`); } else { footer.push( @@ -433,7 +435,7 @@ export function promptSubcommand( } if (isEnterKey(key)) { - const argRequired = focused.arg && focused.arg.startsWith('<'); + const argRequired = focused.arg?.includes('<'); if (argRequired && input.length === 0) { return; } diff --git a/packages/void/test/unit/project-args.test.ts b/packages/void/test/unit/project-args.test.ts index 2698cd05b..965fa915f 100644 --- a/packages/void/test/unit/project-args.test.ts +++ b/packages/void/test/unit/project-args.test.ts @@ -426,6 +426,7 @@ describe('parseProjectArgs preview', () => { [['preview', 'delete', '-x']], [['preview', 'delete', 'pr-64', 'pr-65']], [['preview', 'list']], + [['preview', 'delete pr-64']], [['preview', 'delete', 'pr-64', '--platform', 'aws']], ])('refuses %j', (args) => { expect(() => parseProjectArgs(args)).toThrow( diff --git a/packages/void/test/unit/subcommand-prompt.test.ts b/packages/void/test/unit/subcommand-prompt.test.ts index e2145cd2c..5c924708d 100644 --- a/packages/void/test/unit/subcommand-prompt.test.ts +++ b/packages/void/test/unit/subcommand-prompt.test.ts @@ -111,6 +111,18 @@ it('shows the end of long input while submitting the complete value', async () = expect(await prompt.result).toEqual({ subcommand: 'connect', arg: url }); }); +it('requires input for a hint with a placeholder after a word', async () => { + const prompt = openPrompt([ + { name: 'preview', description: 'Delete a preview', arg: 'delete ' }, + ]); + expect(prompt.frame()).toContain('Type delete , then press Enter'); + expect(prompt.frame()).not.toContain('press Enter to skip'); + prompt.key('\r'); + prompt.key('delete pr-64'); + prompt.key('\r'); + expect(await prompt.result).toEqual({ subcommand: 'preview', arg: 'delete pr-64' }); +}); + it('bounds repeat-input history while retaining every submitted entry', async () => { const prompt = openPrompt( [ From ed43670867324b13eb606182f1ba1f765fa35a29 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:00:40 +0800 Subject: [PATCH 08/12] fix(deploy): name a Worker too long for previews With a Worker name of 62 or 63 characters no preview name fits on workers.dev, so say that instead of "use at most 0". The account and delete messages name the right config file, and the 63-character limit is shared from @void/deploy-cloudflare. Co-Authored-By: Claude Opus 5.5 --- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/preview.ts | 8 ++++---- packages/void/src/cli/cloudflare-preview.ts | 16 +++++++++------- .../void/test/unit/cloudflare-deploy.test.ts | 8 +++++++- 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 58ac26f7f..a62c9e480 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -55,6 +55,7 @@ export { type CloudflareWorkersDevSubdomainLookup, } from './version.ts'; export { + CLOUDFLARE_HOST_LABEL_MAX, deleteCloudflarePreview, cloudflarePreviewNameProblem, deployCloudflarePreview, diff --git a/packages/deploy-cloudflare/src/preview.ts b/packages/deploy-cloudflare/src/preview.ts index 0457a80f6..25231d3e2 100644 --- a/packages/deploy-cloudflare/src/preview.ts +++ b/packages/deploy-cloudflare/src/preview.ts @@ -4,8 +4,8 @@ import { isCleanCommandExit, isCompletedCommand, isWorkerNotFound } from './exec import type { CloudflareCommandRunner } from './execute.ts'; import type { CloudflarePreviewUploadResult } from './operations.ts'; -/** A DNS label holds at most 63 characters. */ -const MAX_HOST_LABEL = 63; +/** A DNS label, such as a workers.dev Preview host, holds at most 63 characters. */ +export const CLOUDFLARE_HOST_LABEL_MAX = 63; /** Cloudflare's "Preview not found" API error. */ const PREVIEW_NOT_FOUND = 10_025; @@ -14,8 +14,8 @@ const PREVIEW_NOT_FOUND = 10_025; * unchanged as the start of a hostname label, so the URL Void prints is the one CI expects. */ export function cloudflarePreviewNameProblem(name: string): string | undefined { - if (name.length === 0 || name.length > MAX_HOST_LABEL) { - return `must be 1 to ${MAX_HOST_LABEL} characters`; + if (name.length === 0 || name.length > CLOUDFLARE_HOST_LABEL_MAX) { + return `must be 1 to ${CLOUDFLARE_HOST_LABEL_MAX} characters`; } if (!isLowercaseLetter(name[0])) { return 'must start with a lowercase letter'; diff --git a/packages/void/src/cli/cloudflare-preview.ts b/packages/void/src/cli/cloudflare-preview.ts index ea0e71b66..40457dc64 100644 --- a/packages/void/src/cli/cloudflare-preview.ts +++ b/packages/void/src/cli/cloudflare-preview.ts @@ -1,4 +1,5 @@ import { + CLOUDFLARE_HOST_LABEL_MAX, cloudflarePreviewNameProblem, deleteCloudflarePreview, deployCloudflarePreview, @@ -19,9 +20,6 @@ import type { RunDeployOptions } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { note, printSuccess } from './output.ts'; -/** A workers.dev hostname label holds at most 63 characters. */ -const MAX_HOST_LABEL = 63; - /** Where the user sets a top-level Cloudflare config key, for messages. */ export function cloudflareConfigKey(configPath: string, key: string): string { const file = basename(configPath); @@ -52,12 +50,16 @@ export function checkCloudflarePreviewRequest(options: { !readWranglerTopLevelString(rootConfig, 'account_id') && !process.env.CLOUDFLARE_ACCOUNT_ID?.trim() ) { - return 'deploy: --preview needs a pinned Cloudflare account. Set cloudflare.account_id in void.config.ts or CLOUDFLARE_ACCOUNT_ID.'; + return `deploy: --preview needs a pinned Cloudflare account. Set ${cloudflareConfigKey(configPath, 'account_id')} or CLOUDFLARE_ACCOUNT_ID.`; } // Stricter than a Preview that serves only a custom domain needs, but CI reads the workers.dev // URL. - if (previewName.length + 1 + workerName.length > MAX_HOST_LABEL) { - return `deploy: preview name "${previewName}" is too long for Worker "${workerName}". On workers.dev, "${previewName}-${workerName}" must be at most ${MAX_HOST_LABEL} characters, so use at most ${MAX_HOST_LABEL - 1 - workerName.length}.`; + const room = CLOUDFLARE_HOST_LABEL_MAX - 1 - workerName.length; + if (room < 1) { + return `deploy: Worker name "${workerName}" is too long for a preview. On workers.dev, "-${workerName}" must be at most ${CLOUDFLARE_HOST_LABEL_MAX} characters, so the Worker name can have at most ${CLOUDFLARE_HOST_LABEL_MAX - 2}.`; + } + if (previewName.length > room) { + return `deploy: preview name "${previewName}" is too long for Worker "${workerName}". On workers.dev, "${previewName}-${workerName}" must be at most ${CLOUDFLARE_HOST_LABEL_MAX} characters, so use at most ${room}.`; } return undefined; } @@ -189,7 +191,7 @@ export async function runCloudflarePreviewDelete( } if (result.reason === 'worker-not-found') { throw new Error( - `project: Worker "${workerName}" was not found in Cloudflare account ${context.accountId}. Nothing was deleted. Check cloudflare.name and CLOUDFLARE_ACCOUNT_ID.`, + `project: Worker "${workerName}" was not found in Cloudflare account ${context.accountId}. Nothing was deleted. Check ${cloudflareConfigKey(context.configPath, 'name')} and the pinned account.`, ); } throw new Error( diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index b03f81b2f..d743dbc05 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -12950,7 +12950,7 @@ describe('runCloudflareDeploy — previews', () => { 'no pinned account', 'pr-64', { name: 'spaapp' }, - '--preview needs a pinned Cloudflare account', + '--preview needs a pinned Cloudflare account. Set account_id in wrangler.jsonc', ], [ 'a name too long for the Worker', @@ -12958,6 +12958,12 @@ describe('runCloudflareDeploy — previews', () => { undefined, 'must be at most 63 characters, so use at most 56', ], + [ + 'any name, when the Worker name leaves no room', + 'pr-1', + { name: 'w'.repeat(62), account_id: 'acc123' }, + 'so the Worker name can have at most 61', + ], ])('refuses %s before any Cloudflare call', async (_case, preview, config, message) => { vi.stubEnv('CLOUDFLARE_ACCOUNT_ID', undefined); const root = spa(config); From 2f7f615ea9716eeb0784cced752544757969195b Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:00:42 +0800 Subject: [PATCH 09/12] test(cli): dry-run the staged preview config Build the cf previews deploy dry run from previewStaticWorkerConfig and writeCloudflareStaticDeployConfig, the shape a preview deploy uploads. Co-Authored-By: Claude Opus 5.5 --- .../void/test/unit/cf-build-output.test.ts | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/packages/void/test/unit/cf-build-output.test.ts b/packages/void/test/unit/cf-build-output.test.ts index 760b02d08..f683356cd 100644 --- a/packages/void/test/unit/cf-build-output.test.ts +++ b/packages/void/test/unit/cf-build-output.test.ts @@ -27,8 +27,10 @@ import { } from '@cloudflare/build-output-utils'; import { cloudflare } from '@cloudflare/vite-plugin'; import { + previewStaticWorkerConfig, renderCloudflareStaticEntry, writeCloudflareFrameworkDeployConfig, + writeCloudflareStaticDeployConfig, } from '@void/deploy-cloudflare'; import { toSlash } from 'pathslash'; import { createBuilder } from 'vite'; @@ -1238,11 +1240,35 @@ it.each([ expectCfDryRun(prepared.directory, ['deploy']); }, ); - // `cf previews deploy` accepts only output marked as a Preview build. + // `cf previews deploy` accepts only output marked as a Preview build. Stage the config the way a + // preview deploy does, from a production config with bindings and migrations. + const previewConfigPath = join(generated, 'wrangler-preview.json'); + writeFileSync( + previewConfigPath, + JSON.stringify( + previewStaticWorkerConfig({ + name: 'void-static-test', + account_id: 'account-id', + vars: { SECRET_HINT: 'production' }, + kv_namespaces: [{ binding: 'CACHE', id: 'kv-id' }], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Room'] }], + version_metadata: { binding: 'CF_VERSION_METADATA' }, + }), + ), + ); + writeCloudflareStaticDeployConfig({ + configPath: previewConfigPath, + name: 'void-static-test', + accountId: 'account-id', + main: 'static-edge.mjs', + assetsDirectory: './assets', + compatibilityDate: '2026-09-29', + assetConfig: { run_worker_first: true, not_found_handling: 'single-page-application' }, + }); await withPrepared( prepareCfStaticBuildOutput({ projectRoot: root, - configPath, + configPath: previewConfigPath, assetsDirectory: assets, accountId: 'account-id', isPreview: true, From 81c50445b02743c853fed83ebc5037b015f0feac Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:00:43 +0800 Subject: [PATCH 10/12] docs: preview Worker name keys and one-line JSON Co-Authored-By: Claude Opus 5.5 --- docs/integrations/cloudflare.md | 2 +- docs/reference/cli/deploy.md | 6 +++--- docs/reference/cli/project.md | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 68fea12e2..a55741f9d 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -174,7 +174,7 @@ void deploy --platform cloudflare --preview pr-64 --json # create or upda void project preview delete pr-64 --platform cloudflare # remove ``` -Deploy production once first and set `cloudflare.name`. The token needs **Workers → Editor**, since the Worker already exists, and `CLOUDFLARE_ACCOUNT_ID` pins the account. The preview job runs the pull request's code with this token, which can also deploy production. Pull requests from forks and Dependabot get no preview. +Deploy production once first and set the Worker name (`cloudflare.name`, or `name` in `wrangler.jsonc`). The token needs **Workers → Editor**, since the Worker already exists, and `CLOUDFLARE_ACCOUNT_ID` pins the account. The preview job runs the pull request's code with this token, which can also deploy production. Pull requests from forks and Dependabot get no preview. This workflow deploys a preview on every push, comments its URL once, and deletes it when the pull request closes: diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 3f611807b..a09cf7716 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -138,15 +138,15 @@ A Preview keeps its URL across deploys: `https://-..wor Before the first preview: - Deploy the Worker to production once with `void deploy --platform cloudflare`. A preview never creates the Worker. -- Set `cloudflare.name` in `void.config.ts`. -- Pin the account with `cloudflare.account_id` or `CLOUDFLARE_ACCOUNT_ID`. +- Set the Worker name: `cloudflare.name` in `void.config.ts`, or `name` in `wrangler.jsonc`. +- Pin the account with `cloudflare.account_id` (`account_id` in `wrangler.jsonc`) or `CLOUDFLARE_ACCOUNT_ID`. - Workers that serve only routes or custom domains need `preview_urls: true`. Only static sites and SPAs can deploy a preview. A static preview gets none of the Worker's bindings, vars or secrets. Use lowercase letters, digits and single hyphens, starting with a letter. On workers.dev, `-` must fit in 63 characters. Name previews after the pull request, such as `pr-64`. -With `--json`, stdout carries one line: +With `--json`, stdout carries one JSON object on a single line (shown formatted here): ```json { diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index adb30dea7..e1a65bd1c 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -247,7 +247,7 @@ Database recovery is separate from code rollback. Void asks for confirmation whe void project preview delete [--platform cloudflare] ``` -Delete a Cloudflare Preview made with [`void deploy --preview`](./deploy.md#void-deploy-preview), and all its deployments. Production is unchanged. It needs `cloudflare.name` and a pinned account (`cloudflare.account_id` or `CLOUDFLARE_ACCOUNT_ID`), the same ones the preview deploy used. +Delete a Cloudflare Preview made with [`void deploy --preview`](./deploy.md#void-deploy-preview), and all its deployments. Production is unchanged. It needs the Worker name and a pinned account (`cloudflare.name` and `cloudflare.account_id`, the matching keys in `wrangler.jsonc`, or `CLOUDFLARE_ACCOUNT_ID`), the same ones the preview deploy used. - Exit code 0: the preview was deleted, or it did not exist. A cleanup job can run more than once. - Exit code 1: the Worker was not found in the account, or Cloudflare returned another error. From d4a4e24de4ee3d0f88cbe702119c9555f2219184 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:05:02 +0800 Subject: [PATCH 11/12] fix(cli): list project preview like other nested commands Keep the interactive menu entry a hint, as zero-trust and security are, so the shared prompt and argument builder stay unchanged. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/cli-main.ts | 11 +++-------- packages/void/src/cli/project-args.ts | 9 +-------- packages/void/src/cli/subcommand-prompt.ts | 8 +++----- packages/void/test/unit/subcommand-prompt.test.ts | 12 ------------ 4 files changed, 7 insertions(+), 33 deletions(-) diff --git a/packages/void/src/cli/cli-main.ts b/packages/void/src/cli/cli-main.ts index 1e47301e0..4795f2527 100644 --- a/packages/void/src/cli/cli-main.ts +++ b/packages/void/src/cli/cli-main.ts @@ -27,15 +27,10 @@ import { projectSubcommands, parseProjectArgs } from './project-args.ts'; import { secretSubcommands, parseSecretArgs } from './secret-args.ts'; import type { SubcommandDef, SubcommandResult } from './subcommand-prompt.ts'; -function buildArgs( - result: SubcommandResult, - trailingArgs: Array, - subcommands: Array, -): Array { +function buildArgs(result: SubcommandResult, trailingArgs: Array): Array { const out = [result.subcommand]; if (result.arg) { - const hint = subcommands.find(({ name }) => name === result.subcommand)?.arg; - out.push(...(hint?.includes(' ') ? result.arg.split(' ').filter(Boolean) : [result.arg])); + out.push(result.arg); } if (result.extraArgs) { out.push(...result.extraArgs); @@ -86,7 +81,7 @@ async function runSubcommandGroup( if (!result) { process.exit(0); } - const parsed = parse(buildArgs(result, args.slice(1), subcommands)); + const parsed = parse(buildArgs(result, args.slice(1))); await run(root, parsed); } else { const parsed = parse(args.slice(1)); diff --git a/packages/void/src/cli/project-args.ts b/packages/void/src/cli/project-args.ts index d0334d9c1..529b15c73 100644 --- a/packages/void/src/cli/project-args.ts +++ b/packages/void/src/cli/project-args.ts @@ -51,15 +51,8 @@ export const projectSubcommands: Array = [ }, { name: 'preview', - arg: 'delete ', + hint: 'delete ', description: 'Delete a Cloudflare Preview made by deploy --preview', - flags: [ - { - name: '--platform', - arg: 'cloudflare', - description: 'Delete it after a one-off deploy with --platform cloudflare', - }, - ], }, { name: 'cancel', arg: '[deployId]', description: 'Cancel an active deployment' }, { diff --git a/packages/void/src/cli/subcommand-prompt.ts b/packages/void/src/cli/subcommand-prompt.ts index 3a26f8b76..8bb663094 100644 --- a/packages/void/src/cli/subcommand-prompt.ts +++ b/packages/void/src/cli/subcommand-prompt.ts @@ -37,9 +37,7 @@ export type FollowUpDef = export type SubcommandDef = { name: string; description: string; - // e.g. "": a dim hint that enables text input. A "<...>" part makes the input required, and - // a hint of several words, such as "delete ", is passed as that many arguments. - arg?: string; + arg?: string; // e.g. "" — shown as dim hint, enables inline text input hint?: string; // e.g. "login | logout | whoami" — shown dim after name flags?: Array; followUp?: FollowUpDef; @@ -228,7 +226,7 @@ export function promptSubcommand( ...instructions(SELECT_INSTRUCTIONS), ]; if (focused.arg) { - if (focused.arg.includes('<')) { + if (focused.arg.startsWith('<')) { footer.push(`${guidePrefix()}${pc.dim(`Type ${focused.arg}, then press Enter`)}`); } else { footer.push( @@ -435,7 +433,7 @@ export function promptSubcommand( } if (isEnterKey(key)) { - const argRequired = focused.arg?.includes('<'); + const argRequired = focused.arg && focused.arg.startsWith('<'); if (argRequired && input.length === 0) { return; } diff --git a/packages/void/test/unit/subcommand-prompt.test.ts b/packages/void/test/unit/subcommand-prompt.test.ts index 5c924708d..e2145cd2c 100644 --- a/packages/void/test/unit/subcommand-prompt.test.ts +++ b/packages/void/test/unit/subcommand-prompt.test.ts @@ -111,18 +111,6 @@ it('shows the end of long input while submitting the complete value', async () = expect(await prompt.result).toEqual({ subcommand: 'connect', arg: url }); }); -it('requires input for a hint with a placeholder after a word', async () => { - const prompt = openPrompt([ - { name: 'preview', description: 'Delete a preview', arg: 'delete ' }, - ]); - expect(prompt.frame()).toContain('Type delete , then press Enter'); - expect(prompt.frame()).not.toContain('press Enter to skip'); - prompt.key('\r'); - prompt.key('delete pr-64'); - prompt.key('\r'); - expect(await prompt.result).toEqual({ subcommand: 'preview', arg: 'delete pr-64' }); -}); - it('bounds repeat-input history while retaining every submitted entry', async () => { const prompt = openPrompt( [ From cdf883c9f2ae804e7d585c5629a04bb866658e84 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 18:26:56 +0800 Subject: [PATCH 12/12] fix(cli): link the preview deployment URL Co-Authored-By: Claude Opus 5.5 --- packages/void/src/cli/cloudflare-preview.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/void/src/cli/cloudflare-preview.ts b/packages/void/src/cli/cloudflare-preview.ts index 40457dc64..773ee5a5e 100644 --- a/packages/void/src/cli/cloudflare-preview.ts +++ b/packages/void/src/cli/cloudflare-preview.ts @@ -18,7 +18,7 @@ import { log as deployLog } from './deploy-helpers.ts'; import { formatDeploySummary } from './deploy-summary.ts'; import type { RunDeployOptions } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; -import { note, printSuccess } from './output.ts'; +import { formatUrl, note, printSuccess } from './output.ts'; /** Where the user sets a top-level Cloudflare config key, for messages. */ export function cloudflareConfigKey(configPath: string, key: string): string { @@ -118,7 +118,7 @@ export async function runCloudflareStaticPreview(options: { [ formatDeploySummary({ workerName, typeLabel: options.typeLabel }), `Preview: ${previewName}`, - ...(result.deploymentUrl ? [`This deployment: ${result.deploymentUrl}`] : []), + ...(result.deploymentUrl ? [`This deployment: ${formatUrl(result.deploymentUrl)}`] : []), ].join('\n'), result.previewUrl, );