vue-router.esm-browser.js 100 KB

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