vue-router.cjs 142 KB

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