vue-router.esm-browser.js 100 KB

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