#!/usr/bin/env node // Generates dev-only wrangler.dev.jsonc files for dynamic service bindings, // then launches `wrangler dev` with all discovered workers and the PDF renderer. // // Flags: // --use-workers-ai-binding Include the Workers AI binding in workshop-backend and in the // gatekeepers that declare one (requires Cloudflare login). // --port PORT Listen on PORT instead of 8787. Overrides VITE_BACKEND_HOST. // // Env: // VITE_BACKEND_HOST=localhost:9000 Also pass --port 9000 to wrangler dev. import { existsSync, readFileSync, writeFileSync, readdirSync, statSync, } from "node:fs"; import { spawn, type ChildProcess } from "node:child_process"; import { connect } from "node:net"; import { constants } from "node:os"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { parse } from "jsonc-parser"; import { resolveBinEntry } from "./bin-entry.ts"; import { getDevServerConfig } from "./dev-server-config.ts"; import { generateWorkerConfigs } from "./generate-worker-configs.ts"; import { killProcessTree } from "./kill-process-tree.ts"; import { pnpmCommand } from "./pnpm-command.ts"; import type { ServiceBinding, WranglerBuild } from "./release/manifest-lib.ts"; import { vpRunEnv } from "./vp/concurrency.ts"; const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url)); const ROOT = join(SCRIPTS_DIR, ".."); const PACKAGES_DIR = join(ROOT, "packages"); const WORKSHOP_BACKEND_DIR = join(PACKAGES_DIR, "workshop-backend"); // The Worker that draws PDF pages for the Google gatekeeper, which binds to it by name. It is not a // gatekeeper, so nothing below discovers it, routes to it or gives it credentials. const PDF_RENDERER_DIR = join(PACKAGES_DIR, "pdf-renderer"); /** A gatekeeper package as {@link findGatekeepers} discovers it. */ interface Gatekeeper { /** Package directory name, which is also the worker name. */ name: string; /** Absolute path to the package directory. */ dir: string; } // Load a root `.dev.vars` file (KEY=VALUE lines) into process.env for local development. Existing // shell environment values take precedence. This file is gitignored and may hold local secrets. function loadDevVars(): void { const path = join(ROOT, ".dev.vars"); if (!existsSync(path)) return; for (const rawLine of readFileSync(path, "utf8").split("\n")) { const line = rawLine.trim(); if (!line || line.startsWith("#")) continue; const eq = line.indexOf("="); if (eq === -1) continue; const key = line.slice(0, eq).trim(); let value = line.slice(eq + 1).trim(); // Strip surrounding single or double quotes. if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { value = value.slice(1, -1); } if (process.env[key] === undefined) process.env[key] = value; } } loadDevVars(); const useWorkersAi = process.argv.includes("--use-workers-ai-binding"); // In `run-local` mode the backend serves the pre-built frontend bundle as static assets (there is no // Vite dev server). In normal dev mode we leave assets unconfigured so the frontend is served by // Vite on :3000 and no `vite build` is required to start the dev server. const serveFrontendAssets = process.argv.includes("--serve-frontend-assets"); let backendHost: string; let wranglerPort: string | null; try { ({ backendHost, wranglerPort } = getDevServerConfig( process.argv.slice(2), process.env.VITE_BACKEND_HOST)); } catch (err) { console.error((err as Error).message); process.exit(1); } // The deploy service binds CLOUDFLARE_OS_DEPLOYMENT as JSON, and the backend treats the string form // as absent, so a value from the shell or `.dev.vars` is parsed here, before the builds so bad JSON // fails fast, and written into the backend's config as an object. An empty value counts as unset. let cloudflareOsDeployment: unknown; if (process.env.CLOUDFLARE_OS_DEPLOYMENT) { try { cloudflareOsDeployment = JSON.parse(process.env.CLOUDFLARE_OS_DEPLOYMENT); } catch { console.error("CLOUDFLARE_OS_DEPLOYMENT is not valid JSON; set it as one JSON line."); process.exit(1); } } // --------------------------------------------------------------------------- // Discover gatekeeper packages. // --------------------------------------------------------------------------- function findGatekeepers(parentDir: string): Gatekeeper[] { try { return readdirSync(parentDir) .filter(name => name.startsWith("gatekeeper-")) .filter(name => { try { return statSync(join(parentDir, name, "wrangler.jsonc")).isFile(); } catch { return false; } }) .map(name => ({ name, dir: join(parentDir, name) })); } catch { return []; } } // The committed wrangler.jsonc files are generated from cloudflare.config.ts; regenerate them so a // TypeScript edit reaches `pnpm dev-server` without a separate step. await generateWorkerConfigs({ check: false }); const gatekeepers = findGatekeepers(PACKAGES_DIR); // The Context Library (packages/gatekeeper-context) is discovered by findGatekeepers and bound // like any other gatekeeper (GATEKEEPER_CONTEXT -> GatekeeperVendor). Its describe() reports // autoProvisionsAccount, so core auto-provisions one Context account per user. The only extra // wiring it needs is a sharingDomain in its binding props (see below). const CONTEXT_GATEKEEPER_NAME = "gatekeeper-context"; // What Wrangler picks for itself when no --port is derived, so also what we poll. const DEFAULT_WRANGLER_PORT = 8787; // Watchers rebuild each gatekeeper's generated UI (src/generated/*) on source change; wrangler dev's // `watch_dir: src` then re-bundles the worker. Deferred ones start once Wrangler is listening. const devWatchers: ChildProcess[] = []; const deferredWatchers: (() => void)[] = []; let stoppingDevWatchers = false; let wranglerChild: ChildProcess | null = null; // Resolve once something accepts a TCP connection on `port`, or once `timeoutMs` has elapsed. function waitForPort(port: number, timeoutMs: number): Promise { return new Promise(resolve => { const deadline = Date.now() + timeoutMs; const attempt = () => { const socket = connect({ port, host: "127.0.0.1" }); socket.once("connect", () => { socket.destroy(); resolve(); }); socket.once("error", () => { socket.destroy(); if (Date.now() >= deadline) resolve(); else setTimeout(attempt, 100).unref(); }); }; attempt(); }); } // Spawn a persistent watcher. function spawnDevWatcher(label: string, command: string, args: string[]): void { const watcher = spawn(command, args, { stdio: "inherit", cwd: ROOT }); watcher.on("exit", (code, signal) => { if (stoppingDevWatchers) return; console.error(`${label} exited unexpectedly (code=${code}, signal=${signal}).`); }); devWatchers.push(watcher); } // No-op once shutdown has begun: reaching the port deadline just as the user hits Ctrl-C must not // spawn a watcher that nothing is left to kill. function startDeferredWatchers(): void { if (stoppingDevWatchers) return; for (const start of deferredWatchers.splice(0)) start(); } function stopDevWatchers(): void { stoppingDevWatchers = true; deferredWatchers.length = 0; for (const watcher of devWatchers) watcher.kill(); } process.on("exit", stopDevWatchers); // Reaches each app watcher's `pnpm exec vite build --watch` grandchild, which a bare kill() on the // `node build-app.ts --watch` wrapper leaves holding CPU and file watches after we are gone. Must // not call stopDevWatchers() first: killing a wrapper reparents its children away from it, and the // tree walk can no longer find them. async function stopDevWatchersDeep(): Promise { stoppingDevWatchers = true; deferredWatchers.length = 0; await Promise.all(devWatchers .filter(watcher => watcher.exitCode === null && watcher.signalCode === null) .map(watcher => watcher.pid ? killProcessTree(watcher.pid).catch(() => {}) : null)); } // The single in-flight teardown of each kind. Both shutdown paths join these promises rather than // starting their own walk: the escalation below runs *while* the first signal's walk is still // going, and two concurrent walks over the same pids would have the second find the tree already // reparented. `stopPreflightBuilds` is declared further down but hoisted; these two bindings are // deliberately up here, above the signal handlers that reach them, so that a signal arriving during // module evaluation cannot find them still in TDZ. let devWatchersStopped: Promise | null = null; let preflightBuildsStopped: Promise | null = null; function stopDevWatchersDeepOnce(): Promise { return (devWatchersStopped ??= stopDevWatchersDeep()); } // The pre-flight builds have no equivalent of the watchers' `exit` handler, so abandoning this walk // leaks the whole `vp`/`vite` subtree under each one with nothing left to catch it -- and a signal // during the pre-flight phase is exactly when they are still running. function stopPreflightBuildsOnce(): Promise { return (preflightBuildsStopped ??= stopPreflightBuilds()); } // Shutdown is driven by Wrangler's exit. Ctrl-C reaches the whole process group, so Wrangler is // already tearing down its workerd children and exiting first would orphan them. These handlers // disable Node's default exit-on-signal, so a wedged Wrangler would otherwise make Ctrl-C // ineffective and leave this process waiting forever -- a second signal or the grace deadline // escalates to SIGKILLing Wrangler's whole tree. // // The signal count is only an impatience shortcut on top of that grace deadline, and it is // deliberately left as a plain count rather than trying to tell a repeat interrupt from a fresh // one: nothing here can make that distinction (POSIX exposes no `siginfo.si_code` to Node), and // once the escalation reaps the watchers rather than abandoning them, it does not need to -- // escalating early is then merely early, not lossy. See forceKillWrangler. const FORCE_KILL_GRACE_MS = 10_000; let receivedShutdownSignals = 0; let forcingShutdown = false; let shutdownExitCode: number | null = null; async function forceKillWrangler(exitCode: number): Promise { if (forcingShutdown) return; forcingShutdown = true; // Both walks are joined, not skipped, and before the exit below. This is the force-kill path, so // the temptation is to exit the moment Wrangler is dead -- but `process.exit()` here abandons // whatever they still had to do, and all that runs afterwards is the `exit` handler's *shallow* // stopDevWatchers(): the bare kill() whose surviving grandchild is the reason the deep walk // exists at all (the pre-flight builds have no backstop even that weak). Two ordinary ways in, // so the walks have to finish on this path too: a second Ctrl-C landing inside the first one's // walk, and -- under a supervisor that forwards to the whole tree (relay-termination.ts) -- one // interrupt arriving twice, since the tty's group broadcast and the relay's forward are // indistinguishable from in here. // // Measured, with the walk widened to what a loaded machine costs: two interrupts 60ms apart left // two orphaned `vite build --watch` processes and their esbuild children behind without this // join, and nothing with it. Unwidened it happens to come out clean either way, because the // SIGKILL walk below is itself slow enough for the abandoned walk to finish underneath it -- // which is a coincidence of two tree walks racing, not a guarantee. await stopDevWatchersDeepOnce(); await stopPreflightBuildsOnce(); if (wranglerChild?.exitCode === null && wranglerChild.signalCode === null && wranglerChild.pid) { await killProcessTree(wranglerChild.pid, "SIGKILL").catch(() => {}); } process.exit(exitCode); } async function onShutdownSignal(signal: NodeJS.Signals, exitCode: number): Promise { receivedShutdownSignals++; shutdownExitCode ??= exitCode; if (receivedShutdownSignals > 1) return forceKillWrangler(exitCode); // Awaited before Wrangler is signalled: this process stays alive waiting for Wrangler's exit, so // there is time for the process tree walks. Ctrl-C is group-delivered, but a targeted signal // (kill , IDE stop buttons) reaches only this process, so the pre-flight builds have to be // torn down here too and a live Wrangler has to be signalled explicitly -- on the Ctrl-C path // the forwarded signal lands during Wrangler's own teardown, which tolerates the repeat. await stopDevWatchersDeepOnce(); await stopPreflightBuildsOnce(); if (wranglerChild?.exitCode === null) { wranglerChild.kill(signal); setTimeout(() => forceKillWrangler(exitCode), FORCE_KILL_GRACE_MS).unref(); } else { // Nothing left to wait for; without this exit the disabled default would keep us alive. process.exit(exitCode); } } process.on("SIGINT", () => onShutdownSignal("SIGINT", 130)); process.on("SIGTERM", () => onShutdownSignal("SIGTERM", 143)); // The pre-flight builds still running. Kept separate from `devWatchers`, whose `exit` handler runs // on every shutdown path; these need killing on two paths only: when a sibling build has failed, // and on a SIGTERM that arrives while they are still running. const preflightBuilds = new Set(); let stoppingPreflightBuilds = false; // Two of the three builds are `pnpm exec vp run ...`, so this has to reach each one's `vp`/`vite` // descendants -- a bare kill() would signal only the wrapper and leave them writing. Awaited by // callers: process.exit() would cut the tree walk short. async function stopPreflightBuilds(): Promise { stoppingPreflightBuilds = true; await Promise.all([...preflightBuilds].map(child => child.pid ? killProcessTree(child.pid).catch(() => {}) : null)); } // Run a one-shot build to completion. A promise rather than execFileSync so the pre-flight builds // can overlap. function runBuild( label: string, command: string, args: string[], cwd: string, env?: NodeJS.ProcessEnv, ): Promise { return new Promise((resolve, reject) => { const child = spawn(command, args, { stdio: "inherit", cwd, env }); preflightBuilds.add(child); child.on("error", error => { preflightBuilds.delete(child); reject(error); }); child.on("exit", (code, signal) => { preflightBuilds.delete(child); if (code === 0) resolve(); else reject(new Error(`${label} failed (code=${code}, signal=${signal}).`)); }); }); } // Everything Wrangler needs generated before it bundles: the backend's bundled blueprint module // (gitignored, so absent on a clean checkout) and each gatekeeper's UI. // // The UI groups go through `vp` rather than a loop over `gatekeepers` so they run in parallel and // hit the task cache; `vp run` takes one task name, hence two invocations. `vp` selects packages by // which ones declare the task, matching the directory probes in the watcher loop below -- so a new // gatekeeper needs its `build:configurator` or `build:app:dev` task (declared in its // `vite.config.ts`) to be built here. Tasks rather than package.json scripts so // VITE_FRONTEND_ERROR_REPORTING is passed through and fingerprinted; a cached script would strip // it, and the watchers below, which inherit the shell, would rewrite the outputs moments later. // // `build:app:dev` rather than `build:app`: the app watchers cannot skip their own initial build, so // this output is rebuilt regardless, and unless the bytes match Wrangler sees `src/generated/app.txt` // change and restarts the worker. Same build, unminified. // // The two `vp` runs, listed so the concurrency split below is derived from their number rather than // from a literal that a third would silently invalidate. Both share the one machine-aware limit // (vp/concurrency.ts), divided between them: each run alone would otherwise claim the whole budget, // and the two together twice it. Floored at vp's default of 4, so a small machine is unchanged and a // big one stops double-claiming. Computed once, so the note prints once, and after `loadDevVars()` // so a `.dev.vars` override is honoured. const VP_PREFLIGHT_BUILDS = [ { label: "configurator UIs", args: ["exec", "vp", "run", "-r", "--cache", "build:configurator", "--dev"], }, { label: "gatekeeper app UIs", args: ["exec", "vp", "run", "-r", "--cache", "build:app:dev"] }, ]; const vpEnv = vpRunEnv({ concurrentRuns: VP_PREFLIGHT_BUILDS.length }); try { await Promise.all([ runBuild( "bundled blueprints", process.execPath, [join(WORKSHOP_BACKEND_DIR, "scripts", "build-bundled-blueprints.ts")], WORKSHOP_BACKEND_DIR, ), ...VP_PREFLIGHT_BUILDS.map(({ label, args }) => runBuild(label, ...pnpmCommand(args), ROOT, vpEnv)), ]); } catch (err) { // The SIGTERM handler killing the builds also lands here, as the rejection of whichever build // died first. The handler owns teardown and the exit code (143), so park and let it exit. if (stoppingPreflightBuilds) await new Promise(() => {}); console.error((err as Error).message); // The siblings of the build that failed are still running. Left alone they would outlive this // process, writing their outputs after startup has reported failure and colliding with an // immediate re-run. await stopPreflightBuilds(); process.exit(1); } // Watchers start only after those builds finish. Both watch modes run a full build before they // begin watching, so starting one earlier would put two processes on the same src/generated files. for (const gk of gatekeepers) { // Configurator UI (compiled by build-gatekeeper-configurator.ts). The pre-flight already ran this // same build, so each watcher's own initial build is a no-op write -- and it is what keeps the // watcher self-contained: it reads the sources itself, immediately before it starts watching them, // so an edit made while the watchers are still spawning is either in that build or seen by the // watcher. Skipping it would leave that edit sitting unbuilt until the next save, while Wrangler, // which sees the same edit through `watch_dir: src`, restarted the worker as if it had landed. if (existsSync(join(gk.dir, "src", "configurator"))) { spawnDevWatcher( `configurator UI watcher for ${gk.name}`, process.execPath, [join(SCRIPTS_DIR, "build-gatekeeper-configurator.ts"), gk.dir, "--watch", "--quiet"], ); } // Single-file app UI (Vite bundle written to src/generated/app.txt by build-app.ts). // // Deferred until Wrangler is listening: unlike the configurator watcher, `vite build --watch` // cannot skip its initial build, and these are the largest builds in the repo, so running them now // takes cores from the worker bundles Wrangler is building concurrently. Nothing needs them sooner // -- the pre-flight already wrote the `app.txt` they will produce -- and Vite reads the disk when // it finally starts, so an edit made while the server was coming up is still picked up. if (existsSync(join(gk.dir, "build-app.ts"))) { deferredWatchers.push(() => spawnDevWatcher( `app UI watcher for ${gk.name}`, process.execPath, [join(gk.dir, "build-app.ts"), "--watch"], )); } } // Helper: "gatekeeper-github" -> "GATEKEEPER_GITHUB" function bindingName(gk: Gatekeeper): string { return gk.name.toUpperCase().replaceAll("-", "_"); } // --------------------------------------------------------------------------- // Speed up wrangler's per-worker `build.command`. // // Wrangler runs it twice per worker at startup (cloudflare/workers-sdk#7934) and again on every // watch_dir event, and reaching the binary through `pnpm exec` costs ~0.33s of process startup each // time -- for most of these workers longer than the build itself, and all of it on the startup // critical path. // // So for dev only we rewrite the command to spawn the same binaries directly. What runs does not // change -- same entry point, arguments and cwd -- only how it is reached. Anything that does not // resolve is left exactly as written, so the committed wrangler.jsonc stays the source of truth and // an unrecognised command still works, just at the original speed. // --------------------------------------------------------------------------- // Whether wrapping `path` in plain double quotes is safe in the shell that runs the rewritten // command: inside them POSIX shells still expand `$` and backticks and collapse `\\`, cmd still // expands `%`, and an embedded quote or a trailing backslash would break the quoting itself. // Unsafe paths keep the committed `pnpm exec` form -- slower, but correct for any path. function shellSafe(path: string): boolean { return !/[$`%"]|\\\\|\\$/.test(path); } // `pnpm run