@real-router/core 0.82.0 → 0.82.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/Router-DunclyU6.js +2 -0
- package/dist/cjs/Router-DunclyU6.js.map +1 -0
- package/dist/cjs/Router.d.ts +13 -0
- package/dist/cjs/Router.d.ts.map +1 -1
- package/dist/cjs/Router.js +1 -1
- package/dist/cjs/Router.js.map +1 -1
- package/dist/cjs/api.js +1 -2
- package/dist/cjs/helpers.js +1 -1
- package/dist/cjs/helpers.js.map +1 -1
- package/dist/cjs/index.js +1 -2
- package/dist/cjs/namespaces/NavigationNamespace/InFlightNavigation.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/InFlightNavigation.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js.map +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/constants.js +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/constants.js.map +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js.map +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/executeNavigation.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/executeNavigation.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js.map +1 -1
- package/dist/cjs/namespaces/NavigationNamespace/transition/navigateToNotFound.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/navigateToNotFound.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts +19 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts.map +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js +1 -1
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js.map +1 -1
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js +1 -1
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js.map +1 -1
- package/dist/cjs/pipeline/canonicalize.js +1 -1
- package/dist/cjs/pipeline/canonicalize.js.map +1 -1
- package/dist/cjs/pipeline/materialize.js +1 -1
- package/dist/cjs/pipeline/materialize.js.map +1 -1
- package/dist/cjs/pipeline/port.d.ts +8 -0
- package/dist/cjs/pipeline/port.d.ts.map +1 -1
- package/dist/cjs/validation.js +1 -2
- package/dist/esm/Router-yitiDzP1.mjs +2 -0
- package/dist/esm/Router-yitiDzP1.mjs.map +1 -0
- package/dist/esm/Router.d.mts +13 -0
- package/dist/esm/Router.d.mts.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts +19 -0
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts.map +1 -1
- package/dist/esm/pipeline/port.d.mts +8 -0
- package/dist/esm/pipeline/port.d.mts.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/Router-CCmcEi-S.js +0 -2
- package/dist/cjs/Router-CCmcEi-S.js.map +0 -1
- package/dist/esm/Router-DEpNuwBW.mjs +0 -2
- package/dist/esm/Router-DEpNuwBW.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NavigationNamespace.js","names":["constants","#deps","CACHED_NOT_STARTED_REJECTION","CACHED_ROUTE_NOT_FOUND_ERROR","CACHED_ROUTE_NOT_FOUND_REJECTION","#executeNavigation","RouterError","errorCodes","findMisChanneledKey","misChanneledKeyMessage","#abortPreviousNavigation","nameToIDs","EMPTY_PARAMS","EMPTY_SEARCH","#currentController","CACHED_SAME_STATES_ERROR","CACHED_SAME_STATES_REJECTION","#navigationId","getTransitionPath","#handleNoGuardsLeave","executeGuardPipeline","#finishAsyncNavigation","#cleanupController","completeTransition","#handleNavigateError"],"sources":["../../../../src/namespaces/NavigationNamespace/NavigationNamespace.ts"],"sourcesContent":["import {\n CACHED_NOT_STARTED_REJECTION,\n CACHED_ROUTE_NOT_FOUND_ERROR,\n CACHED_ROUTE_NOT_FOUND_REJECTION,\n CACHED_SAME_STATES_ERROR,\n CACHED_SAME_STATES_REJECTION,\n} from \"./constants\";\nimport { completeTransition } from \"./transition/completeTransition\";\nimport { routeTransitionError } from \"./transition/errorHandling\";\nimport { executeGuardPipeline } from \"./transition/guardPhase\";\nimport { findMisChanneledKey, misChanneledKeyMessage } from \"../../channels\";\nimport {\n EMPTY_PARAMS,\n EMPTY_SEARCH,\n errorCodes,\n constants,\n} from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\nimport { getTransitionPath, nameToIDs } from \"../../transitionPath\";\n\nimport type { NavigationContext, NavigationDependencies } from \"./types\";\nimport type { TransitionPath } from \"../../transitionPath\";\nimport type {\n GuardFn,\n NavigationOptions,\n Params,\n SearchParams,\n State,\n TransitionMeta,\n} from \"../../types\";\n\nconst FROZEN_ACTIVATED: string[] = Object.freeze([\n constants.UNKNOWN_ROUTE,\n]) as unknown as string[];\nconst FROZEN_REPLACE_OPTS: NavigationOptions = Object.freeze({ replace: true });\n\nfunction forceReplaceFromUnknown(\n opts: NavigationOptions,\n fromState: State | undefined,\n): NavigationOptions {\n return fromState?.name === constants.UNKNOWN_ROUTE && !opts.replace\n ? { ...opts, replace: true }\n : opts;\n}\n\nfunction isSameNavigation(\n fromState: State | undefined,\n opts: NavigationOptions,\n toState: State,\n): boolean {\n return (\n !!fromState &&\n !opts.reload &&\n !opts.force &&\n fromState.path === toState.path\n );\n}\n\n/**\n * Independent namespace for managing navigation.\n *\n * Handles navigate(), navigateToDefault(), navigateToNotFound(), and transition state.\n *\n * Performance: navigate() uses optimistic sync execution — guards run synchronously\n * until one returns a Promise, then switches to async. This eliminates Promise/AbortController\n * overhead for the common case (no guards or sync guards).\n */\nexport class NavigationNamespace {\n // Stryker disable next-line BooleanLiteral: equivalent — reset to false at the top of every navigate()/navigateToState()/navigateToDefault(), so the initializer value is never observed.\n lastSyncResolved = false;\n lastSyncRejected = false;\n #deps!: NavigationDependencies;\n #currentController: AbortController | null = null;\n #navigationId = 0;\n\n // =========================================================================\n // Dependency injection\n // =========================================================================\n\n setDependencies(deps: NavigationDependencies): void {\n this.#deps = deps;\n }\n\n // =========================================================================\n // Instance methods\n // =========================================================================\n\n navigate(\n name: string,\n params: Params,\n search: SearchParams | undefined,\n opts: NavigationOptions,\n ): Promise<State> {\n this.lastSyncResolved = false;\n const deps = this.#deps;\n\n // Fast-path sync rejections: cached error + cached Promise.reject\n // No allocations, no throw/catch overhead, facade skips .catch() suppression\n if (!deps.canNavigate()) {\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag, not a correctness gate. Not flagging the cached (pre-suppressed) rejection routes the facade to the else-branch, which re-attaches a harmless .catch; no observable difference.\n this.lastSyncRejected = true;\n\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n let toState: State | undefined;\n\n try {\n toState = deps.buildNavigateState(name, params, search);\n } catch (error) {\n /* v8 ignore next 3 -- @preserve: reachable only via validator-driven\n throws from buildNavigateState (validateStateBuilderArgs) — covered\n in @real-router/validation-plugin's suite, not in core. */\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided buildNavigateState\n return Promise.reject(error);\n }\n\n if (!toState) {\n deps.emitTransitionError(\n undefined,\n deps.getState(),\n CACHED_ROUTE_NOT_FOUND_ERROR,\n );\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_ROUTE_NOT_FOUND_REJECTION;\n }\n\n return this.#executeNavigation(toState, opts);\n }\n\n /**\n * Navigate to a fully-built `State` directly, skipping `buildNavigateState`\n * (forwardState + buildPath + meta lookup). Used by URL plugins after they\n * have already produced a `State` from a browser-initiated event via\n * `api.matchPath(url)` — see issue #525.\n *\n * Semantics vs. `navigate(name, params, opts)`:\n * - `forwardState` is NOT re-applied. matchPath already runs it; reapplying\n * is redundant in the idempotent case and can race in the dynamic case.\n * - `buildPath` is NOT re-run. The caller's `state.path` is used as-is —\n * so `trailingSlash:\"preserve\"` matchedState paths flow through unchanged\n * (closes #525 Q2). `buildPath` interceptors do NOT run; the URL the\n * user navigated to is the source of truth for this code path.\n * - All other pipeline steps run unchanged: SAME_STATES check, FSM\n * transition, guards, `subscribeLeave`, `completeTransition`,\n * plugin lifecycle hooks.\n */\n navigateToState(state: State, opts: NavigationOptions): Promise<State> {\n this.lastSyncResolved = false;\n const deps = this.#deps;\n\n if (!deps.canNavigate()) {\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n // Reject states whose route no longer exists (e.g. the route tree was\n // mutated between matchPath and navigateToState). UNKNOWN_ROUTE is\n // structurally legal — it is the navigateToNotFound output shape.\n if (state.name !== constants.UNKNOWN_ROUTE && !deps.hasRoute(state.name)) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: state.name,\n });\n\n deps.emitTransitionError(undefined, deps.getState(), err);\n\n // This is a FRESH reject (carries `routeName`), not one of the\n // pre-suppressed CACHED_*_REJECTION singletons. `lastSyncRejected`\n // contractually means \"I returned a pre-suppressed cached rejection —\n // skip your .catch()\", so leaving it unset lets the facade attach its\n // own suppression. Setting it here leaked an unhandledRejection on\n // fire-and-forget calls (#721).\n return Promise.reject(err);\n }\n\n // Channel guard, position P3 (#1572). `navigateToState` is the ONE producer\n // that takes a ready-made `State` instead of a `params` argument, so the\n // predicate reads `state.params ∩ queryNames(state.name)`. What it commits\n // becomes `getState()`, so a pre-M2 layout would be silent corruption: the\n // key sits in `state.params` and never reaches `state.path`.\n //\n // Costs nothing on healthy flows — a state produced by core (`matchPath`,\n // `makeState`) is channel-correct by construction, so the predicate is\n // empty on every popstate / memory-restore / SSR-hydration commit. `start()`\n // commits THROUGH here (`RouterLifecycleNamespace`), which is why the guard\n // lives in the namespace rather than on the plugin-API door.\n //\n // Rejects rather than throwing, mirroring the ROUTE_NOT_FOUND guard above:\n // this method returns `Promise<State>` and its URL-plugin callers invoke it\n // from popstate handlers, where a new synchronous throw would be a change\n // of failure shape rather than a new failure.\n const misChanneled = findMisChanneledKey(\n state.params,\n deps.getQueryParams(state.name),\n );\n\n if (misChanneled !== undefined) {\n const err = new RouterError(errorCodes.WRONG_CHANNEL, {\n routeName: state.name,\n message: `[router.navigateToState] ${misChanneledKeyMessage(\n state.name,\n misChanneled,\n \"`state.params`\",\n )}`,\n });\n\n deps.emitTransitionError(undefined, deps.getState(), err);\n\n return Promise.reject(err);\n }\n\n // States from `matchPath` are deeply frozen (`freezeStateInPlace`).\n // `completeTransition` mutates `toState.transition` and `context` is\n // intentionally extensible for plugin claim writes, so we hand the\n // pipeline a writable shell — same shape `makeState(skipFreeze=true)`\n // produces. `params` stays referentially shared (already frozen).\n // `transition` is omitted so completeTransition can assign it.\n const writableState = {\n name: state.name,\n params: state.params,\n // Carry the query channel through the writable shell (RFC-4 M2 / #1548) —\n // without this, start()'s navigateToState(matchPath(...)) would drop the\n // matched query from the committed state.\n search: state.search,\n path: state.path,\n context: { ...state.context },\n } as State;\n\n // No route-meta to carry any more (RFC-4 M2 / #1548): ownership is read from\n // the live matcher by `state.name` (`getTransitionPath`'s `getMeta`), not\n // from a per-State WeakMap. The former #1170 carry — which existed only so a\n // matchPath-derived writable shell stayed non-meta-less across consecutive\n // popstate navs — is obsolete: any state whose name is in the tree takes the\n // STANDARD PATH regardless of object identity.\n\n return this.#executeNavigation(writableState, opts);\n }\n\n navigateToDefault(opts: NavigationOptions): Promise<State> {\n // Reset the sync-resolution flag on entry, mirroring navigate() and\n // navigateToState(). start() leaves `lastSyncResolved = true`, and the\n // early reject paths below return before delegating to navigate(), so a\n // stale `true` would make the facade take the \"already resolved\" branch\n // and skip .catch() suppression — leaking an unhandledRejection on\n // fire-and-forget calls (#721).\n this.lastSyncResolved = false;\n const deps = this.#deps;\n const options = deps.getOptions();\n\n if (!options.defaultRoute) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute not configured\",\n }),\n );\n }\n\n let route: string;\n let params: Params;\n let search: SearchParams;\n\n try {\n ({ route, params, search } = deps.resolveDefault());\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided resolveDefault callback\n return Promise.reject(error);\n }\n\n if (!route) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute resolved to empty\",\n }),\n );\n }\n\n // Both channels, never one bag (RFC-4 M2 / #1548). The query slot took\n // `undefined` until `defaultSearch` existed as a router option, so a\n // query-declared name in `defaultParams` reached the URL only via the\n // `forwardState` seam's channel re-separation — the repair the pipeline\n // design removes. Passing the query here makes the default route's query\n // defaults independent of that stage.\n return this.navigate(route, params, search, opts);\n }\n\n navigateToNotFound(path: string): State {\n // #1186 — liveness gate. This internal commit primitive has no FSM\n // transition of its own, so without this check a `dispose()` that lands\n // while a start-interceptor is parked (FSM already DISPOSED) would let the\n // resuming pipeline commit an UNKNOWN_ROUTE state on the disposed router and\n // `start()` resolve. Symmetric with `navigateToState`'s `canNavigate()` gate\n // (the matched-route branch is already protected). `!isActive()` also covers\n // a merely-stopped (IDLE) router: the only reachable path to that is a direct\n // `router.navigateToNotFound()` on a stopped instance (internal callers run\n // during STARTING, which is active), so the ROUTER_DISPOSED code is slightly\n // broad there — fail-closed is deliberate (committing on a stopped router is\n // out of contract), and the disposed race is the case that matters.\n if (!this.#deps.isActive()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n this.#abortPreviousNavigation();\n\n const fromState = this.#deps.getState();\n const deactivated: string[] = fromState\n ? nameToIDs(fromState.name).toReversed()\n : [];\n\n Object.freeze(deactivated);\n\n const segments: TransitionMeta[\"segments\"] = {\n deactivated,\n activated: FROZEN_ACTIVATED,\n intersection: \"\",\n };\n\n Object.freeze(segments);\n\n const transitionMeta: TransitionMeta = {\n phase: \"activating\",\n ...(fromState && { from: fromState.name }),\n reason: \"success\",\n replace: true,\n segments,\n };\n\n Object.freeze(transitionMeta);\n\n const state: State = {\n name: constants.UNKNOWN_ROUTE,\n params: EMPTY_PARAMS,\n search: EMPTY_SEARCH,\n path,\n transition: transitionMeta,\n context: {},\n };\n\n Object.freeze(state);\n\n this.#deps.setState(state);\n this.#deps.emitTransitionSuccess(state, fromState, FROZEN_REPLACE_OPTS);\n\n return state;\n }\n\n /**\n * Aborts and releases the in-flight navigation's `AbortController` (waking the\n * parked async pipeline via `onInternalAbort`). This is the\n * **effect** of the FSM `CANCEL` action (`handleCancel` → injected\n * `deps.abortCurrentController`), not something cancellation sources call\n * directly — so \"FSM `CANCEL` ⟹ controller aborted\" holds in one place (RFC\n * navigation-cancellation-unification §5). `reason` (e.g. an external\n * `opts.signal`'s reason, #943) becomes the controller's `signal.reason`;\n * defaults to `TRANSITION_CANCELLED`.\n */\n abortCurrentController(reason?: unknown): void {\n this.#currentController?.abort(\n reason ?? new RouterError(errorCodes.TRANSITION_CANCELLED),\n );\n this.#currentController = null;\n }\n\n #executeNavigation(toState: State, opts: NavigationOptions): Promise<State> {\n const deps = this.#deps;\n let fromState: State | undefined;\n let transitionStarted = false;\n let controller: AbortController | null = null;\n\n try {\n fromState = deps.getState();\n opts = forceReplaceFromUnknown(opts, fromState);\n\n if (isSameNavigation(fromState, opts, toState)) {\n deps.emitTransitionError(toState, fromState, CACHED_SAME_STATES_ERROR);\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_SAME_STATES_REJECTION;\n }\n\n this.#abortPreviousNavigation(opts.signal);\n\n // Stryker disable next-line UpdateOperator: equivalent — `#navigationId` is only ever compared by identity (`!== myId`) to detect supersession; uniqueness per navigation is all that matters, so `--` (decreasing ids) is indistinguishable from `++`.\n const myId = ++this.#navigationId;\n\n // #1169 commit-gate — liveness snapshot captured BEFORE the pre-commit\n // listener windows. A listener's `stop()`/`dispose()` runs `clearAll()`,\n // which empties the listener lists, so the marker must be read now, not at\n // the commit site (that self-destruct was the QB/QE hole, RFC §5-bis).\n // `suspendable` is true only when a synchronous supersede is reachable — an\n // external `opts.signal`, `subscribeLeave` listeners, or a pre-commit\n // plugin listener (`onTransitionStart` / `onTransitionLeaveApprove`); the\n // pure synchronous navigate (none of these) is uncancellable and skips the\n // gate, keeping the #307 hot path perf-neutral.\n const suspendable =\n opts.signal !== undefined ||\n deps.hasLeaveListeners() ||\n deps.hasPreCommitListeners();\n\n deps.startTransition(toState, fromState);\n transitionStarted = true;\n\n // Post-`startTransition` supersession is now caught at the commit-gate\n // below (before `completeTransition`'s setState): a `stop()`/`dispose()`/\n // external-abort from the TRANSITION_START listener leaves the FSM in\n // IDLE/DISPOSED, which `!deps.isActive()` detects. (Async supersession is\n // additionally caught in `#finishAsyncNavigation` / the guard pipeline's\n // `isCurrentNav`; a reentrant navigate() is banned — REENTRANT_NAVIGATION.)\n\n const [canDeactivateFunctions, canActivateFunctions] =\n deps.getLifecycleFunctions();\n const isUnknownRoute = toState.name === constants.UNKNOWN_ROUTE;\n\n const transitionPath = getTransitionPath(toState, fromState, (name) =>\n deps.getMetaForState(name),\n );\n const { toDeactivate, toActivate, intersection } = transitionPath;\n\n const shouldDeactivate =\n fromState && !opts.forceDeactivate && toDeactivate.length > 0;\n const shouldActivate = !isUnknownRoute && toActivate.length > 0;\n const hasGuards =\n canDeactivateFunctions.size > 0 || canActivateFunctions.size > 0;\n\n const confirmedToState = toState;\n\n if (!hasGuards) {\n const asyncLeave = this.#handleNoGuardsLeave(\n confirmedToState,\n fromState,\n myId,\n opts,\n transitionPath,\n canDeactivateFunctions,\n );\n\n if (asyncLeave !== undefined) {\n return asyncLeave;\n }\n }\n\n // Stryker disable next-line ConditionalExpression: equivalent — running the guard pipeline on the no-guards path does not double-emit LEAVE_APPROVE (full suite green with `if (true)`); the BlockStatement mutant stays live (killed by guarded-route tests).\n // eslint-disable-next-line unicorn/prefer-else-if -- two exhaustive `if`s read clearer here than an else-if; merging cascades into no-negated-condition / no-unnecessary-condition in this hot guard-setup branch\n if (hasGuards) {\n controller = new AbortController();\n this.#currentController = controller;\n const isCurrentNav = () =>\n this.#navigationId === myId && deps.isActive();\n\n const signal = controller.signal;\n\n const emitLeaveApproveCallback = (): Promise<void> | undefined => {\n deps.sendLeaveApprove(confirmedToState, fromState);\n\n if (deps.hasLeaveListeners()) {\n return deps.awaitLeaveListeners(\n confirmedToState,\n fromState,\n signal,\n );\n }\n\n return undefined;\n };\n\n const guardCompletion = executeGuardPipeline(\n canDeactivateFunctions,\n canActivateFunctions,\n toDeactivate,\n toActivate,\n !!shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isCurrentNav,\n emitLeaveApproveCallback,\n );\n\n if (guardCompletion !== undefined) {\n return this.#finishAsyncNavigation(\n guardCompletion,\n {\n toState,\n fromState,\n opts,\n toDeactivate,\n toActivate,\n intersection,\n canDeactivateFunctions,\n },\n controller,\n myId,\n );\n }\n\n if (!isCurrentNav()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n this.#cleanupController(controller, false);\n }\n\n // #1169 commit-gate — refuse to commit a navigation cancelled or\n // terminated during a listener window, BEFORE `completeTransition`'s\n // setState. The FSM table (D-full) already prevents the forceState\n // resurrection; this prevents the state commit that precedes the emit.\n // Gated on `suspendable` so the pure sync hot path pays nothing. A\n // `stop()`/`dispose()` from the listener lands the FSM in IDLE/DISPOSED\n // (caught by `!isActive()`); an external `opts.signal` abort is caught\n // directly. No `#navigationId` check: a reentrant navigate() (the only\n // thing that could bump it synchronously) is banned (REENTRANT_NAVIGATION,\n // §4), so on this sync path `#navigationId === myId` always holds — async\n // supersede is caught in `#finishAsyncNavigation`'s `isCurrentNav`.\n if (suspendable && (!deps.isActive() || opts.signal?.aborted === true)) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const finalState = completeTransition(deps, {\n toState,\n fromState,\n opts,\n toDeactivate,\n toActivate,\n intersection,\n canDeactivateFunctions,\n });\n\n // Mark sync-resolution only AFTER completeTransition returns. It emits\n // TRANSITION_SUCCESS; listener throws are all isolated via onListenerError\n // (the emitter re-throws nothing now that re-entrant emits are coalesced,\n // #1033, and reentrant navigate/CRUD are banned), so the emit itself does\n // not throw. Should completeTransition throw for any other reason, setting\n // the flag optimistically BEFORE it would leave the flag stale-true, so the\n // facade would read lastSyncResolved and skip its suppressing `.catch()` —\n // the rejection would then leak as a Node unhandledRejection. Post-emit\n // placement keeps the flag false on a throw, so control falls to catch and\n // the facade attaches its `.catch`.\n // Stryker disable next-line BooleanLiteral: equivalent — flipping to false routes the facade to the else-branch, which attaches a harmless .catch to an already-resolved promise; there is no rejection to suppress.\n this.lastSyncResolved = true;\n\n return Promise.resolve(finalState);\n } catch (error) {\n this.#handleNavigateError(\n error,\n controller,\n transitionStarted,\n toState,\n fromState,\n );\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from guards or transition pipeline\n return Promise.reject(error);\n }\n }\n\n async #finishAsyncNavigation(\n guardCompletion: Promise<void>,\n nav: NavigationContext,\n controller: AbortController,\n myId: number,\n ): Promise<State> {\n const deps = this.#deps;\n const isActive = () =>\n this.#navigationId === myId &&\n !controller.signal.aborted &&\n deps.isActive();\n\n const externalSignal = nav.opts.signal;\n let onExternalAbort: (() => void) | undefined;\n let onInternalAbort: (() => void) | undefined;\n let succeeded = false;\n let failureReason: unknown;\n\n // #1018: race the guard completion against the controller's abort so a\n // non-cooperative guard whose Promise never settles (and ignores `signal`)\n // cannot wedge navigate() forever. `abortRace` RESOLVES on abort, so the\n // post-race `isActive()` check below throws TRANSITION_CANCELLED — the same\n // path that already handles a guard which swallows the abort and resolves\n // `true`. `stop()`/`dispose()`/supersede all abort the controller. Mirrors\n // the leave-path protection `settleLeavePromises` (#663/#673).\n const abortRace = new Promise<void>((resolve) => {\n if (controller.signal.aborted) {\n resolve();\n\n return;\n }\n\n onInternalAbort = () => {\n resolve();\n };\n\n controller.signal.addEventListener(\"abort\", onInternalAbort, {\n once: true,\n });\n });\n\n // Consume `guardCompletion` when the abort wins the race: a slow or\n // never-settling guard that settles later then has no awaiter, which would\n // surface as an unhandled rejection without this catch.\n guardCompletion.catch(() => {\n /* settlement consumed — the race already decided the navigation */\n });\n\n try {\n if (externalSignal) {\n if (externalSignal.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: externalSignal.reason,\n });\n }\n\n // Bridge an external `{ signal }` abort onto the internal controller.\n // It is NOT scoped to `controller.signal` (the old `{ signal }` option)\n // because success no longer aborts the controller (#722) — the listener\n // is detached explicitly in `finally` instead.\n onExternalAbort = () => {\n // (#1030): route the external abort through the FSM. The\n // `CANCEL` action aborts the internal controller (waking THIS pipeline)\n // with the external `reason` (#943 — surfaces via the leave signal) AND\n // returns the FSM to READY, atomically. No direct `controller.abort`\n // here — \"FSM CANCEL ⟹ controller aborted\" lives in one place\n // (handleCancel). onExternalAbort only fires while the navigation is in\n // flight (the listener is removed in `finally` once it settles), so the\n // FSM is always cancellable here.\n deps.cancelNavigation(externalSignal.reason);\n };\n // Stryker disable next-line ObjectLiteral: equivalent — `{ once: true }` is redundant: the per-navigation signal aborts at most once and is discarded unaborted on success, and the `finally` block explicitly removeEventListener's it.\n externalSignal.addEventListener(\"abort\", onExternalAbort, {\n // Stryker disable next-line BooleanLiteral: equivalent — `once` redundant (see ObjectLiteral above); the listener is explicitly removed in `finally`.\n once: true,\n });\n }\n\n await Promise.race([guardCompletion, abortRace]);\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const state = completeTransition(deps, nav);\n\n succeeded = true;\n\n return state;\n } catch (error) {\n failureReason = error;\n\n routeTransitionError(deps, error, nav.toState, nav.fromState);\n\n throw error;\n // NB: the `} finally {}` BlockStatement mutant SURVIVES but is EQUIVALENT —\n // emptying the finally only skips #cleanupController, which is unobservable\n // (defense-in-depth: on a CANCEL the FSM CANCEL action already aborted+nulled\n // the controller via abortCurrentController, RFC §5; the success-path\n // ref-release is proven unobservable — see #cleanupController's disable). It\n // cannot be inline-`Stryker disable`d: the catch `}` and finally `{` share one\n // line, so there is no comment position that targets the finally body. Left documented.\n } finally {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — listener cleanup is redundant: the per-navigation signal is discarded on completion, so skipping the removeEventListener leaks nothing observable.\n if (onExternalAbort) {\n // Stryker disable next-line StringLiteral: equivalent — cleanup event name is redundant (listener is `{ once: true }` and the signal is discarded), so a wrong name removes nothing observable.\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n\n // Detach the abort-race listener before #cleanupController aborts the\n // controller below, so the cleanup abort cannot re-fire it. `undefined`\n // only when the controller was already aborted at setup (the early-resolve\n // branch above registered no listener).\n if (onInternalAbort) {\n controller.signal.removeEventListener(\"abort\", onInternalAbort);\n }\n\n // Success drops the controller without aborting (the subscribeLeave signal\n // must stay unaborted); cancel/error aborts it with the originating reason\n // so captured signals expose the real cause via `signal.reason` (#943).\n this.#cleanupController(controller, !succeeded, failureReason);\n }\n }\n\n #handleNavigateError(\n error: unknown,\n controller: AbortController | null,\n transitionStarted: boolean,\n toState: State | undefined,\n fromState: State | undefined,\n ): void {\n if (controller) {\n this.#cleanupController(controller, true, error);\n }\n\n if (transitionStarted && toState) {\n routeTransitionError(this.#deps, error, toState, fromState);\n }\n }\n\n #handleNoGuardsLeave(\n toState: State,\n fromState: State | undefined,\n myId: number,\n opts: NavigationOptions,\n transitionPath: TransitionPath,\n canDeactivateFunctions: Map<string, GuardFn>,\n ): Promise<State> | undefined {\n const deps = this.#deps;\n\n deps.sendLeaveApprove(toState, fromState);\n\n if (deps.hasLeaveListeners()) {\n const controller = new AbortController();\n\n // Track as the current navigation BEFORE listeners run so a reentrant\n // navigate() / stop() / dispose() from a sync listener aborts THIS leave\n // signal — parity with the guard path (#722). On success the controller is\n // released without aborting (see #cleanupController).\n this.#currentController = controller;\n\n let leaveResult: Promise<void> | undefined;\n\n try {\n leaveResult = deps.awaitLeaveListeners(\n toState,\n fromState,\n controller.signal,\n );\n } catch (error) {\n // A sync listener threw — the navigation fails; abort the leave signal\n // with the thrown value so a listener that captured the signal sees the\n // real cause via `signal.reason`, not a generic AbortError (#943).\n this.#cleanupController(controller, true, error);\n\n throw error;\n }\n\n if (leaveResult !== undefined) {\n return this.#finishAsyncNavigation(\n leaveResult,\n {\n toState,\n fromState,\n opts,\n toDeactivate: transitionPath.toDeactivate,\n toActivate: transitionPath.toActivate,\n intersection: transitionPath.intersection,\n canDeactivateFunctions,\n },\n controller,\n myId,\n );\n }\n\n // Sync listeners settled. A synchronous reentrant navigate() can no longer\n // supersede here (banned, RFC §4), so the leave always succeeds: release the\n // controller WITHOUT aborting (the subscribeLeave signal must stay live).\n this.#cleanupController(controller, false);\n\n return undefined;\n }\n\n // No leave listeners: nothing synchronous could have superseded this\n // navigation during the LEAVE_APPROVE emit (reentrant navigate is banned).\n return undefined;\n }\n\n /**\n * Release a navigation's AbortController. The same `controller.signal` is\n * handed to `subscribeLeave` listeners, so it must abort **only** when the\n * navigation is cancelled or errors — never on success (#722). On the success\n * path pass `cancelled = false`: the reference is dropped without aborting, so\n * a listener that captured the signal still sees `aborted === false`.\n *\n * On the failure/cancellation path (`cancelled = true`) pass the originating\n * `reason` so `signal.reason` carries router/error context (a `RouterError`,\n * or the value a sync leave listener threw) — consistent with the cancellation\n * abort `RouterError(TRANSITION_CANCELLED)`, not a generic `AbortError` (#943).\n * `abort()` is idempotent: a controller already aborted by a superseding\n * navigation keeps its first (also-meaningful) reason.\n */\n #cleanupController(\n controller: AbortController,\n cancelled: boolean,\n reason?: unknown,\n ): void {\n if (cancelled) {\n controller.abort(reason);\n }\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,BlockStatement: equivalent — controller identity-guard; cleanup correctness is enforced by #abortPreviousNavigation + the navigationId/isCurrentNav checks. Full suite stays green with `=== → !==` (nulls the wrong controller) and with the body removed (ref never nulled), so no mutant here is observable.\n if (this.#currentController === controller) {\n this.#currentController = null;\n }\n }\n\n #abortPreviousNavigation(externalSignal?: AbortSignal): void {\n if (this.#deps.isTransitioning()) {\n this.#deps.logger.warn(\n \"router.navigate\",\n \"Concurrent navigation detected on shared router instance. \" +\n \"For SSR, use cloneRouter() to create isolated instance per request.\",\n );\n // The FSM CANCEL action aborts the previous controller — no\n // direct controller.abort here (RFC navigation-cancellation-unification §5).\n this.#deps.cancelNavigation();\n }\n\n if (externalSignal?.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: externalSignal.reason,\n });\n }\n }\n}\n"],"mappings":"iTA+BM,EAA6B,OAAO,OAAO,CAC/CA,EAAAA,UAAU,aACZ,CAAC,EACK,EAAyC,OAAO,OAAO,CAAE,QAAS,EAAK,CAAC,EAE9E,SAAS,EACP,EACA,EACmB,CACnB,OAAO,GAAW,OAASA,EAAAA,UAAU,eAAiB,CAAC,EAAK,QACxD,CAAE,GAAG,EAAM,QAAS,EAAK,EACzB,CACN,CAEA,SAAS,EACP,EACA,EACA,EACS,CACT,MACE,CAAC,CAAC,GACF,CAAC,EAAK,QACN,CAAC,EAAK,OACN,EAAU,OAAS,EAAQ,IAE/B,CAWA,IAAa,EAAb,KAAiC,CAE/B,iBAAmB,GACnB,iBAAmB,GACnB,GACA,GAA6C,KAC7C,GAAgB,EAMhB,gBAAgB,EAAoC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AS,EAAO,CAMd,MAFA,KAAKQ,GAAmB,EAAY,GAAM,CAAK,EAEzC,CACR,CAEA,GAAI,IAAgB,IAAA,GAClB,OAAO,KAAKD,GACV,EACA,CACE,UACA,YACA,OACA,aAAc,EAAe,aAC7B,WAAY,EAAe,WAC3B,aAAc,EAAe,aAC7B,wBACF,EACA,EACA,CACF,EAMF,KAAKC,GAAmB,EAAY,EAAK,EAEzC,MACF,CAKF,CAgBA,GACE,EACA,EACA,EACM,CACF,GACF,EAAW,MAAM,CAAM,EAIrB,KAAKR,KAAuB,IAC9B,KAAKA,GAAqB,KAE9B,CAEA,GAAyB,EAAoC,CAY3D,GAXI,KAAKb,GAAM,gBAAgB,IAC7B,KAAKA,GAAM,OAAO,KAChB,kBACA,+HAEF,EAGA,KAAKA,GAAM,iBAAiB,GAG1B,GAAgB,QAClB,MAAM,IAAIK,EAAAA,YAAYC,EAAAA,WAAW,qBAAsB,CACrD,OAAQ,EAAe,MACzB,CAAC,CAEL,CACF"}
|
|
1
|
+
{"version":3,"file":"NavigationNamespace.js","names":["#inFlight","InFlightNavigation","#deps","#onSuppressed","isExpectedRejection","#settle","#navigate","#navigateToState","#navigateToDefault","navigateToNotFound","PRE_SUPPRESSED","CACHED_NOT_STARTED_REJECTION","CACHED_ROUTE_NOT_FOUND_ERROR","CACHED_ROUTE_NOT_FOUND_REJECTION","executeNavigation","constants","RouterError","errorCodes","findMisChanneledKey","misChanneledKeyMessage"],"sources":["../../../../src/namespaces/NavigationNamespace/NavigationNamespace.ts"],"sourcesContent":["import {\n CACHED_NOT_STARTED_REJECTION,\n CACHED_ROUTE_NOT_FOUND_ERROR,\n CACHED_ROUTE_NOT_FOUND_REJECTION,\n isExpectedRejection,\n PRE_SUPPRESSED,\n} from \"./constants\";\nimport { InFlightNavigation } from \"./InFlightNavigation\";\nimport { executeNavigation } from \"./transition/executeNavigation\";\nimport { navigateToNotFound } from \"./transition/navigateToNotFound\";\nimport { findMisChanneledKey, misChanneledKeyMessage } from \"../../channels\";\nimport { errorCodes, constants } from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\n\nimport type { NavigationDependencies } from \"./types\";\nimport type {\n NavigationOptions,\n Params,\n SearchParams,\n State,\n} from \"../../types\";\n\n/**\n * Independent namespace for managing navigation.\n *\n * Handles navigate(), navigateToDefault(), navigateToNotFound(), and transition state.\n *\n * Performance: navigate() uses optimistic sync execution — guards run synchronously\n * until one returns a Promise, then switches to async. This eliminates Promise/AbortController\n * overhead for the common case (no guards or sync guards).\n */\nexport class NavigationNamespace {\n #deps!: NavigationDependencies;\n #onSuppressed!: (error: unknown) => void;\n // The controller + supersession token of the navigation in flight, owned as\n // one thing (#1607). Built here, one per router — never per navigation.\n readonly #inFlight = new InFlightNavigation();\n\n // =========================================================================\n // Dependency injection\n // =========================================================================\n\n setDependencies(deps: NavigationDependencies): void {\n this.#deps = deps;\n // Built once here rather than per call: the closure needs THIS router's\n // logger, so it cannot be static, and `setDependencies` is a pure\n // assignment that runs exactly once at wiring (#1331).\n this.#onSuppressed = (error: unknown): void => {\n if (isExpectedRejection(error)) {\n return;\n }\n\n deps.logger.error(\n \"router.navigate\",\n \"Unexpected navigation error\",\n error,\n );\n };\n }\n\n // =========================================================================\n // Instance methods\n // =========================================================================\n\n navigate(\n name: string,\n params: Params,\n search: SearchParams | undefined,\n opts: NavigationOptions,\n ): State | Promise<State> {\n return this.#settle(this.#navigate(name, params, search, opts));\n }\n\n /**\n * Navigate to a fully-built `State` directly, skipping `buildNavigateState`\n * (forwardState + buildPath + meta lookup). Used by URL plugins after they\n * have already produced a `State` from a browser-initiated event via\n * `api.matchPath(url)` — see issue #525.\n *\n * Semantics vs. `navigate(name, params, opts)`:\n * - `forwardState` is NOT re-applied. matchPath already runs it; reapplying\n * is redundant in the idempotent case and can race in the dynamic case.\n * - `buildPath` is NOT re-run. The caller's `state.path` is used as-is —\n * so `trailingSlash:\"preserve\"` matchedState paths flow through unchanged\n * (closes #525 Q2). `buildPath` interceptors do NOT run; the URL the\n * user navigated to is the source of truth for this code path.\n * - All other pipeline steps run unchanged: SAME_STATES check, FSM\n * transition, guards, `subscribeLeave`, `completeTransition`,\n * plugin lifecycle hooks.\n */\n navigateToState(\n state: State,\n opts: NavigationOptions,\n ): State | Promise<State> {\n return this.#settle(this.#navigateToState(state, opts));\n }\n\n navigateToDefault(opts: NavigationOptions): State | Promise<State> {\n return this.#settle(this.#navigateToDefault(opts));\n }\n\n navigateToNotFound(path: string): State {\n return navigateToNotFound(this.#deps, path);\n }\n\n /**\n * Aborts and releases the in-flight navigation's `AbortController` (waking the\n * parked async pipeline via `onInternalAbort`). This is the\n * **effect** of the FSM `CANCEL` action (`handleCancel` → injected\n * `deps.abortCurrentController`), not something cancellation sources call\n * directly — so \"FSM `CANCEL` ⟹ controller aborted\" holds in one place (RFC\n * navigation-cancellation-unification §5). `reason` (e.g. an external\n * `opts.signal`'s reason, #943) becomes the controller's `signal.reason`;\n * defaults to `TRANSITION_CANCELLED`.\n */\n abortCurrentController(reason?: unknown): void {\n this.#inFlight.abort(reason);\n }\n\n /**\n * The producer's own fire-and-forget guarantee (#721): whatever leaves a\n * public method here is safe to drop on the floor.\n *\n * ONE checkpoint per public method, deliberately — not a `.catch()` at each of\n * the six return sites. A forgotten site is invisible until it leaks, which is\n * the bug this replaces; a single choke point cannot be forgotten. And the\n * discriminator is the returned VALUE's identity, not a flag the facade reads\n * afterwards: `PRE_SUPPRESSED` promises already carry a module-load handler, so\n * re-suppressing them buys nothing and costs a derived promise.\n *\n * A synchronously-returned `State` needs nothing at all — there is no rejection\n * to suppress, which is precisely what makes `lastSyncResolved` unnecessary:\n * the TYPE now carries what the flag used to announce.\n */\n #settle(result: State | Promise<State>): State | Promise<State> {\n if (result instanceof Promise && !PRE_SUPPRESSED.has(result)) {\n result.catch(this.#onSuppressed);\n }\n\n return result;\n }\n\n /**\n * `navigate`'s body, minus the fire-and-forget checkpoint.\n *\n * Split out because `navigateToDefault` delegates HERE, not to the public\n * method: routing it through `navigate` would run `#settle` twice per default\n * navigation and attach a second, pointless `.catch()` — an extra derived\n * promise on a path that has none today.\n */\n #navigate(\n name: string,\n params: Params,\n search: SearchParams | undefined,\n opts: NavigationOptions,\n ): State | Promise<State> {\n const deps = this.#deps;\n\n // Fast-path sync rejections: cached error + cached Promise.reject.\n // No allocations, no throw/catch overhead; `#settle` recognises the\n // singleton by identity and skips its `.catch()`.\n if (!deps.canNavigate()) {\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n let toState: State | undefined;\n\n try {\n toState = deps.buildNavigateState(name, params, search);\n } catch (error) {\n // No `v8 ignore` here any more: the comment that used to sit above this\n // line claimed the path was \"reachable only via validator-driven throws\n // … covered in @real-router/validation-plugin's suite, not in core\", and\n // that stopped being true when the always-on channel guard (#1572) began\n // throwing from core's own `buildNavigateState`. Measured: with the ignore\n // removed, core's suite still reports 100% — it was masking a live region.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided buildNavigateState\n return Promise.reject(error);\n }\n\n if (!toState) {\n deps.emitTransitionError(\n undefined,\n deps.getState(),\n CACHED_ROUTE_NOT_FOUND_ERROR,\n );\n\n return CACHED_ROUTE_NOT_FOUND_REJECTION;\n }\n\n return executeNavigation(this.#deps, this.#inFlight, toState, opts);\n }\n\n #navigateToState(\n state: State,\n opts: NavigationOptions,\n ): State | Promise<State> {\n const deps = this.#deps;\n\n if (!deps.canNavigate()) {\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n // Reject states whose route no longer exists (e.g. the route tree was\n // mutated between matchPath and navigateToState). UNKNOWN_ROUTE is\n // structurally legal — it is the navigateToNotFound output shape.\n if (state.name !== constants.UNKNOWN_ROUTE && !deps.hasRoute(state.name)) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: state.name,\n });\n\n deps.emitTransitionError(undefined, deps.getState(), err);\n\n // A FRESH reject (it carries `routeName`), so it is deliberately NOT in\n // `PRE_SUPPRESSED` and `#settle` will attach its `.catch()`. Adding it to\n // that set — the modern shape of the mistake that caused #721 — would skip\n // suppression on a promise nobody else handles and leak it.\n return Promise.reject(err);\n }\n\n // Channel guard, position P3 (#1572). `navigateToState` is the ONE producer\n // that takes a ready-made `State` instead of a `params` argument, so the\n // predicate reads `state.params ∩ queryNames(state.name)`. What it commits\n // becomes `getState()`, so a pre-M2 layout would be silent corruption: the\n // key sits in `state.params` and never reaches `state.path`.\n //\n // Costs nothing on healthy flows — a state produced by core (`matchPath`,\n // `makeState`) is channel-correct by construction, so the predicate is\n // empty on every popstate / memory-restore / SSR-hydration commit. `start()`\n // commits THROUGH here (`RouterLifecycleNamespace`), which is why the guard\n // lives in the namespace rather than on the plugin-API door.\n //\n // Rejects rather than throwing, mirroring the ROUTE_NOT_FOUND guard above:\n // this method returns `Promise<State>` and its URL-plugin callers invoke it\n // from popstate handlers, where a new synchronous throw would be a change\n // of failure shape rather than a new failure.\n const misChanneled = findMisChanneledKey(\n state.params,\n deps.getQueryParams(state.name),\n );\n\n if (misChanneled !== undefined) {\n const err = new RouterError(errorCodes.WRONG_CHANNEL, {\n routeName: state.name,\n message: `[router.navigateToState] ${misChanneledKeyMessage(\n state.name,\n misChanneled,\n \"`state.params`\",\n )}`,\n });\n\n deps.emitTransitionError(undefined, deps.getState(), err);\n\n return Promise.reject(err);\n }\n\n // States from `matchPath` are deeply frozen (`freezeStateShell`).\n // `completeTransition` mutates `toState.transition` and `context` is\n // intentionally extensible for plugin claim writes, so we hand the\n // pipeline a writable shell — same shape `makeState(skipFreeze=true)`\n // produces. `params` stays referentially shared (already frozen).\n // `transition` is omitted so completeTransition can assign it.\n const writableState = {\n name: state.name,\n params: state.params,\n // Carry the query channel through the writable shell (RFC-4 M2 / #1548) —\n // without this, start()'s navigateToState(matchPath(...)) would drop the\n // matched query from the committed state.\n search: state.search,\n path: state.path,\n context: { ...state.context },\n } as State;\n\n // No route-meta to carry any more (RFC-4 M2 / #1548): ownership is read from\n // the live matcher by `state.name` (`getTransitionPath`'s `getMeta`), not\n // from a per-State WeakMap. The former #1170 carry — which existed only so a\n // matchPath-derived writable shell stayed non-meta-less across consecutive\n // popstate navs — is obsolete: any state whose name is in the tree takes the\n // STANDARD PATH regardless of object identity.\n\n return executeNavigation(this.#deps, this.#inFlight, writableState, opts);\n }\n\n #navigateToDefault(opts: NavigationOptions): State | Promise<State> {\n const deps = this.#deps;\n const options = deps.getOptions();\n\n if (!options.defaultRoute) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute not configured\",\n }),\n );\n }\n\n let route: string;\n let params: Params;\n let search: SearchParams;\n\n try {\n ({ route, params, search } = deps.resolveDefault());\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided resolveDefault callback\n return Promise.reject(error);\n }\n\n if (!route) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute resolved to empty\",\n }),\n );\n }\n\n // Both channels, never one bag (RFC-4 M2 / #1548). The query slot took\n // `undefined` until `defaultSearch` existed as a router option, so a\n // query-declared name in `defaultParams` reached the URL only via the\n // `forwardState` seam's channel re-separation — the repair the pipeline\n // design removes. Passing the query here makes the default route's query\n // defaults independent of that stage.\n //\n // Delegates to the PRIVATE core: the public `navigate` would run `#settle`\n // here and again in this method's own wrapper, costing a second `.catch()`\n // per default navigation.\n return this.#navigate(route, params, search, opts);\n }\n}\n"],"mappings":"6QA+BA,IAAa,EAAb,KAAiC,CAC/B,GACA,GAGA,GAAqB,IAAIC,EAAAA,mBAMzB,gBAAgB,EAAoC,CAClD,KAAKC,GAAQ,EAIb,KAAKC,GAAiB,GAAyB,CACzCC,EAAAA,oBAAoB,CAAK,GAI7B,EAAK,OAAO,MACV,kBACA,8BACA,CACF,CACF,CACF,CAMA,SACE,EACA,EACA,EACA,EACwB,CACxB,OAAO,KAAKC,GAAQ,KAAKC,GAAU,EAAM,EAAQ,EAAQ,CAAI,CAAC,C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M,OACN,EAAK,eAAe,EAAM,IAAI,CAChC,EAEA,GAAI,IAAiB,IAAA,GAAW,CAC9B,IAAM,EAAM,IAAIF,EAAAA,YAAYC,EAAAA,WAAW,cAAe,CACpD,UAAW,EAAM,KACjB,QAAS,4BAA4BE,EAAAA,uBACnC,EAAM,KACN,EACA,gBACF,GACF,CAAC,EAID,OAFA,EAAK,oBAAoB,IAAA,GAAW,EAAK,SAAS,EAAG,CAAG,EAEjD,QAAQ,OAAO,CAAG,CAC3B,CAQA,IAAM,EAAgB,CACpB,KAAM,EAAM,KACZ,OAAQ,EAAM,OAId,OAAQ,EAAM,OACd,KAAM,EAAM,KACZ,QAAS,CAAE,GAAG,EAAM,OAAQ,CAC9B,EASA,OAAOL,EAAAA,kBAAkB,KAAKZ,GAAO,KAAKF,GAAW,EAAe,CAAI,CAC1E,CAEA,GAAmB,EAAiD,CAClE,IAAM,EAAO,KAAKE,GAGlB,GAAI,CAFY,EAAK,WAEV,CAAC,CAAC,aACX,OAAO,QAAQ,OACb,IAAIc,EAAAA,YAAYC,EAAAA,WAAW,gBAAiB,CAC1C,UAAW,6BACb,CAAC,CACH,EAGF,IAAI,EACA,EACA,EAEJ,GAAI,EACD,4BAA4B,EAAK,eAAe,EACnD,OAAS,EAAO,CAEd,OAAO,QAAQ,OAAO,CAAK,CAC7B,CAoBA,OAlBK,EAkBE,KAAKX,GAAU,EAAO,EAAQ,EAAQ,CAAI,EAjBxC,QAAQ,OACb,IAAIU,EAAAA,YAAYC,EAAAA,WAAW,gBAAiB,CAC1C,UAAW,gCACb,CAAC,CACH,CAcJ,CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../constants.js"),t=require("../../RouterError.js"),n=new t.RouterError(e.errorCodes.ROUTER_NOT_STARTED),r=new t.RouterError(e.errorCodes.ROUTE_NOT_FOUND),i=new t.RouterError(e.errorCodes.SAME_STATES),a=Promise.reject(n),o=Promise.reject(r),s=Promise.reject(i);a.catch(()=>{}),o.catch(()=>{}),s.catch(()=>{}),exports.CACHED_NOT_STARTED_ERROR=n,exports.CACHED_NOT_STARTED_REJECTION=a,exports.CACHED_ROUTE_NOT_FOUND_ERROR=r,exports.CACHED_ROUTE_NOT_FOUND_REJECTION=o,exports.CACHED_SAME_STATES_ERROR=i,exports.CACHED_SAME_STATES_REJECTION=s;
|
|
1
|
+
const e=require("../../constants.js"),t=require("../../RouterError.js"),n=new t.RouterError(e.errorCodes.ROUTER_NOT_STARTED),r=new t.RouterError(e.errorCodes.ROUTE_NOT_FOUND),i=new t.RouterError(e.errorCodes.SAME_STATES),a=Promise.reject(n),o=Promise.reject(r),s=Promise.reject(i);a.catch(()=>{}),o.catch(()=>{}),s.catch(()=>{});const c=new Set([e.errorCodes.SAME_STATES,e.errorCodes.TRANSITION_CANCELLED,e.errorCodes.ROUTER_NOT_STARTED,e.errorCodes.ROUTE_NOT_FOUND,e.errorCodes.CANNOT_ACTIVATE,e.errorCodes.CANNOT_DEACTIVATE,e.errorCodes.ROUTER_ALREADY_STARTED]);function l(e){return e instanceof t.RouterError&&c.has(e.code)}const u=new Set([a,o,s]);exports.CACHED_NOT_STARTED_ERROR=n,exports.CACHED_NOT_STARTED_REJECTION=a,exports.CACHED_ROUTE_NOT_FOUND_ERROR=r,exports.CACHED_ROUTE_NOT_FOUND_REJECTION=o,exports.CACHED_SAME_STATES_ERROR=i,exports.CACHED_SAME_STATES_REJECTION=s,exports.PRE_SUPPRESSED=u,exports.SUPPRESSED_ERROR_CODES=c,exports.isExpectedRejection=l;
|
|
2
2
|
//# sourceMappingURL=constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":["RouterError","errorCodes"],"sources":["../../../../src/namespaces/NavigationNamespace/constants.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/constants.ts\n\nimport { errorCodes } from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\n\nimport type { State } from \"../../types\";\n\n// =============================================================================\n// Cached Errors & Rejected Promises (Performance Optimization)\n// =============================================================================\n// Pre-create error instances and rejected promises for sync error paths\n// in navigate(). Eliminates per-call allocations:\n// - new RouterError() — object + stack trace capture (~500ns-2μs)\n// - Promise.reject() — promise allocation\n// - .catch(handler) — derived promise from suppression\n//\n// Trade-off: All error instances share the same stack trace (points here).\n// This is acceptable because:\n// 1. These errors indicate expected conditions, not internal bugs\n// 2. Error code and message are sufficient for debugging\n// 3. The
|
|
1
|
+
{"version":3,"file":"constants.js","names":["RouterError","errorCodes"],"sources":["../../../../src/namespaces/NavigationNamespace/constants.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/constants.ts\n\nimport { errorCodes } from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\n\nimport type { State } from \"../../types\";\n\n// =============================================================================\n// Cached Errors & Rejected Promises (Performance Optimization)\n// =============================================================================\n// Pre-create error instances and rejected promises for sync error paths\n// in navigate(). Eliminates per-call allocations:\n// - new RouterError() — object + stack trace capture (~500ns-2μs)\n// - Promise.reject() — promise allocation\n// - .catch(handler) — derived promise from suppression\n//\n// Trade-off: All error instances share the same stack trace (points here).\n// This is acceptable because:\n// 1. These errors indicate expected conditions, not internal bugs\n// 2. Error code and message are sufficient for debugging\n// 3. The producer skips .catch() suppression for these promises (zero alloc) —\n// see PRE_SUPPRESSED at the bottom of this file\n// =============================================================================\n\nexport const CACHED_NOT_STARTED_ERROR = new RouterError(\n errorCodes.ROUTER_NOT_STARTED,\n);\n\nexport const CACHED_ROUTE_NOT_FOUND_ERROR = new RouterError(\n errorCodes.ROUTE_NOT_FOUND,\n);\n\nexport const CACHED_SAME_STATES_ERROR = new RouterError(errorCodes.SAME_STATES);\n\n// Pre-suppressed rejected promises — .catch() at module load prevents\n// unhandled rejection warnings. `NavigationNamespace.#settle` skips additional\n// .catch() calls by recognising these three by IDENTITY (`PRE_SUPPRESSED`\n// below), so no derived promise is allocated. The retired `lastSyncRejected`\n// flag used to carry that signal to the facade instead.\nexport const CACHED_NOT_STARTED_REJECTION: Promise<State> = Promise.reject(\n CACHED_NOT_STARTED_ERROR,\n);\n\nexport const CACHED_ROUTE_NOT_FOUND_REJECTION: Promise<State> = Promise.reject(\n CACHED_ROUTE_NOT_FOUND_ERROR,\n);\n\nexport const CACHED_SAME_STATES_REJECTION: Promise<State> = Promise.reject(\n CACHED_SAME_STATES_ERROR,\n);\n\n// Suppress once at module load — prevents unhandled rejection events.\n// Subsequent .catch() / await by user code still works correctly:\n// a rejected promise stays rejected forever, each .catch() creates\n// its own derived promise and fires its handler.\nCACHED_NOT_STARTED_REJECTION.catch(() => {}); // NOSONAR -- intentional suppression, not a promise chain\nCACHED_ROUTE_NOT_FOUND_REJECTION.catch(() => {}); // NOSONAR\nCACHED_SAME_STATES_REJECTION.catch(() => {}); // NOSONAR\n\n// =============================================================================\n// Fire-and-forget suppression policy (#721) — shared, not per-caller\n// =============================================================================\n\n/**\n * Rejection codes that are EXPECTED, caller-owned outcomes, not internal bugs.\n * The fire-and-forget safety net stays silent for them and lets an awaiting\n * caller see the rejection. `CANNOT_ACTIVATE` / `CANNOT_DEACTIVATE` belong here:\n * a guard blocking (or a plugin's guard-blocked `back()`/`forward()`) is a\n * normal result, so a call without `await` must not emit a spurious \"Unexpected\n * navigation error\".\n *\n * Most of them are navigation outcomes, but not all — `ROUTER_ALREADY_STARTED`\n * is a LIFECYCLE precondition (#1605), and it is the same kind of thing:\n * `start()` called twice says \"already done\", exactly as `SAME_STATES` does for\n * `navigate()`. Silence is the symmetric answer; logging it would report a\n * caller's own no-op as an internal fault. It costs nothing on the navigation\n * side — `navigate()` cannot produce that code.\n *\n * Lives here rather than moving into the namespace with navigate-suppression,\n * because it is genuinely SHARED: `Router.start()` classifies its own failures\n * by the same policy (`#onSuppressedStartError`), and start commits through\n * `navigateToState`, so its rejections are navigation rejections. One owner, two\n * readers — duplicating the classifier is the copy this refactor exists to\n * remove.\n */\nexport const SUPPRESSED_ERROR_CODES: ReadonlySet<string> = new Set([\n errorCodes.SAME_STATES,\n errorCodes.TRANSITION_CANCELLED,\n errorCodes.ROUTER_NOT_STARTED,\n errorCodes.ROUTE_NOT_FOUND,\n errorCodes.CANNOT_ACTIVATE,\n errorCodes.CANNOT_DEACTIVATE,\n errorCodes.ROUTER_ALREADY_STARTED,\n]);\n\n/** Module-level, so classifying allocates nothing per navigate()/start(). */\nexport function isExpectedRejection(error: unknown): boolean {\n return error instanceof RouterError && SUPPRESSED_ERROR_CODES.has(error.code);\n}\n\n/**\n * The three cached rejections ABOVE, by identity.\n *\n * They already carry a `.catch()` from module load, so they can never raise an\n * `unhandledRejection` — a second `.catch()` on them prevents nothing and only\n * allocates a derived promise (measured: ~40 ns, which is ~12.5% of a\n * SAME_STATES `navigate()`). This set is what lets the producer skip that work\n * without a mutable cross-layer flag.\n *\n * Identity, not a flag, because the two fail in OPPOSITE directions: a missed\n * identity costs 40 ns and nothing else, while a flag left stale-true skips\n * suppression on a LATER navigation and leaks the rejection — #721 exactly. The\n * mechanism is therefore fail-safe by construction: anything not recognised here\n * gets suppressed.\n */\nexport const PRE_SUPPRESSED: ReadonlySet<unknown> = new Set([\n CACHED_NOT_STARTED_REJECTION,\n CACHED_ROUTE_NOT_FOUND_REJECTION,\n CACHED_SAME_STATES_REJECTION,\n]);\n"],"mappings":"wEAwBa,EAA2B,IAAIA,EAAAA,YAC1CC,EAAAA,WAAW,kBACb,EAEa,EAA+B,IAAID,EAAAA,YAC9CC,EAAAA,WAAW,eACb,EAEa,EAA2B,IAAID,EAAAA,YAAYC,EAAAA,WAAW,WAAW,EAOjE,EAA+C,QAAQ,OAClE,CACF,EAEa,EAAmD,QAAQ,OACtE,CACF,EAEa,EAA+C,QAAQ,OAClE,CACF,EAMA,EAA6B,UAAY,CAAC,CAAC,EAC3C,EAAiC,UAAY,CAAC,CAAC,EAC/C,EAA6B,UAAY,CAAC,CAAC,EA4B3C,MAAa,EAA8C,IAAI,IAAI,CACjEA,EAAAA,WAAW,YACXA,EAAAA,WAAW,qBACXA,EAAAA,WAAW,mBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,gBACXA,EAAAA,WAAW,kBACXA,EAAAA,WAAW,sBACb,CAAC,EAGD,SAAgB,EAAoB,EAAyB,CAC3D,OAAO,aAAiBD,EAAAA,aAAe,EAAuB,IAAI,EAAM,IAAI,CAC9E,CAiBA,MAAa,EAAuC,IAAI,IAAI,CAC1D,EACA,EACA,CACF,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../../constants.js"),t=require("../../../RouterError.js");function n(t,n,r,i){let a=n;a.code!==e.errorCodes.TRANSITION_CANCELLED&&a.code!==e.errorCodes.ROUTE_NOT_FOUND&&t.sendTransitionFail(r,i,a)}function r(n,r,a){if(n instanceof DOMException&&n.name===`AbortError`)throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(n instanceof t.RouterError&&n.code===e.errorCodes.TRANSITION_CANCELLED)throw n;i(n,r,a)}function i(e,n,r){throw e instanceof t.RouterError?(e.setCode(n),e):new t.RouterError(n,o(e,r))}const a=new Set([`code`,`segment`,`path`,`then`]);function o(e,t){let n={segment:t};if(e instanceof Error)return{...n,message:e.message,stack:e.stack,...`cause`in e&&e.cause!==void 0&&{cause:e.cause}};if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))a.has(n)||(t[n]=r);return{...n,...t}}return n}exports.handleGuardError=r,exports.rethrowAsRouterError=i,exports.routeTransitionError=n,exports.wrapSyncError=o;
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../RouterError.js");function n(t,n,r,i){let a=n;a.code!==e.errorCodes.TRANSITION_CANCELLED&&a.code!==e.errorCodes.ROUTE_NOT_FOUND&&t.sendTransitionFail(r,i,a)}function r(n,r,a){if(n instanceof DOMException&&n.name===`AbortError`)throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(n instanceof t.RouterError&&n.code===e.errorCodes.TRANSITION_CANCELLED)throw n;i(n,r,a)}function i(e,n,r){throw e instanceof t.RouterError?(e.setCode(n),e):new t.RouterError(n,o(e,r))}const a=new Set([`code`,`segment`,`path`,`then`]);function o(e,t){let n={segment:t};if(e instanceof Error)return{...n,message:e.message,stack:e.stack,...`cause`in e&&e.cause!==void 0&&{cause:e.cause}};if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))a.has(n)||(t[n]=r);return{...n,...t}}return n}async function s(e,n,i){let a;try{a=await e}catch(e){r(e,n,i);return}if(!a)throw new t.RouterError(n,{segment:i})}exports.handleGuardError=r,exports.resolveAsyncGuard=s,exports.rethrowAsRouterError=i,exports.routeTransitionError=n,exports.wrapSyncError=o;
|
|
2
2
|
//# sourceMappingURL=errorHandling.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errorHandling.js","names":["errorCodes","RouterError"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/errorHandling.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/transition/errorHandling.ts\n\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { State } from \"../../../types\";\nimport type { NavigationDependencies } from \"../types\";\n\nexport function routeTransitionError(\n deps: NavigationDependencies,\n error: unknown,\n toState: State,\n fromState: State | undefined,\n): void {\n const routerError = error as RouterError;\n\n if (\n routerError.code === errorCodes.TRANSITION_CANCELLED ||\n routerError.code === errorCodes.ROUTE_NOT_FOUND\n ) {\n return;\n }\n\n deps.sendTransitionFail(toState, fromState, routerError);\n}\n\nexport function handleGuardError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n // A guard can also signal a quiet cancel by throwing\n // RouterError(TRANSITION_CANCELLED) directly — the same intent as a thrown\n // AbortError. Preserve it as-is instead of letting rethrowAsRouterError\n // overwrite the code with CANNOT_ACTIVATE / CANNOT_DEACTIVATE: that code\n // drives the downstream suppression (routeTransitionError early-returns,\n // fire-and-forget stays silent), so re-coding would surface the intended\n // quiet cancel as a reported transition error (#933).\n if (\n error instanceof RouterError &&\n error.code === errorCodes.TRANSITION_CANCELLED\n ) {\n throw error;\n }\n\n rethrowAsRouterError(error, errorCode, segment);\n}\n\n/**\n * Error metadata structure for transition errors.\n * Contains information extracted from caught exceptions.\n */\nexport interface SyncErrorMetadata {\n [key: string]: unknown;\n message?: string;\n stack?: string | undefined;\n cause?: unknown;\n segment?: string;\n}\n\n/**\n * Re-throws a caught error as a RouterError with the given error code.\n * If the error is already a RouterError, sets the code directly.\n * Otherwise wraps it with wrapSyncError metadata.\n */\nexport function rethrowAsRouterError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof RouterError) {\n error.setCode(errorCode);\n\n throw error;\n }\n\n throw new RouterError(errorCode, wrapSyncError(error, segment));\n}\n\n// Own-enumerable keys that must never be copied from a thrown object onto the\n// RouterError metadata:\n// - `code` / `segment` / `path` are reserved — the RouterError constructor\n// throws a TypeError on them (#39).\n// - `then` would make the RouterError itself thenable, so a consumer that\n// awaits it (or passes it through Promise.resolve / returns it from an async\n// function) would have it assimilated as a Promise instead of treated as a\n// plain rejection reason (#947).\nconst reservedRouterErrorProps = new Set([\"code\", \"segment\", \"path\", \"then\"]);\n\n/**\n * Wraps a synchronously thrown value into structured error metadata.\n *\n * This helper extracts useful debugging information from various thrown values:\n * - Error instances: extracts message, stack, and cause (ES2022+)\n * - Plain objects: spreads properties into metadata\n * - Primitives (string, number, etc.): returns minimal metadata\n *\n * @param thrown - The value caught in a try-catch block\n * @param segment - Route segment name (for lifecycle hooks)\n * @returns Structured error metadata for RouterError\n */\nexport function wrapSyncError(\n thrown: unknown,\n segment: string,\n): SyncErrorMetadata {\n const base: SyncErrorMetadata = { segment };\n\n // Handle Error instances - extract all useful properties\n if (thrown instanceof Error) {\n return {\n ...base,\n message: thrown.message,\n stack: thrown.stack,\n // Error.cause requires ES2022+ - safely access if present\n ...(\"cause\" in thrown &&\n thrown.cause !== undefined && { cause: thrown.cause }),\n };\n }\n\n // Handle plain objects - spread properties into metadata, filtering reserved props\n if (thrown && typeof thrown === \"object\") {\n const filtered: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(thrown)) {\n // Skip reserved / hazardous keys: #39 (constructor TypeError on code/\n // segment/path) and #947 (`then` would make the error thenable).\n if (!reservedRouterErrorProps.has(key)) {\n filtered[key] = value;\n }\n }\n\n return { ...base, ...filtered };\n }\n\n // Primitives (string, number, boolean, null, undefined, symbol, bigint)\n // Return base metadata only - the primitive value isn't useful as metadata\n return base;\n}\n"],"mappings":"8EAQA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAc,EAGlB,EAAY,OAASA,EAAAA,WAAW,sBAChC,EAAY,OAASA,EAAAA,WAAW,iBAKlC,EAAK,mBAAmB,EAAS,EAAW,CAAW,CACzD,CAEA,SAAgB,EACd,EACA,EACA,EACO,CACP,GAAI,aAAiB,cAAgB,EAAM,OAAS,aAClD,MAAM,IAAIC,EAAAA,YAAYD,EAAAA,WAAW,oBAAoB,EAUvD,GACE,aAAiBC,EAAAA,aACjB,EAAM,OAASD,EAAAA,WAAW,qBAE1B,MAAM,EAGR,EAAqB,EAAO,EAAW,CAAO,CAChD,CAmBA,SAAgB,EACd,EACA,EACA,EACO,CAOP,MANI,aAAiBC,EAAAA,aACnB,EAAM,QAAQ,CAAS,EAEjB,GAGF,IAAIA,EAAAA,YAAY,EAAW,EAAc,EAAO,CAAO,CAAC,CAChE,CAUA,MAAM,EAA2B,IAAI,IAAI,CAAC,OAAQ,UAAW,OAAQ,MAAM,CAAC,EAc5E,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAA0B,CAAE,SAAQ,EAG1C,GAAI,aAAkB,MACpB,MAAO,CACL,GAAG,EACH,QAAS,EAAO,QAChB,MAAO,EAAO,MAEd,GAAI,UAAW,GACb,EAAO,QAAU,IAAA,IAAa,CAAE,MAAO,EAAO,KAAM,CACxD,EAIF,GAAI,GAAU,OAAO,GAAW,SAAU,CACxC,IAAM,EAAoC,CAAC,EAE3C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAGzC,EAAyB,IAAI,CAAG,IACnC,EAAS,GAAO,GAIpB,MAAO,CAAE,GAAG,EAAM,GAAG,CAAS,CAChC,CAIA,OAAO,CACT"}
|
|
1
|
+
{"version":3,"file":"errorHandling.js","names":["errorCodes","RouterError"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/errorHandling.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/transition/errorHandling.ts\n\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { State } from \"../../../types\";\nimport type { NavigationDependencies } from \"../types\";\n\nexport function routeTransitionError(\n deps: NavigationDependencies,\n error: unknown,\n toState: State,\n fromState: State | undefined,\n): void {\n const routerError = error as RouterError;\n\n if (\n routerError.code === errorCodes.TRANSITION_CANCELLED ||\n routerError.code === errorCodes.ROUTE_NOT_FOUND\n ) {\n return;\n }\n\n deps.sendTransitionFail(toState, fromState, routerError);\n}\n\nexport function handleGuardError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n // A guard can also signal a quiet cancel by throwing\n // RouterError(TRANSITION_CANCELLED) directly — the same intent as a thrown\n // AbortError. Preserve it as-is instead of letting rethrowAsRouterError\n // overwrite the code with CANNOT_ACTIVATE / CANNOT_DEACTIVATE: that code\n // drives the downstream suppression (routeTransitionError early-returns,\n // fire-and-forget stays silent), so re-coding would surface the intended\n // quiet cancel as a reported transition error (#933).\n if (\n error instanceof RouterError &&\n error.code === errorCodes.TRANSITION_CANCELLED\n ) {\n throw error;\n }\n\n rethrowAsRouterError(error, errorCode, segment);\n}\n\n/**\n * Error metadata structure for transition errors.\n * Contains information extracted from caught exceptions.\n */\nexport interface SyncErrorMetadata {\n [key: string]: unknown;\n message?: string;\n stack?: string | undefined;\n cause?: unknown;\n segment?: string;\n}\n\n/**\n * Re-throws a caught error as a RouterError with the given error code.\n * If the error is already a RouterError, sets the code directly.\n * Otherwise wraps it with wrapSyncError metadata.\n */\nexport function rethrowAsRouterError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof RouterError) {\n error.setCode(errorCode);\n\n throw error;\n }\n\n throw new RouterError(errorCode, wrapSyncError(error, segment));\n}\n\n// Own-enumerable keys that must never be copied from a thrown object onto the\n// RouterError metadata:\n// - `code` / `segment` / `path` are reserved — the RouterError constructor\n// throws a TypeError on them (#39).\n// - `then` would make the RouterError itself thenable, so a consumer that\n// awaits it (or passes it through Promise.resolve / returns it from an async\n// function) would have it assimilated as a Promise instead of treated as a\n// plain rejection reason (#947).\nconst reservedRouterErrorProps = new Set([\"code\", \"segment\", \"path\", \"then\"]);\n\n/**\n * Wraps a synchronously thrown value into structured error metadata.\n *\n * This helper extracts useful debugging information from various thrown values:\n * - Error instances: extracts message, stack, and cause (ES2022+)\n * - Plain objects: spreads properties into metadata\n * - Primitives (string, number, etc.): returns minimal metadata\n *\n * @param thrown - The value caught in a try-catch block\n * @param segment - Route segment name (for lifecycle hooks)\n * @returns Structured error metadata for RouterError\n */\nexport function wrapSyncError(\n thrown: unknown,\n segment: string,\n): SyncErrorMetadata {\n const base: SyncErrorMetadata = { segment };\n\n // Handle Error instances - extract all useful properties\n if (thrown instanceof Error) {\n return {\n ...base,\n message: thrown.message,\n stack: thrown.stack,\n // Error.cause requires ES2022+ - safely access if present\n ...(\"cause\" in thrown &&\n thrown.cause !== undefined && { cause: thrown.cause }),\n };\n }\n\n // Handle plain objects - spread properties into metadata, filtering reserved props\n if (thrown && typeof thrown === \"object\") {\n const filtered: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(thrown)) {\n // Skip reserved / hazardous keys: #39 (constructor TypeError on code/\n // segment/path) and #947 (`then` would make the error thenable).\n if (!reservedRouterErrorProps.has(key)) {\n filtered[key] = value;\n }\n }\n\n return { ...base, ...filtered };\n }\n\n // Primitives (string, number, boolean, null, undefined, symbol, bigint)\n // Return base metadata only - the primitive value isn't useful as metadata\n return base;\n}\n\n/**\n * Settle a guard's Promise into the pipeline's terms: `false` and a rejection\n * both become the phase's `RouterError`, nothing else escapes.\n *\n * Lives here rather than with the interpreter because that IS this module's\n * concern — turning a guard's refusal into the right error (#1607). The\n * interpreter only decides WHERE it stopped.\n */\nexport async function resolveAsyncGuard(\n promise: Promise<boolean>,\n errorCode: string,\n segment: string,\n): Promise<void> {\n let result: boolean;\n\n try {\n result = await promise;\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n\n return; // unreachable — handleGuardError returns never\n }\n\n if (!result) {\n throw new RouterError(errorCode, { segment });\n }\n}\n"],"mappings":"8EAQA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAc,EAGlB,EAAY,OAASA,EAAAA,WAAW,sBAChC,EAAY,OAASA,EAAAA,WAAW,iBAKlC,EAAK,mBAAmB,EAAS,EAAW,CAAW,CACzD,CAEA,SAAgB,EACd,EACA,EACA,EACO,CACP,GAAI,aAAiB,cAAgB,EAAM,OAAS,aAClD,MAAM,IAAIC,EAAAA,YAAYD,EAAAA,WAAW,oBAAoB,EAUvD,GACE,aAAiBC,EAAAA,aACjB,EAAM,OAASD,EAAAA,WAAW,qBAE1B,MAAM,EAGR,EAAqB,EAAO,EAAW,CAAO,CAChD,CAmBA,SAAgB,EACd,EACA,EACA,EACO,CAOP,MANI,aAAiBC,EAAAA,aACnB,EAAM,QAAQ,CAAS,EAEjB,GAGF,IAAIA,EAAAA,YAAY,EAAW,EAAc,EAAO,CAAO,CAAC,CAChE,CAUA,MAAM,EAA2B,IAAI,IAAI,CAAC,OAAQ,UAAW,OAAQ,MAAM,CAAC,EAc5E,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAA0B,CAAE,SAAQ,EAG1C,GAAI,aAAkB,MACpB,MAAO,CACL,GAAG,EACH,QAAS,EAAO,QAChB,MAAO,EAAO,MAEd,GAAI,UAAW,GACb,EAAO,QAAU,IAAA,IAAa,CAAE,MAAO,EAAO,KAAM,CACxD,EAIF,GAAI,GAAU,OAAO,GAAW,SAAU,CACxC,IAAM,EAAoC,CAAC,EAE3C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAGzC,EAAyB,IAAI,CAAG,IACnC,EAAS,GAAO,GAIpB,MAAO,CAAE,GAAG,EAAM,GAAG,CAAS,CAChC,CAIA,OAAO,CACT,CAUA,eAAsB,EACpB,EACA,EACA,EACe,CACf,IAAI,EAEJ,GAAI,CACF,EAAS,MAAM,CACjB,OAAS,EAAgB,CACvB,EAAiB,EAAO,EAAW,CAAO,EAE1C,MACF,CAEA,GAAI,CAAC,EACH,MAAM,IAAIA,EAAAA,YAAY,EAAW,CAAE,SAAQ,CAAC,CAEhD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../transitionPath.js"),n=require("../../../RouterError.js"),r=require("../constants.js"),i=require("./completeTransition.js"),a=require("./errorHandling.js"),o=require("./guardPhase.js"),s=Object.freeze([]),c=new Map;function l(t,n){return n?.name===e.constants.UNKNOWN_ROUTE&&!t.replace?{...t,replace:!0}:t}function u(e,t,n){return!!e&&!t.reload&&!t.force&&e.path===n.path}function d(e,t){if(e.size===0)return!1;for(let n of t)if(e.has(n))return!0;return!1}function f(e,t,n,r,i){y(e,i.signal);let a={toState:n,fromState:r,opts:i,myId:t.begin(),suspendable:i.signal!==void 0||e.hasLeaveListeners()||e.hasPreCommitListeners(),toDeactivate:s,toActivate:s,intersection:``,canDeactivateFunctions:c,canActivateFunctions:c,shouldDeactivate:!1,shouldActivate:!1,hasGuards:!1};return e.startTransition(n,r),a}function p(e,t){return e.sendLeaveApprove(t.toState,t.fromState),i.completeTransition(e,t)}function m(n,r){let[i,a]=n.getLifecycleFunctions(),{toDeactivate:o,toActivate:s,intersection:c}=t.getTransitionPath(r.toState,r.fromState,e=>n.getMetaForState(e));r.canDeactivateFunctions=i,r.canActivateFunctions=a,r.toDeactivate=o,r.toActivate=s,r.intersection=c,r.shouldDeactivate=!!r.fromState&&!r.opts.forceDeactivate&&o.length>0,r.shouldActivate=r.toState.name!==e.constants.UNKNOWN_ROUTE&&s.length>0,r.hasGuards=r.shouldDeactivate&&d(i,o)||r.shouldActivate&&d(a,s)}function h(t,a,s,c){let d,h=!1,y=null;try{if(d=t.getState(),c=l(c,d),u(d,c,s))return t.emitTransitionError(s,d,r.CACHED_SAME_STATES_ERROR),r.CACHED_SAME_STATES_REJECTION;let _=f(t,a,s,d,c);if(h=!0,m(t,_),!_.hasGuards&&!_.suspendable)return p(t,_);let{myId:b,suspendable:x,canDeactivateFunctions:S,canActivateFunctions:C,toDeactivate:w,toActivate:T,shouldDeactivate:E,shouldActivate:D,hasGuards:O}=_,k=s;if(!O){let e=v(t,a,_);if(e!==void 0)return e}if(O){y=new AbortController,a.adopt(y);let r=()=>a.isCurrent(b)&&t.isActive(),i=y.signal,c=o.executeGuardPipeline(S,C,w,T,E,D,s,d,i,r,()=>{if(t.sendLeaveApprove(k,d),t.hasLeaveListeners())return t.awaitLeaveListeners(k,d,i)});if(c!==void 0)return g(t,a,c,_,y,b);if(!r())throw new n.RouterError(e.errorCodes.TRANSITION_CANCELLED);a.release(y,!1)}if(x&&(!t.isActive()||c.signal?.aborted===!0))throw new n.RouterError(e.errorCodes.TRANSITION_CANCELLED);return i.completeTransition(t,_)}catch(e){return _(t,a,e,y,h,s,d),Promise.reject(e)}}async function g(t,r,o,s,c,l){let u=()=>r.isCurrent(l)&&!c.signal.aborted&&t.isActive(),d=s.opts.signal,f,p,m=!1,h,g=new Promise(e=>{if(c.signal.aborted){e();return}p=()=>{e()},c.signal.addEventListener(`abort`,p,{once:!0})});o.catch(()=>{});try{if(d){if(d.aborted)throw new n.RouterError(e.errorCodes.TRANSITION_CANCELLED,{reason:d.reason});f=()=>{t.cancelNavigation(d.reason)},d.addEventListener(`abort`,f,{once:!0})}if(await Promise.race([o,g]),!u())throw new n.RouterError(e.errorCodes.TRANSITION_CANCELLED);let r=i.completeTransition(t,s);return m=!0,r}catch(e){throw h=e,a.routeTransitionError(t,e,s.toState,s.fromState),e}finally{f&&d?.removeEventListener(`abort`,f),p&&c.signal.removeEventListener(`abort`,p),r.release(c,!m,h)}}function _(e,t,n,r,i,o,s){r&&t.release(r,!0,n),i&&o&&a.routeTransitionError(e,n,o,s)}function v(e,t,n){let{toState:r,fromState:i,myId:a}=n;if(e.sendLeaveApprove(r,i),e.hasLeaveListeners()){let o=new AbortController;t.adopt(o);let s;try{s=e.awaitLeaveListeners(r,i,o.signal)}catch(e){throw t.release(o,!0,e),e}if(s!==void 0)return g(e,t,s,n,o,a);t.release(o,!1);return}}function y(t,r){if(t.isTransitioning()&&(t.logger.warn(`router.navigate`,`Concurrent navigation detected on shared router instance. For SSR, use cloneRouter() to create isolated instance per request.`),t.cancelNavigation()),r?.aborted)throw new n.RouterError(e.errorCodes.TRANSITION_CANCELLED,{reason:r.reason})}exports.abortPreviousNavigation=y,exports.executeNavigation=h;
|
|
2
|
+
//# sourceMappingURL=executeNavigation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"executeNavigation.js","names":["constants","completeTransition","getTransitionPath","CACHED_SAME_STATES_ERROR","CACHED_SAME_STATES_REJECTION","executeGuardPipeline","RouterError","errorCodes"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/executeNavigation.ts"],"sourcesContent":["import { completeTransition } from \"./completeTransition\";\nimport { routeTransitionError } from \"./errorHandling\";\nimport { executeGuardPipeline } from \"./guardPhase\";\nimport { errorCodes, constants } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\nimport { getTransitionPath } from \"../../../transitionPath\";\nimport {\n CACHED_SAME_STATES_ERROR,\n CACHED_SAME_STATES_REJECTION,\n} from \"../constants\";\n\nimport type { GuardFn, NavigationOptions, State } from \"../../../types\";\nimport type { InFlightNavigation } from \"../InFlightNavigation\";\nimport type {\n NavigationContext,\n NavigationDependencies,\n NavigationPlan,\n} from \"../types\";\n\n/**\n * The orchestration of one navigation, end to end.\n *\n * These were methods on `NavigationNamespace` until the per-navigation state\n * they shared was named (#1607). With the controller and the supersession token\n * owned by {@link InFlightNavigation}, nothing here needs `this`: every function\n * is over `(deps, inFlight, plan)`, and the namespace above is left with what it\n * actually is — the entry points, their fire-and-forget checkpoint, and the DI\n * bag.\n *\n * Parameter lists stay flat rather than growing a context object: the plan IS\n * the per-navigation bag already (`NavigationPlan` extends `NavigationContext`),\n * and a second one would be an allocation on the #307 hot path — the same reason\n * `guardPhase.ts` carries its own flat signatures.\n */\n\n// Write-once placeholders for `NavigationPlan`'s pass-2 fields. Module-level so\n// building a plan allocates nothing beyond the plan itself; never mutated —\n// `planPhases` overwrites the SLOTS, it does not write through them.\nconst NO_SEGMENTS: string[] = Object.freeze([]) as unknown as string[];\nconst NO_GUARDS = new Map<string, GuardFn>();\n\nfunction forceReplaceFromUnknown(\n opts: NavigationOptions,\n fromState: State | undefined,\n): NavigationOptions {\n return fromState?.name === constants.UNKNOWN_ROUTE && !opts.replace\n ? { ...opts, replace: true }\n : opts;\n}\n\nfunction isSameNavigation(\n fromState: State | undefined,\n opts: NavigationOptions,\n toState: State,\n): boolean {\n return (\n !!fromState &&\n !opts.reload &&\n !opts.force &&\n fromState.path === toState.path\n );\n}\n\n/**\n * Does any segment this phase walks carry a guard?\n *\n * The empty-Map check first, so a router with no guards at all pays one load —\n * and a router that HAS guards pays one `Map.has` per segment on the path,\n * against the ~40 ns + 482 B an AbortController costs when the answer is no.\n */\nfunction hasGuardOnPath(\n guards: Map<string, GuardFn>,\n segments: string[],\n): boolean {\n if (guards.size === 0) {\n return false;\n }\n\n for (const segment of segments) {\n if (guards.has(segment)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Pass 1 of the shared prologue: reserve the navigation, then announce it.\n *\n * Ends with `startTransition` DELIBERATELY, and nothing follows it here. That\n * makes \"this threw\" strictly equivalent to \"TRANSITION_START never fired\", so\n * the caller can set its `transitionStarted` marker immediately after the call\n * and stay exactly as accurate as the inline version was.\n *\n * The three statements before it are ordered, not incidental:\n * `#abortPreviousNavigation` may run FSM `CANCEL` (whose listeners can add or\n * drop subscriptions), so `suspendable` has to be read after it — and before\n * `startTransition`, whose listeners a `stop()` would use to empty those same\n * lists (#1169, the QB/QE hole).\n */\nfunction beginTransition(\n deps: NavigationDependencies,\n inFlight: InFlightNavigation,\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n): NavigationPlan {\n abortPreviousNavigation(deps, opts.signal);\n\n const myId = inFlight.begin();\n\n // `suspendable` is true only when a synchronous supersede is reachable — an\n // external `opts.signal`, `subscribeLeave` listeners, or a pre-commit plugin\n // listener (`onTransitionStart` / `onTransitionLeaveApprove`); the pure\n // synchronous navigate (none of these) is uncancellable and skips the\n // commit-gate, keeping the #307 hot path perf-neutral.\n const plan: NavigationPlan = {\n toState,\n fromState,\n opts,\n myId,\n suspendable:\n opts.signal !== undefined ||\n deps.hasLeaveListeners() ||\n deps.hasPreCommitListeners(),\n // Write-once placeholders — pass 2 fills them (see `NavigationPlan`).\n toDeactivate: NO_SEGMENTS,\n toActivate: NO_SEGMENTS,\n intersection: \"\",\n canDeactivateFunctions: NO_GUARDS,\n canActivateFunctions: NO_GUARDS,\n shouldDeactivate: false,\n shouldActivate: false,\n hasGuards: false,\n };\n\n deps.startTransition(toState, fromState);\n\n return plan;\n}\n\n/**\n * The uninterruptible navigation, end to end (RFC §5.1, разрез А).\n *\n * Reached only when `!hasGuards && !suspendable` — no guards to run, no\n * `subscribeLeave` listener, no caller `signal`, no pre-commit plugin\n * listener. Nothing can cancel it and nothing in it can suspend, so the\n * cancellation machinery is not *skipped* here: it is ABSENT. No\n * `AbortController`, no `isCurrentNav` closure, no commit-gate, and the return\n * type is a plain `State` rather than a Promise — being unable to suspend is a\n * property of the code, not a fact one has to remember.\n *\n * The `LEAVE_APPROVE` emit stays: it is an FSM transition every navigation\n * makes, and with no leave listeners there is nothing to await behind it.\n */\nfunction completeImmediate(\n deps: NavigationDependencies,\n plan: NavigationPlan,\n): State {\n deps.sendLeaveApprove(plan.toState, plan.fromState);\n\n return completeTransition(deps, plan);\n}\n\n/**\n * Pass 2: work out the shape of the transition, now that it is announced.\n *\n * Runs AFTER `startTransition` because a `TRANSITION_START` listener may still\n * register a guard, and the guard maps must reflect that.\n */\nfunction planPhases(deps: NavigationDependencies, plan: NavigationPlan): void {\n const [canDeactivateFunctions, canActivateFunctions] =\n deps.getLifecycleFunctions();\n\n const { toDeactivate, toActivate, intersection } = getTransitionPath(\n plan.toState,\n plan.fromState,\n (name) => deps.getMetaForState(name),\n );\n\n plan.canDeactivateFunctions = canDeactivateFunctions;\n plan.canActivateFunctions = canActivateFunctions;\n plan.toDeactivate = toDeactivate;\n plan.toActivate = toActivate;\n plan.intersection = intersection;\n plan.shouldDeactivate =\n !!plan.fromState && !plan.opts.forceDeactivate && toDeactivate.length > 0;\n plan.shouldActivate =\n plan.toState.name !== constants.UNKNOWN_ROUTE && toActivate.length > 0;\n // The guards of THIS transition, not of the router. Asking the Maps for\n // their size answered a different question — \"does the app have a guard\n // anywhere\" — so one `canActivate` on an admin page armed the cancellation\n // machinery for every public navigation: an AbortController, the liveness\n // closure, and a walk that found no guard on any of its steps (measured:\n // +643 B and +84 ns per navigation that never touches the guarded route).\n //\n // The predicate mirrors what the interpreter would actually do — a phase\n // whose short-circuit is false runs no step, so its guards cannot fire —\n // which is what keeps this a fast-path gate and not a second policy.\n plan.hasGuards =\n (plan.shouldDeactivate &&\n hasGuardOnPath(canDeactivateFunctions, toDeactivate)) ||\n (plan.shouldActivate && hasGuardOnPath(canActivateFunctions, toActivate));\n}\n\nexport function executeNavigation(\n deps: NavigationDependencies,\n inFlight: InFlightNavigation,\n toState: State,\n opts: NavigationOptions,\n): State | Promise<State> {\n let fromState: State | undefined;\n let transitionStarted = false;\n let controller: AbortController | null = null;\n\n try {\n fromState = deps.getState();\n opts = forceReplaceFromUnknown(opts, fromState);\n\n if (isSameNavigation(fromState, opts, toState)) {\n deps.emitTransitionError(toState, fromState, CACHED_SAME_STATES_ERROR);\n\n return CACHED_SAME_STATES_REJECTION;\n }\n\n const plan = beginTransition(deps, inFlight, toState, fromState, opts);\n\n transitionStarted = true;\n\n // Post-`startTransition` supersession is now caught at the commit-gate\n // below (before `completeTransition`'s setState): a `stop()`/`dispose()`/\n // external-abort from the TRANSITION_START listener leaves the FSM in\n // IDLE/DISPOSED, which `!deps.isActive()` detects. (Async supersession is\n // additionally caught in `#finishAsyncNavigation` / the guard pipeline's\n // `isCurrentNav`; a reentrant navigate() is banned — REENTRANT_NAVIGATION.)\n\n planPhases(deps, plan);\n\n // Разрез А (RFC §5.1). `immediate` is the RFC's four-term predicate\n // written in the terms that already exist: `suspendable` IS\n // `signal || leaveListeners || preCommitListeners`, so the whole thing is\n // `!hasGuards && !suspendable`. Nothing can interrupt such a navigation and\n // nothing in it can suspend, so the machinery for both is not skipped —\n // `#completeImmediate` does not contain it.\n //\n // Decided HERE and not at the entry point, deliberately: `hasGuards` is\n // only knowable after `startTransition`, because a `TRANSITION_START`\n // listener may still register a guard. Hoisting the read would change\n // behaviour, not just shape.\n if (!plan.hasGuards && !plan.suspendable) {\n return completeImmediate(deps, plan);\n }\n\n const {\n myId,\n suspendable,\n canDeactivateFunctions,\n canActivateFunctions,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n hasGuards,\n } = plan;\n\n const confirmedToState = toState;\n\n if (!hasGuards) {\n const asyncLeave = handleNoGuardsLeave(deps, inFlight, plan);\n\n if (asyncLeave !== undefined) {\n return asyncLeave;\n }\n }\n\n // NOT equivalent, and the `Stryker disable: equivalent` that used to sit\n // here was wrong: with `if (true)` the guard branch runs AFTER\n // `#handleNoGuardsLeave` already emitted LEAVE_APPROVE, so\n // `emitLeaveApproveCallback` dispatches every `subscribeLeave` listener a\n // SECOND time (measured: 2 calls, 1 expected). The whole suite stayed\n // green because the shared `createTestRouter` fixture carries definition\n // guards, so no test ever reached this branch with `hasGuards` false —\n // `guard-phase-emit-leave-approve.test.ts` now builds a guard-free router\n // and kills both mutants.\n // eslint-disable-next-line unicorn/prefer-else-if -- two exhaustive `if`s read clearer here than an else-if; merging cascades into no-negated-condition / no-unnecessary-condition in this hot guard-setup branch\n if (hasGuards) {\n controller = new AbortController();\n inFlight.adopt(controller);\n const isCurrentNav = () => inFlight.isCurrent(myId) && deps.isActive();\n\n const signal = controller.signal;\n\n const emitLeaveApproveCallback = (): Promise<void> | undefined => {\n deps.sendLeaveApprove(confirmedToState, fromState);\n\n if (deps.hasLeaveListeners()) {\n return deps.awaitLeaveListeners(confirmedToState, fromState, signal);\n }\n\n return undefined;\n };\n\n const guardCompletion = executeGuardPipeline(\n canDeactivateFunctions,\n canActivateFunctions,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isCurrentNav,\n emitLeaveApproveCallback,\n );\n\n if (guardCompletion !== undefined) {\n // The plan IS the `NavigationContext` (a superset of it), so the\n // second literal this used to build is gone — one bag per navigation.\n return finishAsyncNavigation(\n deps,\n inFlight,\n guardCompletion,\n plan,\n controller,\n myId,\n );\n }\n\n if (!isCurrentNav()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n inFlight.release(controller, false);\n }\n\n // #1169 commit-gate — refuse to commit a navigation cancelled or\n // terminated during a listener window, BEFORE `completeTransition`'s\n // setState. The FSM table (D-full) already prevents the forceState\n // resurrection; this prevents the state commit that precedes the emit.\n // Gated on `suspendable` so the pure sync hot path pays nothing. A\n // `stop()`/`dispose()` from the listener lands the FSM in IDLE/DISPOSED\n // (caught by `!isActive()`); an external `opts.signal` abort is caught\n // directly. No supersession check: a reentrant navigate() (the only thing\n // that could bump the token synchronously) is banned\n // (REENTRANT_NAVIGATION, §4), so on this sync path the token still holds — async\n // supersede is caught in `#finishAsyncNavigation`'s `isCurrentNav`.\n if (suspendable && (!deps.isActive() || opts.signal?.aborted === true)) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const finalState = completeTransition(deps, plan);\n\n // A bare `State`, not `Promise.resolve(state)` — the RETURN TYPE is what\n // announces \"this navigation already settled, synchronously\", which used\n // to be `lastSyncResolved`'s job. The ordering hazard the flag carried is\n // gone with it: there is no window in which a value says \"resolved\" while\n // `completeTransition` may still throw, because the value only exists once\n // it returned. The Promise wrap moves up to the facade, which owes callers\n // `Promise<State>`; the allocation is the same one, one frame higher.\n return finalState;\n } catch (error) {\n handleNavigateError(\n deps,\n inFlight,\n error,\n controller,\n transitionStarted,\n toState,\n fromState,\n );\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from guards or transition pipeline\n return Promise.reject(error);\n }\n}\n\nasync function finishAsyncNavigation(\n deps: NavigationDependencies,\n inFlight: InFlightNavigation,\n guardCompletion: Promise<void>,\n nav: NavigationContext,\n controller: AbortController,\n myId: number,\n): Promise<State> {\n const isActive = () =>\n inFlight.isCurrent(myId) && !controller.signal.aborted && deps.isActive();\n\n const externalSignal = nav.opts.signal;\n let onExternalAbort: (() => void) | undefined;\n let onInternalAbort: (() => void) | undefined;\n let succeeded = false;\n let failureReason: unknown;\n\n // #1018: race the guard completion against the controller's abort so a\n // non-cooperative guard whose Promise never settles (and ignores `signal`)\n // cannot wedge navigate() forever. `abortRace` RESOLVES on abort, so the\n // post-race `isActive()` check below throws TRANSITION_CANCELLED — the same\n // path that already handles a guard which swallows the abort and resolves\n // `true`. `stop()`/`dispose()`/supersede all abort the controller. Mirrors\n // the leave-path protection `settleLeavePromises` (#663/#673).\n const abortRace = new Promise<void>((resolve) => {\n if (controller.signal.aborted) {\n resolve();\n\n return;\n }\n\n onInternalAbort = () => {\n resolve();\n };\n\n controller.signal.addEventListener(\"abort\", onInternalAbort, {\n once: true,\n });\n });\n\n // Consume `guardCompletion` when the abort wins the race: a slow or\n // never-settling guard that settles later then has no awaiter, which would\n // surface as an unhandled rejection without this catch.\n guardCompletion.catch(() => {\n /* settlement consumed — the race already decided the navigation */\n });\n\n try {\n if (externalSignal) {\n if (externalSignal.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: externalSignal.reason,\n });\n }\n\n // Bridge an external `{ signal }` abort onto the internal controller.\n // It is NOT scoped to `controller.signal` (the old `{ signal }` option)\n // because success no longer aborts the controller (#722) — the listener\n // is detached explicitly in `finally` instead.\n onExternalAbort = () => {\n // (#1030): route the external abort through the FSM. The\n // `CANCEL` action aborts the internal controller (waking THIS pipeline)\n // with the external `reason` (#943 — surfaces via the leave signal) AND\n // returns the FSM to READY, atomically. No direct `controller.abort`\n // here — \"FSM CANCEL ⟹ controller aborted\" lives in one place\n // (handleCancel). onExternalAbort only fires while the navigation is in\n // flight (the listener is removed in `finally` once it settles), so the\n // FSM is always cancellable here.\n deps.cancelNavigation(externalSignal.reason);\n };\n // Stryker disable next-line ObjectLiteral: equivalent — `{ once: true }` is redundant: the per-navigation signal aborts at most once and is discarded unaborted on success, and the `finally` block explicitly removeEventListener's it.\n externalSignal.addEventListener(\"abort\", onExternalAbort, {\n // Stryker disable next-line BooleanLiteral: equivalent — `once` redundant (see ObjectLiteral above); the listener is explicitly removed in `finally`.\n once: true,\n });\n }\n\n await Promise.race([guardCompletion, abortRace]);\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const state = completeTransition(deps, nav);\n\n succeeded = true;\n\n return state;\n } catch (error) {\n failureReason = error;\n\n routeTransitionError(deps, error, nav.toState, nav.fromState);\n\n throw error;\n // NB: the `} finally {}` BlockStatement mutant SURVIVES but is EQUIVALENT —\n // emptying the finally only skips the controller release, which is unobservable\n // (defense-in-depth: on a CANCEL the FSM CANCEL action already aborted+nulled\n // the controller via abortCurrentController, RFC §5; the success-path\n // ref-release is proven unobservable — see InFlightNavigation.release's disable). It\n // cannot be inline-`Stryker disable`d: the catch `}` and finally `{` share one\n // line, so there is no comment position that targets the finally body. Left documented.\n } finally {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — listener cleanup is redundant: the per-navigation signal is discarded on completion, so skipping the removeEventListener leaks nothing observable.\n if (onExternalAbort) {\n // Stryker disable next-line StringLiteral: equivalent — cleanup event name is redundant (listener is `{ once: true }` and the signal is discarded), so a wrong name removes nothing observable.\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n\n // Detach the abort-race listener before the release below aborts the\n // controller below, so the cleanup abort cannot re-fire it. `undefined`\n // only when the controller was already aborted at setup (the early-resolve\n // branch above registered no listener).\n if (onInternalAbort) {\n controller.signal.removeEventListener(\"abort\", onInternalAbort);\n }\n\n // Success drops the controller without aborting (the subscribeLeave signal\n // must stay unaborted); cancel/error aborts it with the originating reason\n // so captured signals expose the real cause via `signal.reason` (#943).\n inFlight.release(controller, !succeeded, failureReason);\n }\n}\n\nfunction handleNavigateError(\n deps: NavigationDependencies,\n inFlight: InFlightNavigation,\n error: unknown,\n controller: AbortController | null,\n transitionStarted: boolean,\n toState: State | undefined,\n fromState: State | undefined,\n): void {\n if (controller) {\n inFlight.release(controller, true, error);\n }\n\n if (transitionStarted && toState) {\n routeTransitionError(deps, error, toState, fromState);\n }\n}\n\n/**\n * The leave phase for a navigation with no guards, but with something that\n * can suspend it. Takes the `plan` whole rather than six projections of it:\n * every argument it used to receive was a field of that same bag, and the bag\n * IS a `NavigationContext`, so handing it straight to `#finishAsyncNavigation`\n * keeps this arc at ONE context object per navigation — the allocation\n * neutrality the extracted prologue was supposed to buy everywhere, not only\n * on the guard path.\n */\nfunction handleNoGuardsLeave(\n deps: NavigationDependencies,\n inFlight: InFlightNavigation,\n plan: NavigationPlan,\n): Promise<State> | undefined {\n const { toState, fromState, myId } = plan;\n\n deps.sendLeaveApprove(toState, fromState);\n\n if (deps.hasLeaveListeners()) {\n const controller = new AbortController();\n\n // Adopted BEFORE listeners run so a reentrant navigate() / stop() /\n // dispose() from a sync listener aborts THIS leave signal — parity with\n // the guard path (#722).\n inFlight.adopt(controller);\n\n let leaveResult: Promise<void> | undefined;\n\n // This catches the SYNCHRONOUS throw only — a leave listener that throws\n // inline, before any Promise exists (three tests in\n // `leave-signal-cancellation.test.ts` fail without it: the sync-throw\n // rejection, its `signal.reason` (#943), and the reentrant-navigate abort).\n // A rejection of the RETURNED Promise is deliberately not caught here: it is\n // awaited in `finishAsyncNavigation`, which routes it through\n // `routeTransitionError` with the controller released as cancelled. Sonar's\n // S4822 flags the shape (a promise-returning call inside `try`) and cannot\n // see that split.\n try {\n // NOSONAR -- S4822: the try is for the sync listener throw, never for the Promise\n leaveResult = deps.awaitLeaveListeners(\n toState,\n fromState,\n controller.signal,\n );\n } catch (error) {\n // A sync listener threw — the navigation fails; abort the leave signal\n // with the thrown value so a listener that captured the signal sees the\n // real cause via `signal.reason`, not a generic AbortError (#943).\n inFlight.release(controller, true, error);\n\n throw error;\n }\n\n if (leaveResult !== undefined) {\n return finishAsyncNavigation(\n deps,\n inFlight,\n leaveResult,\n plan,\n controller,\n myId,\n );\n }\n\n // Sync listeners settled. A synchronous reentrant navigate() can no longer\n // supersede here (banned, RFC §4), so the leave always succeeds: release the\n // controller WITHOUT aborting (the subscribeLeave signal must stay live).\n inFlight.release(controller, false);\n\n return undefined;\n }\n\n // No leave listeners: nothing synchronous could have superseded this\n // navigation during the LEAVE_APPROVE emit (reentrant navigate is banned).\n return undefined;\n}\n\nexport function abortPreviousNavigation(\n deps: NavigationDependencies,\n externalSignal?: AbortSignal,\n): void {\n if (deps.isTransitioning()) {\n deps.logger.warn(\n \"router.navigate\",\n \"Concurrent navigation detected on shared router instance. \" +\n \"For SSR, use cloneRouter() to create isolated instance per request.\",\n );\n // The FSM CANCEL action aborts the previous controller — no\n // direct controller.abort here (RFC navigation-cancellation-unification §5).\n deps.cancelNavigation();\n }\n\n if (externalSignal?.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: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errorHandling.js");
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../RouterError.js"),n=require("./errorHandling.js");function r(r,i,a,o,s,c,l,u,d,f){if(!d())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(r===1){let e=f();return e===void 0?void 0:{phase:r,index:i+1,pending:e}}let p=a[i],m=o.get(p);if(!m)return;let h=!1;try{h=m(c,l,u)}catch(e){n.handleGuardError(e,s,p)}if(h instanceof Promise)return{phase:r,index:i+1,pending:h};if(!h)throw new t.RouterError(s,{segment:p})}function i(t,n,i,a,o,s,c,l,u,d,f,p,m){let h=t===1,g=t===0;if(!h&&!(g?c:l))return;let _=g?o:s,v=h?1:_.length,y=g?i:a,b=g?e.errorCodes.CANNOT_DEACTIVATE:e.errorCodes.CANNOT_ACTIVATE;for(let e=n;e<v;e++){let n=r(t,e,_,y,b,u,d,f,p,m);if(n!==void 0)return n}}function a(e,t,n,r,a,o,s,c,l,u,d,f,p){for(let m=f;m<=2;m++){let h=i(m,m===f?p:0,e,t,n,r,a,o,s,c,l,u,d);if(h!==void 0)return h}}async function o(t,r,i,o,s,c,l,u,d,f,p,m){let h=t;for(;h!==void 0;){if(h.phase===1)await h.pending;else{let t=h.phase===0;await n.resolveAsyncGuard(h.pending,t?e.errorCodes.CANNOT_DEACTIVATE:e.errorCodes.CANNOT_ACTIVATE,(t?o:s)[h.index-1])}h=a(r,i,o,s,c,l,u,d,f,p,m,h.phase,h.index)}}function s(e,t,n,r,i,s,c,l,u,d,f){let p=a(e,t,n,r,i,s,c,l,u,d,f,0,0);return p===void 0?void 0:o(p,e,t,n,r,i,s,c,l,u,d,f)}exports.executeGuardPipeline=s;
|
|
2
2
|
//# sourceMappingURL=guardPhase.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"guardPhase.js","names":["RouterError","errorCodes"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/guardPhase.ts"],"sourcesContent":["import { handleGuardError } from \"./errorHandling\";\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { GuardFn, State } from \"../../../types\";\n\nasync function resolveAsyncGuard(\n promise: Promise<boolean>,\n errorCode: string,\n segment: string,\n): Promise<void> {\n let result: boolean;\n\n try {\n result = await promise;\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n\n return; // unreachable — handleGuardError returns never\n }\n\n if (!result) {\n throw new RouterError(errorCode, { segment });\n }\n}\n\nasync function resolveRemainingGuards( // NOSONAR -- params kept flat to avoid object allocation on hot path\n guards: Map<string, GuardFn>,\n segments: string[],\n errorCode: string,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n startIndex: number,\n firstResult: Promise<boolean>,\n firstSegment: string,\n): Promise<void> {\n await resolveAsyncGuard(firstResult, errorCode, firstSegment);\n\n for (let i = startIndex; i < segments.length; i++) {\n // Stryker disable next-line BlockStatement: equivalent — emptying the body drops the async-tail cancellation throw, but supersession is independently enforced by the navigationId/isCurrentNav checks in NavigationNamespace, so the navigation still rejects with TRANSITION_CANCELLED (full suite green). The ConditionalExpression sibling stays live (its →true variant always-cancels and is killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const segment = segments[i];\n const guardFn = guards.get(segment);\n\n if (!guardFn) {\n continue;\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — guardResult is unconditionally reassigned by guardFn() on the next line, or the catch calls handleGuardError() (returns never), so the init value is never read.\n let guardResult: boolean | Promise<boolean> = false;\n\n try {\n guardResult = guardFn(toState, fromState, signal);\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n }\n\n if (guardResult instanceof Promise) {\n await resolveAsyncGuard(guardResult, errorCode, segment);\n continue;\n }\n\n if (!guardResult) {\n throw new RouterError(errorCode, { segment });\n }\n }\n}\n\nasync function finishAsyncPipeline( // NOSONAR\n deactivateCompletion: Promise<void>,\n activateGuards: Map<string, GuardFn>,\n toActivate: string[],\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> {\n await deactivateCompletion;\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const leaveResult = emitLeaveApprove();\n\n if (leaveResult !== undefined) {\n await leaveResult;\n\n // Stryker disable next-line BlockStatement: equivalent — defensive-redundancy: this post-leave cancellation re-check is already enforced upstream (navigationId / isCurrentNav supersession in NavigationNamespace), so emptying the throw is unobservable. Mirrors the disabled L42/L115/L228 cancel-checks.\n /* v8 ignore next 3 -- @preserve: V8 cannot track cancellation check through async leave continuation after Promise.allSettled */\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n\n if (shouldActivate) {\n const pending = runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n await pending;\n }\n\n // Stryker disable next-line BlockStatement: equivalent — same async-tail cancellation throw as L42; dropping it is covered by the outer navigationId guard (full suite green). CE sibling stays live (→true killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n}\n\nexport function executeGuardPipeline( // NOSONAR\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> | undefined {\n if (shouldDeactivate) {\n const pending = runGuards(\n deactivateGuards,\n toDeactivate,\n errorCodes.CANNOT_DEACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n return finishAsyncPipeline(\n pending,\n activateGuards,\n toActivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n );\n }\n }\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const leaveResult = emitLeaveApprove();\n\n if (leaveResult !== undefined) {\n return finishAfterAsyncLeave(\n leaveResult,\n /* v8 ignore next -- @preserve: false-branch unreachable — navigateToNotFound bypasses guards pipeline */\n shouldActivate ? activateGuards : undefined,\n toActivate,\n toState,\n fromState,\n signal,\n isActive,\n );\n }\n\n if (shouldActivate) {\n return runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n }\n\n return undefined;\n}\n\nasync function finishAfterAsyncLeave(\n leaveCompletion: Promise<void>,\n activateGuards: Map<string, GuardFn> | undefined,\n toActivate: string[],\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n await leaveCompletion;\n\n // Stryker disable next-line BlockStatement: equivalent — defensive-redundancy: same post-leave cancellation re-check as guardPhase's other `!isActive()` guards; supersession is enforced upstream (navigationId / isCurrentNav), so emptying the throw is unobservable.\n /* v8 ignore next 3 -- @preserve: unreachable after #663 — signal abort\n mid-leave rejects via settleLeavePromises, so `await leaveCompletion`\n throws directly instead of completing with a stale isActive() */\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n /* v8 ignore next -- @preserve: false-branch unreachable — navigateToNotFound bypasses guards pipeline */\n if (activateGuards !== undefined) {\n const pending = runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n await pending;\n }\n\n // Stryker disable next-line BlockStatement: equivalent — same async-tail cancellation throw as L42; dropping it is covered by the outer navigationId guard (full suite green). CE sibling stays live (→true killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n}\n\nfunction runGuards(\n guards: Map<string, GuardFn>,\n segments: string[],\n errorCode: string,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n): Promise<void> | undefined {\n for (const [i, segment] of segments.entries()) {\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const guardFn = guards.get(segment);\n\n if (!guardFn) {\n continue;\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — guardResult is unconditionally reassigned by guardFn() on the next line, or the catch calls handleGuardError() (returns never), so the init value is never read.\n let guardResult: boolean | Promise<boolean> = false;\n\n try {\n guardResult = guardFn(toState, fromState, signal);\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n }\n\n if (guardResult instanceof Promise) {\n return resolveRemainingGuards(\n guards,\n segments,\n errorCode,\n toState,\n fromState,\n signal,\n isActive,\n i + 1,\n guardResult,\n segment,\n );\n }\n\n if (!guardResult) {\n throw new RouterError(errorCode, { segment });\n }\n }\n\n return undefined;\n}\n"],"mappings":"8GAMA,eAAe,EACb,EACA,EACA,EACe,CACf,IAAI,EAEJ,GAAI,CACF,EAAS,MAAM,CACjB,OAAS,EAAgB,CACvB,EAAA,iBAAiB,EAAO,EAAW,CAAO,EAE1C,MACF,CAEA,GAAI,CAAC,EACH,MAAM,IAAIA,EAAAA,YAAY,EAAW,CAAE,SAAQ,CAAC,CAEhD,CAEA,eAAe,EACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACe,CACf,MAAM,EAAkB,EAAa,EAAW,CAAY,EAE5D,IAAK,IAAI,EAAI,EAAY,EAAI,EAAS,OAAQ,IAAK,CAEjD,GAAI,CAAC,EAAS,EACZ,MAAM,IAAIA,EAAAA,YAAYC,EAAAA,WAAW,oBAAoB,EAGvD,IAAM,EAAU,EAAS,GACnB,EAAU,EAAO,IAAI,CAAO,EAElC,GAAI,CAAC,EACH,SAIF,IAAI,EAA0C,GAE9C,GAAI,CACF,EAAc,EAAQ,EAAS,EAAW,CAAM,CAClD,OA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EACA,EACA,EACA,CACF,CAIJ,CAEA,eAAe,EACb,EACA,EACA,EACA,EACA,EACA,EACA,EACe,CAOf,GANA,MAAM,EAMF,CAAC,EAAS,EACZ,MAAM,IAAID,EAAAA,YAAYC,EAAAA,WAAW,oBAAoB,EAIvD,GAAI,IAAmB,IAAA,GAAW,CAChC,IAAM,EAAU,EACd,EACA,EACAA,EAAAA,WAAW,gBACX,EACA,EACA,EACA,CACF,EAOA,GALI,IAAY,IAAA,IACd,MAAM,EAIJ,CAAC,EAAS,EACZ,MAAM,IAAID,EAAAA,YAAYC,EAAAA,WAAW,oBAAoB,CAEzD,CACF,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACA,EACA,EAC2B,CAC3B,IAAK,GAAM,CAAC,EAAG,KAAY,EAAS,QAAQ,EAAG,CAC7C,GAAI,CAAC,EAAS,EACZ,MAAM,IAAID,EAAAA,YAAYC,EAAAA,WAAW,oBAAoB,EAGvD,IAAM,EAAU,EAAO,IAAI,CAAO,EAElC,GAAI,CAAC,EACH,SAIF,IAAI,EAA0C,GAE9C,GAAI,CACF,EAAc,EAAQ,EAAS,EAAW,CAAM,CAClD,OAAS,EAAgB,CACvB,EAAA,iBAAiB,EAAO,EAAW,CAAO,CAC5C,CAEA,GAAI,aAAuB,QACzB,OAAO,EACL,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAI,EACJ,EACA,CACF,EAGF,GAAI,CAAC,EACH,MAAM,IAAID,EAAAA,YAAY,EAAW,CAAE,SAAQ,CAAC,CAEhD,CAGF"}
|
|
1
|
+
{"version":3,"file":"guardPhase.js","names":["RouterError","errorCodes","resolveAsyncGuard"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/guardPhase.ts"],"sourcesContent":["import { handleGuardError, resolveAsyncGuard } from \"./errorHandling\";\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { GuardFn, State } from \"../../../types\";\n\n/**\n * The guard pipeline as ONE program and TWO interpreters (RFC two-pipelines,\n * разрез Б).\n *\n * The program is three fixed phases — deactivate, leave, activate — walked by a\n * cursor of two numbers. `runFrom` is the synchronous interpreter: it walks\n * until a step hands back a Promise, then stops and reports where it stopped.\n * `resumeFrom` is the asynchronous one: it settles that Promise and hands the\n * cursor straight back to `runFrom`. Switching pipelines is therefore a single\n * act — give up the cursor — rather than four continuation functions each wired\n * to its own entry point.\n *\n * What that buys, and it is the reason the step exists: **one cancellation\n * check**. There were eight, and five of them were mutationally unkillable —\n * their breakage was as unobservable as their removal, because a navigation\n * reaching them was already covered by the liveness check one layer up. A single\n * check in the head of the step runs at every position that mattered, and it\n * sits where nothing else guards it, so it is killable again (removing it fails\n * four tests).\n *\n * It does NOT reproduce the five redundant positions, deliberately: there is no\n * check after the LAST activation guard settles, nor after an async leave when\n * `shouldActivate` is false, because the walk simply ends there. Those were two\n * of the five, and `#finishAsyncNavigation`'s liveness check still covers both.\n */\n\nconst PHASE_DEACTIVATE = 0;\nconst PHASE_LEAVE = 1;\nconst PHASE_ACTIVATE = 2;\n\n/**\n * Where the synchronous interpreter stopped, and what it is waiting on.\n *\n * Allocated ONLY when a step actually suspends — a fully synchronous navigation\n * never builds one, which is what keeps the hot path where it was. `index` is\n * already the cursor for the NEXT step, so resuming needs no off-by-one\n * reasoning.\n */\ninterface Suspension {\n phase: number;\n index: number;\n pending: Promise<unknown>;\n}\n\n/**\n * ONE step of the program: the cancellation check, then the step's own work.\n *\n * Returns a {@link Suspension} when the step handed back a Promise, `undefined`\n * when it finished synchronously, and throws when it refused — a guard returning\n * `false`, a guard throwing, or the navigation having been cancelled.\n */\nfunction runStep( // NOSONAR -- params kept flat to avoid object allocation on hot path\n phase: number,\n index: number,\n segments: string[],\n guards: Map<string, GuardFn>,\n errorCode: string,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Suspension | undefined {\n // THE cancellation check — the only one left in this file, and literally in\n // the head of a step. Eight became one, and unlike five of those eight it is\n // killable: nothing else guards this position.\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n if (phase === PHASE_LEAVE) {\n const leaveResult = emitLeaveApprove();\n\n return leaveResult === undefined\n ? undefined\n : { phase, index: index + 1, pending: leaveResult };\n }\n\n const segment = segments[index];\n const guardFn = guards.get(segment);\n\n if (!guardFn) {\n return undefined;\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — guardResult is unconditionally reassigned by guardFn() on the next line, or the catch calls handleGuardError() (returns never), so the init value is never read.\n let guardResult: boolean | Promise<boolean> = false;\n\n try {\n guardResult = guardFn(toState, fromState, signal);\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n }\n\n if (guardResult instanceof Promise) {\n return { phase, index: index + 1, pending: guardResult };\n }\n\n if (!guardResult) {\n throw new RouterError(errorCode, { segment });\n }\n\n return undefined;\n}\n\n/**\n * One PHASE of the program: its short-circuit, then its steps.\n *\n * Split from the walk so neither function carries the whole program — phase-level\n * and step-level nesting in one body is what pushed the first draft past the\n * complexity budget, and past a lint rule against `continue` across nested loops.\n */\nfunction runPhase( // NOSONAR -- params kept flat to avoid object allocation on hot path\n phase: number,\n from: number,\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Suspension | undefined {\n const isLeave = phase === PHASE_LEAVE;\n const isDeactivate = phase === PHASE_DEACTIVATE;\n\n // Today's per-phase short-circuits, reproduced. `shouldDeactivate` carries\n // `!opts.forceDeactivate`, so this is a user-facing contract and not merely an\n // emptiness test — forcing it on is measurably NOT equivalent.\n if (!isLeave && !(isDeactivate ? shouldDeactivate : shouldActivate)) {\n return undefined;\n }\n\n const segments = isDeactivate ? toDeactivate : toActivate;\n // The leave phase is a single step, so one loop shape covers all three phases\n // — which is what gives the cancellation check exactly one home.\n const stepCount = isLeave ? 1 : segments.length;\n const guards = isDeactivate ? deactivateGuards : activateGuards;\n const errorCode = isDeactivate\n ? errorCodes.CANNOT_DEACTIVATE\n : errorCodes.CANNOT_ACTIVATE;\n\n for (let index = from; index < stepCount; index++) {\n const suspension = runStep(\n phase,\n index,\n segments,\n guards,\n errorCode,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n );\n\n if (suspension !== undefined) {\n return suspension;\n }\n }\n\n return undefined;\n}\n\n/**\n * The synchronous interpreter: walk the program from `startPhase`/`startIndex`\n * until a step suspends (returns the {@link Suspension}) or the program ends\n * (returns `undefined` — done).\n *\n * Parameters are flat rather than a context object on purpose: a bag would be an\n * allocation on every guarded navigation, and this is the #307 hot path.\n */\nfunction runFrom( // NOSONAR -- params kept flat to avoid object allocation on hot path\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n startPhase: number,\n startIndex: number,\n): Suspension | undefined {\n for (let phase = startPhase; phase <= PHASE_ACTIVATE; phase++) {\n const suspension = runPhase(\n phase,\n phase === startPhase ? startIndex : 0,\n deactivateGuards,\n activateGuards,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n );\n\n if (suspension !== undefined) {\n return suspension;\n }\n }\n\n return undefined;\n}\n\n/**\n * The asynchronous interpreter: settle what the synchronous one stopped on, then\n * hand the cursor straight back to it.\n *\n * It owns no phase logic of its own, and that is the point — everything it knows\n * about the program it learns from the cursor, so the two interpreters cannot\n * drift apart the way the three continuation functions did.\n */\nasync function resumeFrom( // NOSONAR -- params kept flat to avoid object allocation on hot path\n suspension: Suspension,\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> {\n let at: Suspension | undefined = suspension;\n\n while (at !== undefined) {\n if (at.phase === PHASE_LEAVE) {\n await at.pending;\n } else {\n const isDeactivate = at.phase === PHASE_DEACTIVATE;\n\n await resolveAsyncGuard(\n at.pending as Promise<boolean>,\n isDeactivate\n ? errorCodes.CANNOT_DEACTIVATE\n : errorCodes.CANNOT_ACTIVATE,\n (isDeactivate ? toDeactivate : toActivate)[at.index - 1],\n );\n }\n\n at = runFrom(\n deactivateGuards,\n activateGuards,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n at.phase,\n at.index,\n );\n }\n}\n\n/**\n * Runs the guard program. Returns `undefined` when it completed synchronously,\n * or the Promise that finishes it otherwise — the same contract the three\n * orchestrators used to provide between them.\n */\nexport function executeGuardPipeline( // NOSONAR -- params kept flat to avoid object allocation on hot path\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> | undefined {\n const suspension = runFrom(\n deactivateGuards,\n activateGuards,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n PHASE_DEACTIVATE,\n 0,\n );\n\n return suspension === undefined\n ? undefined\n : resumeFrom(\n suspension,\n deactivateGuards,\n activateGuards,\n toDeactivate,\n toActivate,\n shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n );\n}\n"],"mappings":"8GAyDA,SAAS,EACP,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACwB,CAIxB,GAAI,CAAC,EAAS,EACZ,MAAM,IAAIA,EAAAA,YAAYC,EAAAA,WAAW,oBAAoB,EAGvD,GAAI,IAAU,EAAa,CACzB,IAAM,EAAc,EAAiB,EAErC,OAAO,IAAgB,IAAA,GACnB,IAAA,GACA,CAAE,QAAO,MAAO,EAAQ,EAAG,QAAS,CAAY,CACtD,CAEA,IAAM,EAAU,EAAS,GACnB,EAAU,EAAO,IAAI,CAAO,EAElC,GAAI,CAAC,EACH,OAIF,IAAI,EAA0C,GAE9C,GAAI,CACF,EAAc,EAAQ,EAAS,EAAW,CAAM,CAClD,OAAS,EAAgB,CACvB,EAAA,iBAAiB,EAAO,EAAW,CAAO,CAC5C,CAEA,GAAI,aAAuB,QACzB,MAAO,CAAE,QAAO,MAAO,EAAQ,EAAG,QAAS,CAAY,EAGzD,GAAI,CAAC,EACH,MAAM,IAAID,EAAAA,YAAY,EAAW,CAAE,SAAQ,CAAC,CAIhD,CASA,SAAS,EACP,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACwB,CACxB,IAAM,EAAU,IAAU,EACpB,EAAe,IAAU,EAK/B,GAAI,CAAC,GAAW,EAAE,EAAe,EAAmB,GAClD,OAGF,IAAM,EAAW,EAAe,EAAe,EAGzC,EAAY,EAAU,EAAI,EAAS,OACnC,EAAS,EAAe,EAAmB,EAC3C,EAAY,EACdC,EAAAA,WAAW,kBACXA,EAAAA,WAAW,gBAEf,IAAK,IAAI,EAAQ,EAAM,EAAQ,EAAW,IAAS,CACjD,IAAM,EAAa,EACjB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACF,EAEA,GAAI,IAAe,IAAA,GACjB,OAAO,CAEX,CAGF,CAUA,SAAS,EACP,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACwB,CACxB,IAAK,IAAI,EAAQ,EAAY,GAAS,EAAgB,IAAS,CAC7D,IAAM,EAAa,EACjB,EACA,IAAU,EAAa,EAAa,EACpC,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACF,EAEA,GAAI,IAAe,IAAA,GACjB,OAAO,CAEX,CAGF,CAUA,eAAe,EACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACe,CACf,IAAI,EAA6B,EAEjC,KAAO,IAAO,IAAA,IAAW,CACvB,GAAI,EAAG,QAAU,EACf,MAAM,EAAG,YACJ,CACL,IAAM,EAAe,EAAG,QAAU,EAElC,MAAMC,EAAAA,kBACJ,EAAG,QACH,EACID,EAAAA,WAAW,kBACXA,EAAAA,WAAW,iBACd,EAAe,EAAe,EAAA,CAAY,EAAG,MAAQ,EACxD,CACF,CAEA,EAAK,EACH,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAAG,MACH,EAAG,KACL,CACF,CACF,CAOA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAC2B,CAC3B,IAAM,EAAa,EACjB,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACF,EAEA,OAAO,IAAe,IAAA,GAClB,IAAA,GACA,EACE,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACF,CACN"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../transitionPath.js"),n=require("../../../RouterError.js"),r=require("./executeNavigation.js"),i=Object.freeze([e.constants.UNKNOWN_ROUTE]),a=Object.freeze({replace:!0});function o(o,s){if(!o.isActive())throw new n.RouterError(e.errorCodes.ROUTER_DISPOSED);r.abortPreviousNavigation(o);let c=o.getState(),l=c?t.nameToIDs(c.name).toReversed():[];Object.freeze(l);let u={deactivated:l,activated:i,intersection:``};Object.freeze(u);let d={phase:`activating`,...c&&{from:c.name},reason:`success`,replace:!0,segments:u};Object.freeze(d);let f={name:e.constants.UNKNOWN_ROUTE,params:e.EMPTY_PARAMS,search:e.EMPTY_SEARCH,path:s,transition:d,context:{}};return Object.freeze(f),o.setState(f),o.emitTransitionSuccess(f,c,a),f}exports.navigateToNotFound=o;
|
|
2
|
+
//# sourceMappingURL=navigateToNotFound.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"navigateToNotFound.js","names":["constants","RouterError","errorCodes","nameToIDs","EMPTY_PARAMS","EMPTY_SEARCH"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/navigateToNotFound.ts"],"sourcesContent":["import { abortPreviousNavigation } from \"./executeNavigation\";\nimport {\n EMPTY_PARAMS,\n EMPTY_SEARCH,\n errorCodes,\n constants,\n} from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\nimport { nameToIDs } from \"../../../transitionPath\";\n\nimport type { NavigationOptions, State, TransitionMeta } from \"../../../types\";\nimport type { NavigationDependencies } from \"../types\";\n\n/**\n * The one commit primitive that is NOT a transition.\n *\n * It hand-builds an `UNKNOWN_ROUTE` state, freezes it, commits it and emits only\n * `TRANSITION_SUCCESS` — no guards, no FSM transition, no controller, no plan.\n * That is why it sat oddly among the transition machinery it shared a file with\n * (#1607); the one thing it does share is supersession, since committing a\n * not-found state must displace whatever navigation is in flight.\n */\n\nconst FROZEN_ACTIVATED: string[] = Object.freeze([\n constants.UNKNOWN_ROUTE,\n]) as unknown as string[];\nconst FROZEN_REPLACE_OPTS: NavigationOptions = Object.freeze({ replace: true });\n\nexport function navigateToNotFound(\n deps: NavigationDependencies,\n path: string,\n): State {\n // #1186 — liveness gate. This internal commit primitive has no FSM\n // transition of its own, so without this check a `dispose()` that lands\n // while a start-interceptor is parked (FSM already DISPOSED) would let the\n // resuming pipeline commit an UNKNOWN_ROUTE state on the disposed router and\n // `start()` resolve. Symmetric with `navigateToState`'s `canNavigate()` gate\n // (the matched-route branch is already protected). `!isActive()` also covers\n // a merely-stopped (IDLE) router: the only reachable path to that is a direct\n // `router.navigateToNotFound()` on a stopped instance (internal callers run\n // during STARTING, which is active), so the ROUTER_DISPOSED code is slightly\n // broad there — fail-closed is deliberate (committing on a stopped router is\n // out of contract), and the disposed race is the case that matters.\n if (!deps.isActive()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n abortPreviousNavigation(deps);\n\n const fromState = deps.getState();\n const deactivated: string[] = fromState\n ? nameToIDs(fromState.name).toReversed()\n : [];\n\n Object.freeze(deactivated);\n\n const segments: TransitionMeta[\"segments\"] = {\n deactivated,\n activated: FROZEN_ACTIVATED,\n intersection: \"\",\n };\n\n Object.freeze(segments);\n\n const transitionMeta: TransitionMeta = {\n phase: \"activating\",\n ...(fromState && { from: fromState.name }),\n reason: \"success\",\n replace: true,\n segments,\n };\n\n Object.freeze(transitionMeta);\n\n const state: State = {\n name: constants.UNKNOWN_ROUTE,\n params: EMPTY_PARAMS,\n search: EMPTY_SEARCH,\n path,\n transition: transitionMeta,\n context: {},\n };\n\n Object.freeze(state);\n\n deps.setState(state);\n deps.emitTransitionSuccess(state, fromState, FROZEN_REPLACE_OPTS);\n\n return state;\n}\n"],"mappings":"0JAuBM,EAA6B,OAAO,OAAO,CAC/CA,EAAAA,UAAU,aACZ,CAAC,EACK,EAAyC,OAAO,OAAO,CAAE,QAAS,EAAK,CAAC,EAE9E,SAAgB,EACd,EACA,EACO,CAYP,GAAI,CAAC,EAAK,SAAS,EACjB,MAAM,IAAIC,EAAAA,YAAYC,EAAAA,WAAW,eAAe,EAGlD,EAAA,wBAAwB,CAAI,EAE5B,IAAM,EAAY,EAAK,SAAS,EAC1B,EAAwB,EAC1BC,EAAAA,UAAU,EAAU,IAAI,CAAC,CAAC,WAAW,EACrC,CAAC,EAEL,OAAO,OAAO,CAAW,EAEzB,IAAM,EAAuC,CAC3C,cACA,UAAW,EACX,aAAc,EAChB,EAEA,OAAO,OAAO,CAAQ,EAEtB,IAAM,EAAiC,CACrC,MAAO,aACP,GAAI,GAAa,CAAE,KAAM,EAAU,IAAK,EACxC,OAAQ,UACR,QAAS,GACT,UACF,EAEA,OAAO,OAAO,CAAc,EAE5B,IAAM,EAAe,CACnB,KAAMH,EAAAA,UAAU,cAChB,OAAQI,EAAAA,aACR,OAAQC,EAAAA,aACR,OACA,WAAY,EACZ,QAAS,CAAC,CACZ,EAOA,OALA,OAAO,OAAO,CAAK,EAEnB,EAAK,SAAS,CAAK,EACnB,EAAK,sBAAsB,EAAO,EAAW,CAAmB,EAEzD,CACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../channels/guard.js"),t=require("../../constants.js"),n=require("../../helpers.js"),r=require("../../pipeline/canonicalize.js"),i=require("../../pipeline/materialize.js"),a=require("./helpers.js"),o=require("./routesStore.js"),s=require("../../transitionPath.js");function c(e,t){return{name:t??e.segments.at(-1).fullName,params:e.params,search:e.search,meta:e.meta}}var l=class{#e;#t;#n;get#r(){return this.#e.depsStore}constructor(e,t,n){this.#e=o.createRoutesStore(e,t,n)}static shouldUpdateNode(e,t){return(n,r)=>{if(!(n&&typeof n==`object`&&`name`in n))throw TypeError(`[router.shouldUpdateNode] toState must be valid State object`);if(n.transition.reload||e===``)return!0;let{intersection:i,toActivate:a,toDeactivate:o}=s.getTransitionPath(n,r,t);return e===i||a.includes(e)?!0:o.includes(e)}}setDependencies(e){this.#e.depsStore=e}flushPendingGuards(){let e=this.#r;for(let[t,n]of this.#e.pendingCanActivate)e.addActivateGuard(t,n);this.#e.pendingCanActivate.clear();for(let[t,n]of this.#e.pendingCanDeactivate)e.addDeactivateGuard(t,n);this.#e.pendingCanDeactivate.clear()}setLifecycleNamespace(e){this.#e.lifecycleNamespace=e}setRootPath(e){o.applyRootPath(this.#e,e)}hasRoute(e){return this.#e.matcher.hasRoute(e)}clearRoutes(){o.resetStore(this.#e)}buildPath(e,n,i,a){if(e===t.constants.UNKNOWN_ROUTE)return typeof n.path==`string`?n.path:``;let o=r.canonicalize(this.#r.port,e,n,i,{resolveForward:!1});if(typeof this.#e.config.encoders[e]==`function`){let t=this.#e.config.encoders[e]({params:{...o.path},search:{...o.query}});return this.#e.matcher.buildPath(e,t.params,t.search,this.#c(a))}return this.#e.matcher.buildPath(e,o.path,o.query,this.#c(a))}matchPath(t,n){let o=n,s=this.#e.matcher.match(t);if(!s)return;let l=c(s),{name:u,params:d}=l,f=l.search,p=this.#e.config.decoders[u],m;typeof p==`function`?(m=p({params:d,search:f}),this.#r.getValidator()?.routes.validateStateBuilderArgs(u,m.params,`matchPath`),e.assertChannelCorrect(`matchPath`,u,m.params,this.getQueryParams(u),"the `params` returned by this route's `decodeParams`")):m={params:d,search:f};let h=r.canonicalize(this.#r.port,u,m.params,m.search),g=h.name,_=h.path,v=h.query,y=t;if(o.rewritePathOnMatch){let e=typeof this.#e.config.encoders[g]==`function`?this.#e.config.encoders[g]({params:_,search:v}):{params:_,search:v},n=o.trailingSlash;try{y=this.#e.matcher.buildPath(g,e.params,e.search,{trailingSlash:n===`never`||n===`always`?n:void 0,queryParamsMode:o.queryParamsMode}),n===`preserve`&&(y=a.matchSourceTrailingSlash(t,y))}catch{y=t}}return i.materialize(h,{path:y})}forwardState(e,n,r){let i=r??t.EMPTY_SEARCH;if(Object.hasOwn(this.#e.config.forwardFnMap,e)){let t=this.#e.config.forwardFnMap[e],{target:r,chain:a}=this.#l(e,t,n);return this.#s(r,a,n,i)}let a=this.#e.resolvedForwardMap[e]??e;if(a!==e&&Object.hasOwn(this.#e.config.forwardFnMap,a)){let t=this.#e.config.forwardFnMap[a],{target:r,chain:o}=this.#l(a,t,n);return this.#s(r,[...this.#o(e),...o],n,i)}return a===e?{name:e,params:n,search:i}:this.#s(a,this.#o(e),n,i)}buildStateResolved(e,t){let n=this.#e.matcher.getSegmentsByName(e);if(n)return c({segments:n,params:t,search:{},meta:this.#e.matcher.getMetaByName(e)},e)}isActiveRoute(e,n=t.EMPTY_PARAMS,r=t.EMPTY_SEARCH,i=!1,a=!0){if(this.#i(e,n,r,i,a))return!0;if(!Object.hasOwn(this.#e.config.forwardMap,e)&&!Object.hasOwn(this.#e.config.forwardFnMap,e))return!1;let o;try{o=this.forwardState(e,n,r)}catch(t){return this.#r.logger.warn(`router.isActiveRoute`,`Dynamic forwardTo of route "${e}" threw while resolving the active-link destination; treating the link as inactive.`,t),!1}return this.#i(o.name,o.params,o.search,i,a)}getMetaForState(e){return this.#e.matcher.hasRoute(e)?this.#e.matcher.getMetaByName(e):void 0}getUrlParams(e){return a.urlParamsOf(this.#e,e)}getQueryParams(e){return a.queryParamsOf(this.#e,e)}getStore(){return this.#e}getPort(){return this.#r.port}#i(e,t,n,r,i){try{return this.#a(e,t,n,r,i)}catch(t){return this.#r.logger.warn(`router.isActiveRoute`,`Reading the arguments for route "${e}" threw while resolving the active-link state; treating the link as inactive.`,t),!1}}#a(e,t,n,o,s){let c=this.#r.getState();if(!c)return!1;let l=c.name;if(l!==e&&!l.startsWith(`${e}.`)&&!e.startsWith(`${l}.`))return!1;let u=r.canonicalize(this.#r.port,e,t,n,{resolveForward:!1});return o||l===e?this.#r.areStatesEqual(i.materialize(u,{path:``,skipFreeze:!0}),c,s):!(!l.startsWith(`${e}.`)||!a.paramsMatch(u.path,c.params)||!s&&!a.paramsMatch(u.query,c.search))}#o(e){let t=[],n=e;for(;Object.hasOwn(this.#e.config.forwardMap,n);)t.push(n),n=this.#e.config.forwardMap[n];return t}#s(e,t,r,i){let a,o;for(let e of t)a=n.mergeDefined(this.#e.config.defaultParams[e],a),o=n.mergeDefined(this.#e.config.defaultSearch[e],o);return{name:e,params:n.mergeDefined(a,r),search:n.mergeDefined(o,i)}}#c(e){if(this.#t)return e!==this.#n&&this.#r.logger.warn(`router.buildPath`,"`options` differs from the cached source reference; router options are immutable per router instance, so the first-cached buildPath options are reused (#957)."),this.#t;this.#n=e;let t=e?.trailingSlash;return this.#t=Object.freeze({trailingSlash:t===`never`||t===`always`?t:void 0,queryParamsMode:e?.queryParamsMode}),this.#t}#l(e,t,n){let r=new Set([e]),i=[e],a=t(this.#r.getDependency,n),o=0;if(typeof a!=`string`)throw TypeError(`forwardTo callback must return a string, got ${typeof a}`);for(;o<100;){if(this.#e.matcher.getSegmentsByName(a)===void 0)throw Error(`Route "${a}" does not exist`);if(r.has(a)){let e=[...r,a].join(` → `);throw Error(`Circular forwardTo: ${e}`)}if(r.add(a),Object.hasOwn(this.#e.config.forwardFnMap,a)){let e=this.#e.config.forwardFnMap[a];i.push(a),a=e(this.#r.getDependency,n),o++;continue}let e=this.#e.config.forwardMap[a];if(e!==void 0){i.push(a),a=e,o++;continue}return{target:a,chain:i}}throw Error(`forwardTo exceeds maximum depth of 100`)}};exports.RoutesNamespace=l;
|
|
1
|
+
const e=require("../../channels/guard.js"),t=require("../../constants.js"),n=require("../../helpers.js"),r=require("../../pipeline/canonicalize.js"),i=require("../../pipeline/materialize.js"),a=require("./helpers.js"),o=require("./routesStore.js"),s=require("../../transitionPath.js");function c(e,t){return{name:t??e.segments.at(-1).fullName,params:e.params,search:e.search,meta:e.meta}}var l=class{#e;#t;#n;get#r(){return this.#e.depsStore}constructor(e,t,n){this.#e=o.createRoutesStore(e,t,n)}static shouldUpdateNode(e,t){return(n,r)=>{if(!(n&&typeof n==`object`&&`name`in n))throw TypeError(`[router.shouldUpdateNode] toState must be valid State object`);if(n.transition.reload||e===``)return!0;let{intersection:i,toActivate:a,toDeactivate:o}=s.getTransitionPath(n,r,t);return e===i||a.includes(e)?!0:o.includes(e)}}setDependencies(e){this.#e.depsStore=e}flushPendingGuards(){let e=this.#r;for(let[t,n]of this.#e.pendingCanActivate)e.addActivateGuard(t,n);this.#e.pendingCanActivate.clear();for(let[t,n]of this.#e.pendingCanDeactivate)e.addDeactivateGuard(t,n);this.#e.pendingCanDeactivate.clear()}setLifecycleNamespace(e){this.#e.lifecycleNamespace=e}setRootPath(e){o.applyRootPath(this.#e,e)}hasRoute(e){return this.#e.matcher.hasRoute(e)}clearRoutes(){o.resetStore(this.#e)}buildPath(e,n,i,a){if(e===t.constants.UNKNOWN_ROUTE)return typeof n.path==`string`?n.path:``;let o=r.canonicalize(this.#r.port,e,n,i,{resolveForward:!1});if(typeof this.#e.config.encoders[e]==`function`){let t=this.#e.config.encoders[e]({params:{...o.path},search:{...o.query}});return this.#e.matcher.buildPath(e,t.params,t.search,this.#c(a))}return this.#e.matcher.buildPath(e,o.path,o.query,this.#c(a))}matchPath(t,n){let o=n,s=this.#e.matcher.match(t);if(!s)return;let l=c(s),{name:u,params:d}=l,f=l.search,p=this.#e.config.decoders[u],m;typeof p==`function`?(m=p({params:d,search:f}),this.#r.getValidator()?.routes.validateStateBuilderArgs(u,m.params,`matchPath`),e.assertChannelCorrect(`matchPath`,u,m.params,this.getQueryParams(u),"the `params` returned by this route's `decodeParams`")):m={params:d,search:f};let h=r.canonicalize(this.#r.port,u,m.params,m.search),g=h.name,_=h.path,v=h.query,y=t;if(o.rewritePathOnMatch){let e=typeof this.#e.config.encoders[g]==`function`?this.#e.config.encoders[g]({params:_,search:v}):{params:_,search:v},n=o.trailingSlash;try{y=this.#e.matcher.buildPath(g,e.params,e.search,{trailingSlash:n===`never`||n===`always`?n:void 0,queryParamsMode:o.queryParamsMode}),n===`preserve`&&(y=a.matchSourceTrailingSlash(t,y))}catch{y=t}}return i.materialize(h,{path:y})}forwardState(e,n,r){let i=r??t.EMPTY_SEARCH;if(Object.hasOwn(this.#e.config.forwardFnMap,e)){let t=this.#e.config.forwardFnMap[e],{target:r,chain:a}=this.#l(e,t,n);return this.#s(r,a,n,i)}let a=this.#e.resolvedForwardMap[e]??e;if(a!==e&&Object.hasOwn(this.#e.config.forwardFnMap,a)){let t=this.#e.config.forwardFnMap[a],{target:r,chain:o}=this.#l(a,t,n);return this.#s(r,[...this.#o(e),...o],n,i)}return a===e?{name:e,params:n,search:i}:this.#s(a,this.#o(e),n,i)}buildStateResolved(e,t){let n=this.#e.matcher.getSegmentsByName(e);if(n)return c({segments:n,params:t,search:{},meta:this.#e.matcher.getMetaByName(e)},e)}isActiveRoute(e,n=t.EMPTY_PARAMS,r=t.EMPTY_SEARCH,i=!1,a=!0){if(this.#i(e,n,r,i,a))return!0;if(!this.#e.hasAnyForward||!Object.hasOwn(this.#e.config.forwardMap,e)&&!Object.hasOwn(this.#e.config.forwardFnMap,e))return!1;let o;try{o=this.forwardState(e,n,r)}catch(t){return this.#r.logger.warn(`router.isActiveRoute`,`Dynamic forwardTo of route "${e}" threw while resolving the active-link destination; treating the link as inactive.`,t),!1}return this.#i(o.name,o.params,o.search,i,a)}getMetaForState(e){return this.#e.matcher.hasRoute(e)?this.#e.matcher.getMetaByName(e):void 0}getUrlParams(e){return a.urlParamsOf(this.#e,e)}getQueryParams(e){return a.queryParamsOf(this.#e,e)}getStore(){return this.#e}getPort(){return this.#r.port}#i(e,t,n,r,i){try{return this.#a(e,t,n,r,i)}catch(t){return this.#r.logger.warn(`router.isActiveRoute`,`Reading the arguments for route "${e}" threw while resolving the active-link state; treating the link as inactive.`,t),!1}}#a(e,t,n,o,s){let c=this.#r.getState();if(!c)return!1;let l=c.name;if(l!==e&&!l.startsWith(`${e}.`)&&!e.startsWith(`${l}.`))return!1;let u=r.canonicalize(this.#r.port,e,t,n,{resolveForward:!1});return o||l===e?this.#r.areStatesEqual(i.materialize(u,{path:``,skipFreeze:!0}),c,s):!(!l.startsWith(`${e}.`)||!a.paramsMatch(u.path,c.params)||!s&&!a.paramsMatch(u.query,c.search))}#o(e){let t=[],n=e;for(;Object.hasOwn(this.#e.config.forwardMap,n);)t.push(n),n=this.#e.config.forwardMap[n];return t}#s(e,t,r,i){let a,o;for(let e of t)a=n.mergeDefined(this.#e.config.defaultParams[e],a),o=n.mergeDefined(this.#e.config.defaultSearch[e],o);return{name:e,params:n.mergeDefined(a,r),search:n.mergeDefined(o,i)}}#c(e){if(this.#t)return e!==this.#n&&this.#r.logger.warn(`router.buildPath`,"`options` differs from the cached source reference; router options are immutable per router instance, so the first-cached buildPath options are reused (#957)."),this.#t;this.#n=e;let t=e?.trailingSlash;return this.#t=Object.freeze({trailingSlash:t===`never`||t===`always`?t:void 0,queryParamsMode:e?.queryParamsMode}),this.#t}#l(e,t,n){let r=new Set([e]),i=[e],a=t(this.#r.getDependency,n),o=0;if(typeof a!=`string`)throw TypeError(`forwardTo callback must return a string, got ${typeof a}`);for(;o<100;){if(this.#e.matcher.getSegmentsByName(a)===void 0)throw Error(`Route "${a}" does not exist`);if(r.has(a)){let e=[...r,a].join(` → `);throw Error(`Circular forwardTo: ${e}`)}if(r.add(a),Object.hasOwn(this.#e.config.forwardFnMap,a)){let e=this.#e.config.forwardFnMap[a];i.push(a),a=e(this.#r.getDependency,n),o++;continue}let e=this.#e.config.forwardMap[a];if(e!==void 0){i.push(a),a=e,o++;continue}return{target:a,chain:i}}throw Error(`forwardTo exceeds maximum depth of 100`)}};exports.RoutesNamespace=l;
|
|
2
2
|
//# sourceMappingURL=RoutesNamespace.js.map
|