devtools-EWN81iOl.mjs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. /*!
  2. * vue-router v4.6.4
  3. * (c) 2025 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. import { getCurrentInstance, inject, onActivated, onDeactivated, onUnmounted, watch } from "vue";
  7. import { setupDevtoolsPlugin } from "@vue/devtools-api";
  8. //#region src/utils/env.ts
  9. const isBrowser = typeof document !== "undefined";
  10. //#endregion
  11. //#region src/utils/index.ts
  12. /**
  13. * Identity function that returns the value as is.
  14. *
  15. * @param v - the value to return
  16. *
  17. * @internal
  18. */
  19. const identityFn = (v) => v;
  20. /**
  21. * Allows differentiating lazy components from functional components and vue-class-component
  22. * @internal
  23. *
  24. * @param component
  25. */
  26. function isRouteComponent(component) {
  27. return typeof component === "object" || "displayName" in component || "props" in component || "__vccOpts" in component;
  28. }
  29. function isESModule(obj) {
  30. return obj.__esModule || obj[Symbol.toStringTag] === "Module" || obj.default && isRouteComponent(obj.default);
  31. }
  32. const assign = Object.assign;
  33. function applyToParams(fn, params) {
  34. const newParams = {};
  35. for (const key in params) {
  36. const value = params[key];
  37. newParams[key] = isArray(value) ? value.map(fn) : fn(value);
  38. }
  39. return newParams;
  40. }
  41. const noop = () => {};
  42. /**
  43. * Typesafe alternative to Array.isArray
  44. * https://github.com/microsoft/TypeScript/pull/48228
  45. *
  46. * @internal
  47. */
  48. const isArray = Array.isArray;
  49. function mergeOptions(defaults, partialOptions) {
  50. const options = {};
  51. for (const key in defaults) options[key] = key in partialOptions ? partialOptions[key] : defaults[key];
  52. return options;
  53. }
  54. //#endregion
  55. //#region src/warning.ts
  56. function warn$1(msg) {
  57. const args = Array.from(arguments).slice(1);
  58. console.warn.apply(console, ["[Vue Router warn]: " + msg].concat(args));
  59. }
  60. //#endregion
  61. //#region src/encoding.ts
  62. /**
  63. * Encoding Rules (␣ = Space)
  64. * - Path: ␣ " < > # ? { }
  65. * - Query: ␣ " < > # & =
  66. * - Hash: ␣ " < > `
  67. *
  68. * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2)
  69. * defines some extra characters to be encoded. Most browsers do not encode them
  70. * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to
  71. * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`)
  72. * plus `-._~`. This extra safety should be applied to query by patching the
  73. * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\`
  74. * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\`
  75. * into a `/` if directly typed in. The _backtick_ (`````) should also be
  76. * encoded everywhere because some browsers like FF encode it when directly
  77. * written while others don't. Safari and IE don't encode ``"<>{}``` in hash.
  78. */
  79. const HASH_RE = /#/g;
  80. const AMPERSAND_RE = /&/g;
  81. const SLASH_RE = /\//g;
  82. const EQUAL_RE = /=/g;
  83. const IM_RE = /\?/g;
  84. const PLUS_RE = /\+/g;
  85. /**
  86. * NOTE: It's not clear to me if we should encode the + symbol in queries, it
  87. * seems to be less flexible than not doing so and I can't find out the legacy
  88. * systems requiring this for regular requests like text/html. In the standard,
  89. * the encoding of the plus character is only mentioned for
  90. * application/x-www-form-urlencoded
  91. * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo
  92. * leave the plus character as is in queries. To be more flexible, we allow the
  93. * plus character on the query, but it can also be manually encoded by the user.
  94. *
  95. * Resources:
  96. * - https://url.spec.whatwg.org/#urlencoded-parsing
  97. * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20
  98. */
  99. const ENC_BRACKET_OPEN_RE = /%5B/g;
  100. const ENC_BRACKET_CLOSE_RE = /%5D/g;
  101. const ENC_CARET_RE = /%5E/g;
  102. const ENC_BACKTICK_RE = /%60/g;
  103. const ENC_CURLY_OPEN_RE = /%7B/g;
  104. const ENC_PIPE_RE = /%7C/g;
  105. const ENC_CURLY_CLOSE_RE = /%7D/g;
  106. const ENC_SPACE_RE = /%20/g;
  107. /**
  108. * Encode characters that need to be encoded on the path, search and hash
  109. * sections of the URL.
  110. *
  111. * @internal
  112. * @param text - string to encode
  113. * @returns encoded string
  114. */
  115. function commonEncode(text) {
  116. return text == null ? "" : encodeURI("" + text).replace(ENC_PIPE_RE, "|").replace(ENC_BRACKET_OPEN_RE, "[").replace(ENC_BRACKET_CLOSE_RE, "]");
  117. }
  118. /**
  119. * Encode characters that need to be encoded on the hash section of the URL.
  120. *
  121. * @param text - string to encode
  122. * @returns encoded string
  123. */
  124. function encodeHash(text) {
  125. return commonEncode(text).replace(ENC_CURLY_OPEN_RE, "{").replace(ENC_CURLY_CLOSE_RE, "}").replace(ENC_CARET_RE, "^");
  126. }
  127. /**
  128. * Encode characters that need to be encoded query values on the query
  129. * section of the URL.
  130. *
  131. * @param text - string to encode
  132. * @returns encoded string
  133. */
  134. function encodeQueryValue(text) {
  135. 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, "^");
  136. }
  137. /**
  138. * Like `encodeQueryValue` but also encodes the `=` character.
  139. *
  140. * @param text - string to encode
  141. */
  142. function encodeQueryKey(text) {
  143. return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
  144. }
  145. /**
  146. * Encode characters that need to be encoded on the path section of the URL.
  147. *
  148. * @param text - string to encode
  149. * @returns encoded string
  150. */
  151. function encodePath(text) {
  152. return commonEncode(text).replace(HASH_RE, "%23").replace(IM_RE, "%3F");
  153. }
  154. /**
  155. * Encode characters that need to be encoded on the path section of the URL as a
  156. * param. This function encodes everything {@link encodePath} does plus the
  157. * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty
  158. * string instead.
  159. *
  160. * @param text - string to encode
  161. * @returns encoded string
  162. */
  163. function encodeParam(text) {
  164. return encodePath(text).replace(SLASH_RE, "%2F");
  165. }
  166. function decode(text) {
  167. if (text == null) return null;
  168. try {
  169. return decodeURIComponent("" + text);
  170. } catch (err) {
  171. process.env.NODE_ENV !== "production" && warn$1(`Error decoding "${text}". Using original value`);
  172. }
  173. return "" + text;
  174. }
  175. //#endregion
  176. //#region src/location.ts
  177. const TRAILING_SLASH_RE = /\/$/;
  178. const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, "");
  179. /**
  180. * Transforms a URI into a normalized history location
  181. *
  182. * @param parseQuery
  183. * @param location - URI to normalize
  184. * @param currentLocation - current absolute location. Allows resolving relative
  185. * paths. Must start with `/`. Defaults to `/`
  186. * @returns a normalized history location
  187. */
  188. function parseURL(parseQuery$1, location, currentLocation = "/") {
  189. let path, query = {}, searchString = "", hash = "";
  190. const hashPos = location.indexOf("#");
  191. let searchPos = location.indexOf("?");
  192. searchPos = hashPos >= 0 && searchPos > hashPos ? -1 : searchPos;
  193. if (searchPos >= 0) {
  194. path = location.slice(0, searchPos);
  195. searchString = location.slice(searchPos, hashPos > 0 ? hashPos : location.length);
  196. query = parseQuery$1(searchString.slice(1));
  197. }
  198. if (hashPos >= 0) {
  199. path = path || location.slice(0, hashPos);
  200. hash = location.slice(hashPos, location.length);
  201. }
  202. path = resolveRelativePath(path != null ? path : location, currentLocation);
  203. return {
  204. fullPath: path + searchString + hash,
  205. path,
  206. query,
  207. hash: decode(hash)
  208. };
  209. }
  210. function NEW_stringifyURL(stringifyQuery$1, path, query, hash = "") {
  211. const searchText = stringifyQuery$1(query);
  212. return path + (searchText && "?") + searchText + encodeHash(hash);
  213. }
  214. /**
  215. * Stringifies a URL object
  216. *
  217. * @param stringifyQuery
  218. * @param location
  219. */
  220. function stringifyURL(stringifyQuery$1, location) {
  221. const query = location.query ? stringifyQuery$1(location.query) : "";
  222. return location.path + (query && "?") + query + (location.hash || "");
  223. }
  224. /**
  225. * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way.
  226. *
  227. * @param pathname - location.pathname
  228. * @param base - base to strip off
  229. */
  230. function stripBase(pathname, base) {
  231. if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) return pathname;
  232. return pathname.slice(base.length) || "/";
  233. }
  234. /**
  235. * Checks if two RouteLocation are equal. This means that both locations are
  236. * pointing towards the same {@link RouteRecord} and that all `params`, `query`
  237. * parameters and `hash` are the same
  238. *
  239. * @param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it.
  240. * @param a - first {@link RouteLocation}
  241. * @param b - second {@link RouteLocation}
  242. */
  243. function isSameRouteLocation(stringifyQuery$1, a, b) {
  244. const aLastIndex = a.matched.length - 1;
  245. const bLastIndex = b.matched.length - 1;
  246. 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;
  247. }
  248. /**
  249. * Check if two `RouteRecords` are equal. Takes into account aliases: they are
  250. * considered equal to the `RouteRecord` they are aliasing.
  251. *
  252. * @param a - first {@link RouteRecord}
  253. * @param b - second {@link RouteRecord}
  254. */
  255. function isSameRouteRecord(a, b) {
  256. return (a.aliasOf || a) === (b.aliasOf || b);
  257. }
  258. function isSameRouteLocationParams(a, b) {
  259. if (Object.keys(a).length !== Object.keys(b).length) return false;
  260. for (var key in a) if (!isSameRouteLocationParamsValue(a[key], b[key])) return false;
  261. return true;
  262. }
  263. function isSameRouteLocationParamsValue(a, b) {
  264. return isArray(a) ? isEquivalentArray(a, b) : isArray(b) ? isEquivalentArray(b, a) : a?.valueOf() === b?.valueOf();
  265. }
  266. /**
  267. * Check if two arrays are the same or if an array with one single entry is the
  268. * same as another primitive value. Used to check query and parameters
  269. *
  270. * @param a - array of values
  271. * @param b - array of values or a single value
  272. */
  273. function isEquivalentArray(a, b) {
  274. return isArray(b) ? a.length === b.length && a.every((value, i) => value === b[i]) : a.length === 1 && a[0] === b;
  275. }
  276. /**
  277. * Resolves a relative path that starts with `.`.
  278. *
  279. * @param to - path location we are resolving
  280. * @param from - currentLocation.path, should start with `/`
  281. */
  282. function resolveRelativePath(to, from) {
  283. if (to.startsWith("/")) return to;
  284. if (process.env.NODE_ENV !== "production" && !from.startsWith("/")) {
  285. warn$1(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`);
  286. return to;
  287. }
  288. if (!to) return from;
  289. const fromSegments = from.split("/");
  290. const toSegments = to.split("/");
  291. const lastToSegment = toSegments[toSegments.length - 1];
  292. if (lastToSegment === ".." || lastToSegment === ".") toSegments.push("");
  293. let position = fromSegments.length - 1;
  294. let toPosition;
  295. let segment;
  296. for (toPosition = 0; toPosition < toSegments.length; toPosition++) {
  297. segment = toSegments[toPosition];
  298. if (segment === ".") continue;
  299. if (segment === "..") {
  300. if (position > 1) position--;
  301. } else break;
  302. }
  303. return fromSegments.slice(0, position).join("/") + "/" + toSegments.slice(toPosition).join("/");
  304. }
  305. /**
  306. * Initial route location where the router is. Can be used in navigation guards
  307. * to differentiate the initial navigation.
  308. *
  309. * @example
  310. * ```js
  311. * import { START_LOCATION } from 'vue-router'
  312. *
  313. * router.beforeEach((to, from) => {
  314. * if (from === START_LOCATION) {
  315. * // initial navigation
  316. * }
  317. * })
  318. * ```
  319. */
  320. const START_LOCATION_NORMALIZED = {
  321. path: "/",
  322. name: void 0,
  323. params: {},
  324. query: {},
  325. hash: "",
  326. fullPath: "/",
  327. matched: [],
  328. meta: {},
  329. redirectedFrom: void 0
  330. };
  331. //#endregion
  332. //#region src/history/common.ts
  333. let NavigationType = /* @__PURE__ */ function(NavigationType$1) {
  334. NavigationType$1["pop"] = "pop";
  335. NavigationType$1["push"] = "push";
  336. return NavigationType$1;
  337. }({});
  338. let NavigationDirection = /* @__PURE__ */ function(NavigationDirection$1) {
  339. NavigationDirection$1["back"] = "back";
  340. NavigationDirection$1["forward"] = "forward";
  341. NavigationDirection$1["unknown"] = "";
  342. return NavigationDirection$1;
  343. }({});
  344. /**
  345. * Starting location for Histories
  346. */
  347. const START = "";
  348. /**
  349. * Normalizes a base by removing any trailing slash and reading the base tag if
  350. * present.
  351. *
  352. * @param base - base to normalize
  353. */
  354. function normalizeBase(base) {
  355. if (!base) if (isBrowser) {
  356. const baseEl = document.querySelector("base");
  357. base = baseEl && baseEl.getAttribute("href") || "/";
  358. base = base.replace(/^\w+:\/\/[^\/]+/, "");
  359. } else base = "/";
  360. if (base[0] !== "/" && base[0] !== "#") base = "/" + base;
  361. return removeTrailingSlash(base);
  362. }
  363. const BEFORE_HASH_RE = /^[^#]+#/;
  364. function createHref(base, location) {
  365. return base.replace(BEFORE_HASH_RE, "#") + location;
  366. }
  367. //#endregion
  368. //#region src/scrollBehavior.ts
  369. function getElementPosition(el, offset) {
  370. const docRect = document.documentElement.getBoundingClientRect();
  371. const elRect = el.getBoundingClientRect();
  372. return {
  373. behavior: offset.behavior,
  374. left: elRect.left - docRect.left - (offset.left || 0),
  375. top: elRect.top - docRect.top - (offset.top || 0)
  376. };
  377. }
  378. const computeScrollPosition = () => ({
  379. left: window.scrollX,
  380. top: window.scrollY
  381. });
  382. function scrollToPosition(position) {
  383. let scrollToOptions;
  384. if ("el" in position) {
  385. const positionEl = position.el;
  386. const isIdSelector = typeof positionEl === "string" && positionEl.startsWith("#");
  387. /**
  388. * `id`s can accept pretty much any characters, including CSS combinators
  389. * like `>` or `~`. It's still possible to retrieve elements using
  390. * `document.getElementById('~')` but it needs to be escaped when using
  391. * `document.querySelector('#\\~')` for it to be valid. The only
  392. * requirements for `id`s are them to be unique on the page and to not be
  393. * empty (`id=""`). Because of that, when passing an id selector, it should
  394. * be properly escaped for it to work with `querySelector`. We could check
  395. * for the id selector to be simple (no CSS combinators `+ >~`) but that
  396. * would make things inconsistent since they are valid characters for an
  397. * `id` but would need to be escaped when using `querySelector`, breaking
  398. * their usage and ending up in no selector returned. Selectors need to be
  399. * escaped:
  400. *
  401. * - `#1-thing` becomes `#\31 -thing`
  402. * - `#with~symbols` becomes `#with\\~symbols`
  403. *
  404. * - More information about the topic can be found at
  405. * https://mathiasbynens.be/notes/html5-id-class.
  406. * - Practical example: https://mathiasbynens.be/demo/html5-id
  407. */
  408. if (process.env.NODE_ENV !== "production" && typeof position.el === "string") {
  409. if (!isIdSelector || !document.getElementById(position.el.slice(1))) try {
  410. const foundEl = document.querySelector(position.el);
  411. if (isIdSelector && foundEl) {
  412. warn$1(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`);
  413. return;
  414. }
  415. } catch (err) {
  416. warn$1(`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).`);
  417. return;
  418. }
  419. }
  420. const el = typeof positionEl === "string" ? isIdSelector ? document.getElementById(positionEl.slice(1)) : document.querySelector(positionEl) : positionEl;
  421. if (!el) {
  422. process.env.NODE_ENV !== "production" && warn$1(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`);
  423. return;
  424. }
  425. scrollToOptions = getElementPosition(el, position);
  426. } else scrollToOptions = position;
  427. if ("scrollBehavior" in document.documentElement.style) window.scrollTo(scrollToOptions);
  428. else window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.scrollX, scrollToOptions.top != null ? scrollToOptions.top : window.scrollY);
  429. }
  430. function getScrollKey(path, delta) {
  431. return (history.state ? history.state.position - delta : -1) + path;
  432. }
  433. const scrollPositions = /* @__PURE__ */ new Map();
  434. function saveScrollPosition(key, scrollPosition) {
  435. scrollPositions.set(key, scrollPosition);
  436. }
  437. function getSavedScrollPosition(key) {
  438. const scroll = scrollPositions.get(key);
  439. scrollPositions.delete(key);
  440. return scroll;
  441. }
  442. /**
  443. * ScrollBehavior instance used by the router to compute and restore the scroll
  444. * position when navigating.
  445. */
  446. //#endregion
  447. //#region src/types/typeGuards.ts
  448. function isRouteLocation(route) {
  449. return typeof route === "string" || route && typeof route === "object";
  450. }
  451. function isRouteName(name) {
  452. return typeof name === "string" || typeof name === "symbol";
  453. }
  454. //#endregion
  455. //#region src/errors.ts
  456. /**
  457. * Flags so we can combine them when checking for multiple errors. This is the internal version of
  458. * {@link NavigationFailureType}.
  459. *
  460. * @internal
  461. */
  462. let ErrorTypes = /* @__PURE__ */ function(ErrorTypes$1) {
  463. ErrorTypes$1[ErrorTypes$1["MATCHER_NOT_FOUND"] = 1] = "MATCHER_NOT_FOUND";
  464. ErrorTypes$1[ErrorTypes$1["NAVIGATION_GUARD_REDIRECT"] = 2] = "NAVIGATION_GUARD_REDIRECT";
  465. ErrorTypes$1[ErrorTypes$1["NAVIGATION_ABORTED"] = 4] = "NAVIGATION_ABORTED";
  466. ErrorTypes$1[ErrorTypes$1["NAVIGATION_CANCELLED"] = 8] = "NAVIGATION_CANCELLED";
  467. ErrorTypes$1[ErrorTypes$1["NAVIGATION_DUPLICATED"] = 16] = "NAVIGATION_DUPLICATED";
  468. return ErrorTypes$1;
  469. }({});
  470. const NavigationFailureSymbol = Symbol(process.env.NODE_ENV !== "production" ? "navigation failure" : "");
  471. /**
  472. * Enumeration with all possible types for navigation failures. Can be passed to
  473. * {@link isNavigationFailure} to check for specific failures.
  474. */
  475. let NavigationFailureType = /* @__PURE__ */ function(NavigationFailureType$1) {
  476. /**
  477. * An aborted navigation is a navigation that failed because a navigation
  478. * guard returned `false` or called `next(false)`
  479. */
  480. NavigationFailureType$1[NavigationFailureType$1["aborted"] = 4] = "aborted";
  481. /**
  482. * A cancelled navigation is a navigation that failed because a more recent
  483. * navigation finished started (not necessarily finished).
  484. */
  485. NavigationFailureType$1[NavigationFailureType$1["cancelled"] = 8] = "cancelled";
  486. /**
  487. * A duplicated navigation is a navigation that failed because it was
  488. * initiated while already being at the exact same location.
  489. */
  490. NavigationFailureType$1[NavigationFailureType$1["duplicated"] = 16] = "duplicated";
  491. return NavigationFailureType$1;
  492. }({});
  493. const ErrorTypeMessages = {
  494. [ErrorTypes.MATCHER_NOT_FOUND]({ location, currentLocation }) {
  495. return `No match for\n ${JSON.stringify(location)}${currentLocation ? "\nwhile being at\n" + JSON.stringify(currentLocation) : ""}`;
  496. },
  497. [ErrorTypes.NAVIGATION_GUARD_REDIRECT]({ from, to }) {
  498. return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`;
  499. },
  500. [ErrorTypes.NAVIGATION_ABORTED]({ from, to }) {
  501. return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`;
  502. },
  503. [ErrorTypes.NAVIGATION_CANCELLED]({ from, to }) {
  504. return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`;
  505. },
  506. [ErrorTypes.NAVIGATION_DUPLICATED]({ from, to }) {
  507. return `Avoided redundant navigation to current location: "${from.fullPath}".`;
  508. }
  509. };
  510. /**
  511. * Creates a typed NavigationFailure object.
  512. * @internal
  513. * @param type - NavigationFailureType
  514. * @param params - { from, to }
  515. */
  516. function createRouterError(type, params) {
  517. if (process.env.NODE_ENV !== "production" || false) return assign(new Error(ErrorTypeMessages[type](params)), {
  518. type,
  519. [NavigationFailureSymbol]: true
  520. }, params);
  521. else return assign(/* @__PURE__ */ new Error(), {
  522. type,
  523. [NavigationFailureSymbol]: true
  524. }, params);
  525. }
  526. function isNavigationFailure(error, type) {
  527. return error instanceof Error && NavigationFailureSymbol in error && (type == null || !!(error.type & type));
  528. }
  529. const propertiesToLog = [
  530. "params",
  531. "query",
  532. "hash"
  533. ];
  534. function stringifyRoute(to) {
  535. if (typeof to === "string") return to;
  536. if (to.path != null) return to.path;
  537. const location = {};
  538. for (const key of propertiesToLog) if (key in to) location[key] = to[key];
  539. return JSON.stringify(location, null, 2);
  540. }
  541. //#endregion
  542. //#region src/query.ts
  543. /**
  544. * Transforms a queryString into a {@link LocationQuery} object. Accept both, a
  545. * version with the leading `?` and without Should work as URLSearchParams
  546. * @internal
  547. *
  548. * @param search - search string to parse
  549. * @returns a query object
  550. */
  551. function parseQuery(search) {
  552. const query = {};
  553. if (search === "" || search === "?") return query;
  554. const searchParams = (search[0] === "?" ? search.slice(1) : search).split("&");
  555. for (let i = 0; i < searchParams.length; ++i) {
  556. const searchParam = searchParams[i].replace(PLUS_RE, " ");
  557. const eqPos = searchParam.indexOf("=");
  558. const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos));
  559. const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1));
  560. if (key in query) {
  561. let currentValue = query[key];
  562. if (!isArray(currentValue)) currentValue = query[key] = [currentValue];
  563. currentValue.push(value);
  564. } else query[key] = value;
  565. }
  566. return query;
  567. }
  568. /**
  569. * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
  570. * doesn't prepend a `?`
  571. *
  572. * @internal
  573. *
  574. * @param query - query object to stringify
  575. * @returns string version of the query without the leading `?`
  576. */
  577. function stringifyQuery(query) {
  578. let search = "";
  579. for (let key in query) {
  580. const value = query[key];
  581. key = encodeQueryKey(key);
  582. if (value == null) {
  583. if (value !== void 0) search += (search.length ? "&" : "") + key;
  584. continue;
  585. }
  586. (isArray(value) ? value.map((v) => v && encodeQueryValue(v)) : [value && encodeQueryValue(value)]).forEach((value$1) => {
  587. if (value$1 !== void 0) {
  588. search += (search.length ? "&" : "") + key;
  589. if (value$1 != null) search += "=" + value$1;
  590. }
  591. });
  592. }
  593. return search;
  594. }
  595. /**
  596. * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting
  597. * numbers into strings, removing keys with an undefined value and replacing
  598. * undefined with null in arrays
  599. *
  600. * @param query - query object to normalize
  601. * @returns a normalized query object
  602. */
  603. function normalizeQuery(query) {
  604. const normalizedQuery = {};
  605. for (const key in query) {
  606. const value = query[key];
  607. if (value !== void 0) normalizedQuery[key] = isArray(value) ? value.map((v) => v == null ? null : "" + v) : value == null ? value : "" + value;
  608. }
  609. return normalizedQuery;
  610. }
  611. //#endregion
  612. //#region src/injectionSymbols.ts
  613. /**
  614. * RouteRecord being rendered by the closest ancestor Router View. Used for
  615. * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
  616. * Location Matched
  617. *
  618. * @internal
  619. */
  620. const matchedRouteKey = Symbol(process.env.NODE_ENV !== "production" ? "router view location matched" : "");
  621. /**
  622. * Allows overriding the router view depth to control which component in
  623. * `matched` is rendered. rvd stands for Router View Depth
  624. *
  625. * @internal
  626. */
  627. const viewDepthKey = Symbol(process.env.NODE_ENV !== "production" ? "router view depth" : "");
  628. /**
  629. * Allows overriding the router instance returned by `useRouter` in tests. r
  630. * stands for router
  631. *
  632. * @internal
  633. */
  634. const routerKey = Symbol(process.env.NODE_ENV !== "production" ? "router" : "");
  635. /**
  636. * Allows overriding the current route returned by `useRoute` in tests. rl
  637. * stands for route location
  638. *
  639. * @internal
  640. */
  641. const routeLocationKey = Symbol(process.env.NODE_ENV !== "production" ? "route location" : "");
  642. /**
  643. * Allows overriding the current route used by router-view. Internally this is
  644. * used when the `route` prop is passed.
  645. *
  646. * @internal
  647. */
  648. const routerViewLocationKey = Symbol(process.env.NODE_ENV !== "production" ? "router view location" : "");
  649. //#endregion
  650. //#region src/utils/callbacks.ts
  651. /**
  652. * Create a list of callbacks that can be reset. Used to create before and after navigation guards list
  653. */
  654. function useCallbacks() {
  655. let handlers = [];
  656. function add(handler) {
  657. handlers.push(handler);
  658. return () => {
  659. const i = handlers.indexOf(handler);
  660. if (i > -1) handlers.splice(i, 1);
  661. };
  662. }
  663. function reset() {
  664. handlers = [];
  665. }
  666. return {
  667. add,
  668. list: () => handlers.slice(),
  669. reset
  670. };
  671. }
  672. //#endregion
  673. //#region src/navigationGuards.ts
  674. function registerGuard(record, name, guard) {
  675. const removeFromList = () => {
  676. record[name].delete(guard);
  677. };
  678. onUnmounted(removeFromList);
  679. onDeactivated(removeFromList);
  680. onActivated(() => {
  681. record[name].add(guard);
  682. });
  683. record[name].add(guard);
  684. }
  685. /**
  686. * Add a navigation guard that triggers whenever the component for the current
  687. * location is about to be left. Similar to {@link beforeRouteLeave} but can be
  688. * used in any component. The guard is removed when the component is unmounted.
  689. *
  690. * @param leaveGuard - {@link NavigationGuard}
  691. */
  692. function onBeforeRouteLeave(leaveGuard) {
  693. if (process.env.NODE_ENV !== "production" && !getCurrentInstance()) {
  694. warn$1("getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function");
  695. return;
  696. }
  697. const activeRecord = inject(matchedRouteKey, {}).value;
  698. if (!activeRecord) {
  699. process.env.NODE_ENV !== "production" && warn$1("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?");
  700. return;
  701. }
  702. registerGuard(activeRecord, "leaveGuards", leaveGuard);
  703. }
  704. /**
  705. * Add a navigation guard that triggers whenever the current location is about
  706. * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
  707. * component. The guard is removed when the component is unmounted.
  708. *
  709. * @param updateGuard - {@link NavigationGuard}
  710. */
  711. function onBeforeRouteUpdate(updateGuard) {
  712. if (process.env.NODE_ENV !== "production" && !getCurrentInstance()) {
  713. warn$1("getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function");
  714. return;
  715. }
  716. const activeRecord = inject(matchedRouteKey, {}).value;
  717. if (!activeRecord) {
  718. process.env.NODE_ENV !== "production" && warn$1("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?");
  719. return;
  720. }
  721. registerGuard(activeRecord, "updateGuards", updateGuard);
  722. }
  723. function guardToPromiseFn(guard, to, from, record, name, runWithContext = (fn) => fn()) {
  724. const enterCallbackArray = record && (record.enterCallbacks[name] = record.enterCallbacks[name] || []);
  725. return () => new Promise((resolve, reject) => {
  726. const next = (valid) => {
  727. if (valid === false) reject(createRouterError(ErrorTypes.NAVIGATION_ABORTED, {
  728. from,
  729. to
  730. }));
  731. else if (valid instanceof Error) reject(valid);
  732. else if (isRouteLocation(valid)) reject(createRouterError(ErrorTypes.NAVIGATION_GUARD_REDIRECT, {
  733. from: to,
  734. to: valid
  735. }));
  736. else {
  737. if (enterCallbackArray && record.enterCallbacks[name] === enterCallbackArray && typeof valid === "function") enterCallbackArray.push(valid);
  738. resolve();
  739. }
  740. };
  741. const guardReturn = runWithContext(() => guard.call(record && record.instances[name], to, from, process.env.NODE_ENV !== "production" ? canOnlyBeCalledOnce(next, to, from) : next));
  742. let guardCall = Promise.resolve(guardReturn);
  743. if (guard.length < 3) guardCall = guardCall.then(next);
  744. if (process.env.NODE_ENV !== "production" && guard.length > 2) {
  745. 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.`;
  746. if (typeof guardReturn === "object" && "then" in guardReturn) guardCall = guardCall.then((resolvedValue) => {
  747. if (!next._called) {
  748. warn$1(message);
  749. return Promise.reject(/* @__PURE__ */ new Error("Invalid navigation guard"));
  750. }
  751. return resolvedValue;
  752. });
  753. else if (guardReturn !== void 0) {
  754. if (!next._called) {
  755. warn$1(message);
  756. reject(/* @__PURE__ */ new Error("Invalid navigation guard"));
  757. return;
  758. }
  759. }
  760. }
  761. guardCall.catch((err) => reject(err));
  762. });
  763. }
  764. function canOnlyBeCalledOnce(next, to, from) {
  765. let called = 0;
  766. return function() {
  767. if (called++ === 1) warn$1(`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.`);
  768. next._called = true;
  769. if (called === 1) next.apply(null, arguments);
  770. };
  771. }
  772. function extractComponentsGuards(matched, guardType, to, from, runWithContext = (fn) => fn()) {
  773. const guards = [];
  774. for (const record of matched) {
  775. if (process.env.NODE_ENV !== "production" && !record.components && record.children && !record.children.length) warn$1(`Record with path "${record.path}" is either missing a "component(s)" or "children" property.`);
  776. for (const name in record.components) {
  777. let rawComponent = record.components[name];
  778. if (process.env.NODE_ENV !== "production") {
  779. if (!rawComponent || typeof rawComponent !== "object" && typeof rawComponent !== "function") {
  780. warn$1(`Component "${name}" in record with path "${record.path}" is not a valid component. Received "${String(rawComponent)}".`);
  781. throw new Error("Invalid route component");
  782. } else if ("then" in rawComponent) {
  783. warn$1(`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.`);
  784. const promise = rawComponent;
  785. rawComponent = () => promise;
  786. } else if (rawComponent.__asyncLoader && !rawComponent.__warnedDefineAsync) {
  787. rawComponent.__warnedDefineAsync = true;
  788. warn$1(`Component "${name}" in record with path "${record.path}" is defined using "defineAsyncComponent()". Write "() => import('./MyPage.vue')" instead of "defineAsyncComponent(() => import('./MyPage.vue'))".`);
  789. }
  790. }
  791. if (guardType !== "beforeRouteEnter" && !record.instances[name]) continue;
  792. if (isRouteComponent(rawComponent)) {
  793. const guard = (rawComponent.__vccOpts || rawComponent)[guardType];
  794. guard && guards.push(guardToPromiseFn(guard, to, from, record, name, runWithContext));
  795. } else {
  796. let componentPromise = rawComponent();
  797. if (process.env.NODE_ENV !== "production" && !("catch" in componentPromise)) {
  798. warn$1(`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.`);
  799. componentPromise = Promise.resolve(componentPromise);
  800. }
  801. guards.push(() => componentPromise.then((resolved) => {
  802. if (!resolved) throw new Error(`Couldn't resolve component "${name}" at "${record.path}"`);
  803. const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
  804. record.mods[name] = resolved;
  805. record.components[name] = resolvedComponent;
  806. const guard = (resolvedComponent.__vccOpts || resolvedComponent)[guardType];
  807. return guard && guardToPromiseFn(guard, to, from, record, name, runWithContext)();
  808. }));
  809. }
  810. }
  811. }
  812. return guards;
  813. }
  814. /**
  815. * Ensures a route is loaded, so it can be passed as o prop to `<RouterView>`.
  816. *
  817. * @param route - resolved route to load
  818. */
  819. function loadRouteLocation(route) {
  820. 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) => {
  821. const rawComponent = record.components[name];
  822. if (typeof rawComponent === "function" && !("displayName" in rawComponent)) promises.push(rawComponent().then((resolved) => {
  823. 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.`));
  824. const resolvedComponent = isESModule(resolved) ? resolved.default : resolved;
  825. record.mods[name] = resolved;
  826. record.components[name] = resolvedComponent;
  827. }));
  828. return promises;
  829. }, [])))).then(() => route);
  830. }
  831. /**
  832. * Split the leaving, updating, and entering records.
  833. * @internal
  834. *
  835. * @param to - Location we are navigating to
  836. * @param from - Location we are navigating from
  837. */
  838. function extractChangingRecords(to, from) {
  839. const leavingRecords = [];
  840. const updatingRecords = [];
  841. const enteringRecords = [];
  842. const len = Math.max(from.matched.length, to.matched.length);
  843. for (let i = 0; i < len; i++) {
  844. const recordFrom = from.matched[i];
  845. if (recordFrom) if (to.matched.find((record) => isSameRouteRecord(record, recordFrom))) updatingRecords.push(recordFrom);
  846. else leavingRecords.push(recordFrom);
  847. const recordTo = to.matched[i];
  848. if (recordTo) {
  849. if (!from.matched.find((record) => isSameRouteRecord(record, recordTo))) enteringRecords.push(recordTo);
  850. }
  851. }
  852. return [
  853. leavingRecords,
  854. updatingRecords,
  855. enteringRecords
  856. ];
  857. }
  858. //#endregion
  859. //#region src/devtools.ts
  860. /**
  861. * Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Vue instances).
  862. *
  863. * @param routeLocation - routeLocation to format
  864. * @param tooltip - optional tooltip
  865. * @returns a copy of the routeLocation
  866. */
  867. function formatRouteLocation(routeLocation, tooltip) {
  868. const copy = assign({}, routeLocation, { matched: routeLocation.matched.map((matched) => omit(matched, [
  869. "instances",
  870. "children",
  871. "aliasOf"
  872. ])) });
  873. return { _custom: {
  874. type: null,
  875. readOnly: true,
  876. display: routeLocation.fullPath,
  877. tooltip,
  878. value: copy
  879. } };
  880. }
  881. function formatDisplay(display) {
  882. return { _custom: { display } };
  883. }
  884. let routerId = 0;
  885. function addDevtools(app, router, matcher) {
  886. if (router.__hasDevtools) return;
  887. router.__hasDevtools = true;
  888. const id = routerId++;
  889. setupDevtoolsPlugin({
  890. id: "org.vuejs.router" + (id ? "." + id : ""),
  891. label: "Vue Router",
  892. packageName: "vue-router",
  893. homepage: "https://router.vuejs.org",
  894. logo: "https://router.vuejs.org/logo.png",
  895. componentStateTypes: ["Routing"],
  896. app
  897. }, (api) => {
  898. if (typeof api.now !== "function") warn$1("[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.");
  899. api.on.inspectComponent((payload, ctx) => {
  900. if (payload.instanceData) payload.instanceData.state.push({
  901. type: "Routing",
  902. key: "$route",
  903. editable: false,
  904. value: formatRouteLocation(router.currentRoute.value, "Current Route")
  905. });
  906. });
  907. api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
  908. if (componentInstance.__vrv_devtools) {
  909. const info = componentInstance.__vrv_devtools;
  910. node.tags.push({
  911. label: (info.name ? `${info.name.toString()}: ` : "") + info.path,
  912. textColor: 0,
  913. tooltip: "This component is rendered by &lt;router-view&gt;",
  914. backgroundColor: PINK_500
  915. });
  916. }
  917. if (isArray(componentInstance.__vrl_devtools)) {
  918. componentInstance.__devtoolsApi = api;
  919. componentInstance.__vrl_devtools.forEach((devtoolsData) => {
  920. let label = devtoolsData.route.path;
  921. let backgroundColor = ORANGE_400;
  922. let tooltip = "";
  923. let textColor = 0;
  924. if (devtoolsData.error) {
  925. label = devtoolsData.error;
  926. backgroundColor = RED_100;
  927. textColor = RED_700;
  928. } else if (devtoolsData.isExactActive) {
  929. backgroundColor = LIME_500;
  930. tooltip = "This is exactly active";
  931. } else if (devtoolsData.isActive) {
  932. backgroundColor = BLUE_600;
  933. tooltip = "This link is active";
  934. }
  935. node.tags.push({
  936. label,
  937. textColor,
  938. tooltip,
  939. backgroundColor
  940. });
  941. });
  942. }
  943. });
  944. watch(router.currentRoute, () => {
  945. refreshRoutesView();
  946. api.notifyComponentUpdate();
  947. api.sendInspectorTree(routerInspectorId);
  948. api.sendInspectorState(routerInspectorId);
  949. });
  950. const navigationsLayerId = "router:navigations:" + id;
  951. api.addTimelineLayer({
  952. id: navigationsLayerId,
  953. label: `Router${id ? " " + id : ""} Navigations`,
  954. color: 4237508
  955. });
  956. router.onError((error, to) => {
  957. api.addTimelineEvent({
  958. layerId: navigationsLayerId,
  959. event: {
  960. title: "Error during Navigation",
  961. subtitle: to.fullPath,
  962. logType: "error",
  963. time: api.now(),
  964. data: { error },
  965. groupId: to.meta.__navigationId
  966. }
  967. });
  968. });
  969. let navigationId = 0;
  970. router.beforeEach((to, from) => {
  971. const data = {
  972. guard: formatDisplay("beforeEach"),
  973. from: formatRouteLocation(from, "Current Location during this navigation"),
  974. to: formatRouteLocation(to, "Target location")
  975. };
  976. Object.defineProperty(to.meta, "__navigationId", { value: navigationId++ });
  977. api.addTimelineEvent({
  978. layerId: navigationsLayerId,
  979. event: {
  980. time: api.now(),
  981. title: "Start of navigation",
  982. subtitle: to.fullPath,
  983. data,
  984. groupId: to.meta.__navigationId
  985. }
  986. });
  987. });
  988. router.afterEach((to, from, failure) => {
  989. const data = { guard: formatDisplay("afterEach") };
  990. if (failure) {
  991. data.failure = { _custom: {
  992. type: Error,
  993. readOnly: true,
  994. display: failure ? failure.message : "",
  995. tooltip: "Navigation Failure",
  996. value: failure
  997. } };
  998. data.status = formatDisplay("❌");
  999. } else data.status = formatDisplay("✅");
  1000. data.from = formatRouteLocation(from, "Current Location during this navigation");
  1001. data.to = formatRouteLocation(to, "Target location");
  1002. api.addTimelineEvent({
  1003. layerId: navigationsLayerId,
  1004. event: {
  1005. title: "End of navigation",
  1006. subtitle: to.fullPath,
  1007. time: api.now(),
  1008. data,
  1009. logType: failure ? "warning" : "default",
  1010. groupId: to.meta.__navigationId
  1011. }
  1012. });
  1013. });
  1014. /**
  1015. * Inspector of Existing routes
  1016. */
  1017. const routerInspectorId = "router-inspector:" + id;
  1018. api.addInspector({
  1019. id: routerInspectorId,
  1020. label: "Routes" + (id ? " " + id : ""),
  1021. icon: "book",
  1022. treeFilterPlaceholder: "Search routes"
  1023. });
  1024. function refreshRoutesView() {
  1025. if (!activeRoutesPayload) return;
  1026. const payload = activeRoutesPayload;
  1027. let routes = matcher.getRoutes().filter((route) => !route.parent || !route.parent.record.components);
  1028. routes.forEach(resetMatchStateOnRouteRecord);
  1029. if (payload.filter) routes = routes.filter((route) => isRouteMatching(route, payload.filter.toLowerCase()));
  1030. routes.forEach((route) => markRouteRecordActive(route, router.currentRoute.value));
  1031. payload.rootNodes = routes.map(formatRouteRecordForInspector);
  1032. }
  1033. let activeRoutesPayload;
  1034. api.on.getInspectorTree((payload) => {
  1035. activeRoutesPayload = payload;
  1036. if (payload.app === app && payload.inspectorId === routerInspectorId) refreshRoutesView();
  1037. });
  1038. /**
  1039. * Display information about the currently selected route record
  1040. */
  1041. api.on.getInspectorState((payload) => {
  1042. if (payload.app === app && payload.inspectorId === routerInspectorId) {
  1043. const route = matcher.getRoutes().find((route$1) => route$1.record.__vd_id === payload.nodeId);
  1044. if (route) payload.state = { options: formatRouteRecordMatcherForStateInspector(route) };
  1045. }
  1046. });
  1047. api.sendInspectorTree(routerInspectorId);
  1048. api.sendInspectorState(routerInspectorId);
  1049. });
  1050. }
  1051. function modifierForKey(key) {
  1052. if (key.optional) return key.repeatable ? "*" : "?";
  1053. else return key.repeatable ? "+" : "";
  1054. }
  1055. function formatRouteRecordMatcherForStateInspector(route) {
  1056. const { record } = route;
  1057. const fields = [{
  1058. editable: false,
  1059. key: "path",
  1060. value: record.path
  1061. }];
  1062. if (record.name != null) fields.push({
  1063. editable: false,
  1064. key: "name",
  1065. value: record.name
  1066. });
  1067. fields.push({
  1068. editable: false,
  1069. key: "regexp",
  1070. value: route.re
  1071. });
  1072. if (route.keys.length) fields.push({
  1073. editable: false,
  1074. key: "keys",
  1075. value: { _custom: {
  1076. type: null,
  1077. readOnly: true,
  1078. display: route.keys.map((key) => `${key.name}${modifierForKey(key)}`).join(" "),
  1079. tooltip: "Param keys",
  1080. value: route.keys
  1081. } }
  1082. });
  1083. if (record.redirect != null) fields.push({
  1084. editable: false,
  1085. key: "redirect",
  1086. value: record.redirect
  1087. });
  1088. if (route.alias.length) fields.push({
  1089. editable: false,
  1090. key: "aliases",
  1091. value: route.alias.map((alias) => alias.record.path)
  1092. });
  1093. if (Object.keys(route.record.meta).length) fields.push({
  1094. editable: false,
  1095. key: "meta",
  1096. value: route.record.meta
  1097. });
  1098. fields.push({
  1099. key: "score",
  1100. editable: false,
  1101. value: { _custom: {
  1102. type: null,
  1103. readOnly: true,
  1104. display: route.score.map((score) => score.join(", ")).join(" | "),
  1105. tooltip: "Score used to sort routes",
  1106. value: route.score
  1107. } }
  1108. });
  1109. return fields;
  1110. }
  1111. /**
  1112. * Extracted from tailwind palette
  1113. */
  1114. const PINK_500 = 15485081;
  1115. const BLUE_600 = 2450411;
  1116. const LIME_500 = 8702998;
  1117. const CYAN_400 = 2282478;
  1118. const ORANGE_400 = 16486972;
  1119. const DARK = 6710886;
  1120. const RED_100 = 16704226;
  1121. const RED_700 = 12131356;
  1122. function formatRouteRecordForInspector(route) {
  1123. const tags = [];
  1124. const { record } = route;
  1125. if (record.name != null) tags.push({
  1126. label: String(record.name),
  1127. textColor: 0,
  1128. backgroundColor: CYAN_400
  1129. });
  1130. if (record.aliasOf) tags.push({
  1131. label: "alias",
  1132. textColor: 0,
  1133. backgroundColor: ORANGE_400
  1134. });
  1135. if (route.__vd_match) tags.push({
  1136. label: "matches",
  1137. textColor: 0,
  1138. backgroundColor: PINK_500
  1139. });
  1140. if (route.__vd_exactActive) tags.push({
  1141. label: "exact",
  1142. textColor: 0,
  1143. backgroundColor: LIME_500
  1144. });
  1145. if (route.__vd_active) tags.push({
  1146. label: "active",
  1147. textColor: 0,
  1148. backgroundColor: BLUE_600
  1149. });
  1150. if (record.redirect) tags.push({
  1151. label: typeof record.redirect === "string" ? `redirect: ${record.redirect}` : "redirects",
  1152. textColor: 16777215,
  1153. backgroundColor: DARK
  1154. });
  1155. let id = record.__vd_id;
  1156. if (id == null) {
  1157. id = String(routeRecordId++);
  1158. record.__vd_id = id;
  1159. }
  1160. return {
  1161. id,
  1162. label: record.path,
  1163. tags,
  1164. children: route.children.map(formatRouteRecordForInspector)
  1165. };
  1166. }
  1167. let routeRecordId = 0;
  1168. const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
  1169. function markRouteRecordActive(route, currentRoute) {
  1170. const isExactActive = currentRoute.matched.length && isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
  1171. route.__vd_exactActive = route.__vd_active = isExactActive;
  1172. if (!isExactActive) route.__vd_active = currentRoute.matched.some((match) => isSameRouteRecord(match, route.record));
  1173. route.children.forEach((childRoute) => markRouteRecordActive(childRoute, currentRoute));
  1174. }
  1175. function resetMatchStateOnRouteRecord(route) {
  1176. route.__vd_match = false;
  1177. route.children.forEach(resetMatchStateOnRouteRecord);
  1178. }
  1179. function isRouteMatching(route, filter) {
  1180. const found = String(route.re).match(EXTRACT_REGEXP_RE);
  1181. route.__vd_match = false;
  1182. if (!found || found.length < 3) return false;
  1183. if (new RegExp(found[1].replace(/\$$/, ""), found[2]).test(filter)) {
  1184. route.children.forEach((child) => isRouteMatching(child, filter));
  1185. if (route.record.path !== "/" || filter === "/") {
  1186. route.__vd_match = route.re.test(filter);
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. const path = route.record.path.toLowerCase();
  1192. const decodedPath = decode(path);
  1193. if (!filter.startsWith("/") && (decodedPath.includes(filter) || path.includes(filter))) return true;
  1194. if (decodedPath.startsWith(filter) || path.startsWith(filter)) return true;
  1195. if (route.record.name && String(route.record.name).includes(filter)) return true;
  1196. return route.children.some((child) => isRouteMatching(child, filter));
  1197. }
  1198. function omit(obj, keys) {
  1199. const ret = {};
  1200. for (const key in obj) if (!keys.includes(key)) ret[key] = obj[key];
  1201. return ret;
  1202. }
  1203. //#endregion
  1204. export { isBrowser as $, START as A, stringifyURL as B, computeScrollPosition as C, scrollToPosition as D, saveScrollPosition as E, isSameRouteLocation as F, encodePath as G, decode as H, isSameRouteLocationParams as I, assign as J, warn$1 as K, isSameRouteRecord as L, normalizeBase as M, NEW_stringifyURL as N, NavigationDirection as O, START_LOCATION_NORMALIZED as P, noop as Q, parseURL as R, isRouteName as S, getScrollKey as T, encodeHash as U, stripBase as V, encodeParam as W, isArray as X, identityFn as Y, mergeOptions as Z, ErrorTypes as _, loadRouteLocation as a, isNavigationFailure as b, useCallbacks as c, routerKey as d, routerViewLocationKey as f, stringifyQuery as g, parseQuery as h, guardToPromiseFn as i, createHref as j, NavigationType as k, matchedRouteKey as l, normalizeQuery as m, extractChangingRecords as n, onBeforeRouteLeave as o, viewDepthKey as p, applyToParams as q, extractComponentsGuards as r, onBeforeRouteUpdate as s, addDevtools as t, routeLocationKey as u, NavigationFailureType as v, getSavedScrollPosition as w, isRouteLocation as x, createRouterError as y, resolveRelativePath as z };