@vielzeug/wayfinder 1.0.3
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 +90 -0
- package/dist/_dev.cjs +2 -0
- package/dist/_dev.cjs.map +1 -0
- package/dist/_dev.d.ts +2 -0
- package/dist/_dev.d.ts.map +1 -0
- package/dist/_dev.js +12 -0
- package/dist/_dev.js.map +1 -0
- package/dist/compile.cjs +2 -0
- package/dist/compile.cjs.map +1 -0
- package/dist/compile.d.ts +7 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +50 -0
- package/dist/compile.js.map +1 -0
- package/dist/context.cjs +2 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.ts +17 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +59 -0
- package/dist/context.js.map +1 -0
- package/dist/devtools.cjs +2 -0
- package/dist/devtools.cjs.map +1 -0
- package/dist/devtools.d.ts +47 -0
- package/dist/devtools.d.ts.map +1 -0
- package/dist/devtools.js +13 -0
- package/dist/devtools.js.map +1 -0
- package/dist/errors.cjs +2 -0
- package/dist/errors.cjs.map +1 -0
- package/dist/errors.d.ts +20 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +21 -0
- package/dist/errors.js.map +1 -0
- package/dist/guards.cjs +2 -0
- package/dist/guards.cjs.map +1 -0
- package/dist/guards.d.ts +22 -0
- package/dist/guards.d.ts.map +1 -0
- package/dist/guards.js +10 -0
- package/dist/guards.js.map +1 -0
- package/dist/history.cjs +2 -0
- package/dist/history.cjs.map +1 -0
- package/dist/history.d.ts +13 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +66 -0
- package/dist/history.js.map +1 -0
- package/dist/hydration.cjs +2 -0
- package/dist/hydration.cjs.map +1 -0
- package/dist/hydration.d.ts +7 -0
- package/dist/hydration.d.ts.map +1 -0
- package/dist/hydration.js +55 -0
- package/dist/hydration.js.map +1 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/middleware.cjs +2 -0
- package/dist/middleware.cjs.map +1 -0
- package/dist/middleware.d.ts +17 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +10 -0
- package/dist/middleware.js.map +1 -0
- package/dist/path.cjs +2 -0
- package/dist/path.cjs.map +1 -0
- package/dist/path.d.ts +34 -0
- package/dist/path.d.ts.map +1 -0
- package/dist/path.js +138 -0
- package/dist/path.js.map +1 -0
- package/dist/preload.cjs +2 -0
- package/dist/preload.cjs.map +1 -0
- package/dist/preload.d.ts +18 -0
- package/dist/preload.d.ts.map +1 -0
- package/dist/preload.js +30 -0
- package/dist/preload.js.map +1 -0
- package/dist/router.cjs +2 -0
- package/dist/router.cjs.map +1 -0
- package/dist/router.d.ts +102 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +502 -0
- package/dist/router.js.map +1 -0
- package/dist/types.d.ts +327 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/wayfinder.cjs +2 -0
- package/dist/wayfinder.cjs.map +1 -0
- package/dist/wayfinder.iife.js +2 -0
- package/dist/wayfinder.iife.js.map +1 -0
- package/dist/wayfinder.js +2 -0
- package/dist/wayfinder.js.map +1 -0
- package/package.json +49 -0
package/README.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# @vielzeug/wayfinder
|
|
2
|
+
|
|
3
|
+
> Lightweight, type-safe client-side router with nested routes, data loading, middleware, and named navigation.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@vielzeug/wayfinder) [](https://opensource.org/licenses/MIT)
|
|
6
|
+
|
|
7
|
+
<details>
|
|
8
|
+
<summary>Quick Reference</summary>
|
|
9
|
+
|
|
10
|
+
**Package:** `@vielzeug/wayfinder` **Category:** Routing
|
|
11
|
+
|
|
12
|
+
**Key exports:** `createRouter`, `createBrowserHistory`, `createMemoryHistory`, `redirectTo`
|
|
13
|
+
|
|
14
|
+
**When to use:** Framework-agnostic client-side router with typed params, async data loading, middleware, leave guards, and View Transitions support.
|
|
15
|
+
|
|
16
|
+
**Related:** [@vielzeug/ripple](https://vielzeug.dev/ripple/) · [@vielzeug/ward](https://vielzeug.dev/ward/) · [@vielzeug/herald](https://vielzeug.dev/herald/)
|
|
17
|
+
|
|
18
|
+
</details>
|
|
19
|
+
|
|
20
|
+
`@vielzeug/wayfinder` is part of Vielzeug and ships as a zero-dependency TypeScript package with ESM+CJS output.
|
|
21
|
+
|
|
22
|
+
## What You Get
|
|
23
|
+
|
|
24
|
+
- Declarative route tables with nested names (`dashboard.settings`)
|
|
25
|
+
- Named and raw-path navigation through one `navigate()` API
|
|
26
|
+
- Route middleware, data loaders, and lazy route modules
|
|
27
|
+
- Global `beforeLeave` leave guards with optional route scoping
|
|
28
|
+
- `component` + `meta` + `data` payloads on matched branch state
|
|
29
|
+
- Per-match `status` for granular loading/streaming feedback in nested layouts
|
|
30
|
+
- Streaming data loaders via async generators
|
|
31
|
+
- Declarative `notFound` fallback route
|
|
32
|
+
- Browser and memory history drivers
|
|
33
|
+
- `redirectTo()` middleware helper
|
|
34
|
+
- SSR-compatible `match()` for data prefetching without side effects
|
|
35
|
+
- `waitFor(name)` for testing and lifecycle coordination
|
|
36
|
+
|
|
37
|
+
## Installation
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
pnpm add @vielzeug/wayfinder
|
|
41
|
+
npm install @vielzeug/wayfinder
|
|
42
|
+
yarn add @vielzeug/wayfinder
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
import { createRouter } from '@vielzeug/wayfinder';
|
|
49
|
+
|
|
50
|
+
const router = createRouter({
|
|
51
|
+
routes: {
|
|
52
|
+
home: { path: '/' },
|
|
53
|
+
dashboard: {
|
|
54
|
+
path: '/dashboard',
|
|
55
|
+
children: {
|
|
56
|
+
index: { index: true },
|
|
57
|
+
settings: {
|
|
58
|
+
path: 'settings',
|
|
59
|
+
data: async () => fetchSettings(),
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
},
|
|
63
|
+
},
|
|
64
|
+
notFound: {
|
|
65
|
+
component: NotFoundPage,
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// React to state changes:
|
|
70
|
+
router.subscribe((state) => {
|
|
71
|
+
const leaf = state.matches.at(-1);
|
|
72
|
+
render(leaf?.component, leaf?.data);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
await router.navigate({ name: 'dashboard.settings' });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Documentation
|
|
79
|
+
|
|
80
|
+
- [Overview](https://vielzeug.dev/wayfinder/)
|
|
81
|
+
- [Usage Guide](https://vielzeug.dev/wayfinder/usage)
|
|
82
|
+
- [API Reference](https://vielzeug.dev/wayfinder/api)
|
|
83
|
+
- [Examples](https://vielzeug.dev/wayfinder/examples)
|
|
84
|
+
- [React Integration Example](https://vielzeug.dev/wayfinder/examples/react-integration)
|
|
85
|
+
- [Vue Integration Example](https://vielzeug.dev/wayfinder/examples/vue-integration)
|
|
86
|
+
- [Svelte Integration Example](https://vielzeug.dev/wayfinder/examples/svelte-integration)
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
MIT © [Helmuth Saatkamp](https://github.com/helmuthdu) — part of the [Vielzeug](https://github.com/helmuthdu/vielzeug) monorepo.
|
package/dist/_dev.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.cjs","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":"AAAA,IAAM,EAAQ,CAAE,WAAgD,mBAGhE,SAAgB,EAAK,EAAmB,CAClC,GAAO,QAAQ,KAAK,yBAAyB,GAAK,CACxD,CAGA,SAAgB,EAAM,EAAa,GAAG,EAAuB,CACvD,GAAO,QAAQ,MAAM,yBAAyB,IAAO,GAAG,CAAI,CAClE"}
|
package/dist/_dev.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.d.ts","sourceRoot":"","sources":["../src/_dev.ts"],"names":[],"mappings":""}
|
package/dist/_dev.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/_dev.ts
|
|
2
|
+
var e = !globalThis.__WAYFINDER_PROD__;
|
|
3
|
+
function t(t) {
|
|
4
|
+
e && console.warn(`[@vielzeug/wayfinder] ${t}`);
|
|
5
|
+
}
|
|
6
|
+
function n(t, ...n) {
|
|
7
|
+
e && console.error(`[@vielzeug/wayfinder] ${t}`, ...n);
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { n as error, t as warn };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=_dev.js.map
|
package/dist/_dev.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"_dev.js","names":[],"sources":["../src/_dev.ts"],"sourcesContent":["const isDev = !(globalThis as { __WAYFINDER_PROD__?: boolean }).__WAYFINDER_PROD__;\n\n/** @internal @security Messages may include user-supplied data. */\nexport function warn(msg: string): void {\n if (isDev) console.warn(`[@vielzeug/wayfinder] ${msg}`);\n}\n\n/** @internal */\nexport function error(msg: string, ...args: unknown[]): void {\n if (isDev) console.error(`[@vielzeug/wayfinder] ${msg}`, ...args);\n}\n\n/** @internal — Run fn only in dev builds. Use when dev-only logic goes beyond a single warn() / error() call. */\nexport function devOnly(fn: () => void): void {\n if (isDev) fn();\n}\n"],"mappings":";AAAA,IAAM,IAAQ,CAAE,WAAgD;AAGhE,SAAgB,EAAK,GAAmB;CACtC,AAAI,KAAO,QAAQ,KAAK,yBAAyB,GAAK;AACxD;AAGA,SAAgB,EAAM,GAAa,GAAG,GAAuB;CAC3D,AAAI,KAAO,QAAQ,MAAM,yBAAyB,KAAO,GAAG,CAAI;AAClE"}
|
package/dist/compile.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./_dev.cjs"),t=require("./errors.cjs"),n=require("./path.cjs");function r(r){let i=[],a=(e,r,o,s,c)=>{if(r.index&&r.path!==void 0)throw new t.WayfinderRouteError(`Route "${e}" cannot define both index and path`);if(!r.index&&r.path===void 0)throw new t.WayfinderRouteError(`Route "${e}" must define path or set index: true`);let l=r.index?o:n.normalizePath(r.path?n.joinPaths(o,r.path):o),u=[...s,{component:r.component,dataFn:r.data,lazy:r.lazy,meta:r.meta,name:e,onError:r.onError}],d=[...c,...r.middleware??[]];if(r.children)for(let[t,n]of Object.entries(r.children))a(`${e}.${t}`,n,l,u,d);if(r.lazy!==void 0||r.redirect!==void 0||!r.children||r.data!==void 0){let e=u[u.length-1];i.push({branchDefs:u,coerceSearch:r.coerceSearch,leaf:e,matcher:n.compilePathMatcher(l),ownMiddleware:d,path:l,redirect:r.redirect})}};for(let[e,t]of Object.entries(r.routes))a(e,t,`/`,[],[]);let o=new Set;for(let e of i){if(o.has(e.leaf.name))throw new t.WayfinderRouteError(`Duplicate route name: "${e.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);o.add(e.leaf.name)}let s=!1;for(let t of i){let n=t.path===`/*`||t.path.endsWith(`/*`)||t.path.includes(`:`)&&t.path.endsWith(`*`);s&&!n&&e.warn(`Route "${t.leaf.name}" (${t.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`),n&&(s=!0)}return{records:i,routesByName:new Map(i.map(e=>[e.leaf.name,e]))}}exports.compileRoutes=r;
|
|
2
|
+
//# sourceMappingURL=compile.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile.cjs","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nimport { warn } from './_dev';\nimport { WayfinderRouteError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\n\nexport type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {\n records: readonly RouteRecord<TMeta, TComponent>[];\n routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(\n options: RouterOptions<TRoutes, TMeta, TComponent>,\n): CompiledRoutes<TMeta, TComponent> {\n const records: RouteRecord<TMeta, TComponent>[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef<TMeta, TComponent>[],\n ancestorMiddleware: RouteRecord<TMeta, TComponent>['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef<TMeta, TComponent>[] = [\n ...ancestorBranchDefs,\n {\n component: route.component as TComponent | undefined,\n dataFn: route.data,\n lazy: route.lazy as RouteBranchDef<TMeta, TComponent>['lazy'],\n meta: route.meta as TMeta | undefined,\n name,\n onError: route.onError as RouteBranchDef<TMeta, TComponent>['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // R9: emit a record for leaf routes (no children), redirects, lazy routes, and routes with data.\n // A bare parent-only route (children but no data/lazy/redirect) is not emitted as a leaf.\n if (route.lazy !== undefined || route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderRouteError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":"gFAWA,SAAgB,EACd,EACmC,CACnC,IAAM,EAA4C,CAAC,EAE7C,GACJ,EACA,EACA,EACA,EACA,IACS,CACT,GAAI,EAAM,OAAS,EAAM,OAAS,IAAA,GAChC,MAAM,IAAI,EAAA,oBAAoB,UAAU,EAAK,oCAAoC,EAGnF,GAAI,CAAC,EAAM,OAAS,EAAM,OAAS,IAAA,GACjC,MAAM,IAAI,EAAA,oBAAoB,UAAU,EAAK,sCAAsC,EAGrF,IAAM,EAAU,EAAM,MAClB,EACA,EAAA,cAAc,EAAM,KAAO,EAAA,UAAU,EAAc,EAAM,IAAI,EAAI,CAAY,EAE3E,EAAkD,CACtD,GAAG,EACH,CACE,UAAW,EAAM,UACjB,OAAQ,EAAM,KACd,KAAM,EAAM,KACZ,KAAM,EAAM,KACZ,OACA,QAAS,EAAM,OACjB,CACF,EAEM,EAA8B,CAClC,GAAG,EACH,GAAK,EAAM,YAAc,CAAC,CAC5B,EAEA,GAAI,EAAM,SACR,IAAK,GAAM,CAAC,EAAW,KAAe,OAAO,QAAQ,EAAM,QAAQ,EACjE,EAAQ,GAAG,EAAK,GAAG,IAAa,EAAY,EAAS,EAAY,CAAa,EAMlF,GAAI,EAAM,OAAS,IAAA,IAAa,EAAM,WAAa,IAAA,IAAa,CAAC,EAAM,UAAY,EAAM,OAAS,IAAA,GAAW,CAC3G,IAAM,EAAO,EAAW,EAAW,OAAS,GAE5C,EAAQ,KAAK,CACX,aACA,aAAc,EAAM,aACpB,OACA,QAAS,EAAA,mBAAmB,CAAO,EACnC,gBACA,KAAM,EACN,SAAU,EAAM,QAClB,CAAC,CACH,CACF,EAEA,IAAK,GAAM,CAAC,EAAM,KAAU,OAAO,QAAQ,EAAQ,MAAM,EACvD,EAAQ,EAAM,EAAO,IAAK,CAAC,EAAG,CAAC,CAAC,EAIlC,IAAM,EAAY,IAAI,IAEtB,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,EAAU,IAAI,EAAO,KAAK,IAAI,EAChC,MAAM,IAAI,EAAA,oBACR,0BAA0B,EAAO,KAAK,KAAK,oFAC7C,EAGF,EAAU,IAAI,EAAO,KAAK,IAAI,CAChC,CAIA,IAAI,EAAe,GAEnB,IAAK,IAAM,KAAU,EAAS,CAC5B,IAAM,EACJ,EAAO,OAAS,MAAQ,EAAO,KAAK,SAAS,IAAI,GAAM,EAAO,KAAK,SAAS,GAAG,GAAK,EAAO,KAAK,SAAS,GAAG,EAE1G,GAAgB,CAAC,GACnB,EAAA,KACE,UAAU,EAAO,KAAK,KAAK,KAAK,EAAO,KAAK,2GAC9C,EAGE,IAAY,EAAe,GACjC,CAEA,MAAO,CACL,UACA,aAAc,IAAI,IAAI,EAAQ,IAAK,GAAM,CAAC,EAAE,KAAK,KAAM,CAAC,CAAC,CAAC,CAC5D,CACF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { RouteRecord, RouterOptions, RouteTable } from './types';
|
|
2
|
+
export type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {
|
|
3
|
+
records: readonly RouteRecord<TMeta, TComponent>[];
|
|
4
|
+
routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;
|
|
5
|
+
};
|
|
6
|
+
export declare function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(options: RouterOptions<TRoutes, TMeta, TComponent>): CompiledRoutes<TMeta, TComponent>;
|
|
7
|
+
//# sourceMappingURL=compile.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../src/compile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAA+C,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAMnH,MAAM,MAAM,cAAc,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,IAAI;IAClE,OAAO,EAAE,SAAS,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;IACnD,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;CACnE,CAAC;AAEF,wBAAgB,aAAa,CAAC,OAAO,SAAS,UAAU,EAAE,KAAK,EAAE,UAAU,EACzE,OAAO,EAAE,aAAa,CAAC,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,GACjD,cAAc,CAAC,KAAK,EAAE,UAAU,CAAC,CAoGnC"}
|
package/dist/compile.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { warn as e } from "./_dev.js";
|
|
2
|
+
import { WayfinderRouteError as t } from "./errors.js";
|
|
3
|
+
import { compilePathMatcher as n, joinPaths as r, normalizePath as i } from "./path.js";
|
|
4
|
+
//#region src/compile.ts
|
|
5
|
+
function a(a) {
|
|
6
|
+
let o = [], s = (e, a, c, l, u) => {
|
|
7
|
+
if (a.index && a.path !== void 0) throw new t(`Route "${e}" cannot define both index and path`);
|
|
8
|
+
if (!a.index && a.path === void 0) throw new t(`Route "${e}" must define path or set index: true`);
|
|
9
|
+
let d = a.index ? c : i(a.path ? r(c, a.path) : c), f = [...l, {
|
|
10
|
+
component: a.component,
|
|
11
|
+
dataFn: a.data,
|
|
12
|
+
lazy: a.lazy,
|
|
13
|
+
meta: a.meta,
|
|
14
|
+
name: e,
|
|
15
|
+
onError: a.onError
|
|
16
|
+
}], p = [...u, ...a.middleware ?? []];
|
|
17
|
+
if (a.children) for (let [t, n] of Object.entries(a.children)) s(`${e}.${t}`, n, d, f, p);
|
|
18
|
+
if (a.lazy !== void 0 || a.redirect !== void 0 || !a.children || a.data !== void 0) {
|
|
19
|
+
let e = f[f.length - 1];
|
|
20
|
+
o.push({
|
|
21
|
+
branchDefs: f,
|
|
22
|
+
coerceSearch: a.coerceSearch,
|
|
23
|
+
leaf: e,
|
|
24
|
+
matcher: n(d),
|
|
25
|
+
ownMiddleware: p,
|
|
26
|
+
path: d,
|
|
27
|
+
redirect: a.redirect
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
for (let [e, t] of Object.entries(a.routes)) s(e, t, "/", [], []);
|
|
32
|
+
let c = /* @__PURE__ */ new Set();
|
|
33
|
+
for (let e of o) {
|
|
34
|
+
if (c.has(e.leaf.name)) throw new t(`Duplicate route name: "${e.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);
|
|
35
|
+
c.add(e.leaf.name);
|
|
36
|
+
}
|
|
37
|
+
let l = !1;
|
|
38
|
+
for (let t of o) {
|
|
39
|
+
let n = t.path === "/*" || t.path.endsWith("/*") || t.path.includes(":") && t.path.endsWith("*");
|
|
40
|
+
l && !n && e(`Route "${t.leaf.name}" (${t.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`), n && (l = !0);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
records: o,
|
|
44
|
+
routesByName: new Map(o.map((e) => [e.leaf.name, e]))
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { a as compileRoutes };
|
|
49
|
+
|
|
50
|
+
//# sourceMappingURL=compile.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compile.js","names":[],"sources":["../src/compile.ts"],"sourcesContent":["import type { Middleware, RouteBranchDef, RouteDefinition, RouteRecord, RouterOptions, RouteTable } from './types';\n\nimport { warn } from './_dev';\nimport { WayfinderRouteError } from './errors';\nimport { compilePathMatcher, joinPaths, normalizePath } from './path';\n\nexport type CompiledRoutes<TMeta = unknown, TComponent = unknown> = {\n records: readonly RouteRecord<TMeta, TComponent>[];\n routesByName: ReadonlyMap<string, RouteRecord<TMeta, TComponent>>;\n};\n\nexport function compileRoutes<TRoutes extends RouteTable, TMeta, TComponent>(\n options: RouterOptions<TRoutes, TMeta, TComponent>,\n): CompiledRoutes<TMeta, TComponent> {\n const records: RouteRecord<TMeta, TComponent>[] = [];\n\n const compile = (\n name: string,\n route: RouteDefinition,\n ancestorPath: string,\n ancestorBranchDefs: RouteBranchDef<TMeta, TComponent>[],\n ancestorMiddleware: RouteRecord<TMeta, TComponent>['ownMiddleware'],\n ): void => {\n if (route.index && route.path !== undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" cannot define both index and path`);\n }\n\n if (!route.index && route.path === undefined) {\n throw new WayfinderRouteError(`Route \"${name}\" must define path or set index: true`);\n }\n\n const ownPath = route.index\n ? ancestorPath\n : normalizePath(route.path ? joinPaths(ancestorPath, route.path) : ancestorPath);\n\n const branchDefs: RouteBranchDef<TMeta, TComponent>[] = [\n ...ancestorBranchDefs,\n {\n component: route.component as TComponent | undefined,\n dataFn: route.data,\n lazy: route.lazy as RouteBranchDef<TMeta, TComponent>['lazy'],\n meta: route.meta as TMeta | undefined,\n name,\n onError: route.onError as RouteBranchDef<TMeta, TComponent>['onError'],\n },\n ];\n\n const ownMiddleware: Middleware[] = [\n ...ancestorMiddleware,\n ...((route.middleware ?? []) as unknown as Middleware[]),\n ];\n\n if (route.children) {\n for (const [childName, childRoute] of Object.entries(route.children)) {\n compile(`${name}.${childName}`, childRoute, ownPath, branchDefs, ownMiddleware);\n }\n }\n\n // R9: emit a record for leaf routes (no children), redirects, lazy routes, and routes with data.\n // A bare parent-only route (children but no data/lazy/redirect) is not emitted as a leaf.\n if (route.lazy !== undefined || route.redirect !== undefined || !route.children || route.data !== undefined) {\n const leaf = branchDefs[branchDefs.length - 1]!;\n\n records.push({\n branchDefs,\n coerceSearch: route.coerceSearch,\n leaf,\n matcher: compilePathMatcher(ownPath),\n ownMiddleware,\n path: ownPath,\n redirect: route.redirect,\n });\n }\n };\n\n for (const [name, route] of Object.entries(options.routes)) {\n compile(name, route, '/', [], []);\n }\n\n // Validate duplicate names.\n const namesSeen = new Set<string>();\n\n for (const record of records) {\n if (namesSeen.has(record.leaf.name)) {\n throw new WayfinderRouteError(\n `Duplicate route name: \"${record.leaf.name}\". A top-level route key must not coincide with a nested route's dot-notation name.`,\n );\n }\n\n namesSeen.add(record.leaf.name);\n }\n\n // Warn when a catch-all or wildcard-param route precedes more specific routes.\n // Routes match in array order (object key order), so a wildcard placed too early silently shadows later routes.\n let wildcardSeen = false;\n\n for (const record of records) {\n const isCatchAll =\n record.path === '/*' || record.path.endsWith('/*') || (record.path.includes(':') && record.path.endsWith('*'));\n\n if (wildcardSeen && !isCatchAll) {\n warn(\n `Route \"${record.leaf.name}\" (${record.path}) is defined after a wildcard/catch-all route and will never match. Move specific routes before wildcards.`,\n );\n }\n\n if (isCatchAll) wildcardSeen = true;\n }\n\n return {\n records,\n routesByName: new Map(records.map((r) => [r.leaf.name, r])),\n };\n}\n"],"mappings":";;;;AAWA,SAAgB,EACd,GACmC;CACnC,IAAM,IAA4C,CAAC,GAE7C,KACJ,GACA,GACA,GACA,GACA,MACS;EACT,IAAI,EAAM,SAAS,EAAM,SAAS,KAAA,GAChC,MAAM,IAAI,EAAoB,UAAU,EAAK,oCAAoC;EAGnF,IAAI,CAAC,EAAM,SAAS,EAAM,SAAS,KAAA,GACjC,MAAM,IAAI,EAAoB,UAAU,EAAK,sCAAsC;EAGrF,IAAM,IAAU,EAAM,QAClB,IACA,EAAc,EAAM,OAAO,EAAU,GAAc,EAAM,IAAI,IAAI,CAAY,GAE3E,IAAkD,CACtD,GAAG,GACH;GACE,WAAW,EAAM;GACjB,QAAQ,EAAM;GACd,MAAM,EAAM;GACZ,MAAM,EAAM;GACZ;GACA,SAAS,EAAM;EACjB,CACF,GAEM,IAA8B,CAClC,GAAG,GACH,GAAK,EAAM,cAAc,CAAC,CAC5B;EAEA,IAAI,EAAM,UACR,KAAK,IAAM,CAAC,GAAW,MAAe,OAAO,QAAQ,EAAM,QAAQ,GACjE,EAAQ,GAAG,EAAK,GAAG,KAAa,GAAY,GAAS,GAAY,CAAa;EAMlF,IAAI,EAAM,SAAS,KAAA,KAAa,EAAM,aAAa,KAAA,KAAa,CAAC,EAAM,YAAY,EAAM,SAAS,KAAA,GAAW;GAC3G,IAAM,IAAO,EAAW,EAAW,SAAS;GAE5C,EAAQ,KAAK;IACX;IACA,cAAc,EAAM;IACpB;IACA,SAAS,EAAmB,CAAO;IACnC;IACA,MAAM;IACN,UAAU,EAAM;GAClB,CAAC;EACH;CACF;CAEA,KAAK,IAAM,CAAC,GAAM,MAAU,OAAO,QAAQ,EAAQ,MAAM,GACvD,EAAQ,GAAM,GAAO,KAAK,CAAC,GAAG,CAAC,CAAC;CAIlC,IAAM,oBAAY,IAAI,IAAY;CAElC,KAAK,IAAM,KAAU,GAAS;EAC5B,IAAI,EAAU,IAAI,EAAO,KAAK,IAAI,GAChC,MAAM,IAAI,EACR,0BAA0B,EAAO,KAAK,KAAK,oFAC7C;EAGF,EAAU,IAAI,EAAO,KAAK,IAAI;CAChC;CAIA,IAAI,IAAe;CAEnB,KAAK,IAAM,KAAU,GAAS;EAC5B,IAAM,IACJ,EAAO,SAAS,QAAQ,EAAO,KAAK,SAAS,IAAI,KAAM,EAAO,KAAK,SAAS,GAAG,KAAK,EAAO,KAAK,SAAS,GAAG;EAQ9G,AANI,KAAgB,CAAC,KACnB,EACE,UAAU,EAAO,KAAK,KAAK,KAAK,EAAO,KAAK,2GAC9C,GAGE,MAAY,IAAe;CACjC;CAEA,OAAO;EACL;EACA,cAAc,IAAI,IAAI,EAAQ,KAAK,MAAM,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC,CAAC;CAC5D;AACF"}
|
package/dist/context.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./_dev.cjs"),t=require("./errors.cjs");function n(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function r(e,t,n,r,i){return e.map((e,a)=>({component:e.component,data:r[a],meta:e.meta,name:e.name,params:{...t},pathname:n,status:i?.[a]??`idle`}))}function i(e,t,n,r,i){return{hash:e.hash,historyState:e.historyState,locals:{},matches:r,navigate:i,params:n,pathname:e.pathname,query:t}}async function a(e,n,r){async function i(a){if(a<n.length){let r=!1;await n[a](e,async()=>{if(r)throw new t.WayfinderApiError(`next() called multiple times`);r=!0,await i(a+1)});return}await r()}await i(0)}function o(t,n,r){if(r){r(t,n);return}e.error(`Unhandled router error. Provide an onError callback to handle errors explicitly:`,t)}exports.buildMatchBranch=r,exports.createRouteContext=i,exports.createRouteState=n,exports.executeMiddlewarePipeline=a,exports.reportError=o;
|
|
2
|
+
//# sourceMappingURL=context.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.cjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type {\n MatchStatus,\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\nimport { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** R5: No defensive deep-copy — RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState<TMeta = unknown, TComponent = unknown>(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch<TMeta, TComponent>;\n status: NavigationStatus;\n}): RouteState<TMeta, TComponent> {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs, data results, and optional per-node statuses.\n * F1: Each node carries its own `status` for fine-grained nested layout feedback.\n */\nexport function buildMatchBranch<TMeta = unknown, TComponent = unknown>(\n branchDefs: readonly RouteBranchDef<TMeta, TComponent>[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n statuses?: readonly MatchStatus[],\n): RouteMatchBranch<TMeta, TComponent> {\n return branchDefs.map((def, i): RouteMatchBranch<TMeta, TComponent>[number] => ({\n component: def.component as TComponent,\n data: dataResults[i],\n meta: def.meta as TMeta,\n name: def.name,\n params: { ...params },\n pathname,\n status: statuses?.[i] ?? 'idle',\n }));\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n): Promise<void> {\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n await middleware[index]!(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n\n return;\n }\n\n await terminal();\n }\n\n await dispatch(0);\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":"wDAqBA,SAAgB,EAAwD,EAKtC,CAChC,MAAO,CACL,MAAO,EAAM,MACb,SAAU,EAAM,SAChB,QAAS,EAAM,QACf,OAAQ,EAAM,MAChB,CACF,CAMA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACqC,CACrC,OAAO,EAAW,KAAK,EAAK,KAAoD,CAC9E,UAAW,EAAI,UACf,KAAM,EAAY,GAClB,KAAM,EAAI,KACV,KAAM,EAAI,KACV,OAAQ,CAAE,GAAG,CAAO,EACpB,WACA,OAAQ,IAAW,IAAM,MAC3B,EAAE,CACJ,CAIA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACoC,CACpC,MAAO,CACL,KAAM,EAAS,KACf,aAAc,EAAS,aACvB,OAAQ,CAAC,EACT,UACA,WACA,SACA,SAAU,EAAS,SACnB,MAAO,CACT,CACF,CAIA,eAAsB,EACpB,EACA,EACA,EACe,CACf,eAAe,EAAS,EAA8B,CACpD,GAAI,EAAQ,EAAW,OAAQ,CAC7B,IAAI,EAAS,GAEb,MAAM,EAAW,EAAM,CAAE,EAAS,SAAY,CAC5C,GAAI,EAAQ,MAAM,IAAI,EAAA,kBAAkB,8BAA8B,EAEtE,EAAS,GACT,MAAM,EAAS,EAAQ,CAAC,CAC1B,CAAC,EAED,MACF,CAEA,MAAM,EAAS,CACjB,CAEA,MAAM,EAAS,CAAC,CAClB,CAIA,SAAgB,EACd,EACA,EACA,EACM,CACN,GAAI,EAAS,CACX,EAAQ,EAAO,CAAO,EAEtB,MACF,CAEA,EAAA,MAAS,mFAAoF,CAAK,CACpG"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { MatchStatus, Middleware, NavigationStatus, ResolvedQueryParams, RouteBranchDef, RouteContext, RouteLocation, RouteMatchBranch, RouteParams, RouterErrorContext, RouteState, RouteTable } from './types';
|
|
2
|
+
/** R5: No defensive deep-copy — RouteState is typed readonly; callers always pass fresh objects. */
|
|
3
|
+
export declare function createRouteState<TMeta = unknown, TComponent = unknown>(input: {
|
|
4
|
+
error?: unknown;
|
|
5
|
+
location: RouteLocation;
|
|
6
|
+
matches: RouteMatchBranch<TMeta, TComponent>;
|
|
7
|
+
status: NavigationStatus;
|
|
8
|
+
}): RouteState<TMeta, TComponent>;
|
|
9
|
+
/**
|
|
10
|
+
* Build a RouteMatchBranch from compiled defs, data results, and optional per-node statuses.
|
|
11
|
+
* F1: Each node carries its own `status` for fine-grained nested layout feedback.
|
|
12
|
+
*/
|
|
13
|
+
export declare function buildMatchBranch<TMeta = unknown, TComponent = unknown>(branchDefs: readonly RouteBranchDef<TMeta, TComponent>[], params: RouteParams, pathname: string, dataResults: unknown[], statuses?: readonly MatchStatus[]): RouteMatchBranch<TMeta, TComponent>;
|
|
14
|
+
export declare function createRouteContext<TRoutes extends RouteTable>(location: RouteLocation, resolvedQuery: ResolvedQueryParams, params: RouteParams, matches: RouteMatchBranch, navigate: RouteContext<RouteParams, TRoutes>['navigate']): RouteContext<RouteParams, TRoutes>;
|
|
15
|
+
export declare function executeMiddlewarePipeline<TRoutes extends RouteTable>(context: RouteContext<RouteParams, TRoutes>, middleware: readonly Middleware<TRoutes>[], terminal: () => Promise<void>): Promise<void>;
|
|
16
|
+
export declare function reportError(error: unknown, context: RouterErrorContext, onError?: (e: unknown, ctx: RouterErrorContext) => void): void;
|
|
17
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,WAAW,EACX,kBAAkB,EAClB,UAAU,EACV,UAAU,EACX,MAAM,SAAS,CAAC;AAOjB,oGAAoG;AACpG,wBAAgB,gBAAgB,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,EAAE,KAAK,EAAE;IAC7E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,QAAQ,EAAE,aAAa,CAAC;IACxB,OAAO,EAAE,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAC7C,MAAM,EAAE,gBAAgB,CAAC;CAC1B,GAAG,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,CAOhC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,EACpE,UAAU,EAAE,SAAS,cAAc,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,EACxD,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,OAAO,EAAE,EACtB,QAAQ,CAAC,EAAE,SAAS,WAAW,EAAE,GAChC,gBAAgB,CAAC,KAAK,EAAE,UAAU,CAAC,CAUrC;AAID,wBAAgB,kBAAkB,CAAC,OAAO,SAAS,UAAU,EAC3D,QAAQ,EAAE,aAAa,EACvB,aAAa,EAAE,mBAAmB,EAClC,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,gBAAgB,EACzB,QAAQ,EAAE,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,UAAU,CAAC,GACvD,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,CAWpC;AAID,wBAAsB,yBAAyB,CAAC,OAAO,SAAS,UAAU,EACxE,OAAO,EAAE,YAAY,CAAC,WAAW,EAAE,OAAO,CAAC,EAC3C,UAAU,EAAE,SAAS,UAAU,CAAC,OAAO,CAAC,EAAE,EAC1C,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAC5B,OAAO,CAAC,IAAI,CAAC,CAmBf;AAID,wBAAgB,WAAW,CACzB,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,kBAAkB,EAC3B,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,kBAAkB,KAAK,IAAI,GACtD,IAAI,CAQN"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { error as e } from "./_dev.js";
|
|
2
|
+
import { WayfinderApiError as t } from "./errors.js";
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
function n(e) {
|
|
5
|
+
return {
|
|
6
|
+
error: e.error,
|
|
7
|
+
location: e.location,
|
|
8
|
+
matches: e.matches,
|
|
9
|
+
status: e.status
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function r(e, t, n, r, i) {
|
|
13
|
+
return e.map((e, a) => ({
|
|
14
|
+
component: e.component,
|
|
15
|
+
data: r[a],
|
|
16
|
+
meta: e.meta,
|
|
17
|
+
name: e.name,
|
|
18
|
+
params: { ...t },
|
|
19
|
+
pathname: n,
|
|
20
|
+
status: i?.[a] ?? "idle"
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
function i(e, t, n, r, i) {
|
|
24
|
+
return {
|
|
25
|
+
hash: e.hash,
|
|
26
|
+
historyState: e.historyState,
|
|
27
|
+
locals: {},
|
|
28
|
+
matches: r,
|
|
29
|
+
navigate: i,
|
|
30
|
+
params: n,
|
|
31
|
+
pathname: e.pathname,
|
|
32
|
+
query: t
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
async function a(e, n, r) {
|
|
36
|
+
async function i(a) {
|
|
37
|
+
if (a < n.length) {
|
|
38
|
+
let r = !1;
|
|
39
|
+
await n[a](e, async () => {
|
|
40
|
+
if (r) throw new t("next() called multiple times");
|
|
41
|
+
r = !0, await i(a + 1);
|
|
42
|
+
});
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
await r();
|
|
46
|
+
}
|
|
47
|
+
await i(0);
|
|
48
|
+
}
|
|
49
|
+
function o(t, n, r) {
|
|
50
|
+
if (r) {
|
|
51
|
+
r(t, n);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
e("Unhandled router error. Provide an onError callback to handle errors explicitly:", t);
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
export { r as buildMatchBranch, i as createRouteContext, n as createRouteState, a as executeMiddlewarePipeline, o as reportError };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import type {\n MatchStatus,\n Middleware,\n NavigationStatus,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteParams,\n RouterErrorContext,\n RouteState,\n RouteTable,\n} from './types';\n\nimport { error as logError } from './_dev';\nimport { WayfinderApiError } from './errors';\n\n// ─── Route state ──────────────────────────────────────────────────────────────\n\n/** R5: No defensive deep-copy — RouteState is typed readonly; callers always pass fresh objects. */\nexport function createRouteState<TMeta = unknown, TComponent = unknown>(input: {\n error?: unknown;\n location: RouteLocation;\n matches: RouteMatchBranch<TMeta, TComponent>;\n status: NavigationStatus;\n}): RouteState<TMeta, TComponent> {\n return {\n error: input.error,\n location: input.location,\n matches: input.matches,\n status: input.status,\n };\n}\n\n/**\n * Build a RouteMatchBranch from compiled defs, data results, and optional per-node statuses.\n * F1: Each node carries its own `status` for fine-grained nested layout feedback.\n */\nexport function buildMatchBranch<TMeta = unknown, TComponent = unknown>(\n branchDefs: readonly RouteBranchDef<TMeta, TComponent>[],\n params: RouteParams,\n pathname: string,\n dataResults: unknown[],\n statuses?: readonly MatchStatus[],\n): RouteMatchBranch<TMeta, TComponent> {\n return branchDefs.map((def, i): RouteMatchBranch<TMeta, TComponent>[number] => ({\n component: def.component as TComponent,\n data: dataResults[i],\n meta: def.meta as TMeta,\n name: def.name,\n params: { ...params },\n pathname,\n status: statuses?.[i] ?? 'idle',\n }));\n}\n\n// ─── Context factory ──────────────────────────────────────────────────────────\n\nexport function createRouteContext<TRoutes extends RouteTable>(\n location: RouteLocation,\n resolvedQuery: ResolvedQueryParams,\n params: RouteParams,\n matches: RouteMatchBranch,\n navigate: RouteContext<RouteParams, TRoutes>['navigate'],\n): RouteContext<RouteParams, TRoutes> {\n return {\n hash: location.hash,\n historyState: location.historyState,\n locals: {},\n matches,\n navigate,\n params,\n pathname: location.pathname,\n query: resolvedQuery,\n };\n}\n\n// ─── Middleware pipeline ──────────────────────────────────────────────────────\n\nexport async function executeMiddlewarePipeline<TRoutes extends RouteTable>(\n context: RouteContext<RouteParams, TRoutes>,\n middleware: readonly Middleware<TRoutes>[],\n terminal: () => Promise<void>,\n): Promise<void> {\n async function dispatch(index: number): Promise<void> {\n if (index < middleware.length) {\n let called = false;\n\n await middleware[index]!(context, async () => {\n if (called) throw new WayfinderApiError('next() called multiple times');\n\n called = true;\n await dispatch(index + 1);\n });\n\n return;\n }\n\n await terminal();\n }\n\n await dispatch(0);\n}\n\n// ─── Error reporting ──────────────────────────────────────────────────────────\n\nexport function reportError(\n error: unknown,\n context: RouterErrorContext,\n onError?: (e: unknown, ctx: RouterErrorContext) => void,\n): void {\n if (onError) {\n onError(error, context);\n\n return;\n }\n\n logError('Unhandled router error. Provide an onError callback to handle errors explicitly:', error);\n}\n"],"mappings":";;;AAqBA,SAAgB,EAAwD,GAKtC;CAChC,OAAO;EACL,OAAO,EAAM;EACb,UAAU,EAAM;EAChB,SAAS,EAAM;EACf,QAAQ,EAAM;CAChB;AACF;AAMA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACqC;CACrC,OAAO,EAAW,KAAK,GAAK,OAAoD;EAC9E,WAAW,EAAI;EACf,MAAM,EAAY;EAClB,MAAM,EAAI;EACV,MAAM,EAAI;EACV,QAAQ,EAAE,GAAG,EAAO;EACpB;EACA,QAAQ,IAAW,MAAM;CAC3B,EAAE;AACJ;AAIA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACoC;CACpC,OAAO;EACL,MAAM,EAAS;EACf,cAAc,EAAS;EACvB,QAAQ,CAAC;EACT;EACA;EACA;EACA,UAAU,EAAS;EACnB,OAAO;CACT;AACF;AAIA,eAAsB,EACpB,GACA,GACA,GACe;CACf,eAAe,EAAS,GAA8B;EACpD,IAAI,IAAQ,EAAW,QAAQ;GAC7B,IAAI,IAAS;GAEb,MAAM,EAAW,EAAM,CAAE,GAAS,YAAY;IAC5C,IAAI,GAAQ,MAAM,IAAI,EAAkB,8BAA8B;IAGtE,AADA,IAAS,IACT,MAAM,EAAS,IAAQ,CAAC;GAC1B,CAAC;GAED;EACF;EAEA,MAAM,EAAS;CACjB;CAEA,MAAM,EAAS,CAAC;AAClB;AAIA,SAAgB,EACd,GACA,GACA,GACM;CACN,IAAI,GAAS;EACX,EAAQ,GAAO,CAAO;EAEtB;CACF;CAEA,EAAS,oFAAoF,CAAK;AACpG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./router.cjs");function t(t){let{label:n=`nav`,...r}=t,i=e.createRouter(r),a=`[wayfinder:${n}]`;return i.subscribe(e=>{let t=e.matches.map(e=>e.name).filter(Boolean).join(`, `),n=t?` [${t}]`:``;e.status===`error`?console.debug(`${a} error ${e.location.pathname}${n}`,e.error):console.debug(`${a} ${e.status.padEnd(8)} ${e.location.pathname}${n}`)}),i}exports.debugRouter=t;
|
|
2
|
+
//# sourceMappingURL=devtools.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.cjs","names":[],"sources":["../src/devtools.ts"],"sourcesContent":["/**\n * @vielzeug/wayfinder — debug utilities for router navigation visualisation.\n *\n * Import from the dedicated sub-path so it is tree-shaken from production bundles:\n * ```ts\n * import { debugRouter } from '@vielzeug/wayfinder/devtools';\n * ```\n */\n\nimport type { Router, RouterOptions, RouteState, RouteTable } from './index';\n\nimport { createRouter } from './router';\n\n/** Options for {@link debugRouter}. Extends {@link RouterOptions} with debug-specific settings. */\nexport interface DebugRouterOptions<\n TRoutes extends RouteTable,\n TMeta = unknown,\n TComponent = unknown,\n> extends RouterOptions<TRoutes, TMeta, TComponent> {\n /**\n * Label used in log prefixes. Defaults to `'nav'`, producing `[wayfinder:nav]`.\n * Useful when running multiple routers (e.g. a main router and a modal router)\n * so their log output can be distinguished:\n * ```ts\n * debugRouter({ label: 'modal', routes });\n * // [wayfinder:modal] loading /confirm\n * ```\n */\n label?: string;\n}\n\n/**\n * Creates a {@link Router} with navigation lifecycle logging pre-wired to `console.debug`.\n *\n * Equivalent to `createRouter(options)` with a `subscribe` listener attached, but imported\n * from a dedicated sub-path so `console.debug` references are tree-shaken from production\n * bundles when this sub-path is not imported.\n *\n * Logs every navigation state change with `[wayfinder:<label>]` prefixes showing the pathname,\n * status (`loading` → `idle` / `error`), and matched route names.\n *\n * @example\n * ```ts\n * import { debugRouter } from '@vielzeug/wayfinder/devtools';\n *\n * const router = debugRouter({ routes });\n * // [wayfinder:nav] loading /users\n * // [wayfinder:nav] idle /users [users]\n *\n * // Multi-router setup:\n * const modal = debugRouter({ label: 'modal', routes: modalRoutes });\n * // [wayfinder:modal] loading /confirm\n * ```\n */\nexport function debugRouter<const TRoutes extends RouteTable, TMeta = unknown, TComponent = unknown>(\n options: DebugRouterOptions<TRoutes, TMeta, TComponent>,\n): Router<TRoutes, TMeta, TComponent> {\n const { label = 'nav', ...routerOptions } = options;\n const router = createRouter<TRoutes, TMeta, TComponent>(routerOptions);\n const prefix = `[wayfinder:${label}]`;\n\n const log = (state: RouteState<TMeta, TComponent>): void => {\n const names = state.matches\n .map((m) => m.name)\n .filter(Boolean)\n .join(', ');\n const suffix = names ? ` [${names}]` : '';\n\n if (state.status === 'error') {\n console.debug(`${prefix} error ${state.location.pathname}${suffix}`, state.error);\n } else {\n console.debug(`${prefix} ${state.status.padEnd(8)} ${state.location.pathname}${suffix}`);\n }\n };\n\n router.subscribe(log);\n\n return router;\n}\n"],"mappings":"mGAsDA,SAAgB,EACd,EACoC,CACpC,GAAM,CAAE,QAAQ,MAAO,GAAG,GAAkB,EACtC,EAAS,EAAA,aAAyC,CAAa,EAC/D,EAAS,cAAc,EAAM,GAkBnC,OAFA,EAAO,UAdM,GAA+C,CAC1D,IAAM,EAAQ,EAAM,QACjB,IAAK,GAAM,EAAE,IAAI,CAAC,CAClB,OAAO,OAAO,CAAC,CACf,KAAK,IAAI,EACN,EAAS,EAAQ,MAAM,EAAM,GAAK,GAEpC,EAAM,SAAW,QACnB,QAAQ,MAAM,GAAG,EAAO,YAAY,EAAM,SAAS,WAAW,IAAU,EAAM,KAAK,EAEnF,QAAQ,MAAM,GAAG,EAAO,GAAG,EAAM,OAAO,OAAO,CAAC,EAAE,GAAG,EAAM,SAAS,WAAW,GAAQ,CAE3F,CAEoB,EAEb,CACT"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vielzeug/wayfinder — debug utilities for router navigation visualisation.
|
|
3
|
+
*
|
|
4
|
+
* Import from the dedicated sub-path so it is tree-shaken from production bundles:
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { debugRouter } from '@vielzeug/wayfinder/devtools';
|
|
7
|
+
* ```
|
|
8
|
+
*/
|
|
9
|
+
import type { Router, RouterOptions, RouteTable } from './index';
|
|
10
|
+
/** Options for {@link debugRouter}. Extends {@link RouterOptions} with debug-specific settings. */
|
|
11
|
+
export interface DebugRouterOptions<TRoutes extends RouteTable, TMeta = unknown, TComponent = unknown> extends RouterOptions<TRoutes, TMeta, TComponent> {
|
|
12
|
+
/**
|
|
13
|
+
* Label used in log prefixes. Defaults to `'nav'`, producing `[wayfinder:nav]`.
|
|
14
|
+
* Useful when running multiple routers (e.g. a main router and a modal router)
|
|
15
|
+
* so their log output can be distinguished:
|
|
16
|
+
* ```ts
|
|
17
|
+
* debugRouter({ label: 'modal', routes });
|
|
18
|
+
* // [wayfinder:modal] loading /confirm
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
label?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Creates a {@link Router} with navigation lifecycle logging pre-wired to `console.debug`.
|
|
25
|
+
*
|
|
26
|
+
* Equivalent to `createRouter(options)` with a `subscribe` listener attached, but imported
|
|
27
|
+
* from a dedicated sub-path so `console.debug` references are tree-shaken from production
|
|
28
|
+
* bundles when this sub-path is not imported.
|
|
29
|
+
*
|
|
30
|
+
* Logs every navigation state change with `[wayfinder:<label>]` prefixes showing the pathname,
|
|
31
|
+
* status (`loading` → `idle` / `error`), and matched route names.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* import { debugRouter } from '@vielzeug/wayfinder/devtools';
|
|
36
|
+
*
|
|
37
|
+
* const router = debugRouter({ routes });
|
|
38
|
+
* // [wayfinder:nav] loading /users
|
|
39
|
+
* // [wayfinder:nav] idle /users [users]
|
|
40
|
+
*
|
|
41
|
+
* // Multi-router setup:
|
|
42
|
+
* const modal = debugRouter({ label: 'modal', routes: modalRoutes });
|
|
43
|
+
* // [wayfinder:modal] loading /confirm
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function debugRouter<const TRoutes extends RouteTable, TMeta = unknown, TComponent = unknown>(options: DebugRouterOptions<TRoutes, TMeta, TComponent>): Router<TRoutes, TMeta, TComponent>;
|
|
47
|
+
//# sourceMappingURL=devtools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.d.ts","sourceRoot":"","sources":["../src/devtools.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,aAAa,EAAc,UAAU,EAAE,MAAM,SAAS,CAAC;AAI7E,mGAAmG;AACnG,MAAM,WAAW,kBAAkB,CACjC,OAAO,SAAS,UAAU,EAC1B,KAAK,GAAG,OAAO,EACf,UAAU,GAAG,OAAO,CACpB,SAAQ,aAAa,CAAC,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC;IACjD;;;;;;;;OAQG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,WAAW,CAAC,KAAK,CAAC,OAAO,SAAS,UAAU,EAAE,KAAK,GAAG,OAAO,EAAE,UAAU,GAAG,OAAO,EACjG,OAAO,EAAE,kBAAkB,CAAC,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,GACtD,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,UAAU,CAAC,CAsBpC"}
|
package/dist/devtools.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRouter as e } from "./router.js";
|
|
2
|
+
//#region src/devtools.ts
|
|
3
|
+
function t(t) {
|
|
4
|
+
let { label: n = "nav", ...r } = t, i = e(r), a = `[wayfinder:${n}]`;
|
|
5
|
+
return i.subscribe((e) => {
|
|
6
|
+
let t = e.matches.map((e) => e.name).filter(Boolean).join(", "), n = t ? ` [${t}]` : "";
|
|
7
|
+
e.status === "error" ? console.debug(`${a} error ${e.location.pathname}${n}`, e.error) : console.debug(`${a} ${e.status.padEnd(8)} ${e.location.pathname}${n}`);
|
|
8
|
+
}), i;
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
export { t as debugRouter };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=devtools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.js","names":[],"sources":["../src/devtools.ts"],"sourcesContent":["/**\n * @vielzeug/wayfinder — debug utilities for router navigation visualisation.\n *\n * Import from the dedicated sub-path so it is tree-shaken from production bundles:\n * ```ts\n * import { debugRouter } from '@vielzeug/wayfinder/devtools';\n * ```\n */\n\nimport type { Router, RouterOptions, RouteState, RouteTable } from './index';\n\nimport { createRouter } from './router';\n\n/** Options for {@link debugRouter}. Extends {@link RouterOptions} with debug-specific settings. */\nexport interface DebugRouterOptions<\n TRoutes extends RouteTable,\n TMeta = unknown,\n TComponent = unknown,\n> extends RouterOptions<TRoutes, TMeta, TComponent> {\n /**\n * Label used in log prefixes. Defaults to `'nav'`, producing `[wayfinder:nav]`.\n * Useful when running multiple routers (e.g. a main router and a modal router)\n * so their log output can be distinguished:\n * ```ts\n * debugRouter({ label: 'modal', routes });\n * // [wayfinder:modal] loading /confirm\n * ```\n */\n label?: string;\n}\n\n/**\n * Creates a {@link Router} with navigation lifecycle logging pre-wired to `console.debug`.\n *\n * Equivalent to `createRouter(options)` with a `subscribe` listener attached, but imported\n * from a dedicated sub-path so `console.debug` references are tree-shaken from production\n * bundles when this sub-path is not imported.\n *\n * Logs every navigation state change with `[wayfinder:<label>]` prefixes showing the pathname,\n * status (`loading` → `idle` / `error`), and matched route names.\n *\n * @example\n * ```ts\n * import { debugRouter } from '@vielzeug/wayfinder/devtools';\n *\n * const router = debugRouter({ routes });\n * // [wayfinder:nav] loading /users\n * // [wayfinder:nav] idle /users [users]\n *\n * // Multi-router setup:\n * const modal = debugRouter({ label: 'modal', routes: modalRoutes });\n * // [wayfinder:modal] loading /confirm\n * ```\n */\nexport function debugRouter<const TRoutes extends RouteTable, TMeta = unknown, TComponent = unknown>(\n options: DebugRouterOptions<TRoutes, TMeta, TComponent>,\n): Router<TRoutes, TMeta, TComponent> {\n const { label = 'nav', ...routerOptions } = options;\n const router = createRouter<TRoutes, TMeta, TComponent>(routerOptions);\n const prefix = `[wayfinder:${label}]`;\n\n const log = (state: RouteState<TMeta, TComponent>): void => {\n const names = state.matches\n .map((m) => m.name)\n .filter(Boolean)\n .join(', ');\n const suffix = names ? ` [${names}]` : '';\n\n if (state.status === 'error') {\n console.debug(`${prefix} error ${state.location.pathname}${suffix}`, state.error);\n } else {\n console.debug(`${prefix} ${state.status.padEnd(8)} ${state.location.pathname}${suffix}`);\n }\n };\n\n router.subscribe(log);\n\n return router;\n}\n"],"mappings":";;AAsDA,SAAgB,EACd,GACoC;CACpC,IAAM,EAAE,WAAQ,OAAO,GAAG,MAAkB,GACtC,IAAS,EAAyC,CAAa,GAC/D,IAAS,cAAc,EAAM;CAkBnC,OAFA,EAAO,WAdM,MAA+C;EAC1D,IAAM,IAAQ,EAAM,QACjB,KAAK,MAAM,EAAE,IAAI,CAAC,CAClB,OAAO,OAAO,CAAC,CACf,KAAK,IAAI,GACN,IAAS,IAAQ,MAAM,EAAM,KAAK;EAExC,AAAI,EAAM,WAAW,UACnB,QAAQ,MAAM,GAAG,EAAO,YAAY,EAAM,SAAS,WAAW,KAAU,EAAM,KAAK,IAEnF,QAAQ,MAAM,GAAG,EAAO,GAAG,EAAM,OAAO,OAAO,CAAC,EAAE,GAAG,EAAM,SAAS,WAAW,GAAQ;CAE3F,CAEoB,GAEb;AACT"}
|
package/dist/errors.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class e extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}static is(t){return t instanceof e}},t=class extends e{constructor(){super(`Router is disposed`)}},n=class extends e{},r=class extends e{constructor(){super(`Redirect loop detected`)}},i=class extends e{};exports.WayfinderApiError=i,exports.WayfinderDisposedError=t,exports.WayfinderError=e,exports.WayfinderRedirectLoopError=r,exports.WayfinderRouteError=n;
|
|
2
|
+
//# sourceMappingURL=errors.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.cjs","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is WayfinderError {\n return err instanceof WayfinderError;\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed. */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":"AACA,IAAa,EAAb,MAAa,UAAuB,KAAM,CACxC,YAAY,EAAiB,EAAqB,CAChD,MAAM,EAAS,CAAI,EACnB,KAAK,KAAO,IAAI,OAAO,KACvB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,CAClD,CAEA,OAAO,GAAG,EAAqC,CAC7C,OAAO,aAAe,CACxB,CACF,EAGa,EAAb,cAA4C,CAAe,CACzD,aAAc,CACZ,MAAM,oBAAoB,CAC5B,CACF,EAGa,EAAb,cAAyC,CAAe,CAAC,EAG5C,EAAb,cAAgD,CAAe,CAC7D,aAAc,CACZ,MAAM,wBAAwB,CAChC,CACF,EAGa,EAAb,cAAuC,CAAe,CAAC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */
|
|
2
|
+
export declare class WayfinderError extends Error {
|
|
3
|
+
constructor(message: string, opts?: ErrorOptions);
|
|
4
|
+
static is(err: unknown): err is WayfinderError;
|
|
5
|
+
}
|
|
6
|
+
/** Thrown when any router method is called after the router has been disposed. */
|
|
7
|
+
export declare class WayfinderDisposedError extends WayfinderError {
|
|
8
|
+
constructor();
|
|
9
|
+
}
|
|
10
|
+
/** Thrown when a route or path definition is malformed. */
|
|
11
|
+
export declare class WayfinderRouteError extends WayfinderError {
|
|
12
|
+
}
|
|
13
|
+
/** Thrown when the router detects an infinite redirect loop. */
|
|
14
|
+
export declare class WayfinderRedirectLoopError extends WayfinderError {
|
|
15
|
+
constructor();
|
|
16
|
+
}
|
|
17
|
+
/** Thrown on API misuse (e.g. calling next() multiple times). */
|
|
18
|
+
export declare class WayfinderApiError extends WayfinderError {
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,iHAAiH;AACjH,qBAAa,cAAe,SAAQ,KAAK;gBAC3B,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,YAAY;IAMhD,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,cAAc;CAG/C;AAED,kFAAkF;AAClF,qBAAa,sBAAuB,SAAQ,cAAc;;CAIzD;AAED,2DAA2D;AAC3D,qBAAa,mBAAoB,SAAQ,cAAc;CAAG;AAE1D,gEAAgE;AAChE,qBAAa,0BAA2B,SAAQ,cAAc;;CAI7D;AAED,iEAAiE;AACjE,qBAAa,iBAAkB,SAAQ,cAAc;CAAG"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/errors.ts
|
|
2
|
+
var e = class e extends Error {
|
|
3
|
+
constructor(e, t) {
|
|
4
|
+
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
|
+
}
|
|
6
|
+
static is(t) {
|
|
7
|
+
return t instanceof e;
|
|
8
|
+
}
|
|
9
|
+
}, t = class extends e {
|
|
10
|
+
constructor() {
|
|
11
|
+
super("Router is disposed");
|
|
12
|
+
}
|
|
13
|
+
}, n = class extends e {}, r = class extends e {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("Redirect loop detected");
|
|
16
|
+
}
|
|
17
|
+
}, i = class extends e {};
|
|
18
|
+
//#endregion
|
|
19
|
+
export { i as WayfinderApiError, t as WayfinderDisposedError, e as WayfinderError, r as WayfinderRedirectLoopError, n as WayfinderRouteError };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","names":[],"sources":["../src/errors.ts"],"sourcesContent":["/** Base class for all wayfinder errors. Use `instanceof WayfinderError` to catch any router-originated error. */\nexport class WayfinderError extends Error {\n constructor(message: string, opts?: ErrorOptions) {\n super(message, opts);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n static is(err: unknown): err is WayfinderError {\n return err instanceof WayfinderError;\n }\n}\n\n/** Thrown when any router method is called after the router has been disposed. */\nexport class WayfinderDisposedError extends WayfinderError {\n constructor() {\n super('Router is disposed');\n }\n}\n\n/** Thrown when a route or path definition is malformed. */\nexport class WayfinderRouteError extends WayfinderError {}\n\n/** Thrown when the router detects an infinite redirect loop. */\nexport class WayfinderRedirectLoopError extends WayfinderError {\n constructor() {\n super('Redirect loop detected');\n }\n}\n\n/** Thrown on API misuse (e.g. calling next() multiple times). */\nexport class WayfinderApiError extends WayfinderError {}\n"],"mappings":";AACA,IAAa,IAAb,MAAa,UAAuB,MAAM;CACxC,YAAY,GAAiB,GAAqB;EAGhD,AAFA,MAAM,GAAS,CAAI,GACnB,KAAK,OAAO,IAAI,OAAO,MACvB,OAAO,eAAe,MAAM,IAAI,OAAO,SAAS;CAClD;CAEA,OAAO,GAAG,GAAqC;EAC7C,OAAO,aAAe;CACxB;AACF,GAGa,IAAb,cAA4C,EAAe;CACzD,cAAc;EACZ,MAAM,oBAAoB;CAC5B;AACF,GAGa,IAAb,cAAyC,EAAe,CAAC,GAG5C,IAAb,cAAgD,EAAe;CAC7D,cAAc;EACZ,MAAM,wBAAwB;CAChC;AACF,GAGa,IAAb,cAAuC,EAAe,CAAC"}
|
package/dist/guards.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.cjs","names":[],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * R4: `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":"AAsBA,eAAsB,EACpB,EACA,EACA,EACkB,CAClB,IAAM,EAAc,IAAI,IAAI,CAAgB,EAEtC,EAAW,CAAC,GAAG,CAAQ,EAE7B,IAAK,GAAM,CAAE,UAAS,YAAY,EAC5B,SAAW,IAAA,IAAa,CAAC,EAAO,KAAM,GAAS,EAAY,IAAI,CAAI,CAAC,IAIpE,CAAC,MAFiB,EAAQ,CAAW,EAE3B,MAAO,GAGvB,MAAO,EACT"}
|
package/dist/guards.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { BeforeLeaveBlocker, NavigationDestination } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* A registered leave guard. `routes` scopes the guard to navigations that depart from
|
|
4
|
+
* any route whose name appears in the array (matched against any node in the active branch,
|
|
5
|
+
* not just the leaf). When `routes` is omitted the guard fires on every navigation.
|
|
6
|
+
*/
|
|
7
|
+
export type RegisteredBlocker = {
|
|
8
|
+
handler: BeforeLeaveBlocker;
|
|
9
|
+
routes?: string[];
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* Run all registered leave blockers in registration order.
|
|
13
|
+
* Guards whose `routes` filter does not overlap the current active match names are skipped.
|
|
14
|
+
* Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.
|
|
15
|
+
*
|
|
16
|
+
* A snapshot of the blocker set is taken before iteration so that guards added or removed
|
|
17
|
+
* during execution do not affect the current run.
|
|
18
|
+
*
|
|
19
|
+
* R4: `destination` is passed to each blocker so guards can make context-aware decisions.
|
|
20
|
+
*/
|
|
21
|
+
export declare function runLeaveBlockers(blockers: ReadonlySet<RegisteredBlocker>, activeMatchNames: readonly string[], destination: NavigationDestination): Promise<boolean>;
|
|
22
|
+
//# sourceMappingURL=guards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.d.ts","sourceRoot":"","sources":["../src/guards.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAEzE;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,kBAAkB,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,EAAE,WAAW,CAAC,iBAAiB,CAAC,EACxC,gBAAgB,EAAE,SAAS,MAAM,EAAE,EACnC,WAAW,EAAE,qBAAqB,GACjC,OAAO,CAAC,OAAO,CAAC,CAclB"}
|
package/dist/guards.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/guards.ts
|
|
2
|
+
async function e(e, t, n) {
|
|
3
|
+
let r = new Set(t), i = [...e];
|
|
4
|
+
for (let { handler: e, routes: t } of i) if (!(t !== void 0 && !t.some((e) => r.has(e))) && !await e(n)) return !1;
|
|
5
|
+
return !0;
|
|
6
|
+
}
|
|
7
|
+
//#endregion
|
|
8
|
+
export { e as runLeaveBlockers };
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=guards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guards.js","names":[],"sources":["../src/guards.ts"],"sourcesContent":["import type { BeforeLeaveBlocker, NavigationDestination } from './types';\n\n/**\n * A registered leave guard. `routes` scopes the guard to navigations that depart from\n * any route whose name appears in the array (matched against any node in the active branch,\n * not just the leaf). When `routes` is omitted the guard fires on every navigation.\n */\nexport type RegisteredBlocker = {\n handler: BeforeLeaveBlocker;\n routes?: string[];\n};\n\n/**\n * Run all registered leave blockers in registration order.\n * Guards whose `routes` filter does not overlap the current active match names are skipped.\n * Returns `false` as soon as any blocker returns `false`; returns `true` if all pass.\n *\n * A snapshot of the blocker set is taken before iteration so that guards added or removed\n * during execution do not affect the current run.\n *\n * R4: `destination` is passed to each blocker so guards can make context-aware decisions.\n */\nexport async function runLeaveBlockers(\n blockers: ReadonlySet<RegisteredBlocker>,\n activeMatchNames: readonly string[],\n destination: NavigationDestination,\n): Promise<boolean> {\n const activeNames = new Set(activeMatchNames);\n // Snapshot so that removals during iteration don't skip entries.\n const snapshot = [...blockers];\n\n for (const { handler, routes } of snapshot) {\n if (routes !== undefined && !routes.some((name) => activeNames.has(name))) continue;\n\n const allowed = await handler(destination);\n\n if (!allowed) return false;\n }\n\n return true;\n}\n"],"mappings":";AAsBA,eAAsB,EACpB,GACA,GACA,GACkB;CAClB,IAAM,IAAc,IAAI,IAAI,CAAgB,GAEtC,IAAW,CAAC,GAAG,CAAQ;CAE7B,KAAK,IAAM,EAAE,YAAS,eAAY,GAC5B,YAAW,KAAA,KAAa,CAAC,EAAO,MAAM,MAAS,EAAY,IAAI,CAAI,CAAC,MAIpE,CAAC,MAFiB,EAAQ,CAAW,GAE3B,OAAO;CAGvB,OAAO;AACT"}
|
package/dist/history.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(){return{back(){window.history.back()},get location(){return{hash:window.location.hash,pathname:window.location.pathname,search:window.location.search,state:window.history.state}},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,e)},replace(e,t){window.history.replaceState(t,``,e)}}}function t(e=`/`){let t=new URL(e,`http://localhost`),n=[{hash:t.hash,pathname:t.pathname,search:t.search,state:null}],r=0,i=new Set;return{back(){r<=0||(--r,i.forEach(e=>e()))},get location(){return n[r]},onPopstate(e){return i.add(e),()=>i.delete(e)},push(e,t=null){let i=new URL(e,`http://localhost`);n.splice(r+1),n.push({hash:i.hash,pathname:i.pathname,search:i.search,state:t}),r=n.length-1},replace(e,t=null){let i=new URL(e,`http://localhost`);n[r]={hash:i.hash,pathname:i.pathname,search:i.search,state:t}}}}exports.createBrowserHistory=e,exports.createMemoryHistory=t;
|
|
2
|
+
//# sourceMappingURL=history.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.cjs","names":[],"sources":["../src/history.ts"],"sourcesContent":["import type { HistoryDriver } from './types';\n\n/** Creates a history driver backed by the browser History API. */\nexport function createBrowserHistory(): HistoryDriver {\n return {\n back() {\n window.history.back();\n },\n get location() {\n return {\n hash: window.location.hash,\n pathname: window.location.pathname,\n search: window.location.search,\n // State lives on window.history.state, not window.location.\n state: window.history.state,\n };\n },\n onPopstate(listener) {\n window.addEventListener('popstate', listener);\n\n return () => window.removeEventListener('popstate', listener);\n },\n push(url, state) {\n window.history.pushState(state, '', url);\n },\n replace(url, state) {\n window.history.replaceState(state, '', url);\n },\n };\n}\n\ntype MemoryLocation = { hash: string; pathname: string; search: string; state: unknown };\n\n/**\n * Creates an in-memory history driver. Suitable for SSR, tests, and non-browser environments.\n *\n * Semantics mirror the browser History API:\n * - `push()` and `replace()` update the location silently (no listener notification),\n * matching `pushState`/`replaceState` which do not fire `popstate`.\n * - `back()` moves one entry back and notifies subscribers, matching a browser back-button press.\n */\nexport function createMemoryHistory(initialPath = '/'): HistoryDriver {\n const parsed = new URL(initialPath, 'http://localhost');\n const stack: MemoryLocation[] = [\n { hash: parsed.hash, pathname: parsed.pathname, search: parsed.search, state: null },\n ];\n let cursor = 0;\n const listeners = new Set<() => void>();\n\n return {\n back() {\n if (cursor <= 0) return;\n\n cursor -= 1;\n listeners.forEach((l) => l());\n },\n get location(): MemoryLocation {\n return stack[cursor]!;\n },\n onPopstate(listener) {\n listeners.add(listener);\n\n return () => listeners.delete(listener);\n },\n push(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack.splice(cursor + 1);\n stack.push({ hash: p.hash, pathname: p.pathname, search: p.search, state });\n cursor = stack.length - 1;\n // Silent — mirrors browser pushState semantics. Router drives navigation via #handleRoute directly.\n },\n replace(url, state = null) {\n const p = new URL(url, 'http://localhost');\n\n stack[cursor] = { hash: p.hash, pathname: p.pathname, search: p.search, state };\n // Silent — mirrors browser replaceState semantics.\n },\n };\n}\n"],"mappings":"AAGA,SAAgB,GAAsC,CACpD,MAAO,CACL,MAAO,CACL,OAAO,QAAQ,KAAK,CACtB,EACA,IAAI,UAAW,CACb,MAAO,CACL,KAAM,OAAO,SAAS,KACtB,SAAU,OAAO,SAAS,SAC1B,OAAQ,OAAO,SAAS,OAExB,MAAO,OAAO,QAAQ,KACxB,CACF,EACA,WAAW,EAAU,CAGnB,OAFA,OAAO,iBAAiB,WAAY,CAAQ,MAE/B,OAAO,oBAAoB,WAAY,CAAQ,CAC9D,EACA,KAAK,EAAK,EAAO,CACf,OAAO,QAAQ,UAAU,EAAO,GAAI,CAAG,CACzC,EACA,QAAQ,EAAK,EAAO,CAClB,OAAO,QAAQ,aAAa,EAAO,GAAI,CAAG,CAC5C,CACF,CACF,CAYA,SAAgB,EAAoB,EAAc,IAAoB,CACpE,IAAM,EAAS,IAAI,IAAI,EAAa,kBAAkB,EAChD,EAA0B,CAC9B,CAAE,KAAM,EAAO,KAAM,SAAU,EAAO,SAAU,OAAQ,EAAO,OAAQ,MAAO,IAAK,CACrF,EACI,EAAS,EACP,EAAY,IAAI,IAEtB,MAAO,CACL,MAAO,CACD,GAAU,IAEd,IACA,EAAU,QAAS,GAAM,EAAE,CAAC,EAC9B,EACA,IAAI,UAA2B,CAC7B,OAAO,EAAM,EACf,EACA,WAAW,EAAU,CAGnB,OAFA,EAAU,IAAI,CAAQ,MAET,EAAU,OAAO,CAAQ,CACxC,EACA,KAAK,EAAK,EAAQ,KAAM,CACtB,IAAM,EAAI,IAAI,IAAI,EAAK,kBAAkB,EAEzC,EAAM,OAAO,EAAS,CAAC,EACvB,EAAM,KAAK,CAAE,KAAM,EAAE,KAAM,SAAU,EAAE,SAAU,OAAQ,EAAE,OAAQ,OAAM,CAAC,EAC1E,EAAS,EAAM,OAAS,CAE1B,EACA,QAAQ,EAAK,EAAQ,KAAM,CACzB,IAAM,EAAI,IAAI,IAAI,EAAK,kBAAkB,EAEzC,EAAM,GAAU,CAAE,KAAM,EAAE,KAAM,SAAU,EAAE,SAAU,OAAQ,EAAE,OAAQ,OAAM,CAEhF,CACF,CACF"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { HistoryDriver } from './types';
|
|
2
|
+
/** Creates a history driver backed by the browser History API. */
|
|
3
|
+
export declare function createBrowserHistory(): HistoryDriver;
|
|
4
|
+
/**
|
|
5
|
+
* Creates an in-memory history driver. Suitable for SSR, tests, and non-browser environments.
|
|
6
|
+
*
|
|
7
|
+
* Semantics mirror the browser History API:
|
|
8
|
+
* - `push()` and `replace()` update the location silently (no listener notification),
|
|
9
|
+
* matching `pushState`/`replaceState` which do not fire `popstate`.
|
|
10
|
+
* - `back()` moves one entry back and notifies subscribers, matching a browser back-button press.
|
|
11
|
+
*/
|
|
12
|
+
export declare function createMemoryHistory(initialPath?: string): HistoryDriver;
|
|
13
|
+
//# sourceMappingURL=history.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../src/history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,kEAAkE;AAClE,wBAAgB,oBAAoB,IAAI,aAAa,CA0BpD;AAID;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,SAAM,GAAG,aAAa,CAsCpE"}
|