@real-router/core 0.77.2 → 0.77.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/cjs/{Router-CLGzVSB7.js → Router-27ftBmfo.js} +2 -2
  2. package/dist/cjs/Router-27ftBmfo.js.map +1 -0
  3. package/dist/cjs/api.d.ts +1 -1
  4. package/dist/cjs/api.js +1 -1
  5. package/dist/cjs/api.js.map +1 -1
  6. package/dist/cjs/{cloneRouter-B9QmW8WN.js → cloneRouter-B1tPtpNE.js} +2 -2
  7. package/dist/cjs/cloneRouter-B1tPtpNE.js.map +1 -0
  8. package/dist/cjs/esm-egdCFOaS.js +2 -0
  9. package/dist/cjs/esm-egdCFOaS.js.map +1 -0
  10. package/dist/cjs/{index-cgB7PGoM.d.ts → index-0GKsQ2r9.d.ts} +79 -110
  11. package/dist/cjs/index-0GKsQ2r9.d.ts.map +1 -0
  12. package/dist/cjs/index.d.ts +1 -1
  13. package/dist/cjs/index.js +1 -1
  14. package/dist/cjs/utils.js +1 -1
  15. package/dist/cjs/utils.js.map +1 -1
  16. package/dist/cjs/validation.d.ts +1 -1
  17. package/dist/cjs/validation.d.ts.map +1 -1
  18. package/dist/cjs/validation.js +1 -1
  19. package/dist/esm/{Router-x5kV9fKk.mjs → Router-CTGJBKd7.mjs} +2 -2
  20. package/dist/esm/Router-CTGJBKd7.mjs.map +1 -0
  21. package/dist/esm/api.d.mts +1 -1
  22. package/dist/esm/api.mjs +1 -1
  23. package/dist/esm/api.mjs.map +1 -1
  24. package/dist/esm/cloneRouter-C4v9Xl2F.mjs +2 -0
  25. package/dist/esm/cloneRouter-C4v9Xl2F.mjs.map +1 -0
  26. package/dist/esm/esm-Cnywzxys.mjs +2 -0
  27. package/dist/esm/esm-Cnywzxys.mjs.map +1 -0
  28. package/dist/esm/{index-cgB7PGoM.d.mts → index-0GKsQ2r9.d.mts} +79 -110
  29. package/dist/esm/index-0GKsQ2r9.d.mts.map +1 -0
  30. package/dist/esm/index.d.mts +1 -1
  31. package/dist/esm/index.mjs +1 -1
  32. package/dist/esm/utils.mjs +1 -1
  33. package/dist/esm/utils.mjs.map +1 -1
  34. package/dist/esm/validation.d.mts +1 -1
  35. package/dist/esm/validation.d.mts.map +1 -1
  36. package/dist/esm/validation.mjs +1 -1
  37. package/package.json +4 -4
  38. package/dist/cjs/Router-CLGzVSB7.js.map +0 -1
  39. package/dist/cjs/cloneRouter-B9QmW8WN.js.map +0 -1
  40. package/dist/cjs/esm-6qkkdCI3.js +0 -2
  41. package/dist/cjs/esm-6qkkdCI3.js.map +0 -1
  42. package/dist/cjs/index-cgB7PGoM.d.ts.map +0 -1
  43. package/dist/esm/Router-x5kV9fKk.mjs.map +0 -1
  44. package/dist/esm/cloneRouter-C6fB27Wq.mjs +0 -2
  45. package/dist/esm/cloneRouter-C6fB27Wq.mjs.map +0 -1
  46. package/dist/esm/esm-DgICGBiW.mjs +0 -2
  47. package/dist/esm/esm-DgICGBiW.mjs.map +0 -1
  48. package/dist/esm/index-cgB7PGoM.d.mts.map +0 -1
package/dist/cjs/api.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as RouteTree } from "./index-cgB7PGoM.js";
1
+ import { i as RouteTree } from "./index-0GKsQ2r9.js";
2
2
  import { t as Router$1 } from "./Router-Bm2qafJA.js";
3
3
  import { DefaultDependencies, DependenciesApi, LifecycleApi, PluginApi as PluginApi$1, Router, RoutesApi } from "@real-router/types";
4
4
 
package/dist/cjs/api.js CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-CLGzVSB7.js"),t=require("./esm-6qkkdCI3.js"),n=require("./cloneRouter-B9QmW8WN.js");let r=require("@real-router/logger");function i(e,t,n){if(t){let n=t===e,i=t.startsWith(`${e}.`);if(n||i){let i=n?``:` (current: "${t}")`;return r.logger.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return n&&r.logger.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}function a(e){return e?(r.logger.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const o=Object.freeze({replace:!0,revalidate:!0});function s(t,n,r,i){let a=e=>e===t||e.startsWith(`${t}.`);e.v(n.decoders,a),e.v(n.encoders,a),e.v(n.defaultParams,a),e.v(n.forwardMap,a),e.v(n.forwardFnMap,a),e.v(r,a),e.v(n.forwardMap,e=>a(n.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 c(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function l(e,t,n,r){let i={name:e.name,path:e.path};return c(i,t,n,r),e.children&&(i.children=e.children.map(e=>l(e,`${t}.${e.name}`,n,r))),i}function u(e,t,n,r){let i={name:e,path:t};return c(i,e,n,r),Object.freeze(i)}function d(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,u(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function f(e,t){let n=`${t}.`,r=d(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function p(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(u(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function m(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 h(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function g(t,n,r){e.a(t,n,r);let i=e.u(t,n,r);t.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),e.i(t,i)}function _(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,o)}function v(t,n,r,i,a){e.c(n,`addRoute`),e.o(n,``,`addRoute`),e.s(n,``,`addRoute`);let o=e.d(n,t.rootPath,t.matcherOptions);t.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=e.m(o,t.depsStore);if(t.lifecycleNamespace.clearDefinitionGuards(),e.i(t,o,s),a?.(),i!==void 0){let n=r.matchPath(i.path,r.getOptions());if(n)if(n.name===i.name)_(r,{...n,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o}=e.r(n,i);t.lifecycleNamespace.canNavigateTo(a,o,n,i)?_(r,{...n,transition:i.transition},i):r.navigateToNotFound(i.path)}else r.navigateToNotFound(i.path)}}function y(t,n){let r=t.definitions;return e.y(r,n)?(s(n,t.config,t.routeCustomFields,t.lifecycleNamespace),e.p(t,r),!0):!1}function b(e,n){let r=e.matcher.getSegmentsByName(n);if(!r)return;let i=t.i(r.at(-1)),a=e.lifecycleNamespace.getFactories();return l(i,n,e.config,a)}const x=new WeakMap;function S(o){let s=x.get(o);if(s)return s;let c=t.l(o),l=c.routeGetStore(),u=e=>{c.treeChanged.emit(e)},_={add:(t,r)=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let i=Array.isArray(t)?t:[t],a=r?.parent;if(e.b(i,c.validator),a!==void 0&&c.validator?.routes.validateParentOption(a,l.tree),c.validator?.routes.throwIfInternalRouteInArray(i,`addRoute`),c.validator?.routes.validateAddRouteArgs(i),c.validator?.routes.validateRoutes(i,l,a),g(l,i,a),c.treeChanged.listenerCount()>0){let e=p(i,a,l);u(a===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:a})}},remove:t=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateRemoveRouteArgs(t),c.validator?.routes.throwIfInternalRoute(t,`removeRoute`),e.l(t,`removeRoute`),!i(t,c.getStateName(),c.isTransitioning()))return;let a=c.treeChanged.listenerCount()>0?f(l,t):void 0;if(!y(l,t)){r.logger.warn(`router.removeRoute`,`Route "${t}" not found. No changes made.`);return}a!==void 0&&u({op:`remove`,name:t,removedSubtree:a})},update:(t,i)=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateUpdateRouteBasicArgs(t,i),c.validator?.routes.throwIfInternalRoute(t,`updateRoute`),e.l(t,`updateRoute`),c.validator?.routes.validateUpdateRoutePropertyTypes(t,i),c.isTransitioning()&&r.logger.error(`router.updateRoute`,`Updating route "${t}" while navigation is in progress. This may cause unexpected behavior.`),c.validator?.routes.validateUpdateRoute(t,i,l),!l.matcher.hasRoute(t))return;let a=l.lifecycleNamespace,o=e.f(l,a,t,i);if(c.treeChanged.listenerCount()>0){let e=h(o);Object.keys(e).length>0&&u({op:`update`,name:t,patch:e})}},clear:()=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),!a(c.isTransitioning()))return;let t=c.treeChanged.listenerCount()>0?Object.freeze([...d(l,()=>!0).values()]):void 0;e.h(l),l.lifecycleNamespace.clearAll(),c.clearState(),t!==void 0&&u({op:`clear`,removed:t})},has:e=>(c.validator?.routes.validateRouteName(e,`hasRoute`),l.matcher.hasRoute(e)),get:e=>(c.validator?.routes.validateRouteName(e,`getRoute`),b(l,e)),replace:t=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t];if(!a(c.isTransitioning()))return;e.b(r,c.validator),c.validator?.routes.throwIfInternalRouteInArray(r,`replaceRoutes`),c.validator?.routes.validateAddRouteArgs(r),c.validator?.routes.validateRoutes(r,l);let i=o.getState(),s=c.treeChanged.listenerCount()>0?d(l,()=>!0):void 0;v(l,r,c,i,s===void 0?void 0:()=>{let{removed:e,added:t}=m(s,d(l,()=>!0));u({op:`replace`,removed:e,added:t})})},subscribeChanges:e=>c.treeChanged.subscribe(e)};return x.set(o,_),_}function C(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 w(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 T(e){let r=t.l(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),n=t.dependencies[e];return r.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>({...r.dependenciesGetStore().dependencies}),set:(e,t)=>{n.i(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),C(r.dependenciesGetStore(),e,t,r.validator)},setAll:e=>{n.i(r.isDisposed);let t=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),w(t,e,r.validator)},remove:e=>{n.i(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=r.dependenciesGetStore();Object.hasOwn(t.dependencies,e)||r.validator?.dependencies.warnRemoveNonExistent(e),delete t.dependencies[e]},reset:()=>{n.i(r.isDisposed);let e=r.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(r.dependenciesGetStore().dependencies,e))}}exports.cloneRouter=n.t,exports.getDependenciesApi=T,exports.getLifecycleApi=n.n,exports.getPluginApi=n.r,exports.getRoutesApi=S;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-27ftBmfo.js"),t=require("./esm-egdCFOaS.js"),n=require("./cloneRouter-B1tPtpNE.js");let r=require("@real-router/logger");function i(e,t,n){if(t){let n=t===e,i=t.startsWith(`${e}.`);if(n||i){let i=n?``:` (current: "${t}")`;return r.logger.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return n&&r.logger.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}function a(e){return e?(r.logger.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const o=Object.freeze({replace:!0,revalidate:!0});function s(t,n,r,i){let a=e=>e===t||e.startsWith(`${t}.`);e.v(n.decoders,a),e.v(n.encoders,a),e.v(n.defaultParams,a),e.v(n.forwardMap,a),e.v(n.forwardFnMap,a),e.v(r,a),e.v(n.forwardMap,e=>a(n.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 c(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function l(e,t,n,r){let i={name:e.name,path:e.path};return c(i,t,n,r),e.children&&(i.children=e.children.map(e=>l(e,`${t}.${e.name}`,n,r))),i}function u(e,t,n,r){let i={name:e,path:t};return c(i,e,n,r),Object.freeze(i)}function d(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,u(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function f(e,t){let n=`${t}.`,r=d(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function p(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(u(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function m(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 h(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function g(t,n,r){e.a(t,n,r);let i=e.u(t,n,r);t.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),e.i(t,i)}function _(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,o)}function v(t,n,r,i,a){e.c(n,`addRoute`),e.o(n,``,`addRoute`),e.s(n,``,`addRoute`);let o=e.d(n,t.rootPath,t.matcherOptions);t.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=e.m(o,t.depsStore);if(t.lifecycleNamespace.clearDefinitionGuards(),e.i(t,o,s),a?.(),i!==void 0){let n=r.matchPath(i.path,r.getOptions());if(n)if(n.name===i.name)_(r,{...n,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o}=e.r(n,i);t.lifecycleNamespace.canNavigateTo(a,o,n,i)?_(r,{...n,transition:i.transition},i):r.navigateToNotFound(i.path)}else r.navigateToNotFound(i.path)}}function y(t,n){let r=t.definitions;return e.y(r,n)?(s(n,t.config,t.routeCustomFields,t.lifecycleNamespace),e.p(t,r),!0):!1}function b(e,n){let r=e.matcher.getSegmentsByName(n);if(!r)return;let i=t.i(r.at(-1)),a=e.lifecycleNamespace.getFactories();return l(i,n,e.config,a)}const x=new WeakMap;function S(o){let s=x.get(o);if(s)return s;let c=t.l(o),l=c.routeGetStore(),u=e=>{c.treeChanged.emit(e)},_={add:(t,r)=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let i=Array.isArray(t)?t:[t],a=r?.parent;if(e.b(i,c.validator),a!==void 0&&c.validator?.routes.validateParentOption(a,l.tree),c.validator?.routes.throwIfInternalRouteInArray(i,`addRoute`),c.validator?.routes.validateAddRouteArgs(i),c.validator?.routes.validateRoutes(i,l,a),g(l,i,a),c.treeChanged.listenerCount()>0){let e=p(i,a,l);u(a===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:a})}},remove:t=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateRemoveRouteArgs(t),c.validator?.routes.throwIfInternalRoute(t,`removeRoute`),e.l(t,`removeRoute`),!i(t,c.getStateName(),c.isTransitioning()))return;let a=c.treeChanged.listenerCount()>0?f(l,t):void 0;if(!y(l,t)){r.logger.warn(`router.removeRoute`,`Route "${t}" not found. No changes made.`);return}a!==void 0&&u({op:`remove`,name:t,removedSubtree:a})},update:(t,i)=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateUpdateRouteBasicArgs(t,i),c.validator?.routes.throwIfInternalRoute(t,`updateRoute`),e.l(t,`updateRoute`),c.validator?.routes.validateUpdateRoutePropertyTypes(t,i),c.isTransitioning()&&r.logger.error(`router.updateRoute`,`Updating route "${t}" while navigation is in progress. This may cause unexpected behavior.`),c.validator?.routes.validateUpdateRoute(t,i,l),!l.matcher.hasRoute(t))return;let a=l.lifecycleNamespace,o=e.f(l,a,t,i);if(c.treeChanged.listenerCount()>0){let e=h(o);Object.keys(e).length>0&&u({op:`update`,name:t,patch:e})}},clear:()=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),!a(c.isTransitioning()))return;let t=c.treeChanged.listenerCount()>0?Object.freeze([...d(l,()=>!0).values()]):void 0;e.h(l),l.lifecycleNamespace.clearAll(),c.clearState(),t!==void 0&&u({op:`clear`,removed:t})},has:e=>(c.validator?.routes.validateRouteName(e,`hasRoute`),l.matcher.hasRoute(e)),get:e=>(c.validator?.routes.validateRouteName(e,`getRoute`),b(l,e)),replace:t=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t];if(!a(c.isTransitioning()))return;e.b(r,c.validator),c.validator?.routes.throwIfInternalRouteInArray(r,`replaceRoutes`),c.validator?.routes.validateAddRouteArgs(r),c.validator?.routes.validateRoutes(r,l);let i=o.getState(),s=c.treeChanged.listenerCount()>0?d(l,()=>!0):void 0;v(l,r,c,i,s===void 0?void 0:()=>{let{removed:e,added:t}=m(s,d(l,()=>!0));u({op:`replace`,removed:e,added:t})})},subscribeChanges:e=>c.treeChanged.subscribe(e)};return x.set(o,_),_}function C(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 w(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 T(e){let r=t.l(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),n=t.dependencies[e];return r.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>({...r.dependenciesGetStore().dependencies}),set:(e,t)=>{n.i(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),C(r.dependenciesGetStore(),e,t,r.validator)},setAll:e=>{n.i(r.isDisposed);let t=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),w(t,e,r.validator)},remove:e=>{n.i(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=r.dependenciesGetStore();Object.hasOwn(t.dependencies,e)||r.validator?.dependencies.warnRemoveNonExistent(e),delete t.dependencies[e]},reset:()=>{n.i(r.isDisposed);let e=r.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(r.dependenciesGetStore().dependencies,e))}}exports.cloneRouter=n.t,exports.getDependenciesApi=T,exports.getLifecycleApi=n.n,exports.getPluginApi=n.r,exports.getRoutesApi=S;
2
2
  //# sourceMappingURL=api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","names":["buildAddArtifacts","buildReplaceArtifacts","compileArtifactGuards","getTransitionPath","removeFromDefinitions","nodeToDefinition","getInternals","commitRouteUpdate","getInternals"],"sources":["../../src/namespaces/RoutesNamespace/routeGuards.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts"],"sourcesContent":["import { logger } from \"@real-router/logger\";\n\n/**\n * Validates removeRoute constraints.\n * Returns false if removal should be blocked (route is active).\n * Logs warnings for edge cases.\n *\n * @param name - Route name to remove\n * @param currentStateName - Current active route name (or undefined)\n * @param isNavigating - Whether navigation is in progress\n * @returns true if removal can proceed, false if blocked\n */\nexport function validateRemoveRoute(\n name: string,\n currentStateName: string | undefined,\n isNavigating: boolean,\n): boolean {\n if (currentStateName) {\n const isExactMatch = currentStateName === name;\n const isParentOfCurrent = currentStateName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentStateName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return false;\n }\n }\n\n if (isNavigating) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n return true;\n}\n\n/**\n * Validates clearRoutes operation.\n * Returns false if operation should be blocked (navigation in progress).\n *\n * @param isNavigating - Whether navigation is in progress\n * @returns true if clearRoutes can proceed, false if blocked\n */\nexport function validateClearRoutes(isNavigating: boolean): boolean {\n if (isNavigating) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return false;\n }\n\n return true;\n}\n","import { logger } from \"@real-router/logger\";\nimport { nodeToDefinition } from \"route-tree\";\n\nimport { throwIfDisposed, throwIfReentrantTreeMutation } from \"./helpers\";\nimport { guardRouteStructure } from \"../guards\";\nimport { getInternals } from \"../internals\";\nimport {\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 { RouterInternals } from \"../internals\";\nimport type { RouteLifecycleNamespace, RouteConfig } from \"../namespaces\";\nimport type { RoutesStore } from \"../namespaces/RoutesNamespace\";\nimport type { GuardFnFactory, Route } from \"../types\";\nimport type {\n DefaultDependencies,\n ForwardToCallback,\n NavigationOptions,\n Params,\n Router,\n State,\n TreeChangedEvent,\n TreeStructuralPatch,\n} from \"@real-router/types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\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.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.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 decodeParams?: ((params: Params) => Params) | null | undefined;\n encodeParams?: ((params: Params) => Params) | 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.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,\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);\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 );\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 );\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);\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 );\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 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 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());\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());\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","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { DependenciesApi } from \"./types\";\nimport type { DependenciesStore } from \"../namespaces\";\nimport type { RouterValidator } from \"../types/RouterValidator\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\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":"sNAYA,SAAgB,EACd,EACA,EACA,EACS,CACT,GAAI,EAAkB,CACpB,IAAM,EAAe,IAAqB,EACpC,EAAoB,EAAiB,WAAW,GAAG,EAAK,EAAE,EAEhE,GAAI,GAAgB,EAAmB,CACrC,IAAM,EAAS,EAAe,GAAK,eAAe,EAAiB,IAOnE,OALA,EAAA,OAAO,KACL,qBACA,wB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,SACN,CACF,EACA,OAAS,GAAS,CAChB,EAAA,EAAgB,EAAI,UAAU,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,EAAgB,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
+ {"version":3,"file":"api.js","names":["buildAddArtifacts","buildReplaceArtifacts","compileArtifactGuards","getTransitionPath","removeFromDefinitions","nodeToDefinition","getInternals","commitRouteUpdate","getInternals"],"sources":["../../src/namespaces/RoutesNamespace/routeGuards.ts","../../src/api/getRoutesApi.ts","../../src/api/getDependenciesApi.ts"],"sourcesContent":["import { logger } from \"@real-router/logger\";\n\n/**\n * Validates removeRoute constraints.\n * Returns false if removal should be blocked (route is active).\n * Logs warnings for edge cases.\n *\n * @param name - Route name to remove\n * @param currentStateName - Current active route name (or undefined)\n * @param isNavigating - Whether navigation is in progress\n * @returns true if removal can proceed, false if blocked\n */\nexport function validateRemoveRoute(\n name: string,\n currentStateName: string | undefined,\n isNavigating: boolean,\n): boolean {\n if (currentStateName) {\n const isExactMatch = currentStateName === name;\n const isParentOfCurrent = currentStateName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentStateName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return false;\n }\n }\n\n if (isNavigating) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n return true;\n}\n\n/**\n * Validates clearRoutes operation.\n * Returns false if operation should be blocked (navigation in progress).\n *\n * @param isNavigating - Whether navigation is in progress\n * @returns true if clearRoutes can proceed, false if blocked\n */\nexport function validateClearRoutes(isNavigating: boolean): boolean {\n if (isNavigating) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return false;\n }\n\n return true;\n}\n","import { logger } from \"@real-router/logger\";\nimport { nodeToDefinition } from \"engine\";\n\nimport { throwIfDisposed, throwIfReentrantTreeMutation } from \"./helpers\";\nimport { guardRouteStructure } from \"../guards\";\nimport { getInternals } from \"../internals\";\nimport {\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 { RouterInternals } from \"../internals\";\nimport type { RouteLifecycleNamespace, RouteConfig } from \"../namespaces\";\nimport type { RoutesStore } from \"../namespaces/RoutesNamespace\";\nimport type { GuardFnFactory, Route } from \"../types\";\nimport type {\n DefaultDependencies,\n ForwardToCallback,\n NavigationOptions,\n Params,\n Router,\n State,\n TreeChangedEvent,\n TreeStructuralPatch,\n} from \"@real-router/types\";\nimport type { RouteDefinition, RouteTree } from \"engine\";\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.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.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 decodeParams?: ((params: Params) => Params) | null | undefined;\n encodeParams?: ((params: Params) => Params) | 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.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,\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);\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 );\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 );\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);\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 );\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 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 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());\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());\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","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { DependenciesApi } from \"./types\";\nimport type { DependenciesStore } from \"../namespaces\";\nimport type { RouterValidator } from \"../types/RouterValidator\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\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":"sNAYA,SAAgB,EACd,EACA,EACA,EACS,CACT,GAAI,EAAkB,CACpB,IAAM,EAAe,IAAqB,EACpC,EAAoB,EAAiB,WAAW,GAAG,EAAK,EAAE,EAEhE,GAAI,GAAgB,EAAmB,CACrC,IAAM,EAAS,EAAe,GAAK,eAAe,EAAiB,IAOnE,OALA,EAAA,OAAO,KACL,qBACA,wBAAwB,EAAK,4BAA4B,EAAO,uBAClE,EAEO,EACT,CACF,CASA,OAPI,GACF,EAAA,OAAO,KACL,qBACA,UAAU,EAAK,+EACjB,EAGK,EACT,CASA,SAAgB,EAAoB,EAAgC,CAUlE,OATI,GACF,EAAA,OAAO,MACL,qBACA,uFACF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W,aAAa,sBAAsB,CAAI,EAGxD,OAAQ,EAAM,aAAyC,EACzD,EACA,UAAa,CACX,EAAA,EAAgB,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 +1,2 @@
1
- const e=require("./Router-CLGzVSB7.js"),t=require("./esm-6qkkdCI3.js");function n(t){if(t())throw new e.n(e.C.ROUTER_DISPOSED)}function r(t){if(t())throw new e.n(e.C.REENTRANT_TREE_MUTATION)}const i=new WeakMap;function a(r){let a=i.get(r);if(a)return a;let o=t.l(r),s={makeState:(e,t,n,r)=>(o.validator?.state.validateMakeStateArgs(e,t,n),o.makeState(e,t,n,r?.params)),buildState:(e,t)=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=o.forwardState(e,t);return o.buildStateResolved(n,r)},forwardState:(e,t)=>(o.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),o.forwardState(e,t)),matchPath:e=>(o.validator?.routes.validateMatchPathArgs(e),o.matchPath(e,o.getOptions())),navigateToState:(e,t)=>(n(o.isDisposed),o.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&o.validator?.navigation.validateNavigationOptions(t,`navigateToState`),o.navigateToState(e,t)),setRootPath:e=>{n(o.isDisposed),o.validator?.routes.validateSetRootPathArgs(e),o.setRootPath(e)},getRootPath:o.getRootPath,addEventListener:(e,t)=>(n(o.isDisposed),o.validator?.eventBus.validateListenerArgs(e,t),o.addEventListener(e,t)),buildNavigationState:(e,t={})=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=o.forwardState(e,t),i=o.buildStateResolved(n,r);if(i)return o.makeState(i.name,i.params,o.buildPath(i.name,i.params),i.meta)},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{n(o.isDisposed),o.validator?.plugins.validateAddInterceptorArgs(e,t);let r=o.interceptors.get(e);r||(r=[],o.interceptors.set(e,r)),r.push(t);let i=!1;return()=>{i||(i=!0,r.splice(r.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{n(o.isDisposed);let i=Object.keys(t);for(let t of i)if(t in r)throw new e.n(e.C.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of i)r[e]=t[e];let a={keys:i};o.routerExtensions.push(a);let s=!1;return()=>{if(s)return;s=!0;for(let e of a.keys)delete r[e];let e=o.routerExtensions.indexOf(a);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{n(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:t=>{if(n(o.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(o.contextClaimRecords.has(t))throw new e.n(e.C.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return o.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(){o.contextClaimRecords.delete(t)}}}};return i.set(r,s),s}function o(e){let r=t.l(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t)},addDeactivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t)},removeActivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}function s(n,r){let i=t.l(n);if(i.isDisposed())throw new e.n(e.C.ROUTER_DISPOSED);i.validator?.dependencies.validateCloneArgs(r);let a=i.routeGetStore(),s=t.r(a.tree),c=a.config,l=a.resolvedForwardMap,u=a.routeCustomFields,{options:d,dependencies:f,pluginFactories:p}=i.getCloneState(),{definition:m,external:h}=a.lifecycleNamespace.getFactoriesByOrigin(),g=new e.t(s,d,{...f,...r}),_=t.l(g),v=_.routeGetStore(),y=v.lifecycleNamespace;e._(v.config,c),Object.assign(v.resolvedForwardMap,l),Object.assign(v.routeCustomFields,u),a.rootPath!==``&&_.setRootPath(a.rootPath);let[b,x]=m,[S,C]=h;for(let[e,t]of Object.entries(b))y.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(x))y.addCanActivate(e,t,!0);let w=o(g);for(let[e,t]of Object.entries(S))w.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(C))w.addActivateGuard(e,t);let T=new Set(_.getCloneState().pluginFactories),E=p.filter(e=>!T.has(e));return E.length>0&&g.usePlugin(...E),g}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
2
- //# sourceMappingURL=cloneRouter-B9QmW8WN.js.map
1
+ const e=require("./Router-27ftBmfo.js"),t=require("./esm-egdCFOaS.js");function n(t){if(t())throw new e.n(e.C.ROUTER_DISPOSED)}function r(t){if(t())throw new e.n(e.C.REENTRANT_TREE_MUTATION)}const i=new WeakMap;function a(r){let a=i.get(r);if(a)return a;let o=t.l(r),s={makeState:(e,t,n,r)=>(o.validator?.state.validateMakeStateArgs(e,t,n),o.makeState(e,t,n,r?.params)),buildState:(e,t)=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=o.forwardState(e,t);return o.buildStateResolved(n,r)},forwardState:(e,t)=>(o.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),o.forwardState(e,t)),matchPath:e=>(o.validator?.routes.validateMatchPathArgs(e),o.matchPath(e,o.getOptions())),navigateToState:(e,t)=>(n(o.isDisposed),o.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&o.validator?.navigation.validateNavigationOptions(t,`navigateToState`),o.navigateToState(e,t)),setRootPath:e=>{n(o.isDisposed),o.validator?.routes.validateSetRootPathArgs(e),o.setRootPath(e)},getRootPath:o.getRootPath,addEventListener:(e,t)=>(n(o.isDisposed),o.validator?.eventBus.validateListenerArgs(e,t),o.addEventListener(e,t)),buildNavigationState:(e,t={})=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=o.forwardState(e,t),i=o.buildStateResolved(n,r);if(i)return o.makeState(i.name,i.params,o.buildPath(i.name,i.params),i.meta)},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{n(o.isDisposed),o.validator?.plugins.validateAddInterceptorArgs(e,t);let r=o.interceptors.get(e);r||(r=[],o.interceptors.set(e,r)),r.push(t);let i=!1;return()=>{i||(i=!0,r.splice(r.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{n(o.isDisposed);let i=Object.keys(t);for(let t of i)if(t in r)throw new e.n(e.C.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of i)r[e]=t[e];let a={keys:i};o.routerExtensions.push(a);let s=!1;return()=>{if(s)return;s=!0;for(let e of a.keys)delete r[e];let e=o.routerExtensions.indexOf(a);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{n(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:t=>{if(n(o.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(o.contextClaimRecords.has(t))throw new e.n(e.C.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return o.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(){o.contextClaimRecords.delete(t)}}}};return i.set(r,s),s}function o(e){let r=t.l(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t)},addDeactivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t)},removeActivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}function s(n,r){let i=t.l(n);if(i.isDisposed())throw new e.n(e.C.ROUTER_DISPOSED);i.validator?.dependencies.validateCloneArgs(r);let a=i.routeGetStore(),s=t.a(a.tree),c=a.config,l=a.resolvedForwardMap,u=a.routeCustomFields,{options:d,dependencies:f,pluginFactories:p}=i.getCloneState(),{definition:m,external:h}=a.lifecycleNamespace.getFactoriesByOrigin(),g=new e.t(s,d,{...f,...r}),_=t.l(g),v=_.routeGetStore(),y=v.lifecycleNamespace;e._(v.config,c),Object.assign(v.resolvedForwardMap,l),Object.assign(v.routeCustomFields,u),a.rootPath!==``&&_.setRootPath(a.rootPath);let[b,x]=m,[S,C]=h;for(let[e,t]of Object.entries(b))y.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(x))y.addCanActivate(e,t,!0);let w=o(g);for(let[e,t]of Object.entries(S))w.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(C))w.addActivateGuard(e,t);let T=new Set(_.getCloneState().pluginFactories),E=p.filter(e=>!T.has(e));return E.length>0&&g.usePlugin(...E),g}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
2
+ //# sourceMappingURL=cloneRouter-B1tPtpNE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloneRouter-B1tPtpNE.js","names":["RouterError","errorCodes","getInternals","RouterError","errorCodes","getInternals","getInternals","RouterError","errorCodes","routeTreeToDefinitions","RouterClass"],"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.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","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"@real-router/types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n Record<string, Record<string, \"url\" | \"query\">> | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n // Input-shape guard, symmetric with the other always-on invariant guards\n // (subscribe / start / navigateToNotFound each typeof-check their input).\n // A non-string namespace coerces to an inconsistent key (\"42\"); an empty\n // string is a meaningless namespace (#1191 N4).\n if (typeof namespace !== \"string\" || namespace === \"\") {\n throw new TypeError(\n `[claimContextNamespace] namespace must be a non-empty string, got ${\n typeof namespace === \"string\" ? \"an empty string\" : typeof namespace\n }`,\n );\n }\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n // `state.context[namespace] = value` dispatches into the inherited\n // Object.prototype.__proto__ setter for the literal key \"__proto__\",\n // swapping the prototype instead of creating an own entry — the data\n // then vanishes from Object.keys / serializeRouterState (#1191 N3).\n // Mirror search-params' assignParam: defineProperty writes a genuine\n // own property; normal names keep the plain-assignment fast path.\n if (namespace === \"__proto__\") {\n Object.defineProperty(state.context, namespace, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n state.context[namespace] = value;\n }\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"@real-router/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","import { routeTreeToDefinitions } from \"engine\";\n\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\n\nimport type { Route } from \"../types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\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/core/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): 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 } = 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 const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n options,\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":"uEAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAIA,EAAAA,EAAYC,EAAAA,EAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAID,EAAAA,EAAYC,EAAAA,EAAW,uBAAuB,CAE5D,CCFA,MAAM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAMC,EAAAA,EAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAM,KAC9B,EAAI,WAAW,MAAM,sBAAsB,EAAM,EAAQ,CAAI,EAEtD,EAAI,UACT,EACA,EACA,EACA,GAAM,MAER,GAEF,YAAa,EAAW,IAAgB,CACtC,EAAI,WAAW,OAAO,yBACpB,EACA,EACA,YACF,EAEA,GAAM,CAAE,OAAM,UAAW,EAAI,aAAa,EAAW,CAAW,EAEhE,OAAO,EAAI,mBAAmB,EAAM,CAAM,CAC5C,EACA,cACE,EACA,KAEA,EAAI,WAAW,OAAO,yB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BAEhC,CACJ,UACA,aAAc,EACd,mBACE,EAAI,cAAc,EAOhB,CAAE,WAAY,EAAqB,SAAU,GADlB,EAAY,mBAElB,qBAAqB,EAO1C,EAAY,IAAIC,EAAAA,EACpB,EACA,EACA,CAPA,GAAG,EACH,GAAG,CAMM,CACX,EAEM,EAASJ,EAAAA,EAAa,CAAS,EAC/B,EAAW,EAAO,cAAc,EAEhC,EAAwB,EAAS,mBAUvC,EAAA,EAAoB,EAAS,OAAQ,CAAW,EAChD,OAAO,OAAO,EAAS,mBAAoB,CAAkB,EAC7D,OAAO,OAAO,EAAS,kBAAmB,CAAiB,EASvD,EAAY,WAAa,IAC3B,EAAO,YAAY,EAAY,QAAQ,EAGzC,GAAM,CAAC,EAAsB,GAAsB,EAC7C,CAAC,EAAoB,GAAoB,EAE/C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAoB,EAC/D,EAAsB,iBAAiB,EAAM,EAAS,EAAI,EAG5D,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAkB,EAC7D,EAAsB,eAAe,EAAM,EAAS,EAAI,EAG1D,IAAM,EAAY,EAAgB,CAAS,EAE3C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAkB,EAC7D,EAAU,mBAAmB,EAAM,CAAO,EAG5C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAgB,EAC3D,EAAU,iBAAiB,EAAM,CAAO,EAO1C,IAAM,EAAoB,IAAI,IAAI,EAAO,cAAc,CAAC,CAAC,eAAe,EAClE,EAAkB,EAAgB,OACrC,GAAY,CAAC,EAAkB,IAAI,CAAO,CAC7C,EAOA,OAJI,EAAgB,OAAS,GAC3B,EAAU,UAAU,GAAG,CAAe,EAGjC,CACT"}
@@ -0,0 +1,2 @@
1
+ const e=new WeakMap;function t(t){let n=e.get(t);if(!n)throw TypeError(`[real-router] Invalid router instance — not found in internals registry`);return n}function n(t,n){e.set(t,n)}function r(e,t,n){let r=t;for(let t of e){let e=r;r=(...n)=>t(e,...n)}return r(...n)}function i(e,t,n){return((...i)=>{let a=n.get(e);return!a||a.length===0?t(...i):r(a,t,i)})}function a(e,t,n){return(i,a)=>{let o=n.get(e);return!o||o.length===0?t(i,a):r(o,t,[i,a])}}function o(e,t){let n=e.path,r=n.startsWith(`~`),i=r?n.slice(1):n,a={name:e.name,path:i,absolute:r,children:[],parent:t};if(e.children)for(let t of e.children){let e=o(t,a);a.children.push(e)}return a}function s(e,t,n){let r=o({name:e,path:t},null);for(let e of n){let t=o(e,r);r.children.push(t)}return r}const c=`[^>]*`;function l(e){let t=!1;for(let n of e)if(n===`<`)t=!0;else if(n===`>`){if(!t)return!1;t=!1}return!t}const u=/[<>]/u,d=e=>e===58||e===42;function f(e){let t=[],n=0,r=!1;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);a===60?r=!0:a===62?r=!1:a===47&&!r&&(t.push(e.slice(n,i)),n=i+1)}return t.push(e.slice(n)),t}function p(e){let t=e.length;if(t===0)return{kind:`static`,text:``};if(!d(e.charCodeAt(0))){for(let n=0;n<t;n+=1){let r=e.charCodeAt(n);if(r===60)return{error:`constraint-in-static`};if(d(r)&&n+1<t&&e.charCodeAt(n+1)!==60)return{error:`fused-marker`}}return e.charCodeAt(t-1)===63?{error:`name-less`}:{kind:`static`,text:e}}let n=e.charCodeAt(0)===42,r=1;for(;r<t;){let t=e.charCodeAt(r);if(t===60||t===63)break;r+=1}let i=e.slice(1,r);if(i.length===0)return{error:`name-less`};if(d(i.charCodeAt(i.length-1)))return{error:`trailing-marker`};let a,o=!1;if(r<t)if(e.charCodeAt(r)===60){let n=e.indexOf(`>`,r+1);if(n===-1)return{error:`unbalanced-constraint`};if(n===r+1)return{error:`empty-constraint`};a=e.slice(r,n+1);let i=n+1;if(i<t)if(e.charCodeAt(i)===63)o=!0;else return{error:`fused-constraint-suffix`}}else o=!0;return n?o?{error:`optional-splat`}:{kind:`splat`,name:i}:a===void 0?{kind:`param`,name:i,optional:o}:{kind:`param`,name:i,constraint:a,optional:o}}function m(e){for(let t of f(e)){let e=p(t);if(`error`in e)return e.error}}function h(e){let t=f(e);for(let e=2;e<t.length;e+=1)if(t[e].startsWith(`*`)&&g(t[e-1])&&g(t[e-2]))return!0;return!1}function g(e){return e.startsWith(`:`)&&e.endsWith(`?`)}function ee(e){return`(${e.slice(1,-1)})`}function te(e,t){try{return RegExp(`^${ee(e)}$`)}catch{throw Error(`[buildParamMeta] Invalid constraint '${e}' on parameter '${t}': the body between '<' and '>' must be a valid regular expression (e.g. '<[0-9]+>', '<[a-z]+>').`)}}const ne=new RegExp(String.raw`([:*]${`[^/?<]+`}(?:<${c}>)?)\?(?=[/?]|$)`,`g`),re=RegExp(`<${c}>`,`g`),ie=/\?(.+)$/;function ae(e){return e.replaceAll(re,e=>`<${`x`.repeat(e.length-2)}>`).replaceAll(ne,`$1\0`)}const _=Object.freeze([]),v=Object.freeze({}),oe=new Map,se=Object.freeze({urlParams:_,queryParams:_,spatParams:_,paramTypeMap:v,constraintPatterns:oe,pathPattern:``});function ce(e,t,n,r,i){for(let a of f(e)){if(a.length===0)continue;let e=p(a);`error`in e||e.kind===`static`||(t.push(e.name),r[e.name]=`url`,e.kind===`splat`?n.push(e.name):e.constraint!==void 0&&i.set(e.name,{pattern:te(e.constraint,e.name),constraint:e.constraint}))}}function le(e){let t=[],n=[],r=[],i={},a=new Map,o=ie.exec(ae(e));if(o!==null){let t=e.slice(o.index+1).split(`&`);for(let e of t){let t=e.trim();t.length>0&&(n.push(t),i[t]=`query`)}e=e.slice(0,o.index)}return ce(e,t,r,i,a),ue(t,n,r,i,a,e)}function ue(e,t,n,r,i,a){return{urlParams:e.length===0?_:e,queryParams:t.length===0?_:t,spatParams:n.length===0?_:n,paramTypeMap:e.length===0&&t.length===0?v:r,constraintPatterns:i.size===0?oe:i,pathPattern:a}}const de=/[^\w!$'()*+,.:;|~-]/gu,fe=/[^\w!$'()*+,.:;|~-]/u,pe=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,y=e=>t=>{try{return e(t)}catch{return e(t.replaceAll(pe,`�`))}},me=y(e=>e.replaceAll(de,e=>encodeURIComponent(e))),b={default:e=>fe.test(e)?me(e):e,uri:y(encodeURI),uriComponent:y(encodeURIComponent),none:e=>e},he={default:decodeURIComponent,uri:decodeURI,uriComponent:decodeURIComponent,none:e=>e},ge=(e,t)=>{let n=b[t],r=String(e).split(`/`),i=n(r[0]);for(let e=1;e<r.length;e++)i+=`/`+n(r[e]);return i},x=Object.freeze(Object.create(null));function S(){return{staticChildren:x,hasChildren:!1,paramChild:void 0,splatChild:void 0,route:void 0,routeIsStrong:!1,slashChildRoute:void 0}}function C(e){return e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e}function _e(e,t){return e===``?t:t===``?e:e+t}function w(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ve(e){let t=0;for(;t<e.length;)if(e.codePointAt(t)===37){if(t+2>=e.length)return!1;let n=e.codePointAt(t+1)??0,r=e.codePointAt(t+2)??0;if(!w(n)||!w(r))return!1;t+=3}else t++;return!0}const ye=Object.freeze([]),T=Object.freeze(new Set),be=Object.freeze(new Map),xe=Object.freeze([]),Se=Object.freeze({}),Ce=Object.freeze({}),we=RegExp(`<${c}>`,`g`);function Te(e,t,n){let r=t.has(e.name);return{paramName:e.name,isOptional:e.kind===`param`?e.optional:!1,encoder:r?e=>ge(e,n):b[n]}}function Ee(e,t,n){let r=new Set,i=new Set;for(let e of t){for(let t of e.paramMeta.urlParams)r.add(t);for(let t of e.paramMeta.spatParams)i.add(t)}if(r.size===0)return{buildStaticParts:[e],buildParamSlots:xe};let a=[],o=[],s=``,c=f(e);for(let[e,t]of c.entries()){e>0&&(s+=`/`);let r=p(t);if(`error`in r||r.kind===`static`){s+=t;continue}a.push(s),s=``,o.push(Te(r,i,n))}return a.push(s),{buildStaticParts:a,buildParamSlots:o}}function E(e,t,n){throw Error(`[SegmentMatcher.registerTree] Parameter name conflict at the same path position: '${n}${e}' and '${n}${t}'. A parametric URL segment binds to a single name across every route that shares that position — the value cannot be captured under two names. Rename one so both routes agree (e.g. use '${n}${e}' in both).`)}function D(){throw Error(`[SegmentMatcher.registerTree] Empty parameter name: a parameter marker (':' or '*') or an optional '?' must be followed by a name (e.g. ':id', '*rest', ':id?'). A name-less marker or modifier would capture under an empty key at match but emit a literal at build — the two disagree, so it is rejected.`)}function De(e){throw Error(`[SegmentMatcher.registerTree] Fused parameter marker in segment "${e}": a ':'/'*' marker must begin a segment (e.g. 'a/:b', not 'a:b'). build extracts it as a param while the trie treats the segment as a literal — the two disagree.`)}function Oe(e){throw Error(`[SegmentMatcher.registerTree] Trailing parameter marker in segment "${e}": a param name cannot end in a bare ':' or '*' (e.g. ':y*' — the name is 'y' plus a stray marker). build/meta would capture the marker into the name while the gate rejects it as name-less — the two disagree, so it is rejected.`)}function ke(e){throw Error(`[SegmentMatcher.registerTree] Two optional params directly before a splat in "${e}": a single trie slot carries only one optional→splat fork, so the outer optional would overwrite the inner and the omit-outer/take-inner form would silently reshape into the splat. Split into separate routes, or drop the '?' on one.`)}function Ae(e){throw Error(`[SegmentMatcher.registerTree] Non-ASCII static segment "${e}": match rejects non-ASCII input and compares static keys raw, so this route would never match. Percent-encode it (e.g. "/caf%C3%A9") or use a param.`)}function je(e){throw Error(`[SegmentMatcher.registerTree] Optional splat "${e}" is not supported: a splat cannot be optional — build emits multi-segment URLs the matcher rejects. Use a required splat "*name".`)}function Me(e){throw Error(`[SegmentMatcher.registerTree] Optional param ":${e}?" before a splat must be constrained: an unconstrained optional before a splat is ambiguous (every multi-segment value has two readings). Add a constraint, e.g. ":${e}<[a-z]+>?", or model it as two routes.`)}function O(e){throw Error(`[SegmentMatcher.registerTree] Unbalanced constraint delimiter ('<' or '>') in path "${e}": every '<' must be closed by a '>'. A stray delimiter desyncs match vs build (buildPath would emit a URL match rejects).`)}function Ne(e){throw Error(`[SegmentMatcher.registerTree] Empty constraint '<>' in path "${e}": a constraint body must be non-empty (e.g. '<[0-9]+>'). An empty '<>' compiles to a never-matching pattern.`)}function Pe(e){throw Error(`[SegmentMatcher.registerTree] Text fused to a constraint '>' in path "${e}": a '<...>' constraint must end its segment or be followed by '/' or an optional '?' — use "/:id<...>/rest", not "/:id<...>rest".`)}function Fe(e){throw Error(`[SegmentMatcher.registerTree] Constraint '<...>' in a static segment in path "${e}": a '<...>' constraint must follow a parameter marker (':' or '*') — a static segment carrying '<...>' is silently stripped. Attach it to a param (e.g. "/:id<...>") or drop it.`)}function Ie(e,t,n){switch(e){case`name-less`:return D();case`trailing-marker`:return Oe(t);case`fused-marker`:return De(t);case`optional-splat`:return je(t);case`empty-constraint`:return Ne(n);case`fused-constraint-suffix`:return Pe(n);case`constraint-in-static`:return Fe(n);case`unbalanced-constraint`:return O(n)}}function Le(e,t){let n=new Set,r=``;for(let e of t){if(n.has(e)){r=e;break}n.add(e)}throw Error(`[SegmentMatcher.registerTree] Duplicate parameter name ':${r}' in route "${e}": a param name must be unique within a route — two positions cannot both bind ':${r}' (the second silently overwrites the first). Rename one.`)}function Re(e,t){throw Error(`[SegmentMatcher.registerTree] Invalid query-param declaration "${t}" in route "${e}": a query-param name cannot contain '<' or '>'. This is a reverse-order modifier typo that leaked a constraint into the query — put the optional '?' AFTER the constraint (':id<...>?', not ':id?<...>'). It would never round-trip.`)}function ze(e,t){throw Error(`[SegmentMatcher.registerTree] Name collision in route "${e}": "${t}" is declared as BOTH a path param (':${t}') and a query param ('?${t}'). buildPath would emit its value twice (once in the path, once in the query). Rename one.`)}function Be(e,t){throw Error(`[SegmentMatcher.registerTree] Duplicate route path: routes "${e}" and "${t}" resolve to the same URL. The later registration would silently shadow the earlier (its deep link would resolve to the other route). Give them distinct paths.`)}function Ve(e,t){throw Error(`[SegmentMatcher.registerTree] Index route "${e}" (path "/") under the dynamic parent "${t}" is not supported: the index cannot reliably replace the parent on every form of its path — under an optional param it binds only the present form, under a splat it is unreachable. Give the index a distinct path, or make the parent static.`)}function k(e){let t=p(e);return(`error`in t||t.kind===`static`)&&D(),t.name}function A(e,t,n){return e.paramChild?e.paramChild.name!==t&&!n.has(e)&&E(e.paramChild.name,t,`:`):(e.paramChild={node:S(),name:t,fork:void 0},n.add(e)),e.paramChild.node}function He(e,t,n,r,i,a){let o=t.constraintPatterns.get(n)?.pattern;if(e.paramChild&&e.splatChild){o===void 0&&Me(n),e.paramChild.fork={constraint:o};return}let s=i+1;if(s<=a){let t=r.indexOf(`/`,s),n=r.slice(s,t===-1?a:t);e.paramChild&&n.startsWith(`:`)&&!n.endsWith(`?`)&&(e.paramChild.fork={skipName:k(n)})}}function Ue(e,t,n){if(!t.hasConstraints||!n.startsWith(`:`)||e.paramChild===void 0)return;let r=t.constraintPatterns.get(k(n))?.pattern;if(r===void 0)return;let i=e.paramChild;i.fork?.constraint===void 0?i.fork={...i.fork,constraint:r}:i.fork.constraint.source!==r.source&&(i.fork={...i.fork,constraint:RegExp(`(?:${i.fork.constraint.source})|(?:${r.source})`,i.fork.constraint.flags)})}function We(e,t,n){return e.splatChild?e.splatChild.name!==t&&!n.has(e)&&E(e.splatChild.name,t,`*`):(e.splatChild={node:S(),name:t},n.add(e)),e.splatChild.node}function j(e,t){e.route!==void 0&&e.route!==t&&e.routeIsStrong===!0&&Be(e.route.name,t.name),e.route=t,e.routeIsStrong=!0}function Ge(e){for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>=128)return!0;return!1}function Ke(e,t,n){let r=C(n);if(r===`/`){j(e.root,t);return}let i=new Set,a=new Map;M(e,e.root,r,1,t,i,a)}function M(e,t,n,r,i,a,o){let s=o.get(t);if(s===void 0)s=new Set,o.set(t,s);else if(s.has(r))return;s.add(r);let c=n.length;for(;r<=c;){let s=n.indexOf(`/`,r),l=s===-1?c:s,u=n.slice(r,l);if(u.endsWith(`?`)){let r=k(u);M(e,A(t,r,a),n,l+1,i,a,o),l>=c?t.route??=i:M(e,t,n,l+1,i,a,o),He(t,i,r,n,l,c);return}let d=t;t=N(e,t,u,a),Ue(d,i,u),r=l+1}j(t,i)}function qe(e,t,n){let r=n.slice(n.lastIndexOf(`/`)+1),i=n.split(`/`).some(e=>e.startsWith(`:`)&&e.endsWith(`?`)),a=r.startsWith(`*`);(i||a)&&Ve(t.name,n);let o=Je(e,n);o.slashChildRoute=t}function Je(e,t){return Ye(e,e.root,t)}function Ye(e,t,n){let r=C(n);if(r===`/`||r===``)return t;let i=t,a=1,o=r.length,s=new Set;for(;a<=o;){let t=r.indexOf(`/`,a),n=t===-1?o:t;if(n<=a)break;let c=r.slice(a,n);i=N(e,i,c,s),a=n+1}return i}function N(e,t,n,r){if(n.startsWith(`*`)){let e=We(t,k(n),r);return t.hasChildren=!0,e}if(n.startsWith(`:`)){let e=A(t,k(n),r);return t.hasChildren=!0,e}Ge(n)&&Ae(n);let i=e.options.caseSensitive?n:n.toLowerCase();return i in t.staticChildren||(t.staticChildren===x&&(t.staticChildren=Object.create(null)),t.staticChildren[i]=S(),t.hasChildren=!0),t.staticChildren[i]}function P(e,t,n,r,i){let a=t.fullName===``;a||r.push(t);let o=t.absolute,s=t.paramMeta===se?t.path:t.paramMeta.pathPattern,c=o&&s.startsWith(`~`)?s.slice(1):s,u=o?c:s;l(u)||O(u);for(let e of f(u)){let t=p(e);`error`in t&&Ie(t.error,e,u)}let d=u.replaceAll(we,``);h(u)&&ke(u);let m=o?d:_e(n,d),g=a?i:Xe(e,t,m,o?``:n,r,i);for(let n of t.children.values())P(e,n,m,r,g);a||r.pop()}function Xe(e,t,n,r,i,a){let o=tt(n,r),s=Object.freeze([...i]),c=Ze(s),l=C(n),u=nt(e.rootQueryParams,i),d=rt(i),{buildStaticParts:f,buildParamSlots:p}=Ee(o?C(r):l,o?i.slice(0,-1):i,e.options.urlParamsEncoding),m=p.map(e=>e.paramName),h=m.length===0?T:new Set(m);h.size!==m.length&&Le(t.fullName,m),it(t.fullName,u,h);let g={name:t.fullName,parent:a,matchSegments:s,meta:c,declaredQueryParams:u,declaredQueryParamsSet:u.length===0?T:new Set(u),hasTrailingSlash:n.length>1&&n.endsWith(`/`),constraintPatterns:d,hasConstraints:d.size>0,buildStaticParts:f,buildParamSlots:p,buildParamNamesSet:h,cachedResult:void 0};return t.paramMeta.urlParams.length===0&&(g.cachedResult=Object.freeze({segments:g.matchSegments,params:Se,meta:g.meta})),e.routesByName.set(t.fullName,g),o?$e(e,g,r):et(e,g,n,l,t),g}function Ze(e){let t;for(let n of e)Qe(n.paramTypeMap)&&(t??={},t[n.fullName]=n.paramTypeMap);return t===void 0?Ce:Object.freeze(t)}function Qe(e){for(let t in e)if(Object.hasOwn(e,t))return!0;return!1}function $e(e,t,n){qe(e,t,n);let r=C(n),i=e.options.caseSensitive?r:r.toLowerCase();e.staticCache.has(i)&&e.staticCache.set(i,t)}function et(e,t,n,r,i){if(Ke(e,t,n),i.paramMeta.urlParams.length===0){let n=e.options.caseSensitive?r:r.toLowerCase();e.staticCache.set(n,t)}}function tt(e,t){return C(e)===C(t)}function nt(e,t){let n=[];e.length>0&&n.push(...e);for(let e of t)e.paramMeta.queryParams.length>0&&n.push(...e.paramMeta.queryParams);return n.length===0?ye:n}function rt(e){let t=new Map;for(let n of e)for(let[e,r]of n.paramMeta.constraintPatterns)t.set(e,r);return t.size===0?be:t}function it(e,t,n){for(let r of t)u.test(r)&&Re(e,r),n.has(r)&&ze(e,r)}function at(e){return typeof e==`string`?e:typeof e==`object`?JSON.stringify(e):String(e)}function F(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}var ot=class{get options(){return this.#e}#e;#t=S();#n=new Map;#r=new Map;#i={cleanPath:``,normalized:``,queryString:void 0};#a=[];#o=``;#s;#c;constructor(e){this.#e={caseSensitive:e.caseSensitive??!0,strictTrailingSlash:e.strictTrailingSlash??!1,strictQueryParams:e.strictQueryParams??!1,urlParamsEncoding:e.urlParamsEncoding??`default`,parseQueryString:e.parseQueryString,buildQueryString:e.buildQueryString},this.#s=this.#e.caseSensitive,this.#c=this.#e.urlParamsEncoding===`none`?null:he[this.#e.urlParamsEncoding]}registerTree(e){this.#a=e.paramMeta.queryParams,P({root:this.#t,options:this.#e,routesByName:this.#n,staticCache:this.#r,rootQueryParams:this.#a},e,``,[],null)}match(e){if(!this.#p(e))return;let{cleanPath:t,normalized:n,queryString:r}=this.#i,i=this.#s?n:n.toLowerCase(),a=this.#r.get(i);if(a)return this.#e.strictTrailingSlash&&!this.#_(t,a)?void 0:r===void 0&&a.cachedResult?a.cachedResult:this.#h(a,{},r);let o={},s=this.#v(n,o);if(s&&!(this.#e.strictTrailingSlash&&!this.#_(t,s))&&this.#S(o)&&!(s.hasConstraints&&!this.#w(o,s)))return this.#h(s,o,r)}buildPath(e,t,n){let r=this.#n.get(e);if(!r)throw Error(`[SegmentMatcher.buildPath] '${e}' is not defined`);r.hasConstraints&&t&&this.#l(r,e,t);let i=this.#u(r,t),a=this.#d(i,n?.trailingSlash),o=this.#f(r,t,n?.queryParamsMode);return a+(o?`?${o}`:``)}getSegmentsByName(e){return this.#n.get(e)?.matchSegments}getMetaByName(e){return this.#n.get(e)?.meta}hasRoute(e){return this.#n.has(e)}#l(e,t,n){for(let[r,i]of e.constraintPatterns){let e=n[r];if(e!=null){let n=typeof e==`object`?JSON.stringify(e):String(e);if(!i.pattern.test(n))throw Error(`[SegmentMatcher.buildPath] '${t}' — param '${r}' value '${n}' does not match constraint '${i.constraint}'`)}}}#u(e,t){let n=e.buildStaticParts,r=e.buildParamSlots;if(r.length===0)return n[0];let i=n[0];for(let[e,a]of r.entries()){let r=t?.[a.paramName];if(r==null){if(!a.isOptional)throw Error(`[SegmentMatcher.buildPath] Missing required param '${a.paramName}'`);i.length>1?i=i.slice(0,-1):n[e+1].startsWith(`/`)&&(i=``),i+=n[e+1];continue}if(r===``&&!a.isOptional)throw Error(`[SegmentMatcher.buildPath] Missing required param '${a.paramName}' (empty string)`);let o=a.encoder(at(r));i+=o+n[e+1]}return i}#d(e,t){return t===`always`&&!e.endsWith(`/`)?`${e}/`:t===`never`&&e!==`/`&&e.endsWith(`/`)?e.slice(0,-1):e}#f(e,t,n){if(!t||e.declaredQueryParams.length===0&&n!==`loose`)return``;let r={},i=!1;for(let n of e.declaredQueryParams)n in t&&(r[n]=t[n],i=!0);if(n===`loose`)for(let n in t)Object.hasOwn(t,n)&&!e.declaredQueryParamsSet.has(n)&&!e.buildParamNamesSet.has(n)&&(r[n]=t[n],i=!0);return i?this.#e.buildQueryString(r):``}#p(e){if(e===``&&(e=`/`),e.codePointAt(0)!==47)return!1;let t=this.#m(e);if(t===-2)return!1;t===-3&&(e=this.#o);let n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):void 0;if(r!==void 0){let e=r.indexOf(`#`);e!==-1&&(r=r.slice(0,e))}let i=C(n);return this.#i.cleanPath=n,this.#i.normalized=i,this.#i.queryString=r,!0}#m(e){let t=!1;for(let n=0;n<e.length;n++){let r=e.codePointAt(n);if(r===35)return this.#o=e.slice(0,n),-3;if(r===63)return n;if(r>=128)return-2;if(r===47){if(t)return-2;t=!0}else t=!1}return-1}#h(e,t,n){if(!(n!==void 0&&!this.#g(e,t,n)))return{segments:e.matchSegments,params:t,meta:e.meta}}#g(e,t,n){let r;try{r=this.#e.parseQueryString(n)}catch{return!1}if(this.#e.strictQueryParams){let n=e.declaredQueryParamsSet;for(let e in r){if(!n.has(e))return!1;F(t,e,r[e])}}else for(let e in r)F(t,e,r[e]);return!0}#_(e,t){return(e.length>1&&e.endsWith(`/`))===t.hasTrailingSlash}#v(e,t){return e.length===1?this.#t.slashChildRoute??this.#t.route:this.#y(this.#t,e,1,t)}#y(e,t,n,r){let i=e,a=t.length,o=this.#s;for(;n<=a;){let e=t.indexOf(`/`,n),s=e===-1?a:e,c=t.slice(n,s),l=o?c:c.toLowerCase(),u;if(l in i.staticChildren)u=i.staticChildren[l];else if(i.paramChild){let e=i.paramChild,o=e.fork;if(i.splatChild!==void 0){if(o?.constraint!==void 0&&!this.#x(o.constraint,c))return this.#b(i.splatChild,t,n,r);let l={[o?.skipName!==void 0&&s>=a?o.skipName:e.name]:c},u=this.#y(e.node,t,s+1,l);return u!==void 0&&(!u.hasConstraints||this.#C(u,l))?(Object.assign(r,l),u):this.#b(i.splatChild,t,n,r)}u=e.node,o?.skipName!==void 0&&s>=a?r[o.skipName]=c:r[e.name]=c}else if(i.splatChild)return this.#b(i.splatChild,t,n,r);else return;i=u,n=s+1}return i.slashChildRoute??i.route}#b(e,t,n,r){let i=e.node;if(!i.hasChildren)return r[e.name]=t.slice(n),i.route;let a={},o=this.#y(i,t,n,a);return o&&(!o.hasConstraints||this.#C(o,a))?(Object.assign(r,a),o):(r[e.name]=t.slice(n),i.route)}#x(e,t){try{return e.test(this.#c?this.#c(t):t)}catch{return!1}}#S(e){let t=this.#c;if(!t)return!0;for(let n in e){let r=e[n];if(r.includes(`%`)){if(!ve(r))return!1;try{e[n]=t(r)}catch{return!1}}}return!0}#C(e,t){let n=this.#c;for(let[r,i]of e.constraintPatterns){if(!Object.hasOwn(t,r))continue;let e=t[r];if(n&&e.includes(`%`))try{e=n(e)}catch{return!1}if(!i.pattern.test(e))return!1}return!0}#w(e,t){for(let[n,r]of t.constraintPatterns)if(Object.hasOwn(e,n)&&!r.pattern.test(e[n]))return!1;return!0}};const st=Object.freeze(new Map),ct=Object.freeze([]);function lt(e){return e.parent?.name?`${e.parent.fullName}.${e.name}`:e.name}function ut(e){let t=new Map;for(let n of e)t.set(n.name,n);return t}function dt(e,t){let n=[],r=[];for(let i of e){let e=I(i,t);n.push(e),e.absolute||r.push(e)}return{childrenMap:ut(n),nonAbsoluteChildren:r}}function I(e,t){let n=le(e.path),r=n.urlParams.length===0&&n.queryParams.length===0&&n.spatParams.length===0&&n.constraintPatterns.size===0&&n.pathPattern===e.path?se:n,i=r.paramTypeMap,a={name:e.name,path:e.path,absolute:e.absolute,parent:t,children:void 0,paramMeta:r,nonAbsoluteChildren:void 0,fullName:``,paramTypeMap:i};if(a.fullName=lt(a),e.children.length===0)a.children=st,a.nonAbsoluteChildren=ct;else{let{childrenMap:t,nonAbsoluteChildren:n}=dt(e.children,a);a.children=t,a.nonAbsoluteChildren=n,Object.freeze(a.nonAbsoluteChildren),Object.freeze(a.children)}return Object.freeze(i),Object.freeze(r.urlParams),Object.freeze(r.queryParams),Object.freeze(r.spatParams),Object.freeze(r),Object.freeze(a),a}function ft(e){return I(e,null)}function pt(e,t,n){return ft(s(e,t,n))}function L(e){let t=e.absolute?`~${e.path}`:e.path,n={name:e.name,path:t};return e.children.size>0&&(n.children=Array.from(e.children.values(),L)),n}function mt(e){return Array.from(e.children.values(),L)}const R=e=>{let t=e.indexOf(`%`),n=e.indexOf(`+`);if(t===-1&&n===-1)return e;let r=n===-1?e:e.replaceAll(`+`,` `);return t===-1?r:decodeURIComponent(r)},z=(e,t)=>{if(e===void 0)return t.boolean.decodeUndefined();let n=t.boolean.decodeRaw(e);if(n!==null)return n;let r=R(e),i=t.number.decode(r);return i===null?t.boolean.decodeValue(r):i},ht=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,B=e=>{try{return encodeURIComponent(e)}catch(t){if(!(t instanceof URIError))throw t;return encodeURIComponent(String(e).replaceAll(ht,`�`))}},V=e=>{let t=typeof e;if(t!==`string`&&t!==`number`&&t!==`boolean`)throw TypeError(`[search-params] Array element must be a string, number, or boolean — received ${t}`);return B(e)},H=(e,t,n,r)=>{let i=`${e}${n}`,a=[];for(let e of t)if(e===null){let e=r.encode(i);e&&a.push(e)}else a.push(`${i}=${V(e)}`);return a.join(`&`)},U={none:{encodeArray:(e,t,n)=>H(e,t,``,n)},brackets:{encodeArray:(e,t,n)=>H(e,t,`[]`,n)},index:{encodeArray:(e,t,n)=>{let r=[];for(let[i,a]of t.entries()){let t=`${e}[${i}]`;if(a===null){let e=n.encode(t);e&&r.push(e)}else r.push(`${t}=${V(a)}`)}return r.join(`&`)},indexed:!0},comma:{encodeArray:(e,t)=>{let n=[];for(let e of t)e!==null&&n.push(V(e));return n.length===0?``:`${e}=${n.join(`,`)}`},decodeValue:e=>e.includes(`,`)?e.split(`,`):null}},W={none:{encode:(e,t)=>`${e}=${t}`,decodeUndefined:()=>null,decodeRaw:()=>null,decodeValue:e=>e},auto:{encode:(e,t)=>`${e}=${t}`,decodeUndefined:()=>null,decodeRaw:e=>e===`true`?!0:e===`false`?!1:null,decodeValue:e=>e},"empty-true":{encode:(e,t)=>t?e:`${e}=false`,decodeUndefined:()=>!0,decodeRaw:e=>e===`true`?!0:e===`false`?!1:null,decodeValue:e=>e}},G={default:{encode:e=>e},hidden:{encode:()=>``}},gt={auto:{decode:e=>{let t=e.length;if(t===0)return null;let n=+(e.codePointAt(0)===45);if(n===t||t-n>1&&e.codePointAt(n)===48&&e.codePointAt(n+1)!==46)return null;let r=!1;for(let i=n;i<t;i++){let a=e.codePointAt(i);if(!(a!==void 0&&a>=48&&a<=57)){if(a===46&&!r&&i!==n&&i!==t-1){r=!0;continue}return null}}let i=Number(e);return Object.is(i,-0)||!Number.isSafeInteger(i)&&!r?null:i}},none:{decode:()=>null}},K=(e,t,n,r)=>{if(e===void 0)throw TypeError(`[search-params] Unknown ${t} "${n}" — expected ${r}`);return e},_t=(e,t,n,r)=>({boolean:K(W[t],`booleanFormat`,t,`"none" | "auto" | "empty-true"`),null:K(G[n],`nullFormat`,n,`"default" | "hidden"`),number:K(gt[r],`numberFormat`,r,`"none" | "auto"`),array:K(U[e],`arrayFormat`,e,`"none" | "brackets" | "index" | "comma"`)}),vt={boolean:W.auto,null:G.default,number:gt.auto,array:U.none},q={arrayFormat:`none`,booleanFormat:`auto`,nullFormat:`default`,numberFormat:`auto`},yt={...q,strategies:vt},bt=e=>{if(!e||e.arrayFormat===void 0&&e.booleanFormat===void 0&&e.nullFormat===void 0&&e.numberFormat===void 0)return yt;let t=e.arrayFormat??q.arrayFormat,n=e.booleanFormat??q.booleanFormat,r=e.nullFormat??q.nullFormat,i=e.numberFormat??q.numberFormat;return{arrayFormat:t,booleanFormat:n,nullFormat:r,numberFormat:i,strategies:_t(t,n,r,i)}},J=e=>B(e),xt=(e,t,n)=>{let r=J(e);switch(typeof t){case`string`:case`number`:return`${r}=${J(t)}`;case`boolean`:return n.strategies.boolean.encode(r,t);case`object`:return t===null?n.strategies.null.encode(r):Array.isArray(t)?n.strategies.array.encodeArray(r,t,n.strategies.null):`${r}=${J(t)}`;default:return`${r}=${J(t)}`}};function Y(e,t,n){t===`__proto__`?Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function St(e,t,n,r){if(!Object.hasOwn(e,t)){Y(e,t,r?[n]:n);return}let i=e[t];Array.isArray(i)?i.push(n):Y(e,t,[i,n])}function Ct(e,t,n,r,i){return z(r?e.slice(t+1,n):void 0,i)}function wt(e,t,n){let r=t+1,i=0,a=!1;for(;r<n;){let t=e.codePointAt(r);if(t===93)return a?i:null;if(t!==void 0&&t>=48&&t<=57){i=i*10+(t-48),a=!0,r++;continue}return null}return null}function Tt(e,t,n){let{searchPart:r,nameEnd:i,nameSourceEnd:a,eqPos:o,end:s,hasValue:c,decodedName:l}=e,u=wt(r,i,a);if(u===null)return!1;let d=Ct(r,o,s,c,t),f=n.get(l);return f===void 0?n.set(l,[[u,d]]):f.push([u,d]),!0}function Et(e,t,n,r,i,a,o){let s=a!==-1&&a<n,c=s?a:n,l=c,u=!1;for(let n=t;n<c;n++)if(e.codePointAt(n)===91){l=n,u=!0;break}let d=R(e.slice(t,l));if(!(o!==void 0&&u&&Tt({searchPart:e,nameEnd:l,nameSourceEnd:c,eqPos:a,end:n,hasValue:s,decodedName:d},i,o))){if(!u&&s&&i.array.decodeValue){let t=e.slice(a+1,n),o=i.array.decodeValue(t);if(o){for(let e of o)St(r,d,z(e,i),!0);return}}St(r,d,Ct(e,a,n,s,i),u)}}const Dt=(e,t)=>{if(e===``||e===`?`)return{};let n={};return Ot(e,n,bt(t).strategies),n};function Ot(e,t,n){let r=n.array.indexed?new Map:void 0,i=0,a=e.length,o=-2;for(;i<a;){let s=e.indexOf(`&`,i);s===-1&&(s=a),s>i&&(o!==-1&&o<i&&(o=e.indexOf(`=`,i)),Et(e,i,s,t,n,o,r)),i=s+1}if(r!==void 0)for(let[e,n]of r)n.sort((e,t)=>e[0]-t[0]),Y(t,e,n.map(e=>e[1]))}const kt=(e,t)=>{let n=Object.keys(e);if(n.length===0)return``;let r=bt(t),i=[];for(let t of n){let n=e[t];if(n===void 0)continue;let a=xt(t,n,r);a&&i.push(a)}return i.join(`&`)};function At(e){let t=e?.queryParams;return new ot({...e?.caseSensitive!==void 0&&{caseSensitive:e.caseSensitive},...e?.strictTrailingSlash!==void 0&&{strictTrailingSlash:e.strictTrailingSlash},...e?.strictQueryParams!==void 0&&{strictQueryParams:e.strictQueryParams},...e?.urlParamsEncoding!==void 0&&{urlParamsEncoding:e.urlParamsEncoding},parseQueryString:e=>Dt(e,t),buildQueryString:e=>kt(e,t)})}function X(e,t){return TypeError(`[router.${e}] ${t}`)}function jt(e,t,n){if(!l(e))throw X(n,`Invalid path for route "${t}": unbalanced constraint delimiter ('<' or '>') in "${e}"`);if(e.includes(`<>`))throw X(n,`Invalid path for route "${t}": empty constraint '<>' in "${e}" (a constraint body must be non-empty, e.g. '<[0-9]+>')`)}function Mt(e,t,n,r){let i=new Set;for(let a of e){if(i.has(a))throw X(n,`Invalid path for route "${t}": duplicate parameter name ':${a}' in "${r}" (a param name must be unique within a route — the second binding would overwrite the first)`);i.add(a)}}function Nt(e,t,n,r,i){let a=new Set(e);for(let e of t){if(u.test(e))throw X(r,`Invalid path for route "${n}": invalid query-param name "${e}" in "${i}" (a query-param name cannot contain '<' or '>' — a reverse-order modifier typo that leaked a constraint into the query; put the optional '?' after the constraint, ':id<...>?')`);if(a.has(e))throw X(r,`Invalid path for route "${n}": "${e}" is declared as both a path param and a query param in "${i}" — buildPath would emit its value twice (rename one)`)}}function Pt(e){let t=!0,n=!1,r=!1;for(let i of e){if(r){r=i!==`>`;continue}if(i===`<`){r=!0;continue}if(i===`/`){t=!0;continue}if(t&&=(n=i===`:`||i===`*`,!1),!n&&i.codePointAt(0)>=128)return!0}return!1}function Ft(e){for(let t=1;t<e.length;t++)if(e[t]===`?`&&e[t-1]!==`>`&&e[t+1]===`/`&&e[t+2]===`*`)return!0;return!1}function It(e,t,n,r){if(h(e))throw X(r,`Invalid path for route "${t}": two optional params directly before a splat are not supported in "${n}" — a single trie slot carries one optional→splat fork, so the omit-outer/take-inner form would silently reshape into the splat. Split into two routes, or drop the '?' on one`);if(Ft(e))throw X(r,`Invalid path for route "${t}": an unconstrained optional param before a splat is not supported in "${n}" — it is ambiguous (every multi-segment value has two readings). Add a constraint (e.g. ':lang<[a-z]+>?') or model it as two routes`)}function Lt(e,t,n){switch(e){case`name-less`:case`trailing-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') without a name in "${n}"`;case`fused-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') must begin a segment, but "${n}" fuses one to a static prefix (use a boundary marker like "/a/:b")`;case`fused-constraint-suffix`:return`Invalid path for route "${t}": text fused to a constraint '>' in "${n}" (a '<...>' must end its segment or be followed by '/' or an optional '?' — use "/:id<...>/rest", not "/:id<...>rest")`;case`constraint-in-static`:return`Invalid path for route "${t}": constraint '<...>' in a static segment in "${n}" (a '<...>' must follow a parameter marker ':' or '*' — attach it to a param like "/:id<...>", or drop it)`;case`optional-splat`:return`Invalid path for route "${t}": optional splat ('*name?') is not supported in "${n}" — a splat cannot be optional (use a required splat '*name')`;case`unbalanced-constraint`:case`empty-constraint`:return`Invalid path for route "${t}": invalid constraint in "${n}"`}}function Rt(e,t,n){try{return le(e)}catch(r){throw X(n,`Invalid path for route "${t}": ${(r instanceof Error?r.message:String(r)).replace(/^\[buildParamMeta] /,``)} (in "${e}")`)}}function zt(e,t,n,r){if(typeof e!=`string`){let t;throw t=e===null?`null`:Array.isArray(e)?`array`:typeof e,X(n,`Route path must be a string, got ${t}`)}if(e===``)return;if(/\s/.test(e))throw X(n,`Invalid path for route "${t}": whitespace not allowed in "${e}"`);if(!/^([/?~]|[^/]+$)/.test(e))throw X(n,`Route "${t}" has invalid path format: "${e}". Path should start with '/', '~', '?' or be a relative segment.`);if(e.includes(`//`))throw X(n,`Invalid path for route "${t}": double slashes not allowed in "${e}"`);jt(e,t,n);let{pathPattern:i,urlParams:a,queryParams:o}=Rt(e,t,n);Mt(a,t,n,e),Nt(a,o,t,n,e);let s=m(i);if(s!==void 0)throw X(n,Lt(s,t,e));if(It(i,t,e,n),Pt(i))throw X(n,`Invalid path for route "${t}": non-ASCII static segment in "${e}" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`);let c=r&&r.paramMeta.urlParams.length>0;if(e.startsWith(`~`)&&c)throw X(n,`Absolute path "${e}" cannot be used under parent route with URL parameters`)}const Bt=/^[A-Z_a-z][\w-]*$/,Vt=/\S/,Ht=1e4;function Z(e){if(e===null)return`null`;if(typeof e==`object`){try{let t=e.constructor;if(typeof t==`function`&&t.name!==`Object`)return t.name||`object`}catch{}return`object`}return typeof e}function Ut(e){for(let t of Object.keys(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&(n.get||n.set))return!0}return!1}function Wt(e,t){if(!e||typeof e!=`object`)throw TypeError(`[router.${t}] Route must be an object, got ${Z(e)}`);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`[router.${t}] Route must be a plain object, got ${Z(e)}`);if(Ut(e))throw TypeError(`[router.${t}] Route must not have getters or setters`)}function Gt(e,t){if(e.encodeParams!==void 0&&typeof e.encodeParams!=`function`)throw TypeError(`[router.${t}] Route "${String(e.name)}" encodeParams must be a function`)}function Kt(e,t){if(e.decodeParams!==void 0&&typeof e.decodeParams!=`function`)throw TypeError(`[router.${t}] Route "${String(e.name)}" decodeParams must be a function`)}function qt(e,t){if(typeof e.name!=`string`)throw TypeError(`[router.${t}] Route name must be a string, got ${Z(e.name)}`);let n=e.name;if(n===``)throw TypeError(`[router.${t}] Route name cannot be empty`);if(!Vt.test(n))throw TypeError(`[router.${t}] Route name cannot contain only whitespace`);if(n.length>Ht)throw TypeError(`[router.${t}] Route name exceeds maximum length of ${Ht} characters`);if(!n.startsWith(`@@`)){if(n.includes(`.`))throw TypeError(`[router.${t}] Route name "${n}" cannot contain dots. Use children array or { parent } option in addRoute() instead.`);if(!Bt.test(n))throw TypeError(`[router.${t}] Invalid route name "${n}". Name must start with a letter or underscore, followed by letters, numbers, underscores, or hyphens.`)}}function Q(e,t){if(!t.includes(`.`))return e.children.get(t);let n=e;for(let e of t.split(`.`))if(n=n.children.get(e),!n)return;return n}function Jt(e,t,n){if(Q(e,t))throw Error(`[router.${n}] Route "${t}" already exists`)}function Yt(e,t,n){if(e.has(t))throw Error(`[router.${n}] Duplicate route "${t}" in batch`);e.add(t)}function Xt(e,t,n,r){let i=t===``?e:Q(e,t);if(i){for(let e of i.children.values())if(e.path===n)throw Error(`[router.${r}] Path "${n}" is already defined`)}}function Zt(e,t,n,r){let i=e.get(t);if(i?.has(n))throw Error(`[router.${r}] Path "${n}" is already defined`);i?i.add(n):e.set(t,new Set([n]))}function $(e,t,n,r=``,i,a){Wt(e,t);let o=e;qt(o,t),zt(o.path,o.name,t,n),Gt(o,t),Kt(o,t);let s=o.name,c=r?`${r}.${s}`:s;n&&c&&Jt(n,c,t),i&&Yt(i,c,t);let l=o.path,u=r;if(n&&Xt(n,u,l,t),a&&Zt(a,u,l,t),o.children!==void 0){if(!Array.isArray(o.children))throw TypeError(`[router.${t}] Route "${s}" children must be an array, got ${Z(o.children)}`);for(let e of o.children)$(e,t,n,c,i,a)}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return mt}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return pt}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return At}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return n}});
2
+ //# sourceMappingURL=esm-egdCFOaS.js.map