@vielzeug/wayfinder 26.11.13 → 26.11.14
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 +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/query-state.cjs +2 -0
- package/dist/query-state.cjs.map +1 -0
- package/dist/query-state.d.ts +80 -0
- package/dist/query-state.d.ts.map +1 -0
- package/dist/query-state.js +90 -0
- package/dist/query-state.js.map +1 -0
- 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 +95 -11
- package/dist/wayfinder.js.map +1 -1
- package/package.json +2 -2
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("./route-signals.cjs"),
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./history.cjs"),n=require("./middleware.cjs"),r=require("./query-state.cjs"),i=require("./route-signals.cjs"),a=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.createQueryState=r.createQueryState,exports.createRouteSignals=i.createRouteSignals,exports.createRouter=a.createRouter,exports.param=r.param,exports.redirectTo=n.redirectTo;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
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 { ParamSpec, QueryState, QueryStateOptions, QueryStateSetOptions, QueryStateSpec, RawParamValue, } from './query-state';
|
|
5
|
+
export { createQueryState, param } from './query-state';
|
|
4
6
|
export type { RouteSignals } from './route-signals';
|
|
5
7
|
export { createRouteSignals } from './route-signals';
|
|
6
8
|
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,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"}
|
|
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,EACV,SAAS,EACT,UAAU,EACV,iBAAiB,EACjB,oBAAoB,EACpB,cAAc,EACd,aAAa,GACd,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACxD,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,6 +1,7 @@
|
|
|
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
|
-
|
|
4
|
+
import { createQueryState as d, param as f } from "./query-state.js";
|
|
5
|
+
import { createRouteSignals as p } from "./route-signals.js";
|
|
6
|
+
import { createRouter as m } from "./router.js";
|
|
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 createQueryState, p as createRouteSignals, m as createRouter, f as param, u as redirectTo };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./route-signals.cjs");let n=require("@vielzeug/ripple");var r=Object.freeze([]),first=e=>Array.isArray(e)?e[0]:e,i=Object.freeze({boolean(e=!1){return{decode:t=>{let n=first(t);return n===`1`||n===`true`?!0:n===`0`||n===`false`?!1:e},default:e,encode:t=>t===e?void 0:t?`1`:`0`}},list(){return{decode:e=>e===void 0?r:Array.isArray(e)?[...e]:[e],default:r,encode:e=>e.length===0?void 0:e.length===1?e[0]:[...e]}},number(e=0){return{decode:t=>{let n=first(t);if(n===void 0||n===``)return e;let r=Number(n);return Number.isFinite(r)?r:e},default:e,encode:t=>t===e||!Number.isFinite(t)?void 0:String(t)}},pick:((e,t)=>({decode:n=>{let r=first(n);return r!==void 0&&e.includes(r)?r:t},default:t,encode:e=>e===void 0||e===t?void 0:e})),string(e=``){return{decode:t=>first(t)??e,default:e,encode:t=>t===e?void 0:t}}});function createQueryState(r,i,a={}){let o=t.createRouteSignals(r),s=Object.keys(i),c={};for(let e of s){let t=i[e];c[e]=(0,n.computed)(()=>t.decode(o.query.value[e]))}let readAll=()=>{let e={};for(let t of s)e[t]=c[t]?.value;return e},write=(t,n)=>{for(let n of Object.keys(t))if(!Object.hasOwn(i,n))throw new e.WayfinderConfigError(`createQueryState: undeclared param "${n}"`);let o=r.getSnapshot().location,s={...o.query};for(let[e,n]of Object.entries(t)){let t=i[e].encode(n);t===void 0?delete s[e]:s[e]=t}let c=new URLSearchParams;for(let[e,t]of Object.entries(s))if(Array.isArray(t))for(let n of t)c.append(e,n);else c.set(e,t);let l=c.toString(),u=`${o.pathname}${l===``?``:`?${l}`}${o.hash===``?``:`#${o.hash}`}`,d={replace:!0};for(let e of[a,n])for(let[t,n]of Object.entries(e??{}))n!==void 0&&(d[t]=n);r.navigate(u,d).catch(()=>{})};return{params:c,query:(0,n.computed)(readAll),reset:e=>{let t={};for(let e of s)t[e]=i[e].default;write(t,e)},set:(e,t)=>{write(e,t)}}}exports.createQueryState=createQueryState,exports.param=i;
|
|
2
|
+
//# sourceMappingURL=query-state.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.cjs","names":["createRouteSignals","computed","WayfinderConfigError","require_errors","require_route_signals","_vielzeug_ripple","EMPTY_LIST","raw","param","value","defaultValue","parsed","values","routeSignals","router","keys","spec","params","key","definition","out","patch","location","next","search","item","query","href","navigation","source","options","opts","defaults"],"sources":["../src/query-state.ts"],"sourcesContent":["import { computed, type Readable } from '@vielzeug/ripple';\nimport { WayfinderConfigError } from './errors';\nimport { createRouteSignals } from './route-signals';\nimport type { Router } from './router';\nimport type { NavigateOptions, RouteTable } from './types';\n\n/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */\nexport type RawParamValue = string | string[] | undefined;\n\n/** One URL query parameter: a default that equals \"absent\", plus lenient decode/encode. */\nexport type ParamSpec<T> = {\n /** Missing or malformed input always decodes to `default` — the URL is untrusted. */\n decode(raw: string | string[] | undefined): T;\n /** Returning `undefined` (the value equals the default) removes the parameter. */\n encode(value: T): RawParamValue;\n readonly default: T;\n};\n\nconst EMPTY_LIST: readonly string[] = Object.freeze([]);\n\nconst first = (raw: string | string[] | undefined): string | undefined => (Array.isArray(raw) ? raw[0] : raw);\n\n/** The built-in parameter codecs; a codec's default is always the param-absent state. */\nexport interface PickParam {\n /** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;\n /** Absent or unknown values decode to `defaultValue` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;\n}\n\nexport const param = Object.freeze({\n boolean(defaultValue = false): ParamSpec<boolean> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === '1' || value === 'true') return true;\n if (value === '0' || value === 'false') return false;\n return defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value ? '1' : '0'),\n };\n },\n list(): ParamSpec<readonly string[]> {\n return {\n decode: (raw) => (raw === undefined ? EMPTY_LIST : Array.isArray(raw) ? [...raw] : [raw]),\n default: EMPTY_LIST,\n encode: (value) => (value.length === 0 ? undefined : value.length === 1 ? value[0] : [...value]),\n };\n },\n number(defaultValue = 0): ParamSpec<number> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === undefined || value === '') return defaultValue;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue || !Number.isFinite(value) ? undefined : String(value)),\n };\n },\n pick: ((values: readonly string[], defaultValue?: string) => ({\n decode: (raw: string | string[] | undefined) => {\n const value = first(raw);\n return value !== undefined && values.includes(value) ? value : defaultValue;\n },\n default: defaultValue,\n encode: (value: string | undefined) => (value === undefined || value === defaultValue ? undefined : value),\n })) as PickParam,\n string(defaultValue = ''): ParamSpec<string> {\n return {\n decode: (raw) => first(raw) ?? defaultValue,\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value),\n };\n },\n});\n\nexport type QueryStateSpec = { readonly [key: string]: ParamSpec<unknown> };\n\ntype SpecValue<S extends QueryStateSpec> = { [K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never };\n\nexport type QueryStateOptions = NavigateOptions;\n\n/** Per-write overrides of the state-level navigation options. */\nexport type QueryStateSetOptions = NavigateOptions;\n\n/**\n * Navigation options accepted by a write: the router's own `NavigateOptions`, with\n * `replace` defaulted to `true` because a query-parameter edit is a revision of the\n * current view, not a new page. Any other option (`viewTransition`, `force`, `state`)\n * is forwarded untouched, so a page whose router animates route changes can still\n * suppress the transition for a filter edit.\n */\n\nexport type QueryState<S extends QueryStateSpec> = {\n /** Reactive value per declared parameter. */\n readonly params: { readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never> };\n /** Reactive snapshot of every declared parameter at once. */\n readonly query: Readable<SpecValue<S>>;\n /** Declared parameters removed from the URL (their defaults restored) in one navigation. */\n reset(options?: QueryStateSetOptions): void;\n /** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */\n set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;\n};\n\n/**\n * Reactive, typed bindings between ripple state and the URL query string.\n *\n * Reads are derived from the router's live location, so back/forward and external\n * `navigate()` calls update them automatically. Writes merge into the *current* query —\n * undeclared parameters, the path, and the hash survive untouched — and land as a single\n * (replace by default) navigation through the router, so history mode, base path,\n * middleware, and guards keep working. A parameter written back to its default is removed\n * from the URL. Decoding is lenient: a malformed URL value falls back to the default\n * instead of throwing, because query strings are untrusted input.\n *\n * ```ts\n * const filters = createQueryState(router, {\n * page: param.number(1),\n * sort: param.pick(['price', 'name'] as const, 'price'),\n * tags: param.list(),\n * });\n *\n * filters.page.value; // reactive number, `1` when ?page is absent\n * filters.set({ page: 2 }); // ?page=2, replace, other params preserved\n * ```\n */\nexport function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(\n router: Router<TRoutes>,\n spec: S,\n options: QueryStateOptions = {},\n): QueryState<S> {\n const routeSignals = createRouteSignals(router);\n const keys = Object.keys(spec);\n\n const params: Record<string, Readable<unknown>> = {};\n for (const key of keys) {\n const definition = spec[key] as ParamSpec<unknown>;\n params[key] = computed(() => definition.decode(routeSignals.query.value[key]));\n }\n\n const readAll = (): SpecValue<S> => {\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = params[key]?.value;\n return out as SpecValue<S>;\n };\n\n const write = (patch: Partial<SpecValue<S>>, opts: QueryStateSetOptions | undefined): void => {\n for (const key of Object.keys(patch)) {\n if (!Object.hasOwn(spec, key)) throw new WayfinderConfigError(`createQueryState: undeclared param \"${key}\"`);\n }\n const location = router.getSnapshot().location;\n const next: Record<string, string | string[]> = { ...location.query };\n for (const [key, value] of Object.entries(patch)) {\n const raw = (spec[key] as ParamSpec<unknown>).encode(value);\n if (raw === undefined) delete next[key];\n else next[key] = raw;\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(next)) {\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, value);\n }\n const query = search.toString();\n const href = `${location.pathname}${query === '' ? '' : `?${query}`}${location.hash === '' ? '' : `#${location.hash}`}`;\n\n // Fire-and-forget for UI handlers: loader failures still surface through the router's\n // onError/status channels, so the floating promise is deliberately swallowed here.\n const navigation: NavigateOptions = { replace: true };\n for (const source of [options, opts]) {\n for (const [key, value] of Object.entries(source ?? {})) {\n if (value !== undefined) (navigation as Record<string, unknown>)[key] = value;\n }\n }\n\n router.navigate(href, navigation).catch(() => {});\n };\n\n return {\n params: params as unknown as QueryState<S>['params'],\n query: computed(readAll),\n reset: (opts) => {\n const defaults: Partial<SpecValue<S>> = {};\n for (const key of keys) (defaults as Record<string, unknown>)[key] = spec[key].default;\n write(defaults, opts);\n },\n set: (patch, opts) => {\n write(patch, opts);\n },\n };\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type Readable } from '@vielzeug/ripple';
|
|
2
|
+
import type { Router } from './router';
|
|
3
|
+
import type { NavigateOptions, RouteTable } from './types';
|
|
4
|
+
/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */
|
|
5
|
+
export type RawParamValue = string | string[] | undefined;
|
|
6
|
+
/** One URL query parameter: a default that equals "absent", plus lenient decode/encode. */
|
|
7
|
+
export type ParamSpec<T> = {
|
|
8
|
+
/** Missing or malformed input always decodes to `default` — the URL is untrusted. */
|
|
9
|
+
decode(raw: string | string[] | undefined): T;
|
|
10
|
+
/** Returning `undefined` (the value equals the default) removes the parameter. */
|
|
11
|
+
encode(value: T): RawParamValue;
|
|
12
|
+
readonly default: T;
|
|
13
|
+
};
|
|
14
|
+
/** The built-in parameter codecs; a codec's default is always the param-absent state. */
|
|
15
|
+
export interface PickParam {
|
|
16
|
+
/** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */
|
|
17
|
+
<const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;
|
|
18
|
+
/** Absent or unknown values decode to `defaultValue` (and are omitted when written). */
|
|
19
|
+
<const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;
|
|
20
|
+
}
|
|
21
|
+
export declare const param: Readonly<{
|
|
22
|
+
boolean(defaultValue?: boolean): ParamSpec<boolean>;
|
|
23
|
+
list(): ParamSpec<readonly string[]>;
|
|
24
|
+
number(defaultValue?: number): ParamSpec<number>;
|
|
25
|
+
pick: PickParam;
|
|
26
|
+
string(defaultValue?: string): ParamSpec<string>;
|
|
27
|
+
}>;
|
|
28
|
+
export type QueryStateSpec = {
|
|
29
|
+
readonly [key: string]: ParamSpec<unknown>;
|
|
30
|
+
};
|
|
31
|
+
type SpecValue<S extends QueryStateSpec> = {
|
|
32
|
+
[K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never;
|
|
33
|
+
};
|
|
34
|
+
export type QueryStateOptions = NavigateOptions;
|
|
35
|
+
/** Per-write overrides of the state-level navigation options. */
|
|
36
|
+
export type QueryStateSetOptions = NavigateOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Navigation options accepted by a write: the router's own `NavigateOptions`, with
|
|
39
|
+
* `replace` defaulted to `true` because a query-parameter edit is a revision of the
|
|
40
|
+
* current view, not a new page. Any other option (`viewTransition`, `force`, `state`)
|
|
41
|
+
* is forwarded untouched, so a page whose router animates route changes can still
|
|
42
|
+
* suppress the transition for a filter edit.
|
|
43
|
+
*/
|
|
44
|
+
export type QueryState<S extends QueryStateSpec> = {
|
|
45
|
+
/** Reactive value per declared parameter. */
|
|
46
|
+
readonly params: {
|
|
47
|
+
readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never>;
|
|
48
|
+
};
|
|
49
|
+
/** Reactive snapshot of every declared parameter at once. */
|
|
50
|
+
readonly query: Readable<SpecValue<S>>;
|
|
51
|
+
/** Declared parameters removed from the URL (their defaults restored) in one navigation. */
|
|
52
|
+
reset(options?: QueryStateSetOptions): void;
|
|
53
|
+
/** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */
|
|
54
|
+
set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Reactive, typed bindings between ripple state and the URL query string.
|
|
58
|
+
*
|
|
59
|
+
* Reads are derived from the router's live location, so back/forward and external
|
|
60
|
+
* `navigate()` calls update them automatically. Writes merge into the *current* query —
|
|
61
|
+
* undeclared parameters, the path, and the hash survive untouched — and land as a single
|
|
62
|
+
* (replace by default) navigation through the router, so history mode, base path,
|
|
63
|
+
* middleware, and guards keep working. A parameter written back to its default is removed
|
|
64
|
+
* from the URL. Decoding is lenient: a malformed URL value falls back to the default
|
|
65
|
+
* instead of throwing, because query strings are untrusted input.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* const filters = createQueryState(router, {
|
|
69
|
+
* page: param.number(1),
|
|
70
|
+
* sort: param.pick(['price', 'name'] as const, 'price'),
|
|
71
|
+
* tags: param.list(),
|
|
72
|
+
* });
|
|
73
|
+
*
|
|
74
|
+
* filters.page.value; // reactive number, `1` when ?page is absent
|
|
75
|
+
* filters.set({ page: 2 }); // ?page=2, replace, other params preserved
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(router: Router<TRoutes>, spec: S, options?: QueryStateOptions): QueryState<S>;
|
|
79
|
+
export {};
|
|
80
|
+
//# sourceMappingURL=query-state.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.d.ts","sourceRoot":"","sources":["../src/query-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAG3D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE3D,2FAA2F;AAC3F,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AAE1D,2FAA2F;AAC3F,MAAM,MAAM,SAAS,CAAC,CAAC,IAAI;IACzB,qFAAqF;IACrF,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,GAAG,CAAC,CAAC;IAC9C,kFAAkF;IAClF,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,aAAa,CAAC;IAChC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC;CACrB,CAAC;AAMF,yFAAyF;AACzF,MAAM,WAAW,SAAS;IACxB,wGAAwG;IACxG,CAAC,KAAK,CAAC,MAAM,SAAS,SAAS,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,CAAC;IAChG,wFAAwF;IACxF,CAAC,KAAK,CAAC,MAAM,SAAS,SAAS,MAAM,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;CACnH;AAED,eAAO,MAAM,KAAK;qCACe,SAAS,CAAC,OAAO,CAAC;YAYzC,SAAS,CAAC,SAAS,MAAM,EAAE,CAAC;mCAOV,SAAS,CAAC,MAAM,CAAC;UAmBpC,SAAS;mCACW,SAAS,CAAC,MAAM,CAAC;EAO5C,CAAC;AAEH,MAAM,MAAM,cAAc,GAAG;IAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,SAAS,CAAC,OAAO,CAAC,CAAA;CAAE,CAAC;AAE5E,KAAK,SAAS,CAAC,CAAC,SAAS,cAAc,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK;CAAE,CAAC;AAE3G,MAAM,MAAM,iBAAiB,GAAG,eAAe,CAAC;AAEhD,iEAAiE;AACjE,MAAM,MAAM,oBAAoB,GAAG,eAAe,CAAC;AAEnD;;;;;;GAMG;AAEH,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,cAAc,IAAI;IACjD,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,CAAC,IAAI,MAAM,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;KAAE,CAAC;IACpG,6DAA6D;IAC7D,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACvC,4FAA4F;IAC5F,KAAK,CAAC,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAAC;IAC5C,gGAAgG;IAChG,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,IAAI,CAAC;CACzE,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,SAAS,UAAU,EACnF,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,EACvB,IAAI,EAAE,CAAC,EACP,OAAO,GAAE,iBAAsB,GAC9B,UAAU,CAAC,CAAC,CAAC,CA4Df"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { WayfinderConfigError as e } from "./errors.js";
|
|
2
|
+
import { createRouteSignals as t } from "./route-signals.js";
|
|
3
|
+
import { computed as n } from "@vielzeug/ripple";
|
|
4
|
+
// src/query-state.ts
|
|
5
|
+
var r = Object.freeze([]), first = (e) => Array.isArray(e) ? e[0] : e, i = Object.freeze({
|
|
6
|
+
boolean(e = !1) {
|
|
7
|
+
return {
|
|
8
|
+
decode: (t) => {
|
|
9
|
+
let n = first(t);
|
|
10
|
+
return n === "1" || n === "true" ? !0 : n === "0" || n === "false" ? !1 : e;
|
|
11
|
+
},
|
|
12
|
+
default: e,
|
|
13
|
+
encode: (t) => t === e ? void 0 : t ? "1" : "0"
|
|
14
|
+
};
|
|
15
|
+
},
|
|
16
|
+
list() {
|
|
17
|
+
return {
|
|
18
|
+
decode: (e) => e === void 0 ? r : Array.isArray(e) ? [...e] : [e],
|
|
19
|
+
default: r,
|
|
20
|
+
encode: (e) => e.length === 0 ? void 0 : e.length === 1 ? e[0] : [...e]
|
|
21
|
+
};
|
|
22
|
+
},
|
|
23
|
+
number(e = 0) {
|
|
24
|
+
return {
|
|
25
|
+
decode: (t) => {
|
|
26
|
+
let n = first(t);
|
|
27
|
+
if (n === void 0 || n === "") return e;
|
|
28
|
+
let r = Number(n);
|
|
29
|
+
return Number.isFinite(r) ? r : e;
|
|
30
|
+
},
|
|
31
|
+
default: e,
|
|
32
|
+
encode: (t) => t === e || !Number.isFinite(t) ? void 0 : String(t)
|
|
33
|
+
};
|
|
34
|
+
},
|
|
35
|
+
pick: ((e, t) => ({
|
|
36
|
+
decode: (n) => {
|
|
37
|
+
let r = first(n);
|
|
38
|
+
return r !== void 0 && e.includes(r) ? r : t;
|
|
39
|
+
},
|
|
40
|
+
default: t,
|
|
41
|
+
encode: (e) => e === void 0 || e === t ? void 0 : e
|
|
42
|
+
})),
|
|
43
|
+
string(e = "") {
|
|
44
|
+
return {
|
|
45
|
+
decode: (t) => first(t) ?? e,
|
|
46
|
+
default: e,
|
|
47
|
+
encode: (t) => t === e ? void 0 : t
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
function createQueryState(r, i, a = {}) {
|
|
52
|
+
let o = t(r), s = Object.keys(i), c = {};
|
|
53
|
+
for (let e of s) {
|
|
54
|
+
let t = i[e];
|
|
55
|
+
c[e] = n(() => t.decode(o.query.value[e]));
|
|
56
|
+
}
|
|
57
|
+
let readAll = () => {
|
|
58
|
+
let e = {};
|
|
59
|
+
for (let t of s) e[t] = c[t]?.value;
|
|
60
|
+
return e;
|
|
61
|
+
}, write = (t, n) => {
|
|
62
|
+
for (let n of Object.keys(t)) if (!Object.hasOwn(i, n)) throw new e(`createQueryState: undeclared param "${n}"`);
|
|
63
|
+
let o = r.getSnapshot().location, s = { ...o.query };
|
|
64
|
+
for (let [e, n] of Object.entries(t)) {
|
|
65
|
+
let t = i[e].encode(n);
|
|
66
|
+
t === void 0 ? delete s[e] : s[e] = t;
|
|
67
|
+
}
|
|
68
|
+
let c = new URLSearchParams();
|
|
69
|
+
for (let [e, t] of Object.entries(s)) if (Array.isArray(t)) for (let n of t) c.append(e, n);
|
|
70
|
+
else c.set(e, t);
|
|
71
|
+
let l = c.toString(), u = `${o.pathname}${l === "" ? "" : `?${l}`}${o.hash === "" ? "" : `#${o.hash}`}`, d = { replace: !0 };
|
|
72
|
+
for (let e of [a, n]) for (let [t, n] of Object.entries(e ?? {})) n !== void 0 && (d[t] = n);
|
|
73
|
+
r.navigate(u, d).catch(() => {});
|
|
74
|
+
};
|
|
75
|
+
return {
|
|
76
|
+
params: c,
|
|
77
|
+
query: n(readAll),
|
|
78
|
+
reset: (e) => {
|
|
79
|
+
let t = {};
|
|
80
|
+
for (let e of s) t[e] = i[e].default;
|
|
81
|
+
write(t, e);
|
|
82
|
+
},
|
|
83
|
+
set: (e, t) => {
|
|
84
|
+
write(e, t);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export { createQueryState, i as param };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=query-state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"query-state.js","names":["EMPTY_LIST","raw","param","value","defaultValue","parsed","values","routeSignals","createRouteSignals","router","keys","spec","params","key","definition","computed","out","patch","WayfinderConfigError","location","next","search","item","query","href","navigation","source","options","opts","defaults"],"sources":["../src/query-state.ts"],"sourcesContent":["import { computed, type Readable } from '@vielzeug/ripple';\nimport { WayfinderConfigError } from './errors';\nimport { createRouteSignals } from './route-signals';\nimport type { Router } from './router';\nimport type { NavigateOptions, RouteTable } from './types';\n\n/** Encode result: a raw query value, or `undefined` to omit the parameter from the URL. */\nexport type RawParamValue = string | string[] | undefined;\n\n/** One URL query parameter: a default that equals \"absent\", plus lenient decode/encode. */\nexport type ParamSpec<T> = {\n /** Missing or malformed input always decodes to `default` — the URL is untrusted. */\n decode(raw: string | string[] | undefined): T;\n /** Returning `undefined` (the value equals the default) removes the parameter. */\n encode(value: T): RawParamValue;\n readonly default: T;\n};\n\nconst EMPTY_LIST: readonly string[] = Object.freeze([]);\n\nconst first = (raw: string | string[] | undefined): string | undefined => (Array.isArray(raw) ? raw[0] : raw);\n\n/** The built-in parameter codecs; a codec's default is always the param-absent state. */\nexport interface PickParam {\n /** Without a default, absent or unknown values decode to `undefined` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values): ParamSpec<Values[number] | undefined>;\n /** Absent or unknown values decode to `defaultValue` (and are omitted when written). */\n <const Values extends readonly string[]>(values: Values, defaultValue: Values[number]): ParamSpec<Values[number]>;\n}\n\nexport const param = Object.freeze({\n boolean(defaultValue = false): ParamSpec<boolean> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === '1' || value === 'true') return true;\n if (value === '0' || value === 'false') return false;\n return defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value ? '1' : '0'),\n };\n },\n list(): ParamSpec<readonly string[]> {\n return {\n decode: (raw) => (raw === undefined ? EMPTY_LIST : Array.isArray(raw) ? [...raw] : [raw]),\n default: EMPTY_LIST,\n encode: (value) => (value.length === 0 ? undefined : value.length === 1 ? value[0] : [...value]),\n };\n },\n number(defaultValue = 0): ParamSpec<number> {\n return {\n decode: (raw) => {\n const value = first(raw);\n if (value === undefined || value === '') return defaultValue;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : defaultValue;\n },\n default: defaultValue,\n encode: (value) => (value === defaultValue || !Number.isFinite(value) ? undefined : String(value)),\n };\n },\n pick: ((values: readonly string[], defaultValue?: string) => ({\n decode: (raw: string | string[] | undefined) => {\n const value = first(raw);\n return value !== undefined && values.includes(value) ? value : defaultValue;\n },\n default: defaultValue,\n encode: (value: string | undefined) => (value === undefined || value === defaultValue ? undefined : value),\n })) as PickParam,\n string(defaultValue = ''): ParamSpec<string> {\n return {\n decode: (raw) => first(raw) ?? defaultValue,\n default: defaultValue,\n encode: (value) => (value === defaultValue ? undefined : value),\n };\n },\n});\n\nexport type QueryStateSpec = { readonly [key: string]: ParamSpec<unknown> };\n\ntype SpecValue<S extends QueryStateSpec> = { [K in keyof S]: S[K] extends ParamSpec<infer T> ? T : never };\n\nexport type QueryStateOptions = NavigateOptions;\n\n/** Per-write overrides of the state-level navigation options. */\nexport type QueryStateSetOptions = NavigateOptions;\n\n/**\n * Navigation options accepted by a write: the router's own `NavigateOptions`, with\n * `replace` defaulted to `true` because a query-parameter edit is a revision of the\n * current view, not a new page. Any other option (`viewTransition`, `force`, `state`)\n * is forwarded untouched, so a page whose router animates route changes can still\n * suppress the transition for a filter edit.\n */\n\nexport type QueryState<S extends QueryStateSpec> = {\n /** Reactive value per declared parameter. */\n readonly params: { readonly [K in keyof S]: Readable<S[K] extends ParamSpec<infer T> ? T : never> };\n /** Reactive snapshot of every declared parameter at once. */\n readonly query: Readable<SpecValue<S>>;\n /** Declared parameters removed from the URL (their defaults restored) in one navigation. */\n reset(options?: QueryStateSetOptions): void;\n /** Typed partial update of declared parameters; unknown keys throw. One navigation per call. */\n set(patch: Partial<SpecValue<S>>, options?: QueryStateSetOptions): void;\n};\n\n/**\n * Reactive, typed bindings between ripple state and the URL query string.\n *\n * Reads are derived from the router's live location, so back/forward and external\n * `navigate()` calls update them automatically. Writes merge into the *current* query —\n * undeclared parameters, the path, and the hash survive untouched — and land as a single\n * (replace by default) navigation through the router, so history mode, base path,\n * middleware, and guards keep working. A parameter written back to its default is removed\n * from the URL. Decoding is lenient: a malformed URL value falls back to the default\n * instead of throwing, because query strings are untrusted input.\n *\n * ```ts\n * const filters = createQueryState(router, {\n * page: param.number(1),\n * sort: param.pick(['price', 'name'] as const, 'price'),\n * tags: param.list(),\n * });\n *\n * filters.page.value; // reactive number, `1` when ?page is absent\n * filters.set({ page: 2 }); // ?page=2, replace, other params preserved\n * ```\n */\nexport function createQueryState<S extends QueryStateSpec, TRoutes extends RouteTable>(\n router: Router<TRoutes>,\n spec: S,\n options: QueryStateOptions = {},\n): QueryState<S> {\n const routeSignals = createRouteSignals(router);\n const keys = Object.keys(spec);\n\n const params: Record<string, Readable<unknown>> = {};\n for (const key of keys) {\n const definition = spec[key] as ParamSpec<unknown>;\n params[key] = computed(() => definition.decode(routeSignals.query.value[key]));\n }\n\n const readAll = (): SpecValue<S> => {\n const out: Record<string, unknown> = {};\n for (const key of keys) out[key] = params[key]?.value;\n return out as SpecValue<S>;\n };\n\n const write = (patch: Partial<SpecValue<S>>, opts: QueryStateSetOptions | undefined): void => {\n for (const key of Object.keys(patch)) {\n if (!Object.hasOwn(spec, key)) throw new WayfinderConfigError(`createQueryState: undeclared param \"${key}\"`);\n }\n const location = router.getSnapshot().location;\n const next: Record<string, string | string[]> = { ...location.query };\n for (const [key, value] of Object.entries(patch)) {\n const raw = (spec[key] as ParamSpec<unknown>).encode(value);\n if (raw === undefined) delete next[key];\n else next[key] = raw;\n }\n\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(next)) {\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, value);\n }\n const query = search.toString();\n const href = `${location.pathname}${query === '' ? '' : `?${query}`}${location.hash === '' ? '' : `#${location.hash}`}`;\n\n // Fire-and-forget for UI handlers: loader failures still surface through the router's\n // onError/status channels, so the floating promise is deliberately swallowed here.\n const navigation: NavigateOptions = { replace: true };\n for (const source of [options, opts]) {\n for (const [key, value] of Object.entries(source ?? {})) {\n if (value !== undefined) (navigation as Record<string, unknown>)[key] = value;\n }\n }\n\n router.navigate(href, navigation).catch(() => {});\n };\n\n return {\n params: params as unknown as QueryState<S>['params'],\n query: computed(readAll),\n reset: (opts) => {\n const defaults: Partial<SpecValue<S>> = {};\n for (const key of keys) (defaults as Record<string, unknown>)[key] = spec[key].default;\n write(defaults, opts);\n },\n set: (patch, opts) => {\n write(patch, opts);\n },\n };\n}\n"],"mappings":";;;;AAkBA,IAAMA,IAAgC,OAAO,OAAO,CAAC,CAAC,GAEhD,SAAS,MAA4D,MAAM,QAAQC,CAAG,IAAIA,EAAI,KAAKA,GAU5FC,IAAQ,OAAO,OAAO;CACjC,QAAQ,IAAe,IAA2B;EAChD,OAAO;GACL,SAAS,MAAQ;IACf,IAAMC,IAAQ,MAAMF,CAAG;IAGvB,OAFIE,MAAU,OAAOA,MAAU,SAAe,KAC1CA,MAAU,OAAOA,MAAU,UAAgB,KACxCC;GACT;GACA,SAASA;GACT,SAAS,MAAWD,MAAUC,IAAe,KAAA,IAAYD,IAAQ,MAAM;EACzE;CACF;CACA,OAAqC;EACnC,OAAO;GACL,SAAS,MAASF,MAAQ,KAAA,IAAYD,IAAa,MAAM,QAAQC,CAAG,IAAI,CAAC,GAAGA,CAAG,IAAI,CAACA,CAAG;GACvF,SAASD;GACT,SAAS,MAAWG,EAAM,WAAW,IAAI,KAAA,IAAYA,EAAM,WAAW,IAAIA,EAAM,KAAK,CAAC,GAAGA,CAAK;EAChG;CACF;CACA,OAAO,IAAe,GAAsB;EAC1C,OAAO;GACL,SAAS,MAAQ;IACf,IAAMA,IAAQ,MAAMF,CAAG;IACvB,IAAIE,MAAU,KAAA,KAAaA,MAAU,IAAI,OAAOC;IAChD,IAAMC,IAAS,OAAOF,CAAK;IAC3B,OAAO,OAAO,SAASE,CAAM,IAAIA,IAASD;GAC5C;GACA,SAASA;GACT,SAAS,MAAWD,MAAUC,KAAgB,CAAC,OAAO,SAASD,CAAK,IAAI,KAAA,IAAY,OAAOA,CAAK;EAClG;CACF;CACA,QAAQ,GAA2B,OAA2B;EAC5D,SAAS,MAAuC;GAC9C,IAAMA,IAAQ,MAAMF,CAAG;GACvB,OAAOE,MAAU,KAAA,KAAaG,EAAO,SAASH,CAAK,IAAIA,IAAQC;EACjE;EACA,SAASA;EACT,SAAS,MAA+BD,MAAU,KAAA,KAAaA,MAAUC,IAAe,KAAA,IAAYD;CACtG;CACA,OAAO,IAAe,IAAuB;EAC3C,OAAO;GACL,SAAS,MAAQ,MAAMF,CAAG,KAAKG;GAC/B,SAASA;GACT,SAAS,MAAWD,MAAUC,IAAe,KAAA,IAAYD;EAC3D;CACF;AACF,CAAC;AAoDD,SAAgB,iBACd,GACA,GACA,IAA6B,CAAC,GACf;CACf,IAAMI,IAAeC,EAAmBC,CAAM,GACxCC,IAAO,OAAO,KAAKC,CAAI,GAEvBC,IAA4C,CAAC;CACnD,KAAK,IAAMC,KAAOH,GAAM;EACtB,IAAMI,IAAaH,EAAKE;EACxB,EAAOA,KAAOE,QAAeD,EAAW,OAAOP,EAAa,MAAM,MAAMM,EAAI,CAAC;CAC/E;CAEA,IAAM,gBAA8B;EAClC,IAAMG,IAA+B,CAAC;EACtC,KAAK,IAAMH,KAAOH,GAAM,EAAIG,KAAOD,EAAOC,EAAI,EAAE;EAChD,OAAOG;CACT,GAEM,SAAS,GAA8B,MAAiD;EAC5F,KAAK,IAAMH,KAAO,OAAO,KAAKI,CAAK,GACjC,IAAI,CAAC,OAAO,OAAON,GAAME,CAAG,GAAG,MAAM,IAAIK,EAAqB,uCAAuCL,EAAI,EAAE;EAE7G,IAAMM,IAAWV,EAAO,YAAY,CAAC,CAAC,UAChCW,IAA0C,EAAE,GAAGD,EAAS,MAAM;EACpE,KAAK,IAAM,CAACN,GAAKV,MAAU,OAAO,QAAQc,CAAK,GAAG;GAChD,IAAMhB,IAAOU,EAAKE,EAAI,CAAwB,OAAOV,CAAK;GAC1D,AAAIF,MAAQ,KAAA,IAAW,OAAOmB,EAAKP,KAC9B,EAAKA,KAAOZ;EACnB;EAEA,IAAMoB,IAAS,IAAI,gBAAgB;EACnC,KAAK,IAAM,CAACR,GAAKV,MAAU,OAAO,QAAQiB,CAAI,GAC5C,IAAI,MAAM,QAAQjB,CAAK,GAAG,KAAK,IAAMmB,KAAQnB,GAAO,EAAO,OAAOU,GAAKS,CAAI;OACtE,EAAO,IAAIT,GAAKV,CAAK;EAE5B,IAAMoB,IAAQF,EAAO,SAAS,GACxBG,IAAO,GAAGL,EAAS,WAAWI,MAAU,KAAK,KAAK,IAAIA,MAAUJ,EAAS,SAAS,KAAK,KAAK,IAAIA,EAAS,UAIzGM,IAA8B,EAAE,SAAS,GAAK;EACpD,KAAK,IAAMC,KAAU,CAACC,GAASC,CAAI,GACjC,KAAK,IAAM,CAACf,GAAKV,MAAU,OAAO,QAAQuB,KAAU,CAAC,CAAC,GACpD,AAAIvB,MAAU,KAAA,MAAW,EAAwCU,KAAOV;EAI5E,EAAO,SAASqB,GAAMC,CAAU,CAAC,CAAC,YAAY,CAAC,CAAC;CAClD;CAEA,OAAO;EACG;EACR,OAAOV,EAAS,OAAO;EACvB,QAAQ,MAAS;GACf,IAAMc,IAAkC,CAAC;GACzC,KAAK,IAAMhB,KAAOH,GAAM,EAAsCG,KAAOF,EAAKE,EAAI,CAAC;GAC/E,MAAMgB,GAAUD,CAAI;EACtB;EACA,MAAM,GAAO,MAAS;GACpB,MAAMX,GAAOW,CAAI;EACnB;CACF;AACF"}
|
package/dist/wayfinder.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");var WayfinderError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},WayfinderDisposedError=class extends WayfinderError{constructor(){super(`Router is disposed`)}},WayfinderConfigError=class extends WayfinderError{},WayfinderRouteError=class extends WayfinderError{},WayfinderRedirectLoopError=class extends WayfinderError{constructor(){super(`Redirect loop detected`)}},WayfinderApiError=class extends WayfinderError{};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(e){let t=normalizePath(e);if(t===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let n=[],r=t.slice(1).split(`/`),i=[`^`],a=[`^`];for(let t=0;t<r.length;t+=1){let o=r[t];if(o===`*`){if(t!==r.length-1)throw new WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${e}`);i.push(`(?:/.*)?`);break}if(o.startsWith(`:`)&&o.endsWith(`*`)){if(t!==r.length-1)throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${e}`);let s=o.slice(1,-1);if(!/^\w+$/.test(s))throw new WayfinderConfigError(`Invalid param name ":${s}" in path "${e}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);n.push(s),i.push(t===r.length-1?`(?:/(.*))?`:`/(.*)`),a.push(`/.*`);break}if(o.startsWith(`:`)){let t=o.slice(1);if(!/^\w+$/.test(t))throw new WayfinderConfigError(`Invalid param name ":${t}" in path "${e}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);n.push(t),i.push(`/([^/]+)`),a.push(`/[^/]+`);continue}let s=escapeRegex(o);i.push(`/${s}`),a.push(`/${s}`)}return i.push(`$`),a.push(`(?:/.*)?$`),{paramNames:n,pattern:new RegExp(i.join(``)),prefixPattern:new RegExp(a.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(e,t,n={},r){let i=t.replace(/:(\w+)(\*)?/g,(e,t,r)=>{let i=n[t];if(i==null)throw new WayfinderRouteError(`Missing path param: ${t}`);return r?i.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(i)});if(r&&Object.keys(r).length){let e=new URLSearchParams;Object.entries(r).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),i+=`?${e.toString()}`}return joinPaths(e,i)}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}function createBrowserHistory(){return{back(){window.history.back()},get location(){return{hash:window.location.hash,pathname:window.location.pathname,search:window.location.search,state:window.history.state}},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,e)},replace(e,t){window.history.replaceState(t,``,e)}}}function createHashHistory(e={}){let t=normalizePath(e.base??`/`),n=t===`/`?`/`:`${t}/`,location=()=>{let e=new URL(window.location.hash.slice(1)||`/`,`http://localhost`);return{hash:e.hash,pathname:joinPaths(t,e.pathname),search:e.search,state:window.history.state}},destination=e=>{let r=new URL(e,`http://localhost`),i=stripBase(r.pathname,t);return`${n}#${i}${r.search}${r.hash}`};return{back(){window.history.back()},href:destination,get location(){return location()},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,destination(e))},replace(e,t){window.history.replaceState(t,``,destination(e))}}}function createHistoryForBase(e){return e===`/`?createBrowserHistory():createHashHistory({base:e})}function createMemoryHistory(e=`/`){let t=new URL(e,`http://localhost`),n=[{hash:t.hash,pathname:t.pathname,search:t.search,state:null}],r=0,i=new Set;return{back(){r<=0||(--r,i.forEach(e=>{e()}))},get location(){return n[r]},onPopstate(e){return i.add(e),()=>i.delete(e)},push(e,t=null){let i=new URL(e,`http://localhost`);n.splice(r+1),n.push({hash:i.hash,pathname:i.pathname,search:i.search,state:t}),r=n.length-1},replace(e,t=null){let i=new URL(e,`http://localhost`);n[r]={hash:i.hash,pathname:i.pathname,search:i.search,state:t}}}}function redirectTo(e,t){return async n=>{await n.navigate(e,t)}}function createRouteSignals(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.getSnapshot(),subscribe:e=>t.subscribe(()=>e())});return{name:(0,e.computed)(()=>n.value.matches.at(-1)?.name??null),params:(0,e.computed)(()=>n.value.matches.at(-1)?.params??{}),query:(0,e.computed)(()=>n.value.location.query),state:n}}function createNavigationCoordinator(){let e;return{begin(){e?.abort();let t=new AbortController;return e=t,{isCurrent:()=>e===t&&!t.signal.aborted,signal:t.signal}},invalidate(t){e?.abort(t),e=void 0}}}function compileRoutes(e){let t=[],compile=(e,n,r,i,a)=>{if(n.index&&n.path!==void 0)throw new WayfinderConfigError(`Route "${e}" cannot define both index and path`);if(!n.index&&n.path===void 0)throw new WayfinderConfigError(`Route "${e}" must define path or set index: true`);let o=n.index?r:normalizePath(n.path?joinPaths(r,n.path):r),s=[...i,{dataFn:n.data,name:e,onError:n.onError}],c=[...a,...n.middleware??[]];if(n.children)for(let[t,r]of Object.entries(n.children))compile(`${e}.${t}`,r,o,s,c);if(n.redirect!==void 0||!n.children||n.data!==void 0){let e=s[s.length-1];t.push({branchDefs:s,coerceSearch:n.coerceSearch,leaf:e,matcher:compilePathMatcher(o),ownMiddleware:c,path:o,redirect:n.redirect})}};for(let[t,n]of Object.entries(e.routes))compile(t,n,`/`,[],[]);let n=new Set;for(let e of t){if(n.has(e.leaf.name))throw new WayfinderConfigError(`Duplicate route name: "${e.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);n.add(e.leaf.name)}let r=!1;for(let e of t){let t=e.path===`/*`||e.path.endsWith(`/*`)||e.path.includes(`:`)&&e.path.endsWith(`*`);r&&!t&&`${e.leaf.name}${e.path}`,t&&(r=!0)}return{records:t,routesByName:new Map(t.map(e=>[e.leaf.name,e]))}}function createRouteState(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function buildMatchBranch(e,t,n,r){return e.map((e,i)=>({data:r[i],name:e.name,params:{...t},pathname:n}))}function createRouteContext(e,t,n,r,i){return{hash:e.hash,historyState:e.historyState,locals:{},matches:r,navigate:i,params:n,pathname:e.pathname,query:t}}async function executeMiddlewarePipeline(e,t,n,r){let i=!1;async function dispatch(a){if(a<t.length){let n=!1;try{await t[a]?.(e,async()=>{if(n)throw new WayfinderApiError(`next() called multiple times`);n=!0,await dispatch(a+1)})}catch(e){throw r?.(e)??e}}else i=!0,await n()}return await dispatch(0),i}function reportError(e,t,n){n&&n(e,t)}async function runLeaveBlockers(e,t,n){let r=new Set(t),i=[...e];for(let{handler:e,routes:t}of i)if((t===void 0||t.some(e=>r.has(e)))&&!await e(n))return!1;return!0}function getRouteByName(e,t){let n=t.get(e);if(n)return n;let r=[...t.keys()].join(`, `);throw new WayfinderRouteError(r?`Unknown route name: ${e}. Available routes: ${r}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=buildUrl(n,getRouteByName(e.name,t).path,e.params,e.query);return e.hash?`${r}#${e.hash}`:r}var t=Symbol(`wayfinder.routerError`),n=5;function carryError(e,n){return{[t]:!0,context:n,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&t 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=createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let t=compileRoutes(e);if(this.#e=normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=t.records,this.#a=t.routesByName,this.#d=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:n,pathname:r,search:i,state:a}=this.#r.location,o=`${r}${i}${n}`;this.#m=o;let s=this.#u.begin(),c=this.#j(s,o,a,(e,t)=>{if(!s.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=c.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(c,{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 buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=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?matchRouteFor(r,[n]).record!=null:matchesPrefix(r,n)}match(e){let t=stripBase(normalizePath(e),this.#e),{params:n,record:r}=matchRouteFor(t,this.#i);if(!r||r.redirect)return null;let i=buildMatchBranch(r.branchDefs,n,t,r.branchDefs.map(()=>void 0));return i.length?i:null}async load(e,t){let{decision:n}=await this.#D(e,null);if(n.type!==`matched`)return null;let{location:r,params:i,record:a,resolvedQuery:o}=n,s=a.branchDefs,c=s.some(e=>e.dataFn!=null),l=s.map(()=>void 0),u,d=`idle`;if(c){let e=t?.signal??new AbortController().signal,n=createRouteContext(r,o,i,buildMatchBranch(s,i,r.pathname,l),()=>Promise.resolve());try{l=await this.#E(s,n,e)}catch(e){u=e,d=`error`}}return createRouteState({error:u,location:r,matches:buildMatchBranch(s,i,r.pathname,l),status:d})}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 WayfinderDisposedError),this.#y(),this.#p.abort(new WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new 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),i=this.#L(e),a=await runLeaveBlockers(this.#l,r,i);if(!n.isCurrent())return;if(!a){this.#r.replace(t,this.#d.location.historyState);return}let o=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()&&!o&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){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 r=e,i=!1;for(let e=0;;e+=1){let a=await this.#k(this.#F(r,t));if(a.type!==`redirect`)return{decision:a,hopped:i};if(e>=n)throw new WayfinderRedirectLoopError;r=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:n}=matchRouteFor(e.pathname,this.#i);if(!n)return this.#v?{branch: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(n.redirect)return{location:e,params:t,redirectTo:resolveTarget(n.redirect,this.#a,this.#e),type:`redirect`};let r=this.#O(e,n.coerceSearch??this.#n);return{branch:buildMatchBranch(n.branchDefs,t,e.pathname,n.branchDefs.map(()=>void 0)),location:e,params:t,record:n,resolvedQuery:r,type:`matched`}}async#A(e,t,n,r,i,a,o){if(!a())return;let s=e.branchDefs,c=s.some(e=>e.dataFn!=null),l=s.map(()=>void 0);if(c){let e=this.#I(n),c=this.#_.get(e);if(c&&(await c.catch(()=>void 0),!a()))return;let u=this.#g.get(e);if(u)this.#g.delete(e),l=u;else{this.#d=createRouteState({location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`loading`}),this.#T();try{l=await this.#E(s,t,i)}catch(e){if(!a())return;throw this.#d=createRouteState({error:e,location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`error`}),o?.(e),e}}}a()&&(this.#d=createRouteState({location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`idle`}))}async#j(e,t,n,r,i,a){let o=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,{decision:s,hopped:c}=await this.#D(t,n);if(!isCurrent())return!1;if(s.type===`unmatched`)return r(s.location,a||c),isCurrent()?(this.#d=createRouteState({location:s.location,matches:[],status:`idle`}),this.#T(),this.#N(this.#d,o),!0):!1;let{branch:l,location:u,params:d,record:f,resolvedQuery:p}=s,m=a||c,h=!1,g,_=!1,v=!1,y=!1,run=async()=>{if(!isCurrent())return;let t=createRouteContext(u,p,d,l,(e,t)=>this.navigate(e,t));v=await executeMiddlewarePipeline(t,[...this.#t,...f.ownMiddleware],async()=>{isCurrent()&&(h=!0,r(u,m),isCurrent()&&(await this.#A(f,t,u,d,e.signal,isCurrent,e=>{g=e,_=!0}),isCurrent()&&(y=!0,this.#T(),this.#N(this.#d,o))))},e=>isRouterErrorCarrier(e)||_&&e===g?e:carryError(e,{routeName:f.leaf.name,source:`middleware`}))};try{await this.#M(run,i)}catch(e){throw _&&e===g?carryError(e,{routeName:f.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&h&&!y&&(this.#T(),this.#N(this.#d,o))}return v&&h}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=stripBase(t.pathname,this.#e);return`${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:stripBase(n.pathname,this.#e),query: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`${joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#L(e){let t=new URL(e,`http://localhost`),n=stripBase(t.pathname,this.#e),{params:r,record:i}=matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query: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(),i=this.#d.matches.map(e=>e.name),a=await runLeaveBlockers(this.#l,i,this.#L(n));if(r.isCurrent()&&a)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.WayfinderApiError=WayfinderApiError,exports.WayfinderConfigError=WayfinderConfigError,exports.WayfinderDisposedError=WayfinderDisposedError,exports.WayfinderError=WayfinderError,exports.WayfinderRedirectLoopError=WayfinderRedirectLoopError,exports.WayfinderRouteError=WayfinderRouteError,exports.createBrowserHistory=createBrowserHistory,exports.createHashHistory=createHashHistory,exports.createHistoryForBase=createHistoryForBase,exports.createMemoryHistory=createMemoryHistory,exports.createRouteSignals=createRouteSignals,exports.createRouter=createRouter,exports.redirectTo=redirectTo;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@vielzeug/ripple");var WayfinderError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},WayfinderDisposedError=class extends WayfinderError{constructor(){super(`Router is disposed`)}},WayfinderConfigError=class extends WayfinderError{},WayfinderRouteError=class extends WayfinderError{},WayfinderRedirectLoopError=class extends WayfinderError{constructor(){super(`Redirect loop detected`)}},WayfinderApiError=class extends WayfinderError{};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(e){let t=normalizePath(e);if(t===`/`)return{paramNames:[],pattern:/^\/$/,prefixPattern:/^\/$/};let n=[],r=t.slice(1).split(`/`),i=[`^`],a=[`^`];for(let t=0;t<r.length;t+=1){let o=r[t];if(o===`*`){if(t!==r.length-1)throw new WayfinderConfigError(`Wildcard "*" must be the final segment in path: ${e}`);i.push(`(?:/.*)?`);break}if(o.startsWith(`:`)&&o.endsWith(`*`)){if(t!==r.length-1)throw new WayfinderConfigError(`Wildcard param must be final segment in path: ${e}`);let s=o.slice(1,-1);if(!/^\w+$/.test(s))throw new WayfinderConfigError(`Invalid param name ":${s}" in path "${e}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);n.push(s),i.push(t===r.length-1?`(?:/(.*))?`:`/(.*)`),a.push(`/.*`);break}if(o.startsWith(`:`)){let t=o.slice(1);if(!/^\w+$/.test(t))throw new WayfinderConfigError(`Invalid param name ":${t}" in path "${e}". Param names must only contain word characters (a–z, A–Z, 0–9, _).`);n.push(t),i.push(`/([^/]+)`),a.push(`/[^/]+`);continue}let s=escapeRegex(o);i.push(`/${s}`),a.push(`/${s}`)}return i.push(`$`),a.push(`(?:/.*)?$`),{paramNames:n,pattern:new RegExp(i.join(``)),prefixPattern:new RegExp(a.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(e,t,n={},r){let i=t.replace(/:(\w+)(\*)?/g,(e,t,r)=>{let i=n[t];if(i==null)throw new WayfinderRouteError(`Missing path param: ${t}`);return r?i.split(`/`).map(e=>encodeURIComponent(e)).join(`/`):encodeURIComponent(i)});if(r&&Object.keys(r).length){let e=new URLSearchParams;Object.entries(r).forEach(([t,n])=>{Array.isArray(n)?n.forEach(n=>{e.append(t,String(n))}):e.set(t,String(n))}),i+=`?${e.toString()}`}return joinPaths(e,i)}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}function createBrowserHistory(){return{back(){window.history.back()},get location(){return{hash:window.location.hash,pathname:window.location.pathname,search:window.location.search,state:window.history.state}},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,e)},replace(e,t){window.history.replaceState(t,``,e)}}}function createHashHistory(e={}){let t=normalizePath(e.base??`/`),n=t===`/`?`/`:`${t}/`,location=()=>{let e=new URL(window.location.hash.slice(1)||`/`,`http://localhost`);return{hash:e.hash,pathname:joinPaths(t,e.pathname),search:e.search,state:window.history.state}},destination=e=>{let r=new URL(e,`http://localhost`),i=stripBase(r.pathname,t);return`${n}#${i}${r.search}${r.hash}`};return{back(){window.history.back()},href:destination,get location(){return location()},onPopstate(e){return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},push(e,t){window.history.pushState(t,``,destination(e))},replace(e,t){window.history.replaceState(t,``,destination(e))}}}function createHistoryForBase(e){return e===`/`?createBrowserHistory():createHashHistory({base:e})}function createMemoryHistory(e=`/`){let t=new URL(e,`http://localhost`),n=[{hash:t.hash,pathname:t.pathname,search:t.search,state:null}],r=0,i=new Set;return{back(){r<=0||(--r,i.forEach(e=>{e()}))},get location(){return n[r]},onPopstate(e){return i.add(e),()=>i.delete(e)},push(e,t=null){let i=new URL(e,`http://localhost`);n.splice(r+1),n.push({hash:i.hash,pathname:i.pathname,search:i.search,state:t}),r=n.length-1},replace(e,t=null){let i=new URL(e,`http://localhost`);n[r]={hash:i.hash,pathname:i.pathname,search:i.search,state:t}}}}function redirectTo(e,t){return async n=>{await n.navigate(e,t)}}function createRouteSignals(t){let n=(0,e.fromSubscribable)({getSnapshot:()=>t.getSnapshot(),subscribe:e=>t.subscribe(()=>e())});return{name:(0,e.computed)(()=>n.value.matches.at(-1)?.name??null),params:(0,e.computed)(()=>n.value.matches.at(-1)?.params??{}),query:(0,e.computed)(()=>n.value.location.query),state:n}}var t=Object.freeze([]),first=e=>Array.isArray(e)?e[0]:e,n=Object.freeze({boolean(e=!1){return{decode:t=>{let n=first(t);return n===`1`||n===`true`?!0:n===`0`||n===`false`?!1:e},default:e,encode:t=>t===e?void 0:t?`1`:`0`}},list(){return{decode:e=>e===void 0?t:Array.isArray(e)?[...e]:[e],default:t,encode:e=>e.length===0?void 0:e.length===1?e[0]:[...e]}},number(e=0){return{decode:t=>{let n=first(t);if(n===void 0||n===``)return e;let r=Number(n);return Number.isFinite(r)?r:e},default:e,encode:t=>t===e||!Number.isFinite(t)?void 0:String(t)}},pick:((e,t)=>({decode:n=>{let r=first(n);return r!==void 0&&e.includes(r)?r:t},default:t,encode:e=>e===void 0||e===t?void 0:e})),string(e=``){return{decode:t=>first(t)??e,default:e,encode:t=>t===e?void 0:t}}});function createQueryState(t,n,r={}){let i=createRouteSignals(t),a=Object.keys(n),o={};for(let t of a){let r=n[t];o[t]=(0,e.computed)(()=>r.decode(i.query.value[t]))}let readAll=()=>{let e={};for(let t of a)e[t]=o[t]?.value;return e},write=(e,i)=>{for(let t of Object.keys(e))if(!Object.hasOwn(n,t))throw new WayfinderConfigError(`createQueryState: undeclared param "${t}"`);let a=t.getSnapshot().location,o={...a.query};for(let[t,r]of Object.entries(e)){let e=n[t].encode(r);e===void 0?delete o[t]:o[t]=e}let s=new URLSearchParams;for(let[e,t]of Object.entries(o))if(Array.isArray(t))for(let n of t)s.append(e,n);else s.set(e,t);let c=s.toString(),l=`${a.pathname}${c===``?``:`?${c}`}${a.hash===``?``:`#${a.hash}`}`,u={replace:!0};for(let e of[r,i])for(let[t,n]of Object.entries(e??{}))n!==void 0&&(u[t]=n);t.navigate(l,u).catch(()=>{})};return{params:o,query:(0,e.computed)(readAll),reset:e=>{let t={};for(let e of a)t[e]=n[e].default;write(t,e)},set:(e,t)=>{write(e,t)}}}function createNavigationCoordinator(){let e;return{begin(){e?.abort();let t=new AbortController;return e=t,{isCurrent:()=>e===t&&!t.signal.aborted,signal:t.signal}},invalidate(t){e?.abort(t),e=void 0}}}function compileRoutes(e){let t=[],compile=(e,n,r,i,a)=>{if(n.index&&n.path!==void 0)throw new WayfinderConfigError(`Route "${e}" cannot define both index and path`);if(!n.index&&n.path===void 0)throw new WayfinderConfigError(`Route "${e}" must define path or set index: true`);let o=n.index?r:normalizePath(n.path?joinPaths(r,n.path):r),s=[...i,{dataFn:n.data,name:e,onError:n.onError}],c=[...a,...n.middleware??[]];if(n.children)for(let[t,r]of Object.entries(n.children))compile(`${e}.${t}`,r,o,s,c);if(n.redirect!==void 0||!n.children||n.data!==void 0){let e=s[s.length-1];t.push({branchDefs:s,coerceSearch:n.coerceSearch,leaf:e,matcher:compilePathMatcher(o),ownMiddleware:c,path:o,redirect:n.redirect})}};for(let[t,n]of Object.entries(e.routes))compile(t,n,`/`,[],[]);let n=new Set;for(let e of t){if(n.has(e.leaf.name))throw new WayfinderConfigError(`Duplicate route name: "${e.leaf.name}". A top-level route key must not coincide with a nested route's dot-notation name.`);n.add(e.leaf.name)}let r=!1;for(let e of t){let t=e.path===`/*`||e.path.endsWith(`/*`)||e.path.includes(`:`)&&e.path.endsWith(`*`);r&&!t&&`${e.leaf.name}${e.path}`,t&&(r=!0)}return{records:t,routesByName:new Map(t.map(e=>[e.leaf.name,e]))}}function createRouteState(e){return{error:e.error,location:e.location,matches:e.matches,status:e.status}}function buildMatchBranch(e,t,n,r){return e.map((e,i)=>({data:r[i],name:e.name,params:{...t},pathname:n}))}function createRouteContext(e,t,n,r,i){return{hash:e.hash,historyState:e.historyState,locals:{},matches:r,navigate:i,params:n,pathname:e.pathname,query:t}}async function executeMiddlewarePipeline(e,t,n,r){let i=!1;async function dispatch(a){if(a<t.length){let n=!1;try{await t[a]?.(e,async()=>{if(n)throw new WayfinderApiError(`next() called multiple times`);n=!0,await dispatch(a+1)})}catch(e){throw r?.(e)??e}}else i=!0,await n()}return await dispatch(0),i}function reportError(e,t,n){n&&n(e,t)}async function runLeaveBlockers(e,t,n){let r=new Set(t),i=[...e];for(let{handler:e,routes:t}of i)if((t===void 0||t.some(e=>r.has(e)))&&!await e(n))return!1;return!0}function getRouteByName(e,t){let n=t.get(e);if(n)return n;let r=[...t.keys()].join(`, `);throw new WayfinderRouteError(r?`Unknown route name: ${e}. Available routes: ${r}`:`Unknown route name: ${e}`)}function resolveTarget(e,t,n=`/`){if(`path`in e)return e.path;let r=buildUrl(n,getRouteByName(e.name,t).path,e.params,e.query);return e.hash?`${r}#${e.hash}`:r}var r=Symbol(`wayfinder.routerError`),i=5;function carryError(e,t){return{[r]:!0,context:t,error:e}}function isRouterErrorCarrier(e){return typeof e==`object`&&!!e&&r 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=createNavigationCoordinator();#d;#f=!1;#p=new AbortController;#m=`/`;#h=new Set;#g=new Map;#_=new Map;#v;#y;ready;constructor(e){let t=compileRoutes(e);if(this.#e=normalizePath(e.base??`/`),this.#t=e.middleware??[],this.#n=e.coerceSearch,this.#r=e.history??createBrowserHistory(),this.#o=e.onError,this.#s=e.scroll,this.#c=e.viewTransition??!1,this.#i=t.records,this.#a=t.routesByName,this.#d=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:n,pathname:r,search:i,state:a}=this.#r.location,o=`${r}${i}${n}`;this.#m=o;let s=this.#u.begin(),c=this.#j(s,o,a,(e,t)=>{if(!s.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=c.catch(unwrapCarrier),this.ready.catch(()=>{}),this.#w(c,{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 buildUrl(this.#e,r.path,t,n)}href(e,t,n){let r=getRouteByName(e,this.#a),i=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?matchRouteFor(r,[n]).record!=null:matchesPrefix(r,n)}match(e){let t=stripBase(normalizePath(e),this.#e),{params:n,record:r}=matchRouteFor(t,this.#i);if(!r||r.redirect)return null;let i=buildMatchBranch(r.branchDefs,n,t,r.branchDefs.map(()=>void 0));return i.length?i:null}async load(e,t){let{decision:n}=await this.#D(e,null);if(n.type!==`matched`)return null;let{location:r,params:i,record:a,resolvedQuery:o}=n,s=a.branchDefs,c=s.some(e=>e.dataFn!=null),l=s.map(()=>void 0),u,d=`idle`;if(c){let e=t?.signal??new AbortController().signal,n=createRouteContext(r,o,i,buildMatchBranch(s,i,r.pathname,l),()=>Promise.resolve());try{l=await this.#E(s,n,e)}catch(e){u=e,d=`error`}}return createRouteState({error:u,location:r,matches:buildMatchBranch(s,i,r.pathname,l),status:d})}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 WayfinderDisposedError),this.#y(),this.#p.abort(new WayfinderDisposedError))}[Symbol.dispose](){this.dispose()}#b(){if(this.#f)throw new 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),i=this.#L(e),a=await runLeaveBlockers(this.#l,r,i);if(!n.isCurrent())return;if(!a){this.#r.replace(t,this.#d.location.historyState);return}let o=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()&&!o&&this.#r.replace(t,this.#d.location.historyState)}#C(e,t){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,r=!1;for(let e=0;;e+=1){let a=await this.#k(this.#F(n,t));if(a.type!==`redirect`)return{decision:a,hopped:r};if(e>=i)throw new WayfinderRedirectLoopError;n=a.redirectTo,r=!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:n}=matchRouteFor(e.pathname,this.#i);if(!n)return this.#v?{branch: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(n.redirect)return{location:e,params:t,redirectTo:resolveTarget(n.redirect,this.#a,this.#e),type:`redirect`};let r=this.#O(e,n.coerceSearch??this.#n);return{branch:buildMatchBranch(n.branchDefs,t,e.pathname,n.branchDefs.map(()=>void 0)),location:e,params:t,record:n,resolvedQuery:r,type:`matched`}}async#A(e,t,n,r,i,a,o){if(!a())return;let s=e.branchDefs,c=s.some(e=>e.dataFn!=null),l=s.map(()=>void 0);if(c){let e=this.#I(n),c=this.#_.get(e);if(c&&(await c.catch(()=>void 0),!a()))return;let u=this.#g.get(e);if(u)this.#g.delete(e),l=u;else{this.#d=createRouteState({location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`loading`}),this.#T();try{l=await this.#E(s,t,i)}catch(e){if(!a())return;throw this.#d=createRouteState({error:e,location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`error`}),o?.(e),e}}}a()&&(this.#d=createRouteState({location:n,matches:buildMatchBranch(s,r,n.pathname,l),status:`idle`}))}async#j(e,t,n,r,i,a){let o=this.#d,isCurrent=()=>e.isCurrent()&&!this.#f,{decision:s,hopped:c}=await this.#D(t,n);if(!isCurrent())return!1;if(s.type===`unmatched`)return r(s.location,a||c),isCurrent()?(this.#d=createRouteState({location:s.location,matches:[],status:`idle`}),this.#T(),this.#N(this.#d,o),!0):!1;let{branch:l,location:u,params:d,record:f,resolvedQuery:p}=s,m=a||c,h=!1,g,_=!1,v=!1,y=!1,run=async()=>{if(!isCurrent())return;let t=createRouteContext(u,p,d,l,(e,t)=>this.navigate(e,t));v=await executeMiddlewarePipeline(t,[...this.#t,...f.ownMiddleware],async()=>{isCurrent()&&(h=!0,r(u,m),isCurrent()&&(await this.#A(f,t,u,d,e.signal,isCurrent,e=>{g=e,_=!0}),isCurrent()&&(y=!0,this.#T(),this.#N(this.#d,o))))},e=>isRouterErrorCarrier(e)||_&&e===g?e:carryError(e,{routeName:f.leaf.name,source:`middleware`}))};try{await this.#M(run,i)}catch(e){throw _&&e===g?carryError(e,{routeName:f.leaf.name,source:`data-loader`}):e}finally{isCurrent()&&h&&!y&&(this.#T(),this.#N(this.#d,o))}return v&&h}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=stripBase(t.pathname,this.#e);return`${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:stripBase(n.pathname,this.#e),query: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`${joinPaths(this.#e,e.pathname)}${n?`?${n}`:``}${r}`}#L(e){let t=new URL(e,`http://localhost`),n=stripBase(t.pathname,this.#e),{params:r,record:i}=matchRouteFor(n,this.#i);return{name:i?.leaf.name,params:r,pathname:n,query: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(),i=this.#d.matches.map(e=>e.name),a=await runLeaveBlockers(this.#l,i,this.#L(n));if(r.isCurrent()&&a)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.WayfinderApiError=WayfinderApiError,exports.WayfinderConfigError=WayfinderConfigError,exports.WayfinderDisposedError=WayfinderDisposedError,exports.WayfinderError=WayfinderError,exports.WayfinderRedirectLoopError=WayfinderRedirectLoopError,exports.WayfinderRouteError=WayfinderRouteError,exports.createBrowserHistory=createBrowserHistory,exports.createHashHistory=createHashHistory,exports.createHistoryForBase=createHistoryForBase,exports.createMemoryHistory=createMemoryHistory,exports.createQueryState=createQueryState,exports.createRouteSignals=createRouteSignals,exports.createRouter=createRouter,exports.param=n,exports.redirectTo=redirectTo;
|
|
2
2
|
//# sourceMappingURL=wayfinder.cjs.map
|