ui5-lib-guard-router 1.6.2 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
  2. package/CHANGELOG.md +197 -0
  3. package/README.md +695 -327
  4. package/dist/index.d.ts +9 -5
  5. package/dist/resources/ui5/guard/router/.library +1 -1
  6. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js +222 -0
  7. package/dist/resources/ui5/guard/router/GuardConfig-dbg.js.map +1 -0
  8. package/dist/resources/ui5/guard/router/GuardConfig.d.ts +89 -0
  9. package/dist/resources/ui5/guard/router/GuardConfig.d.ts.map +1 -0
  10. package/dist/resources/ui5/guard/router/GuardConfig.js +2 -0
  11. package/dist/resources/ui5/guard/router/GuardConfig.js.map +1 -0
  12. package/dist/resources/ui5/guard/router/GuardModules-dbg.js +253 -0
  13. package/dist/resources/ui5/guard/router/GuardModules-dbg.js.map +1 -0
  14. package/dist/resources/ui5/guard/router/GuardModules.d.ts +72 -0
  15. package/dist/resources/ui5/guard/router/GuardModules.d.ts.map +1 -0
  16. package/dist/resources/ui5/guard/router/GuardModules.js +2 -0
  17. package/dist/resources/ui5/guard/router/GuardModules.js.map +1 -0
  18. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js +125 -122
  19. package/dist/resources/ui5/guard/router/GuardPipeline-dbg.js.map +1 -1
  20. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts +45 -26
  21. package/dist/resources/ui5/guard/router/GuardPipeline.d.ts.map +1 -1
  22. package/dist/resources/ui5/guard/router/GuardPipeline.js +1 -1
  23. package/dist/resources/ui5/guard/router/GuardPipeline.js.map +1 -1
  24. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js +3 -3
  25. package/dist/resources/ui5/guard/router/NavigationOutcome-dbg.js.map +1 -1
  26. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts +3 -3
  27. package/dist/resources/ui5/guard/router/NavigationOutcome.d.ts.map +1 -1
  28. package/dist/resources/ui5/guard/router/NavigationOutcome.js.map +1 -1
  29. package/dist/resources/ui5/guard/router/PatternTree-dbg.js +156 -0
  30. package/dist/resources/ui5/guard/router/PatternTree-dbg.js.map +1 -0
  31. package/dist/resources/ui5/guard/router/PatternTree.d.ts +71 -0
  32. package/dist/resources/ui5/guard/router/PatternTree.d.ts.map +1 -0
  33. package/dist/resources/ui5/guard/router/PatternTree.js +2 -0
  34. package/dist/resources/ui5/guard/router/PatternTree.js.map +1 -0
  35. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js +84 -0
  36. package/dist/resources/ui5/guard/router/RouteMeta-dbg.js.map +1 -0
  37. package/dist/resources/ui5/guard/router/RouteMeta.d.ts +33 -0
  38. package/dist/resources/ui5/guard/router/RouteMeta.d.ts.map +1 -0
  39. package/dist/resources/ui5/guard/router/RouteMeta.js +2 -0
  40. package/dist/resources/ui5/guard/router/RouteMeta.js.map +1 -0
  41. package/dist/resources/ui5/guard/router/Router-dbg.js +900 -1033
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +362 -212
  44. package/dist/resources/ui5/guard/router/Router.d.ts.map +1 -1
  45. package/dist/resources/ui5/guard/router/Router.js +1 -1
  46. package/dist/resources/ui5/guard/router/Router.js.map +1 -1
  47. package/dist/resources/ui5/guard/router/library-dbg.js +1 -1
  48. package/dist/resources/ui5/guard/router/library-dbg.js.map +1 -1
  49. package/dist/resources/ui5/guard/router/library-preload.js +8 -4
  50. package/dist/resources/ui5/guard/router/library-preload.js.map +1 -1
  51. package/dist/resources/ui5/guard/router/library.js +1 -1
  52. package/dist/resources/ui5/guard/router/library.js.map +1 -1
  53. package/dist/resources/ui5/guard/router/manifest.json +5 -2
  54. package/dist/resources/ui5/guard/router/types-dbg.js.map +1 -1
  55. package/dist/resources/ui5/guard/router/types.d.ts +94 -39
  56. package/dist/resources/ui5/guard/router/types.d.ts.map +1 -1
  57. package/package.json +10 -6
  58. package/src/GuardConfig.ts +272 -0
  59. package/src/GuardModules.ts +249 -0
  60. package/src/GuardPipeline.ts +158 -129
  61. package/src/NavigationOutcome.ts +3 -3
  62. package/src/PatternTree.ts +145 -0
  63. package/src/RouteMeta.ts +82 -0
  64. package/src/Router.ts +1110 -1150
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
package/src/Router.ts CHANGED
@@ -1,42 +1,112 @@
1
1
  import MobileRouter from "sap/m/routing/Router";
2
2
  import Log from "sap/base/Log";
3
3
  import coreLibrary from "sap/ui/core/library";
4
- import type { ComponentTargetParameters } from "sap/ui/core/routing/Router";
4
+ import HashChanger from "sap/ui/core/routing/HashChanger";
5
+ import History from "sap/ui/core/routing/History";
6
+ import type { HashChangerBase$HashChangedEvent } from "sap/ui/core/routing/HashChangerBase";
7
+ import type { ComponentTargetParameters, RouteInfo, Router$RouteMatchedEvent } from "sap/ui/core/routing/Router";
8
+ import type Route from "sap/ui/core/routing/Route";
5
9
  import type { $RouteSettings } from "sap/ui/core/routing/Route";
10
+ import type UIComponent from "sap/ui/core/UIComponent";
6
11
  import type {
7
12
  GuardFn,
8
13
  GuardContext,
9
14
  GuardNavToOptions,
10
- GuardResult,
11
15
  GuardRedirect,
12
16
  GuardRouter,
13
- GuardLoading,
14
- Inheritance,
17
+ GuardRouterConfig,
15
18
  LeaveGuardFn,
16
- ManifestRouteGuardConfig,
17
- NavToPreflightMode,
18
19
  NavigationResult,
19
20
  Router$NavigationSettledEvent,
20
21
  RouteGuardConfig,
21
- UnknownRouteRegistrationPolicy,
22
22
  } from "./types";
23
23
  import NavigationOutcome from "./NavigationOutcome";
24
- import GuardPipeline, { type GuardDecision, isPromiseLike } from "./GuardPipeline";
24
+ import GuardPipeline, { type GuardDecision, isPromiseLike, isPromiseResolver, LOG_COMPONENT } from "./GuardPipeline";
25
+ import { type GuardDescriptor, isRecord, parseGuardRouterConfig, type ResolvedGuardRouterOptions } from "./GuardConfig";
26
+ import { createLazyGuards, loadGuardModules } from "./GuardModules";
27
+ import { byRouteDepth, expandForNewRoute, expandToDescendants, type RoutePattern } from "./PatternTree";
28
+ import RouteMetaStore, { EMPTY_META } from "./RouteMeta";
25
29
 
26
30
  const HistoryDirection = coreLibrary.routing.HistoryDirection;
31
+ type Direction = ReturnType<History["getDirection"]>;
27
32
 
28
- const LOG_COMPONENT = "ui5.guard.router.Router";
33
+ /**
34
+ * The router config as UI5 gets it: the caller's object without `guardRouter`. It is a view and
35
+ * not a copy, because UIComponent adds `targetParent` (the ID of the root view) to its config
36
+ * object after it has constructed the router, and the native router reads it from that object.
37
+ */
38
+ function withoutGuardRouter(config: object): object {
39
+ const hidden = (key: PropertyKey): boolean => key === "guardRouter";
40
+ return new Proxy(config, {
41
+ get: (target, key, receiver): unknown => (hidden(key) ? undefined : Reflect.get(target, key, receiver)),
42
+ has: (target, key) => !hidden(key) && Reflect.has(target, key),
43
+ ownKeys: (target) => Reflect.ownKeys(target).filter((key) => !hidden(key)),
44
+ getOwnPropertyDescriptor: (target, key) =>
45
+ hidden(key) ? undefined : Reflect.getOwnPropertyDescriptor(target, key),
46
+ });
47
+ }
29
48
 
30
49
  function isRouteGuardConfig(guard: GuardFn | RouteGuardConfig): guard is RouteGuardConfig {
31
50
  return typeof guard === "object" && guard !== null;
32
51
  }
33
52
 
53
+ /** A step through the browser history (back, forward): how far it went, and the URL it arrived at. */
54
+ interface HistoryStep {
55
+ readonly offset: number;
56
+ readonly href: string;
57
+ }
58
+
59
+ /** The step through the browser history that brought the browser to the URL it shows, if a step did. */
60
+ let lastStep: HistoryStep | null = null;
61
+ /** The URL of a step that a router is taking back, until the browser reports the next URL change. */
62
+ let undoneHref: string | null = null;
63
+
64
+ // The Navigation API tells how far a step through the history went, before UI5 learns of the
65
+ // hash change. UI5's History only infers it, and wrongly once an entry lacks its state. Without
66
+ // the API (Firefox before 147, Safari before 26.2) no step is known and the entry is replaced.
67
+ window.navigation?.addEventListener("currententrychange", (event) => {
68
+ const href = window.location.href;
69
+ if (undoneHref !== href) undoneHref = null;
70
+ const entry = window.navigation.currentEntry;
71
+ if (entry && event.navigationType === "traverse") {
72
+ lastStep = { offset: entry.index - event.from.index, href };
73
+ } else if (lastStep?.href !== href) {
74
+ // Not an entry whose state alone is replaced, as UI5's History does after a step.
75
+ lastStep = null;
76
+ }
77
+ });
78
+
79
+ /** What it takes to undo the hash change that an uncommitted navigation arrived with. */
80
+ interface HashChangeUndo {
81
+ /** The hash of the root hash changer after the first change that this takes back. */
82
+ readonly first: string;
83
+ /**
84
+ * The hash of the root hash changer before that change, with the hashes of nested routers.
85
+ * The root hash changer reports it with the change, after the routers have parsed their part.
86
+ */
87
+ fullHash: string | undefined;
88
+ /** The hash of the root hash changer after the change. */
89
+ readonly shown: string;
90
+ /** Whether the router has started to put the URL back, and the hash change that does it is still to come. */
91
+ started: boolean;
92
+ /** The step through the browser history that the change was, if it was one. */
93
+ readonly step: HistoryStep | null;
94
+ }
95
+
96
+ /** A manifest guard entry of a route, with the declared entry it stems from: itself, or the entry of an ancestor route. */
97
+ interface ManifestGuardDescriptor extends GuardDescriptor {
98
+ readonly source: GuardDescriptor;
99
+ }
100
+
34
101
  /** Snapshot of an in-flight navigation being evaluated by the guard pipeline. */
35
102
  interface NavigationAttempt {
36
103
  readonly hash: string;
37
- readonly route: string;
38
104
  readonly controller: AbortController;
39
105
  readonly generation: number;
106
+ /** Whether the URL shows a hash that never committed, so that it must be restored unless this attempt moves it. */
107
+ readonly restoreHash: boolean;
108
+ /** How the browser got to the hash that started the navigation; `undefined` after `navTo()` or `parse()`. */
109
+ readonly direction: Direction | undefined;
40
110
  }
41
111
 
42
112
  interface PhaseIdle {
@@ -46,388 +116,47 @@ interface PhaseIdle {
46
116
  interface PhaseEvaluating {
47
117
  readonly kind: "evaluating";
48
118
  readonly attempt: NavigationAttempt;
119
+ /** Whether the navigation waits for async guards: the native router would be matching its route by now. */
120
+ readonly postponed?: true;
49
121
  }
50
122
 
51
123
  interface PhaseCommitting {
52
124
  readonly kind: "committing";
53
- readonly hash: string;
54
125
  readonly route: string;
126
+ /** The hash of the route: `parse()` commits the navigation when it receives this hash. */
127
+ readonly hash: string;
55
128
  readonly origin: "preflight" | "redirect" | "parse";
56
- }
57
-
58
- type RouterPhase = PhaseIdle | PhaseEvaluating | PhaseCommitting;
59
-
60
- const IDLE: PhaseIdle = { kind: "idle" };
61
-
62
- /** Type guard for plain objects. */
63
- function isRecord(value: unknown): value is Record<string, unknown> {
64
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
65
- const proto = Object.getPrototypeOf(value);
66
- return proto === Object.prototype || proto === null;
67
- }
68
-
69
- /** Create a type-narrowing validator for a finite set of string literal values. */
70
- function isOneOf<T extends string>(...values: T[]): (v: unknown) => v is T {
71
- const set: ReadonlySet<string> = new Set(values);
72
- return (v: unknown): v is T => typeof v === "string" && set.has(v);
73
- }
74
-
75
- const isUnknownRouteRegistrationPolicy = isOneOf<UnknownRouteRegistrationPolicy>("ignore", "warn", "throw");
76
- const isNavToPreflightMode = isOneOf<NavToPreflightMode>("guard", "bypass", "off");
77
- const isGuardLoading = isOneOf<GuardLoading>("block", "lazy");
78
- const isInheritance = isOneOf<Inheritance>("none", "pattern-tree");
79
-
80
- /** Matches a standalone optional (`:param:`) or rest (`:param*:`) segment. */
81
- const OPTIONAL_OR_REST_SEGMENT = /^:[^:]*\*?:$/;
82
-
83
- /**
84
- * Strips inline query and optional-query suffixes from a segment.
85
- *
86
- * UI5 (crossroads.js) allows query parameters to attach directly to a
87
- * path segment without a `/` separator:
88
- * - `product{?query}` → mandatory query on `product`
89
- * - `product:?query:` → optional query on `product`
90
- * - `{id}{?query}` → mandatory param + mandatory query
91
- *
92
- * For pattern-tree ancestry we only care about the path portion,
93
- * so these suffixes are stripped.
94
- */
95
- function stripInlineQuery(seg: string): string {
96
- // Strip mandatory query `{?...}` suffix
97
- const mqIdx = seg.indexOf("{?");
98
- if (mqIdx !== -1) return seg.slice(0, mqIdx);
99
- // Strip optional query `:?...:` suffix
100
- const oqIdx = seg.indexOf(":?");
101
- if (oqIdx !== -1) return seg.slice(0, oqIdx);
102
- return seg;
103
- }
104
-
105
- /**
106
- * Extract mandatory path segments from a UI5 route pattern.
107
- *
108
- * Splits on `/`, strips inline query suffixes, then drops empty segments,
109
- * standalone optional (`:param:`), and rest (`:param*:`) segments.
110
- */
111
- function patternSegments(pattern: string): string[] {
112
- return pattern
113
- .split("/")
114
- .map(stripInlineQuery)
115
- .filter((seg) => seg !== "" && !OPTIONAL_OR_REST_SEGMENT.test(seg));
116
- }
117
-
118
- /**
119
- * Check if `ancestorPattern` is a URL-tree ancestor of `candidatePattern`.
120
- *
121
- * Both patterns are reduced to their mandatory path segments and compared
122
- * positionally. Mandatory parameter segments (`{paramA}`, `{paramB}`) are
123
- * treated as equivalent regardless of name, so `employees/{empId}` is
124
- * recognized as an ancestor of `employees/{id}/resume`.
125
- */
126
- function isPatternAncestor(ancestorPattern: string, candidatePattern: string): boolean {
127
- if (ancestorPattern === "") return true;
128
- const ancestorSegments = patternSegments(ancestorPattern);
129
- if (ancestorSegments.length === 0) return false;
130
- const candidateSegments = patternSegments(candidatePattern);
131
- if (candidateSegments.length <= ancestorSegments.length) return false;
132
- return ancestorSegments.every((seg, i) => {
133
- const candidateSeg = candidateSegments[i];
134
- if (seg === candidateSeg) return true;
135
- // Treat any two mandatory parameter segments as equivalent
136
- return seg.startsWith("{") && candidateSeg.startsWith("{");
137
- });
138
- }
139
-
140
- /** Parsed guard declaration from the manifest `guards` block. */
141
- interface GuardDescriptor {
142
- readonly route: string; // "*" for global, route name for per-route
143
- readonly type: "enter" | "leave";
144
- readonly modulePath: string;
145
- readonly name: string;
146
- readonly exportKey?: string;
147
- }
148
-
149
- /**
150
- * Resolve a guard module path to a slash-separated AMD module path.
151
- *
152
- * Inspired by `sap.ui.core.routing.Target._getEffectiveObjectName()`,
153
- * which skips namespace prepending for `"module:"`-prefixed paths. This
154
- * function goes further: it also converts dots to slashes in a single
155
- * step, so both dot notation (`module:some.lib.guard`) and slash
156
- * notation (`module:some/lib/guard`) are accepted.
157
- *
158
- * - Paths prefixed with `"module:"` are treated as absolute (the prefix
159
- * is stripped, dots become slashes).
160
- * - All other paths are prefixed with the component namespace, then dots
161
- * become slashes.
162
- */
163
- function resolveGuardModulePath(dotPath: string, componentNamespace: string): string {
164
- if (dotPath.startsWith("module:")) {
165
- return dotPath.slice("module:".length).replace(/\./g, "/");
166
- }
167
- const fullDotPath = componentNamespace ? componentNamespace + "." + dotPath : dotPath;
168
- return fullDotPath.replace(/\./g, "/");
169
- }
170
-
171
- /**
172
- * Split a manifest guard entry on the first `#` to separate the module path
173
- * from an optional export key, then derive a human-readable guard name.
174
- */
175
- function parseGuardEntry(
176
- entry: string,
177
- componentNamespace: string,
178
- ): { modulePath: string; name: string; exportKey?: string } {
179
- const hashIndex = entry.indexOf("#");
180
- const rawPath = hashIndex === -1 ? entry : entry.slice(0, hashIndex);
181
- const exportKey = hashIndex === -1 ? undefined : entry.slice(hashIndex + 1);
182
-
183
- const modulePath = resolveGuardModulePath(rawPath, componentNamespace);
184
-
185
- // Name: export key if present, otherwise last segment of the dot path
186
- const lastSegment = rawPath.split(".").pop() ?? rawPath;
187
- const name = exportKey ?? lastSegment;
188
-
189
- return { modulePath, name, exportKey };
190
- }
191
-
192
- interface ResolvedGuardExport {
193
- readonly name: string;
194
- readonly fn: GuardFn;
195
- }
196
-
197
- /** Log a warning about a guard module entry in the manifest. */
198
- function guardWarning(modulePath: string, detail: string): void {
199
- Log.warning(`guardRouter.guards: "${modulePath}" ${detail}`, undefined, LOG_COMPONENT);
200
- }
201
-
202
- /**
203
- * Detect the export shape of a loaded guard module and extract guard functions.
204
- *
205
- * Shapes:
206
- * - function → single guard
207
- * - Array → ordered guards (non-functions warned and skipped)
208
- * - plain object → named guards in key order (non-functions warned and skipped)
209
- *
210
- * When `exportKey` is set, only the matching export is returned.
211
- * When `exportKey` is set on a function export, the key is ignored with a debug warning.
212
- */
213
- function resolveModuleExports(
214
- moduleExport: unknown,
215
- modulePath: string,
216
- descriptorName: string,
217
- exportKey?: string,
218
- ): ResolvedGuardExport[] {
219
- const moduleName = modulePath.split("/").pop() ?? modulePath;
220
-
221
- // Shape 1: function
222
- if (typeof moduleExport === "function") {
223
- if (exportKey !== undefined) {
224
- Log.debug(
225
- `guardRouter.guards: "${modulePath}#${exportKey}" is a single function, ignoring export key`,
226
- undefined,
227
- LOG_COMPONENT,
228
- );
229
- }
230
- return [{ name: descriptorName, fn: moduleExport as GuardFn }];
231
- }
232
-
233
- // Shape 2: array
234
- if (Array.isArray(moduleExport)) {
235
- if (moduleExport.length === 0) {
236
- guardWarning(modulePath, "exported an empty array, skipping");
237
- return [];
238
- }
239
-
240
- if (exportKey !== undefined) {
241
- const index = parseInt(exportKey, 10);
242
- if (Number.isNaN(index) || index < 0 || index >= moduleExport.length) {
243
- guardWarning(modulePath, `#${exportKey} - index out of range, skipping`);
244
- return [];
245
- }
246
- const entry = moduleExport[index] as unknown;
247
- if (typeof entry !== "function") {
248
- guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
249
- return [];
250
- }
251
- return [{ name: `${moduleName}#${exportKey}`, fn: entry as GuardFn }];
252
- }
253
-
254
- const results: ResolvedGuardExport[] = [];
255
- for (let i = 0; i < moduleExport.length; i++) {
256
- const entry = moduleExport[i] as unknown;
257
- if (typeof entry !== "function") {
258
- guardWarning(modulePath, `[${i}] is not a function, skipping`);
259
- continue;
260
- }
261
- results.push({ name: `${moduleName}#${i}`, fn: entry as GuardFn });
262
- }
263
- return results;
264
- }
265
-
266
- // Shape 3: plain object
267
- if (isRecord(moduleExport)) {
268
- const entries = Object.entries(moduleExport);
269
- if (entries.length === 0) {
270
- guardWarning(modulePath, "exported an empty object, skipping");
271
- return [];
272
- }
273
-
274
- if (exportKey !== undefined) {
275
- let value: unknown = moduleExport[exportKey];
276
- let resolvedName = exportKey;
277
- if (value === undefined) {
278
- const index = parseInt(exportKey, 10);
279
- if (!Number.isNaN(index) && index >= 0 && index < entries.length) {
280
- const [key, val] = entries[index];
281
- value = val;
282
- resolvedName = key;
283
- }
284
- }
285
- if (value === undefined) {
286
- guardWarning(modulePath, `#${exportKey} - key not found, skipping`);
287
- return [];
288
- }
289
- if (typeof value !== "function") {
290
- guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
291
- return [];
292
- }
293
- return [{ name: resolvedName, fn: value as GuardFn }];
294
- }
295
-
296
- const results: ResolvedGuardExport[] = [];
297
- for (const [key, value] of entries) {
298
- if (typeof value !== "function") {
299
- guardWarning(modulePath, `.${key} is not a function, skipping`);
300
- continue;
301
- }
302
- results.push({ name: key, fn: value as GuardFn });
303
- }
304
- return results;
305
- }
306
-
307
- guardWarning(modulePath, "did not export a function, array, or plain object, skipping");
308
- return [];
129
+ /** How the browser got to the history entry that the route replaces (see {@link RedirectChainContext.direction}). */
130
+ readonly direction?: Direction;
131
+ /** Whether the URL showed a hash that never committed when `navTo()` wrote the hash (see {@link NavigationAttempt.restoreHash}). */
132
+ readonly restoreHash: boolean;
133
+ /** What the root hash changer showed before `navTo()` wrote the hash: the write is undone with it. */
134
+ readonly writtenOver?: string;
309
135
  }
310
136
 
311
137
  /**
312
- * Parse the `guards` block from the guardRouter config into an array of
313
- * {@link GuardDescriptor} objects.
314
- *
315
- * Handles:
316
- * - `"*"` key with `string[]` -> global enter guards
317
- * - Route name with `string[]` (shorthand) -> enter guards
318
- * - Route name with `{ enter: [...], leave: [...] }` -> enter + leave guards
319
- * - `"*"` with object form -> warn, treat enter as global
320
- * - `"*"` leave -> warn, skip (global leave guards not supported)
321
- * - Invalid entries -> warn, skip
138
+ * An allowed navigation waits for UI5 to write its hash. With component targets UI5 does that
139
+ * once the nested components are loaded, and never if one of them fails to load.
322
140
  */
323
- function parseGuardDescriptors(guards: unknown, componentNamespace: string): GuardDescriptor[] {
324
- if (!isRecord(guards)) {
325
- Log.warning("guardRouter.guards is not a plain object, skipping", JSON.stringify(guards), LOG_COMPONENT);
326
- return [];
327
- }
328
-
329
- const descriptors: GuardDescriptor[] = [];
330
-
331
- function pushEntries(entries: unknown[], route: string, type: "enter" | "leave", label: string): void {
332
- for (const entry of entries) {
333
- if (typeof entry !== "string" || entry.length === 0) {
334
- Log.warning(
335
- `guardRouter.guards${label}: invalid entry, skipping`,
336
- JSON.stringify(entry),
337
- LOG_COMPONENT,
338
- );
339
- continue;
340
- }
341
- const parsed = parseGuardEntry(entry, componentNamespace);
342
- descriptors.push({ route, type, ...parsed });
343
- }
344
- }
345
-
346
- for (const [key, value] of Object.entries(guards)) {
347
- if (Array.isArray(value)) {
348
- pushEntries(value, key, "enter", `["${key}"]`);
349
- } else if (isRecord(value)) {
350
- const config = value as ManifestRouteGuardConfig;
351
-
352
- if (key === "*" && config.leave !== undefined) {
353
- Log.warning(
354
- 'guardRouter.guards["*"].leave: global leave guards are not supported, skipping',
355
- undefined,
356
- LOG_COMPONENT,
357
- );
358
- }
359
-
360
- if (key === "*" && config.enter === undefined && config.leave !== undefined) {
361
- continue;
362
- }
363
-
364
- if (key === "*" && config.enter !== undefined) {
365
- Log.info('guardRouter.guards["*"]: object form; treating enter as global', undefined, LOG_COMPONENT);
366
- }
367
-
368
- if (Array.isArray(config.enter)) {
369
- pushEntries(config.enter, key, "enter", `["${key}"].enter`);
370
- }
371
-
372
- if (key !== "*" && Array.isArray(config.leave)) {
373
- pushEntries(config.leave, key, "leave", `["${key}"].leave`);
374
- }
375
- } else {
376
- Log.warning(
377
- `guardRouter.guards["${key}"]: expected string[] or { enter?, leave? }, skipping`,
378
- JSON.stringify(value),
379
- LOG_COMPONENT,
380
- );
381
- }
382
- }
383
-
384
- return descriptors;
141
+ interface PhaseAwaitingHash {
142
+ readonly kind: "awaitingHash";
143
+ /** The phase that commits the navigation when `parse()` receives its hash. */
144
+ readonly commit: PhaseCommitting;
385
145
  }
386
146
 
387
- interface ResolvedGuardRouterOptions {
388
- readonly unknownRouteRegistration: UnknownRouteRegistrationPolicy;
389
- readonly navToPreflight: NavToPreflightMode;
390
- readonly guardLoading: GuardLoading;
391
- readonly inheritance: Inheritance;
147
+ /** A navigation that did not commit waits for the URL to be back before it settles. */
148
+ interface PhaseRestoring {
149
+ readonly kind: "restoring";
150
+ readonly result: NavigationResult;
151
+ /** Whether the previous hash is written once UI5 has reported the hash change to every router. */
152
+ readonly awaitsReport?: true;
153
+ /** What a redirect to the route that is shown still has to do once the navigation has settled. */
154
+ readonly whenBack?: () => void;
392
155
  }
393
156
 
394
- const DEFAULT_OPTIONS: ResolvedGuardRouterOptions = {
395
- unknownRouteRegistration: "warn",
396
- navToPreflight: "guard",
397
- guardLoading: "lazy",
398
- inheritance: "none",
399
- };
400
-
401
- function applyOption<K extends keyof ResolvedGuardRouterOptions>(
402
- raw: Record<string, unknown>,
403
- key: K,
404
- guard: (v: unknown) => v is ResolvedGuardRouterOptions[K],
405
- target: { -readonly [P in keyof ResolvedGuardRouterOptions]: ResolvedGuardRouterOptions[P] },
406
- ): void {
407
- if (raw[key] !== undefined) {
408
- if (guard(raw[key])) {
409
- target[key] = raw[key] as ResolvedGuardRouterOptions[K];
410
- } else {
411
- Log.warning(`guardRouter.${key} has invalid value, using default`, JSON.stringify(raw[key]), LOG_COMPONENT);
412
- }
413
- }
414
- }
157
+ type RouterPhase = PhaseIdle | PhaseEvaluating | PhaseCommitting | PhaseAwaitingHash | PhaseRestoring;
415
158
 
416
- function normalizeGuardRouterOptions(raw: unknown): ResolvedGuardRouterOptions {
417
- if (!isRecord(raw)) {
418
- if (raw !== undefined) {
419
- Log.warning("guardRouter config is not a plain object, using defaults", JSON.stringify(raw), LOG_COMPONENT);
420
- }
421
- return DEFAULT_OPTIONS;
422
- }
423
-
424
- const result = { ...DEFAULT_OPTIONS };
425
- applyOption(raw, "unknownRouteRegistration", isUnknownRouteRegistrationPolicy, result);
426
- applyOption(raw, "navToPreflight", isNavToPreflightMode, result);
427
- applyOption(raw, "guardLoading", isGuardLoading, result);
428
- applyOption(raw, "inheritance", isInheritance, result);
429
- return result;
430
- }
159
+ const IDLE: PhaseIdle = { kind: "idle" };
431
160
 
432
161
  /** Maximum number of hops in a redirect chain before it is treated as a loop. */
433
162
  const MAX_REDIRECT_DEPTH = 10;
@@ -438,12 +167,19 @@ interface RedirectChainContext {
438
167
  visited: Set<string>;
439
168
  /** Hash of the originally attempted navigation (for settlement / hash restore). */
440
169
  readonly attemptedHash: string | undefined;
441
- /** Whether to restore the hash on block (true for parse path, false for preflight). */
170
+ /** Whether to restore the hash on block (see {@link NavigationAttempt.restoreHash}). */
442
171
  readonly restoreHash: boolean;
443
172
  /** Original source route (the route the user occupies). */
444
173
  readonly fromRoute: string;
445
174
  /** Original source hash (the hash the user occupies). */
446
175
  readonly fromHash: string;
176
+ /** Whether the target replaces the current history entry: as the `navTo()` call asked, always after a hash change. */
177
+ readonly replace: boolean | undefined;
178
+ /**
179
+ * How the browser got to the history entry that the target replaces, for the title history
180
+ * of UI5 (see {@link Router._alignTitleHistory}); `undefined` after `navTo()` or `parse()`.
181
+ */
182
+ readonly direction: Direction | undefined;
447
183
  /** Shared AbortSignal from the original navigation. */
448
184
  readonly signal: AbortSignal;
449
185
  /** Shared generation counter from the original navigation. */
@@ -460,8 +196,8 @@ interface RedirectChainContext {
460
196
  * loading, or event firing occurs.
461
197
  *
462
198
  * Two entry points feed the same pipeline:
463
- * - `navTo()` runs guards as a preflight check. Blocked or redirected
464
- * navigations never change the hash or push history entries.
199
+ * - `navTo()` runs guards as a preflight check. A blocked navigation
200
+ * never changes the hash; a redirected one only writes its final target.
465
201
  * - `parse()` runs guards as a fallback for browser back/forward, URL
466
202
  * bar entry, and direct hash changes where the hash has already changed
467
203
  * before guards can intercept.
@@ -477,80 +213,167 @@ interface RedirectChainContext {
477
213
  * @extends sap.m.routing.Router
478
214
  */
479
215
  export default class Router extends MobileRouter implements GuardRouter {
480
- private _options: ResolvedGuardRouterOptions = DEFAULT_OPTIONS;
216
+ private _options: ResolvedGuardRouterOptions;
481
217
  private _pipeline = new GuardPipeline();
482
218
  private _currentRoute = "";
483
219
  private _currentHash: string | null = null;
484
220
  private _phase: RouterPhase = IDLE;
485
221
  private _parseGeneration = 0;
486
222
  private _suppressedHash: string | null = null;
223
+ /** How to undo the hash change of the pending navigation (see {@link _undoHashChange}). */
224
+ private _undo: HashChangeUndo | null = null;
225
+ /** The hash that the hash changer of this router is reporting, until `parse()` receives it. */
226
+ private _reportedHash: unknown = null;
227
+ /** The hash that the hash changer of this router reported last, reports that are out of date aside. */
228
+ private _lastReport: unknown = null;
229
+ /** Whether the hash changer shows a later hash than the one it is reporting (see {@link _onHashReported}). */
230
+ private _reportOutdated = false;
231
+ /** The global hash changer that {@link _onRootHashChanged} is attached to, behind the listener of UI5 that informs the routers. */
232
+ private _rootHashChanger: HashChanger | null = null;
233
+ /** The route that was current when the router stopped: `initialize(true)` resumes it, as UI5 does. */
234
+ private _stoppedRoute = "";
487
235
  private _settlementResolvers: ((result: NavigationResult) => void)[] = [];
488
236
  private _lastSettlement: NavigationResult | null = null;
489
- private _pendingGuardDescriptors: GuardDescriptor[] = [];
490
- private _sourceDescriptors: GuardDescriptor[] = [];
237
+ private _pendingGuardDescriptors: GuardDescriptor[];
238
+ private _sourceDescriptors: ManifestGuardDescriptor[] = [];
239
+ /** The manifest guards registered for a route, by which `addRoute()` places the guards a route inherits then. */
240
+ private _manifestGuards: { descriptor: ManifestGuardDescriptor; fn: GuardFn }[] = [];
491
241
  private _destroyed = false;
492
- private _manifestMeta = new Map<string, Readonly<Record<string, unknown>>>();
493
- private _runtimeMeta = new Map<string, Readonly<Record<string, unknown>>>();
494
- private _resolvedMetaCache = new Map<string, Readonly<Record<string, unknown>>>();
495
- private _routeNames: string[] = [];
496
-
497
- constructor(...args: ConstructorParameters<typeof MobileRouter>) {
498
- const [routes, config, owner, ...rest] = args;
499
- const rawConfig = config as Record<string, unknown> | undefined;
500
- const isRecordConfig = isRecord(rawConfig);
501
- const { guardRouter, ...cleanConfig } = isRecordConfig ? rawConfig : ({} as Record<string, unknown>);
502
- super(routes, isRecordConfig ? (cleanConfig as typeof config) : config, owner, ...rest);
503
- this._options = normalizeGuardRouterOptions(guardRouter);
504
-
505
- // Collect route names from the constructor's routes parameter for pattern-tree traversal.
506
- if (Array.isArray(routes)) {
507
- this._routeNames = routes
508
- .filter((r): r is { name: string } => isRecord(r) && typeof r.name === "string")
509
- .map((r) => r.name);
510
- } else if (isRecord(routes)) {
511
- this._routeNames = Object.keys(routes);
242
+ /** What UI5 itself wrote to `_bMatchingProcessStarted` (see {@link _mirrorMatchingProcess}). */
243
+ private _nativeMatching = false;
244
+ /** Promises that wait for the `routeMatched` of a match that has not started (see {@link attachRouteMatched}). */
245
+ private _matchWaiters: (() => void)[] = [];
246
+ /**
247
+ * Set while block-mode guard modules load; `start` says whether to initialize once they have,
248
+ * `ignoreInitialHash` is the argument of the `initialize()` call that asked for it.
249
+ */
250
+ private _blockLoad: { start: boolean; ignoreInitialHash?: boolean } | null = null;
251
+ private _meta: RouteMetaStore;
252
+ /** Recorded by `addRoute()`, which the UI5 constructor calls before field setup; `declare` keeps field setup from resetting it. */
253
+ declare private _routeNames: string[];
254
+ /** Routes that also match when an earlier route has matched the hash (`greedy: true`). */
255
+ declare private _greedyRouteNames: string[];
256
+ private readonly _ownerComponent: UIComponent | undefined;
257
+
258
+ constructor(routes?: object | object[], config?: GuardRouterConfig, owner?: UIComponent, targetsConfig?: object);
259
+ constructor(
260
+ routes?: object | object[],
261
+ config?: GuardRouterConfig,
262
+ owner?: UIComponent,
263
+ ...rest: [targetsConfig?: object]
264
+ ) {
265
+ const isRecordConfig = isRecord(config);
266
+ const guardRouter = isRecordConfig ? config.guardRouter : undefined;
267
+ // UI5 passes more than its types declare: after the targets config comes the
268
+ // hash changer of a component that is loaded as a routing target.
269
+ super(routes, isRecordConfig ? withoutGuardRouter(config) : config, owner, ...rest);
270
+ this._ownerComponent = owner;
271
+ // A config without routes has made no addRoute() call.
272
+ this._routeNames ??= [];
273
+ this._greedyRouteNames ??= [];
274
+ this._mirrorMatchingProcess();
275
+ let componentNamespace = "";
276
+ const appConfig: unknown = owner?.getManifestEntry("sap.app");
277
+ if (isRecord(appConfig) && typeof appConfig.id === "string") {
278
+ componentNamespace = appConfig.id;
512
279
  }
280
+ const parsed = parseGuardRouterConfig(guardRouter, componentNamespace);
281
+ this._options = parsed.options;
282
+ this._meta = new RouteMetaStore(
283
+ parsed.routeMeta,
284
+ this._options.inheritance === "pattern-tree" ? () => this._collectRoutePatterns() : null,
285
+ );
286
+ this._pendingGuardDescriptors = parsed.guards;
513
287
 
514
- if (isRecord(guardRouter) && guardRouter.routeMeta !== undefined) {
515
- if (isRecord(guardRouter.routeMeta)) {
516
- for (const [routeName, meta] of Object.entries(guardRouter.routeMeta)) {
517
- if (isRecord(meta)) {
518
- this._manifestMeta.set(routeName, Object.freeze({ ...meta }));
519
- } else {
520
- Log.warning(
521
- `guardRouter.routeMeta["${routeName}"]: expected object, skipping`,
522
- JSON.stringify(meta),
523
- LOG_COMPONENT,
524
- );
525
- }
526
- }
527
- } else {
528
- Log.warning(
529
- "guardRouter.routeMeta: expected object, skipping",
530
- JSON.stringify(guardRouter.routeMeta),
531
- LOG_COMPONENT,
532
- );
533
- }
288
+ // Fire-and-forget preload hint: a module cached by initialize()
289
+ // needs no async load on navigation (see _registerLazyGuards).
290
+ // Block mode loads modules itself in initialize().
291
+ if (this._options.guardLoading === "lazy") {
292
+ const uniquePaths = [...new Set(this._pendingGuardDescriptors.map((d) => d.modulePath))];
293
+ // A failed preload is reported when the guard runs: its lazy load warns
294
+ // and the navigation settles as Error.
295
+ sap.ui.require(uniquePaths, undefined, () => {});
534
296
  }
297
+ }
535
298
 
536
- if (isRecord(guardRouter) && guardRouter.guards !== undefined) {
537
- let componentNamespace = "";
538
- if (owner) {
539
- const appConfig = owner.getManifestEntry("sap.app") as Record<string, unknown> | undefined;
540
- if (isRecord(appConfig) && typeof appConfig.id === "string") {
541
- componentNamespace = appConfig.id;
542
- }
543
- }
544
- this._pendingGuardDescriptors = parseGuardDescriptors(guardRouter.guards, componentNamespace);
545
-
546
- // Fire-and-forget preload hint: warm the module cache so lazy
547
- // wrappers resolve synchronously on first navigation.
548
- // Block mode loads modules itself in initialize().
549
- if (this._pendingGuardDescriptors.length > 0 && this._options.guardLoading === "lazy") {
550
- const uniquePaths = [...new Set(this._pendingGuardDescriptors.map((d) => d.modulePath))];
551
- sap.ui.require(uniquePaths);
552
- }
299
+ /**
300
+ * Report a navigation that waits for async guards as a route match in progress, through the
301
+ * UI5-private member `_bMatchingProcessStarted` of `sap.ui.core.routing.Router`. UI5 reads it
302
+ * to tell whether the router of a nested component is still matching; without this, a parent
303
+ * route would count the component as displayed before its first route matched. The router does
304
+ * not write the member: it replaces it with an accessor that keeps what UI5 writes in
305
+ * {@link _nativeMatching} and also reads `true` while a navigation is postponed.
306
+ *
307
+ * See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
308
+ * relies on, and docs/reference/upstream-parity.md for the tests that pin it.
309
+ */
310
+ private _mirrorMatchingProcess(): void {
311
+ Object.defineProperty(this, "_bMatchingProcessStarted", {
312
+ get: () => this._isMatching(),
313
+ set: (matching: boolean) => {
314
+ this._nativeMatching = matching;
315
+ },
316
+ });
317
+ }
318
+
319
+ /** Whether a route match is in progress: in UI5, or postponed until async guards have decided. */
320
+ private _isMatching(): boolean {
321
+ return this._nativeMatching || (this._phase.kind === "evaluating" && this._phase.postponed === true);
322
+ }
323
+
324
+ /**
325
+ * Attach an event handler for the `routeMatched` event, as the native router does. In addition,
326
+ * remember a Promise resolve function ({@link isPromiseResolver}) that is subscribed while the
327
+ * router is not initialized or a match is in progress: that is how a UI5 component target
328
+ * waits for this router. UI5 relies on a match always ending in `routeMatched`, which a
329
+ * navigation that guards block, fail or cancel never fires, so {@link _settleMatchWaiters}
330
+ * resolves the Promise then. Application code that subscribes a Promise resolve function under
331
+ * the same condition is treated alike.
332
+ *
333
+ * See docs/reference/architecture.md ("UI5 Internals the Router Relies On") for the UI5 code this
334
+ * relies on, and docs/reference/upstream-parity.md for the tests that pin it.
335
+ *
336
+ * @override sap.ui.core.routing.Router#attachRouteMatched
337
+ * @since 1.7.0
338
+ */
339
+ override attachRouteMatched(
340
+ oData: object,
341
+ fnFunction: (evt: Router$RouteMatchedEvent) => void,
342
+ oListener?: object,
343
+ ): this;
344
+ override attachRouteMatched(fnFunction: (evt: Router$RouteMatchedEvent) => void, oListener?: object): this;
345
+ override attachRouteMatched(
346
+ oData: object,
347
+ fnFunction: (evt: Router$RouteMatchedEvent) => void,
348
+ oListener?: object,
349
+ ): this {
350
+ if (isPromiseResolver(oData) && (!this.isInitialized() || this._isMatching())) {
351
+ this._matchWaiters.push(oData);
553
352
  }
353
+ // The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
354
+ return super.attachRouteMatched(oData, fnFunction, oListener);
355
+ }
356
+
357
+ /**
358
+ * Decide what becomes of the Promises that wait for a `routeMatched`
359
+ * (see {@link attachRouteMatched}). Runs in a microtask after a settlement, so that a commit
360
+ * has reached `super.parse()` and a navigation that supersedes the settled one has started:
361
+ * - A navigation waits for async guards: the Promises keep waiting, for its settlement.
362
+ * - UI5 is matching a route: the Promises are forgotten, the `routeMatched` of that match
363
+ * resolves them. If UI5 never fires it, because the display of a target fails, they wait
364
+ * forever, as with the native router.
365
+ * - Otherwise no match is coming, and the Promises are resolved.
366
+ *
367
+ * A navigation that starts after this microtask is not waited for. A Promise that is resolved
368
+ * here stays subscribed, and UI5 calls it again with the next `routeMatched`, which has no
369
+ * effect on a Promise.
370
+ */
371
+ private _settleMatchWaiters(): void {
372
+ if (this._phase.kind === "evaluating" && this._phase.postponed) return;
373
+ const waiters = this._matchWaiters;
374
+ this._matchWaiters = [];
375
+ if (this._nativeMatching) return;
376
+ for (const resolve of waiters) resolve();
554
377
  }
555
378
 
556
379
  /**
@@ -560,127 +383,192 @@ export default class Router extends MobileRouter implements GuardRouter {
560
383
  * In `"lazy"` mode, lazy wrappers are registered synchronously
561
384
  * and `super.initialize()` is called immediately.
562
385
  *
386
+ * While block-mode modules load, the router is not initialized yet:
387
+ * calling `initialize()` again changes nothing, and `stop()` cancels
388
+ * the pending start until `initialize()` is called again.
389
+ *
390
+ * @param bIgnoreInitialHash - Whether the current hash is left unparsed, as in the native router (since 1.7.0).
563
391
  * @override sap.ui.core.routing.Router#initialize
564
392
  * @since 1.0.1
565
393
  */
566
- override initialize(): this {
394
+ override initialize(bIgnoreInitialHash?: boolean): this {
395
+ if (this._blockLoad) {
396
+ if (!this._blockLoad.start) {
397
+ this._blockLoad.start = true;
398
+ this._blockLoad.ignoreInitialHash = bIgnoreInitialHash;
399
+ }
400
+ return this;
401
+ }
567
402
  if (this._pendingGuardDescriptors.length === 0) {
568
- return super.initialize();
403
+ return this._start(bIgnoreInitialHash);
569
404
  }
570
405
 
571
- const descriptors = this._pendingGuardDescriptors;
406
+ const descriptors = this._pendingGuardDescriptors.map((source) => ({ ...source, source }));
572
407
  this._pendingGuardDescriptors = [];
573
408
  this._sourceDescriptors = descriptors;
574
409
 
575
410
  const expandedDescriptors =
576
- this._options.inheritance === "pattern-tree" ? this._expandGuardDescriptors(descriptors) : descriptors;
411
+ this._options.inheritance === "pattern-tree"
412
+ ? expandToDescendants(descriptors, this._collectRoutePatterns())
413
+ : descriptors;
577
414
 
578
415
  if (this._options.guardLoading === "lazy") {
579
416
  this._registerLazyGuards(expandedDescriptors);
580
- return super.initialize();
417
+ return this._start(bIgnoreInitialHash);
581
418
  }
582
419
 
583
- // "block" mode: load all modules, then initialize.
584
- // Guard against destroy() being called while modules are still loading.
585
- this._loadAndRegisterGuards(expandedDescriptors)
586
- .then(() => {
587
- if (!this._destroyed) super.initialize();
588
- })
589
- .catch((err: unknown) => {
590
- if (this._destroyed) return;
591
- Log.error(
592
- "guardRouter.guards: module loading failed, initializing without manifest guards",
593
- String(err),
594
- LOG_COMPONENT,
595
- );
596
- super.initialize();
597
- });
420
+ // "block" mode: load all modules, then register their guards in declaration order
421
+ // and initialize. Load and registration failures are logged per module and never
422
+ // reject. A router destroyed while modules load stays destroyed.
423
+ const blockLoad = { start: true, ignoreInitialHash: bIgnoreInitialHash };
424
+ this._blockLoad = blockLoad;
425
+ void loadGuardModules(expandedDescriptors).then((results) => {
426
+ this._blockLoad = null;
427
+ if (this._destroyed) return;
428
+ for (const { descriptor, guards } of results) {
429
+ for (const fn of guards) this._registerManifestGuard(descriptor, fn);
430
+ }
431
+ if (blockLoad.start) this._start(blockLoad.ignoreInitialHash);
432
+ });
433
+ return this;
434
+ }
435
+
436
+ /**
437
+ * Start the native router. With `ignoreInitialHash` it parses nothing and resumes the route
438
+ * that was displayed when the router stopped. That route is the current one again, on the hash
439
+ * that the URL shows now, so that its leave guards run and a blocked hash change returns to it.
440
+ */
441
+ private _start(ignoreInitialHash?: boolean): this {
442
+ // UI5 only warns about a router that is initialized already.
443
+ const starting = !this.isInitialized();
444
+ if (starting) {
445
+ // Before the listener of UI5 that calls parse(), which initialize() attaches.
446
+ this.getHashChanger().attachEvent("hashChanged", this._onHashReported, this);
447
+ // After the listener of UI5 that informs the routers, which is attached with the hash
448
+ // changer of the first router: UI5 has reported a hash change to every router when
449
+ // this one runs.
450
+ this._rootHashChanger = HashChanger.getInstance();
451
+ this._rootHashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
452
+ }
453
+ super.initialize(ignoreInitialHash);
454
+ if (starting && ignoreInitialHash) {
455
+ // UI5 has reset the hash of the hash changer if a target was displayed without a route.
456
+ const shownHash: string | undefined = this.getHashChanger().getHash();
457
+ this._currentRoute = this._stoppedRoute;
458
+ this._currentHash = shownHash ?? null;
459
+ }
598
460
  return this;
599
461
  }
600
462
 
463
+ /**
464
+ * The hash changer of this router reports a hash change: `parse()` is called with it next.
465
+ *
466
+ * The report is out of date if the hash changer shows a later hash by now, one that it has
467
+ * reported to this router already. That happens to a router that shares its hash changer, as
468
+ * the routers of all components that are not routing targets do: a router that is informed
469
+ * first redirects the hash, UI5 reports the target to every router, and only then the hash
470
+ * that was redirected to the routers that are informed later. A hash changer that reports
471
+ * while a parent router collects the hashes of a navigation shows no hash at all.
472
+ */
473
+ private _onHashReported(event: HashChangerBase$HashChangedEvent): void {
474
+ // A string, which the UI5 types declare as an object.
475
+ const newHash: unknown = event.getParameter("newHash");
476
+ const shown: unknown = this.getHashChanger().getHash();
477
+ this._reportedHash = newHash;
478
+ this._reportOutdated = shown !== newHash && shown === this._lastReport;
479
+ if (!this._reportOutdated) this._lastReport = newHash;
480
+ }
481
+
482
+ /**
483
+ * UI5 has reported a hash change to every router. The event tells what the URL showed before
484
+ * the change, which is what undoes it. A snapshot of the URL taken at any other time would not
485
+ * do: the URL also changes without an event, as when the Fiori launchpad puts it back after
486
+ * a cross-app navigation that the user cancelled. A navigation that waited for this to put
487
+ * the URL back does so now (see {@link _undoHashChange}).
488
+ */
489
+ private _onRootHashChanged(event: HashChangerBase$HashChangedEvent): void {
490
+ // A string, which the UI5 types declare as an object.
491
+ const newHash: unknown = event.getParameter("newHash");
492
+ // Only the first hash change that the page reports has no previous hash.
493
+ const oldHash = event.getParameter("oldHash") ?? "";
494
+ const hashChanger = HashChanger.getInstance();
495
+ if (hashChanger === this._rootHashChanger) {
496
+ this._completeUndo(newHash, oldHash);
497
+ return;
498
+ }
499
+ // The global hash changer was replaced (HashChanger.replaceHashChanger(), as the shell of
500
+ // the Fiori launchpad does). UI5 has moved this listener to the new one, in front of its
501
+ // listener that informs the routers. From the next hash change on it runs behind again;
502
+ // for this one, the routers are informed once this listener has returned.
503
+ hashChanger.detachEvent("hashChanged", this._onRootHashChanged, this);
504
+ hashChanger.attachEvent("hashChanged", this._onRootHashChanged, this);
505
+ this._rootHashChanger = hashChanger;
506
+ queueMicrotask(() => this._completeUndo(newHash, oldHash));
507
+ }
508
+
509
+ /**
510
+ * Tell the undo of the pending navigation what the URL showed before the hash change
511
+ * `newHash`, and put the URL back if the navigation waited for that.
512
+ */
513
+ private _completeUndo(newHash: unknown, oldHash: string): void {
514
+ const undo = this._undo;
515
+ if (!undo || undo.first !== newHash) return;
516
+ undo.fullHash ??= oldHash;
517
+ if (this._phase.kind === "restoring" && this._phase.awaitsReport) this._replaceFullHash(undo.fullHash);
518
+ }
519
+
601
520
  /**
602
521
  * Add a route dynamically and integrate it into pattern-tree inheritance.
603
522
  *
604
523
  * Appends the route name to the internal route list so that
605
524
  * `_collectRoutePatterns()` includes it in subsequent inheritance
606
525
  * lookups, clears the metadata cache, and registers any inherited
607
- * manifest guards when `inheritance` is `"pattern-tree"`.
526
+ * manifest guards when `inheritance` is `"pattern-tree"`: on every
527
+ * route, ancestor guards still run before descendant guards.
608
528
  *
609
529
  * @param oConfig - Route configuration object as defined by `sap.ui.core.routing.Route`.
610
- * @param rest - Additional arguments forwarded to the parent `addRoute`.
530
+ * @param oParent - Optional parent route, forwarded to the parent `addRoute`.
611
531
  * @override sap.ui.core.routing.Router#addRoute
612
532
  * @since 1.6.0
613
533
  */
614
- override addRoute(oConfig: $RouteSettings, ...rest: unknown[]): void {
615
- // @ts-expect-error -- oParent is required in the type declaration but optional at runtime
616
- super.addRoute(oConfig, ...rest);
617
-
618
- // Skip when called by the parent constructor before field initializers have run.
619
- // Routes from the constructor args are captured in _routeNames by the constructor body.
620
- if (!this._routeNames) return;
534
+ override addRoute(oConfig: $RouteSettings, oParent?: Route): void {
535
+ super.addRoute(oConfig, oParent);
621
536
 
622
537
  const name = oConfig.name;
623
- if (typeof name !== "string") return;
538
+ this._routeNames ??= [];
539
+ this._greedyRouteNames ??= [];
624
540
  if (this._routeNames.includes(name)) return;
625
541
 
626
542
  this._routeNames.push(name);
627
- this._resolvedMetaCache.clear();
543
+ if (oConfig.greedy) this._greedyRouteNames.push(name);
544
+ // The UI5 constructor adds the routes of the config before this constructor sets up the rest.
545
+ if (!this._meta) return;
546
+ this._meta.invalidate();
628
547
 
629
548
  if (this._options.inheritance !== "pattern-tree") return;
630
- if (this._sourceDescriptors.length === 0) return;
631
549
 
632
- const route = this.getRoute(name);
633
- if (!route) return;
634
- const newPattern = route.getPattern();
635
- if (newPattern === undefined) return;
636
-
637
- const newDescriptors = this._expandGuardDescriptorsForNewRoute(name, newPattern);
638
- if (newDescriptors.length === 0) return;
550
+ const patterns = this._collectRoutePatterns();
551
+ const declared = byRouteDepth(this._sourceDescriptors, new Map(patterns.map((r) => [r.name, r.pattern])));
552
+ const rankOf = (descriptor: ManifestGuardDescriptor): number =>
553
+ declared.findIndex((entry) => entry.source === descriptor.source);
639
554
 
640
555
  // Always use lazy registration: if the module was loaded during
641
556
  // initialize() (block mode), the sync cache probe succeeds immediately.
642
557
  // This avoids an async gap between addRoute() and the first navigation.
643
- this._registerLazyGuards(newDescriptors);
644
- }
645
-
646
- /**
647
- * Expand manifest guard descriptors for a single newly added route.
648
- *
649
- * For each source descriptor whose route is an ancestor of the new
650
- * route's pattern, emits a copy targeting the new route. Also emits
651
- * copies for existing routes that are descendants of the new route
652
- * (in case the new route has declared guards). Sorted by depth.
653
- */
654
- private _expandGuardDescriptorsForNewRoute(newName: string, newPattern: string): GuardDescriptor[] {
655
- const result: GuardDescriptor[] = [];
656
-
657
- for (const descriptor of this._sourceDescriptors) {
658
- if (descriptor.route === "*") continue;
659
-
660
- if (descriptor.route !== newName) {
661
- // Check if the source descriptor's route is an ancestor of the new route.
662
- const ancestorRoute = this.getRoute(descriptor.route);
663
- const ancestorPattern = ancestorRoute?.getPattern();
664
- if (ancestorPattern !== undefined && isPatternAncestor(ancestorPattern, newPattern)) {
665
- result.push({ ...descriptor, route: newName });
666
- }
667
- } else {
668
- // The new route itself has a source descriptor: expand to existing descendants.
669
- for (const { name, pattern } of this._collectRoutePatterns()) {
670
- if (name === newName) continue;
671
- if (isPatternAncestor(newPattern, pattern)) {
672
- result.push({ ...descriptor, route: name });
673
- }
674
- }
675
- }
558
+ for (const descriptor of expandForNewRoute(this._sourceDescriptors, name, patterns)) {
559
+ // Ancestor guards run first: the new guards go before the manifest guards of the route
560
+ // that stem from an entry of a deeper route, or from a later entry of the same depth.
561
+ const rank = rankOf(descriptor);
562
+ const next = this._manifestGuards
563
+ .filter(
564
+ (guard) =>
565
+ guard.descriptor.route === descriptor.route &&
566
+ guard.descriptor.type === descriptor.type &&
567
+ rankOf(guard.descriptor) > rank,
568
+ )
569
+ .toSorted((a, b) => rankOf(a.descriptor) - rankOf(b.descriptor))[0];
570
+ for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn, next?.fn);
676
571
  }
677
-
678
- // Sort by pattern depth (ancestor guards run before descendant guards).
679
- return result.toSorted((a, b) => {
680
- const pa = this.getRoute(a.route)?.getPattern() ?? "";
681
- const pb = this.getRoute(b.route)?.getPattern() ?? "";
682
- return patternSegments(pa).length - patternSegments(pb).length;
683
- });
684
572
  }
685
573
 
686
574
  /**
@@ -722,34 +610,22 @@ export default class Router extends MobileRouter implements GuardRouter {
722
610
  */
723
611
  addRouteGuard(routeName: string, guard: GuardFn | RouteGuardConfig): this {
724
612
  if (isRouteGuardConfig(guard)) {
725
- if (!this._handleUnknownRouteRegistration(routeName, "addRouteGuard")) {
726
- return this;
727
- }
728
- let hasHandler = false;
729
-
730
- if (guard.beforeEnter !== undefined) {
731
- hasHandler = true;
732
- if (this._isFn(guard.beforeEnter, "addRouteGuard", routeName)) {
733
- this._pipeline.addEnterGuard(routeName, guard.beforeEnter);
734
- }
735
- }
736
- if (guard.beforeLeave !== undefined) {
737
- hasHandler = true;
738
- if (this._isFn(guard.beforeLeave, "addRouteGuard", routeName)) {
739
- this._pipeline.addLeaveGuard(routeName, guard.beforeLeave);
740
- }
741
- }
742
-
743
- if (!hasHandler) {
613
+ const { beforeEnter, beforeLeave } = guard;
614
+ if (beforeEnter === undefined && beforeLeave === undefined) {
744
615
  Log.info("addRouteGuard: config has no beforeEnter or beforeLeave", routeName, LOG_COMPONENT);
745
616
  return this;
746
617
  }
618
+ // As for a guard function: the route is checked only when something is registered.
619
+ const enter = beforeEnter !== undefined && this._isFn(beforeEnter, "addRouteGuard", routeName);
620
+ const leave = beforeLeave !== undefined && this._isFn(beforeLeave, "addRouteGuard", routeName);
621
+ if (!enter && !leave) return this;
622
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
623
+ if (enter) this._pipeline.addEnterGuard(routeName, beforeEnter);
624
+ if (leave) this._pipeline.addLeaveGuard(routeName, beforeLeave);
747
625
  return this;
748
626
  }
749
627
  if (!this._isFn(guard, "addRouteGuard", routeName)) return this;
750
- if (!this._handleUnknownRouteRegistration(routeName, "addRouteGuard")) {
751
- return this;
752
- }
628
+ this._handleUnknownRouteRegistration(routeName, "addRouteGuard");
753
629
  this._pipeline.addEnterGuard(routeName, guard);
754
630
  return this;
755
631
  }
@@ -795,9 +671,7 @@ export default class Router extends MobileRouter implements GuardRouter {
795
671
  */
796
672
  addLeaveGuard(routeName: string, guard: LeaveGuardFn): this {
797
673
  if (!this._isFn(guard, "addLeaveGuard", routeName)) return this;
798
- if (!this._handleUnknownRouteRegistration(routeName, "addLeaveGuard")) {
799
- return this;
800
- }
674
+ this._handleUnknownRouteRegistration(routeName, "addLeaveGuard");
801
675
  this._pipeline.addLeaveGuard(routeName, guard);
802
676
  return this;
803
677
  }
@@ -808,6 +682,7 @@ export default class Router extends MobileRouter implements GuardRouter {
808
682
  * UI5's native `navTo` has two signatures where the third parameter is either
809
683
  * `componentTargetInfo` (object) or `bReplace` (boolean). This method normalizes
810
684
  * both forms so the rest of `navTo` can work with a single set of variables.
685
+ * The options follow `bReplace`, or take its place when it is left out.
811
686
  */
812
687
  private _resolveNavToArgs(
813
688
  componentTargetInfoOrReplace?: Record<string, ComponentTargetParameters> | boolean,
@@ -822,15 +697,14 @@ export default class Router extends MobileRouter implements GuardRouter {
822
697
  // Short form: navTo(name, params, replace, options?)
823
698
  return {
824
699
  replace: componentTargetInfoOrReplace,
825
- guardOptions:
826
- typeof replaceOrOptions === "object" && replaceOrOptions !== null ? replaceOrOptions : undefined,
700
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : undefined,
827
701
  };
828
702
  }
829
703
  // Long form: navTo(name, params, componentTargetInfo, replace, options?)
830
704
  return {
831
705
  componentTargetInfo: componentTargetInfoOrReplace,
832
706
  replace: typeof replaceOrOptions === "boolean" ? replaceOrOptions : undefined,
833
- guardOptions: options,
707
+ guardOptions: typeof replaceOrOptions === "object" ? replaceOrOptions : options,
834
708
  };
835
709
  }
836
710
 
@@ -841,25 +715,20 @@ export default class Router extends MobileRouter implements GuardRouter {
841
715
  return false;
842
716
  }
843
717
 
844
- /**
845
- * Handle guard registration for a potentially unknown route.
846
- * Returns `true` if registration should proceed, `false` if not.
847
- */
848
- private _handleUnknownRouteRegistration(routeName: string, methodName: string): boolean {
849
- if (this.getRoute(routeName)) return true;
718
+ /** Apply the `unknownRouteRegistration` policy: warn or throw when the route is unknown. */
719
+ private _handleUnknownRouteRegistration(routeName: string, methodName: string, kept = "guard registered"): void {
720
+ if (this.getRoute(routeName)) return;
850
721
 
851
722
  switch (this._options.unknownRouteRegistration) {
852
723
  case "ignore":
853
- return true;
724
+ return;
854
725
  case "throw":
855
726
  throw new Error(
856
727
  `${methodName} called for unknown route "${routeName}". ` +
857
728
  `Set guardRouter.unknownRouteRegistration to "warn" or "ignore" to allow this.`,
858
729
  );
859
730
  case "warn":
860
- default:
861
- Log.warning(`${methodName}: unknown route, guard registered anyway`, routeName, LOG_COMPONENT);
862
- return true;
731
+ Log.warning(`${methodName}: unknown route, ${kept} anyway`, routeName, LOG_COMPONENT);
863
732
  }
864
733
  }
865
734
 
@@ -877,8 +746,6 @@ export default class Router extends MobileRouter implements GuardRouter {
877
746
  return this;
878
747
  }
879
748
 
880
- private static readonly _EMPTY_META: Readonly<Record<string, unknown>> = Object.freeze({});
881
-
882
749
  /**
883
750
  * Return the resolved metadata for a route.
884
751
  *
@@ -898,28 +765,9 @@ export default class Router extends MobileRouter implements GuardRouter {
898
765
  // Empty string is a valid root route name (initial state before first navigation)
899
766
  if (routeName !== "" && !this.getRoute(routeName)) {
900
767
  Log.warning("getRouteMeta: unknown route, returning empty metadata", routeName, LOG_COMPONENT);
901
- return Router._EMPTY_META;
902
- }
903
-
904
- // Cache hit
905
- const cached = this._resolvedMetaCache.get(routeName);
906
- if (cached) return cached;
907
-
908
- let result: Readonly<Record<string, unknown>>;
909
-
910
- if (this._options.inheritance === "pattern-tree") {
911
- result = this._resolveInheritedMeta(routeName);
912
- } else {
913
- result = this._resolveFlatMeta(routeName);
768
+ return EMPTY_META;
914
769
  }
915
-
916
- if (Object.keys(result).length === 0) {
917
- this._resolvedMetaCache.set(routeName, Router._EMPTY_META);
918
- return Router._EMPTY_META;
919
- }
920
-
921
- this._resolvedMetaCache.set(routeName, result);
922
- return result;
770
+ return this._meta.get(routeName);
923
771
  }
924
772
 
925
773
  /**
@@ -941,11 +789,8 @@ export default class Router extends MobileRouter implements GuardRouter {
941
789
  Log.warning("setRouteMeta: expected object, ignoring", routeName, LOG_COMPONENT);
942
790
  return this;
943
791
  }
944
- if (routeName !== "" && !this._handleUnknownRouteRegistration(routeName, "setRouteMeta")) {
945
- return this;
946
- }
947
- this._runtimeMeta.set(routeName, Object.freeze({ ...meta }));
948
- this._resolvedMetaCache.clear();
792
+ if (routeName !== "") this._handleUnknownRouteRegistration(routeName, "setRouteMeta", "metadata stored");
793
+ this._meta.set(routeName, meta);
949
794
  return this;
950
795
  }
951
796
 
@@ -957,13 +802,13 @@ export default class Router extends MobileRouter implements GuardRouter {
957
802
  * settlement result. Before any navigation has settled, it falls back to a
958
803
  * synthetic `Committed` result derived from the router's current route/hash
959
804
  * state. After `stop()`, that idle fallback reports empty route/hash values
960
- * until a new navigation settles.
805
+ * until a new navigation settles, or `initialize(true)` resumes the route.
961
806
  *
962
807
  * @returns Promise that resolves with a {@link NavigationResult} once the pipeline settles.
963
808
  * @since 1.2.0
964
809
  */
965
810
  navigationSettled(): Promise<NavigationResult> {
966
- if (this._phase.kind !== "evaluating") {
811
+ if (this._phase.kind === "idle" || this._phase.kind === "committing") {
967
812
  return Promise.resolve(
968
813
  this._lastSettlement ?? {
969
814
  status: NavigationOutcome.Committed,
@@ -983,7 +828,8 @@ export default class Router extends MobileRouter implements GuardRouter {
983
828
  * Fires synchronously after every guard pipeline settlement with
984
829
  * a {@link NavigationResult} payload. Unlike the one-shot
985
830
  * `navigationSettled()` Promise, this event fires for every
986
- * navigation outcome without re-registration.
831
+ * navigation outcome without re-registration. It does not fire for the
832
+ * navigation that `destroy()` cancels.
987
833
  *
988
834
  * @param oData - Application-specific payload passed to the handler as second argument.
989
835
  * @param fnFunction - The function to be called when the event occurs.
@@ -996,18 +842,17 @@ export default class Router extends MobileRouter implements GuardRouter {
996
842
  oListener?: object,
997
843
  ): this;
998
844
  attachNavigationSettled(fnFunction: (evt: Router$NavigationSettledEvent) => void, oListener?: object): this;
999
- attachNavigationSettled(oData: unknown, fnFunction?: unknown, oListener?: unknown): this {
1000
- this.attachEvent(
1001
- "navigationSettled",
1002
- oData as object,
1003
- fnFunction as (...args: unknown[]) => void,
1004
- oListener as object,
1005
- );
1006
- return this;
1007
- }
1008
-
1009
- /**
1010
- * Detach a previously attached `navigationSettled` event handler.
845
+ attachNavigationSettled(
846
+ oData: object,
847
+ fnFunction: (evt: Router$NavigationSettledEvent) => void,
848
+ oListener?: object,
849
+ ): this {
850
+ // The arguments go on as received: EventProvider#attachEvent tells the two call forms apart.
851
+ return this.attachEvent("navigationSettled", oData, fnFunction, oListener);
852
+ }
853
+
854
+ /**
855
+ * Detach a previously attached `navigationSettled` event handler.
1011
856
  *
1012
857
  * The passed parameters must match those used for registration with
1013
858
  * {@link #attachNavigationSettled} beforehand.
@@ -1017,7 +862,7 @@ export default class Router extends MobileRouter implements GuardRouter {
1017
862
  * @since 1.3.0
1018
863
  */
1019
864
  detachNavigationSettled(fnFunction: (evt: Router$NavigationSettledEvent) => void, oListener?: object): this {
1020
- this.detachEvent("navigationSettled", fnFunction as (...args: unknown[]) => void, oListener);
865
+ this.detachEvent("navigationSettled", fnFunction, oListener);
1021
866
  return this;
1022
867
  }
1023
868
 
@@ -1027,12 +872,23 @@ export default class Router extends MobileRouter implements GuardRouter {
1027
872
  */
1028
873
  private _flushSettlement(result: NavigationResult): void {
1029
874
  this._lastSettlement = result;
875
+ Log.debug(`Navigation settled: ${result.status}`, result.hash, LOG_COMPONENT);
876
+ // After the call that settled: by then a commit has reached super.parse(), and a navigation
877
+ // that supersedes this one has started.
878
+ queueMicrotask(() => this._settleMatchWaiters());
1030
879
  const resolvers = this._settlementResolvers;
1031
880
  this._settlementResolvers = [];
1032
881
  for (const resolve of resolvers) {
1033
882
  resolve(result);
1034
883
  }
1035
- this.fireEvent("navigationSettled", result);
884
+ // No handler runs while destroy() tears the router down; the native destroy() fires no event either.
885
+ if (this._destroyed) return;
886
+ try {
887
+ this.fireEvent("navigationSettled", result);
888
+ } catch (error) {
889
+ // A handler must not keep the router from finishing the navigation it reports.
890
+ Log.error("A navigationSettled handler threw", String(error), LOG_COMPONENT);
891
+ }
1036
892
  }
1037
893
 
1038
894
  /**
@@ -1041,12 +897,13 @@ export default class Router extends MobileRouter implements GuardRouter {
1041
897
  * For programmatic navigation, guards run BEFORE the hash changes.
1042
898
  * This prevents history pollution: blocked navigations never push a
1043
899
  * history entry, and redirected navigations go directly to the final
1044
- * target.
900
+ * target, which is written the way this call asked for (`bReplace`).
1045
901
  *
1046
- * Same-hash navigations are deduped: if the target hash matches
1047
- * `_currentHash`, any pending navigation is cancelled and the call
1048
- * returns without navigating. If it matches the in-flight attempt's
1049
- * hash, the in-flight preflight continues undisturbed.
902
+ * A `navTo()` to the committed hash changes no route of this router, so
903
+ * no guard runs: any pending navigation is cancelled and the call goes
904
+ * to the native `navTo()`, which sets or resets the hashes of nested
905
+ * components (`componentTargetInfo`). If the target matches the
906
+ * in-flight attempt's hash, the in-flight preflight continues undisturbed.
1050
907
  *
1051
908
  * When all guards are synchronous, the decision and the resulting
1052
909
  * hash change happen in the same tick. When any guard returns a
@@ -1055,7 +912,23 @@ export default class Router extends MobileRouter implements GuardRouter {
1055
912
  *
1056
913
  * Assumes `super.navTo()` calls `HashChanger.setHash()` which fires
1057
914
  * `hashChanged` synchronously, causing `parse()` to re-enter in the
1058
- * same call stack (validated by test).
915
+ * same call stack (validated by test). If the hash changer refuses the
916
+ * hash change, as the Fiori launchpad's navigation filter does when its
917
+ * dirty-state check stops it, nothing is committed and the navigation
918
+ * settles as `Blocked`.
919
+ *
920
+ * With component targets (`componentTargetInfo`) UI5 writes the hash
921
+ * later, once the nested components are loaded. The navigation commits
922
+ * and settles when `parse()` receives that hash. Until then it is
923
+ * pending: a navigation that supersedes it, `stop()` or `destroy()`
924
+ * settles it as `Cancelled`. That also ends a navigation whose hash UI5
925
+ * never writes, because a nested component failed to load or the router
926
+ * is not async.
927
+ *
928
+ * On a router that is not initialized (before `initialize()`, while
929
+ * block-mode guard modules load, after `stop()`) the call goes straight
930
+ * to the native `navTo()`, which only sets the hash or does nothing when
931
+ * stopped. The guards run when the router starts and parses the hash.
1059
932
  *
1060
933
  * @override sap.ui.core.routing.Router#navTo
1061
934
  * @since 1.0.1
@@ -1082,6 +955,11 @@ export default class Router extends MobileRouter implements GuardRouter {
1082
955
  replaceOrOptions?: boolean | GuardNavToOptions,
1083
956
  options?: GuardNavToOptions,
1084
957
  ): this {
958
+ // The guards are gone: code that awaited navigationSettled() may still call navTo().
959
+ if (this._destroyed) {
960
+ Log.warning("navTo: router is destroyed, ignoring", routeName, LOG_COMPONENT);
961
+ return this;
962
+ }
1085
963
  const { componentTargetInfo, replace, guardOptions } = this._resolveNavToArgs(
1086
964
  componentTargetInfoOrReplace,
1087
965
  replaceOrOptions,
@@ -1095,74 +973,89 @@ export default class Router extends MobileRouter implements GuardRouter {
1095
973
  return this;
1096
974
  }
1097
975
 
1098
- // Resolve the target hash so we can build a guard context.
1099
- // getURL() returns the hash pattern with parameters substituted.
976
+ // A router that does not listen to hash changes (not initialized, loading block-mode
977
+ // guards, or stopped) navigates like the native one: the guards run once it parses the hash.
978
+ if (!this.isInitialized()) {
979
+ super.navTo(routeName, parameters, componentTargetInfo, replace);
980
+ return this;
981
+ }
982
+
1100
983
  const route = this.getRoute(routeName);
1101
984
  if (!route) {
1102
- // Unknown route -- let parent handle it (may fire bypassed event).
985
+ // Unknown route -- let the parent handle it (it logs a warning).
1103
986
  // Cancel any pending async navigation so settlement resolvers drain
1104
987
  // and the stale pipeline does not commit a superseded navigation.
1105
- this._cancelPendingNavigation();
988
+ this._cancelPendingNavigation(true);
1106
989
  super.navTo(routeName, parameters, componentTargetInfo, replace);
1107
990
  return this;
1108
991
  }
1109
992
 
1110
993
  const targetHash = route.getURL(parameters ?? {});
1111
- const routeInfo = this.getRouteInfoByHash(targetHash);
1112
- const toRoute = routeInfo?.name ?? "";
1113
-
1114
- // Same-hash dedup: cancel any pending navigation and return without navigating.
1115
- if (this._currentHash !== null && targetHash === this._currentHash) {
1116
- this._cancelPendingNavigation();
994
+ const routeInfo = this._matchRoute(targetHash);
995
+ const toRoute = routeInfo.name;
996
+
997
+ // Same hash: no route of this router changes, so there is nothing to guard. Cancel any
998
+ // pending navigation and navigate natively: UI5 still sets the hashes of nested
999
+ // components (componentTargetInfo), or resets them when none are given.
1000
+ if (targetHash === this._currentHash) {
1001
+ this._cancelPendingNavigation(true);
1002
+ // A navigationSettled handler of the cancelled navigation may have navigated on.
1003
+ const shownHash: string | undefined = this.getHashChanger().getHash();
1004
+ if (shownHash === undefined || shownHash === targetHash) {
1005
+ // If UI5 has reset the hash of the hash changer, after a target was displayed without
1006
+ // a route, it reports the hash again, and parse() lets the route match again.
1007
+ super.navTo(routeName, parameters, componentTargetInfo, replace);
1008
+ }
1117
1009
  return this;
1118
1010
  }
1119
1011
 
1012
+ const skipGuards = guardOptions?.skipGuards === true || this._options.navToPreflight === "bypass";
1013
+
1120
1014
  // Pending-hash dedup: if an async preflight for this exact hash is
1121
- // already running, don't cancel and restart it.
1122
- if (this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
1015
+ // already running, don't cancel and restart it. A navigation that skips
1016
+ // the guards does not wait for them.
1017
+ if (!skipGuards && this._phase.kind === "evaluating" && targetHash === this._phase.attempt.hash) {
1123
1018
  return this;
1124
1019
  }
1125
1020
 
1126
- // Cancel any pending navigation (including previous async preflight).
1127
- this._cancelPendingNavigation();
1128
-
1129
- const skipGuards = guardOptions?.skipGuards === true;
1130
-
1131
- // Bypass mode: skip guards for programmatic navTo() -- commit directly.
1132
- if (skipGuards || this._options.navToPreflight === "bypass") {
1133
- this._phase = { kind: "committing", hash: targetHash, route: toRoute, origin: "preflight" };
1021
+ // parse() evaluates the guards once the hash has changed. It supersedes a pending
1022
+ // navigation then, and undoes the hash change of that navigation with its own.
1023
+ if (!skipGuards && this._options.navToPreflight === "off") {
1134
1024
  super.navTo(routeName, parameters, componentTargetInfo, replace);
1135
- // Safety: if super.navTo didn't trigger parse (e.g. hash didn't change),
1136
- // clear the marker to avoid stale state.
1137
- if (this._phase.kind === "committing" && this._phase.hash === targetHash) {
1138
- this._commitNavigation(targetHash, toRoute);
1139
- }
1140
1025
  return this;
1141
1026
  }
1142
1027
 
1143
- // Off mode: defer guard evaluation to parse() fallback.
1144
- if (this._options.navToPreflight === "off") {
1145
- super.navTo(routeName, parameters, componentTargetInfo, replace);
1028
+ // Cancel any pending navigation (including previous async preflight).
1029
+ // A superseded hash-change navigation leaves its hash in the URL: restore it
1030
+ // unless this navigation moves the URL.
1031
+ const restoreHash = this._pendingRestoresHash();
1032
+ this._cancelPendingNavigation();
1033
+
1034
+ if (skipGuards) {
1035
+ this._navigateAllowed(
1036
+ routeName,
1037
+ parameters,
1038
+ componentTargetInfo,
1039
+ replace,
1040
+ targetHash,
1041
+ toRoute,
1042
+ restoreHash,
1043
+ );
1146
1044
  return this;
1147
1045
  }
1148
1046
 
1149
- // Default "guard" mode: evaluate guards before hash change.
1150
- const controller = new AbortController();
1151
- const generation = this._parseGeneration;
1152
-
1153
- this._phase = {
1154
- kind: "evaluating",
1155
- attempt: { hash: targetHash, route: toRoute, controller, generation },
1156
- };
1047
+ const attempt = this._startAttempt(targetHash, restoreHash);
1048
+ const { generation } = attempt;
1157
1049
 
1158
- const context = this._createGuardContext(toRoute, targetHash, routeInfo, controller.signal);
1050
+ const context = this._createGuardContext(routeInfo, targetHash, attempt.controller.signal);
1159
1051
 
1160
- const decision = this._pipeline.evaluate(context);
1052
+ const decision = this._evaluateGuards(context);
1161
1053
 
1162
1054
  if (isPromiseLike(decision)) {
1163
- decision
1164
- .then((d: GuardDecision) => {
1165
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
1055
+ this._applyWhenDecided(
1056
+ decision,
1057
+ (d) => {
1058
+ if (generation !== this._parseGeneration) {
1166
1059
  Log.debug(
1167
1060
  "Async preflight result discarded (superseded by newer navigation)",
1168
1061
  targetHash,
@@ -1179,24 +1072,15 @@ export default class Router extends MobileRouter implements GuardRouter {
1179
1072
  targetHash,
1180
1073
  toRoute,
1181
1074
  context.bag,
1075
+ attempt,
1182
1076
  );
1183
- })
1184
- .catch((error: unknown) => {
1185
- // Only check generation here, not phase. If _redirect threw and its
1186
- // finally already reset phase to idle, we still need to drain
1187
- // settlement resolvers via _errorNavigation.
1188
- if (generation !== this._parseGeneration) return;
1189
- Log.error(
1190
- `Async preflight guard failed for route "${routeName}", navigation failed`,
1191
- String(error),
1192
- LOG_COMPONENT,
1193
- );
1194
- this._errorNavigation(error, targetHash, false);
1195
- });
1077
+ },
1078
+ targetHash,
1079
+ restoreHash,
1080
+ );
1196
1081
  return this;
1197
1082
  }
1198
1083
 
1199
- // Sync path: apply the decision immediately.
1200
1084
  this._applyPreflightDecision(
1201
1085
  decision,
1202
1086
  routeName,
@@ -1206,23 +1090,51 @@ export default class Router extends MobileRouter implements GuardRouter {
1206
1090
  targetHash,
1207
1091
  toRoute,
1208
1092
  context.bag,
1093
+ attempt,
1209
1094
  );
1210
1095
  return this;
1211
1096
  }
1212
1097
 
1098
+ /**
1099
+ * Navigate to a `navTo()` target that needs no guards (allowed or bypassed) and commit it,
1100
+ * or block it if the hash change was refused (see {@link _commitAfterNavTo}).
1101
+ */
1102
+ private _navigateAllowed(
1103
+ routeName: string,
1104
+ parameters: object | undefined,
1105
+ componentTargetInfo: Record<string, ComponentTargetParameters> | undefined,
1106
+ bReplace: boolean | undefined,
1107
+ targetHash: string,
1108
+ toRoute: string,
1109
+ restoreHash: boolean,
1110
+ ): void {
1111
+ this._phase = {
1112
+ kind: "committing",
1113
+ route: toRoute,
1114
+ hash: targetHash,
1115
+ origin: "preflight",
1116
+ restoreHash,
1117
+ writtenOver: HashChanger.getInstance().getHash(),
1118
+ };
1119
+ try {
1120
+ super.navTo(routeName, parameters, componentTargetInfo, bReplace);
1121
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
1122
+ this._blockNavigation(targetHash, restoreHash);
1123
+ }
1124
+ } finally {
1125
+ // A failed hash change must not leave the next one to be committed without guards.
1126
+ if (this._phase.kind === "committing") {
1127
+ this._phase = IDLE;
1128
+ }
1129
+ }
1130
+ }
1131
+
1213
1132
  /**
1214
1133
  * Apply a preflight guard decision. For "allow", enter the committing
1215
- * phase and call super.navTo(). For "block", flush settlement without
1216
- * touching the hash. For "redirect", start a redirect chain.
1134
+ * phase and call super.navTo(). For "block", flush settlement; the hash is
1135
+ * only touched to restore it after a superseded hash-change navigation.
1136
+ * For "redirect", start a redirect chain.
1217
1137
  * For "error", flush Error settlement with the guard's error.
1218
- *
1219
- * @param decision - Normalized guard pipeline result.
1220
- * @param routeName - Original route name passed to navTo().
1221
- * @param parameters - Original route parameters.
1222
- * @param componentTargetInfo - Optional component target info from the navTo() overload.
1223
- * @param bReplace - Whether to replace the current history entry.
1224
- * @param targetHash - Resolved hash for the target route.
1225
- * @param toRoute - Resolved route name (may differ from routeName for nested routes).
1226
1138
  */
1227
1139
  private _applyPreflightDecision(
1228
1140
  decision: GuardDecision,
@@ -1233,26 +1145,30 @@ export default class Router extends MobileRouter implements GuardRouter {
1233
1145
  targetHash: string,
1234
1146
  toRoute: string,
1235
1147
  bag: Map<string, unknown>,
1148
+ attempt: NavigationAttempt,
1236
1149
  ): void {
1150
+ // A guard that navigated itself has superseded the navigation it was guarding.
1151
+ if (attempt.generation !== this._parseGeneration) return;
1237
1152
  switch (decision.action) {
1238
1153
  case "allow":
1239
- this._phase = { kind: "committing", hash: targetHash, route: toRoute, origin: "preflight" };
1240
- super.navTo(routeName, parameters, componentTargetInfo, bReplace);
1241
- // Safety: if super.navTo didn't trigger parse (e.g. hash didn't change),
1242
- // clear the marker to avoid stale state.
1243
- if (this._phase.kind === "committing" && this._phase.hash === targetHash) {
1244
- // Hash didn't change, so parse() wasn't called. Commit manually.
1245
- this._commitNavigation(targetHash, toRoute);
1246
- }
1154
+ this._navigateAllowed(
1155
+ routeName,
1156
+ parameters,
1157
+ componentTargetInfo,
1158
+ bReplace,
1159
+ targetHash,
1160
+ toRoute,
1161
+ attempt.restoreHash,
1162
+ );
1247
1163
  break;
1248
1164
  case "block":
1249
- this._blockNavigation(targetHash, false);
1165
+ this._blockNavigation(targetHash, attempt.restoreHash);
1250
1166
  break;
1251
1167
  case "redirect":
1252
- this._startRedirectChain(decision.target, targetHash, false, bag);
1168
+ this._startRedirectChain(decision.target, targetHash, bag, attempt, bReplace);
1253
1169
  break;
1254
1170
  case "error":
1255
- this._errorNavigation(decision.error, targetHash, false);
1171
+ this._errorNavigation(decision.error, targetHash, attempt.restoreHash);
1256
1172
  break;
1257
1173
  }
1258
1174
  }
@@ -1271,48 +1187,82 @@ export default class Router extends MobileRouter implements GuardRouter {
1271
1187
  * @since 1.0.1
1272
1188
  */
1273
1189
  override parse(newHash: string): void {
1274
- if (this._suppressedHash !== null) {
1275
- if (newHash === this._suppressedHash) {
1276
- this._suppressedHash = null;
1277
- return;
1278
- }
1279
- this._suppressedHash = null;
1190
+ if (this._destroyed) {
1191
+ // The base router only warns about a hash change that reaches a destroyed router.
1192
+ super.parse(newHash);
1193
+ return;
1194
+ }
1195
+ const reported = this._reportedHash === newHash;
1196
+ this._reportedHash = null;
1197
+ // The URL shows a later hash, which this router has parsed.
1198
+ if (reported && this._reportOutdated) return;
1199
+ // The hash that _restoreHash() is writing.
1200
+ if (newHash === this._suppressedHash) return;
1201
+
1202
+ const undo = this._undo;
1203
+ if (undo?.started && undo.fullHash === HashChanger.getInstance().getHash()) {
1204
+ // The URL is back where the router has put it (see _undoHashChange), so nothing is
1205
+ // evaluated. What the hash changer reports now is the hash of the route that is shown.
1206
+ this._undo = null;
1207
+ this._currentHash = newHash;
1208
+ this._finishRestore(newHash);
1209
+ return;
1280
1210
  }
1281
1211
 
1282
- if (this._phase.kind === "committing") {
1283
- this._commitNavigation(
1284
- newHash,
1285
- this._phase.route !== "" ? this._phase.route : (this.getRouteInfoByHash(newHash)?.name ?? ""),
1286
- );
1212
+ const phase = this._phase;
1213
+ const commit = phase.kind === "awaitingHash" ? phase.commit : phase.kind === "committing" ? phase : null;
1214
+ if (commit?.hash === newHash) {
1215
+ this._phase = commit;
1216
+ this._commitNavigation(newHash, commit.route);
1287
1217
  return;
1288
1218
  }
1289
1219
 
1290
- if (this._currentHash !== null && newHash === this._currentHash) {
1291
- this._cancelPendingNavigation();
1220
+ const currentHash = this._currentHash;
1221
+ if (newHash === currentHash) {
1222
+ if (this._pendingRestoresHash()) {
1223
+ // The URL is back on the committed hash, whose route was never left. That ends the
1224
+ // navigation that had moved it away; one that waits for UI5 to write its hash goes on.
1225
+ if (this._phase.kind === "evaluating") this._cancelPendingNavigation();
1226
+ else this._undo = null;
1227
+ } else {
1228
+ // The committed hash is reported again, and its route matches again as it does
1229
+ // natively: UI5 has written the hash of a navigation with component targets, or has
1230
+ // reset the hash of the hash changer after a target was displayed without a route,
1231
+ // or parse() was called directly.
1232
+ super.parse(newHash);
1233
+ }
1292
1234
  return;
1293
1235
  }
1294
1236
 
1295
- const routeInfo = this.getRouteInfoByHash(newHash);
1296
- const toRoute = routeInfo?.name ?? "";
1237
+ const routeInfo = this._matchRoute(newHash);
1238
+ const toRoute = routeInfo.name;
1297
1239
 
1240
+ // A pending navigation that has moved the URL as well leaves this one to undo both changes.
1241
+ const pendingUndo = this._pendingRestoresHash() ? undo : null;
1242
+ // The router is putting the URL back and gets another hash: that one is not undone as a
1243
+ // whole, so that an undo cannot cause the next one.
1244
+ const undoing = this._phase.kind === "restoring";
1298
1245
  this._cancelPendingNavigation();
1246
+ // A navigationSettled handler that navigated on the cancellation has moved the URL on.
1247
+ if (this._currentHash !== currentHash) return;
1248
+ this._undo = undoing ? null : this._describeUndo(pendingUndo, reported);
1249
+ // Another listener of the hash change that navTo() caused has replaced the hash, before
1250
+ // this router received it: undoing this hash change undoes the one of navTo() as well.
1251
+ if (this._undo && commit === phase && !commit.restoreHash) this._undo.fullHash = commit.writtenOver;
1299
1252
 
1300
- const controller = new AbortController();
1301
- const generation = this._parseGeneration;
1253
+ const direction = reported ? History.getInstance().getDirection() : undefined;
1254
+ const attempt = this._startAttempt(newHash, true, direction);
1255
+ const { generation } = attempt;
1302
1256
 
1303
- this._phase = {
1304
- kind: "evaluating",
1305
- attempt: { hash: newHash, route: toRoute, controller, generation },
1306
- };
1307
-
1308
- const context = this._createGuardContext(toRoute, newHash, routeInfo, controller.signal);
1257
+ const context = this._createGuardContext(routeInfo, newHash, attempt.controller.signal);
1309
1258
 
1310
- const decision = this._pipeline.evaluate(context);
1259
+ const decision = this._evaluateGuards(context);
1311
1260
 
1312
1261
  if (isPromiseLike(decision)) {
1313
- decision
1314
- .then((d: GuardDecision) => {
1315
- if (generation !== this._parseGeneration || this._phase.kind !== "evaluating") {
1262
+ this._applyWhenDecided(
1263
+ decision,
1264
+ (d) => {
1265
+ if (generation !== this._parseGeneration) {
1316
1266
  Log.debug(
1317
1267
  "Async guard result discarded (superseded by newer navigation)",
1318
1268
  newHash,
@@ -1320,24 +1270,15 @@ export default class Router extends MobileRouter implements GuardRouter {
1320
1270
  );
1321
1271
  return;
1322
1272
  }
1323
- this._applyDecision(d, newHash, toRoute, context.bag);
1324
- })
1325
- .catch((error: unknown) => {
1326
- // Only check generation here, not phase. If _redirect threw and its
1327
- // finally already reset phase to idle, we still need to drain
1328
- // settlement resolvers via _errorNavigation.
1329
- if (generation !== this._parseGeneration) return;
1330
- Log.error(
1331
- `Guard pipeline failed for "${newHash}", navigation failed`,
1332
- String(error),
1333
- LOG_COMPONENT,
1334
- );
1335
- this._errorNavigation(error, newHash);
1336
- });
1273
+ this._applyDecision(d, newHash, toRoute, context.bag, attempt);
1274
+ },
1275
+ newHash,
1276
+ true,
1277
+ );
1337
1278
  return;
1338
1279
  }
1339
1280
 
1340
- this._applyDecision(decision, newHash, toRoute, context.bag);
1281
+ this._applyDecision(decision, newHash, toRoute, context.bag, attempt);
1341
1282
  }
1342
1283
 
1343
1284
  /**
@@ -1345,55 +1286,149 @@ export default class Router extends MobileRouter implements GuardRouter {
1345
1286
  *
1346
1287
  * Resets `_currentRoute` and `_currentHash` so that a subsequent
1347
1288
  * `initialize()` re-parses the current hash and fires `routeMatched`,
1348
- * matching the native `sap.m.routing.Router` behavior.
1289
+ * matching the native `sap.m.routing.Router` behavior. The route is
1290
+ * kept for `initialize(true)`, which resumes it instead.
1349
1291
  *
1350
1292
  * @override sap.ui.core.routing.Router#stop
1351
1293
  * @since 1.0.1
1352
1294
  */
1353
1295
  override stop(): this {
1296
+ if (this._blockLoad) this._blockLoad.start = false;
1354
1297
  // Cancel first so in-flight navigationSettled() resolvers receive the
1355
1298
  // Cancelled result before _lastSettlement is cleared below.
1356
1299
  this._cancelPendingNavigation();
1357
- this._suppressedHash = null;
1300
+ // A hash change that was to put the URL back does not reach a stopped router.
1301
+ this._undo = null;
1302
+ // Nothing is committed on a router that is stopped already, or stops before its first navigation settles.
1303
+ if (this._currentHash !== null) this._stoppedRoute = this._currentRoute;
1358
1304
  this._currentRoute = "";
1359
1305
  this._currentHash = null;
1360
1306
  this._lastSettlement = null;
1307
+ this._detachHashListeners();
1361
1308
  super.stop();
1362
1309
  return this;
1363
1310
  }
1364
1311
 
1312
+ /** Detach what {@link _start} has attached. */
1313
+ private _detachHashListeners(): void {
1314
+ this.getHashChanger().detachEvent("hashChanged", this._onHashReported, this);
1315
+ // UI5 moves the listener along when the global hash changer is replaced.
1316
+ HashChanger.getInstance().detachEvent("hashChanged", this._onRootHashChanged, this);
1317
+ this._rootHashChanger = null;
1318
+ }
1319
+
1365
1320
  /**
1366
1321
  * Invalidate any in-flight async guard work. Bumps the generation counter
1367
1322
  * so pending `.then()` callbacks see they are stale, aborts the signal,
1368
- * and transitions to idle.
1323
+ * and transitions to idle. A navigation that waits for its guards or for
1324
+ * its hash settles as `Cancelled`. With `restoreHash`, a cancelled hash-change
1325
+ * navigation also gets its hash restored: `navTo()` passes it when the
1326
+ * call itself will not move the URL.
1369
1327
  */
1370
- private _cancelPendingNavigation(): void {
1328
+ private _cancelPendingNavigation(restoreHash = false): void {
1371
1329
  ++this._parseGeneration;
1372
- if (this._phase.kind === "evaluating") {
1373
- this._phase.attempt.controller.abort();
1374
- this._flushSettlement({
1375
- status: NavigationOutcome.Cancelled,
1376
- route: this._currentRoute,
1377
- hash: this._currentHash ?? "",
1378
- });
1379
- }
1330
+ const phase = this._phase;
1331
+ const pendingRestoresHash = this._pendingRestoresHash();
1332
+ // Idle before the settlement fires, so that a handler can navigate.
1380
1333
  this._phase = IDLE;
1334
+ // A navigation that is committing ends with the navigation that supersedes it.
1335
+ if (phase.kind === "idle" || phase.kind === "committing") return;
1336
+ if (phase.kind === "restoring") {
1337
+ // A navigation that waits for the URL to be back has ended already: it settles as it ended.
1338
+ this._flushSettlement(phase.result);
1339
+ return;
1340
+ }
1341
+ if (phase.kind === "evaluating") phase.attempt.controller.abort();
1342
+ this._settleUncommitted(
1343
+ { status: NavigationOutcome.Cancelled, route: this._currentRoute, hash: this._currentHash ?? "" },
1344
+ phase.kind === "evaluating" ? phase.attempt.hash : phase.commit.hash,
1345
+ restoreHash && pendingRestoresHash,
1346
+ );
1347
+ }
1348
+
1349
+ /**
1350
+ * Whether the pending navigation leaves a hash in the URL that never committed, the one of a
1351
+ * hash-change navigation: it must be restored unless a navigation moves the URL.
1352
+ */
1353
+ private _pendingRestoresHash(): boolean {
1354
+ const phase = this._phase;
1355
+ if (phase.kind === "evaluating") return phase.attempt.restoreHash;
1356
+ if (phase.kind === "committing") return phase.restoreHash;
1357
+ return phase.kind === "awaitingHash" && phase.commit.restoreHash;
1358
+ }
1359
+
1360
+ /**
1361
+ * Start evaluating a navigation. Its generation is its own, so the result of any earlier
1362
+ * attempt is stale: also one that a navigationSettled handler started while this
1363
+ * navigation cancelled its predecessor, which is aborted here without a settlement.
1364
+ */
1365
+ private _startAttempt(hash: string, restoreHash: boolean, direction?: Direction): NavigationAttempt {
1366
+ if (this._phase.kind === "evaluating") this._phase.attempt.controller.abort();
1367
+ const attempt: NavigationAttempt = {
1368
+ hash,
1369
+ controller: new AbortController(),
1370
+ generation: ++this._parseGeneration,
1371
+ restoreHash,
1372
+ direction,
1373
+ };
1374
+ this._phase = { kind: "evaluating", attempt };
1375
+ return attempt;
1376
+ }
1377
+
1378
+ /**
1379
+ * Apply the decision of async guards once it is there. Until then the navigation is postponed,
1380
+ * which UI5 sees as a route match in progress (see {@link _mirrorMatchingProcess}). The pipeline
1381
+ * turns a failing guard into an error decision, so an error thrown here comes from applying the
1382
+ * decision, which has no caller to throw to: it is logged, and fails the navigation unless that
1383
+ * has settled.
1384
+ */
1385
+ private _applyWhenDecided(
1386
+ decision: PromiseLike<GuardDecision>,
1387
+ apply: (decision: GuardDecision) => void,
1388
+ attemptedHash: string | undefined,
1389
+ restoreHash: boolean,
1390
+ ): void {
1391
+ if (this._phase.kind === "evaluating") this._phase = { ...this._phase, postponed: true };
1392
+ decision.then((d) => {
1393
+ const lastSettlement = this._lastSettlement;
1394
+ try {
1395
+ apply(d);
1396
+ } catch (error) {
1397
+ Log.error(
1398
+ "Navigation failed after its guards had settled",
1399
+ error instanceof Error ? error : String(error),
1400
+ LOG_COMPONENT,
1401
+ );
1402
+ if (this._lastSettlement === lastSettlement) {
1403
+ this._errorNavigation(error, attemptedHash, restoreHash);
1404
+ }
1405
+ }
1406
+ });
1381
1407
  }
1382
1408
 
1383
1409
  /**
1384
1410
  * Apply a guard decision for the parse() fallback path.
1385
1411
  */
1386
- private _applyDecision(decision: GuardDecision, hash: string, route: string, bag: Map<string, unknown>): void {
1412
+ private _applyDecision(
1413
+ decision: GuardDecision,
1414
+ hash: string,
1415
+ route: string,
1416
+ bag: Map<string, unknown>,
1417
+ attempt: NavigationAttempt,
1418
+ ): void {
1419
+ // A guard that navigated itself has superseded the navigation it was guarding.
1420
+ if (attempt.generation !== this._parseGeneration) return;
1387
1421
  switch (decision.action) {
1388
1422
  case "allow":
1389
- this._phase = { kind: "committing", hash, route, origin: "parse" };
1423
+ this._phase = { kind: "committing", route, hash, origin: "parse", restoreHash: false };
1390
1424
  this._commitNavigation(hash, route);
1391
1425
  break;
1392
1426
  case "block":
1393
1427
  this._blockNavigation(hash);
1394
1428
  break;
1395
1429
  case "redirect":
1396
- this._startRedirectChain(decision.target, hash, true, bag);
1430
+ // The hash that redirects has reached the browser: the target takes its history entry.
1431
+ this._startRedirectChain(decision.target, hash, bag, attempt, true);
1397
1432
  break;
1398
1433
  case "error":
1399
1434
  this._errorNavigation(decision.error, hash);
@@ -1401,17 +1436,45 @@ export default class Router extends MobileRouter implements GuardRouter {
1401
1436
  }
1402
1437
  }
1403
1438
 
1439
+ /**
1440
+ * Leave the title history of UI5 (`getTitleHistory()`) as after the native equivalent of a
1441
+ * redirected hash change: the hash change, then `navTo(target, ..., true)`. The route of the
1442
+ * hash change never matched, so UI5 has not handled its title:
1443
+ * - A new entry or a step forward would have added a title, which the title of the target
1444
+ * replaces: UI5 must not remove the title of the route before it.
1445
+ * - A step back would have removed the title of the route that was left, so that the target
1446
+ * replaces the title of the entry the step arrived at: UI5 removes the first for the
1447
+ * replaced hash, the router removes the second, under the condition of UI5 for a step back.
1448
+ */
1449
+ private _alignTitleHistory(direction: Direction | undefined): void {
1450
+ if (direction === HistoryDirection.NewEntry || direction === HistoryDirection.Forwards) {
1451
+ Reflect.set(this, "_bLastHashReplaced", false);
1452
+ } else if (direction === HistoryDirection.Backwards) {
1453
+ const titles: unknown[] = this.getTitleHistory();
1454
+ const left = titles.at(-1);
1455
+ const replaced = titles.at(-2);
1456
+ if (isRecord(left) && isRecord(replaced) && !left.isHome && left.title !== replaced.title) {
1457
+ titles.splice(-2, 1);
1458
+ }
1459
+ }
1460
+ }
1461
+
1404
1462
  /**
1405
1463
  * Delegate to the parent router and update internal state.
1406
1464
  *
1407
1465
  * State is updated BEFORE calling parse to ensure that if event handlers
1408
1466
  * (e.g., routeMatched) trigger nested navigation, the leave guards will
1409
- * run for the correct (new) route rather than the old one.
1467
+ * run for the correct (new) route rather than the old one. The settlement
1468
+ * fires before parse as well, so the settlements of such nested navigations
1469
+ * follow it.
1410
1470
  */
1411
- private _commitNavigation(hash: string, route?: string): void {
1471
+ private _commitNavigation(hash: string, route: string): void {
1412
1472
  const wasRedirect = this._phase.kind === "committing" && this._phase.origin === "redirect";
1473
+ if (this._phase.kind === "committing") this._alignTitleHistory(this._phase.direction);
1474
+ // The URL has moved on: a hash change that was to put it back is not awaited any more.
1475
+ this._undo = null;
1413
1476
  this._currentHash = hash;
1414
- this._currentRoute = route ?? this.getRouteInfoByHash(hash)?.name ?? "";
1477
+ this._currentRoute = route;
1415
1478
  // Transition to idle before super.parse so that routeMatched/patternMatched
1416
1479
  // handlers that call navTo() go through the full guard pipeline.
1417
1480
  this._phase = IDLE;
@@ -1424,14 +1487,39 @@ export default class Router extends MobileRouter implements GuardRouter {
1424
1487
  route: this._currentRoute,
1425
1488
  hash,
1426
1489
  });
1490
+ // A navigationSettled handler that navigated on has committed its own hash.
1491
+ if (this._currentHash !== hash) return;
1427
1492
  super.parse(hash);
1428
1493
  }
1429
1494
 
1495
+ /**
1496
+ * Commit the navigation of the committing phase after `super.navTo()` unless `parse()` has
1497
+ * committed it. Returns whether the navigation takes place:
1498
+ * - The hash changer shows the target hash: the route matches here.
1499
+ * - UI5 writes the hash later, which it does with component targets, once the nested
1500
+ * components are loaded. The navigation waits for it: it commits, and the route matches,
1501
+ * when `parse()` gets that hash, as the route does natively. Committed here, the router
1502
+ * would be on a route that UI5 does not display if the hash is never written.
1503
+ * - Otherwise the hash changer has refused the hash change, as the Fiori launchpad does while
1504
+ * it asks the user about unsaved data. Nothing changed, so nothing is committed.
1505
+ */
1506
+ private _commitAfterNavTo(componentTargetInfo: Record<string, ComponentTargetParameters> | undefined): boolean {
1507
+ const phase = this._phase;
1508
+ if (phase.kind !== "committing") return true;
1509
+ if (this.getHashChanger().getHash() === phase.hash) {
1510
+ this._commitNavigation(phase.hash, phase.route);
1511
+ return true;
1512
+ }
1513
+ if (!componentTargetInfo || Object.keys(componentTargetInfo).length === 0) return false;
1514
+ this._phase = { kind: "awaitingHash", commit: phase };
1515
+ return true;
1516
+ }
1517
+
1430
1518
  /**
1431
1519
  * Evaluate guards on a redirect target and apply the resulting decision.
1432
1520
  *
1433
- * Handles loop detection (visited-hash set + depth cap), unknown-route
1434
- * fallback, sync/async guard evaluation, and recursive chaining when
1521
+ * Handles the unknown-route block, loop detection (visited-hash set +
1522
+ * depth cap), sync/async guard evaluation, and recursive chaining when
1435
1523
  * the target's guard itself returns a redirect. All hops in a chain
1436
1524
  * share the same AbortSignal and generation counter from the original
1437
1525
  * navigation so that a superseding navigation correctly discards
@@ -1442,19 +1530,30 @@ export default class Router extends MobileRouter implements GuardRouter {
1442
1530
  */
1443
1531
  private _redirect(target: string | GuardRedirect, chain: RedirectChainContext): void {
1444
1532
  const targetName = typeof target === "string" ? target : target.route;
1445
- let targetHash: string | null = null;
1446
- const targetParameters = typeof target === "string" ? {} : (target.parameters ?? {});
1447
1533
  const targetRoute = this.getRoute(targetName);
1448
- if (targetRoute) {
1449
- try {
1450
- targetHash = targetRoute.getURL(targetParameters);
1451
- } catch {
1452
- targetHash = null;
1453
- }
1534
+ if (!targetRoute) {
1535
+ Log.warning(
1536
+ `Guard redirect target "${targetName}" is not a known route, treating as blocked`,
1537
+ undefined,
1538
+ LOG_COMPONENT,
1539
+ );
1540
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1541
+ return;
1542
+ }
1543
+ let targetHash: string;
1544
+ try {
1545
+ targetHash = targetRoute.getURL(typeof target === "string" ? {} : (target.parameters ?? {}));
1546
+ } catch (error) {
1547
+ Log.error(
1548
+ `Guard redirect target "${targetName}" has no valid hash, navigation failed`,
1549
+ String(error),
1550
+ LOG_COMPONENT,
1551
+ );
1552
+ this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
1553
+ return;
1454
1554
  }
1455
1555
 
1456
- // Loop detection: visited set (exact hash match) + depth cap.
1457
- if (targetHash !== null && chain.visited.has(targetHash)) {
1556
+ if (chain.visited.has(targetHash)) {
1458
1557
  Log.error(
1459
1558
  `Guard redirect loop detected: ${[...chain.visited, targetHash].join(" -> ")}`,
1460
1559
  undefined,
@@ -1472,130 +1571,101 @@ export default class Router extends MobileRouter implements GuardRouter {
1472
1571
  this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1473
1572
  return;
1474
1573
  }
1475
- if (targetHash !== null) {
1476
- chain.visited.add(targetHash);
1477
- }
1478
-
1479
- // If the target route doesn't exist or the hash couldn't be resolved,
1480
- // attempt navTo (parent may fire bypassed) and fall back to blocked.
1481
- if (targetHash === null) {
1482
- const settlementBefore = this._lastSettlement;
1483
- this._phase = { kind: "committing", hash: "", route: targetName, origin: "redirect" };
1484
- try {
1485
- if (typeof target === "string") {
1486
- this.navTo(target, {}, {}, true);
1487
- } else {
1488
- this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
1489
- }
1490
- } finally {
1491
- if (this._phase.kind === "committing") {
1492
- this._phase = IDLE;
1493
- }
1494
- }
1495
- if (this._lastSettlement === settlementBefore) {
1496
- Log.warning(
1497
- `Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`,
1498
- undefined,
1499
- LOG_COMPONENT,
1500
- );
1501
- this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1502
- }
1503
- return;
1504
- }
1574
+ chain.visited.add(targetHash);
1505
1575
 
1506
- // Narrowed after the null-branch early return; const carries it into the async closure.
1507
- const resolvedHash: string = targetHash;
1508
-
1509
- // Build guard context for the redirect target.
1510
- const routeInfo = this.getRouteInfoByHash(resolvedHash);
1511
- const context: GuardContext = {
1512
- toRoute: routeInfo?.name ?? "",
1513
- toHash: resolvedHash,
1514
- toArguments: routeInfo?.arguments ?? {},
1515
- fromRoute: chain.fromRoute,
1516
- fromHash: chain.fromHash,
1517
- signal: chain.signal,
1518
- bag: chain.bag,
1519
- toMeta: this.getRouteMeta(routeInfo?.name ?? ""),
1520
- fromMeta: this.getRouteMeta(chain.fromRoute),
1521
- };
1576
+ const routeInfo = this._matchRoute(targetHash);
1577
+ const toRoute = routeInfo.name;
1578
+ const context = this._createGuardContext(routeInfo, targetHash, chain.signal, chain);
1522
1579
 
1523
- const decision = this._pipeline.evaluate(context, { skipLeaveGuards: true });
1580
+ const decision = this._evaluateGuards(context, true);
1524
1581
 
1525
1582
  if (isPromiseLike(decision)) {
1526
- decision
1527
- .then((d: GuardDecision) => {
1528
- if (chain.generation !== this._parseGeneration) return;
1529
- this._applyRedirectDecision(d, target, resolvedHash, chain);
1530
- })
1531
- .catch((error: unknown) => {
1532
- if (chain.generation !== this._parseGeneration) return;
1533
- Log.error(
1534
- `Guard pipeline failed during redirect chain for "${targetName}", navigation failed`,
1535
- String(error),
1536
- LOG_COMPONENT,
1537
- );
1538
- this._errorNavigation(error, chain.attemptedHash, chain.restoreHash);
1539
- });
1583
+ this._applyWhenDecided(
1584
+ decision,
1585
+ (d) => this._applyRedirectDecision(d, target, targetHash, toRoute, chain),
1586
+ chain.attemptedHash,
1587
+ chain.restoreHash,
1588
+ );
1540
1589
  return;
1541
1590
  }
1542
1591
 
1543
- this._applyRedirectDecision(decision, target, resolvedHash, chain);
1592
+ this._applyRedirectDecision(decision, target, targetHash, toRoute, chain);
1544
1593
  }
1545
1594
 
1546
1595
  /**
1547
1596
  * Apply a guard decision within a redirect chain. For "allow", enter
1548
- * committing phase and delegate to navTo (which hits the existing bypass).
1597
+ * committing phase and delegate to navTo (which hits the existing bypass);
1598
+ * if that does not reach parse(), commit the target directly. A target that
1599
+ * is displayed already settles the navigation without a commit.
1549
1600
  * For "block", block the entire chain. For "redirect", recurse.
1550
1601
  *
1551
1602
  * @param decision - Normalized guard pipeline result for this hop.
1552
1603
  * @param target - The redirect target (route name or {@link GuardRedirect}).
1553
- * @param targetHash - Resolved hash for the redirect target (guaranteed non-null).
1604
+ * @param targetHash - Resolved hash for the redirect target.
1605
+ * @param toRoute - Route that matches the hash, as in the hop's guard context: the route UI5 displays.
1554
1606
  * @param chain - Shared redirect chain context with visited set, signals, etc.
1555
1607
  */
1556
1608
  private _applyRedirectDecision(
1557
1609
  decision: GuardDecision,
1558
1610
  target: string | GuardRedirect,
1559
1611
  targetHash: string,
1612
+ toRoute: string,
1560
1613
  chain: RedirectChainContext,
1561
1614
  ): void {
1615
+ // Superseded while the hop's guards ran: by a newer navigation, or by a guard that navigated.
1616
+ if (chain.generation !== this._parseGeneration) return;
1562
1617
  switch (decision.action) {
1563
1618
  case "allow": {
1564
- const targetName = typeof target === "string" ? target : target.route;
1565
- const settlementBefore = this._lastSettlement;
1566
- this._phase = { kind: "committing", hash: targetHash, route: targetName, origin: "redirect" };
1619
+ const componentTargetInfo = typeof target === "string" ? undefined : target.componentTargetInfo;
1620
+ if (targetHash === this._currentHash) {
1621
+ // The target is displayed already, so no route matches again, as for a navTo() to
1622
+ // the committed hash: the URL is put back and UI5 sets the hashes of nested components.
1623
+ this._phase = IDLE;
1624
+ this._settleUncommitted(
1625
+ { status: NavigationOutcome.Redirected, route: this._currentRoute, hash: targetHash },
1626
+ chain.attemptedHash,
1627
+ chain.restoreHash,
1628
+ typeof target !== "string" && componentTargetInfo
1629
+ ? () => {
1630
+ // Unless a settlement handler has moved the URL on.
1631
+ if (this.getHashChanger().getHash() !== targetHash) return;
1632
+ super.navTo(
1633
+ target.route,
1634
+ target.parameters ?? {},
1635
+ componentTargetInfo,
1636
+ chain.replace,
1637
+ );
1638
+ }
1639
+ : undefined,
1640
+ );
1641
+ break;
1642
+ }
1643
+ this._phase = {
1644
+ kind: "committing",
1645
+ route: toRoute,
1646
+ hash: targetHash,
1647
+ origin: "redirect",
1648
+ direction: chain.direction,
1649
+ restoreHash: chain.restoreHash,
1650
+ writtenOver: HashChanger.getInstance().getHash(),
1651
+ };
1567
1652
  try {
1653
+ // Writing the hash the URL already shows changes nothing, except that a nested
1654
+ // router would add its prefix for an empty hash (see _restoreHash).
1655
+ const hashShown = this.getHashChanger().getHash() === targetHash;
1568
1656
  if (typeof target === "string") {
1569
- this.navTo(target, {}, {}, true);
1570
- } else {
1571
- this.navTo(target.route, target.parameters ?? {}, target.componentTargetInfo, true);
1657
+ if (!hashShown) this.navTo(target, {}, {}, chain.replace);
1658
+ } else if (!hashShown || componentTargetInfo) {
1659
+ this.navTo(target.route, target.parameters ?? {}, componentTargetInfo, chain.replace);
1660
+ }
1661
+ if (!this._commitAfterNavTo(componentTargetInfo)) {
1662
+ this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1572
1663
  }
1573
1664
  } finally {
1574
1665
  if (this._phase.kind === "committing") {
1575
1666
  this._phase = IDLE;
1576
1667
  }
1577
1668
  }
1578
- // Safety net: if navTo didn't produce a settlement (e.g. unknown route
1579
- // or redirect to current hash where HashChanger doesn't fire), handle it.
1580
- if (this._lastSettlement === settlementBefore) {
1581
- const redirectsToCurrentHash = targetHash === (this._currentHash ?? "");
1582
- if (redirectsToCurrentHash) {
1583
- this._phase = {
1584
- kind: "committing",
1585
- hash: this._currentHash ?? "",
1586
- route: this._currentRoute,
1587
- origin: "redirect",
1588
- };
1589
- this._commitNavigation(this._currentHash ?? "", this._currentRoute);
1590
- return;
1591
- }
1592
- Log.warning(
1593
- `Guard redirect target "${targetName}" did not produce a navigation, treating as blocked`,
1594
- undefined,
1595
- LOG_COMPONENT,
1596
- );
1597
- this._blockNavigation(chain.attemptedHash, chain.restoreHash);
1598
- }
1599
1669
  break;
1600
1670
  }
1601
1671
  case "block":
@@ -1610,31 +1680,59 @@ export default class Router extends MobileRouter implements GuardRouter {
1610
1680
  }
1611
1681
  }
1612
1682
 
1683
+ /** The route that matches a hash, and its arguments. For a hash that no route matches: no route (`""`), no arguments. */
1684
+ private _matchRoute(hash: string): RouteInfo {
1685
+ const info = this.getRouteInfoByHash(hash);
1686
+ return { name: info?.name ?? "", arguments: info?.arguments ?? {} };
1687
+ }
1688
+
1689
+ /**
1690
+ * The greedy routes that match `hash` in addition to `firstMatch`, the first route that
1691
+ * matches it. UI5 matches them as well and fires their events.
1692
+ */
1693
+ private _greedyMatches(hash: string, firstMatch: string): string[] {
1694
+ return this._greedyRouteNames.filter((name) => name !== firstMatch && this.getRoute(name)?.match(hash));
1695
+ }
1696
+
1697
+ /**
1698
+ * Evaluate the guards of a navigation: of the routes in its context, and of the greedy routes
1699
+ * that are left and entered with them. A hop of a redirect chain leaves no route.
1700
+ */
1701
+ private _evaluateGuards(context: GuardContext, redirectHop = false): GuardDecision | Promise<GuardDecision> {
1702
+ return this._pipeline.evaluate(context, {
1703
+ skipLeaveGuards: redirectHop,
1704
+ alsoLeaving: this._greedyMatches(context.fromHash, context.fromRoute),
1705
+ alsoEntering: this._greedyMatches(context.toHash, context.toRoute),
1706
+ });
1707
+ }
1708
+
1613
1709
  /**
1614
- * Build a guard context for a new navigation.
1615
- * Called by {@link navTo} (preflight path) and {@link parse} (browser-initiated path).
1710
+ * Build the guard context of a navigation to `routeInfo`. A hop of a redirect chain passes the
1711
+ * chain, whose source route, source hash and bag are those of the original navigation.
1616
1712
  */
1617
1713
  private _createGuardContext(
1618
- toRoute: string,
1714
+ routeInfo: RouteInfo,
1619
1715
  toHash: string,
1620
- routeInfo: { arguments: Record<string, string | Record<string, string>> } | undefined,
1621
1716
  signal: AbortSignal,
1717
+ chain?: RedirectChainContext,
1622
1718
  ): GuardContext {
1719
+ const fromRoute = chain ? chain.fromRoute : this._currentRoute;
1623
1720
  return {
1624
- toRoute,
1721
+ toRoute: routeInfo.name,
1625
1722
  toHash,
1626
- toArguments: routeInfo?.arguments ?? {},
1627
- fromRoute: this._currentRoute,
1628
- fromHash: this._currentHash ?? "",
1723
+ toArguments: routeInfo.arguments,
1724
+ fromRoute,
1725
+ fromHash: chain ? chain.fromHash : (this._currentHash ?? ""),
1629
1726
  signal,
1630
- bag: new Map(),
1631
- toMeta: this.getRouteMeta(toRoute),
1632
- fromMeta: this.getRouteMeta(this._currentRoute),
1727
+ bag: chain ? chain.bag : new Map<string, unknown>(),
1728
+ toMeta: this.getRouteMeta(routeInfo.name),
1729
+ fromMeta: this.getRouteMeta(fromRoute),
1730
+ ownerComponent: this._ownerComponent,
1633
1731
  };
1634
1732
  }
1635
1733
 
1636
1734
  /**
1637
- * Start a new redirect chain from the current evaluating phase.
1735
+ * Start a new redirect chain for the given evaluating attempt.
1638
1736
  * Called by {@link _applyPreflightDecision} and {@link _applyDecision}
1639
1737
  * when a guard returns a redirect. Delegates to {@link _redirect} with
1640
1738
  * a fresh {@link RedirectChainContext}.
@@ -1642,16 +1740,18 @@ export default class Router extends MobileRouter implements GuardRouter {
1642
1740
  private _startRedirectChain(
1643
1741
  target: string | GuardRedirect,
1644
1742
  hash: string,
1645
- restoreHash: boolean,
1646
1743
  bag: Map<string, unknown>,
1744
+ attempt: NavigationAttempt,
1745
+ replace: boolean | undefined,
1647
1746
  ): void {
1648
- const { attempt } = this._phase as PhaseEvaluating;
1649
1747
  const visited = new Set<string>();
1650
1748
  visited.add(hash);
1651
1749
  this._redirect(target, {
1652
1750
  visited,
1653
1751
  attemptedHash: hash,
1654
- restoreHash,
1752
+ restoreHash: attempt.restoreHash,
1753
+ replace,
1754
+ direction: attempt.direction,
1655
1755
  fromRoute: this._currentRoute,
1656
1756
  fromHash: this._currentHash ?? "",
1657
1757
  signal: attempt.controller.signal,
@@ -1661,19 +1761,17 @@ export default class Router extends MobileRouter implements GuardRouter {
1661
1761
  }
1662
1762
 
1663
1763
  /**
1664
- * Clear pending state and flush a Blocked settlement.
1665
- * When `restoreHash` is true (default), also restores the browser hash
1666
- * to `_currentHash`. Preflight callers pass false because the hash was
1667
- * never changed.
1764
+ * Settle as Blocked. With `restoreHash` (default), the hash change of the navigation is
1765
+ * undone first (see {@link _settleUncommitted}). Preflight callers pass false unless they
1766
+ * superseded a hash-change navigation: otherwise the hash was never changed.
1668
1767
  */
1669
1768
  private _blockNavigation(attemptedHash?: string, restoreHash = true): void {
1670
1769
  this._phase = IDLE;
1671
- this._flushSettlement({
1672
- status: NavigationOutcome.Blocked,
1673
- route: this._currentRoute,
1674
- hash: this._currentHash ?? "",
1675
- });
1676
- this._restoreHashIfNeeded(attemptedHash, restoreHash);
1770
+ this._settleUncommitted(
1771
+ { status: NavigationOutcome.Blocked, route: this._currentRoute, hash: this._currentHash ?? "" },
1772
+ attemptedHash,
1773
+ restoreHash,
1774
+ );
1677
1775
  }
1678
1776
 
1679
1777
  /**
@@ -1683,337 +1781,199 @@ export default class Router extends MobileRouter implements GuardRouter {
1683
1781
  */
1684
1782
  private _errorNavigation(error: unknown, attemptedHash?: string, restoreHash = true): void {
1685
1783
  this._phase = IDLE;
1686
- this._flushSettlement({
1687
- status: NavigationOutcome.Error,
1688
- route: this._currentRoute,
1689
- hash: this._currentHash ?? "",
1690
- error,
1691
- });
1692
- this._restoreHashIfNeeded(attemptedHash, restoreHash);
1693
- }
1694
-
1695
- /** Conditionally restore the browser hash after a blocked or errored navigation. */
1696
- private _restoreHashIfNeeded(attemptedHash: string | undefined, restoreHash: boolean): void {
1697
- if (!restoreHash) return;
1698
- if (this._currentHash === null && attemptedHash && attemptedHash !== "") {
1699
- this._restoreHash("", false);
1700
- return;
1701
- }
1702
- this._restoreHash(this._currentHash ?? "");
1784
+ this._settleUncommitted(
1785
+ { status: NavigationOutcome.Error, route: this._currentRoute, hash: this._currentHash ?? "", error },
1786
+ attemptedHash,
1787
+ restoreHash,
1788
+ );
1703
1789
  }
1704
1790
 
1705
1791
  /**
1706
- * Restore the previous hash without creating a history entry.
1707
- * Assumes replaceHash fires hashChanged synchronously (validated by test).
1708
- * `_currentRoute` stays unchanged because the navigation never
1709
- * committed. The user remains on the same logical route.
1792
+ * Settle a navigation that did not commit. With `restoreHash`, the hash it left in the URL
1793
+ * is restored first, so that settlement handlers run on the final URL and a hash they set
1794
+ * is not overwritten. The exception is a first navigation: nothing is committed yet, so the
1795
+ * empty hash is restored after the settlement and parsed as a navigation of its own.
1796
+ * `whenBack` runs after the settlement.
1710
1797
  */
1711
- private _restoreHash(hash: string, suppressParse = true): void {
1712
- const hashChanger = this.getHashChanger();
1713
- if (hashChanger) {
1714
- this._suppressedHash = suppressParse ? hash : null;
1715
- hashChanger.replaceHash(hash, HistoryDirection.Unknown);
1716
- if (this._suppressedHash === hash) {
1717
- this._suppressedHash = null;
1718
- }
1719
- }
1798
+ private _settleUncommitted(
1799
+ result: NavigationResult,
1800
+ attemptedHash: string | undefined,
1801
+ restoreHash: boolean,
1802
+ whenBack?: () => void,
1803
+ ): void {
1804
+ const loadDefaultRoute = restoreHash && this._currentHash === null && !!attemptedHash;
1805
+ // It settles once the URL is back.
1806
+ if (restoreHash && !loadDefaultRoute && !this._undoHashChange(result, whenBack)) return;
1807
+ this._flushSettlement(result);
1808
+ whenBack?.();
1809
+ // Unless a handler navigated and committed in the meantime.
1810
+ if (loadDefaultRoute && this._currentHash === null) this._restoreHash("", false);
1720
1811
  }
1721
1812
 
1722
1813
  /**
1723
- * Collect all route names and their patterns from the router.
1724
- * Skips routes whose pattern is undefined (no pattern configured).
1814
+ * Describe how to undo the hash change that the navigation starts with. After `pending`, the
1815
+ * undo of a navigation that this one supersedes, it takes back both changes. A `parse()` that
1816
+ * is not `reported` by the hash changer comes with no hash change.
1725
1817
  */
1726
- private _collectRoutePatterns(): { name: string; pattern: string }[] {
1727
- const result: { name: string; pattern: string }[] = [];
1728
- for (const name of this._routeNames) {
1729
- const route = this.getRoute(name);
1730
- if (route) {
1731
- const pattern = route.getPattern();
1732
- if (pattern !== undefined) {
1733
- result.push({ name, pattern });
1734
- }
1735
- }
1736
- }
1737
- return result;
1818
+ private _describeUndo(pending: HashChangeUndo | null, reported: boolean): HashChangeUndo | null {
1819
+ if (!reported) return pending;
1820
+ const shown = HashChanger.getInstance().getHash();
1821
+ const step = lastStep;
1822
+ if (!pending) return { first: shown, fullHash: undefined, shown, step, started: false };
1823
+ const offset = pending.step && step ? pending.step.offset + step.offset : 0;
1824
+ return {
1825
+ first: pending.first,
1826
+ fullHash: pending.fullHash,
1827
+ shown,
1828
+ step: step && offset ? { offset, href: step.href } : null,
1829
+ started: false,
1830
+ };
1738
1831
  }
1739
1832
 
1740
1833
  /**
1741
- * Expand guard descriptors to descendant routes when guard inheritance
1742
- * is set to `"pattern-tree"`. Global (`"*"`) descriptors are kept as-is.
1743
- * Descriptors are sorted by pattern depth (ancestor guards run before
1744
- * descendant guards).
1834
+ * Put the URL back after a navigation that did not commit. Returns whether it is back;
1835
+ * otherwise `result` settles when it is.
1836
+ *
1837
+ * While the URL still shows the hash change that started the navigation, that change is undone
1838
+ * as a whole, so that the hashes of nested routers are back as well:
1839
+ * - A step through the browser history is taken back, which leaves the history as it was.
1840
+ * The browser does that asynchronously.
1841
+ * - Any other change (a new entry, or a step the browser does not report) has its entry replaced with
1842
+ * the full previous hash, once UI5 has reported the change to every router. Nested routers
1843
+ * have received their part of the refused hash by then; they receive the previous one next.
1844
+ *
1845
+ * `parse()` ends the wait when the hash change arrives that shows the full previous hash.
1846
+ *
1847
+ * If the URL has moved on since, only the hash of this router is restored. So it is while
1848
+ * no navigation has committed: the URL before the change showed no route of this router either.
1745
1849
  */
1746
- private _expandGuardDescriptors(descriptors: GuardDescriptor[]): GuardDescriptor[] {
1747
- const allRoutes = this._collectRoutePatterns();
1748
- if (allRoutes.length === 0) return descriptors;
1749
-
1750
- // Build a name -> pattern map for quick lookup
1751
- const patternByName = new Map(allRoutes.map((r) => [r.name, r.pattern]));
1752
-
1753
- const expanded: GuardDescriptor[] = [];
1754
-
1755
- for (const descriptor of descriptors) {
1756
- expanded.push(descriptor);
1757
-
1758
- // Global guards and routes without a known pattern are not expanded
1759
- if (descriptor.route === "*") continue;
1760
- const ancestorPattern = patternByName.get(descriptor.route);
1761
- if (ancestorPattern === undefined) continue;
1762
-
1763
- // Find descendant routes whose pattern extends the ancestor's pattern
1764
- for (const { name, pattern } of allRoutes) {
1765
- if (name === descriptor.route) continue;
1766
- if (isPatternAncestor(ancestorPattern, pattern)) {
1767
- expanded.push({ ...descriptor, route: name });
1768
- }
1769
- }
1850
+ private _undoHashChange(result: NavigationResult, whenBack?: () => void): boolean {
1851
+ const undo = this._undo;
1852
+ const hash = this._currentHash;
1853
+ const rootHash = HashChanger.getInstance().getHash();
1854
+ if (undo === null || hash === null || undo.shown !== rootHash || undo.fullHash === rootHash) {
1855
+ this._restoreHash(hash ?? "");
1856
+ return true;
1770
1857
  }
1771
-
1772
- // Sort by pattern depth (segment count) so ancestor guards run first.
1773
- // Global ("*") descriptors return 0 here -- their relative position is irrelevant
1774
- // because GuardPipeline evaluates globals separately from route-specific guards.
1775
- return expanded.toSorted((a, b) => {
1776
- if (a.route === "*" || b.route === "*") return 0;
1777
- const pa = patternByName.get(a.route) ?? "";
1778
- const pb = patternByName.get(b.route) ?? "";
1779
- return patternSegments(pa).length - patternSegments(pb).length;
1780
- });
1858
+ const href = window.location.href;
1859
+ undo.started = true;
1860
+ this._phase = { kind: "restoring", result, whenBack };
1861
+ if (undoneHref === href) {
1862
+ // Another router is taking the step back.
1863
+ } else if (undo.step) {
1864
+ undoneHref = href;
1865
+ window.history.go(-undo.step.offset);
1866
+ } else if (undo.fullHash === undefined) {
1867
+ // UI5 is still reporting the change to the nested routers.
1868
+ this._phase = { ...this._phase, awaitsReport: true };
1869
+ } else {
1870
+ this._replaceFullHash(undo.fullHash);
1871
+ }
1872
+ return false;
1781
1873
  }
1782
1874
 
1783
1875
  /**
1784
- * Resolve metadata for a route without inheritance (flat merge of
1785
- * manifest and runtime metadata).
1876
+ * Replace the hash of the root hash changer with the full previous hash, and settle the
1877
+ * navigation that waits for it unless `parse()` has done so.
1786
1878
  */
1787
- private _resolveFlatMeta(routeName: string): Readonly<Record<string, unknown>> {
1788
- const manifest = this._manifestMeta.get(routeName);
1789
- const runtime = this._runtimeMeta.get(routeName);
1790
- if (!manifest && !runtime) return Router._EMPTY_META;
1791
- if (!runtime) return manifest!;
1792
- if (!manifest) return runtime;
1793
- return Object.freeze({ ...manifest, ...runtime });
1879
+ private _replaceFullHash(fullHash: string): void {
1880
+ HashChanger.getInstance().replaceHash(fullHash, HistoryDirection.Unknown);
1881
+ this._finishRestore();
1794
1882
  }
1795
1883
 
1796
1884
  /**
1797
- * Resolve metadata for a route with pattern-tree inheritance.
1798
- * Walks ancestor patterns shallowest-first, merging manifest and
1799
- * runtime metadata at each level, then overlays the route's own.
1885
+ * Settle the navigation that waited for the URL to be back: on `hash`, if the hash changer
1886
+ * has reported one with the URL.
1800
1887
  */
1801
- private _resolveInheritedMeta(routeName: string): Readonly<Record<string, unknown>> {
1802
- const allRoutes = this._collectRoutePatterns();
1803
- const routeEntry = allRoutes.find((r) => r.name === routeName);
1804
- if (!routeEntry) return this._resolveFlatMeta(routeName);
1805
-
1806
- // Find ancestors that have declared metadata (manifest or runtime)
1807
- const ancestors = allRoutes.filter(
1808
- (r) =>
1809
- r.name !== routeName &&
1810
- (this._manifestMeta.has(r.name) || this._runtimeMeta.has(r.name)) &&
1811
- isPatternAncestor(r.pattern, routeEntry.pattern),
1812
- );
1813
- // oxlint-disable-next-line unicorn/no-array-sort -- ancestors is a fresh array from filter()
1814
- ancestors.sort((a, b) => patternSegments(a.pattern).length - patternSegments(b.pattern).length);
1815
-
1816
- // Merge shallowest-first: root ancestor -> deeper ancestors -> own manifest -> own runtime
1817
- const merged: Record<string, unknown> = {};
1818
-
1819
- for (const ancestor of ancestors) {
1820
- const ancestorManifest = this._manifestMeta.get(ancestor.name);
1821
- if (ancestorManifest) Object.assign(merged, ancestorManifest);
1822
- const ancestorRuntime = this._runtimeMeta.get(ancestor.name);
1823
- if (ancestorRuntime) Object.assign(merged, ancestorRuntime);
1824
- }
1825
-
1826
- const ownManifest = this._manifestMeta.get(routeName);
1827
- if (ownManifest) Object.assign(merged, ownManifest);
1828
- const ownRuntime = this._runtimeMeta.get(routeName);
1829
- if (ownRuntime) Object.assign(merged, ownRuntime);
1830
-
1831
- if (Object.keys(merged).length === 0) return Router._EMPTY_META;
1832
- return Object.freeze(merged);
1888
+ private _finishRestore(hash?: string): void {
1889
+ const phase = this._phase;
1890
+ if (phase.kind !== "restoring") return;
1891
+ this._phase = IDLE;
1892
+ this._flushSettlement(hash === undefined ? phase.result : { ...phase.result, hash });
1893
+ phase.whenBack?.();
1833
1894
  }
1834
1895
 
1835
1896
  /**
1836
- * Load guard modules individually via `sap.ui.require` and register
1837
- * each resolved function with the appropriate guard API.
1897
+ * Restore the previous hash of this router without creating a history entry
1898
+ * (see {@link _undoHashChange} for the hash change of a navigation).
1899
+ * Assumes replaceHash fires hashChanged synchronously (validated by test).
1900
+ * `_currentRoute` stays unchanged because the navigation never
1901
+ * committed. The user remains on the same logical route.
1838
1902
  *
1839
- * Each module is loaded in its own `sap.ui.require` call so that a
1840
- * single invalid path only skips that guard (with a warning) rather
1841
- * than failing the entire batch. Once all loads settle, guards
1842
- * register in declaration order. Registration errors (e.g. from
1843
- * `unknownRouteRegistration: "throw"`) are caught per-module.
1903
+ * A hash that the hash changer already shows is not written again: the navigation never
1904
+ * moved it. For a nested router, writing its empty hash would add its prefix to the browser
1905
+ * hash (`shell` becomes `shell&/child/`).
1844
1906
  */
1845
- private _loadAndRegisterGuards(descriptors: GuardDescriptor[]): Promise<void> {
1846
- const promises = descriptors.map((descriptor) => {
1847
- return new Promise<{ descriptor: GuardDescriptor; moduleExport: unknown }>((resolve) => {
1848
- sap.ui.require(
1849
- [descriptor.modulePath],
1850
- (moduleExport: unknown) => {
1851
- resolve({ descriptor, moduleExport });
1852
- },
1853
- (err: Error) => {
1854
- Log.warning(
1855
- `guardRouter.guards: failed to load module "${descriptor.modulePath}", skipping`,
1856
- String(err),
1857
- LOG_COMPONENT,
1858
- );
1859
- resolve({ descriptor, moduleExport: null });
1860
- },
1861
- );
1862
- });
1863
- });
1864
- return Promise.all(promises).then((results) => {
1865
- for (const { descriptor, moduleExport } of results) {
1866
- if (moduleExport === null) continue;
1867
- const exports = resolveModuleExports(
1868
- moduleExport,
1869
- descriptor.modulePath,
1870
- descriptor.name,
1871
- descriptor.exportKey,
1872
- );
1873
- for (const { fn } of exports) {
1874
- try {
1875
- this._registerGuardFromDescriptor(descriptor, fn);
1876
- } catch (err: unknown) {
1877
- Log.error(
1878
- `guardRouter.guards: failed to register "${descriptor.modulePath}"`,
1879
- String(err),
1880
- LOG_COMPONENT,
1881
- );
1882
- }
1883
- }
1884
- }
1885
- });
1907
+ private _restoreHash(hash: string, suppressParse = true): void {
1908
+ const hashChanger = this.getHashChanger();
1909
+ if (hashChanger.getHash() === hash) return;
1910
+ this._suppressedHash = suppressParse ? hash : null;
1911
+ void hashChanger.replaceHash(hash, HistoryDirection.Unknown);
1912
+ this._suppressedHash = null;
1886
1913
  }
1887
1914
 
1888
1915
  /**
1889
- * Route a parsed guard descriptor to the correct registration method.
1916
+ * Collect all route names and their patterns from the router.
1917
+ * Skips routes whose pattern is undefined (no pattern configured).
1890
1918
  */
1891
- private _registerGuardFromDescriptor(descriptor: GuardDescriptor, guardFn: GuardFn): void {
1892
- if (descriptor.route === "*") {
1893
- this.addGuard(guardFn);
1894
- } else if (descriptor.type === "leave") {
1895
- if (!this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard")) return;
1896
- this._pipeline.addLeaveGuard(descriptor.route, guardFn);
1897
- } else {
1898
- this.addRouteGuard(descriptor.route, guardFn);
1919
+ private _collectRoutePatterns(): RoutePattern[] {
1920
+ const result: RoutePattern[] = [];
1921
+ for (const name of this._routeNames) {
1922
+ const pattern = this.getRoute(name)?.getPattern();
1923
+ if (pattern !== undefined) result.push({ name, pattern });
1899
1924
  }
1925
+ return result;
1900
1926
  }
1901
1927
 
1902
1928
  /**
1903
- * Register lazy wrapper functions that load guard modules on first use.
1904
- *
1905
- * Cherry-picked descriptors (with exportKey) get one lazy wrapper each.
1906
- * Bare-path descriptors try a sync cache probe first; if the module is
1907
- * cached (preload likely finished), all guards are expanded immediately.
1908
- * On cache miss, a single "expander" wrapper loads the module on first
1909
- * navigation, registers remaining guards, and executes the first.
1929
+ * Register one manifest guard: as the last guard of its route, or in front of the guard
1930
+ * `before`. A registration error (`unknownRouteRegistration: "throw"` for an unknown route)
1931
+ * is logged and skips the guard: no caller of the manifest config could catch it, and it
1932
+ * must not keep the router from starting.
1910
1933
  */
1911
- private _registerLazyGuards(descriptors: GuardDescriptor[]): void {
1912
- for (const descriptor of descriptors) {
1913
- const { modulePath, exportKey, name } = descriptor;
1914
-
1915
- if (exportKey !== undefined) {
1916
- // Cherry-picked: one lazy wrapper, resolves to exactly one guard
1917
- const lazyGuard = (context: GuardContext): GuardResult | PromiseLike<GuardResult> => {
1918
- const cached = sap.ui.require(modulePath) as unknown;
1919
- if (cached !== undefined) {
1920
- const exports = resolveModuleExports(cached, modulePath, name, exportKey);
1921
- if (exports.length === 0) return true;
1922
- return exports[0].fn(context);
1923
- }
1924
- return new Promise<GuardResult>((resolve, reject) => {
1925
- sap.ui.require(
1926
- [modulePath],
1927
- (mod: unknown) => {
1928
- const exports = resolveModuleExports(mod, modulePath, name, exportKey);
1929
- if (exports.length === 0) {
1930
- resolve(true);
1931
- return;
1932
- }
1933
- resolve(exports[0].fn(context));
1934
- },
1935
- (err: Error) => {
1936
- Log.warning(
1937
- `guardRouter.guards: lazy load of "${modulePath}" failed`,
1938
- String(err),
1939
- LOG_COMPONENT,
1940
- );
1941
- reject(err);
1942
- },
1943
- );
1944
- });
1945
- };
1946
- this._registerGuardFromDescriptor(descriptor, lazyGuard);
1947
- continue;
1934
+ private _registerManifestGuard(descriptor: ManifestGuardDescriptor, guardFn: GuardFn, before?: GuardFn): void {
1935
+ try {
1936
+ if (descriptor.route === "*") {
1937
+ this.addGuard(guardFn);
1938
+ return;
1948
1939
  }
1949
-
1950
- // Bare-path: try sync expansion from cache (preload likely finished)
1951
- const cached = sap.ui.require(modulePath) as unknown;
1952
- if (cached !== undefined) {
1953
- const exports = resolveModuleExports(cached, modulePath, name);
1954
- for (const exp of exports) {
1955
- this._registerGuardFromDescriptor(descriptor, exp.fn);
1956
- }
1957
- continue;
1940
+ if (descriptor.type === "leave") {
1941
+ this._handleUnknownRouteRegistration(descriptor.route, "addLeaveGuard");
1942
+ this._pipeline.addLeaveGuard(descriptor.route, guardFn, before);
1943
+ } else {
1944
+ this._handleUnknownRouteRegistration(descriptor.route, "addRouteGuard");
1945
+ this._pipeline.addEnterGuard(descriptor.route, guardFn, before);
1958
1946
  }
1947
+ this._manifestGuards.push({ descriptor, fn: guardFn });
1948
+ } catch (err: unknown) {
1949
+ Log.error(`guardRouter.guards: failed to register "${descriptor.modulePath}"`, String(err), LOG_COMPONENT);
1950
+ }
1951
+ }
1959
1952
 
1960
- // Cache miss: register an expander that loads, expands once, and runs guard[0].
1961
- // NOTE: Guards 1..N are appended to the guard array on first invocation,
1962
- // which means they execute AFTER any imperative guards registered between
1963
- // initialize() and first navigation. This differs from block mode where
1964
- // all guards occupy contiguous positions. In practice this is rare because
1965
- // the preload hint fires in the constructor and modules are typically cached
1966
- // by the time initialize() runs.
1967
- let expanded = false;
1968
- const lazyExpander = (context: GuardContext): PromiseLike<GuardResult> => {
1969
- return new Promise<GuardResult>((resolve, reject) => {
1970
- sap.ui.require(
1971
- [modulePath],
1972
- (mod: unknown) => {
1973
- const exports = resolveModuleExports(mod, modulePath, name);
1974
- if (exports.length === 0) {
1975
- resolve(true);
1976
- return;
1977
- }
1978
- if (!expanded) {
1979
- expanded = true;
1980
- for (let i = 1; i < exports.length; i++) {
1981
- this._registerGuardFromDescriptor(descriptor, exports[i].fn);
1982
- }
1983
- }
1984
- resolve(exports[0].fn(context));
1985
- },
1986
- (err: Error) => {
1987
- Log.warning(
1988
- `guardRouter.guards: lazy load of "${modulePath}" failed`,
1989
- String(err),
1990
- LOG_COMPONENT,
1991
- );
1992
- reject(err);
1993
- },
1994
- );
1995
- });
1996
- };
1997
- this._registerGuardFromDescriptor(descriptor, lazyExpander);
1953
+ /** Register the guards of each descriptor, loading their modules on first use (see `createLazyGuards`). */
1954
+ private _registerLazyGuards(descriptors: ManifestGuardDescriptor[]): void {
1955
+ for (const descriptor of descriptors) {
1956
+ for (const fn of createLazyGuards(descriptor)) this._registerManifestGuard(descriptor, fn);
1998
1957
  }
1999
1958
  }
2000
1959
 
2001
1960
  /**
2002
1961
  * Clean up guards on destroy. Bumps generation to discard pending async results.
1962
+ * A second call does nothing, like `sap.ui.core.routing.Router#destroy`.
2003
1963
  *
2004
1964
  * @since 1.0.1
2005
1965
  */
2006
1966
  override destroy(): this {
1967
+ if (this._destroyed) return this;
2007
1968
  this._destroyed = true;
2008
1969
  this._pipeline.clear();
2009
1970
  this._pendingGuardDescriptors = [];
2010
1971
  this._sourceDescriptors = [];
1972
+ this._manifestGuards = [];
2011
1973
  this._cancelPendingNavigation();
2012
- this._suppressedHash = null;
2013
1974
  this._lastSettlement = null;
2014
- this._manifestMeta.clear();
2015
- this._runtimeMeta.clear();
2016
- this._resolvedMetaCache.clear();
1975
+ this._detachHashListeners();
1976
+ this._meta.clear();
2017
1977
  super.destroy();
2018
1978
  return this;
2019
1979
  }