@real-router/core 0.150.0 → 0.152.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cjs/Router-BSgyC0DG.js +2 -0
  2. package/dist/cjs/Router-BSgyC0DG.js.map +1 -0
  3. package/dist/cjs/Router.d.ts.map +1 -1
  4. package/dist/cjs/RouterError-aGkUvcJJ.js +2 -0
  5. package/dist/cjs/RouterError-aGkUvcJJ.js.map +1 -0
  6. package/dist/cjs/RouterError.d.ts +3 -0
  7. package/dist/cjs/RouterError.d.ts.map +1 -1
  8. package/dist/cjs/api.js +1 -1
  9. package/dist/cjs/api.js.map +1 -1
  10. package/dist/cjs/{helpers-B2Zsa5R_.js → helpers-DdpDlqWS.js} +2 -2
  11. package/dist/cjs/{helpers-B2Zsa5R_.js.map → helpers-DdpDlqWS.js.map} +1 -1
  12. package/dist/cjs/index.js +1 -1
  13. package/dist/cjs/{internals-C18omEfg.js → internals-BEKzn5ug.js} +2 -2
  14. package/dist/cjs/{internals-C18omEfg.js.map → internals-BEKzn5ug.js.map} +1 -1
  15. package/dist/cjs/internals.d.ts +1 -3
  16. package/dist/cjs/internals.d.ts.map +1 -1
  17. package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.ts +5 -1
  18. package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.ts.map +1 -1
  19. package/dist/cjs/utils.js +1 -1
  20. package/dist/cjs/validation.js +1 -1
  21. package/dist/esm/Router-Cam5bJgP.mjs +2 -0
  22. package/dist/esm/Router-Cam5bJgP.mjs.map +1 -0
  23. package/dist/esm/Router.d.mts.map +1 -1
  24. package/dist/esm/RouterError-DyPeuufj.mjs +2 -0
  25. package/dist/esm/RouterError-DyPeuufj.mjs.map +1 -0
  26. package/dist/esm/RouterError.d.mts +3 -0
  27. package/dist/esm/RouterError.d.mts.map +1 -1
  28. package/dist/esm/api.mjs +1 -1
  29. package/dist/esm/api.mjs.map +1 -1
  30. package/dist/esm/{helpers-BnQy9vYH.mjs → helpers-BXXeSrT8.mjs} +2 -2
  31. package/dist/esm/{helpers-BnQy9vYH.mjs.map → helpers-BXXeSrT8.mjs.map} +1 -1
  32. package/dist/esm/index.mjs +1 -1
  33. package/dist/esm/index.mjs.map +1 -1
  34. package/dist/esm/internals-BNRNi6Fp.mjs +2 -0
  35. package/dist/esm/{internals-CBAb3okL.mjs.map → internals-BNRNi6Fp.mjs.map} +1 -1
  36. package/dist/esm/internals.d.mts +1 -3
  37. package/dist/esm/internals.d.mts.map +1 -1
  38. package/dist/esm/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.mts +5 -1
  39. package/dist/esm/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.mts.map +1 -1
  40. package/dist/esm/utils.mjs +1 -1
  41. package/dist/esm/validation.mjs +1 -1
  42. package/package.json +1 -1
  43. package/dist/cjs/Router-_0vZHk6R.js +0 -2
  44. package/dist/cjs/Router-_0vZHk6R.js.map +0 -1
  45. package/dist/cjs/RouterError-CentZBJj.js +0 -2
  46. package/dist/cjs/RouterError-CentZBJj.js.map +0 -1
  47. package/dist/esm/Router-DVdK_R0k.mjs +0 -2
  48. package/dist/esm/Router-DVdK_R0k.mjs.map +0 -1
  49. package/dist/esm/RouterError-Dy1_FfLa.mjs +0 -2
  50. package/dist/esm/RouterError-Dy1_FfLa.mjs.map +0 -1
  51. package/dist/esm/internals-CBAb3okL.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"Router.d.ts","names":["RouterInterface"],"sources":["../../src/Router.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;qBAiHa,OACX,qBAAqB,sBAAsB,gCAChCA,SAAgB;;GAC1B;;;;;;EAgFC,YAAA,SAAQ,MAAM,iBACd,UAAS,QAAQ,QAAQ,gBACzB,eAAc;EAmqBhB,cACE,cACA,SAAS,QACT,SAAS,cACT,0BACA;EAwCF,UAAU,eAAe,SA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;EA+EX,kBAAkB,UAAU,oBAAoB,QAAQ;EAiBxD,mBAAmB,gBAAgB"}
@@ -0,0 +1,2 @@
1
+ const e=Object.freeze({ROUTER_NOT_STARTED:`NOT_STARTED`,NO_START_PATH_OR_STATE:`NO_START_PATH_OR_STATE`,ROUTER_ALREADY_STARTED:`ALREADY_STARTED`,ROUTE_NOT_FOUND:`ROUTE_NOT_FOUND`,SAME_STATES:`SAME_STATES`,CANNOT_DEACTIVATE:`CANNOT_DEACTIVATE`,CANNOT_ACTIVATE:`CANNOT_ACTIVATE`,TRANSITION_ERR:`TRANSITION_ERR`,TRANSITION_CANCELLED:`CANCELLED`,ROUTER_DISPOSED:`DISPOSED`,PLUGIN_CONFLICT:`PLUGIN_CONFLICT`,CONTEXT_NAMESPACE_ALREADY_CLAIMED:`CONTEXT_NAMESPACE_ALREADY_CLAIMED`,REENTRANT_NAVIGATION:`REENTRANT_NAVIGATION`,REENTRANT_TREE_MUTATION:`REENTRANT_TREE_MUTATION`,ROUTER_NOT_STOPPED:`NOT_STOPPED`,WRONG_CHANNEL:`WRONG_CHANNEL`}),t=`@@router/UNKNOWN_ROUTE`,n=`__proto__`,r=Object.freeze({UNKNOWN_ROUTE:t}),i=Object.freeze({ROUTER_START:`onStart`,ROUTER_STOP:`onStop`,TRANSITION_START:`onTransitionStart`,TRANSITION_LEAVE_APPROVE:`onTransitionLeaveApprove`,TRANSITION_CANCEL:`onTransitionCancel`,TRANSITION_SUCCESS:`onTransitionSuccess`,TRANSITION_ERROR:`onTransitionError`}),a=Object.freeze({ROUTER_START:`$start`,ROUTER_STOP:`$stop`,TRANSITION_START:`$$start`,TRANSITION_LEAVE_APPROVE:`$$leaveApprove`,TRANSITION_CANCEL:`$$cancel`,TRANSITION_SUCCESS:`$$success`,TRANSITION_ERROR:`$$error`}),o=Object.freeze({maxDependencies:100,maxPlugins:50,maxListeners:1e4,warnListeners:1e3,maxLifecycleHandlers:200}),s=Object.freeze({}),c=Object.freeze({}),l=Object.freeze({}),u=Object.freeze({deactivated:Object.freeze([]),activated:Object.freeze([]),intersection:``}),d=Object.freeze({phase:`activating`,reason:`success`,segments:u}),f=new WeakSet,p=new WeakSet;function m(e){f.add(e)}function h(e){f.has(e)&&p.add(e)}function g(e){return p.has(e)}const _=Object.create,v=Object.entries;function y(){return _(null)}function b(e){return{...e}}const x=Object.defineProperty,S=Object.hasOwn;function C(e){return S(e,`__proto__`)&&x(e,n,{value:e[n],writable:!0,enumerable:!1,configurable:!0}),e}function w(e,t,n){t in e&&!S(e,t)?x(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e[t]=n}function T(e,t){for(let[n,r]of v(t))w(e,n,r)}const E=Object.freeze,D=Object.entries,O=Object.values,k=Object.hasOwn,A=new Set(O(e)),j=new Set([`code`,`segment`,`path`]),M=new Set([`setCode`,`setErrorInstance`,`setAdditionalFields`,`hasField`,`getField`,`toJSON`]);function N(e){return m(e),E(e)}var P=class extends Error{segment;path;code;constructor(e,{message:t,segment:n,path:r,...i}={}){super(t??e),this.name=`RouterError`,this.code=e,this.segment=n,this.path=r;for(let[e,t]of D(i)){if(j.has(e))throw L.type`Cannot set reserved property "${e}"`;e!==`__proto__`&&!M.has(e)&&w(this,e,t)}}setCode(e){this.code=e,A.has(this.message)&&(this.message=e)}setErrorInstance(e){if(!e)throw R.type`err parameter is required and must be an Error instance`;this.message=e.message,w(this,`cause`,e.cause),this.stack=e.stack??``}setAdditionalFields(e){for(let[t,n]of D(e)){if(j.has(t))throw z.type`Cannot set reserved property "${t}"`;t!==`__proto__`&&!M.has(t)&&w(this,t,n)}}hasField(e){return k(this,e)}getField(e){return k(this,e)?this[e]:void 0}toJSON(){let e={code:this.code,message:this.message};this.segment!==void 0&&(e.segment=this.segment),this.path!==void 0&&(e.path=this.path);let t=new Set([`code`,`message`,`segment`,`path`,`stack`,`name`]);for(let n in this)k(this,n)&&!t.has(n)&&w(e,n,this[n]);return e}};const F=(e,t)=>{let n=e[0];for(let[r,i]of t.entries())n+=String(i)+e[r+1];return n};function I(e,t){let n=t===void 0||t===``?`[${e}] `:`[${e}.${t}] `,r=(e,t)=>n+F(e,t),i=e=>((t,...n)=>Array.isArray(t)?e(r(t,n)):(n,...i)=>e(r(n,i),t));return{type:i((e,t)=>TypeError(e,t)),plain:i((e,t)=>Error(e,t)),ref:(e,...t)=>ReferenceError(r(e,t)),range:(e,...t)=>RangeError(r(e,t)),code:(e,t)=>(n,...i)=>N(new P(e,{...t,message:r(n,i)}))}}const L=I(`RouterError`),R=I(`RouterError`,`setErrorInstance`),z=I(`RouterError`,`setAdditionalFields`),B={plain:(e,...t)=>Error(`Internal error (please report): ${F(e,t)}`)};Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return r}});
2
+ //# sourceMappingURL=RouterError-aGkUvcJJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterError-aGkUvcJJ.js","names":["objectEntries","hasOwn","errorCodes","UNKNOWN_ROUTE","UNSAFE_KEY","constants","plugins","events","DEFAULT_LIMITS","EMPTY_PARAMS","EMPTY_SEARCH","EMPTY_OPTS","FROZEN_EMPTY_SEGMENTS","DEFAULT_TRANSITION","built","ends","recordConstruction","error","recordNavigationEnd","value","isNavigationEnd","objectCreate","objectEntries$1","emptyRecord","publishRecord","source","defineProperty","hasOwn$1","concealUnsafeKey","record","putField","key","target","copyFields","freeze","objectEntries","objectValues","hasOwn","errorCodeValues","reservedProperties","reservedMethods","freezeThrownError","RouterError","rest","message","code","segment","path","newCode","err","fields","result","excludeKeys","interpolate","text","strings","index","values","raiser","head","door","receiver","flavour","first","build","options","atRouterError","atSetErrorInstance","atSetAdditionalFields","internalDefect"],"sources":["../../src/constants.ts","../../src/navigationEnds.ts","../../src/utils/ingest.ts","../../src/RouterError.ts"],"sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n TransitionMeta,\n} from \"./types\";\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Readonly<Record<ConstantsKeys, string>>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n CONTEXT_NAMESPACE_ALREADY_CLAIMED: \"CONTEXT_NAMESPACE_ALREADY_CLAIMED\", // Plugin tried to claim a context namespace already owned by another plugin\n REENTRANT_NAVIGATION: \"REENTRANT_NAVIGATION\", // a navigation (the navigate family, or start() restarting the router) called synchronously from inside a navigation core has not finished with (banned — defer it)\n REENTRANT_TREE_MUTATION: \"REENTRANT_TREE_MUTATION\", // a tree mutator — route-CRUD or setRootPath (#1751) — called synchronously from inside a subscribeChanges handler (banned — use await/async/queueMicrotask)\n ROUTER_NOT_STOPPED: \"NOT_STOPPED\", // clear() called while a state is committed — tear down with stop() first, or swap the tree with replace() (#1612)\n WRONG_CHANNEL: \"WRONG_CHANNEL\", // a declared query key was supplied in the path channel (`params`) instead of `search` (#1572)\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\n/**\n * The one key the router will not copy into a state channel (#1792), and — at\n * `getDependenciesApi.getAll` — will not hand back out of a container either.\n *\n * `__proto__` is the only ACCESSOR among `Object.prototype`'s twelve own\n * members, so `target[key] = value` for that one name reaches the inherited\n * setter: no own key is created, the value vanishes with no error and no log,\n * and an OBJECT value replaces the target's prototype instead.\n *\n * ⚠ Core REFUSES it nowhere — not at a door, not at registration. It is dropped\n * where core copies into a CHANNEL and kept everywhere else, because a route's\n * custom fields and a plugin's context namespace are not containers a consumer\n * merges.\n *\n * ⚠ A `grep` for this constant does not find the sites carrying the opposite\n * contract: they go through `putField` (#1852), which keeps every name.\n *\n * The rule this serves, the doors exempt from it and the level it closes are\n * `INVARIANTS.md` — *Supported input shapes*, *WRITE* (#1852) and *HAND-OUT*\n * (#1957), with `handed-out-containers-1957.test.ts` as the authority. They are\n * deliberately not restated here: this docblock carried a second copy of that\n * section, and the two had already diverged.\n */\nexport const UNSAFE_KEY = \"__proto__\";\n\nexport const constants: Constants = Object.freeze({\n UNKNOWN_ROUTE,\n});\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = Object.freeze({\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_LEAVE_APPROVE: \"onTransitionLeaveApprove\", // Plugin method called when deactivation guards pass\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n});\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = Object.freeze({\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_LEAVE_APPROVE: \"$$leaveApprove\", // Emitted when deactivation guards pass\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n});\n\nexport const DEFAULT_LIMITS = Object.freeze({\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxLifecycleHandlers: 200,\n} as const);\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty query bag reused for `State.search` when a navigation\n * carries no query params — the search-channel twin of {@link EMPTY_PARAMS}\n * (RFC-4 M2 / #1548). Lets `makeState` reuse one frozen `{}` (zero transient\n * allocation, #1027) instead of minting an object per query-less state.\n */\nexport const EMPTY_SEARCH: Readonly<Record<string, never>> = Object.freeze({});\n\n/**\n * Shared frozen empty `NavigationOptions`, substituted by the facade when a\n * caller passes none — the options-channel twin of {@link EMPTY_PARAMS}.\n *\n * ⚑ It lives here rather than in `Router.ts` so the entry door can recognise it\n * by IDENTITY (#1962). `navigate(\"b\")` is the commonest call in the library, and\n * matching this singleton is what keeps the door's cost on it to one comparison\n * instead of a copy nobody asked for.\n */\n/**\n * The options bag the facade substitutes when the caller passes none.\n *\n * ⚠ **An ordinary `{}`, and the flags read off it are own-gated at the read\n * instead (#2132).** This object reaches the entry unchanged, so an ambient\n * `Object.prototype.signal` would answer here with no caller bag in the picture\n * at all — core acting on an option nobody supplied. A prototype-less singleton\n * closes that structurally and was measured too expensive: `Object.create(null)`\n * puts it in V8's dictionary mode, and every downstream read of the bag becomes\n * a hash lookup — **+7.6 %** per navigation on this path, **+39.6 %** on the one\n * that copies. The gates cost **+2.9 %** / **+3.0 %**.\n */\nexport const EMPTY_OPTS: Readonly<Record<string, never>> = Object.freeze({});\n\nconst FROZEN_EMPTY_SEGMENTS = Object.freeze({\n deactivated: Object.freeze([]) as unknown as string[],\n activated: Object.freeze([]) as unknown as string[],\n intersection: \"\",\n});\n\nexport const DEFAULT_TRANSITION = Object.freeze({\n phase: \"activating\",\n reason: \"success\",\n segments: FROZEN_EMPTY_SEGMENTS,\n}) as TransitionMeta;\n","// packages/core/src/navigationEnds.ts\n\n/**\n * The values core has handed out as the END of a navigation: what its signal\n * was aborted with, and what its promise rejected with.\n *\n * A guard receives one of them only by waiting on that navigation's work — a\n * request bound to its signal and deduplicated across navigations, or its\n * promise — so `handleGuardError` asks this to tell such a value from the\n * guard's own quiet cancel (#933), which is a value the guard made.\n *\n * ⚑ Only a value core BUILT is recorded, and `freezeThrownError` marks it so.\n * An end the application handed in — the reason of a caller's `opts.signal`\n * (#943), a quiet cancel a guard threw — is one it holds apart from any\n * navigation, and may raise again as its own quiet cancel: one `RouterError`\n * thrown from every guard, the reason of a signal it passed to an earlier\n * navigation. `abort-dispatch-authority-2778.test.ts` holds that every\n * `TRANSITION_CANCELLED` core builds passes through `freezeThrownError`.\n *\n * ⚑ An abort site records what the signal holds once aborted — what a request\n * bound to it rejects with. Every raw abort of a navigation's controller\n * records it — `abort-dispatch-authority-2778.test.ts` holds that.\n */\nconst built = new WeakSet<object>();\nconst ends = new WeakSet<object>();\n\nexport function recordConstruction(error: object): void {\n built.add(error);\n}\n\nexport function recordNavigationEnd(value: unknown): void {\n // A primitive is never built, so it is never recorded either.\n if (built.has(value as object)) {\n ends.add(value as object);\n }\n}\n\nexport function isNavigationEnd(value: unknown): boolean {\n return ends.has(value as object);\n}\n","// packages/core/src/utils/ingest.ts\n//\n// One discipline for the records core BUILDS under a key it did not CHOOSE.\n//\n// Two halves, and they answer different questions — a reader who takes them for\n// one primitive will draw the wrong conclusion from either:\n//\n// `emptyRecord` / `publishRecord` (#1825) — a record with no prototype for the\n// BUILD, handed out plain. Used where the record is core's alone:\n// `buildParamMeta`, the segment-meta walk.\n// `putField` / `copyFields` (#1852) — a guarded WRITE for the records that\n// cannot be prototype-less because they are published, read on every render,\n// or belong to someone else. Used across core and, through\n// `@real-router/core/utils`, by four plugins.\n// ⚠ The site COUNTS deliberately do not live here. This comment carried\n// \"twenty-one in core, fourteen across four plugins\" and both halves were\n// wrong (22 and 13, measured) — a second copy of a number `CLAUDE.md`\n// already calls descriptive-not-contract. The count lives in `CLAUDE.md`\n// (\"The WRITE side of the same rule\"); the CONTRACT is the derived set in\n// `tests/functional/computed-key-write-authority-1852.test.ts`.\n//\n// ⚠ Neither decides whether a key is PUBLISHED. `__proto__` stays out of\n// `state.params` / `state.search` by a separate skip at the channel copy sites\n// in `helpers.ts`, and stays IN a route's custom fields and a plugin's context\n// namespace, because those are not containers a consumer merges. See `putField`'s\n// docblock for that split.\n//\n// `concealUnsafeKey` (#1957) is the one member of this file that DOES decide\n// that — for exactly one record, `buildMeta`'s, which core both hands out\n// and reads back by key. It withholds the name from ENUMERATION rather than\n// removing it, because removing it is a measured behaviour loss there. The\n// doors that only hand a container OUT drop the key instead\n// (`dropUnsafeKey`, `helpers.ts`).\n//\n// ⚠ The rest are WRITE-side primitives only, and the boundary is deliberate. A\n// READ-side primitive that walks a caller's prototype chain was written here,\n// wired, measured — and removed: `CLAUDE.md` \"Supported Input Shapes\" settles\n// that axis already (\"own enumerable properties only\", owner decision\n// 2026-08-18), and core is the layer that DEGRADES on a violation while\n// `@real-router/validation-plugin` is the layer that reports it. A primitive\n// that honoured inherited keys would have made core contradict its own canon,\n// and it additionally admitted the ambient `Object.prototype` — the #1840\n// class, introduced by the fix.\n//\n// So what is left is the half the canon does not cover: what happens when core\n// writes into a record of its own under a key it did not choose.\n\nimport { UNSAFE_KEY } from \"../constants\";\n\n/** Captured like the deciding seven, but this one BUILDS the guarantee (#2072). */\nconst objectCreate = Object.create;\n\nconst objectEntries = Object.entries;\n\n/**\n * The target discipline: a record with NO prototype.\n *\n * ⚑ This one line closes two axes at once, which is why it is a primitive and\n * not an idiom. #1856 tabulates them as a structural trade — a key-by-key copy\n * fixes `\"__proto__\"` but turns a `[[DefineOwnProperty]]` into a `[[Set]]`, so\n * an ambient accessor starts throwing — and calls the conflict unavoidable. It\n * is unavoidable only while the target inherits from `Object.prototype`:\n *\n * - `\"__proto__\"` (#1825, #1794, #1809) is an ordinary key here, because the\n * magic accessor lives on `Object.prototype` and this object has none.\n * - an ambient accessor named `id` / `page` / `tab` (#1852) cannot hijack the\n * write for the same reason. #1852 notes the key's provenance is\n * irrelevant — `SegmentMatcher` writes a name from the ROUTE TABLE and\n * throws just the same — so a name-based skip cannot close it and this can.\n */\nexport function emptyRecord<V>(): Record<string, V> {\n return objectCreate(null) as Record<string, V>;\n}\n\n/**\n * Hand a privately-built record out with the ORDINARY prototype, keeping every\n * own key — including a literal `\"__proto__\"`.\n *\n * Discovered by measurement, not designed: wiring `emptyRecord` into\n * `buildParamMeta` alone reds **21** existing tests, all of the shape\n * `expected { id: 'url' } to strictly equal { id: 'url' }` — identical content,\n * different prototype, because `toStrictEqual` compares prototypes and\n * `paramTypeMap` is published through `getPluginApi(router).getTree()`. A\n * prototype-less record is not a drop-in at a published surface.\n *\n * The spread is what makes this work rather than undo it: it\n * `[[DefineOwnProperty]]`s, so an own `\"__proto__\"` carried on the private\n * record lands as an ordinary own key here (measured: own keys\n * `[\"__proto__\",\"keep\"]`, value intact, prototype back to `Object.prototype`).\n * Writing that same key into a fresh `{}` with `[[Set]]` loses it entirely\n * (measured: own keys `[]`) — which is the defect the private record exists to\n * avoid.\n *\n * So the rule is: **build private, publish plain.** The window in which the\n * ambient-accessor hazard (#1852) could bite is the build, and the build never\n * touches `Object.prototype`.\n */\nexport function publishRecord<V>(source: Record<string, V>): Record<string, V> {\n return { ...source };\n}\n\n/**\n * Captured at module load for the reason `helpers.ts` gives for `freeze` /\n * `hasOwn` / `objectKeys`: this is the operation {@link putField} writes\n * through, so a guard reading it late would be reading whatever an application\n * had re-pointed it to.\n */\nconst defineProperty = Object.defineProperty;\nconst hasOwn = Object.hasOwn;\n\n/**\n * Withhold `UNSAFE_KEY` from ENUMERATION on a record core hands out AND reads\n * back by key (#1957).\n *\n * ⚑ The hazard is the CONSUMER's merge, not core's own write. `Object.assign`\n * and a `for…in` copy `[[Set]]` each own ENUMERABLE key on the TARGET, where\n * `Object.prototype`'s `\"__proto__\"` accessor replaces that target's prototype\n * instead of adding an entry.\n *\n * ⚠ A SPREAD is NOT in that list. `{ ...source }` performs `CreateDataProperty`,\n * i.e. `[[DefineOwnProperty]]`, which never reaches an inherited accessor —\n * measured on the poisoned bag, on a null-prototype carrier and through a\n * pass-through Proxy, a spread swaps in none of the three. The list is exactly\n * `Object.assign` or a `for…in` copy (#1823), and the hazard is that narrow.\n *\n * So the SOURCE's own prototype decides nothing either — measured, an\n * `Object.create(null)` source swaps the target exactly the same — and the only\n * two fixes are removing the key or removing it from enumeration.\n *\n * ⚠ **Dropping is not a milder fix here, it is a WRONG one.** The route-meta\n * record is core's working table: `segmentParamsEqual` reads `meta[segmentName]`\n * on every navigation, so with the entry gone the read reaches the INHERITED\n * accessor and answers `Object.prototype` — an object, whose `Object.keys` is\n * `[]`, so the segment reports \"params unchanged\". Measured end to end on a\n * route named `__proto__`: `/p/1` → `/p/2` activates `[\"__proto__\"]` today and\n * `[]` with the entry deleted. Core accepts that name (#1801), so the loss is\n * real and silent.\n *\n * Non-enumerable keeps the read exact for core AND for a consumer asking by\n * key, while `Object.assign` / a spread / `for…in` skip it — measured, all\n * three.\n *\n * ⚠ NOT applied by {@link publishRecord} itself. Its other caller is\n * `buildParamMeta`, whose map core ENUMERATES (`Object.keys` in\n * `segmentParamsEqual`, `for…in` in `hasAnyParam`) and which is not a swap\n * primitive anyway: a param's value is the string `\"url\"` / `\"query\"`, and the\n * inherited setter ignores primitives.\n *\n * Returns the input untouched, with no descriptor write, when the key is absent\n * — which is every ordinary route.\n */\nexport function concealUnsafeKey<V>(\n record: Record<string, V>,\n): Record<string, V> {\n if (!hasOwn(record, UNSAFE_KEY)) {\n return record;\n }\n\n defineProperty(record, UNSAFE_KEY, {\n value: record[UNSAFE_KEY],\n writable: true,\n enumerable: false,\n configurable: true,\n });\n\n return record;\n}\n\n/**\n * Write one field of a record core BUILDS under a key it did not choose.\n *\n * ⚑ The rule this exists to enforce: **a caller's object contributes DATA, and\n * nothing else.** No trap, no accessor, no inherited member of a bag handed to\n * the router may change what the router ends up holding — which is what\n * \"treat it as a pure dictionary\" means on the WRITE side. `Object.keys` and\n * the one-read-per-key discipline (#1854 / #1899) already say it on the read\n * side; this is the other half.\n *\n * Plain `target[key] = value` cannot say it. `[[Set]]` walks the prototype\n * chain first, so a key that resolves to an accessor or a non-writable data\n * property up there is HIJACKED — the write dispatches into application code\n * (or is silently dropped in sloppy mode, and throws in a module). The key's\n * provenance is irrelevant: `SegmentMatcher` writes a name straight off the\n * ROUTE TABLE, so `id` / `tab` / `page` are as exposed as `__proto__` (#1852),\n * and a name-based skip therefore cannot close it.\n *\n * `Object.defineProperty` CAN say it — it ignores the chain entirely — but it\n * measures ~100 ns per field against ~0 for a store, which is why #1852 priced\n * it as unaffordable on a path that runs per navigation and per `<Link>`\n * render.\n *\n * So the write is guarded rather than replaced: **ask the chain first, and pay\n * only where it answers.** In a pristine environment `in` answers `false` for\n * every name an application routes under, so the store is taken and nothing is\n * paid. It covers both halves of the hazard, which a `__proto__` name test does\n * not: an accessor (getter-only THROWS, getter+setter silently diverts the\n * value) and a **non-writable** data property. Verified on all four shapes plus\n * the overwrite cases.\n *\n * ⚠ It asks `key in target`, NOT `key in Object.prototype`, and the difference\n * is the whole robustness of the primitive rather than a style choice. The\n * cheaper form is right only while every target is a fresh `{}`, i.e. while its\n * chain IS `Object.prototype` — measured, a target inheriting the accessor from\n * anywhere else walks straight past that predicate and throws. Asking the\n * object\n * being written to cannot be wrong for any target. Measured cost of the\n * difference, measured when the two forms were compared directly: a wash on\n * every arc, bought for a predicate with no precondition. ⚠ Those figures\n * predate both the `!hasOwn` term and the restored channel skips, and the\n * number\n * that supersedes them is below — the whole guard sits under the noise floor,\n * so\n * the choice between the two predicates cannot be visible in it.\n *\n * ⚑ **`&& !hasOwn`, and that second term is not an optimisation — it is what\n * keeps this a guarded WRITE instead of a redefinition.** When the key is\n * already an OWN property of the target, `[[Set]]` finds it and never consults\n * the chain, so a plain store is both safe AND semantically right there.\n * `defineProperty` is not: it replaces the whole DESCRIPTOR with this\n * function's\n * fixed one, and that has three measured consequences.\n *\n * - It **throws where a plain store works**: a `configurable: false` own key\n * (a sealed target, an array's `length`) refuses `defineProperty` while\n * accepting an assignment.\n * - It **silently unlocks**: an own `writable: false` key was overwritten and\n * came back writable, and an own `enumerable: false` key came back\n * enumerable — a \"guarded write\" that also removes the guard.\n * - It **changed a shipped shape**, which is how this was caught rather than\n * reasoned about. `RouterError`'s own `stack` is a non-enumerable accessor;\n * `wrapSyncError` passes `stack` through here, so every error built from a\n * thrown one gained an own enumerable `stack`. `Object.keys(err)` changed,\n * and two errors differing only in stack stopped comparing equal under\n * `isDeepStrictEqual` / `toEqual`. The two arms of `rethrowAsRouterError`\n * disagreed with each other, because one of them assigns.\n *\n * `in` answers `false` for a fresh bag's new key and short-circuits, so\n * `hasOwn`\n * runs only on the rare branch it disambiguates. ⚠ That short-circuit does NOT\n * leave the hot path untouched — one dictionary lookup per written field is the\n * price, and it is measured below.\n *\n * ⚠ The alternative that looks equivalent and is not: a prototype-less target.\n * It also closes the axis, and it costs far MORE, because the price is not on\n * the write at all — V8 puts such an object in dictionary mode, so every later\n * READ of the bag pays. Re-measured on the SHIPPED tree rather than carried\n * over from an earlier one: `buildPath` goes **+65.4 %** (one path slot) and\n * **+36.2 %** (slot + query). `{ __proto__: null }` as a literal is no better\n * (76 ns vs 70 ns for `Object.create(null)`, against 7.5 ns plain).\n *\n * ⚑ **The guard COSTS, and \"not measurable\" is a resolution artefact.** Medians\n * of five floor at an A/A of 5-6 %, which hides it; on a quiet machine this\n * harness floors at 0.1-1.7 %, and at that resolution the cost is plain.\n * Same-session A/B, ALTERNATING PROCESSES (two\n * copies of the module in one process is not a valid A/B), medians of 20 pairs,\n * against the SHIPPED bundle rather than `src`, each arc's own A/A floor in\n * brackets:\n *\n * buildPath, splat param 232.4 -> 260.3 ns +12.0 % (0.7 %)\n * isActiveRoute, exact 117.5 -> 125.4 ns +6.8 % (0.1 %)\n * matchPath, path params 664.0 -> 693.8 ns +4.5 % (0.8 %)\n * buildPath, static 97.5 -> 99.2 ns +1.7 % (1.7 %)\n * buildPath, one path slot 145.0 -> 140.5 ns -3.1 % (1.0 %)\n * isActiveRoute, sibling 38.4 -> 38.3 ns -0.3 % (0.3 %)\n *\n * Isolated by building the tree with the predicate replaced by `false`: it is\n * worth -6.1 % on the splat arc and -7.5 % on the exact one, i.e. the whole of\n * the regression there; the rest of `matchPath`'s is `withoutUnsafeKey`\n * (#1904), -2.1 %.\n *\n * ⚠ The old claim was less a bad measurement than a measurement of the WRONG\n * ARCS. `warm-params` and the sibling arm genuinely do not move — those are the\n * two it sampled — while the splat and exact arms do. Sampling what does not\n * move and generalising to \"not measurable\" is the same trap the reachability\n * arguments elsewhere in this file are written against.\n *\n * The price is ACCEPTED, deliberately, and three cheaper forms were measured\n * and rejected before accepting it:\n *\n * - asking a captured `Object.prototype` instead of the target, so the `in`\n * receiver is monomorphic: every arc inside the A/A floor. The cost is the\n * dictionary lookup, not who is asked.\n * - a prototype-less accumulator in `normalizeChannel` published through\n * `publishRecord`: **+134 % … +284 %** — the dictionary-mode price above,\n * now measured end to end rather than argued.\n * - an optimistic plain store repaired afterwards (`hasOwn` + `try`/`catch`):\n * -3.5 % and -2.8 % on two arcs but **+8.3 %** on a third, and it re-opens\n * the descriptor question `&& !hasOwn(target, key)` exists to close.\n *\n * ⚠ **CodSpeed reports this change at -13.83 %, and that is not the shipped\n * cost.** The gap is measured, not assumed. The suite runs\n * `tsx tests/benchmarks/run.ts` — against `src`, unbundled — so its flamegraph\n * carries ESM module-namespace getter frames (`get (ingest.ts)`, 2.67 % of one\n * arc) that the bundle does not have: `grep -c 'get: ()' dist/esm/index.mjs` is\n * 0. `Simulation` mode additionally over-counts instructions a superscalar CPU\n * hides. On the worst-reported arc the sign inverts — -17.25 % simulated,\n * -3.1 % (i.e. FASTER) in the bundle.\n *\n * A prototype-less channel additionally changes a PUBLISHED shape:\n * `state.params` would stop inheriting from `Object.prototype`, which reds\n * tests across **17 packages**, none of them for a behavioural reason.\n *\n * ⚠ **The package count is the half that holds; the TEST count is not restated,\n * because it moves with the tier while the shape does not.** Published as \"263\n * in 15\", corrected to 352/17 by a full-monorepo run, and 374/17 when re-run on\n * 2026-09-04 — three figures, one answer. Re-run the mutation rather than trust\n * a number here: make the two channel singletons and the channel accumulators\n * `Object.create(null)` and run the monorepo. It was never a question of which\n * sites to mutate, because 17 came back every time.\n *\n * The qualitative half is the load-bearing one: the failures are\n * `AssertionError`, none are thrown; they are `toStrictEqual` cells plus a\n * handful of explicit prototype pins; and NO `toEqual` / `toMatchObject` cell\n * moves, which is the internal control that only the prototype axis shifted.\n *\n * ⚑ `defineProperty` also makes `__proto__` an ordinary own key rather than a\n * write that swaps the target's prototype — which is why the `claim.write`\n * (#1191), `assignParam` (#855) and custom-field (#1788) special cases could be\n * replaced by this one primitive instead of kept beside it.\n *\n * ⚠ **It does NOT decide whether that key is PUBLISHED, and the two questions\n * were briefly conflated here.** The channel copy sites in `helpers.ts` still\n * drop `__proto__` before it reaches `state.params` / `state.search`, and that\n * skip is orthogonal to this primitive: a bag core hands BACK carrying the key\n * is a prototype-swap primitive for any consumer that merges it with\n * `Object.assign` — measured, `?__proto__` alone yields `null` and\n * `?__proto__=1&__proto__=2` an array, and the inherited setter accepts both.\n * `getDependenciesApi.getAll()` deletes the same key for the same reason and in\n * those words. Where the record does NOT escape to a merging consumer — a\n * route's custom fields, a plugin's context namespace — the key stays as data,\n * which is what #1788 and #1191 are about.\n */\nexport function putField<V>(\n target: Record<string, V>,\n key: string,\n value: V,\n): void {\n if (key in target && !hasOwn(target, key)) {\n defineProperty(target, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n target[key] = value;\n }\n}\n\n/**\n * {@link putField} for a whole source record — what `Object.assign` would do,\n * without the hazard.\n *\n * ⚑ It exists because `Object.assign` IS the hazard, written in a form a census\n * keyed on `dst[key] = value` cannot see. It copies with `[[Set]]`, one key at\n * a\n * time, so every argument in {@link putField}'s docblock applies to it verbatim\n * — and it is the reason this class needed a second look after the obvious\n * sweep: the matcher's junction walk builds `childParams` with a computed-key\n * literal (safe: that DEFINES) and then commits it with `Object.assign` (not).\n * Measured with an ambient setter under a route's own param name, the route\n * still MATCHED and `state.params` came back empty — the URL's parameter gone,\n * with no error anywhere.\n *\n * `Object.entries` for the walk: it hands back the value it already read, so\n * there is exactly ONE read per key and no window for a drifting accessor\n * between the test and the use (#1899). It is also the idiom the sibling copy\n * loops use.\n *\n * ⚠ **Two things it does NOT buy, both measured.**\n *\n * - It is **not** a filter against a lying Proxy source. `ownKeys` is asked\n * first, so a key that list does not contain cannot appear — but a source\n * whose `ownKeys` DOES name a phantom and whose descriptor trap calls it\n * enumerable gets that phantom copied, identically to `Object.assign`. The\n * #1854 protection is narrower than \"the trap is never consulted\".\n * - It is **not** a drop-in for `Object.assign`. `Object.entries` is\n * string-keyed, so own enumerable SYMBOL entries are dropped where\n * `Object.assign` copies them. That matches core's stated policy for the\n * channels (\"symbols are dropped, always\") and is a real behaviour difference\n * from `Object.assign` at one call site (`persistent-params`' factory). ⚠ It also disagrees with `publishRecord`\n * two functions up, which spreads and therefore keeps symbols — the same\n * internal split `helpers.ts` records as the #1792 defect.\n */\nexport function copyFields<V>(\n target: Record<string, V>,\n source: Record<string, V>,\n): void {\n for (const [key, value] of objectEntries(source)) {\n putField(target, key, value);\n }\n}\n","// packages/core/src/RouterError.ts\n\nimport { errorCodes, UNSAFE_KEY } from \"./constants\";\nimport { recordConstruction } from \"./navigationEnds\";\nimport { putField } from \"./utils/ingest\";\n\n/** Captured like the deciding seven, but this one BUILDS the guarantee (#2073). */\nconst freeze = Object.freeze;\n\nconst objectEntries = Object.entries;\nconst objectValues = Object.values;\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\n// ⚑ Captured at module load, for the reason `helpers.ts` states over its own\n// three: an application can re-point `Object.hasOwn` after boot, and this one\n// gates a PUBLIC read (#1829). ⚠ The file's four other intrinsic reads are still\n// raw — #1971 owns that sweep, and a point fix here would be the N+1 it exists\n// to prevent; capturing the read this commit ADDS is not the same thing as\n// sweeping the ones it found.\nconst hasOwn = Object.hasOwn;\n\nconst errorCodeValues = new Set(objectValues(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\n/**\n * Freeze a `RouterError` at the moment it stops being core's to change — the\n * throw (#1960).\n *\n * ⚑ At the THROW, never in the constructor. `RouterError` publishes three\n * mutators (`setCode`, `setErrorInstance`, `setAdditionalFields`) with worked\n * examples in the wiki, and `rethrowAsRouterError` copies an error and re-codes\n * the copy before throwing it. Freezing on construction was measured: it reds\n * across the tier and concentrates in this class's own suite, because it\n * withdraws published API from errors a CONSUMER builds. Freezing here\n * withdraws exactly one thing — writing to an error core threw at you — which\n * #1606 already established is corruption when the instance is one of the\n * cached, process-shared ones, and which a repository-wide sweep of every\n * `catch` binding found nobody doing.\n *\n * ⚠ Only for errors core CONSTRUCTED. A re-thrown foreign error stays untouched:\n * freezing someone else's object on the way through is the hazard, not the fix.\n *\n * ⚑ It also records the error as one core built: `navigationEnds.ts` keeps a\n * navigation's end only when core built it.\n */\nexport function freezeThrownError<E extends RouterError>(error: E): E {\n recordConstruction(error);\n\n return freeze(error);\n}\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with the `RouterError` interface in `types/base.ts`\n readonly segment: string | undefined;\n readonly path: string | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n // Subclasses don't auto-set `name`; without this `error.name` inherits\n // \"Error\", breaking `error.name === \"RouterError\"` checks at catch sites that\n // can't `instanceof` across bundle boundaries.\n this.name = \"RouterError\";\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of objectEntries(rest)) {\n if (reservedProperties.has(key)) {\n throw atRouterError.type`Cannot set reserved property \"${key}\"`;\n }\n\n // ⚑ `UNSAFE_KEY` skipped for the reason the state channels give (#1852):\n // this instance is a container core hands out and `toJSON` serializes, so\n // an own `\"__proto__\"` on it is a prototype-swap primitive for whoever\n // merges or re-parses the error — measured, a guard throwing a plain\n // object put the key into `JSON.stringify(err)`.\n //\n // ⚠ Plain assignment is the alternative that looks equivalent and is\n // worse than losing the key: measured, `new RouterError(\"X\", bag)` swaps\n // the INSTANCE's prototype and `instanceof RouterError` answers `false`.\n // `putField` keeps the instance intact; the skip keeps the key off a\n // container someone will merge.\n if (key !== UNSAFE_KEY && !reservedMethods.has(key)) {\n // ⚑ `putField` (#1852). The target is `this`, whose chain runs\n // `RouterError.prototype → Error.prototype → Object.prototype`, and the\n // key comes from the caller's bag. `reservedProperties` / `reservedMethods`\n // above filter by NAME and therefore cannot see an ambient one: measured,\n // an accessor under a custom field name threw out of the constructor,\n // and a setter left the field non-own while reading back the hijacked\n // value.\n putField(this as unknown as Record<string, unknown>, key, value);\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw atSetErrorInstance.type`err parameter is required and must be an Error instance`;\n }\n\n this.message = err.message;\n // ⚑ `putField` for THIS slot only, and the set was recounted rather than\n // assumed (#2142 / #1852). `message` and `stack` are already own on every\n // instance — `super(message ?? code)` always passes a string, and the\n // `Error` constructor installs `stack` — so their assignments define own\n // data and cannot reach the chain. `cause` has no own slot unless the\n // constructor was given one, and this class never is.\n //\n // ⚠ Measured on the plain form: an ambient `Object.prototype.cause` setter\n // took the value and left `cause` absent, and a getter-only one made this\n // line THROW — from inside the method that wraps a native failure into the\n // router's own error, so the throw would replace the error being reported.\n putField(this as unknown as Record<string, unknown>, \"cause\", err.cause);\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of objectEntries(fields)) {\n if (reservedProperties.has(key)) {\n throw atSetAdditionalFields.type`Cannot set reserved property \"${key}\"`;\n }\n\n // ⚑ `UNSAFE_KEY` skipped, and `putField` rather than assignment, for the\n // reasons the constructor's own field loop states (#1852). Not restated\n // here — one mechanism, one explanation.\n if (key !== UNSAFE_KEY && !reservedMethods.has(key)) {\n // ⚑ `putField` (#1852). The target is `this`, whose chain runs\n // `RouterError.prototype → Error.prototype → Object.prototype`, and the\n // key comes from the caller's bag. `reservedProperties` / `reservedMethods`\n // above filter by NAME and therefore cannot see an ambient one: measured,\n // an accessor under a custom field name threw out of the constructor,\n // and a setter left the field non-own while reading back the hijacked\n // value.\n putField(this as unknown as Record<string, unknown>, key, value);\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * segment: \"users\",\n * path: \"/users/7\",\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"code\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"path\"); // true\n * err.hasField(\"userId\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n // ⚑ `hasOwn`, not `in` (#1829). `in` walks the prototype chain, so this\n // answered `true` for `Object.prototype`'s twelve members and for the\n // class's own six methods — eighteen names for an error carrying ONE field\n // and `toString` / `constructor` are ordinary strings arriving from a config\n // key, a route param name or a serialized payload.\n //\n // ⚠ NOT `toJSON`'s `excludeKeys`, which the issue proposed. Measured against\n // the docstring above: that set excludes `code`, `segment` and `path`,\n // which this method documents as answering `true`. The two functions ask\n // different questions (what to SERIALIZE vs what the error CARRIES), so\n // agreeing on those three is the contract and diverging on `message` /\n // `stack` / `name` is not drift.\n return hasOwn(this, key);\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n // Reachable without `hasField` — a consumer may just read — so the same gate\n // stands here rather than being implied by the predicate (#1829). Before\n // this, `getField(\"toString\")` handed back the native function.\n return hasOwn(this, key) ? this[key] : undefined;\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"stack\",\n // `name` is now an own enumerable prop (constructor sets it to\n // \"RouterError\"); it's class metadata, not a custom field — keep it out of\n // the serialized output (preserves toJSON shape).\n \"name\",\n ]);\n\n for (const key in this) {\n if (hasOwn(this, key) && !excludeKeys.has(key)) {\n // ⚑ `putField` (#1852): `result` is a fresh literal and the keys are the\n // user's own error fields. Measured, a setter under one of them made the\n // field vanish from the serialized output with no error at all.\n putField(result, key, this[key]);\n }\n }\n\n return result;\n }\n}\n\n/**\n * A receiver a reader can IMPORT, plus this package's own name for a refusal no\n * call reaches (#1845). The door beside it is an unconstrained `string`, so the\n * type is not the guard — `message-prefix-authority-1845` judges the argument.\n */\nexport type Receiver =\n \"router\" | \"RouterError\" | \"cloneRouter\" | \"validation-plugin\";\n\ntype Tag<E extends Error> = (\n strings: TemplateStringsArray,\n ...values: unknown[]\n) => E;\n\n/** One member per constructor the refusal surface holds. */\nexport interface Raiser {\n /**\n * ⚠ `type` and `plain` also take `ErrorOptions` and RETURN the tag, because\n * `cause` cannot be attached afterwards: measured, the constructor defines it\n * non-enumerable and an assignment defines it enumerable.\n */\n type: Tag<TypeError> & ((options: ErrorOptions) => Tag<TypeError>);\n plain: Tag<Error> & ((options: ErrorOptions) => Tag<Error>);\n ref: Tag<ReferenceError>;\n range: Tag<RangeError>;\n /**\n * A coded `RouterError`, frozen for the throw (#1960) — so a site using this\n * flavour needs no `freezeThrownError` of its own. `fields` carries the bag's\n * other entries; `message` is not among them, since the template writes it.\n */\n code: (\n code: string,\n fields?: Readonly<Record<string, unknown>>,\n ) => Tag<RouterError>;\n}\n\n/** A refusal unreachable from caller input: no bracket, an explicit marker. */\nexport interface InternalDefect {\n plain: Tag<Error>;\n}\n\nconst interpolate = (\n strings: TemplateStringsArray,\n values: readonly unknown[],\n): string => {\n let text = strings[0];\n\n for (const [index, value] of values.entries()) {\n text += String(value) + strings[index + 1];\n }\n\n return text;\n};\n\n/**\n * Build the refusals of one door, so the head is written once per module rather\n * than once per throw (#2487).\n *\n * ```ts\n * const at = raiser(\"router\", \"buildPath\");\n *\n * throw at.type`Missing required param '${name}'`;\n * throw at.code(errorCodes.ROUTE_NOT_FOUND, { routeName })`No route '${routeName}'`;\n * ```\n *\n * ⚠ It RETURNS the error rather than throwing it, so the site keeps `throw` —\n * which greps, narrows types natively, and leaves room to tag the error between\n * construction and throw, as the search-params config fault does.\n *\n * ⚠ Omit `door` only where several doors reach one raiser; a head that names a\n * door the caller never called is the defect this exists to remove.\n */\nexport function raiser(receiver: Receiver, door?: string): Raiser {\n // An empty door reads as the bare form rather than printing `[router.]`, a\n // head that looks like a door without naming one.\n const head =\n door === undefined || door === \"\"\n ? `[${receiver}] `\n : `[${receiver}.${door}] `;\n const message = (\n strings: TemplateStringsArray,\n values: readonly unknown[],\n ): string => head + interpolate(strings, values);\n\n const flavour = <E extends Error>(\n build: (text: string, options?: ErrorOptions) => E,\n ): Tag<E> & ((options: ErrorOptions) => Tag<E>) =>\n ((\n first: TemplateStringsArray | ErrorOptions,\n ...values: readonly unknown[]\n ) =>\n Array.isArray(first)\n ? build(message(first as TemplateStringsArray, values))\n : (strings: TemplateStringsArray, ...rest: readonly unknown[]) =>\n build(message(strings, rest), first as ErrorOptions)) as Tag<E> &\n ((options: ErrorOptions) => Tag<E>);\n\n return {\n type: flavour((text, options) => new TypeError(text, options)),\n plain: flavour((text, options) => new Error(text, options)),\n ref: (strings, ...values) => new ReferenceError(message(strings, values)),\n range: (strings, ...values) => new RangeError(message(strings, values)),\n code:\n (code, fields) =>\n (strings, ...values) =>\n freezeThrownError(\n new RouterError(code, {\n ...fields,\n message: message(strings, values),\n }),\n ),\n };\n}\nconst atRouterError = raiser(\"RouterError\");\nconst atSetErrorInstance = raiser(\"RouterError\", \"setErrorInstance\");\nconst atSetAdditionalFields = raiser(\"RouterError\", \"setAdditionalFields\");\n\n/**\n * A defect a caller cannot provoke. Unbracketed on purpose: there is no door to\n * name, and a marker is greppable where a bare sentence is not (#1845).\n */\nexport const internalDefect: InternalDefect = {\n plain: (strings, ...values) =>\n new Error(\n `Internal error (please report): ${interpolate(strings, values)}`,\n ),\n};\n"],"mappings":"AA0BA,MAAaE,EAAkC,OAAO,OAAO,CAC3D,mBAAoB,cACpB,uBAAwB,yBACxB,uBAAwB,kBACxB,gBAAiB,kBACjB,YAAa,cACb,kBAAmB,oBACnB,gBAAiB,kBACjB,eAAgB,iBAChB,qBAAsB,YACtB,gBAAiB,WACjB,gBAAiB,kBACjB,kCAAmC,oCACnC,qBAAsB,uBACtB,wBAAyB,0BACzB,mBAAoB,cACpB,cAAe,eACjB,CAAC,EAMYC,EAAgB,yBAyBhBC,EAAa,YAEbC,EAAuB,OAAO,OAAO,CAChD,eACF,CAAC,EAMYC,EAA4B,OAAO,OAAO,CACrD,aAAc,UACd,YAAa,SACb,iBAAkB,oBAClB,yBAA0B,2BAC1B,kBAAmB,qBACnB,mBAAoB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AAS,IAAA,IAAaA,IAAS,GAC3B,IAAIC,EAAS,IACb,IAAIA,EAAS,GAAGD,EAAK,IACrBhB,GACJ,EACA,IACWe,EAAON,EAAYE,EAASE,CAAM,EAEzCK,EACJ,KAGE,EACA,GAAGL,IAEH,MAAM,QAAQM,CAAK,EACfC,EAAMpB,EAAQmB,EAA+BN,CAAM,CAAC,GACnD,EAA+B,GAAGd,IACjCqB,EAAMpB,EAAQW,EAASZ,CAAI,EAAGoB,CAAqB,GAG7D,MAAO,CACL,KAAMD,GAAS,EAAM,IAAgB,UAAUR,EAAMW,CAAO,CAAC,EAC7D,MAAOH,GAAS,EAAM,IAAgB,MAAMR,EAAMW,CAAO,CAAC,EAC1D,KAAM,EAAS,GAAGR,IAAe,eAAeb,EAAQW,EAASE,CAAM,CAAC,EACxE,OAAQ,EAAS,GAAGA,IAAe,WAAWb,EAAQW,EAASE,CAAM,CAAC,EACtE,MACG,EAAM,KACN,EAAS,GAAGA,IACXhB,EACE,IAAIC,EAAYG,EAAM,CACpB,GAAGK,EACH,QAASN,EAAQW,EAASE,CAAM,CAClC,CAAC,CACH,CACN,CACF,CACA,MAAMS,EAAgBR,EAAO,aAAa,EACpCS,EAAqBT,EAAO,cAAe,kBAAkB,EAC7DU,EAAwBV,EAAO,cAAe,qBAAqB,EAM5DW,EAAiC,CAC5C,OAAQ,EAAS,GAAGZ,IACd,MACF,mCAAmCJ,EAAYE,EAASE,CAAM,GAChE,CACJ,E"}
@@ -16,6 +16,9 @@
16
16
  *
17
17
  * ⚠ Only for errors core CONSTRUCTED. A re-thrown foreign error stays untouched:
18
18
  * freezing someone else's object on the way through is the hazard, not the fix.
19
+ *
20
+ * ⚑ It also records the error as one core built: `navigationEnds.ts` keeps a
21
+ * navigation's end only when core built it.
19
22
  */
20
23
  export declare function freezeThrownError<E extends RouterError>(error: E): E;
21
24
  export declare class RouterError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"RouterError.d.ts","names":[],"sources":["../../src/RouterError.ts"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;;;;;;;;;;;;;;;;;;EA+C5B,SAAS;;;;;;;;;;;;;;;;;;;;;EAoCT,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkCT,UAAU;;;;;;;YA8CA;KAGP,IAAI,UAAU,UACjB,SAAS,yBACN,sBACA;;iBAGY;;;;;;EAMf,MAAM,IAAI,eAAe,SAAS,iBAAiB,IAAI;EACvD,OAAO,IAAI,WAAW,SAAS,iBAAiB,IAAI;EACpD,KAAK,IAAI;EACT,OAAO,IAAI;;;;;;EAMX,OACE,cACA,SAAS,SAAS,6BACf,IAAI;;;iBAIM;EACf,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;wBAkCG,OAAO,UAAU,UAAU,gBAAgB;;;;;qBAiD9C,gBAAgB"}
package/dist/cjs/api.js CHANGED
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RouterError-CentZBJj.js"),t=require("./internals-C18omEfg.js"),n=require("./Router-_0vZHk6R.js"),r=require("./helpers-B2Zsa5R_.js"),i=e.i(`router`);function a(t,n){if(t())throw i.code(e.v.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside a subscribeChanges handler — the mutation would run while a TREE_CHANGED emit is on the stack and the tree must stay atomic. Defer it: queueMicrotask(() => routes.add(...)) or await.`;if(n())throw i.code(e.v.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside replace()'s revalidation — the tree would move under a state that has not been revalidated yet. Defer it: queueMicrotask(() => routes.replace(...)) or await.`}function o(e,t,n){if(t){let r=t===e;if(r||t.startsWith(`${e}.`)){let i=r?``:` (current: "${t}")`;return n.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return!0}function s(e,t){t.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. Removing a route the router is navigating to (or an ancestor of it) fails that navigation. The rejected navigate() promise carries "CANCELLED" while the guard walk is synchronous and "ROUTE_NOT_FOUND" once it has gone async; onTransitionError always reports "ROUTE_NOT_FOUND", and onTransitionCancel never fires. The committed state is not affected either way.`)}function c(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function l(e,t,n,r){return n&&c(e)!==c(t)?(r.error(`router.setRootPath`,"Cannot change the root PATH while navigation is in progress — it moves every route's path, including the one being navigated to. Wait for navigation to complete. (Changing only the `?`-declared query names is allowed here: it moves no paths.)"),!1):!0}function u(e,t){return!e||(t.error(`router.clear`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1)}const d=e.i(`router`,`claimContextNamespace`),f=e.i(`router`,`extendRouter`),p=Object.freeze,m=Object.keys,h=new WeakMap;function g(i){let o=h.get(i);if(o)return o;let s=t.o(i),c={makeState:(e,t,n,r)=>s.makeState(e,t,n,r),forwardState:(e,n,r)=>(t.c(s.checks,t.n[`forwardState:entry`],e,n,r),s.forwardState(e,n,r)),matchPath:e=>s.matchPath(e,s.getOptions()),navigateToState:(e,t)=>s.navigateToState(e,t),setRootPath:e=>{if(t.l(s.isDisposed),a(s.treeChanged.isEmitting,()=>s.routeGetStore().revalidating),!l(s.getRootPath(),e,s.isTransitioning(),s.logger))return!1;let n=s.getRootPath();return s.setRootPath(e),n!==e&&s.treeChanged.emit({op:`rootPath`,previous:n,next:e}),!0},getRootPath:s.getRootPath,addEventListener:(e,t)=>s.addEventListener(e,t),buildNavigationState:(e,i={},a={})=>{t.u(s,`buildNavigationState`,e,i);let o=r.t(i);t.c(s.checks,t.n[`buildNavigationState:state`],e,o,a);let c=n.E(s.port(),e,o,a,{diagnoseUndeclared:!0});if(s.buildStateResolved(c.name,c.path))return t.S(`buildNavigationState`,c.name,c.path,s.port().queryNames(c.name)),n.w(c,n.T(c,s.port()))},buildPathResolved:(e,t,n)=>s.buildPathResolved(e,t,n),getAdoptedOrigins:s.getAdoptedOrigins,logger:p({log:(e,t,...n)=>{s.logger.log(e,t,...n)},warn:(e,t,...n)=>{s.logger.warn(e,t,...n)},error:(e,t,...n)=>{s.logger.error(e,t,...n)}}),getDeclaredQueryNames:e=>s.getDeclaredQueryNames(e),getUrlParams:e=>n.C(s.routeGetStore(),e),getForwardMap:()=>{let t=e.s();return e.o(t,s.routeGetStore().config.forwardMap),p(t)},getResolvedLimits:()=>s.dependenciesGetStore().limits,getDependencyKeys:()=>p(m(s.dependenciesGetStore().dependencies)),getExternalGuardNames:()=>{let[e,t]=s.routeGetStore().lifecycleNamespace.getFactoriesByOrigin().external;return p([...new Set([...m(e),...m(t)])])},getOptions:s.getOptions,getTree:s.getTree,addInterceptor:(e,r)=>{t.l(s.isDisposed),n.N(e,r);let i=s.interceptors.get(e);i||(i=[],s.interceptors.set(e,i)),i.push(r);let a=!1;return()=>{a||(a=!0,i.splice(i.indexOf(r),1))}},subscribeDiagnostic:s.subscribeDiagnostic,addCheck:(e,r)=>{t.l(s.isDisposed),n.j(e,r);let i=s.checks.get(e);i||(i=[],s.checks.set(e,i)),i.push(r);let a=!1;return()=>{a||(a=!0,i.splice(i.indexOf(r),1))}},getRouteConfig:e=>{let t=s.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:r=>{t.l(s.isDisposed),n.M(r);let a=m(r);for(let t of a)if(t in i)throw f.code(e.v.PLUGIN_CONFLICT)`Cannot extend router: property "${t}" already exists`;let o=a.map(e=>r[e]),c={keys:a};for(let[e,t]of a.entries())i[t]=o[e];s.routerExtensions.push(c);let l=!1;return()=>{if(l)return;l=!0;for(let e of c.keys)delete i[e];let e=s.routerExtensions.indexOf(c);e!==-1&&s.routerExtensions.splice(e,1)}},emitTransitionError:e=>{t.l(s.isDisposed),s.emitTransitionError(e)},claimContextNamespace:n=>{if(t.l(s.isDisposed),typeof n!=`string`||n===``)throw d.type`namespace must be a non-empty string, got ${typeof n==`string`?`an empty string`:typeof n}`;if(s.contextClaimRecords.has(n))throw d.code(e.v.CONTEXT_NAMESPACE_ALREADY_CLAIMED)`Cannot claim context namespace: "${n}" is already claimed by another plugin`;let r={write(t,i){s.contextClaimRecords.get(n)===r&&e.l(t.context,n,i)},release(){s.contextClaimRecords.get(n)===r&&s.contextClaimRecords.delete(n)}};return s.contextClaimRecords.set(n,r),r}},u=p(c);return h.set(i,u),u}const _=e.i(`router`,`clear`),v=Object.freeze,y=Object.keys,b=Object.freeze({replace:!0,revalidate:!0}),x=Object.freeze([]);function S(e,t,r,i){let a=t=>e.has(t);n.x(t.decoders,a),n.x(t.encoders,a),n.x(t.defaultParams,a),n.x(t.defaultSearch,a),n.x(t.forwardMap,a),n.x(t.forwardFnMap,a),n.x(r,a),n.x(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of y(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of y(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.defaultSearch&&(e.defaultSearch=n.defaultSearch[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function w(t,n,r,i){let a={name:t.name,path:t.path};return C(a,n,r,i),t.children&&e.l(a,`children`,t.children.map(e=>w(e,`${n}.${e.name}`,r,i))),a}function T(e,t,n,r){let i={name:e,path:t};return C(i,e,n,r),v(i)}function E(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,T(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function D(e,t){let n=E(e,e=>t.has(e));return v([...n.values()])}function O(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(T(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),v(i)}function k(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:v(n),added:v(r)}}function A(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.defaultSearch!==void 0&&(t.defaultSearch=e.defaultSearch),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),v(t)}function j(e,t,r,i){n.a(e,t,r);let a=n.f(e,t,r,i);n.y(a.matcher,a.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(a.pendingCanActivate.keys(),a.pendingCanDeactivate.keys(),!1),n.i(e,a)}function M(e,t,n){e.systemCommit(t,n,b)}function N(e,t,r,i,a){n.l(t,`addRoute`),n.d(t,`addRoute`),n.o(t,`addRoute`),n.s(t,``,`addRoute`),n.c(t,``,`addRoute`);let o=n.p(t,e.rootPath,e.matcherOptions,r.logger);n.y(o.matcher,o.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=n.g(o,e.depsStore);e.lifecycleNamespace.clearDefinitionGuards(),n.i(e,o,s),e.revalidating=!0;try{if(a?.(),i!==void 0){let t=r.matchPath(i.path,r.getOptions());if(t){if(t.name===i.name)M(r,{...t,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o,intersection:s}=n.n(t,i,r.getMetaForState);if(e.lifecycleNamespace.canNavigateTo([],o,t,i)){let e={phase:`activating`,from:i.name,reason:`success`,replace:!0,segments:{deactivated:a,activated:o,intersection:s}};M(r,{...t,transition:e},i)}else r.revalidateToNotFound(i.path)}}else r.revalidateToNotFound(i.path)}}finally{e.revalidating=!1}}function P(e,t,r){let i=e.definitions,a=n.S(i,t);if(a===void 0)return;let o=r?D(e,a):x;return S(a,e.config,e.routeCustomFields,e.lifecycleNamespace),n.h(e,i),o}function F(e,t){let r=e.matcher.getSegmentsByName(t);if(!r)return;let i=r.at(-1),a=n.R(i),o=e.lifecycleNamespace.getFactories();return w(a,t,e.config,o)}const I=new WeakMap;function L(r){let i=I.get(r);if(i)return i;let c=t.o(r),l=c.routeGetStore(),d=e=>{c.treeChanged.emit(e)},f=v({add:(e,r)=>{t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating);let i=Array.isArray(e)?e:[e],o=r?.parent,s=n.I(i);if(t.c(c.checks,t.n[`addRoute:batch`],s,o),j(l,s,o,c.logger),c.treeChanged.listenerCount()>0){let e=O(s,o,l);d(o===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:o})}},remove:e=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),t.c(c.checks,t.n[`removeRoute:entry`],e),n.u(e,`removeRoute`),!o(e,c.getStateName(),c.logger))return;let r=c.treeChanged.listenerCount()>0,i=P(l,e,r);i===void 0?c.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`):(c.isTransitioning()&&s(e,c.logger),r&&d({op:`remove`,name:e,removedSubtree:i}))},update:(e,r)=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),t.c(c.checks,t.n[`updateRoute:entry`],e,r),n.u(e,`updateRoute`),!l.matcher.hasRoute(e))return;c.isTransitioning()&&c.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let i=l.lifecycleNamespace,o=n.m(l,i,e,r);if(c.treeChanged.listenerCount()>0){let t=A(o);y(t).length>0&&d({op:`update`,name:e,patch:t})}},clear:()=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),c.getStateName()!==void 0)throw _.code(e.v.ROUTER_NOT_STOPPED)`Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`;if(!u(c.isTransitioning(),c.logger))return;let r=c.treeChanged.listenerCount()>0?v([...E(l,()=>!0).values()]):void 0;n._(l),l.lifecycleNamespace.clearAll(),r!==void 0&&d({op:`clear`,removed:r})},has:e=>(t.c(c.checks,t.n[`hasRoute:entry`],e),l.matcher.hasRoute(e)),get:e=>(t.c(c.checks,t.n[`getRoute:entry`],e),F(l,e)),replace:e=>{t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating);let i=Array.isArray(e)?e:[e];if(!u(c.isTransitioning(),c.logger))return;let o=n.I(i);t.c(c.checks,t.n[`replaceRoutes:batch`],o);let s=r.getState(),f=c.treeChanged.listenerCount()>0?E(l,()=>!0):void 0;N(l,o,c,s,f===void 0?void 0:()=>{let e=E(l,()=>!0),{removed:t,added:n}=k(f,e);d({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>(n.F(e),c.treeChanged.subscribe(e))});return I.set(r,f),f}const R=Object.hasOwn,z=Object.keys,B=e=>typeof e==`symbol`?e:String(e),V=[];function H(e,t,n,r){if(n===void 0)return;let i=e.dependencies,a=B(t),o=r?z(i):V;if(o.includes(a)){let e=i[a];e!==n&&!(Number.isNaN(e)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(String(a),`setDependency`)}else r?.dependencies.validateDependencyCount(o.length,e.limits.maxDependencies,`setDependency`);i[a]=n}function U(e,t,r){let i=[],a=e.dependencies,o=new Set(r?z(a):V);n.L(t,(t,s)=>{o.has(t)?i.push(t):(r?.dependencies.validateDependencyCount(o.size,e.limits.maxDependencies,`setDependencies`),o.add(t)),n.A(a,t,s)}),i.length>0&&r?.dependencies.warnBatchOverwrite(i,`setDependencies`)}function W(e){let r=t.o(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),i=n.O(t,e);return r.validator?.dependencies.validateDependencyExists(e,i),i},getAll:()=>n.k(r.dependenciesGetStore()),set:(e,n)=>{t.l(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,n,`setDependency`),H(r.dependenciesGetStore(),e,n,r.validator),t.l(r.isDisposed)},setAll:e=>{t.l(r.isDisposed);let n=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),U(n,e,r.validator),t.l(r.isDisposed)},remove:e=>{t.l(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let n=r.dependenciesGetStore(),i=B(e);R(n.dependencies,i)||r.validator?.dependencies.warnRemoveNonExistent(String(i)),delete n.dependencies[i]},reset:()=>{t.l(r.isDisposed),n.D(r.dependenciesGetStore())},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),R(r.dependenciesGetStore().dependencies,e))}}function G(e){let r=t.o(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,a){t.l(r.isDisposed),n.P(e,`addActivateGuard`),t.c(r.checks,t.n[`addActivateGuard:entry`],e,a),i.addCanActivate(e,a,!1)},addDeactivateGuard(e,a){t.l(r.isDisposed),n.P(e,`addDeactivateGuard`),t.c(r.checks,t.n[`addDeactivateGuard:entry`],e,a),i.addCanDeactivate(e,a,!1)},removeActivateGuard(e){t.l(r.isDisposed),n.P(e,`removeActivateGuard`),t.c(r.checks,t.n[`removeActivateGuard:entry`],e),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){t.l(r.isDisposed),n.P(e,`removeDeactivateGuard`),t.c(r.checks,t.n[`removeDeactivateGuard:entry`],e),i.clearCanDeactivate(e,`external`)}}}const K=Object.entries,q=Object.hasOwn,J=e.i(`cloneRouter`);function Y(r,i,a){let o=t.o(r);if(o.isDisposed())throw J.code(e.v.ROUTER_DISPOSED)`cannot clone a disposed router — dispose() is terminal`;o.validator?.dependencies.validateCloneArgs(i);let s=o.routeGetStore(),c=n.z(s.tree),l=s.config,u=s.resolvedForwardMap,d=s.routeCustomFields,{options:f,dependencies:p,pluginFactories:m,loggerConfig:h,limits:g,limitKeys:_}=o.getCloneState(),{definition:v,external:y}=s.lifecycleNamespace.getFactoriesByOrigin(),b={...p};i!==void 0&&n.L(i,(t,n)=>{e.l(b,t,n)});let x=a?.logger,S=x?{...h,...x}:h,C=new n.t(c,{...f,...s.matcherOptions?.queryParams!==void 0&&{queryParams:s.matcherOptions.queryParams},logger:S,..._!==void 0&&{limits:Object.fromEntries(_.filter(e=>q(g,e)).map(e=>[e,g[e]]))},...s.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:s.matcherOptions.urlParamsEncoding}},b),w=t.o(C),T=w.routeGetStore(),E=T.lifecycleNamespace;n.b(T.config,l),n.r(T,Object.assign(T.resolvedForwardMap,u)),Object.assign(T.routeCustomFields,d),s.rootPath!==``&&w.setRootPath(s.rootPath);let[D,O]=v,[k,A]=y;for(let[e,t]of K(D))E.addCanDeactivate(e,t,!0);for(let[e,t]of K(O))E.addCanActivate(e,t,!0);let j=G(C);for(let[e,t]of K(k))j.addDeactivateGuard(e,t);for(let[e,t]of K(A))j.addActivateGuard(e,t);let M=new Set(w.getCloneState().pluginFactories),N=m.filter(e=>!M.has(e));return N.length>0&&C.usePlugin(...N),C}exports.cloneRouter=Y,exports.getDependenciesApi=W,exports.getLifecycleApi=G,exports.getPluginApi=g,exports.getRoutesApi=L;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RouterError-aGkUvcJJ.js"),t=require("./internals-BEKzn5ug.js"),n=require("./Router-BSgyC0DG.js"),r=require("./helpers-DdpDlqWS.js"),i=e.i(`router`);function a(t,n){if(t())throw i.code(e.b.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside a subscribeChanges handler — the mutation would run while a TREE_CHANGED emit is on the stack and the tree must stay atomic. Defer it: queueMicrotask(() => routes.add(...)) or await.`;if(n())throw i.code(e.b.REENTRANT_TREE_MUTATION)`cannot mutate the route tree from inside replace()'s revalidation — the tree would move under a state that has not been revalidated yet. Defer it: queueMicrotask(() => routes.replace(...)) or await.`}function o(e,t,n){if(t){let r=t===e;if(r||t.startsWith(`${e}.`)){let i=r?``:` (current: "${t}")`;return n.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return!0}function s(e,t){t.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. Removing a route the router is navigating to (or an ancestor of it) fails that navigation with "ROUTE_NOT_FOUND" — the rejected navigate() promise and onTransitionError carry the same code, and onTransitionCancel never fires. The committed state is not affected either way.`)}function c(e){let t=e.indexOf(`?`);return t===-1?e:e.slice(0,t)}function l(e,t,n,r){return n&&c(e)!==c(t)?(r.error(`router.setRootPath`,"Cannot change the root PATH while navigation is in progress — it moves every route's path, including the one being navigated to. Wait for navigation to complete. (Changing only the `?`-declared query names is allowed here: it moves no paths.)"),!1):!0}const u=e.i(`router`,`claimContextNamespace`),d=e.i(`router`,`extendRouter`),f=Object.freeze,p=Object.keys,m=new WeakMap;function h(i){let o=m.get(i);if(o)return o;let s=t.o(i),c={makeState:(e,t,n,r)=>s.makeState(e,t,n,r),forwardState:(e,n,r)=>(t.c(s.checks,t.n[`forwardState:entry`],e,n,r),s.forwardState(e,n,r)),matchPath:e=>s.matchPath(e,s.getOptions()),navigateToState:(e,t)=>s.navigateToState(e,t),setRootPath:e=>{if(t.l(s.isDisposed),a(s.treeChanged.isEmitting,()=>s.routeGetStore().revalidating),!l(s.getRootPath(),e,s.isTransitioning(),s.logger))return!1;let n=s.getRootPath();return s.setRootPath(e),n!==e&&s.treeChanged.emit({op:`rootPath`,previous:n,next:e}),!0},getRootPath:s.getRootPath,addEventListener:(e,t)=>s.addEventListener(e,t),buildNavigationState:(e,i={},a={})=>{t.u(s,`buildNavigationState`,e,i);let o=r.t(i);t.c(s.checks,t.n[`buildNavigationState:state`],e,o,a);let c=n.E(s.port(),e,o,a,{diagnoseUndeclared:!0});if(s.buildStateResolved(c.name,c.path))return t.S(`buildNavigationState`,c.name,c.path,s.port().queryNames(c.name)),n.w(c,n.T(c,s.port()))},buildPathResolved:(e,t,n)=>s.buildPathResolved(e,t,n),getAdoptedOrigins:s.getAdoptedOrigins,logger:f({log:(e,t,...n)=>{s.logger.log(e,t,...n)},warn:(e,t,...n)=>{s.logger.warn(e,t,...n)},error:(e,t,...n)=>{s.logger.error(e,t,...n)}}),getDeclaredQueryNames:e=>s.getDeclaredQueryNames(e),getUrlParams:e=>n.C(s.routeGetStore(),e),getForwardMap:()=>{let t=e.s();return e.o(t,s.routeGetStore().config.forwardMap),f(t)},getResolvedLimits:()=>s.dependenciesGetStore().limits,getDependencyKeys:()=>f(p(s.dependenciesGetStore().dependencies)),getExternalGuardNames:()=>{let[e,t]=s.routeGetStore().lifecycleNamespace.getFactoriesByOrigin().external;return f([...new Set([...p(e),...p(t)])])},getOptions:s.getOptions,getTree:s.getTree,addInterceptor:(e,r)=>{t.l(s.isDisposed),n.N(e,r);let i=s.interceptors.get(e);i||(i=[],s.interceptors.set(e,i)),i.push(r);let a=!1;return()=>{a||(a=!0,i.splice(i.indexOf(r),1))}},subscribeDiagnostic:s.subscribeDiagnostic,addCheck:(e,r)=>{t.l(s.isDisposed),n.j(e,r);let i=s.checks.get(e);i||(i=[],s.checks.set(e,i)),i.push(r);let a=!1;return()=>{a||(a=!0,i.splice(i.indexOf(r),1))}},getRouteConfig:e=>{let t=s.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:r=>{t.l(s.isDisposed),n.M(r);let a=p(r);for(let t of a)if(t in i)throw d.code(e.b.PLUGIN_CONFLICT)`Cannot extend router: property "${t}" already exists`;let o=a.map(e=>r[e]),c={keys:a};for(let[e,t]of a.entries())i[t]=o[e];s.routerExtensions.push(c);let l=!1;return()=>{if(l)return;l=!0;for(let e of c.keys)delete i[e];let e=s.routerExtensions.indexOf(c);e!==-1&&s.routerExtensions.splice(e,1)}},emitTransitionError:e=>{t.l(s.isDisposed),s.emitTransitionError(e)},claimContextNamespace:n=>{if(t.l(s.isDisposed),typeof n!=`string`||n===``)throw u.type`namespace must be a non-empty string, got ${typeof n==`string`?`an empty string`:typeof n}`;if(s.contextClaimRecords.has(n))throw u.code(e.b.CONTEXT_NAMESPACE_ALREADY_CLAIMED)`Cannot claim context namespace: "${n}" is already claimed by another plugin`;let r={write(t,i){s.contextClaimRecords.get(n)===r&&e.l(t.context,n,i)},release(){s.contextClaimRecords.get(n)===r&&s.contextClaimRecords.delete(n)}};return s.contextClaimRecords.set(n,r),r}},h=f(c);return m.set(i,h),h}const g=e.i(`router`,`clear`),_=Object.freeze,v=Object.keys,y=Object.freeze({replace:!0,revalidate:!0}),b=Object.freeze([]);function x(e,t,r,i){let a=t=>e.has(t);n.x(t.decoders,a),n.x(t.encoders,a),n.x(t.defaultParams,a),n.x(t.defaultSearch,a),n.x(t.forwardMap,a),n.x(t.forwardFnMap,a),n.x(r,a),n.x(t.forwardMap,e=>a(t.forwardMap[e]));let[o,s]=i.getFactories();for(let e of v(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of v(o))a(e)&&i.clearCanDeactivate(e,`both`)}function S(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.defaultSearch&&(e.defaultSearch=n.defaultSearch[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function C(t,n,r,i){let a={name:t.name,path:t.path};return S(a,n,r,i),t.children&&e.l(a,`children`,t.children.map(e=>C(e,`${n}.${e.name}`,r,i))),a}function w(e,t,n,r){let i={name:e,path:t};return S(i,e,n,r),_(i)}function T(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,w(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function E(e,t){let n=T(e,e=>t.has(e));return _([...n.values()])}function D(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(w(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),_(i)}function O(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:_(n),added:_(r)}}function k(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.defaultSearch!==void 0&&(t.defaultSearch=e.defaultSearch),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),_(t)}function A(e,t,r,i){n.a(e,t,r);let a=n.f(e,t,r,i);n.y(a.matcher,a.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(a.pendingCanActivate.keys(),a.pendingCanDeactivate.keys(),!1),n.i(e,a)}function j(e,t,n){e.systemCommit(t,n,y)}function M(e,t,r,i,a){n.l(t,`addRoute`),n.d(t,`addRoute`),n.o(t,`addRoute`),n.s(t,``,`addRoute`),n.c(t,``,`addRoute`);let o=n.p(t,e.rootPath,e.matcherOptions,r.logger);n.y(o.matcher,o.config,`addRoute`),e.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=n.g(o,e.depsStore);e.lifecycleNamespace.clearDefinitionGuards(),n.i(e,o,s),e.revalidating=!0;try{if(a?.(),i!==void 0){let t=r.matchPath(i.path,r.getOptions());if(t){if(t.name===i.name)j(r,{...t,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o,intersection:s}=n.n(t,i,r.getMetaForState);if(e.lifecycleNamespace.canNavigateTo([],o,t,i,`replace`)){let e={phase:`activating`,from:i.name,reason:`success`,replace:!0,segments:{deactivated:a,activated:o,intersection:s}};j(r,{...t,transition:e},i)}else r.revalidateToNotFound(i.path)}}else r.revalidateToNotFound(i.path)}}finally{e.revalidating=!1}}function N(e,t,r){let i=e.definitions,a=n.S(i,t);if(a===void 0)return;let o=r?E(e,a):b;return x(a,e.config,e.routeCustomFields,e.lifecycleNamespace),n.h(e,i),o}function P(e,t){let r=e.matcher.getSegmentsByName(t);if(!r)return;let i=r.at(-1),a=n.R(i),o=e.lifecycleNamespace.getFactories();return C(a,t,e.config,o)}const F=new WeakMap;function I(r){let i=F.get(r);if(i)return i;let c=t.o(r),l=c.routeGetStore(),u=e=>{c.treeChanged.emit(e)},d=_({add:(e,r)=>{t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating);let i=Array.isArray(e)?e:[e],o=r?.parent,s=n.I(i);if(t.c(c.checks,t.n[`addRoute:batch`],s,o),A(l,s,o,c.logger),c.treeChanged.listenerCount()>0){let e=D(s,o,l);u(o===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:o})}},remove:e=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),t.c(c.checks,t.n[`removeRoute:entry`],e),n.u(e,`removeRoute`),!o(e,c.getStateName(),c.logger))return;let r=c.treeChanged.listenerCount()>0,i=N(l,e,r);i===void 0?c.logger.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`):(c.isTransitioning()&&s(e,c.logger),r&&u({op:`remove`,name:e,removedSubtree:i}))},update:(e,r)=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),t.c(c.checks,t.n[`updateRoute:entry`],e,r),n.u(e,`updateRoute`),!l.matcher.hasRoute(e))return;c.isTransitioning()&&c.logger.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`);let i=l.lifecycleNamespace,o=n.m(l,i,e,r);if(c.treeChanged.listenerCount()>0){let t=k(o);v(t).length>0&&u({op:`update`,name:e,patch:t})}},clear:()=>{if(t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating),c.getStateName()!==void 0)throw g.code(e.b.ROUTER_NOT_STOPPED)`Cannot clear routes while a state is committed. Use replace(routes) to swap the tree on a running router, or stop() first.`;if(c.isTransitioning()){c.logger.error(`router.clear`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`);return}let r=c.treeChanged.listenerCount()>0?_([...T(l,()=>!0).values()]):void 0;n._(l),l.lifecycleNamespace.clearAll(),r!==void 0&&u({op:`clear`,removed:r})},has:e=>(t.c(c.checks,t.n[`hasRoute:entry`],e),l.matcher.hasRoute(e)),get:e=>(t.c(c.checks,t.n[`getRoute:entry`],e),P(l,e)),replace:e=>{t.l(c.isDisposed),a(c.treeChanged.isEmitting,()=>l.revalidating);let i=Array.isArray(e)?e:[e];if(c.isTransitioning()){c.logger.error(`router.replace`,`Cannot replace routes while navigation is in progress. Wait for navigation to complete.`);return}let o=n.I(i);t.c(c.checks,t.n[`replaceRoutes:batch`],o);let s=r.getState(),d=c.treeChanged.listenerCount()>0?T(l,()=>!0):void 0;M(l,o,c,s,d===void 0?void 0:()=>{let e=T(l,()=>!0),{removed:t,added:n}=O(d,e);u({op:`replace`,removed:t,added:n})})},subscribeChanges:e=>(n.F(e),c.treeChanged.subscribe(e))});return F.set(r,d),d}const L=Object.hasOwn,R=Object.keys,z=e=>typeof e==`symbol`?e:String(e),B=[];function V(e,t,n,r){if(n===void 0)return;let i=e.dependencies,a=z(t),o=r?R(i):B;if(o.includes(a)){let e=i[a];e!==n&&!(Number.isNaN(e)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(String(a),`setDependency`)}else r?.dependencies.validateDependencyCount(o.length,e.limits.maxDependencies,`setDependency`);i[a]=n}function H(e,t,r){let i=[],a=e.dependencies,o=new Set(r?R(a):B);n.L(t,(t,s)=>{o.has(t)?i.push(t):(r?.dependencies.validateDependencyCount(o.size,e.limits.maxDependencies,`setDependencies`),o.add(t)),n.A(a,t,s)}),i.length>0&&r?.dependencies.warnBatchOverwrite(i,`setDependencies`)}function U(e){let r=t.o(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),i=n.O(t,e);return r.validator?.dependencies.validateDependencyExists(e,i),i},getAll:()=>n.k(r.dependenciesGetStore()),set:(e,n)=>{t.l(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,n,`setDependency`),V(r.dependenciesGetStore(),e,n,r.validator),t.l(r.isDisposed)},setAll:e=>{t.l(r.isDisposed);let n=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),H(n,e,r.validator),t.l(r.isDisposed)},remove:e=>{t.l(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let n=r.dependenciesGetStore(),i=z(e);L(n.dependencies,i)||r.validator?.dependencies.warnRemoveNonExistent(String(i)),delete n.dependencies[i]},reset:()=>{t.l(r.isDisposed),n.D(r.dependenciesGetStore())},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),L(r.dependenciesGetStore().dependencies,e))}}function W(e){let r=t.o(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,a){t.l(r.isDisposed),n.P(e,`addActivateGuard`),t.c(r.checks,t.n[`addActivateGuard:entry`],e,a),i.addCanActivate(e,a,!1)},addDeactivateGuard(e,a){t.l(r.isDisposed),n.P(e,`addDeactivateGuard`),t.c(r.checks,t.n[`addDeactivateGuard:entry`],e,a),i.addCanDeactivate(e,a,!1)},removeActivateGuard(e){t.l(r.isDisposed),n.P(e,`removeActivateGuard`),t.c(r.checks,t.n[`removeActivateGuard:entry`],e),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){t.l(r.isDisposed),n.P(e,`removeDeactivateGuard`),t.c(r.checks,t.n[`removeDeactivateGuard:entry`],e),i.clearCanDeactivate(e,`external`)}}}const G=Object.entries,K=Object.hasOwn,q=e.i(`cloneRouter`);function J(r,i,a){let o=t.o(r);if(o.isDisposed())throw q.code(e.b.ROUTER_DISPOSED)`cannot clone a disposed router — dispose() is terminal`;o.validator?.dependencies.validateCloneArgs(i);let s=o.routeGetStore(),c=n.z(s.tree),l=s.config,u=s.resolvedForwardMap,d=s.routeCustomFields,{options:f,dependencies:p,pluginFactories:m,loggerConfig:h,limits:g,limitKeys:_}=o.getCloneState(),{definition:v,external:y}=s.lifecycleNamespace.getFactoriesByOrigin(),b={...p};i!==void 0&&n.L(i,(t,n)=>{e.l(b,t,n)});let x=a?.logger,S=x?{...h,...x}:h,C=new n.t(c,{...f,...s.matcherOptions?.queryParams!==void 0&&{queryParams:s.matcherOptions.queryParams},logger:S,..._!==void 0&&{limits:Object.fromEntries(_.filter(e=>K(g,e)).map(e=>[e,g[e]]))},...s.matcherOptions?.urlParamsEncoding!==void 0&&{urlParamsEncoding:s.matcherOptions.urlParamsEncoding}},b),w=t.o(C),T=w.routeGetStore(),E=T.lifecycleNamespace;n.b(T.config,l),n.r(T,Object.assign(T.resolvedForwardMap,u)),Object.assign(T.routeCustomFields,d),s.rootPath!==``&&w.setRootPath(s.rootPath);let[D,O]=v,[k,A]=y;for(let[e,t]of G(D))E.addCanDeactivate(e,t,!0);for(let[e,t]of G(O))E.addCanActivate(e,t,!0);let j=W(C);for(let[e,t]of G(k))j.addDeactivateGuard(e,t);for(let[e,t]of G(A))j.addActivateGuard(e,t);let M=new Set(w.getCloneState().pluginFactories),N=m.filter(e=>!M.has(e));return N.length>0&&C.usePlugin(...N),C}exports.cloneRouter=J,exports.getDependenciesApi=U,exports.getLifecycleApi=W,exports.getPluginApi=h,exports.getRoutesApi=I;
2
2
  //# sourceMappingURL=api.js.map