vue-router.esm-browser.js 136 KB

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