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