{"owner":"nitrojs","repo":"nitro","hasSkills":true,"totalSkillsCount":7,"totalTokensCount":5057,"categories":["anthropic-skill","plugin-manifest","subagent-persona","copilot-instructions","project-spec","root-instruction"],"hasMcp":false,"mcpConfig":null,"found":["examples/plugins/package.json","examples/plugins/README.md",".github/agents/maintainer.agent.md",".github/copilot-instructions.md",".agents/architecture.md","AGENTS.md","examples/plugins/tsconfig.json"],"skills":{"examples/plugins/package.json":"{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"nitro dev\",\n    \"build\": \"nitro build\"\n  },\n  \"devDependencies\": {\n    \"nitro\": \"latest\"\n  }\n}\n","examples/plugins/README.md":"Plugins let you hook into Nitro's runtime lifecycle. This example shows a plugin that modifies the `Content-Type` header on every response. Create files in `server/plugins/` and they're automatically loaded at startup.\n\n## Defining a Plugin\n\n```ts [server/plugins/test.ts]\nimport { definePlugin } from \"nitro\";\nimport { useNitroHooks } from \"nitro/app\";\n\nexport default definePlugin(() => {\n  const hooks = useNitroHooks();\n  hooks.hook(\"response\", (res) => {\n    res.headers.set(\"content-type\", \"html; charset=utf-8\");\n  });\n});\n```\n\nThe plugin uses `useNitroHooks()` to access the hooks system, then registers a `response` hook that runs after every request and receives the outgoing `Response`. Here it sets the content type to HTML, but you could log requests, add security headers, or modify responses in any way.\n\n## Main Handler\n\n```ts [server.ts]\nimport { defineHandler } from \"nitro\";\n\nexport default defineHandler(() => \"<h1>Hello Nitro!</h1>\");\n```\n\nThe handler returns HTML without setting a content type. The plugin automatically adds the correct `Content-Type: html; charset=utf-8` header to the response.\n",".github/agents/maintainer.agent.md":"---\nname: Maintainer\ndescription: >\n  Nitro project maintainer agent. Handles bug fixes, feature implementation,\n  code review, and contributions following project conventions. Understands the\n  build system, runtime constraints, deployment presets, and testing strategy.\ntools:\n  - \"*\"\n---\n\nYou are a maintainer of the Nitro project. Follow all instructions in [AGENTS.md](../../AGENTS.md) strictly.\n\nFor deeper architectural context, refer to the `.agents/` directory:\n\n- `.agents/architecture.md` — Core architecture, build system, config resolution, virtual modules, runtime internals.\n- `.agents/presets.md` — Deployment presets, preset structure, resolution logic.\n- `.agents/testing.md` — Test structure, adding regression tests, running tests.\n- `.agents/vite.md` — Vite build system, plugin architecture, dev server, HMR.\n- `.agents/docs.md` — Documentation conventions, H3 v2 API patterns.\n\nH3 v2 docs are at `node_modules/h3/dist/docs/README.md`.\n\n## Key principles\n\n- Prefer minimal, targeted changes over large refactors.\n- Code in `src/runtime/` must be runtime-agnostic (Web APIs, no Node.js-specific APIs).\n- Use `pathe` instead of `node:path`.\n- Use existing UnJS utilities (`defu`, `consola`, `unstorage`) before adding new packages.\n- Bug fixes MUST include a failing regression test first.\n- Always run `pnpm fmt` and `pnpm typecheck` after changes.\n- Use semantic commit messages with scope (e.g., `fix(runtime): ...`).\n",".github/copilot-instructions.md":"@../AGENTS.md\n\nRefer to [AGENTS.md](../AGENTS.md) for project instructions.\n",".agents/architecture.md":"# Nitro Architecture Deep Dive\n\n## Core Instance (`src/nitro.ts`)\n\n`createNitro(config, opts)` creates the main context with:\n- `options: NitroOptions` — Resolved configuration\n- `hooks: Hookable<NitroHooks>` — Build lifecycle hooks\n- `vfs: Map<string, { render }>` — Virtual file system\n- `routing: { routes, routeRules, globalMiddleware, routedMiddleware }`\n- `scannedHandlers: NitroEventHandler[]`\n- `logger: ConsolaInstance`\n- `updateConfig(config)` — Hot-reload config\n- `close()` — Cleanup\n\n**Setup flow:**\n1. Load options via `loadOptions()`\n2. Install modules via `installModules()`\n3. Init routing via `initNitroRouting()`\n4. Scan handlers/plugins/tasks via `scanAndSyncOptions()`\n5. Setup hooks\n\n## Entry Points\n\n- `src/builder.ts` — Main public API: `createNitro()`, `build()`, `createDevServer()`, `prerender()`, `copyPublicAssets()`, `prepare()`, `runTask()`, `listTasks()`\n- `src/vite.ts` — Vite plugin export from `src/build/vite/plugin.ts`\n\n## Build System (`src/build/`)\n\n**Builder dispatch** (`build/build.ts`): delegates to `rollup`, `rolldown`, or `vite` based on `nitro.options.builder`.\n\n**Builder selection** (resolved in `config/resolvers/builder.ts`):\n- Check `NITRO_BUILDER` env var\n- Auto-detect: `vite` when a `vite.config` uses `nitro()`, otherwise `rolldown`\n- No builder package is a dependency of Nitro: they are imported from the user project and installed on demand (`rolldown` via `build/rolldown/_import.ts`)\n- Dev without `rolldown` (and no `rollupConfig`/`rolldownConfig`) falls back to `builder: false`\n\n**Base config** (`build/config.ts`):\n- Extensions: `.ts`, `.mjs`, `.js`, `.json`, `.node`, `.tsx`, `.jsx`\n- Import.meta replacements (`import.meta.dev`, `import.meta.preset`, etc.)\n- Node.js compatibility aliases (`unenv` targets go to the unenv plugin)\n- External dependency patterns\n\n**Plugins** (`build/plugins.ts`):\n1. Virtual modules — renders from `build/virtual/`\n2. Unenv — resolves `unenv/*` polyfills, installing `unenv` on demand\n3. WASM loader — unwasm\n4. Server main injection — `globalThis.__server_main__`\n5. Raw imports — `?raw` suffix\n6. Route meta — OpenAPI metadata\n7. Replace plugin — variable substitution\n8. Externals plugin — Node.js native resolution\n9. Sourcemap minify (optional)\n\nUser `buildPlugins` are added around this list by `withBuildPlugins()` (`enforce: \"pre\"` before, the others after the builder's own plugins). With `builder: false`, they are appended to the env-runner plugins (`build/unbundled/plugins.ts`).\n\n**Virtual modules** (`build/virtual/`, 14 templates):\nAll prefixed `#nitro/virtual/<name>`:\n- `routing.ts` — Compiled router matcher\n- `plugins.ts` — Plugin registry\n- `error-handler.ts` — Error handler\n- `public-assets.ts` — Public asset metadata\n- `server-assets.ts` — Server asset metadata\n- `runtime-config.ts` — Runtime config object\n- `database.ts` — Database setup\n- `kv.ts` — KV storage backends\n- `tasks.ts` — Task registry\n- `polyfills.ts` — Env polyfills\n- `feature-flags.ts` — Feature detection\n- `routing-meta.ts` — Route metadata (OpenAPI)\n- `renderer-template.ts` — SSR renderer\n- `_all.ts` — Aggregator\n\n## Configuration System (`src/config/`)\n\n**Loader** (`config/loader.ts`): `loadOptions(config, opts)`\n1. Merge with defaults (`NitroDefaults`)\n2. Load c12 config files (`nitro.config.ts`, `package.json.nitro`, etc.)\n3. Resolve preset\n4. Run config resolvers sequentially\n\n**Resolvers** (`config/resolvers/`):\n`compatibility`, `tsconfig`, `paths`, `imports`, `route-rules`, `database`, `export-conditions`, `runtime-config`, `open-api`, `url`, `assets`, `storage`, `error`, `unenv`, `builder`\n\n**Defaults** (`config/defaults.ts`): All NitroConfig defaults.\n\n## Runtime (`src/runtime/`)\n\n**Internal** (`runtime/internal/`):\n- `app.ts` — NitroApp creation, H3 app setup\n- `cache.ts` — Response caching\n- `context.ts` — Async context\n- `route-rule-handlers.ts` — Nitro's rule handlers for the compiled matcher: a `cache` handler bound to Nitro's cache runtime. The built-ins (headers, redirect, proxy, cors) and rule matching/normalization live in [`h3/rules`](https://h3.dev/guide/rules).\n- `static.ts` — Static file serving\n- `task.ts` — Task execution\n- `plugin.ts` — Plugin helpers\n- `runtime-config.ts` — Config getter\n\n**Public exports**: `runtime/app.ts` (`defineConfig()`), `runtime/nitro.ts` (`serverFetch()`), `runtime/cache.ts`, `runtime/task.ts`, `runtime/kv.ts`, etc.\n\n## Dev Server (`src/dev/`)\n\n- `dev/server.ts` — `createDevServer()` (public `NitroDevServer` interface, internal `DevServer` class): Worker management via `env-runner`, restart on failure (max 3 retries), WebSocket support, VFS debug endpoint (`/_vfs/**`)\n- `dev/app.ts` — `NitroDevApp`: H3 app with error handling, static serving with compression, dev proxy\n\n## Prerender (`src/prerender/`)\n\n- `prerender/prerender.ts` — Main flow: parse routes → build prerenderer (preset: `nitro-prerender`) → execute in parallel → link crawling → write to disk → compress\n- `prerender/utils.ts` — `extractLinks()`, `matchesIgnorePattern()`, `formatPrerenderRoute()`\n\n## Routing & Scanning (`src/routing.ts`, `src/scan.ts`)\n\n**Scanning**: Discovers routes, middleware, plugins, tasks, modules from filesystem.\n\nRoute file conventions:\n- `routes/index.ts` → `GET /`\n- `routes/users/[id].ts` → `GET /users/:id`\n- `routes/users/[...slug].ts` → `GET /users/:slug(.*)` (also matches `/users`)\n- `api/users.post.ts` → `POST /api/users`\n- `.dev`/`.prod`/`.prerender` suffixes for environment filtering\n\n**Router** (`Router` class): Based on `rou3`, compiles to optimized string matcher, supports method routing + env conditions.\n\n## Presets (`src/presets/`)\n\nSeveral deployment-target presets (+ internal `_nitro`/`_static`); see `.agents/presets.md`. Structure per preset:\n\n```\npresets/<name>/\n├── preset.ts        # defineNitroPreset()\n├── runtime/         # Runtime entry (bundled)\n├── types.ts         # Types (optional)\n├── utils.ts         # Build-time utils (optional)\n└── unenv/           # Env overrides (optional)\n```\n\nKey presets: `standard`, `node` (server/middleware/cluster), `cloudflare` (pages/workers), `vercel`, `netlify`, `aws-lambda`, `deno`, `firebase`, `azure`, `bun`\n\nResolution: `presets/_resolve.ts` handles aliases, dev/prod, compat dates, static hosting.\n\n## CLI (`src/cli/`)\n\nUses `citty` with lazy-loaded commands: `dev`, `build`, `deploy`, `preview`, `prepare`, `task`, `docs`.\n\n## Key Libraries\n\n| Library | Purpose |\n|---------|---------|\n| `h3` | HTTP framework |\n| `rou3` | Route matching |\n| `c12` | Config loading |\n| `citty` | CLI framework |\n| `hookable` | Hook system |\n| `unstorage` | Storage abstraction (`nitro/kv`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `db0` | SQL database layer (`nitro/database`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `ocache` | Caching (`nitro/cache`, `cache` route rules) |\n| `unenv` | Node.js polyfills for `node: false` builds (`build/_node-compat.ts`), installed on demand by `build/plugins/unenv.ts` |\n| `defu` | Config merging |\n| `pathe` | Path operations |\n| `consola` | Logging |\n| `env-runner` | Worker management |\n","AGENTS.md":"## Project Identity\n\nNitro is a framework-agnostic and deployment-agnostic server framework powered by [H3](https://github.com/h3js/h3) (v2), [UnJS] (https://github.com/unjs), and Vite | Rolldown | Rollup.\n\n## First-time Setup for Development\n\n- Run `corepack enable` to ensure `pnpm` is available.\n- Run `pnpm install` to install dependencies.\n- Run `pnpm build --stub` to prepare development mode.\n\n## Key Scripts\n\n- `pnpm build --stub` — Fast stub build (`obuild --stub`) for development.\n- `pnpm build` — Full build (`pnpm gen-presets && obuild`).\n- `pnpm lint` — Check lint and formatting (`oxlint` + `oxfmt --check`).\n- `pnpm fmt` — Auto-fix lint and formatting (`automd` + `oxlint --fix` + `oxfmt`).\n- `pnpm test` — Full pipeline: `lint && build && typecheck && test:rollup && test:rolldown` (runs vitest against both the rollup and rolldown builders).\n- `pnpm test:rollup` / `pnpm test:rolldown` — Run vitest against a single builder (`NITRO_BUILDER`).\n- `pnpm typecheck` — Type-check with the TypeScript native-preview compiler (`tsgo --noEmit --skipLibCheck`).\n\n**Always run** `pnpm fmt` and `pnpm typecheck` after making changes.\n\n## Repository Structure\n\n- `.github/` — GitHub Actions workflows.\n- `docs/` — Documentation site built with [UnDocs](https://github.com/unjs/undocs).\n- `examples/` — Example projects and integrations.\n- `src/` — Project source code.\n- `test/` — Unit, minimal, and end-to-end tests.\n\n### Code Structure\n\nProject source is centralized under `src/`:\n\n- `src/build` — Build logic (Vite | Rolldown | Rollup config, virtual templates in `src/build/virtual/`, plugins in `src/build/plugins/`).\n- `src/cli` — `nitro` CLI subcommands (each file in `src/cli/commands` is a command).\n- `src/config/` — Config defaults (`src/config/defaults.ts`) and resolvers/normalizers (`src/config/resolvers`).\n- `src/dev` — Development server logic (`app.ts`, `server.ts`, `vfs.ts`).\n- `src/prerender` — Prerender logic.\n- `src/presets` — Deployment presets and runtime entry.\n- `src/types` — Shared types.\n- `src/utils` — Internal utilities.\n- `src/runtime` — Runtime code that goes into the bundle (runtime and platform agnostic).\n\n### Why Changes in `src/` Are High-Impact\n\nCode in `src/` affects all Nitro users:\n\n- Changes in `src/runtime` are bundled and run across all deployment targets.\n- Changes in `src/build` affect build output and performance.\n- Changes in `src/presets` affect specific deployment platforms.\n- Changes in `src/config` affect default behavior.\n\nReview these changes carefully for backwards compatibility, bundle size, and cross-runtime support.\n\n## Code Patterns & Conventions\n\n- `pathe` — Cross-platform path operations (always prefer over `node:path`).\n- `defu` — Deep object merging and config defaults.\n- `consola` — Logging in build/dev code (use `nitro.logger` when available).\n- `unstorage` — Storage abstraction.\n\n### Optional Dependencies\n\nPackages that are only needed by some presets, builders, or opt-in features are imported on demand\nfrom the user project via `src/utils/dep.ts` (`ensureDep` / `importDep` / `isDepInstalled`), which\nresolves from `nitro.options.rootDir` and offers to install what is missing.\n\n- Don't add a `peerDependencies` entry. Add the package to `devDependencies` (for tests and types)\n  and to the `deps.json` manifest (supported `version` range, `reason` and install defaults, typed\n  in `src/utils/_deps.ts`), then import it with `importDep({ id, dir: nitro.options.rootDir, paths: nitro.options.deps?.paths })`\n  (`paths` honours the explicit packages of the `deps.paths` option, e.g. passed by frameworks).\n- Manifest entries are kept external in `build.config.ts`. A unit test checks that each range covers\n  the `devDependencies` version: after bumping one out of its range, run `pnpm sync-deps`.\n- `import type` from such a package is fine; only value imports must go through `utils/dep.ts`.\n- Optional dependencies of the libraries Nitro *bundles* (e.g. `jiti` for `c12`) cannot resolve from\n  `dist/`. Those are not in the manifest: they get a bundle-time alias to a shim in `src/shims/`\n  (one file per package), with a range within the one of the bundled library (`shims` in `deps.json`).\n- Nitro has no peer dependencies at all: `vite` is imported from the user project too\n  (`src/build/vite/_import.ts`). Its `DevEnvironment` subclass is therefore defined lazily, against\n  the class of the resolved instance (see `src/build/vite/dev.ts`).\n\n### Runtime Constraints\n\nCode in `src/runtime/` must be runtime-agnostic:\n\n- **Don't use Node.js-specific APIs** (unless behind runtime checks).\n- Prefer **Web APIs** (fetch, Request, Response, URL, etc.).\n- Only use `console` for logging (no `consola` in runtime).\n- Keep bundle size minimal and side-effect free.\n\n## Testing Strategy\n\n### Test Structure\n\nMain tests are defined in `test/tests.ts` and setup per each deployment provider in `test/presets` and run against `test/fixture` nitro app. Add new regression tests to `test/fixture`.\n\nOther tests:\n\n- **Unit** (`test/unit/`) — Isolated unit tests.\n- **Minimal** (`test/minimal/`) — Smallest bundle output.\n\n### Testing Requirements\n\n- Run `pnpm run test` before submitting.\n- **Bug fixes MUST include a failing test first** — add regression tests to `test/fixture/` and make sure test script fails before attempting the fix and resolves after.\n- Keep tests deterministic and environment-independent.\n\n## Working with Presets\n\nEach preset in `src/presets/` defines deployment target behavior:\n\n- Runtime logic and entry is in `src/presets/<name>/runtime`\n- Preset config and utils (build time) are in `src/presets/<name>/*.ts`.\n\n## Development Workflow\n\n### Making Changes\n\n1. Make changes in `src/`.\n2. Run `pnpm stub` if you changed build logic.\n3. Test with `pnpm test`.\n4. Run `pnpm fmt`.\n5. Run `pnpm typecheck`.\n6. Run `pnpm test:rollup` and/or `pnpm test:rolldown` to run vitest against a specific builder.\n\n## Contribution Principles\n\n- Prefer **minimal, targeted changes** over large refactors.\n- Avoid introducing new dependencies unless strictly necessary.\n  Add them to `devDependencies` unless they are required in runtime logic.\n- Be mindful of **bundle size**, startup cost, and runtime overhead.\n- Maintain **backwards compatibility** unless explicitly instructed otherwise.\n- Batch multiple related edits together. Avoid sequential micro-changes.\n- Never modify files outside the scope of the requested change.\n\n## Common Gotchas\n\n- **Don't use Node.js-specific APIs in `src/runtime/`** — Code runs in multiple runtimes (Node, workers, edge).\n- **Virtual modules must be registered** in `src/build/virtual/_all.ts` (one template per file under `src/build/virtual/`).\n- **CLI commands** are in `src/cli/commands/` — Each file exports a command definition.\n- **Runtime size matters** — Check bundle impact with `pnpm build`.\n- **Use `pathe` not `node:path`** — Ensures cross-platform compatibility.\n- **No peer dependencies** — Optional packages are imported on demand via `src/utils/dep.ts`.\n\n## Error & Logging Guidelines\n\n- Prefer explicit errors over silent failures.\n- Use `nitro.logger` in build/dev code, `consola` as fallback.\n- Use `console` only in `src/runtime/` code.\n- Use warnings for recoverable situations; throw for invalid states.\n- Include actionable context in error messages.\n\n## Documentation Requirements\n\n- Update `docs/` for user-facing changes.\n- Update types and JSDoc for API changes.\n- Examples in `examples/` should reflect best practices and be added for new integrations.\n- Add migration notes for breaking changes.\n\n## Code Conventions\n\n- Use **ESM** and modern JavaScript; use explicit extensions (`.ts`, `.mjs`) in imports.\n- For `.json` imports, use `with { \"type\": \"json\" }`.\n- Avoid barrel files (`index.ts` re-exports); import directly from specific modules.\n- Place non-exported/internal helpers at the end of the file.\n- For multi-arg functions, use an options object as the second parameter.\n- Split logic across files; avoid long single-file modules (>200 LoC). Use `_*` prefix for internal files.\n- Prefer **Web APIs** over Node.js APIs where possible.\n- Do not add comments explaining what the line does unless prompted.\n- Before adding new code, study surrounding patterns, naming conventions, and architectural decisions.\n- Use existing UnJS utilities and dependencies before adding new packages.\n- Keep runtime code minimal and fast.\n\n## Commit Conventions\n\n- Use **semantic commit messages**, lower-case (e.g., `fix(cli): resolve path issue`).\n- Prefer to include scope (e.g., `feat(runtime):`, `fix(build):`).\n- Add a short description on the second line when helpful.\n\n## Detailed References\n\nFor deeper context, see `.agents/`:\n\n- [`.agents/architecture.md`](.agents/architecture.md) — Full architecture: core instance, build system, config resolution, virtual modules, runtime internals, dev server, routing, key libraries.\n- [`.agents/presets.md`](.agents/presets.md) — All presets (multiple deployment targets + internal `_nitro`/`_static`), preset structure, how to create presets, resolution logic.\n- [`.agents/testing.md`](.agents/testing.md) — Test structure, how tests work, adding regression tests, running tests.\n- [`.agents/vite.md`](.agents/vite.md) — Vite build system: plugin architecture (6 sub-plugins), environments API, dev server integration, production build stages, bundler config, HMR, runtime worker.\n- [`.agents/docs.md`](.agents/docs.md) — Docs site: UnDocs structure, the `.docs/` theme layer (imports, styling tokens, content queries), MDC blocks, and content conventions (preset naming, import paths, H3 v2 patterns, common mistakes).\n\nH3 v2 updated docs is at `node_modules/h3/dist/docs/README.md`\n","examples/plugins/tsconfig.json":"{\n  \"extends\": \"nitro/tsconfig\"\n}\n"},"files":{"examples/plugins/package.json":"{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"nitro dev\",\n    \"build\": \"nitro build\"\n  },\n  \"devDependencies\": {\n    \"nitro\": \"latest\"\n  }\n}\n","examples/plugins/README.md":"Plugins let you hook into Nitro's runtime lifecycle. This example shows a plugin that modifies the `Content-Type` header on every response. Create files in `server/plugins/` and they're automatically loaded at startup.\n\n## Defining a Plugin\n\n```ts [server/plugins/test.ts]\nimport { definePlugin } from \"nitro\";\nimport { useNitroHooks } from \"nitro/app\";\n\nexport default definePlugin(() => {\n  const hooks = useNitroHooks();\n  hooks.hook(\"response\", (res) => {\n    res.headers.set(\"content-type\", \"html; charset=utf-8\");\n  });\n});\n```\n\nThe plugin uses `useNitroHooks()` to access the hooks system, then registers a `response` hook that runs after every request and receives the outgoing `Response`. Here it sets the content type to HTML, but you could log requests, add security headers, or modify responses in any way.\n\n## Main Handler\n\n```ts [server.ts]\nimport { defineHandler } from \"nitro\";\n\nexport default defineHandler(() => \"<h1>Hello Nitro!</h1>\");\n```\n\nThe handler returns HTML without setting a content type. The plugin automatically adds the correct `Content-Type: html; charset=utf-8` header to the response.\n",".github/agents/maintainer.agent.md":"---\nname: Maintainer\ndescription: >\n  Nitro project maintainer agent. Handles bug fixes, feature implementation,\n  code review, and contributions following project conventions. Understands the\n  build system, runtime constraints, deployment presets, and testing strategy.\ntools:\n  - \"*\"\n---\n\nYou are a maintainer of the Nitro project. Follow all instructions in [AGENTS.md](../../AGENTS.md) strictly.\n\nFor deeper architectural context, refer to the `.agents/` directory:\n\n- `.agents/architecture.md` — Core architecture, build system, config resolution, virtual modules, runtime internals.\n- `.agents/presets.md` — Deployment presets, preset structure, resolution logic.\n- `.agents/testing.md` — Test structure, adding regression tests, running tests.\n- `.agents/vite.md` — Vite build system, plugin architecture, dev server, HMR.\n- `.agents/docs.md` — Documentation conventions, H3 v2 API patterns.\n\nH3 v2 docs are at `node_modules/h3/dist/docs/README.md`.\n\n## Key principles\n\n- Prefer minimal, targeted changes over large refactors.\n- Code in `src/runtime/` must be runtime-agnostic (Web APIs, no Node.js-specific APIs).\n- Use `pathe` instead of `node:path`.\n- Use existing UnJS utilities (`defu`, `consola`, `unstorage`) before adding new packages.\n- Bug fixes MUST include a failing regression test first.\n- Always run `pnpm fmt` and `pnpm typecheck` after changes.\n- Use semantic commit messages with scope (e.g., `fix(runtime): ...`).\n",".github/copilot-instructions.md":"@../AGENTS.md\n\nRefer to [AGENTS.md](../AGENTS.md) for project instructions.\n",".agents/architecture.md":"# Nitro Architecture Deep Dive\n\n## Core Instance (`src/nitro.ts`)\n\n`createNitro(config, opts)` creates the main context with:\n- `options: NitroOptions` — Resolved configuration\n- `hooks: Hookable<NitroHooks>` — Build lifecycle hooks\n- `vfs: Map<string, { render }>` — Virtual file system\n- `routing: { routes, routeRules, globalMiddleware, routedMiddleware }`\n- `scannedHandlers: NitroEventHandler[]`\n- `logger: ConsolaInstance`\n- `updateConfig(config)` — Hot-reload config\n- `close()` — Cleanup\n\n**Setup flow:**\n1. Load options via `loadOptions()`\n2. Install modules via `installModules()`\n3. Init routing via `initNitroRouting()`\n4. Scan handlers/plugins/tasks via `scanAndSyncOptions()`\n5. Setup hooks\n\n## Entry Points\n\n- `src/builder.ts` — Main public API: `createNitro()`, `build()`, `createDevServer()`, `prerender()`, `copyPublicAssets()`, `prepare()`, `runTask()`, `listTasks()`\n- `src/vite.ts` — Vite plugin export from `src/build/vite/plugin.ts`\n\n## Build System (`src/build/`)\n\n**Builder dispatch** (`build/build.ts`): delegates to `rollup`, `rolldown`, or `vite` based on `nitro.options.builder`.\n\n**Builder selection** (resolved in `config/resolvers/builder.ts`):\n- Check `NITRO_BUILDER` env var\n- Auto-detect: `vite` when a `vite.config` uses `nitro()`, otherwise `rolldown`\n- No builder package is a dependency of Nitro: they are imported from the user project and installed on demand (`rolldown` via `build/rolldown/_import.ts`)\n- Dev without `rolldown` (and no `rollupConfig`/`rolldownConfig`) falls back to `builder: false`\n\n**Base config** (`build/config.ts`):\n- Extensions: `.ts`, `.mjs`, `.js`, `.json`, `.node`, `.tsx`, `.jsx`\n- Import.meta replacements (`import.meta.dev`, `import.meta.preset`, etc.)\n- Node.js compatibility aliases (`unenv` targets go to the unenv plugin)\n- External dependency patterns\n\n**Plugins** (`build/plugins.ts`):\n1. Virtual modules — renders from `build/virtual/`\n2. Unenv — resolves `unenv/*` polyfills, installing `unenv` on demand\n3. WASM loader — unwasm\n4. Server main injection — `globalThis.__server_main__`\n5. Raw imports — `?raw` suffix\n6. Route meta — OpenAPI metadata\n7. Replace plugin — variable substitution\n8. Externals plugin — Node.js native resolution\n9. Sourcemap minify (optional)\n\nUser `buildPlugins` are added around this list by `withBuildPlugins()` (`enforce: \"pre\"` before, the others after the builder's own plugins). With `builder: false`, they are appended to the env-runner plugins (`build/unbundled/plugins.ts`).\n\n**Virtual modules** (`build/virtual/`, 14 templates):\nAll prefixed `#nitro/virtual/<name>`:\n- `routing.ts` — Compiled router matcher\n- `plugins.ts` — Plugin registry\n- `error-handler.ts` — Error handler\n- `public-assets.ts` — Public asset metadata\n- `server-assets.ts` — Server asset metadata\n- `runtime-config.ts` — Runtime config object\n- `database.ts` — Database setup\n- `kv.ts` — KV storage backends\n- `tasks.ts` — Task registry\n- `polyfills.ts` — Env polyfills\n- `feature-flags.ts` — Feature detection\n- `routing-meta.ts` — Route metadata (OpenAPI)\n- `renderer-template.ts` — SSR renderer\n- `_all.ts` — Aggregator\n\n## Configuration System (`src/config/`)\n\n**Loader** (`config/loader.ts`): `loadOptions(config, opts)`\n1. Merge with defaults (`NitroDefaults`)\n2. Load c12 config files (`nitro.config.ts`, `package.json.nitro`, etc.)\n3. Resolve preset\n4. Run config resolvers sequentially\n\n**Resolvers** (`config/resolvers/`):\n`compatibility`, `tsconfig`, `paths`, `imports`, `route-rules`, `database`, `export-conditions`, `runtime-config`, `open-api`, `url`, `assets`, `storage`, `error`, `unenv`, `builder`\n\n**Defaults** (`config/defaults.ts`): All NitroConfig defaults.\n\n## Runtime (`src/runtime/`)\n\n**Internal** (`runtime/internal/`):\n- `app.ts` — NitroApp creation, H3 app setup\n- `cache.ts` — Response caching\n- `context.ts` — Async context\n- `route-rule-handlers.ts` — Nitro's rule handlers for the compiled matcher: a `cache` handler bound to Nitro's cache runtime. The built-ins (headers, redirect, proxy, cors) and rule matching/normalization live in [`h3/rules`](https://h3.dev/guide/rules).\n- `static.ts` — Static file serving\n- `task.ts` — Task execution\n- `plugin.ts` — Plugin helpers\n- `runtime-config.ts` — Config getter\n\n**Public exports**: `runtime/app.ts` (`defineConfig()`), `runtime/nitro.ts` (`serverFetch()`), `runtime/cache.ts`, `runtime/task.ts`, `runtime/kv.ts`, etc.\n\n## Dev Server (`src/dev/`)\n\n- `dev/server.ts` — `createDevServer()` (public `NitroDevServer` interface, internal `DevServer` class): Worker management via `env-runner`, restart on failure (max 3 retries), WebSocket support, VFS debug endpoint (`/_vfs/**`)\n- `dev/app.ts` — `NitroDevApp`: H3 app with error handling, static serving with compression, dev proxy\n\n## Prerender (`src/prerender/`)\n\n- `prerender/prerender.ts` — Main flow: parse routes → build prerenderer (preset: `nitro-prerender`) → execute in parallel → link crawling → write to disk → compress\n- `prerender/utils.ts` — `extractLinks()`, `matchesIgnorePattern()`, `formatPrerenderRoute()`\n\n## Routing & Scanning (`src/routing.ts`, `src/scan.ts`)\n\n**Scanning**: Discovers routes, middleware, plugins, tasks, modules from filesystem.\n\nRoute file conventions:\n- `routes/index.ts` → `GET /`\n- `routes/users/[id].ts` → `GET /users/:id`\n- `routes/users/[...slug].ts` → `GET /users/:slug(.*)` (also matches `/users`)\n- `api/users.post.ts` → `POST /api/users`\n- `.dev`/`.prod`/`.prerender` suffixes for environment filtering\n\n**Router** (`Router` class): Based on `rou3`, compiles to optimized string matcher, supports method routing + env conditions.\n\n## Presets (`src/presets/`)\n\nSeveral deployment-target presets (+ internal `_nitro`/`_static`); see `.agents/presets.md`. Structure per preset:\n\n```\npresets/<name>/\n├── preset.ts        # defineNitroPreset()\n├── runtime/         # Runtime entry (bundled)\n├── types.ts         # Types (optional)\n├── utils.ts         # Build-time utils (optional)\n└── unenv/           # Env overrides (optional)\n```\n\nKey presets: `standard`, `node` (server/middleware/cluster), `cloudflare` (pages/workers), `vercel`, `netlify`, `aws-lambda`, `deno`, `firebase`, `azure`, `bun`\n\nResolution: `presets/_resolve.ts` handles aliases, dev/prod, compat dates, static hosting.\n\n## CLI (`src/cli/`)\n\nUses `citty` with lazy-loaded commands: `dev`, `build`, `deploy`, `preview`, `prepare`, `task`, `docs`.\n\n## Key Libraries\n\n| Library | Purpose |\n|---------|---------|\n| `h3` | HTTP framework |\n| `rou3` | Route matching |\n| `c12` | Config loading |\n| `citty` | CLI framework |\n| `hookable` | Hook system |\n| `unstorage` | Storage abstraction (`nitro/kv`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `db0` | SQL database layer (`nitro/database`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `ocache` | Caching (`nitro/cache`, `cache` route rules) |\n| `unenv` | Node.js polyfills for `node: false` builds (`build/_node-compat.ts`), installed on demand by `build/plugins/unenv.ts` |\n| `defu` | Config merging |\n| `pathe` | Path operations |\n| `consola` | Logging |\n| `env-runner` | Worker management |\n","AGENTS.md":"## Project Identity\n\nNitro is a framework-agnostic and deployment-agnostic server framework powered by [H3](https://github.com/h3js/h3) (v2), [UnJS] (https://github.com/unjs), and Vite | Rolldown | Rollup.\n\n## First-time Setup for Development\n\n- Run `corepack enable` to ensure `pnpm` is available.\n- Run `pnpm install` to install dependencies.\n- Run `pnpm build --stub` to prepare development mode.\n\n## Key Scripts\n\n- `pnpm build --stub` — Fast stub build (`obuild --stub`) for development.\n- `pnpm build` — Full build (`pnpm gen-presets && obuild`).\n- `pnpm lint` — Check lint and formatting (`oxlint` + `oxfmt --check`).\n- `pnpm fmt` — Auto-fix lint and formatting (`automd` + `oxlint --fix` + `oxfmt`).\n- `pnpm test` — Full pipeline: `lint && build && typecheck && test:rollup && test:rolldown` (runs vitest against both the rollup and rolldown builders).\n- `pnpm test:rollup` / `pnpm test:rolldown` — Run vitest against a single builder (`NITRO_BUILDER`).\n- `pnpm typecheck` — Type-check with the TypeScript native-preview compiler (`tsgo --noEmit --skipLibCheck`).\n\n**Always run** `pnpm fmt` and `pnpm typecheck` after making changes.\n\n## Repository Structure\n\n- `.github/` — GitHub Actions workflows.\n- `docs/` — Documentation site built with [UnDocs](https://github.com/unjs/undocs).\n- `examples/` — Example projects and integrations.\n- `src/` — Project source code.\n- `test/` — Unit, minimal, and end-to-end tests.\n\n### Code Structure\n\nProject source is centralized under `src/`:\n\n- `src/build` — Build logic (Vite | Rolldown | Rollup config, virtual templates in `src/build/virtual/`, plugins in `src/build/plugins/`).\n- `src/cli` — `nitro` CLI subcommands (each file in `src/cli/commands` is a command).\n- `src/config/` — Config defaults (`src/config/defaults.ts`) and resolvers/normalizers (`src/config/resolvers`).\n- `src/dev` — Development server logic (`app.ts`, `server.ts`, `vfs.ts`).\n- `src/prerender` — Prerender logic.\n- `src/presets` — Deployment presets and runtime entry.\n- `src/types` — Shared types.\n- `src/utils` — Internal utilities.\n- `src/runtime` — Runtime code that goes into the bundle (runtime and platform agnostic).\n\n### Why Changes in `src/` Are High-Impact\n\nCode in `src/` affects all Nitro users:\n\n- Changes in `src/runtime` are bundled and run across all deployment targets.\n- Changes in `src/build` affect build output and performance.\n- Changes in `src/presets` affect specific deployment platforms.\n- Changes in `src/config` affect default behavior.\n\nReview these changes carefully for backwards compatibility, bundle size, and cross-runtime support.\n\n## Code Patterns & Conventions\n\n- `pathe` — Cross-platform path operations (always prefer over `node:path`).\n- `defu` — Deep object merging and config defaults.\n- `consola` — Logging in build/dev code (use `nitro.logger` when available).\n- `unstorage` — Storage abstraction.\n\n### Optional Dependencies\n\nPackages that are only needed by some presets, builders, or opt-in features are imported on demand\nfrom the user project via `src/utils/dep.ts` (`ensureDep` / `importDep` / `isDepInstalled`), which\nresolves from `nitro.options.rootDir` and offers to install what is missing.\n\n- Don't add a `peerDependencies` entry. Add the package to `devDependencies` (for tests and types)\n  and to the `deps.json` manifest (supported `version` range, `reason` and install defaults, typed\n  in `src/utils/_deps.ts`), then import it with `importDep({ id, dir: nitro.options.rootDir, paths: nitro.options.deps?.paths })`\n  (`paths` honours the explicit packages of the `deps.paths` option, e.g. passed by frameworks).\n- Manifest entries are kept external in `build.config.ts`. A unit test checks that each range covers\n  the `devDependencies` version: after bumping one out of its range, run `pnpm sync-deps`.\n- `import type` from such a package is fine; only value imports must go through `utils/dep.ts`.\n- Optional dependencies of the libraries Nitro *bundles* (e.g. `jiti` for `c12`) cannot resolve from\n  `dist/`. Those are not in the manifest: they get a bundle-time alias to a shim in `src/shims/`\n  (one file per package), with a range within the one of the bundled library (`shims` in `deps.json`).\n- Nitro has no peer dependencies at all: `vite` is imported from the user project too\n  (`src/build/vite/_import.ts`). Its `DevEnvironment` subclass is therefore defined lazily, against\n  the class of the resolved instance (see `src/build/vite/dev.ts`).\n\n### Runtime Constraints\n\nCode in `src/runtime/` must be runtime-agnostic:\n\n- **Don't use Node.js-specific APIs** (unless behind runtime checks).\n- Prefer **Web APIs** (fetch, Request, Response, URL, etc.).\n- Only use `console` for logging (no `consola` in runtime).\n- Keep bundle size minimal and side-effect free.\n\n## Testing Strategy\n\n### Test Structure\n\nMain tests are defined in `test/tests.ts` and setup per each deployment provider in `test/presets` and run against `test/fixture` nitro app. Add new regression tests to `test/fixture`.\n\nOther tests:\n\n- **Unit** (`test/unit/`) — Isolated unit tests.\n- **Minimal** (`test/minimal/`) — Smallest bundle output.\n\n### Testing Requirements\n\n- Run `pnpm run test` before submitting.\n- **Bug fixes MUST include a failing test first** — add regression tests to `test/fixture/` and make sure test script fails before attempting the fix and resolves after.\n- Keep tests deterministic and environment-independent.\n\n## Working with Presets\n\nEach preset in `src/presets/` defines deployment target behavior:\n\n- Runtime logic and entry is in `src/presets/<name>/runtime`\n- Preset config and utils (build time) are in `src/presets/<name>/*.ts`.\n\n## Development Workflow\n\n### Making Changes\n\n1. Make changes in `src/`.\n2. Run `pnpm stub` if you changed build logic.\n3. Test with `pnpm test`.\n4. Run `pnpm fmt`.\n5. Run `pnpm typecheck`.\n6. Run `pnpm test:rollup` and/or `pnpm test:rolldown` to run vitest against a specific builder.\n\n## Contribution Principles\n\n- Prefer **minimal, targeted changes** over large refactors.\n- Avoid introducing new dependencies unless strictly necessary.\n  Add them to `devDependencies` unless they are required in runtime logic.\n- Be mindful of **bundle size**, startup cost, and runtime overhead.\n- Maintain **backwards compatibility** unless explicitly instructed otherwise.\n- Batch multiple related edits together. Avoid sequential micro-changes.\n- Never modify files outside the scope of the requested change.\n\n## Common Gotchas\n\n- **Don't use Node.js-specific APIs in `src/runtime/`** — Code runs in multiple runtimes (Node, workers, edge).\n- **Virtual modules must be registered** in `src/build/virtual/_all.ts` (one template per file under `src/build/virtual/`).\n- **CLI commands** are in `src/cli/commands/` — Each file exports a command definition.\n- **Runtime size matters** — Check bundle impact with `pnpm build`.\n- **Use `pathe` not `node:path`** — Ensures cross-platform compatibility.\n- **No peer dependencies** — Optional packages are imported on demand via `src/utils/dep.ts`.\n\n## Error & Logging Guidelines\n\n- Prefer explicit errors over silent failures.\n- Use `nitro.logger` in build/dev code, `consola` as fallback.\n- Use `console` only in `src/runtime/` code.\n- Use warnings for recoverable situations; throw for invalid states.\n- Include actionable context in error messages.\n\n## Documentation Requirements\n\n- Update `docs/` for user-facing changes.\n- Update types and JSDoc for API changes.\n- Examples in `examples/` should reflect best practices and be added for new integrations.\n- Add migration notes for breaking changes.\n\n## Code Conventions\n\n- Use **ESM** and modern JavaScript; use explicit extensions (`.ts`, `.mjs`) in imports.\n- For `.json` imports, use `with { \"type\": \"json\" }`.\n- Avoid barrel files (`index.ts` re-exports); import directly from specific modules.\n- Place non-exported/internal helpers at the end of the file.\n- For multi-arg functions, use an options object as the second parameter.\n- Split logic across files; avoid long single-file modules (>200 LoC). Use `_*` prefix for internal files.\n- Prefer **Web APIs** over Node.js APIs where possible.\n- Do not add comments explaining what the line does unless prompted.\n- Before adding new code, study surrounding patterns, naming conventions, and architectural decisions.\n- Use existing UnJS utilities and dependencies before adding new packages.\n- Keep runtime code minimal and fast.\n\n## Commit Conventions\n\n- Use **semantic commit messages**, lower-case (e.g., `fix(cli): resolve path issue`).\n- Prefer to include scope (e.g., `feat(runtime):`, `fix(build):`).\n- Add a short description on the second line when helpful.\n\n## Detailed References\n\nFor deeper context, see `.agents/`:\n\n- [`.agents/architecture.md`](.agents/architecture.md) — Full architecture: core instance, build system, config resolution, virtual modules, runtime internals, dev server, routing, key libraries.\n- [`.agents/presets.md`](.agents/presets.md) — All presets (multiple deployment targets + internal `_nitro`/`_static`), preset structure, how to create presets, resolution logic.\n- [`.agents/testing.md`](.agents/testing.md) — Test structure, how tests work, adding regression tests, running tests.\n- [`.agents/vite.md`](.agents/vite.md) — Vite build system: plugin architecture (6 sub-plugins), environments API, dev server integration, production build stages, bundler config, HMR, runtime worker.\n- [`.agents/docs.md`](.agents/docs.md) — Docs site: UnDocs structure, the `.docs/` theme layer (imports, styling tokens, content queries), MDC blocks, and content conventions (preset naming, import paths, H3 v2 patterns, common mistakes).\n\nH3 v2 updated docs is at `node_modules/h3/dist/docs/README.md`\n","examples/plugins/tsconfig.json":"{\n  \"extends\": \"nitro/tsconfig\"\n}\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"## Project Identity\n\nNitro is a framework-agnostic and deployment-agnostic server framework powered by [H3](https://github.com/h3js/h3) (v2), [UnJS] (https://github.com/unjs), and Vite | Rolldown | Rollup.\n\n## First-time Setup for Development\n\n- Run `corepack enable` to ensure `pnpm` is available.\n- Run `pnpm install` to install dependencies.\n- Run `pnpm build --stub` to prepare development mode.\n\n## Key Scripts\n\n- `pnpm build --stub` — Fast stub build (`obuild --stub`) for development.\n- `pnpm build` — Full build (`pnpm gen-presets && obuild`).\n- `pnpm lint` — Check lint and formatting (`oxlint` + `oxfmt --check`).\n- `pnpm fmt` — Auto-fix lint and formatting (`automd` + `oxlint --fix` + `oxfmt`).\n- `pnpm test` — Full pipeline: `lint && build && typecheck && test:rollup && test:rolldown` (runs vitest against both the rollup and rolldown builders).\n- `pnpm test:rollup` / `pnpm test:rolldown` — Run vitest against a single builder (`NITRO_BUILDER`).\n- `pnpm typecheck` — Type-check with the TypeScript native-preview compiler (`tsgo --noEmit --skipLibCheck`).\n\n**Always run** `pnpm fmt` and `pnpm typecheck` after making changes.\n\n## Repository Structure\n\n- `.github/` — GitHub Actions workflows.\n- `docs/` — Documentation site built with [UnDocs](https://github.com/unjs/undocs).\n- `examples/` — Example projects and integrations.\n- `src/` — Project source code.\n- `test/` — Unit, minimal, and end-to-end tests.\n\n### Code Structure\n\nProject source is centralized under `src/`:\n\n- `src/build` — Build logic (Vite | Rolldown | Rollup config, virtual templates in `src/build/virtual/`, plugins in `src/build/plugins/`).\n- `src/cli` — `nitro` CLI subcommands (each file in `src/cli/commands` is a command).\n- `src/config/` — Config defaults (`src/config/defaults.ts`) and resolvers/normalizers (`src/config/resolvers`).\n- `src/dev` — Development server logic (`app.ts`, `server.ts`, `vfs.ts`).\n- `src/prerender` — Prerender logic.\n- `src/presets` — Deployment presets and runtime entry.\n- `src/types` — Shared types.\n- `src/utils` — Internal utilities.\n- `src/runtime` — Runtime code that goes into the bundle (runtime and platform agnostic).\n\n### Why Changes in `src/` Are High-Impact\n\nCode in `src/` affects all Nitro users:\n\n- Changes in `src/runtime` are bundled and run across all deployment targets.\n- Changes in `src/build` affect build output and performance.\n- Changes in `src/presets` affect specific deployment platforms.\n- Changes in `src/config` affect default behavior.\n\nReview these changes carefully for backwards compatibility, bundle size, and cross-runtime support.\n\n## Code Patterns & Conventions\n\n- `pathe` — Cross-platform path operations (always prefer over `node:path`).\n- `defu` — Deep object merging and config defaults.\n- `consola` — Logging in build/dev code (use `nitro.logger` when available).\n- `unstorage` — Storage abstraction.\n\n### Optional Dependencies\n\nPackages that are only needed by some presets, builders, or opt-in features are imported on demand\nfrom the user project via `src/utils/dep.ts` (`ensureDep` / `importDep` / `isDepInstalled`), which\nresolves from `nitro.options.rootDir` and offers to install what is missing.\n\n- Don't add a `peerDependencies` entry. Add the package to `devDependencies` (for tests and types)\n  and to the `deps.json` manifest (supported `version` range, `reason` and install defaults, typed\n  in `src/utils/_deps.ts`), then import it with `importDep({ id, dir: nitro.options.rootDir, paths: nitro.options.deps?.paths })`\n  (`paths` honours the explicit packages of the `deps.paths` option, e.g. passed by frameworks).\n- Manifest entries are kept external in `build.config.ts`. A unit test checks that each range covers\n  the `devDependencies` version: after bumping one out of its range, run `pnpm sync-deps`.\n- `import type` from such a package is fine; only value imports must go through `utils/dep.ts`.\n- Optional dependencies of the libraries Nitro *bundles* (e.g. `jiti` for `c12`) cannot resolve from\n  `dist/`. Those are not in the manifest: they get a bundle-time alias to a shim in `src/shims/`\n  (one file per package), with a range within the one of the bundled library (`shims` in `deps.json`).\n- Nitro has no peer dependencies at all: `vite` is imported from the user project too\n  (`src/build/vite/_import.ts`). Its `DevEnvironment` subclass is therefore defined lazily, against\n  the class of the resolved instance (see `src/build/vite/dev.ts`).\n\n### Runtime Constraints\n\nCode in `src/runtime/` must be runtime-agnostic:\n\n- **Don't use Node.js-specific APIs** (unless behind runtime checks).\n- Prefer **Web APIs** (fetch, Request, Response, URL, etc.).\n- Only use `console` for logging (no `consola` in runtime).\n- Keep bundle size minimal and side-effect free.\n\n## Testing Strategy\n\n### Test Structure\n\nMain tests are defined in `test/tests.ts` and setup per each deployment provider in `test/presets` and run against `test/fixture` nitro app. Add new regression tests to `test/fixture`.\n\nOther tests:\n\n- **Unit** (`test/unit/`) — Isolated unit tests.\n- **Minimal** (`test/minimal/`) — Smallest bundle output.\n\n### Testing Requirements\n\n- Run `pnpm run test` before submitting.\n- **Bug fixes MUST include a failing test first** — add regression tests to `test/fixture/` and make sure test script fails before attempting the fix and resolves after.\n- Keep tests deterministic and environment-independent.\n\n## Working with Presets\n\nEach preset in `src/presets/` defines deployment target behavior:\n\n- Runtime logic and entry is in `src/presets/<name>/runtime`\n- Preset config and utils (build time) are in `src/presets/<name>/*.ts`.\n\n## Development Workflow\n\n### Making Changes\n\n1. Make changes in `src/`.\n2. Run `pnpm stub` if you changed build logic.\n3. Test with `pnpm test`.\n4. Run `pnpm fmt`.\n5. Run `pnpm typecheck`.\n6. Run `pnpm test:rollup` and/or `pnpm test:rolldown` to run vitest against a specific builder.\n\n## Contribution Principles\n\n- Prefer **minimal, targeted changes** over large refactors.\n- Avoid introducing new dependencies unless strictly necessary.\n  Add them to `devDependencies` unless they are required in runtime logic.\n- Be mindful of **bundle size**, startup cost, and runtime overhead.\n- Maintain **backwards compatibility** unless explicitly instructed otherwise.\n- Batch multiple related edits together. Avoid sequential micro-changes.\n- Never modify files outside the scope of the requested change.\n\n## Common Gotchas\n\n- **Don't use Node.js-specific APIs in `src/runtime/`** — Code runs in multiple runtimes (Node, workers, edge).\n- **Virtual modules must be registered** in `src/build/virtual/_all.ts` (one template per file under `src/build/virtual/`).\n- **CLI commands** are in `src/cli/commands/` — Each file exports a command definition.\n- **Runtime size matters** — Check bundle impact with `pnpm build`.\n- **Use `pathe` not `node:path`** — Ensures cross-platform compatibility.\n- **No peer dependencies** — Optional packages are imported on demand via `src/utils/dep.ts`.\n\n## Error & Logging Guidelines\n\n- Prefer explicit errors over silent failures.\n- Use `nitro.logger` in build/dev code, `consola` as fallback.\n- Use `console` only in `src/runtime/` code.\n- Use warnings for recoverable situations; throw for invalid states.\n- Include actionable context in error messages.\n\n## Documentation Requirements\n\n- Update `docs/` for user-facing changes.\n- Update types and JSDoc for API changes.\n- Examples in `examples/` should reflect best practices and be added for new integrations.\n- Add migration notes for breaking changes.\n\n## Code Conventions\n\n- Use **ESM** and modern JavaScript; use explicit extensions (`.ts`, `.mjs`) in imports.\n- For `.json` imports, use `with { \"type\": \"json\" }`.\n- Avoid barrel files (`index.ts` re-exports); import directly from specific modules.\n- Place non-exported/internal helpers at the end of the file.\n- For multi-arg functions, use an options object as the second parameter.\n- Split logic across files; avoid long single-file modules (>200 LoC). Use `_*` prefix for internal files.\n- Prefer **Web APIs** over Node.js APIs where possible.\n- Do not add comments explaining what the line does unless prompted.\n- Before adding new code, study surrounding patterns, naming conventions, and architectural decisions.\n- Use existing UnJS utilities and dependencies before adding new packages.\n- Keep runtime code minimal and fast.\n\n## Commit Conventions\n\n- Use **semantic commit messages**, lower-case (e.g., `fix(cli): resolve path issue`).\n- Prefer to include scope (e.g., `feat(runtime):`, `fix(build):`).\n- Add a short description on the second line when helpful.\n\n## Detailed References\n\nFor deeper context, see `.agents/`:\n\n- [`.agents/architecture.md`](.agents/architecture.md) — Full architecture: core instance, build system, config resolution, virtual modules, runtime internals, dev server, routing, key libraries.\n- [`.agents/presets.md`](.agents/presets.md) — All presets (multiple deployment targets + internal `_nitro`/`_static`), preset structure, how to create presets, resolution logic.\n- [`.agents/testing.md`](.agents/testing.md) — Test structure, how tests work, adding regression tests, running tests.\n- [`.agents/vite.md`](.agents/vite.md) — Vite build system: plugin architecture (6 sub-plugins), environments API, dev server integration, production build stages, bundler config, HMR, runtime worker.\n- [`.agents/docs.md`](.agents/docs.md) — Docs site: UnDocs structure, the `.docs/` theme layer (imports, styling tokens, content queries), MDC blocks, and content conventions (preset naming, import paths, H3 v2 patterns, common mistakes).\n\nH3 v2 updated docs is at `node_modules/h3/dist/docs/README.md`\n","isInternal":false,"tokens":2405,"sizeBytes":9769},{"name":"architecture.md","path":".agents/architecture.md","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/.agents/architecture.md","title":".agents - System Architecture & Module Boundaries","category":"project-spec","format":"markdown","content":"# Nitro Architecture Deep Dive\n\n## Core Instance (`src/nitro.ts`)\n\n`createNitro(config, opts)` creates the main context with:\n- `options: NitroOptions` — Resolved configuration\n- `hooks: Hookable<NitroHooks>` — Build lifecycle hooks\n- `vfs: Map<string, { render }>` — Virtual file system\n- `routing: { routes, routeRules, globalMiddleware, routedMiddleware }`\n- `scannedHandlers: NitroEventHandler[]`\n- `logger: ConsolaInstance`\n- `updateConfig(config)` — Hot-reload config\n- `close()` — Cleanup\n\n**Setup flow:**\n1. Load options via `loadOptions()`\n2. Install modules via `installModules()`\n3. Init routing via `initNitroRouting()`\n4. Scan handlers/plugins/tasks via `scanAndSyncOptions()`\n5. Setup hooks\n\n## Entry Points\n\n- `src/builder.ts` — Main public API: `createNitro()`, `build()`, `createDevServer()`, `prerender()`, `copyPublicAssets()`, `prepare()`, `runTask()`, `listTasks()`\n- `src/vite.ts` — Vite plugin export from `src/build/vite/plugin.ts`\n\n## Build System (`src/build/`)\n\n**Builder dispatch** (`build/build.ts`): delegates to `rollup`, `rolldown`, or `vite` based on `nitro.options.builder`.\n\n**Builder selection** (resolved in `config/resolvers/builder.ts`):\n- Check `NITRO_BUILDER` env var\n- Auto-detect: `vite` when a `vite.config` uses `nitro()`, otherwise `rolldown`\n- No builder package is a dependency of Nitro: they are imported from the user project and installed on demand (`rolldown` via `build/rolldown/_import.ts`)\n- Dev without `rolldown` (and no `rollupConfig`/`rolldownConfig`) falls back to `builder: false`\n\n**Base config** (`build/config.ts`):\n- Extensions: `.ts`, `.mjs`, `.js`, `.json`, `.node`, `.tsx`, `.jsx`\n- Import.meta replacements (`import.meta.dev`, `import.meta.preset`, etc.)\n- Node.js compatibility aliases (`unenv` targets go to the unenv plugin)\n- External dependency patterns\n\n**Plugins** (`build/plugins.ts`):\n1. Virtual modules — renders from `build/virtual/`\n2. Unenv — resolves `unenv/*` polyfills, installing `unenv` on demand\n3. WASM loader — unwasm\n4. Server main injection — `globalThis.__server_main__`\n5. Raw imports — `?raw` suffix\n6. Route meta — OpenAPI metadata\n7. Replace plugin — variable substitution\n8. Externals plugin — Node.js native resolution\n9. Sourcemap minify (optional)\n\nUser `buildPlugins` are added around this list by `withBuildPlugins()` (`enforce: \"pre\"` before, the others after the builder's own plugins). With `builder: false`, they are appended to the env-runner plugins (`build/unbundled/plugins.ts`).\n\n**Virtual modules** (`build/virtual/`, 14 templates):\nAll prefixed `#nitro/virtual/<name>`:\n- `routing.ts` — Compiled router matcher\n- `plugins.ts` — Plugin registry\n- `error-handler.ts` — Error handler\n- `public-assets.ts` — Public asset metadata\n- `server-assets.ts` — Server asset metadata\n- `runtime-config.ts` — Runtime config object\n- `database.ts` — Database setup\n- `kv.ts` — KV storage backends\n- `tasks.ts` — Task registry\n- `polyfills.ts` — Env polyfills\n- `feature-flags.ts` — Feature detection\n- `routing-meta.ts` — Route metadata (OpenAPI)\n- `renderer-template.ts` — SSR renderer\n- `_all.ts` — Aggregator\n\n## Configuration System (`src/config/`)\n\n**Loader** (`config/loader.ts`): `loadOptions(config, opts)`\n1. Merge with defaults (`NitroDefaults`)\n2. Load c12 config files (`nitro.config.ts`, `package.json.nitro`, etc.)\n3. Resolve preset\n4. Run config resolvers sequentially\n\n**Resolvers** (`config/resolvers/`):\n`compatibility`, `tsconfig`, `paths`, `imports`, `route-rules`, `database`, `export-conditions`, `runtime-config`, `open-api`, `url`, `assets`, `storage`, `error`, `unenv`, `builder`\n\n**Defaults** (`config/defaults.ts`): All NitroConfig defaults.\n\n## Runtime (`src/runtime/`)\n\n**Internal** (`runtime/internal/`):\n- `app.ts` — NitroApp creation, H3 app setup\n- `cache.ts` — Response caching\n- `context.ts` — Async context\n- `route-rule-handlers.ts` — Nitro's rule handlers for the compiled matcher: a `cache` handler bound to Nitro's cache runtime. The built-ins (headers, redirect, proxy, cors) and rule matching/normalization live in [`h3/rules`](https://h3.dev/guide/rules).\n- `static.ts` — Static file serving\n- `task.ts` — Task execution\n- `plugin.ts` — Plugin helpers\n- `runtime-config.ts` — Config getter\n\n**Public exports**: `runtime/app.ts` (`defineConfig()`), `runtime/nitro.ts` (`serverFetch()`), `runtime/cache.ts`, `runtime/task.ts`, `runtime/kv.ts`, etc.\n\n## Dev Server (`src/dev/`)\n\n- `dev/server.ts` — `createDevServer()` (public `NitroDevServer` interface, internal `DevServer` class): Worker management via `env-runner`, restart on failure (max 3 retries), WebSocket support, VFS debug endpoint (`/_vfs/**`)\n- `dev/app.ts` — `NitroDevApp`: H3 app with error handling, static serving with compression, dev proxy\n\n## Prerender (`src/prerender/`)\n\n- `prerender/prerender.ts` — Main flow: parse routes → build prerenderer (preset: `nitro-prerender`) → execute in parallel → link crawling → write to disk → compress\n- `prerender/utils.ts` — `extractLinks()`, `matchesIgnorePattern()`, `formatPrerenderRoute()`\n\n## Routing & Scanning (`src/routing.ts`, `src/scan.ts`)\n\n**Scanning**: Discovers routes, middleware, plugins, tasks, modules from filesystem.\n\nRoute file conventions:\n- `routes/index.ts` → `GET /`\n- `routes/users/[id].ts` → `GET /users/:id`\n- `routes/users/[...slug].ts` → `GET /users/:slug(.*)` (also matches `/users`)\n- `api/users.post.ts` → `POST /api/users`\n- `.dev`/`.prod`/`.prerender` suffixes for environment filtering\n\n**Router** (`Router` class): Based on `rou3`, compiles to optimized string matcher, supports method routing + env conditions.\n\n## Presets (`src/presets/`)\n\nSeveral deployment-target presets (+ internal `_nitro`/`_static`); see `.agents/presets.md`. Structure per preset:\n\n```\npresets/<name>/\n├── preset.ts        # defineNitroPreset()\n├── runtime/         # Runtime entry (bundled)\n├── types.ts         # Types (optional)\n├── utils.ts         # Build-time utils (optional)\n└── unenv/           # Env overrides (optional)\n```\n\nKey presets: `standard`, `node` (server/middleware/cluster), `cloudflare` (pages/workers), `vercel`, `netlify`, `aws-lambda`, `deno`, `firebase`, `azure`, `bun`\n\nResolution: `presets/_resolve.ts` handles aliases, dev/prod, compat dates, static hosting.\n\n## CLI (`src/cli/`)\n\nUses `citty` with lazy-loaded commands: `dev`, `build`, `deploy`, `preview`, `prepare`, `task`, `docs`.\n\n## Key Libraries\n\n| Library | Purpose |\n|---------|---------|\n| `h3` | HTTP framework |\n| `rou3` | Route matching |\n| `c12` | Config loading |\n| `citty` | CLI framework |\n| `hookable` | Hook system |\n| `unstorage` | Storage abstraction (`nitro/kv`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `db0` | SQL database layer (`nitro/database`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `ocache` | Caching (`nitro/cache`, `cache` route rules) |\n| `unenv` | Node.js polyfills for `node: false` builds (`build/_node-compat.ts`), installed on demand by `build/plugins/unenv.ts` |\n| `defu` | Config merging |\n| `pathe` | Path operations |\n| `consola` | Logging |\n| `env-runner` | Worker management |\n","isInternal":false,"tokens":1973,"sizeBytes":7232},{"name":"package.json","path":"examples/plugins/package.json","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/examples/plugins/package.json","title":"Plugins Skill","category":"anthropic-skill","format":"json","content":"{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"nitro dev\",\n    \"build\": \"nitro build\"\n  },\n  \"devDependencies\": {\n    \"nitro\": \"latest\"\n  }\n}\n","frontmatter":{"type":"module","scripts":{"dev":"nitro dev","build":"nitro build"},"devDependencies":{"nitro":"latest"}},"isInternal":false,"tokens":50,"sizeBytes":144},{"name":"tsconfig.json","path":"examples/plugins/tsconfig.json","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/examples/plugins/tsconfig.json","title":"Plugins Skill","category":"anthropic-skill","format":"json","content":"{\n  \"extends\": \"nitro/tsconfig\"\n}\n","frontmatter":{"extends":"nitro/tsconfig"},"isInternal":false,"tokens":12,"sizeBytes":34},{"name":"copilot-instructions.md","path":".github/copilot-instructions.md","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/.github/copilot-instructions.md","title":"GitHub Copilot Instructions","category":"copilot-instructions","format":"markdown","content":"@../AGENTS.md\n\nRefer to [AGENTS.md](../AGENTS.md) for project instructions.\n","isInternal":false,"tokens":22,"sizeBytes":76},{"name":"README.md","path":"examples/plugins/README.md","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/examples/plugins/README.md","title":"plugins Documentation","category":"plugin-manifest","format":"markdown","content":"Plugins let you hook into Nitro's runtime lifecycle. This example shows a plugin that modifies the `Content-Type` header on every response. Create files in `server/plugins/` and they're automatically loaded at startup.\n\n## Defining a Plugin\n\n```ts [server/plugins/test.ts]\nimport { definePlugin } from \"nitro\";\nimport { useNitroHooks } from \"nitro/app\";\n\nexport default definePlugin(() => {\n  const hooks = useNitroHooks();\n  hooks.hook(\"response\", (res) => {\n    res.headers.set(\"content-type\", \"html; charset=utf-8\");\n  });\n});\n```\n\nThe plugin uses `useNitroHooks()` to access the hooks system, then registers a `response` hook that runs after every request and receives the outgoing `Response`. Here it sets the content type to HTML, but you could log requests, add security headers, or modify responses in any way.\n\n## Main Handler\n\n```ts [server.ts]\nimport { defineHandler } from \"nitro\";\n\nexport default defineHandler(() => \"<h1>Hello Nitro!</h1>\");\n```\n\nThe handler returns HTML without setting a content type. The plugin automatically adds the correct `Content-Type: html; charset=utf-8` header to the response.\n","isInternal":false,"tokens":260,"sizeBytes":1120},{"name":"maintainer.agent.md","path":".github/agents/maintainer.agent.md","rawUrl":"https://raw.githubusercontent.com/nitrojs/nitro/HEAD/.github/agents/maintainer.agent.md","title":"Maintainer","category":"subagent-persona","format":"markdown","content":"---\nname: Maintainer\ndescription: >\n  Nitro project maintainer agent. Handles bug fixes, feature implementation,\n  code review, and contributions following project conventions. Understands the\n  build system, runtime constraints, deployment presets, and testing strategy.\ntools:\n  - \"*\"\n---\n\nYou are a maintainer of the Nitro project. Follow all instructions in [AGENTS.md](../../AGENTS.md) strictly.\n\nFor deeper architectural context, refer to the `.agents/` directory:\n\n- `.agents/architecture.md` — Core architecture, build system, config resolution, virtual modules, runtime internals.\n- `.agents/presets.md` — Deployment presets, preset structure, resolution logic.\n- `.agents/testing.md` — Test structure, adding regression tests, running tests.\n- `.agents/vite.md` — Vite build system, plugin architecture, dev server, HMR.\n- `.agents/docs.md` — Documentation conventions, H3 v2 API patterns.\n\nH3 v2 docs are at `node_modules/h3/dist/docs/README.md`.\n\n## Key principles\n\n- Prefer minimal, targeted changes over large refactors.\n- Code in `src/runtime/` must be runtime-agnostic (Web APIs, no Node.js-specific APIs).\n- Use `pathe` instead of `node:path`.\n- Use existing UnJS utilities (`defu`, `consola`, `unstorage`) before adding new packages.\n- Bug fixes MUST include a failing regression test first.\n- Always run `pnpm fmt` and `pnpm typecheck` after changes.\n- Use semantic commit messages with scope (e.g., `fix(runtime): ...`).\n","frontmatter":{"name":"Maintainer","description":"Nitro project maintainer agent. Handles bug fixes, feature implementation, code review, and contributions following project conventions. Understands the build system, runtime constraints, deployment presets, and testing strategy.\n","tools":["*"]},"isInternal":false,"tokens":335,"sizeBytes":1451}],"systemPromptSnippet":"<yakaai_skills repo=\"nitrojs/nitro\">\n<!-- File: AGENTS.md (Tokens: ~2405 | Category: root-instruction) -->\n## Project Identity\n\nNitro is a framework-agnostic and deployment-agnostic server framework powered by [H3](https://github.com/h3js/h3) (v2), [UnJS] (https://github.com/unjs), and Vite | Rolldown | Rollup.\n\n## First-time Setup for Development\n\n- Run `corepack enable` to ensure `pnpm` is available.\n- Run `pnpm install` to install dependencies.\n- Run `pnpm build --stub` to prepare development mode.\n\n## Key Scripts\n\n- `pnpm build --stub` — Fast stub build (`obuild --stub`) for development.\n- `pnpm build` — Full build (`pnpm gen-presets && obuild`).\n- `pnpm lint` — Check lint and formatting (`oxlint` + `oxfmt --check`).\n- `pnpm fmt` — Auto-fix lint and formatting (`automd` + `oxlint --fix` + `oxfmt`).\n- `pnpm test` — Full pipeline: `lint && build && typecheck && test:rollup && test:rolldown` (runs vitest against both the rollup and rolldown builders).\n- `pnpm test:rollup` / `pnpm test:rolldown` — Run vitest against a single builder (`NITRO_BUILDER`).\n- `pnpm typecheck` — Type-check with the TypeScript native-preview compiler (`tsgo --noEmit --skipLibCheck`).\n\n**Always run** `pnpm fmt` and `pnpm typecheck` after making changes.\n\n## Repository Structure\n\n- `.github/` — GitHub Actions workflows.\n- `docs/` — Documentation site built with [UnDocs](https://github.com/unjs/undocs).\n- `examples/` — Example projects and integrations.\n- `src/` — Project source code.\n- `test/` — Unit, minimal, and end-to-end tests.\n\n### Code Structure\n\nProject source is centralized under `src/`:\n\n- `src/build` — Build logic (Vite | Rolldown | Rollup config, virtual templates in `src/build/virtual/`, plugins in `src/build/plugins/`).\n- `src/cli` — `nitro` CLI subcommands (each file in `src/cli/commands` is a command).\n- `src/config/` — Config defaults (`src/config/defaults.ts`) and resolvers/normalizers (`src/config/resolvers`).\n- `src/dev` — Development server logic (`app.ts`, `server.ts`, `vfs.ts`).\n- `src/prerender` — Prerender logic.\n- `src/presets` — Deployment presets and runtime entry.\n- `src/types` — Shared types.\n- `src/utils` — Internal utilities.\n- `src/runtime` — Runtime code that goes into the bundle (runtime and platform agnostic).\n\n### Why Changes in `src/` Are High-Impact\n\nCode in `src/` affects all Nitro users:\n\n- Changes in `src/runtime` are bundled and run across all deployment targets.\n- Changes in `src/build` affect build output and performance.\n- Changes in `src/presets` affect specific deployment platforms.\n- Changes in `src/config` affect default behavior.\n\nReview these changes carefully for backwards compatibility, bundle size, and cross-runtime support.\n\n## Code Patterns & Conventions\n\n- `pathe` — Cross-platform path operations (always prefer over `node:path`).\n- `defu` — Deep object merging and config defaults.\n- `consola` — Logging in build/dev code (use `nitro.logger` when available).\n- `unstorage` — Storage abstraction.\n\n### Optional Dependencies\n\nPackages that are only needed by some presets, builders, or opt-in features are imported on demand\nfrom the user project via `src/utils/dep.ts` (`ensureDep` / `importDep` / `isDepInstalled`), which\nresolves from `nitro.options.rootDir` and offers to install what is missing.\n\n- Don't add a `peerDependencies` entry. Add the package to `devDependencies` (for tests and types)\n  and to the `deps.json` manifest (supported `version` range, `reason` and install defaults, typed\n  in `src/utils/_deps.ts`), then import it with `importDep({ id, dir: nitro.options.rootDir, paths: nitro.options.deps?.paths })`\n  (`paths` honours the explicit packages of the `deps.paths` option, e.g. passed by frameworks).\n- Manifest entries are kept external in `build.config.ts`. A unit test checks that each range covers\n  the `devDependencies` version: after bumping one out of its range, run `pnpm sync-deps`.\n- `import type` from such a package is fine; only value imports must go through `utils/dep.ts`.\n- Optional dependencies of the libraries Nitro *bundles* (e.g. `jiti` for `c12`) cannot resolve from\n  `dist/`. Those are not in the manifest: they get a bundle-time alias to a shim in `src/shims/`\n  (one file per package), with a range within the one of the bundled library (`shims` in `deps.json`).\n- Nitro has no peer dependencies at all: `vite` is imported from the user project too\n  (`src/build/vite/_import.ts`). Its `DevEnvironment` subclass is therefore defined lazily, against\n  the class of the resolved instance (see `src/build/vite/dev.ts`).\n\n### Runtime Constraints\n\nCode in `src/runtime/` must be runtime-agnostic:\n\n- **Don't use Node.js-specific APIs** (unless behind runtime checks).\n- Prefer **Web APIs** (fetch, Request, Response, URL, etc.).\n- Only use `console` for logging (no `consola` in runtime).\n- Keep bundle size minimal and side-effect free.\n\n## Testing Strategy\n\n### Test Structure\n\nMain tests are defined in `test/tests.ts` and setup per each deployment provider in `test/presets` and run against `test/fixture` nitro app. Add new regression tests to `test/fixture`.\n\nOther tests:\n\n- **Unit** (`test/unit/`) — Isolated unit tests.\n- **Minimal** (`test/minimal/`) — Smallest bundle output.\n\n### Testing Requirements\n\n- Run `pnpm run test` before submitting.\n- **Bug fixes MUST include a failing test first** — add regression tests to `test/fixture/` and make sure test script fails before attempting the fix and resolves after.\n- Keep tests deterministic and environment-independent.\n\n## Working with Presets\n\nEach preset in `src/presets/` defines deployment target behavior:\n\n- Runtime logic and entry is in `src/presets/<name>/runtime`\n- Preset config and utils (build time) are in `src/presets/<name>/*.ts`.\n\n## Development Workflow\n\n### Making Changes\n\n1. Make changes in `src/`.\n2. Run `pnpm stub` if you changed build logic.\n3. Test with `pnpm test`.\n4. Run `pnpm fmt`.\n5. Run `pnpm typecheck`.\n6. Run `pnpm test:rollup` and/or `pnpm test:rolldown` to run vitest against a specific builder.\n\n## Contribution Principles\n\n- Prefer **minimal, targeted changes** over large refactors.\n- Avoid introducing new dependencies unless strictly necessary.\n  Add them to `devDependencies` unless they are required in runtime logic.\n- Be mindful of **bundle size**, startup cost, and runtime overhead.\n- Maintain **backwards compatibility** unless explicitly instructed otherwise.\n- Batch multiple related edits together. Avoid sequential micro-changes.\n- Never modify files outside the scope of the requested change.\n\n## Common Gotchas\n\n- **Don't use Node.js-specific APIs in `src/runtime/`** — Code runs in multiple runtimes (Node, workers, edge).\n- **Virtual modules must be registered** in `src/build/virtual/_all.ts` (one template per file under `src/build/virtual/`).\n- **CLI commands** are in `src/cli/commands/` — Each file exports a command definition.\n- **Runtime size matters** — Check bundle impact with `pnpm build`.\n- **Use `pathe` not `node:path`** — Ensures cross-platform compatibility.\n- **No peer dependencies** — Optional packages are imported on demand via `src/utils/dep.ts`.\n\n## Error & Logging Guidelines\n\n- Prefer explicit errors over silent failures.\n- Use `nitro.logger` in build/dev code, `consola` as fallback.\n- Use `console` only in `src/runtime/` code.\n- Use warnings for recoverable situations; throw for invalid states.\n- Include actionable context in error messages.\n\n## Documentation Requirements\n\n- Update `docs/` for user-facing changes.\n- Update types and JSDoc for API changes.\n- Examples in `examples/` should reflect best practices and be added for new integrations.\n- Add migration notes for breaking changes.\n\n## Code Conventions\n\n- Use **ESM** and modern JavaScript; use explicit extensions (`.ts`, `.mjs`) in imports.\n- For `.json` imports, use `with { \"type\": \"json\" }`.\n- Avoid barrel files (`index.ts` re-exports); import directly from specific modules.\n- Place non-exported/internal helpers at the end of the file.\n- For multi-arg functions, use an options object as the second parameter.\n- Split logic across files; avoid long single-file modules (>200 LoC). Use `_*` prefix for internal files.\n- Prefer **Web APIs** over Node.js APIs where possible.\n- Do not add comments explaining what the line does unless prompted.\n- Before adding new code, study surrounding patterns, naming conventions, and architectural decisions.\n- Use existing UnJS utilities and dependencies before adding new packages.\n- Keep runtime code minimal and fast.\n\n## Commit Conventions\n\n- Use **semantic commit messages**, lower-case (e.g., `fix(cli): resolve path issue`).\n- Prefer to include scope (e.g., `feat(runtime):`, `fix(build):`).\n- Add a short description on the second line when helpful.\n\n## Detailed References\n\nFor deeper context, see `.agents/`:\n\n- [`.agents/architecture.md`](.agents/architecture.md) — Full architecture: core instance, build system, config resolution, virtual modules, runtime internals, dev server, routing, key libraries.\n- [`.agents/presets.md`](.agents/presets.md) — All presets (multiple deployment targets + internal `_nitro`/`_static`), preset structure, how to create presets, resolution logic.\n- [`.agents/testing.md`](.agents/testing.md) — Test structure, how tests work, adding regression tests, running tests.\n- [`.agents/vite.md`](.agents/vite.md) — Vite build system: plugin architecture (6 sub-plugins), environments API, dev server integration, production build stages, bundler config, HMR, runtime worker.\n- [`.agents/docs.md`](.agents/docs.md) — Docs site: UnDocs structure, the `.docs/` theme layer (imports, styling tokens, content queries), MDC blocks, and content conventions (preset naming, import paths, H3 v2 patterns, common mistakes).\n\nH3 v2 updated docs is at `node_modules/h3/dist/docs/README.md`\n\n<!-- File: .agents/architecture.md (Tokens: ~1973 | Category: project-spec) -->\n# Nitro Architecture Deep Dive\n\n## Core Instance (`src/nitro.ts`)\n\n`createNitro(config, opts)` creates the main context with:\n- `options: NitroOptions` — Resolved configuration\n- `hooks: Hookable<NitroHooks>` — Build lifecycle hooks\n- `vfs: Map<string, { render }>` — Virtual file system\n- `routing: { routes, routeRules, globalMiddleware, routedMiddleware }`\n- `scannedHandlers: NitroEventHandler[]`\n- `logger: ConsolaInstance`\n- `updateConfig(config)` — Hot-reload config\n- `close()` — Cleanup\n\n**Setup flow:**\n1. Load options via `loadOptions()`\n2. Install modules via `installModules()`\n3. Init routing via `initNitroRouting()`\n4. Scan handlers/plugins/tasks via `scanAndSyncOptions()`\n5. Setup hooks\n\n## Entry Points\n\n- `src/builder.ts` — Main public API: `createNitro()`, `build()`, `createDevServer()`, `prerender()`, `copyPublicAssets()`, `prepare()`, `runTask()`, `listTasks()`\n- `src/vite.ts` — Vite plugin export from `src/build/vite/plugin.ts`\n\n## Build System (`src/build/`)\n\n**Builder dispatch** (`build/build.ts`): delegates to `rollup`, `rolldown`, or `vite` based on `nitro.options.builder`.\n\n**Builder selection** (resolved in `config/resolvers/builder.ts`):\n- Check `NITRO_BUILDER` env var\n- Auto-detect: `vite` when a `vite.config` uses `nitro()`, otherwise `rolldown`\n- No builder package is a dependency of Nitro: they are imported from the user project and installed on demand (`rolldown` via `build/rolldown/_import.ts`)\n- Dev without `rolldown` (and no `rollupConfig`/`rolldownConfig`) falls back to `builder: false`\n\n**Base config** (`build/config.ts`):\n- Extensions: `.ts`, `.mjs`, `.js`, `.json`, `.node`, `.tsx`, `.jsx`\n- Import.meta replacements (`import.meta.dev`, `import.meta.preset`, etc.)\n- Node.js compatibility aliases (`unenv` targets go to the unenv plugin)\n- External dependency patterns\n\n**Plugins** (`build/plugins.ts`):\n1. Virtual modules — renders from `build/virtual/`\n2. Unenv — resolves `unenv/*` polyfills, installing `unenv` on demand\n3. WASM loader — unwasm\n4. Server main injection — `globalThis.__server_main__`\n5. Raw imports — `?raw` suffix\n6. Route meta — OpenAPI metadata\n7. Replace plugin — variable substitution\n8. Externals plugin — Node.js native resolution\n9. Sourcemap minify (optional)\n\nUser `buildPlugins` are added around this list by `withBuildPlugins()` (`enforce: \"pre\"` before, the others after the builder's own plugins). With `builder: false`, they are appended to the env-runner plugins (`build/unbundled/plugins.ts`).\n\n**Virtual modules** (`build/virtual/`, 14 templates):\nAll prefixed `#nitro/virtual/<name>`:\n- `routing.ts` — Compiled router matcher\n- `plugins.ts` — Plugin registry\n- `error-handler.ts` — Error handler\n- `public-assets.ts` — Public asset metadata\n- `server-assets.ts` — Server asset metadata\n- `runtime-config.ts` — Runtime config object\n- `database.ts` — Database setup\n- `kv.ts` — KV storage backends\n- `tasks.ts` — Task registry\n- `polyfills.ts` — Env polyfills\n- `feature-flags.ts` — Feature detection\n- `routing-meta.ts` — Route metadata (OpenAPI)\n- `renderer-template.ts` — SSR renderer\n- `_all.ts` — Aggregator\n\n## Configuration System (`src/config/`)\n\n**Loader** (`config/loader.ts`): `loadOptions(config, opts)`\n1. Merge with defaults (`NitroDefaults`)\n2. Load c12 config files (`nitro.config.ts`, `package.json.nitro`, etc.)\n3. Resolve preset\n4. Run config resolvers sequentially\n\n**Resolvers** (`config/resolvers/`):\n`compatibility`, `tsconfig`, `paths`, `imports`, `route-rules`, `database`, `export-conditions`, `runtime-config`, `open-api`, `url`, `assets`, `storage`, `error`, `unenv`, `builder`\n\n**Defaults** (`config/defaults.ts`): All NitroConfig defaults.\n\n## Runtime (`src/runtime/`)\n\n**Internal** (`runtime/internal/`):\n- `app.ts` — NitroApp creation, H3 app setup\n- `cache.ts` — Response caching\n- `context.ts` — Async context\n- `route-rule-handlers.ts` — Nitro's rule handlers for the compiled matcher: a `cache` handler bound to Nitro's cache runtime. The built-ins (headers, redirect, proxy, cors) and rule matching/normalization live in [`h3/rules`](https://h3.dev/guide/rules).\n- `static.ts` — Static file serving\n- `task.ts` — Task execution\n- `plugin.ts` — Plugin helpers\n- `runtime-config.ts` — Config getter\n\n**Public exports**: `runtime/app.ts` (`defineConfig()`), `runtime/nitro.ts` (`serverFetch()`), `runtime/cache.ts`, `runtime/task.ts`, `runtime/kv.ts`, etc.\n\n## Dev Server (`src/dev/`)\n\n- `dev/server.ts` — `createDevServer()` (public `NitroDevServer` interface, internal `DevServer` class): Worker management via `env-runner`, restart on failure (max 3 retries), WebSocket support, VFS debug endpoint (`/_vfs/**`)\n- `dev/app.ts` — `NitroDevApp`: H3 app with error handling, static serving with compression, dev proxy\n\n## Prerender (`src/prerender/`)\n\n- `prerender/prerender.ts` — Main flow: parse routes → build prerenderer (preset: `nitro-prerender`) → execute in parallel → link crawling → write to disk → compress\n- `prerender/utils.ts` — `extractLinks()`, `matchesIgnorePattern()`, `formatPrerenderRoute()`\n\n## Routing & Scanning (`src/routing.ts`, `src/scan.ts`)\n\n**Scanning**: Discovers routes, middleware, plugins, tasks, modules from filesystem.\n\nRoute file conventions:\n- `routes/index.ts` → `GET /`\n- `routes/users/[id].ts` → `GET /users/:id`\n- `routes/users/[...slug].ts` → `GET /users/:slug(.*)` (also matches `/users`)\n- `api/users.post.ts` → `POST /api/users`\n- `.dev`/`.prod`/`.prerender` suffixes for environment filtering\n\n**Router** (`Router` class): Based on `rou3`, compiles to optimized string matcher, supports method routing + env conditions.\n\n## Presets (`src/presets/`)\n\nSeveral deployment-target presets (+ internal `_nitro`/`_static`); see `.agents/presets.md`. Structure per preset:\n\n```\npresets/<name>/\n├── preset.ts        # defineNitroPreset()\n├── runtime/         # Runtime entry (bundled)\n├── types.ts         # Types (optional)\n├── utils.ts         # Build-time utils (optional)\n└── unenv/           # Env overrides (optional)\n```\n\nKey presets: `standard`, `node` (server/middleware/cluster), `cloudflare` (pages/workers), `vercel`, `netlify`, `aws-lambda`, `deno`, `firebase`, `azure`, `bun`\n\nResolution: `presets/_resolve.ts` handles aliases, dev/prod, compat dates, static hosting.\n\n## CLI (`src/cli/`)\n\nUses `citty` with lazy-loaded commands: `dev`, `build`, `deploy`, `preview`, `prepare`, `task`, `docs`.\n\n## Key Libraries\n\n| Library | Purpose |\n|---------|---------|\n| `h3` | HTTP framework |\n| `rou3` | Route matching |\n| `c12` | Config loading |\n| `citty` | CLI framework |\n| `hookable` | Hook system |\n| `unstorage` | Storage abstraction (`nitro/kv`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `db0` | SQL database layer (`nitro/database`), installed on demand by `build/plugins/runtime-deps.ts` |\n| `ocache` | Caching (`nitro/cache`, `cache` route rules) |\n| `unenv` | Node.js polyfills for `node: false` builds (`build/_node-compat.ts`), installed on demand by `build/plugins/unenv.ts` |\n| `defu` | Config merging |\n| `pathe` | Path operations |\n| `consola` | Logging |\n| `env-runner` | Worker management |\n\n<!-- File: examples/plugins/package.json (Tokens: ~50 | Category: anthropic-skill) -->\n{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"nitro dev\",\n    \"build\": \"nitro build\"\n  },\n  \"devDependencies\": {\n    \"nitro\": \"latest\"\n  }\n}\n\n<!-- File: examples/plugins/tsconfig.json (Tokens: ~12 | Category: anthropic-skill) -->\n{\n  \"extends\": \"nitro/tsconfig\"\n}\n\n<!-- File: .github/copilot-instructions.md (Tokens: ~22 | Category: copilot-instructions) -->\n@../AGENTS.md\n\nRefer to [AGENTS.md](../AGENTS.md) for project instructions.\n\n<!-- File: examples/plugins/README.md (Tokens: ~260 | Category: plugin-manifest) -->\nPlugins let you hook into Nitro's runtime lifecycle. This example shows a plugin that modifies the `Content-Type` header on every response. Create files in `server/plugins/` and they're automatically loaded at startup.\n\n## Defining a Plugin\n\n```ts [server/plugins/test.ts]\nimport { definePlugin } from \"nitro\";\nimport { useNitroHooks } from \"nitro/app\";\n\nexport default definePlugin(() => {\n  const hooks = useNitroHooks();\n  hooks.hook(\"response\", (res) => {\n    res.headers.set(\"content-type\", \"html; charset=utf-8\");\n  });\n});\n```\n\nThe plugin uses `useNitroHooks()` to access the hooks system, then registers a `response` hook that runs after every request and receives the outgoing `Response`. Here it sets the content type to HTML, but you could log requests, add security headers, or modify responses in any way.\n\n## Main Handler\n\n```ts [server.ts]\nimport { defineHandler } from \"nitro\";\n\nexport default defineHandler(() => \"<h1>Hello Nitro!</h1>\");\n```\n\nThe handler returns HTML without setting a content type. The plugin automatically adds the correct `Content-Type: html; charset=utf-8` header to the response.\n\n<!-- File: .github/agents/maintainer.agent.md (Tokens: ~335 | Category: subagent-persona) -->\n---\nname: Maintainer\ndescription: >\n  Nitro project maintainer agent. Handles bug fixes, feature implementation,\n  code review, and contributions following project conventions. Understands the\n  build system, runtime constraints, deployment presets, and testing strategy.\ntools:\n  - \"*\"\n---\n\nYou are a maintainer of the Nitro project. Follow all instructions in [AGENTS.md](../../AGENTS.md) strictly.\n\nFor deeper architectural context, refer to the `.agents/` directory:\n\n- `.agents/architecture.md` — Core architecture, build system, config resolution, virtual modules, runtime internals.\n- `.agents/presets.md` — Deployment presets, preset structure, resolution logic.\n- `.agents/testing.md` — Test structure, adding regression tests, running tests.\n- `.agents/vite.md` — Vite build system, plugin architecture, dev server, HMR.\n- `.agents/docs.md` — Documentation conventions, H3 v2 API patterns.\n\nH3 v2 docs are at `node_modules/h3/dist/docs/README.md`.\n\n## Key principles\n\n- Prefer minimal, targeted changes over large refactors.\n- Code in `src/runtime/` must be runtime-agnostic (Web APIs, no Node.js-specific APIs).\n- Use `pathe` instead of `node:path`.\n- Use existing UnJS utilities (`defu`, `consola`, `unstorage`) before adding new packages.\n- Bug fixes MUST include a failing regression test first.\n- Always run `pnpm fmt` and `pnpm typecheck` after changes.\n- Use semantic commit messages with scope (e.g., `fix(runtime): ...`).\n</yakaai_skills>"}