@loozo/angular-router 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,633 @@
1
+ const presence = new WeakMap();
2
+ function codecPresence(codec) {
3
+ return presence.get(codec);
4
+ }
5
+ function validateCodec(codec) {
6
+ if (codec === null ||
7
+ (typeof codec !== "object" && typeof codec !== "function") ||
8
+ typeof codec.parse !== "function" ||
9
+ typeof codec.stringify !== "function") {
10
+ throw new TypeError("Codec must have callable parse and stringify methods");
11
+ }
12
+ }
13
+ /**
14
+ * Preserves strings verbatim, including empty strings and literal percent text.
15
+ *
16
+ * @remarks
17
+ * Empty, dot and dotdot values are valid codec values but cannot be serialized
18
+ * into path segments by URL creation. Search values may contain them.
19
+ */
20
+ const stringParam = {
21
+ parse(raw) {
22
+ return raw;
23
+ },
24
+ stringify(value) {
25
+ if (typeof value !== "string") {
26
+ throw new TypeError("Expected a string");
27
+ }
28
+ return value;
29
+ },
30
+ };
31
+ /**
32
+ * Parses nonblank text with JavaScript `Number` and requires a finite result.
33
+ *
34
+ * @remarks
35
+ * Whitespace around numbers, exponent notation and hexadecimal text are accepted.
36
+ * Blank text, NaN and infinities throw. Stringification requires a finite number
37
+ * and uses its JavaScript string representation (including `-0` becoming `"0"`).
38
+ */
39
+ const numberParam = {
40
+ parse(raw) {
41
+ const value = Number(raw);
42
+ if (raw.trim() === "" || !Number.isFinite(value)) {
43
+ throw new Error("Expected a finite number");
44
+ }
45
+ return value;
46
+ },
47
+ stringify(value) {
48
+ if (typeof value !== "number" || !Number.isFinite(value)) {
49
+ throw new Error("Expected a finite number");
50
+ }
51
+ return String(value);
52
+ },
53
+ };
54
+ /**
55
+ * Parses only lowercase `"true"` and `"false"`, and emits those same strings.
56
+ * Other representations and nonboolean values throw.
57
+ */
58
+ const booleanParam = {
59
+ parse(raw) {
60
+ if (raw === "true") {
61
+ return true;
62
+ }
63
+ if (raw === "false") {
64
+ return false;
65
+ }
66
+ throw new Error("Expected true or false");
67
+ },
68
+ stringify(value) {
69
+ if (value === true) {
70
+ return "true";
71
+ }
72
+ if (value === false) {
73
+ return "false";
74
+ }
75
+ throw new Error("Expected a boolean");
76
+ },
77
+ };
78
+ /**
79
+ * Creates a case-sensitive string codec from a snapshotted list of members.
80
+ *
81
+ * @typeParam Values - The literal list from which the value union is inferred.
82
+ * @param values - Allowed decoded strings; an empty string is valid when listed.
83
+ * @returns A codec whose parser and stringifier reject nonmembers.
84
+ * @throws TypeError if the list or its entries are malformed.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * const tab = enumParam(["details", "reviews"]);
89
+ * tab.parse("reviews"); // "reviews"
90
+ * ```
91
+ */
92
+ function enumParam(values) {
93
+ if (!Array.isArray(values)) {
94
+ throw new TypeError("Enum values must be a string list");
95
+ }
96
+ const members = new Set();
97
+ for (const value of values) {
98
+ if (typeof value !== "string") {
99
+ throw new TypeError("Enum values must be strings");
100
+ }
101
+ members.add(value);
102
+ }
103
+ return {
104
+ parse(raw) {
105
+ if (!members.has(raw)) {
106
+ throw new Error("Unknown enum value");
107
+ }
108
+ return raw;
109
+ },
110
+ stringify(value) {
111
+ if (!members.has(value)) {
112
+ throw new Error("Unknown enum value");
113
+ }
114
+ return value;
115
+ },
116
+ };
117
+ }
118
+ /**
119
+ * Makes a search key optional without changing the handling of present values.
120
+ *
121
+ * @remarks
122
+ * Generated parsing omits absent keys; URL creation omits absent or `undefined`
123
+ * values. The wrapper's parser delegates present strings unchanged, preserving
124
+ * promises and failures. Its stringifier cannot serialize `undefined` directly.
125
+ * This wrapper is not a path codec. For optional nullable values, wrap
126
+ * {@link nullableSearchParam} with this function, not the other way around.
127
+ *
128
+ * @typeParam Value - The wrapped codec's logical value.
129
+ * @param codec - The codec used for present search values.
130
+ * @returns A search-only codec allowing omission.
131
+ * @throws TypeError if the codec lacks callable parse/stringify methods.
132
+ */
133
+ function optionalSearchParam(codec) {
134
+ validateCodec(codec);
135
+ const wrapper = {
136
+ parse(raw) {
137
+ return codec.parse(raw);
138
+ },
139
+ stringify(value) {
140
+ if (value === undefined) {
141
+ throw new TypeError("Omitted search has no scalar representation");
142
+ }
143
+ return codec.stringify(value);
144
+ },
145
+ };
146
+ presence.set(wrapper, "optional");
147
+ return wrapper;
148
+ }
149
+ /**
150
+ * Adds explicit null to a search codec, represented by the decoded text `"null"`.
151
+ *
152
+ * @remarks
153
+ * The key remains required unless wrapped with {@link optionalSearchParam}.
154
+ * Non-null values delegate unchanged, including promise/failure identity. The
155
+ * text `"null"` is reserved by this wrapper even if the inner codec accepts it.
156
+ * This wrapper is not a path codec and cannot wrap an optional search codec.
157
+ *
158
+ * @typeParam Value - The wrapped codec's non-null logical value.
159
+ * @param codec - The codec used for values other than null.
160
+ * @returns A search-only codec accepting and serializing null.
161
+ * @throws TypeError if the codec is malformed or is an optional search wrapper.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * const score = optionalSearchParam(nullableSearchParam(numberParam));
166
+ * // Omission, null, and a present number remain distinct.
167
+ * ```
168
+ */
169
+ function nullableSearchParam(codec) {
170
+ validateCodec(codec);
171
+ if (codecPresence(codec) === "optional") {
172
+ throw new TypeError("Nullable cannot wrap optional");
173
+ }
174
+ const wrapper = {
175
+ parse(raw) {
176
+ if (raw === "null") {
177
+ return null;
178
+ }
179
+ return codec.parse(raw);
180
+ },
181
+ stringify(value) {
182
+ if (value === null) {
183
+ return "null";
184
+ }
185
+ return codec.stringify(value);
186
+ },
187
+ };
188
+ presence.set(wrapper, "nullable");
189
+ return wrapper;
190
+ }
191
+
192
+ function parsePath(path) {
193
+ if (typeof path !== "string") {
194
+ throw new TypeError("Path must be a string");
195
+ }
196
+ if (path === "") {
197
+ return Object.freeze([]);
198
+ }
199
+ const segments = [];
200
+ const scalarNames = new Set();
201
+ const parts = path.split("/");
202
+ for (let index = 0; index < parts.length; index += 1) {
203
+ const part = parts[index];
204
+ if (part.startsWith("$")) {
205
+ let name = part.slice(1);
206
+ let kind = "scalar";
207
+ if (name.endsWith("[]")) {
208
+ name = name.slice(0, -2);
209
+ kind = "catchall";
210
+ }
211
+ if (name === "" ||
212
+ name === "__proto__" ||
213
+ name.startsWith("...") ||
214
+ name.includes("?") ||
215
+ name.includes("*") ||
216
+ name.includes("[]")) {
217
+ throw new TypeError(`Invalid parameter name: ${name}`);
218
+ }
219
+ if (kind === "catchall" && (index !== parts.length - 1 || scalarNames.has(name))) {
220
+ throw new TypeError("Catchall must be terminal and cannot repeat a scalar name");
221
+ }
222
+ scalarNames.add(name);
223
+ segments.push(Object.freeze({ kind, name }));
224
+ }
225
+ else {
226
+ if (part === "" ||
227
+ part === "." ||
228
+ part === ".." ||
229
+ part === "*" ||
230
+ part === "**" ||
231
+ part.startsWith(":")) {
232
+ throw new TypeError(`Invalid static segment: ${part}`);
233
+ }
234
+ if (!part.isWellFormed()) {
235
+ throw new TypeError("Static path Unicode must be well formed");
236
+ }
237
+ segments.push(Object.freeze({ kind: "static", text: part }));
238
+ }
239
+ }
240
+ return Object.freeze(segments);
241
+ }
242
+
243
+ function ownRecord(value, label, allowSymbols = false) {
244
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
245
+ throw new TypeError(`${label} must be an own record`);
246
+ }
247
+ const prototype = Object.getPrototypeOf(value);
248
+ if (prototype !== Object.prototype && prototype !== null) {
249
+ throw new TypeError(`${label} cannot contain inherited entries`);
250
+ }
251
+ for (const key of Reflect.ownKeys(value)) {
252
+ if ((!allowSymbols && typeof key !== "string") ||
253
+ !Object.prototype.propertyIsEnumerable.call(value, key)) {
254
+ throw new TypeError(`${label} contains an unsupported key`);
255
+ }
256
+ }
257
+ return value;
258
+ }
259
+ function checkKeys(record, allowed, label) {
260
+ for (const key of Object.keys(record)) {
261
+ if (!allowed.has(key)) {
262
+ throw new TypeError(`Unknown ${label} key: ${key}`);
263
+ }
264
+ }
265
+ }
266
+ function has(record, key) {
267
+ return Object.hasOwn(record, key);
268
+ }
269
+
270
+ const routes = new WeakMap();
271
+ const configKeys = new Set([
272
+ "parent",
273
+ "params",
274
+ "search",
275
+ "resolve",
276
+ "runGuardsAndResolvers",
277
+ "redirect",
278
+ "fragments",
279
+ "canActivate",
280
+ "canActivateChild",
281
+ "canMatch",
282
+ "canDeactivate",
283
+ "providers",
284
+ "title",
285
+ "data",
286
+ ]);
287
+ const policies = new Set([
288
+ "pathParamsChange",
289
+ "pathParamsOrQueryParamsChange",
290
+ "paramsChange",
291
+ "paramsOrQueryParamsChange",
292
+ "always",
293
+ ]);
294
+ const identityKey = "__loozoAngularRouterRouteId";
295
+ function routeMetadata(route) {
296
+ if (route === null || typeof route !== "object" || !routes.has(route)) {
297
+ throw new TypeError("Expected a genuine route from this package instance");
298
+ }
299
+ return routes.get(route);
300
+ }
301
+ function copyCodecs(value, path) {
302
+ const record = ownRecord(value, "Codec map");
303
+ const result = Object.create(null);
304
+ for (const key of Object.keys(record)) {
305
+ const codec = record[key];
306
+ validateCodec(codec);
307
+ if (path && codecPresence(codec) !== undefined) {
308
+ throw new TypeError("Search wrappers cannot be path codecs");
309
+ }
310
+ result[key] = codec;
311
+ }
312
+ return Object.freeze(result);
313
+ }
314
+ function snapshotRedirect(value, source) {
315
+ const redirect = ownRecord(value, "Redirect");
316
+ checkKeys(redirect, new Set(["to", "params", "search", "fragment"]), "redirect");
317
+ const target = routeMetadata(redirect.to);
318
+ const mapping = Object.create(null);
319
+ if (has(redirect, "params")) {
320
+ const supplied = ownRecord(redirect.params, "Redirect params");
321
+ checkKeys(supplied, new Set(Object.keys(target.params)), "redirect params");
322
+ for (const key of Object.keys(target.params)) {
323
+ const sourceKey = supplied[key];
324
+ if (!has(supplied, key) || typeof sourceKey !== "string" || !has(source.params, sourceKey)) {
325
+ throw new TypeError(`Missing or invalid redirect mapping: ${key}`);
326
+ }
327
+ mapping[key] = sourceKey;
328
+ }
329
+ }
330
+ else {
331
+ for (const key of Object.keys(target.params)) {
332
+ if (!has(source.params, key)) {
333
+ throw new TypeError(`Cannot forward redirect param: ${key}`);
334
+ }
335
+ mapping[key] = key;
336
+ }
337
+ }
338
+ const search = ownRecord(redirect.search, "Redirect search");
339
+ let searchSnapshot;
340
+ if (search.mode === "replace") {
341
+ checkKeys(search, new Set(["mode", "values"]), "redirect search");
342
+ const values = ownRecord(search.values, "Redirect replacement");
343
+ validateSearchValues(target.search, values);
344
+ searchSnapshot = { mode: "replace", values: Object.freeze({ ...values }) };
345
+ }
346
+ else if (search.mode === "preserve" || search.mode === "drop") {
347
+ checkKeys(search, new Set(["mode"]), "redirect search");
348
+ for (const key of Object.keys(target.search)) {
349
+ if (codecPresence(target.search[key]) === "optional") {
350
+ continue;
351
+ }
352
+ if (search.mode === "drop" ||
353
+ !has(source.search, key) ||
354
+ codecPresence(source.search[key]) === "optional") {
355
+ throw new TypeError(`Redirect cannot guarantee required search: ${key}`);
356
+ }
357
+ }
358
+ searchSnapshot = { mode: search.mode };
359
+ }
360
+ else {
361
+ throw new TypeError("Invalid redirect search policy");
362
+ }
363
+ const fragment = ownRecord(redirect.fragment, "Redirect fragment");
364
+ if (fragment.mode === "replace") {
365
+ checkKeys(fragment, new Set(["mode", "value"]), "redirect fragment");
366
+ if (typeof fragment.value !== "string" || !target.fragments.includes(fragment.value)) {
367
+ throw new TypeError("Redirect fragment must belong to target declaration");
368
+ }
369
+ }
370
+ else if (fragment.mode === "preserve" || fragment.mode === "drop") {
371
+ checkKeys(fragment, new Set(["mode"]), "redirect fragment");
372
+ }
373
+ else {
374
+ throw new TypeError("Invalid redirect fragment policy");
375
+ }
376
+ return Object.freeze({
377
+ to: redirect.to,
378
+ params: Object.freeze(mapping),
379
+ search: Object.freeze(searchSnapshot),
380
+ fragment: Object.freeze({ ...fragment }),
381
+ });
382
+ }
383
+ function validateSearchValues(codecs, values) {
384
+ checkKeys(values, new Set(Object.keys(codecs)), "search values");
385
+ for (const key of Object.keys(codecs)) {
386
+ if (codecPresence(codecs[key]) !== "optional" && !has(values, key)) {
387
+ throw new TypeError(`Missing required search: ${key}`);
388
+ }
389
+ }
390
+ }
391
+ function defineRoute(path, config) {
392
+ const supplied = ownRecord(config, "Route config");
393
+ checkKeys(supplied, configKeys, "route config");
394
+ const localSegments = parsePath(path);
395
+ let parent;
396
+ let inherited;
397
+ if (has(supplied, "parent")) {
398
+ inherited = routeMetadata(supplied.parent);
399
+ parent = supplied.parent;
400
+ for (const segment of inherited.segments) {
401
+ if (segment.kind === "catchall") {
402
+ throw new TypeError("Catchall declarations cannot have children");
403
+ }
404
+ }
405
+ }
406
+ const localNames = new Set();
407
+ for (const segment of localSegments) {
408
+ if (segment.kind !== "static") {
409
+ localNames.add(segment.name);
410
+ }
411
+ }
412
+ let localParams = Object.freeze(Object.create(null));
413
+ if (localNames.size === 0) {
414
+ if (has(supplied, "params")) {
415
+ throw new TypeError("Static paths cannot declare params");
416
+ }
417
+ }
418
+ else {
419
+ localParams = copyCodecs(supplied.params, true);
420
+ checkKeys(localParams, localNames, "local params");
421
+ for (const key of localNames) {
422
+ if (!has(localParams, key)) {
423
+ throw new TypeError(`Missing local codec: ${key}`);
424
+ }
425
+ if (inherited && has(inherited.params, key)) {
426
+ throw new TypeError(`Inherited param already owned: ${key}`);
427
+ }
428
+ }
429
+ }
430
+ let localSearch = Object.freeze(Object.create(null));
431
+ if (has(supplied, "search")) {
432
+ localSearch = copyCodecs(supplied.search, false);
433
+ }
434
+ for (const key of Object.keys(localSearch)) {
435
+ if (inherited && has(inherited.search, key)) {
436
+ throw new TypeError(`Inherited search already owned: ${key}`);
437
+ }
438
+ }
439
+ const retained = { ...supplied };
440
+ const result = { path: path };
441
+ if (has(supplied, "resolve")) {
442
+ const resolve = ownRecord(supplied.resolve, "Resolvers", true);
443
+ const copied = Object.create(null);
444
+ for (const key of Reflect.ownKeys(resolve)) {
445
+ if (key === identityKey || typeof resolve[key] !== "function") {
446
+ throw new TypeError(`Invalid resolver: ${String(key)}`);
447
+ }
448
+ copied[key] = resolve[key];
449
+ }
450
+ result.resolve = Object.freeze(copied);
451
+ retained.resolve = result.resolve;
452
+ }
453
+ if (has(supplied, "runGuardsAndResolvers")) {
454
+ const policy = supplied.runGuardsAndResolvers;
455
+ if (typeof policy !== "function" && (typeof policy !== "string" || !policies.has(policy))) {
456
+ throw new TypeError("Invalid native rerun policy");
457
+ }
458
+ result.runGuardsAndResolvers = policy;
459
+ }
460
+ for (const key of ["canActivate", "canActivateChild", "canMatch", "canDeactivate", "providers"]) {
461
+ if (!has(supplied, key)) {
462
+ continue;
463
+ }
464
+ const list = supplied[key];
465
+ if (!Array.isArray(list)) {
466
+ throw new TypeError(`${key} must be an array`);
467
+ }
468
+ if (key === "canActivate" || key === "canActivateChild" || key === "canMatch") {
469
+ for (const callback of list) {
470
+ if (typeof callback !== "function") {
471
+ throw new TypeError(`${key} entries must be callbacks`);
472
+ }
473
+ }
474
+ }
475
+ else if (key === "canDeactivate") {
476
+ for (const guard of list) {
477
+ if (guard === null ||
478
+ (typeof guard !== "function" && typeof guard !== "object" && typeof guard !== "string")) {
479
+ throw new TypeError("canDeactivate entries must be native callbacks or tokens");
480
+ }
481
+ }
482
+ }
483
+ retained[key] = Object.freeze([...list]);
484
+ }
485
+ if (has(supplied, "title") &&
486
+ typeof supplied.title !== "string" &&
487
+ typeof supplied.title !== "function") {
488
+ throw new TypeError("Invalid native title");
489
+ }
490
+ if (has(supplied, "data")) {
491
+ const data = ownRecord(supplied.data, "Static data", true);
492
+ if (has(data, identityKey)) {
493
+ throw new TypeError("Static data cannot set generated identity");
494
+ }
495
+ retained.data = Object.freeze({ ...data });
496
+ }
497
+ const fragments = [];
498
+ if (has(supplied, "fragments")) {
499
+ if (!Array.isArray(supplied.fragments)) {
500
+ throw new TypeError("Fragments must be a string list");
501
+ }
502
+ for (const name of supplied.fragments) {
503
+ if (typeof name !== "string") {
504
+ throw new TypeError("Fragment names must be strings");
505
+ }
506
+ fragments.push(name);
507
+ }
508
+ }
509
+ retained.fragments = Object.freeze(fragments);
510
+ retained.params = localParams;
511
+ retained.search = localSearch;
512
+ const metadata = {
513
+ parent,
514
+ localSegments,
515
+ segments: Object.freeze([...(inherited?.segments ?? []), ...localSegments]),
516
+ localParams,
517
+ localSearch,
518
+ params: Object.freeze({ ...inherited?.params, ...localParams }),
519
+ search: Object.freeze({ ...inherited?.search, ...localSearch }),
520
+ fragments: retained.fragments,
521
+ config: retained,
522
+ };
523
+ if (has(supplied, "redirect")) {
524
+ if (has(supplied, "canActivate") || has(supplied, "canMatch")) {
525
+ throw new TypeError("Redirect cannot declare own canActivate or canMatch");
526
+ }
527
+ retained.redirect = snapshotRedirect(supplied.redirect, metadata);
528
+ }
529
+ Object.freeze(retained);
530
+ routes.set(result, Object.freeze(metadata));
531
+ return Object.freeze(result);
532
+ }
533
+
534
+ function encode(value) {
535
+ return encodeURIComponent(value).replaceAll("(", "%28").replaceAll(")", "%29");
536
+ }
537
+ function stringify(codec, value, path) {
538
+ const text = codec.stringify(value);
539
+ if (typeof text !== "string") {
540
+ throw new TypeError("Codec stringify must return a string");
541
+ }
542
+ if (path && (text === "" || text === "." || text === "..")) {
543
+ throw new TypeError("Path output cannot be empty, dot or dotdot");
544
+ }
545
+ return encode(text);
546
+ }
547
+ function createUrl(route, values) {
548
+ const metadata = routeMetadata(route);
549
+ const options = ownRecord(values, "URL options");
550
+ checkKeys(options, new Set(["params", "search", "fragment"]), "URL options");
551
+ const paramKeys = Object.keys(metadata.params);
552
+ let params = Object.create(null);
553
+ if (paramKeys.length === 0) {
554
+ if (has(options, "params")) {
555
+ throw new TypeError("Route has no path params");
556
+ }
557
+ }
558
+ else {
559
+ params = ownRecord(options.params, "Path values");
560
+ checkKeys(params, new Set(paramKeys), "path values");
561
+ for (const key of paramKeys) {
562
+ if (!has(params, key)) {
563
+ throw new TypeError(`Missing path value: ${key}`);
564
+ }
565
+ }
566
+ }
567
+ const searchKeys = Object.keys(metadata.search).sort();
568
+ let search = Object.create(null);
569
+ if (searchKeys.length === 0) {
570
+ if (has(options, "search")) {
571
+ throw new TypeError("Route has no search declarations");
572
+ }
573
+ }
574
+ else {
575
+ if (has(options, "search")) {
576
+ search = ownRecord(options.search, "Search values");
577
+ }
578
+ validateSearchValues(metadata.search, search);
579
+ }
580
+ if (has(options, "fragment")) {
581
+ if (typeof options.fragment !== "string" || !metadata.fragments.includes(options.fragment)) {
582
+ throw new TypeError("Fragment must belong to this declaration");
583
+ }
584
+ }
585
+ // Check all cardinalities before invoking application stringifiers.
586
+ for (const segment of metadata.segments) {
587
+ if (segment.kind === "catchall" && !Array.isArray(params[segment.name])) {
588
+ throw new TypeError(`Catchall requires an array: ${segment.name}`);
589
+ }
590
+ }
591
+ const parts = [];
592
+ for (const segment of metadata.segments) {
593
+ if (segment.kind === "static") {
594
+ parts.push(encode(segment.text));
595
+ }
596
+ else if (segment.kind === "scalar") {
597
+ parts.push(stringify(metadata.params[segment.name], params[segment.name], true));
598
+ }
599
+ else {
600
+ for (const value of params[segment.name]) {
601
+ parts.push(stringify(metadata.params[segment.name], value, true));
602
+ }
603
+ }
604
+ }
605
+ let url = `/${parts.join("/")}`;
606
+ const query = [];
607
+ for (const key of searchKeys) {
608
+ const codec = metadata.search[key];
609
+ const optional = codecPresence(codec) === "optional";
610
+ if (optional && !has(search, key)) {
611
+ continue;
612
+ }
613
+ const value = search[key];
614
+ if (optional && value === undefined) {
615
+ continue;
616
+ }
617
+ query.push(`${encode(key)}=${stringify(codec, value, false)}`);
618
+ }
619
+ if (query.length > 0) {
620
+ url += `?${query.join("&")}`;
621
+ }
622
+ if (has(options, "fragment")) {
623
+ url += `#${encode(options.fragment)}`;
624
+ }
625
+ return url;
626
+ }
627
+
628
+ /**
629
+ * Generated bundle index. Do not edit.
630
+ */
631
+
632
+ export { booleanParam, codecPresence, createUrl, defineRoute, enumParam, nullableSearchParam, numberParam, optionalSearchParam, routeMetadata, stringParam };
633
+ //# sourceMappingURL=loozo-angular-router-_core.mjs.map