vue-router.cjs 148 KB

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