vue-router.mjs 144 KB

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