@vtj/materials 0.8.130 → 0.8.132

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