@real-router/core 0.83.1 → 0.85.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/dist/cjs/Router-BOyV6_me.js +2 -0
- package/dist/cjs/Router-BOyV6_me.js.map +1 -0
- package/dist/cjs/api/getRoutesApi.d.ts.map +1 -1
- package/dist/cjs/api.js +2 -1
- package/dist/cjs/api.js.map +1 -1
- package/dist/cjs/constants.d.ts.map +1 -1
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/types/constants.d.ts +2 -1
- package/dist/cjs/types/constants.d.ts.map +1 -1
- package/dist/cjs/validation.js +2 -1
- package/dist/esm/Router-A9Vko7z1.mjs +2 -0
- package/dist/esm/Router-A9Vko7z1.mjs.map +1 -0
- 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/constants.d.mts.map +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/types/constants.d.mts +2 -1
- package/dist/esm/types/constants.d.mts.map +1 -1
- package/package.json +2 -2
- package/dist/cjs/Router-DDJ1AZzR.js +0 -2
- package/dist/cjs/Router-DDJ1AZzR.js.map +0 -1
- package/dist/cjs/Router.js +0 -2
- package/dist/cjs/Router.js.map +0 -1
- package/dist/cjs/RouterError.js +0 -2
- package/dist/cjs/RouterError.js.map +0 -1
- package/dist/cjs/api/cloneRouter.js +0 -2
- package/dist/cjs/api/cloneRouter.js.map +0 -1
- package/dist/cjs/api/getDependenciesApi.js +0 -2
- package/dist/cjs/api/getDependenciesApi.js.map +0 -1
- package/dist/cjs/api/getLifecycleApi.js +0 -2
- package/dist/cjs/api/getLifecycleApi.js.map +0 -1
- package/dist/cjs/api/getPluginApi.js +0 -2
- package/dist/cjs/api/getPluginApi.js.map +0 -1
- package/dist/cjs/api/getRoutesApi.js +0 -2
- package/dist/cjs/api/getRoutesApi.js.map +0 -1
- package/dist/cjs/api/helpers.js +0 -2
- package/dist/cjs/api/helpers.js.map +0 -1
- package/dist/cjs/channels/defaults.js +0 -2
- package/dist/cjs/channels/defaults.js.map +0 -1
- package/dist/cjs/channels/guard.js +0 -2
- package/dist/cjs/channels/guard.js.map +0 -1
- package/dist/cjs/channels/modeGate.js +0 -2
- package/dist/cjs/channels/modeGate.js.map +0 -1
- package/dist/cjs/constants.js +0 -2
- package/dist/cjs/constants.js.map +0 -1
- package/dist/cjs/createRouter.js +0 -2
- package/dist/cjs/createRouter.js.map +0 -1
- package/dist/cjs/engine/builder/buildTree.js +0 -2
- package/dist/cjs/engine/builder/buildTree.js.map +0 -1
- package/dist/cjs/engine/builder/computeCaches.js +0 -2
- package/dist/cjs/engine/builder/computeCaches.js.map +0 -1
- package/dist/cjs/engine/builder/createRouteTree.js +0 -2
- package/dist/cjs/engine/builder/createRouteTree.js.map +0 -1
- package/dist/cjs/engine/createMatcher.js +0 -2
- package/dist/cjs/engine/createMatcher.js.map +0 -1
- package/dist/cjs/engine/operations/routeTreeToDefinitions.js +0 -2
- package/dist/cjs/engine/operations/routeTreeToDefinitions.js.map +0 -1
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js +0 -2
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js.map +0 -1
- package/dist/cjs/engine/path-matcher/buildParamMeta.js +0 -2
- package/dist/cjs/engine/path-matcher/buildParamMeta.js.map +0 -1
- package/dist/cjs/engine/path-matcher/encoding.js +0 -2
- package/dist/cjs/engine/path-matcher/encoding.js.map +0 -1
- package/dist/cjs/engine/path-matcher/parseSegment.js +0 -2
- package/dist/cjs/engine/path-matcher/parseSegment.js.map +0 -1
- package/dist/cjs/engine/path-matcher/pathUtils.js +0 -2
- package/dist/cjs/engine/path-matcher/pathUtils.js.map +0 -1
- package/dist/cjs/engine/path-matcher/percentEncoding.js +0 -2
- package/dist/cjs/engine/path-matcher/percentEncoding.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/buildParts.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/buildParts.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/context.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/context.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/errors.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/errors.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/index.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/index.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/trie.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/trie.js.map +0 -1
- package/dist/cjs/engine/path-matcher/registration/trieNodes.js +0 -2
- package/dist/cjs/engine/path-matcher/registration/trieNodes.js.map +0 -1
- package/dist/cjs/engine/search-params/decode.js +0 -2
- package/dist/cjs/engine/search-params/decode.js.map +0 -1
- package/dist/cjs/engine/search-params/encode.js +0 -2
- package/dist/cjs/engine/search-params/encode.js.map +0 -1
- package/dist/cjs/engine/search-params/searchParams.js +0 -2
- package/dist/cjs/engine/search-params/searchParams.js.map +0 -1
- package/dist/cjs/engine/search-params/strategies/array.js +0 -2
- package/dist/cjs/engine/search-params/strategies/array.js.map +0 -1
- package/dist/cjs/engine/search-params/strategies/boolean.js +0 -2
- package/dist/cjs/engine/search-params/strategies/boolean.js.map +0 -1
- package/dist/cjs/engine/search-params/strategies/index.js +0 -2
- package/dist/cjs/engine/search-params/strategies/index.js.map +0 -1
- package/dist/cjs/engine/search-params/strategies/null.js +0 -2
- package/dist/cjs/engine/search-params/strategies/null.js.map +0 -1
- package/dist/cjs/engine/search-params/strategies/number.js +0 -2
- package/dist/cjs/engine/search-params/strategies/number.js.map +0 -1
- package/dist/cjs/engine/search-params/utils.js +0 -2
- package/dist/cjs/engine/search-params/utils.js.map +0 -1
- package/dist/cjs/engine/validation/route-batch.js +0 -2
- package/dist/cjs/engine/validation/route-batch.js.map +0 -1
- package/dist/cjs/engine/validation/routes.js +0 -2
- package/dist/cjs/engine/validation/routes.js.map +0 -1
- package/dist/cjs/getNavigator.js +0 -2
- package/dist/cjs/getNavigator.js.map +0 -1
- package/dist/cjs/guards.js +0 -2
- package/dist/cjs/guards.js.map +0 -1
- package/dist/cjs/helpers.js +0 -2
- package/dist/cjs/helpers.js.map +0 -1
- package/dist/cjs/internals.js +0 -2
- package/dist/cjs/internals.js.map +0 -1
- package/dist/cjs/limits.js +0 -2
- package/dist/cjs/limits.js.map +0 -1
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.js +0 -2
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.js.map +0 -1
- package/dist/cjs/namespaces/EventBusNamespace/EventBusNamespace.js +0 -2
- package/dist/cjs/namespaces/EventBusNamespace/EventBusNamespace.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/InFlightNavigation.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/InFlightNavigation.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/constants.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/constants.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/completeTransition.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/transition/completeTransition.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/executeNavigation.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/transition/executeNavigation.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js.map +0 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/navigateToNotFound.js +0 -2
- package/dist/cjs/namespaces/NavigationNamespace/transition/navigateToNotFound.js.map +0 -1
- package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js +0 -2
- package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js.map +0 -1
- package/dist/cjs/namespaces/OptionsNamespace/constants.js +0 -2
- package/dist/cjs/namespaces/OptionsNamespace/constants.js.map +0 -1
- package/dist/cjs/namespaces/OptionsNamespace/helpers.js +0 -2
- package/dist/cjs/namespaces/OptionsNamespace/helpers.js.map +0 -1
- package/dist/cjs/namespaces/OptionsNamespace/validators.js +0 -2
- package/dist/cjs/namespaces/OptionsNamespace/validators.js.map +0 -1
- package/dist/cjs/namespaces/PluginsNamespace/PluginsNamespace.js +0 -2
- package/dist/cjs/namespaces/PluginsNamespace/PluginsNamespace.js.map +0 -1
- package/dist/cjs/namespaces/PluginsNamespace/constants.js +0 -2
- package/dist/cjs/namespaces/PluginsNamespace/constants.js.map +0 -1
- package/dist/cjs/namespaces/PluginsNamespace/validators.js +0 -2
- package/dist/cjs/namespaces/PluginsNamespace/validators.js.map +0 -1
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js +0 -2
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js.map +0 -1
- package/dist/cjs/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js +0 -2
- package/dist/cjs/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js.map +0 -1
- package/dist/cjs/namespaces/RouterLifecycleNamespace/constants.js +0 -2
- package/dist/cjs/namespaces/RouterLifecycleNamespace/constants.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/constants.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/constants.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/routeGuards.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/routeGuards.js.map +0 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js +0 -2
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js.map +0 -1
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js +0 -2
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js.map +0 -1
- package/dist/cjs/pipeline/buildURL.js +0 -2
- package/dist/cjs/pipeline/buildURL.js.map +0 -1
- package/dist/cjs/pipeline/canonicalize.js +0 -2
- package/dist/cjs/pipeline/canonicalize.js.map +0 -1
- package/dist/cjs/pipeline/materialize.js +0 -2
- package/dist/cjs/pipeline/materialize.js.map +0 -1
- package/dist/cjs/routerFSM.js +0 -2
- package/dist/cjs/routerFSM.js.map +0 -1
- package/dist/cjs/transitionPath.js +0 -2
- package/dist/cjs/transitionPath.js.map +0 -1
- package/dist/cjs/utils/event-emitter/EventEmitter.js +0 -2
- package/dist/cjs/utils/event-emitter/EventEmitter.js.map +0 -1
- package/dist/cjs/utils/fsm/fsm.js +0 -2
- package/dist/cjs/utils/fsm/fsm.js.map +0 -1
- package/dist/cjs/utils/logger/RouterLogger.js +0 -2
- package/dist/cjs/utils/logger/RouterLogger.js.map +0 -1
- package/dist/cjs/utils/logger/constants.js +0 -2
- package/dist/cjs/utils/logger/constants.js.map +0 -1
- package/dist/cjs/wiring/wireNamespaces.js +0 -2
- package/dist/cjs/wiring/wireNamespaces.js.map +0 -1
- package/dist/esm/Router-C7jMPCyc.mjs +0 -2
- package/dist/esm/Router-C7jMPCyc.mjs.map +0 -1
package/dist/cjs/Router.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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/constants.js"),v=require("./namespaces/NavigationNamespace/NavigationNamespace.js"),y=require("./namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js"),b=require("./routerFSM.js"),x=require("./namespaces/EventBusNamespace/EventBusNamespace.js"),S=require("./namespaces/RouterLifecycleNamespace/constants.js"),C=require("./utils/event-emitter/EventEmitter.js"),w=require("./utils/logger/RouterLogger.js"),T=require("./wiring/wireNamespaces.js"),E=Object.freeze({});var D=class D{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;constructor(r=[],c={},l={}){let{logger:u,...m}=c;u&&n.assertLoggerConfig(u);let g=new w.RouterLogger(u);this.#u=e=>{_.isExpectedRejection(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 v.NavigationNamespace,this.#c=new y.RouterLifecycleNamespace;let S=b.createRouterFSM(),O=new C.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 x.EventBusNamespace({routerFSM:S,emitter:O,abortController:e=>{this.#s.abortCurrentController(e)}});let A=new Map,j=i.createTernaryInterceptable(`forwardState`,(e,t,n)=>this.#i.forwardState(e,t,n),A);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=j(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()),A),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),A),navigateToState:(e,t)=>(this.#p(),D.#d(this.#s.navigateToState(e,t??E))),interceptors:A,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}),T.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){let t=this.#f(e);return t.catch(this.#u),t}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.#h()}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 x.EventBusNamespace.validateSubscribeListener(e),this.#l.subscribe(e)}subscribeLeave(e){return x.EventBusNamespace.validateSubscribeLeaveListener(e),this.#l.subscribeLeave(e)}isLeaveApproved(){return this.#l.isLeaveApproved()}navigate(e,n,r,a){this.#p();let o=i.getInternals(this),s,c,l,u;return typeof e==`object`&&e?(s=e.name,c=e.params,l=e.search,u=n??E):(s=e,c=n,l=r,u=a??E),i.throwOnMisChanneledKey(o,`navigate`,s,c),o.validator?.navigation.validateNavigateArgs(s),o.validator?.navigation.validateParams(c,`navigate`),o.validator?.navigation.validateNavigationOptions(u,`navigate`),D.#d(this.#s.navigate(s,c??t.EMPTY_PARAMS,l,u))}navigateToDefault(e){this.#p();let t=i.getInternals(this);t.validator?.navigation.validateNavigateToDefaultArgs(e);let n=e??E;return t.validator?.navigation.validateNavigationOptions(n,`navigateToDefault`),D.#d(this.#s.navigateToDefault(n))}navigateToNotFound(e){if(this.#p(),!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#d(e){return e instanceof Promise?e:Promise.resolve(e)}#f(e){if(!this.#l.canStart())return Promise.reject(S.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)}return t.catch(e=>this.#m(e))}#p(){if(this.#l.isProcessing()||this.#s.isPreparing())throw new g.RouterError(t.errorCodes.REENTRANT_NAVIGATION)}#m(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}#h(){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
|
-
//# sourceMappingURL=Router.js.map
|
package/dist/cjs/Router.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Router.js","names":["#options","#limits","#dependenciesStore","#state","#routes","#routeLifecycle","#plugins","#navigation","#lifecycle","#eventBus","#onSuppressedStartError","RouterLogger","isExpectedRejection","OptionsNamespace","createLimits","createDependenciesStore","StateNamespace","RoutesNamespace","RouteLifecycleNamespace","PluginsNamespace","NavigationNamespace","RouterLifecycleNamespace","createRouterFSM","EventEmitter","EventBusNamespace","createTernaryInterceptable","EMPTY_PARAMS","createInterceptable","#assertNotReentrant","#asPromise","getInternals","normalizeParams","#runStart","#markDisposed","findMisChanneledKey","canonicalize","materialize","buildURL","getTransitionPath","RouterError","errorCodes","CACHED_ALREADY_STARTED_ERROR","#unwindFailedStart"],"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 { isExpectedRejection } from \"./namespaces/NavigationNamespace/constants\";\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/**\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 suppressor for fire-and-forget `start()`. It logs through THIS\n * router's logger (built in the constructor), so it cannot be static (#724).\n *\n * Only start, since Step 0: the navigate/navigateToState/navigateToDefault\n * suppressor moved to `NavigationNamespace`, which is where those promises are\n * created and therefore the only layer that knows which of them are already\n * pre-suppressed. Start keeps its own because it suppresses a promise the\n * FACADE builds (`internalStart.catch(#unwindFailedStart)`), and because the\n * #931 category split survives — start failures log under \"router.start\" (a\n * start interceptor throwing a plain Error after next() committed, #763, or a\n * cryptic path TypeError — neither a suppressed RouterError). Both sides still\n * classify through ONE shared policy, `isExpectedRejection`.\n */\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 suppressor (see the field declaration): it\n // logs through THIS router's logger, so it is built here, not static.\n this.#onSuppressedStartError = (error: unknown): void => {\n if (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). Fire-and-forget safe like the\n // public facade methods — popstate handlers call it without awaiting —\n // but the safety now belongs to the namespace that creates the promise,\n // so this closure only owes callers the Promise shape.\n this.#assertNotReentrant();\n\n return Router.#asPromise(\n this.#navigation.navigateToState(state, navOpts ?? EMPTY_OPTS),\n );\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 /**\n * ONE fire-and-forget checkpoint for `start()`, deliberately — the same shape\n * `NavigationNamespace.#settle` gives the navigate family, and for the same\n * reason: a `.catch()` remembered at each `return` site is a thing that can be\n * forgotten, and a forgotten one is invisible until it leaks.\n *\n * It HAD been forgotten (#1605). The `ALREADY_STARTED` rejection left through\n * an early `return` above the suppressor, so a second, unawaited `start()`\n * raised an `unhandledRejection` — process-fatal under Node 22+'s default\n * `--unhandled-rejections=throw`, with a stack pointing at the cached error's\n * module constant rather than at the caller. Every return site now leaves\n * through `#runStart`, so no future early return can reopen it.\n */\n start(startPath: string): Promise<State> {\n const promiseState = this.#runStart(startPath);\n\n promiseState.catch(this.#onSuppressedStartError);\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 return Router.#asPromise(\n this.#navigation.navigate(\n routeName,\n routeParams ?? EMPTY_PARAMS,\n search,\n opts,\n ),\n );\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 return Router.#asPromise(this.#navigation.navigateToDefault(opts));\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 * Hands the namespace's result back as the `Promise<State>` the public API\n * owes, and does nothing else.\n *\n * A non-Promise means the navigation already settled synchronously — the\n * return TYPE says so, which is what retired `lastSyncResolved`. Suppression is\n * not the facade's business any more: the namespace attaches it where the\n * promise is created, the only layer that can tell a fresh rejection from one\n * of its own pre-suppressed singletons.\n *\n * The Promise wrap is not a new cost — the namespace used to allocate exactly\n * this one and return it.\n */\n static #asPromise(result: State | Promise<State>): Promise<State> {\n return result instanceof Promise ? result : Promise.resolve(result);\n }\n\n #runStart(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 return internalStart.catch((error: unknown) =>\n this.#unwindFailedStart(error),\n );\n }\n\n /**\n * Rejects a synchronous reentrant navigation — `navigate` /\n * `navigateToDefault` / `navigateToState` / `navigateToNotFound` called from\n * inside a navigation core has not finished with. Throws synchronously: inside\n * a listener the emit's `onListenerError` isolation surfaces it (visible,\n * non-fatal); a DEFERRED (async / microtask) navigate runs after the window\n * closes and is allowed. Always-on core invariant guard (not validator-gated).\n *\n * TWO windows, because application code runs in two places core does not\n * control, on opposite sides of the announce:\n *\n * - **Dispatch** (`isProcessing`) — a transition-event listener, mid-emit\n * (RFC navigation-cancellation-unification §4).\n * - **Pre-start** (`isPreparing`, #1610) — a `forwardState` / `buildPath`\n * interceptor or a route codec, BEFORE the first emit. The dispatch depth\n * cannot see it: there has been no emit yet, which is exactly how a nested\n * `navigate()` used to run to completion here, commit a phantom\n * `TRANSITION_SUCCESS`, and shift the outer transition's `fromState`.\n *\n * A guard is deliberately NOT either of them: it runs after the announce, so\n * the classic guard-redirect (`navigate(...)` then `return false`) stays a\n * plain supersede.\n */\n #assertNotReentrant(): void {\n if (this.#eventBus.isProcessing() || this.#navigation.isPreparing()) {\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":"wtCAiEM,EAA0C,OAAO,OAAO,CAAC,CAAC,EAkBhE,IAAa,EAAb,MAAa,CAE8B,CAOzC,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GAEA,GAgBA,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,IAAIW,EAAAA,aAAa,CAAY,EAI5C,KAAKD,GAA2B,GAAyB,CACnDE,EAAAA,oBAAoB,CAAK,GAI7B,EAAO,MAAM,eAAgB,yBAA0B,CAAK,CAC9D,EAOA,EAAA,iBAAiB,wBAAwB,CAAO,EAGhD,EAAA,kBAAkB,CAAY,EAG1B,EAAO,OAAS,GAClB,EAAA,oBAAoB,CAAM,EAO5B,KAAKZ,GAAW,IAAIa,EAAAA,iBAAiB,CAAa,EAClD,KAAKZ,GAAUa,EAAAA,aAAa,EAAc,MAAM,EAChD,KAAKZ,GACHa,EAAAA,wBAAsC,CAAY,EACpD,KAAKZ,GAAS,IAAIa,EAAAA,eAClB,KAAK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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,IAAI8B,EAAAA,YAAYC,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"}
|
package/dist/cjs/RouterError.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./constants.js"),t=new Set(Object.values(e.errorCodes)),n=new Set([`code`,`segment`,`path`]),r=new Set([`setCode`,`setErrorInstance`,`setAdditionalFields`,`hasField`,`getField`,`toJSON`]);var i=class extends Error{segment;path;code;constructor(e,{message:t,segment:i,path:a,...o}={}){super(t??e),this.name=`RouterError`,this.code=e,this.segment=i,this.path=a;for(let[e,t]of Object.entries(o)){if(n.has(e))throw TypeError(`[RouterError] Cannot set reserved property "${e}"`);r.has(e)||(this[e]=t)}}setCode(e){this.code=e,t.has(this.message)&&(this.message=e)}setErrorInstance(e){if(!e)throw TypeError(`[RouterError.setErrorInstance] err parameter is required and must be an Error instance`);this.message=e.message,this.cause=e.cause,this.stack=e.stack??``}setAdditionalFields(e){for(let[t,i]of Object.entries(e)){if(n.has(t))throw TypeError(`[RouterError.setAdditionalFields] Cannot set reserved property "${t}"`);r.has(t)||(this[t]=i)}}hasField(e){return e in this}getField(e){return this[e]}toJSON(){let e={code:this.code,message:this.message};this.segment!==void 0&&(e.segment=this.segment),this.path!==void 0&&(e.path=this.path);let t=new Set([`code`,`message`,`segment`,`path`,`stack`,`name`]);for(let n in this)Object.hasOwn(this,n)&&!t.has(n)&&(e[n]=this[n]);return e}};exports.RouterError=i;
|
|
2
|
-
//# sourceMappingURL=RouterError.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"RouterError.js","names":["errorCodes"],"sources":["../../src/RouterError.ts"],"sourcesContent":["// packages/core/src/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\nconst errorCodeValues = new Set(Object.values(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with RouterError interface in core-types\n readonly segment: string | undefined;\n readonly path: string | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n // Subclasses don't auto-set `name`; without this `error.name` inherits\n // \"Error\", breaking `error.name === \"RouterError\"` checks at catch sites that\n // can't `instanceof` across bundle boundaries.\n this.name = \"RouterError\";\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of Object.entries(rest)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw new TypeError(\n \"[RouterError.setErrorInstance] err parameter is required and must be an Error instance\",\n );\n }\n\n this.message = err.message;\n this.cause = err.cause;\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of Object.entries(fields)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError.setAdditionalFields] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\", { segment: \"users\" });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"userId\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n return key in this;\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n return this[key];\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"stack\",\n // `name` is now an own enumerable prop (constructor sets it to\n // \"RouterError\"); it's class metadata, not a custom field — keep it out of\n // the serialized output (preserves toJSON shape).\n \"name\",\n ]);\n\n for (const key in this) {\n if (Object.hasOwn(this, key) && !excludeKeys.has(key)) {\n result[key] = this[key];\n }\n }\n\n return result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,KAAK,UAAY,IAAA,KACnB,EAAO,QAAU,KAAK,SAEpB,KAAK,OAAS,IAAA,KAChB,EAAO,KAAO,KAAK,MAMrB,IAAM,EAAc,IAAI,IAAI,CAC1B,OACA,UACA,UACA,OACA,QAIA,MACF,CAAC,EAED,IAAK,IAAM,KAAO,KACZ,OAAO,OAAO,KAAM,CAAG,GAAK,CAAC,EAAY,IAAI,CAAG,IAClD,EAAO,GAAO,KAAK,IAIvB,OAAO,CACT,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../constants.js"),t=require("../internals.js"),n=require("../engine/operations/routeTreeToDefinitions.js"),r=require("../namespaces/RoutesNamespace/helpers.js"),i=require("../RouterError.js"),a=require("../Router.js"),o=require("./getLifecycleApi.js");function s(s,c,l){let u=t.getInternals(s);if(u.isDisposed())throw new i.RouterError(e.errorCodes.ROUTER_DISPOSED);u.validator?.dependencies.validateCloneArgs(c);let d=u.routeGetStore(),f=n.routeTreeToDefinitions(d.tree),p=d.config,m=d.resolvedForwardMap,h=d.routeCustomFields,{options:g,dependencies:_,pluginFactories:v,loggerConfig:y}=u.getCloneState(),{definition:b,external:x}=d.lifecycleNamespace.getFactoriesByOrigin(),S={..._,...c},C=l?.logger?{...y,...l.logger}:y,w=new a.Router(f,{...g,logger:C},S),T=t.getInternals(w),E=T.routeGetStore(),D=E.lifecycleNamespace;r.assignConfigEntries(E.config,p),Object.assign(E.resolvedForwardMap,m),Object.assign(E.routeCustomFields,h),d.rootPath!==``&&T.setRootPath(d.rootPath);let[O,k]=b,[A,j]=x;for(let[e,t]of Object.entries(O))D.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(k))D.addCanActivate(e,t,!0);let M=o.getLifecycleApi(w);for(let[e,t]of Object.entries(A))M.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(j))M.addActivateGuard(e,t);let N=new Set(T.getCloneState().pluginFactories),P=v.filter(e=>!N.has(e));return P.length>0&&w.usePlugin(...P),w}exports.cloneRouter=s;
|
|
2
|
-
//# sourceMappingURL=cloneRouter.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloneRouter.js","names":["getInternals","RouterError","errorCodes","routeTreeToDefinitions","RouterClass","getLifecycleApi"],"sources":["../../../src/api/cloneRouter.ts"],"sourcesContent":["import { errorCodes } from \"../constants\";\nimport { routeTreeToDefinitions } from \"../engine\";\nimport { getInternals } from \"../internals\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\n\nimport type {\n DefaultDependencies,\n LoggerConfig,\n Router,\n Route,\n} from \"../types\";\n\n/**\n * Per-clone overrides beyond dependencies.\n */\nexport interface CloneOptions {\n /**\n * Per-clone logger config override, merged **over** the base router's resolved\n * logger config. Primary use: per-request `traceId` in SSR — a fresh\n * `callback` closed over the request id, while `level` inherits the base.\n * Omitted keys inherit the base (level / callback / callbackIgnoresLevel).\n *\n * Override is by **config**, not a logger instance: `RouterLogger` is\n * core-internal (only its `{ log, warn, error }` interface is public), so\n * nothing outside core constructs one — configuration is the whole surface.\n */\n logger?: Partial<LoggerConfig>;\n}\n\n/**\n * Build an independent router instance that shares the route tree, options,\n * lifecycle guards, and plugin factories of `router`. The primary use case\n * is **SSR multi-tenancy** — one base router per process, one clone per\n * request.\n *\n * @param router - Source router (must not be disposed).\n * @param dependencies - Optional per-clone overrides merged on top of the\n * base router's dependencies. Always **fresh per call** in the documented\n * SSR pattern: pass per-request state here, never store it in the base.\n *\n * @remarks\n *\n * **Dependency merge — shallow by design.** `base.dependencies` are spread\n * into the clone via `{ ...sourceDeps, ...dependencies }`. Top-level keys\n * are new objects, but **values are shared by reference**: a `Map`, `Set`,\n * class instance, function, or nested plain object stored in\n * `base.dependencies` is the **same instance** in every clone. Mutations\n * in one clone are visible in the base and in every sibling clone.\n *\n * This is intentional. `structuredClone` of dep values is **not** applied\n * because it would:\n * - strip class prototypes (`new DbClient()` → plain object, methods lost)\n * - reject functions and symbols (`DataCloneError`)\n * - fragment singleton pools (one connection pool per request — pool\n * semantics destroyed)\n * - reject circular references\n *\n * **SSR rule of thumb.** Place values in `base.dependencies` according to\n * their lifecycle:\n *\n * - **Singletons / shared services** → `base.dependencies`. Examples: DB\n * client, connection pool, logger, config, feature-flag client. Process-\n * wide pooling depends on sharing these by reference.\n * - **Per-request state** → the `dependencies` override parameter (or\n * `createRequestScope`'s `deps` argument). Examples: `currentUser`,\n * `traceId`, `sessionId`, `abortSignal`. The override is applied last,\n * so it wins over base keys; pass a fresh object per call.\n *\n * Cross-request data leaks are **only possible** when per-request mutable\n * state is incorrectly placed in `base.dependencies`. The override slot is\n * the safe channel.\n *\n * @example\n * ```typescript\n * // Server boot — singletons only\n * const base = createRouter(routes, options, {\n * db: new DbClient(dbUrl),\n * logger,\n * });\n *\n * // Per request — fresh override per call\n * const clone = cloneRouter(base, {\n * currentUser,\n * traceId,\n * });\n * // clone.deps.db === base.deps.db ✓ shared pool (intentional)\n * // clone.deps.currentUser ✓ unique per request\n * ```\n *\n * @see createRequestScope — `@real-router/ssr-utils` SSR helper that\n * wraps this function and injects `abortSignal` automatically.\n */\nexport function cloneRouter<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n dependencies?: Dependencies,\n opts?: CloneOptions,\n): RouterClass<Dependencies> {\n const ctx = getInternals(router);\n\n if (ctx.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n ctx.validator?.dependencies.validateCloneArgs(dependencies);\n\n // Get source store directly\n const sourceStore = ctx.routeGetStore();\n const routes = routeTreeToDefinitions(sourceStore.tree);\n const routeConfig = sourceStore.config;\n const resolvedForwardMap = sourceStore.resolvedForwardMap;\n const routeCustomFields = sourceStore.routeCustomFields;\n\n const {\n options,\n dependencies: sourceDeps,\n pluginFactories,\n loggerConfig,\n } = ctx.getCloneState();\n // Origin-aware factory snapshot — definition guards are re-registered with\n // `isFromDefinition=true` on the clone so `replace()` can still strip them\n // via `clearDefinitionGuards()`. External guards take the public lifecycle\n // API path so they survive `replace()` symmetric with the base.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const sourceLifecycleNamespace = sourceStore.lifecycleNamespace!;\n const { definition: definitionFactories, external: externalFactories } =\n sourceLifecycleNamespace.getFactoriesByOrigin();\n\n const mergedDeps = {\n ...sourceDeps,\n ...dependencies,\n } as Dependencies;\n\n // The clone builds its OWN logger (isolation, #724) but INHERITS the base's\n // resolved config — frozen options don't carry `logger`, so without this the\n // clone would fall back to the default logger and lose the base's\n // callback/level (an M1 regression the singleton used to mask). A per-request\n // `opts.logger` override (e.g. a traceId-bound callback) merges on top.\n const clonedLoggerConfig: Partial<LoggerConfig> = opts?.logger\n ? { ...loggerConfig, ...opts.logger }\n : loggerConfig;\n\n const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n { ...options, logger: clonedLoggerConfig },\n mergedDeps,\n );\n\n const newCtx = getInternals(newRouter);\n const newStore = newCtx.routeGetStore();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const newLifecycleNamespace = newStore.lifecycleNamespace!;\n\n // Copy the source config + store-level maps BEFORE re-registering guards\n // (#1331 review): the definition-guard factories re-executed below must\n // observe the fully-built clone (encoders/decoders/defaultParams/custom\n // fields), mirroring the constructor where flushPendingGuards runs after the\n // store is complete. The five RouteConfig sub-maps go through a single\n // enumeration so a newly added config field is carried over automatically\n // (#965); resolvedForwardMap and routeCustomFields are store-level (not part\n // of RouteConfig) and stay explicit.\n assignConfigEntries(newStore.config, routeConfig);\n Object.assign(newStore.resolvedForwardMap, resolvedForwardMap);\n Object.assign(newStore.routeCustomFields, routeCustomFields);\n\n // #1175: carry the source rootPath. It lives in the store (not options/config),\n // and neither routeTreeToDefinitions nor getCloneState include it — so a clone\n // of a base configured with `setRootPath(\"/app\")` would otherwise build/match\n // under \"\" and 404 every request of a sub-path SSR deployment. setRootPath\n // rebuilds the tree in place with the just-copied config; the rebuild is only\n // paid when a rootPath is actually set, and it runs before the definition-guard\n // factories below so they observe the fully-built clone (rootPath included).\n if (sourceStore.rootPath !== \"\") {\n newCtx.setRootPath(sourceStore.rootPath);\n }\n\n const [definitionDeactivate, definitionActivate] = definitionFactories;\n const [externalDeactivate, externalActivate] = externalFactories;\n\n for (const [name, handler] of Object.entries(definitionDeactivate)) {\n newLifecycleNamespace.addCanDeactivate(name, handler, true);\n }\n\n for (const [name, handler] of Object.entries(definitionActivate)) {\n newLifecycleNamespace.addCanActivate(name, handler, true);\n }\n\n const lifecycle = getLifecycleApi(newRouter);\n\n for (const [name, handler] of Object.entries(externalDeactivate)) {\n lifecycle.addDeactivateGuard(name, handler);\n }\n\n for (const [name, handler] of Object.entries(externalActivate)) {\n lifecycle.addActivateGuard(name, handler);\n }\n\n // Plugin replay runs last and skips factories that a (contract-violating)\n // definition-guard factory already registered on the clone during the\n // re-compilation above — without the filter every clone would double-apply\n // such a plugin: once via the factory, once via this replay (#1331 review).\n const alreadyRegistered = new Set(newCtx.getCloneState().pluginFactories);\n const pluginsToReplay = pluginFactories.filter(\n (factory) => !alreadyRegistered.has(factory),\n );\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `usePlugin(...[])` with an empty spread is a no-op, so entering the block on an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips a real plugin list and is killable.)\n if (pluginsToReplay.length > 0) {\n newRouter.usePlugin(...pluginsToReplay);\n }\n\n return newRouter;\n}\n"],"mappings":"6QA+FA,SAAgB,EAGd,EACA,EACA,EAC2B,CAC3B,IAAM,EAAMA,EAAAA,aAAa,CAAM,EAE/B,GAAI,EAAI,WAAW,EACjB,MAAM,IAAIC,EAAAA,YAAYC,EAAAA,WAAW,eAAe,EAGlD,EAAI,WAAW,aAAa,kBAAkB,CAAY,EAG1D,IAAM,EAAc,EAAI,cAAc,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AC,EAAkB,IAAI,CAAO,CAC7C,EAOA,OAJI,EAAgB,OAAS,GAC3B,EAAU,UAAU,GAAG,CAAe,EAGjC,CACT"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../internals.js"),t=require("./helpers.js");function n(e,t,n,r){if(n!==void 0){if(!Object.hasOwn(e.dependencies,t))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let i=e.dependencies[t];i!==n&&!(Number.isNaN(i)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(t,`setDependency`)}e.dependencies[t]=n}}function r(e,t,n){let r=[];for(let i in t)t[i]!==void 0&&(Object.hasOwn(e.dependencies,i)?r.push(i):n?.dependencies.validateDependencyCount(e,`setDependencies`),e.dependencies[i]=t[i]);r.length>0&&n?.dependencies.warnBatchOverwrite(r,`setDependencies`)}function i(i){let a=e.getInternals(i);return{get:e=>{a.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=a.dependenciesGetStore(),n=t.dependencies[e];return a.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>({...a.dependenciesGetStore().dependencies}),set:(e,r)=>{t.throwIfDisposed(a.isDisposed),a.validator?.dependencies.validateSetDependencyArgs(e,r,`setDependency`),n(a.dependenciesGetStore(),e,r,a.validator)},setAll:e=>{t.throwIfDisposed(a.isDisposed);let n=a.dependenciesGetStore();a.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),r(n,e,a.validator)},remove:e=>{t.throwIfDisposed(a.isDisposed),a.validator?.dependencies.validateDependencyName(e,`removeDependency`);let n=a.dependenciesGetStore();Object.hasOwn(n.dependencies,e)||a.validator?.dependencies.warnRemoveNonExistent(e),delete n.dependencies[e]},reset:()=>{t.throwIfDisposed(a.isDisposed);let e=a.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(a.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(a.dependenciesGetStore().dependencies,e))}}exports.getDependenciesApi=i;
|
|
2
|
-
//# sourceMappingURL=getDependenciesApi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getDependenciesApi.js","names":["getInternals"],"sources":["../../../src/api/getDependenciesApi.ts"],"sourcesContent":["import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { DependenciesApi } from \"./types\";\nimport type { DependenciesStore } from \"../namespaces\";\nimport type { DefaultDependencies, Router } from \"../types\";\nimport type { RouterValidator } from \"../types/RouterValidator\";\n\n// =============================================================================\n// Module-private CRUD functions\n// =============================================================================\n\nfunction setDependency(\n store: DependenciesStore,\n dependencyName: string,\n dependencyValue: unknown,\n validator?: RouterValidator | null,\n): void {\n // undefined = \"don't set\" (feature for conditional setting)\n if (dependencyValue === undefined) {\n return;\n }\n\n const isNewKey = !Object.hasOwn(store.dependencies, dependencyName);\n\n if (isNewKey) {\n // Only check limit when adding new keys (overwrites don't increase count)\n validator?.dependencies.validateDependencyCount(store, \"setDependency\");\n } else {\n const oldValue = (store.dependencies as Record<string, unknown>)[\n dependencyName\n ];\n const isChanging = oldValue !== dependencyValue;\n // Special case for NaN idempotency (NaN !== NaN is always true)\n const bothAreNaN = Number.isNaN(oldValue) && Number.isNaN(dependencyValue);\n\n if (isChanging && !bothAreNaN) {\n validator?.dependencies.warnOverwrite(dependencyName, \"setDependency\");\n }\n }\n\n (store.dependencies as Record<string, unknown>)[dependencyName] =\n dependencyValue;\n}\n\nfunction setMultipleDependencies(\n store: DependenciesStore,\n deps: Record<string, unknown>,\n validator?: RouterValidator | null,\n): void {\n const overwrittenKeys: string[] = [];\n\n for (const key in deps) {\n if (deps[key] === undefined) {\n continue;\n }\n\n if (Object.hasOwn(store.dependencies, key)) {\n overwrittenKeys.push(key);\n } else {\n validator?.dependencies.validateDependencyCount(store, \"setDependencies\");\n }\n\n (store.dependencies as Record<string, unknown>)[key] = deps[key];\n }\n\n if (overwrittenKeys.length > 0) {\n validator?.dependencies.warnBatchOverwrite(\n overwrittenKeys,\n \"setDependencies\",\n );\n }\n}\n\n// =============================================================================\n// Public API factory\n// =============================================================================\n\nexport function getDependenciesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): DependenciesApi<Dependencies> {\n const ctx = getInternals(router);\n\n return {\n get: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"getDependency\");\n\n const store = ctx.dependenciesGetStore();\n const value = (store.dependencies as Record<string, unknown>)[\n name as string\n ];\n\n ctx.validator?.dependencies.validateDependencyExists(\n name as string,\n store,\n );\n\n return value as Dependencies[typeof name];\n },\n getAll: () => ({ ...ctx.dependenciesGetStore().dependencies }),\n set: (name, value) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateSetDependencyArgs(\n name,\n value,\n \"setDependency\",\n );\n\n setDependency(ctx.dependenciesGetStore(), name, value, ctx.validator);\n },\n setAll: (deps) => {\n throwIfDisposed(ctx.isDisposed);\n\n const store = ctx.dependenciesGetStore();\n\n ctx.validator?.dependencies.validateDependenciesObject(\n deps,\n \"setDependencies\",\n );\n\n setMultipleDependencies(\n store,\n deps as Record<string, unknown>,\n ctx.validator,\n );\n },\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.dependencies.validateDependencyName(\n name,\n \"removeDependency\",\n );\n\n const store = ctx.dependenciesGetStore();\n\n if (!Object.hasOwn(store.dependencies, name)) {\n ctx.validator?.dependencies.warnRemoveNonExistent(name);\n }\n\n delete (store.dependencies as Record<string, unknown>)[name as string];\n },\n reset: () => {\n throwIfDisposed(ctx.isDisposed);\n const store = ctx.dependenciesGetStore();\n\n store.dependencies = Object.create(null) as Partial<Dependencies>;\n },\n has: (name) => {\n ctx.validator?.dependencies.validateDependencyName(name, \"hasDependency\");\n\n return Object.hasOwn(ctx.dependenciesGetStore().dependencies, name);\n },\n };\n}\n"],"mappings":"6DAYA,SAAS,EACP,EACA,EACA,EACA,EACM,CAEF,OAAoB,IAAA,GAMxB,IAAI,CAFc,OAAO,OAAO,EAAM,a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,EAE9B,EAAI,WAAW,aAAa,uBAC1B,EACA,kBACF,EAEA,IAAM,EAAQ,EAAI,qBAAqB,EAElC,OAAO,OAAO,EAAM,aAAc,CAAI,GACzC,EAAI,WAAW,aAAa,sBAAsB,CAAI,EAGxD,OAAQ,EAAM,aAAyC,EACzD,EACA,UAAa,CACX,EAAA,gBAAgB,EAAI,UAAU,EAC9B,IAAM,EAAQ,EAAI,qBAAqB,EAEvC,EAAM,aAAe,OAAO,OAAO,IAAI,CACzC,EACA,IAAM,IACJ,EAAI,WAAW,aAAa,uBAAuB,EAAM,eAAe,EAEjE,OAAO,OAAO,EAAI,qBAAqB,CAAC,CAAC,aAAc,CAAI,EAEtE,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../internals.js"),t=require("./helpers.js");function n(n){let r=e.getInternals(n),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,n){t.throwIfDisposed(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(n,`addActivateGuard`),i.addCanActivate(e,n)},addDeactivateGuard(e,n){t.throwIfDisposed(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(n,`addDeactivateGuard`),i.addCanDeactivate(e,n)},removeActivateGuard(e){t.throwIfDisposed(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){t.throwIfDisposed(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}exports.getLifecycleApi=n;
|
|
2
|
-
//# sourceMappingURL=getLifecycleApi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getLifecycleApi.js","names":["getInternals"],"sources":["../../../src/api/getLifecycleApi.ts"],"sourcesContent":["import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"../types\";\n\nexport function getLifecycleApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): LifecycleApi<Dependencies> {\n const ctx = getInternals(router);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycleNamespace = ctx.routeGetStore().lifecycleNamespace!;\n\n return {\n addActivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addActivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addActivateGuard\");\n\n // Handler-limit enforcement lives at the namespace registration choke point\n // (RouteLifecycleNamespace.#registerHandler) so all paths are bounded\n // uniformly — see #961.\n lifecycleNamespace.addCanActivate(name, handler);\n },\n\n addDeactivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addDeactivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addDeactivateGuard\");\n\n lifecycleNamespace.addCanDeactivate(name, handler);\n },\n\n removeActivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeActivateGuard\");\n\n // Inverse of addActivateGuard (external): clears only the external guard;\n // a route-config (definition) canActivate survives (#1171).\n lifecycleNamespace.clearCanActivate(name, \"external\");\n },\n\n removeDeactivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeDeactivateGuard\");\n\n // Inverse of addDeactivateGuard (external): clears only the external guard;\n // a route-config (definition) canDeactivate survives (#1171).\n lifecycleNamespace.clearCanDeactivate(name, \"external\");\n },\n };\n}\n"],"mappings":"6DAMA,SAAgB,EAEd,EAA0D,CAC1D,IAAM,EAAMA,EAAAA,aAAa,CAAM,EAEzB,EAAqB,EAAI,cAAc,CAAC,CAAC,mBAE/C,MAAO,CACL,iBAAiB,EAAM,EAAS,CAC9B,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,OAAO,kBAAkB,EAAM,kBAAkB,EAChE,EAAI,WAAW,UAAU,gBAAgB,EAAS,kBAAkB,EAKpE,EAAmB,eAAe,EAAM,CAAO,CACjD,EAEA,mBAAmB,EAAM,EAAS,CAChC,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,OAAO,kBAAkB,EAAM,oBAAoB,EAClE,EAAI,WAAW,UAAU,gBAAgB,EAAS,oBAAoB,EAEtE,EAAmB,iBAAiB,EAAM,CAAO,CACnD,EAEA,oBAAoB,EAAM,CACxB,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,OAAO,kBAAkB,EAAM,qBAAqB,EAInE,EAAmB,iBAAiB,EAAM,UAAU,CACtD,EAEA,sBAAsB,EAAM,CAC1B,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,OAAO,kBAAkB,EAAM,uBAAuB,EAIrE,EAAmB,mBAAmB,EAAM,UAAU,CACxD,CACF,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
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
|
-
//# sourceMappingURL=getPluginApi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
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,IACd,EAAI,WAAW,WAAW,0BACxB,EACA,iBACF,EAGK,EAAI,gBAAgB,EAAO,CAAO,GAE3C,YAAc,GAAa,CACzB,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,OAAO,wBAAwB,CAAQ,EAEtD,EAAI,YAAY,CAAQ,CAC1B,EACA,YAAa,EAAI,YACjB,kBAAmB,EAAW,KAC5B,EAAA,gBAAgB,EAAI,UAAU,EAE9B,EAAI,WAAW,SAAS,qBAAqB,EAAW,CAAE,EAEnD,EAAI,iBAAiB,EAAW,CAAE,GAE3C,sBAAuB,EAAM,EAAS,CAAC,EAAG,EAAS,CAAC,IAAM,CACxD,EAAA,uBAAuB,EAAK,uBAAw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gB,KAChC,OAAQ,EAAmC,GAG7C,IAAM,EAAM,EAAI,iBAAiB,QAAQ,CAAe,EAGpD,IAAQ,IACV,EAAI,iBAAiB,OAAO,EAAK,CAAC,CAEtC,CACF,EACA,oBAAsB,GAAU,CAC9B,EAAA,gBAAgB,EAAI,UAAU,EAC9B,EAAI,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,2 +0,0 @@
|
|
|
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
|
-
//# sourceMappingURL=getRoutesApi.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"getRoutesApi.js","names":["buildAddArtifacts","buildReplaceArtifacts","compileArtifactGuards","getTransitionPath","removeFromDefinitions","nodeToDefinition","getInternals","validateRemoveRoute","commitRouteUpdate","validateClearRoutes"],"sources":["../../../src/api/getRoutesApi.ts"],"sourcesContent":["import { nodeToDefinition } from \"../engine\";\nimport { throwIfDisposed, throwIfReentrantTreeMutation } from \"./helpers\";\nimport { guardRouteStructure } from \"../guards\";\nimport { getInternals } from \"../internals\";\nimport {\n assertRouteDefaultChannelsFor,\n clearConfigEntries,\n removeFromDefinitions,\n} from \"../namespaces/RoutesNamespace/helpers\";\nimport {\n validateClearRoutes,\n validateRemoveRoute,\n} from \"../namespaces/RoutesNamespace/routeGuards\";\nimport {\n adoptRouteArtifacts,\n assertAddable,\n assertNoDuplicateNamesInBatch,\n assertNoDuplicatePathsInBatch,\n assertNoInternalNamesInBatch,\n assertNoInternalRouteName,\n buildAddArtifacts,\n buildReplaceArtifacts,\n commitRouteUpdate,\n commitTreeChanges,\n compileArtifactGuards,\n resetStore,\n} from \"../namespaces/RoutesNamespace/routesStore\";\nimport { getTransitionPath } from \"../transitionPath\";\n\nimport type { RoutesApi } from \"./types\";\nimport type { RouteDefinition, RouteTree } from \"../engine\";\nimport type { RouterInternals } from \"../internals\";\nimport type { RouteLifecycleNamespace, RouteConfig } from \"../namespaces\";\nimport type { RoutesStore } from \"../namespaces/RoutesNamespace\";\nimport type {\n DefaultDependencies,\n ForwardToCallback,\n NavigationOptions,\n Params,\n ParamsSearch,\n SearchParams,\n Router,\n RouterLogger,\n State,\n TreeChangedEvent,\n TreeStructuralPatch,\n GuardFnFactory,\n Route,\n} from \"../types\";\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/**\n * Opts attached to the `TRANSITION_SUCCESS` emitted by `replace()` when it\n * revalidates the active state (#950). `replace` does not push history, so it\n * is a replace-type success — matching `navigateToNotFound`'s opts for the\n * dropped-route branch.\n */\nconst REVALIDATE_OPTS: NavigationOptions = Object.freeze({\n replace: true,\n revalidate: true,\n});\n\n/**\n * Clears all config entries and lifecycle handlers for a removed route\n * (and all its descendants).\n */\nfunction clearRouteConfigurations<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeName: string,\n config: RouteConfig,\n routeCustomFields: Record<string, Record<string, unknown>>,\n lifecycleNamespace: RouteLifecycleNamespace<Dependencies>,\n): void {\n const shouldClear = (name: string): boolean =>\n name === routeName || name.startsWith(`${routeName}.`);\n\n clearConfigEntries(config.decoders, shouldClear);\n clearConfigEntries(config.encoders, shouldClear);\n clearConfigEntries(config.defaultParams, shouldClear);\n clearConfigEntries(config.defaultSearch, shouldClear);\n clearConfigEntries(config.forwardMap, shouldClear);\n clearConfigEntries(config.forwardFnMap, shouldClear);\n clearConfigEntries(routeCustomFields, shouldClear);\n\n // Clear forwardMap entries pointing TO the deleted route (or its descendants)\n clearConfigEntries(config.forwardMap, (key) =>\n shouldClear(config.forwardMap[key]),\n );\n\n // Clear lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n lifecycleNamespace.getFactories();\n\n for (const name of Object.keys(canActivateFactories)) {\n if (shouldClear(name)) {\n // Route removed from the tree — both origin slots go (route no longer exists).\n lifecycleNamespace.clearCanActivate(name, \"both\");\n }\n }\n\n for (const name of Object.keys(canDeactivateFactories)) {\n if (shouldClear(name)) {\n lifecycleNamespace.clearCanDeactivate(name, \"both\");\n }\n }\n}\n\n/**\n * Re-attaches the stored config (forwardTo / defaultParams / encode-decode) and\n * lifecycle guards for `lookupName` onto `route`, then returns it (mutates in\n * place). Shared by {@link enrichRoute} (nested, bare `name`) and\n * {@link buildFlatRoute} (flat, full dotted `name`) — one source of truth for\n * the route-config field set.\n */\nfunction assignRouteConfig<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n route: Route<Dependencies>,\n lookupName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const forwardToFn = config.forwardFnMap[lookupName];\n const forwardToStr = config.forwardMap[lookupName];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (forwardToFn !== undefined) {\n route.forwardTo = forwardToFn;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n } else if (forwardToStr !== undefined) {\n route.forwardTo = forwardToStr;\n }\n\n if (lookupName in config.defaultParams) {\n route.defaultParams = config.defaultParams[lookupName];\n }\n\n if (lookupName in config.defaultSearch) {\n route.defaultSearch = config.defaultSearch[lookupName];\n }\n\n if (lookupName in config.decoders) {\n route.decodeParams = config.decoders[lookupName];\n }\n\n if (lookupName in config.encoders) {\n route.encodeParams = config.encoders[lookupName];\n }\n\n const [canDeactivateFactories, canActivateFactories] = factories;\n\n if (lookupName in canActivateFactories) {\n route.canActivate = canActivateFactories[lookupName];\n }\n\n if (lookupName in canDeactivateFactories) {\n route.canDeactivate = canDeactivateFactories[lookupName];\n }\n\n return route;\n}\n\n/**\n * Builds a full Route object from a bare RouteDefinition by re-attaching\n * config entries and lifecycle factories.\n *\n * RECURSIVE — call with the factories tuple obtained ONCE from\n * `lifecycleNamespace.getFactories()` and pass it through to children.\n */\nfunction enrichRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routeDef: RouteDefinition,\n routeName: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = {\n name: routeDef.name,\n path: routeDef.path,\n };\n\n assignRouteConfig(route, routeName, config, factories);\n\n if (routeDef.children) {\n route.children = routeDef.children.map((child) =>\n enrichRoute(child, `${routeName}.${child.name}`, config, factories),\n );\n }\n\n return route;\n}\n\n// ============================================================================\n// TREE_CHANGED payload helpers\n// ============================================================================\n\n/**\n * Builds a single FLAT `Route` for `fullName` from the store config + lifecycle\n * factories — `name` is the FULL dotted name and there is no `children` array\n * (consumers want a flat, by-name list). Frozen on construction.\n */\nfunction buildFlatRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n fullName: string,\n path: string,\n config: RouteConfig,\n factories: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ],\n): Route<Dependencies> {\n const route: Route<Dependencies> = { name: fullName, path };\n\n assignRouteConfig(route, fullName, config, factories);\n\n return Object.freeze(route);\n}\n\n/**\n * Walks the store's definitions depth-first, building a FLAT\n * `Map<fullName, Route>` for every node whose full dotted name satisfies\n * `include`. Reads the live store, so call it at the right moment relative to\n * the mutation (before for removed, after for added).\n */\nfunction collectFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n include: (fullName: string) => boolean,\n): Map<string, Route<Dependencies>> {\n const result = new Map<string, Route<Dependencies>>();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n\n const walk = (defs: readonly RouteDefinition[], parentName: string): void => {\n for (const def of defs) {\n const fullName = parentName ? `${parentName}.${def.name}` : def.name;\n\n if (include(fullName)) {\n result.set(\n fullName,\n buildFlatRoute(fullName, def.path, store.config, factories),\n );\n }\n\n if (def.children) {\n walk(def.children, fullName);\n }\n }\n };\n\n walk(store.definitions, \"\");\n\n return result;\n}\n\n/**\n * Collects the route `name` and all of its descendants as a FLAT, frozen array.\n * MUST be called BEFORE the removal mutation — the nodes are gone afterwards.\n */\nfunction collectSubtree<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): readonly Route<Dependencies>[] {\n const prefix = `${name}.`;\n const subtree = collectFlatRoutes(\n store,\n (fullName) => fullName === name || fullName.startsWith(prefix),\n );\n\n return Object.freeze([...subtree.values()]);\n}\n\n/**\n * Builds the FLAT, frozen payload array for an `add`, walking only the input\n * routes — O(added), not O(tree). `path` is taken from the input verbatim\n * (`sanitizeRoute` never rewrites it); config fields are read from the\n * post-commit store by full name. `add` never removes, so the input subtree is\n * exactly what changed.\n */\nfunction collectAddedRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n parentName: string | undefined,\n store: RoutesStore<Dependencies>,\n): readonly Route<Dependencies>[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const factories = store.lifecycleNamespace!.getFactories();\n const result: Route<Dependencies>[] = [];\n\n const walk = (\n input: readonly Route<Dependencies>[],\n parent: string,\n ): void => {\n for (const route of input) {\n const fullName = parent ? `${parent}.${route.name}` : route.name;\n\n result.push(\n buildFlatRoute(fullName, route.path, store.config, factories),\n );\n\n if (route.children) {\n walk(route.children, fullName);\n }\n }\n };\n\n walk(routes, parentName ?? \"\");\n\n return Object.freeze(result);\n}\n\n/** Diffs two flat route maps by full name into frozen removed/added arrays. */\nfunction diffFlatRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n before: ReadonlyMap<string, Route<Dependencies>>,\n after: ReadonlyMap<string, Route<Dependencies>>,\n): {\n removed: readonly Route<Dependencies>[];\n added: readonly Route<Dependencies>[];\n} {\n const removed: Route<Dependencies>[] = [];\n const added: Route<Dependencies>[] = [];\n\n for (const [fullName, route] of before) {\n if (!after.has(fullName)) {\n removed.push(route);\n }\n }\n\n for (const [fullName, route] of after) {\n if (!before.has(fullName)) {\n added.push(route);\n }\n }\n\n return { removed: Object.freeze(removed), added: Object.freeze(added) };\n}\n\n/**\n * Builds the structural subset of an `update()` patch (forwardTo /\n * defaultParams / encodeParams / decodeParams) from the already-destructured\n * update fields — so user getters are not re-invoked. A guard-only patch yields\n * an empty object → the caller emits no TREE_CHANGED (О-7: guards are\n * invoked-on-demand, not cached, so they need no observation channel).\n *\n * The returned envelope is a fresh object (caller's patch untouched) and is\n * frozen on construction. Nested values (e.g. `defaultParams`) are kept by\n * reference — the same objects the router stored — so exotic inputs (circular\n * refs, class instances) are tolerated, matching `update()`'s existing contract.\n */\nfunction buildStructuralPatch<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(fields: {\n forwardTo?: string | ForwardToCallback<Dependencies> | null | undefined;\n defaultParams?: Params | null | undefined;\n defaultSearch?: SearchParams | null | undefined;\n decodeParams?: ((channels: ParamsSearch) => ParamsSearch) | null | undefined;\n encodeParams?: ((channels: ParamsSearch) => ParamsSearch) | null | undefined;\n}): Readonly<TreeStructuralPatch<Dependencies>> {\n const patch: TreeStructuralPatch<Dependencies> = {};\n\n if (fields.forwardTo !== undefined) {\n patch.forwardTo = fields.forwardTo;\n }\n\n if (fields.defaultParams !== undefined) {\n patch.defaultParams = fields.defaultParams;\n }\n\n if (fields.defaultSearch !== undefined) {\n patch.defaultSearch = fields.defaultSearch;\n }\n\n if (fields.encodeParams !== undefined) {\n patch.encodeParams = fields.encodeParams;\n }\n\n if (fields.decodeParams !== undefined) {\n patch.decodeParams = fields.decodeParams;\n }\n\n return Object.freeze(patch);\n}\n\n// ============================================================================\n// CRUD operations\n// ============================================================================\n\n/**\n * Adds one or more routes to the router.\n * Input already validated by facade.\n */\nfunction addRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n parentName: string | undefined,\n logger: RouterLogger,\n): void {\n // Prepare-then-commit (issue #698): reject the silent-corruption cases\n // up front (dup name vs existing, missing parent), build the merged tree /\n // config into locals (async/circular forwardTo + invalid constraint throw\n // here), then swap atomically. A rejected add leaves the store untouched.\n assertAddable(store, routes, parentName);\n\n const artifacts = buildAddArtifacts(store, routes, parentName, logger);\n\n // Config-time channel check on the PREPARED artifacts, in PREPARE — the same\n // position `replace` gives it, and for the same reason (a throw must precede\n // every mutation, not merely the swap).\n assertRouteDefaultChannelsFor(\n artifacts.matcher,\n artifacts.config,\n \"addRoute\",\n );\n\n // Pre-flight the #961 handler-limit into PREPARE so a limit-exceeding batch\n // aborts before the swap (#1046). `add` does not clear guards, so the\n // projection runs against the live union count (clearsDefinition = false).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n false,\n );\n\n adoptRouteArtifacts(store, artifacts);\n}\n\n/**\n * Commits a revalidated state after `replace()` and emits `TRANSITION_SUCCESS`\n * so `router.subscribe` / adapters re-render (#950). The emit carries\n * `REVALIDATE_OPTS` — the single distinguishable marker (`revalidate: true`) a\n * plugin's `onTransitionSuccess` can read to special-case a revalidation vs a\n * real navigation (#1201).\n */\nfunction commitRevalidated<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n ctx: RouterInternals<Dependencies>,\n nextState: State,\n fromState: State,\n): void {\n ctx.setState(nextState);\n ctx.emitTransitionSuccess(nextState, fromState, REVALIDATE_OPTS);\n}\n\n/**\n * Atomically replaces all routes with a new set (HMR / code-splitting).\n * Prepare-then-commit (issue #698): the new set is fully built into locals\n * first — a circular/async forwardTo or invalid path throws here, leaving the\n * existing tree intact — then committed.\n */\nfunction replaceRoutes<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n routes: Route<Dependencies>[],\n ctx: RouterInternals<Dependencies>,\n currentState: State | undefined,\n onCommitted?: () => void,\n): void {\n // Reject the silent-corruption cases `assertAddable` catches for `add`, BEFORE\n // building/swapping, so bare-core parity is symmetric (#1047): within-batch\n // duplicate names (#968), reserved \"@@\" names (#954), and within-batch\n // duplicate paths (#955). methodName is \"addRoute\" to match validation-plugin\n // (which reports \"addRoute\" for replace batches too), so the no-plugin error\n // is identical to the with-plugin one.\n assertNoInternalNamesInBatch(routes, \"addRoute\");\n assertNoDuplicateNamesInBatch(routes, \"\", \"addRoute\");\n assertNoDuplicatePathsInBatch(routes, \"\", \"addRoute\");\n\n // Build the whole new set BEFORE touching the store.\n const artifacts = buildReplaceArtifacts(\n routes,\n store.rootPath,\n store.matcherOptions,\n ctx.logger,\n );\n\n // Config-time channel check BEFORE clearDefinitionGuards mutates. It used to\n // live inside `adoptRouteArtifacts`, one line before the swap — early enough\n // for `add`, too late here: a refused batch left the tree intact and the old\n // definition guards ERASED, so a guarded route became freely activatable. Same\n // fail-open shape #1046 and #1193 hoisted their own throws out of, now for the\n // third throwing step this path grew.\n assertRouteDefaultChannelsFor(\n artifacts.matcher,\n artifacts.config,\n \"addRoute\",\n );\n\n // Pre-flight the #961 handler-limit BEFORE clearDefinitionGuards mutates, so a\n // limit-exceeding batch aborts with BOTH the tree and the definition guards\n // intact (#1046). replace clears definition guards first, so the projection\n // runs against the surviving external guards (clearsDefinition = true).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.preflightHandlerLimit(\n artifacts.pendingCanActivate.keys(),\n artifacts.pendingCanDeactivate.keys(),\n true,\n );\n\n // Pre-compile the new batch's guard factories in the PREPARE phase — BEFORE\n // clearDefinitionGuards — so a compile-throwing factory (or a non-function)\n // aborts here with BOTH the tree AND the old definition guards intact (#1193,\n // mirror of the #1046 handler-limit hoist). adoptRouteArtifacts then installs\n // these pre-compiled functions without re-running the factories.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const compiledGuards = compileArtifactGuards(artifacts, store.depsStore!);\n\n // Clear definition lifecycle handlers (preserve external guards), then swap.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearDefinitionGuards();\n adoptRouteArtifacts(store, artifacts, compiledGuards);\n\n // TREE_CHANGED fires here (О-5): the new tree is committed but state is not\n // yet revalidated, so the handler sees the new tree and the still-old state.\n onCommitted?.();\n\n // Revalidate the active state against the new tree AND notify subscribers\n // (#950). A structural replace can change or drop the currently-active state;\n // emitting TRANSITION_SUCCESS makes router.subscribe / useSyncExternalStore\n // adapters re-render instead of rendering the pre-replace state. (This is the\n // one structural mutation that emits a transition event — clear() stays a\n // silent reset; the asymmetry is deliberate, see #950.)\n if (currentState !== undefined) {\n const revalidated = ctx.matchPath(currentState.path, ctx.getOptions());\n\n if (revalidated) {\n if (revalidated.name === currentState.name) {\n // Survivor — the URL still maps to the route the user was already on.\n // Keep it WITHOUT re-running guards: the user legitimately reached this\n // route via a real navigation, and `replace()` is not a navigation they\n // performed, so re-checking guards here would evict them on a stateful\n // or async guard (parity with `update()`, which never revalidates the\n // active state). Preserve the prior transition meta and emit so\n // subscribers see the revalidated state (#1201). Carry the prior\n // `context` (#1236): the route name and path are unchanged, so the\n // plugin data written into `state.context.<namespace>` (SSR data, rsc,\n // navigation, …) is still valid — the matchPath-rebuilt state would\n // otherwise wipe it, and revalidation re-runs neither the loader nor the\n // start interceptor to bring it back.\n const nextState: State = {\n ...revalidated,\n context: currentState.context,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n // Route-identity change — the URL is now owned by a DIFFERENT route (an\n // ownership reshuffle, or a newly-added `forwardTo` that teleports the\n // state). That is effectively a navigation the user never performed, so\n // consult the new route's guards exactly as `navigate` would (#1201).\n // Commit on pass; on a block — or an async guard that cannot be\n // evaluated synchronously (mirrors `canNavigateTo`) — route to\n // not-found rather than silently activating a guarded route.\n const { toDeactivate, toActivate } = getTransitionPath(\n revalidated,\n currentState,\n ctx.getMetaForState,\n );\n\n const allowed =\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.canNavigateTo(\n toDeactivate,\n toActivate,\n revalidated,\n currentState,\n );\n\n if (allowed) {\n const nextState: State = {\n ...revalidated,\n transition: currentState.transition,\n };\n\n commitRevalidated(ctx, nextState, currentState);\n } else {\n ctx.navigateToNotFound(currentState.path);\n }\n }\n } else {\n // The active route no longer exists in the new tree — surface it as\n // not-found (commits UNKNOWN_ROUTE + emits TRANSITION_SUCCESS) so the\n // change is observable, rather than silently clearing the state.\n ctx.navigateToNotFound(currentState.path);\n }\n }\n}\n\n/**\n * Removes a route and all its children.\n *\n * @returns true if removed, false if not found\n */\nfunction removeRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(store: RoutesStore<Dependencies>, name: string): boolean {\n // `store.definitions` is a fresh tree-derived snapshot — mutate it locally,\n // then commit the mutated table as the new tree.\n const definitions = store.definitions;\n const wasRemoved = removeFromDefinitions(definitions, name);\n\n if (!wasRemoved) {\n return false;\n }\n\n clearRouteConfigurations(\n name,\n store.config,\n store.routeCustomFields,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n store.lifecycleNamespace!,\n );\n\n commitTreeChanges(store, definitions);\n\n return true;\n}\n\n/**\n * Gets a route by name with all its configuration.\n */\nfunction getRoute<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n store: RoutesStore<Dependencies>,\n name: string,\n): Route<Dependencies> | undefined {\n const segments = store.matcher.getSegmentsByName(name);\n\n if (!segments) {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- segments is non-empty (checked above)\n const targetNode = segments.at(-1)! as RouteTree;\n const definition = nodeToDefinition(targetNode);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const factories = store.lifecycleNamespace!.getFactories();\n\n return enrichRoute(definition, name, store.config, factories);\n}\n\n// ============================================================================\n// API factory\n// ============================================================================\n\n// Cache the assembled RoutesApi per router — mirrors getPluginApi()/getNavigator():\n// avoids re-allocating the 9-closure bag on each call (adapters/plugins poll it\n// from constructors) and gives spy/stub helpers a stable object identity. Closures\n// capture `ctx`/`store`, both stable for the router's lifetime, so caching is safe.\n// Single cast site: the value is stored as `unknown` (RoutesApi is invariant in\n// Dependencies, so one typed map can't hold every instantiation) and cast on read.\nconst cache = new WeakMap<object, unknown>();\n\nexport function getRoutesApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): RoutesApi<Dependencies> {\n const cached = cache.get(router);\n\n if (cached) {\n return cached as RoutesApi<Dependencies>;\n }\n\n const ctx = getInternals(router);\n\n const store = ctx.routeGetStore();\n\n // Single cast site: the channel is typed with default Dependencies on\n // RouterInternals (RouterEventMap is non-generic), but payloads are built\n // with this api's Dependencies. The runtime shape is identical.\n const emitChange = (event: TreeChangedEvent<Dependencies>): void => {\n ctx.treeChanged.emit(event as TreeChangedEvent);\n };\n\n const api: RoutesApi<Dependencies> = {\n add: (routes, options) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n const parentName = options?.parent;\n\n guardRouteStructure(routeArray, ctx.validator);\n\n if (parentName !== undefined) {\n ctx.validator?.routes.validateParentOption(parentName, store.tree);\n }\n\n ctx.validator?.routes.throwIfInternalRouteInArray(routeArray, \"addRoute\");\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store, parentName);\n\n addRoutes(store, routeArray, parentName, ctx.logger);\n\n // Built from the post-commit store (О-1), only when someone is listening.\n if (ctx.treeChanged.listenerCount() > 0) {\n const added = collectAddedRoutes(routeArray, parentName, store);\n\n emitChange(\n parentName === undefined\n ? { op: \"add\", added }\n : { op: \"add\", added, parent: parentName },\n );\n }\n },\n\n remove: (name) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateRemoveRouteArgs(name);\n ctx.validator?.routes.throwIfInternalRoute(name, \"removeRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be removed, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"removeRoute\");\n\n const canRemove = validateRemoveRoute(\n name,\n ctx.getStateName(),\n ctx.isTransitioning(),\n ctx.logger,\n );\n\n if (!canRemove) {\n return;\n }\n\n // Snapshot the subtree BEFORE the mutation — the nodes are gone after.\n const removedSubtree =\n ctx.treeChanged.listenerCount() > 0\n ? collectSubtree(store, name)\n : undefined;\n const wasRemoved = removeRoute(store, name);\n\n if (!wasRemoved) {\n ctx.logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" not found. No changes made.`,\n );\n\n return;\n }\n\n if (removedSubtree !== undefined) {\n emitChange({ op: \"remove\", name, removedSubtree });\n }\n },\n\n update: (name, updates) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n ctx.validator?.routes.validateUpdateRouteBasicArgs(name, updates);\n ctx.validator?.routes.throwIfInternalRoute(name, \"updateRoute\");\n // Always-on parity backstop (#1047 / #238): a reserved \"@@\" name is\n // internal and cannot be updated, with or without the validation-plugin.\n assertNoInternalRouteName(name, \"updateRoute\");\n\n ctx.validator?.routes.validateUpdateRoutePropertyTypes(name, updates);\n\n /* v8 ignore next 6 -- @preserve: race condition guard, mirrors Router.updateRoute() same-path guard tested via Router.ts unit tests */\n if (ctx.isTransitioning()) {\n ctx.logger.error(\n \"router.updateRoute\",\n `Updating route \"${name}\" while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n ctx.validator?.routes.validateUpdateRoute(name, updates, store);\n\n // #1205: bare-core existence backstop as a TRUE no-op — NOT a throw\n // (validation is opt-in). update() of a route that does not exist used to\n // seed config.defaultParams + compile/register the guard (commitRouteUpdate\n // below) and emit a lying TREE_CHANGED \"update\" event for a route get()/\n // has() cannot see; a future add() of that name then inherited the phantom\n // config + a blocking guard. Skip the commit and the emit entirely when the\n // route is absent. (With the validation-plugin, validateUpdateRoute above\n // already threw a ReferenceError, so this is only reached in bare core.)\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n // Field-patch commit core (NO_TREE_REBUILD) — co-located in routesStore.ts\n // beside the add/replace (adoptRouteArtifacts) / remove (commitTreeChanges)\n // / clear (resetStore) cores. Returns the structural fields for the\n // conditional emit below (each user getter read once inside).\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycle = store.lifecycleNamespace!;\n const structural = commitRouteUpdate(store, lifecycle, name, updates);\n\n // Conditional emit: structural fields only. A guard-only or empty patch\n // produces no event (О-7 + empty-patch rule).\n if (ctx.treeChanged.listenerCount() > 0) {\n const patch = buildStructuralPatch<Dependencies>(structural);\n\n if (Object.keys(patch).length > 0) {\n emitChange({ op: \"update\", name, patch });\n }\n }\n },\n\n clear: () => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const canClear = validateClearRoutes(ctx.isTransitioning(), ctx.logger);\n\n /* v8 ignore next 3 -- @preserve: race condition guard, mirrors Router.clearRoutes() same-path guard tested via validateClearRoutes unit tests */\n if (!canClear) {\n return;\n }\n\n // Snapshot the routes BEFORE the reset empties them. Emitted whenever\n // there is a listener — even for an empty clear (О-4).\n const removed =\n ctx.treeChanged.listenerCount() > 0\n ? Object.freeze([...collectFlatRoutes(store, () => true).values()])\n : undefined;\n\n resetStore(store);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n store.lifecycleNamespace!.clearAll();\n ctx.clearState();\n\n if (removed !== undefined) {\n emitChange({ op: \"clear\", removed });\n }\n },\n\n has: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"hasRoute\");\n\n return store.matcher.hasRoute(name);\n },\n\n get: (name) => {\n ctx.validator?.routes.validateRouteName(name, \"getRoute\");\n\n return getRoute(store, name);\n },\n\n replace: (routes) => {\n throwIfDisposed(ctx.isDisposed);\n throwIfReentrantTreeMutation(ctx.treeChanged.isEmitting);\n\n const routeArray = Array.isArray(routes) ? routes : [routes];\n\n const canReplace = validateClearRoutes(ctx.isTransitioning(), ctx.logger);\n\n if (!canReplace) {\n return;\n }\n\n guardRouteStructure(routeArray, ctx.validator);\n\n ctx.validator?.routes.throwIfInternalRouteInArray(\n routeArray,\n \"replaceRoutes\",\n );\n ctx.validator?.routes.validateAddRouteArgs(routeArray);\n ctx.validator?.routes.validateRoutes(routeArray, store);\n\n const currentState = router.getState();\n\n // The flat removed/added diff is O(N) — compute it only when someone is\n // listening (Решение 3.B). Snapshot the old tree BEFORE the swap.\n const before =\n ctx.treeChanged.listenerCount() > 0\n ? collectFlatRoutes(store, () => true)\n : undefined;\n\n replaceRoutes(\n store,\n routeArray,\n ctx,\n currentState,\n before === undefined\n ? undefined\n : () => {\n const after = collectFlatRoutes(store, () => true);\n const { removed, added } = diffFlatRoutes(before, after);\n\n emitChange({ op: \"replace\", removed, added });\n },\n );\n },\n\n subscribeChanges: (handler) => ctx.treeChanged.subscribe(handler),\n };\n\n cache.set(router, api);\n\n return api;\n}\n"],"mappings":"+VA4DM,EAAqC,OAAO,OAAO,CACvD,QAAS,GACT,WAAY,EACd,CAAC,EAMD,SAAS,EAGP,EACA,EACA,E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U,CAAO,CAClE,EAIA,OAFA,EAAM,IAAI,EAAQ,CAAG,EAEd,CACT"}
|
package/dist/cjs/api/helpers.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("../constants.js"),t=require("../RouterError.js");function n(n){if(n())throw new t.RouterError(e.errorCodes.ROUTER_DISPOSED)}function r(n){if(n())throw new t.RouterError(e.errorCodes.REENTRANT_TREE_MUTATION)}exports.throwIfDisposed=n,exports.throwIfReentrantTreeMutation=r;
|
|
2
|
-
//# sourceMappingURL=helpers.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["RouterError","errorCodes"],"sources":["../../../src/api/helpers.ts"],"sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n\n/**\n * Bans synchronous reentrant route-CRUD: a CRUD op called while a `TREE_CHANGED`\n * emit is on the stack (i.e. from inside a `subscribeChanges` handler) throws\n * `REENTRANT_TREE_MUTATION` BEFORE mutating — the tree stays atomic (#1032).\n * Deferred CRUD (`queueMicrotask` / `await`) runs after the dispatch settles and\n * is unaffected; CRUD from a transition listener is not a TREE_CHANGED dispatch.\n */\nexport function throwIfReentrantTreeMutation(isEmitting: () => boolean): void {\n if (isEmitting()) {\n throw new RouterError(errorCodes.REENTRANT_TREE_MUTATION);\n }\n}\n"],"mappings":"kEAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAIA,EAAAA,YAAYC,EAAAA,WAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAID,EAAAA,YAAYC,EAAAA,WAAW,uBAAuB,CAE5D"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./guard.js");function t(e,t,n){if(e===void 0||n.length===0)return e;let r,i=!1;for(let[a,o]of Object.entries(e)){if(Object.hasOwn(t,a)&&t[a]!==void 0&&n.includes(a)){i=!0;continue}r??={},r[a]=o}return i?r:e}function n(t,n,r){for(let[i,a]of Object.entries(t))e.assertChannelCorrect(r,i,a,n(i),"this route's `defaultParams`","Move it to `defaultSearch`")}exports.assertRouteDefaultChannels=n,exports.withholdFilledSlots=t;
|
|
2
|
-
//# sourceMappingURL=defaults.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"defaults.js","names":[],"sources":["../../../src/channels/defaults.ts"],"sourcesContent":["// packages/core/src/channels/defaults.ts\n\nimport { assertChannelCorrect } from \"./guard\";\n\nimport type { Params, SearchParams } from \"../types\";\n\n/**\n * Withholds a query default whose key the caller already filled with the RETIRED\n * single-bag spelling — the rule #1570 states for a `forwardTo` chain's\n * defaults, applied where no seam runs to enforce it.\n *\n * Nothing is moved between channels: the caller's key stays in the bag the\n * caller chose, only the default is declined. Without this the default and the\n * caller's params-twin sit in DIFFERENT channels, where no merge ranks them, and\n * the query default wins by default — the §1.1 priority inversion the channel\n * split exists to remove.\n *\n * ⚠ Scoped to `declaredQuery` — the route's `?`-declared names — and the scope\n * is what keeps `buildPath` in step with every other producer. Only a DECLARED\n * query name can have a params-bag \"twin\" at all: that spelling is the v1\n * single-bag form the migrated entry points retired, so withholding is the whole\n * point. A key the route declares NOWHERE (`/u` + `defaultSearch { theme }`) or\n * one that owns a PATH SLOT beside its query twin (`/items/:id?id`, the\n * #843/#1549 carve-out) is not a twin — the caller's params entry and the query\n * default describe different things, and withholding there printed an href the\n * route's own `matchPath` immediately rewrote (the #1552/#1578 class: href ≠\n * destination, with `buildPath` the only producer out of agreement).\n *\n * `undefined` is absence (#1550 / #1551), so a caller's removal marker does not\n * count as \"already filled\" and the default survives it.\n *\n * Returns the input untouched (no allocation) when nothing is withheld — the\n * common path, and the only one the zero-default hot path ever takes.\n */\nexport function withholdFilledSlots(\n defaults: SearchParams | undefined,\n params: Params,\n declaredQuery: readonly string[],\n): SearchParams | undefined {\n if (defaults === undefined || declaredQuery.length === 0) {\n return defaults;\n }\n\n let kept: Record<string, unknown> | undefined;\n let dropped = false;\n\n for (const [key, value] of Object.entries(defaults)) {\n // `Object.hasOwn` before the read, exactly as `findMisChanneledKey` does in\n // `./guard` and for the same reason: a bare `params[key]` walks\n // the PROTOTYPE, so a route declaring `?toString` / `?constructor` /\n // `?valueOf` read as \"the caller already filled this slot\" on an EMPTY bag.\n // The default was then withheld from every LITERAL-form producer while the\n // resolving form still applied it — `buildPath` out of agreement with\n // `navigate`, printing an href its own `matchPath` does not reproduce, which\n // is the #1552/#1578 class this very rule exists to close. (`makeState`\n // joined the literal form in Phase 4, so it withholds too; the shape stayed\n // unreachable there because `PluginApi.makeState`'s P1 guard refuses the\n // triggering bag on the same predicate.)\n if (\n Object.hasOwn(params, key) &&\n params[key] !== undefined &&\n declaredQuery.includes(key)\n ) {\n dropped = true;\n continue;\n }\n\n kept ??= {};\n kept[key] = value;\n }\n\n return dropped ? (kept as SearchParams | undefined) : defaults;\n}\n\n/**\n * Config-time channel check: a route's `defaultParams` may not name a key the\n * route declares with `?`.\n *\n * The static half of \"params and search meet only in the URL\". Without it the\n * router builds a state out of its OWN config that its OWN always-on channel\n * guard then rejects — `start()` throwing `WRONG_CHANNEL` about a bag the user\n * never passed, which is the deferred-crash shape core's invariant guards exist\n * to prevent. The dynamic half (a forwarding hop whose target is only known at\n * resolution) is caught at the `forwardState` seam instead.\n *\n * Runs over the WHOLE config after every rebuild rather than over the routes\n * just added: `setRootPath(\"?lang\")` declares a name on every route at once, so\n * a config that was legal a moment ago can stop being legal without any route\n * changing.\n *\n * Takes `queryNamesOf` as DATA rather than reaching for a matcher, so this\n * subsystem imports nothing from the namespaces or the engine — the same\n * inversion `src/pipeline` makes with its `RouteResolver` port. The caller owns\n * the derivation AND its caches, which matters here: every call site runs on\n * PREPARED artifacts before any swap, with caches local to the attempt, because\n * checking against the live store would validate a tree the rejected batch has\n * not installed. `RoutesNamespace/helpers.assertRouteDefaultChannelsFor` is that\n * caller — a small adapter holding the per-attempt caches, so the four entry\n * points do not each rebuild the closure.\n */\nexport function assertRouteDefaultChannels(\n defaultParams: Readonly<Record<string, Params>>,\n queryNamesOf: (name: string) => readonly string[],\n method: string,\n): void {\n for (const [name, defaults] of Object.entries(defaultParams)) {\n assertChannelCorrect(\n method,\n name,\n defaults,\n queryNamesOf(name),\n \"this route's `defaultParams`\",\n \"Move it to `defaultSearch`\",\n );\n }\n}\n"],"mappings":"8BAkCA,SAAgB,EACd,EACA,EACA,EAC0B,CAC1B,GAAI,IAAa,IAAA,IAAa,EAAc,SAAW,EACrD,OAAO,EAGT,IAAI,EACA,EAAU,GAEd,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAQ,EAAG,CAYnD,GACE,OAAO,OAAO,EAAQ,CAAG,GACzB,EAAO,KAAS,IAAA,IAChB,EAAc,SAAS,CAAG,EAC1B,CACA,EAAU,GACV,QACF,CAEA,IAAS,CAAC,EACV,EAAK,GAAO,CACd,CAEA,OAAO,EAAW,EAAoC,CACxD,CA4BA,SAAgB,EACd,EACA,EACA,EACM,CACN,IAAK,GAAM,CAAC,EAAM,KAAa,OAAO,QAAQ,CAAa,EACzD,EAAA,qBACE,EACA,EACA,EACA,EAAa,CAAI,EACjB,+BACA,4BACF,CAEJ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e,t){if(t.length!==0&&e!==void 0)for(let n of t){if(!Object.hasOwn(e,n))continue;let t;try{t=e[n]}catch{return}if(t!==void 0)return n}}function t(t,r,i,a,o,s){let c=e(i,a);if(c!==void 0)throw TypeError(`[router.${t}] ${n(r,c,typeof o==`function`?o():o,s)}`)}function n(e,t,n="the `params` argument",r="Pass it in `search` instead"){return`Route "${e}" declares \`${t}\` as a query param, but it was given in ${n} — the path channel. ${r}; the two channels are separate since RFC-4 M2 and the router never moves a key between them.`}exports.assertChannelCorrect=t,exports.findMisChanneledKey=e,exports.misChanneledKeyMessage=n;
|
|
2
|
-
//# sourceMappingURL=guard.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"guard.js","names":[],"sources":["../../../src/channels/guard.ts"],"sourcesContent":["// packages/core/src/channels/guard.ts\n\nimport type { Params } from \"../types\";\n\n/**\n * THE predicate of the always-on channel guard: the first key the caller put in\n * the PATH bag while the route declares it as a QUERY param, or `undefined`\n * when the bag is channel-correct.\n *\n * A DETECTOR, not a normaliser — the key is never moved. Moving it is what\n * `separateChannels` (stage ②) used to do — a function that no longer exists.\n * Channel-correctness is the producer's contract now, not a repair the pipeline\n * performs behind everyone's back.\n *\n * Scans `queryNames` (a route's declared query names — small, cached) rather\n * than the bag, so there is no `Object.keys` allocation, and short-circuits on\n * a route with no query declarations, which is the common case.\n *\n * `undefined` is absence on both sides (#1550 / #1551), so an\n * `undefined`-valued key is NOT a mis-channel: it is the documented removal\n * marker `persistent-params` relies on, and it never reaches a built state\n * anyway. A name that also occupies a path slot (`/items/:id?id`) is absent\n * from `queryNames` by construction (#843 / #1549 carve-out), so the collision\n * form is legitimately path-owned and passes.\n *\n * @internal\n */\nexport function findMisChanneledKey(\n params: Params | undefined,\n queryNames: readonly string[],\n): string | undefined {\n if (queryNames.length === 0 || params === undefined) {\n return undefined;\n }\n\n for (const key of queryNames) {\n if (!Object.hasOwn(params, key)) {\n continue;\n }\n\n let value: unknown;\n\n try {\n value = params[key];\n } catch {\n // A DIAGNOSTIC must never become the thing that throws. The bag may be\n // backed by accessors (a Proxy, a getter, a framework's reactive object),\n // and reading one here happens EARLIER than any consumer would have read\n // it — so an accessor that throws would surface from the guard instead of\n // from the code that actually needed the value, moving the origin of an\n // existing failure. Treat it as \"nothing to report\" and let the real\n // consumer hit the same accessor exactly as it did before.\n return undefined;\n }\n\n if (value !== undefined) {\n return key;\n }\n }\n\n return undefined;\n}\n\n/**\n * THE centralized channel check — the single place a mis-channelled bag is\n * refused, wherever it came from.\n *\n * Replaces the repair `separateChannels` (stage ②, since deleted) used to\n * perform at the `forwardState` seam. A key the route declares with `?`, sitting in the PATH\n * bag, is a producer's mistake — the producer named the route, so it knows the\n * declaration — and the router now says so instead of quietly moving the field\n * into the other object. Moving it was invisible: the caller kept believing\n * their bag was the one that shipped, and two producers of the SAME intent\n * could disagree about which channel a key ended up in.\n *\n * `source` names WHOSE bag is wrong, which is the whole diagnostic value at a\n * seam: the caller's argument, a `forwardState` interceptor's return, or the\n * output of a route's own `decodeParams`. It takes a THUNK as well as a string\n * because the seam sits on the navigation hot path — a source that has to be\n * composed (naming the route a chain forwarded from) must not build its string\n * on every call just to discard it on the 99.99% of calls that pass.\n *\n * @internal\n */\nexport function assertChannelCorrect(\n method: string,\n routeName: string,\n params: Params | undefined,\n queryNames: readonly string[],\n source?: string | (() => string),\n remedy?: string,\n): void {\n const key = findMisChanneledKey(params, queryNames);\n\n if (key !== undefined) {\n throw new TypeError(\n `[router.${method}] ${misChanneledKeyMessage(\n routeName,\n key,\n typeof source === \"function\" ? source() : source,\n remedy,\n )}`,\n );\n }\n}\n\n/**\n * The guard's actionable message. One builder for every position, so the\n * wording a user sees does not depend on which door they came through — the\n * facade's `TypeError`, the seam's, the decoder's, and `navigateToState`'s\n * `RouterError(WRONG_CHANNEL)`, which needs the wording WITHOUT the throw and is\n * why this is a separate function from {@link assertChannelCorrect}.\n *\n * @internal\n */\nexport function misChanneledKeyMessage(\n routeName: string,\n key: string,\n source = \"the `params` argument\",\n remedy = \"Pass it in `search` instead\",\n): string {\n return `Route \"${routeName}\" declares \\`${key}\\` as a query param, but it was given in ${source} — the path channel. ${remedy}; the two channels are separate since RFC-4 M2 and the router never moves a key between them.`;\n}\n"],"mappings":"AA2BA,SAAgB,EACd,EACA,EACoB,CAChB,KAAW,SAAW,GAAK,IAAW,IAAA,GAI1C,IAAK,IAAM,KAAO,EAAY,CAC5B,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAG,EAC5B,SAGF,IAAI,EAEJ,GAAI,CACF,EAAQ,EAAO,EACjB,MAAQ,CAQN,MACF,CAEA,GAAI,IAAU,IAAA,GACZ,OAAO,CAEX,CAGF,CAuBA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACM,CACN,IAAM,EAAM,EAAoB,EAAQ,CAAU,EAElD,GAAI,IAAQ,IAAA,GACV,MAAU,UACR,WAAW,EAAO,IAAI,EACpB,EACA,EACA,OAAO,GAAW,WAAa,EAAO,EAAI,EAC1C,CACF,GACF,CAEJ,CAWA,SAAgB,EACd,EACA,EACA,EAAS,wBACT,EAAS,8BACD,CACR,MAAO,UAAU,EAAU,eAAe,EAAI,2CAA2C,EAAO,uBAAuB,EAAO,8FAChI"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"modeGate.js","names":["EMPTY_SEARCH"],"sources":["../../../src/channels/modeGate.ts"],"sourcesContent":["// packages/core/src/channels/modeGate.ts\n\nimport { EMPTY_SEARCH } from \"../constants\";\n\nimport type { SearchParams } from \"../types\";\n\n/**\n * The mode gate (#1575): the query channel restricted to what the active\n * `queryParamsMode` will actually PRINT.\n *\n * Under `loose` the build prints undeclared keys too, so the whole bag is\n * admitted and the caller skips this entirely (`admitsUndeclaredQuery()`).\n * Under `default` / `strict` the build prints declared names only — so a key\n * that survives into `state.search` here can never appear in `state.path`, and\n * the two channels of one state disagree. Filtering at the merge, on BOTH\n * directions, is what buys the invariant `keys(state.search) ⊆\n * keys(matchPath(state.path).search)` in every mode.\n *\n * A DROP, not a move: the key does not migrate to `state.params` (that would\n * re-create the channel ambiguity #1553 is about) — it simply is not state.\n * `validation-plugin` reports the drop; bare core is silent by the same\n * always-on-fixes / opt-in-diagnoses split as the channel guard.\n *\n * Returns the input bag unchanged when nothing is dropped, so the common case\n * (a route whose query keys are all declared) allocates nothing.\n *\n * @internal\n */\nexport function admittedSearch<S extends SearchParams>(\n search: S,\n queryNames: readonly string[],\n onDropped?: (key: string) => void,\n): S {\n let admitted: Record<string, unknown> | undefined;\n let dropped = false;\n\n // `Object.entries` (own enumerable only) rather than `for…in` + `Object.hasOwn`\n // — the same idiom the deleted `separateChannels` used, and it keeps the guard branch\n // out of the file instead of leaving one no test can reach.\n for (const [key, value] of Object.entries(search)) {\n if (queryNames.includes(key)) {\n admitted ??= {};\n admitted[key] = value;\n } else {\n dropped = true;\n // The drop is silent in bare core; `validation-plugin` passes a reporter.\n // Reported from HERE rather than re-derived by the caller so the message\n // can never disagree with what was actually dropped, and so the scan\n // happens once. The callback is only ever supplied when a validator is\n // installed, so the default path stays a plain filter.\n onDropped?.(key);\n }\n }\n\n if (!dropped) {\n return search;\n }\n\n // Frozen, because this is the ONLY branch that hands back a bag the caller did\n // not already freeze: `search` arrives frozen from `mergeWithDefault`, and the\n // no-drop branch returns it untouched. Before nav-pipeline Phase 2 the gap was\n // invisible — every consumer re-merged (and re-froze) downstream in the\n // then-separate `makeState`. `materialize` deliberately does not, so an\n // unfrozen `admitted` reached `state.search` verbatim and broke \"states are\n // deeply frozen\" for exactly the states the gate had touched. Phase 4 folded\n // `makeState` onto `canonicalize` + `materialize`, so there is no re-merge\n // left anywhere: this freeze is now the only one on the drop path.\n return Object.freeze(admitted ?? EMPTY_SEARCH) as S;\n}\n"],"mappings":"mCA4BA,SAAgB,EACd,EACA,EACA,EACG,CACH,IAAI,EACA,EAAU,GAKd,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAC1C,EAAW,SAAS,CAAG,GACzB,IAAa,CAAC,EACd,EAAS,GAAO,IAEhB,EAAU,GAMV,IAAY,CAAG,GAiBnB,OAbK,EAaE,OAAO,OAAO,GAAYA,EAAAA,YAAY,EAZpC,CAaX"}
|
package/dist/cjs/constants.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=Object.freeze({ROUTER_NOT_STARTED:`NOT_STARTED`,NO_START_PATH_OR_STATE:`NO_START_PATH_OR_STATE`,ROUTER_ALREADY_STARTED:`ALREADY_STARTED`,ROUTE_NOT_FOUND:`ROUTE_NOT_FOUND`,SAME_STATES:`SAME_STATES`,CANNOT_DEACTIVATE:`CANNOT_DEACTIVATE`,CANNOT_ACTIVATE:`CANNOT_ACTIVATE`,TRANSITION_ERR:`TRANSITION_ERR`,TRANSITION_CANCELLED:`CANCELLED`,ROUTER_DISPOSED:`DISPOSED`,PLUGIN_CONFLICT:`PLUGIN_CONFLICT`,CONTEXT_NAMESPACE_ALREADY_CLAIMED:`CONTEXT_NAMESPACE_ALREADY_CLAIMED`,REENTRANT_NAVIGATION:`REENTRANT_NAVIGATION`,REENTRANT_TREE_MUTATION:`REENTRANT_TREE_MUTATION`,WRONG_CHANNEL:`WRONG_CHANNEL`}),t=`@@router/UNKNOWN_ROUTE`,n={UNKNOWN_ROUTE:t},r={ROUTER_START:`onStart`,ROUTER_STOP:`onStop`,TRANSITION_START:`onTransitionStart`,TRANSITION_LEAVE_APPROVE:`onTransitionLeaveApprove`,TRANSITION_CANCEL:`onTransitionCancel`,TRANSITION_SUCCESS:`onTransitionSuccess`,TRANSITION_ERROR:`onTransitionError`},i={ROUTER_START:`$start`,ROUTER_STOP:`$stop`,TRANSITION_START:`$$start`,TRANSITION_LEAVE_APPROVE:`$$leaveApprove`,TRANSITION_CANCEL:`$$cancel`,TRANSITION_SUCCESS:`$$success`,TRANSITION_ERROR:`$$error`},a={maxDependencies:100,maxPlugins:50,maxListeners:1e4,warnListeners:1e3,maxLifecycleHandlers:200},o=Object.freeze({}),s=Object.freeze({}),c=Object.freeze({deactivated:Object.freeze([]),activated:Object.freeze([]),intersection:``}),l=Object.freeze({phase:`activating`,reason:`success`,segments:c});exports.DEFAULT_LIMITS=a,exports.DEFAULT_TRANSITION=l,exports.EMPTY_PARAMS=o,exports.EMPTY_SEARCH=s,exports.UNKNOWN_ROUTE=t,exports.constants=n,exports.errorCodes=e,exports.events=i,exports.plugins=r;
|
|
2
|
-
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../../src/constants.ts"],"sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n TransitionMeta,\n} from \"./types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Record<ConstantsKeys, string>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n CONTEXT_NAMESPACE_ALREADY_CLAIMED: \"CONTEXT_NAMESPACE_ALREADY_CLAIMED\", // Plugin tried to claim a context namespace already owned by another plugin\n REENTRANT_NAVIGATION: \"REENTRANT_NAVIGATION\", // navigate() called synchronously from inside a transition-event listener (banned — use await/async listener)\n REENTRANT_TREE_MUTATION: \"REENTRANT_TREE_MUTATION\", // route-CRUD called synchronously from inside a subscribeChanges handler (banned — use await/async/queueMicrotask)\n WRONG_CHANNEL: \"WRONG_CHANNEL\", // a declared query key was supplied in the path channel (`params`) instead of `search` (#1572)\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\nexport const constants: Constants = {\n UNKNOWN_ROUTE,\n};\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = {\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_LEAVE_APPROVE: \"onTransitionLeaveApprove\", // Plugin method called when deactivation guards pass\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n};\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = {\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_LEAVE_APPROVE: \"$$leaveApprove\", // Emitted when deactivation guards pass\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n};\n\nexport const DEFAULT_LIMITS = {\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxLifecycleHandlers: 200,\n} as const;\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty query bag reused for `State.search` when a navigation\n * carries no query params — the search-channel twin of {@link EMPTY_PARAMS}\n * (RFC-4 M2 / #1548). Lets `makeState` reuse one frozen `{}` (zero transient\n * allocation, #1027) instead of minting an object per query-less state.\n */\nexport const EMPTY_SEARCH: Readonly<Record<string, never>> = Object.freeze({});\n\nconst FROZEN_EMPTY_SEGMENTS = Object.freeze({\n deactivated: Object.freeze([]) as unknown as string[],\n activated: Object.freeze([]) as unknown as string[],\n intersection: \"\",\n});\n\nexport const DEFAULT_TRANSITION = Object.freeze({\n phase: \"activating\",\n reason: \"success\",\n segments: FROZEN_EMPTY_SEGMENTS,\n}) as TransitionMeta;\n"],"mappings":"AA0BA,MAAa,EAAkC,OAAO,OAAO,CAC3D,mBAAoB,cACpB,uBAAwB,yBACxB,uBAAwB,kBACxB,gBAAiB,kBACjB,YAAa,cACb,kBAAmB,oBACnB,gBAAiB,kBACjB,eAAgB,iBAChB,qBAAsB,YACtB,gBAAiB,WACjB,gBAAiB,kBACjB,kCAAmC,oCACnC,qBAAsB,uBACtB,wBAAyB,0BACzB,cAAe,eACjB,CAAC,EAMY,EAAgB,yBAEhB,EAAuB,CAClC,eACF,EAMa,EAA4B,CACvC,aAAc,UACd,YAAa,SACb,iBAAkB,oBAClB,yBAA0B,2BAC1B,kBAAmB,qBACnB,mBAAoB,sBACpB,iBAAkB,mBACpB,EAMa,EAAyB,CACpC,aAAc,SACd,YAAa,QACb,iBAAkB,UAClB,yBAA0B,iBAC1B,kBAAmB,WACnB,mBAAoB,YACpB,iBAAkB,SACpB,EAEa,EAAiB,CAC5B,gBAAiB,IACjB,WAAY,GACZ,aAAc,IACd,cAAe,IACf,qBAAsB,GACxB,EAEa,EAAgD,OAAO,OAAO,CAAC,CAAC,EAQhE,EAAgD,OAAO,OAAO,CAAC,CAAC,EAEvE,EAAwB,OAAO,OAAO,CAC1C,YAAa,OAAO,OAAO,CAAC,CAAC,EAC7B,UAAW,OAAO,OAAO,CAAC,CAAC,EAC3B,aAAc,EAChB,CAAC,EAEY,EAAqB,OAAO,OAAO,CAC9C,MAAO,aACP,OAAQ,UACR,SAAU,CACZ,CAAC"}
|
package/dist/cjs/createRouter.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createRouter.js","names":["Router"],"sources":["../../src/createRouter.ts"],"sourcesContent":["// packages/core/src/createRouter.ts\n\nimport { Router } from \"./Router\";\n\nimport type { DefaultDependencies, Options, Route } from \"./types\";\n\n/**\n * Creates a new router instance.\n *\n * @param routes - Array of route definitions\n * @param options - Router configuration options\n * @param dependencies - Dependencies to inject into the router\n * @returns A new Router instance\n *\n * @example\n * const router = createRouter([\n * { name: 'home', path: '/' },\n * { name: 'users', path: '/users' },\n * ]);\n *\n * router.start('/');\n */\nexport const createRouter = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options<Dependencies>> = {},\n dependencies: Dependencies = {} as Dependencies,\n): Router<Dependencies> => {\n return new Router<Dependencies>(routes, options, dependencies);\n};\n"],"mappings":"+BAsBa,GAGX,EAAgC,CAAC,EACjC,EAA0C,CAAC,EAC3C,EAA6B,CAAC,IAEvB,IAAIA,EAAAA,OAAqB,EAAQ,EAAS,CAAY"}
|