kdu-router 4.0.16-rc.0 → 4.1.6

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