vue-router.global.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629
  1. /*!
  2. * vue-router v4.0.16
  3. * (c) 2022 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. var VueRouter = (function (exports, vue) {
  7. 'use strict';
  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. exports.NavigationFailureType = void 0;
  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. })(exports.NavigationFailureType || (exports.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. vue.onUnmounted(removeFromList);
  1836. vue.onDeactivated(removeFromList);
  1837. vue.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 (!vue.getCurrentInstance()) {
  1851. warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function');
  1852. return;
  1853. }
  1854. const activeRecord = vue.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 (!vue.getCurrentInstance()) {
  1872. warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function');
  1873. return;
  1874. }
  1875. const activeRecord = vue.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 = vue.inject(routerKey);
  2040. const currentRoute = vue.inject(routeLocationKey);
  2041. const route = vue.computed(() => router.resolve(vue.unref(props.to)));
  2042. const activeRecordIndex = vue.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 = vue.computed(() => activeRecordIndex.value > -1 &&
  2067. includesParams(currentRoute.params, route.value.params));
  2068. const isExactActive = vue.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[vue.unref(props.replace) ? 'replace' : 'push'](vue.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 = vue.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. vue.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: vue.computed(() => route.value.href),
  2102. isActive,
  2103. isExactActive,
  2104. navigate,
  2105. };
  2106. }
  2107. const RouterLinkImpl = /*#__PURE__*/ vue.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 = vue.reactive(useLink(props));
  2128. const { options } = vue.inject(routerKey);
  2129. const elClass = vue.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. : vue.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__*/ vue.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 = vue.inject(routerViewLocationKey);
  2236. const routeToDisplay = vue.computed(() => props.route || injectedRoute.value);
  2237. const depth = vue.inject(viewDepthKey, 0);
  2238. const matchedRouteRef = vue.computed(() => routeToDisplay.value.matched[depth]);
  2239. vue.provide(viewDepthKey, depth + 1);
  2240. vue.provide(matchedRouteKey, matchedRouteRef);
  2241. vue.provide(routerViewLocationKey, routeToDisplay);
  2242. const viewRef = vue.ref();
  2243. // watch at the same time the component instance, the route record we are
  2244. // rendering, and the name
  2245. vue.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 = vue.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 = vue.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 getDevtoolsGlobalHook() {
  2359. return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
  2360. }
  2361. function getTarget() {
  2362. // @ts-ignore
  2363. return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
  2364. ? window
  2365. : typeof global !== 'undefined'
  2366. ? global
  2367. : {};
  2368. }
  2369. const isProxyAvailable = typeof Proxy === 'function';
  2370. const HOOK_SETUP = 'devtools-plugin:setup';
  2371. const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
  2372. class ApiProxy {
  2373. constructor(plugin, hook) {
  2374. this.target = null;
  2375. this.targetQueue = [];
  2376. this.onQueue = [];
  2377. this.plugin = plugin;
  2378. this.hook = hook;
  2379. const defaultSettings = {};
  2380. if (plugin.settings) {
  2381. for (const id in plugin.settings) {
  2382. const item = plugin.settings[id];
  2383. defaultSettings[id] = item.defaultValue;
  2384. }
  2385. }
  2386. const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
  2387. let currentSettings = Object.assign({}, defaultSettings);
  2388. try {
  2389. const raw = localStorage.getItem(localSettingsSaveId);
  2390. const data = JSON.parse(raw);
  2391. Object.assign(currentSettings, data);
  2392. }
  2393. catch (e) {
  2394. // noop
  2395. }
  2396. this.fallbacks = {
  2397. getSettings() {
  2398. return currentSettings;
  2399. },
  2400. setSettings(value) {
  2401. try {
  2402. localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
  2403. }
  2404. catch (e) {
  2405. // noop
  2406. }
  2407. currentSettings = value;
  2408. },
  2409. };
  2410. if (hook) {
  2411. hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
  2412. if (pluginId === this.plugin.id) {
  2413. this.fallbacks.setSettings(value);
  2414. }
  2415. });
  2416. }
  2417. this.proxiedOn = new Proxy({}, {
  2418. get: (_target, prop) => {
  2419. if (this.target) {
  2420. return this.target.on[prop];
  2421. }
  2422. else {
  2423. return (...args) => {
  2424. this.onQueue.push({
  2425. method: prop,
  2426. args,
  2427. });
  2428. };
  2429. }
  2430. },
  2431. });
  2432. this.proxiedTarget = new Proxy({}, {
  2433. get: (_target, prop) => {
  2434. if (this.target) {
  2435. return this.target[prop];
  2436. }
  2437. else if (prop === 'on') {
  2438. return this.proxiedOn;
  2439. }
  2440. else if (Object.keys(this.fallbacks).includes(prop)) {
  2441. return (...args) => {
  2442. this.targetQueue.push({
  2443. method: prop,
  2444. args,
  2445. resolve: () => { },
  2446. });
  2447. return this.fallbacks[prop](...args);
  2448. };
  2449. }
  2450. else {
  2451. return (...args) => {
  2452. return new Promise(resolve => {
  2453. this.targetQueue.push({
  2454. method: prop,
  2455. args,
  2456. resolve,
  2457. });
  2458. });
  2459. };
  2460. }
  2461. },
  2462. });
  2463. }
  2464. async setRealTarget(target) {
  2465. this.target = target;
  2466. for (const item of this.onQueue) {
  2467. this.target.on[item.method](...item.args);
  2468. }
  2469. for (const item of this.targetQueue) {
  2470. item.resolve(await this.target[item.method](...item.args));
  2471. }
  2472. }
  2473. }
  2474. function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
  2475. const descriptor = pluginDescriptor;
  2476. const target = getTarget();
  2477. const hook = getDevtoolsGlobalHook();
  2478. const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
  2479. if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
  2480. hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
  2481. }
  2482. else {
  2483. const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
  2484. const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
  2485. list.push({
  2486. pluginDescriptor: descriptor,
  2487. setupFn,
  2488. proxy,
  2489. });
  2490. if (proxy)
  2491. setupFn(proxy.proxiedTarget);
  2492. }
  2493. }
  2494. function formatRouteLocation(routeLocation, tooltip) {
  2495. const copy = assign({}, routeLocation, {
  2496. // remove variables that can contain vue instances
  2497. matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])),
  2498. });
  2499. return {
  2500. _custom: {
  2501. type: null,
  2502. readOnly: true,
  2503. display: routeLocation.fullPath,
  2504. tooltip,
  2505. value: copy,
  2506. },
  2507. };
  2508. }
  2509. function formatDisplay(display) {
  2510. return {
  2511. _custom: {
  2512. display,
  2513. },
  2514. };
  2515. }
  2516. // to support multiple router instances
  2517. let routerId = 0;
  2518. function addDevtools(app, router, matcher) {
  2519. // Take over router.beforeEach and afterEach
  2520. // make sure we are not registering the devtool twice
  2521. if (router.__hasDevtools)
  2522. return;
  2523. router.__hasDevtools = true;
  2524. // increment to support multiple router instances
  2525. const id = routerId++;
  2526. setupDevtoolsPlugin({
  2527. id: 'org.vuejs.router' + (id ? '.' + id : ''),
  2528. label: 'Vue Router',
  2529. packageName: 'vue-router',
  2530. homepage: 'https://router.vuejs.org',
  2531. logo: 'https://router.vuejs.org/logo.png',
  2532. componentStateTypes: ['Routing'],
  2533. app,
  2534. }, api => {
  2535. // display state added by the router
  2536. api.on.inspectComponent((payload, ctx) => {
  2537. if (payload.instanceData) {
  2538. payload.instanceData.state.push({
  2539. type: 'Routing',
  2540. key: '$route',
  2541. editable: false,
  2542. value: formatRouteLocation(router.currentRoute.value, 'Current Route'),
  2543. });
  2544. }
  2545. });
  2546. // mark router-link as active and display tags on router views
  2547. api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
  2548. if (componentInstance.__vrv_devtools) {
  2549. const info = componentInstance.__vrv_devtools;
  2550. node.tags.push({
  2551. label: (info.name ? `${info.name.toString()}: ` : '') + info.path,
  2552. textColor: 0,
  2553. tooltip: 'This component is rendered by &lt;router-view&gt;',
  2554. backgroundColor: PINK_500,
  2555. });
  2556. }
  2557. // if multiple useLink are used
  2558. if (Array.isArray(componentInstance.__vrl_devtools)) {
  2559. componentInstance.__devtoolsApi = api;
  2560. componentInstance.__vrl_devtools.forEach(devtoolsData => {
  2561. let backgroundColor = ORANGE_400;
  2562. let tooltip = '';
  2563. if (devtoolsData.isExactActive) {
  2564. backgroundColor = LIME_500;
  2565. tooltip = 'This is exactly active';
  2566. }
  2567. else if (devtoolsData.isActive) {
  2568. backgroundColor = BLUE_600;
  2569. tooltip = 'This link is active';
  2570. }
  2571. node.tags.push({
  2572. label: devtoolsData.route.path,
  2573. textColor: 0,
  2574. tooltip,
  2575. backgroundColor,
  2576. });
  2577. });
  2578. }
  2579. });
  2580. vue.watch(router.currentRoute, () => {
  2581. // refresh active state
  2582. refreshRoutesView();
  2583. api.notifyComponentUpdate();
  2584. api.sendInspectorTree(routerInspectorId);
  2585. api.sendInspectorState(routerInspectorId);
  2586. });
  2587. const navigationsLayerId = 'router:navigations:' + id;
  2588. api.addTimelineLayer({
  2589. id: navigationsLayerId,
  2590. label: `Router${id ? ' ' + id : ''} Navigations`,
  2591. color: 0x40a8c4,
  2592. });
  2593. // const errorsLayerId = 'router:errors'
  2594. // api.addTimelineLayer({
  2595. // id: errorsLayerId,
  2596. // label: 'Router Errors',
  2597. // color: 0xea5455,
  2598. // })
  2599. router.onError((error, to) => {
  2600. api.addTimelineEvent({
  2601. layerId: navigationsLayerId,
  2602. event: {
  2603. title: 'Error during Navigation',
  2604. subtitle: to.fullPath,
  2605. logType: 'error',
  2606. time: api.now(),
  2607. data: { error },
  2608. groupId: to.meta.__navigationId,
  2609. },
  2610. });
  2611. });
  2612. // attached to `meta` and used to group events
  2613. let navigationId = 0;
  2614. router.beforeEach((to, from) => {
  2615. const data = {
  2616. guard: formatDisplay('beforeEach'),
  2617. from: formatRouteLocation(from, 'Current Location during this navigation'),
  2618. to: formatRouteLocation(to, 'Target location'),
  2619. };
  2620. // Used to group navigations together, hide from devtools
  2621. Object.defineProperty(to.meta, '__navigationId', {
  2622. value: navigationId++,
  2623. });
  2624. api.addTimelineEvent({
  2625. layerId: navigationsLayerId,
  2626. event: {
  2627. time: api.now(),
  2628. title: 'Start of navigation',
  2629. subtitle: to.fullPath,
  2630. data,
  2631. groupId: to.meta.__navigationId,
  2632. },
  2633. });
  2634. });
  2635. router.afterEach((to, from, failure) => {
  2636. const data = {
  2637. guard: formatDisplay('afterEach'),
  2638. };
  2639. if (failure) {
  2640. data.failure = {
  2641. _custom: {
  2642. type: Error,
  2643. readOnly: true,
  2644. display: failure ? failure.message : '',
  2645. tooltip: 'Navigation Failure',
  2646. value: failure,
  2647. },
  2648. };
  2649. data.status = formatDisplay('❌');
  2650. }
  2651. else {
  2652. data.status = formatDisplay('✅');
  2653. }
  2654. // we set here to have the right order
  2655. data.from = formatRouteLocation(from, 'Current Location during this navigation');
  2656. data.to = formatRouteLocation(to, 'Target location');
  2657. api.addTimelineEvent({
  2658. layerId: navigationsLayerId,
  2659. event: {
  2660. title: 'End of navigation',
  2661. subtitle: to.fullPath,
  2662. time: api.now(),
  2663. data,
  2664. logType: failure ? 'warning' : 'default',
  2665. groupId: to.meta.__navigationId,
  2666. },
  2667. });
  2668. });
  2669. /**
  2670. * Inspector of Existing routes
  2671. */
  2672. const routerInspectorId = 'router-inspector:' + id;
  2673. api.addInspector({
  2674. id: routerInspectorId,
  2675. label: 'Routes' + (id ? ' ' + id : ''),
  2676. icon: 'book',
  2677. treeFilterPlaceholder: 'Search routes',
  2678. });
  2679. function refreshRoutesView() {
  2680. // the routes view isn't active
  2681. if (!activeRoutesPayload)
  2682. return;
  2683. const payload = activeRoutesPayload;
  2684. // children routes will appear as nested
  2685. let routes = matcher.getRoutes().filter(route => !route.parent);
  2686. // reset match state to false
  2687. routes.forEach(resetMatchStateOnRouteRecord);
  2688. // apply a match state if there is a payload
  2689. if (payload.filter) {
  2690. routes = routes.filter(route =>
  2691. // save matches state based on the payload
  2692. isRouteMatching(route, payload.filter.toLowerCase()));
  2693. }
  2694. // mark active routes
  2695. routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value));
  2696. payload.rootNodes = routes.map(formatRouteRecordForInspector);
  2697. }
  2698. let activeRoutesPayload;
  2699. api.on.getInspectorTree(payload => {
  2700. activeRoutesPayload = payload;
  2701. if (payload.app === app && payload.inspectorId === routerInspectorId) {
  2702. refreshRoutesView();
  2703. }
  2704. });
  2705. /**
  2706. * Display information about the currently selected route record
  2707. */
  2708. api.on.getInspectorState(payload => {
  2709. if (payload.app === app && payload.inspectorId === routerInspectorId) {
  2710. const routes = matcher.getRoutes();
  2711. const route = routes.find(route => route.record.__vd_id === payload.nodeId);
  2712. if (route) {
  2713. payload.state = {
  2714. options: formatRouteRecordMatcherForStateInspector(route),
  2715. };
  2716. }
  2717. }
  2718. });
  2719. api.sendInspectorTree(routerInspectorId);
  2720. api.sendInspectorState(routerInspectorId);
  2721. });
  2722. }
  2723. function modifierForKey(key) {
  2724. if (key.optional) {
  2725. return key.repeatable ? '*' : '?';
  2726. }
  2727. else {
  2728. return key.repeatable ? '+' : '';
  2729. }
  2730. }
  2731. function formatRouteRecordMatcherForStateInspector(route) {
  2732. const { record } = route;
  2733. const fields = [
  2734. { editable: false, key: 'path', value: record.path },
  2735. ];
  2736. if (record.name != null) {
  2737. fields.push({
  2738. editable: false,
  2739. key: 'name',
  2740. value: record.name,
  2741. });
  2742. }
  2743. fields.push({ editable: false, key: 'regexp', value: route.re });
  2744. if (route.keys.length) {
  2745. fields.push({
  2746. editable: false,
  2747. key: 'keys',
  2748. value: {
  2749. _custom: {
  2750. type: null,
  2751. readOnly: true,
  2752. display: route.keys
  2753. .map(key => `${key.name}${modifierForKey(key)}`)
  2754. .join(' '),
  2755. tooltip: 'Param keys',
  2756. value: route.keys,
  2757. },
  2758. },
  2759. });
  2760. }
  2761. if (record.redirect != null) {
  2762. fields.push({
  2763. editable: false,
  2764. key: 'redirect',
  2765. value: record.redirect,
  2766. });
  2767. }
  2768. if (route.alias.length) {
  2769. fields.push({
  2770. editable: false,
  2771. key: 'aliases',
  2772. value: route.alias.map(alias => alias.record.path),
  2773. });
  2774. }
  2775. fields.push({
  2776. key: 'score',
  2777. editable: false,
  2778. value: {
  2779. _custom: {
  2780. type: null,
  2781. readOnly: true,
  2782. display: route.score.map(score => score.join(', ')).join(' | '),
  2783. tooltip: 'Score used to sort routes',
  2784. value: route.score,
  2785. },
  2786. },
  2787. });
  2788. return fields;
  2789. }
  2790. /**
  2791. * Extracted from tailwind palette
  2792. */
  2793. const PINK_500 = 0xec4899;
  2794. const BLUE_600 = 0x2563eb;
  2795. const LIME_500 = 0x84cc16;
  2796. const CYAN_400 = 0x22d3ee;
  2797. const ORANGE_400 = 0xfb923c;
  2798. // const GRAY_100 = 0xf4f4f5
  2799. const DARK = 0x666666;
  2800. function formatRouteRecordForInspector(route) {
  2801. const tags = [];
  2802. const { record } = route;
  2803. if (record.name != null) {
  2804. tags.push({
  2805. label: String(record.name),
  2806. textColor: 0,
  2807. backgroundColor: CYAN_400,
  2808. });
  2809. }
  2810. if (record.aliasOf) {
  2811. tags.push({
  2812. label: 'alias',
  2813. textColor: 0,
  2814. backgroundColor: ORANGE_400,
  2815. });
  2816. }
  2817. if (route.__vd_match) {
  2818. tags.push({
  2819. label: 'matches',
  2820. textColor: 0,
  2821. backgroundColor: PINK_500,
  2822. });
  2823. }
  2824. if (route.__vd_exactActive) {
  2825. tags.push({
  2826. label: 'exact',
  2827. textColor: 0,
  2828. backgroundColor: LIME_500,
  2829. });
  2830. }
  2831. if (route.__vd_active) {
  2832. tags.push({
  2833. label: 'active',
  2834. textColor: 0,
  2835. backgroundColor: BLUE_600,
  2836. });
  2837. }
  2838. if (record.redirect) {
  2839. tags.push({
  2840. label: 'redirect: ' +
  2841. (typeof record.redirect === 'string' ? record.redirect : 'Object'),
  2842. textColor: 0xffffff,
  2843. backgroundColor: DARK,
  2844. });
  2845. }
  2846. // add an id to be able to select it. Using the `path` is not possible because
  2847. // empty path children would collide with their parents
  2848. let id = record.__vd_id;
  2849. if (id == null) {
  2850. id = String(routeRecordId++);
  2851. record.__vd_id = id;
  2852. }
  2853. return {
  2854. id,
  2855. label: record.path,
  2856. tags,
  2857. children: route.children.map(formatRouteRecordForInspector),
  2858. };
  2859. }
  2860. // incremental id for route records and inspector state
  2861. let routeRecordId = 0;
  2862. const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/;
  2863. function markRouteRecordActive(route, currentRoute) {
  2864. // no route will be active if matched is empty
  2865. // reset the matching state
  2866. const isExactActive = currentRoute.matched.length &&
  2867. isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record);
  2868. route.__vd_exactActive = route.__vd_active = isExactActive;
  2869. if (!isExactActive) {
  2870. route.__vd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record));
  2871. }
  2872. route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute));
  2873. }
  2874. function resetMatchStateOnRouteRecord(route) {
  2875. route.__vd_match = false;
  2876. route.children.forEach(resetMatchStateOnRouteRecord);
  2877. }
  2878. function isRouteMatching(route, filter) {
  2879. const found = String(route.re).match(EXTRACT_REGEXP_RE);
  2880. route.__vd_match = false;
  2881. if (!found || found.length < 3) {
  2882. return false;
  2883. }
  2884. // use a regexp without $ at the end to match nested routes better
  2885. const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]);
  2886. if (nonEndingRE.test(filter)) {
  2887. // mark children as matches
  2888. route.children.forEach(child => isRouteMatching(child, filter));
  2889. // exception case: `/`
  2890. if (route.record.path !== '/' || filter === '/') {
  2891. route.__vd_match = route.re.test(filter);
  2892. return true;
  2893. }
  2894. // hide the / route
  2895. return false;
  2896. }
  2897. const path = route.record.path.toLowerCase();
  2898. const decodedPath = decode(path);
  2899. // also allow partial matching on the path
  2900. if (!filter.startsWith('/') &&
  2901. (decodedPath.includes(filter) || path.includes(filter)))
  2902. return true;
  2903. if (decodedPath.startsWith(filter) || path.startsWith(filter))
  2904. return true;
  2905. if (route.record.name && String(route.record.name).includes(filter))
  2906. return true;
  2907. return route.children.some(child => isRouteMatching(child, filter));
  2908. }
  2909. function omit(obj, keys) {
  2910. const ret = {};
  2911. for (const key in obj) {
  2912. if (!keys.includes(key)) {
  2913. // @ts-expect-error
  2914. ret[key] = obj[key];
  2915. }
  2916. }
  2917. return ret;
  2918. }
  2919. /**
  2920. * Creates a Router instance that can be used by a Vue app.
  2921. *
  2922. * @param options - {@link RouterOptions}
  2923. */
  2924. function createRouter(options) {
  2925. const matcher = createRouterMatcher(options.routes, options);
  2926. const parseQuery$1 = options.parseQuery || parseQuery;
  2927. const stringifyQuery$1 = options.stringifyQuery || stringifyQuery;
  2928. const routerHistory = options.history;
  2929. if (!routerHistory)
  2930. throw new Error('Provide the "history" option when calling "createRouter()":' +
  2931. ' https://next.router.vuejs.org/api/#history.');
  2932. const beforeGuards = useCallbacks();
  2933. const beforeResolveGuards = useCallbacks();
  2934. const afterGuards = useCallbacks();
  2935. const currentRoute = vue.shallowRef(START_LOCATION_NORMALIZED);
  2936. let pendingLocation = START_LOCATION_NORMALIZED;
  2937. // leave the scrollRestoration if no scrollBehavior is provided
  2938. if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) {
  2939. history.scrollRestoration = 'manual';
  2940. }
  2941. const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue);
  2942. const encodeParams = applyToParams.bind(null, encodeParam);
  2943. const decodeParams =
  2944. // @ts-expect-error: intentionally avoid the type check
  2945. applyToParams.bind(null, decode);
  2946. function addRoute(parentOrRoute, route) {
  2947. let parent;
  2948. let record;
  2949. if (isRouteName(parentOrRoute)) {
  2950. parent = matcher.getRecordMatcher(parentOrRoute);
  2951. record = route;
  2952. }
  2953. else {
  2954. record = parentOrRoute;
  2955. }
  2956. return matcher.addRoute(record, parent);
  2957. }
  2958. function removeRoute(name) {
  2959. const recordMatcher = matcher.getRecordMatcher(name);
  2960. if (recordMatcher) {
  2961. matcher.removeRoute(recordMatcher);
  2962. }
  2963. else {
  2964. warn(`Cannot remove non-existent route "${String(name)}"`);
  2965. }
  2966. }
  2967. function getRoutes() {
  2968. return matcher.getRoutes().map(routeMatcher => routeMatcher.record);
  2969. }
  2970. function hasRoute(name) {
  2971. return !!matcher.getRecordMatcher(name);
  2972. }
  2973. function resolve(rawLocation, currentLocation) {
  2974. // const objectLocation = routerLocationAsObject(rawLocation)
  2975. // we create a copy to modify it later
  2976. currentLocation = assign({}, currentLocation || currentRoute.value);
  2977. if (typeof rawLocation === 'string') {
  2978. const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path);
  2979. const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation);
  2980. const href = routerHistory.createHref(locationNormalized.fullPath);
  2981. {
  2982. if (href.startsWith('//'))
  2983. warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
  2984. else if (!matchedRoute.matched.length) {
  2985. warn(`No match found for location with path "${rawLocation}"`);
  2986. }
  2987. }
  2988. // locationNormalized is always a new object
  2989. return assign(locationNormalized, matchedRoute, {
  2990. params: decodeParams(matchedRoute.params),
  2991. hash: decode(locationNormalized.hash),
  2992. redirectedFrom: undefined,
  2993. href,
  2994. });
  2995. }
  2996. let matcherLocation;
  2997. // path could be relative in object as well
  2998. if ('path' in rawLocation) {
  2999. if ('params' in rawLocation &&
  3000. !('name' in rawLocation) &&
  3001. // @ts-expect-error: the type is never
  3002. Object.keys(rawLocation.params).length) {
  3003. warn(`Path "${
  3004. // @ts-expect-error: the type is never
  3005. rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`);
  3006. }
  3007. matcherLocation = assign({}, rawLocation, {
  3008. path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path,
  3009. });
  3010. }
  3011. else {
  3012. // remove any nullish param
  3013. const targetParams = assign({}, rawLocation.params);
  3014. for (const key in targetParams) {
  3015. if (targetParams[key] == null) {
  3016. delete targetParams[key];
  3017. }
  3018. }
  3019. // pass encoded values to the matcher so it can produce encoded path and fullPath
  3020. matcherLocation = assign({}, rawLocation, {
  3021. params: encodeParams(rawLocation.params),
  3022. });
  3023. // current location params are decoded, we need to encode them in case the
  3024. // matcher merges the params
  3025. currentLocation.params = encodeParams(currentLocation.params);
  3026. }
  3027. const matchedRoute = matcher.resolve(matcherLocation, currentLocation);
  3028. const hash = rawLocation.hash || '';
  3029. if (hash && !hash.startsWith('#')) {
  3030. warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`);
  3031. }
  3032. // decoding them) the matcher might have merged current location params so
  3033. // we need to run the decoding again
  3034. matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params));
  3035. const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, {
  3036. hash: encodeHash(hash),
  3037. path: matchedRoute.path,
  3038. }));
  3039. const href = routerHistory.createHref(fullPath);
  3040. {
  3041. if (href.startsWith('//')) {
  3042. warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`);
  3043. }
  3044. else if (!matchedRoute.matched.length) {
  3045. warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`);
  3046. }
  3047. }
  3048. return assign({
  3049. fullPath,
  3050. // keep the hash encoded so fullPath is effectively path + encodedQuery +
  3051. // hash
  3052. hash,
  3053. query:
  3054. // if the user is using a custom query lib like qs, we might have
  3055. // nested objects, so we keep the query as is, meaning it can contain
  3056. // numbers at `$route.query`, but at the point, the user will have to
  3057. // use their own type anyway.
  3058. // https://github.com/vuejs/router/issues/328#issuecomment-649481567
  3059. stringifyQuery$1 === stringifyQuery
  3060. ? normalizeQuery(rawLocation.query)
  3061. : (rawLocation.query || {}),
  3062. }, matchedRoute, {
  3063. redirectedFrom: undefined,
  3064. href,
  3065. });
  3066. }
  3067. function locationAsObject(to) {
  3068. return typeof to === 'string'
  3069. ? parseURL(parseQuery$1, to, currentRoute.value.path)
  3070. : assign({}, to);
  3071. }
  3072. function checkCanceledNavigation(to, from) {
  3073. if (pendingLocation !== to) {
  3074. return createRouterError(8 /* NAVIGATION_CANCELLED */, {
  3075. from,
  3076. to,
  3077. });
  3078. }
  3079. }
  3080. function push(to) {
  3081. return pushWithRedirect(to);
  3082. }
  3083. function replace(to) {
  3084. return push(assign(locationAsObject(to), { replace: true }));
  3085. }
  3086. function handleRedirectRecord(to) {
  3087. const lastMatched = to.matched[to.matched.length - 1];
  3088. if (lastMatched && lastMatched.redirect) {
  3089. const { redirect } = lastMatched;
  3090. let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect;
  3091. if (typeof newTargetLocation === 'string') {
  3092. newTargetLocation =
  3093. newTargetLocation.includes('?') || newTargetLocation.includes('#')
  3094. ? (newTargetLocation = locationAsObject(newTargetLocation))
  3095. : // force empty params
  3096. { path: newTargetLocation };
  3097. // @ts-expect-error: force empty params when a string is passed to let
  3098. // the router parse them again
  3099. newTargetLocation.params = {};
  3100. }
  3101. if (!('path' in newTargetLocation) &&
  3102. !('name' in newTargetLocation)) {
  3103. 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.`);
  3104. throw new Error('Invalid redirect');
  3105. }
  3106. return assign({
  3107. query: to.query,
  3108. hash: to.hash,
  3109. params: to.params,
  3110. }, newTargetLocation);
  3111. }
  3112. }
  3113. function pushWithRedirect(to, redirectedFrom) {
  3114. const targetLocation = (pendingLocation = resolve(to));
  3115. const from = currentRoute.value;
  3116. const data = to.state;
  3117. const force = to.force;
  3118. // to could be a string where `replace` is a function
  3119. const replace = to.replace === true;
  3120. const shouldRedirect = handleRedirectRecord(targetLocation);
  3121. if (shouldRedirect)
  3122. return pushWithRedirect(assign(locationAsObject(shouldRedirect), {
  3123. state: data,
  3124. force,
  3125. replace,
  3126. }),
  3127. // keep original redirectedFrom if it exists
  3128. redirectedFrom || targetLocation);
  3129. // if it was a redirect we already called `pushWithRedirect` above
  3130. const toLocation = targetLocation;
  3131. toLocation.redirectedFrom = redirectedFrom;
  3132. let failure;
  3133. if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) {
  3134. failure = createRouterError(16 /* NAVIGATION_DUPLICATED */, { to: toLocation, from });
  3135. // trigger scroll to allow scrolling to the same anchor
  3136. handleScroll(from, from,
  3137. // this is a push, the only way for it to be triggered from a
  3138. // history.listen is with a redirect, which makes it become a push
  3139. true,
  3140. // This cannot be the first navigation because the initial location
  3141. // cannot be manually navigated to
  3142. false);
  3143. }
  3144. return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
  3145. .catch((error) => isNavigationFailure(error)
  3146. ? // navigation redirects still mark the router as ready
  3147. isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)
  3148. ? error
  3149. : markAsReady(error) // also returns the error
  3150. : // reject any unknown error
  3151. triggerError(error, toLocation, from))
  3152. .then((failure) => {
  3153. if (failure) {
  3154. if (isNavigationFailure(failure, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
  3155. if (// we are redirecting to the same location we were already at
  3156. isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) &&
  3157. // and we have done it a couple of times
  3158. redirectedFrom &&
  3159. // @ts-expect-error: added only in dev
  3160. (redirectedFrom._count = redirectedFrom._count
  3161. ? // @ts-expect-error
  3162. redirectedFrom._count + 1
  3163. : 1) > 10) {
  3164. 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.`);
  3165. return Promise.reject(new Error('Infinite redirect in navigation guard'));
  3166. }
  3167. return pushWithRedirect(
  3168. // keep options
  3169. assign(locationAsObject(failure.to), {
  3170. state: data,
  3171. force,
  3172. replace,
  3173. }),
  3174. // preserve the original redirectedFrom if any
  3175. redirectedFrom || toLocation);
  3176. }
  3177. }
  3178. else {
  3179. // if we fail we don't finalize the navigation
  3180. failure = finalizeNavigation(toLocation, from, true, replace, data);
  3181. }
  3182. triggerAfterEach(toLocation, from, failure);
  3183. return failure;
  3184. });
  3185. }
  3186. /**
  3187. * Helper to reject and skip all navigation guards if a new navigation happened
  3188. * @param to
  3189. * @param from
  3190. */
  3191. function checkCanceledNavigationAndReject(to, from) {
  3192. const error = checkCanceledNavigation(to, from);
  3193. return error ? Promise.reject(error) : Promise.resolve();
  3194. }
  3195. // TODO: refactor the whole before guards by internally using router.beforeEach
  3196. function navigate(to, from) {
  3197. let guards;
  3198. const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from);
  3199. // all components here have been resolved once because we are leaving
  3200. guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from);
  3201. // leavingRecords is already reversed
  3202. for (const record of leavingRecords) {
  3203. record.leaveGuards.forEach(guard => {
  3204. guards.push(guardToPromiseFn(guard, to, from));
  3205. });
  3206. }
  3207. const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from);
  3208. guards.push(canceledNavigationCheck);
  3209. // run the queue of per route beforeRouteLeave guards
  3210. return (runGuardQueue(guards)
  3211. .then(() => {
  3212. // check global guards beforeEach
  3213. guards = [];
  3214. for (const guard of beforeGuards.list()) {
  3215. guards.push(guardToPromiseFn(guard, to, from));
  3216. }
  3217. guards.push(canceledNavigationCheck);
  3218. return runGuardQueue(guards);
  3219. })
  3220. .then(() => {
  3221. // check in components beforeRouteUpdate
  3222. guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from);
  3223. for (const record of updatingRecords) {
  3224. record.updateGuards.forEach(guard => {
  3225. guards.push(guardToPromiseFn(guard, to, from));
  3226. });
  3227. }
  3228. guards.push(canceledNavigationCheck);
  3229. // run the queue of per route beforeEnter guards
  3230. return runGuardQueue(guards);
  3231. })
  3232. .then(() => {
  3233. // check the route beforeEnter
  3234. guards = [];
  3235. for (const record of to.matched) {
  3236. // do not trigger beforeEnter on reused views
  3237. if (record.beforeEnter && !from.matched.includes(record)) {
  3238. if (Array.isArray(record.beforeEnter)) {
  3239. for (const beforeEnter of record.beforeEnter)
  3240. guards.push(guardToPromiseFn(beforeEnter, to, from));
  3241. }
  3242. else {
  3243. guards.push(guardToPromiseFn(record.beforeEnter, to, from));
  3244. }
  3245. }
  3246. }
  3247. guards.push(canceledNavigationCheck);
  3248. // run the queue of per route beforeEnter guards
  3249. return runGuardQueue(guards);
  3250. })
  3251. .then(() => {
  3252. // NOTE: at this point to.matched is normalized and does not contain any () => Promise<Component>
  3253. // clear existing enterCallbacks, these are added by extractComponentsGuards
  3254. to.matched.forEach(record => (record.enterCallbacks = {}));
  3255. // check in-component beforeRouteEnter
  3256. guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from);
  3257. guards.push(canceledNavigationCheck);
  3258. // run the queue of per route beforeEnter guards
  3259. return runGuardQueue(guards);
  3260. })
  3261. .then(() => {
  3262. // check global guards beforeResolve
  3263. guards = [];
  3264. for (const guard of beforeResolveGuards.list()) {
  3265. guards.push(guardToPromiseFn(guard, to, from));
  3266. }
  3267. guards.push(canceledNavigationCheck);
  3268. return runGuardQueue(guards);
  3269. })
  3270. // catch any navigation canceled
  3271. .catch(err => isNavigationFailure(err, 8 /* NAVIGATION_CANCELLED */)
  3272. ? err
  3273. : Promise.reject(err)));
  3274. }
  3275. function triggerAfterEach(to, from, failure) {
  3276. // navigation is confirmed, call afterGuards
  3277. // TODO: wrap with error handlers
  3278. for (const guard of afterGuards.list())
  3279. guard(to, from, failure);
  3280. }
  3281. /**
  3282. * - Cleans up any navigation guards
  3283. * - Changes the url if necessary
  3284. * - Calls the scrollBehavior
  3285. */
  3286. function finalizeNavigation(toLocation, from, isPush, replace, data) {
  3287. // a more recent navigation took place
  3288. const error = checkCanceledNavigation(toLocation, from);
  3289. if (error)
  3290. return error;
  3291. // only consider as push if it's not the first navigation
  3292. const isFirstNavigation = from === START_LOCATION_NORMALIZED;
  3293. const state = !isBrowser ? {} : history.state;
  3294. // change URL only if the user did a push/replace and if it's not the initial navigation because
  3295. // it's just reflecting the url
  3296. if (isPush) {
  3297. // on the initial navigation, we want to reuse the scroll position from
  3298. // history state if it exists
  3299. if (replace || isFirstNavigation)
  3300. routerHistory.replace(toLocation.fullPath, assign({
  3301. scroll: isFirstNavigation && state && state.scroll,
  3302. }, data));
  3303. else
  3304. routerHistory.push(toLocation.fullPath, data);
  3305. }
  3306. // accept current navigation
  3307. currentRoute.value = toLocation;
  3308. handleScroll(toLocation, from, isPush, isFirstNavigation);
  3309. markAsReady();
  3310. }
  3311. let removeHistoryListener;
  3312. // attach listener to history to trigger navigations
  3313. function setupListeners() {
  3314. // avoid setting up listeners twice due to an invalid first navigation
  3315. if (removeHistoryListener)
  3316. return;
  3317. removeHistoryListener = routerHistory.listen((to, _from, info) => {
  3318. // cannot be a redirect route because it was in history
  3319. const toLocation = resolve(to);
  3320. // due to dynamic routing, and to hash history with manual navigation
  3321. // (manually changing the url or calling history.hash = '#/somewhere'),
  3322. // there could be a redirect record in history
  3323. const shouldRedirect = handleRedirectRecord(toLocation);
  3324. if (shouldRedirect) {
  3325. pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop);
  3326. return;
  3327. }
  3328. pendingLocation = toLocation;
  3329. const from = currentRoute.value;
  3330. // TODO: should be moved to web history?
  3331. if (isBrowser) {
  3332. saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition());
  3333. }
  3334. navigate(toLocation, from)
  3335. .catch((error) => {
  3336. if (isNavigationFailure(error, 4 /* NAVIGATION_ABORTED */ | 8 /* NAVIGATION_CANCELLED */)) {
  3337. return error;
  3338. }
  3339. if (isNavigationFailure(error, 2 /* NAVIGATION_GUARD_REDIRECT */)) {
  3340. // Here we could call if (info.delta) routerHistory.go(-info.delta,
  3341. // false) but this is bug prone as we have no way to wait the
  3342. // navigation to be finished before calling pushWithRedirect. Using
  3343. // a setTimeout of 16ms seems to work but there is not guarantee for
  3344. // it to work on every browser. So Instead we do not restore the
  3345. // history entry and trigger a new navigation as requested by the
  3346. // navigation guard.
  3347. // the error is already handled by router.push we just want to avoid
  3348. // logging the error
  3349. pushWithRedirect(error.to, toLocation
  3350. // avoid an uncaught rejection, let push call triggerError
  3351. )
  3352. .then(failure => {
  3353. // manual change in hash history #916 ending up in the URL not
  3354. // changing but it was changed by the manual url change, so we
  3355. // need to manually change it ourselves
  3356. if (isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ |
  3357. 16 /* NAVIGATION_DUPLICATED */) &&
  3358. !info.delta &&
  3359. info.type === NavigationType.pop) {
  3360. routerHistory.go(-1, false);
  3361. }
  3362. })
  3363. .catch(noop);
  3364. // avoid the then branch
  3365. return Promise.reject();
  3366. }
  3367. // do not restore history on unknown direction
  3368. if (info.delta)
  3369. routerHistory.go(-info.delta, false);
  3370. // unrecognized error, transfer to the global handler
  3371. return triggerError(error, toLocation, from);
  3372. })
  3373. .then((failure) => {
  3374. failure =
  3375. failure ||
  3376. finalizeNavigation(
  3377. // after navigation, all matched components are resolved
  3378. toLocation, from, false);
  3379. // revert the navigation
  3380. if (failure) {
  3381. if (info.delta) {
  3382. routerHistory.go(-info.delta, false);
  3383. }
  3384. else if (info.type === NavigationType.pop &&
  3385. isNavigationFailure(failure, 4 /* NAVIGATION_ABORTED */ | 16 /* NAVIGATION_DUPLICATED */)) {
  3386. // manual change in hash history #916
  3387. // it's like a push but lacks the information of the direction
  3388. routerHistory.go(-1, false);
  3389. }
  3390. }
  3391. triggerAfterEach(toLocation, from, failure);
  3392. })
  3393. .catch(noop);
  3394. });
  3395. }
  3396. // Initialization and Errors
  3397. let readyHandlers = useCallbacks();
  3398. let errorHandlers = useCallbacks();
  3399. let ready;
  3400. /**
  3401. * Trigger errorHandlers added via onError and throws the error as well
  3402. *
  3403. * @param error - error to throw
  3404. * @param to - location we were navigating to when the error happened
  3405. * @param from - location we were navigating from when the error happened
  3406. * @returns the error as a rejected promise
  3407. */
  3408. function triggerError(error, to, from) {
  3409. markAsReady(error);
  3410. const list = errorHandlers.list();
  3411. if (list.length) {
  3412. list.forEach(handler => handler(error, to, from));
  3413. }
  3414. else {
  3415. {
  3416. warn('uncaught error during route navigation:');
  3417. }
  3418. console.error(error);
  3419. }
  3420. return Promise.reject(error);
  3421. }
  3422. function isReady() {
  3423. if (ready && currentRoute.value !== START_LOCATION_NORMALIZED)
  3424. return Promise.resolve();
  3425. return new Promise((resolve, reject) => {
  3426. readyHandlers.add([resolve, reject]);
  3427. });
  3428. }
  3429. function markAsReady(err) {
  3430. if (!ready) {
  3431. // still not ready if an error happened
  3432. ready = !err;
  3433. setupListeners();
  3434. readyHandlers
  3435. .list()
  3436. .forEach(([resolve, reject]) => (err ? reject(err) : resolve()));
  3437. readyHandlers.reset();
  3438. }
  3439. return err;
  3440. }
  3441. // Scroll behavior
  3442. function handleScroll(to, from, isPush, isFirstNavigation) {
  3443. const { scrollBehavior } = options;
  3444. if (!isBrowser || !scrollBehavior)
  3445. return Promise.resolve();
  3446. const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
  3447. ((isFirstNavigation || !isPush) &&
  3448. history.state &&
  3449. history.state.scroll) ||
  3450. null;
  3451. return vue.nextTick()
  3452. .then(() => scrollBehavior(to, from, scrollPosition))
  3453. .then(position => position && scrollToPosition(position))
  3454. .catch(err => triggerError(err, to, from));
  3455. }
  3456. const go = (delta) => routerHistory.go(delta);
  3457. let started;
  3458. const installedApps = new Set();
  3459. const router = {
  3460. currentRoute,
  3461. addRoute,
  3462. removeRoute,
  3463. hasRoute,
  3464. getRoutes,
  3465. resolve,
  3466. options,
  3467. push,
  3468. replace,
  3469. go,
  3470. back: () => go(-1),
  3471. forward: () => go(1),
  3472. beforeEach: beforeGuards.add,
  3473. beforeResolve: beforeResolveGuards.add,
  3474. afterEach: afterGuards.add,
  3475. onError: errorHandlers.add,
  3476. isReady,
  3477. install(app) {
  3478. const router = this;
  3479. app.component('RouterLink', RouterLink);
  3480. app.component('RouterView', RouterView);
  3481. app.config.globalProperties.$router = router;
  3482. Object.defineProperty(app.config.globalProperties, '$route', {
  3483. enumerable: true,
  3484. get: () => vue.unref(currentRoute),
  3485. });
  3486. // this initial navigation is only necessary on client, on server it doesn't
  3487. // make sense because it will create an extra unnecessary navigation and could
  3488. // lead to problems
  3489. if (isBrowser &&
  3490. // used for the initial navigation client side to avoid pushing
  3491. // multiple times when the router is used in multiple apps
  3492. !started &&
  3493. currentRoute.value === START_LOCATION_NORMALIZED) {
  3494. // see above
  3495. started = true;
  3496. push(routerHistory.location).catch(err => {
  3497. warn('Unexpected error when starting the router:', err);
  3498. });
  3499. }
  3500. const reactiveRoute = {};
  3501. for (const key in START_LOCATION_NORMALIZED) {
  3502. // @ts-expect-error: the key matches
  3503. reactiveRoute[key] = vue.computed(() => currentRoute.value[key]);
  3504. }
  3505. app.provide(routerKey, router);
  3506. app.provide(routeLocationKey, vue.reactive(reactiveRoute));
  3507. app.provide(routerViewLocationKey, currentRoute);
  3508. const unmountApp = app.unmount;
  3509. installedApps.add(app);
  3510. app.unmount = function () {
  3511. installedApps.delete(app);
  3512. // the router is not attached to an app anymore
  3513. if (installedApps.size < 1) {
  3514. // invalidate the current navigation
  3515. pendingLocation = START_LOCATION_NORMALIZED;
  3516. removeHistoryListener && removeHistoryListener();
  3517. removeHistoryListener = null;
  3518. currentRoute.value = START_LOCATION_NORMALIZED;
  3519. started = false;
  3520. ready = false;
  3521. }
  3522. unmountApp();
  3523. };
  3524. if (isBrowser) {
  3525. addDevtools(app, router, matcher);
  3526. }
  3527. },
  3528. };
  3529. return router;
  3530. }
  3531. function runGuardQueue(guards) {
  3532. return guards.reduce((promise, guard) => promise.then(() => guard()), Promise.resolve());
  3533. }
  3534. function extractChangingRecords(to, from) {
  3535. const leavingRecords = [];
  3536. const updatingRecords = [];
  3537. const enteringRecords = [];
  3538. const len = Math.max(from.matched.length, to.matched.length);
  3539. for (let i = 0; i < len; i++) {
  3540. const recordFrom = from.matched[i];
  3541. if (recordFrom) {
  3542. if (to.matched.find(record => isSameRouteRecord(record, recordFrom)))
  3543. updatingRecords.push(recordFrom);
  3544. else
  3545. leavingRecords.push(recordFrom);
  3546. }
  3547. const recordTo = to.matched[i];
  3548. if (recordTo) {
  3549. // the type doesn't matter because we are comparing per reference
  3550. if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) {
  3551. enteringRecords.push(recordTo);
  3552. }
  3553. }
  3554. }
  3555. return [leavingRecords, updatingRecords, enteringRecords];
  3556. }
  3557. /**
  3558. * Returns the router instance. Equivalent to using `$router` inside
  3559. * templates.
  3560. */
  3561. function useRouter() {
  3562. return vue.inject(routerKey);
  3563. }
  3564. /**
  3565. * Returns the current route location. Equivalent to using `$route` inside
  3566. * templates.
  3567. */
  3568. function useRoute() {
  3569. return vue.inject(routeLocationKey);
  3570. }
  3571. exports.RouterLink = RouterLink;
  3572. exports.RouterView = RouterView;
  3573. exports.START_LOCATION = START_LOCATION_NORMALIZED;
  3574. exports.createMemoryHistory = createMemoryHistory;
  3575. exports.createRouter = createRouter;
  3576. exports.createRouterMatcher = createRouterMatcher;
  3577. exports.createWebHashHistory = createWebHashHistory;
  3578. exports.createWebHistory = createWebHistory;
  3579. exports.isNavigationFailure = isNavigationFailure;
  3580. exports.matchedRouteKey = matchedRouteKey;
  3581. exports.onBeforeRouteLeave = onBeforeRouteLeave;
  3582. exports.onBeforeRouteUpdate = onBeforeRouteUpdate;
  3583. exports.parseQuery = parseQuery;
  3584. exports.routeLocationKey = routeLocationKey;
  3585. exports.routerKey = routerKey;
  3586. exports.routerViewLocationKey = routerViewLocationKey;
  3587. exports.stringifyQuery = stringifyQuery;
  3588. exports.useLink = useLink;
  3589. exports.useRoute = useRoute;
  3590. exports.useRouter = useRouter;
  3591. exports.viewDepthKey = viewDepthKey;
  3592. Object.defineProperty(exports, '__esModule', { value: true });
  3593. return exports;
  3594. })({}, Vue);