Skip to content

Latest commit

 

History

History
120 lines (97 loc) · 12.8 KB

AGENTS.md

File metadata and controls

120 lines (97 loc) · 12.8 KB

env-runner

Generic environment runner for Node.js. Ported from the nitro env runner concept into a standalone package.

Note: Keep AGENTS.md updated with project status and structure.

Note: Keep README.md usage section updated when adding/changing public API, CLI flags, or runner behavior.

Architecture

src/
├── common/
│   ├── base-runner.ts       # BaseEnvRunner abstract class
│   ├── worker-utils.ts      # AppEntry interface, resolveEntry(), parseServerAddress(), toServerOptions() (+ LISTEN_DATA_KEY), shutdownWorker(), formatInitError()
│   ├── runtime-deps.ts      # resolveRuntimeDep()/resolveRuntimeDepSpecifier() — "module | specifier | false" resolver
│   ├── errors.ts            # errorWithCause()/closedBeforeReadyError() — `<message>: <cause message>` errors (`waitForReady()` rejections)
│   ├── host-env.ts          # hostEnv() — worker/child env: host env + FORCE_COLOR/COLUMNS from the host TTY
│   ├── process-data.ts      # receiveProcessData() — runner data over IPC for process workers
│   ├── ws-proxy.ts          # createRunnerWSProxyPlugin() — runtime-native WS upgrade proxy
│   └── virtual-modules.ts   # registerVirtualModules() — registerHooks()/Bun.plugin wiring for node/bun/deno workers; registerOwnedVirtualModules() for the self runner (host process)
├── plugin/                  # host-side `plugins` runner option (see .agents/PLUGINS.md)
│   ├── pipeline.ts          # public plugin types + createPluginPipeline() (host: filters, ordering, source maps, `this.resolve()`, `fallback` resolveId phase; async + `sync` drivers) + transformVirtualModules()
│   ├── filter.ts            # filter matching shared by host and worker (candidates, serialized filters + expressions, prefilters)
│   ├── glob.ts              # host: resolveGlob() + globToRegExp() — `id` globs compiled to RegExps for host and workers
│   ├── hooks.ts             # worker: registerPluginHooks() — registerHooks/Bun.plugin resolve + load hooks that send imports/modules to the runner
│   └── channel.ts           # sync resolve/load requests: MessagePort (node-worker) / local socket + helper thread (process workers) / direct sync pipeline calls (self)
├── runners/
│   ├── node-worker/         # NodeWorkerEnvRunner + worker (parentPort)
│   ├── node-process/        # NodeProcessEnvRunner + worker (process.send)
│   ├── bun-process/         # BunProcessEnvRunner + worker
│   ├── deno-process/        # DenoProcessEnvRunner + worker
│   ├── self/                # SelfEnvRunner (in-process, no worker; virtual modules + sync plugins via host-process hooks)
│   ├── miniflare/           # MiniflareEnvRunner + wrapper.ts (in-memory workerd wrapper) + wrangler.ts (config → Miniflare options) + exports.ts (declared Worker exports) + exports-runtime.ts (lazy DO/entrypoint/workflow stubs, inlined into the wrapper) + dotenv.ts (minimal-reader dev vars)
│   ├── vercel/              # VercelEnvRunner (extends node-worker) + worker, oidc.ts, queue-dev.ts
│   └── netlify/             # NetlifyEnvRunner (extends node-worker) + worker
├── types.ts                 # Core interfaces
├── virtual-loader.ts        # Virtual module formats/validation/JSON transport + createVirtualHooks() — ESM resolve/load hooks
├── index.ts                 # Public API exports
├── loader.ts                # Dynamic runner loader
├── manager.ts               # RunnerManager for hot-reload
├── server.ts                # EnvServer (high-level API with watch mode)
└── cli.ts                   # CLI entry point

Exports: see package.json exports (., ./runners/<name>, ./runners/<name>/worker, ./vite).

Built-in Workers

Each IPC-based runner defaults to its co-located src/runners/<name>/worker.ts (so entry is optional; data.entry points to the user module). Workers let users write a plain export default { fetch } module and start it with srvx.

User entry format (AppEntry)

export default {
  fetch(request: Request): Response | Promise<Response>,
  websocket?: Partial<Hooks>,  // crossws hooks (recommended)
  upgrade?: (ctx: { node: { req, socket, head } }) => void,  // raw upgrade (Node-only)
  middleware?: [], plugins?: [],
  ...ServerOptions, // other srvx options are forwarded to serve()
  ipc?: { onOpen?({ sendMessage }), onMessage?(message), onClose?() },
  resolveExports?: () => Record<string, unknown> | Promise<...>,  // miniflare: Worker classes (default: entry namespace)
};
  • toServerOptions() strips env-runner keys and pins/drops listener options (RESERVED_SERVER_OPTIONS, RESERVED_RUNTIME_OPTIONS for nested node/bun/deno) since the worker listens on 127.0.0.1:0 behind the runner proxy, or on the runner's listen address (see Key patterns). Behind the proxy, bun.idleTimeout defaults to 0 (Bun's 10s default closed slow responses, nitrojs/nitro#4874); listen keeps Bun's default. Server options are read once at start; reloadModule() only swaps fetch.
  • websocket uses crossws/server, which picks the adapter matching the host runtime (so node-worker/node-process use native Bun/Deno adapters when the host is Bun/Deno).
  • ipc.onMessage receives only user messages (ping/pong/shutdown are filtered); onOpen runs before the ready signal.
  • Worker flow: (process workers: receive data over IPC) → import entry → serve() + ready() → wire upgrade → ipc.onOpen → post { address }. Any init failure posts { event: "init-error", error } (formatInitError(): the message, plus where it was thrown if it doesn't say), logs one [env-runner] worker init failed: ... line and exits 1.

Miniflare

Details in .agents/MINIFLARE.md. In short: the wrapper handles requests like srvx/cloudflare (plugins/middleware/error, request.runtime/ip/waitUntil, internal __ENV_RUNNER_* bindings hidden from env; the crossws option sets crossws Cloudflare bindingName/instanceName under the entry's websocket.options.cloudflare, whose defined values win); wrangler (true | path | inline config) + wranglerConfigPath/wranglerEnv/wranglerEnvFiles load wrangler configs into Miniflare options, with unsupported bindings dropped (warned) and user miniflareOptions winning; Worker classes are exported as lazy stubs that follow reloadModule(): the config's ∪ the entry's (es-module-lexer at startup, then the loaded module after the first load and each reload, restarting Miniflare when the set changes); other classes are Durable Objects unless they extend a built-in (Error, EventTarget, ...): auto-bound in zero-config mode, else unbound namespaces (additionalUnboundDurableObjects, for ctx.exports). exports takes false (no detection) or a module specifier (disk or virtual) re-exported with export * whose bindings come from wrangler/miniflareOptions (its export names are fixed at startup). Supports miniflare v4 and v5: options are built in the v4 format and converted with v5's convertV4MiniflareOptions.

Reference docs (.agents/)

  • ARCHITECTURE.md — core source-file notes, BaseEnvRunner lifecycle, RunnerManager/EnvServer
  • NODE-RUNNERS.md — node-worker, node-process, bun-process, deno-process, self (+ orphan tests)
  • MINIFLARE.md — Miniflare internals, MiniflareEnvRunner, wrangler config + tests
  • VERCEL.md — VercelEnvRunner (env vars, headers, OIDC, Queues) + tests
  • NETLIFY.md — NetlifyEnvRunner + tests
  • VIRTUAL-MODULES.md — virtual modules across Node/Bun/Deno/Miniflare + tests
  • PLUGINS.md — host-side plugins runner option, the sync transform channel, per-runtime load hooks + tests

Testing

  • Runner tests spawn workers from dist/ (resolved via the self-linked env-runner package), so run pnpm build after worker-side changes before pnpm vitest run
  • test/runners.test.ts is the cross-runner suite; bun/deno cases auto-skip when the runtime is missing. Runner-specific test notes live in each runner doc

Scripts

  • pnpm build — obuild
  • pnpm dev — Vitest watch
  • pnpm test — lint + typecheck + vitest with coverage
  • pnpm typecheck — tsgo
  • pnpm fmt — automd + oxlint fix + oxfmt
  • pnpm lint — oxlint + oxfmt check
  • pnpm release — test + build + changelog + publish + push

Dependencies

  • crossws, httpxy, srvx — WebSocket hooks, HTTP/WS proxy, server framework
  • cjs-module-lexer / es-module-lexer — devDependencies inlined into dist (miniflare module fallback service)
  • No peer dependencies. miniflare, wrangler, @netlify/runtime, @vercel/queue are installed by the app and passed as runner options (miniflare, wranglerModule, netlifyRuntime, queue sdk), resolved via resolveRuntimeDep(): imported module | specifier (resolved from cwd) | false (opt out) | omitted (optional import). If nothing resolves: miniflare throws; wrangler → minimal JSON/JSONC reader; netlify → shim; queue → warn-once no-op. netlifyRuntime must be a specifier (imported inside the worker, via resolveRuntimeDepSpecifier()). These packages must stay listed as external in build.config.mjs.

Key patterns

  • Message-driven readiness — workers post { address } when ready
  • WebSocket proxying — RunnerManager.wsSrvxPlugin(): Node host proxies the raw upgrade socket (httpxy); Bun/Deno host terminates with crossws and bridges via a WebSocket client. Reads the active runner lazily (survives hot-reload) and awaits readiness
  • Immediate close, graceful shutdown() — close() terminates the worker/process; shutdown(timeout) first sends shutdown (worker: server.close(), bounded to half the timeout → ipc.onClose → exit), also on RunnerManager/EnvServer
  • Drained reload — RunnerManager.reload(runner, { drain }) (EnvServer: drain option) counts each runner's requests (until the response body settles) and WebSockets, and shuts the previous runner down once they settle instead of closing it at the swap (closes it after timeout, default 60s). See ARCHITECTURE.md
  • Public listener — the listen runner option (node-worker, node-process, bun-process, deno-process) makes the worker's srvx server bind the public address (no proxy hop); sent as data[LISTEN_DATA_KEY], the reported address is loopback for wildcards and has protocol: "https" with TLS. self serves it from the host process (serve(toServerOptions(entry, listen))); miniflare closes with an error. See NODE-RUNNERS.md
  • Orphan protection — node-process/bun-process/deno-process workers call process.on("disconnect", () => process.exit(0)) before the data handshake and entry import
  • Data passing — workerData (threads), IPC handshake (processes: worker listens, sends request-init-data, host replies { event: "init-data", data: "<JSON>" }; env vars are size-limited, see NODE-RUNNERS.md), direct in-process import (self), in-memory script + unsafeModuleFallbackService (miniflare)
  • Host-side plugins — the plugins runner option (not part of data) stays on the host (resolveId, load, transform hooks). Worker resolve/load hooks send matching imports and modules over a dedicated sync channel (Atomics.wait + receiveMessageOnPort, since the runner IPC listener can't run while the loader blocks); virtual modules are transformed on the host before they are sent. resolveId hooks with fallback: true only get imports the runtime failed to resolve; handlers get this.resolve(). The self runner registers the same hooks in the host and runs the pipeline's sync driver in them (synchronous handlers only, except for virtual modules). See PLUGINS.md
  • Virtual module updates — updateVirtualModules() sets/removes (null) keys in one update-virtual-modules round trip (miniflare: host-side); invalidateModule() is the same update with the current source. The host keeps its own map in sync, see VIRTUAL-MODULES.md
  • Terminal capabilities — spawned workers get piped stdout, so hostEnv() forwards FORCE_COLOR/COLUMNS from the host TTY
  • Stdio forwarding — all runners forward entry stdout/stderr to the host
  • Socket cleanup — _closeSocket() skips Windows named pipes and abstract sockets
  • Adding a new runner — src/runners/<name>/runner.ts extending BaseEnvRunner (+ optional worker.ts), add package.json export, add to loaders in src/loader.ts, re-export from src/index.ts