@vielzeug/wayfinder 26.11.11 → 26.11.13
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/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -4
- package/dist/path.cjs +1 -1
- package/dist/path.cjs.map +1 -1
- package/dist/path.d.ts +1 -9
- package/dist/path.d.ts.map +1 -1
- package/dist/path.js +1 -9
- package/dist/path.js.map +1 -1
- package/dist/router.cjs +1 -1
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.ts +5 -3
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +83 -112
- package/dist/router.js.map +1 -1
- package/dist/wayfinder.cjs +1 -1
- package/dist/wayfinder.cjs.map +1 -1
- package/dist/wayfinder.iife.js +1 -1
- package/dist/wayfinder.iife.js.map +1 -1
- package/dist/wayfinder.js +84 -174
- package/dist/wayfinder.js.map +1 -1
- package/package.json +2 -2
- package/dist/phase-mirror.cjs +0 -2
- package/dist/phase-mirror.cjs.map +0 -1
- package/dist/phase-mirror.d.ts +0 -51
- package/dist/phase-mirror.d.ts.map +0 -1
- package/dist/phase-mirror.js +0 -58
- package/dist/phase-mirror.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./route-signals.cjs"),i=require("./router.cjs");exports.WayfinderApiError=e.WayfinderApiError,exports.WayfinderConfigError=e.WayfinderConfigError,exports.WayfinderDisposedError=e.WayfinderDisposedError,exports.WayfinderError=e.WayfinderError,exports.WayfinderRedirectLoopError=e.WayfinderRedirectLoopError,exports.WayfinderRouteError=e.WayfinderRouteError,exports.createBrowserHistory=t.createBrowserHistory,exports.createHashHistory=t.createHashHistory,exports.createHistoryForBase=t.createHistoryForBase,exports.createMemoryHistory=t.createMemoryHistory,exports.createRouteSignals=r.createRouteSignals,exports.createRouter=i.createRouter,exports.redirectTo=n.redirectTo;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
export { WayfinderApiError, WayfinderConfigError, WayfinderDisposedError, WayfinderError, WayfinderRedirectLoopError, WayfinderRouteError, } from './errors';
|
|
2
2
|
export { createBrowserHistory, createHashHistory, createHistoryForBase, createMemoryHistory, type HashHistoryOptions, } from './history';
|
|
3
3
|
export { redirectTo } from './middleware';
|
|
4
|
-
export type { PhaseMirror, PhaseMirrorOptions } from './phase-mirror';
|
|
5
|
-
export { createPhaseMirror } from './phase-mirror';
|
|
6
4
|
export type { RouteSignals } from './route-signals';
|
|
7
5
|
export { createRouteSignals } from './route-signals';
|
|
8
6
|
export type { Router } from './router';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,KAAK,kBAAkB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,sBAAsB,EACtB,cAAc,EACd,0BAA0B,EAC1B,mBAAmB,GACpB,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,KAAK,kBAAkB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,YAAY,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,cAAc,EACd,WAAW,EACX,MAAM,EACN,aAAa,EACb,eAAe,EACf,YAAY,EACZ,UAAU,EACV,qBAAqB,EACrB,eAAe,EACf,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,mBAAmB,EACnB,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,SAAS,EACT,WAAW,EACX,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,UAAU,EACV,UAAU,EACV,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,WAAW,EACX,4BAA4B,GAC7B,MAAM,SAAS,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { WayfinderApiError as e, WayfinderConfigError as t, WayfinderDisposedError as n, WayfinderError as r, WayfinderRedirectLoopError as i, WayfinderRouteError as a } from "./errors.js";
|
|
2
2
|
import { createBrowserHistory as o, createHashHistory as s, createHistoryForBase as c, createMemoryHistory as l } from "./history.js";
|
|
3
3
|
import { redirectTo as u } from "./middleware.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
export { e as WayfinderApiError, t as WayfinderConfigError, n as WayfinderDisposedError, r as WayfinderError, i as WayfinderRedirectLoopError, a as WayfinderRouteError, o as createBrowserHistory, s as createHashHistory, c as createHistoryForBase, l as createMemoryHistory, d as createPhaseMirror, f as createRouteSignals, p as createRouter, u as redirectTo };
|
|
4
|
+
import { createRouteSignals as d } from "./route-signals.js";
|
|
5
|
+
import { createRouter as f } from "./router.js";
|
|
6
|
+
export { e as WayfinderApiError, t as WayfinderConfigError, n as WayfinderDisposedError, r as WayfinderError, i as WayfinderRedirectLoopError, a as WayfinderRouteError, o as createBrowserHistory, s as createHashHistory, c as createHistoryForBase, l as createMemoryHistory, d as createRouteSignals, f as createRouter, u as redirectTo };
|
package/dist/path.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs");function normalizePath(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function joinPaths(e,t){return normalizePath(`${e}/${t}`)}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function compilePathMatcher(t){let n=normalizePath(t);if(n===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let r=[],i=n.slice(1).split(`/`),a=[`^`],o=[`^`];for(let n=0;n<i.length;n+=1){let s=i[n];if(s===`*`){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${t}`);a.push(`(?:/.*)?`);break}if(s.startsWith(`:`)&&s.endsWith(`*`)){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard param must be final segment in path: ${t}`);let c=s.slice(1,-1);if(!/^\w+$/.test(c))throw new e.WayfinderConfigError(`Invalid param name ":${c}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(c),a.push(n===i.length-1?`(?:/(.*))?`:`/(.*)`),o.push(`/.*`);break}if(s.startsWith(`:`)){let n=s.slice(1);if(!/^\w+$/.test(n))throw new e.WayfinderConfigError(`Invalid param name ":${n}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(n),a.push(`/([^/]+)`),o.push(`/[^/]+`);continue}let c=escapeRegex(s);a.push(`/${c}`),o.push(`/${c}`)}return a.push(`$`),o.push(`(?:/.*)?$`),{paramNames:r,pattern:new RegExp(a.join(``)),prefixPattern:new RegExp(o.join(``))}}function matchRecord(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function matchRouteFor(e,t){for(let n of t){let t=matchRecord(e,n);if(t)return{params:t,record:n}}return{params:{}}}function matchesPrefix(e,t){return t.matcher.prefixPattern.test(e)}function parseQuery(e){let t=new URLSearchParams(e),n={},setQueryValue=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,r]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;t===void 0?setQueryValue(e,r):Array.isArray(t)?t.push(r):setQueryValue(e,[t,r])}return n}function buildUrl(t,n,r={},i){let a=n.replace(/:(\w+)(\*)?/g,(t,n,i)=>{let a=r[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return i?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(i&&Object.keys(i).length){let e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),a+=`?${e.toString()}`}return joinPaths(t,a)}function stripBase(e,t=`/`){let n=normalizePath(e),r=normalizePath(t);if(r===`/`)return n;if(n===r)return`/`;let i=`${r}/`;return n.startsWith(i)?normalizePath(n.slice(r.length)):n}
|
|
1
|
+
const e=require("./errors.cjs");function normalizePath(e){let t=`/${e}`.replace(/\/+/g,`/`);return t!==`/`&&t.endsWith(`/`)?t.slice(0,-1):t}function joinPaths(e,t){return normalizePath(`${e}/${t}`)}function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function compilePathMatcher(t){let n=normalizePath(t);if(n===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let r=[],i=n.slice(1).split(`/`),a=[`^`],o=[`^`];for(let n=0;n<i.length;n+=1){let s=i[n];if(s===`*`){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${t}`);a.push(`(?:/.*)?`);break}if(s.startsWith(`:`)&&s.endsWith(`*`)){if(n!==i.length-1)throw new e.WayfinderConfigError(`Wildcard param must be final segment in path: ${t}`);let c=s.slice(1,-1);if(!/^\w+$/.test(c))throw new e.WayfinderConfigError(`Invalid param name ":${c}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(c),a.push(n===i.length-1?`(?:/(.*))?`:`/(.*)`),o.push(`/.*`);break}if(s.startsWith(`:`)){let n=s.slice(1);if(!/^\w+$/.test(n))throw new e.WayfinderConfigError(`Invalid param name ":${n}" in path "${t}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);r.push(n),a.push(`/([^/]+)`),o.push(`/[^/]+`);continue}let c=escapeRegex(s);a.push(`/${c}`),o.push(`/${c}`)}return a.push(`$`),o.push(`(?:/.*)?$`),{paramNames:r,pattern:new RegExp(a.join(``)),prefixPattern:new RegExp(o.join(``))}}function matchRecord(e,t){let n=t.matcher.pattern.exec(e);if(!n)return null;let r={};return t.matcher.paramNames.forEach((e,t)=>{let i=n[t+1]??``;try{r[e]=decodeURIComponent(i)}catch{r[e]=i}}),r}function matchRouteFor(e,t){for(let n of t){let t=matchRecord(e,n);if(t)return{params:t,record:n}}return{params:{}}}function matchesPrefix(e,t){return t.matcher.prefixPattern.test(e)}function parseQuery(e){let t=new URLSearchParams(e),n={},setQueryValue=(e,t)=>{Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})};for(let[e,r]of t.entries()){let t=Object.hasOwn(n,e)?n[e]:void 0;t===void 0?setQueryValue(e,r):Array.isArray(t)?t.push(r):setQueryValue(e,[t,r])}return n}function buildUrl(t,n,r={},i){let a=n.replace(/:(\w+)(\*)?/g,(t,n,i)=>{let a=r[n];if(a==null)throw new e.WayfinderRouteError(`Missing path param: ${n}`);return i?a.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(a)});if(i&&Object.keys(i).length){let e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),a+=`?${e.toString()}`}return joinPaths(t,a)}function stripBase(e,t=`/`){let n=normalizePath(e),r=normalizePath(t);if(r===`/`)return n;if(n===r)return`/`;let i=`${r}/`;return n.startsWith(i)?normalizePath(n.slice(r.length)):n}exports.buildUrl=buildUrl,exports.compilePathMatcher=compilePathMatcher,exports.joinPaths=joinPaths,exports.matchRecord=matchRecord,exports.matchRouteFor=matchRouteFor,exports.matchesPrefix=matchesPrefix,exports.normalizePath=normalizePath,exports.parseQuery=parseQuery,exports.stripBase=stripBase;
|
|
2
2
|
//# sourceMappingURL=path.cjs.map
|
package/dist/path.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.cjs","names":["WayfinderConfigError","WayfinderRouteError","require_errors","normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","isWildcard","query","item","normalizedPath","normalizedBase","prefix","history"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteLocation, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n\nexport function readLocation(\n base: string,\n history: { location: { hash: string; pathname: string; search: string; state: unknown } },\n): RouteLocation {\n return {\n hash: history.location.hash.replace(/^#/, ''),\n historyState: history.location.state,\n pathname: stripBase(history.location.pathname || '/', base),\n query: parseQuery(history.location.search || ''),\n };\n}\n"],"mappings":"A,gCAIA,SAAgB,cAAc,EAAsB,CAClD,IAAMG,EAAa,IAAIC,IAAO,QAAQ,OAAQ,GAAG,EAEjD,OAAOD,IAAe,KAAOA,EAAW,SAAS,GAAG,EAAIA,EAAW,MAAM,EAAG,EAAE,EAAIA,CACpF,CAEA,SAAgB,UAAU,EAAc,EAAsB,CAC5D,OAAO,cAAc,GAAGE,EAAK,GAAGD,GAAM,CACxC,CAEA,SAAS,YAAY,EAAuB,CAC1C,OAAOE,EAAM,QAAQ,sBAAuB,MAAM,CACpD,CAEA,SAAgB,mBAAmB,EAA4B,CAC7D,IAAMH,EAAa,cAAcC,CAAI,EAErC,GAAID,IAAe,IACjB,MAAO,CACL,WAAY,CAAC,EACb,QAAS,OACT,cAAe,MACjB,EAGF,IAAMI,EAAuB,CAAC,EACxBC,EAAWL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I,EAC1D,MAAO,WAAW6B,EAAQ,SAAS,QAAU,EAAE,CACjD,CACF,C"}
|
|
1
|
+
{"version":3,"file":"path.cjs","names":["WayfinderConfigError","WayfinderRouteError","require_errors","normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","isWildcard","query","item","normalizedPath","normalizedBase","prefix"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n"],"mappings":"A,gCAIA,SAAgB,cAAc,EAAsB,CAClD,IAAMG,EAAa,IAAIC,IAAO,QAAQ,OAAQ,GAAG,EAEjD,OAAOD,IAAe,KAAOA,EAAW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ACvCe,EAAiB,cAAc3B,CAAI,EAEzC,GAAI2B,IAAmB,IAAK,OAAOD,EAEnC,GAAIA,IAAmBC,EAAgB,MAAO,IAE9C,IAAMC,EAAS,GAAGD,EAAe,GAEjC,OAAOD,EAAe,WAAWE,CAAM,EACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,EACzDD,CACN,C"}
|
package/dist/path.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { QueryParams, ResolvedQueryParams,
|
|
1
|
+
import type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';
|
|
2
2
|
/** Ensure leading slash, collapse duplicate slashes, preserve root. */
|
|
3
3
|
export declare function normalizePath(path: string): string;
|
|
4
4
|
export declare function joinPaths(base: string, path: string): string;
|
|
@@ -22,12 +22,4 @@ export declare function parseQuery(queryString: string): QueryParams;
|
|
|
22
22
|
/** Build a URL from a path pattern, params, and query, respecting the router base. */
|
|
23
23
|
export declare function buildUrl(base: string, pattern: string, params?: RouteParams, query?: ResolvedQueryParams): string;
|
|
24
24
|
export declare function stripBase(pathname: string, base?: string): string;
|
|
25
|
-
export declare function readLocation(base: string, history: {
|
|
26
|
-
location: {
|
|
27
|
-
hash: string;
|
|
28
|
-
pathname: string;
|
|
29
|
-
search: string;
|
|
30
|
-
state: unknown;
|
|
31
|
-
};
|
|
32
|
-
}): RouteLocation;
|
|
33
25
|
//# sourceMappingURL=path.d.ts.map
|
package/dist/path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,
|
|
1
|
+
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,mBAAmB,EAAE,YAAY,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAExG,uEAAuE;AACvE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAIlD;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE5D;AAMD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CA4E7D;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,WAAW,GAAG,IAAI,CAkBrF;AAED,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,SAAS,WAAW,EAAE,GAC9B;IAAE,MAAM,EAAE,WAAW,CAAC;IAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAAE,CAQ/C;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAE5E;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,WAAW,EAAE,MAAM,GAAG,WAAW,CAyB3D;AAED,sFAAsF;AACtF,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAE,WAAgB,EAAE,KAAK,CAAC,EAAE,mBAAmB,GAAG,MAAM,CA+BrH;AAID,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,SAAM,GAAG,MAAM,CAa9D"}
|
package/dist/path.js
CHANGED
|
@@ -111,14 +111,6 @@ function stripBase(e, t = "/") {
|
|
|
111
111
|
let i = `${r}/`;
|
|
112
112
|
return n.startsWith(i) ? normalizePath(n.slice(r.length)) : n;
|
|
113
113
|
}
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
hash: t.location.hash.replace(/^#/, ""),
|
|
117
|
-
historyState: t.location.state,
|
|
118
|
-
pathname: stripBase(t.location.pathname || "/", e),
|
|
119
|
-
query: parseQuery(t.location.search || "")
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
export { buildUrl, compilePathMatcher, joinPaths, matchRecord, matchRouteFor, matchesPrefix, normalizePath, parseQuery, readLocation, stripBase };
|
|
114
|
+
export { buildUrl, compilePathMatcher, joinPaths, matchRecord, matchRouteFor, matchesPrefix, normalizePath, parseQuery, stripBase };
|
|
123
115
|
|
|
124
116
|
//# sourceMappingURL=path.js.map
|
package/dist/path.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.js","names":["normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","WayfinderConfigError","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","WayfinderRouteError","isWildcard","query","item","normalizedPath","normalizedBase","prefix","history"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteLocation, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n\nexport function readLocation(\n base: string,\n history: { location: { hash: string; pathname: string; search: string; state: unknown } },\n): RouteLocation {\n return {\n hash: history.location.hash.replace(/^#/, ''),\n historyState: history.location.state,\n pathname: stripBase(history.location.pathname || '/', base),\n query: parseQuery(history.location.search || ''),\n };\n}\n"],"mappings":";;AAIA,SAAgB,cAAc,GAAsB;CAClD,IAAMA,IAAa,IAAIC,IAAO,QAAQ,QAAQ,GAAG;CAEjD,OAAOD,MAAe,OAAOA,EAAW,SAAS,GAAG,IAAIA,EAAW,MAAM,GAAG,EAAE,IAAIA;AACpF;AAEA,SAAgB,UAAU,GAAc,GAAsB;CAC5D,OAAO,cAAc,GAAGE,EAAK,GAAGD,GAAM;AACxC;AAEA,SAAS,YAAY,GAAuB;CAC1C,OAAOE,EAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAgB,mBAAmB,GAA4B;CAC7D,IAAMH,IAAa,cAAcC,CAAI;CAErC,IAAID,MAAe,KACjB,OAAO;EACL,YAAY,CAAC;EACb,SAAS;EACT,eAAe;CACjB;CAGF,IAAMI,IAAuB,CAAC,GACxBC,IAAWL,EAAW,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,GACxCM,IAAuB,CAAC,GAAG,GAC3BC,IAAwB,CAAC,GAAG;CAElC,KAAK,IAAIC,IAAI,GAAGA,IAAIH,EAAS,QAAQ,KAAK,GAAG;EAC3C,IAAMI,IAAUJ,EAASG;EAEzB,IAAIC,MAAY,KAAK;GACnB,IAAID,MAAMH,EAAS,SAAS,GAC1B,MAAM,IAAIK,EAAqB,mDAAmDT,GAAM;GAG1F,EAAW,KAAK,UAAU;GAC1B;EACF;EAEA,IAAIQ,EAAQ,WAAW,GAAG,KAAKA,EAAQ,SAAS,GAAG,GAAG;GACpD,IAAID,M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IAAMR,IAAS,IAAI,gBAAgB;EAUnC,AARA,OAAO,QAAQQ,CAAK,CAAC,CAAC,SAAS,CAACL,GAAKN,OAAW;GAC9C,AAAI,MAAM,QAAQA,CAAK,IACrBA,EAAM,SAAS,MAAS;IACtB,EAAO,OAAOM,GAAK,OAAOM,CAAI,CAAC;GACjC,CAAC,IACET,EAAO,IAAIG,GAAK,OAAON,CAAK,CAAC;EACpC,CAAC,GAED,KAAQ,IAAIG,EAAO,SAAS;CAC9B;CAEA,OAAO,UAAUlB,GAAMD,CAAI;AAC7B;AAIA,SAAgB,UAAU,GAAkB,IAAO,KAAa;CAC9D,IAAM6B,IAAiB,cAAcf,CAAQ,GACvCgB,IAAiB,cAAc7B,CAAI;CAEzC,IAAI6B,MAAmB,KAAK,OAAOD;CAEnC,IAAIA,MAAmBC,GAAgB,OAAO;CAE9C,IAAMC,IAAS,GAAGD,EAAe;CAEjC,OAAOD,EAAe,WAAWE,CAAM,IACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,IACzDD;AACN;AAEA,SAAgB,aACd,GACA,GACe;CACf,OAAO;EACL,MAAMG,EAAQ,SAAS,KAAK,QAAQ,MAAM,EAAE;EAC5C,cAAcA,EAAQ,SAAS;EAC/B,UAAU,UAAUA,EAAQ,SAAS,YAAY,KAAK/B,CAAI;EAC1D,OAAO,WAAW+B,EAAQ,SAAS,UAAU,EAAE;CACjD;AACF"}
|
|
1
|
+
{"version":3,"file":"path.js","names":["normalized","path","base","input","paramNames","segments","regexParts","prefixParts","i","segment","WayfinderConfigError","name","escaped","match","record","pathname","params","value","index","records","search","queryString","out","key","existing","pattern","WayfinderRouteError","isWildcard","query","item","normalizedPath","normalizedBase","prefix"],"sources":["../src/path.ts"],"sourcesContent":["import { WayfinderConfigError, WayfinderRouteError } from './errors';\nimport type { QueryParams, ResolvedQueryParams, RouteMatcher, RouteParams, RouteRecord } from './types';\n\n/** Ensure leading slash, collapse duplicate slashes, preserve root. */\nexport function normalizePath(path: string): string {\n const normalized = `/${path}`.replace(/\\/+/g, '/');\n\n return normalized !== '/' && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;\n}\n\nexport function joinPaths(base: string, path: string): string {\n return normalizePath(`${base}/${path}`);\n}\n\nfunction escapeRegex(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function compilePathMatcher(path: string): RouteMatcher {\n const normalized = normalizePath(path);\n\n if (normalized === '/') {\n return {\n paramNames: [],\n pattern: /^\\/$/,\n prefixPattern: /^\\/$/,\n };\n }\n\n const paramNames: string[] = [];\n const segments = normalized.slice(1).split('/');\n const regexParts: string[] = ['^'];\n const prefixParts: string[] = ['^'];\n\n for (let i = 0; i < segments.length; i += 1) {\n const segment = segments[i]!;\n\n if (segment === '*') {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard \"*\" must be the final segment in path: ${path}`);\n }\n\n regexParts.push('(?:/.*)?');\n break;\n }\n\n if (segment.startsWith(':') && segment.endsWith('*')) {\n if (i !== segments.length - 1) {\n throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${path}`);\n }\n\n const name = segment.slice(1, -1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push(i === segments.length - 1 ? '(?:/(.*))?' : '/(.*)');\n prefixParts.push('/.*');\n break;\n }\n\n if (segment.startsWith(':')) {\n const name = segment.slice(1);\n\n if (!/^\\w+$/.test(name)) {\n throw new WayfinderConfigError(\n `Invalid param name \":${name}\" in path \"${path}\". Param names must only contain word characters (a–z, A–Z, 0–9, _).`,\n );\n }\n\n paramNames.push(name);\n regexParts.push('/([^/]+)');\n prefixParts.push('/[^/]+');\n continue;\n }\n\n const escaped = escapeRegex(segment);\n\n regexParts.push(`/${escaped}`);\n prefixParts.push(`/${escaped}`);\n }\n\n regexParts.push('$');\n prefixParts.push('(?:/.*)?$');\n\n return {\n paramNames,\n pattern: new RegExp(regexParts.join('')),\n prefixPattern: new RegExp(prefixParts.join('')),\n };\n}\n\nexport function matchRecord(pathname: string, record: RouteRecord): RouteParams | null {\n const match = record.matcher.pattern.exec(pathname);\n\n if (!match) return null;\n\n const params: RouteParams = {};\n\n record.matcher.paramNames.forEach((name: string, index: number) => {\n const value = match[index + 1] ?? '';\n\n try {\n params[name] = decodeURIComponent(value);\n } catch {\n params[name] = value;\n }\n });\n\n return params;\n}\n\nexport function matchRouteFor(\n pathname: string,\n records: readonly RouteRecord[],\n): { params: RouteParams; record?: RouteRecord } {\n for (const record of records) {\n const params = matchRecord(pathname, record);\n\n if (params) return { params, record };\n }\n\n return { params: {} };\n}\n\nexport function matchesPrefix(pathname: string, record: RouteRecord): boolean {\n return record.matcher.prefixPattern.test(pathname);\n}\n\n/**\n * Parse `?foo=a&foo=b&bar=c` into `{ foo: ['a', 'b'], bar: 'c' }`.\n *\n * @security Query keys come directly from the (attacker-controlled) URL. Plain bracket\n * assignment (`out[key] = value`) would let a key like `__proto__` reach the inherited\n * `Object.prototype.__proto__` setter and silently rewrite `out`'s own prototype instead of\n * storing a value: `setQueryValue` uses `Object.defineProperty` so every key, including\n * `__proto__`/`constructor`/`prototype`, is always stored as a plain own data property.\n */\nexport function parseQuery(queryString: string): QueryParams {\n const search = new URLSearchParams(queryString);\n const out: QueryParams = {};\n\n const setQueryValue = (key: string, value: QueryParams[string]): void => {\n Object.defineProperty(out, key, { configurable: true, enumerable: true, value, writable: true });\n };\n\n for (const [key, value] of search.entries()) {\n const existing = Object.hasOwn(out, key) ? out[key] : undefined;\n\n if (existing === undefined) {\n setQueryValue(key, value);\n continue;\n }\n\n if (Array.isArray(existing)) {\n existing.push(value);\n continue;\n }\n\n setQueryValue(key, [existing, value]);\n }\n\n return out;\n}\n\n/** Build a URL from a path pattern, params, and query, respecting the router base. */\nexport function buildUrl(base: string, pattern: string, params: RouteParams = {}, query?: ResolvedQueryParams): string {\n let path = pattern.replace(/:(\\w+)(\\*)?/g, (_match, key: string, isWildcard: string) => {\n const value = params[key];\n\n if (value == null) throw new WayfinderRouteError(`Missing path param: ${key}`);\n\n if (isWildcard) {\n return value\n .split('/')\n .map((segment) => encodeURIComponent(segment))\n .join('/');\n }\n\n return encodeURIComponent(value);\n });\n\n if (query && Object.keys(query).length) {\n const search = new URLSearchParams();\n\n Object.entries(query).forEach(([key, value]) => {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, String(item));\n });\n else search.set(key, String(value));\n });\n\n path += `?${search.toString()}`;\n }\n\n return joinPaths(base, path);\n}\n\n// ─── Location helpers (formerly in resolve.ts) ────────────────────────────────\n\nexport function stripBase(pathname: string, base = '/'): string {\n const normalizedPath = normalizePath(pathname);\n const normalizedBase = normalizePath(base);\n\n if (normalizedBase === '/') return normalizedPath;\n\n if (normalizedPath === normalizedBase) return '/';\n\n const prefix = `${normalizedBase}/`;\n\n return normalizedPath.startsWith(prefix)\n ? normalizePath(normalizedPath.slice(normalizedBase.length))\n : normalizedPath;\n}\n"],"mappings":";;AAIA,SAAgB,cAAc,GAAsB;CAClD,IAAMA,IAAa,IAAIC,IAAO,QAAQ,QAAQ,GAAG;CAEjD,OAAOD,MAAe,OAAOA,EAAW,SAAS,GAAG,IAAIA,EAAW,MAAM,GAAG,EAAE,IAAIA;AACpF;AAEA,SAAgB,UAAU,GAAc,GAAsB;CAC5D,OAAO,cAAc,GAAGE,EAAK,GAAGD,GAAM;AACxC;AAEA,SAAS,YAAY,GAAuB;CAC1C,OAAOE,EAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAgB,mBAAmB,GAA4B;CAC7D,IAAMH,IAAa,cAAcC,CAAI;CAErC,IAAID,MAAe,KACjB,OAAO;EACL,YAAY,CAAC;EACb,SAAS;EACT,eAAe;CACjB;CAGF,IAAMI,IAAuB,CAAC,GACxBC,IAAWL,EAAW,MAAM,CAAC,CAAC,CAAC,MAAM,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AAG,GAAqC;CACrH,IAAIrB,IAAOwB,EAAQ,QAAQ,iBAAiB,GAAQ,GAAa,MAAuB;EACtF,IAAMR,IAAQD,EAAOO;EAErB,IAAIN,KAAS,MAAM,MAAM,IAAIS,EAAoB,uBAAuBH,GAAK;EAS7E,OAPII,IACKV,EACJ,MAAM,GAAG,CAAC,CACV,KAAK,MAAY,mBAAmBR,CAAO,CAAC,CAAC,CAC7C,KAAK,GAAG,IAGN,mBAAmBQ,CAAK;CACjC,CAAC;CAED,IAAIW,KAAS,OAAO,KAAKA,CAAK,CAAC,CAAC,QAAQ;EACtC,IAAMR,IAAS,IAAI,gBAAgB;EAUnC,AARA,OAAO,QAAQQ,CAAK,CAAC,CAAC,SAAS,CAACL,GAAKN,OAAW;GAC9C,AAAI,MAAM,QAAQA,CAAK,IACrBA,EAAM,SAAS,MAAS;IACtB,EAAO,OAAOM,GAAK,OAAOM,CAAI,CAAC;GACjC,CAAC,IACET,EAAO,IAAIG,GAAK,OAAON,CAAK,CAAC;EACpC,CAAC,GAED,KAAQ,IAAIG,EAAO,SAAS;CAC9B;CAEA,OAAO,UAAUlB,GAAMD,CAAI;AAC7B;AAIA,SAAgB,UAAU,GAAkB,IAAO,KAAa;CAC9D,IAAM6B,IAAiB,cAAcf,CAAQ,GACvCgB,IAAiB,cAAc7B,CAAI;CAEzC,IAAI6B,MAAmB,KAAK,OAAOD;CAEnC,IAAIA,MAAmBC,GAAgB,OAAO;CAE9C,IAAMC,IAAS,GAAGD,EAAe;CAEjC,OAAOD,EAAe,WAAWE,CAAM,IACnC,cAAcF,EAAe,MAAMC,EAAe,MAAM,CAAC,IACzDD;AACN"}
|
package/dist/router.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./_navigation.cjs"),t=require("./compile.cjs"),n=require("./context.cjs"),r=require("./errors.cjs"),i=require("./guards.cjs"),a=require("./history.cjs"),o=require("./path.cjs");function getRouteByName(e,t){let n=t.get(e);if(n)return n;let i=[...t.keys()].join(`, `);throw new r.WayfinderRouteError(i?`Unknown route name: ${e}. Available routes: ${i}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=getRouteByName(e.name,t),i=o.buildUrl(n,r.path,e.params,e.query);return e.hash?`${i}#${e.hash}`:i}var s=Symbol(`wayfinder.routerError`);function carryError(e,t){return{[s]:!0,context:t,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&s in e}function unwrapCarrier(e){throw isRouterErrorCarrier(e)?e.error:e}var Router=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=e.createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let r=t.compileRoutes(e);if(this.#e=o.normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??a.createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=r.records,this.#a=r.routesByName,this.#d=n.createRouteState({location:{hash:``,historyState:null,pathname:`/`,query:{}},matches:[],status:`idle`}),e.notFound){let t=e.notFound,n={dataFn:t.data,name:`__notFound__`};this.#v={branchDefs:[n],leaf:n,matcher:{paramNames:[],pattern:/(?:)/,prefixPattern:/(?:)/},ownMiddleware:t.middleware??[],path:`/*`}}else this.#v=null;this.#y=this.#x();let{hash:i,pathname:s,search:c}=this.#r.location;this.#m=`${s}${c}${i}`;let l=this.#u.begin(),u=this.#A(l,o.readLocation(this.#e,this.#r),(e,t)=>{if(!l.isCurrent())return;let n=this.#F(e);t&&this.#r.replace(n,e.historyState),this.#m=n},void 0,0,!1).then(()=>void 0);this.ready=u.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(u,{source:`initial-navigation`}),this.beforeLeave=this.beforeLeave.bind(this),this.createViewRegistry=this.createViewRegistry.bind(this),this.dispose=this.dispose.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.isActive=this.isActive.bind(this),this.load=this.load.bind(this),this.match=this.match.bind(this),this.navigate=this.navigate.bind(this),this.preload=this.preload.bind(this),this.subscribe=this.subscribe.bind(this),this.url=this.url.bind(this),this.waitFor=this.waitFor.bind(this)}getSnapshot(){return this.#d}createViewRegistry(e,t){return{resolve:n=>{let r=n.matches.at(-1)?.name;return r===`__notFound__`?t?.notFound:r?e[r]:void 0}}}subscribe(e){return this.#b(),this.#h.add(e),()=>{this.#h.delete(e)}}navigate(e,t){let n=resolveTarget(typeof e==`string`?{path:e}:e,this.#a);return this.#L(n,t)}url(e,t,n){let r=getRouteByName(e,this.#a);return o.buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=o.buildUrl(this.#e,r.path,t,n);return this.#r.href?.(i)??i}isActive(e,t={}){let n=getRouteByName(e,this.#a),r=this.#d.location.pathname;return t.exact??!1?o.matchRouteFor(r,[n]).record!=null:o.matchesPrefix(r,n)}match(e){let t=o.stripBase(o.normalizePath(e),this.#e),{params:r,record:i}=o.matchRouteFor(t,this.#i);if(!i||i.redirect)return null;let a=n.buildMatchBranch(i.branchDefs,r,t,i.branchDefs.map(()=>void 0));return a.length?a:null}async load(e,t){let r=await this.#D(e);if(r.type!==`matched`)return null;let{location:i,params:a,record:o,resolvedQuery:s}=r,c=o.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0),d,f=`idle`;if(l){let e=t?.signal??new AbortController().signal,r=n.buildMatchBranch(c,a,i.pathname,u),o=n.createRouteContext(i,s,a,r,()=>Promise.resolve());try{u=await this.#E(c,o,e)}catch(e){d=e,f=`error`}}return n.createRouteState({error:d,location:i,matches:n.buildMatchBranch(c,a,i.pathname,u),status:f})}async preload(e){this.#b();let t=this.#N(resolveTarget(e,this.#a,this.#e)),n=this.#_.get(t);if(n)return n;let r=this.load(t,{signal:this.#p.signal}).then(e=>{if(this.#f)throw this.#p.signal.reason;if(e?.status===`error`)throw e.error;if(e){let t=this.#F(e.location);this.#g.size>=20&&this.#g.delete(this.#g.keys().next().value),this.#g.set(t,e.matches.map(e=>e.data))}return e}).catch(e=>{throw this.#o&&this.#C(e,{source:`preload`}),e}).finally(()=>{this.#_.delete(t)});return this.#_.set(t,r),r}waitFor(e){return this.#b(),new Promise((t,n)=>{let matchesName=t=>t.status===`idle`&&t.matches.some(t=>t.name===e);if(this.#d.status===`error`){n(this.#d.error);return}if(matchesName(this.#d)){t(this.#d);return}let r=this.subscribe(e=>{matchesName(e)?(r(),t(e)):e.status===`error`&&(r(),n(e.error))});this.#p.signal.addEventListener(`abort`,()=>{r(),n(this.#p.signal.reason)},{once:!0})})}beforeLeave(e,t){this.#b();let n={handler:e,routes:t?.routes};return this.#l.add(n),()=>{this.#l.delete(n)}}get disposalSignal(){return this.#p.signal}get disposed(){return this.#f}dispose(){this.#f||(this.#f=!0,this.#l.clear(),this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#u.invalidate(new r.WayfinderDisposedError),this.#y(),this.#p.abort(new r.WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new r.WayfinderDisposedError}#x(){return this.#r.onPopstate(()=>{let{hash:e,pathname:t,search:n}=this.#r.location,r=`${t}${n}${e}`,i=this.#m;r!==i&&this.#w(this.#S(r,i),{source:`history-listener`})})}async#S(e,t){let n=this.#u.begin(),r=this.#d.matches.map(e=>e.name),a=this.#I(e),s=await i.runLeaveBlockers(this.#l,r,a);if(!n.isCurrent())return;if(!s){this.#r.replace(t,this.#d.location.historyState);return}let c=await this.#A(n,o.readLocation(this.#e,this.#r),(e,t)=>{if(!n.isCurrent())return;let r=this.#F(e);t&&this.#r.replace(r,e.historyState),this.#m=r},void 0,0,!1);n.isCurrent()&&!c&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){n.reportError(e,t,this.#o)}#w(e,t){e.catch(e=>{isRouterErrorCarrier(e)?this.#C(e.error,e.context):this.#C(e,t)})}#T(){for(let e of[...this.#h])try{e(this.#d)}catch(e){queueMicrotask(()=>{throw e})}}async#E(e,t,n){return Promise.all(e.map(async e=>{if(!e.dataFn)return;let r=e.dataFn;try{return await r({...t,signal:n})}catch(r){if(e.onError)return e.onError(r,{...t,signal:n});throw r}}))}async#D(e){let t=e;for(let e=0;e<5;e+=1){let e=new URL(t,`http://localhost`),n={hash:e.hash.replace(/^#/,``),historyState:null,pathname:o.stripBase(e.pathname,this.#e),query:o.parseQuery(e.search)},r=await this.#O(n);if(r.type!==`redirect`)return r;t=this.#N(r.redirectTo)}throw new r.WayfinderRedirectLoopError}async#O(e){let{params:t,record:r}=o.matchRouteFor(e.pathname,this.#i);if(!r)return{location:e,params:t,type:`unmatched`};if(r.redirect)return{location:e,params:t,redirectTo:resolveTarget(r.redirect,this.#a,this.#e),type:`redirect`};let i=e.query,a=r.coerceSearch??this.#n;if(a)try{i=a(e.query)}catch(t){this.#C(t,{source:`coerce-search`}),i=e.query}return{branch:n.buildMatchBranch(r.branchDefs,t,e.pathname,r.branchDefs.map(()=>void 0)),location:e,params:t,record:r,resolvedQuery:i,type:`matched`}}async#k(e,t,r,i,a,o,s){if(!o())return;let c=e.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0);if(l){let e=this.#F(r),l=this.#_.get(e);if(l&&(await l.catch(()=>void 0),!o()))return;let d=this.#g.get(e);if(d)this.#g.delete(e),u=d;else{this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`loading`}),this.#T();try{u=await this.#E(c,t,a)}catch(e){if(!o())return;throw this.#d=n.createRouteState({error:e,location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`error`}),s?.(e),e}}}o()&&(this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`idle`}))}async#A(e,t,i,a,o=0,s=!1){let c=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,l=await this.#O(t);if(!isCurrent())return!1;if(l.type===`redirect`){if(o>=5)throw new r.WayfinderRedirectLoopError;return this.#A(e,this.#P(l.redirectTo,t.historyState),i,a,o+1,!0)}if(l.type===`unmatched`){if(this.#v){let r=[this.#v.leaf],o=n.buildMatchBranch(r,{},t.pathname,[void 0]),l=!1,u,d=!1,f=!1,p=t.query,m=!1;if(this.#n)try{p=this.#n(t.query)}catch(e){this.#C(e,{source:`coerce-search`})}let run=async()=>{if(!isCurrent())return;let r=n.createRouteContext(t,p,{},o,(e,t)=>this.navigate(e,t));f=await n.executeMiddlewarePipeline(r,[...this.#t,...this.#v.ownMiddleware],async()=>{isCurrent()&&(l=!0,i(t,s),isCurrent()&&(await this.#k(this.#v,r,t,{},e.signal,isCurrent,e=>{u=e,d=!0}),isCurrent()&&(m=!0,this.#T(),this.#M(this.#d,c))))},e=>isRouterErrorCarrier(e)||d&&e===u?e:carryError(e,{routeName:`__notFound__`,source:`middleware`}))};try{await this.#j(run,a)}catch(e){throw d&&e===u?carryError(e,{routeName:`__notFound__`,source:`data-loader`}):e}finally{isCurrent()&&l&&!m&&(this.#T(),this.#M(this.#d,c))}return f&&l}return!isCurrent()||(i(l.location,s),!isCurrent())?!1:(this.#d=n.createRouteState({location:l.location,matches:[],status:`idle`}),this.#T(),this.#M(this.#d,c),!0)}let{branch:u,location:d,params:f,record:p,resolvedQuery:m}=l,h=!1,g,_=!1,v=!1,y=!1,run=async()=>{if(!isCurrent())return;let t=n.createRouteContext(d,m,f,u,(e,t)=>this.navigate(e,t));v=await n.executeMiddlewarePipeline(t,[...this.#t,...p.ownMiddleware],async()=>{isCurrent()&&(h=!0,i(d,s),isCurrent()&&(await this.#k(p,t,d,f,e.signal,isCurrent,e=>{g=e,_=!0}),isCurrent()&&(y=!0,this.#T(),this.#M(this.#d,c))))},e=>isRouterErrorCarrier(e)||_&&e===g?e:carryError(e,{routeName:p.leaf.name,source:`middleware`}))};try{await this.#j(run,a)}catch(e){throw _&&e===g?carryError(e,{routeName:p.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&h&&!y&&(this.#T(),this.#M(this.#d,c))}return v&&h}async#j(e,t){if((t??this.#c)&&typeof document<`u`){let t=document.startViewTransition;if(t){await t.call(document,e).finished;return}}await e()}#M(e,t){if(!this.#s||typeof window>`u`)return;let n=this.#s(e,t);n!==`preserve`&&(n===`top`?window.scrollTo(0,0):window.scrollTo(n.x,n.y))}#N(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e);return`${o.joinPaths(this.#e,n)}${t.search}${t.hash}`}#P(e,t){let n=new URL(this.#N(e),`http://localhost`);return{hash:n.hash.replace(/^#/,``),historyState:t,pathname:o.stripBase(n.pathname,this.#e),query:o.parseQuery(n.search)}}#F(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e.query))Array.isArray(r)?r.forEach(e=>{t.append(n,e)}):t.set(n,r);let n=t.toString(),r=e.hash?`#${e.hash}`:``;return`${o.joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#I(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e),{params:r,record:i}=o.matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query:o.parseQuery(t.search)}}async#L(e,t={}){this.#b();let n=this.#N(e);if(!t.force&&n===this.#m)return;let r=this.#u.begin(),a=this.#d.matches.map(e=>e.name),o=await i.runLeaveBlockers(this.#l,a,this.#I(n));if(r.isCurrent()&&o)try{await this.#A(r,this.#P(n,t.state),(e,t)=>{if(!r.isCurrent())return;let n=this.#F(e);t?this.#r.replace(n,e.historyState):this.#r.push(n,e.historyState),this.#m=n},t.viewTransition,0,t.replace??!1)}catch(e){throw isRouterErrorCarrier(e)?e.error:e}}};function createRouter(e){return new Router(e)}exports.createRouter=createRouter;
|
|
1
|
+
const e=require("./_navigation.cjs"),t=require("./compile.cjs"),n=require("./context.cjs"),r=require("./errors.cjs"),i=require("./guards.cjs"),a=require("./history.cjs"),o=require("./path.cjs");function getRouteByName(e,t){let n=t.get(e);if(n)return n;let i=[...t.keys()].join(`, `);throw new r.WayfinderRouteError(i?`Unknown route name: ${e}. Available routes: ${i}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=getRouteByName(e.name,t),i=o.buildUrl(n,r.path,e.params,e.query);return e.hash?`${i}#${e.hash}`:i}var s=Symbol(`wayfinder.routerError`),c=5;function carryError(e,t){return{[s]:!0,context:t,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&s in e}function unwrapCarrier(e){throw isRouterErrorCarrier(e)?e.error:e}var Router=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=new Set;#u=e.createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let r=t.compileRoutes(e);if(this.#e=o.normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??a.createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=r.records,this.#a=r.routesByName,this.#d=n.createRouteState({location:{hash:``,historyState:null,pathname:`/`,query:{}},matches:[],status:`idle`}),e.notFound){let t=e.notFound,n={dataFn:t.data,name:`__notFound__`};this.#v={branchDefs:[n],leaf:n,matcher:{paramNames:[],pattern:/(?:)/,prefixPattern:/(?:)/},ownMiddleware:t.middleware??[],path:`/*`}}else this.#v=null;this.#y=this.#x();let{hash:i,pathname:s,search:c,state:l}=this.#r.location,u=`${s}${c}${i}`;this.#m=u;let d=this.#u.begin(),f=this.#j(d,u,l,(e,t)=>{if(!d.isCurrent())return;let n=this.#I(e);t&&this.#r.replace(n,e.historyState),this.#m=n},void 0,!1).then(()=>void 0);this.ready=f.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(f,{source:`initial-navigation`}),this.beforeLeave=this.beforeLeave.bind(this),this.createViewRegistry=this.createViewRegistry.bind(this),this.dispose=this.dispose.bind(this),this.getSnapshot=this.getSnapshot.bind(this),this.isActive=this.isActive.bind(this),this.load=this.load.bind(this),this.match=this.match.bind(this),this.navigate=this.navigate.bind(this),this.preload=this.preload.bind(this),this.subscribe=this.subscribe.bind(this),this.url=this.url.bind(this),this.waitFor=this.waitFor.bind(this)}getSnapshot(){return this.#d}createViewRegistry(e,t){return{resolve:n=>{let r=n.matches.at(-1)?.name;return r===`__notFound__`?t?.notFound:r?e[r]:void 0}}}subscribe(e){return this.#b(),this.#h.add(e),()=>{this.#h.delete(e)}}navigate(e,t){let n=resolveTarget(typeof e==`string`?{path:e}:e,this.#a,this.#e);return this.#R(n,t)}url(e,t,n){let r=getRouteByName(e,this.#a);return o.buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=o.buildUrl(this.#e,r.path,t,n);return this.#r.href?.(i)??i}isActive(e,t={}){let n=getRouteByName(e,this.#a),r=this.#d.location.pathname;return t.exact??!1?o.matchRouteFor(r,[n]).record!=null:o.matchesPrefix(r,n)}match(e){let t=o.stripBase(o.normalizePath(e),this.#e),{params:r,record:i}=o.matchRouteFor(t,this.#i);if(!i||i.redirect)return null;let a=n.buildMatchBranch(i.branchDefs,r,t,i.branchDefs.map(()=>void 0));return a.length?a:null}async load(e,t){let{decision:r}=await this.#D(e,null);if(r.type!==`matched`)return null;let{location:i,params:a,record:o,resolvedQuery:s}=r,c=o.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0),d,f=`idle`;if(l){let e=t?.signal??new AbortController().signal,r=n.buildMatchBranch(c,a,i.pathname,u),o=n.createRouteContext(i,s,a,r,()=>Promise.resolve());try{u=await this.#E(c,o,e)}catch(e){d=e,f=`error`}}return n.createRouteState({error:d,location:i,matches:n.buildMatchBranch(c,a,i.pathname,u),status:f})}async preload(e){this.#b();let t=this.#P(resolveTarget(e,this.#a,this.#e)),n=this.#_.get(t);if(n)return n;let r=this.load(t,{signal:this.#p.signal}).then(e=>{if(this.#f)throw this.#p.signal.reason;if(e?.status===`error`)throw e.error;if(e){let t=this.#I(e.location);this.#g.size>=20&&this.#g.delete(this.#g.keys().next().value),this.#g.set(t,e.matches.map(e=>e.data))}return e}).catch(e=>{throw this.#o&&this.#C(e,{source:`preload`}),e}).finally(()=>{this.#_.delete(t)});return this.#_.set(t,r),r}waitFor(e){return this.#b(),new Promise((t,n)=>{let matchesName=t=>t.status===`idle`&&t.matches.some(t=>t.name===e);if(this.#d.status===`error`){n(this.#d.error);return}if(matchesName(this.#d)){t(this.#d);return}let r=this.subscribe(e=>{matchesName(e)?(r(),t(e)):e.status===`error`&&(r(),n(e.error))});this.#p.signal.addEventListener(`abort`,()=>{r(),n(this.#p.signal.reason)},{once:!0})})}beforeLeave(e,t){this.#b();let n={handler:e,routes:t?.routes};return this.#l.add(n),()=>{this.#l.delete(n)}}get disposalSignal(){return this.#p.signal}get disposed(){return this.#f}dispose(){this.#f||(this.#f=!0,this.#l.clear(),this.#h.clear(),this.#g.clear(),this.#_.clear(),this.#u.invalidate(new r.WayfinderDisposedError),this.#y(),this.#p.abort(new r.WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new r.WayfinderDisposedError}#x(){return this.#r.onPopstate(()=>{let{hash:e,pathname:t,search:n}=this.#r.location,r=`${t}${n}${e}`,i=this.#m;r!==i&&this.#w(this.#S(r,i),{source:`history-listener`})})}async#S(e,t){let n=this.#u.begin(),r=this.#d.matches.map(e=>e.name),a=this.#L(e),o=await i.runLeaveBlockers(this.#l,r,a);if(!n.isCurrent())return;if(!o){this.#r.replace(t,this.#d.location.historyState);return}let s=await this.#j(n,e,this.#r.location.state,(e,t)=>{if(!n.isCurrent())return;let r=this.#I(e);t&&this.#r.replace(r,e.historyState),this.#m=r},void 0,!1);n.isCurrent()&&!s&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){n.reportError(e,t,this.#o)}#w(e,t){e.catch(e=>{isRouterErrorCarrier(e)?this.#C(e.error,e.context):this.#C(e,t)})}#T(){for(let e of[...this.#h])try{e(this.#d)}catch(e){queueMicrotask(()=>{throw e})}}async#E(e,t,n){return Promise.all(e.map(async e=>{if(!e.dataFn)return;let r=e.dataFn;try{return await r({...t,signal:n})}catch(r){if(e.onError)return e.onError(r,{...t,signal:n});throw r}}))}async#D(e,t){let n=e,i=!1;for(let e=0;;e+=1){let a=await this.#k(this.#F(n,t));if(a.type!==`redirect`)return{decision:a,hopped:i};if(e>=c)throw new r.WayfinderRedirectLoopError;n=a.redirectTo,i=!0}}#O(e,t){if(!t)return e.query;try{return t(e.query)}catch(t){return this.#C(t,{source:`coerce-search`}),e.query}}async#k(e){let{params:t,record:r}=o.matchRouteFor(e.pathname,this.#i);if(!r)return this.#v?{branch:n.buildMatchBranch(this.#v.branchDefs,{},e.pathname,[void 0]),location:e,params:{},record:this.#v,resolvedQuery:this.#O(e,this.#n),type:`matched`}:{location:e,params:t,type:`unmatched`};if(r.redirect)return{location:e,params:t,redirectTo:resolveTarget(r.redirect,this.#a,this.#e),type:`redirect`};let i=this.#O(e,r.coerceSearch??this.#n);return{branch:n.buildMatchBranch(r.branchDefs,t,e.pathname,r.branchDefs.map(()=>void 0)),location:e,params:t,record:r,resolvedQuery:i,type:`matched`}}async#A(e,t,r,i,a,o,s){if(!o())return;let c=e.branchDefs,l=c.some(e=>e.dataFn!=null),u=c.map(()=>void 0);if(l){let e=this.#I(r),l=this.#_.get(e);if(l&&(await l.catch(()=>void 0),!o()))return;let d=this.#g.get(e);if(d)this.#g.delete(e),u=d;else{this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`loading`}),this.#T();try{u=await this.#E(c,t,a)}catch(e){if(!o())return;throw this.#d=n.createRouteState({error:e,location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`error`}),s?.(e),e}}}o()&&(this.#d=n.createRouteState({location:r,matches:n.buildMatchBranch(c,i,r.pathname,u),status:`idle`}))}async#j(e,t,r,i,a,o){let s=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,{decision:c,hopped:l}=await this.#D(t,r);if(!isCurrent())return!1;if(c.type===`unmatched`)return i(c.location,o||l),isCurrent()?(this.#d=n.createRouteState({location:c.location,matches:[],status:`idle`}),this.#T(),this.#N(this.#d,s),!0):!1;let{branch:u,location:d,params:f,record:p,resolvedQuery:m}=c,h=o||l,g=!1,_,v=!1,y=!1,b=!1,run=async()=>{if(!isCurrent())return;let t=n.createRouteContext(d,m,f,u,(e,t)=>this.navigate(e,t));y=await n.executeMiddlewarePipeline(t,[...this.#t,...p.ownMiddleware],async()=>{isCurrent()&&(g=!0,i(d,h),isCurrent()&&(await this.#A(p,t,d,f,e.signal,isCurrent,e=>{_=e,v=!0}),isCurrent()&&(b=!0,this.#T(),this.#N(this.#d,s))))},e=>isRouterErrorCarrier(e)||v&&e===_?e:carryError(e,{routeName:p.leaf.name,source:`middleware`}))};try{await this.#M(run,a)}catch(e){throw v&&e===_?carryError(e,{routeName:p.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&g&&!b&&(this.#T(),this.#N(this.#d,s))}return y&&g}async#M(e,t){if((t??this.#c)&&typeof document<`u`){let t=document.startViewTransition;if(t){await t.call(document,e).finished;return}}await e()}#N(e,t){if(!this.#s||typeof window>`u`)return;let n=this.#s(e,t);n!==`preserve`&&(n===`top`?window.scrollTo(0,0):window.scrollTo(n.x,n.y))}#P(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e);return`${o.joinPaths(this.#e,n)}${t.search}${t.hash}`}#F(e,t){let n=new URL(this.#P(e),`http://localhost`);return{hash:n.hash.replace(/^#/,``),historyState:t,pathname:o.stripBase(n.pathname,this.#e),query:o.parseQuery(n.search)}}#I(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e.query))Array.isArray(r)?r.forEach(e=>{t.append(n,e)}):t.set(n,r);let n=t.toString(),r=e.hash?`#${e.hash}`:``;return`${o.joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#L(e){let t=new URL(e,`http://localhost`),n=o.stripBase(t.pathname,this.#e),{params:r,record:i}=o.matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query:o.parseQuery(t.search)}}async#R(e,t={}){this.#b();let n=this.#P(e);if(!t.force&&n===this.#m)return;let r=this.#u.begin(),a=this.#d.matches.map(e=>e.name),o=await i.runLeaveBlockers(this.#l,a,this.#L(n));if(r.isCurrent()&&o)try{await this.#j(r,n,t.state,(e,t)=>{if(!r.isCurrent())return;let n=this.#I(e);t?this.#r.replace(n,e.historyState):this.#r.push(n,e.historyState),this.#m=n},t.viewTransition,t.replace??!1)}catch(e){throw isRouterErrorCarrier(e)?e.error:e}}};function createRouter(e){return new Router(e)}exports.createRouter=createRouter;
|
|
2
2
|
//# sourceMappingURL=router.cjs.map
|
package/dist/router.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.cjs","names":["WayfinderRouteError","buildUrl","createNavigationCoordinator","compileRoutes","normalizePath","createBrowserHistory","createRouteState","readLocation","matchRouteFor","matchesPrefix","stripBase","buildMatchBranch","createRouteContext","WayfinderDisposedError","runLeaveBlockers","parseQuery","WayfinderRedirectLoopError","executeMiddlewarePipeline","joinPaths","require__navigation","require_compile","require_context","require_errors","require_guards","require_history","require_path","route","routesByName","name","available","target","path","base","ROUTER_ERROR","value","compiled","options","#base","#globalMiddleware","#globalCoerceSearch","#history","#onError","#scroll","#useViewTransition","#records","#routesByName","#currentState","nf","leafDef","#notFoundRecord","#unlistenHistory","#registerHistoryListener","#lastHref","pathname","search","hash","attempt","#navigation","navigationPromise","#handleRoute","href","#hrefForLocation","location","replace","#runInBackground","state","views","#assertNotDisposed","#listeners","listener","destination","#navigateToPath","params","query","url","normalizedPathname","record","branch","prepared","#resolveUrl","defs","hasData","d","dataResults","error","status","effectiveSignal","context","resolvedQuery","#loadData","#resolveDestination","existing","#preloads","work","#disposeController","#disposed","key","#preloaded","match","#reportError","m","reject","resolve","unsub","entry","blocker","#beforeLeaveBlockers","newHref","previousHref","#handleHistoryNavigation","activeMatchNames","#navigationDestination","allowed","terminalRan","promise","def","dataFn","err","i","parsed","#prepareRoute","coerce","#runTerminal","isCurrent","preloadKey","preloading","cached","#notifyListeners","signal","onDataError","previousState","currentLocation","depth","#locationFromPath","commit","useTransition","nfDefs","nfBranch","committed","dataError","hasDataError","nfResolvedQuery","notified","#applyScroll","#runWithTransition","startViewTransition","run","decision","to","from","normalizedPath","item"],"sources":["../src/router.ts"],"sourcesContent":["import { createNavigationCoordinator, type NavigationAttempt } from './_navigation';\nimport { compileRoutes } from './compile';\nimport {\n buildMatchBranch,\n createRouteContext,\n createRouteState,\n executeMiddlewarePipeline,\n reportError,\n} from './context';\nimport { WayfinderDisposedError, WayfinderRedirectLoopError, WayfinderRouteError } from './errors';\nimport { type RegisteredBlocker, runLeaveBlockers } from './guards';\nimport { createBrowserHistory } from './history';\nimport {\n buildUrl,\n joinPaths,\n matchesPrefix,\n matchRouteFor,\n normalizePath,\n parseQuery,\n readLocation,\n stripBase,\n} from './path';\nimport type {\n BeforeLeaveBlocker,\n BeforeLeaveOptions,\n CoerceSearchFn,\n DataContext,\n DataFn,\n HistoryDriver,\n IsActiveOptions,\n Middleware,\n NamedNavigationTarget,\n NavigateOptions,\n NavigationDestination,\n PathParams,\n RawNavigationTarget,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteName,\n RouteParams,\n RoutePathByName,\n RouteRecord,\n RouterErrorContext,\n RouterOptions,\n RouteState,\n RouteTable,\n RouteViewMap,\n RouteViewName,\n RouteViewRegistry,\n Unsubscribe,\n} from './types';\n\n// ─── Module-level helpers ────────────────────────────────────────────────────\n\nfunction getRouteByName(name: string, routesByName: ReadonlyMap<string, RouteRecord>): RouteRecord {\n const route = routesByName.get(name);\n\n if (route) return route;\n\n const available = [...routesByName.keys()].join(', ');\n\n throw new WayfinderRouteError(\n available ? `Unknown route name: ${name}. Available routes: ${available}` : `Unknown route name: ${name}`,\n );\n}\n\nfunction resolveTarget(\n target: { path: string } | { hash?: string; name: string; params?: RouteParams; query?: ResolvedQueryParams },\n routesByName: ReadonlyMap<string, RouteRecord>,\n base = '/',\n): string {\n if ('path' in target) return target.path;\n\n const route = getRouteByName(target.name, routesByName);\n const path = buildUrl(base, route.path, target.params, target.query);\n\n return target.hash ? `${path}#${target.hash}` : path;\n}\n\n// ─── Internal error carrier ──────────────────────────────────────────────────\n//\n// Carries error context alongside the original error without mutating the thrown\n// object. The carrier is unwrapped before reaching external callers so error\n// identity and `cause` chains are preserved.\n\nconst ROUTER_ERROR = Symbol('wayfinder.routerError');\n\ntype RouterErrorCarrier = {\n [ROUTER_ERROR]: true;\n readonly error: unknown;\n readonly context: RouterErrorContext;\n};\n\nfunction carryError(error: unknown, context: RouterErrorContext): RouterErrorCarrier {\n return { [ROUTER_ERROR]: true, context, error };\n}\n\nfunction isRouterErrorCarrier(value: unknown): value is RouterErrorCarrier {\n return value !== null && typeof value === 'object' && ROUTER_ERROR in (value as Record<symbol, unknown>);\n}\n\nfunction unwrapCarrier(value: unknown): never {\n if (isRouterErrorCarrier(value)) throw value.error;\n\n throw value;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype NavigationDecision =\n | {\n branch: RouteMatchBranch;\n location: RouteLocation;\n params: RouteParams;\n record: RouteRecord;\n resolvedQuery: ResolvedQueryParams;\n type: 'matched';\n }\n | { location: RouteLocation; params: RouteParams; type: 'unmatched' }\n | { location: RouteLocation; params: RouteParams; redirectTo: string; type: 'redirect' };\n\n// ─── Router class ─────────────────────────────────────────────────────────────\n\nclass Router<TRoutes extends RouteTable = RouteTable> {\n readonly #base: string;\n readonly #globalMiddleware: readonly Middleware[];\n readonly #globalCoerceSearch?: CoerceSearchFn;\n readonly #history: HistoryDriver;\n readonly #records: readonly RouteRecord[];\n readonly #routesByName: ReadonlyMap<string, RouteRecord>;\n readonly #onError?: RouterOptions<TRoutes>['onError'];\n readonly #scroll?: RouterOptions<TRoutes>['scroll'];\n readonly #useViewTransition: boolean;\n\n // Mutable navigation state\n readonly #beforeLeaveBlockers = new Set<RegisteredBlocker>();\n readonly #navigation = createNavigationCoordinator();\n #currentState: RouteState;\n #disposed = false;\n readonly #disposeController = new AbortController();\n #lastHref = '/';\n readonly #listeners = new Set<(state: RouteState) => void>();\n readonly #preloaded = new Map<string, unknown[]>();\n readonly #preloads = new Map<string, Promise<RouteState | null>>();\n // Compiled notFound fallback record\n readonly #notFoundRecord: RouteRecord | null;\n\n readonly #unlistenHistory: () => void;\n\n /** Resolves when the constructor-triggered navigation has settled; rejects if it fails. */\n readonly ready: Promise<void>;\n\n constructor(options: RouterOptions<TRoutes>) {\n const compiled = compileRoutes(options);\n\n this.#base = normalizePath(options.base ?? '/');\n this.#globalMiddleware = (options.middleware ?? []) as unknown as Middleware[];\n this.#globalCoerceSearch = options.coerceSearch;\n this.#history = options.history ?? createBrowserHistory();\n this.#onError = options.onError;\n this.#scroll = options.scroll;\n this.#useViewTransition = options.viewTransition ?? false;\n this.#records = compiled.records as unknown as readonly RouteRecord[];\n this.#routesByName = compiled.routesByName as unknown as ReadonlyMap<string, RouteRecord>;\n this.#currentState = createRouteState({\n location: { hash: '', historyState: null, pathname: '/', query: {} },\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n\n // Build a synthetic RouteRecord for the notFound fallback.\n if (options.notFound) {\n const nf = options.notFound;\n const leafDef: RouteBranchDef = {\n dataFn: nf.data,\n name: '__notFound__',\n };\n\n this.#notFoundRecord = {\n branchDefs: [leafDef],\n leaf: leafDef,\n matcher: { paramNames: [], pattern: /(?:)/, prefixPattern: /(?:)/ },\n ownMiddleware: (nf.middleware ?? []) as unknown as Middleware[],\n path: '/*',\n };\n } else {\n this.#notFoundRecord = null;\n }\n\n this.#unlistenHistory = this.#registerHistoryListener();\n\n const { hash, pathname, search } = this.#history.location;\n\n this.#lastHref = `${pathname}${search}${hash}`;\n\n const attempt = this.#navigation.begin();\n\n const navigationPromise = this.#handleRoute(\n attempt,\n readLocation(this.#base, this.#history),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n 0,\n false,\n ).then(() => undefined);\n\n // ready rejects with the original error (carrier unwrapped) for external consumers.\n this.ready = navigationPromise.catch(unwrapCarrier);\n // Attach a silent handler so an unawaited ready promise doesn't trigger\n // an unhandled-rejection warning. External consumers can still await ready\n // and receive the rejection: each .catch() subscriber fires independently.\n this.ready.catch(() => {});\n // #runInBackground receives the raw promise so it can extract carrier context for onError.\n this.#runInBackground(navigationPromise, { source: 'initial-navigation' });\n\n // Router actions are intentionally bound once so they remain safe when destructured.\n this.beforeLeave = this.beforeLeave.bind(this);\n this.createViewRegistry = this.createViewRegistry.bind(this);\n this.dispose = this.dispose.bind(this);\n this.getSnapshot = this.getSnapshot.bind(this);\n this.isActive = this.isActive.bind(this);\n this.load = this.load.bind(this);\n this.match = this.match.bind(this);\n this.navigate = this.navigate.bind(this);\n this.preload = this.preload.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.url = this.url.bind(this);\n this.waitFor = this.waitFor.bind(this);\n }\n\n // ─── Public state ─────────────────────────────────────────────────────────\n\n /**\n * Returns the current immutable router state snapshot.\n *\n * Compatible with React's `useSyncExternalStore`:\n * ```ts\n * const state = useSyncExternalStore(\n * (cb) => router.subscribe(cb),\n * () => router.getSnapshot()\n * );\n * ```\n */\n getSnapshot(): RouteState {\n return this.#currentState;\n }\n\n createViewRegistry<const TViews extends RouteViewMap<TRoutes>, TNotFound = never>(\n views: TViews & Record<Exclude<keyof TViews, RouteViewName<TRoutes>>, never>,\n options?: { notFound?: TNotFound },\n ): RouteViewRegistry<TViews[keyof TViews] | TNotFound> {\n return {\n resolve: (state) => {\n const name = state.matches.at(-1)?.name;\n\n if (name === '__notFound__') return options?.notFound;\n\n return name ? (views[name as keyof TViews] as TViews[keyof TViews]) : undefined;\n },\n };\n }\n\n // ─── Subscription ─────────────────────────────────────────────────────────\n\n /**\n * Subscribe to state changes. The listener is called on each subsequent state change;\n * use `getSnapshot()` to read the current value immediately.\n */\n subscribe(listener: (state: RouteState) => void): Unsubscribe {\n this.#assertNotDisposed();\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n // ─── Navigation ───────────────────────────────────────────────────────────\n\n /**\n * Navigate using a named route target or a raw path target.\n *\n * If a data loader throws after terminal execution begins, history has already committed\n * the destination and the returned Promise rejects with the loader error.\n */\n navigate(\n target: NamedNavigationTarget<TRoutes> | RawNavigationTarget | string,\n options?: NavigateOptions,\n ): Promise<void> {\n const normalized = typeof target === 'string' ? { path: target } : target;\n const destination = resolveTarget(normalized, this.#routesByName);\n\n return this.#navigateToPath(destination, options);\n }\n\n // ─── URL helpers ──────────────────────────────────────────────────────────\n\n /** Build a URL for a named route, including optional params and query string. */\n url<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n\n return buildUrl(this.#base, route.path, params, query);\n }\n\n /**\n * Build an anchor-ready href for a named route: the address-bar form for the configured\n * history driver. `url()` returns the router-internal path; under `createHashHistory`\n * the same route lives behind `#`, and `href()` returns that form for `<a>` elements.\n */\n href<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n const url = buildUrl(this.#base, route.path, params, query);\n\n return this.#history.href?.(url) ?? url;\n }\n\n /** Returns true when the current location matches the named route by prefix (default) or exactly. */\n isActive<Name extends RouteName<TRoutes>>(name: Name, options: IsActiveOptions = {}): boolean {\n const route = getRouteByName(name, this.#routesByName);\n const pathname = this.#currentState.location.pathname;\n const exact = options.exact ?? false;\n\n return exact ? matchRouteFor(pathname, [route]).record != null : matchesPrefix(pathname, route);\n }\n\n /** Match a pathname to a route branch without running middleware or data loaders. Returns null for redirects or no match. */\n match(pathname: string): RouteMatchBranch | null {\n const normalizedPathname = stripBase(normalizePath(pathname), this.#base);\n const { params, record } = matchRouteFor(normalizedPathname, this.#records);\n\n if (!record || record.redirect) return null;\n\n const branch = buildMatchBranch(\n record.branchDefs,\n params,\n normalizedPathname,\n record.branchDefs.map(() => undefined),\n );\n\n return branch.length ? branch : null;\n }\n\n /**\n * Load a URL into a route state including data loader results, without modifying\n * router state or history. Follows declarative redirects but does not cache results.\n * Middleware is not executed: use `navigate()` when middleware side effects are needed.\n */\n async load(url: string, options?: { signal?: AbortSignal }): Promise<RouteState | null> {\n const prepared = await this.#resolveUrl(url);\n\n if (prepared.type !== 'matched') return null;\n\n const { location, params, record, resolvedQuery } = prepared;\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n let error: unknown;\n let status: 'error' | 'idle' = 'idle';\n\n if (hasData) {\n const effectiveSignal = options?.signal ?? new AbortController().signal;\n const branch = buildMatchBranch(defs, params, location.pathname, dataResults);\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, () => Promise.resolve());\n\n try {\n dataResults = await this.#loadData(defs, context, effectiveSignal);\n } catch (e) {\n error = e;\n status = 'error';\n }\n }\n\n return createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status,\n });\n }\n\n async preload(target: NamedNavigationTarget<TRoutes>): Promise<RouteState | null> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(resolveTarget(target, this.#routesByName, this.#base));\n const existing = this.#preloads.get(destination);\n\n if (existing) return existing;\n\n const work = this.load(destination, { signal: this.#disposeController.signal })\n .then((state) => {\n if (this.#disposed) throw this.#disposeController.signal.reason;\n\n if (state?.status === 'error') throw state.error;\n\n if (state) {\n const key = this.#hrefForLocation(state.location);\n\n if (this.#preloaded.size >= 20) this.#preloaded.delete(this.#preloaded.keys().next().value!);\n\n this.#preloaded.set(\n key,\n state.matches.map((match) => match.data),\n );\n }\n\n return state;\n })\n .catch((error) => {\n if (this.#onError) this.#reportError(error, { source: 'preload' });\n\n throw error;\n })\n .finally(() => {\n this.#preloads.delete(destination);\n });\n\n this.#preloads.set(destination, work);\n\n return work;\n }\n\n /**\n * Returns a Promise that resolves the next time the router reaches `status: 'idle'`\n * and the active matches include a route named `name`.\n *\n * - Resolves immediately if the router is already `idle` at `name`.\n * - Rejects immediately if the router is already in `status: 'error'`.\n * - If the router is currently `idle` at a **different** route and no navigation is in\n * flight, this promise will not resolve until a future navigation lands on `name`.\n * Typical use-case is awaiting a navigation you just triggered:\n * `router.navigate(target); await router.waitFor('routeName')`.\n * @throws {WayfinderDisposedError} if the router is disposed while the promise is pending,\n * or if called after the router has already been disposed.\n */\n waitFor(name: RouteName<TRoutes>): Promise<RouteState> {\n this.#assertNotDisposed();\n\n return new Promise((resolve, reject) => {\n const matchesName = (state: RouteState): boolean =>\n state.status === 'idle' && state.matches.some((m) => m.name === name);\n\n if (this.#currentState.status === 'error') {\n reject(this.#currentState.error);\n\n return;\n }\n\n if (matchesName(this.#currentState)) {\n resolve(this.#currentState);\n\n return;\n }\n\n const unsub = this.subscribe((state) => {\n if (matchesName(state)) {\n unsub();\n resolve(state);\n } else if (state.status === 'error') {\n unsub();\n reject(state.error);\n }\n });\n\n this.#disposeController.signal.addEventListener(\n 'abort',\n () => {\n unsub();\n reject(this.#disposeController.signal.reason);\n },\n { once: true },\n );\n });\n }\n\n // ─── Navigation guards ────────────────────────────────────────────────────\n\n /**\n * Register a leave guard. Called before user-triggered navigation attempts.\n * Return `false` to cancel; `true` to allow.\n * Returns a function that removes the guard.\n *\n * Use `options.routes` to scope the guard to specific routes (fires only when navigating\n * away from a route whose name appears in the array, checked against any node in the active branch).\n */\n beforeLeave(blocker: BeforeLeaveBlocker, options?: BeforeLeaveOptions<TRoutes>): Unsubscribe {\n this.#assertNotDisposed();\n\n const entry: RegisteredBlocker = {\n handler: blocker,\n routes: options?.routes as string[] | undefined,\n };\n\n this.#beforeLeaveBlockers.add(entry);\n\n return () => {\n this.#beforeLeaveBlockers.delete(entry);\n };\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n get disposalSignal(): AbortSignal {\n return this.#disposeController.signal;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /** Dispose event listeners and prevent further router interaction. Idempotent. */\n dispose(): void {\n if (this.#disposed) return;\n\n this.#disposed = true;\n this.#beforeLeaveBlockers.clear();\n this.#listeners.clear();\n this.#preloaded.clear();\n this.#preloads.clear();\n this.#navigation.invalidate(new WayfinderDisposedError());\n this.#unlistenHistory();\n // Abort the disposal signal last: waitFor() listeners clean themselves up via this signal.\n this.#disposeController.abort(new WayfinderDisposedError());\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n // ─── Private: assertions ──────────────────────────────────────────────────\n\n #assertNotDisposed(): void {\n if (this.#disposed) throw new WayfinderDisposedError();\n }\n\n // ─── Private: history listener ────────────────────────────────────────────\n\n #registerHistoryListener(): () => void {\n return this.#history.onPopstate(() => {\n const { hash, pathname, search } = this.#history.location;\n const newHref = `${pathname}${search}${hash}`;\n const previousHref = this.#lastHref;\n\n if (newHref === previousHref) return;\n\n this.#runInBackground(this.#handleHistoryNavigation(newHref, previousHref), { source: 'history-listener' });\n });\n }\n\n async #handleHistoryNavigation(newHref: string, previousHref: string): Promise<void> {\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((m) => m.name);\n const destination = this.#navigationDestination(newHref);\n const allowed = await runLeaveBlockers(this.#beforeLeaveBlockers, activeMatchNames, destination);\n\n if (!attempt.isCurrent()) return;\n\n if (!allowed) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n\n return;\n }\n\n const terminalRan = await this.#handleRoute(\n attempt,\n readLocation(this.#base, this.#history),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n 0,\n false,\n );\n\n if (attempt.isCurrent() && !terminalRan) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n }\n }\n\n // ─── Private: error handling ──────────────────────────────────────────────\n\n #reportError(error: unknown, context: RouterErrorContext): void {\n reportError(error, context, this.#onError);\n }\n\n #runInBackground(promise: Promise<void>, context: RouterErrorContext): void {\n void promise.catch((value) => {\n if (isRouterErrorCarrier(value)) {\n this.#reportError(value.error, value.context);\n } else {\n this.#reportError(value, context);\n }\n });\n }\n\n // ─── Private: listener notification ──────────────────────────────────────\n\n #notifyListeners(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener(this.#currentState);\n } catch (error) {\n // A throwing subscriber must not abort the rest of the notify pass or\n // corrupt navigation state; surface it as an unhandled error instead.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n // ─── Private: data loaders ────────────────────────────────────────────────\n\n /**\n * Run all data loaders and return their results. Per-def `onError` boundaries are applied.\n */\n async #loadData(\n defs: readonly RouteBranchDef[],\n context: RouteContext<RouteParams, TRoutes>,\n signal: AbortSignal,\n ): Promise<unknown[]> {\n return Promise.all(\n defs.map(async (def) => {\n if (!def.dataFn) return undefined;\n\n const dataFn = def.dataFn as unknown as DataFn<RouteParams, TRoutes>;\n\n try {\n return await dataFn({ ...context, signal } as DataContext<RouteParams, TRoutes>);\n } catch (err) {\n if (def.onError) return def.onError(err, { ...context, signal } as unknown as DataContext);\n\n throw err;\n }\n }),\n );\n }\n\n // ─── Private: URL resolution ──────────────────────────────────────────────\n\n /** Parse a URL, call #prepareRoute, and follow declarative redirects up to 5 hops. */\n async #resolveUrl(url: string): Promise<NavigationDecision> {\n let destination = url;\n\n for (let i = 0; i < 5; i += 1) {\n const parsed = new URL(destination, 'http://localhost');\n const location: RouteLocation = {\n hash: parsed.hash.replace(/^#/, ''),\n historyState: null,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n\n const prepared = await this.#prepareRoute(location);\n\n if (prepared.type !== 'redirect') return prepared;\n\n destination = this.#resolveDestination(prepared.redirectTo);\n }\n\n throw new WayfinderRedirectLoopError();\n }\n\n // ─── Private: route preparation ───────────────────────────────────────────\n\n async #prepareRoute(location: RouteLocation): Promise<NavigationDecision> {\n const { params, record } = matchRouteFor(location.pathname, this.#records);\n\n if (!record) {\n return { location, params, type: 'unmatched' };\n }\n\n if (record.redirect) {\n return {\n location,\n params,\n redirectTo: resolveTarget(record.redirect, this.#routesByName, this.#base),\n type: 'redirect',\n };\n }\n\n let resolvedQuery: ResolvedQueryParams = location.query;\n\n const coerce: CoerceSearchFn | undefined = record.coerceSearch ?? this.#globalCoerceSearch;\n\n if (coerce) {\n try {\n resolvedQuery = coerce(location.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n resolvedQuery = location.query;\n }\n }\n\n return {\n branch: buildMatchBranch(\n record.branchDefs,\n params,\n location.pathname,\n record.branchDefs.map(() => undefined),\n ),\n location,\n params,\n record,\n resolvedQuery,\n type: 'matched',\n };\n }\n\n // ─── Private: terminal (data only) ────────────────────────────────────────\n\n async #runTerminal(\n record: RouteRecord,\n context: RouteContext<RouteParams, TRoutes>,\n location: RouteLocation,\n params: RouteParams,\n signal: AbortSignal,\n isCurrent: () => boolean,\n onDataError?: (error: unknown) => void,\n ): Promise<void> {\n if (!isCurrent()) return;\n\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n\n if (hasData) {\n const preloadKey = this.#hrefForLocation(location);\n const preloading = this.#preloads.get(preloadKey);\n\n if (preloading) {\n await preloading.catch(() => undefined);\n\n if (!isCurrent()) return;\n }\n\n const cached = this.#preloaded.get(preloadKey);\n\n if (cached) {\n this.#preloaded.delete(preloadKey);\n dataResults = cached;\n } else {\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'loading',\n });\n this.#notifyListeners();\n\n try {\n dataResults = await this.#loadData(defs, context, signal);\n } catch (error) {\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'error',\n });\n onDataError?.(error);\n throw error;\n }\n }\n }\n\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'idle',\n });\n }\n\n // ─── Private: main navigation orchestrator ────────────────────────────────\n\n /**\n * Declarative redirects reuse the active attempt and replace the final history entry.\n * Middleware redirects call `ctx.navigate()`, which starts a new attempt.\n */\n async #handleRoute(\n attempt: NavigationAttempt,\n currentLocation: RouteLocation,\n commit: (location: RouteLocation, replace: boolean) => void,\n useTransition?: boolean,\n depth = 0,\n replace = false,\n ): Promise<boolean> {\n const previousState = this.#currentState;\n const isCurrent = (): boolean => attempt.isCurrent() && !this.#disposed;\n const prepared = await this.#prepareRoute(currentLocation);\n\n if (!isCurrent()) return false;\n\n if (prepared.type === 'redirect') {\n if (depth >= 5) throw new WayfinderRedirectLoopError();\n\n return this.#handleRoute(\n attempt,\n this.#locationFromPath(prepared.redirectTo, currentLocation.historyState),\n commit,\n useTransition,\n depth + 1,\n true,\n );\n }\n\n if (prepared.type === 'unmatched') {\n // Fall back to notFound record when defined.\n if (this.#notFoundRecord) {\n const nfDefs = [this.#notFoundRecord.leaf];\n const nfBranch = buildMatchBranch(nfDefs, {}, currentLocation.pathname, [undefined]);\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n\n // Apply global coerceSearch to the unmatched location so notFound handlers\n // receive typed query params, consistent with matched-route behaviour.\n let nfResolvedQuery: ResolvedQueryParams = currentLocation.query;\n let notified = false;\n\n if (this.#globalCoerceSearch) {\n try {\n nfResolvedQuery = this.#globalCoerceSearch(currentLocation.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n }\n }\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(\n currentLocation,\n nfResolvedQuery,\n {},\n nfBranch,\n (target, options) => this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...this.#notFoundRecord!.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(currentLocation, replace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(\n this.#notFoundRecord!,\n context,\n currentLocation,\n {},\n attempt.signal,\n isCurrent,\n (error) => {\n dataError = error;\n hasDataError = true;\n },\n );\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: '__notFound__', source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: '__notFound__', source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n if (!isCurrent()) return false;\n\n commit(prepared.location, replace);\n\n if (!isCurrent()) return false;\n\n this.#currentState = createRouteState({\n location: prepared.location,\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n\n return true;\n }\n\n const { branch, location, params, record, resolvedQuery } = prepared;\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n let notified = false;\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, (target, options) =>\n this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...record.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(location, replace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(record, context, location, params, attempt.signal, isCurrent, (error) => {\n dataError = error;\n hasDataError = true;\n });\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: record.leaf.name, source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: record.leaf.name, source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n async #runWithTransition(run: () => Promise<void>, useTransition?: boolean): Promise<void> {\n if ((useTransition ?? this.#useViewTransition) && typeof document !== 'undefined') {\n const startViewTransition = (\n document as Document & {\n startViewTransition?: (callback: () => void | Promise<void>) => { finished: Promise<void> };\n }\n ).startViewTransition;\n\n if (startViewTransition) {\n await startViewTransition.call(document, run).finished;\n\n return;\n }\n }\n\n await run();\n }\n\n #applyScroll(to: RouteState, from: RouteState): void {\n if (!this.#scroll || typeof window === 'undefined') return;\n\n const decision = this.#scroll(to, from);\n\n if (decision === 'preserve') return;\n\n if (decision === 'top') {\n window.scrollTo(0, 0);\n\n return;\n }\n\n window.scrollTo(decision.x, decision.y);\n }\n\n // ─── Private: destination resolution ─────────────────────────────────────\n\n #resolveDestination(path: string): string {\n const parsed = new URL(path, 'http://localhost');\n const normalizedPath = stripBase(parsed.pathname, this.#base);\n\n return `${joinPaths(this.#base, normalizedPath)}${parsed.search}${parsed.hash}`;\n }\n\n #locationFromPath(path: string, historyState: unknown): RouteLocation {\n const parsed = new URL(this.#resolveDestination(path), 'http://localhost');\n\n return {\n hash: parsed.hash.replace(/^#/, ''),\n historyState,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n }\n\n #hrefForLocation(location: RouteLocation): string {\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(location.query)) {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, item);\n });\n else search.set(key, value);\n }\n\n const query = search.toString();\n const hash = location.hash ? `#${location.hash}` : '';\n\n return `${joinPaths(this.#base, location.pathname)}${query ? `?${query}` : ''}${hash}`;\n }\n\n #navigationDestination(href: string): NavigationDestination {\n const parsed = new URL(href, 'http://localhost');\n const pathname = stripBase(parsed.pathname, this.#base);\n const { params, record } = matchRouteFor(pathname, this.#records);\n\n return {\n name: record?.leaf.name,\n params,\n pathname,\n query: parseQuery(parsed.search),\n };\n }\n\n /** User-initiated navigation. History changes only after middleware reaches the terminal stage. */\n async #navigateToPath(path: string, options: NavigateOptions = {}): Promise<void> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(path);\n\n if (!options.force && destination === this.#lastHref) return;\n\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((match) => match.name);\n const allowed = await runLeaveBlockers(\n this.#beforeLeaveBlockers,\n activeMatchNames,\n this.#navigationDestination(destination),\n );\n\n if (!attempt.isCurrent() || !allowed) return;\n\n try {\n await this.#handleRoute(\n attempt,\n this.#locationFromPath(destination, options.state),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n else this.#history.push(href, location.historyState);\n\n this.#lastHref = href;\n },\n options.viewTransition,\n 0,\n options.replace ?? false,\n );\n } catch (value) {\n throw isRouterErrorCarrier(value) ? value.error : value;\n }\n }\n}\n\n// ─── Public factory ───────────────────────────────────────────────────────────\n\n/**\n * Create a new router instance from a route table.\n *\n * @example\n * const router = createRouter({\n * routes: {\n * home: { path: '/' },\n * userDetail: { path: '/users/:id', data: fetchUser },\n * },\n * });\n */\nexport function createRouter<const TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): Router<TRoutes> {\n return new Router(options);\n}\n\n// Export the Router type (not the constructor value) for type annotations.\nexport type { Router };\n"],"mappings":"A,kMAyDA,SAAS,eAAe,EAAc,EAA6D,CACjG,IAAM0B,EAAQC,EAAa,IAAIC,CAAI,EAEnC,GAAIF,EAAO,OAAOA,EAElB,IAAMG,EAAY,CAAC,GAAGF,EAAa,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,EAEpD,MAAM,IAAI3B,EAAAA,oBACR6B,EAAY,uBAAuBD,EAAK,sBAAsBC,IAAc,uBAAuBD,GACrG,CACF,CAEA,SAAS,cACP,EACA,EACA,EAAO,IACC,CACR,GAAI,SAAUE,EAAQ,OAAOA,EAAO,KAEpC,IAAMJ,EAAQ,eAAeI,EAAO,KAAMH,CAAY,EAChDI,EAAO9B,EAAAA,SAAS+B,EAAMN,EAAM,KAAMI,EAAO,OAAQA,EAAO,KAAK,EAEnE,OAAOA,EAAO,KAAO,GAAGC,EAAK,GAAGD,EAAO,OAASC,CAClD,CAQA,IAAME,EAAe,OAAO,uBAAuB,EAQnD,SAAS,WAAW,EAAgB,EAAiD,CACnF,MAAO,EAAGA,GAAe,GAAM,UAAS,OAAM,CAChD,CAEA,SAAS,qBAAqB,EAA6C,CACzE,OAAyB,OAAOC,GAAU,YAAnCA,GAA+CD,KAAiBC,CACzE,CAEA,SAAS,cAAc,EAAuB,CAG5C,MAFI,qBAAqBA,CAAK,EAASA,EAAM,MAEvCA,CACR,CAkBA,IAAM,OAAN,KAAsD,CACpD,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GAGA,GAAgC,IAAI,IACpC,GAAuBhC,EAAAA,4BAA4B,EACnD,GACA,GAAY,GACZ,GA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K,GAAUoD,EAAM,IAAI,EACvEc,EAAU,MAAMlG,EAAAA,iBACpB,KAAK4F,GACLI,EACA,KAAKC,GAAuBzC,CAAW,CACzC,EAEA,GAAKd,EAAQ,UAAU,GAAMwD,EAE7B,GAAI,CACF,MAAM,KAAKrD,GACTH,EACA,KAAK6E,GAAkB/D,EAAalC,EAAQ,KAAK,GAChD,EAAU,IAAY,CACrB,GAAI,CAACoB,EAAQ,UAAU,EAAG,OAE1B,IAAMI,EAAO,KAAKC,GAAiBC,CAAQ,EAEvCC,EAAS,KAAKvB,GAAS,QAAQoB,EAAME,EAAS,YAAY,EACzD,KAAKtB,GAAS,KAAKoB,EAAME,EAAS,YAAY,EAEnD,KAAKV,GAAYQ,CACnB,EACAxB,EAAQ,eACR,EACAA,EAAQ,SAAW,EACrB,CACF,OAASF,EAAO,CACd,MAAM,qBAAqBA,CAAK,EAAIA,EAAM,MAAQA,CACpD,CACF,CACF,EAeA,SAAgB,aAA+C,EAAkD,CAC/G,OAAO,IAAI,OAAOE,CAAO,CAC3B,C"}
|
|
1
|
+
{"version":3,"file":"router.cjs","names":["WayfinderRouteError","buildUrl","createNavigationCoordinator","compileRoutes","normalizePath","createBrowserHistory","createRouteState","matchRouteFor","matchesPrefix","stripBase","buildMatchBranch","createRouteContext","WayfinderDisposedError","runLeaveBlockers","WayfinderRedirectLoopError","executeMiddlewarePipeline","joinPaths","parseQuery","require__navigation","require_compile","require_context","require_errors","require_guards","require_history","require_path","route","routesByName","name","available","target","path","base","ROUTER_ERROR","MAX_REDIRECT_HOPS","value","compiled","options","#base","#globalMiddleware","#globalCoerceSearch","#history","#onError","#scroll","#useViewTransition","#records","#routesByName","#currentState","nf","leafDef","#notFoundRecord","#unlistenHistory","#registerHistoryListener","initialHref","pathname","search","hash","#lastHref","attempt","#navigation","navigationPromise","#handleRoute","state","href","#hrefForLocation","location","replace","#runInBackground","views","#assertNotDisposed","#listeners","listener","destination","#navigateToPath","params","query","url","normalizedPathname","record","branch","prepared","#resolveWithRedirects","defs","hasData","d","dataResults","error","status","effectiveSignal","context","resolvedQuery","#loadData","#resolveDestination","existing","#preloads","work","#disposeController","#disposed","key","#preloaded","match","#reportError","m","reject","resolve","unsub","entry","blocker","#beforeLeaveBlockers","newHref","previousHref","#handleHistoryNavigation","activeMatchNames","#navigationDestination","allowed","terminalRan","promise","def","dataFn","err","hopped","hop","#prepareRoute","#locationFromPath","historyState","coerce","#coerceQuery","#runTerminal","isCurrent","preloadKey","preloading","cached","#notifyListeners","signal","onDataError","previousState","commit","#applyScroll","shouldReplace","committed","dataError","hasDataError","notified","#runWithTransition","useTransition","startViewTransition","run","decision","to","from","parsed","normalizedPath","item"],"sources":["../src/router.ts"],"sourcesContent":["import { createNavigationCoordinator, type NavigationAttempt } from './_navigation';\nimport { compileRoutes } from './compile';\nimport {\n buildMatchBranch,\n createRouteContext,\n createRouteState,\n executeMiddlewarePipeline,\n reportError,\n} from './context';\nimport { WayfinderDisposedError, WayfinderRedirectLoopError, WayfinderRouteError } from './errors';\nimport { type RegisteredBlocker, runLeaveBlockers } from './guards';\nimport { createBrowserHistory } from './history';\nimport { buildUrl, joinPaths, matchesPrefix, matchRouteFor, normalizePath, parseQuery, stripBase } from './path';\nimport type {\n BeforeLeaveBlocker,\n BeforeLeaveOptions,\n CoerceSearchFn,\n DataContext,\n DataFn,\n HistoryDriver,\n IsActiveOptions,\n Middleware,\n NamedNavigationTarget,\n NavigateOptions,\n NavigationDestination,\n PathParams,\n RawNavigationTarget,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteName,\n RouteParams,\n RoutePathByName,\n RouteRecord,\n RouterErrorContext,\n RouterOptions,\n RouteState,\n RouteTable,\n RouteViewMap,\n RouteViewName,\n RouteViewRegistry,\n Unsubscribe,\n} from './types';\n\n// ─── Module-level helpers ────────────────────────────────────────────────────\n\nfunction getRouteByName(name: string, routesByName: ReadonlyMap<string, RouteRecord>): RouteRecord {\n const route = routesByName.get(name);\n\n if (route) return route;\n\n const available = [...routesByName.keys()].join(', ');\n\n throw new WayfinderRouteError(\n available ? `Unknown route name: ${name}. Available routes: ${available}` : `Unknown route name: ${name}`,\n );\n}\n\nfunction resolveTarget(\n target: { path: string } | { hash?: string; name: string; params?: RouteParams; query?: ResolvedQueryParams },\n routesByName: ReadonlyMap<string, RouteRecord>,\n base = '/',\n): string {\n if ('path' in target) return target.path;\n\n const route = getRouteByName(target.name, routesByName);\n const path = buildUrl(base, route.path, target.params, target.query);\n\n return target.hash ? `${path}#${target.hash}` : path;\n}\n\n// ─── Internal error carrier ──────────────────────────────────────────────────\n//\n// Carries error context alongside the original error without mutating the thrown\n// object. The carrier is unwrapped before reaching external callers so error\n// identity and `cause` chains are preserved.\n\nconst ROUTER_ERROR = Symbol('wayfinder.routerError');\n\n/** Declarative redirect hops the router follows before declaring a loop. */\nconst MAX_REDIRECT_HOPS = 5;\n\ntype RouterErrorCarrier = {\n [ROUTER_ERROR]: true;\n readonly error: unknown;\n readonly context: RouterErrorContext;\n};\n\nfunction carryError(error: unknown, context: RouterErrorContext): RouterErrorCarrier {\n return { [ROUTER_ERROR]: true, context, error };\n}\n\nfunction isRouterErrorCarrier(value: unknown): value is RouterErrorCarrier {\n return value !== null && typeof value === 'object' && ROUTER_ERROR in (value as Record<symbol, unknown>);\n}\n\nfunction unwrapCarrier(value: unknown): never {\n if (isRouterErrorCarrier(value)) throw value.error;\n\n throw value;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype NavigationDecision =\n | {\n branch: RouteMatchBranch;\n location: RouteLocation;\n params: RouteParams;\n record: RouteRecord;\n resolvedQuery: ResolvedQueryParams;\n type: 'matched';\n }\n | { location: RouteLocation; params: RouteParams; type: 'unmatched' }\n | { location: RouteLocation; params: RouteParams; redirectTo: string; type: 'redirect' };\n\n/** The decision left after declarative redirects have been followed. */\ntype TerminalDecision = Exclude<NavigationDecision, { type: 'redirect' }>;\n\n// ─── Router class ─────────────────────────────────────────────────────────────\n\nclass Router<TRoutes extends RouteTable = RouteTable> {\n readonly #base: string;\n readonly #globalMiddleware: readonly Middleware[];\n readonly #globalCoerceSearch?: CoerceSearchFn;\n readonly #history: HistoryDriver;\n readonly #records: readonly RouteRecord[];\n readonly #routesByName: ReadonlyMap<string, RouteRecord>;\n readonly #onError?: RouterOptions<TRoutes>['onError'];\n readonly #scroll?: RouterOptions<TRoutes>['scroll'];\n readonly #useViewTransition: boolean;\n\n // Mutable navigation state\n readonly #beforeLeaveBlockers = new Set<RegisteredBlocker>();\n readonly #navigation = createNavigationCoordinator();\n #currentState: RouteState;\n #disposed = false;\n readonly #disposeController = new AbortController();\n #lastHref = '/';\n readonly #listeners = new Set<(state: RouteState) => void>();\n readonly #preloaded = new Map<string, unknown[]>();\n readonly #preloads = new Map<string, Promise<RouteState | null>>();\n // Compiled notFound fallback record\n readonly #notFoundRecord: RouteRecord | null;\n\n readonly #unlistenHistory: () => void;\n\n /** Resolves when the constructor-triggered navigation has settled; rejects if it fails. */\n readonly ready: Promise<void>;\n\n constructor(options: RouterOptions<TRoutes>) {\n const compiled = compileRoutes(options);\n\n this.#base = normalizePath(options.base ?? '/');\n this.#globalMiddleware = (options.middleware ?? []) as unknown as Middleware[];\n this.#globalCoerceSearch = options.coerceSearch;\n this.#history = options.history ?? createBrowserHistory();\n this.#onError = options.onError;\n this.#scroll = options.scroll;\n this.#useViewTransition = options.viewTransition ?? false;\n this.#records = compiled.records as unknown as readonly RouteRecord[];\n this.#routesByName = compiled.routesByName as unknown as ReadonlyMap<string, RouteRecord>;\n this.#currentState = createRouteState({\n location: { hash: '', historyState: null, pathname: '/', query: {} },\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n\n // Build a synthetic RouteRecord for the notFound fallback.\n if (options.notFound) {\n const nf = options.notFound;\n const leafDef: RouteBranchDef = {\n dataFn: nf.data,\n name: '__notFound__',\n };\n\n this.#notFoundRecord = {\n branchDefs: [leafDef],\n leaf: leafDef,\n matcher: { paramNames: [], pattern: /(?:)/, prefixPattern: /(?:)/ },\n ownMiddleware: (nf.middleware ?? []) as unknown as Middleware[],\n path: '/*',\n };\n } else {\n this.#notFoundRecord = null;\n }\n\n this.#unlistenHistory = this.#registerHistoryListener();\n\n const { hash, pathname, search, state } = this.#history.location;\n const initialHref = `${pathname}${search}${hash}`;\n\n this.#lastHref = initialHref;\n\n const attempt = this.#navigation.begin();\n\n const navigationPromise = this.#handleRoute(\n attempt,\n initialHref,\n state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n false,\n ).then(() => undefined);\n\n // ready rejects with the original error (carrier unwrapped) for external consumers.\n this.ready = navigationPromise.catch(unwrapCarrier);\n // Attach a silent handler so an unawaited ready promise doesn't trigger\n // an unhandled-rejection warning. External consumers can still await ready\n // and receive the rejection: each .catch() subscriber fires independently.\n this.ready.catch(() => {});\n // #runInBackground receives the raw promise so it can extract carrier context for onError.\n this.#runInBackground(navigationPromise, { source: 'initial-navigation' });\n\n // Router actions are intentionally bound once so they remain safe when destructured.\n this.beforeLeave = this.beforeLeave.bind(this);\n this.createViewRegistry = this.createViewRegistry.bind(this);\n this.dispose = this.dispose.bind(this);\n this.getSnapshot = this.getSnapshot.bind(this);\n this.isActive = this.isActive.bind(this);\n this.load = this.load.bind(this);\n this.match = this.match.bind(this);\n this.navigate = this.navigate.bind(this);\n this.preload = this.preload.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.url = this.url.bind(this);\n this.waitFor = this.waitFor.bind(this);\n }\n\n // ─── Public state ─────────────────────────────────────────────────────────\n\n /**\n * Returns the current immutable router state snapshot.\n *\n * Compatible with React's `useSyncExternalStore`:\n * ```ts\n * const state = useSyncExternalStore(\n * (cb) => router.subscribe(cb),\n * () => router.getSnapshot()\n * );\n * ```\n */\n getSnapshot(): RouteState {\n return this.#currentState;\n }\n\n createViewRegistry<const TViews extends RouteViewMap<TRoutes>, TNotFound = never>(\n views: TViews & Record<Exclude<keyof TViews, RouteViewName<TRoutes>>, never>,\n options?: { notFound?: TNotFound },\n ): RouteViewRegistry<TViews[keyof TViews] | TNotFound> {\n return {\n resolve: (state) => {\n const name = state.matches.at(-1)?.name;\n\n if (name === '__notFound__') return options?.notFound;\n\n return name ? (views[name as keyof TViews] as TViews[keyof TViews]) : undefined;\n },\n };\n }\n\n // ─── Subscription ─────────────────────────────────────────────────────────\n\n /**\n * Subscribe to state changes. The listener is called on each subsequent state change;\n * use `getSnapshot()` to read the current value immediately.\n */\n subscribe(listener: (state: RouteState) => void): Unsubscribe {\n this.#assertNotDisposed();\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n // ─── Navigation ───────────────────────────────────────────────────────────\n\n /**\n * Navigate using a named route target or a raw path target.\n *\n * If a data loader throws after terminal execution begins, history has already committed\n * the destination and the returned Promise rejects with the loader error.\n */\n navigate(\n target: NamedNavigationTarget<TRoutes> | RawNavigationTarget | string,\n options?: NavigateOptions,\n ): Promise<void> {\n const normalized = typeof target === 'string' ? { path: target } : target;\n const destination = resolveTarget(normalized, this.#routesByName, this.#base);\n\n return this.#navigateToPath(destination, options);\n }\n\n // ─── URL helpers ──────────────────────────────────────────────────────────\n\n /** Build a URL for a named route, including optional params and query string. */\n url<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n\n return buildUrl(this.#base, route.path, params, query);\n }\n\n /**\n * Build an anchor-ready href for a named route: the address-bar form for the configured\n * history driver. `url()` returns the router-internal path; under `createHashHistory`\n * the same route lives behind `#`, and `href()` returns that form for `<a>` elements.\n */\n href<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n const url = buildUrl(this.#base, route.path, params, query);\n\n return this.#history.href?.(url) ?? url;\n }\n\n /** Returns true when the current location matches the named route by prefix (default) or exactly. */\n isActive<Name extends RouteName<TRoutes>>(name: Name, options: IsActiveOptions = {}): boolean {\n const route = getRouteByName(name, this.#routesByName);\n const pathname = this.#currentState.location.pathname;\n const exact = options.exact ?? false;\n\n return exact ? matchRouteFor(pathname, [route]).record != null : matchesPrefix(pathname, route);\n }\n\n /** Match a pathname to a route branch without running middleware or data loaders. Returns null for redirects or no match. */\n match(pathname: string): RouteMatchBranch | null {\n const normalizedPathname = stripBase(normalizePath(pathname), this.#base);\n const { params, record } = matchRouteFor(normalizedPathname, this.#records);\n\n if (!record || record.redirect) return null;\n\n const branch = buildMatchBranch(\n record.branchDefs,\n params,\n normalizedPathname,\n record.branchDefs.map(() => undefined),\n );\n\n return branch.length ? branch : null;\n }\n\n /**\n * Load a router-internal URL into a route state including data loader results,\n * without modifying router state or history. Follows declarative redirects but\n * does not cache results. Middleware is not executed: use `navigate()` when\n * middleware side effects are needed. An unmatched URL resolves to the\n * `notFound` route when configured; otherwise `null` is returned.\n */\n async load(url: string, options?: { signal?: AbortSignal }): Promise<RouteState | null> {\n const { decision: prepared } = await this.#resolveWithRedirects(url, null);\n\n if (prepared.type !== 'matched') return null;\n\n const { location, params, record, resolvedQuery } = prepared;\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n let error: unknown;\n let status: 'error' | 'idle' = 'idle';\n\n if (hasData) {\n const effectiveSignal = options?.signal ?? new AbortController().signal;\n const branch = buildMatchBranch(defs, params, location.pathname, dataResults);\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, () => Promise.resolve());\n\n try {\n dataResults = await this.#loadData(defs, context, effectiveSignal);\n } catch (e) {\n error = e;\n status = 'error';\n }\n }\n\n return createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status,\n });\n }\n\n async preload(target: NamedNavigationTarget<TRoutes>): Promise<RouteState | null> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(resolveTarget(target, this.#routesByName, this.#base));\n const existing = this.#preloads.get(destination);\n\n if (existing) return existing;\n\n const work = this.load(destination, { signal: this.#disposeController.signal })\n .then((state) => {\n if (this.#disposed) throw this.#disposeController.signal.reason;\n\n if (state?.status === 'error') throw state.error;\n\n if (state) {\n const key = this.#hrefForLocation(state.location);\n\n if (this.#preloaded.size >= 20) this.#preloaded.delete(this.#preloaded.keys().next().value!);\n\n this.#preloaded.set(\n key,\n state.matches.map((match) => match.data),\n );\n }\n\n return state;\n })\n .catch((error) => {\n if (this.#onError) this.#reportError(error, { source: 'preload' });\n\n throw error;\n })\n .finally(() => {\n this.#preloads.delete(destination);\n });\n\n this.#preloads.set(destination, work);\n\n return work;\n }\n\n /**\n * Returns a Promise that resolves the next time the router reaches `status: 'idle'`\n * and the active matches include a route named `name`.\n *\n * - Resolves immediately if the router is already `idle` at `name`.\n * - Rejects immediately if the router is already in `status: 'error'`.\n * - If the router is currently `idle` at a **different** route and no navigation is in\n * flight, this promise will not resolve until a future navigation lands on `name`.\n * Typical use-case is awaiting a navigation you just triggered:\n * `router.navigate(target); await router.waitFor('routeName')`.\n * @throws {WayfinderDisposedError} if the router is disposed while the promise is pending,\n * or if called after the router has already been disposed.\n */\n waitFor(name: RouteName<TRoutes>): Promise<RouteState> {\n this.#assertNotDisposed();\n\n return new Promise((resolve, reject) => {\n const matchesName = (state: RouteState): boolean =>\n state.status === 'idle' && state.matches.some((m) => m.name === name);\n\n if (this.#currentState.status === 'error') {\n reject(this.#currentState.error);\n\n return;\n }\n\n if (matchesName(this.#currentState)) {\n resolve(this.#currentState);\n\n return;\n }\n\n const unsub = this.subscribe((state) => {\n if (matchesName(state)) {\n unsub();\n resolve(state);\n } else if (state.status === 'error') {\n unsub();\n reject(state.error);\n }\n });\n\n this.#disposeController.signal.addEventListener(\n 'abort',\n () => {\n unsub();\n reject(this.#disposeController.signal.reason);\n },\n { once: true },\n );\n });\n }\n\n // ─── Navigation guards ────────────────────────────────────────────────────\n\n /**\n * Register a leave guard. Called before user-triggered navigation attempts.\n * Return `false` to cancel; `true` to allow.\n * Returns a function that removes the guard.\n *\n * Use `options.routes` to scope the guard to specific routes (fires only when navigating\n * away from a route whose name appears in the array, checked against any node in the active branch).\n */\n beforeLeave(blocker: BeforeLeaveBlocker, options?: BeforeLeaveOptions<TRoutes>): Unsubscribe {\n this.#assertNotDisposed();\n\n const entry: RegisteredBlocker = {\n handler: blocker,\n routes: options?.routes as string[] | undefined,\n };\n\n this.#beforeLeaveBlockers.add(entry);\n\n return () => {\n this.#beforeLeaveBlockers.delete(entry);\n };\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n get disposalSignal(): AbortSignal {\n return this.#disposeController.signal;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /** Dispose event listeners and prevent further router interaction. Idempotent. */\n dispose(): void {\n if (this.#disposed) return;\n\n this.#disposed = true;\n this.#beforeLeaveBlockers.clear();\n this.#listeners.clear();\n this.#preloaded.clear();\n this.#preloads.clear();\n this.#navigation.invalidate(new WayfinderDisposedError());\n this.#unlistenHistory();\n // Abort the disposal signal last: waitFor() listeners clean themselves up via this signal.\n this.#disposeController.abort(new WayfinderDisposedError());\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n // ─── Private: assertions ──────────────────────────────────────────────────\n\n #assertNotDisposed(): void {\n if (this.#disposed) throw new WayfinderDisposedError();\n }\n\n // ─── Private: history listener ────────────────────────────────────────────\n\n #registerHistoryListener(): () => void {\n return this.#history.onPopstate(() => {\n const { hash, pathname, search } = this.#history.location;\n const newHref = `${pathname}${search}${hash}`;\n const previousHref = this.#lastHref;\n\n if (newHref === previousHref) return;\n\n this.#runInBackground(this.#handleHistoryNavigation(newHref, previousHref), { source: 'history-listener' });\n });\n }\n\n async #handleHistoryNavigation(newHref: string, previousHref: string): Promise<void> {\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((m) => m.name);\n const destination = this.#navigationDestination(newHref);\n const allowed = await runLeaveBlockers(this.#beforeLeaveBlockers, activeMatchNames, destination);\n\n if (!attempt.isCurrent()) return;\n\n if (!allowed) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n\n return;\n }\n\n const terminalRan = await this.#handleRoute(\n attempt,\n newHref,\n this.#history.location.state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n false,\n );\n\n if (attempt.isCurrent() && !terminalRan) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n }\n }\n\n // ─── Private: error handling ──────────────────────────────────────────────\n\n #reportError(error: unknown, context: RouterErrorContext): void {\n reportError(error, context, this.#onError);\n }\n\n #runInBackground(promise: Promise<void>, context: RouterErrorContext): void {\n void promise.catch((value) => {\n if (isRouterErrorCarrier(value)) {\n this.#reportError(value.error, value.context);\n } else {\n this.#reportError(value, context);\n }\n });\n }\n\n // ─── Private: listener notification ──────────────────────────────────────\n\n #notifyListeners(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener(this.#currentState);\n } catch (error) {\n // A throwing subscriber must not abort the rest of the notify pass or\n // corrupt navigation state; surface it as an unhandled error instead.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n // ─── Private: data loaders ────────────────────────────────────────────────\n\n /**\n * Run all data loaders and return their results. Per-def `onError` boundaries are applied.\n */\n async #loadData(\n defs: readonly RouteBranchDef[],\n context: RouteContext<RouteParams, TRoutes>,\n signal: AbortSignal,\n ): Promise<unknown[]> {\n return Promise.all(\n defs.map(async (def) => {\n if (!def.dataFn) return undefined;\n\n const dataFn = def.dataFn as unknown as DataFn<RouteParams, TRoutes>;\n\n try {\n return await dataFn({ ...context, signal } as DataContext<RouteParams, TRoutes>);\n } catch (err) {\n if (def.onError) return def.onError(err, { ...context, signal } as unknown as DataContext);\n\n throw err;\n }\n }),\n );\n }\n\n // ─── Private: URL resolution ──────────────────────────────────────────────\n\n /**\n * Resolve a router-internal URL to its terminal route, following declarative\n * redirects. This is the single redirect-following implementation shared by\n * navigations and `load()`. `hopped` reports whether any redirect was\n * followed; hopped navigations must replace rather than push history.\n */\n async #resolveWithRedirects(\n url: string,\n historyState: unknown,\n ): Promise<{ decision: TerminalDecision; hopped: boolean }> {\n let destination = url;\n let hopped = false;\n\n for (let hop = 0; ; hop += 1) {\n const prepared = await this.#prepareRoute(this.#locationFromPath(destination, historyState));\n\n if (prepared.type !== 'redirect') return { decision: prepared, hopped };\n\n if (hop >= MAX_REDIRECT_HOPS) throw new WayfinderRedirectLoopError();\n\n destination = prepared.redirectTo;\n hopped = true;\n }\n }\n\n /** Run a coercion function with fallback to the raw query, reporting failures through `onError`. */\n #coerceQuery(location: RouteLocation, coerce?: CoerceSearchFn): ResolvedQueryParams {\n if (!coerce) return location.query;\n\n try {\n return coerce(location.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n\n return location.query;\n }\n }\n\n // ─── Private: route preparation ───────────────────────────────────────────\n\n async #prepareRoute(location: RouteLocation): Promise<NavigationDecision> {\n const { params, record } = matchRouteFor(location.pathname, this.#records);\n\n if (!record) {\n // The configured notFound fallback is a plain route record: fold it into a\n // matched decision so fallback navigations run through the same pipeline.\n if (this.#notFoundRecord) {\n return {\n branch: buildMatchBranch(this.#notFoundRecord.branchDefs, {}, location.pathname, [undefined]),\n location,\n params: {},\n record: this.#notFoundRecord,\n resolvedQuery: this.#coerceQuery(location, this.#globalCoerceSearch),\n type: 'matched',\n };\n }\n\n return { location, params, type: 'unmatched' };\n }\n\n if (record.redirect) {\n return {\n location,\n params,\n redirectTo: resolveTarget(record.redirect, this.#routesByName, this.#base),\n type: 'redirect',\n };\n }\n\n const resolvedQuery = this.#coerceQuery(location, record.coerceSearch ?? this.#globalCoerceSearch);\n\n return {\n branch: buildMatchBranch(\n record.branchDefs,\n params,\n location.pathname,\n record.branchDefs.map(() => undefined),\n ),\n location,\n params,\n record,\n resolvedQuery,\n type: 'matched',\n };\n }\n\n // ─── Private: terminal (data only) ────────────────────────────────────────\n\n async #runTerminal(\n record: RouteRecord,\n context: RouteContext<RouteParams, TRoutes>,\n location: RouteLocation,\n params: RouteParams,\n signal: AbortSignal,\n isCurrent: () => boolean,\n onDataError?: (error: unknown) => void,\n ): Promise<void> {\n if (!isCurrent()) return;\n\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n\n if (hasData) {\n const preloadKey = this.#hrefForLocation(location);\n const preloading = this.#preloads.get(preloadKey);\n\n if (preloading) {\n await preloading.catch(() => undefined);\n\n if (!isCurrent()) return;\n }\n\n const cached = this.#preloaded.get(preloadKey);\n\n if (cached) {\n this.#preloaded.delete(preloadKey);\n dataResults = cached;\n } else {\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'loading',\n });\n this.#notifyListeners();\n\n try {\n dataResults = await this.#loadData(defs, context, signal);\n } catch (error) {\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'error',\n });\n onDataError?.(error);\n throw error;\n }\n }\n }\n\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'idle',\n });\n }\n\n // ─── Private: main navigation orchestrator ────────────────────────────────\n\n /**\n * Run a navigation to completion: resolve (following declarative redirects),\n * middleware, history commit, terminal data loaders, scroll, and notification.\n * Declarative redirects reuse the active attempt and replace the final history\n * entry. Middleware redirects call `ctx.navigate()`, which starts a new attempt.\n */\n async #handleRoute(\n attempt: NavigationAttempt,\n url: string,\n historyState: unknown,\n commit: (location: RouteLocation, replace: boolean) => void,\n useTransition: boolean | undefined,\n replace: boolean,\n ): Promise<boolean> {\n const previousState = this.#currentState;\n const isCurrent = (): boolean => attempt.isCurrent() && !this.#disposed;\n const { decision: prepared, hopped } = await this.#resolveWithRedirects(url, historyState);\n\n if (!isCurrent()) return false;\n\n if (prepared.type === 'unmatched') {\n commit(prepared.location, replace || hopped);\n\n if (!isCurrent()) return false;\n\n this.#currentState = createRouteState({\n location: prepared.location,\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n\n return true;\n }\n\n const { branch, location, params, record, resolvedQuery } = prepared;\n const shouldReplace = replace || hopped;\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n let notified = false;\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, (target, options) =>\n this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...record.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(location, shouldReplace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(record, context, location, params, attempt.signal, isCurrent, (error) => {\n dataError = error;\n hasDataError = true;\n });\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: record.leaf.name, source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: record.leaf.name, source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n async #runWithTransition(run: () => Promise<void>, useTransition?: boolean): Promise<void> {\n if ((useTransition ?? this.#useViewTransition) && typeof document !== 'undefined') {\n const startViewTransition = (\n document as Document & {\n startViewTransition?: (callback: () => void | Promise<void>) => { finished: Promise<void> };\n }\n ).startViewTransition;\n\n if (startViewTransition) {\n await startViewTransition.call(document, run).finished;\n\n return;\n }\n }\n\n await run();\n }\n\n #applyScroll(to: RouteState, from: RouteState): void {\n if (!this.#scroll || typeof window === 'undefined') return;\n\n const decision = this.#scroll(to, from);\n\n if (decision === 'preserve') return;\n\n if (decision === 'top') {\n window.scrollTo(0, 0);\n\n return;\n }\n\n window.scrollTo(decision.x, decision.y);\n }\n\n // ─── Private: destination resolution ─────────────────────────────────────\n\n #resolveDestination(path: string): string {\n const parsed = new URL(path, 'http://localhost');\n const normalizedPath = stripBase(parsed.pathname, this.#base);\n\n return `${joinPaths(this.#base, normalizedPath)}${parsed.search}${parsed.hash}`;\n }\n\n #locationFromPath(path: string, historyState: unknown): RouteLocation {\n const parsed = new URL(this.#resolveDestination(path), 'http://localhost');\n\n return {\n hash: parsed.hash.replace(/^#/, ''),\n historyState,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n }\n\n #hrefForLocation(location: RouteLocation): string {\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(location.query)) {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, item);\n });\n else search.set(key, value);\n }\n\n const query = search.toString();\n const hash = location.hash ? `#${location.hash}` : '';\n\n return `${joinPaths(this.#base, location.pathname)}${query ? `?${query}` : ''}${hash}`;\n }\n\n #navigationDestination(href: string): NavigationDestination {\n const parsed = new URL(href, 'http://localhost');\n const pathname = stripBase(parsed.pathname, this.#base);\n const { params, record } = matchRouteFor(pathname, this.#records);\n\n return {\n name: record?.leaf.name,\n params,\n pathname,\n query: parseQuery(parsed.search),\n };\n }\n\n /** User-initiated navigation. History changes only after middleware reaches the terminal stage. */\n async #navigateToPath(path: string, options: NavigateOptions = {}): Promise<void> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(path);\n\n if (!options.force && destination === this.#lastHref) return;\n\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((match) => match.name);\n const allowed = await runLeaveBlockers(\n this.#beforeLeaveBlockers,\n activeMatchNames,\n this.#navigationDestination(destination),\n );\n\n if (!attempt.isCurrent() || !allowed) return;\n\n try {\n await this.#handleRoute(\n attempt,\n destination,\n options.state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n else this.#history.push(href, location.historyState);\n\n this.#lastHref = href;\n },\n options.viewTransition,\n options.replace ?? false,\n );\n } catch (value) {\n throw isRouterErrorCarrier(value) ? value.error : value;\n }\n }\n}\n\n// ─── Public factory ───────────────────────────────────────────────────────────\n\n/**\n * Create a new router instance from a route table.\n *\n * @example\n * const router = createRouter({\n * routes: {\n * home: { path: '/' },\n * userDetail: { path: '/users/:id', data: fetchUser },\n * },\n * });\n */\nexport function createRouter<const TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): Router<TRoutes> {\n return new Router(options);\n}\n\n// Export the Router type (not the constructor value) for type annotations.\nexport type { Router };\n"],"mappings":"A,kMAgDA,SAAS,eAAe,EAAc,EAA6D,CACjG,IAAMyB,EAAQC,EAAa,IAAIC,CAAI,EAEnC,GAAIF,EAAO,OAAOA,EAElB,IAAMG,EAAY,CAAC,GAAGF,EAAa,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,EAEpD,MAAM,IAAI1B,EAAAA,oBACR4B,EAAY,uBAAuBD,EAAK,sBAAsBC,IAAc,uBAAuBD,GACrG,CACF,CAEA,SAAS,cACP,EACA,EACA,EAAO,IACC,CACR,GAAI,SAAUE,EAAQ,OAAOA,EAAO,KAEpC,IAAMJ,EAAQ,eAAeI,EAAO,KAAMH,CAAY,EAChDI,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,KAAMiC,GAAQ,KAAK,KACnB,SACA,WACA,MAAO5D,EAAAA,WAAWoI,EAAO,MAAM,CACjC,CACF,CAGA,KAAM7E,GAAgB,EAAc,EAA2B,CAAC,EAAkB,CAChF,KAAKJ,GAAmB,EAExB,IAAMG,EAAc,KAAKoB,GAAoB7D,CAAI,EAEjD,GAAI,CAACM,EAAQ,OAASmC,IAAgB,KAAKf,GAAW,OAEtD,IAAMC,EAAU,KAAKC,GAAY,MAAM,EACjCqD,EAAmB,KAAKjE,GAAc,QAAQ,IAAK,GAAUqD,EAAM,IAAI,EACvEc,EAAU,MAAMpG,EAAAA,iBACpB,KAAK8F,GACLI,EACA,KAAKC,GAAuBzC,CAAW,CACzC,EAEA,GAAKd,EAAQ,UAAU,GAAMwD,EAE7B,GAAI,CACF,MAAM,KAAKrD,GACTH,EACAc,EACAnC,EAAQ,OACP,EAAU,IAAY,CACrB,GAAI,CAACqB,EAAQ,UAAU,EAAG,OAE1B,IAAMK,EAAO,KAAKC,GAAiBC,CAAQ,EAEvCC,EAAS,KAAKzB,GAAS,QAAQsB,EAAME,EAAS,YAAY,EACzD,KAAKxB,GAAS,KAAKsB,EAAME,EAAS,YAAY,EAEnD,KAAKR,GAAYM,CACnB,EACA1B,EAAQ,eACRA,EAAQ,SAAW,EACrB,CACF,OAASF,EAAO,CACd,MAAM,qBAAqBA,CAAK,EAAIA,EAAM,MAAQA,CACpD,CACF,CACF,EAeA,SAAgB,aAA+C,EAAkD,CAC/G,OAAO,IAAI,OAAOE,CAAO,CAC3B,C"}
|
package/dist/router.d.ts
CHANGED
|
@@ -44,9 +44,11 @@ declare class Router<TRoutes extends RouteTable = RouteTable> {
|
|
|
44
44
|
/** Match a pathname to a route branch without running middleware or data loaders. Returns null for redirects or no match. */
|
|
45
45
|
match(pathname: string): RouteMatchBranch | null;
|
|
46
46
|
/**
|
|
47
|
-
* Load a URL into a route state including data loader results,
|
|
48
|
-
* router state or history. Follows declarative redirects but
|
|
49
|
-
* Middleware is not executed: use `navigate()` when
|
|
47
|
+
* Load a router-internal URL into a route state including data loader results,
|
|
48
|
+
* without modifying router state or history. Follows declarative redirects but
|
|
49
|
+
* does not cache results. Middleware is not executed: use `navigate()` when
|
|
50
|
+
* middleware side effects are needed. An unmatched URL resolves to the
|
|
51
|
+
* `notFound` route when configured; otherwise `null` is returned.
|
|
50
52
|
*/
|
|
51
53
|
load(url: string, options?: {
|
|
52
54
|
signal?: AbortSignal;
|
package/dist/router.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,kBAAkB,EAClB,kBAAkB,EAKlB,eAAe,EAEf,qBAAqB,EACrB,eAAe,EAEf,UAAU,EACV,mBAAmB,EACnB,mBAAmB,EAInB,gBAAgB,EAChB,SAAS,EAET,eAAe,EAGf,aAAa,EACb,UAAU,EACV,UAAU,EACV,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,WAAW,EACZ,MAAM,SAAS,CAAC;AA+EjB,cAAM,MAAM,CAAC,OAAO,SAAS,UAAU,GAAG,UAAU;;IA0BlD,2FAA2F;IAC3F,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;gBAElB,OAAO,EAAE,aAAa,CAAC,OAAO,CAAC;IAyF3C;;;;;;;;;;OAUG;IACH,WAAW,IAAI,UAAU;IAIzB,kBAAkB,CAAC,KAAK,CAAC,MAAM,SAAS,YAAY,CAAC,OAAO,CAAC,EAAE,SAAS,GAAG,KAAK,EAC9E,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,MAAM,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,CAAC,EAC5E,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,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