vue-router.mjs 146 KB

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