@real-router/core 0.81.0 → 0.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -13
- package/dist/cjs/Router-CCmcEi-S.js +2 -0
- package/dist/cjs/Router-CCmcEi-S.js.map +1 -0
- package/dist/cjs/Router.d.ts +7 -6
- package/dist/cjs/Router.d.ts.map +1 -1
- package/dist/cjs/Router.js +1 -1
- package/dist/cjs/Router.js.map +1 -1
- package/dist/cjs/api/getPluginApi.d.ts.map +1 -1
- package/dist/cjs/api/getPluginApi.js +1 -1
- package/dist/cjs/api/getPluginApi.js.map +1 -1
- package/dist/cjs/api/getRoutesApi.d.ts.map +1 -1
- package/dist/cjs/api/getRoutesApi.js +1 -1
- package/dist/cjs/api/getRoutesApi.js.map +1 -1
- package/dist/cjs/api.js +2 -1
- package/dist/cjs/api.js.map +1 -1
- package/dist/cjs/buildParamMeta-0m11OIJS.js +2 -0
- package/dist/cjs/buildParamMeta-0m11OIJS.js.map +1 -0
- package/dist/cjs/channels/defaults.js +2 -0
- package/dist/cjs/channels/defaults.js.map +1 -0
- package/dist/cjs/channels/guard.js +2 -0
- package/dist/cjs/channels/guard.js.map +1 -0
- package/dist/cjs/channels/modeGate.js +2 -0
- package/dist/cjs/channels/modeGate.js.map +1 -0
- package/dist/cjs/constants.d.ts.map +1 -1
- package/dist/cjs/constants.js +1 -1
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/createRouter.d.ts +1 -1
- package/dist/cjs/createRouter.d.ts.map +1 -1
- package/dist/cjs/createRouter.js.map +1 -1
- package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts +14 -1
- package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts.map +1 -1
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js +1 -1
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js.map +1 -1
- package/dist/cjs/engine/path-matcher/registration/buildParts.js +1 -1
- package/dist/cjs/engine/path-matcher/registration/buildParts.js.map +1 -1
- package/dist/cjs/engine/path-matcher/registration/context.js +1 -1
- package/dist/cjs/engine/path-matcher/registration/context.js.map +1 -1
- package/dist/cjs/engine/path-matcher/registration/errors.js +1 -1
- package/dist/cjs/engine/path-matcher/registration/errors.js.map +1 -1
- package/dist/cjs/engine/path-matcher/registration/index.js +1 -1
- package/dist/cjs/engine/path-matcher/registration/index.js.map +1 -1
- package/dist/cjs/engine/path-matcher/types.d.ts +3 -0
- package/dist/cjs/engine/path-matcher/types.d.ts.map +1 -1
- package/dist/cjs/engine/search-params/strategies/number.js +1 -1
- package/dist/cjs/engine/search-params/strategies/number.js.map +1 -1
- package/dist/cjs/engine/validation/routes.js +1 -1
- package/dist/cjs/engine/validation/routes.js.map +1 -1
- package/dist/cjs/helpers.js +1 -1
- package/dist/cjs/helpers.js.map +1 -1
- package/dist/cjs/index.d.ts +3 -3
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/internals.d.ts +30 -8
- package/dist/cjs/internals.d.ts.map +1 -1
- package/dist/cjs/internals.js +1 -1
- package/dist/cjs/internals.js.map +1 -1
- package/dist/cjs/limits.js +2 -0
- package/dist/cjs/limits.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js.map +1 -1
- package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js.map +1 -1
- package/dist/cjs/namespaces/OptionsNamespace/constants.js +1 -1
- package/dist/cjs/namespaces/OptionsNamespace/constants.js.map +1 -1
- package/dist/cjs/namespaces/OptionsNamespace/helpers.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts +8 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/types.d.ts +24 -7
- package/dist/cjs/namespaces/RoutesNamespace/types.d.ts.map +1 -1
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js +1 -1
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js.map +1 -1
- package/dist/cjs/pipeline/buildURL.js +2 -0
- package/dist/cjs/pipeline/buildURL.js.map +1 -0
- package/dist/cjs/pipeline/canonicalize.js +2 -0
- package/dist/cjs/pipeline/canonicalize.js.map +1 -0
- package/dist/cjs/pipeline/materialize.js +2 -0
- package/dist/cjs/pipeline/materialize.js.map +1 -0
- package/dist/cjs/pipeline/port.d.ts +147 -0
- package/dist/cjs/pipeline/port.d.ts.map +1 -0
- package/dist/cjs/transitionPath.js +1 -1
- package/dist/cjs/transitionPath.js.map +1 -1
- package/dist/cjs/types/RouterValidator.d.ts +14 -0
- package/dist/cjs/types/RouterValidator.d.ts.map +1 -1
- package/dist/cjs/types/api.d.ts +20 -11
- package/dist/cjs/types/api.d.ts.map +1 -1
- package/dist/cjs/types/base.d.ts +63 -4
- package/dist/cjs/types/base.d.ts.map +1 -1
- package/dist/cjs/types/constants.d.ts +1 -0
- package/dist/cjs/types/constants.d.ts.map +1 -1
- package/dist/cjs/types/router.d.ts +111 -22
- package/dist/cjs/types/router.d.ts.map +1 -1
- package/dist/cjs/types/tree-changed.d.ts +1 -1
- package/dist/cjs/types/tree-changed.d.ts.map +1 -1
- package/dist/cjs/types.d.ts +20 -11
- package/dist/cjs/types.d.ts.map +1 -1
- package/dist/cjs/validation.js +2 -1
- package/dist/cjs/validation.js.map +1 -1
- package/dist/cjs/wiring/wireNamespaces.js +1 -1
- package/dist/cjs/wiring/wireNamespaces.js.map +1 -1
- package/dist/esm/Router-DEpNuwBW.mjs +2 -0
- package/dist/esm/Router-DEpNuwBW.mjs.map +1 -0
- package/dist/esm/Router.d.mts +7 -6
- package/dist/esm/Router.d.mts.map +1 -1
- package/dist/esm/api/getPluginApi.d.mts.map +1 -1
- package/dist/esm/api/getRoutesApi.d.mts.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/api.mjs.map +1 -1
- package/dist/esm/buildParamMeta-D8td47fL.mjs +2 -0
- package/dist/esm/buildParamMeta-D8td47fL.mjs.map +1 -0
- package/dist/esm/constants.d.mts.map +1 -1
- package/dist/esm/createRouter.d.mts +1 -1
- package/dist/esm/createRouter.d.mts.map +1 -1
- package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts +14 -1
- package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts.map +1 -1
- package/dist/esm/engine/path-matcher/types.d.mts +3 -0
- package/dist/esm/engine/path-matcher/types.d.mts.map +1 -1
- package/dist/esm/index.d.mts +3 -3
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/internals.d.mts +30 -8
- package/dist/esm/internals.d.mts.map +1 -1
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts +8 -0
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts.map +1 -1
- package/dist/esm/namespaces/RoutesNamespace/types.d.mts +24 -7
- package/dist/esm/namespaces/RoutesNamespace/types.d.mts.map +1 -1
- package/dist/esm/pipeline/port.d.mts +147 -0
- package/dist/esm/pipeline/port.d.mts.map +1 -0
- package/dist/esm/types/RouterValidator.d.mts +14 -0
- package/dist/esm/types/RouterValidator.d.mts.map +1 -1
- package/dist/esm/types/api.d.mts +20 -11
- package/dist/esm/types/api.d.mts.map +1 -1
- package/dist/esm/types/base.d.mts +63 -4
- package/dist/esm/types/base.d.mts.map +1 -1
- package/dist/esm/types/constants.d.mts +1 -0
- package/dist/esm/types/constants.d.mts.map +1 -1
- package/dist/esm/types/router.d.mts +111 -22
- package/dist/esm/types/router.d.mts.map +1 -1
- package/dist/esm/types/tree-changed.d.mts +1 -1
- package/dist/esm/types/tree-changed.d.mts.map +1 -1
- package/dist/esm/types.d.mts +20 -11
- package/dist/esm/types.d.mts.map +1 -1
- package/dist/esm/validation.mjs +1 -1
- package/dist/esm/validation.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/cjs/Router-BIYDZRgF.js +0 -2
- package/dist/cjs/Router-BIYDZRgF.js.map +0 -1
- package/dist/cjs/buildParamMeta-DniluAIV.js +0 -2
- package/dist/cjs/buildParamMeta-DniluAIV.js.map +0 -1
- package/dist/cjs/namespaces/StateNamespace/helpers.js +0 -2
- package/dist/cjs/namespaces/StateNamespace/helpers.js.map +0 -1
- package/dist/cjs/stateMetaStore.js +0 -2
- package/dist/cjs/stateMetaStore.js.map +0 -1
- package/dist/esm/Router-BIui2eew.mjs +0 -2
- package/dist/esm/Router-BIui2eew.mjs.map +0 -1
- package/dist/esm/buildParamMeta-bOLhLF9h.mjs +0 -2
- package/dist/esm/buildParamMeta-bOLhLF9h.mjs.map +0 -1
package/dist/cjs/Router.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Params, State, Unsubscribe } from "./types/base.js";
|
|
1
|
+
import { NavigationTarget, Params, SearchParams, State, Unsubscribe } from "./types/base.js";
|
|
2
2
|
import { DefaultDependencies, LeaveFn, Options, PluginFactory, Route, Router as Router$1, SubscribeFn } from "./types/router.js";
|
|
3
3
|
import { NavigationOptions } from "./types.js";
|
|
4
4
|
//#region src/Router.d.ts
|
|
@@ -26,9 +26,9 @@ declare class Router<Dependencies extends DefaultDependencies = DefaultDependenc
|
|
|
26
26
|
* @param options - Router options
|
|
27
27
|
* @param dependencies - DI dependencies
|
|
28
28
|
*/
|
|
29
|
-
constructor(routes?: Route<Dependencies>[], options?: Partial<Options
|
|
30
|
-
isActiveRoute(name: string, params?: Params, strictEquality?: boolean, ignoreQueryParams?: boolean): boolean;
|
|
31
|
-
buildPath(route: string, params?: Params): string;
|
|
29
|
+
constructor(routes?: Route<Dependencies>[], options?: Partial<Options<Dependencies>>, dependencies?: Dependencies);
|
|
30
|
+
isActiveRoute(name: string, params?: Params, search?: SearchParams, strictEquality?: boolean, ignoreQueryParams?: boolean): boolean;
|
|
31
|
+
buildPath(route: string, params?: Params, search?: SearchParams): string;
|
|
32
32
|
getState<P extends Params = Params>(): State<P> | undefined;
|
|
33
33
|
getPreviousState(): State | undefined;
|
|
34
34
|
areStatesEqual(state1: State | undefined, state2: State | undefined, ignoreQueryParams?: boolean): boolean;
|
|
@@ -37,12 +37,13 @@ declare class Router<Dependencies extends DefaultDependencies = DefaultDependenc
|
|
|
37
37
|
start(startPath: string): Promise<State>;
|
|
38
38
|
stop(): this;
|
|
39
39
|
dispose(): void;
|
|
40
|
-
canNavigateTo(name: string, params?: Params): boolean;
|
|
40
|
+
canNavigateTo(name: string, params?: Params, search?: SearchParams): boolean;
|
|
41
41
|
usePlugin(...plugins: (PluginFactory<Dependencies> | false | null | undefined)[]): Unsubscribe;
|
|
42
42
|
subscribe(listener: SubscribeFn): Unsubscribe;
|
|
43
43
|
subscribeLeave(listener: LeaveFn): Unsubscribe;
|
|
44
44
|
isLeaveApproved(): boolean;
|
|
45
|
-
navigate(
|
|
45
|
+
navigate(target: NavigationTarget, options?: NavigationOptions): Promise<State>;
|
|
46
|
+
navigate(routeName: string, routeParams?: Params, routeSearch?: SearchParams, options?: NavigationOptions): Promise<State>;
|
|
46
47
|
navigateToDefault(options?: NavigationOptions): Promise<State>;
|
|
47
48
|
navigateToNotFound(path?: string): State;
|
|
48
49
|
}
|
package/dist/cjs/Router.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Router.d.ts","names":[],"sources":["../../src/Router.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"Router.d.ts","names":[],"sources":["../../src/Router.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;cAkGa,OACX,qBAAqB,sBAAsB,gCAChC,SAAgB;;GAC1B;;;;;;EA4CC,YAAA,SAAQ,MAAM,iBACd,UAAS,QAAQ,QAAQ,gBACzB,eAAc;EAsXhB,cACE,cACA,SAAS,QACT,SAAS,cACT,0BACA;EAmCF,UAAU,eAAe,SAAS,QAAQ,SAAS;EAgBnD,SAAS,UAAU,SAAS,WAAW,MAAM;EAI7C,oBAAoB;EAIpB,eACE,QAAQ,mBACR,QAAQ,mBACR;EAWF,iBACE,oBACE,SAAS,OAAO,YAAY;EAYhC;EAIA,MAAM,oBAAoB,QAAQ;EA4DlC;EAyBA;EAsDA,cAAc,cAAc,SAAS,QAAQ,SAAS;EAuItD,aACK,UAAU,cAAc,8CAC1B;EAyCH,UAAU,UAAU,cAAc;EAMlC,eAAe,UAAU,UAAU;EAMnC;EAQA,SACE,QAAQ,kBACR,UAAU,oBACT,QAAQ;EACX,SACE,mBACA,cAAc,QACd,cAAc,cACd,UAAU,oBACT,QAAQ;EA8DX,kBAAkB,UAAU,oBAAoB,QAAQ;EA2BxD,mBAAmB,gBAAgB"}
|
package/dist/cjs/Router.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants.js"),t=require("./guards.js"),n=require("./helpers.js"),r=require("./internals.js"),i=require("./namespaces/DependenciesNamespace/dependenciesStore.js"),a=require("./namespaces/OptionsNamespace/OptionsNamespace.js"),o=require("./namespaces/StateNamespace/StateNamespace.js"),s=require("./namespaces/PluginsNamespace/PluginsNamespace.js"),c=require("./namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js"),l=require("./transitionPath.js"),u=require("./namespaces/RoutesNamespace/RoutesNamespace.js"),d=require("./RouterError.js"),f=require("./namespaces/NavigationNamespace/NavigationNamespace.js"),p=require("./namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js"),m=require("./routerFSM.js"),h=require("./namespaces/EventBusNamespace/EventBusNamespace.js"),g=require("./namespaces/RouterLifecycleNamespace/constants.js"),_=require("./utils/event-emitter/EventEmitter.js"),v=require("./utils/logger/RouterLogger.js"),y=require("./wiring/wireNamespaces.js"),b=Object.freeze({}),x=new Set([e.errorCodes.SAME_STATES,e.errorCodes.TRANSITION_CANCELLED,e.errorCodes.ROUTER_NOT_STARTED,e.errorCodes.ROUTE_NOT_FOUND,e.errorCodes.CANNOT_ACTIVATE,e.errorCodes.CANNOT_DEACTIVATE]);var S=class S{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(l=[],d={},g={}){let{logger:x,...C}=d;x&&t.assertLoggerConfig(x);let T=new v.RouterLogger(x);this.#u=e=>{S.#f(e)||T.error(`router.navigate`,`Unexpected navigation error`,e)},this.#d=e=>{S.#f(e)||T.error(`router.start`,`Unexpected start error`,e)},a.OptionsNamespace.validateOptionsIsObject(d),t.guardDependencies(g),l.length>0&&t.guardRouteStructure(l),this.#e=new a.OptionsNamespace(C),this.#t=n.createLimits(C.limits),this.#n=i.createDependenciesStore(g),this.#r=new o.StateNamespace,this.#i=new u.RoutesNamespace(l,w(this.#e.get()),T),this.#a=new c.RouteLifecycleNamespace,this.#o=new s.PluginsNamespace,this.#s=new f.NavigationNamespace,this.#c=new p.RouterLifecycleNamespace;let E=m.createRouterFSM(),D=new _.EventEmitter({onListenerError:(e,t)=>{T.error(`Router`,`Error in listener for ${e}:`,t)},onListenerWarn:(e,t)=>{T.warn(`router.addEventListener`,`Event "${e}" has ${t} listeners — possible memory leak`)}});this.#l=new h.EventBusNamespace({routerFSM:E,emitter:D,abortController:e=>{this.#s.abortCurrentController(e)}});let O=new Map;r.registerInternals(this,{logger:T,makeState:(e,t,n,r)=>this.#r.makeState(e,t,n,r),forwardState:r.createBinaryInterceptable(`forwardState`,(e,t)=>this.#i.forwardState(e,t),O),buildStateResolved:(e,t)=>this.#i.buildStateResolved(e,t),matchPath:(e,t)=>this.#i.matchPath(e,t),getOptions:()=>this.#e.get(),addEventListener:(e,t)=>this.#l.addEventListener(e,t),treeChanged:{emit:e=>{this.#l.emitTreeChanged(e)},subscribe:e=>this.#l.subscribeTreeChanged(e),listenerCount:()=>this.#l.treeChangedListenerCount(),isEmitting:()=>this.#l.isEmittingTreeChanged()},buildPath:r.createBinaryInterceptable(`buildPath`,(t,n)=>this.#i.buildPath(t,n??e.EMPTY_PARAMS,this.#e.get()),O),emitTransitionError:e=>{this.#l.sendFailSafe(void 0,this.#r.get(),e)},emitTransitionSuccess:(e,t,n)=>{this.#l.emitTransitionSuccess(e,t,n)},navigateToNotFound:e=>this.#s.navigateToNotFound(e),start:r.createInterceptable(`start`,e=>this.#c.start(e),O),navigateToState:(e,t)=>{this.#m();let n=this.#s.navigateToState(e,t??b);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(n),n},interceptors:O,setRootPath:e=>{this.#i.setRootPath(e)},getRootPath:()=>this.#i.getStore().rootPath,getTree:()=>this.#i.getStore().tree,isDisposed:()=>this.#l.isDisposed(),validator:null,dependenciesGetStore:()=>this.#n,getCloneState:()=>({options:{...this.#e.get()},dependencies:{...this.#n.dependencies},pluginFactories:this.#o.getAll(),loggerConfig:T.getConfig()}),routeGetStore:()=>this.#i.getStore(),getStateName:()=>this.#r.get()?.name,isTransitioning:()=>this.#l.isTransitioning(),clearState:()=>{this.#r.set(void 0)},setState:e=>{this.#r.set(e)},routerExtensions:[],contextClaimRecords:new Set,hydrationState:null}),y.wireNamespaces({router:this,options:this.#e,limits:this.#t,dependenciesStore:this.#n,state:this.#r,routes:this.#i,routeLifecycle:this.#a,plugins:this.#o,navigation:this.#s,lifecycle:this.#c,eventBus:this.#l}),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),this.subscribeLeave=this.subscribeLeave.bind(this),this.isLeaveApproved=this.isLeaveApproved.bind(this);try{this.#i.flushPendingGuards()}catch(e){throw this.dispose(),e}}isActiveRoute(e,t,n,i){return r.getInternals(this).validator?.routes.validateIsActiveRouteArgs(e,t,n,i),r.getInternals(this).validator?.routes.validateRouteName(e,`isActiveRoute`),e===``?(r.getInternals(this).logger.warn(`real-router`,`isActiveRoute("") called with empty string. Root node is not considered a parent of any route.`),!1):this.#i.isActiveRoute(e,t,n,i)}buildPath(e,t){let i=r.getInternals(this);return i.validator?.routes.validateBuildPathArgs(e),i.validator?.navigation.validateParams(t,`buildPath`),i.buildPath(e,n.normalizeParams(t))}getState(){return this.#r.get()}getPreviousState(){return this.#r.getPrevious()}areStatesEqual(e,t,n=!0){return r.getInternals(this).validator?.state.validateAreStatesEqualArgs(e,t,n),this.#r.areStatesEqual(e,t,n)}shouldUpdateNode(e){return r.getInternals(this).validator?.routes.validateShouldUpdateNodeArgs(e),u.RoutesNamespace.shouldUpdateNode(e)}isActive(){return this.#l.isActive()}start(e){if(!this.#l.canStart())return Promise.reject(g.CACHED_ALREADY_STARTED_ERROR);r.getInternals(this).validator?.navigation.validateStartArgs(e),this.#l.sendStart();let t;try{let n=r.getInternals(this).start(e);t=typeof n?.then==`function`?n:Promise.reject(TypeError("[router.start] a `start` interceptor returned without calling next(). Every start interceptor must return `next(path)`."))}catch(e){t=Promise.reject(e)}let n=t.catch(e=>this.#h(e));return this.#p(n,this.#d),n}stop(){return this.#l.sendCancelIfPossible(this.#r.get()),!this.#l.isReady()&&!this.#l.isTransitioning()&&!this.#l.isStarting()?this:(this.#c.stop(),this.#l.sendStop(),this)}dispose(){if(this.#l.isDisposed())return;this.#l.sendCancelIfPossible(this.#r.get()),(this.#l.isReady()||this.#l.isTransitioning())&&(this.#c.stop(),this.#l.sendStop()),this.#l.sendDispose(),this.#l.clearAll(),this.#o.disposeAll();let e=r.getInternals(this);for(let t of e.routerExtensions)for(let e of t.keys)delete this[e];e.routerExtensions.length=0,e.contextClaimRecords.clear(),e.interceptors.clear(),this.#i.clearRoutes(),this.#a.clearAll(),this.#r.reset(),this.#n.dependencies=Object.create(null),this.#g()}canNavigateTo(e,t){let i=r.getInternals(this);if(i.validator?.routes.validateRouteName(e,`canNavigateTo`),i.validator?.navigation.validateParams(t,`canNavigateTo`),!this.#i.hasRoute(e))return!1;let{name:a,params:o}=i.forwardState(e,t??{}),s;try{let e=n.normalizeParams(o),t=this.#i.getMetaForState(a),r=i.buildPath(a,e);s=this.#r.makeState(a,e,r,t,!0)}catch{return!1}let c=this.#r.get(),{toDeactivate:u,toActivate:d}=l.getTransitionPath(s,c);return this.#a.canNavigateTo(u,d,s,c)}usePlugin(...t){if(this.#l.isDisposed())throw new d.RouterError(e.errorCodes.ROUTER_DISPOSED);let n=t.filter(Boolean);if(n.length===0)return()=>{};let i=r.getInternals(this);i.validator?.plugins.validatePluginLimit(this.#o.count(),this.#t);for(let e of n)i.validator?.plugins.validateNoDuplicatePlugins(e,this.#o.getAll());return this.#o.use(...n)}subscribe(e){return h.EventBusNamespace.validateSubscribeListener(e),this.#l.subscribe(e)}subscribeLeave(e){return h.EventBusNamespace.validateSubscribeLeaveListener(e),this.#l.subscribeLeave(e)}isLeaveApproved(){return this.#l.isLeaveApproved()}navigate(t,n,i){this.#m();let a=r.getInternals(this);a.validator?.navigation.validateNavigateArgs(t),a.validator?.navigation.validateParams(n,`navigate`);let o=i??b;a.validator?.navigation.validateNavigationOptions(o,`navigate`);let s=this.#s.navigate(t,n??e.EMPTY_PARAMS,o);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(s),s}navigateToDefault(e){this.#m();let t=r.getInternals(this);t.validator?.navigation.validateNavigateToDefaultArgs(e);let n=e??b;t.validator?.navigation.validateNavigationOptions(n,`navigateToDefault`);let i=this.#s.navigateToDefault(n);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(i),i}navigateToNotFound(t){if(this.#m(),!this.#l.isActive())throw new d.RouterError(e.errorCodes.ROUTER_NOT_STARTED);if(t!==void 0&&typeof t!=`string`)throw TypeError(`[router.navigateToNotFound] path must be a string, got ${typeof t}`);if(t!==void 0)return this.#s.navigateToNotFound(t);let n=this.#r.get();if(n===void 0)throw new d.RouterError(e.errorCodes.ROUTER_NOT_STARTED,{message:`[router.navigateToNotFound] cannot derive the path before the start navigation commits — pass an explicit path`});return this.#s.navigateToNotFound(n.path)}static#f(e){return e instanceof d.RouterError&&x.has(e.code)}#p(e,t=this.#u){e.catch(t)}#m(){if(this.#l.isProcessing())throw new d.RouterError(e.errorCodes.REENTRANT_NAVIGATION)}#h(e){throw this.#l.isReady()&&this.#r.get()===void 0?(this.#c.stop(),this.#l.sendStop()):this.#l.isStarting()&&this.#l.sendFail(void 0,void 0,e),e}#g(){this.navigate=C,this.navigateToDefault=C,this.navigateToNotFound=C,this.start=C,this.stop=C,this.usePlugin=C,this.subscribe=C,this.subscribeLeave=C,this.canNavigateTo=C}};function C(){throw new d.RouterError(e.errorCodes.ROUTER_DISPOSED)}function w(e){return{strictTrailingSlash:e.trailingSlash===`strict`,caseSensitive:e.caseSensitive,strictQueryParams:e.queryParamsMode===`strict`,urlParamsEncoding:e.urlParamsEncoding,queryParams:e.queryParams}}exports.Router=S;
|
|
1
|
+
const e=require("./channels/guard.js"),t=require("./constants.js"),n=require("./guards.js"),r=require("./helpers.js"),i=require("./internals.js"),a=require("./limits.js"),o=require("./namespaces/DependenciesNamespace/dependenciesStore.js"),s=require("./namespaces/OptionsNamespace/OptionsNamespace.js"),c=require("./pipeline/canonicalize.js"),l=require("./pipeline/buildURL.js"),u=require("./pipeline/materialize.js"),d=require("./namespaces/StateNamespace/StateNamespace.js"),f=require("./namespaces/PluginsNamespace/PluginsNamespace.js"),p=require("./namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js"),m=require("./transitionPath.js"),h=require("./namespaces/RoutesNamespace/RoutesNamespace.js"),g=require("./RouterError.js"),_=require("./namespaces/NavigationNamespace/NavigationNamespace.js"),v=require("./namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js"),y=require("./routerFSM.js"),b=require("./namespaces/EventBusNamespace/EventBusNamespace.js"),x=require("./namespaces/RouterLifecycleNamespace/constants.js"),S=require("./utils/event-emitter/EventEmitter.js"),C=require("./utils/logger/RouterLogger.js"),w=require("./wiring/wireNamespaces.js"),T=Object.freeze({}),E=new Set([t.errorCodes.SAME_STATES,t.errorCodes.TRANSITION_CANCELLED,t.errorCodes.ROUTER_NOT_STARTED,t.errorCodes.ROUTE_NOT_FOUND,t.errorCodes.CANNOT_ACTIVATE,t.errorCodes.CANNOT_DEACTIVATE]);var D=class D{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(r=[],c={},l={}){let{logger:u,...m}=c;u&&n.assertLoggerConfig(u);let g=new C.RouterLogger(u);this.#u=e=>{D.#f(e)||g.error(`router.navigate`,`Unexpected navigation error`,e)},this.#d=e=>{D.#f(e)||g.error(`router.start`,`Unexpected start error`,e)},s.OptionsNamespace.validateOptionsIsObject(c),n.guardDependencies(l),r.length>0&&n.guardRouteStructure(r),this.#e=new s.OptionsNamespace(m),this.#t=a.createLimits(m.limits),this.#n=o.createDependenciesStore(l),this.#r=new d.StateNamespace,this.#i=new h.RoutesNamespace(r,k(this.#e.get()),g),this.#a=new p.RouteLifecycleNamespace,this.#o=new f.PluginsNamespace,this.#s=new _.NavigationNamespace,this.#c=new v.RouterLifecycleNamespace;let x=y.createRouterFSM(),E=new S.EventEmitter({onListenerError:(e,t)=>{g.error(`Router`,`Error in listener for ${e}:`,t)},onListenerWarn:(e,t)=>{g.warn(`router.addEventListener`,`Event "${e}" has ${t} listeners — possible memory leak`)}});this.#l=new b.EventBusNamespace({routerFSM:x,emitter:E,abortController:e=>{this.#s.abortCurrentController(e)}});let O=new Map,A=i.createTernaryInterceptable(`forwardState`,(e,t,n)=>this.#i.forwardState(e,t,n),O);i.registerInternals(this,{logger:g,makeState:(e,t,n,r)=>this.#r.makeState(e,t,n,r),getMetaForState:e=>this.#i.getMetaForState(e),getQueryParams:e=>this.#i.getQueryParams(e),forwardState:((n,r,i)=>{let a=A(n,r,i);return e.assertChannelCorrect(`forwardState`,a.name,a.params,this.#i.getQueryParams(a.name),()=>a.name===n?"the `params` bag leaving the forwardState chain":`the \`params\` bag leaving the forwardState chain (forwarded here from "${n}")`),{name:a.name,params:a.params??t.EMPTY_PARAMS,search:a.search}}),buildStateResolved:(e,t)=>this.#i.buildStateResolved(e,t),port:()=>this.#i.getPort(),matchPath:(e,t)=>this.#i.matchPath(e,t),getOptions:()=>this.#e.get(),addEventListener:(e,t)=>this.#l.addEventListener(e,t),treeChanged:{emit:e=>{this.#l.emitTreeChanged(e)},subscribe:e=>this.#l.subscribeTreeChanged(e),listenerCount:()=>this.#l.treeChangedListenerCount(),isEmitting:()=>this.#l.isEmittingTreeChanged()},buildPath:i.createTernaryInterceptable(`buildPath`,(e,n,r)=>this.#i.buildPath(e,n??t.EMPTY_PARAMS,r,this.#e.get()),O),emitTransitionError:e=>{this.#l.sendFailSafe(void 0,this.#r.get(),e)},emitTransitionSuccess:(e,t,n)=>{this.#l.emitTransitionSuccess(e,t,n)},navigateToNotFound:e=>this.#s.navigateToNotFound(e),start:i.createInterceptable(`start`,e=>this.#c.start(e),O),navigateToState:(e,t)=>{this.#m();let n=this.#s.navigateToState(e,t??T);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(n),n},interceptors:O,setRootPath:e=>{this.#i.setRootPath(e)},getRootPath:()=>this.#i.getStore().rootPath,getTree:()=>this.#i.getStore().tree,isDisposed:()=>this.#l.isDisposed(),validator:null,dependenciesGetStore:()=>this.#n,getCloneState:()=>({options:{...this.#e.get()},dependencies:{...this.#n.dependencies},pluginFactories:this.#o.getAll(),loggerConfig:g.getConfig()}),routeGetStore:()=>this.#i.getStore(),getStateName:()=>this.#r.get()?.name,isTransitioning:()=>this.#l.isTransitioning(),clearState:()=>{this.#r.set(void 0)},setState:e=>{this.#r.set(e)},routerExtensions:[],contextClaimRecords:new Set,hydrationState:null}),w.wireNamespaces({router:this,options:this.#e,limits:this.#t,dependenciesStore:this.#n,state:this.#r,routes:this.#i,routeLifecycle:this.#a,plugins:this.#o,navigation:this.#s,lifecycle:this.#c,eventBus:this.#l}),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),this.subscribeLeave=this.subscribeLeave.bind(this),this.isLeaveApproved=this.isLeaveApproved.bind(this);try{this.#i.flushPendingGuards()}catch(e){throw this.dispose(),e}}isActiveRoute(e,t,n,r,a){return i.getInternals(this).validator?.routes.validateIsActiveRouteArgs(e,t,r,a),i.getInternals(this).validator?.routes.validateRouteName(e,`isActiveRoute`),e===``?(i.getInternals(this).logger.warn(`real-router`,`isActiveRoute("") called with empty string. Root node is not considered a parent of any route.`),!1):this.#i.isActiveRoute(e,t,n,r,a)}buildPath(e,t,n){let a=i.getInternals(this);return a.validator?.routes.validateBuildPathArgs(e),a.validator?.navigation.validateParams(t,`buildPath`),a.buildPath(e,r.normalizeParams(t),n)}getState(){return this.#r.get()}getPreviousState(){return this.#r.getPrevious()}areStatesEqual(e,t,n=!0){return i.getInternals(this).validator?.state.validateAreStatesEqualArgs(e,t,n),this.#r.areStatesEqual(e,t,n)}shouldUpdateNode(e){return i.getInternals(this).validator?.routes.validateShouldUpdateNodeArgs(e),h.RoutesNamespace.shouldUpdateNode(e,e=>this.#i.getMetaForState(e))}isActive(){return this.#l.isActive()}start(e){if(!this.#l.canStart())return Promise.reject(x.CACHED_ALREADY_STARTED_ERROR);i.getInternals(this).validator?.navigation.validateStartArgs(e),this.#l.sendStart();let t;try{let n=i.getInternals(this).start(e);t=typeof n?.then==`function`?n:Promise.reject(TypeError("[router.start] a `start` interceptor returned without calling next(). Every start interceptor must return `next(path)`."))}catch(e){t=Promise.reject(e)}let n=t.catch(e=>this.#h(e));return this.#p(n,this.#d),n}stop(){return this.#l.sendCancelIfPossible(this.#r.get()),!this.#l.isReady()&&!this.#l.isTransitioning()&&!this.#l.isStarting()?this:(this.#c.stop(),this.#l.sendStop(),this)}dispose(){if(this.#l.isDisposed())return;this.#l.sendCancelIfPossible(this.#r.get()),(this.#l.isReady()||this.#l.isTransitioning())&&(this.#c.stop(),this.#l.sendStop()),this.#l.sendDispose(),this.#l.clearAll(),this.#o.disposeAll();let e=i.getInternals(this);for(let t of e.routerExtensions)for(let e of t.keys)delete this[e];e.routerExtensions.length=0,e.contextClaimRecords.clear(),e.interceptors.clear(),this.#i.clearRoutes(),this.#a.clearAll(),this.#r.reset(),this.#n.dependencies=Object.create(null),this.#g()}canNavigateTo(n,r,a){let o=i.getInternals(this);if(o.validator?.routes.validateRouteName(n,`canNavigateTo`),o.validator?.navigation.validateParams(r,`canNavigateTo`),!this.#i.hasRoute(n)||e.findMisChanneledKey(r,this.#i.getQueryParams(n))!==void 0)return!1;let s=this.#i.getPort(),d;try{d=c.canonicalize(s,n,r??t.EMPTY_PARAMS,a)}catch(e){return o.logger.warn(`router.canNavigateTo`,`Resolving route "${n}" threw while answering the predicate; treating the route as unreachable.`,e),!1}let f;try{f=u.materialize(d,{path:l.buildURL(d,s),skipFreeze:!0})}catch{return!1}let p=this.#r.get(),{toDeactivate:h,toActivate:g}=m.getTransitionPath(f,p,e=>this.#i.getMetaForState(e));return this.#a.canNavigateTo(h,g,f,p)}usePlugin(...e){if(this.#l.isDisposed())throw new g.RouterError(t.errorCodes.ROUTER_DISPOSED);let n=e.filter(Boolean);if(n.length===0)return()=>{};let r=i.getInternals(this);r.validator?.plugins.validatePluginLimit(this.#o.count(),this.#t);for(let e of n)r.validator?.plugins.validateNoDuplicatePlugins(e,this.#o.getAll());return this.#o.use(...n)}subscribe(e){return b.EventBusNamespace.validateSubscribeListener(e),this.#l.subscribe(e)}subscribeLeave(e){return b.EventBusNamespace.validateSubscribeLeaveListener(e),this.#l.subscribeLeave(e)}isLeaveApproved(){return this.#l.isLeaveApproved()}navigate(e,n,r,a){this.#m();let o=i.getInternals(this),s,c,l,u;typeof e==`object`&&e?(s=e.name,c=e.params,l=e.search,u=n??T):(s=e,c=n,l=r,u=a??T),i.throwOnMisChanneledKey(o,`navigate`,s,c),o.validator?.navigation.validateNavigateArgs(s),o.validator?.navigation.validateParams(c,`navigate`),o.validator?.navigation.validateNavigationOptions(u,`navigate`);let d=this.#s.navigate(s,c??t.EMPTY_PARAMS,l,u);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(d),d}navigateToDefault(e){this.#m();let t=i.getInternals(this);t.validator?.navigation.validateNavigateToDefaultArgs(e);let n=e??T;t.validator?.navigation.validateNavigationOptions(n,`navigateToDefault`);let r=this.#s.navigateToDefault(n);return this.#s.lastSyncResolved?this.#s.lastSyncResolved=!1:this.#s.lastSyncRejected?this.#s.lastSyncRejected=!1:this.#p(r),r}navigateToNotFound(e){if(this.#m(),!this.#l.isActive())throw new g.RouterError(t.errorCodes.ROUTER_NOT_STARTED);if(e!==void 0&&typeof e!=`string`)throw TypeError(`[router.navigateToNotFound] path must be a string, got ${typeof e}`);if(e!==void 0)return this.#s.navigateToNotFound(e);let n=this.#r.get();if(n===void 0)throw new g.RouterError(t.errorCodes.ROUTER_NOT_STARTED,{message:`[router.navigateToNotFound] cannot derive the path before the start navigation commits — pass an explicit path`});return this.#s.navigateToNotFound(n.path)}static#f(e){return e instanceof g.RouterError&&E.has(e.code)}#p(e,t=this.#u){e.catch(t)}#m(){if(this.#l.isProcessing())throw new g.RouterError(t.errorCodes.REENTRANT_NAVIGATION)}#h(e){throw this.#l.isReady()&&this.#r.get()===void 0?(this.#c.stop(),this.#l.sendStop()):this.#l.isStarting()&&this.#l.sendFail(void 0,void 0,e),e}#g(){this.navigate=O,this.navigateToDefault=O,this.navigateToNotFound=O,this.start=O,this.stop=O,this.usePlugin=O,this.subscribe=O,this.subscribeLeave=O,this.canNavigateTo=O}};function O(){throw new g.RouterError(t.errorCodes.ROUTER_DISPOSED)}function k(e){return{strictTrailingSlash:e.trailingSlash===`strict`,caseSensitive:e.caseSensitive,strictQueryParams:e.queryParamsMode===`strict`,urlParamsEncoding:e.urlParamsEncoding,queryParams:e.queryParams}}exports.Router=D;
|
|
2
2
|
//# sourceMappingURL=Router.js.map
|
package/dist/cjs/Router.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Router.js","names":["errorCodes","#options","#limits","#dependenciesStore","#state","#routes","#routeLifecycle","#plugins","#navigation","#lifecycle","#eventBus","#onSuppressedNavigateError","#onSuppressedStartError","RouterLogger","#isExpectedRejection","OptionsNamespace","createLimits","createDependenciesStore","StateNamespace","RoutesNamespace","RouteLifecycleNamespace","PluginsNamespace","NavigationNamespace","RouterLifecycleNamespace","createRouterFSM","EventEmitter","EventBusNamespace","createBinaryInterceptable","EMPTY_PARAMS","createInterceptable","#assertNotReentrant","#suppressUnhandledRejection","getInternals","normalizeParams","CACHED_ALREADY_STARTED_ERROR","#unwindFailedStart","#markDisposed","getTransitionPath","RouterError"],"sources":["../../src/Router.ts"],"sourcesContent":["// packages/core/src/Router.ts\n\n/**\n * Router class - facade with integrated namespaces.\n *\n * All functionality is now provided by namespace classes.\n */\n\nimport { EMPTY_PARAMS, errorCodes } from \"./constants\";\nimport {\n assertLoggerConfig,\n guardDependencies,\n guardRouteStructure,\n} from \"./guards\";\nimport { createLimits, normalizeParams } from \"./helpers\";\nimport {\n createBinaryInterceptable,\n createInterceptable,\n getInternals,\n registerInternals,\n} from \"./internals\";\nimport {\n EventBusNamespace,\n NavigationNamespace,\n OptionsNamespace,\n PluginsNamespace,\n RouteLifecycleNamespace,\n RouterLifecycleNamespace,\n RoutesNamespace,\n StateNamespace,\n createDependenciesStore,\n} from \"./namespaces\";\nimport { CACHED_ALREADY_STARTED_ERROR } from \"./namespaces/RouterLifecycleNamespace/constants\";\nimport { RouterError } from \"./RouterError\";\nimport { createRouterFSM } from \"./routerFSM\";\nimport { getTransitionPath } from \"./transitionPath\";\nimport { EventEmitter } from \"./utils/event-emitter\";\nimport { RouterLogger } from \"./utils/logger\";\nimport { wireNamespaces } from \"./wiring\";\n\nimport type { CreateMatcherOptions } from \"./engine\";\nimport type { RouterInternals } from \"./internals\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type {\n DefaultDependencies,\n LeaveFn,\n NavigationOptions,\n Options,\n Params,\n Router as RouterInterface,\n State,\n SubscribeFn,\n Unsubscribe,\n PluginFactory,\n Route,\n} from \"./types\";\nimport type { Limits, RouterEventMap } from \"./types/internal\";\n\nconst EMPTY_OPTS: Readonly<NavigationOptions> = Object.freeze({});\n\n// Module-level so #isExpectedRejection allocates nothing per navigate()/start() call.\n// These are expected navigation outcomes owned by the caller, not internal\n// bugs — the safety net stays silent for them and lets awaiting callers see\n// the rejection. CANNOT_ACTIVATE / CANNOT_DEACTIVATE belong here: a guard\n// blocking (or a plugin's guard-blocked back()/forward()) is a normal result,\n// so a fire-and-forget call must not emit a spurious \"Unexpected navigation\n// error\" (#721).\nconst SUPPRESSED_ERROR_CODES: ReadonlySet<string> = new Set([\n errorCodes.SAME_STATES,\n errorCodes.TRANSITION_CANCELLED,\n errorCodes.ROUTER_NOT_STARTED,\n errorCodes.ROUTE_NOT_FOUND,\n errorCodes.CANNOT_ACTIVATE,\n errorCodes.CANNOT_DEACTIVATE,\n]);\n\n/**\n * Router class with integrated namespace architecture.\n *\n * All functionality is provided by namespace classes:\n * - OptionsNamespace: getOptions (immutable)\n * - DependenciesStore: get/set/remove dependencies\n * - EventEmitter: subscribe\n * - StateNamespace: state storage (getState, setState, getPreviousState)\n * - RoutesNamespace: route tree operations\n * - RouteLifecycleNamespace: canActivate/canDeactivate guards\n * - PluginsNamespace: plugin lifecycle\n * - NavigationNamespace: navigate\n * - RouterLifecycleNamespace: start, stop, isStarted\n *\n * @internal This class implementation is internal. Use createRouter() instead.\n */\nexport class Router<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> implements RouterInterface<Dependencies> {\n [key: string]: unknown;\n\n // ============================================================================\n // Namespaces\n // ============================================================================\n\n readonly #options: OptionsNamespace;\n readonly #limits: Limits;\n readonly #dependenciesStore: DependenciesStore<Dependencies>;\n readonly #state: StateNamespace;\n readonly #routes: RoutesNamespace<Dependencies>;\n readonly #routeLifecycle: RouteLifecycleNamespace<Dependencies>;\n readonly #plugins: PluginsNamespace<Dependencies>;\n readonly #navigation: NavigationNamespace;\n readonly #lifecycle: RouterLifecycleNamespace;\n\n readonly #eventBus: EventBusNamespace;\n\n /**\n * Per-instance suppressors for fire-and-forget navigate / start. They log\n * through THIS router's logger (built in the constructor) — so, unlike the\n * former static \"one allocation per class\" closures, they are two closures per\n * instance. Trade accepted with the per-router logger (#724): the logger is\n * per-instance, so its suppressors must be too. The #931 category split is\n * preserved — navigate failures log under \"router.navigate\", start failures\n * under \"router.start\" (a start interceptor throwing a plain Error after\n * next() committed, #763, or a cryptic path TypeError — neither a suppressed\n * RouterError). The log line IS reachable: a subscribeLeave listener that\n * throws rejects navigate() with the original NON-suppressed error, and a\n * Symbol path-param's stringify TypeError is likewise non-suppressed.\n */\n readonly #onSuppressedNavigateError: (error: unknown) => void;\n readonly #onSuppressedStartError: (error: unknown) => void;\n\n // ============================================================================\n // Constructor\n // ============================================================================\n\n /**\n * @param routes - Route definitions\n * @param options - Router options\n * @param dependencies - DI dependencies\n */\n constructor(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options> = {},\n dependencies: Dependencies = {} as Dependencies,\n ) {\n // Extract the logger config WITHOUT mutating the caller's `options` object\n // (#724). `routerOptions` is the logger-stripped view handed to the options\n // pipeline so `logger` never lands in the frozen router options.\n const { logger: loggerConfig, ...routerOptions } = options;\n\n if (loggerConfig) {\n assertLoggerConfig(loggerConfig);\n }\n\n // Per-router logger instance — replaces the former process-global singleton\n // whose configure() leaked across every router in the process, last\n // createRouter winning (#724). Stored on ctx (registerInternals below), so\n // the facade reads getInternals(this).logger; namespaces receive it via\n // their deps at wiring; plugins reach it through getPluginApi(router).logger.\n const logger = new RouterLogger(loggerConfig);\n\n // Per-instance fire-and-forget suppressors (see field declarations): they\n // log through THIS router's logger, so they are built here, not static.\n this.#onSuppressedNavigateError = (error: unknown): void => {\n if (Router.#isExpectedRejection(error)) {\n return;\n }\n\n logger.error(\"router.navigate\", \"Unexpected navigation error\", error);\n };\n this.#onSuppressedStartError = (error: unknown): void => {\n if (Router.#isExpectedRejection(error)) {\n return;\n }\n\n logger.error(\"router.start\", \"Unexpected start error\", error);\n };\n\n // =========================================================================\n // Validate inputs before creating namespaces\n // =========================================================================\n\n // Always validate the caller's options (catches non-object / array inputs)\n OptionsNamespace.validateOptionsIsObject(options);\n\n // Unconditional guard-level validation before creating namespaces\n guardDependencies(dependencies);\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `guardRouteStructure([])` on an empty array is a no-op, so validating an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips validation of a real route list and is killable.)\n if (routes.length > 0) {\n guardRouteStructure(routes);\n }\n\n // =========================================================================\n // Create Namespaces\n // =========================================================================\n\n this.#options = new OptionsNamespace(routerOptions);\n this.#limits = createLimits(routerOptions.limits);\n this.#dependenciesStore =\n createDependenciesStore<Dependencies>(dependencies);\n this.#state = new StateNamespace();\n this.#routes = new RoutesNamespace<Dependencies>(\n routes,\n deriveMatcherOptions(this.#options.get()),\n logger,\n );\n this.#routeLifecycle = new RouteLifecycleNamespace<Dependencies>();\n this.#plugins = new PluginsNamespace<Dependencies>();\n this.#navigation = new NavigationNamespace();\n this.#lifecycle = new RouterLifecycleNamespace();\n\n // =========================================================================\n // Initialize EventBus\n // =========================================================================\n\n const routerFSM = createRouterFSM();\n\n const emitter = new EventEmitter<RouterEventMap>({\n // Shared per-listener error sink: EventEmitter reports synchronous listener\n // throws here, and EventBusNamespace.subscribe routes an async listener's\n // rejected Promise through the SAME sink (#944) — both land in one place.\n onListenerError: (eventName, error) => {\n logger.error(\"Router\", `Error in listener for ${eventName}:`, error);\n },\n onListenerWarn: (eventName, count) => {\n logger.warn(\n \"router.addEventListener\",\n `Event \"${eventName}\" has ${count} listeners — possible memory leak`,\n );\n },\n });\n\n this.#eventBus = new EventBusNamespace({\n routerFSM,\n emitter,\n // The FSM CANCEL action aborts the in-flight\n // navigation controller via this injected effect — \"FSM CANCEL ⟹\n // controller aborted\" in one place. `#navigation` is constructed above.\n abortController: (reason) => {\n this.#navigation.abortCurrentController(reason);\n },\n });\n\n // =========================================================================\n // Register Internals (WeakMap for plugin/infrastructure access)\n // =========================================================================\n // Registered BEFORE wiring (#1331) so every namespace's deps-closure sees a\n // router already present in the internals registry — `getInternals(router)`\n // never throws during wiring, and guard factories flushed at the end of the\n // constructor see a fully-registered instance.\n\n const interceptorsMap: RouterInternals[\"interceptors\"] = new Map();\n\n registerInternals(this, {\n logger,\n makeState: (name, params, path, meta) =>\n this.#state.makeState(name, params, path, meta),\n // `as unknown as` is required: createBinaryInterceptable returns a\n // non-generic `(a: A, b: B) => R`, but RouterInternals[\"forwardState\"]\n // is declared with a generic parameter `<P extends Params = Params>`,\n // which tsc will not infer from the non-generic source. Sonar S4325\n // misclassifies this as a redundant cast.\n forwardState: createBinaryInterceptable(\n \"forwardState\",\n (name: string, params: Params) =>\n this.#routes.forwardState(name, params),\n interceptorsMap,\n ) as unknown as RouterInternals[\"forwardState\"],\n buildStateResolved: (name, params) =>\n this.#routes.buildStateResolved(name, params),\n matchPath: (path, matchOptions) =>\n this.#routes.matchPath(path, matchOptions),\n getOptions: () => this.#options.get(),\n addEventListener: (eventName, cb) =>\n this.#eventBus.addEventListener(eventName, cb),\n treeChanged: {\n emit: (event) => {\n this.#eventBus.emitTreeChanged(event);\n },\n subscribe: (handler) => this.#eventBus.subscribeTreeChanged(handler),\n listenerCount: () => this.#eventBus.treeChangedListenerCount(),\n isEmitting: () => this.#eventBus.isEmittingTreeChanged(),\n },\n buildPath: createBinaryInterceptable(\n \"buildPath\",\n (route: string, params?: Params) =>\n this.#routes.buildPath(\n route,\n params ?? EMPTY_PARAMS,\n this.#options.get(),\n ),\n interceptorsMap,\n ),\n emitTransitionError: (error) => {\n this.#eventBus.sendFailSafe(undefined, this.#state.get(), error);\n },\n emitTransitionSuccess: (toState, fromState, opts) => {\n this.#eventBus.emitTransitionSuccess(toState, fromState, opts);\n },\n navigateToNotFound: (path) => this.#navigation.navigateToNotFound(path),\n start: createInterceptable(\n \"start\",\n (path: string) => {\n return this.#lifecycle.start(path);\n },\n interceptorsMap,\n ),\n navigateToState: (state, navOpts) => {\n // Plugin-only navigation primitive (#525). Mirrors the same\n // unhandled-rejection suppression and lastSync* bookkeeping used by\n // the public Router.navigate facade so plugin call-sites can\n // fire-and-forget the returned promise (popstate handlers do).\n this.#assertNotReentrant();\n\n const promiseState = this.#navigation.navigateToState(\n state,\n navOpts ?? EMPTY_OPTS,\n );\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n },\n interceptors: interceptorsMap,\n setRootPath: (rootPath) => {\n this.#routes.setRootPath(rootPath);\n },\n getRootPath: () => this.#routes.getStore().rootPath,\n getTree: () => this.#routes.getStore().tree,\n isDisposed: () => this.#eventBus.isDisposed(),\n validator: null,\n // Dependencies (issue #172)\n dependenciesGetStore: () => this.#dependenciesStore,\n // Clone support (issue #173)\n getCloneState: () => ({\n options: { ...this.#options.get() },\n dependencies: { ...this.#dependenciesStore.dependencies },\n pluginFactories: this.#plugins.getAll(),\n // `logger` is a const in this constructor's scope (a RouterLogger class\n // instance), so getConfig() yields the resolved config a clone inherits\n // — frozen options don't carry `logger`, so cloneRouter reads it here.\n loggerConfig: logger.getConfig(),\n }),\n routeGetStore: () => this.#routes.getStore(),\n // Cross-namespace state (issue #174)\n getStateName: () => this.#state.get()?.name,\n isTransitioning: () => this.#eventBus.isTransitioning(),\n clearState: () => {\n this.#state.set(undefined);\n },\n setState: (state) => {\n this.#state.set(state);\n },\n routerExtensions: [],\n contextClaimRecords: new Set(),\n hydrationState: null,\n });\n\n // =========================================================================\n // Wire Dependencies\n // =========================================================================\n\n wireNamespaces<Dependencies>({\n router: this,\n options: this.#options,\n limits: this.#limits,\n dependenciesStore: this.#dependenciesStore,\n state: this.#state,\n routes: this.#routes,\n routeLifecycle: this.#routeLifecycle,\n plugins: this.#plugins,\n navigation: this.#navigation,\n lifecycle: this.#lifecycle,\n eventBus: this.#eventBus,\n });\n\n // =========================================================================\n // Bind Public Methods\n // =========================================================================\n // All public methods that access private fields must be bound to preserve\n // `this` context when methods are extracted as references.\n // See: https://github.com/tc39/proposal-bind-operator\n // =========================================================================\n\n // Path & State Building\n this.isActiveRoute = this.isActiveRoute.bind(this);\n this.buildPath = this.buildPath.bind(this);\n\n // State Management\n this.getState = this.getState.bind(this);\n this.getPreviousState = this.getPreviousState.bind(this);\n this.areStatesEqual = this.areStatesEqual.bind(this);\n this.shouldUpdateNode = this.shouldUpdateNode.bind(this);\n\n // Router Lifecycle\n this.isActive = this.isActive.bind(this);\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n this.dispose = this.dispose.bind(this);\n\n // Route Lifecycle (Guards)\n this.canNavigateTo = this.canNavigateTo.bind(this);\n\n // Plugins\n this.usePlugin = this.usePlugin.bind(this);\n\n // Navigation\n this.navigate = this.navigate.bind(this);\n this.navigateToDefault = this.navigateToDefault.bind(this);\n this.navigateToNotFound = this.navigateToNotFound.bind(this);\n\n // Subscription\n this.subscribe = this.subscribe.bind(this);\n this.subscribeLeave = this.subscribeLeave.bind(this);\n this.isLeaveApproved = this.isLeaveApproved.bind(this);\n\n // =========================================================================\n // Flush initial-route guard factories\n // =========================================================================\n // Deferred out of wiring (#1331): the pending canActivate/canDeactivate\n // factories from initial route definitions are compiled and executed HERE,\n // on the fully-built and bound router — a factory calling read-only methods\n // (`buildPath()`, `isActiveRoute()`, `getState()`) no longer hits a\n // half-assembled instance. Side-effectful calls (`navigate`, `usePlugin`,\n // route-CRUD) stay OUT OF CONTRACT: factories re-execute outside the\n // constructor (cloneRouter re-compiles definition guards per clone;\n // #recompileSlot re-runs a factory after a definition-only clear), so any\n // side effect would duplicate per re-execution — see CLAUDE.md. Runtime\n // add()/replace() compile guards in their own PREPARE phase and never touch\n // these pending maps.\n //\n // Fail-closed on a factory throw: by this point a router reference leaked\n // from an earlier factory is fully operational, while later guards would\n // stay silently unregistered — a fail-open guard bypass. Disposing before\n // the rethrow turns any leaked reference into a ROUTER_DISPOSED-throwing\n // husk (pre-#1331 such a reference was inert because getInternals threw).\n try {\n this.#routes.flushPendingGuards();\n } catch (error) {\n this.dispose();\n\n throw error;\n }\n }\n\n // ============================================================================\n // Path & State Building\n // ============================================================================\n\n isActiveRoute(\n name: string,\n params?: Params,\n strictEquality?: boolean,\n ignoreQueryParams?: boolean,\n ): boolean {\n getInternals(this).validator?.routes.validateIsActiveRouteArgs(\n name,\n params,\n strictEquality,\n ignoreQueryParams,\n );\n\n getInternals(this).validator?.routes.validateRouteName(\n name,\n \"isActiveRoute\",\n );\n\n // Empty string is special case - warn and return false (root node is not a parent)\n if (name === \"\") {\n getInternals(this).logger.warn(\n \"real-router\",\n 'isActiveRoute(\"\") called with empty string. Root node is not considered a parent of any route.',\n );\n\n return false;\n }\n\n return this.#routes.isActiveRoute(\n name,\n params,\n strictEquality,\n ignoreQueryParams,\n );\n }\n\n buildPath(route: string, params?: Params): string {\n const ctx = getInternals(this);\n\n ctx.validator?.routes.validateBuildPathArgs(route);\n ctx.validator?.navigation.validateParams(params, \"buildPath\");\n\n return ctx.buildPath(route, normalizeParams(params));\n }\n\n // ============================================================================\n // State Management (delegated to StateNamespace)\n // ============================================================================\n\n getState<P extends Params = Params>(): State<P> | undefined {\n return this.#state.get<P>();\n }\n\n getPreviousState(): State | undefined {\n return this.#state.getPrevious();\n }\n\n areStatesEqual(\n state1: State | undefined,\n state2: State | undefined,\n ignoreQueryParams = true,\n ): boolean {\n getInternals(this).validator?.state.validateAreStatesEqualArgs(\n state1,\n state2,\n ignoreQueryParams,\n );\n\n return this.#state.areStatesEqual(state1, state2, ignoreQueryParams);\n }\n\n shouldUpdateNode(\n nodeName: string,\n ): (toState: State, fromState?: State) => boolean {\n getInternals(this).validator?.routes.validateShouldUpdateNodeArgs(nodeName);\n\n return RoutesNamespace.shouldUpdateNode(nodeName);\n }\n\n // ============================================================================\n // Router Lifecycle\n // ============================================================================\n\n isActive(): boolean {\n return this.#eventBus.isActive();\n }\n\n start(startPath: string): Promise<State> {\n if (!this.#eventBus.canStart()) {\n return Promise.reject(CACHED_ALREADY_STARTED_ERROR);\n }\n\n getInternals(this).validator?.navigation.validateStartArgs(startPath);\n\n // FSM bookkeeping is split across the facade and RouterLifecycleNamespace by\n // design, NOT a missed consolidation (#940): `sendStart()` runs HERE, before\n // the interceptor chain, so the STARTING window spans the whole start\n // pipeline. A pre-`next()` interceptor throw then unwinds via STARTING →\n // `sendFail`, which emits TRANSITION_ERROR from STARTING (EventBusNamespace\n // FAIL action) for `onTransitionError` plugins. Moving `sendStart()` into the\n // namespace (the interceptor *target*) would skip STARTING on a pre-`next()`\n // throw — the namespace is never reached — silently dropping that\n // TRANSITION_ERROR: a #668 regression. The commit (`completeStart`) lives in\n // the namespace; recovery needs facade state (`#state`, `#lifecycle`), so it\n // stays here in `#unwindFailedStart`.\n this.#eventBus.sendStart();\n\n // Convert sync interceptor throws to rejections so the recovery path is\n // reachable; otherwise the throw escapes synchronously, the FSM is left in\n // STARTING, and the router is permanently bricked (#668).\n let internalStart: Promise<State>;\n\n try {\n const chainResult: unknown = getInternals(this).start(startPath);\n\n // A `start` interceptor that returns without calling next() yields a\n // non-thenable (typically undefined); the `.catch` below would then throw\n // a cryptic `TypeError: ...reading 'catch'` and leave the FSM stuck in\n // STARTING. Reject with an actionable message so recovery unwinds via\n // #unwindFailedStart — the same deferred-crash class as the #939\n // start-path guard (#1411).\n internalStart =\n typeof (chainResult as { then?: unknown } | null | undefined)?.then ===\n \"function\"\n ? (chainResult as Promise<State>)\n : Promise.reject(\n new TypeError(\n \"[router.start] a `start` interceptor returned without calling next(). Every start interceptor must return `next(path)`.\",\n ),\n );\n } catch (syncError: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided start interceptor\n internalStart = Promise.reject(syncError);\n }\n\n const promiseState = internalStart.catch((error: unknown) =>\n this.#unwindFailedStart(error),\n );\n\n this.#suppressUnhandledRejection(\n promiseState,\n this.#onSuppressedStartError,\n );\n\n return promiseState;\n }\n\n stop(): this {\n // SendCancelIfPossible → FSM CANCEL → the CANCEL action\n // aborts the in-flight controller (waking the pipeline). No separate abort.\n this.#eventBus.sendCancelIfPossible(this.#state.get());\n\n // `isStarting()` is included (#1185): a stop() while `start()` is parked in\n // an async start-interceptor (FSM STARTING, before `next()`) must cancel the\n // start, not silently no-op. `sendStop()` takes STARTING → IDLE (FSM table),\n // and `RouterLifecycleNamespace.start` re-checks `isIdle()` after the\n // interceptor chain and rejects with TRANSITION_CANCELLED — mirroring the\n // guard-phase behavior (which already cancels from TRANSITION_STARTED).\n if (\n !this.#eventBus.isReady() &&\n !this.#eventBus.isTransitioning() &&\n !this.#eventBus.isStarting()\n ) {\n return this;\n }\n\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n\n return this;\n }\n\n dispose(): void {\n // Stryker disable next-line BlockStatement: equivalent — emptying the early-return re-runs the dispose body on a 2nd call, but it is fully idempotent (FSM `send(DISPOSE)` no-ops from DISPOSED, `disposeAll()` already cleared `#unsubscribes`, every clear is idempotent). (ConditionalExpression stays live: `→true` always-returns and never disposes = killed.)\n if (this.#eventBus.isDisposed()) {\n return;\n }\n\n // the FSM CANCEL action aborts the in-flight controller.\n this.#eventBus.sendCancelIfPossible(this.#state.get());\n\n if (this.#eventBus.isReady() || this.#eventBus.isTransitioning()) {\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n }\n\n this.#eventBus.sendDispose();\n this.#eventBus.clearAll();\n\n this.#plugins.disposeAll();\n\n // Safety net: clean up extensions plugins failed to remove in teardown\n const ctx = getInternals(this);\n\n for (const extension of ctx.routerExtensions) {\n for (const key of extension.keys) {\n delete (this as Record<string, unknown>)[key];\n }\n }\n\n ctx.routerExtensions.length = 0;\n\n // Safety net: release context namespace claims plugins failed to release in teardown\n ctx.contextClaimRecords.clear();\n\n // Safety net: drop interceptors plugins failed to remove in teardown (#1199).\n // The third per-plugin registration channel — symmetric with routerExtensions\n // / contextClaimRecords above. `buildPath` is not method-swapped by dispose\n // and reads this Map live, so a leaked interceptor would otherwise still run\n // on the disposed router.\n ctx.interceptors.clear();\n\n this.#routes.clearRoutes();\n this.#routeLifecycle.clearAll();\n this.#state.reset();\n this.#dependenciesStore.dependencies = Object.create(\n null,\n ) as Partial<Dependencies>;\n\n this.#markDisposed();\n }\n\n // ============================================================================\n // Route Lifecycle (Guards)\n // ============================================================================\n\n canNavigateTo(name: string, params?: Params): boolean {\n const ctx = getInternals(this);\n\n ctx.validator?.routes.validateRouteName(name, \"canNavigateTo\");\n ctx.validator?.navigation.validateParams(params, \"canNavigateTo\");\n\n if (!this.#routes.hasRoute(name)) {\n return false;\n }\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params ?? {},\n );\n\n // Build `toState` exactly as `buildNavigateState` does — WITH route-meta and\n // normalized params — so `getTransitionPath` takes its STANDARD PATH and\n // trims the shared ancestor, mirroring navigate's guard set (#970). A\n // meta-less `toState` makes both sides meta-less (the committed `getState()`\n // carries no meta after a path-matched `start()`), so `getTransitionPath`\n // takes FAST PATH 3 and (de)activates the WHOLE chain incl. shared ancestors\n // → false-negative (\"Link disabled though the click would succeed\").\n // `normalizeParams` also aligns the params guards observe with navigate's.\n // `skipFreeze` (5th arg) mirrors the navigate guard phase, where guards see\n // an unfrozen, transition-less `toState` (freeze happens later in\n // `completeTransition`).\n //\n // A capability predicate must answer, not throw: if the target path can't be\n // built from these params (e.g. a required path param is missing), the route\n // is simply unreachable with this input — return `false` rather than letting\n // `buildPath` throw (#725).\n let toState: State;\n\n try {\n const normalizedParams = normalizeParams(resolvedParams);\n const meta = this.#routes.getMetaForState(resolvedName);\n const path = ctx.buildPath(resolvedName, normalizedParams);\n\n toState = this.#state.makeState(\n resolvedName,\n normalizedParams,\n path,\n meta,\n true,\n );\n } catch {\n return false;\n }\n\n const fromState = this.#state.get();\n\n const { toDeactivate, toActivate } = getTransitionPath(toState, fromState);\n\n return this.#routeLifecycle.canNavigateTo(\n toDeactivate,\n toActivate,\n toState,\n fromState,\n );\n }\n\n // ============================================================================\n // Plugins\n // ============================================================================\n\n usePlugin(\n ...plugins: (PluginFactory<Dependencies> | false | null | undefined)[]\n ): Unsubscribe {\n // Post-dispose guard, mirroring #946 for subscribe/subscribeLeave. A\n // reference captured before dispose() (`const up = router.usePlugin`)\n // bypasses the #markDisposed method swap, so the swap alone is not enough:\n // without this, the factory would run on a disposed router (real side\n // effects), listeners would land in the cleared emitter, and teardown would\n // never fire — a silent zombie plugin (#1196).\n if (this.#eventBus.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n const filtered = plugins.filter(Boolean) as PluginFactory<Dependencies>[];\n\n if (filtered.length === 0) {\n return () => {};\n }\n\n const ctx = getInternals(this);\n\n ctx.validator?.plugins.validatePluginLimit(\n this.#plugins.count(),\n this.#limits,\n );\n for (const plugin of filtered) {\n // `getAll()` sits inside the optional-chain argument on purpose: with no\n // validator installed (production default) the `?.` short-circuits and the\n // array is never allocated. Hoisting it out would either allocate on the\n // no-validator hot path or push the dev-only branch out of coverage.\n ctx.validator?.plugins.validateNoDuplicatePlugins(\n plugin,\n this.#plugins.getAll(),\n );\n }\n\n return this.#plugins.use(...filtered);\n }\n\n // ============================================================================\n // Subscription (backed by EventEmitter)\n // ============================================================================\n\n subscribe(listener: SubscribeFn): Unsubscribe {\n EventBusNamespace.validateSubscribeListener(listener);\n\n return this.#eventBus.subscribe(listener);\n }\n\n subscribeLeave(listener: LeaveFn): Unsubscribe {\n EventBusNamespace.validateSubscribeLeaveListener(listener);\n\n return this.#eventBus.subscribeLeave(listener);\n }\n\n isLeaveApproved(): boolean {\n return this.#eventBus.isLeaveApproved();\n }\n\n // ============================================================================\n // Navigation\n // ============================================================================\n\n navigate(\n routeName: string,\n routeParams?: Params,\n options?: NavigationOptions,\n ): Promise<State> {\n this.#assertNotReentrant();\n\n const ctx = getInternals(this);\n\n ctx.validator?.navigation.validateNavigateArgs(routeName);\n ctx.validator?.navigation.validateParams(routeParams, \"navigate\");\n\n const opts = options ?? EMPTY_OPTS;\n\n ctx.validator?.navigation.validateNavigationOptions(opts, \"navigate\");\n\n const promiseState = this.#navigation.navigate(\n routeName,\n routeParams ?? EMPTY_PARAMS,\n opts,\n );\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n // Cached rejection — already pre-suppressed at module load, skip .catch()\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n }\n\n navigateToDefault(options?: NavigationOptions): Promise<State> {\n this.#assertNotReentrant();\n\n const ctx = getInternals(this);\n\n ctx.validator?.navigation.validateNavigateToDefaultArgs(options);\n\n const opts = options ?? EMPTY_OPTS;\n\n ctx.validator?.navigation.validateNavigationOptions(\n opts,\n \"navigateToDefault\",\n );\n\n const promiseState = this.#navigation.navigateToDefault(opts);\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n }\n\n navigateToNotFound(path?: string): State {\n this.#assertNotReentrant();\n\n if (!this.#eventBus.isActive()) {\n throw new RouterError(errorCodes.ROUTER_NOT_STARTED);\n }\n\n if (path !== undefined && typeof path !== \"string\") {\n throw new TypeError(\n `[router.navigateToNotFound] path must be a string, got ${typeof path}`,\n );\n }\n\n if (path !== undefined) {\n return this.#navigation.navigateToNotFound(path);\n }\n\n // #1172: a path-less call derives the default path from the committed state.\n // During the two-phase start window the router is active (`isActive()` true)\n // while `getState()` is still undefined, so throw an actionable RouterError\n // instead of a cryptic `TypeError` from dereferencing the absent state —\n // same class as the #939 always-on invariant guards.\n const current = this.#state.get();\n\n if (current === undefined) {\n throw new RouterError(errorCodes.ROUTER_NOT_STARTED, {\n message:\n \"[router.navigateToNotFound] cannot derive the path before the start navigation commits — pass an explicit path\",\n });\n }\n\n return this.#navigation.navigateToNotFound(current.path);\n }\n\n /**\n * Classifies a fire-and-forget rejection as an EXPECTED outcome that must\n * stay silent (no log). Shared by the navigate and start suppressors so the\n * suppression contract lives in one place.\n *\n * A suppressed RouterError code is a normal caller-owned navigation result\n * (a guard block, SAME_STATES, ROUTER_NOT_STARTED, …) — see\n * SUPPRESSED_ERROR_CODES (#721).\n *\n * The #945 RecursionDepthError carve-out is gone: a reentrant navigate() from a\n * listener can no longer self-feed — it throws REENTRANT_NAVIGATION\n * synchronously at the facade (RFC navigation-cancellation-unification §4), so\n * navigate()'s promise never rejects with a recursion error (re-entrant emits\n * are coalesced at the emitter, #1033; reentrant route-CRUD throws\n * REENTRANT_TREE_MUTATION to the CRUD caller, #1032 — not through a navigate\n * promise).\n */\n static #isExpectedRejection(error: unknown): boolean {\n return (\n error instanceof RouterError && SUPPRESSED_ERROR_CODES.has(error.code)\n );\n }\n\n /**\n * Fire-and-forget safety: prevents unhandled rejection warnings when\n * navigate/navigateToDefault/start is called without await. Expected errors\n * are silently suppressed; unexpected ones are logged under `onSuppressed`'s\n * category — navigate by default; start() passes #onSuppressedStartError so\n * its failures are logged as \"router.start\", not \"router.navigate\" (#931).\n */\n #suppressUnhandledRejection(\n promise: Promise<State>,\n onSuppressed: (error: unknown) => void = this.#onSuppressedNavigateError,\n ): void {\n promise.catch(onSuppressed);\n }\n\n /**\n * Rejects a synchronous reentrant navigation — `navigate` /\n * `navigateToDefault` / `navigateToState` / `navigateToNotFound` called from\n * inside a transition-event listener while a transition is being dispatched\n * (RFC navigation-cancellation-unification §4). Throws synchronously: inside a\n * listener the emit's `onListenerError` isolation surfaces it (visible,\n * non-fatal); a DEFERRED (async / microtask) navigate from a listener runs\n * after dispatch settles and is allowed. Always-on core invariant guard (not\n * validator-gated).\n */\n #assertNotReentrant(): void {\n if (this.#eventBus.isProcessing()) {\n throw new RouterError(errorCodes.REENTRANT_NAVIGATION);\n }\n }\n\n /**\n * Settles the FSM after a failed start pipeline, then re-throws so the\n * rejection still surfaces to the caller. Three cases, by what the pipeline\n * reached before throwing:\n *\n * - **Pre-commit, READY** (`isReady()` and no committed state): an interceptor\n * threw after `completeStart()` reached READY but before any state committed\n * (e.g. an activation guard blocked the start navigation) — return READY →\n * IDLE via `stop()` so the router is reusable.\n * - **Pre-commit, STARTING** (`isStarting()`): the pipeline threw before\n * `completeStart()` — a sync interceptor throw before `next()`, or a throw\n * inside the namespace before commit — so unwind STARTING → IDLE via\n * `sendFail`, which also emits TRANSITION_ERROR from STARTING (#668).\n * - **Post-commit, READY with committed state** (neither branch fires): a\n * loader/interceptor threw AFTER `navigateToState` committed and emitted\n * TRANSITION_SUCCESS (the SSR/RSC loader window). Keep the committed state —\n * rolling back would retract an observed success (\"phantom success\", #763);\n * the error still surfaces via the re-throw.\n */\n #unwindFailedStart(error: unknown): never {\n if (this.#eventBus.isReady() && this.#state.get() === undefined) {\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n } else if (this.#eventBus.isStarting()) {\n this.#eventBus.sendFail(undefined, undefined, error);\n }\n\n throw error;\n }\n\n #markDisposed(): void {\n this.navigate = throwDisposed;\n this.navigateToDefault = throwDisposed;\n this.navigateToNotFound = throwDisposed;\n this.start = throwDisposed;\n this.stop = throwDisposed;\n this.usePlugin = throwDisposed;\n\n this.subscribe = throwDisposed;\n this.subscribeLeave = throwDisposed;\n this.canNavigateTo = throwDisposed;\n }\n}\n\nfunction throwDisposed(): never {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n}\n\n/**\n * Derives CreateMatcherOptions from router Options.\n * Maps core option names to matcher option names.\n */\nfunction deriveMatcherOptions(\n options: Readonly<Options>,\n): CreateMatcherOptions {\n return {\n strictTrailingSlash: options.trailingSlash === \"strict\",\n caseSensitive: options.caseSensitive,\n strictQueryParams: options.queryParamsMode === \"strict\",\n urlParamsEncoding: options.urlParamsEncoding,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n queryParams: options.queryParams!,\n };\n}\n"],"mappings":"g/BA0DM,EAA0C,OAAO,OAAO,CAAC,CAAC,EAS1D,EAA8C,IAAI,IAAI,CAC1DA,EAAAA,WAAW,YACXA,EAAAA,WAAW,qBACXA,EAAAA,WAAW,mBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,iBACb,CAAC,EAkBD,I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W,oBAAoB,CAEzD,CAqBA,GAAmB,EAAuB,CAQxC,MAPI,KAAKU,GAAU,QAAQ,GAAK,KAAKN,GAAO,IAAI,IAAM,IAAA,IACpD,KAAKK,GAAW,KAAK,EACrB,KAAKC,GAAU,SAAS,GACf,KAAKA,GAAU,WAAW,GACnC,KAAKA,GAAU,SAAS,IAAA,GAAW,IAAA,GAAW,CAAK,EAG/C,CACR,CAEA,IAAsB,CACpB,KAAK,SAAW,EAChB,KAAK,kBAAoB,EACzB,KAAK,mBAAqB,EAC1B,KAAK,MAAQ,EACb,KAAK,KAAO,EACZ,KAAK,UAAY,EAEjB,KAAK,UAAY,EACjB,KAAK,eAAiB,EACtB,KAAK,cAAgB,CACvB,CACF,EAEA,SAAS,GAAuB,CAC9B,MAAM,IAAI4B,EAAAA,YAAYtC,EAAAA,WAAW,eAAe,CAClD,CAMA,SAAS,EACP,EACsB,CACtB,MAAO,CACL,oBAAqB,EAAQ,gBAAkB,SAC/C,cAAe,EAAQ,cACvB,kBAAmB,EAAQ,kBAAoB,SAC/C,kBAAmB,EAAQ,kBAE3B,YAAa,EAAQ,WACvB,CACF"}
|
|
1
|
+
{"version":3,"file":"Router.js","names":["errorCodes","#options","#limits","#dependenciesStore","#state","#routes","#routeLifecycle","#plugins","#navigation","#lifecycle","#eventBus","#onSuppressedNavigateError","#onSuppressedStartError","RouterLogger","#isExpectedRejection","OptionsNamespace","createLimits","createDependenciesStore","StateNamespace","RoutesNamespace","RouteLifecycleNamespace","PluginsNamespace","NavigationNamespace","RouterLifecycleNamespace","createRouterFSM","EventEmitter","EventBusNamespace","createTernaryInterceptable","EMPTY_PARAMS","createInterceptable","#assertNotReentrant","#suppressUnhandledRejection","getInternals","normalizeParams","CACHED_ALREADY_STARTED_ERROR","#unwindFailedStart","#markDisposed","findMisChanneledKey","canonicalize","materialize","buildURL","getTransitionPath","RouterError"],"sources":["../../src/Router.ts"],"sourcesContent":["// packages/core/src/Router.ts\n\n/**\n * Router class - facade with integrated namespaces.\n *\n * All functionality is now provided by namespace classes.\n */\n\nimport { assertChannelCorrect, findMisChanneledKey } from \"./channels\";\nimport { EMPTY_PARAMS, errorCodes } from \"./constants\";\nimport {\n assertLoggerConfig,\n guardDependencies,\n guardRouteStructure,\n} from \"./guards\";\nimport { normalizeParams } from \"./helpers\";\nimport {\n createInterceptable,\n createTernaryInterceptable,\n getInternals,\n registerInternals,\n throwOnMisChanneledKey,\n} from \"./internals\";\nimport { createLimits } from \"./limits\";\nimport {\n EventBusNamespace,\n NavigationNamespace,\n OptionsNamespace,\n PluginsNamespace,\n RouteLifecycleNamespace,\n RouterLifecycleNamespace,\n RoutesNamespace,\n StateNamespace,\n createDependenciesStore,\n} from \"./namespaces\";\nimport { CACHED_ALREADY_STARTED_ERROR } from \"./namespaces/RouterLifecycleNamespace/constants\";\nimport { buildURL, canonicalize, materialize } from \"./pipeline\";\nimport { RouterError } from \"./RouterError\";\nimport { createRouterFSM } from \"./routerFSM\";\nimport { getTransitionPath } from \"./transitionPath\";\nimport { EventEmitter } from \"./utils/event-emitter\";\nimport { RouterLogger } from \"./utils/logger\";\nimport { wireNamespaces } from \"./wiring\";\n\nimport type { CreateMatcherOptions } from \"./engine\";\nimport type { RouterInternals } from \"./internals\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type {\n DefaultDependencies,\n LeaveFn,\n NavigationOptions,\n NavigationTarget,\n Options,\n Params,\n Router as RouterInterface,\n SearchParams,\n State,\n SubscribeFn,\n Unsubscribe,\n PluginFactory,\n Route,\n} from \"./types\";\nimport type { Limits, RouterEventMap } from \"./types/internal\";\n\nconst EMPTY_OPTS: Readonly<NavigationOptions> = Object.freeze({});\n\n// Module-level so #isExpectedRejection allocates nothing per navigate()/start() call.\n// These are expected navigation outcomes owned by the caller, not internal\n// bugs — the safety net stays silent for them and lets awaiting callers see\n// the rejection. CANNOT_ACTIVATE / CANNOT_DEACTIVATE belong here: a guard\n// blocking (or a plugin's guard-blocked back()/forward()) is a normal result,\n// so a fire-and-forget call must not emit a spurious \"Unexpected navigation\n// error\" (#721).\nconst SUPPRESSED_ERROR_CODES: ReadonlySet<string> = new Set([\n errorCodes.SAME_STATES,\n errorCodes.TRANSITION_CANCELLED,\n errorCodes.ROUTER_NOT_STARTED,\n errorCodes.ROUTE_NOT_FOUND,\n errorCodes.CANNOT_ACTIVATE,\n errorCodes.CANNOT_DEACTIVATE,\n]);\n\n/**\n * Router class with integrated namespace architecture.\n *\n * All functionality is provided by namespace classes:\n * - OptionsNamespace: getOptions (immutable)\n * - DependenciesStore: get/set/remove dependencies\n * - EventEmitter: subscribe\n * - StateNamespace: state storage (getState, setState, getPreviousState)\n * - RoutesNamespace: route tree operations\n * - RouteLifecycleNamespace: canActivate/canDeactivate guards\n * - PluginsNamespace: plugin lifecycle\n * - NavigationNamespace: navigate\n * - RouterLifecycleNamespace: start, stop, isStarted\n *\n * @internal This class implementation is internal. Use createRouter() instead.\n */\nexport class Router<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> implements RouterInterface<Dependencies> {\n [key: string]: unknown;\n\n // ============================================================================\n // Namespaces\n // ============================================================================\n\n readonly #options: OptionsNamespace<Dependencies>;\n readonly #limits: Limits;\n readonly #dependenciesStore: DependenciesStore<Dependencies>;\n readonly #state: StateNamespace;\n readonly #routes: RoutesNamespace<Dependencies>;\n readonly #routeLifecycle: RouteLifecycleNamespace<Dependencies>;\n readonly #plugins: PluginsNamespace<Dependencies>;\n readonly #navigation: NavigationNamespace;\n readonly #lifecycle: RouterLifecycleNamespace;\n\n readonly #eventBus: EventBusNamespace;\n\n /**\n * Per-instance suppressors for fire-and-forget navigate / start. They log\n * through THIS router's logger (built in the constructor) — so, unlike the\n * former static \"one allocation per class\" closures, they are two closures per\n * instance. Trade accepted with the per-router logger (#724): the logger is\n * per-instance, so its suppressors must be too. The #931 category split is\n * preserved — navigate failures log under \"router.navigate\", start failures\n * under \"router.start\" (a start interceptor throwing a plain Error after\n * next() committed, #763, or a cryptic path TypeError — neither a suppressed\n * RouterError). The log line IS reachable: a subscribeLeave listener that\n * throws rejects navigate() with the original NON-suppressed error, and a\n * Symbol path-param's stringify TypeError is likewise non-suppressed.\n */\n readonly #onSuppressedNavigateError: (error: unknown) => void;\n readonly #onSuppressedStartError: (error: unknown) => void;\n\n // ============================================================================\n // Constructor\n // ============================================================================\n\n /**\n * @param routes - Route definitions\n * @param options - Router options\n * @param dependencies - DI dependencies\n */\n constructor(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options<Dependencies>> = {},\n dependencies: Dependencies = {} as Dependencies,\n ) {\n // Extract the logger config WITHOUT mutating the caller's `options` object\n // (#724). `routerOptions` is the logger-stripped view handed to the options\n // pipeline so `logger` never lands in the frozen router options.\n const { logger: loggerConfig, ...routerOptions } = options;\n\n if (loggerConfig) {\n assertLoggerConfig(loggerConfig);\n }\n\n // Per-router logger instance — replaces the former process-global singleton\n // whose configure() leaked across every router in the process, last\n // createRouter winning (#724). Stored on ctx (registerInternals below), so\n // the facade reads getInternals(this).logger; namespaces receive it via\n // their deps at wiring; plugins reach it through getPluginApi(router).logger.\n const logger = new RouterLogger(loggerConfig);\n\n // Per-instance fire-and-forget suppressors (see field declarations): they\n // log through THIS router's logger, so they are built here, not static.\n this.#onSuppressedNavigateError = (error: unknown): void => {\n if (Router.#isExpectedRejection(error)) {\n return;\n }\n\n logger.error(\"router.navigate\", \"Unexpected navigation error\", error);\n };\n this.#onSuppressedStartError = (error: unknown): void => {\n if (Router.#isExpectedRejection(error)) {\n return;\n }\n\n logger.error(\"router.start\", \"Unexpected start error\", error);\n };\n\n // =========================================================================\n // Validate inputs before creating namespaces\n // =========================================================================\n\n // Always validate the caller's options (catches non-object / array inputs)\n OptionsNamespace.validateOptionsIsObject(options);\n\n // Unconditional guard-level validation before creating namespaces\n guardDependencies(dependencies);\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `guardRouteStructure([])` on an empty array is a no-op, so validating an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips validation of a real route list and is killable.)\n if (routes.length > 0) {\n guardRouteStructure(routes);\n }\n\n // =========================================================================\n // Create Namespaces\n // =========================================================================\n\n this.#options = new OptionsNamespace(routerOptions);\n this.#limits = createLimits(routerOptions.limits);\n this.#dependenciesStore =\n createDependenciesStore<Dependencies>(dependencies);\n this.#state = new StateNamespace();\n this.#routes = new RoutesNamespace<Dependencies>(\n routes,\n deriveMatcherOptions(this.#options.get()),\n logger,\n );\n this.#routeLifecycle = new RouteLifecycleNamespace<Dependencies>();\n this.#plugins = new PluginsNamespace<Dependencies>();\n this.#navigation = new NavigationNamespace();\n this.#lifecycle = new RouterLifecycleNamespace();\n\n // =========================================================================\n // Initialize EventBus\n // =========================================================================\n\n const routerFSM = createRouterFSM();\n\n const emitter = new EventEmitter<RouterEventMap>({\n // Shared per-listener error sink: EventEmitter reports synchronous listener\n // throws here, and EventBusNamespace.subscribe routes an async listener's\n // rejected Promise through the SAME sink (#944) — both land in one place.\n onListenerError: (eventName, error) => {\n logger.error(\"Router\", `Error in listener for ${eventName}:`, error);\n },\n onListenerWarn: (eventName, count) => {\n logger.warn(\n \"router.addEventListener\",\n `Event \"${eventName}\" has ${count} listeners — possible memory leak`,\n );\n },\n });\n\n this.#eventBus = new EventBusNamespace({\n routerFSM,\n emitter,\n // The FSM CANCEL action aborts the in-flight\n // navigation controller via this injected effect — \"FSM CANCEL ⟹\n // controller aborted\" in one place. `#navigation` is constructed above.\n abortController: (reason) => {\n this.#navigation.abortCurrentController(reason);\n },\n });\n\n // =========================================================================\n // Register Internals (WeakMap for plugin/infrastructure access)\n // =========================================================================\n // Registered BEFORE wiring (#1331) so every namespace's deps-closure sees a\n // router already present in the internals registry — `getInternals(router)`\n // never throws during wiring, and guard factories flushed at the end of the\n // constructor see a fully-registered instance.\n\n const interceptorsMap: RouterInternals[\"interceptors\"] = new Map();\n\n // THE single forwardState boundary (#1548/#1549). The interceptable resolves\n // the route (forwardTo) and runs the whole interceptor chain — a plugin\n // injecting params, a search-schema validation, etc. The outer layer then\n // CHECKS the channels once, keyed on the RESOLVED route's `?`-declaration.\n //\n // It used to REPAIR them instead (`separateChannels`, stage ②): a declared\n // query key left in the params bag was moved into the query channel behind\n // the producer's back. Three things were wrong with that. The producer kept\n // believing the bag it wrote was the one that shipped. A plugin could\n // inject past a validation that had already run — search-schema documented\n // exactly that leak, with a test named LEAKS. And the caller's own\n // mis-channelled key and a chain default's query half landed in DIFFERENT\n // channels, where no merge ranks them, so the default silently won (#1570).\n // Refusing is the whole fix: whoever names the route knows its declaration.\n //\n // `as unknown as` is required: the closure is non-generic, but\n // RouterInternals[\"forwardState\"] is declared generic `<P, S>`, which tsc\n // will not infer from a non-generic source (Sonar S4325 misclassifies this\n // as a redundant cast).\n const rawForwardState = createTernaryInterceptable(\n \"forwardState\",\n (name: string, params: Params, search?: SearchParams) =>\n this.#routes.forwardState(name, params, search),\n interceptorsMap,\n );\n\n const forwardState = ((\n name: string,\n params: Params,\n search?: SearchParams,\n ) => {\n const forwarded = rawForwardState(name, params, search);\n\n // The DECLARATION that matters is the RESOLVED route's — it owns the URL\n // that gets printed. When a chain resolved to a different route, say so:\n // a caller who wrote `navigate(\"src\", { lang })` looked at `src`'s config,\n // where `lang` is undeclared and legitimate, and needs to be told that the\n // hop landed somewhere that spells it `?lang`. Naming only the target\n // would read as a message about a route they never mentioned.\n assertChannelCorrect(\n \"forwardState\",\n forwarded.name,\n forwarded.params,\n this.#routes.getQueryParams(forwarded.name),\n () =>\n forwarded.name === name\n ? \"the `params` bag leaving the forwardState chain\"\n : `the \\`params\\` bag leaving the forwardState chain (forwarded here from \"${name}\")`,\n );\n\n return {\n name: forwarded.name,\n // The type says `params: P`, and across THIS boundary the type is a\n // contract, not a guarantee: `rawForwardState` is an interceptable, so\n // the value has passed through user code that can spread a partial\n // result. The net used to be reached by stage ②'s split (an all-query\n // bag left the path half undefined) and is now reached only by that\n // contract violation — still worth surviving rather than putting\n // `undefined` into `state.params`. Pinned by \"normalises a params bag an\n // interceptor dropped to `undefined`\" in forwardState.test.ts, which\n // fails if this is removed.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- see above: the declared type cannot model an interceptor's runtime return\n params: forwarded.params ?? EMPTY_PARAMS,\n search: forwarded.search,\n };\n }) as unknown as RouterInternals[\"forwardState\"];\n\n registerInternals(this, {\n logger,\n makeState: (name, params, search, path) =>\n this.#state.makeState(name, params, search, path),\n getMetaForState: (name) => this.#routes.getMetaForState(name),\n getQueryParams: (name) => this.#routes.getQueryParams(name),\n forwardState,\n buildStateResolved: (name, params) =>\n this.#routes.buildStateResolved(name, params),\n port: () => this.#routes.getPort(),\n matchPath: (path, matchOptions) =>\n this.#routes.matchPath(path, matchOptions),\n getOptions: () => this.#options.get(),\n addEventListener: (eventName, cb) =>\n this.#eventBus.addEventListener(eventName, cb),\n treeChanged: {\n emit: (event) => {\n this.#eventBus.emitTreeChanged(event);\n },\n subscribe: (handler) => this.#eventBus.subscribeTreeChanged(handler),\n listenerCount: () => this.#eventBus.treeChangedListenerCount(),\n isEmitting: () => this.#eventBus.isEmittingTreeChanged(),\n },\n buildPath: createTernaryInterceptable(\n \"buildPath\",\n (route: string, params?: Params, search?: SearchParams) =>\n this.#routes.buildPath(\n route,\n params ?? EMPTY_PARAMS,\n search,\n this.#options.get(),\n ),\n interceptorsMap,\n ),\n emitTransitionError: (error) => {\n this.#eventBus.sendFailSafe(undefined, this.#state.get(), error);\n },\n emitTransitionSuccess: (toState, fromState, opts) => {\n this.#eventBus.emitTransitionSuccess(toState, fromState, opts);\n },\n navigateToNotFound: (path) => this.#navigation.navigateToNotFound(path),\n start: createInterceptable(\n \"start\",\n (path: string) => {\n return this.#lifecycle.start(path);\n },\n interceptorsMap,\n ),\n navigateToState: (state, navOpts) => {\n // Plugin-only navigation primitive (#525). Mirrors the same\n // unhandled-rejection suppression and lastSync* bookkeeping used by\n // the public Router.navigate facade so plugin call-sites can\n // fire-and-forget the returned promise (popstate handlers do).\n this.#assertNotReentrant();\n\n const promiseState = this.#navigation.navigateToState(\n state,\n navOpts ?? EMPTY_OPTS,\n );\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n },\n interceptors: interceptorsMap,\n setRootPath: (rootPath) => {\n this.#routes.setRootPath(rootPath);\n },\n getRootPath: () => this.#routes.getStore().rootPath,\n getTree: () => this.#routes.getStore().tree,\n isDisposed: () => this.#eventBus.isDisposed(),\n validator: null,\n // Dependencies (issue #172)\n dependenciesGetStore: () => this.#dependenciesStore,\n // Clone support (issue #173)\n getCloneState: () => ({\n options: { ...this.#options.get() },\n dependencies: { ...this.#dependenciesStore.dependencies },\n pluginFactories: this.#plugins.getAll(),\n // `logger` is a const in this constructor's scope (a RouterLogger class\n // instance), so getConfig() yields the resolved config a clone inherits\n // — frozen options don't carry `logger`, so cloneRouter reads it here.\n loggerConfig: logger.getConfig(),\n }),\n routeGetStore: () => this.#routes.getStore(),\n // Cross-namespace state (issue #174)\n getStateName: () => this.#state.get()?.name,\n isTransitioning: () => this.#eventBus.isTransitioning(),\n clearState: () => {\n this.#state.set(undefined);\n },\n setState: (state) => {\n this.#state.set(state);\n },\n routerExtensions: [],\n contextClaimRecords: new Set(),\n hydrationState: null,\n });\n\n // =========================================================================\n // Wire Dependencies\n // =========================================================================\n\n wireNamespaces<Dependencies>({\n router: this,\n options: this.#options,\n limits: this.#limits,\n dependenciesStore: this.#dependenciesStore,\n state: this.#state,\n routes: this.#routes,\n routeLifecycle: this.#routeLifecycle,\n plugins: this.#plugins,\n navigation: this.#navigation,\n lifecycle: this.#lifecycle,\n eventBus: this.#eventBus,\n });\n\n // =========================================================================\n // Bind Public Methods\n // =========================================================================\n // All public methods that access private fields must be bound to preserve\n // `this` context when methods are extracted as references.\n // See: https://github.com/tc39/proposal-bind-operator\n // =========================================================================\n\n // Path & State Building\n this.isActiveRoute = this.isActiveRoute.bind(this);\n this.buildPath = this.buildPath.bind(this);\n\n // State Management\n this.getState = this.getState.bind(this);\n this.getPreviousState = this.getPreviousState.bind(this);\n this.areStatesEqual = this.areStatesEqual.bind(this);\n this.shouldUpdateNode = this.shouldUpdateNode.bind(this);\n\n // Router Lifecycle\n this.isActive = this.isActive.bind(this);\n this.start = this.start.bind(this);\n this.stop = this.stop.bind(this);\n this.dispose = this.dispose.bind(this);\n\n // Route Lifecycle (Guards)\n this.canNavigateTo = this.canNavigateTo.bind(this);\n\n // Plugins\n this.usePlugin = this.usePlugin.bind(this);\n\n // Navigation\n this.navigate = this.navigate.bind(this);\n this.navigateToDefault = this.navigateToDefault.bind(this);\n this.navigateToNotFound = this.navigateToNotFound.bind(this);\n\n // Subscription\n this.subscribe = this.subscribe.bind(this);\n this.subscribeLeave = this.subscribeLeave.bind(this);\n this.isLeaveApproved = this.isLeaveApproved.bind(this);\n\n // =========================================================================\n // Flush initial-route guard factories\n // =========================================================================\n // Deferred out of wiring (#1331): the pending canActivate/canDeactivate\n // factories from initial route definitions are compiled and executed HERE,\n // on the fully-built and bound router — a factory calling read-only methods\n // (`buildPath()`, `isActiveRoute()`, `getState()`) no longer hits a\n // half-assembled instance. Side-effectful calls (`navigate`, `usePlugin`,\n // route-CRUD) stay OUT OF CONTRACT: factories re-execute outside the\n // constructor (cloneRouter re-compiles definition guards per clone;\n // #recompileSlot re-runs a factory after a definition-only clear), so any\n // side effect would duplicate per re-execution — see CLAUDE.md. Runtime\n // add()/replace() compile guards in their own PREPARE phase and never touch\n // these pending maps.\n //\n // Fail-closed on a factory throw: by this point a router reference leaked\n // from an earlier factory is fully operational, while later guards would\n // stay silently unregistered — a fail-open guard bypass. Disposing before\n // the rethrow turns any leaked reference into a ROUTER_DISPOSED-throwing\n // husk (pre-#1331 such a reference was inert because getInternals threw).\n try {\n this.#routes.flushPendingGuards();\n } catch (error) {\n this.dispose();\n\n throw error;\n }\n }\n\n // ============================================================================\n // Path & State Building\n // ============================================================================\n\n isActiveRoute(\n name: string,\n params?: Params,\n search?: SearchParams,\n strictEquality?: boolean,\n ignoreQueryParams?: boolean,\n ): boolean {\n getInternals(this).validator?.routes.validateIsActiveRouteArgs(\n name,\n params,\n strictEquality,\n ignoreQueryParams,\n );\n\n getInternals(this).validator?.routes.validateRouteName(\n name,\n \"isActiveRoute\",\n );\n\n // Empty string is special case - warn and return false (root node is not a parent)\n if (name === \"\") {\n getInternals(this).logger.warn(\n \"real-router\",\n 'isActiveRoute(\"\") called with empty string. Root node is not considered a parent of any route.',\n );\n\n return false;\n }\n\n // Slot-shift (RFC-4 M2 / #1548): `search` is the explicit query channel at\n // position 3; `strictEquality` / `ignoreQueryParams` shift to 4 / 5.\n return this.#routes.isActiveRoute(\n name,\n params,\n search,\n strictEquality,\n ignoreQueryParams,\n );\n }\n\n buildPath(route: string, params?: Params, search?: SearchParams): string {\n const ctx = getInternals(this);\n\n ctx.validator?.routes.validateBuildPathArgs(route);\n ctx.validator?.navigation.validateParams(params, \"buildPath\");\n\n // `search` (RFC-4 M2 / #1548) is the explicit query channel; the matcher\n // builds the query string from it and the path from `params`, resolving a\n // colliding name (`/items/:id?id`). Omitted → the v1 single-bag path.\n return ctx.buildPath(route, normalizeParams(params), search);\n }\n\n // ============================================================================\n // State Management (delegated to StateNamespace)\n // ============================================================================\n\n getState<P extends Params = Params>(): State<P> | undefined {\n return this.#state.get<P>();\n }\n\n getPreviousState(): State | undefined {\n return this.#state.getPrevious();\n }\n\n areStatesEqual(\n state1: State | undefined,\n state2: State | undefined,\n ignoreQueryParams = true,\n ): boolean {\n getInternals(this).validator?.state.validateAreStatesEqualArgs(\n state1,\n state2,\n ignoreQueryParams,\n );\n\n return this.#state.areStatesEqual(state1, state2, ignoreQueryParams);\n }\n\n shouldUpdateNode(\n nodeName: string,\n ): (toState: State, fromState?: State) => boolean {\n getInternals(this).validator?.routes.validateShouldUpdateNodeArgs(nodeName);\n\n return RoutesNamespace.shouldUpdateNode(nodeName, (name) =>\n this.#routes.getMetaForState(name),\n );\n }\n\n // ============================================================================\n // Router Lifecycle\n // ============================================================================\n\n isActive(): boolean {\n return this.#eventBus.isActive();\n }\n\n start(startPath: string): Promise<State> {\n if (!this.#eventBus.canStart()) {\n return Promise.reject(CACHED_ALREADY_STARTED_ERROR);\n }\n\n getInternals(this).validator?.navigation.validateStartArgs(startPath);\n\n // FSM bookkeeping is split across the facade and RouterLifecycleNamespace by\n // design, NOT a missed consolidation (#940): `sendStart()` runs HERE, before\n // the interceptor chain, so the STARTING window spans the whole start\n // pipeline. A pre-`next()` interceptor throw then unwinds via STARTING →\n // `sendFail`, which emits TRANSITION_ERROR from STARTING (EventBusNamespace\n // FAIL action) for `onTransitionError` plugins. Moving `sendStart()` into the\n // namespace (the interceptor *target*) would skip STARTING on a pre-`next()`\n // throw — the namespace is never reached — silently dropping that\n // TRANSITION_ERROR: a #668 regression. The commit (`completeStart`) lives in\n // the namespace; recovery needs facade state (`#state`, `#lifecycle`), so it\n // stays here in `#unwindFailedStart`.\n this.#eventBus.sendStart();\n\n // Convert sync interceptor throws to rejections so the recovery path is\n // reachable; otherwise the throw escapes synchronously, the FSM is left in\n // STARTING, and the router is permanently bricked (#668).\n let internalStart: Promise<State>;\n\n try {\n const chainResult: unknown = getInternals(this).start(startPath);\n\n // A `start` interceptor that returns without calling next() yields a\n // non-thenable (typically undefined); the `.catch` below would then throw\n // a cryptic `TypeError: ...reading 'catch'` and leave the FSM stuck in\n // STARTING. Reject with an actionable message so recovery unwinds via\n // #unwindFailedStart — the same deferred-crash class as the #939\n // start-path guard (#1411).\n internalStart =\n typeof (chainResult as { then?: unknown } | null | undefined)?.then ===\n \"function\"\n ? (chainResult as Promise<State>)\n : Promise.reject(\n new TypeError(\n \"[router.start] a `start` interceptor returned without calling next(). Every start interceptor must return `next(path)`.\",\n ),\n );\n } catch (syncError: unknown) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided start interceptor\n internalStart = Promise.reject(syncError);\n }\n\n const promiseState = internalStart.catch((error: unknown) =>\n this.#unwindFailedStart(error),\n );\n\n this.#suppressUnhandledRejection(\n promiseState,\n this.#onSuppressedStartError,\n );\n\n return promiseState;\n }\n\n stop(): this {\n // SendCancelIfPossible → FSM CANCEL → the CANCEL action\n // aborts the in-flight controller (waking the pipeline). No separate abort.\n this.#eventBus.sendCancelIfPossible(this.#state.get());\n\n // `isStarting()` is included (#1185): a stop() while `start()` is parked in\n // an async start-interceptor (FSM STARTING, before `next()`) must cancel the\n // start, not silently no-op. `sendStop()` takes STARTING → IDLE (FSM table),\n // and `RouterLifecycleNamespace.start` re-checks `isIdle()` after the\n // interceptor chain and rejects with TRANSITION_CANCELLED — mirroring the\n // guard-phase behavior (which already cancels from TRANSITION_STARTED).\n if (\n !this.#eventBus.isReady() &&\n !this.#eventBus.isTransitioning() &&\n !this.#eventBus.isStarting()\n ) {\n return this;\n }\n\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n\n return this;\n }\n\n dispose(): void {\n // Stryker disable next-line BlockStatement: equivalent — emptying the early-return re-runs the dispose body on a 2nd call, but it is fully idempotent (FSM `send(DISPOSE)` no-ops from DISPOSED, `disposeAll()` already cleared `#unsubscribes`, every clear is idempotent). (ConditionalExpression stays live: `→true` always-returns and never disposes = killed.)\n if (this.#eventBus.isDisposed()) {\n return;\n }\n\n // the FSM CANCEL action aborts the in-flight controller.\n this.#eventBus.sendCancelIfPossible(this.#state.get());\n\n if (this.#eventBus.isReady() || this.#eventBus.isTransitioning()) {\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n }\n\n this.#eventBus.sendDispose();\n this.#eventBus.clearAll();\n\n this.#plugins.disposeAll();\n\n // Safety net: clean up extensions plugins failed to remove in teardown\n const ctx = getInternals(this);\n\n for (const extension of ctx.routerExtensions) {\n for (const key of extension.keys) {\n delete (this as Record<string, unknown>)[key];\n }\n }\n\n ctx.routerExtensions.length = 0;\n\n // Safety net: release context namespace claims plugins failed to release in teardown\n ctx.contextClaimRecords.clear();\n\n // Safety net: drop interceptors plugins failed to remove in teardown (#1199).\n // The third per-plugin registration channel — symmetric with routerExtensions\n // / contextClaimRecords above. `buildPath` is not method-swapped by dispose\n // and reads this Map live, so a leaked interceptor would otherwise still run\n // on the disposed router.\n ctx.interceptors.clear();\n\n this.#routes.clearRoutes();\n this.#routeLifecycle.clearAll();\n this.#state.reset();\n this.#dependenciesStore.dependencies = Object.create(\n null,\n ) as Partial<Dependencies>;\n\n this.#markDisposed();\n }\n\n // ============================================================================\n // Route Lifecycle (Guards)\n // ============================================================================\n\n canNavigateTo(name: string, params?: Params, search?: SearchParams): boolean {\n const ctx = getInternals(this);\n\n ctx.validator?.routes.validateRouteName(name, \"canNavigateTo\");\n ctx.validator?.navigation.validateParams(params, \"canNavigateTo\");\n\n if (!this.#routes.hasRoute(name)) {\n return false;\n }\n\n // Mirror EVERY way `navigate` refuses these same arguments, not only the\n // guard verdict (#1576). A declared query key handed in the PATH bag makes\n // `navigate` throw synchronously at the facade (channel guard P1, #1572), so\n // the route is unreachable with this input — exactly the situation invariant\n // canNavigateTo #5 already answers `false` to for an unbuildable path (#725).\n // Answering `true` here promised a navigation that throws on the click.\n //\n // The RAW caller bag, before `forwardState`: the same argument, the same\n // registry and the same name P1 reads, so the predicate cannot be stricter\n // OR laxer than the verb. The `/items/:id?id` collision is absent from\n // `queryNames` by construction (#843 / #1549), so it stays navigable in both.\n //\n // A `false` rather than a rethrow: a capability predicate answers, it never\n // throws (#725), and it runs on every `<Link>` render across six adapters —\n // which is exactly why P1 does not instrument the predicates (#1572).\n if (\n findMisChanneledKey(params, this.#routes.getQueryParams(name)) !==\n undefined\n ) {\n return false;\n }\n\n // Resolution runs USER code and must not escape as an exception (#1577):\n // a dynamic `forwardTo` callback, a plugin's `forwardState` interceptor, and\n // the caller's own bag (the merge walks it key by key, so an accessor-backed\n // key throws here — the channel guard itself does NOT, it catches its own\n // read) all sit on this one call. The\n // predicate is documented TOTAL — it answers, it never throws (INVARIANTS\n // canNavigateTo #5, #725) — and its sibling `isActiveRoute` has wrapped the\n // very same primitive since #1573 (`RoutesNamespace.ts:631-645`). Leaving\n // this one bare made the two render-path predicates disagree about what a\n // throwing resolution means.\n //\n // A separate `try` rather than widening the one below: that one is SILENT by\n // design (an unbuildable path is a normal \"unreachable with this input\"\n // answer, #725), while user code crashing is an operational fault that must\n // never vanish — the same split #959 draws for a throwing guard.\n // Stages ① + ③ + the mode gate, one pass through the pipeline (nav-pipeline\n // Phase 2, step 2-3). `canonicalize` reaches the same `forwardState` seam\n // this method used to call directly (`port.resolveForward` IS\n // `ctx.forwardState`), so the resolution, the interceptor zone and the\n // channel CHECK on the seam are all unchanged — what the pipeline\n // replaces is the hand-rolled composition that followed.\n // Read ONCE (#1589): this predicate reached for the port twice — here and\n // again for `buildURL` below — on every `<Link>` render. The port is one\n // object per router, created at wiring time, so the second read could only\n // ever return the same reference.\n const port = this.#routes.getPort();\n\n let canonical;\n\n try {\n canonical = canonicalize(\n port,\n name,\n // The singleton, not a fresh `{}` (#1589): this predicate runs on every\n // `<Link>` render too, and `normalizeParams` recognises `EMPTY_PARAMS` by\n // identity — a literal makes it walk and re-allocate instead.\n params ?? EMPTY_PARAMS,\n search,\n );\n } catch (error) {\n ctx.logger.warn(\n \"router.canNavigateTo\",\n `Resolving route \"${name}\" threw while answering the predicate; treating the route as unreachable.`,\n error,\n );\n\n return false;\n }\n\n // Build `toState` exactly as `buildNavigateState` does — WITH route-meta and\n // normalized params — so `getTransitionPath` takes its STANDARD PATH and\n // trims the shared ancestor, mirroring navigate's guard set (#970). A\n // meta-less `toState` makes both sides meta-less (the committed `getState()`\n // carries no meta after a path-matched `start()`), so `getTransitionPath`\n // takes FAST PATH 3 and (de)activates the WHOLE chain incl. shared ancestors\n // → false-negative (\"Link disabled though the click would succeed\").\n // `normalizeParams` also aligns the params guards observe with navigate's.\n // `skipFreeze` (5th arg) mirrors the navigate guard phase, where guards see\n // an unfrozen, transition-less `toState` (freeze happens later in\n // `completeTransition`).\n //\n // A capability predicate must answer, not throw: if the target path can't be\n // built from these params (e.g. a required path param is missing), the route\n // is simply unreachable with this input — return `false` rather than letting\n // `buildPath` throw (#725).\n let toState: State;\n\n try {\n // ⑤a then ⑤b. `buildURL` is usable HERE (unlike in `buildPath` itself,\n // where it would recurse through the interceptable `ctx.buildPath` that\n // wraps that very method): this point is not the one the port prints\n // through, so the URL is built by the pipeline and the state materialised\n // from the SAME canonical intent — `toState.search` and `toState.path`\n // cannot drift. `skipFreeze` mirrors the navigate guard phase, where\n // guards see an unfrozen, transition-less `toState`.\n toState = materialize(canonical, {\n path: buildURL(canonical, port),\n skipFreeze: true,\n });\n } catch {\n return false;\n }\n\n const fromState = this.#state.get();\n\n const { toDeactivate, toActivate } = getTransitionPath(\n toState,\n fromState,\n (routeName) => this.#routes.getMetaForState(routeName),\n );\n\n return this.#routeLifecycle.canNavigateTo(\n toDeactivate,\n toActivate,\n toState,\n fromState,\n );\n }\n\n // ============================================================================\n // Plugins\n // ============================================================================\n\n usePlugin(\n ...plugins: (PluginFactory<Dependencies> | false | null | undefined)[]\n ): Unsubscribe {\n // Post-dispose guard, mirroring #946 for subscribe/subscribeLeave. A\n // reference captured before dispose() (`const up = router.usePlugin`)\n // bypasses the #markDisposed method swap, so the swap alone is not enough:\n // without this, the factory would run on a disposed router (real side\n // effects), listeners would land in the cleared emitter, and teardown would\n // never fire — a silent zombie plugin (#1196).\n if (this.#eventBus.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n const filtered = plugins.filter(Boolean) as PluginFactory<Dependencies>[];\n\n if (filtered.length === 0) {\n return () => {};\n }\n\n const ctx = getInternals(this);\n\n ctx.validator?.plugins.validatePluginLimit(\n this.#plugins.count(),\n this.#limits,\n );\n for (const plugin of filtered) {\n // `getAll()` sits inside the optional-chain argument on purpose: with no\n // validator installed (production default) the `?.` short-circuits and the\n // array is never allocated. Hoisting it out would either allocate on the\n // no-validator hot path or push the dev-only branch out of coverage.\n ctx.validator?.plugins.validateNoDuplicatePlugins(\n plugin,\n this.#plugins.getAll(),\n );\n }\n\n return this.#plugins.use(...filtered);\n }\n\n // ============================================================================\n // Subscription (backed by EventEmitter)\n // ============================================================================\n\n subscribe(listener: SubscribeFn): Unsubscribe {\n EventBusNamespace.validateSubscribeListener(listener);\n\n return this.#eventBus.subscribe(listener);\n }\n\n subscribeLeave(listener: LeaveFn): Unsubscribe {\n EventBusNamespace.validateSubscribeLeaveListener(listener);\n\n return this.#eventBus.subscribeLeave(listener);\n }\n\n isLeaveApproved(): boolean {\n return this.#eventBus.isLeaveApproved();\n }\n\n // ============================================================================\n // Navigation\n // ============================================================================\n\n navigate(\n target: NavigationTarget,\n options?: NavigationOptions,\n ): Promise<State>;\n navigate(\n routeName: string,\n routeParams?: Params,\n routeSearch?: SearchParams,\n options?: NavigationOptions,\n ): Promise<State>;\n navigate(\n nameOrTarget: string | NavigationTarget,\n paramsOrOptions?: Params | NavigationOptions,\n routeSearch?: SearchParams,\n options?: NavigationOptions,\n ): Promise<State> {\n this.#assertNotReentrant();\n\n const ctx = getInternals(this);\n\n // Two equal-standing forms (RFC-4 M2 / #1548): the descriptor\n // `navigate(target, opts)` (opts at position 2) and the positional\n // `navigate(name, params, search, opts)` (opts at position 4). The v1\n // `navigate(name, params, opts)` form is gone — its position-3 opts is now\n // the `search` slot; unpack whichever form the caller used into one path.\n let routeName: string;\n let routeParams: Params | undefined;\n let search: SearchParams | undefined;\n let opts: NavigationOptions;\n\n // The static type excludes null, but `navigate(null)` is a real runtime\n // misuse that must stay graceful (ROUTE_NOT_FOUND, not a crash on\n // `null.name`) — the null check routes it to the positional branch.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime null guard for navigate(null)\n if (typeof nameOrTarget === \"object\" && nameOrTarget !== null) {\n routeName = nameOrTarget.name;\n routeParams = nameOrTarget.params;\n search = nameOrTarget.search;\n opts = (paramsOrOptions as NavigationOptions | undefined) ?? EMPTY_OPTS;\n } else {\n routeName = nameOrTarget;\n routeParams = paramsOrOptions as Params | undefined;\n search = routeSearch;\n opts = options ?? EMPTY_OPTS;\n }\n\n throwOnMisChanneledKey(ctx, \"navigate\", routeName, routeParams);\n\n ctx.validator?.navigation.validateNavigateArgs(routeName);\n ctx.validator?.navigation.validateParams(routeParams, \"navigate\");\n ctx.validator?.navigation.validateNavigationOptions(opts, \"navigate\");\n\n const promiseState = this.#navigation.navigate(\n routeName,\n routeParams ?? EMPTY_PARAMS,\n search,\n opts,\n );\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n // Cached rejection — already pre-suppressed at module load, skip .catch()\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n }\n\n navigateToDefault(options?: NavigationOptions): Promise<State> {\n this.#assertNotReentrant();\n\n const ctx = getInternals(this);\n\n ctx.validator?.navigation.validateNavigateToDefaultArgs(options);\n\n const opts = options ?? EMPTY_OPTS;\n\n ctx.validator?.navigation.validateNavigationOptions(\n opts,\n \"navigateToDefault\",\n );\n\n const promiseState = this.#navigation.navigateToDefault(opts);\n\n if (this.#navigation.lastSyncResolved) {\n this.#navigation.lastSyncResolved = false;\n } else if (this.#navigation.lastSyncRejected) {\n this.#navigation.lastSyncRejected = false;\n } else {\n this.#suppressUnhandledRejection(promiseState);\n }\n\n return promiseState;\n }\n\n navigateToNotFound(path?: string): State {\n this.#assertNotReentrant();\n\n if (!this.#eventBus.isActive()) {\n throw new RouterError(errorCodes.ROUTER_NOT_STARTED);\n }\n\n if (path !== undefined && typeof path !== \"string\") {\n throw new TypeError(\n `[router.navigateToNotFound] path must be a string, got ${typeof path}`,\n );\n }\n\n if (path !== undefined) {\n return this.#navigation.navigateToNotFound(path);\n }\n\n // #1172: a path-less call derives the default path from the committed state.\n // During the two-phase start window the router is active (`isActive()` true)\n // while `getState()` is still undefined, so throw an actionable RouterError\n // instead of a cryptic `TypeError` from dereferencing the absent state —\n // same class as the #939 always-on invariant guards.\n const current = this.#state.get();\n\n if (current === undefined) {\n throw new RouterError(errorCodes.ROUTER_NOT_STARTED, {\n message:\n \"[router.navigateToNotFound] cannot derive the path before the start navigation commits — pass an explicit path\",\n });\n }\n\n return this.#navigation.navigateToNotFound(current.path);\n }\n\n /**\n * Classifies a fire-and-forget rejection as an EXPECTED outcome that must\n * stay silent (no log). Shared by the navigate and start suppressors so the\n * suppression contract lives in one place.\n *\n * A suppressed RouterError code is a normal caller-owned navigation result\n * (a guard block, SAME_STATES, ROUTER_NOT_STARTED, …) — see\n * SUPPRESSED_ERROR_CODES (#721).\n *\n * The #945 RecursionDepthError carve-out is gone: a reentrant navigate() from a\n * listener can no longer self-feed — it throws REENTRANT_NAVIGATION\n * synchronously at the facade (RFC navigation-cancellation-unification §4), so\n * navigate()'s promise never rejects with a recursion error (re-entrant emits\n * are coalesced at the emitter, #1033; reentrant route-CRUD throws\n * REENTRANT_TREE_MUTATION to the CRUD caller, #1032 — not through a navigate\n * promise).\n */\n static #isExpectedRejection(error: unknown): boolean {\n return (\n error instanceof RouterError && SUPPRESSED_ERROR_CODES.has(error.code)\n );\n }\n\n /**\n * Fire-and-forget safety: prevents unhandled rejection warnings when\n * navigate/navigateToDefault/start is called without await. Expected errors\n * are silently suppressed; unexpected ones are logged under `onSuppressed`'s\n * category — navigate by default; start() passes #onSuppressedStartError so\n * its failures are logged as \"router.start\", not \"router.navigate\" (#931).\n */\n #suppressUnhandledRejection(\n promise: Promise<State>,\n onSuppressed: (error: unknown) => void = this.#onSuppressedNavigateError,\n ): void {\n promise.catch(onSuppressed);\n }\n\n /**\n * Rejects a synchronous reentrant navigation — `navigate` /\n * `navigateToDefault` / `navigateToState` / `navigateToNotFound` called from\n * inside a transition-event listener while a transition is being dispatched\n * (RFC navigation-cancellation-unification §4). Throws synchronously: inside a\n * listener the emit's `onListenerError` isolation surfaces it (visible,\n * non-fatal); a DEFERRED (async / microtask) navigate from a listener runs\n * after dispatch settles and is allowed. Always-on core invariant guard (not\n * validator-gated).\n */\n #assertNotReentrant(): void {\n if (this.#eventBus.isProcessing()) {\n throw new RouterError(errorCodes.REENTRANT_NAVIGATION);\n }\n }\n\n /**\n * Settles the FSM after a failed start pipeline, then re-throws so the\n * rejection still surfaces to the caller. Three cases, by what the pipeline\n * reached before throwing:\n *\n * - **Pre-commit, READY** (`isReady()` and no committed state): an interceptor\n * threw after `completeStart()` reached READY but before any state committed\n * (e.g. an activation guard blocked the start navigation) — return READY →\n * IDLE via `stop()` so the router is reusable.\n * - **Pre-commit, STARTING** (`isStarting()`): the pipeline threw before\n * `completeStart()` — a sync interceptor throw before `next()`, or a throw\n * inside the namespace before commit — so unwind STARTING → IDLE via\n * `sendFail`, which also emits TRANSITION_ERROR from STARTING (#668).\n * - **Post-commit, READY with committed state** (neither branch fires): a\n * loader/interceptor threw AFTER `navigateToState` committed and emitted\n * TRANSITION_SUCCESS (the SSR/RSC loader window). Keep the committed state —\n * rolling back would retract an observed success (\"phantom success\", #763);\n * the error still surfaces via the re-throw.\n */\n #unwindFailedStart(error: unknown): never {\n if (this.#eventBus.isReady() && this.#state.get() === undefined) {\n this.#lifecycle.stop();\n this.#eventBus.sendStop();\n } else if (this.#eventBus.isStarting()) {\n this.#eventBus.sendFail(undefined, undefined, error);\n }\n\n throw error;\n }\n\n #markDisposed(): void {\n this.navigate = throwDisposed;\n this.navigateToDefault = throwDisposed;\n this.navigateToNotFound = throwDisposed;\n this.start = throwDisposed;\n this.stop = throwDisposed;\n this.usePlugin = throwDisposed;\n\n this.subscribe = throwDisposed;\n this.subscribeLeave = throwDisposed;\n this.canNavigateTo = throwDisposed;\n }\n}\n\nfunction throwDisposed(): never {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n}\n\n/**\n * Derives CreateMatcherOptions from router Options.\n * Maps core option names to matcher option names.\n */\nfunction deriveMatcherOptions<Dependencies extends DefaultDependencies>(\n options: Readonly<Options<Dependencies>>,\n): CreateMatcherOptions {\n return {\n strictTrailingSlash: options.trailingSlash === \"strict\",\n caseSensitive: options.caseSensitive,\n strictQueryParams: options.queryParamsMode === \"strict\",\n urlParamsEncoding: options.urlParamsEncoding,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n queryParams: options.queryParams!,\n };\n}\n"],"mappings":"6pCAgEM,EAA0C,OAAO,OAAO,CAAC,CAAC,EAS1D,EAA8C,IAAI,IAAI,CAC1DA,EAAAA,WAAW,YACXA,EAAAA,WAAW,qBACXA,EAAAA,WAAW,mBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,iBACb,CAAC,EAkBD,IAAa,EAAb,MAAa,CAE8B,CAOzC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GAEA,GAeA,GACA,GAWA,YACE,EAAgC,CAAC,EACjC,EAA0C,CAAC,EAC3C,EAA6B,CAAC,EAC9B,CAIA,GAAM,CAAE,OAAQ,EAAc,GAAG,GAAkB,EAE/C,GACF,EAAA,mBAAmB,CAAY,EAQjC,IAAM,EAAS,IAAIa,EAAAA,aAAa,CAAY,EAI5C,KAAKF,GAA8B,GAAyB,CACtD,EAAOG,GAAqB,CAAK,GAIrC,EAAO,MAAM,kBAAmB,8BAA+B,CAAK,CACtE,EACA,KAAKF,GAA2B,GAAyB,CACnD,EAAOE,GAAqB,CAAK,GAIrC,EAAO,MAAM,eAAgB,yBAA0B,CAAK,CAC9D,EAOA,EAAA,iBAAiB,wBAAwB,CAAO,EAGhD,EAAA,kBAAkB,CAAY,EAG1B,EAAO,OAAS,GAClB,EAAA,oBAAoB,CAAM,EAO5B,KAAKb,GAAW,IAAIc,EAAAA,iBAAiB,CAAa,EAClD,KAAKb,GAAUc,EAAAA,aAAa,EAAc,MAAM,EAChD,KAAKb,GACHc,EAAAA,wBAAsC,CAAY,EACpD,KAAKb,GAAS,IAAIc,EAAAA,eAClB,KAAKb,GAAU,IAAIc,EAAAA,gBACjB,E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AM,CAAY,CAC5B,CAYA,IAA4B,CAC1B,GAAI,KAAKD,GAAU,aAAa,EAC9B,MAAM,IAAIgC,EAAAA,YAAY1C,EAAAA,WAAW,oBAAoB,CAEzD,CAqBA,GAAmB,EAAuB,CAQxC,MAPI,KAAKU,GAAU,QAAQ,GAAK,KAAKN,GAAO,IAAI,IAAM,IAAA,IACpD,KAAKK,GAAW,KAAK,EACrB,KAAKC,GAAU,SAAS,GACf,KAAKA,GAAU,WAAW,GACnC,KAAKA,GAAU,SAAS,IAAA,GAAW,IAAA,GAAW,CAAK,EAG/C,CACR,CAEA,IAAsB,CACpB,KAAK,SAAW,EAChB,KAAK,kBAAoB,EACzB,KAAK,mBAAqB,EAC1B,KAAK,MAAQ,EACb,KAAK,KAAO,EACZ,KAAK,UAAY,EAEjB,KAAK,UAAY,EACjB,KAAK,eAAiB,EACtB,KAAK,cAAgB,CACvB,CACF,EAEA,SAAS,GAAuB,CAC9B,MAAM,IAAIgC,EAAAA,YAAY1C,EAAAA,WAAW,eAAe,CAClD,CAMA,SAAS,EACP,EACsB,CACtB,MAAO,CACL,oBAAqB,EAAQ,gBAAkB,SAC/C,cAAe,EAAQ,cACvB,kBAAmB,EAAQ,kBAAoB,SAC/C,kBAAmB,EAAQ,kBAE3B,YAAa,EAAQ,WACvB,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPluginApi.d.ts","names":[],"sources":["../../../src/api/getPluginApi.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"getPluginApi.d.ts","names":[],"sources":["../../../src/api/getPluginApi.ts"],"mappings":";;;iBAwBgB,aACd,qBAAqB,sBAAsB,qBAC3C,QAAQ,OAAO,gBAAgB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../constants.js"),t=require("../internals.js"),n=require("../
|
|
1
|
+
const e=require("../constants.js"),t=require("../internals.js"),n=require("../pipeline/canonicalize.js"),r=require("../pipeline/buildURL.js"),i=require("../pipeline/materialize.js"),a=require("../RouterError.js"),o=require("./helpers.js"),s=new WeakMap;function c(c){let l=s.get(c);if(l)return l;let u=t.getInternals(c),d={makeState:(e,n,r,i)=>(t.throwOnMisChanneledKey(u,`makeState`,e,n),u.validator?.state.validateMakeStateArgs(e,n,i),u.makeState(e,n,r,i)),forwardState:(e,t,n)=>(u.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),u.forwardState(e,t,n)),matchPath:e=>(u.validator?.routes.validateMatchPathArgs(e),u.matchPath(e,u.getOptions())),navigateToState:(e,t)=>(o.throwIfDisposed(u.isDisposed),u.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&u.validator?.navigation.validateNavigationOptions(t,`navigateToState`),u.navigateToState(e,t)),setRootPath:e=>{o.throwIfDisposed(u.isDisposed),u.validator?.routes.validateSetRootPathArgs(e),u.setRootPath(e)},getRootPath:u.getRootPath,addEventListener:(e,t)=>(o.throwIfDisposed(u.isDisposed),u.validator?.eventBus.validateListenerArgs(e,t),u.addEventListener(e,t)),buildNavigationState:(e,a={},o={})=>{t.throwOnMisChanneledKey(u,`buildNavigationState`,e,a),u.validator?.routes.validateStateBuilderArgs(e,a,`buildNavigationState`);let s=n.canonicalize(u.port(),e,a,o,{diagnoseUndeclared:!0});if(u.buildStateResolved(s.name,s.path))return i.materialize(s,{path:r.buildURL(s,u.port())})},getOptions:u.getOptions,getTree:u.getTree,addInterceptor:(e,t)=>{o.throwIfDisposed(u.isDisposed),u.validator?.plugins.validateAddInterceptorArgs(e,t);let n=u.interceptors.get(e);n||(n=[],u.interceptors.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=u.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{o.throwIfDisposed(u.isDisposed);let n=Object.keys(t);for(let t of n)if(t in c)throw new a.RouterError(e.errorCodes.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of n)c[e]=t[e];let r={keys:n};u.routerExtensions.push(r);let i=!1;return()=>{if(i)return;i=!0;for(let e of r.keys)delete c[e];let e=u.routerExtensions.indexOf(r);e!==-1&&u.routerExtensions.splice(e,1)}},emitTransitionError:e=>{o.throwIfDisposed(u.isDisposed),u.emitTransitionError(e)},claimContextNamespace:t=>{if(o.throwIfDisposed(u.isDisposed),typeof t!=`string`||t===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof t==`string`?`an empty string`:typeof t}`);if(u.contextClaimRecords.has(t))throw new a.RouterError(e.errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return u.contextClaimRecords.add(t),{write(e,n){t===`__proto__`?Object.defineProperty(e.context,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e.context[t]=n},release(){u.contextClaimRecords.delete(t)}}}};return s.set(c,d),d}exports.getPluginApi=c;
|
|
2
2
|
//# sourceMappingURL=getPluginApi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getPluginApi.js","names":["getInternals","RouterError","errorCodes"],"sources":["../../../src/api/getPluginApi.ts"],"sourcesContent":["import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"../types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\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\">> | 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 navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\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 // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\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 // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n // Input-shape guard, symmetric with the other always-on invariant guards\n // (subscribe / start / navigateToNotFound each typeof-check their input).\n // A non-string namespace coerces to an inconsistent key (\"42\"); an empty\n // string is a meaningless namespace (#1191 N4).\n if (typeof namespace !== \"string\" || namespace === \"\") {\n throw new TypeError(\n `[claimContextNamespace] namespace must be a non-empty string, got ${\n typeof namespace === \"string\" ? \"an empty string\" : typeof namespace\n }`,\n );\n }\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n // `state.context[namespace] = value` dispatches into the inherited\n // Object.prototype.__proto__ setter for the literal key \"__proto__\",\n // swapping the prototype instead of creating an own entry — the data\n // then vanishes from Object.keys / serializeRouterState (#1191 N3).\n // Mirror search-params' assignParam: defineProperty writes a genuine\n // own property; normal names keep the plain-assignment fast path.\n if (namespace === \"__proto__\") {\n Object.defineProperty(state.context, namespace, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n state.context[namespace] = value;\n }\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n"],"mappings":"yHAoBM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAA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oBAAoB,CAAK,CAC/B,EACA,sBAAwB,GAAsB,CAO5C,GANA,EAAA,gBAAgB,EAAI,UAAU,EAM1B,OAAO,GAAc,UAAY,IAAc,GACjD,MAAU,UACR,qEACE,OAAO,GAAc,SAAW,kBAAoB,OAAO,GAE/D,EAGF,GAAI,EAAI,oBAAoB,IAAI,CAAS,EACvC,MAAM,IAAID,EAAAA,YAAYC,EAAAA,WAAW,kCAAmC,CAClE,QAAS,oCAAoC,EAAU,uCACzD,CAAC,EAKH,OAFA,EAAI,oBAAoB,IAAI,CAAS,EAE9B,CACL,MAAM,EAAc,EAAgB,CAO9B,IAAc,YAChB,OAAO,eAAe,EAAM,QAAS,EAAW,CAC9C,QACA,SAAU,GACV,WAAY,GACZ,aAAc,EAChB,CAAC,EAED,EAAM,QAAQ,GAAa,CAE/B,EACA,SAAU,CACR,EAAI,oBAAoB,OAAO,CAAS,CAC1C,CACF,CACF,CACF,EAIA,OAFA,EAAM,IAAI,EAAQ,CAAG,EAEd,CACT"}
|
|
1
|
+
{"version":3,"file":"getPluginApi.js","names":["getInternals","canonicalize","materialize","buildURL","RouterError","errorCodes"],"sources":["../../../src/api/getPluginApi.ts"],"sourcesContent":["import { buildURL, canonicalize, materialize } from \"../pipeline\";\nimport { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals, throwOnMisChanneledKey } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n SearchParams,\n State,\n} from \"../types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, search, path) => {\n throwOnMisChanneledKey(ctx, \"makeState\", name, params);\n\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n // Public PluginApi.makeState carries the query channel (RFC-4 M2 / #1548)\n // so plugins (e.g. browser-plugin popstate restore) can reconstruct a\n // split state from a serialized history entry. The former `meta` argument\n // (per-segment param-source map) was dropped when the `stateMetaStore`\n // WeakMap was removed — ownership is now read from the live matcher by\n // `state.name`, so a caller-supplied meta had no effect and is gone.\n return ctx.makeState(name, params, search, path);\n },\n forwardState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n routeName: string,\n routeParams: P,\n routeSearch?: S,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState<P, S>(routeName, routeParams, routeSearch);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\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 = {}, search = {}) => {\n throwOnMisChanneledKey(ctx, \"buildNavigationState\", name, params);\n\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n // Stages ① + ③ + the mode gate, one pass through the pipeline\n // (nav-pipeline Phase 2, step 2-4). `search` flows THROUGH the forwardState\n // seam, not past it (#1571) — `port.resolveForward` IS `ctx.forwardState`,\n // so the seam is still where an explicit query value wins over a declared\n // twin the caller rode in `params`, and where a `search-schema`\n // interceptor sees the query channel.\n const canonical = canonicalize(ctx.port(), name, params, search, {\n diagnoseUndeclared: true,\n });\n\n // Existence is checked BEFORE the URL is built, and the order is\n // load-bearing: `buildURL` prints through the matcher, which throws on an\n // unknown route, whereas this entry point answers `undefined` for one —\n // including when a `forwardTo` chain resolves to a target that does not\n // exist. (`canonicalize` itself is total here: a missing route simply has\n // no defaults and no declared query names.)\n if (!ctx.buildStateResolved(canonical.name, canonical.path)) {\n return;\n }\n\n // ⑤a then ⑤b from ONE canonical intent, so `state.search` and `state.path`\n // cannot derive from differently-merged bags. `buildURL` is usable here for\n // the same reason it is in `canNavigateTo`: this point is not the one the\n // port prints through, so there is no recursion (contrast `buildPath`).\n return materialize(canonical, {\n path: buildURL(canonical, ctx.port()),\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 // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\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 // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n // Input-shape guard, symmetric with the other always-on invariant guards\n // (subscribe / start / navigateToNotFound each typeof-check their input).\n // A non-string namespace coerces to an inconsistent key (\"42\"); an empty\n // string is a meaningless namespace (#1191 N4).\n if (typeof namespace !== \"string\" || namespace === \"\") {\n throw new TypeError(\n `[claimContextNamespace] namespace must be a non-empty string, got ${\n typeof namespace === \"string\" ? \"an empty string\" : typeof namespace\n }`,\n );\n }\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n // `state.context[namespace] = value` dispatches into the inherited\n // Object.prototype.__proto__ setter for the literal key \"__proto__\",\n // swapping the prototype instead of creating an own entry — the data\n // then vanishes from Object.keys / serializeRouterState (#1191 N3).\n // Mirror search-params' assignParam: defineProperty writes a genuine\n // own property; normal names keep the plain-assignment fast path.\n if (namespace === \"__proto__\") {\n Object.defineProperty(state.context, namespace, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n state.context[namespace] = value;\n }\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n"],"mappings":"+OAsBM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAMA,EAAAA,aAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAQ,KAChC,EAAA,uBAAuB,EAAK,YAAa,EAAM,CAAM,EAErD,EAAI,WAAW,MAAM,sBAAsB,EAAM,EAAQ,CAAI,EAQtD,EAAI,UAAU,EAAM,EAAQ,EAAQ,CAAI,GAEjD,cAIE,EACA,EACA,KAEA,EAAI,WAAW,OAAO,yBACpB,EACA,EACA,cACF,EAEO,EAAI,aAAmB,EAAW,EAAa,CAAW,GAEnE,UAAY,IACV,EAAI,WAAW,OAAO,sBAAsB,CAAI,EAEzC,EAAI,UAAU,EAAM,EAAI,WAAW,CAAC,GAE7C,iBAAkB,EAAO,KACvB,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,WAAW,4BAA4B,CAAK,EAEvD,IAAY,IAAA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M,IAAI,EAAQ,CAAG,EAEd,CACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getRoutesApi.d.ts","names":[],"sources":["../../../src/api/getRoutesApi.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"getRoutesApi.d.ts","names":[],"sources":["../../../src/api/getRoutesApi.ts"],"mappings":";;;iBAqqBgB,aACd,qBAAqB,sBAAsB,qBAC3C,QAAQ,OAAO,gBAAgB,UAAU"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../guards.js"),t=require("../internals.js"),n=require("../engine/operations/routeTreeToDefinitions.js"),r=require("../namespaces/RoutesNamespace/helpers.js"),i=require("../namespaces/RoutesNamespace/routesStore.js"),a=require("../transitionPath.js"),o=require("./helpers.js"),s=require("../namespaces/RoutesNamespace/routeGuards.js"),c=Object.freeze({replace:!0,revalidate:!0});function l(e,t,n,i){let a=t=>t===e||t.startsWith(`${e}.`);r.clearConfigEntries(t.decoders,a),r.clearConfigEntries(t.encoders,a),r.clearConfigEntries(t.defaultParams,a),r.clearConfigEntries(t.forwardMap,a),r.clearConfigEntries(t.forwardFnMap,a),r.clearConfigEntries(n,a),r.clearConfigEntries(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of Object.keys(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of Object.keys(o))a(e)&&i.clearCanDeactivate(e,`both`)}function u(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function d(e,t,n,r){let i={name:e.name,path:e.path};return u(i,t,n,r),e.children&&(i.children=e.children.map(e=>d(e,`${t}.${e.name}`,n,r))),i}function f(e,t,n,r){let i={name:e,path:t};return u(i,e,n,r),Object.freeze(i)}function p(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,f(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function m(e,t){let n=`${t}.`,r=p(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function h(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(f(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function g(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Object.freeze(n),added:Object.freeze(r)}}function _(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function v(e,t,n,
|
|
1
|
+
const e=require("../guards.js"),t=require("../internals.js"),n=require("../engine/operations/routeTreeToDefinitions.js"),r=require("../namespaces/RoutesNamespace/helpers.js"),i=require("../namespaces/RoutesNamespace/routesStore.js"),a=require("../transitionPath.js"),o=require("./helpers.js"),s=require("../namespaces/RoutesNamespace/routeGuards.js"),c=Object.freeze({replace:!0,revalidate:!0});function l(e,t,n,i){let a=t=>t===e||t.startsWith(`${e}.`);r.clearConfigEntries(t.decoders,a),r.clearConfigEntries(t.encoders,a),r.clearConfigEntries(t.defaultParams,a),r.clearConfigEntries(t.defaultSearch,a),r.clearConfigEntries(t.forwardMap,a),r.clearConfigEntries(t.forwardFnMap,a),r.clearConfigEntries(n,a),r.clearConfigEntries(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of Object.keys(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of Object.keys(o))a(e)&&i.clearCanDeactivate(e,`both`)}function u(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.defaultSearch&&(e.defaultSearch=n.defaultSearch[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function d(e,t,n,r){let i={name:e.name,path:e.path};return u(i,t,n,r),e.children&&(i.children=e.children.map(e=>d(e,`${t}.${e.name}`,n,r))),i}function f(e,t,n,r){let i={name:e,path:t};return u(i,e,n,r),Object.freeze(i)}function p(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,f(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function m(e,t){let n=`${t}.`,r=p(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function h(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(f(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function g(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Object.freeze(n),added:Object.freeze(r)}}function _(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.defaultSearch!==void 0&&(t.defaultSearch=e.defaultSearch),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function v(e,t,n,a){i.assertAddable(e,t,n);let o=i.buildAddArtifacts(e,t,n,a);r.assertRouteDefaultChannelsFor(o.matcher,o.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!1),i.adoptRouteArtifacts(e,o)}function y(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,c)}function b(e,t,n,o,s){i.assertNoInternalNamesInBatch(t,`addRoute`),i.assertNoDuplicateNamesInBatch(t,``,`addRoute`),i.assertNoDuplicatePathsInBatch(t,``,`addRoute`);let c=i.buildReplaceArtifacts(t,e.rootPath,e.matcherOptions,n.logger);r.assertRouteDefaultChannelsFor(c.matcher,c.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(c.pendingCanActivate.keys(),c.pendingCanDeactivate.keys(),!0);let l=i.compileArtifactGuards(c,e.depsStore);if(e.lifecycleNamespace.clearDefinitionGuards(),i.adoptRouteArtifacts(e,c,l),s?.(),o!==void 0){let t=n.matchPath(o.path,n.getOptions());if(t)if(t.name===o.name)y(n,{...t,context:o.context,transition:o.transition},o);else{let{toDeactivate:r,toActivate:i}=a.getTransitionPath(t,o,n.getMetaForState);e.lifecycleNamespace.canNavigateTo(r,i,t,o)?y(n,{...t,transition:o.transition},o):n.navigateToNotFound(o.path)}else n.navigateToNotFound(o.path)}}function x(e,t){let n=e.definitions;return r.removeFromDefinitions(n,t)?(l(t,e.config,e.routeCustomFields,e.lifecycleNamespace),i.commitTreeChanges(e,n),!0):!1}function S(e,t){let r=e.matcher.getSegmentsByName(t);if(!r)return;let i=n.nodeToDefinition(r.at(-1)),a=e.lifecycleNamespace.getFactories();return d(i,t,e.config,a)}const C=new WeakMap;function w(n){let r=C.get(n);if(r)return r;let a=t.getInternals(n),c=a.routeGetStore(),l=e=>{a.treeChanged.emit(e)},u={add:(t,n)=>{o.throwIfDisposed(a.isDisposed),o.throwIfReentrantTreeMutation(a.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t],i=n?.parent;if(e.guardRouteStructure(r,a.validator),i!==void 0&&a.validator?.routes.validateParentOption(i,c.tree),a.validator?.routes.throwIfInternalRouteInArray(r,`addRoute`),a.validator?.routes.validateAddRouteArgs(r),a.validator?.routes.validateRoutes(r,c,i),v(c,r,i,a.logger),a.treeChanged.listenerCount()>0){let e=h(r,i,c);l(i===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:i})}},remove:e=>{if(o.throwIfDisposed(a.isDisposed),o.throwIfReentrantTreeMutation(a.treeChanged.isEmitting),a.validator?.routes.validateRemoveRouteArgs(e),a.validator?.routes.throwIfInternalRoute(e,`removeRoute`),i.assertNoInternalRouteName(e,`removeRoute`),!s.validateRemoveRoute(e,a.getStateName(),a.isTransitioning(),a.logger))return;let t=a.treeChanged.listenerCount()>0?m(c,e):void 0;if(!x(c,e)){a.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`);return}t!==void 0&&l({op:`remove`,name:e,removedSubtree:t})},update:(e,t)=>{if(o.throwIfDisposed(a.isDisposed),o.throwIfReentrantTreeMutation(a.treeChanged.isEmitting),a.validator?.routes.validateUpdateRouteBasicArgs(e,t),a.validator?.routes.throwIfInternalRoute(e,`updateRoute`),i.assertNoInternalRouteName(e,`updateRoute`),a.validator?.routes.validateUpdateRoutePropertyTypes(e,t),a.isTransitioning()&&a.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`),a.validator?.routes.validateUpdateRoute(e,t,c),!c.matcher.hasRoute(e))return;let n=c.lifecycleNamespace,r=i.commitRouteUpdate(c,n,e,t);if(a.treeChanged.listenerCount()>0){let t=_(r);Object.keys(t).length>0&&l({op:`update`,name:e,patch:t})}},clear:()=>{if(o.throwIfDisposed(a.isDisposed),o.throwIfReentrantTreeMutation(a.treeChanged.isEmitting),!s.validateClearRoutes(a.isTransitioning(),a.logger))return;let e=a.treeChanged.listenerCount()>0?Object.freeze([...p(c,()=>!0).values()]):void 0;i.resetStore(c),c.lifecycleNamespace.clearAll(),a.clearState(),e!==void 0&&l({op:`clear`,removed:e})},has:e=>(a.validator?.routes.validateRouteName(e,`hasRoute`),c.matcher.hasRoute(e)),get:e=>(a.validator?.routes.validateRouteName(e,`getRoute`),S(c,e)),replace:t=>{o.throwIfDisposed(a.isDisposed),o.throwIfReentrantTreeMutation(a.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t];if(!s.validateClearRoutes(a.isTransitioning(),a.logger))return;e.guardRouteStructure(r,a.validator),a.validator?.routes.throwIfInternalRouteInArray(r,`replaceRoutes`),a.validator?.routes.validateAddRouteArgs(r),a.validator?.routes.validateRoutes(r,c);let i=n.getState(),u=a.treeChanged.listenerCount()>0?p(c,()=>!0):void 0;b(c,r,a,i,u===void 0?void 0:()=>{let e=p(c,()=>!0),{removed:t,added:n}=g(u,e);l({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>a.treeChanged.subscribe(e)};return C.set(n,u),u}exports.getRoutesApi=w;
|
|
2
2
|
//# sourceMappingURL=getRoutesApi.js.map
|