diff --git a/.changeset/remove-cf-vite.md b/.changeset/remove-cf-vite.md new file mode 100644 index 0000000000..c1bfd052b4 --- /dev/null +++ b/.changeset/remove-cf-vite.md @@ -0,0 +1,9 @@ +--- +"@cloudflare/vite-plugin": minor +--- + +Remove the experimental internal `cf-vite` executable + +Run development and builds through Vite's CLI or your framework's own commands instead. Configure `cloudflare({ remoteBindings: false })` to disable remote bindings. + +When using the plugin through `cf`, upgrade to `cf@1.0.0-rc.0` or newer. This is the first cf release that runs the project's native Vite or Vite+ commands instead of the removed executable. diff --git a/packages/vite-plugin-cloudflare/AGENTS.md b/packages/vite-plugin-cloudflare/AGENTS.md index 9178e34493..193c6fbc71 100644 --- a/packages/vite-plugin-cloudflare/AGENTS.md +++ b/packages/vite-plugin-cloudflare/AGENTS.md @@ -7,8 +7,6 @@ Vite plugin for Cloudflare Workers development. Exports `cloudflare()` plugin fa ## STRUCTURE - `src/index.ts` — Plugin factory -- `src/cf-vite.ts` — `cf-vite` delegate binary entry (see below) -- `bin/cf-vite` — shebang shim that dynamic-imports `dist/cf-vite.mjs` - `src/workers/` — 4 internal worker entries: `asset-worker`, `router-worker`, `runner-worker`, `vite-proxy-worker` - `playground/` — ~47 playground apps, each a workspace member (nested workspace under this package) - `e2e/` — E2E tests with Playwright @@ -18,64 +16,17 @@ Vite plugin for Cloudflare Workers development. Exports `cloudflare()` plugin fa - Only package using `tsdown` as build tool - Outputs ESM (`.mjs`) to `dist/index.mjs` -- `src/cf-vite.ts` is a second top-level tsdown entry, bundled to `dist/cf-vite.mjs` (no dts) - Also bundles 4 internal worker scripts from `src/workers/*/index.ts` as separate neutral-platform outputs to `dist/workers/` - Release builds set `SOURCEMAPS=false` to omit the plugin's JavaScript and declaration maps. Normal builds retain maps for debugging; the setting does not change source maps for applications built with the plugin. -## cf-vite DELEGATE BINARY (experimental / internal) +## CLOUDFLARE TOOLING -`bin/cf-vite` is an experimental, internal delegate binary spawned by -Cloudflare's "cf-dev" parent process — NOT part of the plugin's public -API and not meant for direct end-user invocation. It is the sibling of -`wrangler`'s `cf-wrangler` binary, and the two MUST keep a shared spawn -contract so the parent can drive either impl interchangeably. - -- **Verb dispatch.** `cf-vite [flags]`. `dev` and `build` are the - verbs today; future verbs (`deploy`) follow the same shape. - Unknown/missing verbs exit `2` (this doubles as the parent's - version-detection signal — no JSON handshake). -- **Shared flag vocabulary (`dev`).** For `dev`, only `--mode`, `--port`, - `--host`, `--local` are accepted, mirroring `cf-wrangler` exactly. - Parsed with `node:util.parseArgs` strict mode → unknown flags exit `2`. - Do NOT add flags here unless `cf-wrangler` grows them too. (There is no - `--config` flag: the wrangler config is discovered by `cloudflare()` - itself.) -- **`build`** `cf-vite build` runs Vite's full multi-environment - app build via `createBuilder().buildApp()` (NOT the legacy - single-environment `build()` helper, which would skip the plugin's - worker/build-output orchestration — mirrors Vite's own `vite build` - CLI). It accepts only `--mode` (`--port`/`--host`/`--local` don't apply to - a build and exit `2`). Preview build context is supplied through - `CLOUDFLARE_PREVIEW_BUILD`, which also works when a framework runs Vite as - part of its own build command. -- **Build Output Specification is the core build pipeline.** Every build emits - Build Output; there is no feature flag or legacy output-config path. Preview - reads Workers and Containers exclusively from that output. The v2 plugin - always installs its build-output plugin, so `cf-vite` does not need the - internal force-build-output flag used by v1. -- **Caller identity.** The plugin is only compatible with `cf`, so actionable - messages always name `cf` (`CLI_DISPLAY_NAME` in `src/constants.ts`), whether - or not Vite was started by `cf-vite`. Do not fall back to Wrangler. -- **`dev`** `cf-vite dev` boots Vite via `createServer()` - against the user's own `vite.config.ts` (which must include - `cloudflare()`). Plugin-owned flags are bridged via env vars the plugin - already reads (`--local` → `CLOUDFLARE_VITE_FORCE_LOCAL`); Vite-owned - flags go through inline config (`--port`/`--host` → `server.*`, - `--mode` → `mode`). -- **Authentication.** Profiles resolve through `@cloudflare/workers-auth`, including - `CLOUDFLARE_AUTH_PROFILE` inherited from the parent. Remote-binding credentials - are keyed by the resolved profile as well as project directory and account, - so a profile change on restart replaces the session's authentication. -- **`--local`** forces remote bindings off. There is no plugin env knob - for `remoteBindings` other than `CLOUDFLARE_VITE_FORCE_LOCAL`, which - `resolvePluginConfig` in `plugin-config.ts` honours by overriding the - `remoteBindings` config option. Keep that override in sync if the flag - semantics change. -- **Hotkeys differ by design.** `cf-vite` uses Vite's own - `bindCLIShortcuts` (`h`/`r`/`q`/…), not wrangler's hotkey set. The - parent process should not assume identical hotkey UX across delegates. -- **Exit codes.** `0` graceful, `2` unknown verb / argv parse error, - `130` SIGINT, `143` SIGTERM. +- Run development and builds through Vite's CLI or the framework's own commands. +- Every build emits Build Output; Preview reads Workers and Containers from that output. +- Preview build context is supplied through `CLOUDFLARE_PREVIEW_BUILD`, including when a framework runs Vite as part of its build command. +- Configure `cloudflare({ remoteBindings: false })` to disable remote bindings. +- Actionable messages name `cf` through `CLI_DISPLAY_NAME` in `src/constants.ts`. +- Authentication profiles resolve through `@cloudflare/workers-auth`, including `CLOUDFLARE_AUTH_PROFILE` inherited from the parent. Remote-binding credentials are keyed by the resolved profile as well as project directory and account, so a profile change on restart replaces the session's authentication. ## CONVENTIONS diff --git a/packages/vite-plugin-cloudflare/bin/cf-vite b/packages/vite-plugin-cloudflare/bin/cf-vite deleted file mode 100755 index 76b7d62164..0000000000 --- a/packages/vite-plugin-cloudflare/bin/cf-vite +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -import("../dist/cf-vite.mjs"); diff --git a/packages/vite-plugin-cloudflare/package.json b/packages/vite-plugin-cloudflare/package.json index c680556e73..994c7de458 100644 --- a/packages/vite-plugin-cloudflare/package.json +++ b/packages/vite-plugin-cloudflare/package.json @@ -19,11 +19,7 @@ "url": "https://github.com/cloudflare/workers-sdk.git", "directory": "packages/vite-plugin-cloudflare" }, - "bin": { - "cf-vite": "./bin/cf-vite" - }, "files": [ - "bin", "dist" ], "type": "module", diff --git a/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts index 76feadcac8..58c07e1556 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/package-sourcemaps.spec.ts @@ -11,12 +11,10 @@ it("respects the package source-map setting for all built entry points", ({ const files = fs.readdirSync(distPath, { recursive: true, encoding: "utf8" }); expect(files).toContain("index.mjs"); expect(files).toContain("index.d.mts"); - expect(files).toContain("cf-vite.mjs"); if (process.env.SOURCEMAPS !== "false") { expect(files).toContain("index.mjs.map"); expect(files).toContain("index.d.mts.map"); - expect(files).toContain("cf-vite.mjs.map"); return; } diff --git a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts index 50f7c15b1f..92f1802f93 100644 --- a/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts +++ b/packages/vite-plugin-cloudflare/src/__tests__/resolve-plugin-config.spec.ts @@ -814,23 +814,23 @@ describe("resolvePluginConfig", () => { fs.mkdirSync(envDir); fs.writeFileSync( path.join(envDir, ".env.production"), - "CLOUDFLARE_VITE_FORCE_LOCAL=true\nCLOUDFLARE_ACCOUNT_ID=test-account-id" + "CLOUDFLARE_ACCOUNT_ID=test-account-id" ); fs.writeFileSync( path.join(envDir, ".dev.vars.production"), "CLOUDFLARE_ACCOUNT_ID=from-dev-vars" ); - vi.stubEnv("CLOUDFLARE_VITE_FORCE_LOCAL", undefined); vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined); const result = await resolvePluginConfig( - { remoteBindings: true }, + {}, { root, envDir: "environment" }, buildEnv ); - expect(result.remoteBindings).toBe(false); - expect(result.localEnv.values.CLOUDFLARE_VITE_FORCE_LOCAL).toBe("true"); + expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBe( + "test-account-id" + ); expect(result.devVars?.CLOUDFLARE_ACCOUNT_ID).toBe("from-dev-vars"); expect(process.env.CLOUDFLARE_ACCOUNT_ID).toBe("test-account-id"); }); @@ -839,17 +839,18 @@ describe("resolvePluginConfig", () => { writeEntryConfig(); fs.writeFileSync( path.join(root, ".env.production"), - "CLOUDFLARE_VITE_FORCE_LOCAL=true" + "CLOUDFLARE_ACCOUNT_ID=test-account-id" ); - vi.stubEnv("CLOUDFLARE_VITE_FORCE_LOCAL", undefined); + + vi.stubEnv("CLOUDFLARE_ACCOUNT_ID", undefined); const result = await resolvePluginConfig( - { remoteBindings: true }, + {}, { root, envDir: false }, buildEnv ); - expect(result.remoteBindings).toBe(true); + expect(result.localEnv.values.CLOUDFLARE_ACCOUNT_ID).toBeUndefined(); }); test("rejects duplicate Vite environment names", async ({ expect }) => { diff --git a/packages/vite-plugin-cloudflare/src/cf-vite.ts b/packages/vite-plugin-cloudflare/src/cf-vite.ts deleted file mode 100644 index 1c64c961fd..0000000000 --- a/packages/vite-plugin-cloudflare/src/cf-vite.ts +++ /dev/null @@ -1,239 +0,0 @@ -/** - * `cf-vite` delegate binary entry point for `@cloudflare/vite-plugin`. - * - * EXPERIMENTAL / internal: spawned by Cloudflare's "cf-dev" parent - * process, not invoked directly by end users. Contract may change. - * - * Usage: `/bin/cf-vite [flags...]`. `dev` and `build` - * are the verbs today; future verbs follow the same shape. - * Unknown/missing verbs exit 2 (also the parent's version-detection - * signal). - * - * Spawn contract for `dev`: parent uses `stdio: "inherit"` and forwards - * SIGINT/SIGTERM. Accepted flags mirror the sibling `cf-wrangler` - * delegate (`--mode`, `--port`, `--host`, `--local`) so the parent can - * drive either impl interchangeably; everything else lives in the user's - * `vite.config.ts` / `cloudflare.config.ts`. `cf-vite` boots - * Vite via `createServer()` against the user's own config (expected to - * include `cloudflare()`); flags are bridged to it as documented inline. - * - * `build` runs Vite's full multi-environment app build via - * `createBuilder().buildApp()` (NOT the legacy single-environment - * `build()` helper, which would skip the plugin's worker builds). It - * accepts only `--mode`. Preview build context is supplied through the - * `CLOUDFLARE_PREVIEW_BUILD` environment variable so framework-owned build - * commands can use the same contract. - * - * Exit codes: 0 graceful, 2 unknown verb / parse error, 130 SIGINT, - * 143 SIGTERM. - */ - -import { parseArgs as nodeParseArgs } from "node:util"; -import { createBuilder, createServer } from "vite"; -import type { InlineConfig, ServerOptions } from "vite"; - -interface DevArgs { - mode?: string; - port?: number; - host?: string; - local?: boolean; -} - -class ArgParseError extends Error { - constructor(message: string) { - super(message); - this.name = "ArgParseError"; - } -} - -/** Strict argv parser; mirrors `cf-wrangler`'s flags (unknown → throw). */ -function parseDevArgs(argv: string[]): DevArgs { - let parsed; - try { - parsed = nodeParseArgs({ - args: argv, - options: { - mode: { type: "string" }, - host: { type: "string" }, - // `node:util.parseArgs` has no `number` type; coerce below. - port: { type: "string" }, - local: { type: "boolean" }, - }, - strict: true, - allowPositionals: false, - }); - } catch (err) { - throw new ArgParseError(err instanceof Error ? err.message : String(err)); - } - - const out: DevArgs = {}; - if (parsed.values.mode !== undefined) { - out.mode = parsed.values.mode; - } - if (parsed.values.host !== undefined) { - out.host = parsed.values.host; - } - if (parsed.values.port !== undefined) { - const raw = parsed.values.port; - const n = Number(raw); - // TCP port range; 0 = OS-assigned. - if (!Number.isInteger(n) || n < 0 || n > 65535) { - throw new ArgParseError( - `--port expects an integer between 0 and 65535, got "${raw}"` - ); - } - out.port = n; - } - if (parsed.values.local !== undefined) { - out.local = parsed.values.local; - } - - return out; -} - -interface BuildArgs { - mode?: string; -} - -function parseBuildArgs(argv: string[]): BuildArgs { - let parsed; - try { - parsed = nodeParseArgs({ - args: argv, - options: { - mode: { type: "string" }, - }, - strict: true, - allowPositionals: false, - }); - } catch (err) { - throw new ArgParseError(err instanceof Error ? err.message : String(err)); - } - - const out: BuildArgs = {}; - if (parsed.values.mode !== undefined) { - out.mode = parsed.values.mode; - } - - return out; -} - -async function main(): Promise { - // argv: [0] node [1] cf-vite.mjs [2] verb [3+] forwarded flags. - const verb = process.argv[2]; - const userArgv = process.argv.slice(3); - - if (verb === "dev") { - return runDev(userArgv); - } - - if (verb === "build") { - return runBuild(userArgv); - } - - // Format mirrors `cf-wrangler`. - process.stderr.write( - `Error: unknown subcommand "${verb ?? ""}".\n` + - `Usage: cf-vite [args]\n` - ); - return 2; -} - -async function runDev(userArgv: string[]): Promise { - let args: DevArgs; - try { - args = parseDevArgs(userArgv); - } catch (err) { - if (err instanceof ArgParseError) { - process.stderr.write(`Error: ${err.message}\n`); - return 2; - } - throw err; - } - - // Bridge plugin-owned flags via env vars the plugin reads during config - // resolution — must be set before `createServer()`. - // - `--local`: overrides `remoteBindings` outright, mirroring - // `wrangler dev --local` (force local even if config opts into - // remote). - if (args.local) { - process.env.CLOUDFLARE_VITE_FORCE_LOCAL = "true"; - } - - // Bridge Vite-owned flags via inline config; the rest auto-loads from - // the user's `vite.config.{ts,js,mjs}` (which supplies `cloudflare()`). - const serverOptions: ServerOptions = {}; - if (args.port !== undefined) { - serverOptions.port = args.port; - } - if (args.host !== undefined) { - serverOptions.host = args.host; - } - const inlineConfig: InlineConfig = { server: serverOptions }; - if (args.mode !== undefined) { - inlineConfig.mode = args.mode; - } - - const server = await createServer(inlineConfig); - - await server.listen(); - server.printUrls(); - server.bindCLIShortcuts({ print: true }); - - // Close cleanly on signal so the dev registry entry, workerd - // subprocess, and ports release. `closing` guards against a - // double-signal (e.g. rapid Ctrl+C, or SIGINT then SIGTERM) racing - // two `server.close()` / `process.exit()` calls. - let closing = false; - const shutdown = (signal: NodeJS.Signals) => { - if (closing) { - return; - } - closing = true; - // Signal handlers can't be async; void the IIFE to avoid unhandled - // rejections if `close()` throws. - void (async () => { - try { - await server.close(); - process.exit(0); - } catch { - // Forced-exit: terminate with the 128+N code rather than - // hang. SIGINT=130, SIGTERM=143. - process.exit(signal === "SIGINT" ? 130 : 143); - } - })(); - }; - process.on("SIGINT", () => shutdown("SIGINT")); - process.on("SIGTERM", () => shutdown("SIGTERM")); - - // Keep the event loop alive until a signal handler exits; Vite's own - // handles (HTTP listener, watchers, workerd) hold the process open. - return new Promise(() => {}); -} - -async function runBuild(userArgv: string[]): Promise { - let args: BuildArgs; - try { - args = parseBuildArgs(userArgv); - } catch (err) { - if (err instanceof ArgParseError) { - process.stderr.write(`Error: ${err.message}\n`); - return 2; - } - throw err; - } - - const inlineConfig: InlineConfig = {}; - if (args.mode !== undefined) { - inlineConfig.mode = args.mode; - } - const builder = await createBuilder(inlineConfig); - await builder.buildApp(); - - return 0; -} - -// Let unhandled rejections propagate — Node prints the stack and exits -// non-zero, which the parent surfaces via inherited stdio. -const exitCode = await main(); -process.exit(exitCode); diff --git a/packages/vite-plugin-cloudflare/src/plugin-config.ts b/packages/vite-plugin-cloudflare/src/plugin-config.ts index 94a1a7147c..e4e1d799e1 100644 --- a/packages/vite-plugin-cloudflare/src/plugin-config.ts +++ b/packages/vite-plugin-cloudflare/src/plugin-config.ts @@ -324,13 +324,7 @@ export async function resolvePluginConfig( devVars, }; - // The `cf-vite` delegate binary's `--local` flag sets this env var to - // force remote bindings off, overriding any `remoteBindings` value in the - // plugin config (mirrors `wrangler dev --local`). - const remoteBindings = - localEnv.values.CLOUDFLARE_VITE_FORCE_LOCAL === "true" - ? false - : (pluginConfig.remoteBindings ?? true); + const remoteBindings = pluginConfig.remoteBindings ?? true; if (preview !== undefined) { const { accountId, complianceRegion } = preview.rootConfig.settings ?? {}; diff --git a/packages/vite-plugin-cloudflare/tsdown.config.ts b/packages/vite-plugin-cloudflare/tsdown.config.ts index 9c65b80f1f..848a1928a1 100644 --- a/packages/vite-plugin-cloudflare/tsdown.config.ts +++ b/packages/vite-plugin-cloudflare/tsdown.config.ts @@ -26,21 +26,6 @@ export default defineConfig([ }, ignoreWatch, }, - { - // `cf-vite` delegate-binary entry. Bundled separately from the - // plugin itself so the bin shim (`bin/cf-vite`) can - // dynamic-import it without dragging the plugin's type-export - // overhead. The entry exposes a small subcommand-based CLI - // (currently just `dev`) that any parent process can spawn - // (see `src/cf-vite.ts` for the protocol). - entry: "src/cf-vite.ts", - platform: "node", - sourcemap, - outDir: "dist", - tsconfig: "tsconfig.plugin.json", - dts: false, - ignoreWatch, - }, worker("asset-worker"), worker("router-worker"), worker("runner-worker", {