@gx-design-vue/create-gx-cli 0.1.22 → 0.1.24

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