The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as NodePath from "node:path"; |
| 2 | import type * as Context from "effect/Context"; |
| 3 | import * as vite from "vite"; |
| 4 | import type { RuntimeServices } from "../core/index.ts"; |
| 5 | import { parseStaticRouting } from "../internal/workers-shared/shared/configuration/parseStaticRouting.ts"; |
| 6 | import type { StaticRouting } from "../internal/workers-shared/shared/types.ts"; |
| 7 | import type { ExportTypes } from "../rolldown/export-types.ts"; |
| 8 | import { |
| 9 | haveExportTypesChanged, |
| 10 | isExportTypes, |
| 11 | WORKER_EXPORT_TYPES_EVENT, |
| 12 | } from "../rolldown/export-types.ts"; |
| 13 | import { parseViteEnvironments } from "../rolldown/options.ts"; |
| 14 | import type { OptionsApi } from "../rolldown/plugins/index.ts"; |
| 15 | import { workerEntryId } from "../rolldown/plugins/index.ts"; |
| 16 | import { resolvePluginApi } from "../rolldown/utils.ts"; |
| 17 | import { VITE_ASSET_REQUEST } from "./assets/ViteAssets.ts"; |
| 18 | import { DistilledDevEnvironment } from "./dev-environment.ts"; |
| 19 | import type { ServerHandle } from "./dev-server.ts"; |
| 20 | import { configuredExportTypes, mergeExportTypes } from "./export-types.ts"; |
| 21 | import type { CloudflareVitePluginOptions } from "./plugin.ts"; |
| 22 | import { handleWebSocket } from "./websockets.ts"; |
| 23 | import { forwardWorkerRequest, workerRequestUrl } from "./worker-request.ts"; |
| 24 | |
| 25 | let context: Context.Context<RuntimeServices> | undefined; |
| 26 | |
| 27 | export function dev(options: CloudflareVitePluginOptions): Array<vite.Plugin> { |
| 28 | const environmentNames = parseViteEnvironments(options); |
| 29 | const isWorkerEnvironment = (environment: { name: string } | undefined) => |
| 30 | environment === undefined || environmentNames.includes(environment.name); |
| 31 | const configured = configuredExportTypes(options); |
| 32 | // Which exports the running Worker was generated for. Kept across dev server |
| 33 | // restarts so a restart does not undo what was detected. |
| 34 | let exportTypes: ExportTypes = configured; |
| 35 | let handle: ServerHandle | undefined; |
| 36 | let isServerRestarting = false; |
| 37 | let removeUpgradeListener: (() => void) | undefined; |
| 38 | const close = async () => { |
| 39 | removeUpgradeListener?.(); |
| 40 | removeUpgradeListener = undefined; |
| 41 | await handle?.close(); |
| 42 | handle = undefined; |
| 43 | }; |
| 44 | let optionsApi: OptionsApi | undefined; |
| 45 | const plugins: Array<vite.Plugin> = []; |
| 46 | // The proxy middleware registers in a `configureServer` post callback, which |
| 47 | // Vite runs in plugin order — so when this plugin is appended after a |
| 48 | // framework's plugins, the framework's own post middlewares (e.g. a Node |
| 49 | // request bridge that assumes a runnable environment) would see requests |
| 50 | // first. With `middlewareOrder: "pre"` the proxy is instead inserted |
| 51 | // directly after Vite's internal middlewares, ahead of every other plugin's |
| 52 | // post middlewares. This companion plugin records that insertion point: its |
| 53 | // post callback runs before all normal plugins' post callbacks (it is |
| 54 | // `enforce: "pre"`), i.e. right after Vite registered its internal |
| 55 | // middlewares and before any other plugin registered post middlewares. |
| 56 | let middlewareBoundary: number | undefined; |
| 57 | if (options.dev?.middlewareOrder === "pre") { |
| 58 | plugins.push({ |
| 59 | name: "distilled-cloudflare:dev-middleware-boundary", |
| 60 | enforce: "pre", |
| 61 | configureServer(server) { |
| 62 | middlewareBoundary = undefined; |
| 63 | return () => { |
| 64 | middlewareBoundary = server.middlewares.stack.length; |
| 65 | }; |
| 66 | }, |
| 67 | }); |
| 68 | } |
| 69 | const plugin: vite.Plugin = { |
| 70 | name: "distilled-cloudflare:dev", |
| 71 | configResolved({ plugins }) { |
| 72 | optionsApi = resolvePluginApi<OptionsApi>(plugins ?? [], "distilled-cloudflare:options"); |
| 73 | }, |
| 74 | config() { |
| 75 | const environment: vite.EnvironmentOptions = { |
| 76 | dev: { |
| 77 | createEnvironment(name, config) { |
| 78 | // Framework integrations strip `configureServer` off this plugin |
| 79 | // when they create throwaway dev servers (e.g. Astro's type-gen |
| 80 | // during `build`/`sync`) so we don't boot workerd mid-build. In |
| 81 | // that case there is no runtime to proxy to — degrade to Vite's |
| 82 | // default runnable environment. Check this exact plugin instance |
| 83 | // (not the resolved plugin list) so multiple instances and |
| 84 | // renamed/wrapped plugins behave predictably. |
| 85 | if (!hasConfigureServerHook(plugin)) { |
| 86 | return vite.createRunnableDevEnvironment(name, config); |
| 87 | } |
| 88 | // With no Worker entry at all — no `main`, and nothing the app's |
| 89 | // config names for the entry environment — workerd serves assets |
| 90 | // alone and evaluates nothing, so there is no runtime for these |
| 91 | // environments to run modules in. Taking them over anyway would |
| 92 | // only strip the app's own server-side dev tooling of the runnable |
| 93 | // environment it expects (a framework's `vite dev` rendering, say). |
| 94 | if ( |
| 95 | options.main === undefined && |
| 96 | optionsApi !== undefined && |
| 97 | Object.keys(optionsApi.input()).length === 0 |
| 98 | ) { |
| 99 | return vite.createRunnableDevEnvironment(name, config); |
| 100 | } |
| 101 | return new DistilledDevEnvironment(name, config); |
| 102 | }, |
| 103 | }, |
| 104 | }; |
| 105 | return { |
| 106 | environments: Object.fromEntries(environmentNames.map((name) => [name, environment])), |
| 107 | }; |
| 108 | }, |
| 109 | // The Worker environments' builds end when the dev server closes. Vite's |
| 110 | // bundled dev mode (`experimental.bundledDev`) also builds the client |
| 111 | // while serving, which must not take the runtime down with it. |
| 112 | async buildEnd() { |
| 113 | if (!isServerRestarting && isWorkerEnvironment(this.environment)) { |
| 114 | await close(); |
| 115 | } |
| 116 | }, |
| 117 | async closeBundle() { |
| 118 | if (!isServerRestarting && isWorkerEnvironment(this.environment)) { |
| 119 | await close(); |
| 120 | } |
| 121 | }, |
| 122 | async configureServer(server) { |
| 123 | const restartServer = server.restart.bind(server); |
| 124 | server.restart = async () => { |
| 125 | try { |
| 126 | isServerRestarting = true; |
| 127 | await restartServer(); |
| 128 | } finally { |
| 129 | isServerRestarting = false; |
| 130 | } |
| 131 | }; |
| 132 | if (!optionsApi) { |
| 133 | throw new Error("Cannot resolve the cloudflare-runtime:options plugin"); |
| 134 | } |
| 135 | // Frameworks can register multiple names for the same Worker entry. |
| 136 | const inputs = [...new Set(Object.values(optionsApi.input()))]; |
| 137 | if (inputs.length > 1) { |
| 138 | throw new Error( |
| 139 | `Expected exactly one entry in the input, got ${inputs.length} entries: ${JSON.stringify(inputs)}`, |
| 140 | ); |
| 141 | } |
| 142 | const { createDefaultContext, startServer } = await import("./dev-server.ts"); |
| 143 | if (!options.context) { |
| 144 | context ??= await createDefaultContext(); |
| 145 | } |
| 146 | const [input] = inputs; |
| 147 | if (input) { |
| 148 | // An entry that can't be resolved fails the dev server, as under |
| 149 | // `@cloudflare/vite-plugin`, rather than serving errors. |
| 150 | const environment = server.environments[environmentNames[0]!]; |
| 151 | const resolved = |
| 152 | (await environment?.pluginContainer.resolveId(input)) ?? |
| 153 | (await environment?.pluginContainer.resolveId( |
| 154 | NodePath.resolve(server.config.root, input), |
| 155 | )); |
| 156 | if (!resolved) { |
| 157 | throw new Error( |
| 158 | `Failed to resolve Worker entrypoint "${input}" for environment "${environmentNames[0]}"`, |
| 159 | ); |
| 160 | } |
| 161 | } |
| 162 | const entryEnvironment = { |
| 163 | environmentName: environmentNames[0], |
| 164 | // The module runner imports the generated Worker entry rather than the |
| 165 | // user entry: it is the module that re-exports everything the Worker |
| 166 | // needs and that reports its export types over `import.meta.hot`. |
| 167 | entryId: input ? workerEntryId(input) : input, |
| 168 | entryName: input, |
| 169 | }; |
| 170 | const entryEnvironments = () => |
| 171 | environmentNames |
| 172 | .map((name) => server.environments[name]) |
| 173 | .filter((environment) => environment instanceof DistilledDevEnvironment); |
| 174 | |
| 175 | const connect = async (address: ServerHandle["address"]) => { |
| 176 | for (const environment of entryEnvironments()) { |
| 177 | await environment.depsOptimizer?.init(); |
| 178 | await environment.connect(address); |
| 179 | } |
| 180 | }; |
| 181 | // Match Cloudflare's Vite plugin: rebuild the dev server's environments, |
| 182 | // hot channels and module runners after the runtime recovers. Framework |
| 183 | // state may still refer to the crashed process even with the same ports. |
| 184 | const onRuntimeRestart = () => { |
| 185 | server.config.logger.warn( |
| 186 | "The Worker runtime recovered after a crash; restarting the Vite dev server.", |
| 187 | { timestamp: true }, |
| 188 | ); |
| 189 | if (!handle) return; |
| 190 | void server.restart().catch((error: unknown) => { |
| 191 | server.config.logger.error( |
| 192 | `Failed to restart the Vite dev server after Worker recovery: ${String(error)}`, |
| 193 | { |
| 194 | error: error instanceof Error ? error : undefined, |
| 195 | timestamp: true, |
| 196 | }, |
| 197 | ); |
| 198 | }); |
| 199 | }; |
| 200 | handle ??= await startServer( |
| 201 | options, |
| 202 | entryEnvironment, |
| 203 | server, |
| 204 | options.context ?? context!, |
| 205 | exportTypes, |
| 206 | onRuntimeRestart, |
| 207 | ); |
| 208 | await connect(handle.address); |
| 209 | let address = handle.address; |
| 210 | let proxySharedSecret = handle.proxySharedSecret; |
| 211 | |
| 212 | const bindWebSocket = () => { |
| 213 | removeUpgradeListener?.(); |
| 214 | removeUpgradeListener = server.httpServer |
| 215 | ? handleWebSocket(server.httpServer, address, proxySharedSecret) |
| 216 | : undefined; |
| 217 | }; |
| 218 | |
| 219 | /** |
| 220 | * Replaces the Worker runtime so it is regenerated for `exportTypes`. |
| 221 | * workerd needs a named export for every entrypoint, Durable Object, and |
| 222 | * Workflow class, and those exports are baked into the Worker's entry |
| 223 | * module at startup. |
| 224 | */ |
| 225 | const restartRuntime = async () => { |
| 226 | await handle?.close(); |
| 227 | handle = await startServer( |
| 228 | options, |
| 229 | entryEnvironment, |
| 230 | server, |
| 231 | options.context ?? context!, |
| 232 | exportTypes, |
| 233 | onRuntimeRestart, |
| 234 | ); |
| 235 | await connect(handle.address); |
| 236 | address = handle.address; |
| 237 | proxySharedSecret = handle.proxySharedSecret; |
| 238 | bindWebSocket(); |
| 239 | }; |
| 240 | |
| 241 | /** |
| 242 | * Applies export types reported by the Worker. Returns `true` when they |
| 243 | * no longer match what the running Worker was generated for, in which |
| 244 | * case a runtime restart has been queued on `applying`. |
| 245 | */ |
| 246 | let applying: Promise<void> = Promise.resolve(); |
| 247 | const applyExportTypes = (detected: ExportTypes): boolean => { |
| 248 | const next = mergeExportTypes(configured, detected); |
| 249 | if (!haveExportTypesChanged(exportTypes, next)) { |
| 250 | return false; |
| 251 | } |
| 252 | exportTypes = next; |
| 253 | applying = applying |
| 254 | .catch(() => {}) |
| 255 | .then(restartRuntime) |
| 256 | .catch((error: unknown) => { |
| 257 | server.config.logger.error(`Failed to reload the Worker runtime: ${String(error)}`, { |
| 258 | error: error instanceof Error ? error : undefined, |
| 259 | timestamp: true, |
| 260 | }); |
| 261 | }); |
| 262 | return true; |
| 263 | }; |
| 264 | |
| 265 | if (input) { |
| 266 | // Vite's internal CSS plugins rely on `buildStart` having run for the |
| 267 | // client environment before a server environment transforms a module. |
| 268 | // Vite does that while initializing the dev server, which is after |
| 269 | // this hook, and evaluating the entry now would fail without it. |
| 270 | await server.environments.client.pluginContainer.buildStart(); |
| 271 | // Detect up front so that the first request already reaches a Worker |
| 272 | // exposing every entrypoint the entry module defines. |
| 273 | const detected = await entryEnvironments()[0]?.requestExportTypes(); |
| 274 | if (detected && applyExportTypes(detected)) { |
| 275 | await applying; |
| 276 | } |
| 277 | // From here on the entry reports its exports over HMR every time it is |
| 278 | // re-evaluated, which is how entrypoints added later get picked up. |
| 279 | for (const environment of entryEnvironments()) { |
| 280 | environment.hot.on(WORKER_EXPORT_TYPES_EVENT, (data: unknown) => { |
| 281 | if (!isExportTypes(data) || !applyExportTypes(data)) { |
| 282 | return; |
| 283 | } |
| 284 | server.config.logger.info("Worker exports changed, reloading the Worker runtime.", { |
| 285 | timestamp: true, |
| 286 | }); |
| 287 | }); |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // An assets-only site (no input) still routes through the runtime, whose |
| 292 | // router applies the asset rules; only a Worker takes WebSockets. |
| 293 | if (input) bindWebSocket(); |
| 294 | |
| 295 | // `runWorkerFirst` routes matching requests to the Worker ahead of Vite's |
| 296 | // own middleware (which would otherwise serve a file at that path), as |
| 297 | // `@cloudflare/vite-plugin`'s pre-middleware does. The Worker's router |
| 298 | // applies the same rules once the request arrives. |
| 299 | const staticRouting = input |
| 300 | ? resolveStaticRouting(options.worker?.assets?.runWorkerFirst) |
| 301 | : undefined; |
| 302 | if (staticRouting) { |
| 303 | server.middlewares.use(function distilledCloudflareRunWorkerFirst(req, res, next) { |
| 304 | if (VITE_ASSET_REQUEST in req) return next(); |
| 305 | const { pathname } = workerRequestUrl(req.url, "http://localhost"); |
| 306 | if ( |
| 307 | matchesStaticRoutingRule(staticRouting.asset_worker ?? [], pathname) || |
| 308 | !matchesStaticRoutingRule(staticRouting.user_worker, pathname) |
| 309 | ) { |
| 310 | return next(); |
| 311 | } |
| 312 | const url = workerRequestUrl(req.originalUrl ?? req.url, address); |
| 313 | forwardWorkerRequest(req, res, url, proxySharedSecret, server.config.logger, next); |
| 314 | }); |
| 315 | } |
| 316 | |
| 317 | return () => { |
| 318 | server.middlewares.use(function distilledCloudflareProxyMiddleware(req, res, next) { |
| 319 | // The Worker's own `ASSETS` calls run through Vite's middleware; |
| 320 | // one Vite didn't serve must not come back to the Worker. |
| 321 | if (VITE_ASSET_REQUEST in req) return next(); |
| 322 | const url = workerRequestUrl(req.originalUrl ?? req.url, address); |
| 323 | forwardWorkerRequest(req, res, url, proxySharedSecret, server.config.logger, next); |
| 324 | }); |
| 325 | if (options.dev?.middlewareOrder === "pre" && middlewareBoundary !== undefined) { |
| 326 | // Move the proxy middleware from the end of the stack to directly |
| 327 | // after Vite's internal middlewares, ahead of the post middlewares |
| 328 | // other plugins registered. |
| 329 | const stack = server.middlewares.stack; |
| 330 | const entry = stack.pop(); |
| 331 | if (entry) { |
| 332 | stack.splice(middlewareBoundary, 0, entry); |
| 333 | } |
| 334 | } |
| 335 | }; |
| 336 | }, |
| 337 | }; |
| 338 | plugins.push(plugin); |
| 339 | return plugins; |
| 340 | } |
| 341 | |
| 342 | const resolveStaticRouting = ( |
| 343 | runWorkerFirst: boolean | ReadonlyArray<string> | undefined, |
| 344 | ): StaticRouting | undefined => |
| 345 | runWorkerFirst === true |
| 346 | ? { user_worker: ["/*"] } |
| 347 | : Array.isArray(runWorkerFirst) && runWorkerFirst.length > 0 |
| 348 | ? parseStaticRouting([...runWorkerFirst]) |
| 349 | : undefined; |
| 350 | |
| 351 | /** The glob-only rule matching of the asset worker's static routing. */ |
| 352 | const matchesStaticRoutingRule = (rules: ReadonlyArray<string>, pathname: string) => |
| 353 | rules.some((rule) => |
| 354 | new RegExp(`^${rule.split("*").map(escapeRegex).join(".*")}$`).test(pathname), |
| 355 | ); |
| 356 | |
| 357 | const escapeRegex = (value: string) => value.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); |
| 358 | |
| 359 | const hasConfigureServerHook = (plugin: vite.Plugin): boolean => { |
| 360 | const hook = plugin.configureServer; |
| 361 | if (hook == null) return false; |
| 362 | return typeof hook === "function" || typeof hook.handler === "function"; |
| 363 | }; |