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