vue-router.gloabl.js 156 KB

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