vue-router.esm-bundler.js 139 KB

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