kdu-router 4.0.16 → 4.2.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.
@@ -0,0 +1,3631 @@
1
+ /*!
2
+ * kdu-router v4.2.0
3
+ * (c) 2024 NKDuy
4
+ * @license MIT
5
+ */
6
+ 'use strict';
7
+
8
+ var kdu = require('kdu');
9
+ var devtoolsApi = require('@kdujs/devtools-api');
10
+
11
+ const isBrowser = typeof window !== 'undefined';
12
+
13
+ function isESModule(obj) {
14
+ return obj.__esModule || obj[Symbol.toStringTag] === 'Module';
15
+ }
16
+ const assign = Object.assign;
17
+ function applyToParams(fn, params) {
18
+ const newParams = {};
19
+ for (const key in params) {
20
+ const value = params[key];
21
+ newParams[key] = isArray(value)
22
+ ? value.map(fn)
23
+ : fn(value);
24
+ }
25
+ return newParams;
26
+ }
27
+ const noop = () => { };
28
+ /**
29
+ * Typesafe alternative to Array.isArray
30
+ * https://github.com/microsoft/TypeScript/pull/48228
31
+ */
32
+ const isArray = Array.isArray;
33
+
34
+ function warn(msg) {
35
+ // avoid using ...args as it breaks in older Edge builds
36
+ const args = Array.from(arguments).slice(1);
37
+ console.warn.apply(console, ['[Kdu Router warn]: ' + msg].concat(args));
38
+ }
39
+
40
+ const TRAILING_SLASH_RE = /\/$/;
41
+ const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, '');
42
+ /**
43
+ * Transforms a URI into a normalized history location
44
+ *
45
+ * @param parseQuery
46
+ * @param location - URI to normalize
47
+ * @param currentLocation - current absolute location. Allows resolving relative
48
+ * paths. Must start with `/`. Defaults to `/`
49
+ * @returns a normalized history location
50
+ */
51
+ function parseURL(parseQuery, location, currentLocation = '/') {
52
+ let path, query = {}, searchString = '', hash = '';
53
+ // Could use URL and URLSearchParams but IE 11 doesn't support it
54
+ // TODO: move to new URL()
55
+ const hashPos = location.indexOf('#');
56
+ let searchPos = location.indexOf('?');
57
+ // the hash appears before the search, so it's not part of the search string
58
+ if (hashPos < searchPos && hashPos >= 0) {
59
+ searchPos = -1;
60
+ }
61
+ if (searchPos > -1) {
62
+ path = location.slice(0, searchPos);
63
+ searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length);
64
+ query = parseQuery(searchString);
65
+ }
66
+ if (hashPos > -1) {
67
+ path = path || location.slice(0, hashPos);
68
+ // keep the # character
69
+ hash = location.slice(hashPos, location.length);
70
+ }
71
+ // no search and no query
72
+ path = resolveRelativePath(path != null ? path : location, currentLocation);
73
+ // empty path means a relative query or hash `?foo=f`, `#thing`
74
+ return {
75
+ fullPath: path + (searchString && '?') + searchString + hash,
76
+ path,
77
+ query,
78
+ hash,
79
+ };
80
+ }
81
+ /**
82
+ * Stringifies a URL object
83
+ *
84
+ * @param stringifyQuery
85
+ * @param location
86
+ */
87
+ function stringifyURL(stringifyQuery, location) {
88
+ const query = location.query ? stringifyQuery(location.query) : '';
89
+ return location.path + (query && '?') + query + (location.hash || '');
90
+ }
91
+ /**
92
+ * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way.
93
+ *
94
+ * @param pathname - location.pathname
95
+ * @param base - base to strip off
96
+ */
97
+ function stripBase(pathname, base) {
98
+ // no base or base is not found at the beginning
99
+ if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase()))
100
+ return pathname;
101
+ return pathname.slice(base.length) || '/';
102
+ }
103
+ /**
104
+ * Checks if two RouteLocation are equal. This means that both locations are
105
+ * pointing towards the same {@link RouteRecord} and that all `params`, `query`
106
+ * parameters and `hash` are the same
107
+ *
108
+ * @param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it.
109
+ * @param a - first {@link RouteLocation}
110
+ * @param b - second {@link RouteLocation}
111
+ */
112
+ function isSameRouteLocation(stringifyQuery, a, b) {
113
+ const aLastIndex = a.matched.length - 1;
114
+ const bLastIndex = b.matched.length - 1;
115
+ return (aLastIndex > -1 &&
116
+ aLastIndex === bLastIndex &&
117
+ isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) &&
118
+ isSameRouteLocationParams(a.params, b.params) &&
119
+ stringifyQuery(a.query) === stringifyQuery(b.query) &&
120
+ a.hash === b.hash);
121
+ }
122
+ /**
123
+ * Check if two `RouteRecords` are equal. Takes into account aliases: they are
124
+ * considered equal to the `RouteRecord` they are aliasing.
125
+ *
126
+ * @param a - first {@link RouteRecord}
127
+ * @param b - second {@link RouteRecord}
128
+ */
129
+ function isSameRouteRecord(a, b) {
130
+ // since the original record has an undefined value for aliasOf
131
+ // but all aliases point to the original record, this will always compare
132
+ // the original record
133
+ return (a.aliasOf || a) === (b.aliasOf || b);
134
+ }
135
+ function isSameRouteLocationParams(a, b) {
136
+ if (Object.keys(a).length !== Object.keys(b).length)
137
+ return false;
138
+ for (const key in a) {
139
+ if (!isSameRouteLocationParamsValue(a[key], b[key]))
140
+ return false;
141
+ }
142
+ return true;
143
+ }
144
+ function isSameRouteLocationParamsValue(a, b) {
145
+ return isArray(a)
146
+ ? isEquivalentArray(a, b)
147
+ : isArray(b)
148
+ ? isEquivalentArray(b, a)
149
+ : a === b;
150
+ }
151
+ /**
152
+ * Check if two arrays are the same or if an array with one single entry is the
153
+ * same as another primitive value. Used to check query and parameters
154
+ *
155
+ * @param a - array of values
156
+ * @param b - array of values or a single value
157
+ */
158
+ function isEquivalentArray(a, b) {
159
+ return isArray(b)
160
+ ? a.length === b.length && a.every((value, i) => value === b[i])
161
+ : a.length === 1 && a[0] === b;
162
+ }
163
+ /**
164
+ * Resolves a relative path that starts with `.`.
165
+ *
166
+ * @param to - path location we are resolving
167
+ * @param from - currentLocation.path, should start with `/`
168
+ */
169
+ function resolveRelativePath(to, from) {
170
+ if (to.startsWith('/'))
171
+ return to;
172
+ if (!from.startsWith('/')) {
173
+ warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
174
+ return to;
175
+ }
176
+ if (!to)
177
+ return from;
178
+ const fromSegments = from.split('/');
179
+ const toSegments = to.split('/');
180
+ const lastToSegment = toSegments[toSegments.length - 1];
181
+ // make . and ./ the same (../ === .., ../../ === ../..)
182
+ // this is the same behavior as new URL()
183
+ if (lastToSegment === '..' || lastToSegment === '.') {
184
+ toSegments.push('');
185
+ }
186
+ let position = fromSegments.length - 1;
187
+ let toPosition;
188
+ let segment;
189
+ for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
190
+ segment = toSegments[toPosition];
191
+ // we stay on the same position
192
+ if (segment === '.')
193
+ continue;
194
+ // go up in the from array
195
+ if (segment === '..') {
196
+ // we can't go below zero, but we still need to increment toPosition
197
+ if (position > 1)
198
+ position--;
199
+ // continue
200
+ }
201
+ // we reached a non-relative path, we stop here
202
+ else
203
+ break;
204
+ }
205
+ return (fromSegments.slice(0, position).join('/') +
206
+ '/' +
207
+ toSegments
208
+ // ensure we use at least the last element in the toSegments
209
+ .slice(toPosition - (toPosition === toSegments.length ? 1 : 0))
210
+ .join('/'));
211
+ }
212
+
213
+ var NavigationType;
214
+ (function (NavigationType) {
215
+ NavigationType["pop"] = "pop";
216
+ NavigationType["push"] = "push";
217
+ })(NavigationType || (NavigationType = {}));
218
+ var NavigationDirection;
219
+ (function (NavigationDirection) {
220
+ NavigationDirection["back"] = "back";
221
+ NavigationDirection["forward"] = "forward";
222
+ NavigationDirection["unknown"] = "";
223
+ })(NavigationDirection || (NavigationDirection = {}));
224
+ /**
225
+ * Starting location for Histories
226
+ */
227
+ const START = '';
228
+ // Generic utils
229
+ /**
230
+ * Normalizes a base by removing any trailing slash and reading the base tag if
231
+ * present.
232
+ *
233
+ * @param base - base to normalize
234
+ */
235
+ function normalizeBase(base) {
236
+ if (!base) {
237
+ if (isBrowser) {
238
+ // respect <base> tag
239
+ const baseEl = document.querySelector('base');
240
+ base = (baseEl && baseEl.getAttribute('href')) || '/';
241
+ // strip full URL origin
242
+ base = base.replace(/^\w+:\/\/[^\/]+/, '');
243
+ }
244
+ else {
245
+ base = '/';
246
+ }
247
+ }
248
+ // ensure leading slash when it was removed by the regex above avoid leading
249
+ // slash with hash because the file could be read from the disk like file://
250
+ // and the leading slash would cause problems
251
+ if (base[0] !== '/' && base[0] !== '#')
252
+ base = '/' + base;
253
+ // remove the trailing slash so all other method can just do `base + fullPath`
254
+ // to build an href
255
+ return removeTrailingSlash(base);
256
+ }
257
+ // remove any character before the hash
258
+ const BEFORE_HASH_RE = /^[^#]+#/;
259
+ function createHref(base, location) {
260
+ return base.replace(BEFORE_HASH_RE, '#') + location;
261
+ }
262
+
263
+ function getElementPosition(el, offset) {
264
+ const docRect = document.documentElement.getBoundingClientRect();
265
+ const elRect = el.getBoundingClientRect();
266
+ return {
267
+ behavior: offset.behavior,
268
+ left: elRect.left - docRect.left - (offset.left || 0),
269
+ top: elRect.top - docRect.top - (offset.top || 0),
270
+ };
271
+ }
272
+ const computeScrollPosition = () => ({
273
+ left: window.pageXOffset,
274
+ top: window.pageYOffset,
275
+ });
276
+ function scrollToPosition(position) {
277
+ let scrollToOptions;
278
+ if ('el' in position) {
279
+ const positionEl = position.el;
280
+ const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#');
281
+ /**
282
+ * `id`s can accept pretty much any characters, including CSS combinators
283
+ * like `>` or `~`. It's still possible to retrieve elements using
284
+ * `document.getElementById('~')` but it needs to be escaped when using
285
+ * `document.querySelector('#\\~')` for it to be valid. The only
286
+ * requirements for `id`s are them to be unique on the page and to not be
287
+ * empty (`id=""`). Because of that, when passing an id selector, it should
288
+ * be properly escaped for it to work with `querySelector`. We could check
289
+ * for the id selector to be simple (no CSS combinators `+ >~`) but that
290
+ * would make things inconsistent since they are valid characters for an
291
+ * `id` but would need to be escaped when using `querySelector`, breaking
292
+ * their usage and ending up in no selector returned. Selectors need to be
293
+ * escaped:
294
+ *
295
+ * - `#1-thing` becomes `#\31 -thing`
296
+ * - `#with~symbols` becomes `#with\\~symbols`
297
+ *
298
+ * - More information about the topic can be found at
299
+ * https://mathiasbynens.be/notes/html5-id-class.
300
+ * - Practical example: https://mathiasbynens.be/demo/html5-id
301
+ */
302
+ if (typeof position.el === 'string') {
303
+ if (!isIdSelector || !document.getElementById(position.el.slice(1))) {
304
+ try {
305
+ const foundEl = document.querySelector(position.el);
306
+ if (isIdSelector && foundEl) {
307
+ warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
308
+ // return to avoid other warnings
309
+ return;
310
+ }
311
+ }
312
+ catch (err) {
313
+ warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`);
314
+ // return to avoid other warnings
315
+ return;
316
+ }
317
+ }
318
+ }
319
+ const el = typeof positionEl === 'string'
320
+ ? isIdSelector
321
+ ? document.getElementById(positionEl.slice(1))
322
+ : document.querySelector(positionEl)
323
+ : positionEl;
324
+ if (!el) {
325
+ warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
326
+ return;
327
+ }
328
+ scrollToOptions = getElementPosition(el, position);
329
+ }
330
+ else {
331
+ scrollToOptions = position;
332
+ }
333
+ if ('scrollBehavior' in document.documentElement.style)
334
+ window.scrollTo(scrollToOptions);
335
+ else {
336
+ window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset);
337
+ }
338
+ }
339
+ function getScrollKey(path, delta) {
340
+ const position = history.state ? history.state.position - delta : -1;
341
+ return position + path;
342
+ }
343
+ const scrollPositions = new Map();
344
+ function saveScrollPosition(key, scrollPosition) {
345
+ scrollPositions.set(key, scrollPosition);
346
+ }
347
+ function getSavedScrollPosition(key) {
348
+ const scroll = scrollPositions.get(key);
349
+ // consume it so it's not used again
350
+ scrollPositions.delete(key);
351
+ return scroll;
352
+ }
353
+ // TODO: RFC about how to save scroll position
354
+ /**
355
+ * ScrollBehavior instance used by the router to compute and restore the scroll
356
+ * position when navigating.
357
+ */
358
+ // export interface ScrollHandler<ScrollPositionEntry extends HistoryStateValue, ScrollPosition extends ScrollPositionEntry> {
359
+ // // returns a scroll position that can be saved in history
360
+ // compute(): ScrollPositionEntry
361
+ // // can take an extended ScrollPositionEntry
362
+ // scroll(position: ScrollPosition): void
363
+ // }
364
+ // export const scrollHandler: ScrollHandler<ScrollPosition> = {
365
+ // compute: computeScroll,
366
+ // scroll: scrollToPosition,
367
+ // }
368
+
369
+ let createBaseLocation = () => location.protocol + '//' + location.host;
370
+ /**
371
+ * Creates a normalized history location from a window.location object
372
+ * @param base - The base path
373
+ * @param location - The window.location object
374
+ */
375
+ function createCurrentLocation(base, location) {
376
+ const { pathname, search, hash } = location;
377
+ // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end
378
+ const hashPos = base.indexOf('#');
379
+ if (hashPos > -1) {
380
+ let slicePos = hash.includes(base.slice(hashPos))
381
+ ? base.slice(hashPos).length
382
+ : 1;
383
+ let pathFromHash = hash.slice(slicePos);
384
+ // prepend the starting slash to hash so the url starts with /#
385
+ if (pathFromHash[0] !== '/')
386
+ pathFromHash = '/' + pathFromHash;
387
+ return stripBase(pathFromHash, '');
388
+ }
389
+ const path = stripBase(pathname, base);
390
+ return path + search + hash;
391
+ }
392
+ function useHistoryListeners(base, historyState, currentLocation, replace) {
393
+ let listeners = [];
394
+ let teardowns = [];
395
+ // TODO: should it be a stack? a Dict. Check if the popstate listener
396
+ // can trigger twice
397
+ let pauseState = null;
398
+ const popStateHandler = ({ state, }) => {
399
+ const to = createCurrentLocation(base, location);
400
+ const from = currentLocation.value;
401
+ const fromState = historyState.value;
402
+ let delta = 0;
403
+ if (state) {
404
+ currentLocation.value = to;
405
+ historyState.value = state;
406
+ // ignore the popstate and reset the pauseState
407
+ if (pauseState && pauseState === from) {
408
+ pauseState = null;
409
+ return;
410
+ }
411
+ delta = fromState ? state.position - fromState.position : 0;
412
+ }
413
+ else {
414
+ replace(to);
415
+ }
416
+ // console.log({ deltaFromCurrent })
417
+ // Here we could also revert the navigation by calling history.go(-delta)
418
+ // this listener will have to be adapted to not trigger again and to wait for the url
419
+ // to be updated before triggering the listeners. Some kind of validation function would also
420
+ // need to be passed to the listeners so the navigation can be accepted
421
+ // call all listeners
422
+ listeners.forEach(listener => {
423
+ listener(currentLocation.value, from, {
424
+ delta,
425
+ type: NavigationType.pop,
426
+ direction: delta
427
+ ? delta > 0
428
+ ? NavigationDirection.forward
429
+ : NavigationDirection.back
430
+ : NavigationDirection.unknown,
431
+ });
432
+ });
433
+ };
434
+ function pauseListeners() {
435
+ pauseState = currentLocation.value;
436
+ }
437
+ function listen(callback) {
438
+ // set up the listener and prepare teardown callbacks
439
+ listeners.push(callback);
440
+ const teardown = () => {
441
+ const index = listeners.indexOf(callback);
442
+ if (index > -1)
443
+ listeners.splice(index, 1);
444
+ };
445
+ teardowns.push(teardown);
446
+ return teardown;
447
+ }
448
+ function beforeUnloadListener() {
449
+ const { history } = window;
450
+ if (!history.state)
451
+ return;
452
+ history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), '');
453
+ }
454
+ function destroy() {
455
+ for (const teardown of teardowns)
456
+ teardown();
457
+ teardowns = [];
458
+ window.removeEventListener('popstate', popStateHandler);
459
+ window.removeEventListener('beforeunload', beforeUnloadListener);
460
+ }
461
+ // set up the listeners and prepare teardown callbacks
462
+ window.addEventListener('popstate', popStateHandler);
463
+ // TODO: could we use 'pagehide' or 'visibilitychange' instead?
464
+ // https://developer.chrome.com/blog/page-lifecycle-api/
465
+ window.addEventListener('beforeunload', beforeUnloadListener, {
466
+ passive: true,
467
+ });
468
+ return {
469
+ pauseListeners,
470
+ listen,
471
+ destroy,
472
+ };
473
+ }
474
+ /**
475
+ * Creates a state object
476
+ */
477
+ function buildState(back, current, forward, replaced = false, computeScroll = false) {
478
+ return {
479
+ back,
480
+ current,
481
+ forward,
482
+ replaced,
483
+ position: window.history.length,
484
+ scroll: computeScroll ? computeScrollPosition() : null,
485
+ };
486
+ }
487
+ function useHistoryStateNavigation(base) {
488
+ const { history, location } = window;
489
+ // private variables
490
+ const currentLocation = {
491
+ value: createCurrentLocation(base, location),
492
+ };
493
+ const historyState = { value: history.state };
494
+ // build current history entry as this is a fresh navigation
495
+ if (!historyState.value) {
496
+ changeLocation(currentLocation.value, {
497
+ back: null,
498
+ current: currentLocation.value,
499
+ forward: null,
500
+ // the length is off by one, we need to decrease it
501
+ position: history.length - 1,
502
+ replaced: true,
503
+ // don't add a scroll as the user may have an anchor, and we want
504
+ // scrollBehavior to be triggered without a saved position
505
+ scroll: null,
506
+ }, true);
507
+ }
508
+ function changeLocation(to, state, replace) {
509
+ /**
510
+ * if a base tag is provided, and we are on a normal domain, we have to
511
+ * respect the provided `base` attribute because pushState() will use it and
512
+ * potentially erase anything before the `#` where a base of
513
+ * `/folder/#` but a base of `/` would erase the `/folder/` section. If
514
+ * there is no host, the `<base>` tag makes no sense and if there isn't a
515
+ * base tag we can just use everything after the `#`.
516
+ */
517
+ const hashIndex = base.indexOf('#');
518
+ const url = hashIndex > -1
519
+ ? (location.host && document.querySelector('base')
520
+ ? base
521
+ : base.slice(hashIndex)) + to
522
+ : createBaseLocation() + base + to;
523
+ try {
524
+ // BROWSER QUIRK
525
+ // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds
526
+ history[replace ? 'replaceState' : 'pushState'](state, '', url);
527
+ historyState.value = state;
528
+ }
529
+ catch (err) {
530
+ {
531
+ warn('Error with push/replace State', err);
532
+ }
533
+ // Force the navigation, this also resets the call count
534
+ location[replace ? 'replace' : 'assign'](url);
535
+ }
536
+ }
537
+ function replace(to, data) {
538
+ const state = assign({}, history.state, buildState(historyState.value.back,
539
+ // keep back and forward entries but override current position
540
+ to, historyState.value.forward, true), data, { position: historyState.value.position });
541
+ changeLocation(to, state, true);
542
+ currentLocation.value = to;
543
+ }
544
+ function push(to, data) {
545
+ // Add to current entry the information of where we are going
546
+ // as well as saving the current position
547
+ const currentState = assign({},
548
+ // use current history state to gracefully handle a wrong call to
549
+ // history.replaceState
550
+ historyState.value, history.state, {
551
+ forward: to,
552
+ scroll: computeScrollPosition(),
553
+ });
554
+ if (!history.state) {
555
+ warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` +
556
+ `history.replaceState(history.state, '', url)\n\n` +
557
+ `You can find more information at https://kdujs-router.web.app/guide/migration/#usage-of-history-state.`);
558
+ }
559
+ changeLocation(currentState.current, currentState, true);
560
+ const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data);
561
+ changeLocation(to, state, false);
562
+ currentLocation.value = to;
563
+ }
564
+ return {
565
+ location: currentLocation,
566
+ state: historyState,
567
+ push,
568
+ replace,
569
+ };
570
+ }
571
+ /**
572
+ * Creates an HTML5 history. Most common history for single page applications.
573
+ *
574
+ * @param base -
575
+ */
576
+ function createWebHistory(base) {
577
+ base = normalizeBase(base);
578
+ const historyNavigation = useHistoryStateNavigation(base);
579
+ const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace);
580
+ function go(delta, triggerListeners = true) {
581
+ if (!triggerListeners)
582
+ historyListeners.pauseListeners();
583
+ history.go(delta);
584
+ }
585
+ const routerHistory = assign({
586
+ // it's overridden right after
587
+ location: '',
588
+ base,
589
+ go,
590
+ createHref: createHref.bind(null, base),
591
+ }, historyNavigation, historyListeners);
592
+ Object.defineProperty(routerHistory, 'location', {
593
+ enumerable: true,
594
+ get: () => historyNavigation.location.value,
595
+ });
596
+ Object.defineProperty(routerHistory, 'state', {
597
+ enumerable: true,
598
+ get: () => historyNavigation.state.value,
599
+ });
600
+ return routerHistory;
601
+ }
602
+
603
+ /**
604
+ * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere.
605
+ * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
606
+ *
607
+ * @param base - Base applied to all urls, defaults to '/'
608
+ * @returns a history object that can be passed to the router constructor
609
+ */
610
+ function createMemoryHistory(base = '') {
611
+ let listeners = [];
612
+ let queue = [START];
613
+ let position = 0;
614
+ base = normalizeBase(base);
615
+ function setLocation(location) {
616
+ position++;
617
+ if (position === queue.length) {
618
+ // we are at the end, we can simply append a new entry
619
+ queue.push(location);
620
+ }
621
+ else {
622
+ // we are in the middle, we remove everything from here in the queue
623
+ queue.splice(position);
624
+ queue.push(location);
625
+ }
626
+ }
627
+ function triggerListeners(to, from, { direction, delta }) {
628
+ const info = {
629
+ direction,
630
+ delta,
631
+ type: NavigationType.pop,
632
+ };
633
+ for (const callback of listeners) {
634
+ callback(to, from, info);
635
+ }
636
+ }
637
+ const routerHistory = {
638
+ // rewritten by Object.defineProperty
639
+ location: START,
640
+ // TODO: should be kept in queue
641
+ state: {},
642
+ base,
643
+ createHref: createHref.bind(null, base),
644
+ replace(to) {
645
+ // remove current entry and decrement position
646
+ queue.splice(position--, 1);
647
+ setLocation(to);
648
+ },
649
+ push(to, data) {
650
+ setLocation(to);
651
+ },
652
+ listen(callback) {
653
+ listeners.push(callback);
654
+ return () => {
655
+ const index = listeners.indexOf(callback);
656
+ if (index > -1)
657
+ listeners.splice(index, 1);
658
+ };
659
+ },
660
+ destroy() {
661
+ listeners = [];
662
+ queue = [START];
663
+ position = 0;
664
+ },
665
+ go(delta, shouldTrigger = true) {
666
+ const from = this.location;
667
+ const direction =
668
+ // we are considering delta === 0 going forward, but in abstract mode
669
+ // using 0 for the delta doesn't make sense like it does in html5 where
670
+ // it reloads the page
671
+ delta < 0 ? NavigationDirection.back : NavigationDirection.forward;
672
+ position = Math.max(0, Math.min(position + delta, queue.length - 1));
673
+ if (shouldTrigger) {
674
+ triggerListeners(this.location, from, {
675
+ direction,
676
+ delta,
677
+ });
678
+ }
679
+ },
680
+ };
681
+ Object.defineProperty(routerHistory, 'location', {
682
+ enumerable: true,
683
+ get: () => queue[position],
684
+ });
685
+ return routerHistory;
686
+ }
687
+
688
+ /**
689
+ * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to
690
+ * handle any URL is not possible.
691
+ *
692
+ * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `<base>` tag
693
+ * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState()
694
+ * calls**, meaning that if you use a `<base>` tag, it's `href` value **has to match this parameter** (ignoring anything
695
+ * after the `#`).
696
+ *
697
+ * @example
698
+ * ```js
699
+ * // at https://example.com/folder
700
+ * createWebHashHistory() // gives a url of `https://example.com/folder#`
701
+ * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
702
+ * // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
703
+ * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
704
+ * // you should avoid doing this because it changes the original url and breaks copying urls
705
+ * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
706
+ *
707
+ * // at file:///usr/etc/folder/index.html
708
+ * // for locations with no `host`, the base is ignored
709
+ * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
710
+ * ```
711
+ */
712
+ function createWebHashHistory(base) {
713
+ // Make sure this implementation is fine in terms of encoding, specially for IE11
714
+ // for `file://`, directly use the pathname and ignore the base
715
+ // location.pathname contains an initial `/` even at the root: `https://example.com`
716
+ base = location.host ? base || location.pathname + location.search : '';
717
+ // allow the user to provide a `#` in the middle: `/base/#/app`
718
+ if (!base.includes('#'))
719
+ base += '#';
720
+ if (!base.endsWith('#/') && !base.endsWith('#')) {
721
+ warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`);
722
+ }
723
+ return createWebHistory(base);
724
+ }
725
+
726
+ function isRouteLocation(route) {
727
+ return typeof route === 'string' || (route && typeof route === 'object');
728
+ }
729
+ function isRouteName(name) {
730
+ return typeof name === 'string' || typeof name === 'symbol';
731
+ }
732
+
733
+ /**
734
+ * Initial route location where the router is. Can be used in navigation guards
735
+ * to differentiate the initial navigation.
736
+ *
737
+ * @example
738
+ * ```js
739
+ * import { START_LOCATION } from 'kdu-router'
740
+ *
741
+ * router.beforeEach((to, from) => {
742
+ * if (from === START_LOCATION) {
743
+ * // initial navigation
744
+ * }
745
+ * })
746
+ * ```
747
+ */
748
+ const START_LOCATION_NORMALIZED = {
749
+ path: '/',
750
+ name: undefined,
751
+ params: {},
752
+ query: {},
753
+ hash: '',
754
+ fullPath: '/',
755
+ matched: [],
756
+ meta: {},
757
+ redirectedFrom: undefined,
758
+ };
759
+
760
+ const NavigationFailureSymbol = Symbol('navigation failure' );
761
+ /**
762
+ * Enumeration with all possible types for navigation failures. Can be passed to
763
+ * {@link isNavigationFailure} to check for specific failures.
764
+ */
765
+ exports.NavigationFailureType = void 0;
766
+ (function (NavigationFailureType) {
767
+ /**
768
+ * An aborted navigation is a navigation that failed because a navigation
769
+ * guard returned `false` or called `next(false)`
770
+ */
771
+ NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted";
772
+ /**
773
+ * A cancelled navigation is a navigation that failed because a more recent
774
+ * navigation finished started (not necessarily finished).
775
+ */
776
+ NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled";
777
+ /**
778
+ * A duplicated navigation is a navigation that failed because it was
779
+ * initiated while already being at the exact same location.
780
+ */
781
+ NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated";
782
+ })(exports.NavigationFailureType || (exports.NavigationFailureType = {}));
783
+ // DEV only debug messages
784
+ const ErrorTypeMessages = {
785
+ [1 /* ErrorTypes.MATCHER_NOT_FOUND */]({ location, currentLocation }) {
786
+ return `No match for\n ${JSON.stringify(location)}${currentLocation
787
+ ? '\nwhile being at\n' + JSON.stringify(currentLocation)
788
+ : ''}`;
789
+ },
790
+ [2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */]({ from, to, }) {
791
+ return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
792
+ },
793
+ [4 /* ErrorTypes.NAVIGATION_ABORTED */]({ from, to }) {
794
+ return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
795
+ },
796
+ [8 /* ErrorTypes.NAVIGATION_CANCELLED */]({ from, to }) {
797
+ return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
798
+ },
799
+ [16 /* ErrorTypes.NAVIGATION_DUPLICATED */]({ from, to }) {
800
+ return `Avoided redundant navigation to current location: "${from.fullPath}".`;
801
+ },
802
+ };
803
+ function createRouterError(type, params) {
804
+ // keep full error messages in cjs versions
805
+ {
806
+ return assign(new Error(ErrorTypeMessages[type](params)), {
807
+ type,
808
+ [NavigationFailureSymbol]: true,
809
+ }, params);
810
+ }
811
+ }
812
+ function isNavigationFailure(error, type) {
813
+ return (error instanceof Error &&
814
+ NavigationFailureSymbol in error &&
815
+ (type == null || !!(error.type & type)));
816
+ }
817
+ const propertiesToLog = ['params', 'query', 'hash'];
818
+ function stringifyRoute(to) {
819
+ if (typeof to === 'string')
820
+ return to;
821
+ if ('path' in to)
822
+ return to.path;
823
+ const location = {};
824
+ for (const key of propertiesToLog) {
825
+ if (key in to)
826
+ location[key] = to[key];
827
+ }
828
+ return JSON.stringify(location, null, 2);
829
+ }
830
+
831
+ // default pattern for a param: non-greedy everything but /
832
+ const BASE_PARAM_PATTERN = '[^/]+?';
833
+ const BASE_PATH_PARSER_OPTIONS = {
834
+ sensitive: false,
835
+ strict: false,
836
+ start: true,
837
+ end: true,
838
+ };
839
+ // Special Regex characters that must be escaped in static tokens
840
+ const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g;
841
+ /**
842
+ * Creates a path parser from an array of Segments (a segment is an array of Tokens)
843
+ *
844
+ * @param segments - array of segments returned by tokenizePath
845
+ * @param extraOptions - optional options for the regexp
846
+ * @returns a PathParser
847
+ */
848
+ function tokensToParser(segments, extraOptions) {
849
+ const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions);
850
+ // the amount of scores is the same as the length of segments except for the root segment "/"
851
+ const score = [];
852
+ // the regexp as a string
853
+ let pattern = options.start ? '^' : '';
854
+ // extracted keys
855
+ const keys = [];
856
+ for (const segment of segments) {
857
+ // the root segment needs special treatment
858
+ const segmentScores = segment.length ? [] : [90 /* PathScore.Root */];
859
+ // allow trailing slash
860
+ if (options.strict && !segment.length)
861
+ pattern += '/';
862
+ for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) {
863
+ const token = segment[tokenIndex];
864
+ // resets the score if we are inside a sub-segment /:a-other-:b
865
+ let subSegmentScore = 40 /* PathScore.Segment */ +
866
+ (options.sensitive ? 0.25 /* PathScore.BonusCaseSensitive */ : 0);
867
+ if (token.type === 0 /* TokenType.Static */) {
868
+ // prepend the slash if we are starting a new segment
869
+ if (!tokenIndex)
870
+ pattern += '/';
871
+ pattern += token.value.replace(REGEX_CHARS_RE, '\\$&');
872
+ subSegmentScore += 40 /* PathScore.Static */;
873
+ }
874
+ else if (token.type === 1 /* TokenType.Param */) {
875
+ const { value, repeatable, optional, regexp } = token;
876
+ keys.push({
877
+ name: value,
878
+ repeatable,
879
+ optional,
880
+ });
881
+ const re = regexp ? regexp : BASE_PARAM_PATTERN;
882
+ // the user provided a custom regexp /:id(\\d+)
883
+ if (re !== BASE_PARAM_PATTERN) {
884
+ subSegmentScore += 10 /* PathScore.BonusCustomRegExp */;
885
+ // make sure the regexp is valid before using it
886
+ try {
887
+ new RegExp(`(${re})`);
888
+ }
889
+ catch (err) {
890
+ throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` +
891
+ err.message);
892
+ }
893
+ }
894
+ // when we repeat we must take care of the repeating leading slash
895
+ let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`;
896
+ // prepend the slash if we are starting a new segment
897
+ if (!tokenIndex)
898
+ subPattern =
899
+ // avoid an optional / if there are more segments e.g. /:p?-static
900
+ // or /:p?-:p2
901
+ optional && segment.length < 2
902
+ ? `(?:/${subPattern})`
903
+ : '/' + subPattern;
904
+ if (optional)
905
+ subPattern += '?';
906
+ pattern += subPattern;
907
+ subSegmentScore += 20 /* PathScore.Dynamic */;
908
+ if (optional)
909
+ subSegmentScore += -8 /* PathScore.BonusOptional */;
910
+ if (repeatable)
911
+ subSegmentScore += -20 /* PathScore.BonusRepeatable */;
912
+ if (re === '.*')
913
+ subSegmentScore += -50 /* PathScore.BonusWildcard */;
914
+ }
915
+ segmentScores.push(subSegmentScore);
916
+ }
917
+ // an empty array like /home/ -> [[{home}], []]
918
+ // if (!segment.length) pattern += '/'
919
+ score.push(segmentScores);
920
+ }
921
+ // only apply the strict bonus to the last score
922
+ if (options.strict && options.end) {
923
+ const i = score.length - 1;
924
+ score[i][score[i].length - 1] += 0.7000000000000001 /* PathScore.BonusStrict */;
925
+ }
926
+ // TODO: dev only warn double trailing slash
927
+ if (!options.strict)
928
+ pattern += '/?';
929
+ if (options.end)
930
+ pattern += '$';
931
+ // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else
932
+ else if (options.strict)
933
+ pattern += '(?:/|$)';
934
+ const re = new RegExp(pattern, options.sensitive ? '' : 'i');
935
+ function parse(path) {
936
+ const match = path.match(re);
937
+ const params = {};
938
+ if (!match)
939
+ return null;
940
+ for (let i = 1; i < match.length; i++) {
941
+ const value = match[i] || '';
942
+ const key = keys[i - 1];
943
+ params[key.name] = value && key.repeatable ? value.split('/') : value;
944
+ }
945
+ return params;
946
+ }
947
+ function stringify(params) {
948
+ let path = '';
949
+ // for optional parameters to allow to be empty
950
+ let avoidDuplicatedSlash = false;
951
+ for (const segment of segments) {
952
+ if (!avoidDuplicatedSlash || !path.endsWith('/'))
953
+ path += '/';
954
+ avoidDuplicatedSlash = false;
955
+ for (const token of segment) {
956
+ if (token.type === 0 /* TokenType.Static */) {
957
+ path += token.value;
958
+ }
959
+ else if (token.type === 1 /* TokenType.Param */) {
960
+ const { value, repeatable, optional } = token;
961
+ const param = value in params ? params[value] : '';
962
+ if (isArray(param) && !repeatable) {
963
+ throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`);
964
+ }
965
+ const text = isArray(param)
966
+ ? param.join('/')
967
+ : param;
968
+ if (!text) {
969
+ if (optional) {
970
+ // if we have more than one optional param like /:a?-static we don't need to care about the optional param
971
+ if (segment.length < 2) {
972
+ // remove the last slash as we could be at the end
973
+ if (path.endsWith('/'))
974
+ path = path.slice(0, -1);
975
+ // do not append a slash on the next iteration
976
+ else
977
+ avoidDuplicatedSlash = true;
978
+ }
979
+ }
980
+ else
981
+ throw new Error(`Missing required param "${value}"`);
982
+ }
983
+ path += text;
984
+ }
985
+ }
986
+ }
987
+ // avoid empty path when we have multiple optional params
988
+ return path || '/';
989
+ }
990
+ return {
991
+ re,
992
+ score,
993
+ keys,
994
+ parse,
995
+ stringify,
996
+ };
997
+ }
998
+ /**
999
+ * Compares an array of numbers as used in PathParser.score and returns a
1000
+ * number. This function can be used to `sort` an array
1001
+ *
1002
+ * @param a - first array of numbers
1003
+ * @param b - second array of numbers
1004
+ * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
1005
+ * should be sorted first
1006
+ */
1007
+ function compareScoreArray(a, b) {
1008
+ let i = 0;
1009
+ while (i < a.length && i < b.length) {
1010
+ const diff = b[i] - a[i];
1011
+ // only keep going if diff === 0
1012
+ if (diff)
1013
+ return diff;
1014
+ i++;
1015
+ }
1016
+ // if the last subsegment was Static, the shorter segments should be sorted first
1017
+ // otherwise sort the longest segment first
1018
+ if (a.length < b.length) {
1019
+ return a.length === 1 && a[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */
1020
+ ? -1
1021
+ : 1;
1022
+ }
1023
+ else if (a.length > b.length) {
1024
+ return b.length === 1 && b[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */
1025
+ ? 1
1026
+ : -1;
1027
+ }
1028
+ return 0;
1029
+ }
1030
+ /**
1031
+ * Compare function that can be used with `sort` to sort an array of PathParser
1032
+ *
1033
+ * @param a - first PathParser
1034
+ * @param b - second PathParser
1035
+ * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b
1036
+ */
1037
+ function comparePathParserScore(a, b) {
1038
+ let i = 0;
1039
+ const aScore = a.score;
1040
+ const bScore = b.score;
1041
+ while (i < aScore.length && i < bScore.length) {
1042
+ const comp = compareScoreArray(aScore[i], bScore[i]);
1043
+ // do not return if both are equal
1044
+ if (comp)
1045
+ return comp;
1046
+ i++;
1047
+ }
1048
+ if (Math.abs(bScore.length - aScore.length) === 1) {
1049
+ if (isLastScoreNegative(aScore))
1050
+ return 1;
1051
+ if (isLastScoreNegative(bScore))
1052
+ return -1;
1053
+ }
1054
+ // if a and b share the same score entries but b has more, sort b first
1055
+ return bScore.length - aScore.length;
1056
+ // this is the ternary version
1057
+ // return aScore.length < bScore.length
1058
+ // ? 1
1059
+ // : aScore.length > bScore.length
1060
+ // ? -1
1061
+ // : 0
1062
+ }
1063
+ /**
1064
+ * This allows detecting splats at the end of a path: /home/:id(.*)*
1065
+ *
1066
+ * @param score - score to check
1067
+ * @returns true if the last entry is negative
1068
+ */
1069
+ function isLastScoreNegative(score) {
1070
+ const last = score[score.length - 1];
1071
+ return score.length > 0 && last[last.length - 1] < 0;
1072
+ }
1073
+
1074
+ const ROOT_TOKEN = {
1075
+ type: 0 /* TokenType.Static */,
1076
+ value: '',
1077
+ };
1078
+ const VALID_PARAM_RE = /[a-zA-Z0-9_]/;
1079
+ // After some profiling, the cache seems to be unnecessary because tokenizePath
1080
+ // (the slowest part of adding a route) is very fast
1081
+ // const tokenCache = new Map<string, Token[][]>()
1082
+ function tokenizePath(path) {
1083
+ if (!path)
1084
+ return [[]];
1085
+ if (path === '/')
1086
+ return [[ROOT_TOKEN]];
1087
+ if (!path.startsWith('/')) {
1088
+ throw new Error(`Route paths should start with a "/": "${path}" should be "/${path}".`
1089
+ );
1090
+ }
1091
+ // if (tokenCache.has(path)) return tokenCache.get(path)!
1092
+ function crash(message) {
1093
+ throw new Error(`ERR (${state})/"${buffer}": ${message}`);
1094
+ }
1095
+ let state = 0 /* TokenizerState.Static */;
1096
+ let previousState = state;
1097
+ const tokens = [];
1098
+ // the segment will always be valid because we get into the initial state
1099
+ // with the leading /
1100
+ let segment;
1101
+ function finalizeSegment() {
1102
+ if (segment)
1103
+ tokens.push(segment);
1104
+ segment = [];
1105
+ }
1106
+ // index on the path
1107
+ let i = 0;
1108
+ // char at index
1109
+ let char;
1110
+ // buffer of the value read
1111
+ let buffer = '';
1112
+ // custom regexp for a param
1113
+ let customRe = '';
1114
+ function consumeBuffer() {
1115
+ if (!buffer)
1116
+ return;
1117
+ if (state === 0 /* TokenizerState.Static */) {
1118
+ segment.push({
1119
+ type: 0 /* TokenType.Static */,
1120
+ value: buffer,
1121
+ });
1122
+ }
1123
+ else if (state === 1 /* TokenizerState.Param */ ||
1124
+ state === 2 /* TokenizerState.ParamRegExp */ ||
1125
+ state === 3 /* TokenizerState.ParamRegExpEnd */) {
1126
+ if (segment.length > 1 && (char === '*' || char === '+'))
1127
+ crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`);
1128
+ segment.push({
1129
+ type: 1 /* TokenType.Param */,
1130
+ value: buffer,
1131
+ regexp: customRe,
1132
+ repeatable: char === '*' || char === '+',
1133
+ optional: char === '*' || char === '?',
1134
+ });
1135
+ }
1136
+ else {
1137
+ crash('Invalid state to consume buffer');
1138
+ }
1139
+ buffer = '';
1140
+ }
1141
+ function addCharToBuffer() {
1142
+ buffer += char;
1143
+ }
1144
+ while (i < path.length) {
1145
+ char = path[i++];
1146
+ if (char === '\\' && state !== 2 /* TokenizerState.ParamRegExp */) {
1147
+ previousState = state;
1148
+ state = 4 /* TokenizerState.EscapeNext */;
1149
+ continue;
1150
+ }
1151
+ switch (state) {
1152
+ case 0 /* TokenizerState.Static */:
1153
+ if (char === '/') {
1154
+ if (buffer) {
1155
+ consumeBuffer();
1156
+ }
1157
+ finalizeSegment();
1158
+ }
1159
+ else if (char === ':') {
1160
+ consumeBuffer();
1161
+ state = 1 /* TokenizerState.Param */;
1162
+ }
1163
+ else {
1164
+ addCharToBuffer();
1165
+ }
1166
+ break;
1167
+ case 4 /* TokenizerState.EscapeNext */:
1168
+ addCharToBuffer();
1169
+ state = previousState;
1170
+ break;
1171
+ case 1 /* TokenizerState.Param */:
1172
+ if (char === '(') {
1173
+ state = 2 /* TokenizerState.ParamRegExp */;
1174
+ }
1175
+ else if (VALID_PARAM_RE.test(char)) {
1176
+ addCharToBuffer();
1177
+ }
1178
+ else {
1179
+ consumeBuffer();
1180
+ state = 0 /* TokenizerState.Static */;
1181
+ // go back one character if we were not modifying
1182
+ if (char !== '*' && char !== '?' && char !== '+')
1183
+ i--;
1184
+ }
1185
+ break;
1186
+ case 2 /* TokenizerState.ParamRegExp */:
1187
+ // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix)
1188
+ // it already works by escaping the closing )
1189
+ // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB#
1190
+ // is this really something people need since you can also write
1191
+ // /prefix_:p()_suffix
1192
+ if (char === ')') {
1193
+ // handle the escaped )
1194
+ if (customRe[customRe.length - 1] == '\\')
1195
+ customRe = customRe.slice(0, -1) + char;
1196
+ else
1197
+ state = 3 /* TokenizerState.ParamRegExpEnd */;
1198
+ }
1199
+ else {
1200
+ customRe += char;
1201
+ }
1202
+ break;
1203
+ case 3 /* TokenizerState.ParamRegExpEnd */:
1204
+ // same as finalizing a param
1205
+ consumeBuffer();
1206
+ state = 0 /* TokenizerState.Static */;
1207
+ // go back one character if we were not modifying
1208
+ if (char !== '*' && char !== '?' && char !== '+')
1209
+ i--;
1210
+ customRe = '';
1211
+ break;
1212
+ default:
1213
+ crash('Unknown state');
1214
+ break;
1215
+ }
1216
+ }
1217
+ if (state === 2 /* TokenizerState.ParamRegExp */)
1218
+ crash(`Unfinished custom RegExp for param "${buffer}"`);
1219
+ consumeBuffer();
1220
+ finalizeSegment();
1221
+ // tokenCache.set(path, tokens)
1222
+ return tokens;
1223
+ }
1224
+
1225
+ function createRouteRecordMatcher(record, parent, options) {
1226
+ const parser = tokensToParser(tokenizePath(record.path), options);
1227
+ // warn against params with the same name
1228
+ {
1229
+ const existingKeys = new Set();
1230
+ for (const key of parser.keys) {
1231
+ if (existingKeys.has(key.name))
1232
+ warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`);
1233
+ existingKeys.add(key.name);
1234
+ }
1235
+ }
1236
+ const matcher = assign(parser, {
1237
+ record,
1238
+ parent,
1239
+ // these needs to be populated by the parent
1240
+ children: [],
1241
+ alias: [],
1242
+ });
1243
+ if (parent) {
1244
+ // both are aliases or both are not aliases
1245
+ // we don't want to mix them because the order is used when
1246
+ // passing originalRecord in Matcher.addRoute
1247
+ if (!matcher.record.aliasOf === !parent.record.aliasOf)
1248
+ parent.children.push(matcher);
1249
+ }
1250
+ return matcher;
1251
+ }
1252
+
1253
+ /**
1254
+ * Creates a Router Matcher.
1255
+ *
1256
+ * @internal
1257
+ * @param routes - array of initial routes
1258
+ * @param globalOptions - global route options
1259
+ */
1260
+ function createRouterMatcher(routes, globalOptions) {
1261
+ // normalized ordered array of matchers
1262
+ const matchers = [];
1263
+ const matcherMap = new Map();
1264
+ globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions);
1265
+ function getRecordMatcher(name) {
1266
+ return matcherMap.get(name);
1267
+ }
1268
+ function addRoute(record, parent, originalRecord) {
1269
+ // used later on to remove by name
1270
+ const isRootAdd = !originalRecord;
1271
+ const mainNormalizedRecord = normalizeRouteRecord(record);
1272
+ {
1273
+ checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent);
1274
+ }
1275
+ // we might be the child of an alias
1276
+ mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record;
1277
+ const options = mergeOptions(globalOptions, record);
1278
+ // generate an array of records to correctly handle aliases
1279
+ const normalizedRecords = [
1280
+ mainNormalizedRecord,
1281
+ ];
1282
+ if ('alias' in record) {
1283
+ const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias;
1284
+ for (const alias of aliases) {
1285
+ normalizedRecords.push(assign({}, mainNormalizedRecord, {
1286
+ // this allows us to hold a copy of the `components` option
1287
+ // so that async components cache is hold on the original record
1288
+ components: originalRecord
1289
+ ? originalRecord.record.components
1290
+ : mainNormalizedRecord.components,
1291
+ path: alias,
1292
+ // we might be the child of an alias
1293
+ aliasOf: originalRecord
1294
+ ? originalRecord.record
1295
+ : mainNormalizedRecord,
1296
+ // the aliases are always of the same kind as the original since they
1297
+ // are defined on the same record
1298
+ }));
1299
+ }
1300
+ }
1301
+ let matcher;
1302
+ let originalMatcher;
1303
+ for (const normalizedRecord of normalizedRecords) {
1304
+ const { path } = normalizedRecord;
1305
+ // Build up the path for nested routes if the child isn't an absolute
1306
+ // route. Only add the / delimiter if the child path isn't empty and if the
1307
+ // parent path doesn't have a trailing slash
1308
+ if (parent && path[0] !== '/') {
1309
+ const parentPath = parent.record.path;
1310
+ const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/';
1311
+ normalizedRecord.path =
1312
+ parent.record.path + (path && connectingSlash + path);
1313
+ }
1314
+ if (normalizedRecord.path === '*') {
1315
+ throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' +
1316
+ 'See more at https://kdujs-router.web.app/guide/migration/#removed-star-or-catch-all-routes.');
1317
+ }
1318
+ // create the object beforehand, so it can be passed to children
1319
+ matcher = createRouteRecordMatcher(normalizedRecord, parent, options);
1320
+ if (parent && path[0] === '/')
1321
+ checkMissingParamsInAbsolutePath(matcher, parent);
1322
+ // if we are an alias we must tell the original record that we exist,
1323
+ // so we can be removed
1324
+ if (originalRecord) {
1325
+ originalRecord.alias.push(matcher);
1326
+ {
1327
+ checkSameParams(originalRecord, matcher);
1328
+ }
1329
+ }
1330
+ else {
1331
+ // otherwise, the first record is the original and others are aliases
1332
+ originalMatcher = originalMatcher || matcher;
1333
+ if (originalMatcher !== matcher)
1334
+ originalMatcher.alias.push(matcher);
1335
+ // remove the route if named and only for the top record (avoid in nested calls)
1336
+ // this works because the original record is the first one
1337
+ if (isRootAdd && record.name && !isAliasRecord(matcher))
1338
+ removeRoute(record.name);
1339
+ }
1340
+ if (mainNormalizedRecord.children) {
1341
+ const children = mainNormalizedRecord.children;
1342
+ for (let i = 0; i < children.length; i++) {
1343
+ addRoute(children[i], matcher, originalRecord && originalRecord.children[i]);
1344
+ }
1345
+ }
1346
+ // if there was no original record, then the first one was not an alias and all
1347
+ // other aliases (if any) need to reference this record when adding children
1348
+ originalRecord = originalRecord || matcher;
1349
+ // TODO: add normalized records for more flexibility
1350
+ // if (parent && isAliasRecord(originalRecord)) {
1351
+ // parent.children.push(originalRecord)
1352
+ // }
1353
+ // Avoid adding a record that doesn't display anything. This allows passing through records without a component to
1354
+ // not be reached and pass through the catch all route
1355
+ if ((matcher.record.components &&
1356
+ Object.keys(matcher.record.components).length) ||
1357
+ matcher.record.name ||
1358
+ matcher.record.redirect) {
1359
+ insertMatcher(matcher);
1360
+ }
1361
+ }
1362
+ return originalMatcher
1363
+ ? () => {
1364
+ // since other matchers are aliases, they should be removed by the original matcher
1365
+ removeRoute(originalMatcher);
1366
+ }
1367
+ : noop;
1368
+ }
1369
+ function removeRoute(matcherRef) {
1370
+ if (isRouteName(matcherRef)) {
1371
+ const matcher = matcherMap.get(matcherRef);
1372
+ if (matcher) {
1373
+ matcherMap.delete(matcherRef);
1374
+ matchers.splice(matchers.indexOf(matcher), 1);
1375
+ matcher.children.forEach(removeRoute);
1376
+ matcher.alias.forEach(removeRoute);
1377
+ }
1378
+ }
1379
+ else {
1380
+ const index = matchers.indexOf(matcherRef);
1381
+ if (index > -1) {
1382
+ matchers.splice(index, 1);
1383
+ if (matcherRef.record.name)
1384
+ matcherMap.delete(matcherRef.record.name);
1385
+ matcherRef.children.forEach(removeRoute);
1386
+ matcherRef.alias.forEach(removeRoute);
1387
+ }
1388
+ }
1389
+ }
1390
+ function getRoutes() {
1391
+ return matchers;
1392
+ }
1393
+ function insertMatcher(matcher) {
1394
+ let i = 0;
1395
+ while (i < matchers.length &&
1396
+ comparePathParserScore(matcher, matchers[i]) >= 0 &&
1397
+ // Adding children with empty path should still appear before the parent
1398
+ (matcher.record.path !== matchers[i].record.path ||
1399
+ !isRecordChildOf(matcher, matchers[i])))
1400
+ i++;
1401
+ matchers.splice(i, 0, matcher);
1402
+ // only add the original record to the name map
1403
+ if (matcher.record.name && !isAliasRecord(matcher))
1404
+ matcherMap.set(matcher.record.name, matcher);
1405
+ }
1406
+ function resolve(location, currentLocation) {
1407
+ let matcher;
1408
+ let params = {};
1409
+ let path;
1410
+ let name;
1411
+ if ('name' in location && location.name) {
1412
+ matcher = matcherMap.get(location.name);
1413
+ if (!matcher)
1414
+ throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, {
1415
+ location,
1416
+ });
1417
+ // warn if the user is passing invalid params so they can debug it better when they get removed
1418
+ {
1419
+ const invalidParams = Object.keys(location.params || {}).filter(paramName => !matcher.keys.find(k => k.name === paramName));
1420
+ if (invalidParams.length) {
1421
+ warn(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating.`);
1422
+ }
1423
+ }
1424
+ name = matcher.record.name;
1425
+ params = assign(
1426
+ // paramsFromLocation is a new object
1427
+ paramsFromLocation(currentLocation.params,
1428
+ // only keep params that exist in the resolved location
1429
+ // TODO: only keep optional params coming from a parent record
1430
+ matcher.keys.filter(k => !k.optional).map(k => k.name)),
1431
+ // discard any existing params in the current location that do not exist here
1432
+ // #1497 this ensures better active/exact matching
1433
+ location.params &&
1434
+ paramsFromLocation(location.params, matcher.keys.map(k => k.name)));
1435
+ // throws if cannot be stringified
1436
+ path = matcher.stringify(params);
1437
+ }
1438
+ else if ('path' in location) {
1439
+ // no need to resolve the path with the matcher as it was provided
1440
+ // this also allows the user to control the encoding
1441
+ path = location.path;
1442
+ if (!path.startsWith('/')) {
1443
+ warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in kdu-router. Please open an issue at https://kdujs-new-issue.web.app/?repo=kdujs/router.`);
1444
+ }
1445
+ matcher = matchers.find(m => m.re.test(path));
1446
+ // matcher should have a value after the loop
1447
+ if (matcher) {
1448
+ // we know the matcher works because we tested the regexp
1449
+ params = matcher.parse(path);
1450
+ name = matcher.record.name;
1451
+ }
1452
+ // location is a relative path
1453
+ }
1454
+ else {
1455
+ // match by name or path of current route
1456
+ matcher = currentLocation.name
1457
+ ? matcherMap.get(currentLocation.name)
1458
+ : matchers.find(m => m.re.test(currentLocation.path));
1459
+ if (!matcher)
1460
+ throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, {
1461
+ location,
1462
+ currentLocation,
1463
+ });
1464
+ name = matcher.record.name;
1465
+ // since we are navigating to the same location, we don't need to pick the
1466
+ // params like when `name` is provided
1467
+ params = assign({}, currentLocation.params, location.params);
1468
+ path = matcher.stringify(params);
1469
+ }
1470
+ const matched = [];
1471
+ let parentMatcher = matcher;
1472
+ while (parentMatcher) {
1473
+ // reversed order so parents are at the beginning
1474
+ matched.unshift(parentMatcher.record);
1475
+ parentMatcher = parentMatcher.parent;
1476
+ }
1477
+ return {
1478
+ name,
1479
+ path,
1480
+ params,
1481
+ matched,
1482
+ meta: mergeMetaFields(matched),
1483
+ };
1484
+ }
1485
+ // add initial routes
1486
+ routes.forEach(route => addRoute(route));
1487
+ return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher };
1488
+ }
1489
+ function paramsFromLocation(params, keys) {
1490
+ const newParams = {};
1491
+ for (const key of keys) {
1492
+ if (key in params)
1493
+ newParams[key] = params[key];
1494
+ }
1495
+ return newParams;
1496
+ }
1497
+ /**
1498
+ * Normalizes a RouteRecordRaw. Creates a copy
1499
+ *
1500
+ * @param record
1501
+ * @returns the normalized version
1502
+ */
1503
+ function normalizeRouteRecord(record) {
1504
+ return {
1505
+ path: record.path,
1506
+ redirect: record.redirect,
1507
+ name: record.name,
1508
+ meta: record.meta || {},
1509
+ aliasOf: undefined,
1510
+ beforeEnter: record.beforeEnter,
1511
+ props: normalizeRecordProps(record),
1512
+ children: record.children || [],
1513
+ instances: {},
1514
+ leaveGuards: new Set(),
1515
+ updateGuards: new Set(),
1516
+ enterCallbacks: {},
1517
+ components: 'components' in record
1518
+ ? record.components || null
1519
+ : record.component && { default: record.component },
1520
+ };
1521
+ }
1522
+ /**
1523
+ * Normalize the optional `props` in a record to always be an object similar to
1524
+ * components. Also accept a boolean for components.
1525
+ * @param record
1526
+ */
1527
+ function normalizeRecordProps(record) {
1528
+ const propsObject = {};
1529
+ // props does not exist on redirect records, but we can set false directly
1530
+ const props = record.props || false;
1531
+ if ('component' in record) {
1532
+ propsObject.default = props;
1533
+ }
1534
+ else {
1535
+ // NOTE: we could also allow a function to be applied to every component.
1536
+ // Would need user feedback for use cases
1537
+ for (const name in record.components)
1538
+ propsObject[name] = typeof props === 'boolean' ? props : props[name];
1539
+ }
1540
+ return propsObject;
1541
+ }
1542
+ /**
1543
+ * Checks if a record or any of its parent is an alias
1544
+ * @param record
1545
+ */
1546
+ function isAliasRecord(record) {
1547
+ while (record) {
1548
+ if (record.record.aliasOf)
1549
+ return true;
1550
+ record = record.parent;
1551
+ }
1552
+ return false;
1553
+ }
1554
+ /**
1555
+ * Merge meta fields of an array of records
1556
+ *
1557
+ * @param matched - array of matched records
1558
+ */
1559
+ function mergeMetaFields(matched) {
1560
+ return matched.reduce((meta, record) => assign(meta, record.meta), {});
1561
+ }
1562
+ function mergeOptions(defaults, partialOptions) {
1563
+ const options = {};
1564
+ for (const key in defaults) {
1565
+ options[key] = key in partialOptions ? partialOptions[key] : defaults[key];
1566
+ }
1567
+ return options;
1568
+ }
1569
+ function isSameParam(a, b) {
1570
+ return (a.name === b.name &&
1571
+ a.optional === b.optional &&
1572
+ a.repeatable === b.repeatable);
1573
+ }
1574
+ /**
1575
+ * Check if a path and its alias have the same required params
1576
+ *
1577
+ * @param a - original record
1578
+ * @param b - alias record
1579
+ */
1580
+ function checkSameParams(a, b) {
1581
+ for (const key of a.keys) {
1582
+ if (!key.optional && !b.keys.find(isSameParam.bind(null, key)))
1583
+ return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
1584
+ }
1585
+ for (const key of b.keys) {
1586
+ if (!key.optional && !a.keys.find(isSameParam.bind(null, key)))
1587
+ return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`);
1588
+ }
1589
+ }
1590
+ /**
1591
+ * A route with a name and a child with an empty path without a name should warn when adding the route
1592
+ *
1593
+ * @param mainNormalizedRecord - RouteRecordNormalized
1594
+ * @param parent - RouteRecordMatcher
1595
+ */
1596
+ function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) {
1597
+ if (parent &&
1598
+ parent.record.name &&
1599
+ !mainNormalizedRecord.name &&
1600
+ !mainNormalizedRecord.path) {
1601
+ warn(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`);
1602
+ }
1603
+ }
1604
+ function checkMissingParamsInAbsolutePath(record, parent) {
1605
+ for (const key of parent.keys) {
1606
+ if (!record.keys.find(isSameParam.bind(null, key)))
1607
+ return warn(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`);
1608
+ }
1609
+ }
1610
+ function isRecordChildOf(record, parent) {
1611
+ return parent.children.some(child => child === record || isRecordChildOf(record, child));
1612
+ }
1613
+
1614
+ /**
1615
+ * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ "
1616
+ * < > `
1617
+ *
1618
+ * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
1619
+ * defines some extra characters to be encoded. Most browsers do not encode them
1620
+ * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
1621
+ * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`)
1622
+ * plus `-._~`. This extra safety should be applied to query by patching the
1623
+ * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
1624
+ * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
1625
+ * into a `/` if directly typed in. The _backtick_ (`````) should also be
1626
+ * encoded everywhere because some browsers like FF encode it when directly
1627
+ * written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
1628
+ */
1629
+ // const EXTRA_RESERVED_RE = /[!'()*]/g
1630
+ // const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16)
1631
+ const HASH_RE = /#/g; // %23
1632
+ const AMPERSAND_RE = /&/g; // %26
1633
+ const SLASH_RE = /\//g; // %2F
1634
+ const EQUAL_RE = /=/g; // %3D
1635
+ const IM_RE = /\?/g; // %3F
1636
+ const PLUS_RE = /\+/g; // %2B
1637
+ /**
1638
+ * NOTE: It's not clear to me if we should encode the + symbol in queries, it
1639
+ * seems to be less flexible than not doing so and I can't find out the legacy
1640
+ * systems requiring this for regular requests like text/html. In the standard,
1641
+ * the encoding of the plus character is only mentioned for
1642
+ * application/x-www-form-urlencoded
1643
+ * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
1644
+ * leave the plus character as is in queries. To be more flexible, we allow the
1645
+ * plus character on the query, but it can also be manually encoded by the user.
1646
+ *
1647
+ * Resources:
1648
+ * - https://url.spec.whatwg.org/#urlencoded-parsing
1649
+ * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20
1650
+ */
1651
+ const ENC_BRACKET_OPEN_RE = /%5B/g; // [
1652
+ const ENC_BRACKET_CLOSE_RE = /%5D/g; // ]
1653
+ const ENC_CARET_RE = /%5E/g; // ^
1654
+ const ENC_BACKTICK_RE = /%60/g; // `
1655
+ const ENC_CURLY_OPEN_RE = /%7B/g; // {
1656
+ const ENC_PIPE_RE = /%7C/g; // |
1657
+ const ENC_CURLY_CLOSE_RE = /%7D/g; // }
1658
+ const ENC_SPACE_RE = /%20/g; // }
1659
+ /**
1660
+ * Encode characters that need to be encoded on the path, search and hash
1661
+ * sections of the URL.
1662
+ *
1663
+ * @internal
1664
+ * @param text - string to encode
1665
+ * @returns encoded string
1666
+ */
1667
+ function commonEncode(text) {
1668
+ return encodeURI('' + text)
1669
+ .replace(ENC_PIPE_RE, '|')
1670
+ .replace(ENC_BRACKET_OPEN_RE, '[')
1671
+ .replace(ENC_BRACKET_CLOSE_RE, ']');
1672
+ }
1673
+ /**
1674
+ * Encode characters that need to be encoded on the hash section of the URL.
1675
+ *
1676
+ * @param text - string to encode
1677
+ * @returns encoded string
1678
+ */
1679
+ function encodeHash(text) {
1680
+ return commonEncode(text)
1681
+ .replace(ENC_CURLY_OPEN_RE, '{')
1682
+ .replace(ENC_CURLY_CLOSE_RE, '}')
1683
+ .replace(ENC_CARET_RE, '^');
1684
+ }
1685
+ /**
1686
+ * Encode characters that need to be encoded query values on the query
1687
+ * section of the URL.
1688
+ *
1689
+ * @param text - string to encode
1690
+ * @returns encoded string
1691
+ */
1692
+ function encodeQueryValue(text) {
1693
+ return (commonEncode(text)
1694
+ // Encode the space as +, encode the + to differentiate it from the space
1695
+ .replace(PLUS_RE, '%2B')
1696
+ .replace(ENC_SPACE_RE, '+')
1697
+ .replace(HASH_RE, '%23')
1698
+ .replace(AMPERSAND_RE, '%26')
1699
+ .replace(ENC_BACKTICK_RE, '`')
1700
+ .replace(ENC_CURLY_OPEN_RE, '{')
1701
+ .replace(ENC_CURLY_CLOSE_RE, '}')
1702
+ .replace(ENC_CARET_RE, '^'));
1703
+ }
1704
+ /**
1705
+ * Like `encodeQueryValue` but also encodes the `=` character.
1706
+ *
1707
+ * @param text - string to encode
1708
+ */
1709
+ function encodeQueryKey(text) {
1710
+ return encodeQueryValue(text).replace(EQUAL_RE, '%3D');
1711
+ }
1712
+ /**
1713
+ * Encode characters that need to be encoded on the path section of the URL.
1714
+ *
1715
+ * @param text - string to encode
1716
+ * @returns encoded string
1717
+ */
1718
+ function encodePath(text) {
1719
+ return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F');
1720
+ }
1721
+ /**
1722
+ * Encode characters that need to be encoded on the path section of the URL as a
1723
+ * param. This function encodes everything {@link encodePath} does plus the
1724
+ * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty
1725
+ * string instead.
1726
+ *
1727
+ * @param text - string to encode
1728
+ * @returns encoded string
1729
+ */
1730
+ function encodeParam(text) {
1731
+ return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F');
1732
+ }
1733
+ /**
1734
+ * Decode text using `decodeURIComponent`. Returns the original text if it
1735
+ * fails.
1736
+ *
1737
+ * @param text - string to decode
1738
+ * @returns decoded string
1739
+ */
1740
+ function decode(text) {
1741
+ try {
1742
+ return decodeURIComponent('' + text);
1743
+ }
1744
+ catch (err) {
1745
+ warn(`Error decoding "${text}". Using original value`);
1746
+ }
1747
+ return '' + text;
1748
+ }
1749
+
1750
+ /**
1751
+ * Transforms a queryString into a {@link LocationQuery} object. Accept both, a
1752
+ * version with the leading `?` and without Should work as URLSearchParams
1753
+
1754
+ * @internal
1755
+ *
1756
+ * @param search - search string to parse
1757
+ * @returns a query object
1758
+ */
1759
+ function parseQuery(search) {
1760
+ const query = {};
1761
+ // avoid creating an object with an empty key and empty value
1762
+ // because of split('&')
1763
+ if (search === '' || search === '?')
1764
+ return query;
1765
+ const hasLeadingIM = search[0] === '?';
1766
+ const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&');
1767
+ for (let i = 0; i < searchParams.length; ++i) {
1768
+ // pre decode the + into space
1769
+ const searchParam = searchParams[i].replace(PLUS_RE, ' ');
1770
+ // allow the = character
1771
+ const eqPos = searchParam.indexOf('=');
1772
+ const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
1773
+ const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
1774
+ if (key in query) {
1775
+ // an extra variable for ts types
1776
+ let currentValue = query[key];
1777
+ if (!isArray(currentValue)) {
1778
+ currentValue = query[key] = [currentValue];
1779
+ }
1780
+ currentValue.push(value);
1781
+ }
1782
+ else {
1783
+ query[key] = value;
1784
+ }
1785
+ }
1786
+ return query;
1787
+ }
1788
+ /**
1789
+ * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
1790
+ * doesn't prepend a `?`
1791
+ *
1792
+ * @internal
1793
+ *
1794
+ * @param query - query object to stringify
1795
+ * @returns string version of the query without the leading `?`
1796
+ */
1797
+ function stringifyQuery(query) {
1798
+ let search = '';
1799
+ for (let key in query) {
1800
+ const value = query[key];
1801
+ key = encodeQueryKey(key);
1802
+ if (value == null) {
1803
+ // only null adds the value
1804
+ if (value !== undefined) {
1805
+ search += (search.length ? '&' : '') + key;
1806
+ }
1807
+ continue;
1808
+ }
1809
+ // keep null values
1810
+ const values = isArray(value)
1811
+ ? value.map(v => v && encodeQueryValue(v))
1812
+ : [value && encodeQueryValue(value)];
1813
+ values.forEach(value => {
1814
+ // skip undefined values in arrays as if they were not present
1815
+ // smaller code than using filter
1816
+ if (value !== undefined) {
1817
+ // only append & with non-empty search
1818
+ search += (search.length ? '&' : '') + key;
1819
+ if (value != null)
1820
+ search += '=' + value;
1821
+ }
1822
+ });
1823
+ }
1824
+ return search;
1825
+ }
1826
+ /**
1827
+ * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting
1828
+ * numbers into strings, removing keys with an undefined value and replacing
1829
+ * undefined with null in arrays
1830
+ *
1831
+ * @param query - query object to normalize
1832
+ * @returns a normalized query object
1833
+ */
1834
+ function normalizeQuery(query) {
1835
+ const normalizedQuery = {};
1836
+ for (const key in query) {
1837
+ const value = query[key];
1838
+ if (value !== undefined) {
1839
+ normalizedQuery[key] = isArray(value)
1840
+ ? value.map(v => (v == null ? null : '' + v))
1841
+ : value == null
1842
+ ? value
1843
+ : '' + value;
1844
+ }
1845
+ }
1846
+ return normalizedQuery;
1847
+ }
1848
+
1849
+ /**
1850
+ * RouteRecord being rendered by the closest ancestor Router View. Used for
1851
+ * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
1852
+ * Location Matched
1853
+ *
1854
+ * @internal
1855
+ */
1856
+ const matchedRouteKey = Symbol('router view location matched' );
1857
+ /**
1858
+ * Allows overriding the router view depth to control which component in
1859
+ * `matched` is rendered. rvd stands for Router View Depth
1860
+ *
1861
+ * @internal
1862
+ */
1863
+ const viewDepthKey = Symbol('router view depth' );
1864
+ /**
1865
+ * Allows overriding the router instance returned by `useRouter` in tests. r
1866
+ * stands for router
1867
+ *
1868
+ * @internal
1869
+ */
1870
+ const routerKey = Symbol('router' );
1871
+ /**
1872
+ * Allows overriding the current route returned by `useRoute` in tests. rl
1873
+ * stands for route location
1874
+ *
1875
+ * @internal
1876
+ */
1877
+ const routeLocationKey = Symbol('route location' );
1878
+ /**
1879
+ * Allows overriding the current route used by router-view. Internally this is
1880
+ * used when the `route` prop is passed.
1881
+ *
1882
+ * @internal
1883
+ */
1884
+ const routerViewLocationKey = Symbol('router view location' );
1885
+
1886
+ /**
1887
+ * Create a list of callbacks that can be reset. Used to create before and after navigation guards list
1888
+ */
1889
+ function useCallbacks() {
1890
+ let handlers = [];
1891
+ function add(handler) {
1892
+ handlers.push(handler);
1893
+ return () => {
1894
+ const i = handlers.indexOf(handler);
1895
+ if (i > -1)
1896
+ handlers.splice(i, 1);
1897
+ };
1898
+ }
1899
+ function reset() {
1900
+ handlers = [];
1901
+ }
1902
+ return {
1903
+ add,
1904
+ list: () => handlers,
1905
+ reset,
1906
+ };
1907
+ }
1908
+
1909
+ function registerGuard(record, name, guard) {
1910
+ const removeFromList = () => {
1911
+ record[name].delete(guard);
1912
+ };
1913
+ kdu.onUnmounted(removeFromList);
1914
+ kdu.onDeactivated(removeFromList);
1915
+ kdu.onActivated(() => {
1916
+ record[name].add(guard);
1917
+ });
1918
+ record[name].add(guard);
1919
+ }
1920
+ /**
1921
+ * Add a navigation guard that triggers whenever the component for the current
1922
+ * location is about to be left. Similar to {@link beforeRouteLeave} but can be
1923
+ * used in any component. The guard is removed when the component is unmounted.
1924
+ *
1925
+ * @param leaveGuard - {@link NavigationGuard}
1926
+ */
1927
+ function onBeforeRouteLeave(leaveGuard) {
1928
+ if (!kdu.getCurrentInstance()) {
1929
+ warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function');
1930
+ return;
1931
+ }
1932
+ const activeRecord = kdu.inject(matchedRouteKey,
1933
+ // to avoid warning
1934
+ {}).value;
1935
+ if (!activeRecord) {
1936
+ warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside a component child of <router-view>. Maybe you called it inside of App.kdu?');
1937
+ return;
1938
+ }
1939
+ registerGuard(activeRecord, 'leaveGuards', leaveGuard);
1940
+ }
1941
+ /**
1942
+ * Add a navigation guard that triggers whenever the current location is about
1943
+ * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
1944
+ * component. The guard is removed when the component is unmounted.
1945
+ *
1946
+ * @param updateGuard - {@link NavigationGuard}
1947
+ */
1948
+ function onBeforeRouteUpdate(updateGuard) {
1949
+ if (!kdu.getCurrentInstance()) {
1950
+ warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function');
1951
+ return;
1952
+ }
1953
+ const activeRecord = kdu.inject(matchedRouteKey,
1954
+ // to avoid warning
1955
+ {}).value;
1956
+ if (!activeRecord) {
1957
+ warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside a component child of <router-view>. Maybe you called it inside of App.kdu?');
1958
+ return;
1959
+ }
1960
+ registerGuard(activeRecord, 'updateGuards', updateGuard);
1961
+ }
1962
+ function guardToPromiseFn(guard, to, from, record, name) {
1963
+ // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place
1964
+ const enterCallbackArray = record &&
1965
+ // name is defined if record is because of the function overload
1966
+ (record.enterCallbacks[name] = record.enterCallbacks[name] || []);
1967
+ return () => new Promise((resolve, reject) => {
1968
+ const next = (valid) => {
1969
+ if (valid === false) {
1970
+ reject(createRouterError(4 /* ErrorTypes.NAVIGATION_ABORTED */, {
1971
+ from,
1972
+ to,
1973
+ }));
1974
+ }
1975
+ else if (valid instanceof Error) {
1976
+ reject(valid);
1977
+ }
1978
+ else if (isRouteLocation(valid)) {
1979
+ reject(createRouterError(2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */, {
1980
+ from: to,
1981
+ to: valid,
1982
+ }));
1983
+ }
1984
+ else {
1985
+ if (enterCallbackArray &&
1986
+ // since enterCallbackArray is truthy, both record and name also are
1987
+ record.enterCallbacks[name] === enterCallbackArray &&
1988
+ typeof valid === 'function') {
1989
+ enterCallbackArray.push(valid);
1990
+ }
1991
+ resolve();
1992
+ }
1993
+ };
1994
+ // wrapping with Promise.resolve allows it to work with both async and sync guards
1995
+ const guardReturn = guard.call(record && record.instances[name], to, from, canOnlyBeCalledOnce(next, to, from) );
1996
+ let guardCall = Promise.resolve(guardReturn);
1997
+ if (guard.length < 3)
1998
+ guardCall = guardCall.then(next);
1999
+ if (guard.length > 2) {
2000
+ const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`;
2001
+ if (typeof guardReturn === 'object' && 'then' in guardReturn) {
2002
+ guardCall = guardCall.then(resolvedValue => {
2003
+ // @ts-expect-error: _called is added at canOnlyBeCalledOnce
2004
+ if (!next._called) {
2005
+ warn(message);
2006
+ return Promise.reject(new Error('Invalid navigation guard'));
2007
+ }
2008
+ return resolvedValue;
2009
+ });
2010
+ }
2011
+ else if (guardReturn !== undefined) {
2012
+ // @ts-expect-error: _called is added at canOnlyBeCalledOnce
2013
+ if (!next._called) {
2014
+ warn(message);
2015
+ reject(new Error('Invalid navigation guard'));
2016
+ return;
2017
+ }
2018
+ }
2019
+ }
2020
+ guardCall.catch(err => reject(err));
2021
+ });
2022
+ }
2023
+ function canOnlyBeCalledOnce(next, to, from) {
2024
+ let called = 0;
2025
+ return function () {
2026
+ if (called++ === 1)
2027
+ warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`);
2028
+ // @ts-expect-error: we put it in the original one because it's easier to check
2029
+ next._called = true;
2030
+ if (called === 1)
2031
+ next.apply(null, arguments);
2032
+ };
2033
+ }
2034
+ function extractComponentsGuards(matched, guardType, to, from) {
2035
+ const guards = [];
2036
+ for (const record of matched) {
2037
+ if (!record.components && !record.children.length) {
2038
+ warn(`Record with path "${record.path}" is either missing a "component(s)"` +
2039
+ ` or "children" property.`);
2040
+ }
2041
+ for (const name in record.components) {
2042
+ let rawComponent = record.components[name];
2043
+ {
2044
+ if (!rawComponent ||
2045
+ (typeof rawComponent !== 'object' &&
2046
+ typeof rawComponent !== 'function')) {
2047
+ warn(`Component "${name}" in record with path "${record.path}" is not` +
2048
+ ` a valid component. Received "${String(rawComponent)}".`);
2049
+ // throw to ensure we stop here but warn to ensure the message isn't
2050
+ // missed by the user
2051
+ throw new Error('Invalid route component');
2052
+ }
2053
+ else if ('then' in rawComponent) {
2054
+ // warn if user wrote import('/component.kdu') instead of () =>
2055
+ // import('./component.kdu')
2056
+ warn(`Component "${name}" in record with path "${record.path}" is a ` +
2057
+ `Promise instead of a function that returns a Promise. Did you ` +
2058
+ `write "import('./MyPage.kdu')" instead of ` +
2059
+ `"() => import('./MyPage.kdu')" ? This will break in ` +
2060
+ `production if not fixed.`);
2061
+ const promise = rawComponent;
2062
+ rawComponent = () => promise;
2063
+ }
2064
+ else if (rawComponent.__asyncLoader &&
2065
+ // warn only once per component
2066
+ !rawComponent.__warnedDefineAsync) {
2067
+ rawComponent.__warnedDefineAsync = true;
2068
+ warn(`Component "${name}" in record with path "${record.path}" is defined ` +
2069
+ `using "defineAsyncComponent()". ` +
2070
+ `Write "() => import('./MyPage.kdu')" instead of ` +
2071
+ `"defineAsyncComponent(() => import('./MyPage.kdu'))".`);
2072
+ }
2073
+ }
2074
+ // skip update and leave guards if the route component is not mounted
2075
+ if (guardType !== 'beforeRouteEnter' && !record.instances[name])
2076
+ continue;
2077
+ if (isRouteComponent(rawComponent)) {
2078
+ // __kccOpts is added by kdu-class-component and contain the regular options
2079
+ const options = rawComponent.__kccOpts || rawComponent;
2080
+ const guard = options[guardType];
2081
+ guard && guards.push(guardToPromiseFn(guard, to, from, record, name));
2082
+ }
2083
+ else {
2084
+ // start requesting the chunk already
2085
+ let componentPromise = rawComponent();
2086
+ if (!('catch' in componentPromise)) {
2087
+ warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`);
2088
+ componentPromise = Promise.resolve(componentPromise);
2089
+ }
2090
+ guards.push(() => componentPromise.then(resolved => {
2091
+ if (!resolved)
2092
+ return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`));
2093
+ const resolvedComponent = isESModule(resolved)
2094
+ ? resolved.default
2095
+ : resolved;
2096
+ // replace the function with the resolved component
2097
+ // cannot be null or undefined because we went into the for loop
2098
+ record.components[name] = resolvedComponent;
2099
+ // __kccOpts is added by kdu-class-component and contain the regular options
2100
+ const options = resolvedComponent.__kccOpts || resolvedComponent;
2101
+ const guard = options[guardType];
2102
+ return guard && guardToPromiseFn(guard, to, from, record, name)();
2103
+ }));
2104
+ }
2105
+ }
2106
+ }
2107
+ return guards;
2108
+ }
2109
+ /**
2110
+ * Allows differentiating lazy components from functional components and kdu-class-component
2111
+ * @internal
2112
+ *
2113
+ * @param component
2114
+ */
2115
+ function isRouteComponent(component) {
2116
+ return (typeof component === 'object' ||
2117
+ 'displayName' in component ||
2118
+ 'props' in component ||
2119
+ '__kccOpts' in component);
2120
+ }
2121
+ /**
2122
+ * Ensures a route is loaded, so it can be passed as o prop to `<RouterView>`.
2123
+ *
2124
+ * @param route - resolved route to load
2125
+ */
2126
+ function loadRouteLocation(route) {
2127
+ return route.matched.every(record => record.redirect)
2128
+ ? Promise.reject(new Error('Cannot load a route that redirects.'))
2129
+ : Promise.all(route.matched.map(record => record.components &&
2130
+ Promise.all(Object.keys(record.components).reduce((promises, name) => {
2131
+ const rawComponent = record.components[name];
2132
+ if (typeof rawComponent === 'function' &&
2133
+ !('displayName' in rawComponent)) {
2134
+ promises.push(rawComponent().then(resolved => {
2135
+ if (!resolved)
2136
+ return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`));
2137
+ const resolvedComponent = isESModule(resolved)
2138
+ ? resolved.default
2139
+ : resolved;
2140
+ // replace the function with the resolved component
2141
+ // cannot be null or undefined because we went into the for loop
2142
+ record.components[name] = resolvedComponent;
2143
+ return;
2144
+ }));
2145
+ }
2146
+ return promises;
2147
+ }, [])))).then(() => route);
2148
+ }
2149
+
2150
+ // TODO: we could allow currentRoute as a prop to expose `isActive` and
2151
+ // `isExactActive` behavior should go through an RFC
2152
+ function useLink(props) {
2153
+ const router = kdu.inject(routerKey);
2154
+ const currentRoute = kdu.inject(routeLocationKey);
2155
+ const route = kdu.computed(() => router.resolve(kdu.unref(props.to)));
2156
+ const activeRecordIndex = kdu.computed(() => {
2157
+ const { matched } = route.value;
2158
+ const { length } = matched;
2159
+ const routeMatched = matched[length - 1];
2160
+ const currentMatched = currentRoute.matched;
2161
+ if (!routeMatched || !currentMatched.length)
2162
+ return -1;
2163
+ const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched));
2164
+ if (index > -1)
2165
+ return index;
2166
+ // possible parent record
2167
+ const parentRecordPath = getOriginalPath(matched[length - 2]);
2168
+ return (
2169
+ // we are dealing with nested routes
2170
+ length > 1 &&
2171
+ // if the parent and matched route have the same path, this link is
2172
+ // referring to the empty child. Or we currently are on a different
2173
+ // child of the same parent
2174
+ getOriginalPath(routeMatched) === parentRecordPath &&
2175
+ // avoid comparing the child with its parent
2176
+ currentMatched[currentMatched.length - 1].path !== parentRecordPath
2177
+ ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2]))
2178
+ : index);
2179
+ });
2180
+ const isActive = kdu.computed(() => activeRecordIndex.value > -1 &&
2181
+ includesParams(currentRoute.params, route.value.params));
2182
+ const isExactActive = kdu.computed(() => activeRecordIndex.value > -1 &&
2183
+ activeRecordIndex.value === currentRoute.matched.length - 1 &&
2184
+ isSameRouteLocationParams(currentRoute.params, route.value.params));
2185
+ function navigate(e = {}) {
2186
+ if (guardEvent(e)) {
2187
+ return router[kdu.unref(props.replace) ? 'replace' : 'push'](kdu.unref(props.to)
2188
+ // avoid uncaught errors are they are logged anyway
2189
+ ).catch(noop);
2190
+ }
2191
+ return Promise.resolve();
2192
+ }
2193
+ // devtools only
2194
+ if (isBrowser) {
2195
+ const instance = kdu.getCurrentInstance();
2196
+ if (instance) {
2197
+ const linkContextDevtools = {
2198
+ route: route.value,
2199
+ isActive: isActive.value,
2200
+ isExactActive: isExactActive.value,
2201
+ };
2202
+ // @ts-expect-error: this is internal
2203
+ instance.__krl_devtools = instance.__krl_devtools || [];
2204
+ // @ts-expect-error: this is internal
2205
+ instance.__krl_devtools.push(linkContextDevtools);
2206
+ kdu.watchEffect(() => {
2207
+ linkContextDevtools.route = route.value;
2208
+ linkContextDevtools.isActive = isActive.value;
2209
+ linkContextDevtools.isExactActive = isExactActive.value;
2210
+ }, { flush: 'post' });
2211
+ }
2212
+ }
2213
+ /**
2214
+ * NOTE: update {@link _RouterLinkI}'s `$slots` type when updating this
2215
+ */
2216
+ return {
2217
+ route,
2218
+ href: kdu.computed(() => route.value.href),
2219
+ isActive,
2220
+ isExactActive,
2221
+ navigate,
2222
+ };
2223
+ }
2224
+ const RouterLinkImpl = /*#__PURE__*/ kdu.defineComponent({
2225
+ name: 'RouterLink',
2226
+ compatConfig: { MODE: 3 },
2227
+ props: {
2228
+ to: {
2229
+ type: [String, Object],
2230
+ required: true,
2231
+ },
2232
+ replace: Boolean,
2233
+ activeClass: String,
2234
+ // inactiveClass: String,
2235
+ exactActiveClass: String,
2236
+ custom: Boolean,
2237
+ ariaCurrentValue: {
2238
+ type: String,
2239
+ default: 'page',
2240
+ },
2241
+ },
2242
+ useLink,
2243
+ setup(props, { slots }) {
2244
+ const link = kdu.reactive(useLink(props));
2245
+ const { options } = kdu.inject(routerKey);
2246
+ const elClass = kdu.computed(() => ({
2247
+ [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive,
2248
+ // [getLinkClass(
2249
+ // props.inactiveClass,
2250
+ // options.linkInactiveClass,
2251
+ // 'router-link-inactive'
2252
+ // )]: !link.isExactActive,
2253
+ [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive,
2254
+ }));
2255
+ return () => {
2256
+ const children = slots.default && slots.default(link);
2257
+ return props.custom
2258
+ ? children
2259
+ : kdu.h('a', {
2260
+ 'aria-current': link.isExactActive
2261
+ ? props.ariaCurrentValue
2262
+ : null,
2263
+ href: link.href,
2264
+ // this would override user added attrs but Kdu will still add
2265
+ // the listener, so we end up triggering both
2266
+ onClick: link.navigate,
2267
+ class: elClass.value,
2268
+ }, children);
2269
+ };
2270
+ },
2271
+ });
2272
+ // export the public type for h/tsx inference
2273
+ // also to avoid inline import() in generated d.ts files
2274
+ /**
2275
+ * Component to render a link that triggers a navigation on click.
2276
+ */
2277
+ const RouterLink = RouterLinkImpl;
2278
+ function guardEvent(e) {
2279
+ // don't redirect with control keys
2280
+ if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey)
2281
+ return;
2282
+ // don't redirect when preventDefault called
2283
+ if (e.defaultPrevented)
2284
+ return;
2285
+ // don't redirect on right click
2286
+ if (e.button !== undefined && e.button !== 0)
2287
+ return;
2288
+ // don't redirect if `target="_blank"`
2289
+ // @ts-expect-error getAttribute does exist
2290
+ if (e.currentTarget && e.currentTarget.getAttribute) {
2291
+ // @ts-expect-error getAttribute exists
2292
+ const target = e.currentTarget.getAttribute('target');
2293
+ if (/\b_blank\b/i.test(target))
2294
+ return;
2295
+ }
2296
+ // this may be a Weex event which doesn't have this method
2297
+ if (e.preventDefault)
2298
+ e.preventDefault();
2299
+ return true;
2300
+ }
2301
+ function includesParams(outer, inner) {
2302
+ for (const key in inner) {
2303
+ const innerValue = inner[key];
2304
+ const outerValue = outer[key];
2305
+ if (typeof innerValue === 'string') {
2306
+ if (innerValue !== outerValue)
2307
+ return false;
2308
+ }
2309
+ else {
2310
+ if (!isArray(outerValue) ||
2311
+ outerValue.length !== innerValue.length ||
2312
+ innerValue.some((value, i) => value !== outerValue[i]))
2313
+ return false;
2314
+ }
2315
+ }
2316
+ return true;
2317
+ }
2318
+ /**
2319
+ * Get the original path value of a record by following its aliasOf
2320
+ * @param record
2321
+ */
2322
+ function getOriginalPath(record) {
2323
+ return record ? (record.aliasOf ? record.aliasOf.path : record.path) : '';
2324
+ }
2325
+ /**
2326
+ * Utility class to get the active class based on defaults.
2327
+ * @param propClass
2328
+ * @param globalClass
2329
+ * @param defaultClass
2330
+ */
2331
+ const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null
2332
+ ? propClass
2333
+ : globalClass != null
2334
+ ? globalClass
2335
+ : defaultClass;
2336
+
2337
+ const RouterViewImpl = /*#__PURE__*/ kdu.defineComponent({
2338
+ name: 'RouterView',
2339
+ // #674 we manually inherit them
2340
+ inheritAttrs: false,
2341
+ props: {
2342
+ name: {
2343
+ type: String,
2344
+ default: 'default',
2345
+ },
2346
+ route: Object,
2347
+ },
2348
+ // Better compat for @kdujs/compat users
2349
+ compatConfig: { MODE: 3 },
2350
+ setup(props, { attrs, slots }) {
2351
+ warnDeprecatedUsage();
2352
+ const injectedRoute = kdu.inject(routerViewLocationKey);
2353
+ const routeToDisplay = kdu.computed(() => props.route || injectedRoute.value);
2354
+ const injectedDepth = kdu.inject(viewDepthKey, 0);
2355
+ // The depth changes based on empty components option, which allows passthrough routes e.g. routes with children
2356
+ // that are used to reuse the `path` property
2357
+ const depth = kdu.computed(() => {
2358
+ let initialDepth = kdu.unref(injectedDepth);
2359
+ const { matched } = routeToDisplay.value;
2360
+ let matchedRoute;
2361
+ while ((matchedRoute = matched[initialDepth]) &&
2362
+ !matchedRoute.components) {
2363
+ initialDepth++;
2364
+ }
2365
+ return initialDepth;
2366
+ });
2367
+ const matchedRouteRef = kdu.computed(() => routeToDisplay.value.matched[depth.value]);
2368
+ kdu.provide(viewDepthKey, kdu.computed(() => depth.value + 1));
2369
+ kdu.provide(matchedRouteKey, matchedRouteRef);
2370
+ kdu.provide(routerViewLocationKey, routeToDisplay);
2371
+ const viewRef = kdu.ref();
2372
+ // watch at the same time the component instance, the route record we are
2373
+ // rendering, and the name
2374
+ kdu.watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => {
2375
+ // copy reused instances
2376
+ if (to) {
2377
+ // this will update the instance for new instances as well as reused
2378
+ // instances when navigating to a new route
2379
+ to.instances[name] = instance;
2380
+ // the component instance is reused for a different route or name, so
2381
+ // we copy any saved update or leave guards. With async setup, the
2382
+ // mounting component will mount before the matchedRoute changes,
2383
+ // making instance === oldInstance, so we check if guards have been
2384
+ // added before. This works because we remove guards when
2385
+ // unmounting/deactivating components
2386
+ if (from && from !== to && instance && instance === oldInstance) {
2387
+ if (!to.leaveGuards.size) {
2388
+ to.leaveGuards = from.leaveGuards;
2389
+ }
2390
+ if (!to.updateGuards.size) {
2391
+ to.updateGuards = from.updateGuards;
2392
+ }
2393
+ }
2394
+ }
2395
+ // trigger beforeRouteEnter next callbacks
2396
+ if (instance &&
2397
+ to &&
2398
+ // if there is no instance but to and from are the same this might be
2399
+ // the first visit
2400
+ (!from || !isSameRouteRecord(to, from) || !oldInstance)) {
2401
+ (to.enterCallbacks[name] || []).forEach(callback => callback(instance));
2402
+ }
2403
+ }, { flush: 'post' });
2404
+ return () => {
2405
+ const route = routeToDisplay.value;
2406
+ // we need the value at the time we render because when we unmount, we
2407
+ // navigated to a different location so the value is different
2408
+ const currentName = props.name;
2409
+ const matchedRoute = matchedRouteRef.value;
2410
+ const ViewComponent = matchedRoute && matchedRoute.components[currentName];
2411
+ if (!ViewComponent) {
2412
+ return normalizeSlot(slots.default, { Component: ViewComponent, route });
2413
+ }
2414
+ // props from route configuration
2415
+ const routePropsOption = matchedRoute.props[currentName];
2416
+ const routeProps = routePropsOption
2417
+ ? routePropsOption === true
2418
+ ? route.params
2419
+ : typeof routePropsOption === 'function'
2420
+ ? routePropsOption(route)
2421
+ : routePropsOption
2422
+ : null;
2423
+ const onKnodeUnmounted = knode => {
2424
+ // remove the instance reference to prevent leak
2425
+ if (knode.component.isUnmounted) {
2426
+ matchedRoute.instances[currentName] = null;
2427
+ }
2428
+ };
2429
+ const component = kdu.h(ViewComponent, assign({}, routeProps, attrs, {
2430
+ onKnodeUnmounted,
2431
+ ref: viewRef,
2432
+ }));
2433
+ if (isBrowser &&
2434
+ component.ref) {
2435
+ // TODO: can display if it's an alias, its props
2436
+ const info = {
2437
+ depth: depth.value,
2438
+ name: matchedRoute.name,
2439
+ path: matchedRoute.path,
2440
+ meta: matchedRoute.meta,
2441
+ };
2442
+ const internalInstances = isArray(component.ref)
2443
+ ? component.ref.map(r => r.i)
2444
+ : [component.ref.i];
2445
+ internalInstances.forEach(instance => {
2446
+ // @ts-expect-error
2447
+ instance.__krv_devtools = info;
2448
+ });
2449
+ }
2450
+ return (
2451
+ // pass the knode to the slot as a prop.
2452
+ // h and <component :is="..."> both accept knodes
2453
+ normalizeSlot(slots.default, { Component: component, route }) ||
2454
+ component);
2455
+ };
2456
+ },
2457
+ });
2458
+ function normalizeSlot(slot, data) {
2459
+ if (!slot)
2460
+ return null;
2461
+ const slotContent = slot(data);
2462
+ return slotContent.length === 1 ? slotContent[0] : slotContent;
2463
+ }
2464
+ // export the public type for h/tsx inference
2465
+ // also to avoid inline import() in generated d.ts files
2466
+ /**
2467
+ * Component to display the current route the user is at.
2468
+ */
2469
+ const RouterView = RouterViewImpl;
2470
+ // warn against deprecated usage with <transition> & <keep-alive>
2471
+ // due to functional component being no longer eager in Kdu 3
2472
+ function warnDeprecatedUsage() {
2473
+ const instance = kdu.getCurrentInstance();
2474
+ const parentName = instance.parent && instance.parent.type.name;
2475
+ const parentSubTreeType = instance.parent && instance.parent.subTree && instance.parent.subTree.type;
2476
+ if (parentName &&
2477
+ (parentName === 'KeepAlive' || parentName.includes('Transition')) &&
2478
+ typeof parentSubTreeType === 'object' &&
2479
+ parentSubTreeType.name === 'RouterView') {
2480
+ const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition';
2481
+ warn(`<router-view> can no longer be used directly inside <transition> or <keep-alive>.\n` +
2482
+ `Use slot props instead:\n\n` +
2483
+ `<router-view k-slot="{ Component }">\n` +
2484
+ ` <${comp}>\n` +
2485
+ ` <component :is="Component" />\n` +
2486
+ ` </${comp}>\n` +
2487
+ `</router-view>`);
2488
+ }
2489
+ }
2490
+
2491
+ /**
2492
+ * Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Kdu instances).
2493
+ *
2494
+ * @param routeLocation - routeLocation to format
2495
+ * @param tooltip - optional tooltip
2496
+ * @returns a copy of the routeLocation
2497
+ */
2498
+ function formatRouteLocation(routeLocation, tooltip) {
2499
+ const copy = assign({}, routeLocation, {
2500
+ // remove variables that can contain kdu instances
2501
+ matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])),
2502
+ });
2503
+ return {
2504
+ _custom: {
2505
+ type: null,
2506
+ readOnly: true,
2507
+ display: routeLocation.fullPath,
2508
+ tooltip,
2509
+ value: copy,
2510
+ },
2511
+ };
2512
+ }
2513
+ function formatDisplay(display) {
2514
+ return {
2515
+ _custom: {
2516
+ display,
2517
+ },
2518
+ };
2519
+ }
2520
+ // to support multiple router instances
2521
+ let routerId = 0;
2522
+ function addDevtools(app, router, matcher) {
2523
+ // Take over router.beforeEach and afterEach
2524
+ // make sure we are not registering the devtool twice
2525
+ if (router.__hasDevtools)
2526
+ return;
2527
+ router.__hasDevtools = true;
2528
+ // increment to support multiple router instances
2529
+ const id = routerId++;
2530
+ devtoolsApi.setupDevtoolsPlugin({
2531
+ id: 'app.web.kdujs.router' + (id ? '.' + id : ''),
2532
+ label: 'Kdu Router',
2533
+ packageName: 'kdu-router',
2534
+ homepage: 'https://kdujs-router.web.app',
2535
+ logo: 'https://kdujs-router.web.app/logo.png',
2536
+ componentStateTypes: ['Routing'],
2537
+ app,
2538
+ }, api => {
2539
+ if (typeof api.now !== 'function') {
2540
+ console.warn('[Kdu Router]: You seem to be using an outdated version of Kdu Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://kdujs-devtools.web.app/guide/installation.html.');
2541
+ }
2542
+ // display state added by the router
2543
+ api.on.inspectComponent((payload, ctx) => {
2544
+ if (payload.instanceData) {
2545
+ payload.instanceData.state.push({
2546
+ type: 'Routing',
2547
+ key: '$route',
2548
+ editable: false,
2549
+ value: formatRouteLocation(router.currentRoute.value, 'Current Route'),
2550
+ });
2551
+ }
2552
+ });
2553
+ // mark router-link as active and display tags on router views
2554
+ api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
2555
+ if (componentInstance.__krv_devtools) {
2556
+ const info = componentInstance.__krv_devtools;
2557
+ node.tags.push({
2558
+ label: (info.name ? `${info.name.toString()}: ` : '') + info.path,
2559
+ textColor: 0,
2560
+ tooltip: 'This component is rendered by &lt;router-view&gt;',
2561
+ backgroundColor: PINK_500,
2562
+ });
2563
+ }
2564
+ // if multiple useLink are used
2565
+ if (isArray(componentInstance.__krl_devtools)) {
2566
+ componentInstance.__devtoolsApi = api;
2567
+ componentInstance.__krl_devtools.forEach(devtoolsData => {
2568
+ let backgroundColor = ORANGE_400;
2569
+ let tooltip = '';
2570
+ if (devtoolsData.isExactActive) {
2571
+ backgroundColor = LIME_500;
2572
+ tooltip = 'This is exactly active';
2573
+ }
2574
+ else if (devtoolsData.isActive) {
2575
+ backgroundColor = BLUE_600;
2576
+ tooltip = 'This link is active';
2577
+ }
2578
+ node.tags.push({
2579
+ label: devtoolsData.route.path,
2580
+ textColor: 0,
2581
+ tooltip,
2582
+ backgroundColor,
2583
+ });
2584
+ });
2585
+ }
2586
+ });
2587
+ kdu.watch(router.currentRoute, () => {
2588
+ // refresh active state
2589
+ refreshRoutesView();
2590
+ api.notifyComponentUpdate();
2591
+ api.sendInspectorTree(routerInspectorId);
2592
+ api.sendInspectorState(routerInspectorId);
2593
+ });
2594
+ const navigationsLayerId = 'router:navigations:' + id;
2595
+ api.addTimelineLayer({
2596
+ id: navigationsLayerId,
2597
+ label: `Router${id ? ' ' + id : ''} Navigations`,
2598
+ color: 0x40a8c4,
2599
+ });
2600
+ // const errorsLayerId = 'router:errors'
2601
+ // api.addTimelineLayer({
2602
+ // id: errorsLayerId,
2603
+ // label: 'Router Errors',
2604
+ // color: 0xea5455,
2605
+ // })
2606
+ router.onError((error, to) => {
2607
+ api.addTimelineEvent({
2608
+ layerId: navigationsLayerId,
2609
+ event: {
2610
+ title: 'Error during Navigation',
2611
+ subtitle: to.fullPath,
2612
+ logType: 'error',
2613
+ time: api.now(),
2614
+ data: { error },
2615
+ groupId: to.meta.__navigationId,
2616
+ },
2617
+ });
2618
+ });
2619
+ // attached to `meta` and used to group events
2620
+ let navigationId = 0;
2621
+ router.beforeEach((to, from) => {
2622
+ const data = {
2623
+ guard: formatDisplay('beforeEach'),
2624
+ from: formatRouteLocation(from, 'Current Location during this navigation'),
2625
+ to: formatRouteLocation(to, 'Target location'),
2626
+ };
2627
+ // Used to group navigations together, hide from devtools
2628
+ Object.defineProperty(to.meta, '__navigationId', {
2629
+ value: navigationId++,
2630
+ });
2631
+ api.addTimelineEvent({
2632
+ layerId: navigationsLayerId,
2633
+ event: {
2634
+ time: api.now(),
2635
+ title: 'Start of navigation',
2636
+ subtitle: to.fullPath,
2637
+ data,
2638
+ groupId: to.meta.__navigationId,
2639
+ },
2640
+ });
2641
+ });
2642
+ router.afterEach((to, from, failure) => {
2643
+ const data = {
2644
+ guard: formatDisplay('afterEach'),
2645
+ };
2646
+ if (failure) {
2647
+ data.failure = {
2648
+ _custom: {
2649
+ type: Error,
2650
+ readOnly: true,
2651
+ display: failure ? failure.message : '',
2652
+ tooltip: 'Navigation Failure',
2653
+ value: failure,
2654
+ },
2655
+ };
2656
+ data.status = formatDisplay('❌');
2657
+ }
2658
+ else {
2659
+ data.status = formatDisplay('✅');
2660
+ }
2661
+ // we set here to have the right order
2662
+ data.from = formatRouteLocation(from, 'Current Location during this navigation');
2663
+ data.to = formatRouteLocation(to, 'Target location');
2664
+ api.addTimelineEvent({
2665
+ layerId: navigationsLayerId,
2666
+ event: {
2667
+ title: 'End of navigation',
2668
+ subtitle: to.fullPath,
2669
+ time: api.now(),
2670
+ data,
2671
+ logType: failure ? 'warning' : 'default',
2672
+ groupId: to.meta.__navigationId,
2673
+ },
2674
+ });
2675
+ });
2676
+ /**
2677
+ * Inspector of Existing routes
2678
+ */
2679
+ const routerInspectorId = 'router-inspector:' + id;
2680
+ api.addInspector({
2681
+ id: routerInspectorId,
2682
+ label: 'Routes' + (id ? ' ' + id : ''),
2683
+ icon: 'book',
2684
+ treeFilterPlaceholder: 'Search routes',
2685
+ });
2686
+ function refreshRoutesView() {
2687
+ // the routes view isn't active
2688
+ if (!activeRoutesPayload)
2689
+ return;
2690
+ const payload = activeRoutesPayload;
2691
+ // children routes will appear as nested
2692
+ let routes = matcher.getRoutes().filter(route => !route.parent);
2693
+ // reset match state to false
2694
+ routes.forEach(resetMatchStateOnRouteRecord);
2695
+ // apply a match state if there is a payload
2696
+ if (payload.filter) {
2697
+ routes = routes.filter(route =>
2698
+ // save matches state based on the payload
2699
+ isRouteMatching(route, payload.filter.toLowerCase()));
2700
+ }
2701
+ // mark active routes
2702
+ routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value));
2703
+ payload.rootNodes = routes.map(formatRouteRecordForInspector);
2704
+ }
2705
+ let activeRoutesPayload;
2706
+ api.on.getInspectorTree(payload => {
2707
+ activeRoutesPayload = payload;
2708
+ if (payload.app === app && payload.inspectorId === routerInspectorId) {
2709
+ refreshRoutesView();
2710
+ }
2711
+ });
2712
+ /**
2713
+ * Display information about the currently selected route record
2714
+ */
2715
+ api.on.getInspectorState(payload => {
2716
+ if (payload.app === app && payload.inspectorId === routerInspectorId) {
2717
+ const routes = matcher.getRoutes();
2718
+ const route = routes.find(route => route.record.__kd_id === payload.nodeId);
2719
+ if (route) {
2720
+ payload.state = {
2721
+ options: formatRouteRecordMatcherForStateInspector(route),
2722
+ };
2723
+ }
2724
+ }
2725
+ });
2726
+ api.sendInspectorTree(routerInspectorId);
2727
+ api.sendInspectorState(routerInspectorId);
2728
+ });
2729
+ }
2730
+ function modifierForKey(key) {
2731
+ if (key.optional) {
2732
+ return key.repeatable ? '*' : '?';
2733
+ }
2734
+ else {
2735
+ return key.repeatable ? '+' : '';
2736
+ }
2737
+ }
2738
+ function formatRouteRecordMatcherForStateInspector(route) {
2739
+ const { record } = route;
2740
+ const fields = [
2741
+ { editable: false, key: 'path', value: record.path },
2742
+ ];
2743
+ if (record.name != null) {
2744
+ fields.push({
2745
+ editable: false,
2746
+ key: 'name',
2747
+ value: record.name,
2748
+ });
2749
+ }
2750
+ fields.push({ editable: false, key: 'regexp', value: route.re });
2751
+ if (route.keys.length) {
2752
+ fields.push({
2753
+ editable: false,
2754
+ key: 'keys',
2755
+ value: {
2756
+ _custom: {
2757
+ type: null,
2758
+ readOnly: true,
2759
+ display: route.keys
2760
+ .map(key => `${key.name}${modifierForKey(key)}`)
2761
+ .join(' '),
2762
+ tooltip: 'Param keys',
2763
+ value: route.keys,
2764
+ },
2765
+ },
2766
+ });
2767
+ }
2768
+ if (record.redirect != null) {
2769
+ fields.push({
2770
+ editable: false,
2771
+ key: 'redirect',
2772
+ value: record.redirect,
2773
+ });
2774
+ }
2775
+ if (route.alias.length) {
2776
+ fields.push({
2777
+ editable: false,
2778
+ key: 'aliases',
2779
+ value: route.alias.map(alias => alias.record.path),
2780
+ });
2781
+ }
2782
+ if (Object.keys(route.record.meta).length) {
2783
+ fields.push({
2784
+ editable: false,
2785
+ key: 'meta',
2786
+ value: route.record.meta,
2787
+ });
2788
+ }
2789
+ fields.push({
2790
+ key: 'score',
2791
+ editable: false,
2792
+ value: {
2793
+ _custom: {
2794
+ type: null,
2795
+ readOnly: true,
2796
+ display: route.score.map(score => score.join(', ')).join(' | '),
2797
+ tooltip: 'Score used to sort routes',
2798
+ value: route.score,
2799
+ },
2800
+ },
2801
+ });
2802
+ return fields;
2803
+ }
2804
+ /**
2805
+ * Extracted from tailwind palette
2806
+ */
2807
+ const PINK_500 = 0xec4899;
2808
+ const BLUE_600 = 0x2563eb;
2809
+ const LIME_500 = 0x84cc16;
2810
+ const CYAN_400 = 0x22d3ee;
2811
+ const ORANGE_400 = 0xfb923c;
2812
+ // const GRAY_100 = 0xf4f4f5
2813
+ const DARK = 0x666666;
2814
+ function formatRouteRecordForInspector(route) {
2815
+ const tags = [];
2816
+ const { record } = route;
2817
+ if (record.name != null) {
2818
+ tags.push({
2819
+ label: String(record.name),
2820
+ textColor: 0,
2821
+ backgroundColor: CYAN_400,
2822
+ });
2823
+ }
2824
+ if (record.aliasOf) {
2825
+ tags.push({
2826
+ label: 'alias',
2827
+ textColor: 0,
2828
+ backgroundColor: ORANGE_400,
2829
+ });
2830
+ }
2831
+ if (route.__kd_match) {
2832
+ tags.push({
2833
+ label: 'matches',
2834
+ textColor: 0,
2835
+ backgroundColor: PINK_500,
2836
+ });
2837
+ }
2838
+ if (route.__kd_exactActive) {
2839
+ tags.push({
2840
+ label: 'exact',
2841
+ textColor: 0,
2842
+ backgroundColor: LIME_500,
2843
+ });
2844
+ }
2845
+ if (route.__kd_active) {
2846
+ tags.push({
2847
+ label: 'active',
2848
+ textColor: 0,
2849
+ backgroundColor: BLUE_600,
2850
+ });
2851
+ }
2852
+ if (record.redirect) {
2853
+ tags.push({
2854
+ label: typeof record.redirect === 'string'
2855
+ ? `redirect: ${record.redirect}`
2856
+ : 'redirects',
2857
+ textColor: 0xffffff,
2858
+ backgroundColor: DARK,
2859
+ });
2860
+ }
2861
+ // add an id to be able to select it. Using the `path` is not possible because
2862
+ // empty path children would collide with their parents
2863
+ let id = record.__kd_id;
2864
+ if (id == null) {
2865
+ id = String(routeRecordId++);
2866
+ record.__kd_id = id;
2867
+ }
2868
+ return {
2869
+ id,
2870
+ label: record.path,
2871
+ tags,
2872
+ children: route.children.map(formatRouteRecordForInspector),
2873
+ };
2874
+ }
2875
+ // incremental id for route records and inspector state
2876
+ let routeRecordId = 0;
2877
+ const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
2878
+ function markRouteRecordActive(route, currentRoute) {
2879
+ // no route will be active if matched is empty
2880
+ // reset the matching state
2881
+ const isExactActive = currentRoute.matched.length &&
2882
+ isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
2883
+ route.__kd_exactActive = route.__kd_active = isExactActive;
2884
+ if (!isExactActive) {
2885
+ route.__kd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record));
2886
+ }
2887
+ route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute));
2888
+ }
2889
+ function resetMatchStateOnRouteRecord(route) {
2890
+ route.__kd_match = false;
2891
+ route.children.forEach(resetMatchStateOnRouteRecord);
2892
+ }
2893
+ function isRouteMatching(route, filter) {
2894
+ const found = String(route.re).match(EXTRACT_REGEXP_RE);
2895
+ route.__kd_match = false;
2896
+ if (!found || found.length < 3) {
2897
+ return false;
2898
+ }
2899
+ // use a regexp without $ at the end to match nested routes better
2900
+ const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]);
2901
+ if (nonEndingRE.test(filter)) {
2902
+ // mark children as matches
2903
+ route.children.forEach(child => isRouteMatching(child, filter));
2904
+ // exception case: `/`
2905
+ if (route.record.path !== '/' || filter === '/') {
2906
+ route.__kd_match = route.re.test(filter);
2907
+ return true;
2908
+ }
2909
+ // hide the / route
2910
+ return false;
2911
+ }
2912
+ const path = route.record.path.toLowerCase();
2913
+ const decodedPath = decode(path);
2914
+ // also allow partial matching on the path
2915
+ if (!filter.startsWith('/') &&
2916
+ (decodedPath.includes(filter) || path.includes(filter)))
2917
+ return true;
2918
+ if (decodedPath.startsWith(filter) || path.startsWith(filter))
2919
+ return true;
2920
+ if (route.record.name && String(route.record.name).includes(filter))
2921
+ return true;
2922
+ return route.children.some(child => isRouteMatching(child, filter));
2923
+ }
2924
+ function omit(obj, keys) {
2925
+ const ret = {};
2926
+ for (const key in obj) {
2927
+ if (!keys.includes(key)) {
2928
+ // @ts-expect-error
2929
+ ret[key] = obj[key];
2930
+ }
2931
+ }
2932
+ return ret;
2933
+ }
2934
+
2935
+ /**
2936
+ * Creates a Router instance that can be used by a Kdu app.
2937
+ *
2938
+ * @param options - {@link RouterOptions}
2939
+ */
2940
+ function createRouter(options) {
2941
+ const matcher = createRouterMatcher(options.routes, options);
2942
+ const parseQuery$1 = options.parseQuery || parseQuery;
2943
+ const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
2944
+ const routerHistory = options.history;
2945
+ if (!routerHistory)
2946
+ throw new Error('Provide the "history" option when calling "createRouter()":' +
2947
+ ' https://kdujs-router.web.app/api/#history.');
2948
+ const beforeGuards = useCallbacks();
2949
+ const beforeResolveGuards = useCallbacks();
2950
+ const afterGuards = useCallbacks();
2951
+ const currentRoute = kdu.shallowRef(START_LOCATION_NORMALIZED);
2952
+ let pendingLocation = START_LOCATION_NORMALIZED;
2953
+ // leave the scrollRestoration if no scrollBehavior is provided
2954
+ if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) {
2955
+ history.scrollRestoration = 'manual';
2956
+ }
2957
+ const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue);
2958
+ const encodeParams = applyToParams.bind(null, encodeParam);
2959
+ const decodeParams =
2960
+ // @ts-expect-error: intentionally avoid the type check
2961
+ applyToParams.bind(null, decode);
2962
+ function addRoute(parentOrRoute, route) {
2963
+ let parent;
2964
+ let record;
2965
+ if (isRouteName(parentOrRoute)) {
2966
+ parent = matcher.getRecordMatcher(parentOrRoute);
2967
+ record = route;
2968
+ }
2969
+ else {
2970
+ record = parentOrRoute;
2971
+ }
2972
+ return matcher.addRoute(record, parent);
2973
+ }
2974
+ function removeRoute(name) {
2975
+ const recordMatcher = matcher.getRecordMatcher(name);
2976
+ if (recordMatcher) {
2977
+ matcher.removeRoute(recordMatcher);
2978
+ }
2979
+ else {
2980
+ warn(`Cannot remove non-existent route "${String(name)}"`);
2981
+ }
2982
+ }
2983
+ function getRoutes() {
2984
+ return matcher.getRoutes().map(routeMatcher => routeMatcher.record);
2985
+ }
2986
+ function hasRoute(name) {
2987
+ return !!matcher.getRecordMatcher(name);
2988
+ }
2989
+ function resolve(rawLocation, currentLocation) {
2990
+ // const objectLocation = routerLocationAsObject(rawLocation)
2991
+ // we create a copy to modify it later
2992
+ currentLocation = assign({}, currentLocation || currentRoute.value);
2993
+ if (typeof rawLocation === 'string') {
2994
+ const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
2995
+ const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation);
2996
+ const href = routerHistory.createHref(locationNormalized.fullPath);
2997
+ {
2998
+ if (href.startsWith('//'))
2999
+ warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
3000
+ else if (!matchedRoute.matched.length) {
3001
+ warn(`No match found for location with path "${rawLocation}"`);
3002
+ }
3003
+ }
3004
+ // locationNormalized is always a new object
3005
+ return assign(locationNormalized, matchedRoute, {
3006
+ params: decodeParams(matchedRoute.params),
3007
+ hash: decode(locationNormalized.hash),
3008
+ redirectedFrom: undefined,
3009
+ href,
3010
+ });
3011
+ }
3012
+ let matcherLocation;
3013
+ // path could be relative in object as well
3014
+ if ('path' in rawLocation) {
3015
+ if ('params' in rawLocation &&
3016
+ !('name' in rawLocation) &&
3017
+ // @ts-expect-error: the type is never
3018
+ Object.keys(rawLocation.params).length) {
3019
+ warn(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
3020
+ }
3021
+ matcherLocation = assign({}, rawLocation, {
3022
+ path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path,
3023
+ });
3024
+ }
3025
+ else {
3026
+ // remove any nullish param
3027
+ const targetParams = assign({}, rawLocation.params);
3028
+ for (const key in targetParams) {
3029
+ if (targetParams[key] == null) {
3030
+ delete targetParams[key];
3031
+ }
3032
+ }
3033
+ // pass encoded values to the matcher, so it can produce encoded path and fullPath
3034
+ matcherLocation = assign({}, rawLocation, {
3035
+ params: encodeParams(targetParams),
3036
+ });
3037
+ // current location params are decoded, we need to encode them in case the
3038
+ // matcher merges the params
3039
+ currentLocation.params = encodeParams(currentLocation.params);
3040
+ }
3041
+ const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
3042
+ const hash = rawLocation.hash || '';
3043
+ if (hash && !hash.startsWith('#')) {
3044
+ warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
3045
+ }
3046
+ // the matcher might have merged current location params, so
3047
+ // we need to run the decoding again
3048
+ matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
3049
+ const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
3050
+ hash: encodeHash(hash),
3051
+ path: matchedRoute.path,
3052
+ }));
3053
+ const href = routerHistory.createHref(fullPath);
3054
+ {
3055
+ if (href.startsWith('//')) {
3056
+ warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
3057
+ }
3058
+ else if (!matchedRoute.matched.length) {
3059
+ warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`);
3060
+ }
3061
+ }
3062
+ return assign({
3063
+ fullPath,
3064
+ // keep the hash encoded so fullPath is effectively path + encodedQuery +
3065
+ // hash
3066
+ hash,
3067
+ query:
3068
+ // if the user is using a custom query lib like qs, we might have
3069
+ // nested objects, so we keep the query as is, meaning it can contain
3070
+ // numbers at `$route.query`, but at the point, the user will have to
3071
+ // use their own type anyway.
3072
+ stringifyQuery$1 === stringifyQuery
3073
+ ? normalizeQuery(rawLocation.query)
3074
+ : (rawLocation.query || {}),
3075
+ }, matchedRoute, {
3076
+ redirectedFrom: undefined,
3077
+ href,
3078
+ });
3079
+ }
3080
+ function locationAsObject(to) {
3081
+ return typeof to === 'string'
3082
+ ? parseURL(parseQuery$1, to, currentRoute.value.path)
3083
+ : assign({}, to);
3084
+ }
3085
+ function checkCanceledNavigation(to, from) {
3086
+ if (pendingLocation !== to) {
3087
+ return createRouterError(8 /* ErrorTypes.NAVIGATION_CANCELLED */, {
3088
+ from,
3089
+ to,
3090
+ });
3091
+ }
3092
+ }
3093
+ function push(to) {
3094
+ return pushWithRedirect(to);
3095
+ }
3096
+ function replace(to) {
3097
+ return push(assign(locationAsObject(to), { replace: true }));
3098
+ }
3099
+ function handleRedirectRecord(to) {
3100
+ const lastMatched = to.matched[to.matched.length - 1];
3101
+ if (lastMatched && lastMatched.redirect) {
3102
+ const { redirect } = lastMatched;
3103
+ let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect;
3104
+ if (typeof newTargetLocation === 'string') {
3105
+ newTargetLocation =
3106
+ newTargetLocation.includes('?') || newTargetLocation.includes('#')
3107
+ ? (newTargetLocation = locationAsObject(newTargetLocation))
3108
+ : // force empty params
3109
+ { path: newTargetLocation };
3110
+ // @ts-expect-error: force empty params when a string is passed to let
3111
+ // the router parse them again
3112
+ newTargetLocation.params = {};
3113
+ }
3114
+ if (!('path' in newTargetLocation) &&
3115
+ !('name' in newTargetLocation)) {
3116
+ warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`);
3117
+ throw new Error('Invalid redirect');
3118
+ }
3119
+ return assign({
3120
+ query: to.query,
3121
+ hash: to.hash,
3122
+ // avoid transferring params if the redirect has a path
3123
+ params: 'path' in newTargetLocation ? {} : to.params,
3124
+ }, newTargetLocation);
3125
+ }
3126
+ }
3127
+ function pushWithRedirect(to, redirectedFrom) {
3128
+ const targetLocation = (pendingLocation = resolve(to));
3129
+ const from = currentRoute.value;
3130
+ const data = to.state;
3131
+ const force = to.force;
3132
+ // to could be a string where `replace` is a function
3133
+ const replace = to.replace === true;
3134
+ const shouldRedirect = handleRedirectRecord(targetLocation);
3135
+ if (shouldRedirect)
3136
+ return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
3137
+ state: typeof shouldRedirect === 'object'
3138
+ ? assign({}, data, shouldRedirect.state)
3139
+ : data,
3140
+ force,
3141
+ replace,
3142
+ }),
3143
+ // keep original redirectedFrom if it exists
3144
+ redirectedFrom || targetLocation);
3145
+ // if it was a redirect we already called `pushWithRedirect` above
3146
+ const toLocation = targetLocation;
3147
+ toLocation.redirectedFrom = redirectedFrom;
3148
+ let failure;
3149
+ if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
3150
+ failure = createRouterError(16 /* ErrorTypes.NAVIGATION_DUPLICATED */, { to: toLocation, from });
3151
+ // trigger scroll to allow scrolling to the same anchor
3152
+ handleScroll(from, from,
3153
+ // this is a push, the only way for it to be triggered from a
3154
+ // history.listen is with a redirect, which makes it become a push
3155
+ true,
3156
+ // This cannot be the first navigation because the initial location
3157
+ // cannot be manually navigated to
3158
+ false);
3159
+ }
3160
+ return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
3161
+ .catch((error) => isNavigationFailure(error)
3162
+ ? // navigation redirects still mark the router as ready
3163
+ isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)
3164
+ ? error
3165
+ : markAsReady(error) // also returns the error
3166
+ : // reject any unknown error
3167
+ triggerError(error, toLocation, from))
3168
+ .then((failure) => {
3169
+ if (failure) {
3170
+ if (isNavigationFailure(failure, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) {
3171
+ if (// we are redirecting to the same location we were already at
3172
+ isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) &&
3173
+ // and we have done it a couple of times
3174
+ redirectedFrom &&
3175
+ // @ts-expect-error: added only in dev
3176
+ (redirectedFrom._count = redirectedFrom._count
3177
+ ? // @ts-expect-error
3178
+ redirectedFrom._count + 1
3179
+ : 1) > 30) {
3180
+ warn(`Detected a possibly infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.\n Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`);
3181
+ return Promise.reject(new Error('Infinite redirect in navigation guard'));
3182
+ }
3183
+ return pushWithRedirect(
3184
+ // keep options
3185
+ assign({
3186
+ // preserve an existing replacement but allow the redirect to override it
3187
+ replace,
3188
+ }, locationAsObject(failure.to), {
3189
+ state: typeof failure.to === 'object'
3190
+ ? assign({}, data, failure.to.state)
3191
+ : data,
3192
+ force,
3193
+ }),
3194
+ // preserve the original redirectedFrom if any
3195
+ redirectedFrom || toLocation);
3196
+ }
3197
+ }
3198
+ else {
3199
+ // if we fail we don't finalize the navigation
3200
+ failure = finalizeNavigation(toLocation, from, true, replace, data);
3201
+ }
3202
+ triggerAfterEach(toLocation, from, failure);
3203
+ return failure;
3204
+ });
3205
+ }
3206
+ /**
3207
+ * Helper to reject and skip all navigation guards if a new navigation happened
3208
+ * @param to
3209
+ * @param from
3210
+ */
3211
+ function checkCanceledNavigationAndReject(to, from) {
3212
+ const error = checkCanceledNavigation(to, from);
3213
+ return error ? Promise.reject(error) : Promise.resolve();
3214
+ }
3215
+ function runWithContext(fn) {
3216
+ const app = installedApps.values().next().value;
3217
+ // support Kdu < 3.3
3218
+ return app && typeof app.runWithContext === 'function'
3219
+ ? app.runWithContext(fn)
3220
+ : fn();
3221
+ }
3222
+ // TODO: refactor the whole before guards by internally using router.beforeEach
3223
+ function navigate(to, from) {
3224
+ let guards;
3225
+ const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
3226
+ // all components here have been resolved once because we are leaving
3227
+ guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from);
3228
+ // leavingRecords is already reversed
3229
+ for (const record of leavingRecords) {
3230
+ record.leaveGuards.forEach(guard => {
3231
+ guards.push(guardToPromiseFn(guard, to, from));
3232
+ });
3233
+ }
3234
+ const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
3235
+ guards.push(canceledNavigationCheck);
3236
+ // run the queue of per route beforeRouteLeave guards
3237
+ return (runGuardQueue(guards)
3238
+ .then(() => {
3239
+ // check global guards beforeEach
3240
+ guards = [];
3241
+ for (const guard of beforeGuards.list()) {
3242
+ guards.push(guardToPromiseFn(guard, to, from));
3243
+ }
3244
+ guards.push(canceledNavigationCheck);
3245
+ return runGuardQueue(guards);
3246
+ })
3247
+ .then(() => {
3248
+ // check in components beforeRouteUpdate
3249
+ guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from);
3250
+ for (const record of updatingRecords) {
3251
+ record.updateGuards.forEach(guard => {
3252
+ guards.push(guardToPromiseFn(guard, to, from));
3253
+ });
3254
+ }
3255
+ guards.push(canceledNavigationCheck);
3256
+ // run the queue of per route beforeEnter guards
3257
+ return runGuardQueue(guards);
3258
+ })
3259
+ .then(() => {
3260
+ // check the route beforeEnter
3261
+ guards = [];
3262
+ for (const record of to.matched) {
3263
+ // do not trigger beforeEnter on reused views
3264
+ if (record.beforeEnter && !from.matched.includes(record)) {
3265
+ if (isArray(record.beforeEnter)) {
3266
+ for (const beforeEnter of record.beforeEnter)
3267
+ guards.push(guardToPromiseFn(beforeEnter, to, from));
3268
+ }
3269
+ else {
3270
+ guards.push(guardToPromiseFn(record.beforeEnter, to, from));
3271
+ }
3272
+ }
3273
+ }
3274
+ guards.push(canceledNavigationCheck);
3275
+ // run the queue of per route beforeEnter guards
3276
+ return runGuardQueue(guards);
3277
+ })
3278
+ .then(() => {
3279
+ // NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
3280
+ // clear existing enterCallbacks, these are added by extractComponentsGuards
3281
+ to.matched.forEach(record => (record.enterCallbacks = {}));
3282
+ // check in-component beforeRouteEnter
3283
+ guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from);
3284
+ guards.push(canceledNavigationCheck);
3285
+ // run the queue of per route beforeEnter guards
3286
+ return runGuardQueue(guards);
3287
+ })
3288
+ .then(() => {
3289
+ // check global guards beforeResolve
3290
+ guards = [];
3291
+ for (const guard of beforeResolveGuards.list()) {
3292
+ guards.push(guardToPromiseFn(guard, to, from));
3293
+ }
3294
+ guards.push(canceledNavigationCheck);
3295
+ return runGuardQueue(guards);
3296
+ })
3297
+ // catch any navigation canceled
3298
+ .catch(err => isNavigationFailure(err, 8 /* ErrorTypes.NAVIGATION_CANCELLED */)
3299
+ ? err
3300
+ : Promise.reject(err)));
3301
+ }
3302
+ function triggerAfterEach(to, from, failure) {
3303
+ // navigation is confirmed, call afterGuards
3304
+ // TODO: wrap with error handlers
3305
+ for (const guard of afterGuards.list()) {
3306
+ runWithContext(() => guard(to, from, failure));
3307
+ }
3308
+ }
3309
+ /**
3310
+ * - Cleans up any navigation guards
3311
+ * - Changes the url if necessary
3312
+ * - Calls the scrollBehavior
3313
+ */
3314
+ function finalizeNavigation(toLocation, from, isPush, replace, data) {
3315
+ // a more recent navigation took place
3316
+ const error = checkCanceledNavigation(toLocation, from);
3317
+ if (error)
3318
+ return error;
3319
+ // only consider as push if it's not the first navigation
3320
+ const isFirstNavigation = from === START_LOCATION_NORMALIZED;
3321
+ const state = !isBrowser ? {} : history.state;
3322
+ // change URL only if the user did a push/replace and if it's not the initial navigation because
3323
+ // it's just reflecting the url
3324
+ if (isPush) {
3325
+ // on the initial navigation, we want to reuse the scroll position from
3326
+ // history state if it exists
3327
+ if (replace || isFirstNavigation)
3328
+ routerHistory.replace(toLocation.fullPath, assign({
3329
+ scroll: isFirstNavigation && state && state.scroll,
3330
+ }, data));
3331
+ else
3332
+ routerHistory.push(toLocation.fullPath, data);
3333
+ }
3334
+ // accept current navigation
3335
+ currentRoute.value = toLocation;
3336
+ handleScroll(toLocation, from, isPush, isFirstNavigation);
3337
+ markAsReady();
3338
+ }
3339
+ let removeHistoryListener;
3340
+ // attach listener to history to trigger navigations
3341
+ function setupListeners() {
3342
+ // avoid setting up listeners twice due to an invalid first navigation
3343
+ if (removeHistoryListener)
3344
+ return;
3345
+ removeHistoryListener = routerHistory.listen((to, _from, info) => {
3346
+ if (!router.listening)
3347
+ return;
3348
+ // cannot be a redirect route because it was in history
3349
+ const toLocation = resolve(to);
3350
+ // due to dynamic routing, and to hash history with manual navigation
3351
+ // (manually changing the url or calling history.hash = '#/somewhere'),
3352
+ // there could be a redirect record in history
3353
+ const shouldRedirect = handleRedirectRecord(toLocation);
3354
+ if (shouldRedirect) {
3355
+ pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
3356
+ return;
3357
+ }
3358
+ pendingLocation = toLocation;
3359
+ const from = currentRoute.value;
3360
+ // TODO: should be moved to web history?
3361
+ if (isBrowser) {
3362
+ saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
3363
+ }
3364
+ navigate(toLocation, from)
3365
+ .catch((error) => {
3366
+ if (isNavigationFailure(error, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) {
3367
+ return error;
3368
+ }
3369
+ if (isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) {
3370
+ // Here we could call if (info.delta) routerHistory.go(-info.delta,
3371
+ // false) but this is bug prone as we have no way to wait the
3372
+ // navigation to be finished before calling pushWithRedirect. Using
3373
+ // a setTimeout of 16ms seems to work but there is no guarantee for
3374
+ // it to work on every browser. So instead we do not restore the
3375
+ // history entry and trigger a new navigation as requested by the
3376
+ // navigation guard.
3377
+ // the error is already handled by router.push we just want to avoid
3378
+ // logging the error
3379
+ pushWithRedirect(error.to, toLocation
3380
+ // avoid an uncaught rejection, let push call triggerError
3381
+ )
3382
+ .then(failure => {
3383
+ // manual change in hash history #916 ending up in the URL not
3384
+ // changing, but it was changed by the manual url change, so we
3385
+ // need to manually change it ourselves
3386
+ if (isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ |
3387
+ 16 /* ErrorTypes.NAVIGATION_DUPLICATED */) &&
3388
+ !info.delta &&
3389
+ info.type === NavigationType.pop) {
3390
+ routerHistory.go(-1, false);
3391
+ }
3392
+ })
3393
+ .catch(noop);
3394
+ // avoid the then branch
3395
+ return Promise.reject();
3396
+ }
3397
+ // do not restore history on unknown direction
3398
+ if (info.delta) {
3399
+ routerHistory.go(-info.delta, false);
3400
+ }
3401
+ // unrecognized error, transfer to the global handler
3402
+ return triggerError(error, toLocation, from);
3403
+ })
3404
+ .then((failure) => {
3405
+ failure =
3406
+ failure ||
3407
+ finalizeNavigation(
3408
+ // after navigation, all matched components are resolved
3409
+ toLocation, from, false);
3410
+ // revert the navigation
3411
+ if (failure) {
3412
+ if (info.delta &&
3413
+ // a new navigation has been triggered, so we do not want to revert, that will change the current history
3414
+ // entry while a different route is displayed
3415
+ !isNavigationFailure(failure, 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) {
3416
+ routerHistory.go(-info.delta, false);
3417
+ }
3418
+ else if (info.type === NavigationType.pop &&
3419
+ isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 16 /* ErrorTypes.NAVIGATION_DUPLICATED */)) {
3420
+ // manual change in hash history #916
3421
+ // it's like a push but lacks the information of the direction
3422
+ routerHistory.go(-1, false);
3423
+ }
3424
+ }
3425
+ triggerAfterEach(toLocation, from, failure);
3426
+ })
3427
+ .catch(noop);
3428
+ });
3429
+ }
3430
+ // Initialization and Errors
3431
+ let readyHandlers = useCallbacks();
3432
+ let errorHandlers = useCallbacks();
3433
+ let ready;
3434
+ /**
3435
+ * Trigger errorHandlers added via onError and throws the error as well
3436
+ *
3437
+ * @param error - error to throw
3438
+ * @param to - location we were navigating to when the error happened
3439
+ * @param from - location we were navigating from when the error happened
3440
+ * @returns the error as a rejected promise
3441
+ */
3442
+ function triggerError(error, to, from) {
3443
+ markAsReady(error);
3444
+ const list = errorHandlers.list();
3445
+ if (list.length) {
3446
+ list.forEach(handler => handler(error, to, from));
3447
+ }
3448
+ else {
3449
+ {
3450
+ warn('uncaught error during route navigation:');
3451
+ }
3452
+ console.error(error);
3453
+ }
3454
+ return Promise.reject(error);
3455
+ }
3456
+ function isReady() {
3457
+ if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
3458
+ return Promise.resolve();
3459
+ return new Promise((resolve, reject) => {
3460
+ readyHandlers.add([resolve, reject]);
3461
+ });
3462
+ }
3463
+ function markAsReady(err) {
3464
+ if (!ready) {
3465
+ // still not ready if an error happened
3466
+ ready = !err;
3467
+ setupListeners();
3468
+ readyHandlers
3469
+ .list()
3470
+ .forEach(([resolve, reject]) => (err ? reject(err) : resolve()));
3471
+ readyHandlers.reset();
3472
+ }
3473
+ return err;
3474
+ }
3475
+ // Scroll behavior
3476
+ function handleScroll(to, from, isPush, isFirstNavigation) {
3477
+ const { scrollBehavior } = options;
3478
+ if (!isBrowser || !scrollBehavior)
3479
+ return Promise.resolve();
3480
+ const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
3481
+ ((isFirstNavigation || !isPush) &&
3482
+ history.state &&
3483
+ history.state.scroll) ||
3484
+ null;
3485
+ return kdu.nextTick()
3486
+ .then(() => scrollBehavior(to, from, scrollPosition))
3487
+ .then(position => position && scrollToPosition(position))
3488
+ .catch(err => triggerError(err, to, from));
3489
+ }
3490
+ const go = (delta) => routerHistory.go(delta);
3491
+ let started;
3492
+ const installedApps = new Set();
3493
+ const router = {
3494
+ currentRoute,
3495
+ listening: true,
3496
+ addRoute,
3497
+ removeRoute,
3498
+ hasRoute,
3499
+ getRoutes,
3500
+ resolve,
3501
+ options,
3502
+ push,
3503
+ replace,
3504
+ go,
3505
+ back: () => go(-1),
3506
+ forward: () => go(1),
3507
+ beforeEach: beforeGuards.add,
3508
+ beforeResolve: beforeResolveGuards.add,
3509
+ afterEach: afterGuards.add,
3510
+ onError: errorHandlers.add,
3511
+ isReady,
3512
+ install(app) {
3513
+ const router = this;
3514
+ app.component('RouterLink', RouterLink);
3515
+ app.component('RouterView', RouterView);
3516
+ app.config.globalProperties.$router = router;
3517
+ Object.defineProperty(app.config.globalProperties, '$route', {
3518
+ enumerable: true,
3519
+ get: () => kdu.unref(currentRoute),
3520
+ });
3521
+ // this initial navigation is only necessary on client, on server it doesn't
3522
+ // make sense because it will create an extra unnecessary navigation and could
3523
+ // lead to problems
3524
+ if (isBrowser &&
3525
+ // used for the initial navigation client side to avoid pushing
3526
+ // multiple times when the router is used in multiple apps
3527
+ !started &&
3528
+ currentRoute.value === START_LOCATION_NORMALIZED) {
3529
+ // see above
3530
+ started = true;
3531
+ push(routerHistory.location).catch(err => {
3532
+ warn('Unexpected error when starting the router:', err);
3533
+ });
3534
+ }
3535
+ const reactiveRoute = {};
3536
+ for (const key in START_LOCATION_NORMALIZED) {
3537
+ // @ts-expect-error: the key matches
3538
+ reactiveRoute[key] = kdu.computed(() => currentRoute.value[key]);
3539
+ }
3540
+ app.provide(routerKey, router);
3541
+ app.provide(routeLocationKey, kdu.reactive(reactiveRoute));
3542
+ app.provide(routerViewLocationKey, currentRoute);
3543
+ const unmountApp = app.unmount;
3544
+ installedApps.add(app);
3545
+ app.unmount = function () {
3546
+ installedApps.delete(app);
3547
+ // the router is not attached to an app anymore
3548
+ if (installedApps.size < 1) {
3549
+ // invalidate the current navigation
3550
+ pendingLocation = START_LOCATION_NORMALIZED;
3551
+ removeHistoryListener && removeHistoryListener();
3552
+ removeHistoryListener = null;
3553
+ currentRoute.value = START_LOCATION_NORMALIZED;
3554
+ started = false;
3555
+ ready = false;
3556
+ }
3557
+ unmountApp();
3558
+ };
3559
+ // TODO: this probably needs to be updated so it can be used by kdu-termui
3560
+ if (isBrowser) {
3561
+ addDevtools(app, router, matcher);
3562
+ }
3563
+ },
3564
+ };
3565
+ // TODO: type this as NavigationGuardReturn or similar instead of any
3566
+ function runGuardQueue(guards) {
3567
+ return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve());
3568
+ }
3569
+ return router;
3570
+ }
3571
+ function extractChangingRecords(to, from) {
3572
+ const leavingRecords = [];
3573
+ const updatingRecords = [];
3574
+ const enteringRecords = [];
3575
+ const len = Math.max(from.matched.length, to.matched.length);
3576
+ for (let i = 0; i < len; i++) {
3577
+ const recordFrom = from.matched[i];
3578
+ if (recordFrom) {
3579
+ if (to.matched.find(record => isSameRouteRecord(record, recordFrom)))
3580
+ updatingRecords.push(recordFrom);
3581
+ else
3582
+ leavingRecords.push(recordFrom);
3583
+ }
3584
+ const recordTo = to.matched[i];
3585
+ if (recordTo) {
3586
+ // the type doesn't matter because we are comparing per reference
3587
+ if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) {
3588
+ enteringRecords.push(recordTo);
3589
+ }
3590
+ }
3591
+ }
3592
+ return [leavingRecords, updatingRecords, enteringRecords];
3593
+ }
3594
+
3595
+ /**
3596
+ * Returns the router instance. Equivalent to using `$router` inside
3597
+ * templates.
3598
+ */
3599
+ function useRouter() {
3600
+ return kdu.inject(routerKey);
3601
+ }
3602
+ /**
3603
+ * Returns the current route location. Equivalent to using `$route` inside
3604
+ * templates.
3605
+ */
3606
+ function useRoute() {
3607
+ return kdu.inject(routeLocationKey);
3608
+ }
3609
+
3610
+ exports.RouterLink = RouterLink;
3611
+ exports.RouterView = RouterView;
3612
+ exports.START_LOCATION = START_LOCATION_NORMALIZED;
3613
+ exports.createMemoryHistory = createMemoryHistory;
3614
+ exports.createRouter = createRouter;
3615
+ exports.createRouterMatcher = createRouterMatcher;
3616
+ exports.createWebHashHistory = createWebHashHistory;
3617
+ exports.createWebHistory = createWebHistory;
3618
+ exports.isNavigationFailure = isNavigationFailure;
3619
+ exports.loadRouteLocation = loadRouteLocation;
3620
+ exports.matchedRouteKey = matchedRouteKey;
3621
+ exports.onBeforeRouteLeave = onBeforeRouteLeave;
3622
+ exports.onBeforeRouteUpdate = onBeforeRouteUpdate;
3623
+ exports.parseQuery = parseQuery;
3624
+ exports.routeLocationKey = routeLocationKey;
3625
+ exports.routerKey = routerKey;
3626
+ exports.routerViewLocationKey = routerViewLocationKey;
3627
+ exports.stringifyQuery = stringifyQuery;
3628
+ exports.useLink = useLink;
3629
+ exports.useRoute = useRoute;
3630
+ exports.useRouter = useRouter;
3631
+ exports.viewDepthKey = viewDepthKey;