# HTTP Server CLI — Router

The Router provides a flexible and powerful routing system for the HTTP Server CLI.
It features **automatic route caching** for high performance, **parameter constraint types** for input validation, and a **middleware pipeline** for cross-cutting concerns.

## Basic usage

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Response;

return static function
(Request $Request, Response $Response, Router $Router): Generator
{
   yield $Router->route('/', function (Request $Request, Response $Response) {
      return $Response(body: 'Hello World!');
   }, GET);

   // @ Catch-all 404
   yield $Router->route('/*', function (Request $Request, Response $Response) {
      return $Response(code: 404, body: 'Not Found');
   });
};
```

> You should use `yield` (Generator) if you define more than one route. This ensures consistency and performance in HTTP Responses under the hood.

## Route Callbacks

### Passing Closures as handler

Inside a Closure handler, `$this` is bound to the `Route` object, giving direct access to `$this->Params`.

```php
yield $Router->route('/', fn (Request $Request, Response $Response) => $Response(body: 'Hello World!'), GET);
```

```php
yield $Router->route('/', function (Request $Request, Response $Response) {
   return $Response(body: 'Hello World!');
}, GET);
```

### Passing functions as handler

Consider that you have the following function:

```php
function talk (Request $Request, Response $Response): Response
{
   $queries = $Request->queries;
   $message = 'Hello ' . ($queries['who'] ?? 'World!');

   return $Response(code: 200, body: $message);
}
```

```php
yield $Router->route('/hello', 'talk', GET);
```

### Passing methods as handler

Consider that you have the following class:

```php
class World
{
   public static function hello (Request $Request, Response $Response): Response
   {
      return $Response(body: 'Hello World!!!');
   }
}
```

```php
yield $Router->route('/hello', __NAMESPACE__ . '\World::hello', GET);
```

## Route with multiple HTTP methods

```php
yield $Router->route('/data', function ($Request, $Response) {
   return $Response(body: 'Data!');
}, [GET, POST]);
```

## Fixed-body routes

`serve()` registers a route that always answers with the same string — there is no handler. It is the shortest and fastest way to publish a constant response, such as a health check or a fixed page:

```php
yield $Router->serve('/health', 'OK', GET);
yield $Router->serve('/about', '<h1>About us</h1>', GET);
```

It behaves like `route()` with a handler that returns `$Response(body: $body)`:

- The response is `200 OK` with `$body` as the body. It sets no headers of its own.
- `$methods`, route params, groups and catch-all work exactly as in `route()`. When the same route is registered with both `route()` and `serve()`, a static route and the catch-all answer with the later registration, a route with params with the earlier one (see [A registration log](#a-registration-log)).
- `$middlewares` (and group middlewares from `intercept()`) still run for every request.
- A static route without middlewares skips the handler call altogether: the stored string is copied straight into the response.

`$body` is the response content itself, fixed when the routes are registered — it is **not** a file path: `serve('/logo', 'statics/logo.png')` answers with the text `statics/logo.png`. To send a file, use [`Response::upload()`](/manual/WPI/HTTP/HTTP_Server_CLI/Response/#upload-files) (download) or [read it in a handler](/manual/WPI/HTTP/HTTP_Server_CLI/Response/#send-file-contents-inline) (inline). For content that changes per request, use `route()`.

## Route Params

Route params are defined with the `:paramName` syntax. Inside Closure handlers, access params via `$this->Params->paramName`.

### Basic params (no constraint)

When no regex or constraint type is defined, the param matches any non-slash characters:

```php
yield $Router->route('/user/:id', function ($Request, $Response) {
   return $Response(body: 'User ID: ' . $this->Params->id);
}, GET);
```

### Pre-set regex constraint

Set a regex pattern on the `Route->Params` object before defining the route:

```php
$Route->Params->id = '[0-9]+';

yield $Router->route('/user/:id', function ($Request, $Response) {
   return $Response(body: 'User ID: ' . $this->Params->id);
}, GET);
```

### Inline regex constraint

Define the regex directly in the route pattern using parentheses `:paramName(regex)`:

```php
yield $Router->route('/order/:oid(\\d+)', function ($Request, $Response) {
   return $Response(body: 'Order ID: ' . $this->Params->oid);
}, GET);
```

### Parameter Constraint Types

Use the `<type>` syntax for built-in validation constraints. These are expanded to regex at **compile-time** with **zero runtime cost**:

```php
yield $Router->route('/user/:id<int>', function ($Request, $Response) {
   // :id only matches integers (e.g., /user/42 ✅, /user/abc ❌)
   return $Response(body: 'User ID: ' . $this->Params->id);
}, GET);
```

| Type | Pattern | Description | Example Match |
|------|---------|-------------|---------------|
| `int` | `[0-9]+` | Integer numbers | `42`, `123` |
| `alpha` | `[a-zA-Z]+` | Alphabetic characters only | `books`, `Admin` |
| `alphanum` | `[a-zA-Z0-9]+` | Alphanumeric characters | `abc123`, `Item5` |
| `slug` | `[a-zA-Z0-9_-]+` | URL-safe slug (letters, numbers, hyphen, underscore) | `hello-world_2` |
| `uuid` | UUID v4 pattern | Standard UUID format | `550e8400-e29b-41d4-a716-446655440000` |

#### Examples

```php
// @ Alpha constraint — only letters
yield $Router->route('/category/:name<alpha>', function ($Request, $Response) {
   return $Response(body: 'Category: ' . $this->Params->name);
}, GET);

// @ Slug constraint — URL-friendly strings
yield $Router->route('/tag/:slug<slug>', function ($Request, $Response) {
   return $Response(body: 'Tag: ' . $this->Params->slug);
}, GET);

// @ UUID constraint — standard UUID format
yield $Router->route('/resource/:id<uuid>', function ($Request, $Response) {
   return $Response(body: 'UUID: ' . $this->Params->id);
}, GET);

// @ Alphanum constraint — letters and numbers only
yield $Router->route('/item/:code<alphanum>', function ($Request, $Response) {
   return $Response(body: 'Item: ' . $this->Params->code);
}, GET);
```

When a constraint does not match, the route is skipped and the next route is tried (usually falling through to the catch-all 404).

### Multiple params

```php
yield $Router->route('/posts/:pid/comments/:cid', function ($Request, $Response) {
   return $Response(body: 'Post: ' . $this->Params->pid . ', Comment: ' . $this->Params->cid);
}, GET);
```

### Duplicate (equal) param names

When the same param name appears multiple times, it becomes an indexed array:

```php
$Route->Params->id = '[0-9]+';

yield $Router->route('/param/:id/param/:id', function ($Request, $Response) {
   return $Response(body: 'ID 1: ' . $this->Params->id[0] . ', ID 2: ' . $this->Params->id[1]);
}, GET);
```

## Nested Routes (Route Groups)

Groups allow organizing routes under a shared prefix:

```php
yield $Router->route('/profile/:*', function () use ($Router) {
   yield $Router->route('maria', function ($Request, $Response) {
      return $Response(body: 'Hello Maria!');
   });
   yield $Router->route('bob', function ($Request, $Response) {
      return $Response(body: 'Hello Bob!');
   });
}, GET);
```

### Parameterized nested routes

```php
$Route->Params->id = '[0-9]+';

yield $Router->route('/page/:*', function () use ($Router) {
   yield $Router->route(':id', function ($Request, $Response) {
      return $Response(body: 'Page ID: ' . $this->Params->id);
   });
}, GET);
```

## Catch-All Routes

### Generic catch-all (404 fallback)

Matches any URL that was not matched by previous routes:

```php
yield $Router->route('/*', function ($Request, $Response) {
   return $Response(code: 404, body: 'Not Found');
});
```

### Parameterized catch-all

Captures the remaining path segments into a named param. The `*` modifier after the param name captures everything including forward slashes:

```php
yield $Router->route('/search/:query*', function ($Request, $Response) {
   // /search/hello       → $this->Params->query === 'hello'
   // /search/hello/world → $this->Params->query === 'hello/world'
   return $Response(body: 'Search: ' . $this->Params->query);
});
```

> The catch-all param must be the **last** path segment.

## Route Caching

The Router automatically caches all route definitions on the **first request**. Subsequent requests resolve routes from the cache without re-executing the Generator.

### How it works

1. **First request**: the Generator is fully iterated, each `yield $Router->route(...)` populates the cache tables.
2. **Subsequent requests**: the `resolve()` method performs a direct lookup:
   - **Static routes** — O(1) hash-table lookup by URL + method.
   - **Dynamic routes** — O(1) first-segment index + O(m) regex match within the segment bucket.
   - **Catch-all** — fallback after all specific routes are checked.
3. **Nested groups** are flattened into the cache during warmup (e.g., `/admin/:*` → `/admin/dashboard`, `/admin/settings`).

The cache is per-worker (each worker process warms its own cache on the first request).

### Cache status

```php
$Router->cached; // bool — true after the cache is warmed
```

## Route Response Cache

Routes can opt in to a **response cache**: the server stores the fully built
response (status line + headers + body) and serves repeated requests directly
from those bytes — before routing, middlewares, the handler and serialization
run. A database-backed route served from the cache responds at static-route
speed (~10× throughput in the Bootgly benchmark: 93k → 938k req/s).

Opt in per route with the `cache` option and a `TTL` (entry lifetime, in
seconds):

```php
yield $Router->route('/report', function ($Request, $Response) {
   return $Response->defer(function (Response $Response): void {
      $Result = $Response->Database->fetch('SELECT count(*) AS total FROM orders');

      $Response->JSON->send($Result->row);
   });
}, GET, cache: ['TTL' => 30]);
```

The first request runs the handler and stores the built response; every
request in the next 30 seconds is answered from the stored bytes. When the
`TTL` expires, the next request runs the handler again and refreshes the
entry.

### What is cached — and what never is

Entries are keyed by **method + path + query string** — `/report?page=1` and
`/report?page=2` are distinct entries. A response is only stored when the
exchange is safely cacheable:

- `GET` over `HTTP/1.1`, status `200`, plain identity body (no streaming,
  chunking or compression);
- the request carries **no credentials** (`Cookie` / `Authorization`) and asks
  to keep the connection alive;
- the response sets **no cookies** (`Set-Cookie`).

Credentialed requests also never **read** the cache — a logged-in user always
reaches the handler.

### When the cache steps aside

Each of these keeps a `cache:` route running its handler on every request.
None of them is reported — the route simply behaves as if it had no `cache`
option:

- **The route has middlewares** — its own `middlewares:` or a group's
  `intercept()`. Cache replay skips the handler, so a route whose middlewares
  must run on every request is never stored.
- **The server has a global middleware** — any entry in `SAPI::$Middlewares`,
  or a listener on `Request\Events::Received` / `Request\Events::Handled`,
  turns the cache off for every route.
- **The request came through a proxy** — a request carrying
  `X-Forwarded-For`, `X-Forwarded-Proto` or `X-Real-IP` — or a `header`/`relay`
  a [TrustedProxy](/manual/WPI/HTTP/HTTP_Server_CLI/Middlewares/overview/#trustedproxy)
  was configured with, such as `CF-Connecting-IP` — is looked up in its own key
  space and never stores an entry, so behind a load balancer that adds these
  fields the cache stays empty.
- **The request asks for a fresh answer** — `Cache-Control: no-cache` skips
  the lookup.
- **The response is too large** — an entry is stored only up to 1 MiB of wire
  bytes.
- **The handler defers** — a response answered through `$Response->defer()`
  is never stored, whether its work waits or completes at once: the route runs
  its handler on every request.

Browsers send their cookies with every request to your site, so on a site
that uses a Session the cache serves only cookieless clients. It fits public
API responses fetched by clients without cookies; for static assets, rely on
`Cache-Control` and a CDN — see [Static Files](/manual/WPI/HTTP/HTTP_Server_CLI/#static-files).

### Scope and limits

The store is **per worker** (in-process), holds up to 512 entries (oldest
evicted first) and refreshes the `Date` header of stored responses once per
second. There is no cross-worker sharing: each worker warms its own entry
within one `TTL` window. The stored bytes of one worker are capped at 64 MiB
(`HTTP_Server_CLI\Cache::$maxBytes`, set before the server starts), and the
entries also draw on the worker's [memory budget](/manual/WPI/HTTP/HTTP_Server_CLI/#memory-budget):
at what the allocator spends to keep them, at most a quarter of it — 16 MiB by
default, so 8 entries of about 1 MiB (each costs a whole 2 MiB chunk) or many
more small ones. A store that does not fit evicts the oldest entries first; a
response that still does not fit is served without being cached.

## Route Group Middlewares (intercept)

`intercept()` applies middlewares to all routes defined after the call within the current routing scope. A warm Router ignores the call — no route is registered after the warm-up:

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\CORS;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\RateLimit;

$Router->intercept(new CORS, new RateLimit(limit: 100, window: 60, scope: 'public-api'));

yield $Router->route('/api/:*', function ($Request, $Response) use ($Router) {
   // All nested routes inherit CORS + RateLimit
   yield $Router->route('users', function ($Request, $Response) {
      return $Response->JSON->send(['users' => []]);
   }, GET);
}, GET);
```

### Per-route middlewares

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\RequestId;

$RequestId = new RequestId;
yield $Router->route('/protected/dashboard', function ($Request, $Response) {
   return $Response(body: 'Protected Dashboard');
}, GET, middlewares: [$RequestId]);
```

When both group and route-level middlewares are present, they are **merged** — group middlewares execute first, then route-level ones, forming a single onion pipeline around the handler.

See [Middlewares](/manual/WPI/HTTP/HTTP_Server_CLI/Middlewares) for the full middleware pipeline documentation.

## Route List

`$Router->Routes` lists the routes the Router stored — one row per route, in the order they were registered. It is read-only and costs nothing per request: rows are written while the routes are registered, and the dispatcher never reads them.

### Reading the list in a handler

The route inventory — every path, method and parameter pattern of the application — is not public information: guard a route that publishes it, as any private route (see [Authentication](/manual/WPI/HTTP/HTTP_Server_CLI/Authentication/overview/)).

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authenticating;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Middlewares\Authentication\Bearer;

$Admin = new Authentication(new Authenticating(
   new Bearer(function (string $token, Request $Request): bool {
      return hash_equals((string) getenv('ROUTES_TOKEN'), $token);
   })
));

yield $Router->route('/routes', function ($Request, $Response) use ($Router) {
   $routes = [];
   foreach ($Router->Routes as $Registration) {
      $routes[] = [
         'path' => $Registration->path,
         'methods' => $Registration->methods ?? 'any',
         'kind' => $Registration->Kind->name,
      ];
   }

   return $Response->JSON->send($routes);
}, GET, middlewares: [$Admin]);
```

The list is complete once `$Router->cached` is `true`. A route handler always sees it complete — route handlers run after the warm-up — including the routes registered after its own. The request handler itself and a group handler run during the warm-up: they see the list as far as it has got, with `$Router->cached` still `false`. A request handler that registers with direct calls also runs again after the warm-up, on a request no route answers: it then sees the list complete. The routes of a group come after the top-level ones: a group registers its routes when it is flattened, at the end of the warm-up.

### Reading the list without a request

Outside the server — a test, a command, a tool — there is no first request to warm the Router. `warm()` does it: pass it the Generator your route set returns.

This check fails when an API route was added without a line in the published list:

```php
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Request;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Response;
use Bootgly\WPI\Nodes\HTTP_Server_CLI\Router;

$Router = new Router;
$Handler = $Router->load(__DIR__ . '/router'); // the folder your server loads
$Router->warm($Handler(new Request, new Response, $Router));

$published = [
   'GET /api/users',
   'POST /api/users',
   'GET /api/users/:id<int>',
];

$missing = [];
foreach ($Router->Routes as $Registration) {
   if (str_starts_with($Registration->path, '/api/') === false) {
      continue;
   }

   foreach ($Registration->methods ?? ['ANY'] as $method) {
      $line = "$method {$Registration->path}";
      if (in_array($line, $published, true) === false) {
         $missing[] = $line;
      }
   }
}
// $missing — the API routes nobody published
```

`warm()` leaves `$Router->cached` at `true`, exactly as the first request does. On a Router that is already warm it does nothing.

### What a row says

- **`path`** — the path as you wrote it, with the group prefix applied: `/api/users/:id<int>`. The root is `/` and the generic catch-all is `/*`.
- **`methods`** — the methods the Router accepts for the route; `null` means every method. A route in a group registered without methods inherits the group's; one registered with methods keeps only those the group also has.
- **`Middlewares`** — every middleware that runs for the route, outermost first: the ones from `intercept()` in effect when the route was registered, the group's, then the route's own `middlewares:`. A route registered before an `intercept()` call does not carry it.
- **`handler`** — the callable you passed to `route()`. A `serve()` route has no handler: it has a **`body`**.
- **`parameters`** — one entry per `:param`, in path order, with its `name`, its `constraint` type when you used one (`int`, `slug`, …) and the `pattern` a segment must match.
- **`cache`** — the `cache:` options as you wrote them. A route with middlewares is never served from the response cache (see [When the cache steps aside](#when-the-cache-steps-aside)), so check `Middlewares` too.
- **`Kind`** — how the Router finds the route: `Static`, `Dynamic`, `CatchAll`, or `Body` for a `serve()` route answered without a handler call.

### A registration log

The list records what was registered, not which route wins a request:

- **A path registered twice has two rows.** For a static path and for the generic catch-all, the later registration is the one that answers; for a dynamic path, the earlier one.
- **A row says what the Router does**, where that differs from the arguments:
  - the generic catch-all `/*` answers every method, so its `methods` is `null` whatever was passed;
  - a dynamic route registered with an empty method list (`[]`) answers every method — `null` too;
  - a static route registered with an empty method list is not stored: it has no row and matches nothing;
  - a static route registered with an empty method name (`''`, alone or in a list) answers every method — `null` too;
  - a route registered as `''` inside a group lands on the site root — its `path` is `/`.
- **A dynamic route keeps an empty method name as written.** Its `methods` lists `''` — `['']`, `['GET', '']` — though no request has that method: the route answers only the other methods of its list, and `['']` none.
- **Not everything leaves a row.** A group (`/admin/:*`) is not a route — its children are. A registration made while the Router is paused, after the warm-up, or one that threw an exception stored nothing.
- **A warm-up that throws** leaves `$Router->cached` at `false` and the Router as the warm-up found it — the list and the lookup tables alike — so the next request registers every route again. The exception is a route set that warmed the Router by itself (a `warm()` call of its own) before it threw: the Router then stays warm, with the routes stored up to that call.
- **A route set that runs more than once is listed once.** A handler that registers with direct `$Router->route()` calls runs again on every request until the Router is warm, and the Router stays cold while that handler answers the request itself or throws. The server rewinds the Router before each of those runs: the first route a run registers starts from what the Router held before the first run, so the list and the lookup tables hold one copy of each route. A run that registers nothing changes nothing. Outside the server, call `rewind()` before each run of such a handler.
- **The routes of a run are whole or nothing.** Once a run registers a route, the routes an earlier run registered and this one does not repeat are gone: do not guard part of the routes to run once (a `static` flag, a `require_once`) while the rest runs on every request.
- **The `intercept()` middlewares follow the registration, and never shrink.** In a handler that registers with direct calls, a registration an earlier run made too — the same methods and path, the same how-many-th time in the run (a refused registration does not count) — is stored with the middlewares this run intercepted itself up to there, in their order, plus each one it had then that this run did not intercept, kept in its place. A middleware built again the same way on each run — the same class with the same property values, the objects and closures it holds compared the same way — is the same middleware and is kept once; one with another configuration is another middleware, so both run. What cannot be compared counts as another one: an object of a class PHP defines, or of one extending it (`stdClass` and the objects `json_decode()` returns, `PDO`, `DateTime`, `SplObjectStorage`, a `WeakMap` — so the bundled `AccessLog` too), a lazy object not initialized yet, a closure declared on a line that declares another function (`fn ($role) => new Gate(fn () => …)`: put the inner closure on a line of its own), a closure from `eval()` or declared in a PHP file larger than 256 KiB, `NAN`, and anything nested deeper than 16 levels — and so does a middleware built from what changes on every run (the request, the time). Such a middleware is kept once per run while the Router stays cold, and then runs once per such run on each request: build it once, before the first request or outside the handler. A middleware is compared as it stands when the route is registered: what it keeps elsewhere (a `WeakMap` or static table keyed by it) or what changes in it later is not seen, so a middleware whose access decision depends on that must not be intercepted on one run only. A new registration takes the middlewares in effect at that point: until the run's first `intercept()`, the ones the previous run ended with; after it, the ones intercepted before the first request plus this run's. So a route stays behind a middleware intercepted on the first run only — beside other `intercept()` calls that run every time, or not — or on a later run only, a middleware built the same way on every run runs once, and a public route registered ahead of `intercept()` on every run stays public. Two shapes still lose a middleware intercepted on the first run only, so avoid them: a route that only a later run registers, after an `intercept()` of that run, when the run skips the first-run-only one; and a path a run registers fewer times than the run before, when an earlier registration of it sat ahead of the first-run-only `intercept()`. A route set that yields its routes takes nothing from an earlier run — the warm-up registers it on its own, starting with no middleware — so guard none of it, an `intercept()` least of all.

## Route Object

`Route` is the **current match**: the state of the route the Router matched for the request being handled — `$this` inside a Closure handler. It is not a registered route; for that, read a row of the [route list](#route-list).

The Router keeps one `Route` for the worker's life, and every handler's `$this` is that object. A handler reached from deferred work — behind a middleware that deferred ahead of `$next`, or routed by a Router whose routes registered inside a deferral — still reads its own request's `path` and `Params`: each slice of deferred work installs its request's match in that `Route` while it runs, and keeps what it routed across `wait()` and a nested `defer()`. Treat the `Route` as read-only from a handler. An entry a handler writes into `$this->Params` lives for its request only: it is kept across a `wait()`, and the Router empties `Params` before it routes the next request, so no later request's handler — another client's included — reads it. Code that runs outside a routed handler — a global middleware, or a response answered from the [route response cache](#route-response-cache) — still sees the map of the last request routed. Inside deferred work, read params through `$this->Params`, never through a `Params` object captured before the `defer()`: that object is the worker's, and the next request empties it. A whole property replaced from deferred work (`$this->path = …`) can be lost at the next `wait()`.

The `Route` class (`Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Route`) exposes the following properties:

| Property | Type | Description |
|----------|------|-------------|
| `path` | `string` | The path of the request that matched (`/user/42`), not the route pattern |
| `Params` | `Params` | Route parameters container |
| `Middlewares` | `array<Middleware>` | The middleware chain folded around the matched route (group entries first, then the route's own), present only while a middleware-bearing dispatch runs — the chain a deferred generation keeps for its `Recovering` boundaries (see [Middlewares](/manual/WPI/HTTP/HTTP_Server_CLI/Middlewares)) |
| `base` | `string` | The request base path (property hook) |

### Params Object

The `Params` class (`Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Route\Params`) provides dynamic typed access to route parameters:

```php
$this->Params->id;       // string — single param value
$this->Params->id[0];    // string — first value of duplicate param
$this->Params->id[1];    // string — second value of duplicate param
```

`Params` implements `IteratorAggregate`, so you can iterate over all captured params:

```php
foreach ($this->Params as $name => $value) {
   // $name  → 'id', 'slug', etc.
   // $value → 'abc', ['val1', 'val2'], etc.
}
```

## Reference

### Router

```php
route (string $route, callable $handler, null|string|array $methods = null, array $middlewares = [], null|array $cache = null) : false
```

Registers a route and returns `false`; a paused or warm Router ignores the call. `$route` is the URL pattern to match — params, constraints and catch-all included. `$handler` runs when a request matches: it receives the `Request` and the `Response`, and inside a Closure `$this` is the matched `Route`. `$methods` is the HTTP method or methods the route answers, every method when `null`. `$middlewares` holds the middlewares of this route alone, and `$cache` the [route response cache](#route-response-cache) options: `['TTL' => <seconds>]`.

```php
serve (string $route, string $body, null|string|array $methods = null, array $middlewares = []) : false
```

Registers a route that always answers `200 OK` with `$body` (see [Fixed-body routes](#fixed-body-routes)) and returns `false`. `$route`, `$methods` and `$middlewares` work as in `route()`; a paused or warm Router ignores the call.

```php
intercept (Middleware ...$Middlewares) : void
```

Applies `$Middlewares` to every route registered after the call in the current routing scope (see [Route Group Middlewares](#route-group-middlewares-intercept)). A warm Router ignores the call.

```php
public private(set) array $Routes
```

The route list: `array<int,Registration>`, one row per stored route, in registration order. Complete once `$cached` is `true`. Readable from anywhere, written only by the Router.

```php
warm (null|Generator $Routes = null) : void
```

Warms the route cache without a request: drains `$Routes` (the Generator a route set returns), then flattens the route groups. Pass `null` when the routes were registered with direct `$Router->route()` calls. Does nothing on a warm Router. If a route set or a registration throws, the exception is rethrown and the Router stays cold, as `warm()` found it: the routes registered before the call stay, their groups pending again — unless the route set warmed the Router by itself before it threw, which leaves it warm with the routes stored up to then.

```php
rewind () : void
```

Marks the start of a registration attempt on a cold Router. The first call records what the Router holds. After each later call the first route registered puts the recorded state back before it is stored — the lookup tables, the pending groups and the route list — and the first `intercept()` starts again from the recorded middlewares. Routes registered before the first call stay, and an attempt that registers nothing keeps what the last one left; one that registers a route keeps only the routes it registers itself. A registration an earlier attempt made too is stored with the middlewares this attempt intercepted itself up to there, plus each one it was stored with then that they lack, in its place; a new one takes the ones in effect when it is made (see [A registration log](#a-registration-log)). Does nothing on a warm Router. The server calls it before each run of the request handler while the Router is cold; call it yourself only to run a handler that registers with direct `$Router->route()` calls more than once outside the server.

### Registration

`Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Registration` — one row of the route list. Every property is read-only.

| Property | Type | Description |
|----------|------|-------------|
| `path` | `string` | The registered path with its group prefix; `/` for the root, `/*` for the generic catch-all |
| `methods` | `null\|array<int,string>` | The methods the Router accepts; `null` when the route answers every method |
| `handler` | `null\|object\|array\|string` | The callable as registered; `null` for a `serve()` route |
| `body` | `null\|string` | The fixed body of a `serve()` route; `null` for a `route()` one |
| `Middlewares` | `array<int,Middleware>` | The middlewares that run for the route, outermost first |
| `parameters` | `array<int,array{name: string, constraint: null\|string, pattern: string}>` | The path params in path order; `pattern` is `[^\/]+` for a plain param and `.+` for a `:name*` one |
| `cache` | `null\|array{TTL: int}` | The `cache:` options as registered; `null` without them |
| `Kind` | `Kinds` | How the Router finds the route |

### Kinds

`Bootgly\WPI\Nodes\HTTP_Server_CLI\Router\Registration\Kinds`

| Case | Meaning |
|------|---------|
| `Static` | A literal path, found by one lookup and answered by its handler |
| `Dynamic` | A path with `:param` segments |
| `CatchAll` | The generic `/*` fallback |
| `Body` | A literal path registered with `serve()` and no middleware: the body is copied into the response without a handler call |
