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

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