@real-router/core 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/cjs/{Router-B-Pev7K2.d.ts → Router-DoJ3NWsT.d.ts} +1 -1
  2. package/dist/cjs/{RouterValidator-mx2Zooya.d.ts → RouterValidator-CaIeCVeB.d.ts} +1 -1
  3. package/dist/cjs/api.d.ts +1 -1
  4. package/dist/cjs/api.js +1 -1
  5. package/dist/cjs/api.js.map +1 -1
  6. package/dist/cjs/index.d.ts +3 -3
  7. package/dist/cjs/index.js +1 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/metafile-cjs.json +1 -1
  10. package/dist/cjs/utils.js +1 -1
  11. package/dist/cjs/utils.js.map +1 -1
  12. package/dist/cjs/validation.d.ts +4 -4
  13. package/dist/cjs/validation.js.map +1 -1
  14. package/dist/esm/{Router-B-Pev7K2.d.mts → Router-DoJ3NWsT.d.mts} +1 -1
  15. package/dist/esm/{RouterValidator-mx2Zooya.d.mts → RouterValidator-CaIeCVeB.d.mts} +1 -1
  16. package/dist/esm/api.d.mts +1 -1
  17. package/dist/esm/api.mjs +1 -1
  18. package/dist/esm/{chunk-5QXFUUDL.mjs → chunk-EPF2YSMX.mjs} +1 -1
  19. package/dist/esm/{chunk-5QXFUUDL.mjs.map → chunk-EPF2YSMX.mjs.map} +1 -1
  20. package/dist/esm/chunk-UPJLWPEL.mjs +1 -0
  21. package/dist/esm/chunk-UPJLWPEL.mjs.map +1 -0
  22. package/dist/esm/{chunk-QUUNDESP.mjs → chunk-UUG7DSTN.mjs} +1 -1
  23. package/dist/esm/chunk-UUG7DSTN.mjs.map +1 -0
  24. package/dist/esm/chunk-XQJDGUQE.mjs +1 -0
  25. package/dist/esm/chunk-XQJDGUQE.mjs.map +1 -0
  26. package/dist/esm/index.d.mts +3 -3
  27. package/dist/esm/index.mjs +1 -1
  28. package/dist/esm/metafile-esm.json +1 -1
  29. package/dist/esm/utils.mjs +1 -1
  30. package/dist/esm/validation.d.mts +4 -4
  31. package/dist/esm/validation.mjs +1 -1
  32. package/package.json +4 -3
  33. package/src/Router.ts +4 -6
  34. package/src/api/getPluginApi.ts +2 -3
  35. package/src/helpers.ts +0 -1
  36. package/src/index.ts +0 -1
  37. package/src/internals.ts +4 -5
  38. package/src/namespaces/NavigationNamespace/NavigationNamespace.ts +2 -4
  39. package/src/namespaces/NavigationNamespace/types.ts +0 -7
  40. package/src/namespaces/OptionsNamespace/helpers.ts +0 -1
  41. package/src/namespaces/RouterLifecycleNamespace/types.ts +1 -3
  42. package/src/namespaces/RoutesNamespace/RoutesNamespace.ts +3 -3
  43. package/src/namespaces/RoutesNamespace/types.ts +2 -2
  44. package/src/namespaces/StateNamespace/StateNamespace.ts +30 -34
  45. package/src/namespaces/StateNamespace/helpers.ts +8 -27
  46. package/src/stateMetaStore.ts +15 -0
  47. package/src/transitionPath.ts +13 -16
  48. package/src/types/RouterValidator.ts +0 -1
  49. package/src/wiring/RouterWiringBuilder.ts +1 -3
  50. package/dist/esm/chunk-HHIXK5UM.mjs +0 -1
  51. package/dist/esm/chunk-HHIXK5UM.mjs.map +0 -1
  52. package/dist/esm/chunk-QUUNDESP.mjs.map +0 -1
  53. package/dist/esm/chunk-RA5VYM7M.mjs +0 -1
  54. package/dist/esm/chunk-RA5VYM7M.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { L as Limits, R as RouterValidator } from './RouterValidator-mx2Zooya.js';
1
+ import { L as Limits, R as RouterValidator } from './RouterValidator-CaIeCVeB.js';
2
2
  import { DefaultDependencies, Params, ForwardToCallback, GuardFnFactory, State, SimpleState, GuardFn, RouteTreeState, Options, EventName, Plugin, EventMethodMap, Unsubscribe, PluginFactory, Router } from '@real-router/types';
3
3
  import { a as RouteDefinition, R as RouteTree, M as Matcher, C as CreateMatcherOptions } from './index.d-y2b-8_3Y.js';
4
4
 
@@ -19,7 +19,7 @@ interface RoutesDependencies<Dependencies extends DefaultDependencies = DefaultD
19
19
  /** Register canDeactivate handler for a route */
20
20
  addDeactivateGuard: (name: string, handler: GuardFnFactory<Dependencies>) => void;
21
21
  /** Create state object */
22
- makeState: <P extends Params = Params, MP extends Params = Params>(name: string, params?: P, path?: string, meta?: Record<string, Record<string, "url" | "query">>) => State<P, MP>;
22
+ makeState: <P extends Params = Params>(name: string, params?: P, path?: string, meta?: Record<string, Record<string, "url" | "query">>) => State<P>;
23
23
  /** Get current router state */
24
24
  getState: () => State | undefined;
25
25
  /** Compare two states for equality */
@@ -148,10 +148,10 @@ interface RoutesStore<Dependencies extends DefaultDependencies = DefaultDependen
148
148
  }
149
149
 
150
150
  interface RouterInternals<D extends DefaultDependencies = DefaultDependencies> {
151
- readonly makeState: <P extends Params = Params, MP extends Params = Params>(name: string, params?: P, path?: string, meta?: Record<string, Record<string, "url" | "query">>, forceId?: number) => State<P, MP>;
151
+ readonly makeState: <P extends Params = Params>(name: string, params?: P, path?: string, meta?: Record<string, Record<string, "url" | "query">>) => State<P>;
152
152
  readonly forwardState: <P extends Params = Params>(routeName: string, routeParams: P) => SimpleState<P>;
153
153
  readonly buildStateResolved: (resolvedName: string, resolvedParams: Params) => RouteTreeState | undefined;
154
- readonly matchPath: <P extends Params = Params, MP extends Params = Params>(path: string, options?: Options) => State<P, MP> | undefined;
154
+ readonly matchPath: <P extends Params = Params>(path: string, options?: Options) => State<P> | undefined;
155
155
  readonly getOptions: () => Options;
156
156
  readonly addEventListener: <E extends EventName>(eventName: E, cb: Plugin[EventMethodMap[E]]) => Unsubscribe;
157
157
  readonly buildPath: (route: string, params?: Params) => string;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/internals.ts"],"names":[],"mappings":";AAgGA,IAAM,SAAA,uBAAgB,OAAA,EAAsC;AAErD,SAAS,aACd,MAAA,EACoB;AACpB,EAAA,MAAM,GAAA,GAAM,SAAA,CAAU,GAAA,CAAI,MAAM,CAAA;AAEhC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,SAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,GAAA;AACT","file":"validation.js","sourcesContent":["import type { DependenciesStore } from \"./namespaces/DependenciesNamespace\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type { EventMethodMap, GuardFnFactory, PluginFactory } from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\nimport type {\n DefaultDependencies,\n EventName,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouteTreeState,\n SimpleState,\n State,\n Unsubscribe,\n} from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <P extends Params = Params, MP extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: Record<string, Record<string, \"url\" | \"query\">>,\n forceId?: number,\n ) => State<P, MP>;\n\n readonly forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => SimpleState<P>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params, MP extends Params = Params>(\n path: string,\n options?: Options,\n ) => State<P, MP> | undefined;\n\n readonly getOptions: () => Options;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n readonly buildPath: (route: string, params?: Params) => string;\n\n readonly start: (path: string) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173)\n readonly cloneOptions: () => Options;\n readonly cloneDependencies: () => Record<string, unknown>;\n readonly getLifecycleFactories: () => [\n Record<string, GuardFnFactory<D>>,\n Record<string, GuardFnFactory<D>>,\n ];\n readonly getPluginFactories: () => PluginFactory<D>[];\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n readonly clearState: () => void;\n readonly setState: (state: State) => void;\n readonly routerExtensions: { keys: string[] }[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\nexport function createInterceptable2<A, B, R>(\n name: string,\n original: (a: A, b: B) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B) => R {\n return (arg1: A, arg2: B) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n"]}
1
+ {"version":3,"sources":["../../src/internals.ts"],"names":[],"mappings":";AA+FA,IAAM,SAAA,uBAAgB,OAAA,EAAsC;AAErD,SAAS,aACd,MAAA,EACoB;AACpB,EAAA,MAAM,GAAA,GAAM,SAAA,CAAU,GAAA,CAAI,MAAM,CAAA;AAEhC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,SAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,GAAA;AACT","file":"validation.js","sourcesContent":["import type { DependenciesStore } from \"./namespaces/DependenciesNamespace\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type { EventMethodMap, GuardFnFactory, PluginFactory } from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\nimport type {\n DefaultDependencies,\n EventName,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouteTreeState,\n SimpleState,\n State,\n Unsubscribe,\n} from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <P extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: Record<string, Record<string, \"url\" | \"query\">>,\n ) => State<P>;\n\n readonly forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => SimpleState<P>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: Options,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n readonly buildPath: (route: string, params?: Params) => string;\n\n readonly start: (path: string) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173)\n readonly cloneOptions: () => Options;\n readonly cloneDependencies: () => Record<string, unknown>;\n readonly getLifecycleFactories: () => [\n Record<string, GuardFnFactory<D>>,\n Record<string, GuardFnFactory<D>>,\n ];\n readonly getPluginFactories: () => PluginFactory<D>[];\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n readonly clearState: () => void;\n readonly setState: (state: State) => void;\n readonly routerExtensions: { keys: string[] }[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\nexport function createInterceptable2<A, B, R>(\n name: string,\n original: (a: A, b: B) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B) => R {\n return (arg1: A, arg2: B) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n"]}
@@ -27,7 +27,7 @@ declare class Router<Dependencies extends DefaultDependencies = DefaultDependenc
27
27
  constructor(routes?: Route<Dependencies>[], options?: Partial<Options>, dependencies?: Dependencies);
28
28
  isActiveRoute(name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean): boolean;
29
29
  buildPath(route: string, params?: Params): string;
30
- getState<P extends Params = Params, MP extends Params = Params>(): State<P, MP> | undefined;
30
+ getState<P extends Params = Params>(): State<P> | undefined;
31
31
  getPreviousState(): State | undefined;
32
32
  areStatesEqual(state1: State | undefined, state2: State | undefined, ignoreQueryParams?: boolean): boolean;
33
33
  shouldUpdateNode(nodeName: string): (toState: State, fromState?: State) => boolean;
@@ -121,7 +121,7 @@ interface RouterValidator {
121
121
  * State validation methods
122
122
  */
123
123
  state: {
124
- validateMakeStateArgs: (name: unknown, params: unknown, path: unknown, forceId: unknown) => void;
124
+ validateMakeStateArgs: (name: unknown, params: unknown, path: unknown) => void;
125
125
  validateAreStatesEqualArgs: (s1: unknown, s2: unknown, ignoreQP: unknown) => void;
126
126
  };
127
127
  /**
@@ -1,7 +1,7 @@
1
1
  import { PluginApi as PluginApi$1, DefaultDependencies, Router, RoutesApi, DependenciesApi, LifecycleApi } from '@real-router/types';
2
2
  export { DependenciesApi, LifecycleApi, RoutesApi } from '@real-router/types';
3
3
  import { R as RouteTree } from './index.d-y2b-8_3Y.mjs';
4
- import { R as Router$1 } from './Router-B-Pev7K2.mjs';
4
+ import { R as Router$1 } from './Router-DoJ3NWsT.mjs';
5
5
 
6
6
  interface PluginApi extends Omit<PluginApi$1, "getTree"> {
7
7
  getTree: () => RouteTree;
package/dist/esm/api.mjs CHANGED
@@ -1 +1 @@
1
- import{guardRouteStructure as e,f as t,Router as a,clearRouteData as n,sanitizeRoute as r,registerAllRouteHandlers as o,removeFromDefinitions as i,clearConfigEntries as d,refreshForwardMap as s}from"./chunk-RA5VYM7M.mjs";import{throwIfDisposed as c}from"./chunk-HHIXK5UM.mjs";export{getPluginApi}from"./chunk-HHIXK5UM.mjs";import{RouterError as l,errorCodes as u}from"./chunk-5QXFUUDL.mjs";import{getInternals as p}from"./chunk-QUUNDESP.mjs";import{logger as v}from"@real-router/logger";function f(e){return!e||(v.error("router.clearRoutes","Cannot clear routes while navigation is in progress. Wait for navigation to complete."),!1)}function m(e,t,a=""){for(const n of e){const e=a?`${a}.${n.name}`:n.name;if(e===t)return n;if(n.children&&t.startsWith(`${e}.`))return m(n.children,t,e)}}function g(e,t,a,n){const r={name:e.name,path:e.path},o=a.forwardFnMap[t],i=a.forwardMap[t];void 0!==o?r.forwardTo=o:void 0!==i&&(r.forwardTo=i),t in a.defaultParams&&(r.defaultParams=a.defaultParams[t]),t in a.decoders&&(r.decodeParams=a.decoders[t]),t in a.encoders&&(r.encodeParams=a.encoders[t]);const[d,s]=n;return t in s&&(r.canActivate=s[t]),t in d&&(r.canDeactivate=d[t]),e.children&&(r.children=e.children.map(e=>g(e,`${t}.${e.name}`,a,n))),r}function D(e,t,a){if(a){const n=m(e.definitions,a);n.children??=[];for(const e of t)n.children.push(r(e))}else for(const a of t)e.definitions.push(r(a));o(t,e.config,e.routeCustomFields,e.pendingCanActivate,e.pendingCanDeactivate,e.depsStore,a??""),e.treeOperations.commitTreeChanges(e)}function h(e,t){const a=e.matcher.getSegmentsByName(t);if(!a)return;const n=a.at(-1),r=e.treeOperations.nodeToDefinition(n),o=e.lifecycleNamespace.getFactories();return g(r,t,e.config,o)}function w(t){const a=p(t),l=a.routeGetStore();return{add:(t,n)=>{c(a.isDisposed);const r=Array.isArray(t)?t:[t],o=n?.parent;e(r,a.validator),void 0!==o&&a.validator?.routes.validateParentOption(o,l.tree),a.validator?.routes.throwIfInternalRouteInArray(r,"addRoute"),a.validator?.routes.validateAddRouteArgs(r),a.validator?.routes.validateRoutes(r,l),D(l,r,o)},remove:e=>{c(a.isDisposed),a.validator?.routes.validateRemoveRouteArgs(e),a.validator?.routes.throwIfInternalRoute(e,"removeRoute");const t=function(e,t,a){if(t){const a=t===e,n=t.startsWith(`${e}.`);if(a||n)return v.warn("router.removeRoute",`Cannot remove route "${e}" — it is currently active${a?"":` (current: "${t}")`}. Navigate away first.`),!1}return a&&v.warn("router.removeRoute",`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}(e,a.getStateName(),a.isTransitioning());t&&(function(e,t){return!!i(e.definitions,t)&&(function(e,t,a,n){const r=t=>t===e||t.startsWith(`${e}.`);d(t.decoders,r),d(t.encoders,r),d(t.defaultParams,r),d(t.forwardMap,r),d(t.forwardFnMap,r),d(a,r),d(t.forwardMap,e=>r(t.forwardMap[e]));const[o,i]=n.getFactories();for(const e of Object.keys(i))r(e)&&n.clearCanActivate(e);for(const e of Object.keys(o))r(e)&&n.clearCanDeactivate(e)}(t,e.config,e.routeCustomFields,e.lifecycleNamespace),e.treeOperations.commitTreeChanges(e),!0)}(l,e)||v.warn("router.removeRoute",`Route "${e}" not found. No changes made.`))},update:(e,t)=>{c(a.isDisposed),a.validator?.routes.validateUpdateRouteBasicArgs(e,t),a.validator?.routes.throwIfInternalRoute(e,"updateRoute");const{forwardTo:n,defaultParams:r,decodeParams:o,encodeParams:i,canActivate:d,canDeactivate:u}=t;a.validator?.routes.validateUpdateRoutePropertyTypes(e,t),a.isTransitioning()&&v.error("router.updateRoute",`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`),a.validator?.routes.validateUpdateRoute(e,t,l),function(e,t,a){if(void 0!==a.forwardTo&&(e.resolvedForwardMap=function(e,t,a){return null===t?(delete a.forwardMap[e],delete a.forwardFnMap[e]):"string"==typeof t?(delete a.forwardFnMap[e],a.forwardMap[e]=t):(delete a.forwardMap[e],a.forwardFnMap[e]=t),(e=>s(e))(a)}(t,a.forwardTo,e.config)),void 0!==a.defaultParams&&(null===a.defaultParams?delete e.config.defaultParams[t]:e.config.defaultParams[t]=a.defaultParams),void 0!==a.decodeParams)if(null===a.decodeParams)delete e.config.decoders[t];else{const n=a.decodeParams;e.config.decoders[t]=e=>n(e)??e}if(void 0!==a.encodeParams)if(null===a.encodeParams)delete e.config.encoders[t];else{const n=a.encodeParams;e.config.encoders[t]=e=>n(e)??e}}(l,e,{forwardTo:n,defaultParams:r,decodeParams:o,encodeParams:i}),void 0!==d&&(null===d?l.lifecycleNamespace.clearCanActivate(e):l.lifecycleNamespace.addCanActivate(e,d,!0)),void 0!==u&&(null===u?l.lifecycleNamespace.clearCanDeactivate(e):l.lifecycleNamespace.addCanDeactivate(e,u,!0))},clear:()=>{c(a.isDisposed),f(a.isTransitioning())&&(l.treeOperations.resetStore(l),l.lifecycleNamespace.clearAll(),a.clearState())},has:e=>(a.validator?.routes.validateRouteName(e,"hasRoute"),l.matcher.hasRoute(e)),get:e=>(a.validator?.routes.validateRouteName(e,"getRoute"),h(l,e)),replace:i=>{c(a.isDisposed);const d=Array.isArray(i)?i:[i];if(!f(a.isTransitioning()))return;e(d,a.validator),a.validator?.routes.throwIfInternalRouteInArray(d,"replaceRoutes"),a.validator?.routes.validateAddRouteArgs(d),a.validator?.routes.validateRoutes(d,l);const s=t.getState()?.path;!function(e,t,a,i){n(e),e.lifecycleNamespace.clearDefinitionGuards();for(const a of t)e.definitions.push(r(a));if(o(t,e.config,e.routeCustomFields,e.pendingCanActivate,e.pendingCanDeactivate,e.depsStore,""),e.treeOperations.commitTreeChanges(e),void 0!==i){const e=a.matchPath(i,a.getOptions());e?a.setState(e):a.clearState()}}(l,d,a,s)}}}function y(e){const t=p(e);return{get:e=>{t.validator?.dependencies.validateDependencyName(e,"getDependency");const a=t.dependenciesGetStore(),n=a.dependencies[e];return t.validator?.dependencies.validateDependencyExists(e,a),n},getAll:()=>({...t.dependenciesGetStore().dependencies}),set:(e,a)=>{c(t.isDisposed),t.validator?.dependencies.validateSetDependencyArgs(e,a,"setDependency"),function(e,t,a,n){if(void 0===a)return!1;if(Object.hasOwn(e.dependencies,t)){const r=e.dependencies[t],o=r!==a,i=Number.isNaN(r)&&Number.isNaN(a);o&&!i&&n?.dependencies.warnOverwrite(t,"setDependency")}else n?.dependencies.validateDependencyCount(e,"setDependency");e.dependencies[t]=a}(t.dependenciesGetStore(),e,a,t.validator)},setAll:e=>{c(t.isDisposed);const a=t.dependenciesGetStore();t.validator?.dependencies.validateDependenciesObject(e,"setDependencies"),t.validator?.dependencies.validateDependencyLimit(a,a.limits),function(e,t,a){const n=[];for(const r in t)void 0!==t[r]&&(Object.hasOwn(e.dependencies,r)?n.push(r):a?.dependencies.validateDependencyCount(e,"setDependencies"),e.dependencies[r]=t[r]);n.length>0&&a?.dependencies.warnBatchOverwrite(n,"setDependencies")}(a,e,t.validator)},remove:e=>{c(t.isDisposed),t.validator?.dependencies.validateDependencyName(e,"removeDependency");const a=t.dependenciesGetStore();Object.hasOwn(a.dependencies,e)||t.validator?.dependencies.warnRemoveNonExistent(e),delete a.dependencies[e]},reset:()=>{c(t.isDisposed),t.dependenciesGetStore().dependencies=Object.create(null)},has:e=>(t.validator?.dependencies.validateDependencyName(e,"hasDependency"),Object.hasOwn(t.dependenciesGetStore().dependencies,e))}}function R(e){const t=p(e),a=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,n){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"addActivateGuard"),t.validator?.lifecycle.validateHandler(n,"addActivateGuard");const r=a.getHandlerCount("activate");t.validator?.lifecycle.validateHandlerLimit(r,t.dependenciesGetStore().limits,"canActivate"),a.addCanActivate(e,n)},addDeactivateGuard(e,n){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"addDeactivateGuard"),t.validator?.lifecycle.validateHandler(n,"addDeactivateGuard");const r=a.getHandlerCount("deactivate");t.validator?.lifecycle.validateHandlerLimit(r,t.dependenciesGetStore().limits,"canDeactivate"),a.addCanDeactivate(e,n)},removeActivateGuard(e){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"removeActivateGuard"),a.clearCanActivate(e)},removeDeactivateGuard(e){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"removeDeactivateGuard"),a.clearCanDeactivate(e)}}}function A(e,n){const r=p(e);if(r.isDisposed())throw new l(u.ROUTER_DISPOSED);r.validator?.dependencies.validateCloneArgs(n);const o=r.routeGetStore(),i=t(o.tree),d=o.config,s=o.resolvedForwardMap,c=o.routeCustomFields,v=r.cloneOptions(),f=r.cloneDependencies(),[m,g]=r.getLifecycleFactories(),D=r.getPluginFactories(),h={...f,...n},w=new a(i,v,h),y=R(w);for(const[e,t]of Object.entries(m))y.addDeactivateGuard(e,t);for(const[e,t]of Object.entries(g))y.addActivateGuard(e,t);D.length>0&&w.usePlugin(...D);const A=p(w).routeGetStore();return Object.assign(A.config.decoders,d.decoders),Object.assign(A.config.encoders,d.encoders),Object.assign(A.config.defaultParams,d.defaultParams),Object.assign(A.config.forwardMap,d.forwardMap),Object.assign(A.config.forwardFnMap,d.forwardFnMap),Object.assign(A.resolvedForwardMap,s),Object.assign(A.routeCustomFields,c),w}export{A as cloneRouter,y as getDependenciesApi,R as getLifecycleApi,w as getRoutesApi};//# sourceMappingURL=api.mjs.map
1
+ import{guardRouteStructure as e,f as t,Router as a,clearRouteData as n,sanitizeRoute as r,registerAllRouteHandlers as o,removeFromDefinitions as i,clearConfigEntries as d,refreshForwardMap as s}from"./chunk-XQJDGUQE.mjs";import{throwIfDisposed as c}from"./chunk-UPJLWPEL.mjs";export{getPluginApi}from"./chunk-UPJLWPEL.mjs";import{RouterError as l,errorCodes as u}from"./chunk-EPF2YSMX.mjs";import{getInternals as p}from"./chunk-UUG7DSTN.mjs";import{logger as v}from"@real-router/logger";function f(e){return!e||(v.error("router.clearRoutes","Cannot clear routes while navigation is in progress. Wait for navigation to complete."),!1)}function m(e,t,a=""){for(const n of e){const e=a?`${a}.${n.name}`:n.name;if(e===t)return n;if(n.children&&t.startsWith(`${e}.`))return m(n.children,t,e)}}function g(e,t,a,n){const r={name:e.name,path:e.path},o=a.forwardFnMap[t],i=a.forwardMap[t];void 0!==o?r.forwardTo=o:void 0!==i&&(r.forwardTo=i),t in a.defaultParams&&(r.defaultParams=a.defaultParams[t]),t in a.decoders&&(r.decodeParams=a.decoders[t]),t in a.encoders&&(r.encodeParams=a.encoders[t]);const[d,s]=n;return t in s&&(r.canActivate=s[t]),t in d&&(r.canDeactivate=d[t]),e.children&&(r.children=e.children.map(e=>g(e,`${t}.${e.name}`,a,n))),r}function D(e,t,a){if(a){const n=m(e.definitions,a);n.children??=[];for(const e of t)n.children.push(r(e))}else for(const a of t)e.definitions.push(r(a));o(t,e.config,e.routeCustomFields,e.pendingCanActivate,e.pendingCanDeactivate,e.depsStore,a??""),e.treeOperations.commitTreeChanges(e)}function h(e,t){const a=e.matcher.getSegmentsByName(t);if(!a)return;const n=a.at(-1),r=e.treeOperations.nodeToDefinition(n),o=e.lifecycleNamespace.getFactories();return g(r,t,e.config,o)}function w(t){const a=p(t),l=a.routeGetStore();return{add:(t,n)=>{c(a.isDisposed);const r=Array.isArray(t)?t:[t],o=n?.parent;e(r,a.validator),void 0!==o&&a.validator?.routes.validateParentOption(o,l.tree),a.validator?.routes.throwIfInternalRouteInArray(r,"addRoute"),a.validator?.routes.validateAddRouteArgs(r),a.validator?.routes.validateRoutes(r,l),D(l,r,o)},remove:e=>{c(a.isDisposed),a.validator?.routes.validateRemoveRouteArgs(e),a.validator?.routes.throwIfInternalRoute(e,"removeRoute");const t=function(e,t,a){if(t){const a=t===e,n=t.startsWith(`${e}.`);if(a||n)return v.warn("router.removeRoute",`Cannot remove route "${e}" — it is currently active${a?"":` (current: "${t}")`}. Navigate away first.`),!1}return a&&v.warn("router.removeRoute",`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}(e,a.getStateName(),a.isTransitioning());t&&(function(e,t){return!!i(e.definitions,t)&&(function(e,t,a,n){const r=t=>t===e||t.startsWith(`${e}.`);d(t.decoders,r),d(t.encoders,r),d(t.defaultParams,r),d(t.forwardMap,r),d(t.forwardFnMap,r),d(a,r),d(t.forwardMap,e=>r(t.forwardMap[e]));const[o,i]=n.getFactories();for(const e of Object.keys(i))r(e)&&n.clearCanActivate(e);for(const e of Object.keys(o))r(e)&&n.clearCanDeactivate(e)}(t,e.config,e.routeCustomFields,e.lifecycleNamespace),e.treeOperations.commitTreeChanges(e),!0)}(l,e)||v.warn("router.removeRoute",`Route "${e}" not found. No changes made.`))},update:(e,t)=>{c(a.isDisposed),a.validator?.routes.validateUpdateRouteBasicArgs(e,t),a.validator?.routes.throwIfInternalRoute(e,"updateRoute");const{forwardTo:n,defaultParams:r,decodeParams:o,encodeParams:i,canActivate:d,canDeactivate:u}=t;a.validator?.routes.validateUpdateRoutePropertyTypes(e,t),a.isTransitioning()&&v.error("router.updateRoute",`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`),a.validator?.routes.validateUpdateRoute(e,t,l),function(e,t,a){if(void 0!==a.forwardTo&&(e.resolvedForwardMap=function(e,t,a){return null===t?(delete a.forwardMap[e],delete a.forwardFnMap[e]):"string"==typeof t?(delete a.forwardFnMap[e],a.forwardMap[e]=t):(delete a.forwardMap[e],a.forwardFnMap[e]=t),(e=>s(e))(a)}(t,a.forwardTo,e.config)),void 0!==a.defaultParams&&(null===a.defaultParams?delete e.config.defaultParams[t]:e.config.defaultParams[t]=a.defaultParams),void 0!==a.decodeParams)if(null===a.decodeParams)delete e.config.decoders[t];else{const n=a.decodeParams;e.config.decoders[t]=e=>n(e)??e}if(void 0!==a.encodeParams)if(null===a.encodeParams)delete e.config.encoders[t];else{const n=a.encodeParams;e.config.encoders[t]=e=>n(e)??e}}(l,e,{forwardTo:n,defaultParams:r,decodeParams:o,encodeParams:i}),void 0!==d&&(null===d?l.lifecycleNamespace.clearCanActivate(e):l.lifecycleNamespace.addCanActivate(e,d,!0)),void 0!==u&&(null===u?l.lifecycleNamespace.clearCanDeactivate(e):l.lifecycleNamespace.addCanDeactivate(e,u,!0))},clear:()=>{c(a.isDisposed),f(a.isTransitioning())&&(l.treeOperations.resetStore(l),l.lifecycleNamespace.clearAll(),a.clearState())},has:e=>(a.validator?.routes.validateRouteName(e,"hasRoute"),l.matcher.hasRoute(e)),get:e=>(a.validator?.routes.validateRouteName(e,"getRoute"),h(l,e)),replace:i=>{c(a.isDisposed);const d=Array.isArray(i)?i:[i];if(!f(a.isTransitioning()))return;e(d,a.validator),a.validator?.routes.throwIfInternalRouteInArray(d,"replaceRoutes"),a.validator?.routes.validateAddRouteArgs(d),a.validator?.routes.validateRoutes(d,l);const s=t.getState()?.path;!function(e,t,a,i){n(e),e.lifecycleNamespace.clearDefinitionGuards();for(const a of t)e.definitions.push(r(a));if(o(t,e.config,e.routeCustomFields,e.pendingCanActivate,e.pendingCanDeactivate,e.depsStore,""),e.treeOperations.commitTreeChanges(e),void 0!==i){const e=a.matchPath(i,a.getOptions());e?a.setState(e):a.clearState()}}(l,d,a,s)}}}function y(e){const t=p(e);return{get:e=>{t.validator?.dependencies.validateDependencyName(e,"getDependency");const a=t.dependenciesGetStore(),n=a.dependencies[e];return t.validator?.dependencies.validateDependencyExists(e,a),n},getAll:()=>({...t.dependenciesGetStore().dependencies}),set:(e,a)=>{c(t.isDisposed),t.validator?.dependencies.validateSetDependencyArgs(e,a,"setDependency"),function(e,t,a,n){if(void 0===a)return!1;if(Object.hasOwn(e.dependencies,t)){const r=e.dependencies[t],o=r!==a,i=Number.isNaN(r)&&Number.isNaN(a);o&&!i&&n?.dependencies.warnOverwrite(t,"setDependency")}else n?.dependencies.validateDependencyCount(e,"setDependency");e.dependencies[t]=a}(t.dependenciesGetStore(),e,a,t.validator)},setAll:e=>{c(t.isDisposed);const a=t.dependenciesGetStore();t.validator?.dependencies.validateDependenciesObject(e,"setDependencies"),t.validator?.dependencies.validateDependencyLimit(a,a.limits),function(e,t,a){const n=[];for(const r in t)void 0!==t[r]&&(Object.hasOwn(e.dependencies,r)?n.push(r):a?.dependencies.validateDependencyCount(e,"setDependencies"),e.dependencies[r]=t[r]);n.length>0&&a?.dependencies.warnBatchOverwrite(n,"setDependencies")}(a,e,t.validator)},remove:e=>{c(t.isDisposed),t.validator?.dependencies.validateDependencyName(e,"removeDependency");const a=t.dependenciesGetStore();Object.hasOwn(a.dependencies,e)||t.validator?.dependencies.warnRemoveNonExistent(e),delete a.dependencies[e]},reset:()=>{c(t.isDisposed),t.dependenciesGetStore().dependencies=Object.create(null)},has:e=>(t.validator?.dependencies.validateDependencyName(e,"hasDependency"),Object.hasOwn(t.dependenciesGetStore().dependencies,e))}}function P(e){const t=p(e),a=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,n){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"addActivateGuard"),t.validator?.lifecycle.validateHandler(n,"addActivateGuard");const r=a.getHandlerCount("activate");t.validator?.lifecycle.validateHandlerLimit(r,t.dependenciesGetStore().limits,"canActivate"),a.addCanActivate(e,n)},addDeactivateGuard(e,n){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"addDeactivateGuard"),t.validator?.lifecycle.validateHandler(n,"addDeactivateGuard");const r=a.getHandlerCount("deactivate");t.validator?.lifecycle.validateHandlerLimit(r,t.dependenciesGetStore().limits,"canDeactivate"),a.addCanDeactivate(e,n)},removeActivateGuard(e){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"removeActivateGuard"),a.clearCanActivate(e)},removeDeactivateGuard(e){c(t.isDisposed),t.validator?.routes.validateRouteName(e,"removeDeactivateGuard"),a.clearCanDeactivate(e)}}}function R(e,n){const r=p(e);if(r.isDisposed())throw new l(u.ROUTER_DISPOSED);r.validator?.dependencies.validateCloneArgs(n);const o=r.routeGetStore(),i=t(o.tree),d=o.config,s=o.resolvedForwardMap,c=o.routeCustomFields,v=r.cloneOptions(),f=r.cloneDependencies(),[m,g]=r.getLifecycleFactories(),D=r.getPluginFactories(),h={...f,...n},w=new a(i,v,h),y=P(w);for(const[e,t]of Object.entries(m))y.addDeactivateGuard(e,t);for(const[e,t]of Object.entries(g))y.addActivateGuard(e,t);D.length>0&&w.usePlugin(...D);const R=p(w).routeGetStore();return Object.assign(R.config.decoders,d.decoders),Object.assign(R.config.encoders,d.encoders),Object.assign(R.config.defaultParams,d.defaultParams),Object.assign(R.config.forwardMap,d.forwardMap),Object.assign(R.config.forwardFnMap,d.forwardFnMap),Object.assign(R.resolvedForwardMap,s),Object.assign(R.routeCustomFields,c),w}export{R as cloneRouter,y as getDependenciesApi,P as getLifecycleApi,w as getRoutesApi};//# sourceMappingURL=api.mjs.map
@@ -1 +1 @@
1
- var e=Object.freeze({ROUTER_NOT_STARTED:"NOT_STARTED",NO_START_PATH_OR_STATE:"NO_START_PATH_OR_STATE",ROUTER_ALREADY_STARTED:"ALREADY_STARTED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",SAME_STATES:"SAME_STATES",CANNOT_DEACTIVATE:"CANNOT_DEACTIVATE",CANNOT_ACTIVATE:"CANNOT_ACTIVATE",TRANSITION_ERR:"TRANSITION_ERR",TRANSITION_CANCELLED:"CANCELLED",ROUTER_DISPOSED:"DISPOSED",PLUGIN_CONFLICT:"PLUGIN_CONFLICT"}),t="@@router/UNKNOWN_ROUTE",r={UNKNOWN_ROUTE:t},s={ROUTER_START:"onStart",ROUTER_STOP:"onStop",TRANSITION_START:"onTransitionStart",TRANSITION_CANCEL:"onTransitionCancel",TRANSITION_SUCCESS:"onTransitionSuccess",TRANSITION_ERROR:"onTransitionError"},n={ROUTER_START:"$start",ROUTER_STOP:"$stop",TRANSITION_START:"$$start",TRANSITION_CANCEL:"$$cancel",TRANSITION_SUCCESS:"$$success",TRANSITION_ERROR:"$$error"},o={maxDependencies:100,maxPlugins:50,maxListeners:1e4,warnListeners:1e3,maxEventDepth:5,maxLifecycleHandlers:200},i=Object.freeze({}),T=new WeakSet;function a(e){if(null!==e&&"object"==typeof e&&!Object.isFrozen(e))if(Object.freeze(e),Array.isArray(e))for(const t of e)a(t);else for(const t in e)a(e[t])}function c(e){return e?(T.has(e)||(a(e),T.add(e)),e):e}function O(e={}){return{...o,...e}}var E=new Set(Object.values(e)),A=new Set(["code","segment","path","redirect"]),R=new Set(["setCode","setErrorInstance","setAdditionalFields","hasField","getField","toJSON"]),S=class extends Error{segment;path;redirect;code;constructor(e,{message:t,segment:r,path:s,redirect:n,...o}={}){super(t??e),this.code=e,this.segment=r,this.path=s,this.redirect=n?function(e){if(!e)return e;if(null===(t=e)||"object"!=typeof t||"string"!=typeof t.name||"string"!=typeof t.path||"object"!=typeof t.params||null===t.params)throw new TypeError("[deepFreezeState] Expected valid State object, got: "+typeof e);var t;const r=structuredClone(e),s=new WeakSet;return function e(t){if(null===t||"object"!=typeof t)return;if(s.has(t))return;s.add(t),Object.freeze(t);const r=Array.isArray(t)?t:Object.values(t);for(const t of r)e(t)}(r),r}(n):void 0;for(const[e,t]of Object.entries(o)){if(A.has(e))throw new TypeError(`[RouterError] Cannot set reserved property "${e}"`);R.has(e)||(this[e]=t)}}setCode(e){this.code=e,E.has(this.message)&&(this.message=e)}setErrorInstance(e){if(!e)throw new TypeError("[RouterError.setErrorInstance] err parameter is required and must be an Error instance");this.message=e.message,this.cause=e.cause,this.stack=e.stack??""}setAdditionalFields(e){for(const[t,r]of Object.entries(e)){if(A.has(t))throw new TypeError(`[RouterError.setAdditionalFields] Cannot set reserved property "${t}"`);R.has(t)||(this[t]=r)}}hasField(e){return e in this}getField(e){return this[e]}toJSON(){const e={code:this.code,message:this.message};void 0!==this.segment&&(e.segment=this.segment),void 0!==this.path&&(e.path=this.path),void 0!==this.redirect&&(e.redirect=this.redirect);const t=new Set(["code","message","segment","path","redirect","stack"]);for(const r in this)Object.hasOwn(this,r)&&!t.has(r)&&(e[r]=this[r]);return e}};export{o as DEFAULT_LIMITS,i as EMPTY_PARAMS,S as RouterError,t as UNKNOWN_ROUTE,r as constants,O as createLimits,e as errorCodes,n as events,c as freezeStateInPlace,s as plugins};//# sourceMappingURL=chunk-5QXFUUDL.mjs.map
1
+ var e=Object.freeze({ROUTER_NOT_STARTED:"NOT_STARTED",NO_START_PATH_OR_STATE:"NO_START_PATH_OR_STATE",ROUTER_ALREADY_STARTED:"ALREADY_STARTED",ROUTE_NOT_FOUND:"ROUTE_NOT_FOUND",SAME_STATES:"SAME_STATES",CANNOT_DEACTIVATE:"CANNOT_DEACTIVATE",CANNOT_ACTIVATE:"CANNOT_ACTIVATE",TRANSITION_ERR:"TRANSITION_ERR",TRANSITION_CANCELLED:"CANCELLED",ROUTER_DISPOSED:"DISPOSED",PLUGIN_CONFLICT:"PLUGIN_CONFLICT"}),t="@@router/UNKNOWN_ROUTE",r={UNKNOWN_ROUTE:t},s={ROUTER_START:"onStart",ROUTER_STOP:"onStop",TRANSITION_START:"onTransitionStart",TRANSITION_CANCEL:"onTransitionCancel",TRANSITION_SUCCESS:"onTransitionSuccess",TRANSITION_ERROR:"onTransitionError"},n={ROUTER_START:"$start",ROUTER_STOP:"$stop",TRANSITION_START:"$$start",TRANSITION_CANCEL:"$$cancel",TRANSITION_SUCCESS:"$$success",TRANSITION_ERROR:"$$error"},o={maxDependencies:100,maxPlugins:50,maxListeners:1e4,warnListeners:1e3,maxEventDepth:5,maxLifecycleHandlers:200},i=Object.freeze({}),T=new WeakSet;function a(e){if(null!==e&&"object"==typeof e&&!Object.isFrozen(e))if(Object.freeze(e),Array.isArray(e))for(const t of e)a(t);else for(const t in e)a(e[t])}function c(e){return e?(T.has(e)||(a(e),T.add(e)),e):e}function O(e={}){return{...o,...e}}var E=new Set(Object.values(e)),A=new Set(["code","segment","path","redirect"]),R=new Set(["setCode","setErrorInstance","setAdditionalFields","hasField","getField","toJSON"]),S=class extends Error{segment;path;redirect;code;constructor(e,{message:t,segment:r,path:s,redirect:n,...o}={}){super(t??e),this.code=e,this.segment=r,this.path=s,this.redirect=n?function(e){if(!e)return e;if(null===(t=e)||"object"!=typeof t||"string"!=typeof t.name||"string"!=typeof t.path||"object"!=typeof t.params||null===t.params)throw new TypeError("[deepFreezeState] Expected valid State object, got: "+typeof e);var t;const r=structuredClone(e),s=new WeakSet;return function e(t){if(null===t||"object"!=typeof t)return;if(s.has(t))return;s.add(t),Object.freeze(t);const r=Array.isArray(t)?t:Object.values(t);for(const t of r)e(t)}(r),r}(n):void 0;for(const[e,t]of Object.entries(o)){if(A.has(e))throw new TypeError(`[RouterError] Cannot set reserved property "${e}"`);R.has(e)||(this[e]=t)}}setCode(e){this.code=e,E.has(this.message)&&(this.message=e)}setErrorInstance(e){if(!e)throw new TypeError("[RouterError.setErrorInstance] err parameter is required and must be an Error instance");this.message=e.message,this.cause=e.cause,this.stack=e.stack??""}setAdditionalFields(e){for(const[t,r]of Object.entries(e)){if(A.has(t))throw new TypeError(`[RouterError.setAdditionalFields] Cannot set reserved property "${t}"`);R.has(t)||(this[t]=r)}}hasField(e){return e in this}getField(e){return this[e]}toJSON(){const e={code:this.code,message:this.message};void 0!==this.segment&&(e.segment=this.segment),void 0!==this.path&&(e.path=this.path),void 0!==this.redirect&&(e.redirect=this.redirect);const t=new Set(["code","message","segment","path","redirect","stack"]);for(const r in this)Object.hasOwn(this,r)&&!t.has(r)&&(e[r]=this[r]);return e}};export{o as DEFAULT_LIMITS,i as EMPTY_PARAMS,S as RouterError,t as UNKNOWN_ROUTE,r as constants,O as createLimits,e as errorCodes,n as events,c as freezeStateInPlace,s as plugins};//# sourceMappingURL=chunk-EPF2YSMX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/RouterError.ts"],"names":[],"mappings":";AAyBO,IAAM,UAAA,GAAkC,OAAO,MAAA,CAAO;AAAA,EAC3D,kBAAA,EAAoB,aAAA;AAAA;AAAA,EACpB,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EACxB,sBAAA,EAAwB,iBAAA;AAAA;AAAA,EACxB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,WAAA,EAAa,aAAA;AAAA;AAAA,EACb,iBAAA,EAAmB,mBAAA;AAAA;AAAA,EACnB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,cAAA,EAAgB,gBAAA;AAAA;AAAA,EAChB,oBAAA,EAAsB,WAAA;AAAA;AAAA,EACtB,eAAA,EAAiB,UAAA;AAAA;AAAA,EACjB,eAAA,EAAiB;AAAA;AACnB,CAAC;AAMM,IAAM,aAAA,GAAgB;AAEtB,IAAM,SAAA,GAAuB;AAAA,EAClC;AACF;AAMO,IAAM,OA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chunk-5QXFUUDL.mjs","sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n} from \"@real-router/types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Record<ConstantsKeys, string>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\nexport const constants: Constants = {\n UNKNOWN_ROUTE,\n};\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = {\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n};\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = {\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n};\n\nexport const DEFAULT_LIMITS = {\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxEventDepth: 5,\n maxLifecycleHandlers: 200,\n} as const;\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n","// packages/core/src/helpers.ts\n\nimport { DEFAULT_LIMITS } from \"./constants\";\n\nimport type { Limits } from \"./types\";\nimport type { State, LimitsConfig } from \"@real-router/types\";\n\n// =============================================================================\n// State Helpers\n// =============================================================================\n\n/**\n * Structural type guard for State object.\n * Only checks required fields exist with correct types.\n * Does NOT validate params serializability (allows circular refs).\n *\n * Use `isState` from type-guards for full validation (serializable params).\n * Use this for internal operations like deepFreezeState that handle any object structure.\n *\n * @param value - Value to check\n * @returns true if value has State structure\n * @internal\n */\nfunction isStateStructural(value: unknown): value is State {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n return (\n typeof obj.name === \"string\" &&\n typeof obj.path === \"string\" &&\n typeof obj.params === \"object\" &&\n obj.params !== null\n );\n}\n\n/**\n * Deep freezes State object to prevent mutations.\n * Creates a deep clone first, then recursively freezes the clone and all nested objects.\n * Uses simple recursive freezing after cloning (no need for WeakSet since clone has no circular refs).\n *\n * @param state - The State object to freeze\n * @returns A frozen deep clone of the state\n * @throws {TypeError} If state is not a valid State object\n *\n * @example\n * const state = { name: 'home', params: {}, path: '/' };\n * const frozen = deepFreezeState(state);\n * // frozen.params is now immutable\n * // original state is unchanged\n */\nexport function deepFreezeState<T extends State>(state: T): T {\n // Early return for null/undefined\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Validate State structure (structural check, allows circular refs)\n if (!isStateStructural(state)) {\n throw new TypeError(\n `[deepFreezeState] Expected valid State object, got: ${typeof state}`,\n );\n }\n\n // Create a deep clone to avoid mutating the original\n // structuredClone preserves circular references, so we need to track visited objects\n const clonedState = structuredClone(state);\n\n // WeakSet to track visited objects (prevent infinite recursion with circular refs)\n const visited = new WeakSet<object>();\n\n // Recursive freeze function with circular reference protection\n function freezeClonedRecursive(obj: unknown): void {\n // Skip primitives, null, undefined\n // Note: typeof undefined === \"undefined\" !== \"object\", so checking undefined is redundant\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already visited objects (circular reference protection)\n if (visited.has(obj)) {\n return;\n }\n\n // Mark as visited\n visited.add(obj);\n\n // Freeze the object/array itself\n Object.freeze(obj);\n\n // Get all values to freeze recursively\n const values = Array.isArray(obj) ? obj : Object.values(obj);\n\n // Recursively freeze nested values\n for (const value of values) {\n freezeClonedRecursive(value);\n }\n }\n\n // Freeze the entire cloned state tree\n freezeClonedRecursive(clonedState);\n\n return clonedState;\n}\n\n// WeakSet to track already frozen root objects for O(1) re-freeze check\nconst frozenRoots = new WeakSet<object>();\n\n// Module-scope recursive freeze function - better JIT optimization, no allocation per call\nfunction freezeRecursive(obj: unknown): void {\n // Skip primitives, null\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already frozen objects (handles potential shared refs)\n if (Object.isFrozen(obj)) {\n return;\n }\n\n // Freeze the object/array\n Object.freeze(obj);\n\n // Iterate without Object.values() allocation\n if (Array.isArray(obj)) {\n for (const item of obj) {\n freezeRecursive(item);\n }\n } else {\n for (const key in obj) {\n freezeRecursive((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Freezes State object in-place without cloning.\n * Optimized for hot paths where state is known to be a fresh object.\n *\n * IMPORTANT: Only use this when you know the state is a fresh object\n * that hasn't been exposed to external code yet (e.g., from makeState()).\n *\n * @param state - The State object to freeze (must be a fresh object)\n * @returns The same state object, now frozen\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // Early return for null/undefined - state from makeState() is never null\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Fast path: already processed root object - O(1) check\n if (frozenRoots.has(state)) {\n return state;\n }\n\n // Freeze the entire state tree\n freezeRecursive(state);\n\n // Mark root as processed for future calls\n frozenRoots.add(state);\n\n return state;\n}\n\n/**\n * Merges user limits with defaults.\n * Returns frozen object for immutability.\n */\nexport function createLimits(userLimits: Partial<LimitsConfig> = {}): Limits {\n return { ...DEFAULT_LIMITS, ...userLimits };\n}\n","// packages/core/src/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\nimport { deepFreezeState } from \"./helpers\";\n\nimport type { State } from \"@real-router/types\";\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\nconst errorCodeValues = new Set(Object.values(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\", \"redirect\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with RouterError interface in core-types\n readonly segment: string | undefined;\n readonly path: string | undefined;\n readonly redirect: State | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path, redirect)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n * @param options.redirect - Optional redirect state for navigation errors\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n *\n * // Error with redirect\n * const err4 = new RouterError(\"TRANSITION_ERR\", {\n * redirect: { name: \"home\", path: \"/\", params: {} }\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n redirect,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n redirect?: State | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n // Deep freeze redirect to prevent mutations (creates a frozen clone)\n this.redirect = redirect ? deepFreezeState(redirect) : undefined;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of Object.entries(rest)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw new TypeError(\n \"[RouterError.setErrorInstance] err parameter is required and must be an Error instance\",\n );\n }\n\n this.message = err.message;\n this.cause = err.cause;\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of Object.entries(fields)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError.setAdditionalFields] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\", { segment: \"users\" });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"userId\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n return key in this;\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n return this[key];\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n if (this.redirect !== undefined) {\n result.redirect = this.redirect;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"redirect\",\n \"stack\",\n ]);\n\n for (const key in this) {\n if (Object.hasOwn(this, key) && !excludeKeys.has(key)) {\n result[key] = this[key];\n }\n }\n\n return result;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/RouterError.ts"],"names":[],"mappings":";AAyBO,IAAM,UAAA,GAAkC,OAAO,MAAA,CAAO;AAAA,EAC3D,kBAAA,EAAoB,aAAA;AAAA;AAAA,EACpB,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EACxB,sBAAA,EAAwB,iBAAA;AAAA;AAAA,EACxB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,WAAA,EAAa,aAAA;AAAA;AAAA,EACb,iBAAA,EAAmB,mBAAA;AAAA;AAAA,EACnB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,cAAA,EAAgB,gBAAA;AAAA;AAAA,EAChB,oBAAA,EAAsB,WAAA;AAAA;AAAA,EACtB,eAAA,EAAiB,UAAA;AAAA;AAAA,EACjB,eAAA,EAAiB;AAAA;AACnB,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AAA,CAAK,GAAG,CAAA;AAAA,MACxB;AAAA,IACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-EPF2YSMX.mjs","sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n} from \"@real-router/types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Record<ConstantsKeys, string>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\nexport const constants: Constants = {\n UNKNOWN_ROUTE,\n};\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = {\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n};\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = {\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n};\n\nexport const DEFAULT_LIMITS = {\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxEventDepth: 5,\n maxLifecycleHandlers: 200,\n} as const;\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n","// packages/core/src/helpers.ts\n\nimport { DEFAULT_LIMITS } from \"./constants\";\n\nimport type { Limits } from \"./types\";\nimport type { State, LimitsConfig } from \"@real-router/types\";\n\n// =============================================================================\n// State Helpers\n// =============================================================================\n\n/**\n * Structural type guard for State object.\n * Only checks required fields exist with correct types.\n * Does NOT validate params serializability (allows circular refs).\n *\n * Use `isState` from type-guards for full validation (serializable params).\n * Use this for internal operations like deepFreezeState that handle any object structure.\n *\n * @param value - Value to check\n * @returns true if value has State structure\n * @internal\n */\nfunction isStateStructural(value: unknown): value is State {\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n return (\n typeof obj.name === \"string\" &&\n typeof obj.path === \"string\" &&\n typeof obj.params === \"object\" &&\n obj.params !== null\n );\n}\n\n/**\n * Deep freezes State object to prevent mutations.\n * Creates a deep clone first, then recursively freezes the clone and all nested objects.\n * Uses simple recursive freezing after cloning (no need for WeakSet since clone has no circular refs).\n *\n * @param state - The State object to freeze\n * @returns A frozen deep clone of the state\n * @throws {TypeError} If state is not a valid State object\n *\n * @example\n * const state = { name: 'home', params: {}, path: '/' };\n * const frozen = deepFreezeState(state);\n * // frozen.params is now immutable\n * // original state is unchanged\n */\nexport function deepFreezeState<T extends State>(state: T): T {\n // Early return for null/undefined\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Validate State structure (structural check, allows circular refs)\n if (!isStateStructural(state)) {\n throw new TypeError(\n `[deepFreezeState] Expected valid State object, got: ${typeof state}`,\n );\n }\n\n // Create a deep clone to avoid mutating the original\n // structuredClone preserves circular references, so we need to track visited objects\n const clonedState = structuredClone(state);\n\n // WeakSet to track visited objects (prevent infinite recursion with circular refs)\n const visited = new WeakSet<object>();\n\n // Recursive freeze function with circular reference protection\n function freezeClonedRecursive(obj: unknown): void {\n // Skip primitives, null, undefined\n // Note: typeof undefined === \"undefined\" !== \"object\", so checking undefined is redundant\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already visited objects (circular reference protection)\n if (visited.has(obj)) {\n return;\n }\n\n // Mark as visited\n visited.add(obj);\n\n // Freeze the object/array itself\n Object.freeze(obj);\n\n // Get all values to freeze recursively\n const values = Array.isArray(obj) ? obj : Object.values(obj);\n\n // Recursively freeze nested values\n for (const value of values) {\n freezeClonedRecursive(value);\n }\n }\n\n // Freeze the entire cloned state tree\n freezeClonedRecursive(clonedState);\n\n return clonedState;\n}\n\n// WeakSet to track already frozen root objects for O(1) re-freeze check\nconst frozenRoots = new WeakSet<object>();\n\n// Module-scope recursive freeze function - better JIT optimization, no allocation per call\nfunction freezeRecursive(obj: unknown): void {\n // Skip primitives, null\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already frozen objects (handles potential shared refs)\n if (Object.isFrozen(obj)) {\n return;\n }\n\n // Freeze the object/array\n Object.freeze(obj);\n\n // Iterate without Object.values() allocation\n if (Array.isArray(obj)) {\n for (const item of obj) {\n freezeRecursive(item);\n }\n } else {\n for (const key in obj) {\n freezeRecursive((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Freezes State object in-place without cloning.\n * Optimized for hot paths where state is known to be a fresh object.\n *\n * IMPORTANT: Only use this when you know the state is a fresh object\n * that hasn't been exposed to external code yet (e.g., from makeState()).\n *\n * @param state - The State object to freeze (must be a fresh object)\n * @returns The same state object, now frozen\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // Early return for null/undefined - state from makeState() is never null\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Fast path: already processed root object - O(1) check\n if (frozenRoots.has(state)) {\n return state;\n }\n\n freezeRecursive(state);\n\n // Mark root as processed for future calls\n frozenRoots.add(state);\n\n return state;\n}\n\n/**\n * Merges user limits with defaults.\n * Returns frozen object for immutability.\n */\nexport function createLimits(userLimits: Partial<LimitsConfig> = {}): Limits {\n return { ...DEFAULT_LIMITS, ...userLimits };\n}\n","// packages/core/src/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\nimport { deepFreezeState } from \"./helpers\";\n\nimport type { State } from \"@real-router/types\";\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\nconst errorCodeValues = new Set(Object.values(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\", \"redirect\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with RouterError interface in core-types\n readonly segment: string | undefined;\n readonly path: string | undefined;\n readonly redirect: State | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path, redirect)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n * @param options.redirect - Optional redirect state for navigation errors\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n *\n * // Error with redirect\n * const err4 = new RouterError(\"TRANSITION_ERR\", {\n * redirect: { name: \"home\", path: \"/\", params: {} }\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n redirect,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n redirect?: State | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n // Deep freeze redirect to prevent mutations (creates a frozen clone)\n this.redirect = redirect ? deepFreezeState(redirect) : undefined;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of Object.entries(rest)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw new TypeError(\n \"[RouterError.setErrorInstance] err parameter is required and must be an Error instance\",\n );\n }\n\n this.message = err.message;\n this.cause = err.cause;\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of Object.entries(fields)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError.setAdditionalFields] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\", { segment: \"users\" });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"userId\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n return key in this;\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n return this[key];\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n if (this.redirect !== undefined) {\n result.redirect = this.redirect;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"redirect\",\n \"stack\",\n ]);\n\n for (const key in this) {\n if (Object.hasOwn(this, key) && !excludeKeys.has(key)) {\n result[key] = this[key];\n }\n }\n\n return result;\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ import{RouterError as t,errorCodes as e}from"./chunk-EPF2YSMX.mjs";import{getInternals as a}from"./chunk-UUG7DSTN.mjs";function r(a){if(a())throw new t(e.ROUTER_DISPOSED)}function o(o){const s=a(o);return{makeState:(t,e,a,r)=>(s.validator?.state.validateMakeStateArgs(t,e,a),s.makeState(t,e,a,r?.params)),buildState:(t,e)=>{s.validator?.routes.validateStateBuilderArgs(t,e,"buildState");const{name:a,params:r}=s.forwardState(t,e);return s.buildStateResolved(a,r)},forwardState:(t,e)=>(s.validator?.routes.validateStateBuilderArgs(t,e,"forwardState"),s.forwardState(t,e)),matchPath:t=>(s.validator?.routes.validateMatchPathArgs(t),s.matchPath(t,s.getOptions())),setRootPath:t=>{r(s.isDisposed),s.validator?.routes.validateSetRootPathArgs(t),s.setRootPath(t)},getRootPath:s.getRootPath,addEventListener:(t,e)=>(r(s.isDisposed),s.validator?.eventBus.validateListenerArgs(t,e),s.addEventListener(t,e)),buildNavigationState:(t,e={})=>{s.validator?.routes.validateStateBuilderArgs(t,e,"buildNavigationState");const{name:a,params:r}=s.forwardState(t,e),o=s.buildStateResolved(a,r);if(o)return s.makeState(o.name,o.params,s.buildPath(o.name,o.params),o.meta)},getOptions:s.getOptions,getTree:s.getTree,addInterceptor:(t,e)=>{r(s.isDisposed),s.validator?.plugins.validateAddInterceptorArgs(t,e);let a=s.interceptors.get(t);return a||(a=[],s.interceptors.set(t,a)),a.push(e),()=>{const t=a.indexOf(e);-1!==t&&a.splice(t,1)}},getRouteConfig:t=>{const e=s.routeGetStore();if(e.matcher.hasRoute(t))return e.routeCustomFields[t]},extendRouter:a=>{r(s.isDisposed);const i=Object.keys(a);for(const a of i)if(a in o)throw new t(e.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${a}" already exists`});for(const t of i)o[t]=a[t];const n={keys:i};s.routerExtensions.push(n);let d=!1;return()=>{if(d)return;d=!0;for(const t of n.keys)delete o[t];const t=s.routerExtensions.indexOf(n);-1!==t&&s.routerExtensions.splice(t,1)}}}}export{o as getPluginApi,r as throwIfDisposed};//# sourceMappingURL=chunk-UPJLWPEL.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts"],"names":[],"mappings":";AAKO,SAAS,gBAAgB,UAAA,EAAiC;AAC/D,EAAA,IAAI,YAAW,EAAG;AAChB,IAAA,MAAM,IAAI,WAAA,CAAY,UAAA,CAAW,eAAe,CAAA;AAAA,EAClD;AACF;;;ACDO,SAAS,aAEd,MAAA,EAAyC;AACzC,EAAA,MAAM,GAAA,GAAM,aAAa,MAAM,CAAA;AAE/B,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,CAAC,IAAA,EAAM,MAAA,EAAQ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AA,EAAM;AACtB,QAAC,MAAA,CAAmC,GAAG,CAAA,GAAI,UAAA,CAAW,GAAG,CAAA;AAAA,MAC3D;AAEA,MAAA,MAAM,eAAA,GAAkB,EAAE,IAAA,EAAK;AAE/B,MAAA,GAAA,CAAI,gBAAA,CAAiB,KAAK,eAAe,CAAA;AAEzC,MAAA,IAAI,OAAA,GAAU,KAAA;AAEd,MAAA,OAAO,MAAM;AACX,QAAA,IAAI,OAAA,EAAS;AACX,UAAA;AAAA,QACF;AAEA,QAAA,OAAA,GAAU,IAAA;AAEV,QAAA,KAAA,MAAW,GAAA,IAAO,gBAAgB,IAAA,EAAM;AACtC,UAAA,OAAQ,OAAmC,GAAG,CAAA;AAAA,QAChD;AAEA,QAAA,MAAM,GAAA,GAAM,GAAA,CAAI,gBAAA,CAAiB,OAAA,CAAQ,eAAe,CAAA;AAExD,QAAA,IAAI,QAAQ,EAAA,EAAI;AACd,UAAA,GAAA,CAAI,gBAAA,CAAiB,MAAA,CAAO,GAAA,EAAK,CAAC,CAAA;AAAA,QACpC;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACF;AACF","file":"chunk-UPJLWPEL.mjs","sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type { DefaultDependencies, Params, Router } from \"@real-router/types\";\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const ctx = getInternals(router);\n\n return {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n | Record<string, Record<string, \"url\" | \"query\">>\n | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n return () => {\n const index = list.indexOf(fn);\n\n if (index !== -1) {\n list.splice(index, 1);\n }\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n };\n}\n"]}
@@ -1 +1 @@
1
- var n=new WeakMap;function t(t){const r=n.get(t);if(!r)throw new TypeError("[real-router] Invalid router instance — not found in internals registry");return r}function r(t,r){n.set(t,r)}function e(n,t,r){let e=t;for(const t of n){const n=e;e=(...r)=>t(n,...r)}return e(...r)}function o(n,t,r){return(...o)=>{const u=r.get(n);return u&&0!==u.length?e(u,t,o):t(...o)}}function u(n,t,r){return(o,u)=>{const c=r.get(n);return c&&0!==c.length?e(c,t,[o,u]):t(o,u)}}export{o as createInterceptable,u as createInterceptable2,t as getInternals,r as registerInternals};//# sourceMappingURL=chunk-QUUNDESP.mjs.map
1
+ var n=new WeakMap;function t(t){const r=n.get(t);if(!r)throw new TypeError("[real-router] Invalid router instance — not found in internals registry");return r}function r(t,r){n.set(t,r)}function e(n,t,r){let e=t;for(const t of n){const n=e;e=(...r)=>t(n,...r)}return e(...r)}function o(n,t,r){return(...o)=>{const u=r.get(n);return u&&0!==u.length?e(u,t,o):t(...o)}}function u(n,t,r){return(o,u)=>{const c=r.get(n);return c&&0!==c.length?e(c,t,[o,u]):t(o,u)}}export{o as createInterceptable,u as createInterceptable2,t as getInternals,r as registerInternals};//# sourceMappingURL=chunk-UUG7DSTN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/internals.ts"],"names":[],"mappings":";AA+FA,IAAM,SAAA,uBAAgB,OAAA,EAAsC;AAErD,SAAS,aACd,MAAA,EACoB;AACpB,EAAA,MAAM,GAAA,GAAM,SAAA,CAAU,GAAA,CAAI,MAAM,CAAA;AAEhC,EAAA,IAAI,CAAC,GAAA,EAAK;AACR,IAAA,MAAM,IAAI,SAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,OAAO,GAAA;AACT;AAEO,SAAS,iBAAA,CACd,QACA,GAAA,EACM;AACN,EAAA,SAAA,CAAU,GAAA,CAAI,QAAQ,GAAG,CAAA;AAC3B;AAGA,SAAS,uBAAA,CACP,YAAA,EACA,QAAA,EACA,IAAA,EACG;AACH,EAAA,IAAI,KAAA,GAAQ,QAAA;AAEZ,EAAA,KAAA,MAAW,eAAe,YAAA,EAAc;AACtC,IAAA,MAAM,IAAA,GAAO,KAAA;AAEb,IAAA,KAAA,GAAQ,CAAA,GAAI,SAAA,KAAqB,WAAA,CAAY,IAAA,EAAM,GAAG,SAAS,CAAA;AAAA,EACjE;AAEA,EAAA,OAAO,KAAA,CAAM,GAAG,IAAI,CAAA;AACtB;AAEO,SAAS,mBAAA,CACd,IAAA,EACA,QAAA,EACA,YAAA,EAIG;AACH,EAAA,QAAQ,IAAI,IAAA,KAAgB;AAC1B,IAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AAEnC,IAAA,IAAI,CAAC,KAAA,IAAS,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG;AAChC,MAAA,OAAO,QAAA,CAAS,GAAG,IAAI,CAAA;AAAA,IACzB;AAEA,IAAA,OAAO,uBAAA,CAAwB,KAAA,EAAO,QAAA,EAAU,IAAI,CAAA;AAAA,EACtD,CAAA;AACF;AAEO,SAAS,oBAAA,CACd,IAAA,EACA,QAAA,EACA,YAAA,EAImB;AACnB,EAAA,OAAO,CAAC,MAAS,IAAA,KAAY;AAC3B,IAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,GAAA,CAAI,IAAI,CAAA;AAEnC,IAAA,IAAI,CAAC,KAAA,IAAS,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG;AAChC,MAAA,OAAO,QAAA,CAAS,MAAM,IAAI,CAAA;AAAA,IAC5B;AAEA,IAAA,OAAO,wBAAwB,KAAA,EAAO,QAAA,EAAU,CAAC,IAAA,EAAM,IAAI,CAAC,CAAA;AAAA,EAC9D,CAAA;AACF","file":"chunk-UUG7DSTN.mjs","sourcesContent":["import type { DependenciesStore } from \"./namespaces/DependenciesNamespace\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type { EventMethodMap, GuardFnFactory, PluginFactory } from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\nimport type {\n DefaultDependencies,\n EventName,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouteTreeState,\n SimpleState,\n State,\n Unsubscribe,\n} from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <P extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: Record<string, Record<string, \"url\" | \"query\">>,\n ) => State<P>;\n\n readonly forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => SimpleState<P>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: Options,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n readonly buildPath: (route: string, params?: Params) => string;\n\n readonly start: (path: string) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173)\n readonly cloneOptions: () => Options;\n readonly cloneDependencies: () => Record<string, unknown>;\n readonly getLifecycleFactories: () => [\n Record<string, GuardFnFactory<D>>,\n Record<string, GuardFnFactory<D>>,\n ];\n readonly getPluginFactories: () => PluginFactory<D>[];\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n readonly clearState: () => void;\n readonly setState: (state: State) => void;\n readonly routerExtensions: { keys: string[] }[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\nexport function createInterceptable2<A, B, R>(\n name: string,\n original: (a: A, b: B) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B) => R {\n return (arg1: A, arg2: B) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n"]}
@@ -0,0 +1 @@
1
+ import{plugins as t,events as e,RouterError as n,errorCodes as i,constants as s,createLimits as r,EMPTY_PARAMS as a,DEFAULT_LIMITS as o,freezeStateInPlace as c}from"./chunk-EPF2YSMX.mjs";import{registerInternals as u,createInterceptable as l,createInterceptable2 as h,getInternals as d}from"./chunk-UUG7DSTN.mjs";import{logger as f}from"@real-router/logger";import{FSM as p}from"@real-router/fsm";function m(t,e,n=100){const i=new Set,s=[t];let r=t;for(;e[r];){const t=e[r];if(i.has(t)){const e=s.indexOf(t),n=[...s.slice(e),t];throw new Error(`Circular forwardTo: ${n.join(" → ")}`)}if(i.add(r),s.push(t),r=t,s.length>n)throw new Error(`forwardTo chain exceeds maximum depth (${n}): ${s.join(" → ")}`)}return r}var g={maxListeners:0,warnListeners:0,maxEventDepth:0},v=class extends Error{},S=class{#t=new Map;#e=null;#n=g;#i;#s;constructor(t){t?.limits&&(this.#n=t.limits),this.#i=t?.onListenerError??null,this.#s=t?.onListenerWarn??null}static validateCallback(t,e){if("function"!=typeof t)throw new TypeError(`Expected callback to be a function for event ${e}`)}setLimits(t){this.#n=t}on(t,e){const n=this.#r(t);if(n.has(e))throw new Error(`Duplicate listener for "${t}"`);const{maxListeners:i,warnListeners:s}=this.#n;if(0!==s&&n.size===s&&this.#s?.(t,s),0!==i&&n.size>=i)throw new Error(`Listener limit (${i}) reached for "${t}"`);return n.add(e),()=>{this.off(t,e)}}off(t,e){this.#t.get(t)?.delete(e)}emit(t,e,n,i,s){const r=this.#t.get(t);if(!r||0===r.size)return;const a=arguments.length-1;0!==this.#n.maxEventDepth?this.#a(r,t,a,e,n,i,s):this.#o(r,t,a,e,n,i,s)}clearAll(){this.#t.clear(),this.#e=null}listenerCount(t){return this.#t.get(t)?.size??0}#o(t,e,n,i,s,r,a){if(1===t.size){const[o]=t;try{this.#c(o,n,i,s,r,a)}catch(t){this.#i?.(e,t)}return}const o=[...t];for(const t of o)try{this.#c(t,n,i,s,r,a)}catch(t){this.#i?.(e,t)}}#c(t,e,n,i,s,r){switch(e){case 0:t();break;case 1:t(n);break;case 2:t(n,i);break;case 3:t(n,i,s);break;default:t(n,i,s,r)}}#a(t,e,n,i,s,r,a){this.#e??=new Map;const o=this.#e,c=o.get(e)??0;if(c>=this.#n.maxEventDepth)throw new v(`Maximum recursion depth (${this.#n.maxEventDepth}) exceeded for event: ${e}`);try{o.set(e,c+1);const u=1===t.size?t:[...t];for(const t of u)try{this.#c(t,n,i,s,r,a)}catch(t){if(t instanceof v)throw t;this.#i?.(e,t)}}finally{o.set(e,o.get(e)-1)}}#r(t){const e=this.#t.get(t);if(e)return e;const n=new Set;return this.#t.set(t,n),n}},y="IDLE",T="STARTING",w="READY",b="TRANSITIONING",N="DISPOSED",P="START",A="STARTED",O="NAVIGATE",E="COMPLETE",R="FAIL",C="CANCEL",D="STOP",F="DISPOSE",j={initial:y,context:null,transitions:{[y]:{[P]:T,[F]:N},[T]:{[A]:w,[R]:y},[w]:{[O]:b,[R]:w,[D]:y},[b]:{[O]:b,[E]:w,[C]:w,[R]:w},[N]:{}}};function L(t,e){for(const n of t){if(null===n||"object"!=typeof n||Array.isArray(n))throw new TypeError("route must be a non-array object");e?.routes.guardRouteCallbacks(n),e?.routes.guardNoAsyncCallbacks(n);const t=n.children;t&&L(t,e)}}var I={defaultRoute:"",defaultParams:{},trailingSlash:"preserve",queryParamsMode:"loose",queryParams:{arrayFormat:"none",booleanFormat:"none",nullFormat:"default"},urlParamsEncoding:"default",allowNotFound:!0,rewritePathOnMatch:!0};function M(t){Object.freeze(t);for(const e of Object.keys(t)){const n=t[e];n&&"object"==typeof n&&n.constructor===Object&&M(n)}return t}function U(t,e){return"function"==typeof t?t(e):t}var $=class{#u;constructor(t={}){this.#u=M({...I,...t})}static validateOptionsIsObject(t){!function(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("[router.constructor] options must be a plain object")}(t)}get(){return this.#u}};function B(t,e){if(t===e)return!0;if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!B(t[n],e[n]))return!1;return!0}return!1}var _=new WeakMap;function k(t){return _.get(t)}var x=class{#l=void 0;#h=void 0;#d;#f=new Map;get(){return this.#l}set(t){this.#h=this.#l,this.#l=t?c(t):void 0}getPrevious(){return this.#h}reset(){this.#l=void 0,this.#h=void 0,this.#f.clear()}setDependencies(t){this.#d=t}makeState(t,e,n,i,s){const r=this.#d.getDefaultParams();let o;o=Object.hasOwn(r,t)?{...r[t],...e}:e&&e!==a?{...e}:a;const u={name:t,params:o,path:n??this.#d.buildPath(t,e)};return i&&function(t,e){_.set(t,e)}(u,i),s?u:c(u)}areStatesEqual(t,e,n=!0){if(!t||!e)return!!t==!!e;if(t.name!==e.name)return!1;if(n){const n=this.#p(t.name);for(const i of n)if(!B(t.params[i],e.params[i]))return!1;return!0}const i=Object.keys(t.params),s=Object.keys(e.params);if(i.length!==s.length)return!1;for(const n of i)if(!(n in e.params)||!B(t.params[n],e.params[n]))return!1;return!0}#p(t){const e=this.#f.get(t);if(void 0!==e)return e;const n=this.#d.getUrlParams(t);return this.#f.set(t,n),n}},z={[t.ROUTER_START]:e.ROUTER_START,[t.ROUTER_STOP]:e.ROUTER_STOP,[t.TRANSITION_SUCCESS]:e.TRANSITION_SUCCESS,[t.TRANSITION_START]:e.TRANSITION_START,[t.TRANSITION_ERROR]:e.TRANSITION_ERROR,[t.TRANSITION_CANCEL]:e.TRANSITION_CANCEL},G=Object.keys(z),q="router.usePlugin",W=class t{#m=new Set;#g=new Set;#d;#v=o;#S=null;static validatePlugin(t){!function(t){if(!t||"object"!=typeof t||Array.isArray(t))throw new TypeError("[router.usePlugin] Plugin factory must return an object, got "+typeof t);if("function"==typeof t.then)throw new TypeError("[router.usePlugin] Async plugin factories are not supported. Factory returned a Promise instead of a plugin object.")}(t)}static validateNoDuplicatePlugins(t,e){for(const n of t)if(e(n))throw new Error("[router.usePlugin] Plugin factory already registered. To re-register, first unsubscribe the existing plugin.")}setDependencies(t){this.#d=t}setLimits(t){this.#v=t,this.#v}setValidatorGetter(t){this.#S=t}count(){return this.#m.size}use(...t){if(this.#S?.()?.plugins.validateCountThresholds(this.#m.size+t.length),1===t.length){const e=t[0],n=this.#y(e);this.#m.add(e);let i=!1;const s=()=>{if(!i){i=!0,this.#m.delete(e),this.#g.delete(s);try{n()}catch(t){f.error(q,"Error during cleanup:",t)}}};return this.#g.add(s),s}const e=this.#T(t),n=[];try{for(const t of e){const e=this.#y(t);n.push({factory:t,cleanup:e})}}catch(t){for(const{cleanup:t}of n)try{t()}catch(t){f.error(q,"Cleanup error:",t)}throw t}for(const{factory:t}of n)this.#m.add(t);let i=!1;const s=()=>{if(!i){i=!0,this.#g.delete(s);for(const{factory:t}of n)this.#m.delete(t);for(const{cleanup:t}of n)try{t()}catch(t){f.error(q,"Error during cleanup:",t)}}};return this.#g.add(s),s}getAll(){return[...this.#m]}has(t){return this.#m.has(t)}disposeAll(){for(const t of this.#g)t();this.#m.clear(),this.#g.clear()}#T(t){const e=new Set;for(const n of t)e.has(n)?this.#S?.()?.plugins.warnBatchDuplicates(t):e.add(n);return e}#y(e){const n=this.#d.compileFactory(e);t.validatePlugin(n),this.#S?.()?.plugins.validatePluginKeys(n),Object.freeze(n);const i=[];for(const t of G)t in n&&("function"==typeof n[t]?(i.push(this.#d.addEventListener(z[t],n[t])),"onStart"===t&&this.#d.canNavigate()&&this.#S?.()?.plugins.warnPluginAfterStart(t)):this.#S?.()?.plugins.warnPluginMethodType(t));return()=>{for(const t of i)t();"function"==typeof n.teardown&&n.teardown()}}},V=class{#w=new Map;#b=new Map;#N=new Map;#P=new Map;#A=[this.#N,this.#P];#O=new Set;#E=new Set;#R=new Set;#d;#v=o;#S=null;setDependencies(t){this.#d=t}setLimits(t){this.#v=t,this.#v}setValidatorGetter(t){this.#S=t}getHandlerCount(t){return"activate"===t?this.#b.size:this.#w.size}addCanActivate(t,e,n=!1){n?this.#E.add(t):this.#E.delete(t);const i=this.#b.has(t);this.#C("activate",t,e,this.#b,this.#P,"canActivate",i)}addCanDeactivate(t,e,n=!1){n?this.#R.add(t):this.#R.delete(t);const i=this.#w.has(t);this.#C("deactivate",t,e,this.#w,this.#N,"canDeactivate",i)}clearCanActivate(t){this.#b.delete(t),this.#P.delete(t),this.#E.delete(t)}clearCanDeactivate(t){this.#w.delete(t),this.#N.delete(t),this.#R.delete(t)}clearAll(){this.#b.clear(),this.#P.clear(),this.#w.clear(),this.#N.clear(),this.#E.clear(),this.#R.clear()}clearDefinitionGuards(){for(const t of this.#E)this.#b.delete(t),this.#P.delete(t);for(const t of this.#R)this.#w.delete(t),this.#N.delete(t);this.#E.clear(),this.#R.clear()}getFactories(){const t={},e={};for(const[e,n]of this.#w)t[e]=n;for(const[t,n]of this.#b)e[t]=n;return[t,e]}getFunctions(){return this.#A}canNavigateTo(t,e,n,i){for(const e of t)if(!this.#D(this.#N,e,n,i,"canNavigateTo"))return!1;for(const t of e)if(!this.#D(this.#P,t,n,i,"canNavigateTo"))return!1;return!0}#C(t,e,n,i,s,r,a){a?this.#S?.()?.lifecycle.warnOverwrite(e,t,r):this.#S?.()?.lifecycle.validateCountThresholds(i.size+1,r);const o="boolean"==typeof n?function(t){const e=()=>t;return()=>e}(n):n;i.set(e,o),this.#O.add(e);try{const t=this.#d.compileFactory(o);if("function"!=typeof t)throw new TypeError(`[router.${r}] Factory must return a function, got ${typeof t}`);s.set(e,t)}catch(t){throw i.delete(e),t}finally{this.#O.delete(e)}}#D(t,e,n,i,s){const r=t.get(e);if(!r)return!0;try{const t=r(n,i);return"boolean"==typeof t?t:(this.#S?.()?.lifecycle.warnAsyncGuardSync(e,s),!1)}catch{return!1}}};function Q(){return{decoders:Object.create(null),encoders:Object.create(null),defaultParams:Object.create(null),forwardMap:Object.create(null),forwardFnMap:Object.create(null)}}function K(t){const e={name:t.name,path:t.path};return t.children&&(e.children=t.children.map(t=>K(t))),e}function H(t,e,n=""){for(let i=0;i<t.length;i++){const s=t[i],r=n?`${n}.${s.name}`:s.name;if(r===e)return t.splice(i,1),!0;if(s.children&&e.startsWith(`${r}.`)&&H(s.children,e,r))return!0}return!1}function J(t,e){for(const n of Object.keys(t))e(n)&&delete t[n]}function Y(t){return`(${t.replaceAll(/(^<|>$)/g,"")})`}var X=/([:*])([^/?<]+)(<[^>]+>)?(\?)?/g,Z=/([:*][^/?<]+(?:<[^>]+>)?)\?(?=\/|$)/g,tt=/\?(.+)$/,et=/[^\w!$'()*+,.:;|~-]/gu,nt=/[^\w!$'()*+,.:;|~-]/u,it={default:t=>nt.test(t)?t.replaceAll(et,t=>encodeURIComponent(t)):t,uri:encodeURI,uriComponent:encodeURIComponent,none:t=>t},st={default:decodeURIComponent,uri:decodeURI,uriComponent:decodeURIComponent,none:t=>t};function rt(){return{staticChildren:Object.create(null),paramChild:void 0,splatChild:void 0,route:void 0,slashChildRoute:void 0}}function at(t){return t.length>1&&t.endsWith("/")?t.slice(0,-1):t}function ot(t){const e={};if(0===t.length)return e;const n=t.split("&");for(const t of n){const n=t.indexOf("=");-1===n?e[t]="":e[t.slice(0,n)]=t.slice(n+1)}return e}function ct(t){const e=[];for(const n of Object.keys(t)){const i=t[n],s=encodeURIComponent(n);e.push(""===i?s:`${s}=${encodeURIComponent(String(i))}`)}return e.join("&")}function ut(t){return t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102}function lt(t){let e=0;for(;e<t.length;)if("%"===t[e]){if(e+2>=t.length)return!1;const n=t.codePointAt(e+1)??0,i=t.codePointAt(e+2)??0;if(!ut(n)||!ut(i))return!1;e+=3}else e++;return!0}var ht=/<[^>]*>/g;function dt(t,e,n,i,s){const r=""===e.fullName;r||i.push(e);const a=e.absolute,o=e.paramMeta.pathPattern,c=a&&o.startsWith("~")?o.slice(1):o,u=(a?c:o).replaceAll(ht,""),l=a?u:(d=u,""===(h=n)?d:""===d?h:h+d);var h,d;let f=s;r||(f=function(t,e,n,i,s,r){const a=(g=i,at(n)===at(g)),o=Object.freeze([...s]),c=function(t){const e={};for(const n of t)e[n.fullName]=n.paramTypeMap;return Object.freeze(e)}(o),u=at(n),l=function(t,e){const n=[];t.length>0&&n.push(...t);for(const t of e)t.paramMeta.queryParams.length>0&&n.push(...t.paramMeta.queryParams);return n}(t.rootQueryParams,s),h=function(t){const e=new Map;for(const n of t)for(const[t,i]of n.paramMeta.constraintPatterns)e.set(t,i);return e}(s),d=a?at(i):u,{buildStaticParts:f,buildParamSlots:p}=function(t,e,n){const i=new Set,s=new Set;for(const t of e){for(const e of t.paramMeta.urlParams)i.add(e);for(const e of t.paramMeta.spatParams)s.add(e)}if(0===i.size)return{buildStaticParts:[t],buildParamSlots:[]};const r=[],a=[],o=/[:*]([\w]+)(?:<[^>]*>)?(\?)?/gu;let c,u=0;for(;null!==(c=o.exec(t));){const e=c[1],i="?"===c[2];r.push(t.slice(u,c.index));const o=s.has(e);a.push({paramName:e,isOptional:i,encoder:o?t=>{const e=it[n],i=t.split("/");let s=e(i[0]);for(let t=1;t<i.length;t++)s+=`/${e(i[t])}`;return s}:it[n]}),u=c.index+c[0].length}return r.push(t.slice(u)),{buildStaticParts:r,buildParamSlots:a}}(d,a?s.slice(0,-1):s,t.options.urlParamsEncoding),m={name:e.fullName,parent:r,depth:s.length-1,matchSegments:o,meta:c,declaredQueryParams:l,declaredQueryParamsSet:new Set(l),hasTrailingSlash:n.length>1&&n.endsWith("/"),constraintPatterns:h,hasConstraints:h.size>0,buildStaticParts:f,buildParamSlots:p,buildParamNamesSet:new Set(p.map(t=>t.paramName))};var g;return t.routesByName.set(e.fullName,m),t.segmentsByName.set(e.fullName,o),t.metaByName.set(e.fullName,c),a?function(t,e,n){var i,s;i=e,(function(t,e,n){const i=at(n);if("/"===i||""===i)return e;let s=e,r=1;const a=i.length;for(;r<=a;){const e=i.indexOf("/",r),n=-1===e?a:e;if(n<=r)break;s=pt(t,s,i.slice(r,n)),r=n+1}return s}(s=t,s.root,n)).slashChildRoute=i;const r=at(n),a=t.options.caseSensitive?r:r.toLowerCase();t.staticCache.has(a)&&t.staticCache.set(a,e)}(t,m,i):function(t,e,n,i,s){if(function(t,e,n){const i=at(n);"/"!==i?ft(t,t.root,i,1,e):t.root.route=e}(t,e,n),0===s.paramMeta.urlParams.length){const n=t.options.caseSensitive?i:i.toLowerCase();t.staticCache.set(n,e)}}(t,m,n,u,e),m}(t,e,l,a?"":n,i,s));for(const n of e.children.values())dt(t,n,l,i,f);r||i.pop()}function ft(t,e,n,i,s){const r=n.length;for(;i<=r;){const a=n.indexOf("/",i),o=-1===a?r:a,c=n.slice(i,o);if(c.endsWith("?")){const i=c.slice(1).replaceAll(ht,"").replace(/\?$/,"");return e.paramChild??={node:rt(),name:i},ft(t,e.paramChild.node,n,o+1,s),void(o>=r?e.route??=s:ft(t,e,n,o+1,s))}e=pt(t,e,c),i=o+1}e.route=s}function pt(t,e,n){if(n.startsWith("*")){const t=n.slice(1);return e.splatChild??={node:rt(),name:t},e.splatChild.node}if(n.startsWith(":")){const t=n.slice(1).replaceAll(ht,"").replace(/\?$/,"");return e.paramChild??={node:rt(),name:t},e.paramChild.node}const i=t.options.caseSensitive?n:n.toLowerCase();return i in e.staticChildren||(e.staticChildren[i]=rt()),e.staticChildren[i]}var mt=/[\u0080-\uFFFF]/,gt=class{get options(){return this.#t}#t;#e=rt();#s=new Map;#r=new Map;#n=new Map;#a=new Map;#i="";#F=[];constructor(t){this.#t={caseSensitive:t?.caseSensitive??!0,strictTrailingSlash:t?.strictTrailingSlash??!1,strictQueryParams:t?.strictQueryParams??!1,urlParamsEncoding:t?.urlParamsEncoding??"default",parseQueryString:t?.parseQueryString??ot,buildQueryString:t?.buildQueryString??ct}}registerTree(t){this.#F=t.paramMeta.queryParams,dt({root:this.#e,options:this.#t,routesByName:this.#s,segmentsByName:this.#r,metaByName:this.#n,staticCache:this.#a,rootQueryParams:this.#F},t,"",[],null)}match(t){const e=this.#c(t);if(!e)return;const[n,i,s]=e,r=this.#t.caseSensitive?i:i.toLowerCase(),a=this.#a.get(r);if(a){if(this.#t.strictTrailingSlash&&!this.#o(n,a))return;return this.#j(a,{},s)}const o={},c=this.#L(i,o);return!c||this.#t.strictTrailingSlash&&!this.#o(n,c)||c.hasConstraints&&!this.#I(o,c)||!this.#M(o)?void 0:this.#j(c,o,s)}buildPath(t,e,n){const i=this.#s.get(t);if(!i)throw new Error(`[SegmentMatcher.buildPath] '${t}' is not defined`);i.hasConstraints&&e&&this.#U(i,t,e);const s=this.#$(i,e),r=this.#B(s,n?.trailingSlash),a=this.#_(i,e,n?.queryParamsMode);return r+(a?`?${a}`:"")}getSegmentsByName(t){return this.#r.get(t)}getMetaByName(t){return this.#n.get(t)}hasRoute(t){return this.#s.has(t)}setRootPath(t){this.#i=t}#U(t,e,n){for(const[i,s]of t.constraintPatterns){const t=n[i];if(null!=t){const n="object"==typeof t?JSON.stringify(t):String(t);if(!s.pattern.test(n))throw new Error(`[SegmentMatcher.buildPath] '${e}' — param '${i}' value '${n}' does not match constraint '${s.constraint}'`)}}}#$(t,e){const n=t.buildStaticParts,i=t.buildParamSlots;if(0===i.length)return this.#i+n[0];let s=this.#i+n[0];for(const[t,r]of i.entries()){const i=e?.[r.paramName];if(null==i){if(!r.isOptional)throw new Error(`[SegmentMatcher.buildPath] Missing required param '${r.paramName}'`);s.length>1&&s.endsWith("/")&&(s=s.slice(0,-1)),s+=n[t+1];continue}const a="object"==typeof i?JSON.stringify(i):String(i);s+=r.encoder(a)+n[t+1]}return s}#B(t,e){return"always"!==e||t.endsWith("/")?"never"===e&&"/"!==t&&t.endsWith("/")?t.slice(0,-1):t:`${t}/`}#_(t,e,n){if(!e)return"";const i={};let s=!1;for(const n of t.declaredQueryParams)n in e&&(i[n]=e[n],s=!0);if("loose"===n)for(const n in e)!Object.hasOwn(e,n)||t.declaredQueryParamsSet.has(n)||t.buildParamNamesSet.has(n)||(i[n]=e[n],s=!0);return s?this.#t.buildQueryString(i):""}#c(t){if(""===t&&(t="/"),!t.startsWith("/"))return;const e=t.indexOf("#");if(-1!==e&&(t=t.slice(0,e)),mt.test(t))return;if(this.#i.length>0){if(!t.startsWith(this.#i))return;t=t.slice(this.#i.length)||"/"}const n=t.indexOf("?"),i=-1===n?t:t.slice(0,n),s=-1===n?void 0:t.slice(n+1);return i.includes("//")?void 0:[i,at(i),s]}#j(t,e,n){if(void 0!==n){const i=this.#t.parseQueryString(n);if(this.#t.strictQueryParams){const e=t.declaredQueryParamsSet;for(const t of Object.keys(i))if(!e.has(t))return}for(const t of Object.keys(i))e[t]=i[t]}return{segments:t.matchSegments,params:e,meta:t.meta}}#o(t,e){return(t.length>1&&t.endsWith("/"))===e.hasTrailingSlash}#L(t,e){return 1===t.length?this.#e.slashChildRoute??this.#e.route:this.#k(this.#e,t,1,e)}#k(t,e,n,i){let s=t;const r=e.length;for(;n<=r;){const t=e.indexOf("/",n),a=-1===t?r:t,o=e.slice(n,a),c=this.#t.caseSensitive?o:o.toLowerCase();let u;if(c in s.staticChildren)u=s.staticChildren[c];else{if(!s.paramChild){if(s.splatChild){const t={},r=this.#k(s.splatChild.node,e,n,t);return r?(Object.assign(i,t),r):(i[s.splatChild.name]=e.slice(n),s.splatChild.node.route)}return}u=s.paramChild.node,i[s.paramChild.name]=o}s=u,n=a+1}return s.slashChildRoute??s.route}#M(t){const e=this.#t.urlParamsEncoding;if("none"===e)return!0;const n=st[e];for(const e in t){const i=t[e];if(i.includes("%")){if(!lt(i))return!1;t[e]=n(i)}}return!0}#I(t,e){for(const[n,i]of e.constraintPatterns)if(!i.pattern.test(t[n]))return!1;return!0}},vt=t=>{const e=t.indexOf("%"),n=t.indexOf("+");if(-1===e&&-1===n)return t;const i=-1===n?t:t.split("+").join(" ");return-1===e?i:decodeURIComponent(i)},St=t=>{const e=typeof t;if("string"!==e&&"number"!==e&&"boolean"!==e)throw new TypeError(`[search-params] Array element must be a string, number, or boolean — received ${"object"===e&&null===t?"null":e}`);return encodeURIComponent(t)},yt={none:{encodeArray:(t,e)=>e.map(e=>`${t}=${St(e)}`).join("&")},brackets:{encodeArray:(t,e)=>e.map(e=>`${t}[]=${St(e)}`).join("&")},index:{encodeArray:(t,e)=>e.map((e,n)=>`${t}[${n}]=${St(e)}`).join("&")},comma:{encodeArray:(t,e)=>`${t}=${e.map(t=>St(t)).join(",")}`}},Tt={none:{encode:(t,e)=>`${t}=${e}`,decodeUndefined:()=>null,decodeRaw:()=>null,decodeValue:t=>t},string:{encode:(t,e)=>`${t}=${e}`,decodeUndefined:()=>null,decodeRaw:t=>"true"===t||"false"!==t&&null,decodeValue:t=>t},"empty-true":{encode:(t,e)=>e?t:`${t}=false`,decodeUndefined:()=>!0,decodeRaw:()=>null,decodeValue:t=>t}},wt={default:{encode:t=>t},hidden:{encode:()=>""}},bt=(t,e,n)=>({boolean:Tt[e],null:wt[n],array:yt[t]}),Nt={arrayFormat:"none",booleanFormat:"none",nullFormat:"default",strategies:{boolean:Tt.none,null:wt.default,array:yt.none}},Pt=t=>{if(!t||void 0===t.arrayFormat&&void 0===t.booleanFormat&&void 0===t.nullFormat)return Nt;const e=t.arrayFormat??"none",n=t.booleanFormat??"none",i=t.nullFormat??"default";return{arrayFormat:e,booleanFormat:n,nullFormat:i,strategies:bt(e,n,i)}},At=t=>encodeURIComponent(t),Ot=(t,e,n)=>{const i=At(t);switch(typeof e){case"string":case"number":default:return`${i}=${At(e)}`;case"boolean":return n.strategies.boolean.encode(i,e);case"object":return null===e?n.strategies.null.encode(i):Array.isArray(e)?n.strategies.array.encodeArray(i,e):`${i}=${At(e)}`}};function Et(t,e,n,i,s){const r=t.indexOf("=",e),a=-1!==r&&r<n,o=t.slice(e,a?r:n),{name:c,hasBrackets:u}=function(t){const e=t.indexOf("[");return-1===e?{name:t,hasBrackets:!1}:{name:t.slice(0,e),hasBrackets:!0}}(o);var l,h,d,f,p;!function(t,e,n,i){const s=t[e];void 0===s?t[e]=i?[n]:n:Array.isArray(s)?s.push(n):t[e]=[s,n]}(i,vt(c),(l=t,h=r,d=n,f=a,p=s,p?((t,e)=>{if(void 0===t)return e.boolean.decodeUndefined();const n=e.boolean.decodeRaw(t);if(null!==n)return n;const i=vt(t);return e.boolean.decodeValue(i)})(f?l.slice(h+1,d):void 0,p):f?vt(l.slice(h+1,d)):null),u)}function Rt(t,e){const n=t.path,i=n.startsWith("~"),s=i?n.slice(1):n,r={name:t.name,path:s,absolute:i,children:[],parent:e,nonAbsoluteChildren:[],fullName:""};if(t.children)for(const e of t.children){const t=Rt(e,r);r.children.push(t)}return r}function Ct(t,e){return t.endsWith("/")&&e.startsWith("/")?t+e.slice(1):t+e}function Dt(t){const e=new Map;for(const n of t)e.set(n.name,n);return e}function Ft(t,e,n){const i=function(t){const e=[],n=[],i=[],s={},r=new Map,a=t.replaceAll(Z,"$1"),o=tt.exec(a);if(null!==o){const e=o[1].split("&");for(const t of e){const e=t.trim();e.length>0&&(n.push(e),s[e]="query")}t=t.slice(0,o.index)}let c;for(;null!==(c=X.exec(t));){const t=c[2],n=c[3];if("*"===c[1])i.push(t),e.push(t),s[t]="url";else if(e.push(t),s[t]="url",n){const e=`^${Y(n)}$`;r.set(t,{pattern:new RegExp(e),constraint:n})}}return{urlParams:e,queryParams:n,spatParams:i,paramTypeMap:s,constraintPatterns:r,pathPattern:t}}(t.path),s=function(t){const e={};for(const n of t.urlParams)e[n]="url";for(const n of t.queryParams)e[n]="query";return e}(i),r={name:t.name,path:t.path,absolute:t.absolute,parent:e,children:void 0,paramMeta:i,nonAbsoluteChildren:void 0,fullName:"",staticPath:null,paramTypeMap:s};var a;r.fullName=(a=r,a.parent?.name?`${a.parent.fullName}.${a.name}`:a.name);const{childrenMap:o,nonAbsoluteChildren:c}=function(t,e,n){const i=[],s=[];for(const r of t){const t=Ft(r,e,n);i.push(t),t.absolute||s.push(t)}return{childrenMap:Dt(i),nonAbsoluteChildren:s}}(t.children,r,n);return r.children=o,r.nonAbsoluteChildren=c,r.staticPath=function(t){if(!t.path)return null;const{urlParams:e,queryParams:n,spatParams:i}=t.paramMeta;if(e.length>0||n.length>0||i.length>0)return null;const s=[];let r=t.parent;for(;r?.path;)s.unshift(r),r=r.parent;let a="";for(const t of s){const{urlParams:e,queryParams:n,spatParams:i}=t.paramMeta;if(e.length>0||n.length>0||i.length>0)return null;a=t.absolute?t.path:Ct(a,t.path)}return t.absolute?t.path:Ct(a,t.path)}(r),n&&(Object.freeze(c),Object.freeze(s),Object.freeze(r.children),Object.freeze(r)),r}function jt(t,e,n,i){return function(t,e){const n=[];return{add(t){return n.push(t),this},addMany(t){return n.push(...t),this},build:i=>function(t,e=!0){return Ft(t,null,e)}(function(t,e,n){const i=Rt({name:t,path:e},null);for(const t of n){const e=Rt(t,i);i.children.push(e)}return i}(t,e,n),!i?.skipFreeze)}}(t,e).addMany(n).build(i)}function Lt(t){const e={name:t.name,path:t.absolute?`~${t.path}`:t.path};return t.children.size>0&&(e.children=[...t.children.values()].map(t=>Lt(t))),e}function It(t){return[...t.children.values()].map(t=>Lt(t))}function Mt(t){const e=t?.queryParams;return new gt({...void 0===t?.caseSensitive?void 0:{caseSensitive:t.caseSensitive},...void 0===t?.strictTrailingSlash?void 0:{strictTrailingSlash:t.strictTrailingSlash},...void 0===t?.strictQueryParams?void 0:{strictQueryParams:t.strictQueryParams},...void 0===t?.urlParamsEncoding?void 0:{urlParamsEncoding:t.urlParamsEncoding},parseQueryString:t=>((t,e)=>{const n=(t=>{const e=t.indexOf("?");return-1===e?t:t.slice(e+1)})(t);if(""===n||"?"===n)return{};if(!e)return function(t){const e={};return function(t,e){let n=0;const i=t.length;for(;n<i;){let s=t.indexOf("&",n);-1===s&&(s=i),Et(t,n,s,e),n=s+1}}(t,e),e}(n);const i=Pt(e),s={};let r=0;const a=n.length;for(;r<a;){let t=n.indexOf("&",r);-1===t&&(t=a),Et(n,r,t,s,i.strategies),r=t+1}return s})(t,e),buildQueryString:t=>((t,e)=>{const n=Object.keys(t);if(0===n.length)return"";const i=Pt(e),s=[];for(const e of n){const n=t[e];if(void 0===n)continue;const r=Ot(e,n,i);r&&s.push(r)}return s.join("&")})(t,e)})}function Ut(t,e,n){const i=jt("",e,t),s=Mt(n);return s.registerTree(i),{tree:i,matcher:s}}function $t(t){const e=Ut(t.definitions,t.rootPath,t.matcherOptions);t.tree=e.tree,t.matcher=e.matcher,t.resolvedForwardMap=xt(t.config)}function Bt(t){const e=Ut(t.definitions,t.rootPath,t.matcherOptions);t.tree=e.tree,t.matcher=e.matcher}function _t(t){kt(t),Bt(t)}function kt(t){t.definitions.length=0,Object.assign(t.config,Q()),t.resolvedForwardMap=Object.create(null),t.routeCustomFields=Object.create(null)}function xt(t){const e=Object.create(null);for(const n of Object.keys(t.forwardMap))e[n]=m(n,t.forwardMap);return e}function zt(t,e,n,i,s,r,a){const o=new Set(["name","path","children","canActivate","canDeactivate","forwardTo","encodeParams","decodeParams","defaultParams"]),c=Object.fromEntries(Object.entries(t).filter(([t])=>!o.has(t)));Object.keys(c).length>0&&(i[e]=c),t.canActivate&&(a?a.addActivateGuard(e,t.canActivate):s.set(e,t.canActivate)),t.canDeactivate&&(a?a.addDeactivateGuard(e,t.canDeactivate):r.set(e,t.canDeactivate)),t.forwardTo&&function(t,e,n){if(t.canActivate&&f.warn("real-router",`Route "${e}" has both forwardTo and canActivate. canActivate will be ignored because forwardTo creates a redirect (industry standard). Move canActivate to the target route "${"string"==typeof t.forwardTo?t.forwardTo:"[dynamic]"}".`),t.canDeactivate&&f.warn("real-router",`Route "${e}" has both forwardTo and canDeactivate. canDeactivate will be ignored because forwardTo creates a redirect (industry standard). Move canDeactivate to the target route "${"string"==typeof t.forwardTo?t.forwardTo:"[dynamic]"}".`),"function"==typeof t.forwardTo){const n="AsyncFunction"===t.forwardTo.constructor.name,i=t.forwardTo.toString().includes("__awaiter");if(n||i)throw new TypeError(`forwardTo callback cannot be async for route "${e}". Async functions break matchPath/buildPath.`)}"string"==typeof t.forwardTo?n.forwardMap[e]=t.forwardTo:n.forwardFnMap[e]=t.forwardTo}(t,e,n),t.decodeParams&&(n.decoders[e]=e=>t.decodeParams?.(e)??e),t.encodeParams&&(n.encoders[e]=e=>t.encodeParams?.(e)??e),t.defaultParams&&(n.defaultParams[e]=t.defaultParams)}function Gt(t,e,n,i,s,r,a=""){for(const o of t){const t=a?`${a}.${o.name}`:o.name;zt(o,t,e,n,i,s,r),o.children&&Gt(o.children,e,n,i,s,r,t)}}var qt=".",Wt=[];function Vt(t){const e=[];for(let n=t.length-1;n>=0;n--)e.push(t[n]);return e}function Qt(t){const e=typeof t;return"string"===e||"number"===e||"boolean"===e}function Kt(t,e,n,i){const s=e[t];if(!s||"object"!=typeof s)return!0;for(const t of Object.keys(s)){const e=n.params[t],s=i.params[t];if(Qt(e)&&Qt(s)&&String(e)!==String(s))return!1}return!0}Object.freeze(Wt);var Ht,Jt,Yt=new Map;function Xt(t){const e=Yt.get(t);if(e)return e;const n=function(t){if(!t)return[""];const e=t.indexOf(qt);if(-1===e)return[t];const n=t.indexOf(qt,e+1);if(-1===n)return[t.slice(0,e),t];const i=t.indexOf(qt,n+1);if(-1===i)return[t.slice(0,e),t.slice(0,n),t];return-1===t.indexOf(qt,i+1)?[t.slice(0,e),t.slice(0,n),t.slice(0,i),t]:function(t){const e=t.split(qt),n=e.length,i=[e[0]];let s=e[0].length;for(let r=1;r<n-1;r++)s+=1+e[r].length,i.push(t.slice(0,s));return i.push(t),i}(t)}(t);return Object.freeze(n),Yt.set(t,n),n}var Zt,te,ee=null,ne=null;function ie(t,e){if(null!==ee&&t===Ht&&e===Jt)return ee;if(null!==ne&&t===Zt&&e===te)return ne;const n=function(t,e){if(!e)return{intersection:"",toActivate:Xt(t.name),toDeactivate:Wt};const n=k(t),i=k(e);if(!n&&!i)return{intersection:"",toActivate:Xt(t.name),toDeactivate:Vt(Xt(e.name))};const s=Xt(t.name),r=Xt(e.name),a=function(t,e,n,i,s,r){for(let a=0;a<r;a++){const r=i[a];if(r!==s[a])return a;if(!Kt(r,t,e,n))return a}return r}(n??i,t,e,s,r,Math.min(r.length,s.length));let o;if(a>=r.length)o=Wt;else if(0===a&&1===r.length)o=r;else{o=[];for(let t=r.length-1;t>=a;t--)o.push(r[t])}const c=0===a?s:s.slice(a);return{intersection:a>0?r[a-1]:"",toDeactivate:o,toActivate:c}}(t,e);return Zt=Ht,te=Jt,ne=ee,Ht=t,Jt=e,ee=n,n}function se(t,e){var n;return{name:e??(n=t.segments,n.at(-1)?.fullName??""),params:t.params,meta:t.meta}}var re=class{#x;#z;get#d(){return this.#x.depsStore}constructor(t=[],e){this.#x=function(t,e){const n=[],i=Q(),s=Object.create(null),r=new Map,a=new Map;for(const e of t)n.push(K(e));const{tree:o,matcher:c}=Ut(n,"",e);return Gt(t,i,s,r,a,void 0,""),{definitions:n,config:i,tree:o,matcher:c,resolvedForwardMap:xt(i),routeCustomFields:s,rootPath:"",matcherOptions:e,depsStore:void 0,lifecycleNamespace:void 0,pendingCanActivate:r,pendingCanDeactivate:a,treeOperations:{commitTreeChanges:$t,resetStore:_t,nodeToDefinition:Lt}}}(t,e)}static shouldUpdateNode(t){return(e,n)=>{if(!e||"object"!=typeof e||!("name"in e))throw new TypeError("[router.shouldUpdateNode] toState must be valid State object");if(e.transition?.reload)return!0;if(""===t&&!n)return!0;const{intersection:i,toActivate:s,toDeactivate:r}=ie(e,n);return t===i||!!s.includes(t)||r.includes(t)}}setDependencies(t){this.#x.depsStore=t;for(const[e,n]of this.#x.pendingCanActivate)t.addActivateGuard(e,n);this.#x.pendingCanActivate.clear();for(const[e,n]of this.#x.pendingCanDeactivate)t.addDeactivateGuard(e,n);this.#x.pendingCanDeactivate.clear()}setLifecycleNamespace(t){this.#x.lifecycleNamespace=t}setRootPath(t){this.#x.rootPath=t,Bt(this.#x)}hasRoute(t){return this.#x.matcher.hasRoute(t)}clearRoutes(){_t(this.#x)}buildPath(t,e,n){if(t===s.UNKNOWN_ROUTE)return"string"==typeof e?.path?e.path:"";const i=Object.hasOwn(this.#x.config.defaultParams,t)?{...this.#x.config.defaultParams[t],...e}:e??{},r="function"==typeof this.#x.config.encoders[t]?this.#x.config.encoders[t]({...i}):i;return this.#x.matcher.buildPath(t,r,this.#G(n))}matchPath(t,e){const n=e,i=this.#x.matcher.match(t);if(!i)return;const s=se(i),{name:r,params:a,meta:o}=s,c="function"==typeof this.#x.config.decoders[r]?this.#x.config.decoders[r](a):a,{name:u,params:l}=this.#d.forwardState(r,c);let h=t;if(n.rewritePathOnMatch){const t="function"==typeof this.#x.config.encoders[u]?this.#x.config.encoders[u]({...l}):l,e=n.trailingSlash;h=this.#x.matcher.buildPath(u,t,{trailingSlash:"never"===e||"always"===e?e:void 0,queryParamsMode:n.queryParamsMode})}return this.#d.makeState(u,l,h,o)}forwardState(t,e){if(Object.hasOwn(this.#x.config.forwardFnMap,t)){const n=this.#q(t,e),i=this.#x.config.forwardFnMap[t],s=this.#W(t,i,e);return{name:s,params:this.#q(s,n)}}const n=this.#x.resolvedForwardMap[t]??t;if(n!==t&&Object.hasOwn(this.#x.config.forwardFnMap,n)){const i=this.#q(t,e),s=this.#x.config.forwardFnMap[n],r=this.#W(n,s,e);return{name:r,params:this.#q(r,i)}}if(n!==t){const i=this.#q(t,e);return{name:n,params:this.#q(n,i)}}return{name:t,params:this.#q(t,e)}}buildStateResolved(t,e){const n=this.#x.matcher.getSegmentsByName(t);if(n)return se({segments:n,params:e,meta:this.#x.matcher.getMetaByName(t)},t)}isActiveRoute(t,e={},n=!1,i=!0){const s=this.#d.getState();if(!s)return!1;const r=s.name;if(r!==t&&!r.startsWith(`${t}.`)&&!t.startsWith(`${r}.`))return!1;const a=this.#x.config.defaultParams[t];if(n||r===t){const n=a?{...a,...e}:e;return this.#d.areStatesEqual({name:t,params:n,path:""},s,i)}const o=s.params;return!!function(t,e){for(const n in t)if(t[n]!==e[n])return!1;return!0}(e,o)&&(!a||function(t,e,n){for(const i in t)if(!(i in n)&&t[i]!==e[i])return!1;return!0}(a,o,e))}getMetaForState(t){return this.#x.matcher.hasRoute(t)?this.#x.matcher.getMetaByName(t):void 0}getUrlParams(t){const e=this.#x.matcher.getSegmentsByName(t);return e?function(t){const e=[];for(const n of t)for(const t of n.paramMeta.urlParams)e.push(t);return e}(e):[]}getStore(){return this.#x}#q(t,e){return Object.hasOwn(this.#x.config.defaultParams,t)?{...this.#x.config.defaultParams[t],...e}:e}#G(t){if(this.#z)return this.#z;const e=t?.trailingSlash;return this.#z=Object.freeze({trailingSlash:"never"===e||"always"===e?e:void 0,queryParamsMode:t?.queryParamsMode}),this.#z}#W(t,e,n){const i=new Set([t]);let s=e(this.#d.getDependency,n),r=0;if("string"!=typeof s)throw new TypeError("forwardTo callback must return a string, got "+typeof s);for(;r<100;){if(void 0===this.#x.matcher.getSegmentsByName(s))throw new Error(`Route "${s}" does not exist`);if(i.has(s)){const t=[...i,s].join(" → ");throw new Error(`Circular forwardTo detected: ${t}`)}if(i.add(s),Object.hasOwn(this.#x.config.forwardFnMap,s)){s=(0,this.#x.config.forwardFnMap[s])(this.#d.getDependency,n),r++;continue}const t=this.#x.config.forwardMap[s];if(void 0===t)return s;s=t,r++}throw new Error("forwardTo exceeds maximum depth of 100")}},ae=new n(i.ROUTER_NOT_STARTED),oe=new n(i.ROUTE_NOT_FOUND),ce=new n(i.SAME_STATES),ue=Promise.reject(ae),le=Promise.reject(oe),he=Promise.reject(ce);function de(t,e){const{toState:r,fromState:a,opts:o,toDeactivate:u,toActivate:l,intersection:h}=e;if(r.name!==s.UNKNOWN_ROUTE&&!t.hasRoute(r.name)){const e=new n(i.ROUTE_NOT_FOUND,{routeName:r.name});throw t.sendTransitionFail(r,a,e),e}if(a)for(const n of u)!l.includes(n)&&e.canDeactivateFunctions.has(n)&&t.clearCanDeactivate(n);r.transition=function(t,e,n,i,s){const r={phase:"activating",reason:"success",segments:{deactivated:n,activated:i,intersection:s}};return void 0!==t?.name&&(r.from=t.name),void 0!==e.reload&&(r.reload=e.reload),void 0!==e.redirected&&(r.redirected=e.redirected),r}(a,o,u,l,h);const d=c(r);t.setState(d);const f=void 0===o.signal?o:function({signal:t,...e}){return e}(o);return t.sendTransitionDone(d,a,f),d}function fe(t,e,n,s){e.code!==i.TRANSITION_CANCELLED&&e.code!==i.ROUTE_NOT_FOUND&&t.sendTransitionFail(n,s,e)}function pe(t,e,s){if(t instanceof DOMException&&"AbortError"===t.name)throw new n(i.TRANSITION_CANCELLED);!function(t,e,i){if(t instanceof n)throw t.setCode(e),t;throw new n(e,function(t,e){const n={segment:e};if(t instanceof Error)return{...n,message:t.message,stack:t.stack,..."cause"in t&&void 0!==t.cause&&{cause:t.cause}};if(t&&"object"==typeof t){const e={};for(const[n,i]of Object.entries(t))me.has(n)||(e[n]=i);return{...n,...e}}return n}(t,i))}(t,e,s)}ue.catch(()=>{}),le.catch(()=>{}),he.catch(()=>{});var me=new Set(["code","segment","path","redirect"]);async function ge(t,e,i){let s;try{s=await t}catch(t){return void pe(t,e,i)}if(!s)throw new n(e,{segment:i})}async function ve(t,e,s,r,a,o,c,u,l,h){await ge(l,s,h);for(let l=u;l<e.length;l++){if(!c())throw new n(i.TRANSITION_CANCELLED);const u=e[l],h=t.get(u);if(!h)continue;let d=!1;try{d=h(r,a,o)}catch(t){pe(t,s,u)}if(d instanceof Promise)await ge(d,s,u);else if(!d)throw new n(s,{segment:u})}}function Se(t,e,s,r,a,o,c){for(const[u,l]of e.entries()){if(!c())throw new n(i.TRANSITION_CANCELLED);const h=t.get(l);if(!h)continue;let d=!1;try{d=h(r,a,o)}catch(t){pe(t,s,l)}if(d instanceof Promise)return ve(t,e,s,r,a,o,c,u+1,d,l);if(!d)throw new n(s,{segment:l})}}var ye=[s.UNKNOWN_ROUTE];Object.freeze(ye);var Te={replace:!0};Object.freeze(Te);var we=class{lastSyncResolved=!1;lastSyncRejected=!1;#d;#V=null;#Q=0;setDependencies(t){this.#d=t}navigate(t,e,r){this.lastSyncResolved=!1;const a=this.#d;if(!a.canNavigate())return this.lastSyncRejected=!0,ue;let o,c,u=!1,l=null;try{if(o=a.buildNavigateState(t,e),!o)return a.emitTransitionError(void 0,a.getState(),oe),this.lastSyncRejected=!0,le;if(c=a.getState(),r=function(t,e){return e?.name!==s.UNKNOWN_ROUTE||t.replace?t:{...t,replace:!0}}(r,c),function(t,e,n){return!!t&&!e.reload&&!e.force&&t.path===n.path}(c,r,o))return a.emitTransitionError(o,c,ce),this.lastSyncRejected=!0,he;if(this.#K(),r.signal?.aborted)throw new n(i.TRANSITION_CANCELLED,{reason:r.signal.reason});const h=++this.#Q;if(a.startTransition(o,c),u=!0,this.#Q!==h)throw new n(i.TRANSITION_CANCELLED);const[d,f]=a.getLifecycleFunctions(),p=o.name===s.UNKNOWN_ROUTE,{toDeactivate:m,toActivate:g,intersection:v}=ie(o,c),S=c&&!r.forceDeactivate&&m.length>0,y=!p&&g.length>0;if(d.size>0||f.size>0){l=new AbortController,this.#V=l;const t=()=>this.#Q===h&&a.isActive(),e=function(t,e,s,r,a,o,c,u,l,h){if(a){const a=Se(t,s,i.CANNOT_DEACTIVATE,c,u,l,h);if(void 0!==a)return async function(t,e,s,r,a,o,c,u){if(await t,!u())throw new n(i.TRANSITION_CANCELLED);if(r){const t=Se(e,s,i.CANNOT_ACTIVATE,a,o,c,u);if(void 0!==t&&await t,!u())throw new n(i.TRANSITION_CANCELLED)}}(a,e,r,o,c,u,l,h)}if(!h())throw new n(i.TRANSITION_CANCELLED);if(o)return Se(e,r,i.CANNOT_ACTIVATE,c,u,l,h)}(d,f,m,g,!!S,y,o,c,l.signal,t);if(void 0!==e)return this.#H(e,{toState:o,fromState:c,opts:r,toDeactivate:m,toActivate:g,intersection:v,canDeactivateFunctions:d},l,h);if(!t())throw new n(i.TRANSITION_CANCELLED);this.#J(l)}return this.lastSyncResolved=!0,Promise.resolve(de(a,{toState:o,fromState:c,opts:r,toDeactivate:m,toActivate:g,intersection:v,canDeactivateFunctions:d}))}catch(t){return this.#Y(t,l,u,o,c),Promise.reject(t)}}navigateToDefault(t){const e=this.#d;if(!e.getOptions().defaultRoute)return Promise.reject(new n(i.ROUTE_NOT_FOUND,{routeName:"defaultRoute not configured"}));const{route:s,params:r}=e.resolveDefault();return s?this.navigate(s,r,t):Promise.reject(new n(i.ROUTE_NOT_FOUND,{routeName:"defaultRoute resolved to empty"}))}navigateToNotFound(t){this.#K();const e=this.#d.getState(),n=e?Xt(e.name).toReversed():[];Object.freeze(n);const i={deactivated:n,activated:ye,intersection:""};Object.freeze(i);const r={phase:"activating",...e&&{from:e.name},reason:"success",segments:i};Object.freeze(r);const a={name:s.UNKNOWN_ROUTE,params:{},path:t,transition:r};return Object.freeze(a),this.#d.setState(a),this.#d.emitTransitionSuccess(a,e,Te),a}abortCurrentNavigation(){this.#V?.abort(new n(i.TRANSITION_CANCELLED)),this.#V=null}async#H(t,e,s,r){const a=this.#d,o=()=>this.#Q===r&&!s.signal.aborted&&a.isActive();try{if(e.opts.signal){if(e.opts.signal.aborted)throw new n(i.TRANSITION_CANCELLED,{reason:e.opts.signal.reason});e.opts.signal.addEventListener("abort",()=>{s.abort(e.opts.signal?.reason)},{once:!0,signal:s.signal})}if(await t,!o())throw new n(i.TRANSITION_CANCELLED);return de(a,e)}catch(t){throw fe(a,t,e.toState,e.fromState),t}finally{this.#J(s)}}#Y(t,e,n,i,s){e&&this.#J(e),n&&i&&fe(this.#d,t,i,s)}#J(t){t.abort(),this.#V===t&&(this.#V=null)}#K(){this.#d.isTransitioning()&&(f.warn("router.navigate","Concurrent navigation detected on shared router instance. For SSR, use cloneRouter() to create isolated instance per request."),this.#V?.abort(new n(i.TRANSITION_CANCELLED)),this.#d.cancelNavigation())}},be={replace:!0};Object.freeze(be);var Ne=class{#d;setDependencies(t){this.#d=t}async start(t){const e=this.#d,s=e.getOptions(),r=e.matchPath(t);if(!r&&!s.allowNotFound){const s=new n(i.ROUTE_NOT_FOUND,{path:t});throw e.emitTransitionError(void 0,void 0,s),s}return e.completeStart(),r?e.navigate(r.name,r.params,be):e.navigateToNotFound(t)}stop(){this.#d.clearState()}},Pe=class{#X;#Z;#tt;#et;#nt;#it;constructor(t){this.#X=t.routerFSM,this.#Z=t.emitter,this.#tt=void 0,this.#st()}static validateSubscribeListener(t){if("function"!=typeof t)throw new TypeError("[router.subscribe] Expected a function. For Observable pattern use @real-router/rx package")}emitRouterStart(){this.#Z.emit(e.ROUTER_START)}emitRouterStop(){this.#Z.emit(e.ROUTER_STOP)}emitTransitionStart(t,n){this.#Z.emit(e.TRANSITION_START,t,n)}emitTransitionSuccess(t,n,i){this.#Z.emit(e.TRANSITION_SUCCESS,t,n,i)}emitTransitionError(t,n,i){this.#Z.emit(e.TRANSITION_ERROR,t,n,i)}emitTransitionCancel(t,n){this.#Z.emit(e.TRANSITION_CANCEL,t,n)}sendStart(){this.#X.send(P)}sendStop(){this.#X.send(D)}sendDispose(){this.#X.send(F)}sendStarted(){this.#X.send(A)}sendNavigate(t,e){this.#tt=t,this.#X.forceState(b),this.emitTransitionStart(t,e)}sendComplete(t,e,n={}){this.#X.forceState(w),this.emitTransitionSuccess(t,e,n),this.#tt===t&&(this.#tt=void 0)}sendFail(t,e,n){const i=this.#tt;this.#et=t,this.#nt=e,this.#it=n,this.#X.send(R),this.#tt===i&&(this.#tt=void 0)}sendFailSafe(t,e,n){this.isReady()?this.sendFail(t,e,n):this.emitTransitionError(t,e,n)}sendCancel(t,e){const n=this.#tt;this.#et=t,this.#nt=e,this.#X.send(C),this.#tt===n&&(this.#tt=void 0)}canBeginTransition(){return this.#X.canSend(O)}canStart(){return this.#X.canSend(P)}canCancel(){return this.#X.canSend(C)}isActive(){const t=this.#X.getState();return t!==y&&t!==N}isDisposed(){return this.#X.getState()===N}isTransitioning(){return this.#X.getState()===b}isReady(){return this.#X.getState()===w}getCurrentToState(){return this.#tt}addEventListener(t,e){return this.#Z.on(t,e)}subscribe(t){return this.#Z.on(e.TRANSITION_SUCCESS,(e,n)=>{t({route:e,previousRoute:n})})}clearAll(){this.#Z.clearAll()}setLimits(t){this.#Z.setLimits(t)}sendCancelIfTransitioning(t){this.canCancel()&&this.sendCancel(this.#tt,t)}#rt(){this.emitTransitionError(this.#et,this.#nt,this.#it)}#st(){const t=this.#X;t.on(T,A,()=>{this.emitRouterStart()}),t.on(w,D,()=>{this.emitRouterStop()}),t.on(b,C,()=>{const t=this.#et;void 0!==t&&this.emitTransitionCancel(t,this.#nt)}),t.on(T,R,()=>{this.#rt()}),t.on(w,R,()=>{this.#rt()}),t.on(b,R,()=>{this.#rt()})}},Ae=new n(i.ROUTER_ALREADY_STARTED),Oe=new Set(["all","warn-error","error-only"]);var Ee=class{router;options;limits;dependenciesStore;state;routes;routeLifecycle;plugins;navigation;lifecycle;eventBus;constructor(t){this.router=t.router,this.options=t.options,this.limits=t.limits,this.dependenciesStore=t.dependenciesStore,this.state=t.state,this.routes=t.routes,this.routeLifecycle=t.routeLifecycle,this.plugins=t.plugins,this.navigation=t.navigation,this.lifecycle=t.lifecycle,this.eventBus=t.eventBus}wireLimits(){this.dependenciesStore.limits=this.limits,this.plugins.setLimits(this.limits),this.eventBus.setLimits({maxListeners:this.limits.maxListeners,warnListeners:this.limits.warnListeners,maxEventDepth:this.limits.maxEventDepth}),this.routeLifecycle.setLimits(this.limits)}wireRouteLifecycleDeps(){const t={compileFactory:this.createCompileFactory()};this.routeLifecycle.setDependencies(t),this.routeLifecycle.setValidatorGetter(()=>{try{return d(this.router).validator}catch{return null}})}wireRoutesDeps(){this.routes.setDependencies({addActivateGuard:(t,e)=>{this.routeLifecycle.addCanActivate(t,e,!0)},addDeactivateGuard:(t,e)=>{this.routeLifecycle.addCanDeactivate(t,e,!0)},makeState:(t,e,n,i)=>this.state.makeState(t,e,n,i),getState:()=>this.state.get(),areStatesEqual:(t,e,n)=>this.state.areStatesEqual(t,e,n),getDependency:t=>this.dependenciesStore.dependencies[t],forwardState:(t,e)=>{const n=d(this.router);return n.validator?.routes.validateStateBuilderArgs(t,e,"forwardState"),n.forwardState(t,e)}}),this.routes.setLifecycleNamespace(this.routeLifecycle)}wirePluginsDeps(){const t={addEventListener:(t,e)=>this.eventBus.addEventListener(t,e),canNavigate:()=>this.eventBus.canBeginTransition(),compileFactory:this.createCompileFactory()};this.plugins.setDependencies(t),this.plugins.setValidatorGetter(()=>{try{return d(this.router).validator}catch{return null}})}wireNavigationDeps(){this.navigation.setDependencies({getOptions:()=>this.options.get(),hasRoute:t=>this.routes.hasRoute(t),getState:()=>this.state.get(),setState:t=>{this.state.set(t)},buildNavigateState:(t,e)=>{const n=d(this.router);n.validator?.routes.validateStateBuilderArgs(t,e,"navigate");const{name:i,params:s}=n.forwardState(t,e),r=this.routes.getMetaForState(i);if(void 0===r)return;const a=n.buildPath(i,s);return this.state.makeState(i,s,a,r,!0)},resolveDefault:()=>{const t=this.options.get();return{route:U(t.defaultRoute,t=>this.dependenciesStore.dependencies[t]),params:U(t.defaultParams,t=>this.dependenciesStore.dependencies[t])}},startTransition:(t,e)=>{this.eventBus.sendNavigate(t,e)},cancelNavigation:()=>{const t=this.eventBus.getCurrentToState();void 0!==t&&this.eventBus.sendCancel(t,this.state.get())},sendTransitionDone:(t,e,n)=>{this.eventBus.sendComplete(t,e,n)},sendTransitionFail:(t,e,n)=>{this.eventBus.sendFail(t,e,n)},emitTransitionError:(t,e,n)=>{this.eventBus.sendFailSafe(t,e,n)},emitTransitionSuccess:(t,e,n)=>{this.eventBus.emitTransitionSuccess(t,e,n)},canNavigate:()=>this.eventBus.canBeginTransition(),getLifecycleFunctions:()=>this.routeLifecycle.getFunctions(),isActive:()=>this.router.isActive(),isTransitioning:()=>this.eventBus.isTransitioning(),clearCanDeactivate:t=>{this.routeLifecycle.clearCanDeactivate(t)}})}wireLifecycleDeps(){this.lifecycle.setDependencies({getOptions:()=>this.options.get(),navigate:(t,e,n)=>this.navigation.navigate(t,e,n),navigateToNotFound:t=>this.navigation.navigateToNotFound(t),clearState:()=>{this.state.set(void 0)},matchPath:t=>this.routes.matchPath(t,this.options.get()),completeStart:()=>{this.eventBus.sendStarted()},emitTransitionError:(t,e,n)=>{this.eventBus.sendFail(t,e,n)}})}wireStateDeps(){this.state.setDependencies({getDefaultParams:()=>this.routes.getStore().config.defaultParams,buildPath:(t,e)=>d(this.router).buildPath(t,e),getUrlParams:t=>this.routes.getUrlParams(t)})}createCompileFactory(){const{router:t,dependenciesStore:e}=this;return n=>n(t,t=>e.dependencies[t])}},Re=Object.freeze({}),Ce=class t{#u;#v;#at;#ot;#ct;#ut;#m;#lt;#ht;#dt;constructor(t=[],e={},n={}){e.logger&&function(t){if("object"!=typeof t||null===t)throw new TypeError("Logger config must be an object");const e=t;for(const t of Object.keys(e))if("level"!==t&&"callback"!==t)throw new TypeError(`Unknown logger config property: "${t}"`);if("level"in e&&void 0!==e.level&&("string"!=typeof(n=e.level)||!Oe.has(n)))throw new TypeError(`Invalid logger level: ${function(t){return"string"==typeof t?`"${t}"`:"object"==typeof t?JSON.stringify(t):String(t)}(e.level)}. Expected: "all" | "warn-error" | "error-only"`);var n;if("callback"in e&&void 0!==e.callback&&"function"!=typeof e.callback)throw new TypeError("Logger callback must be a function, got "+typeof e.callback);return!0}(e.logger)&&(f.configure(e.logger),delete e.logger),$.validateOptionsIsObject(e),function(t){if(!t||"object"!=typeof t||t.constructor!==Object)throw new TypeError("dependencies must be a plain object");for(const e in t)if(Object.getOwnPropertyDescriptor(t,e)?.get)throw new TypeError(`dependencies cannot contain getters: "${e}"`)}(n),t.length>0&&L(t),this.#u=new $(e),this.#v=r(e.limits),this.#at=function(t={}){const e=Object.create(null);for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return{dependencies:e,limits:o}}(n),this.#ot=new x,this.#ct=new re(t,function(t){return{strictTrailingSlash:"strict"===t.trailingSlash,strictQueryParams:"strict"===t.queryParamsMode,urlParamsEncoding:t.urlParamsEncoding,queryParams:t.queryParams}}(this.#u.get())),this.#ut=new V,this.#m=new W,this.#lt=new we,this.#ht=new Ne;const i=new p(j),s=new S({onListenerError:(t,e)=>{f.error("Router",`Error in listener for ${t}:`,e)},onListenerWarn:(t,e)=>{f.warn("router.addEventListener",`Event "${t}" has ${e} listeners — possible memory leak`)}});var c;this.#dt=new Pe({routerFSM:i,emitter:s}),(c=new Ee({router:this,options:this.#u,limits:this.#v,dependenciesStore:this.#at,state:this.#ot,routes:this.#ct,routeLifecycle:this.#ut,plugins:this.#m,navigation:this.#lt,lifecycle:this.#ht,eventBus:this.#dt})).wireLimits(),c.wireRouteLifecycleDeps(),c.wireRoutesDeps(),c.wirePluginsDeps(),c.wireNavigationDeps(),c.wireLifecycleDeps(),c.wireStateDeps();const d=new Map;u(this,{makeState:(t,e,n,i)=>this.#ot.makeState(t,e,n,i),forwardState:h("forwardState",(t,e)=>this.#ct.forwardState(t,e),d),buildStateResolved:(t,e)=>this.#ct.buildStateResolved(t,e),matchPath:(t,e)=>this.#ct.matchPath(t,e),getOptions:()=>this.#u.get(),addEventListener:(t,e)=>this.#dt.addEventListener(t,e),buildPath:h("buildPath",(t,e)=>this.#ct.buildPath(t,e??a,this.#u.get()),d),start:l("start",t=>this.#ht.start(t),d),interceptors:d,setRootPath:t=>{this.#ct.setRootPath(t)},getRootPath:()=>this.#ct.getStore().rootPath,getTree:()=>this.#ct.getStore().tree,isDisposed:()=>this.#dt.isDisposed(),validator:null,dependenciesGetStore:()=>this.#at,cloneOptions:()=>({...this.#u.get()}),cloneDependencies:()=>({...this.#at.dependencies}),getLifecycleFactories:()=>this.#ut.getFactories(),getPluginFactories:()=>this.#m.getAll(),routeGetStore:()=>this.#ct.getStore(),getStateName:()=>this.#ot.get()?.name,isTransitioning:()=>this.#dt.isTransitioning(),clearState:()=>{this.#ot.set(void 0)},setState:t=>{this.#ot.set(t)},routerExtensions:[]}),this.isActiveRoute=this.isActiveRoute.bind(this),this.buildPath=this.buildPath.bind(this),this.getState=this.getState.bind(this),this.getPreviousState=this.getPreviousState.bind(this),this.areStatesEqual=this.areStatesEqual.bind(this),this.shouldUpdateNode=this.shouldUpdateNode.bind(this),this.isActive=this.isActive.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.dispose=this.dispose.bind(this),this.canNavigateTo=this.canNavigateTo.bind(this),this.usePlugin=this.usePlugin.bind(this),this.navigate=this.navigate.bind(this),this.navigateToDefault=this.navigateToDefault.bind(this),this.navigateToNotFound=this.navigateToNotFound.bind(this),this.subscribe=this.subscribe.bind(this)}isActiveRoute(t,e,n,i){return d(this).validator?.routes.validateIsActiveRouteArgs(t,e,n,i),d(this).validator?.routes.validateRouteName(t,"isActiveRoute"),""===t?(f.warn("real-router",'isActiveRoute("") called with empty string. Root node is not considered a parent of any route.'),!1):this.#ct.isActiveRoute(t,e,n,i)}buildPath(t,e){const n=d(this);return n.validator?.routes.validateBuildPathArgs(t),n.validator?.navigation.validateParams(e,"buildPath"),n.buildPath(t,e)}getState(){return this.#ot.get()}getPreviousState(){return this.#ot.getPrevious()}areStatesEqual(t,e,n=!0){return d(this).validator?.state.validateAreStatesEqualArgs(t,e,n),this.#ot.areStatesEqual(t,e,n)}shouldUpdateNode(t){return d(this).validator?.routes.validateShouldUpdateNodeArgs(t),re.shouldUpdateNode(t)}isActive(){return this.#dt.isActive()}start(e){if(!this.#dt.canStart())return Promise.reject(Ae);d(this).validator?.navigation.validateStartArgs(e),this.#dt.sendStart();const n=d(this).start(e).catch(t=>{throw this.#dt.isReady()&&(this.#ht.stop(),this.#dt.sendStop()),t});return t.#ft(n),n}stop(){return this.#lt.abortCurrentNavigation(),this.#dt.sendCancelIfTransitioning(this.#ot.get()),this.#dt.isReady()||this.#dt.isTransitioning()?(this.#ht.stop(),this.#dt.sendStop(),this):this}dispose(){if(this.#dt.isDisposed())return;this.#lt.abortCurrentNavigation(),this.#dt.sendCancelIfTransitioning(this.#ot.get()),(this.#dt.isReady()||this.#dt.isTransitioning())&&(this.#ht.stop(),this.#dt.sendStop()),this.#dt.sendDispose(),this.#dt.clearAll(),this.#m.disposeAll();const t=d(this);for(const e of t.routerExtensions)for(const t of e.keys)delete this[t];t.routerExtensions.length=0,this.#ct.clearRoutes(),this.#ut.clearAll(),this.#ot.reset(),this.#at.dependencies=Object.create(null),this.#pt()}canNavigateTo(t,e){const n=d(this);if(n.validator?.routes.validateRouteName(t,"canNavigateTo"),n.validator?.navigation.validateParams(e,"canNavigateTo"),!this.#ct.hasRoute(t))return!1;const{name:i,params:s}=n.forwardState(t,e??{}),r=this.#ot.makeState(i,s),a=this.#ot.get(),{toDeactivate:o,toActivate:c}=ie(r,a);return this.#ut.canNavigateTo(o,c,r,a)}usePlugin(...t){const e=t.filter(Boolean);if(0===e.length)return()=>{};const n=d(this);n.validator?.plugins.validatePluginLimit(this.#m.count(),this.#v);for(const t of e)n.validator?.plugins.validateNoDuplicatePlugins(t,this.#m.getAll());return this.#m.use(...e)}subscribe(t){return Pe.validateSubscribeListener(t),this.#dt.subscribe(t)}navigate(e,n,i){const s=d(this);s.validator?.navigation.validateNavigateArgs(e),s.validator?.navigation.validateParams(n,"navigate");const r=i??Re;s.validator?.navigation.validateNavigationOptions(r,"navigate");const o=this.#lt.navigate(e,n??a,r);return this.#lt.lastSyncResolved?this.#lt.lastSyncResolved=!1:this.#lt.lastSyncRejected?this.#lt.lastSyncRejected=!1:t.#ft(o),o}navigateToDefault(e){const n=d(this);n.validator?.navigation.validateNavigateToDefaultArgs(e);const i=e??Re;n.validator?.navigation.validateNavigationOptions(i,"navigateToDefault");const s=this.#lt.navigateToDefault(i);return this.#lt.lastSyncResolved?this.#lt.lastSyncResolved=!1:this.#lt.lastSyncRejected?this.#lt.lastSyncRejected=!1:t.#ft(s),s}navigateToNotFound(t){if(!this.#dt.isActive())throw new n(i.ROUTER_NOT_STARTED);if(void 0!==t&&"string"!=typeof t)throw new TypeError("[router.navigateToNotFound] path must be a string, got "+typeof t);const e=t??this.#ot.get().path;return this.#lt.navigateToNotFound(e)}static#mt=t=>{t instanceof n&&(t.code===i.SAME_STATES||t.code===i.TRANSITION_CANCELLED||t.code===i.ROUTER_NOT_STARTED||t.code===i.ROUTE_NOT_FOUND)||f.error("router.navigate","Unexpected navigation error",t)};static#ft(e){e.catch(t.#mt)}#pt(){this.navigate=De,this.navigateToDefault=De,this.navigateToNotFound=De,this.start=De,this.stop=De,this.usePlugin=De,this.subscribe=De,this.canNavigateTo=De}};function De(){throw new n(i.ROUTER_DISPOSED)}export{Ce as Router,J as clearConfigEntries,kt as clearRouteData,It as f,L as guardRouteStructure,xt as refreshForwardMap,Gt as registerAllRouteHandlers,H as removeFromDefinitions,m as resolveForwardChain,K as sanitizeRoute};//# sourceMappingURL=chunk-XQJDGUQE.mjs.map