vue-router.cjs 148 KB

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