ui5-lib-guard-router 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/{dist/.ui5 → .ui5}/build-manifest.json +56 -8
  2. package/CHANGELOG.md +190 -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 +122 -121
  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 +882 -1020
  42. package/dist/resources/ui5/guard/router/Router-dbg.js.map +1 -1
  43. package/dist/resources/ui5/guard/router/Router.d.ts +360 -211
  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 +155 -128
  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 +1089 -1130
  65. package/src/manifest.json +5 -2
  66. package/src/types.ts +79 -22
  67. package/tsconfig.json +0 -11
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Parsing and validation of the `guardRouter` config block.
3
+ */
4
+ import Log from "sap/base/Log";
5
+ import type {
6
+ GuardLoading,
7
+ GuardRouterLogLevel,
8
+ Inheritance,
9
+ NavToPreflightMode,
10
+ UnknownRouteRegistrationPolicy,
11
+ } from "./types";
12
+ import { LOG_COMPONENT } from "./GuardPipeline";
13
+
14
+ /** Type guard for plain objects. */
15
+ export function isRecord(value: unknown): value is Record<string, unknown> {
16
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
17
+ const proto: unknown = Object.getPrototypeOf(value);
18
+ return proto === Object.prototype || proto === null;
19
+ }
20
+
21
+ /** Create a type-narrowing validator for a finite set of string literal values. */
22
+ function isOneOf<T extends string>(...values: T[]): (v: unknown) => v is T {
23
+ const set: ReadonlySet<string> = new Set(values);
24
+ return (v: unknown): v is T => typeof v === "string" && set.has(v);
25
+ }
26
+
27
+ const isUnknownRouteRegistrationPolicy = isOneOf<UnknownRouteRegistrationPolicy>("ignore", "warn", "throw");
28
+ const isNavToPreflightMode = isOneOf<NavToPreflightMode>("guard", "bypass", "off");
29
+ const isGuardLoading = isOneOf<GuardLoading>("block", "lazy");
30
+ const isInheritance = isOneOf<Inheritance>("none", "pattern-tree");
31
+
32
+ const LOG_LEVELS = {
33
+ error: Log.Level.ERROR,
34
+ warning: Log.Level.WARNING,
35
+ info: Log.Level.INFO,
36
+ debug: Log.Level.DEBUG,
37
+ } satisfies Record<GuardRouterLogLevel, unknown>;
38
+
39
+ const isLogLevel = (v: unknown): v is GuardRouterLogLevel => typeof v === "string" && Object.hasOwn(LOG_LEVELS, v);
40
+
41
+ /** Parsed guard declaration from the manifest `guards` block. */
42
+ export interface GuardDescriptor {
43
+ readonly route: string; // "*" for global, route name for per-route
44
+ readonly type: "enter" | "leave";
45
+ readonly modulePath: string;
46
+ readonly exportKey?: string;
47
+ }
48
+
49
+ /**
50
+ * Resolve a guard module path to a slash-separated AMD module path.
51
+ *
52
+ * Inspired by `sap.ui.core.routing.Target._getEffectiveObjectName()`,
53
+ * which skips namespace prepending for `"module:"`-prefixed paths. This
54
+ * function goes further: it also converts dots to slashes in a single
55
+ * step, so both dot notation (`module:some.lib.guard`) and slash
56
+ * notation (`module:some/lib/guard`) are accepted.
57
+ *
58
+ * - Paths prefixed with `"module:"` are treated as absolute (the prefix
59
+ * is stripped, dots become slashes).
60
+ * - All other paths are prefixed with the component namespace, then dots
61
+ * become slashes.
62
+ */
63
+ function resolveGuardModulePath(dotPath: string, componentNamespace: string): string {
64
+ if (dotPath.startsWith("module:")) {
65
+ return dotPath.slice("module:".length).replace(/\./g, "/");
66
+ }
67
+ const fullDotPath = componentNamespace ? componentNamespace + "." + dotPath : dotPath;
68
+ return fullDotPath.replace(/\./g, "/");
69
+ }
70
+
71
+ /**
72
+ * Split a manifest guard entry on the first `#` to separate the module path
73
+ * from an optional export key.
74
+ */
75
+ function parseGuardEntry(entry: string, componentNamespace: string): { modulePath: string; exportKey?: string } {
76
+ const hashIndex = entry.indexOf("#");
77
+ const rawPath = hashIndex === -1 ? entry : entry.slice(0, hashIndex);
78
+ const exportKey = hashIndex === -1 ? undefined : entry.slice(hashIndex + 1);
79
+
80
+ return { modulePath: resolveGuardModulePath(rawPath, componentNamespace), exportKey };
81
+ }
82
+
83
+ /**
84
+ * Parse the `guards` block from the guardRouter config into an array of
85
+ * {@link GuardDescriptor} objects.
86
+ *
87
+ * Handles:
88
+ * - `"*"` key with `string[]` -> global enter guards
89
+ * - Route name with `string[]` (shorthand) -> enter guards
90
+ * - Route name with `{ enter: [...], leave: [...] }` -> enter + leave guards
91
+ * - `"*"` with object form -> log info, treat enter as global
92
+ * - `"*"` leave -> warn, skip (global leave guards not supported)
93
+ * - Invalid entries, object values that are not arrays, unknown object keys -> warn, skip
94
+ */
95
+ function parseGuardDescriptors(guards: unknown, componentNamespace: string): GuardDescriptor[] {
96
+ if (!isRecord(guards)) {
97
+ Log.warning("guardRouter.guards is not a plain object, skipping", JSON.stringify(guards), LOG_COMPONENT);
98
+ return [];
99
+ }
100
+
101
+ const descriptors: GuardDescriptor[] = [];
102
+
103
+ function pushEntries(entries: unknown[], route: string, type: "enter" | "leave", label: string): void {
104
+ for (const entry of entries) {
105
+ if (typeof entry !== "string" || entry.length === 0) {
106
+ Log.warning(
107
+ `guardRouter.guards${label}: invalid entry, skipping`,
108
+ JSON.stringify(entry),
109
+ LOG_COMPONENT,
110
+ );
111
+ continue;
112
+ }
113
+ const parsed = parseGuardEntry(entry, componentNamespace);
114
+ descriptors.push({ route, type, ...parsed });
115
+ }
116
+ }
117
+
118
+ for (const [key, value] of Object.entries(guards)) {
119
+ if (Array.isArray(value)) {
120
+ pushEntries(value, key, "enter", `["${key}"]`);
121
+ } else if (isRecord(value)) {
122
+ if (key === "*" && value.leave !== undefined) {
123
+ Log.warning(
124
+ 'guardRouter.guards["*"].leave: global leave guards are not supported, skipping',
125
+ undefined,
126
+ LOG_COMPONENT,
127
+ );
128
+ }
129
+
130
+ for (const name of Object.keys(value)) {
131
+ if (name === "enter" || name === "leave") continue;
132
+ Log.warning(
133
+ `guardRouter.guards["${key}"].${name}: unknown key, expected enter or leave, skipping`,
134
+ undefined,
135
+ LOG_COMPONENT,
136
+ );
137
+ }
138
+
139
+ for (const type of ["enter", "leave"] as const) {
140
+ const entries = value[type];
141
+ if (entries === undefined || (key === "*" && type === "leave")) continue;
142
+ if (!Array.isArray(entries)) {
143
+ Log.warning(
144
+ `guardRouter.guards["${key}"].${type}: expected string[], skipping`,
145
+ JSON.stringify(entries),
146
+ LOG_COMPONENT,
147
+ );
148
+ continue;
149
+ }
150
+ if (key === "*") {
151
+ Log.info(
152
+ 'guardRouter.guards["*"]: object form; treating enter as global',
153
+ undefined,
154
+ LOG_COMPONENT,
155
+ );
156
+ }
157
+ pushEntries(entries, key, type, `["${key}"].${type}`);
158
+ }
159
+ } else {
160
+ Log.warning(
161
+ `guardRouter.guards["${key}"]: expected string[] or { enter?, leave? }, skipping`,
162
+ JSON.stringify(value),
163
+ LOG_COMPONENT,
164
+ );
165
+ }
166
+ }
167
+
168
+ return descriptors;
169
+ }
170
+
171
+ export interface ResolvedGuardRouterOptions {
172
+ readonly unknownRouteRegistration: UnknownRouteRegistrationPolicy;
173
+ readonly navToPreflight: NavToPreflightMode;
174
+ readonly guardLoading: GuardLoading;
175
+ readonly inheritance: Inheritance;
176
+ }
177
+
178
+ const DEFAULT_OPTIONS: ResolvedGuardRouterOptions = {
179
+ unknownRouteRegistration: "warn",
180
+ navToPreflight: "guard",
181
+ guardLoading: "lazy",
182
+ inheritance: "none",
183
+ };
184
+
185
+ function applyOption<K extends keyof ResolvedGuardRouterOptions>(
186
+ raw: Record<string, unknown>,
187
+ key: K,
188
+ guard: (v: unknown) => v is ResolvedGuardRouterOptions[K],
189
+ target: { -readonly [P in keyof ResolvedGuardRouterOptions]: ResolvedGuardRouterOptions[P] },
190
+ ): void {
191
+ const value = raw[key];
192
+ if (value === undefined) return;
193
+ if (guard(value)) {
194
+ target[key] = value;
195
+ } else {
196
+ Log.warning(`guardRouter.${key} has invalid value, using default`, JSON.stringify(value), LOG_COMPONENT);
197
+ }
198
+ }
199
+
200
+ /** Raise the page-wide level of the router's log component; a more verbose level is kept. */
201
+ function applyLogLevel(value: unknown): void {
202
+ if (value === undefined) return;
203
+ if (!isLogLevel(value)) {
204
+ // An error, not a warning: the level is not raised, so a warning would be filtered out at the default ERROR level.
205
+ Log.error("guardRouter.logLevel has invalid value, ignoring it", JSON.stringify(value), LOG_COMPONENT);
206
+ return;
207
+ }
208
+ const level = LOG_LEVELS[value];
209
+ if (level > Log.getLevel(LOG_COMPONENT)) Log.setLevel(level, LOG_COMPONENT);
210
+ }
211
+
212
+ function normalizeGuardRouterOptions(raw: unknown): ResolvedGuardRouterOptions {
213
+ if (!isRecord(raw)) {
214
+ if (raw !== undefined) {
215
+ Log.warning("guardRouter config is not a plain object, using defaults", JSON.stringify(raw), LOG_COMPONENT);
216
+ }
217
+ return DEFAULT_OPTIONS;
218
+ }
219
+
220
+ // First, so that the warnings about the other options are logged at the new level.
221
+ applyLogLevel(raw.logLevel);
222
+ const result = { ...DEFAULT_OPTIONS };
223
+ applyOption(raw, "unknownRouteRegistration", isUnknownRouteRegistrationPolicy, result);
224
+ applyOption(raw, "navToPreflight", isNavToPreflightMode, result);
225
+ applyOption(raw, "guardLoading", isGuardLoading, result);
226
+ applyOption(raw, "inheritance", isInheritance, result);
227
+ return result;
228
+ }
229
+
230
+ /** Parse the `routeMeta` block: one frozen plain object per route name. */
231
+ function parseRouteMeta(raw: unknown): Map<string, Readonly<Record<string, unknown>>> {
232
+ const routeMeta = new Map<string, Readonly<Record<string, unknown>>>();
233
+ if (raw === undefined) return routeMeta;
234
+ if (!isRecord(raw)) {
235
+ Log.warning("guardRouter.routeMeta: expected object, skipping", JSON.stringify(raw), LOG_COMPONENT);
236
+ return routeMeta;
237
+ }
238
+ for (const [routeName, meta] of Object.entries(raw)) {
239
+ if (isRecord(meta)) {
240
+ routeMeta.set(routeName, Object.freeze({ ...meta }));
241
+ } else {
242
+ Log.warning(
243
+ `guardRouter.routeMeta["${routeName}"]: expected object, skipping`,
244
+ JSON.stringify(meta),
245
+ LOG_COMPONENT,
246
+ );
247
+ }
248
+ }
249
+ return routeMeta;
250
+ }
251
+
252
+ /** The `guardRouter` config block, validated. Invalid parts are warned about and dropped. */
253
+ interface ParsedGuardRouterConfig {
254
+ readonly options: ResolvedGuardRouterOptions;
255
+ readonly routeMeta: Map<string, Readonly<Record<string, unknown>>>;
256
+ readonly guards: GuardDescriptor[];
257
+ }
258
+
259
+ /**
260
+ * Parse the `guardRouter` config block: options, `routeMeta` and the manifest `guards`.
261
+ * Guard module paths are resolved against `componentNamespace` (the owner's `sap.app/id`).
262
+ * Side effect: a valid `logLevel` raises the page-wide level of the router's log component.
263
+ */
264
+ export function parseGuardRouterConfig(raw: unknown, componentNamespace: string): ParsedGuardRouterConfig {
265
+ const options = normalizeGuardRouterOptions(raw);
266
+ if (!isRecord(raw)) return { options, routeMeta: new Map(), guards: [] };
267
+ return {
268
+ options,
269
+ routeMeta: parseRouteMeta(raw.routeMeta),
270
+ guards: raw.guards === undefined ? [] : parseGuardDescriptors(raw.guards, componentNamespace),
271
+ };
272
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Guard modules: detect a loaded module's export shape, load modules for
3
+ * manifest guards (blocking or lazy), and run a module's guards in order.
4
+ */
5
+ import Log from "sap/base/Log";
6
+ import type { GuardContext, GuardFn, GuardResult } from "./types";
7
+ import { isPromiseLike, LOG_COMPONENT, nameGuard } from "./GuardPipeline";
8
+ import { type GuardDescriptor, isRecord } from "./GuardConfig";
9
+
10
+ /** A guard function from a module, with the name its log messages show. */
11
+ interface NamedGuard {
12
+ readonly name: string;
13
+ readonly fn: GuardFn;
14
+ }
15
+
16
+ /** A guard as a module exports it: any function. Its result is checked when it runs. */
17
+ function isGuardFn(value: unknown): value is GuardFn {
18
+ return typeof value === "function";
19
+ }
20
+
21
+ /** Log a warning about a guard module entry in the manifest. */
22
+ function guardWarning(modulePath: string, detail: string): void {
23
+ Log.warning(`guardRouter.guards: "${modulePath}" ${detail}`, undefined, LOG_COMPONENT);
24
+ }
25
+
26
+ /** The last segment of a module path, by which the guards of the module are named. */
27
+ function moduleNameOf(modulePath: string): string {
28
+ return modulePath.slice(modulePath.lastIndexOf("/") + 1);
29
+ }
30
+
31
+ /** The position an export key selects: a plain non-negative integer, otherwise `NaN`. */
32
+ function positionOf(exportKey: string): number {
33
+ return /^\d+$/.test(exportKey) ? Number(exportKey) : NaN;
34
+ }
35
+
36
+ /**
37
+ * Detect the export shape of a loaded guard module and extract guard functions.
38
+ *
39
+ * Shapes and the names they get (`moduleName` is the last path segment):
40
+ * - function → single guard, named `moduleName` (or the export key when one is given);
41
+ * an export key that names a function among its own properties picks that one
42
+ * - Array → ordered guards, named `moduleName#index` (non-functions warned and skipped)
43
+ * - plain object → guards in key order, named by key (non-functions warned and skipped)
44
+ *
45
+ * The module is read as the value it returns to the UI5 loader, which has no ES module
46
+ * interop. The UI5 transpiler (babel-plugin-transform-modules-ui5) returns a default export
47
+ * as that value, with named exports beside it collapsed onto it as properties, and returns
48
+ * the exports of a module with only named exports as the object `{ __esModule: true, ... }`.
49
+ *
50
+ * When `exportKey` is set, only the matching export is returned.
51
+ * When `exportKey` is set on a function export that has no such function, the key is ignored with a debug log.
52
+ */
53
+ export function resolveModuleExports(moduleExport: unknown, modulePath: string, exportKey?: string): NamedGuard[] {
54
+ const moduleName = moduleNameOf(modulePath);
55
+
56
+ if (isGuardFn(moduleExport)) {
57
+ if (exportKey !== undefined) {
58
+ // A named export beside the default export, which the transpiler has collapsed onto it.
59
+ if (Object.hasOwn(moduleExport, exportKey)) {
60
+ const named: unknown = Reflect.get(moduleExport, exportKey);
61
+ if (isGuardFn(named)) return [{ name: exportKey, fn: named }];
62
+ }
63
+ Log.debug(
64
+ `guardRouter.guards: "${modulePath}#${exportKey}" is a single function, ignoring export key`,
65
+ undefined,
66
+ LOG_COMPONENT,
67
+ );
68
+ }
69
+ return [{ name: exportKey ?? moduleName, fn: moduleExport }];
70
+ }
71
+
72
+ if (Array.isArray(moduleExport)) {
73
+ if (moduleExport.length === 0) {
74
+ guardWarning(modulePath, "exported an empty array, skipping");
75
+ return [];
76
+ }
77
+
78
+ if (exportKey !== undefined) {
79
+ const index = positionOf(exportKey);
80
+ if (Number.isNaN(index) || index >= moduleExport.length) {
81
+ guardWarning(modulePath, `#${exportKey} - index out of range, skipping`);
82
+ return [];
83
+ }
84
+ const entry: unknown = moduleExport[index];
85
+ if (!isGuardFn(entry)) {
86
+ guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
87
+ return [];
88
+ }
89
+ return [{ name: `${moduleName}#${exportKey}`, fn: entry }];
90
+ }
91
+
92
+ const results: NamedGuard[] = [];
93
+ for (let i = 0; i < moduleExport.length; i++) {
94
+ const entry: unknown = moduleExport[i];
95
+ if (!isGuardFn(entry)) {
96
+ guardWarning(modulePath, `[${i}] is not a function, skipping`);
97
+ continue;
98
+ }
99
+ results.push({ name: `${moduleName}#${i}`, fn: entry });
100
+ }
101
+ return results;
102
+ }
103
+
104
+ if (isRecord(moduleExport)) {
105
+ // The transpiler's object of a module with only named exports has `__esModule` as an enumerable first key.
106
+ const entries = Object.entries(moduleExport).filter(([key]) => key !== "__esModule");
107
+ if (entries.length === 0) {
108
+ guardWarning(modulePath, "exported an empty object, skipping");
109
+ return [];
110
+ }
111
+
112
+ if (exportKey !== undefined) {
113
+ // A key wins over a position. A position that is not a number or out of range finds no entry.
114
+ const entry: [string, unknown] | undefined = Object.hasOwn(moduleExport, exportKey)
115
+ ? [exportKey, moduleExport[exportKey]]
116
+ : entries[positionOf(exportKey)];
117
+ if (entry === undefined) {
118
+ guardWarning(modulePath, `#${exportKey} - key not found, skipping`);
119
+ return [];
120
+ }
121
+ const [name, value] = entry;
122
+ if (!isGuardFn(value)) {
123
+ guardWarning(modulePath, `#${exportKey} is not a function, skipping`);
124
+ return [];
125
+ }
126
+ return [{ name, fn: value }];
127
+ }
128
+
129
+ const results: NamedGuard[] = [];
130
+ for (const [key, value] of entries) {
131
+ if (!isGuardFn(value)) {
132
+ guardWarning(modulePath, `.${key} is not a function, skipping`);
133
+ continue;
134
+ }
135
+ results.push({ name: key, fn: value });
136
+ }
137
+ return results;
138
+ }
139
+
140
+ guardWarning(modulePath, "did not export a function, array, or plain object, skipping");
141
+ return [];
142
+ }
143
+
144
+ /** Resolve a module's guards and name each one for log output. */
145
+ function resolveNamedGuards(moduleExport: unknown, modulePath: string, exportKey?: string): GuardFn[] {
146
+ return resolveModuleExports(moduleExport, modulePath, exportKey).map(({ name, fn }) => {
147
+ nameGuard(fn, name);
148
+ return fn;
149
+ });
150
+ }
151
+
152
+ /**
153
+ * Run guards in order, stopping at the first result that is not `true`.
154
+ * Stays synchronous until a guard returns a Promise, like the pipeline.
155
+ */
156
+ export function runGuardsInOrder(guards: GuardFn[], context: GuardContext): GuardResult | Promise<GuardResult> {
157
+ for (let i = 0; i < guards.length; i++) {
158
+ const result = guards[i](context);
159
+ if (isPromiseLike(result)) return finishGuardsAsync(result, guards.slice(i + 1), context);
160
+ if (result !== true) return result;
161
+ }
162
+ return true;
163
+ }
164
+
165
+ /** Await a pending guard result, then run the remaining guards unless the navigation was superseded. */
166
+ async function finishGuardsAsync(
167
+ pending: PromiseLike<GuardResult>,
168
+ remaining: GuardFn[],
169
+ context: GuardContext,
170
+ ): Promise<GuardResult> {
171
+ const result = await pending;
172
+ if (result !== true) return result;
173
+ if (context.signal.aborted) return false;
174
+ return runGuardsInOrder(remaining, context);
175
+ }
176
+
177
+ /** Load a guard module asynchronously. Warns with `failure` and rejects when the load fails. */
178
+ function loadGuardModule(modulePath: string, failure: string): Promise<unknown> {
179
+ return new Promise((resolve, reject) => {
180
+ sap.ui.require([modulePath], resolve, (err: Error) => {
181
+ Log.warning(`guardRouter.guards: ${failure}`, String(err), LOG_COMPONENT);
182
+ reject(err);
183
+ });
184
+ });
185
+ }
186
+
187
+ /**
188
+ * Load the modules of all descriptors (`guardLoading: "block"`) and resolve their guards.
189
+ *
190
+ * Each module is loaded in its own `sap.ui.require` call, so an invalid path
191
+ * only skips that descriptor (with a warning) instead of failing the batch.
192
+ * Results keep declaration order.
193
+ */
194
+ export function loadGuardModules<T extends GuardDescriptor>(
195
+ descriptors: T[],
196
+ ): Promise<{ descriptor: T; guards: GuardFn[] }[]> {
197
+ return Promise.all(
198
+ descriptors.map(async (descriptor) => {
199
+ const { modulePath, exportKey } = descriptor;
200
+ const guards = await loadGuardModule(modulePath, `failed to load module "${modulePath}", skipping`).then(
201
+ (moduleExport) => resolveNamedGuards(moduleExport, modulePath, exportKey),
202
+ () => [],
203
+ );
204
+ return { descriptor, guards };
205
+ }),
206
+ );
207
+ }
208
+
209
+ /**
210
+ * Create the guards to register for one descriptor (`guardLoading: "lazy"`).
211
+ *
212
+ * - Cherry-pick (`module#export`): one wrapper that loads the module on first use
213
+ * and resolves the export once, so a missing export warns once.
214
+ * - Bare path, module already cached (preload finished): the module's guards themselves.
215
+ * - Bare path, cache miss: one wrapper that loads the module on first use and runs all
216
+ * of its guards in order. Registering them on first use would miss the current
217
+ * navigation, whose guard list the pipeline is already iterating. Later navigations
218
+ * run them synchronously.
219
+ *
220
+ * A wrapper is named after the module until it resolves to a single guard, then after that guard.
221
+ */
222
+ export function createLazyGuards(descriptor: GuardDescriptor): GuardFn[] {
223
+ const { modulePath, exportKey } = descriptor;
224
+ const moduleName = moduleNameOf(modulePath);
225
+
226
+ if (exportKey === undefined) {
227
+ const cached: unknown = sap.ui.require(modulePath);
228
+ if (cached !== undefined) return resolveNamedGuards(cached, modulePath);
229
+ }
230
+
231
+ let guards: GuardFn[] | undefined;
232
+ const run = (mod: unknown, context: GuardContext): GuardResult | Promise<GuardResult> => {
233
+ if (guards === undefined) {
234
+ const resolved = resolveModuleExports(mod, modulePath, exportKey);
235
+ if (resolved.length === 1) nameGuard(wrapper, resolved[0].name);
236
+ guards = resolved.map((guard) => guard.fn);
237
+ }
238
+ return runGuardsInOrder(guards, context);
239
+ };
240
+ const wrapper = (context: GuardContext): GuardResult | PromiseLike<GuardResult> => {
241
+ const mod: unknown = sap.ui.require(modulePath);
242
+ if (mod !== undefined) return run(mod, context);
243
+ return loadGuardModule(modulePath, `lazy load of "${modulePath}" failed`).then((loadedModule) =>
244
+ context.signal.aborted ? false : run(loadedModule, context),
245
+ );
246
+ };
247
+ nameGuard(wrapper, exportKey === undefined ? moduleName : `${moduleName}#${exportKey}`);
248
+ return [wrapper];
249
+ }