kdu-router 4.0.16 → 4.2.0

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