@k8ordo/router 2.3.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -23,7 +23,7 @@ pnpm add @k8ordo/router
23
23
 
24
24
  Under `@k8ordo/framework` this package is what the framework builds on: the
25
25
  table is generated from `src/routes/`, and what an application uses of it is
26
- the half that needs no table — `href`, `navigateTo` and `bindParams`;
26
+ the half that needs no table — `href` and `bindParams`;
27
27
  `usePathname`, `useMatch` and `matchPath` — plus the route files' props types,
28
28
  `PageProps` and `LayoutProps`. There it is installed as the framework's peer,
29
29
  and the application imports that half from `@k8ordo/framework`, which
@@ -77,10 +77,10 @@ export const Shell = () => (
77
77
 
78
78
  ```tsx
79
79
  // anywhere — from the pattern string alone, never importing the table
80
- import { href, navigateTo, useMatch, useParams } from '@k8ordo/router';
80
+ import { href, useMatch, useParams } from '@k8ordo/router';
81
81
 
82
82
  <a href={href('/products/:id', { id })}>…</a>; // a plain <a> is a client navigation
83
- navigateTo('/products'); // push; the back button undoes it
83
+ navigation.navigate(href('/products')); // the same URL, from code
84
84
  const { id } = useParams('/products/:id'); // typed from the pattern
85
85
  const inProducts = useMatch('/products/*'); // which section is showing
86
86
  ```
package/dist/base.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * A pathname in the table's terms, as the URL spells it: the base in front.
3
3
  * Under `base: '/docs/'`, `/products` → `/docs/products` and `/` → `/docs/`.
4
- * `href` and `navigateTo` build every link through it, so a table written
4
+ * `href` builds every link through it, so a table written
5
5
  * from the root works wherever the application is served.
6
6
  */
7
7
  export declare const withBase: (pathname: string, base?: string) => string;
package/dist/base.mjs CHANGED
@@ -20,7 +20,7 @@ const prefixOf = (base) => {
20
20
  /**
21
21
  * A pathname in the table's terms, as the URL spells it: the base in front.
22
22
  * Under `base: '/docs/'`, `/products` → `/docs/products` and `/` → `/docs/`.
23
- * `href` and `navigateTo` build every link through it, so a table written
23
+ * `href` builds every link through it, so a table written
24
24
  * from the root works wherever the application is served.
25
25
  */
26
26
  const withBase = (pathname, base = viteBase()) => {
@@ -1,5 +1,5 @@
1
1
  import { ErrorComponent } from "./boundary.mjs";
2
- import { Join, PathMatching } from "./paths.mjs";
2
+ import { Join } from "./paths.mjs";
3
3
  import { ComponentType } from "react";
4
4
  /**
5
5
  * Any component, whatever props it declares. The table is written once and
@@ -32,18 +32,11 @@ type PatternsIn<Record_, Prefix extends string> = { [K in keyof Record_ & string
32
32
  export type PatternOf<R extends RoutesRecord> = PatternsIn<R, ''> & string;
33
33
  /** Patterns a link can point at — wildcards are matched, never linked. */
34
34
  export type NavigablePatternOf<R extends RoutesRecord> = Exclude<PatternOf<R>, `${string}*${string}`>;
35
- /**
36
- * `Path` when one of the table's navigable patterns matches it, segment by
37
- * segment — a literal spelled as the pattern spells it, a `:param` taking any
38
- * one non-empty segment — and `never` when none does. What `@k8ordo/state`
39
- * checks a path against with the `routes` its `Register` is given, and what
40
- * any other typed-path consumer takes.
41
- */
42
- export type NavigablePath<D, Path extends string> = D extends Routes<infer R extends RoutesRecord> ? PathMatching<Path, NavigablePatternOf<R>> : never;
43
35
  export type Match = {
44
36
  /** The full pattern that won, as written in the table. */
45
37
  pattern: string;
46
- params: Readonly<Record<string, string>>;
38
+ /** A `:param` as its segment, a rest param (`:name+`) as its segments. */
39
+ params: Readonly<Record<string, string | readonly string[]>>;
47
40
  /** Layouts outer-first, the leaf last. */
48
41
  stack: readonly RouteComponent[];
49
42
  };
@@ -55,7 +48,7 @@ export type Routes<R extends RoutesRecord = RoutesRecord> = {
55
48
  * Matches a pathname in declaration order, first match wins — precedence
56
49
  * is what you wrote, not a specificity ranking to second-guess. The one
57
50
  * operation that needs the table's value: links and navigation build from
58
- * the pattern string alone (`href` / `navigateTo`), so only `<Router>`
51
+ * the pattern string alone (`href`), so only `<Router>`
59
52
  * ever holds this object.
60
53
  */
61
54
  match: (pathname: string) => Match | null;
@@ -1,6 +1,6 @@
1
- import { decodeOrKeep, isGroupKey, joinPattern, normalizePathname } from "./paths.mjs";
2
1
  import { RouteErrorBoundary } from "./boundary.mjs";
3
2
  import { Outlet } from "./outlet.mjs";
3
+ import { isGroupKey, joinPattern, normalizePathname, readParams } from "./paths.mjs";
4
4
  import { Suspense, createElement } from "react";
5
5
  // src/define-routes.ts
6
6
  const isBranch = (node) => typeof node === "object" && "children" in node;
@@ -27,6 +27,23 @@ const loadingFor = (Fallback) => {
27
27
  const Loading = ({ children }) => createElement(Suspense, { fallback: createElement(Fallback) }, children === void 0 ? createElement(Outlet) : children);
28
28
  return Loading;
29
29
  };
30
+ const PARAM_NAME = /^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u;
31
+ const SYNTAX = /[:*?+{}()\\]/u;
32
+ const GRAMMAR = "a segment is a literal holding none of : * ? + { } ( ) \\, a \":name\", or — last — a \":name+\" or a \"*\"";
33
+ const grammarProblem = (pattern) => {
34
+ if (pattern === "/") return null;
35
+ const segments = pattern.slice(1).split("/");
36
+ const last = segments.length - 1;
37
+ for (const [index, segment] of segments.entries()) {
38
+ if (segment === "") return `route pattern "${pattern}" has an empty segment — ${GRAMMAR}`;
39
+ const isParam = segment.startsWith(":");
40
+ const isRest = isParam && segment.endsWith("+");
41
+ const isWildcard = segment === "*";
42
+ if (!(isParam ? PARAM_NAME.test(segment.slice(1, isRest ? -1 : void 0)) : isWildcard || !SYNTAX.test(segment))) return `route pattern "${pattern}" has the segment "${segment}", which is not part of the grammar — ${GRAMMAR}`;
43
+ if ((isRest || isWildcard) && index !== last) return `route pattern "${pattern}" puts "${segment}" before the end — ${isRest ? "a rest param" : "a wildcard"} must be the last segment`;
44
+ }
45
+ return null;
46
+ };
30
47
  function defineRoutes(record) {
31
48
  const entries = [];
32
49
  const seen = /* @__PURE__ */ new Set();
@@ -45,6 +62,8 @@ function defineRoutes(record) {
45
62
  ];
46
63
  walk(node.children, pattern === "/" ? "" : pattern, below);
47
64
  } else {
65
+ const problem = grammarProblem(pattern);
66
+ if (problem !== null) throw new TypeError(problem);
48
67
  if (seen.has(pattern)) throw new TypeError(`route pattern "${pattern}" is declared twice`);
49
68
  seen.add(pattern);
50
69
  entries.push({
@@ -61,11 +80,9 @@ function defineRoutes(record) {
61
80
  for (const entry of entries) {
62
81
  const result = entry.matcher.exec({ pathname: normalized });
63
82
  if (result === null) continue;
64
- const params = {};
65
- for (const [name, value] of Object.entries(result.pathname.groups)) if (!/^\d+$/u.test(name) && value !== void 0) params[name] = decodeOrKeep(value);
66
83
  yield {
67
84
  pattern: entry.pattern,
68
- params,
85
+ params: readParams(entry.pattern, result.pathname.groups),
69
86
  stack: entry.stack
70
87
  };
71
88
  }
package/dist/index.d.mts CHANGED
@@ -1,14 +1,14 @@
1
1
  import { withBase, withoutBase } from "./base.mjs";
2
2
  import { ErrorComponent, ErrorProps } from "./boundary.mjs";
3
- import { ParamValue, ParamsOf, ParamsSchemaFor, ParsedParams, ParsedParamsMap, PathFor, SchemaOutput, StandardSchemaLike, normalizePathname } from "./paths.mjs";
4
- import { Match, NavigablePath, NavigablePatternOf, PatternOf, RouteComponent, RouteNode, Routes, RoutesRecord, defineRoutes } from "./define-routes.mjs";
5
- import { LayoutProps, PageProps, Register, RegisteredNavigablePattern, RegisteredPageParams, RegisteredParams, RegisteredPattern, RouteContext } from "./register.mjs";
6
- import { BoundLinks, BoundParams, NavigateToOptions, bindParams, href, navigateTo } from "./links.mjs";
3
+ import { Match, NavigablePatternOf, PatternOf, RouteComponent, RouteNode, Routes, RoutesRecord, defineRoutes } from "./define-routes.mjs";
4
+ import { BoundParams, bindParams, href } from "./links.mjs";
7
5
  import { BrowserPathname, PathnameProvider, usePathname } from "./location.mjs";
8
6
  import { MatchOptions, MatchablePattern, matchPath, useMatch } from "./match.mjs";
9
7
  import { isNotFound, notFound } from "./not-found.mjs";
10
8
  import { NavigationGeneration, NavigationHandler, useInterceptedNavigation, usePendingPathname } from "./navigation.mjs";
9
+ import { ParamValue, ParamsOf, ParamsSchemaFor, ParsedParams, ParsedParamsMap, PathFor, SchemaOutput, StandardSchemaLike, normalizePathname } from "./paths.mjs";
10
+ import { LayoutProps, PageProps, Register, RegisteredNavigablePattern, RegisteredPageParams, RegisteredParams, RegisteredPattern, RouteContext } from "./register.mjs";
11
11
  import { Outlet } from "./outlet.mjs";
12
12
  import { Router, useParams, useRoute } from "./router.mjs";
13
13
  import { TreePathname } from "./tree-pathname.mjs";
14
- export { type BoundLinks, type BoundParams, BrowserPathname, type ErrorComponent, type ErrorProps, type LayoutProps, type Match, type MatchOptions, type MatchablePattern, type NavigablePath, type NavigablePatternOf, type NavigateToOptions, NavigationGeneration, type NavigationHandler, Outlet, type PageProps, type ParamValue, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type PathFor, PathnameProvider, type PatternOf, type Register, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteComponent, type RouteContext, type RouteNode, Router, type Routes, type RoutesRecord, type SchemaOutput, type StandardSchemaLike, TreePathname, bindParams, defineRoutes, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useInterceptedNavigation, useMatch, useParams, usePathname, usePendingPathname, useRoute, withBase, withoutBase };
14
+ export { type BoundParams, BrowserPathname, type ErrorComponent, type ErrorProps, type LayoutProps, type Match, type MatchOptions, type MatchablePattern, type NavigablePatternOf, NavigationGeneration, type NavigationHandler, Outlet, type PageProps, type ParamValue, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type PathFor, PathnameProvider, type PatternOf, type Register, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteComponent, type RouteContext, type RouteNode, Router, type Routes, type RoutesRecord, type SchemaOutput, type StandardSchemaLike, TreePathname, bindParams, defineRoutes, href, isNotFound, matchPath, normalizePathname, notFound, useInterceptedNavigation, useMatch, useParams, usePathname, usePendingPathname, useRoute, withBase, withoutBase };
package/dist/index.mjs CHANGED
@@ -1,12 +1,12 @@
1
- import { normalizePathname } from "./paths.mjs";
2
1
  import { withBase, withoutBase } from "./base.mjs";
3
- import { BrowserPathname, PathnameProvider, usePathname } from "./location.mjs";
4
- import { NavigationGeneration, useInterceptedNavigation, usePendingPathname } from "./navigation.mjs";
5
- import { Outlet } from "./outlet.mjs";
6
2
  import { defineRoutes } from "./define-routes.mjs";
7
- import { bindParams, href, navigateTo } from "./links.mjs";
3
+ import { bindParams, href } from "./links.mjs";
4
+ import { BrowserPathname, PathnameProvider, usePathname } from "./location.mjs";
8
5
  import { matchPath, useMatch } from "./match.mjs";
9
6
  import { isNotFound, notFound } from "./not-found.mjs";
10
- import { TreePathname } from "./tree-pathname.mjs";
7
+ import { NavigationGeneration, useInterceptedNavigation, usePendingPathname } from "./navigation.mjs";
8
+ import { normalizePathname } from "./paths.mjs";
9
+ import { Outlet } from "./outlet.mjs";
11
10
  import { Router, useParams, useRoute } from "./router.mjs";
12
- export { BrowserPathname, NavigationGeneration, Outlet, PathnameProvider, Router, TreePathname, bindParams, defineRoutes, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useInterceptedNavigation, useMatch, useParams, usePathname, usePendingPathname, useRoute, withBase, withoutBase };
11
+ import { TreePathname } from "./tree-pathname.mjs";
12
+ export { BrowserPathname, NavigationGeneration, Outlet, PathnameProvider, Router, TreePathname, bindParams, defineRoutes, href, isNotFound, matchPath, normalizePathname, notFound, useInterceptedNavigation, useMatch, useParams, usePathname, usePendingPathname, useRoute, withBase, withoutBase };
package/dist/links.d.mts CHANGED
@@ -1,14 +1,6 @@
1
1
  import { ParamValue } from "./paths.mjs";
2
2
  import { RegisteredNavigablePattern, RegisteredParams } from "./register.mjs";
3
3
  type HrefArgs<Params> = keyof Params extends never ? [] : [params: Readonly<Params & Record<never, never>>];
4
- export type NavigateToOptions = {
5
- /**
6
- * `push` by default: going to a page is what the back button undoes —
7
- * the opposite default from a state refinement.
8
- */
9
- history?: 'push' | 'replace';
10
- };
11
- type NavigateToArgs<Params> = keyof Params extends never ? [options?: NavigateToOptions] : [params: Readonly<Params & Record<never, never>>, options?: NavigateToOptions];
12
4
  /**
13
5
  * Builds the URL a link points at from a pattern and its params — no route
14
6
  * table involved, which is why pages never import one. Params are inferred
@@ -17,17 +9,11 @@ type NavigateToArgs<Params> = keyof Params extends never ? [options?: NavigateTo
17
9
  * page's schema gave each param, so a link takes what the page received.
18
10
  *
19
11
  * What comes back is a URL, with Vite's `base` in front (`withBase`), not a
20
- * pathname in the table's terms — which is why it is typed `string`: handed
21
- * to something that adds the base itself, it would carry it twice.
12
+ * pathname in the table's terms — which is why it is typed `string`. The
13
+ * same URL serves a link and a navigation started from code:
14
+ * `navigation.navigate(href('/products/:id', { id }))`.
22
15
  */
23
16
  export declare const href: <P extends RegisteredNavigablePattern>(pattern: P, ...params: HrefArgs<RegisteredParams<P>>) => string;
24
- /**
25
- * Typed imperative navigation: `href` composed with
26
- * `navigation.navigate()`, returning the platform's own
27
- * `{ committed, finished }`. Changing pages goes through here; changing
28
- * state goes through `@k8ordo/state`'s `update()`.
29
- */
30
- export declare const navigateTo: <P extends RegisteredNavigablePattern>(pattern: P, ...rest: NavigateToArgs<RegisteredParams<P>>) => ReturnType<Navigation['navigate']>;
31
17
  /** What a params source supplies: values with one URL spelling, by name. */
32
18
  export type BoundParams = Readonly<Record<string, ParamValue>>;
33
19
  /**
@@ -36,24 +22,19 @@ export type BoundParams = Readonly<Record<string, ParamValue>>;
36
22
  */
37
23
  type Unbound<Params, Bound> = Omit<Params, keyof Bound> & Partial<Pick<Params, Extract<keyof Bound, keyof Params>>>;
38
24
  type BoundHrefArgs<Params, Bound> = Exclude<keyof Params, keyof Bound> extends never ? [params?: Readonly<Partial<Params> & Record<never, never>>] : [params: Readonly<Unbound<Params, Bound> & Record<never, never>>];
39
- type BoundNavigateToArgs<Params, Bound> = keyof Params extends never ? [options?: NavigateToOptions] : [...BoundHrefArgs<Params, Bound>, options?: NavigateToOptions];
40
- export type BoundLinks<Bound extends BoundParams> = {
41
- readonly href: <P extends RegisteredNavigablePattern>(pattern: P, ...rest: BoundHrefArgs<RegisteredParams<P>, Bound>) => string;
42
- readonly navigateTo: <P extends RegisteredNavigablePattern>(pattern: P, ...rest: BoundNavigateToArgs<RegisteredParams<P>, Bound>) => ReturnType<Navigation['navigate']>;
43
- };
44
25
  /**
45
- * `href` and `navigateTo` with some params supplied by a function instead of
46
- * by every call — a segment the whole application shares, such as a locale
47
- * or a tenant. The source is read at each call, so a value that differs per
48
- * request or per URL is read where it is current. Patterns keep their full
49
- * spelling (`'/:locale/products'`), so the table's types apply unchanged and
50
- * a bound param can still be given to point at another value.
26
+ * `href` with some params supplied by a function instead of by every call —
27
+ * a segment the whole application shares, such as a locale or a tenant. The
28
+ * source is read at each call, so a value that differs per request or per
29
+ * URL is read where it is current. Patterns keep their full spelling
30
+ * (`'/:locale/products'`), so the table's types apply unchanged and a bound
31
+ * param can still be given to point at another value.
51
32
  *
52
33
  * ```ts
53
- * const { href, navigateTo } = bindParams(() => ({ locale: locales.getLocale() }));
34
+ * export const href = bindParams(() => ({ locale: locales.getLocale() }));
54
35
  * href('/:locale/products/:id', { id }); // locale comes from the source
55
- * navigateTo('/:locale', { locale: 'en' }, { history: 'replace' }); // or is overridden
36
+ * href('/:locale', { locale: 'en' }); // or is overridden
56
37
  * ```
57
38
  */
58
- export declare const bindParams: <const Bound extends BoundParams>(source: () => Bound) => BoundLinks<Bound>;
39
+ export declare const bindParams: <const Bound extends BoundParams>(source: () => Bound) => (<P extends RegisteredNavigablePattern>(pattern: P, ...rest: BoundHrefArgs<RegisteredParams<P>, Bound>) => string);
59
40
  export {};
package/dist/links.mjs CHANGED
@@ -1,7 +1,6 @@
1
- import { buildHref } from "./paths.mjs";
2
1
  import { withBase } from "./base.mjs";
2
+ import { buildHref } from "./paths.mjs";
3
3
  // src/links.ts
4
- const navigate = (pattern, params, options) => navigation.navigate(withBase(buildHref(pattern, params)), { history: options?.history ?? "push" });
5
4
  /**
6
5
  * Builds the URL a link points at from a pattern and its params — no route
7
6
  * table involved, which is why pages never import one. Params are inferred
@@ -10,51 +9,27 @@ const navigate = (pattern, params, options) => navigation.navigate(withBase(buil
10
9
  * page's schema gave each param, so a link takes what the page received.
11
10
  *
12
11
  * What comes back is a URL, with Vite's `base` in front (`withBase`), not a
13
- * pathname in the table's terms — which is why it is typed `string`: handed
14
- * to something that adds the base itself, it would carry it twice.
12
+ * pathname in the table's terms — which is why it is typed `string`. The
13
+ * same URL serves a link and a navigation started from code:
14
+ * `navigation.navigate(href('/products/:id', { id }))`.
15
15
  */
16
16
  const href = (pattern, ...params) => withBase(buildHref(pattern, params[0]));
17
17
  /**
18
- * Typed imperative navigation: `href` composed with
19
- * `navigation.navigate()`, returning the platform's own
20
- * `{ committed, finished }`. Changing pages goes through here; changing
21
- * state goes through `@k8ordo/state`'s `update()`.
22
- */
23
- const navigateTo = (pattern, ...rest) => {
24
- const wantsParams = pattern.includes(":");
25
- const args = rest;
26
- const params = wantsParams ? args[0] : void 0;
27
- const options = wantsParams ? args[1] : args[0];
28
- return navigate(pattern, params, options);
29
- };
30
- /**
31
- * `href` and `navigateTo` with some params supplied by a function instead of
32
- * by every call — a segment the whole application shares, such as a locale
33
- * or a tenant. The source is read at each call, so a value that differs per
34
- * request or per URL is read where it is current. Patterns keep their full
35
- * spelling (`'/:locale/products'`), so the table's types apply unchanged and
36
- * a bound param can still be given to point at another value.
18
+ * `href` with some params supplied by a function instead of by every call —
19
+ * a segment the whole application shares, such as a locale or a tenant. The
20
+ * source is read at each call, so a value that differs per request or per
21
+ * URL is read where it is current. Patterns keep their full spelling
22
+ * (`'/:locale/products'`), so the table's types apply unchanged and a bound
23
+ * param can still be given to point at another value.
37
24
  *
38
25
  * ```ts
39
- * const { href, navigateTo } = bindParams(() => ({ locale: locales.getLocale() }));
26
+ * export const href = bindParams(() => ({ locale: locales.getLocale() }));
40
27
  * href('/:locale/products/:id', { id }); // locale comes from the source
41
- * navigateTo('/:locale', { locale: 'en' }, { history: 'replace' }); // or is overridden
28
+ * href('/:locale', { locale: 'en' }); // or is overridden
42
29
  * ```
43
30
  */
44
- const bindParams = (source) => ({
45
- href: (pattern, ...rest) => withBase(buildHref(pattern, {
46
- ...source(),
47
- ...rest[0]
48
- })),
49
- navigateTo: (pattern, ...rest) => {
50
- const wantsParams = pattern.includes(":");
51
- const args = rest;
52
- const params = wantsParams ? args[0] : void 0;
53
- const options = wantsParams ? args[1] : args[0];
54
- return navigate(pattern, {
55
- ...source(),
56
- ...params
57
- }, options);
58
- }
59
- });
60
- export { bindParams, href, navigateTo };
31
+ const bindParams = (source) => (pattern, ...rest) => withBase(buildHref(pattern, {
32
+ ...source(),
33
+ ...rest[0]
34
+ }));
35
+ export { bindParams, href };
package/dist/location.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use client";
2
- import { normalizePathname } from "./paths.mjs";
3
2
  import { withoutBase } from "./base.mjs";
3
+ import { normalizePathname } from "./paths.mjs";
4
4
  import { createContext, use, useMemo, useSyncExternalStore } from "react";
5
5
  import { browser } from "react-dom";
6
6
  import { jsx } from "react/jsx-runtime";
package/dist/match.d.mts CHANGED
@@ -20,7 +20,10 @@ export type MatchOptions = {
20
20
  * Whether a pathname is the one a pattern names, and with which params. Pure
21
21
  * and table-free — the pattern is checked against `Register`, the pathname
22
22
  * is whatever the caller holds — which is why it works where no table is
23
- * mounted, under the framework included.
23
+ * mounted, under the framework included, and in a Server Component: a
24
+ * framework layout marks its current link with `matchPath(p, pathname)`.
25
+ * Compare patterns this way, never `pathname === href(p)`: `pathname` is in
26
+ * the table's terms and `href` carries Vite's `base`.
24
27
  */
25
28
  export declare const matchPath: <P extends MatchablePattern>(pattern: P, pathname: string, options?: MatchOptions) => ParamsOf<P> | null;
26
29
  /**
package/dist/match.mjs CHANGED
@@ -1,12 +1,14 @@
1
- "use client";
2
- import { decodeOrKeep, normalizePathname } from "./paths.mjs";
3
1
  import { usePathname } from "./location.mjs";
2
+ import { normalizePathname, readParams } from "./paths.mjs";
4
3
  // src/match.ts
5
4
  /**
6
5
  * Whether a pathname is the one a pattern names, and with which params. Pure
7
6
  * and table-free — the pattern is checked against `Register`, the pathname
8
7
  * is whatever the caller holds — which is why it works where no table is
9
- * mounted, under the framework included.
8
+ * mounted, under the framework included, and in a Server Component: a
9
+ * framework layout marks its current link with `matchPath(p, pathname)`.
10
+ * Compare patterns this way, never `pathname === href(p)`: `pathname` is in
11
+ * the table's terms and `href` carries Vite's `base`.
10
12
  */
11
13
  const matchPath = (pattern, pathname, options) => {
12
14
  if (options?.inclusive === true && pattern.endsWith("/*")) {
@@ -16,9 +18,7 @@ const matchPath = (pattern, pathname, options) => {
16
18
  }
17
19
  const result = new URLPattern({ pathname: pattern }).exec({ pathname: normalizePathname(pathname) });
18
20
  if (result === null) return null;
19
- const params = {};
20
- for (const [name, value] of Object.entries(result.pathname.groups)) if (!/^\d+$/u.test(name) && value !== void 0) params[name] = decodeOrKeep(value);
21
- return params;
21
+ return readParams(pattern, result.pathname.groups);
22
22
  };
23
23
  /**
24
24
  * `matchPath` against where the browser is. It re-renders when the pathname
@@ -7,6 +7,7 @@ import { Position } from "./left-at.mjs";
7
7
  */
8
8
  export type NavigationFacts = Pick<NavigateEvent, 'canIntercept' | 'hashChange' | 'downloadRequest' | 'navigationType'> & {
9
9
  readonly formData: FormData | null;
10
+ readonly destination: Pick<NavigationDestination, 'sameDocument'>;
10
11
  };
11
12
  /**
12
13
  * Whether this navigation is the application's to handle at all.
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { decodeOrKeep, normalizePathname } from "./paths.mjs";
3
2
  import { leftAt, rememberLeftAt, restoreLeftAt } from "./left-at.mjs";
4
3
  import { appPathname } from "./location.mjs";
5
- import { addTransitionType, createContext, startTransition, useDeferredValue, useEffect, useEffectEvent, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
4
+ import { decodeOrKeep, normalizePathname } from "./paths.mjs";
5
+ import { addTransitionType, createContext, startTransition, useDeferredValue, useEffectEvent, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
6
6
  // src/navigation.ts
7
7
  /**
8
8
  * Whether this navigation is the application's to handle at all.
@@ -13,7 +13,7 @@ import { addTransitionType, createContext, startTransition, useDeferredValue, us
13
13
  * has no `formData`, so the search-shaped navigations `@k8ordo/state` builds
14
14
  * still come through here.
15
15
  */
16
- const isOurs = (event) => event.canIntercept && !event.hashChange && event.downloadRequest === null && event.navigationType !== "reload" && event.formData === null;
16
+ const isOurs = (event) => event.canIntercept && !(event.hashChange && event.destination.sameDocument) && event.downloadRequest === null && event.navigationType !== "reload" && event.formData === null;
17
17
  const scrollPlanFor = (navigationType, hash, left) => {
18
18
  if (navigationType === "traverse" && left !== void 0) return {
19
19
  kind: "position",
@@ -171,7 +171,7 @@ function useInterceptedNavigation(handler) {
171
171
  const latest = useRef(-1);
172
172
  const applying = useRef(null);
173
173
  const onScreenEntry = useRef(null);
174
- useEffect(() => {
174
+ useLayoutEffect(() => {
175
175
  shown.current = normalizePathname(location.pathname);
176
176
  restoreLeftAt();
177
177
  const steps = reloadOnUnannouncedSteps((url) => normalizePathname(url.pathname) === shown.current && pendingPathname === null && !refresh(url));
package/dist/paths.d.mts CHANGED
@@ -1,13 +1,16 @@
1
1
  /**
2
2
  * The type half of the route table: everything here is derived from the
3
3
  * pattern strings by inference alone — no code generation. A pattern like
4
- * `'/:locale/products/:id'` yields its params (`{ locale, id }`), its
5
- * concrete-path type (`` `/${string}/products/${string}` ``), and whether a
6
- * path handed in fits it.
4
+ * `'/:locale/products/:id'` yields its params (`{ locale, id }`) and its
5
+ * concrete-path type (`` `/${string}/products/${string}` ``).
7
6
  */
8
- type SegParam<Segment extends string> = Segment extends `:${infer Name}` ? Record<Name, string> : object;
7
+ type SegParam<Segment extends string> = Segment extends `:${infer Name}+` ? Record<Name, readonly string[]> : Segment extends `:${infer Name}` ? Record<Name, string> : object;
9
8
  type SegListParams<Rest extends string> = Rest extends `${infer Segment}/${infer Tail}` ? SegParam<Segment> & SegListParams<Tail> : SegParam<Rest>;
10
- /** `'/:locale/products/:id'` → `{ locale: string; id: string }` */
9
+ /**
10
+ * `'/:locale/products/:id'` → `{ locale: string; id: string }`, and a rest
11
+ * param — `'/files/:path+'` — is every segment it took:
12
+ * `{ path: readonly string[] }`.
13
+ */
11
14
  export type ParamsOf<Pattern extends string> = Pattern extends `/${infer Rest}` ? SegListParams<Rest> : object;
12
15
  /**
13
16
  * The shape every validation library agrees on (Standard Schema): a value
@@ -30,36 +33,25 @@ export type SchemaOutput<Schema> = Schema extends StandardSchemaLike<infer Outpu
30
33
  * pattern does not name has nothing to validate.
31
34
  */
32
35
  export type ParamsSchemaFor<Pattern extends string> = StandardSchemaLike<Partial<Record<keyof ParamsOf<Pattern> & string, unknown>>>;
33
- type MergedOutput<Schemas extends readonly unknown[]> = Schemas extends readonly [infer Head, ...infer Tail] ? Omit<MergedOutput<Tail>, keyof SchemaOutput<Head>> & SchemaOutput<Head> : object;
36
+ type MergedOutput<Schemas extends readonly unknown[]> = Schemas extends readonly [...infer Init, infer Last] ? Omit<MergedOutput<Init>, keyof SchemaOutput<Last>> & SchemaOutput<Last> : object;
34
37
  /**
35
38
  * A pattern's params after the schemas along its stack have run — outer
36
- * layouts first, the page last — each replacing the strings it names with
37
- * what it produced. Params no schema names stay strings.
39
+ * layouts first, the page last — each replacing what it names with what it
40
+ * produced, so of two schemas that name one param, the later one's output is
41
+ * what the page receives. Params no schema names stay strings. A union of
42
+ * stacks gives the union of what each one produces.
38
43
  */
39
- export type ParsedParams<Pattern extends string, Schemas extends readonly unknown[]> = Omit<ParamsOf<Pattern>, keyof MergedOutput<Schemas>> & MergedOutput<Schemas>;
44
+ export type ParsedParams<Pattern extends string, Schemas extends readonly unknown[]> = Schemas extends unknown ? Omit<ParamsOf<Pattern>, keyof MergedOutput<Schemas>> & MergedOutput<Schemas> : never;
40
45
  /** `{ '/products/:id': [schema, …] }` → `{ '/products/:id': { id: number } }` */
41
46
  export type ParsedParamsMap<Schemas extends Record<string, readonly unknown[]>> = { [Pattern in keyof Schemas & string]: ParsedParams<Pattern, Schemas[Pattern]>; };
42
47
  type SegPath<Segment extends string> = Segment extends `:${string}` ? string : Segment;
43
48
  type SegListPath<Rest extends string> = Rest extends `${infer Segment}/${infer Tail}` ? `${SegPath<Segment>}/${SegListPath<Tail>}` : SegPath<Rest>;
44
- /** `'/:locale/products/:id'` → `` `/${string}/products/${string}` `` */
45
- export type PathFor<Pattern extends string> = Pattern extends `/${infer Rest}` ? `/${SegListPath<Rest>}` : never;
46
- /**
47
- * One segment of a path against one segment of a pattern, the way URLPattern
48
- * reads a `:param`: any single segment that is not empty. A `${string}` in
49
- * the path — a param built into a template literal — counts as one segment.
50
- */
51
- type SegmentFits<Segment extends string, PatternSegment extends string> = PatternSegment extends `:${string}` ? Segment extends '' ? false : true : Segment extends PatternSegment ? true : false;
52
- type SegmentsFit<Rest extends string, PatternRest extends string> = Rest extends `${infer Segment}/${infer Tail}` ? PatternRest extends `${infer PatternSegment}/${infer PatternTail}` ? SegmentFits<Segment, PatternSegment> extends true ? SegmentsFit<Tail, PatternTail> : false : false : PatternRest extends `${string}/${string}` ? false : SegmentFits<Rest, PatternRest>;
53
- type FitsAny<Path extends string, Pattern extends string> = Pattern extends `/${infer PatternRest}` ? Path extends `/${infer Rest}` ? SegmentsFit<Rest, PatternRest> : false : never;
54
49
  /**
55
- * `Path` when one of `Patterns` matches it segment by segment, `never` when
56
- * none does. A union of paths keeps only the members that match.
57
- *
58
- * The path is checked against the patterns, never collected into a union of
59
- * `PathFor` each pattern: `/:locale` would put `/${string}` in that union,
60
- * and `/${string}` takes every path there is.
50
+ * `'/:locale/products/:id'` → `` `/${string}/products/${string}` ``. A rest
51
+ * param is a `${string}` too — `'/files/:path+'` → `` `/files/${string}` `` —
52
+ * since a template's `${string}` spans the slashes between its segments.
61
53
  */
62
- export type PathMatching<Path extends string, Patterns extends string> = Path extends string ? true extends FitsAny<Path, Patterns> ? Path : never : never;
54
+ export type PathFor<Pattern extends string> = Pattern extends `/${infer Rest}` ? `/${SegListPath<Rest>}` : never;
63
55
  /**
64
56
  * Keys that address the parent's own place instead of a place below it:
65
57
  * `'/'` (the branch's index) and `'/(name)'` (a group, which structures the
@@ -80,5 +72,11 @@ export declare const normalizePathname: (pathname: string) => string;
80
72
  export declare const decodeOrKeep: (value: string) => string;
81
73
  /** What a param value may be on the way into a link: anything with one spelling. */
82
74
  export type ParamValue = string | number | bigint | boolean;
75
+ /**
76
+ * A pattern's params out of what URLPattern captured: a `:param` decoded, a
77
+ * rest param (`:name+`) split into the segments it took, each decoded on its
78
+ * own — so an escaped slash stays inside its segment.
79
+ */
80
+ export declare const readParams: (pattern: string, groups: Readonly<Record<string, string | undefined>>) => Record<string, string | readonly string[]>;
83
81
  export declare const buildHref: (pattern: string, params: Readonly<Record<string, unknown>> | undefined) => string;
84
82
  export {};
package/dist/paths.mjs CHANGED
@@ -19,15 +19,43 @@ const decodeOrKeep = (value) => {
19
19
  return value;
20
20
  }
21
21
  };
22
+ /** The name a rest segment (`:name+`) gives its param, or `null` for any other segment. */
23
+ const restNameOf = (segment) => segment.startsWith(":") && segment.endsWith("+") ? segment.slice(1, -1) : null;
24
+ /**
25
+ * A pattern's params out of what URLPattern captured: a `:param` decoded, a
26
+ * rest param (`:name+`) split into the segments it took, each decoded on its
27
+ * own — so an escaped slash stays inside its segment.
28
+ */
29
+ const readParams = (pattern, groups) => {
30
+ const rest = new Set(pattern.split("/").map(restNameOf));
31
+ const params = {};
32
+ for (const [name, value] of Object.entries(groups)) {
33
+ if (/^\d+$/u.test(name) || value === void 0) continue;
34
+ params[name] = rest.has(name) ? value.split("/").map(decodeOrKeep) : decodeOrKeep(value);
35
+ }
36
+ return params;
37
+ };
38
+ const isParamValue = (value) => typeof value === "string" || typeof value === "number" || typeof value === "bigint" || typeof value === "boolean";
39
+ const restSegments = (pattern, name, value) => {
40
+ if (!Array.isArray(value)) throw new TypeError(`"${pattern}" takes an array of segments for ":${name}+"`);
41
+ if (value.length === 0) throw new TypeError(`"${pattern}" needs at least one segment for ":${name}+"`);
42
+ return value.map((segment) => {
43
+ if (!isParamValue(segment)) throw new TypeError(`"${pattern}" got a segment for ":${name}+" that has no URL spelling`);
44
+ if (segment === "") throw new TypeError(`"${pattern}" got an empty segment for ":${name}+"`);
45
+ return encodeURIComponent(String(segment));
46
+ }).join("/");
47
+ };
22
48
  const buildHref = (pattern, params) => {
23
49
  if (pattern.includes("*")) throw new TypeError(`"${pattern}" is a wildcard — it has no href`);
24
50
  return pattern.split("/").map((segment) => {
25
51
  if (!segment.startsWith(":")) return segment;
26
- const name = segment.slice(1);
52
+ const rest = restNameOf(segment);
53
+ const name = rest ?? segment.slice(1);
27
54
  const value = params?.[name];
28
- if (value === void 0) throw new TypeError(`"${pattern}" needs a value for ":${name}"`);
29
- if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint" && typeof value !== "boolean") throw new TypeError(`"${pattern}" got a value for ":${name}" that has no URL spelling`);
55
+ if (value === void 0) throw new TypeError(`"${pattern}" needs a value for "${segment}"`);
56
+ if (rest !== null) return restSegments(pattern, name, value);
57
+ if (!isParamValue(value)) throw new TypeError(`"${pattern}" got a value for ":${name}" that has no URL spelling`);
30
58
  return encodeURIComponent(String(value));
31
59
  }).join("/");
32
60
  };
33
- export { buildHref, decodeOrKeep, isGroupKey, joinPattern, normalizePathname };
61
+ export { buildHref, decodeOrKeep, isGroupKey, joinPattern, normalizePathname, readParams };
@@ -1,5 +1,5 @@
1
- import { ParamValue, ParamsOf } from "./paths.mjs";
2
1
  import { NavigablePatternOf, PatternOf, Routes, RoutesRecord } from "./define-routes.mjs";
2
+ import { ParamValue, ParamsOf } from "./paths.mjs";
3
3
  import { ReactNode } from "react";
4
4
  /**
5
5
  * The app-side hook for the route table's type. An application augments this
@@ -11,7 +11,7 @@ import { ReactNode } from "react";
11
11
  * }
12
12
  * ```
13
13
  *
14
- * and `href` / `navigateTo` / `useParams` verify their pattern against the
14
+ * and `href` / `useParams` verify their pattern against the
15
15
  * table everywhere — without any component importing the table's value.
16
16
  * Only `<Router>` touches the value; everything else needs just the string
17
17
  * pattern, so the routes-module → pages → routes-module import cycle never
@@ -33,8 +33,11 @@ export type RegisteredNavigablePattern = Register extends {
33
33
  type RegisteredParamsMap = Register extends {
34
34
  params: infer M;
35
35
  } ? M : null;
36
- /** The pattern's params as anything with one spelling, before any schema. */
37
- type LooseParamsOf<P extends string> = { [K in keyof ParamsOf<P>]: ParamValue; };
36
+ /**
37
+ * The pattern's params as anything with one spelling, before any schema — a
38
+ * rest param as an array of them, one per segment.
39
+ */
40
+ type LooseParamsOf<P extends string> = { [K in keyof ParamsOf<P>]: ParamsOf<P>[K] extends readonly string[] ? readonly ParamValue[] : ParamValue; };
38
41
  /**
39
42
  * A pattern's params as a link takes them: where the registered `params`
40
43
  * map — written by the framework from the schemas the route files declared
@@ -91,13 +94,13 @@ export type PageProps<P extends RegisteredPattern> = {
91
94
  } & RequestProps & SearchProps<P>;
92
95
  /**
93
96
  * The props a `layout.tsx` receives, by the prefix every route below it
94
- * shares — only where the table also has a page at that prefix, since the
95
- * constraint is a page pattern; a layout with no page of its own declares
96
- * its props inline. Its params are strings whatever it declared: a
97
- * `not-found.tsx` renders under it whether or not its schemas accepted, and
98
- * a typed value there would be a lie.
97
+ * shares — any pattern, a layout whose directory has no page of its own
98
+ * included: the generated table checks the props against the layout's own
99
+ * pattern at the import, so a wrong one fails there. Its params are strings
100
+ * whatever it declared: a `not-found.tsx` renders under it whether or not
101
+ * its schemas accepted, and a typed value there would be a lie.
99
102
  */
100
- export type LayoutProps<P extends RegisteredPattern> = {
103
+ export type LayoutProps<P extends string> = {
101
104
  readonly params: ParamsOf<P>;
102
105
  readonly pathname: string;
103
106
  readonly children: ReactNode;
package/dist/router.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { ParamsOf } from "./paths.mjs";
2
1
  import { Match, Routes } from "./define-routes.mjs";
2
+ import { ParamsOf } from "./paths.mjs";
3
3
  import { RegisteredPattern } from "./register.mjs";
4
4
  import { ReactNode } from "react";
5
5
  /**
package/dist/router.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  "use client";
2
- import { normalizePathname } from "./paths.mjs";
3
2
  import { withoutBase } from "./base.mjs";
4
3
  import { PathnameProvider, appPathname } from "./location.mjs";
5
4
  import { NavigationGeneration, useInterceptedNavigation } from "./navigation.mjs";
6
5
  import { RenderStack } from "./outlet.mjs";
6
+ import { normalizePathname } from "./paths.mjs";
7
7
  import { TreePathname } from "./tree-pathname.mjs";
8
8
  import { createContext, use, useDeferredValue, useMemo, useState } from "react";
9
9
  import { jsx } from "react/jsx-runtime";
package/docs/GUIDE.md CHANGED
@@ -31,7 +31,7 @@ routes.ts defineRoutes({ … }) the pathname schema, one place
31
31
  ↓ mounted once
32
32
  <Router routes> match → stack → render layouts wrap through <Outlet />
33
33
  ↑ never imported by pages
34
- pages href / navigateTo / useParams
34
+ pages href / useParams
35
35
  take the pattern string; Register supplies the check
36
36
  ```
37
37
 
@@ -73,6 +73,8 @@ export const routes = defineRoutes({
73
73
  and a child key of `'/'` is the branch's own index page.
74
74
  - **`/:name`** captures a segment, decoded. **`/*`** matches whatever nothing
75
75
  before it did.
76
+ - **`/:name+`** is a rest param: it captures every remaining segment, one or
77
+ more, as an array ([Rest params](#rest-params)).
76
78
  - **`/(name)`** is a route group: it structures the table — its own layout, its
77
79
  own subtree — without contributing a URL segment. It exists because `'/'` can
78
80
  only appear once in an object, so two sections at the same depth could not
@@ -100,17 +102,66 @@ defineRoutes({ '/about': About, '/:slug': Article }); // /about → About
100
102
 
101
103
  Put `/*` last, for the same reason.
102
104
 
103
- ### What fails at definition time
105
+ ### Rest params
106
+
107
+ `/:name+` ends a pattern and takes every segment left — one or more, never
108
+ zero — as an array, each segment decoded on its own:
109
+
110
+ ```ts
111
+ const routes = defineRoutes({
112
+ '/files': FileIndex,
113
+ '/files/:path+': FilePage,
114
+ });
115
+
116
+ routes.match('/files/a/b')?.params; // { path: ['a', 'b'] }
117
+ routes.match('/files/a%2Fb/c')?.params; // { path: ['a/b', 'c'] }
118
+ routes.match('/files')?.pattern; // '/files' — zero segments is not a match
119
+ ```
120
+
121
+ A link takes the same array, and escapes each segment before joining them
122
+ with `/`:
123
+
124
+ ```ts
125
+ href('/files/:path+', { path: ['a/b', 'c'] }); // '/files/a%2Fb/c'
126
+ href('/files/:path+', { path: [] }); // ✗ throws: at least one segment
127
+ href('/files/:path+', { path: ['a', ''] }); // ✗ throws: an empty segment
128
+ ```
129
+
130
+ A bound `href` (`bindParams`) takes it the same way, and `useParams`,
131
+ `useMatch` and `matchPath` hand back the array. In the types, `ParamsOf`
132
+ gives `{ path: readonly string[] }`, a link takes an array of anything with
133
+ one spelling, and `PathFor<'/files/:path+'>` is `` `/files/${string}` ``.
104
134
 
105
- A table is checked when the module loads, not when someone first navigates:
135
+ It also takes the one segment a `/:name` beside it takes, so order decides
136
+ between them as between everything else: declare `/files/:id` first, or it
137
+ never matches. There is no optional form — `:name*` and `:name?` are refused
138
+ when the table is defined: a pattern for the prefix itself — `/files` above —
139
+ is what answers zero segments.
106
140
 
107
- | written | error |
108
- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
109
- | the same full pattern twice, wherever the copies nest | `route pattern "/x" is declared twice` |
110
- | a group with no children (it would redeclare the index) | `route group "/(oops)" must have children` |
111
- | a key not starting with `/` | `route pattern "x" must start with "/"` |
112
- | parentheses that are not exactly a group (`/(admin)/new`) | `route group "/(admin)/new" must be "/(name)" and nothing else — a regular expression is not part of the grammar` |
113
- | a pattern URLPattern cannot parse | URLPattern's own `TypeError` |
141
+ ### What fails at definition time
142
+
143
+ A table is checked when the module loads, not when someone first navigates.
144
+ The grammar is the forms above and nothing more: a literal segment, a
145
+ `:name` (a JavaScript identifier, as URLPattern reads one), and — as the
146
+ last segment of the full pattern — a `:name+` or a `*`, plus `/(name)`
147
+ groups. URLPattern reads much more (`:id?`, `:path*`, `{…}`, a param inside
148
+ a segment), and the types would read those differently from the matching,
149
+ so every other spelling is refused:
150
+
151
+ | written | error |
152
+ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
153
+ | a segment outside the grammar (`/:id?`, `/files/:path*`, `/foo-:bar`, `/files/*.pdf`) | `route pattern "/:id?" has the segment ":id?", which is not part of the grammar — …`, followed by what a segment may be |
154
+ | a rest param or a wildcard before the end of the full pattern | `route pattern "/files/:path+/edit" puts ":path+" before the end — a rest param must be the last segment` |
155
+ | an empty segment (`/a//b`, `/a/`) | `route pattern "/a/" has an empty segment — …` |
156
+ | the same full pattern twice, wherever the copies nest | `route pattern "/x" is declared twice` |
157
+ | a group with no children (it would redeclare the index) | `route group "/(oops)" must have children` |
158
+ | a key not starting with `/` | `route pattern "x" must start with "/"` |
159
+ | parentheses that are not exactly a group (`/(admin)/new`) | `route group "/(admin)/new" must be "/(name)" and nothing else — a regular expression is not part of the grammar` |
160
+
161
+ The position is read on the full pattern, not on the key:
162
+ `'/files/:path+': { children: { '/edit': FileEditor } }` is refused as
163
+ `/files/:path+/edit`, while a branch whose children are only its `'/'` index
164
+ keeps the rest param last.
114
165
 
115
166
  ## Mounting it
116
167
 
@@ -138,9 +189,11 @@ in the browser; the rest is left alone, so a real document load — and a real
138
189
  nothing rather than guessing.
139
190
 
140
191
  Four kinds of navigation are never the application's, whatever the table says:
141
- a reload, a form submitted with a body (POST), a download, and a fragment-only
142
- change — nor is any navigation the platform does not let a page intercept,
143
- such as one to another origin. Intercepting any of the four would silently do
192
+ a reload, a form submitted with a body (POST), a download, and a move to a
193
+ fragment within the document — nor is any navigation the platform does not
194
+ let a page intercept, such as one to another origin. A move that drops the
195
+ fragment (`/docs#api` to `/docs`) is not a move to a fragment: the platform
196
+ loads a document for it, so it is the application's like any other. Intercepting any of the four would silently do
144
197
  nothing where the platform would have done the obvious thing — a POST body
145
198
  only the server can act on, an `F5` that stops reloading. A GET form carries
146
199
  no body, so the search-shaped submissions `@k8ordo/state` builds still come
@@ -167,19 +220,13 @@ layout, or around the lazy component itself.
167
220
  ## Links and navigation
168
221
 
169
222
  ```tsx
170
- import {
171
- href,
172
- navigateTo,
173
- useParams,
174
- usePathname,
175
- useRoute,
176
- } from '@k8ordo/router';
223
+ import { href, useParams, usePathname, useRoute } from '@k8ordo/router';
177
224
 
178
225
  <a href={href('/products/:id', { id })}>…</a>;
179
226
  <a href={href('/products')}>…</a>; // no params, no second argument
180
227
 
181
- navigateTo('/products/:id', { id }); // pushes: the back button undoes it
182
- navigateTo('/products', { history: 'replace' });
228
+ navigation.navigate(href('/products/:id', { id })); // the same URL, from code
229
+ navigation.navigate(href('/products'), { history: 'replace' });
183
230
 
184
231
  const { id } = useParams('/products/:id');
185
232
  const { pattern } = useRoute(); // untyped: the winning pattern and its params
@@ -197,8 +244,17 @@ import { matchPath, useMatch } from '@k8ordo/router';
197
244
  useMatch('/products/:id'); // { id } when that page is showing, else null
198
245
  useMatch('/products/*'); // {} anywhere under /products, else null
199
246
  matchPath('/products/:id', pathname); // the same, pure, for a pathname in hand
247
+ useMatch('/files/:path+'); // { path: ['a', 'b'] } on /files/a/b
200
248
  ```
201
249
 
250
+ **The current link is asked by pattern, never by URL.** In a Server
251
+ Component — a framework layout, which receives `pathname` — ask
252
+ `matchPath(pattern, pathname)`: it is a pure function in a module with no
253
+ directive, so the server calls it itself. In a Client Component, ask
254
+ `useMatch(pattern)`. Never compare `pathname === href(…)`: a pathname is in
255
+ the table's terms and `href` returns the URL with Vite's `base` in front, so
256
+ under a base the two never agree.
257
+
202
258
  `useMatch` takes a pattern from the table, or a table pattern followed by
203
259
  `/*` to mean "everything below it" — what a sidebar asks when it wants to
204
260
  know which section of the site is open. The pattern's own page is not below
@@ -223,8 +279,8 @@ is going — `null` when none is — set as the navigation starts and cleared on
223
279
  the new page is on screen or the navigation is given up; a state change sets
224
280
  nothing, unless the host loads the page again for it (a framework page that
225
281
  reads the search), which is a load in progress like any other. The caller that
226
- started it can instead await `navigateTo`'s `finished` — it resolves when the
227
- tree is on screen (below).
282
+ started it can instead await the `finished` its `navigation.navigate()`
283
+ returned — it resolves when the tree is on screen (below).
228
284
 
229
285
  `usePathname` reads the platform rather than the table, which is why it is the
230
286
  one that also works under the framework, where the browser holds no table at
@@ -249,39 +305,40 @@ import { bindParams } from '@k8ordo/router';
249
305
 
250
306
  import { locales } from './i18n';
251
307
 
252
- export const { href, navigateTo } = bindParams(() => ({
308
+ export const href = bindParams(() => ({
253
309
  locale: locales.getLocale(),
254
310
  }));
255
311
  ```
256
312
 
257
313
  ```tsx
258
314
  href('/:locale/products/:id', { id }); // locale from the source, id as before
259
- navigateTo('/:locale', { locale: 'en' }, { history: 'replace' }); // or overridden
260
- navigateTo('/:locale', undefined, { history: 'replace' }); // options stay third
315
+ href('/:locale', { locale: 'en' }); // or overridden
261
316
  ```
262
317
 
263
- Patterns keep their full spelling, so the table's types apply unchanged; the
264
- source is read at each call, so a value that differs per request or per URL
265
- is read where it is current. Options still come after the params whenever
266
- the pattern names one, even when the source supplies them all — params and
267
- options are both plain objects, and the pattern alone decides which is which —
268
- so the params slot is passed as `undefined`, as in the last line above. Which
269
- package supplies the value is the application's business — the router knows a
270
- param name, nothing more.
318
+ `bindParams` returns the bound `href` itself. Patterns keep their full
319
+ spelling, so the table's types apply unchanged; the source is read at each
320
+ call, so a value that differs per request or per URL is read where it is
321
+ current. Which package supplies the value is the application's business — the
322
+ router knows a param name, nothing more. Import `href` from that one module
323
+ everywhere, so no link reaches for the unbound one by accident.
271
324
  `normalizePathname` is the router's own reading of a pathname — a trailing
272
325
  slash dropped, root excepted — for code that compares pathnames the way the
273
326
  table does.
274
327
 
275
- `navigateTo` returns the platform's own `{ committed, finished }`. `finished`
276
- resolves once the new page is on screen, so an async action can await it and
277
- let `isPending` cover the wait:
328
+ **A page change from code is the platform's own call.**
329
+ `navigation.navigate(href(…))` goes to the same URL the link would, and the
330
+ router intercepts it the same way. There is no wrapper: `href` already does
331
+ the typing and the base, and a second function would be a second way to
332
+ write the same thing, as `<Link>` would. The call returns the platform's
333
+ `{ committed, finished }`, and `finished` resolves once the new page is on
334
+ screen, so an async action can await it and let `isPending` cover the wait:
278
335
 
279
336
  ```tsx
280
337
  const [isPending, startTransition] = useTransition();
281
338
 
282
339
  startTransition(async () => {
283
340
  try {
284
- await navigateTo('/products/:id', { id }).finished;
341
+ await navigation.navigate(href('/products/:id', { id })).finished;
285
342
  } catch (error) {
286
343
  // overtaken by another navigation
287
344
  if (!(error instanceof DOMException && error.name === 'AbortError')) {
@@ -292,16 +349,43 @@ startTransition(async () => {
292
349
  ```
293
350
 
294
351
  The page change does not join the action, so awaiting `finished` inside one —
295
- `useTransition`'s, `@k8ordo/ui`'s `Button` `onAction`, a `<form action>` —
352
+ `useTransition`'s, `@k8ordo/ui`'s `Button` `action`, a `<form action>` —
296
353
  settles as soon as the page is on screen, and `isPending` covers exactly that
297
354
  wait. An event handler can await it the same way. A page change started while
298
355
  some unrelated action is still pending reaches the screen without waiting for
299
356
  that action either.
300
357
 
301
- Its default is `push`, the opposite of `@k8ordo/state`'s `update()`, and for
302
- the same reason: going to a page is what the back button should undo, while
303
- refining what is on the page is not. **Changing pages goes through
304
- `navigateTo`; changing state goes through `update`.**
358
+ Its default, `'auto'`, pushes an entry for another URL and replaces the
359
+ current one for the same URL, as following a link does — the opposite of
360
+ `@k8ordo/state`'s `update()`, which replaces by default, and for the same
361
+ reason: going to a page is what the back button should undo, while refining
362
+ what is on the page is not. **Changing pages is
363
+ `navigation.navigate(href(…))`, the same URL as `<a href>`; changing state
364
+ is `update()`.**
365
+
366
+ ## One way per URL
367
+
368
+ Each thing an application does with a URL has one spelling, the same under
369
+ `@k8ordo/router`, `@k8ordo/state` and `@k8ordo/framework`:
370
+
371
+ | to | write |
372
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------- |
373
+ | link to a page | `href(pattern, params)` |
374
+ | link to a page with its state | `def.href(href(pattern, params), values)` |
375
+ | link to the page itself with other state | `def.href('', values)` |
376
+ | ask which page is showing | `matchPath(pattern, pathname)` in a Server Component, `useMatch(pattern)` in a client |
377
+ | change the page from code | `navigation.navigate(href(pattern, params))`, the link's own URL |
378
+ | change the state | `update(values)` |
379
+ | move a page for good | `redirect.ts`, its `to` a table pattern (`@k8ordo/framework`) |
380
+ | redirect from a Server Action, a `guard.ts` or a `route.ts` | `redirect(href(pattern, params))` (`@k8ordo/framework/server`) |
381
+ | show the page on screen in another locale | `withBase(locales.localize(pathname, locale))` |
382
+
383
+ The last row is the one URL built from a pathname rather than a pattern: the
384
+ page showing may be any page. Nothing else compares or combines `pathname` and
385
+ `href()` — `pathname` is in the table's terms and `href()` carries Vite's
386
+ `base`. In a `[locale]` application, import `href` only from the module that
387
+ binds the locale (`export const href = bindParams(…)`): the router's own
388
+ `href` has the same name and type-checks too.
305
389
 
306
390
  ## Served under a base
307
391
 
@@ -310,7 +394,7 @@ the application is served below one — Vite's
310
394
  [`base`](https://vite.dev/config/shared-options#base), `base: '/docs/'`. The
311
395
  router reads it from `import.meta.env.BASE_URL` and does the rest:
312
396
 
313
- - `href` and `navigateTo` put it in front of every link: `href('/products')`
397
+ - `href` puts it in front of every link: `href('/products')`
314
398
  is `/docs/products`, and `href('/')` is `/docs/`.
315
399
  - `usePathname` takes it off, so what it returns compares with the patterns:
316
400
  `/products` at `/docs/products`. `useMatch` follows, and `<Router>` matches
@@ -352,15 +436,14 @@ only in an application — a library doing it would impose its table on every
352
436
  consumer.
353
437
 
354
438
  Under `@k8ordo/framework` this file is generated into
355
- `.k8ordo/register.gen.ts` from `routes/` — for `@k8ordo/state` too, when the
356
- application depends on it — so hand-writing it there is writing a second
357
- answer to a question already answered. Hand-write it in a client application
439
+ `.k8ordo/register.gen.ts` from `routes/`, so hand-writing it there is
440
+ writing a second answer to a question already answered. Hand-write it in a client application
358
441
  that mounts `<Router>` itself.
359
442
 
360
443
  The framework's generated `Register` also carries `params`: per pattern, the
361
- type the route file's `paramsSchema` produces. With it, `href` and
362
- `navigateTo` take a param as the page receives it — `{ id: 42 }` for a
363
- schema that said number — and spell it the one way the schema reads back. A
444
+ type the route file's `paramsSchema` produces. With it, `href`
445
+ takes a param as the page receives it — `{ id: 42 }` for a
446
+ schema that said number — and spells it the one way the schema reads back. A
364
447
  value with no URL spelling (an object) is refused. Before `Register` is
365
448
  augmented — or for a pattern no schema along its stack covers — a link takes
366
449
  any value with one spelling (a string, a number, a bigint, a boolean), so a
@@ -377,31 +460,19 @@ link to `P` takes) and `RegisteredPageParams<P>` (what the page at `P`
377
460
  receives). Before the augmentation the first two are any `/`-prefixed
378
461
  string.
379
462
 
380
- ## Typed paths for @k8ordo/state
463
+ ## Links that carry state
381
464
 
382
- `@k8ordo/state`'s `Register` takes the same line this one does:
465
+ `@k8ordo/state` builds on the URL `href` returns: a page state's
466
+ `href(url, values)` puts its own search params and fragment on it, and adds
467
+ no base of its own.
383
468
 
384
469
  ```ts
385
- declare module '@k8ordo/state' {
386
- interface Register {
387
- routes: typeof routes;
388
- }
389
- }
470
+ listState.href(href('/products'), { q, page: 2 }); // '/products?q=…&page=2'
390
471
  ```
391
472
 
392
- With that, `listState.href('/products', { q })` is checked against the same
393
- table this router matches against, and the two packages agree on what a path
394
- is. `NavigablePath<typeof routes, Path>` is that check, for any other
395
- typed-path consumer: `Path` itself when one of the table's linkable patterns
396
- matches it segment by segment — a literal segment spelled as the pattern
397
- spells it, a `:param` taking any one non-empty segment, a `${string}` from a
398
- template literal included — and `never` when none does. A trailing slash is
399
- refused: matching treats `/products/` as `/products`, but a path built for a
400
- link is spelled the one canonical way.
401
-
402
- The path is checked against the patterns rather than collected into a union
403
- of every path the table has: a `/:locale` page would put `/${string}` in such
404
- a union, and `/${string}` takes every path there is.
473
+ The pattern is checked once, here, against the table; state has no table of
474
+ its own to register. A path is never checked on its own: a URL is built with
475
+ `href` from a pattern, so there is no type for a hand-written path to pass.
405
476
 
406
477
  ## What navigation guarantees
407
478
 
@@ -630,8 +701,8 @@ a class, since a page and the framework may hold two copies of this package.
630
701
  Under a client `<Router>` there is no status to answer with, and `notFound()`
631
702
  is an error like any other.
632
703
 
633
- What carries across unchanged is everything that needs no table: `href`,
634
- `navigateTo` and `bindParams`, `usePathname`, `useMatch` and `matchPath`, and
704
+ What carries across unchanged is everything that needs no table: `href` and
705
+ `bindParams`, `usePathname`, `useMatch` and `matchPath`, and
635
706
  `normalizePathname` — an application on the framework imports them from
636
707
  `@k8ordo/framework`, which re-exports them by name, and never names this
637
708
  package. `usePathname` needs one thing on the server,
@@ -658,6 +729,6 @@ strings whatever the schemas say, since `not-found.tsx` renders under a layout
658
729
  whether or not its schemas accepted. In server mode the generated `Register` also carries
659
730
  the `request`, so both types gain `request` there and a page that reads it
660
731
  fails to type-check under a build into files. A route file may equally declare
661
- its props inline — the generated table checks them at the import either way —
662
- and a layout whose pattern has no page of its own has to: `LayoutProps` takes
663
- only a pattern the table has a page at.
732
+ its props inline — the generated table checks them at the import either way.
733
+ `PageProps` takes a pattern the table has a page at, and `LayoutProps` any
734
+ pattern, a layout's with no page of its own included.
package/docs/llms.txt CHANGED
@@ -14,9 +14,11 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
14
14
  ## Guide
15
15
 
16
16
  - [Design Guide](GUIDE.md): the table's grammar (leaves, branches, params,
17
- wildcards, route groups, declaration order), mounting `<Router>` and
18
- `<Outlet>`, links without a `<Link>` component, `useMatch` for active
19
- sections, `Register` for checked patterns, what navigation guarantees
17
+ rest params, wildcards, route groups, declaration order, what fails at
18
+ definition time), mounting `<Router>` and
19
+ `<Outlet>`, links without a `<Link>` component, `useMatch` / `matchPath`
20
+ for active sections, the one way to write each URL (a table shared with
21
+ `@k8ordo/state` and `@k8ordo/framework`), `Register` for checked patterns, what navigation guarantees
20
22
  (`finished` after commit, scroll to top or fragment on a new page, and
21
23
  back to where an entry was left on back and forward), how
22
24
  a `<ViewTransition>` animates page changes by the router's transition
@@ -26,7 +28,11 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
26
28
 
27
29
  ## Entry point
28
30
 
29
- - `@k8ordo/router` — `defineRoutes(record)` returns a table that answers
31
+ - `@k8ordo/router` — `defineRoutes(record)` throws a `TypeError` naming the
32
+ pattern and the rule for any leaf pattern outside the grammar (a segment is
33
+ a literal without `: * ? + { } ( ) \`, a `:name`, or — last in the full
34
+ pattern — a `:name+` or a `*`; plus `/(name)` groups; `:id?`, `:path*` and
35
+ `foo-:bar` are refused), and returns a table that answers
30
36
  `match(pathname)`, the first pattern that fits, and `matchAll(pathname)`,
31
37
  every one in declaration order — the framework walks the second and passes
32
38
  over a fit whose param a schema refused; `<Router routes>` mounts it on the Navigation API and
@@ -34,48 +40,56 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
34
40
  component (props `ErrorProps`, `{ error, reset }`; type `ErrorComponent`)
35
41
  renders in the layout's hole when what is below throws; the next
36
42
  `NavigationGeneration` clears the failure without remounting what the
37
- boundary wraps. `href(pattern, params?)`
38
- and `navigateTo(pattern, params?, options?)` build and perform navigations
39
- from the pattern **string** alone — no table import, so no cycle — with
40
- params inferred from the literal and the pattern itself checked once
41
- `interface Register { routes }` is augmented. `useParams(pattern)` returns
43
+ boundary wraps. `href(pattern, params?)` builds the URL from the pattern
44
+ **string** alone — no table import, so no cycle — with params inferred
45
+ from the literal and the pattern itself checked once
46
+ `interface Register { routes }` is augmented; a page change from code is
47
+ the platform's `navigation.navigate(href(…))`, the same URL a link points
48
+ at (there is no `navigateTo`), and a state change is `@k8ordo/state`'s
49
+ `update()`. A rest param, `/files/:path+`,
50
+ takes every remaining segment — one or more, never zero — and is an array
51
+ everywhere: `match` / `matchPath` / `useMatch` / `useParams` return
52
+ `{ path: ['a', 'b'] }` with each segment decoded on its own, and `href`
53
+ (bound or not) takes `{ path: ['a', 'b'] }`, escapes each
54
+ segment and joins them with `/`, throwing for an empty array or an empty
55
+ segment (`ParamsOf` gives `readonly string[]`, `PathFor` `/files/${string}`).
56
+ `useParams(pattern)` returns
42
57
  typed params and throws if rendered under a different pattern; under the
43
58
  framework `Register` also carries `params` — the type each pattern's
44
59
  `paramsSchema` produces — so `href` takes a param as the page receives it
45
60
  (`ParsedParams` / `ParsedParamsMap` / `ParamsSchemaFor` / `ParamsOf` /
46
61
  `ErrorComponent` are the types the generated code imports); `useRoute()`
47
- is the untyped form.
48
- `@k8ordo/state`'s `Register` takes the same `routes: typeof routes`;
49
- `NavigablePath<typeof routes, Path>` is `Path` when a linkable pattern
50
- matches it segment by segment (a `:param` takes one non-empty segment)
51
- and `never` otherwise — a check of the path given, never a union of every
52
- path, which a `/:locale` page would turn into `/${string}` — for any other
53
- typed-path consumer. `usePathname()` reads the platform's
62
+ is the untyped form. `@k8ordo/state` builds on the URL `href` returns
63
+ (`listState.href(href('/products'), { page: 2 })`), with no `Register` of
64
+ its own; a path is never checked on its own — a URL is built with `href`.
65
+ `usePathname()` reads the platform's
54
66
  pathname — never the search — so it works with or without a table, which
55
67
  makes it the location hook that also works under the framework;
56
68
  `useMatch(pattern, options?)` / `matchPath(pattern, pathname, options?)`
57
69
  answer whether that pattern — or, with a trailing `/*`, anything strictly
58
70
  below it — is the pathname showing, with its params, table-free, so a
59
71
  sidebar can ask which section is open under the framework too, and
60
- `{ inclusive: true }` on either counts a `/*` pattern's own index in;
72
+ `{ inclusive: true }` on either counts a `/*` pattern's own index in —
73
+ `matchPath` sits in a module with no directive, so a Server Component (a
74
+ framework layout, with its `pathname` prop) calls it, while `useMatch` is
75
+ for a client; never compare `pathname === href(…)` (the base differs);
61
76
  `normalizePathname(pathname)` is the router's own trailing-slash rule;
62
- under Vite's `base` (`import.meta.env.BASE_URL`, e.g. `/docs/`) `href` /
63
- `navigateTo` put it in front of every link (so `href` returns a `string`
77
+ under Vite's `base` (`import.meta.env.BASE_URL`, e.g. `/docs/`) `href`
78
+ puts it in front of every link (so `href` returns a `string`
64
79
  URL, not a table path) and `usePathname` / `<Router>` take it off, a URL
65
80
  outside it being left to the browser — `withBase(pathname, base?)` /
66
81
  `withoutBase(pathname, base?)` (`null` outside the base) are the two steps;
67
82
  `usePendingPathname()` is where a page change in progress is going (`null`
68
83
  when none is), for a pending indicator; a branch's `loading` component
69
84
  shows while what is below it suspends (a `<Suspense>` inside its `error`
70
- boundary); `bindParams(() => ({ locale }))` returns `{ href, navigateTo }` with those
71
- params supplied by the source at each call (still overridable), for a
72
- segment every link shares — a pattern that names a param still takes
73
- `options` third, after an `undefined` params slot if the source supplies
74
- them all. `PageProps<P>` / `LayoutProps<P>` type a framework route file's
85
+ boundary); `bindParams(() => ({ locale }))` returns the bound `href`
86
+ itself (`export const href = bindParams(…)`), with those params supplied
87
+ by the source at each call (still overridable), for a segment every link
88
+ shares. `PageProps<P>` / `LayoutProps<P>` type a framework route file's
75
89
  props by its pattern (`PageProps`' `params` from the registered schemas,
76
- `LayoutProps`' `params` always strings and its `P` only a pattern the table
77
- has a page at; `request` when the generated `Register` says the mode has
78
- one), and `RouteContext<P>` types a framework `route.ts` method export's
90
+ `LayoutProps`' `params` always strings and its `P` any pattern, a layout's
91
+ with no page of its own included; `request` when the generated `Register`
92
+ says the mode has one), and `RouteContext<P>` types a framework `route.ts` method export's
79
93
  `{ request, params }`. `notFound()` says, from a framework page, that its pathname is not a
80
94
  page after all — the framework answers with the nearest `not-found.tsx`
81
95
  under a 404 — and `isNotFound(value)` recognises what it throws.
@@ -98,15 +112,14 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
98
112
  the search), which then loads in place — no focus reset or transition
99
113
  types, and no scroll but going back or forward, which returns to where
100
114
  that entry was left once the page loaded again is on screen.
101
- Exported types, by group — the table: `Routes` (`{ kind, record, match }`),
115
+ Exported types, by group — the table: `Routes` (`{ kind, record, match, matchAll }`),
102
116
  `RoutesRecord`, `RouteNode`, `RouteComponent`, `Match`, `ErrorComponent`,
103
- `ErrorProps`; patterns: `PatternOf`, `NavigablePatternOf`, `NavigablePath`,
117
+ `ErrorProps`; patterns: `PatternOf`, `NavigablePatternOf`,
104
118
  `MatchablePattern`; registration: `Register`, `RegisteredPattern`,
105
119
  `RegisteredNavigablePattern`, `RegisteredParams` (what a link takes),
106
120
  `RegisteredPageParams` (what a page receives), `PageProps`, `LayoutProps`;
107
121
  paths and schemas: `ParamsOf`, `PathFor`, `ParamValue`,
108
122
  `StandardSchemaLike`, `SchemaOutput`, `ParamsSchemaFor`, `ParsedParams`,
109
- `ParsedParamsMap`; options and handlers: `NavigateToOptions`
110
- (`{ history? }`), `MatchOptions` (`{ inclusive? }`), `BoundParams` /
111
- `BoundLinks` (what `bindParams`'s source returns / what it returns),
112
- `NavigationHandler` (`{ claim, load, apply }`).
123
+ `ParsedParamsMap`; options and handlers: `MatchOptions`
124
+ (`{ inclusive? }`), `BoundParams` (what `bindParams`'s source returns),
125
+ `NavigationHandler` (`{ claim, load, apply, refresh? }`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/router",
3
- "version": "2.3.1",
3
+ "version": "4.0.0",
4
4
  "description": "The pathname axis of the URL, owned. One route table derives the types, the matching, the links, and the navigation, over the Navigation API and URLPattern.",
5
5
  "keywords": [
6
6
  "navigation-api",
@@ -42,16 +42,16 @@
42
42
  "@arethetypeswrong/cli": "0.18.5",
43
43
  "@types/react": "19.3.0",
44
44
  "@types/react-dom": "19.3.0",
45
- "@vitejs/plugin-react": "6.1.2",
46
- "@vitest/browser-playwright": "5.0.5",
47
- "playwright": "1.63.0",
45
+ "@vitejs/plugin-react": "6.3.0",
46
+ "@vitest/browser-playwright": "5.1.1",
47
+ "playwright": "1.65.1",
48
48
  "publint": "0.3.25",
49
49
  "react": "19.3.1",
50
50
  "react-dom": "19.3.1",
51
51
  "typescript": "7.0.2",
52
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
53
- "vite-plus": "1.4.0",
54
- "vitest": "5.0.5",
52
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8000",
53
+ "vite-plus": "1.7.0",
54
+ "vitest": "5.1.1",
55
55
  "vitest-browser-react": "2.3.0"
56
56
  },
57
57
  "peerDependencies": {