267 lines
17 KiB
Plaintext
267 lines
17 KiB
Plaintext
page wrnexusrouter {
|
|
seo {
|
|
title = "@wrnexus/router"
|
|
description = "Filesystem discovery, route matching, and typed route generation."
|
|
}
|
|
|
|
view {
|
|
<div class="docs-shell">
|
|
<header class="topbar">
|
|
<a class="brand" href="/"><span>W</span> WRNexusJS</a>
|
|
<nav><a href="/getting-started">Get started</a><a href="/packages">Packages</a><a href="/language">Language</a><a href="/architecture">Architecture</a></nav>
|
|
<button data-wire-theme-toggle class="theme-button" aria-label="Toggle theme">Theme</button>
|
|
</header>
|
|
<main class="page package-page">
|
|
<aside class="sidebar"><a href="/packages">← All packages</a><span class="category">Core</span><h1>@wrnexus/router</h1><p>Filesystem discovery, route matching, and typed route generation.</p><code>bun add @wrnexus/router@0.2.12</code><nav><a href="#guide">Guide</a><a href="#api">Complete API</a></nav></aside>
|
|
<article class="documentation"><section class="doc-intro"><span class="eyebrow">Core</span><h1>@wrnexus/router</h1><p>Filesystem discovery, route matching, and typed route generation.</p><pre><code>bun add @wrnexus/router@0.2.12</code></pre></section><section id="guide" class="prose"><blockquote>File-based router that maps an <code>app/</code> directory onto route tables and matches request paths against them.</blockquote>
|
|
<p>Part of the <strong>WRNexusJS</strong> framework — an SSR-first, Bun-native full-stack web framework.</p>
|
|
<h3 id="overview">Overview</h3>
|
|
<p><code>@wrnexus/router</code> scans an application's <code>app/</code> directory once at startup and builds route tables for pages, API endpoints, realtime channels, middleware, server-rendered <code>.wrn</code> components, layouts, and validation schemas. It also compiles URL patterns (<code>/users/[id]</code>) into RegExps and matches request paths against them. Request input is never turned into a file path, which makes the router immune to path traversal. This is a server-side package used by the WRNexusJS runtime to resolve incoming requests, plus a codegen helper for compile-time typed links.</p>
|
|
<h3 id="installation">Installation</h3>
|
|
<pre data-language="bash"><code>bun add @wrnexus/router</code></pre>
|
|
<blockquote>Private package — the machine must be authenticated to the <code>wrnexus</code> npm org</blockquote>
|
|
<blockquote>(a read token in <code>~/.npmrc</code>). Requires <strong>Bun</strong> (Node is not supported).</blockquote>
|
|
<h3 id="directory-conventions">Directory conventions</h3>
|
|
<p>The router maps files under <code>appDir</code> onto routes:</p>
|
|
<pre data-language=""><code>app/pages/index.tsx -> GET /
|
|
app/pages/about.tsx -> GET /about
|
|
app/pages/users/[id].tsx -> GET /users/:id
|
|
app/api/hello.ts -> /api/hello
|
|
app/realtime/chat.ts -> /realtime/chat
|
|
app/pages/*.wrn (api) -> embedded /api/* routes
|
|
app/pages/*.wrn (rt) -> embedded /realtime/* routes
|
|
app/middleware/*.ts -> global middleware (alphabetical)
|
|
app/components/*.wrn -> server-rendered components (by basename)
|
|
app/layouts/*.wrn -> named page layouts
|
|
app/schemas/*.ts -> validation schemas</code></pre>
|
|
<p>Allowed route extensions are <code>.ts</code>, <code>.tsx</code>, and <code>.wrn</code>. Dotfiles and underscore-prefixed files are ignored. A trailing <code>index</code> segment is dropped from the route. <code>.wrn</code> pages may embed <code>api</code> and <code>realtime</code> blocks, which the router extracts and mounts under <code>/api/*</code> and <code>/realtime/*</code>.</p>
|
|
<h3 id="api">API</h3>
|
|
<h4 id="buildrouter-appdir-opts-router"><code>buildRouter(appDir, opts?): Router</code></h4>
|
|
<p>Scan an app directory and build all route tables.</p>
|
|
<pre data-language="ts"><code>function buildRouter(appDir: string, opts?: RouterOptions): Router;
|
|
|
|
interface RouterOptions {
|
|
/** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
|
|
* `app/components`, so an app component of the same name wins. */
|
|
componentDirs?: string[];
|
|
}</code></pre>
|
|
<p>The returned <code>Router</code> exposes the built tables plus per-kind matchers:</p>
|
|
<pre data-language="ts"><code>interface Router {
|
|
pages: Route[];
|
|
api: Route[];
|
|
realtime: Route[];
|
|
/** Absolute paths of middleware modules, in execution order (alphabetical). */
|
|
middlewareFiles: string[];
|
|
/** Server-rendered `.wrn` components, mounted via `data-component`. */
|
|
components: ComponentRef[];
|
|
/** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
|
|
layouts: ComponentRef[];
|
|
/** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
|
|
schemas: ComponentRef[];
|
|
matchPage(pathname: string): RouteMatch | null;
|
|
matchApi(pathname: string): RouteMatch | null;
|
|
matchRealtime(pathname: string): RouteMatch | null;
|
|
}
|
|
|
|
interface ComponentRef {
|
|
/** Validated component name (matches a `data-component` attribute). */
|
|
name: string;
|
|
/** Absolute path to the component's `.wrn` module. */
|
|
file: string;
|
|
}</code></pre>
|
|
<p>Component, layout, and schema names are validated with <code>isSafeIslandName</code> from <code>@wrnexus/core</code>; unsafe names are skipped with a warning. Realtime channel names are validated the same way.</p>
|
|
<h4 id="route-matching">Route matching</h4>
|
|
<div class="table-wrap"><table>
|
|
<thead><tr><th>Export</th><th>Signature</th><th>Description</th></tr></thead>
|
|
<tbody><tr><td><code>compileRoutePattern</code></td><td>`(raw: string) => Pick<Route, "regex" \</td><td>"paramNames">`</td><td>Compile a <code>/users/[id]</code> pattern into a RegExp (with optional trailing slash) plus ordered param names.</td></tr><tr><td><code>matchRoute</code></td><td>`(routes: Route[], pathname: string) => RouteMatch \</td><td>null`</td><td>Return the first route whose regex matches; captured params are <code>decodeURIComponent</code>-decoded.</td></tr><tr><td><code>sortRoutes</code></td><td><code>(routes: Route[]) => Route[]</code></td><td>Order routes so static routes win over dynamic ones (fewer params first), then longer/more specific patterns first.</td></tr></tbody></table></div>
|
|
<pre data-language="ts"><code>interface Route {
|
|
raw: string; // e.g. "/users/[id]"
|
|
file: string; // absolute path to the handling module
|
|
regex: RegExp; // compiled matcher
|
|
paramNames: string[]; // ordered dynamic param names
|
|
}
|
|
|
|
interface RouteMatch {
|
|
route: Route;
|
|
params: Record<string, string>;
|
|
}</code></pre>
|
|
<h4 id="typed-routes-codegen">Typed-routes codegen</h4>
|
|
<pre data-language="ts"><code>function generateRoutesFile(pages: Route[]): string;</code></pre>
|
|
<p>Emits the source for <code>app/routes.gen.ts</code>: a <code>Routes</code> map (each page path → its <code>[param]</code> types), a <code>RoutePath</code> union, and an <code>href()</code> builder that fills params and rejects unknown paths at compile time. Entries are de-duplicated and sorted by path.</p>
|
|
<h4 id="re-exports">Re-exports</h4>
|
|
<p><code>Middleware</code> (the type from <code>@wrnexus/core</code>) is re-exported for callers that load middleware modules themselves.</p>
|
|
<h3 id="usage">Usage</h3>
|
|
<pre data-language="ts"><code>import { buildRouter } from "@wrnexus/router";
|
|
|
|
const router = buildRouter("./app", {
|
|
componentDirs: ["./node_modules/@wrnexus/ui/components"],
|
|
});
|
|
|
|
// Resolve an incoming request.
|
|
const match = router.matchPage("/users/42");
|
|
if (match) {
|
|
console.log(match.route.file); // absolute path to the page module
|
|
console.log(match.params); // { id: "42" }
|
|
}
|
|
|
|
const api = router.matchApi("/api/hello");
|
|
const rt = router.matchRealtime("/realtime/chat");</code></pre>
|
|
<p>Generating the typed-routes file (as <code>wrnexus dev</code> does):</p>
|
|
<pre data-language="ts"><code>import { generateRoutesFile } from "@wrnexus/router";
|
|
import { writeFileSync } from "node:fs";
|
|
|
|
const router = buildRouter("./app");
|
|
writeFileSync("./app/routes.gen.ts", generateRoutesFile(router.pages));</code></pre>
|
|
<pre data-language="ts"><code>// Then, in app code, links are checked at compile time:
|
|
import { href } from "./routes.gen.ts";
|
|
|
|
href("/users/[id]", { id: "42" }); // "/users/42"
|
|
href("/about"); // "/about"
|
|
href("/nope"); // type error: unknown path</code></pre>
|
|
<p>Lower-level pattern matching, if you need it directly:</p>
|
|
<pre data-language="ts"><code>import { compileRoutePattern, matchRoute, sortRoutes, type Route } from "@wrnexus/router";
|
|
|
|
const { regex, paramNames } = compileRoutePattern("/posts/[slug]");
|
|
const routes = sortRoutes([{ raw: "/posts/[slug]", file: "…", regex, paramNames }]);
|
|
const m = matchRoute(routes, "/posts/hello"); // { route, params: { slug: "hello" } }</code></pre>
|
|
<h3 id="requirements-notes">Requirements / Notes</h3>
|
|
<ul>
|
|
<li>Scanning uses <code>node:fs</code> (<code>existsSync</code>, <code>readdirSync</code>, <code>statSync</code>) and <code>node:path</code> — runs under Bun.</li>
|
|
<li>Depends on [<code>@wrnexus/compiler</code>](../compiler) to <code>parse</code> <code>.wrn</code> pages and extract embedded <code>api</code> / <code>realtime</code> blocks.</li>
|
|
<li>Depends on [<code>@wrnexus/core</code>](../core) for <code>isSafeIslandName</code> (name validation) and the <code>Middleware</code> type.</li>
|
|
<li>Missing route directories are tolerated — a route kind you don't use simply yields an empty table.</li>
|
|
</ul></section><section id="api" class="prose api"><h2>Complete TypeScript API</h2><p>This declaration is generated from the exact published package and lists its exported functions, classes, interfaces, and types.</p><pre data-language="typescript"><code>export { Middleware } from '@wrnexus/core';
|
|
|
|
/**
|
|
* Route compilation + matching.
|
|
*
|
|
* A "route" is a URL pattern compiled to a RegExp. We support static segments
|
|
* and dynamic `[param]` segments, e.g. `/users/[id]` -> `{ id }`.
|
|
*/
|
|
interface Route {
|
|
/** The human-readable route pattern, e.g. `/users/[id]`. */
|
|
raw: string;
|
|
/** Absolute path to the module that handles this route. */
|
|
file: string;
|
|
/** Compiled matcher. */
|
|
regex: RegExp;
|
|
/** Ordered names of dynamic params captured by `regex`. */
|
|
paramNames: string[];
|
|
}
|
|
interface RouteMatch {
|
|
route: Route;
|
|
params: Record<string, string>;
|
|
}
|
|
/** Compile a `/users/[id]` style pattern into a RegExp + param names. */
|
|
declare function compileRoutePattern(raw: string): Pick<Route, "regex" | "paramNames">;
|
|
/**
|
|
* Order routes so that static routes win over dynamic ones, and longer/more
|
|
* specific routes win over shorter ones. Sorting once keeps matching simple.
|
|
*/
|
|
declare function sortRoutes(routes: Route[]): Route[];
|
|
/** Find the first route whose pattern matches `pathname`. */
|
|
declare function matchRoute(routes: Route[], pathname: string): RouteMatch | null;
|
|
|
|
/**
|
|
* Typed-routes codegen. From the scanned page routes, emit `app/routes.gen.ts`
|
|
* with a `Routes` map (path → param types) and an `href()` builder — so links
|
|
* are checked at compile time (unknown path or missing param = type error).
|
|
*/
|
|
|
|
declare function generateRoutesFile(pages: Route[]): string;
|
|
|
|
/**
|
|
* @wrnexus/router — file-based router.
|
|
*
|
|
* Maps the `app/` directory onto route tables:
|
|
* app/pages/index.tsx -> GET /
|
|
* app/pages/about.tsx -> GET /about
|
|
* app/pages/users/[id].tsx-> GET /users/:id
|
|
* app/api/hello.ts -> /api/hello
|
|
* app/realtime/chat.ts -> /realtime/chat
|
|
* app/pages/*.wrn api -> embedded /api/* routes
|
|
* app/pages/*.wrn realtime -> embedded /realtime/* routes
|
|
* app/middleware/*.ts -> global middleware (alphabetical)
|
|
* app/components/*.wrn -> server-rendered components (by basename),
|
|
* mounted in a page via data-component="<name>"
|
|
*/
|
|
|
|
interface ComponentRef {
|
|
/** Validated component name (matches a `data-component` attribute). */
|
|
name: string;
|
|
/** Absolute path to the component's `.wrn` module. */
|
|
file: string;
|
|
}
|
|
interface Router {
|
|
pages: Route[];
|
|
api: Route[];
|
|
realtime: Route[];
|
|
/** Absolute paths of middleware modules, in execution order. */
|
|
middlewareFiles: string[];
|
|
/** Server-rendered `.wrn` components, mounted via `data-component`. */
|
|
components: ComponentRef[];
|
|
/** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
|
|
layouts: ComponentRef[];
|
|
/** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
|
|
schemas: ComponentRef[];
|
|
matchPage(pathname: string): RouteMatch | null;
|
|
matchApi(pathname: string): RouteMatch | null;
|
|
matchRealtime(pathname: string): RouteMatch | null;
|
|
}
|
|
interface RouterOptions {
|
|
/**
|
|
* Extra directories to scan for `.wrn` components (e.g. `@wrnexus/ui`).
|
|
* Scanned before `app/components`, so an app component of the same name wins.
|
|
*/
|
|
componentDirs?: string[];
|
|
}
|
|
/** Scan an app directory and build all route tables. */
|
|
declare function buildRouter(appDir: string, opts?: RouterOptions): Router;
|
|
|
|
export { type ComponentRef, type Route, type RouteMatch, type Router, type RouterOptions, buildRouter, compileRoutePattern, generateRoutesFile, matchRoute, sortRoutes };
|
|
</code></pre></section><section id="examples" class="prose examples"><h2>Examples</h2><p>Copy-ready examples taken from this package's published documentation.</p><div class="example-grid"><article class="example-card"><h3>Example 1</h3><pre data-language="bash"><code>bun add @wrnexus/router</code></pre></article><article class="example-card"><h3>Example 2</h3><pre data-language="text"><code>app/pages/index.tsx -> GET /
|
|
app/pages/about.tsx -> GET /about
|
|
app/pages/users/[id].tsx -> GET /users/:id
|
|
app/api/hello.ts -> /api/hello
|
|
app/realtime/chat.ts -> /realtime/chat
|
|
app/pages/*.wrn (api) -> embedded /api/* routes
|
|
app/pages/*.wrn (rt) -> embedded /realtime/* routes
|
|
app/middleware/*.ts -> global middleware (alphabetical)
|
|
app/components/*.wrn -> server-rendered components (by basename)
|
|
app/layouts/*.wrn -> named page layouts
|
|
app/schemas/*.ts -> validation schemas</code></pre></article><article class="example-card"><h3>Example 3</h3><pre data-language="ts"><code>function buildRouter(appDir: string, opts?: RouterOptions): Router;
|
|
|
|
interface RouterOptions {
|
|
/** Extra dirs scanned for `.wrn` components (e.g. `@wrnexus/ui`), before
|
|
* `app/components`, so an app component of the same name wins. */
|
|
componentDirs?: string[];
|
|
}</code></pre></article><article class="example-card"><h3>Example 4</h3><pre data-language="ts"><code>interface Router {
|
|
pages: Route[];
|
|
api: Route[];
|
|
realtime: Route[];
|
|
/** Absolute paths of middleware modules, in execution order (alphabetical). */
|
|
middlewareFiles: string[];
|
|
/** Server-rendered `.wrn` components, mounted via `data-component`. */
|
|
components: ComponentRef[];
|
|
/** Named page layouts (`app/layouts/<name>.wrn`); a page picks one via `layout`. */
|
|
layouts: ComponentRef[];
|
|
/** Validation schemas (`app/schemas/<name>.ts`) shared by API + forms. */
|
|
schemas: ComponentRef[];
|
|
matchPage(pathname: string): RouteMatch | null;
|
|
matchApi(pathname: string): RouteMatch | null;
|
|
matchRealtime(pathname: string): RouteMatch | null;
|
|
}
|
|
|
|
interface ComponentRef {
|
|
/** Validated component name (matches a `data-component` attribute). */
|
|
name: string;
|
|
/** Absolute path to the component's `.wrn` module. */
|
|
file: string;
|
|
}</code></pre></article></div></section></article>
|
|
<aside class="on-this-page"><h2>On this page</h2><nav><a class="toc-level-2" href="#guide">Guide</a><a class="toc-level-3" href="#overview">Overview</a><a class="toc-level-3" href="#installation">Installation</a><a class="toc-level-3" href="#directory-conventions">Directory conventions</a><a class="toc-level-3" href="#api">API</a><a class="toc-level-4" href="#buildrouter-appdir-opts-router">buildRouter(appDir, opts?): Router</a><a class="toc-level-4" href="#route-matching">Route matching</a><a class="toc-level-4" href="#typed-routes-codegen">Typed-routes codegen</a><a class="toc-level-4" href="#re-exports">Re-exports</a><a class="toc-level-3" href="#usage">Usage</a><a class="toc-level-3" href="#requirements-notes">Requirements / Notes</a><a class="toc-level-2" href="#api">Complete API</a><a class="toc-level-2" href="#examples">Examples</a></nav></aside>
|
|
</main>
|
|
<footer>WRNexusJS 0.2.12 · SSR-first · Bun-native · Documentation generated from published package APIs.</footer>
|
|
</div>
|
|
}
|
|
}
|