vue-router.esm-browser.js 143 KB

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