vue-router.cjs 144 KB

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