kdu-router 3.4.0-beta.0 → 4.0.16-rc.0

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