vue-router.common.js 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159
  1. /*!
  2. * vue-router v3.6.5
  3. * (c) 2022 Evan You
  4. * @license MIT
  5. */
  6. 'use strict';
  7. /* */
  8. function assert (condition, message) {
  9. if (!condition) {
  10. throw new Error(("[vue-router] " + message))
  11. }
  12. }
  13. function warn (condition, message) {
  14. if (!condition) {
  15. typeof console !== 'undefined' && console.warn(("[vue-router] " + message));
  16. }
  17. }
  18. function extend (a, b) {
  19. for (var key in b) {
  20. a[key] = b[key];
  21. }
  22. return a
  23. }
  24. /* */
  25. var encodeReserveRE = /[!'()*]/g;
  26. var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); };
  27. var commaRE = /%2C/g;
  28. // fixed encodeURIComponent which is more conformant to RFC3986:
  29. // - escapes [!'()*]
  30. // - preserve commas
  31. var encode = function (str) { return encodeURIComponent(str)
  32. .replace(encodeReserveRE, encodeReserveReplacer)
  33. .replace(commaRE, ','); };
  34. function decode (str) {
  35. try {
  36. return decodeURIComponent(str)
  37. } catch (err) {
  38. if (process.env.NODE_ENV !== 'production') {
  39. warn(false, ("Error decoding \"" + str + "\". Leaving it intact."));
  40. }
  41. }
  42. return str
  43. }
  44. function resolveQuery (
  45. query,
  46. extraQuery,
  47. _parseQuery
  48. ) {
  49. if ( extraQuery === void 0 ) extraQuery = {};
  50. var parse = _parseQuery || parseQuery;
  51. var parsedQuery;
  52. try {
  53. parsedQuery = parse(query || '');
  54. } catch (e) {
  55. process.env.NODE_ENV !== 'production' && warn(false, e.message);
  56. parsedQuery = {};
  57. }
  58. for (var key in extraQuery) {
  59. var value = extraQuery[key];
  60. parsedQuery[key] = Array.isArray(value)
  61. ? value.map(castQueryParamValue)
  62. : castQueryParamValue(value);
  63. }
  64. return parsedQuery
  65. }
  66. var castQueryParamValue = function (value) { return (value == null || typeof value === 'object' ? value : String(value)); };
  67. function parseQuery (query) {
  68. var res = {};
  69. query = query.trim().replace(/^(\?|#|&)/, '');
  70. if (!query) {
  71. return res
  72. }
  73. query.split('&').forEach(function (param) {
  74. var parts = param.replace(/\+/g, ' ').split('=');
  75. var key = decode(parts.shift());
  76. var val = parts.length > 0 ? decode(parts.join('=')) : null;
  77. if (res[key] === undefined) {
  78. res[key] = val;
  79. } else if (Array.isArray(res[key])) {
  80. res[key].push(val);
  81. } else {
  82. res[key] = [res[key], val];
  83. }
  84. });
  85. return res
  86. }
  87. function stringifyQuery (obj) {
  88. var res = obj
  89. ? Object.keys(obj)
  90. .map(function (key) {
  91. var val = obj[key];
  92. if (val === undefined) {
  93. return ''
  94. }
  95. if (val === null) {
  96. return encode(key)
  97. }
  98. if (Array.isArray(val)) {
  99. var result = [];
  100. val.forEach(function (val2) {
  101. if (val2 === undefined) {
  102. return
  103. }
  104. if (val2 === null) {
  105. result.push(encode(key));
  106. } else {
  107. result.push(encode(key) + '=' + encode(val2));
  108. }
  109. });
  110. return result.join('&')
  111. }
  112. return encode(key) + '=' + encode(val)
  113. })
  114. .filter(function (x) { return x.length > 0; })
  115. .join('&')
  116. : null;
  117. return res ? ("?" + res) : ''
  118. }
  119. /* */
  120. var trailingSlashRE = /\/?$/;
  121. function createRoute (
  122. record,
  123. location,
  124. redirectedFrom,
  125. router
  126. ) {
  127. var stringifyQuery = router && router.options.stringifyQuery;
  128. var query = location.query || {};
  129. try {
  130. query = clone(query);
  131. } catch (e) {}
  132. var route = {
  133. name: location.name || (record && record.name),
  134. meta: (record && record.meta) || {},
  135. path: location.path || '/',
  136. hash: location.hash || '',
  137. query: query,
  138. params: location.params || {},
  139. fullPath: getFullPath(location, stringifyQuery),
  140. matched: record ? formatMatch(record) : []
  141. };
  142. if (redirectedFrom) {
  143. route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery);
  144. }
  145. return Object.freeze(route)
  146. }
  147. function clone (value) {
  148. if (Array.isArray(value)) {
  149. return value.map(clone)
  150. } else if (value && typeof value === 'object') {
  151. var res = {};
  152. for (var key in value) {
  153. res[key] = clone(value[key]);
  154. }
  155. return res
  156. } else {
  157. return value
  158. }
  159. }
  160. // the starting route that represents the initial state
  161. var START = createRoute(null, {
  162. path: '/'
  163. });
  164. function formatMatch (record) {
  165. var res = [];
  166. while (record) {
  167. res.unshift(record);
  168. record = record.parent;
  169. }
  170. return res
  171. }
  172. function getFullPath (
  173. ref,
  174. _stringifyQuery
  175. ) {
  176. var path = ref.path;
  177. var query = ref.query; if ( query === void 0 ) query = {};
  178. var hash = ref.hash; if ( hash === void 0 ) hash = '';
  179. var stringify = _stringifyQuery || stringifyQuery;
  180. return (path || '/') + stringify(query) + hash
  181. }
  182. function isSameRoute (a, b, onlyPath) {
  183. if (b === START) {
  184. return a === b
  185. } else if (!b) {
  186. return false
  187. } else if (a.path && b.path) {
  188. return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
  189. a.hash === b.hash &&
  190. isObjectEqual(a.query, b.query))
  191. } else if (a.name && b.name) {
  192. return (
  193. a.name === b.name &&
  194. (onlyPath || (
  195. a.hash === b.hash &&
  196. isObjectEqual(a.query, b.query) &&
  197. isObjectEqual(a.params, b.params))
  198. )
  199. )
  200. } else {
  201. return false
  202. }
  203. }
  204. function isObjectEqual (a, b) {
  205. if ( a === void 0 ) a = {};
  206. if ( b === void 0 ) b = {};
  207. // handle null value #1566
  208. if (!a || !b) { return a === b }
  209. var aKeys = Object.keys(a).sort();
  210. var bKeys = Object.keys(b).sort();
  211. if (aKeys.length !== bKeys.length) {
  212. return false
  213. }
  214. return aKeys.every(function (key, i) {
  215. var aVal = a[key];
  216. var bKey = bKeys[i];
  217. if (bKey !== key) { return false }
  218. var bVal = b[key];
  219. // query values can be null and undefined
  220. if (aVal == null || bVal == null) { return aVal === bVal }
  221. // check nested equality
  222. if (typeof aVal === 'object' && typeof bVal === 'object') {
  223. return isObjectEqual(aVal, bVal)
  224. }
  225. return String(aVal) === String(bVal)
  226. })
  227. }
  228. function isIncludedRoute (current, target) {
  229. return (
  230. current.path.replace(trailingSlashRE, '/').indexOf(
  231. target.path.replace(trailingSlashRE, '/')
  232. ) === 0 &&
  233. (!target.hash || current.hash === target.hash) &&
  234. queryIncludes(current.query, target.query)
  235. )
  236. }
  237. function queryIncludes (current, target) {
  238. for (var key in target) {
  239. if (!(key in current)) {
  240. return false
  241. }
  242. }
  243. return true
  244. }
  245. function handleRouteEntered (route) {
  246. for (var i = 0; i < route.matched.length; i++) {
  247. var record = route.matched[i];
  248. for (var name in record.instances) {
  249. var instance = record.instances[name];
  250. var cbs = record.enteredCbs[name];
  251. if (!instance || !cbs) { continue }
  252. delete record.enteredCbs[name];
  253. for (var i$1 = 0; i$1 < cbs.length; i$1++) {
  254. if (!instance._isBeingDestroyed) { cbs[i$1](instance); }
  255. }
  256. }
  257. }
  258. }
  259. var View = {
  260. name: 'RouterView',
  261. functional: true,
  262. props: {
  263. name: {
  264. type: String,
  265. default: 'default'
  266. }
  267. },
  268. render: function render (_, ref) {
  269. var props = ref.props;
  270. var children = ref.children;
  271. var parent = ref.parent;
  272. var data = ref.data;
  273. // used by devtools to display a router-view badge
  274. data.routerView = true;
  275. // directly use parent context's createElement() function
  276. // so that components rendered by router-view can resolve named slots
  277. var h = parent.$createElement;
  278. var name = props.name;
  279. var route = parent.$route;
  280. var cache = parent._routerViewCache || (parent._routerViewCache = {});
  281. // determine current view depth, also check to see if the tree
  282. // has been toggled inactive but kept-alive.
  283. var depth = 0;
  284. var inactive = false;
  285. while (parent && parent._routerRoot !== parent) {
  286. var vnodeData = parent.$vnode ? parent.$vnode.data : {};
  287. if (vnodeData.routerView) {
  288. depth++;
  289. }
  290. if (vnodeData.keepAlive && parent._directInactive && parent._inactive) {
  291. inactive = true;
  292. }
  293. parent = parent.$parent;
  294. }
  295. data.routerViewDepth = depth;
  296. // render previous view if the tree is inactive and kept-alive
  297. if (inactive) {
  298. var cachedData = cache[name];
  299. var cachedComponent = cachedData && cachedData.component;
  300. if (cachedComponent) {
  301. // #2301
  302. // pass props
  303. if (cachedData.configProps) {
  304. fillPropsinData(cachedComponent, data, cachedData.route, cachedData.configProps);
  305. }
  306. return h(cachedComponent, data, children)
  307. } else {
  308. // render previous empty view
  309. return h()
  310. }
  311. }
  312. var matched = route.matched[depth];
  313. var component = matched && matched.components[name];
  314. // render empty node if no matched route or no config component
  315. if (!matched || !component) {
  316. cache[name] = null;
  317. return h()
  318. }
  319. // cache component
  320. cache[name] = { component: component };
  321. // attach instance registration hook
  322. // this will be called in the instance's injected lifecycle hooks
  323. data.registerRouteInstance = function (vm, val) {
  324. // val could be undefined for unregistration
  325. var current = matched.instances[name];
  326. if (
  327. (val && current !== vm) ||
  328. (!val && current === vm)
  329. ) {
  330. matched.instances[name] = val;
  331. }
  332. }
  333. // also register instance in prepatch hook
  334. // in case the same component instance is reused across different routes
  335. ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) {
  336. matched.instances[name] = vnode.componentInstance;
  337. };
  338. // register instance in init hook
  339. // in case kept-alive component be actived when routes changed
  340. data.hook.init = function (vnode) {
  341. if (vnode.data.keepAlive &&
  342. vnode.componentInstance &&
  343. vnode.componentInstance !== matched.instances[name]
  344. ) {
  345. matched.instances[name] = vnode.componentInstance;
  346. }
  347. // if the route transition has already been confirmed then we weren't
  348. // able to call the cbs during confirmation as the component was not
  349. // registered yet, so we call it here.
  350. handleRouteEntered(route);
  351. };
  352. var configProps = matched.props && matched.props[name];
  353. // save route and configProps in cache
  354. if (configProps) {
  355. extend(cache[name], {
  356. route: route,
  357. configProps: configProps
  358. });
  359. fillPropsinData(component, data, route, configProps);
  360. }
  361. return h(component, data, children)
  362. }
  363. };
  364. function fillPropsinData (component, data, route, configProps) {
  365. // resolve props
  366. var propsToPass = data.props = resolveProps(route, configProps);
  367. if (propsToPass) {
  368. // clone to prevent mutation
  369. propsToPass = data.props = extend({}, propsToPass);
  370. // pass non-declared props as attrs
  371. var attrs = data.attrs = data.attrs || {};
  372. for (var key in propsToPass) {
  373. if (!component.props || !(key in component.props)) {
  374. attrs[key] = propsToPass[key];
  375. delete propsToPass[key];
  376. }
  377. }
  378. }
  379. }
  380. function resolveProps (route, config) {
  381. switch (typeof config) {
  382. case 'undefined':
  383. return
  384. case 'object':
  385. return config
  386. case 'function':
  387. return config(route)
  388. case 'boolean':
  389. return config ? route.params : undefined
  390. default:
  391. if (process.env.NODE_ENV !== 'production') {
  392. warn(
  393. false,
  394. "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " +
  395. "expecting an object, function or boolean."
  396. );
  397. }
  398. }
  399. }
  400. /* */
  401. function resolvePath (
  402. relative,
  403. base,
  404. append
  405. ) {
  406. var firstChar = relative.charAt(0);
  407. if (firstChar === '/') {
  408. return relative
  409. }
  410. if (firstChar === '?' || firstChar === '#') {
  411. return base + relative
  412. }
  413. var stack = base.split('/');
  414. // remove trailing segment if:
  415. // - not appending
  416. // - appending to trailing slash (last segment is empty)
  417. if (!append || !stack[stack.length - 1]) {
  418. stack.pop();
  419. }
  420. // resolve relative path
  421. var segments = relative.replace(/^\//, '').split('/');
  422. for (var i = 0; i < segments.length; i++) {
  423. var segment = segments[i];
  424. if (segment === '..') {
  425. stack.pop();
  426. } else if (segment !== '.') {
  427. stack.push(segment);
  428. }
  429. }
  430. // ensure leading slash
  431. if (stack[0] !== '') {
  432. stack.unshift('');
  433. }
  434. return stack.join('/')
  435. }
  436. function parsePath (path) {
  437. var hash = '';
  438. var query = '';
  439. var hashIndex = path.indexOf('#');
  440. if (hashIndex >= 0) {
  441. hash = path.slice(hashIndex);
  442. path = path.slice(0, hashIndex);
  443. }
  444. var queryIndex = path.indexOf('?');
  445. if (queryIndex >= 0) {
  446. query = path.slice(queryIndex + 1);
  447. path = path.slice(0, queryIndex);
  448. }
  449. return {
  450. path: path,
  451. query: query,
  452. hash: hash
  453. }
  454. }
  455. function cleanPath (path) {
  456. return path.replace(/\/(?:\s*\/)+/g, '/')
  457. }
  458. var isarray = Array.isArray || function (arr) {
  459. return Object.prototype.toString.call(arr) == '[object Array]';
  460. };
  461. /**
  462. * Expose `pathToRegexp`.
  463. */
  464. var pathToRegexp_1 = pathToRegexp;
  465. var parse_1 = parse;
  466. var compile_1 = compile;
  467. var tokensToFunction_1 = tokensToFunction;
  468. var tokensToRegExp_1 = tokensToRegExp;
  469. /**
  470. * The main path matching regexp utility.
  471. *
  472. * @type {RegExp}
  473. */
  474. var PATH_REGEXP = new RegExp([
  475. // Match escaped characters that would otherwise appear in future matches.
  476. // This allows the user to escape special characters that won't transform.
  477. '(\\\\.)',
  478. // Match Express-style parameters and un-named parameters with a prefix
  479. // and optional suffixes. Matches appear as:
  480. //
  481. // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
  482. // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
  483. // "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
  484. '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
  485. ].join('|'), 'g');
  486. /**
  487. * Parse a string for the raw tokens.
  488. *
  489. * @param {string} str
  490. * @param {Object=} options
  491. * @return {!Array}
  492. */
  493. function parse (str, options) {
  494. var tokens = [];
  495. var key = 0;
  496. var index = 0;
  497. var path = '';
  498. var defaultDelimiter = options && options.delimiter || '/';
  499. var res;
  500. while ((res = PATH_REGEXP.exec(str)) != null) {
  501. var m = res[0];
  502. var escaped = res[1];
  503. var offset = res.index;
  504. path += str.slice(index, offset);
  505. index = offset + m.length;
  506. // Ignore already escaped sequences.
  507. if (escaped) {
  508. path += escaped[1];
  509. continue
  510. }
  511. var next = str[index];
  512. var prefix = res[2];
  513. var name = res[3];
  514. var capture = res[4];
  515. var group = res[5];
  516. var modifier = res[6];
  517. var asterisk = res[7];
  518. // Push the current path onto the tokens.
  519. if (path) {
  520. tokens.push(path);
  521. path = '';
  522. }
  523. var partial = prefix != null && next != null && next !== prefix;
  524. var repeat = modifier === '+' || modifier === '*';
  525. var optional = modifier === '?' || modifier === '*';
  526. var delimiter = res[2] || defaultDelimiter;
  527. var pattern = capture || group;
  528. tokens.push({
  529. name: name || key++,
  530. prefix: prefix || '',
  531. delimiter: delimiter,
  532. optional: optional,
  533. repeat: repeat,
  534. partial: partial,
  535. asterisk: !!asterisk,
  536. pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
  537. });
  538. }
  539. // Match any characters still remaining.
  540. if (index < str.length) {
  541. path += str.substr(index);
  542. }
  543. // If the path exists, push it onto the end.
  544. if (path) {
  545. tokens.push(path);
  546. }
  547. return tokens
  548. }
  549. /**
  550. * Compile a string to a template function for the path.
  551. *
  552. * @param {string} str
  553. * @param {Object=} options
  554. * @return {!function(Object=, Object=)}
  555. */
  556. function compile (str, options) {
  557. return tokensToFunction(parse(str, options), options)
  558. }
  559. /**
  560. * Prettier encoding of URI path segments.
  561. *
  562. * @param {string}
  563. * @return {string}
  564. */
  565. function encodeURIComponentPretty (str) {
  566. return encodeURI(str).replace(/[\/?#]/g, function (c) {
  567. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  568. })
  569. }
  570. /**
  571. * Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
  572. *
  573. * @param {string}
  574. * @return {string}
  575. */
  576. function encodeAsterisk (str) {
  577. return encodeURI(str).replace(/[?#]/g, function (c) {
  578. return '%' + c.charCodeAt(0).toString(16).toUpperCase()
  579. })
  580. }
  581. /**
  582. * Expose a method for transforming tokens into the path function.
  583. */
  584. function tokensToFunction (tokens, options) {
  585. // Compile all the tokens into regexps.
  586. var matches = new Array(tokens.length);
  587. // Compile all the patterns before compilation.
  588. for (var i = 0; i < tokens.length; i++) {
  589. if (typeof tokens[i] === 'object') {
  590. matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$', flags(options));
  591. }
  592. }
  593. return function (obj, opts) {
  594. var path = '';
  595. var data = obj || {};
  596. var options = opts || {};
  597. var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent;
  598. for (var i = 0; i < tokens.length; i++) {
  599. var token = tokens[i];
  600. if (typeof token === 'string') {
  601. path += token;
  602. continue
  603. }
  604. var value = data[token.name];
  605. var segment;
  606. if (value == null) {
  607. if (token.optional) {
  608. // Prepend partial segment prefixes.
  609. if (token.partial) {
  610. path += token.prefix;
  611. }
  612. continue
  613. } else {
  614. throw new TypeError('Expected "' + token.name + '" to be defined')
  615. }
  616. }
  617. if (isarray(value)) {
  618. if (!token.repeat) {
  619. throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
  620. }
  621. if (value.length === 0) {
  622. if (token.optional) {
  623. continue
  624. } else {
  625. throw new TypeError('Expected "' + token.name + '" to not be empty')
  626. }
  627. }
  628. for (var j = 0; j < value.length; j++) {
  629. segment = encode(value[j]);
  630. if (!matches[i].test(segment)) {
  631. throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
  632. }
  633. path += (j === 0 ? token.prefix : token.delimiter) + segment;
  634. }
  635. continue
  636. }
  637. segment = token.asterisk ? encodeAsterisk(value) : encode(value);
  638. if (!matches[i].test(segment)) {
  639. throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
  640. }
  641. path += token.prefix + segment;
  642. }
  643. return path
  644. }
  645. }
  646. /**
  647. * Escape a regular expression string.
  648. *
  649. * @param {string} str
  650. * @return {string}
  651. */
  652. function escapeString (str) {
  653. return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
  654. }
  655. /**
  656. * Escape the capturing group by escaping special characters and meaning.
  657. *
  658. * @param {string} group
  659. * @return {string}
  660. */
  661. function escapeGroup (group) {
  662. return group.replace(/([=!:$\/()])/g, '\\$1')
  663. }
  664. /**
  665. * Attach the keys as a property of the regexp.
  666. *
  667. * @param {!RegExp} re
  668. * @param {Array} keys
  669. * @return {!RegExp}
  670. */
  671. function attachKeys (re, keys) {
  672. re.keys = keys;
  673. return re
  674. }
  675. /**
  676. * Get the flags for a regexp from the options.
  677. *
  678. * @param {Object} options
  679. * @return {string}
  680. */
  681. function flags (options) {
  682. return options && options.sensitive ? '' : 'i'
  683. }
  684. /**
  685. * Pull out keys from a regexp.
  686. *
  687. * @param {!RegExp} path
  688. * @param {!Array} keys
  689. * @return {!RegExp}
  690. */
  691. function regexpToRegexp (path, keys) {
  692. // Use a negative lookahead to match only capturing groups.
  693. var groups = path.source.match(/\((?!\?)/g);
  694. if (groups) {
  695. for (var i = 0; i < groups.length; i++) {
  696. keys.push({
  697. name: i,
  698. prefix: null,
  699. delimiter: null,
  700. optional: false,
  701. repeat: false,
  702. partial: false,
  703. asterisk: false,
  704. pattern: null
  705. });
  706. }
  707. }
  708. return attachKeys(path, keys)
  709. }
  710. /**
  711. * Transform an array into a regexp.
  712. *
  713. * @param {!Array} path
  714. * @param {Array} keys
  715. * @param {!Object} options
  716. * @return {!RegExp}
  717. */
  718. function arrayToRegexp (path, keys, options) {
  719. var parts = [];
  720. for (var i = 0; i < path.length; i++) {
  721. parts.push(pathToRegexp(path[i], keys, options).source);
  722. }
  723. var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options));
  724. return attachKeys(regexp, keys)
  725. }
  726. /**
  727. * Create a path regexp from string input.
  728. *
  729. * @param {string} path
  730. * @param {!Array} keys
  731. * @param {!Object} options
  732. * @return {!RegExp}
  733. */
  734. function stringToRegexp (path, keys, options) {
  735. return tokensToRegExp(parse(path, options), keys, options)
  736. }
  737. /**
  738. * Expose a function for taking tokens and returning a RegExp.
  739. *
  740. * @param {!Array} tokens
  741. * @param {(Array|Object)=} keys
  742. * @param {Object=} options
  743. * @return {!RegExp}
  744. */
  745. function tokensToRegExp (tokens, keys, options) {
  746. if (!isarray(keys)) {
  747. options = /** @type {!Object} */ (keys || options);
  748. keys = [];
  749. }
  750. options = options || {};
  751. var strict = options.strict;
  752. var end = options.end !== false;
  753. var route = '';
  754. // Iterate over the tokens and create our regexp string.
  755. for (var i = 0; i < tokens.length; i++) {
  756. var token = tokens[i];
  757. if (typeof token === 'string') {
  758. route += escapeString(token);
  759. } else {
  760. var prefix = escapeString(token.prefix);
  761. var capture = '(?:' + token.pattern + ')';
  762. keys.push(token);
  763. if (token.repeat) {
  764. capture += '(?:' + prefix + capture + ')*';
  765. }
  766. if (token.optional) {
  767. if (!token.partial) {
  768. capture = '(?:' + prefix + '(' + capture + '))?';
  769. } else {
  770. capture = prefix + '(' + capture + ')?';
  771. }
  772. } else {
  773. capture = prefix + '(' + capture + ')';
  774. }
  775. route += capture;
  776. }
  777. }
  778. var delimiter = escapeString(options.delimiter || '/');
  779. var endsWithDelimiter = route.slice(-delimiter.length) === delimiter;
  780. // In non-strict mode we allow a slash at the end of match. If the path to
  781. // match already ends with a slash, we remove it for consistency. The slash
  782. // is valid at the end of a path match, not in the middle. This is important
  783. // in non-ending mode, where "/test/" shouldn't match "/test//route".
  784. if (!strict) {
  785. route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?';
  786. }
  787. if (end) {
  788. route += '$';
  789. } else {
  790. // In non-ending mode, we need the capturing groups to match as much as
  791. // possible by using a positive lookahead to the end or next path segment.
  792. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)';
  793. }
  794. return attachKeys(new RegExp('^' + route, flags(options)), keys)
  795. }
  796. /**
  797. * Normalize the given path string, returning a regular expression.
  798. *
  799. * An empty array can be passed in for the keys, which will hold the
  800. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  801. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  802. *
  803. * @param {(string|RegExp|Array)} path
  804. * @param {(Array|Object)=} keys
  805. * @param {Object=} options
  806. * @return {!RegExp}
  807. */
  808. function pathToRegexp (path, keys, options) {
  809. if (!isarray(keys)) {
  810. options = /** @type {!Object} */ (keys || options);
  811. keys = [];
  812. }
  813. options = options || {};
  814. if (path instanceof RegExp) {
  815. return regexpToRegexp(path, /** @type {!Array} */ (keys))
  816. }
  817. if (isarray(path)) {
  818. return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
  819. }
  820. return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
  821. }
  822. pathToRegexp_1.parse = parse_1;
  823. pathToRegexp_1.compile = compile_1;
  824. pathToRegexp_1.tokensToFunction = tokensToFunction_1;
  825. pathToRegexp_1.tokensToRegExp = tokensToRegExp_1;
  826. /* */
  827. // $flow-disable-line
  828. var regexpCompileCache = Object.create(null);
  829. function fillParams (
  830. path,
  831. params,
  832. routeMsg
  833. ) {
  834. params = params || {};
  835. try {
  836. var filler =
  837. regexpCompileCache[path] ||
  838. (regexpCompileCache[path] = pathToRegexp_1.compile(path));
  839. // Fix #2505 resolving asterisk routes { name: 'not-found', params: { pathMatch: '/not-found' }}
  840. // and fix #3106 so that you can work with location descriptor object having params.pathMatch equal to empty string
  841. if (typeof params.pathMatch === 'string') { params[0] = params.pathMatch; }
  842. return filler(params, { pretty: true })
  843. } catch (e) {
  844. if (process.env.NODE_ENV !== 'production') {
  845. // Fix #3072 no warn if `pathMatch` is string
  846. warn(typeof params.pathMatch === 'string', ("missing param for " + routeMsg + ": " + (e.message)));
  847. }
  848. return ''
  849. } finally {
  850. // delete the 0 if it was added
  851. delete params[0];
  852. }
  853. }
  854. /* */
  855. function normalizeLocation (
  856. raw,
  857. current,
  858. append,
  859. router
  860. ) {
  861. var next = typeof raw === 'string' ? { path: raw } : raw;
  862. // named target
  863. if (next._normalized) {
  864. return next
  865. } else if (next.name) {
  866. next = extend({}, raw);
  867. var params = next.params;
  868. if (params && typeof params === 'object') {
  869. next.params = extend({}, params);
  870. }
  871. return next
  872. }
  873. // relative params
  874. if (!next.path && next.params && current) {
  875. next = extend({}, next);
  876. next._normalized = true;
  877. var params$1 = extend(extend({}, current.params), next.params);
  878. if (current.name) {
  879. next.name = current.name;
  880. next.params = params$1;
  881. } else if (current.matched.length) {
  882. var rawPath = current.matched[current.matched.length - 1].path;
  883. next.path = fillParams(rawPath, params$1, ("path " + (current.path)));
  884. } else if (process.env.NODE_ENV !== 'production') {
  885. warn(false, "relative params navigation requires a current route.");
  886. }
  887. return next
  888. }
  889. var parsedPath = parsePath(next.path || '');
  890. var basePath = (current && current.path) || '/';
  891. var path = parsedPath.path
  892. ? resolvePath(parsedPath.path, basePath, append || next.append)
  893. : basePath;
  894. var query = resolveQuery(
  895. parsedPath.query,
  896. next.query,
  897. router && router.options.parseQuery
  898. );
  899. var hash = next.hash || parsedPath.hash;
  900. if (hash && hash.charAt(0) !== '#') {
  901. hash = "#" + hash;
  902. }
  903. return {
  904. _normalized: true,
  905. path: path,
  906. query: query,
  907. hash: hash
  908. }
  909. }
  910. /* */
  911. // work around weird flow bug
  912. var toTypes = [String, Object];
  913. var eventTypes = [String, Array];
  914. var noop = function () {};
  915. var warnedCustomSlot;
  916. var warnedTagProp;
  917. var warnedEventProp;
  918. var Link = {
  919. name: 'RouterLink',
  920. props: {
  921. to: {
  922. type: toTypes,
  923. required: true
  924. },
  925. tag: {
  926. type: String,
  927. default: 'a'
  928. },
  929. custom: Boolean,
  930. exact: Boolean,
  931. exactPath: Boolean,
  932. append: Boolean,
  933. replace: Boolean,
  934. activeClass: String,
  935. exactActiveClass: String,
  936. ariaCurrentValue: {
  937. type: String,
  938. default: 'page'
  939. },
  940. event: {
  941. type: eventTypes,
  942. default: 'click'
  943. }
  944. },
  945. render: function render (h) {
  946. var this$1$1 = this;
  947. var router = this.$router;
  948. var current = this.$route;
  949. var ref = router.resolve(
  950. this.to,
  951. current,
  952. this.append
  953. );
  954. var location = ref.location;
  955. var route = ref.route;
  956. var href = ref.href;
  957. var classes = {};
  958. var globalActiveClass = router.options.linkActiveClass;
  959. var globalExactActiveClass = router.options.linkExactActiveClass;
  960. // Support global empty active class
  961. var activeClassFallback =
  962. globalActiveClass == null ? 'router-link-active' : globalActiveClass;
  963. var exactActiveClassFallback =
  964. globalExactActiveClass == null
  965. ? 'router-link-exact-active'
  966. : globalExactActiveClass;
  967. var activeClass =
  968. this.activeClass == null ? activeClassFallback : this.activeClass;
  969. var exactActiveClass =
  970. this.exactActiveClass == null
  971. ? exactActiveClassFallback
  972. : this.exactActiveClass;
  973. var compareTarget = route.redirectedFrom
  974. ? createRoute(null, normalizeLocation(route.redirectedFrom), null, router)
  975. : route;
  976. classes[exactActiveClass] = isSameRoute(current, compareTarget, this.exactPath);
  977. classes[activeClass] = this.exact || this.exactPath
  978. ? classes[exactActiveClass]
  979. : isIncludedRoute(current, compareTarget);
  980. var ariaCurrentValue = classes[exactActiveClass] ? this.ariaCurrentValue : null;
  981. var handler = function (e) {
  982. if (guardEvent(e)) {
  983. if (this$1$1.replace) {
  984. router.replace(location, noop);
  985. } else {
  986. router.push(location, noop);
  987. }
  988. }
  989. };
  990. var on = { click: guardEvent };
  991. if (Array.isArray(this.event)) {
  992. this.event.forEach(function (e) {
  993. on[e] = handler;
  994. });
  995. } else {
  996. on[this.event] = handler;
  997. }
  998. var data = { class: classes };
  999. var scopedSlot =
  1000. !this.$scopedSlots.$hasNormal &&
  1001. this.$scopedSlots.default &&
  1002. this.$scopedSlots.default({
  1003. href: href,
  1004. route: route,
  1005. navigate: handler,
  1006. isActive: classes[activeClass],
  1007. isExactActive: classes[exactActiveClass]
  1008. });
  1009. if (scopedSlot) {
  1010. if (process.env.NODE_ENV !== 'production' && !this.custom) {
  1011. !warnedCustomSlot && warn(false, 'In Vue Router 4, the v-slot API will by default wrap its content with an <a> element. Use the custom prop to remove this warning:\n<router-link v-slot="{ navigate, href }" custom></router-link>\n');
  1012. warnedCustomSlot = true;
  1013. }
  1014. if (scopedSlot.length === 1) {
  1015. return scopedSlot[0]
  1016. } else if (scopedSlot.length > 1 || !scopedSlot.length) {
  1017. if (process.env.NODE_ENV !== 'production') {
  1018. warn(
  1019. false,
  1020. ("<router-link> with to=\"" + (this.to) + "\" is trying to use a scoped slot but it didn't provide exactly one child. Wrapping the content with a span element.")
  1021. );
  1022. }
  1023. return scopedSlot.length === 0 ? h() : h('span', {}, scopedSlot)
  1024. }
  1025. }
  1026. if (process.env.NODE_ENV !== 'production') {
  1027. if ('tag' in this.$options.propsData && !warnedTagProp) {
  1028. warn(
  1029. false,
  1030. "<router-link>'s tag prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
  1031. );
  1032. warnedTagProp = true;
  1033. }
  1034. if ('event' in this.$options.propsData && !warnedEventProp) {
  1035. warn(
  1036. false,
  1037. "<router-link>'s event prop is deprecated and has been removed in Vue Router 4. Use the v-slot API to remove this warning: https://next.router.vuejs.org/guide/migration/#removal-of-event-and-tag-props-in-router-link."
  1038. );
  1039. warnedEventProp = true;
  1040. }
  1041. }
  1042. if (this.tag === 'a') {
  1043. data.on = on;
  1044. data.attrs = { href: href, 'aria-current': ariaCurrentValue };
  1045. } else {
  1046. // find the first <a> child and apply listener and href
  1047. var a = findAnchor(this.$slots.default);
  1048. if (a) {
  1049. // in case the <a> is a static node
  1050. a.isStatic = false;
  1051. var aData = (a.data = extend({}, a.data));
  1052. aData.on = aData.on || {};
  1053. // transform existing events in both objects into arrays so we can push later
  1054. for (var event in aData.on) {
  1055. var handler$1 = aData.on[event];
  1056. if (event in on) {
  1057. aData.on[event] = Array.isArray(handler$1) ? handler$1 : [handler$1];
  1058. }
  1059. }
  1060. // append new listeners for router-link
  1061. for (var event$1 in on) {
  1062. if (event$1 in aData.on) {
  1063. // on[event] is always a function
  1064. aData.on[event$1].push(on[event$1]);
  1065. } else {
  1066. aData.on[event$1] = handler;
  1067. }
  1068. }
  1069. var aAttrs = (a.data.attrs = extend({}, a.data.attrs));
  1070. aAttrs.href = href;
  1071. aAttrs['aria-current'] = ariaCurrentValue;
  1072. } else {
  1073. // doesn't have <a> child, apply listener to self
  1074. data.on = on;
  1075. }
  1076. }
  1077. return h(this.tag, data, this.$slots.default)
  1078. }
  1079. };
  1080. function guardEvent (e) {
  1081. // don't redirect with control keys
  1082. if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
  1083. // don't redirect when preventDefault called
  1084. if (e.defaultPrevented) { return }
  1085. // don't redirect on right click
  1086. if (e.button !== undefined && e.button !== 0) { return }
  1087. // don't redirect if `target="_blank"`
  1088. if (e.currentTarget && e.currentTarget.getAttribute) {
  1089. var target = e.currentTarget.getAttribute('target');
  1090. if (/\b_blank\b/i.test(target)) { return }
  1091. }
  1092. // this may be a Weex event which doesn't have this method
  1093. if (e.preventDefault) {
  1094. e.preventDefault();
  1095. }
  1096. return true
  1097. }
  1098. function findAnchor (children) {
  1099. if (children) {
  1100. var child;
  1101. for (var i = 0; i < children.length; i++) {
  1102. child = children[i];
  1103. if (child.tag === 'a') {
  1104. return child
  1105. }
  1106. if (child.children && (child = findAnchor(child.children))) {
  1107. return child
  1108. }
  1109. }
  1110. }
  1111. }
  1112. var _Vue;
  1113. function install (Vue) {
  1114. if (install.installed && _Vue === Vue) { return }
  1115. install.installed = true;
  1116. _Vue = Vue;
  1117. var isDef = function (v) { return v !== undefined; };
  1118. var registerInstance = function (vm, callVal) {
  1119. var i = vm.$options._parentVnode;
  1120. if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) {
  1121. i(vm, callVal);
  1122. }
  1123. };
  1124. Vue.mixin({
  1125. beforeCreate: function beforeCreate () {
  1126. if (isDef(this.$options.router)) {
  1127. this._routerRoot = this;
  1128. this._router = this.$options.router;
  1129. this._router.init(this);
  1130. Vue.util.defineReactive(this, '_route', this._router.history.current);
  1131. } else {
  1132. this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
  1133. }
  1134. registerInstance(this, this);
  1135. },
  1136. destroyed: function destroyed () {
  1137. registerInstance(this);
  1138. }
  1139. });
  1140. Object.defineProperty(Vue.prototype, '$router', {
  1141. get: function get () { return this._routerRoot._router }
  1142. });
  1143. Object.defineProperty(Vue.prototype, '$route', {
  1144. get: function get () { return this._routerRoot._route }
  1145. });
  1146. Vue.component('RouterView', View);
  1147. Vue.component('RouterLink', Link);
  1148. var strats = Vue.config.optionMergeStrategies;
  1149. // use the same hook merging strategy for route hooks
  1150. strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created;
  1151. }
  1152. /* */
  1153. var inBrowser = typeof window !== 'undefined';
  1154. /* */
  1155. function createRouteMap (
  1156. routes,
  1157. oldPathList,
  1158. oldPathMap,
  1159. oldNameMap,
  1160. parentRoute
  1161. ) {
  1162. // the path list is used to control path matching priority
  1163. var pathList = oldPathList || [];
  1164. // $flow-disable-line
  1165. var pathMap = oldPathMap || Object.create(null);
  1166. // $flow-disable-line
  1167. var nameMap = oldNameMap || Object.create(null);
  1168. routes.forEach(function (route) {
  1169. addRouteRecord(pathList, pathMap, nameMap, route, parentRoute);
  1170. });
  1171. // ensure wildcard routes are always at the end
  1172. for (var i = 0, l = pathList.length; i < l; i++) {
  1173. if (pathList[i] === '*') {
  1174. pathList.push(pathList.splice(i, 1)[0]);
  1175. l--;
  1176. i--;
  1177. }
  1178. }
  1179. if (process.env.NODE_ENV === 'development') {
  1180. // warn if routes do not include leading slashes
  1181. var found = pathList
  1182. // check for missing leading slash
  1183. .filter(function (path) { return path && path.charAt(0) !== '*' && path.charAt(0) !== '/'; });
  1184. if (found.length > 0) {
  1185. var pathNames = found.map(function (path) { return ("- " + path); }).join('\n');
  1186. warn(false, ("Non-nested routes must include a leading slash character. Fix the following routes: \n" + pathNames));
  1187. }
  1188. }
  1189. return {
  1190. pathList: pathList,
  1191. pathMap: pathMap,
  1192. nameMap: nameMap
  1193. }
  1194. }
  1195. function addRouteRecord (
  1196. pathList,
  1197. pathMap,
  1198. nameMap,
  1199. route,
  1200. parent,
  1201. matchAs
  1202. ) {
  1203. var path = route.path;
  1204. var name = route.name;
  1205. if (process.env.NODE_ENV !== 'production') {
  1206. assert(path != null, "\"path\" is required in a route configuration.");
  1207. assert(
  1208. typeof route.component !== 'string',
  1209. "route config \"component\" for path: " + (String(
  1210. path || name
  1211. )) + " cannot be a " + "string id. Use an actual component instead."
  1212. );
  1213. warn(
  1214. // eslint-disable-next-line no-control-regex
  1215. !/[^\u0000-\u007F]+/.test(path),
  1216. "Route with path \"" + path + "\" contains unencoded characters, make sure " +
  1217. "your path is correctly encoded before passing it to the router. Use " +
  1218. "encodeURI to encode static segments of your path."
  1219. );
  1220. }
  1221. var pathToRegexpOptions =
  1222. route.pathToRegexpOptions || {};
  1223. var normalizedPath = normalizePath(path, parent, pathToRegexpOptions.strict);
  1224. if (typeof route.caseSensitive === 'boolean') {
  1225. pathToRegexpOptions.sensitive = route.caseSensitive;
  1226. }
  1227. var record = {
  1228. path: normalizedPath,
  1229. regex: compileRouteRegex(normalizedPath, pathToRegexpOptions),
  1230. components: route.components || { default: route.component },
  1231. alias: route.alias
  1232. ? typeof route.alias === 'string'
  1233. ? [route.alias]
  1234. : route.alias
  1235. : [],
  1236. instances: {},
  1237. enteredCbs: {},
  1238. name: name,
  1239. parent: parent,
  1240. matchAs: matchAs,
  1241. redirect: route.redirect,
  1242. beforeEnter: route.beforeEnter,
  1243. meta: route.meta || {},
  1244. props:
  1245. route.props == null
  1246. ? {}
  1247. : route.components
  1248. ? route.props
  1249. : { default: route.props }
  1250. };
  1251. if (route.children) {
  1252. // Warn if route is named, does not redirect and has a default child route.
  1253. // If users navigate to this route by name, the default child will
  1254. // not be rendered (GH Issue #629)
  1255. if (process.env.NODE_ENV !== 'production') {
  1256. if (
  1257. route.name &&
  1258. !route.redirect &&
  1259. route.children.some(function (child) { return /^\/?$/.test(child.path); })
  1260. ) {
  1261. warn(
  1262. false,
  1263. "Named Route '" + (route.name) + "' has a default child route. " +
  1264. "When navigating to this named route (:to=\"{name: '" + (route.name) + "'}\"), " +
  1265. "the default child route will not be rendered. Remove the name from " +
  1266. "this route and use the name of the default child route for named " +
  1267. "links instead."
  1268. );
  1269. }
  1270. }
  1271. route.children.forEach(function (child) {
  1272. var childMatchAs = matchAs
  1273. ? cleanPath((matchAs + "/" + (child.path)))
  1274. : undefined;
  1275. addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs);
  1276. });
  1277. }
  1278. if (!pathMap[record.path]) {
  1279. pathList.push(record.path);
  1280. pathMap[record.path] = record;
  1281. }
  1282. if (route.alias !== undefined) {
  1283. var aliases = Array.isArray(route.alias) ? route.alias : [route.alias];
  1284. for (var i = 0; i < aliases.length; ++i) {
  1285. var alias = aliases[i];
  1286. if (process.env.NODE_ENV !== 'production' && alias === path) {
  1287. warn(
  1288. false,
  1289. ("Found an alias with the same value as the path: \"" + path + "\". You have to remove that alias. It will be ignored in development.")
  1290. );
  1291. // skip in dev to make it work
  1292. continue
  1293. }
  1294. var aliasRoute = {
  1295. path: alias,
  1296. children: route.children
  1297. };
  1298. addRouteRecord(
  1299. pathList,
  1300. pathMap,
  1301. nameMap,
  1302. aliasRoute,
  1303. parent,
  1304. record.path || '/' // matchAs
  1305. );
  1306. }
  1307. }
  1308. if (name) {
  1309. if (!nameMap[name]) {
  1310. nameMap[name] = record;
  1311. } else if (process.env.NODE_ENV !== 'production' && !matchAs) {
  1312. warn(
  1313. false,
  1314. "Duplicate named routes definition: " +
  1315. "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }"
  1316. );
  1317. }
  1318. }
  1319. }
  1320. function compileRouteRegex (
  1321. path,
  1322. pathToRegexpOptions
  1323. ) {
  1324. var regex = pathToRegexp_1(path, [], pathToRegexpOptions);
  1325. if (process.env.NODE_ENV !== 'production') {
  1326. var keys = Object.create(null);
  1327. regex.keys.forEach(function (key) {
  1328. warn(
  1329. !keys[key.name],
  1330. ("Duplicate param keys in route with path: \"" + path + "\"")
  1331. );
  1332. keys[key.name] = true;
  1333. });
  1334. }
  1335. return regex
  1336. }
  1337. function normalizePath (
  1338. path,
  1339. parent,
  1340. strict
  1341. ) {
  1342. if (!strict) { path = path.replace(/\/$/, ''); }
  1343. if (path[0] === '/') { return path }
  1344. if (parent == null) { return path }
  1345. return cleanPath(((parent.path) + "/" + path))
  1346. }
  1347. /* */
  1348. function createMatcher (
  1349. routes,
  1350. router
  1351. ) {
  1352. var ref = createRouteMap(routes);
  1353. var pathList = ref.pathList;
  1354. var pathMap = ref.pathMap;
  1355. var nameMap = ref.nameMap;
  1356. function addRoutes (routes) {
  1357. createRouteMap(routes, pathList, pathMap, nameMap);
  1358. }
  1359. function addRoute (parentOrRoute, route) {
  1360. var parent = (typeof parentOrRoute !== 'object') ? nameMap[parentOrRoute] : undefined;
  1361. // $flow-disable-line
  1362. createRouteMap([route || parentOrRoute], pathList, pathMap, nameMap, parent);
  1363. // add aliases of parent
  1364. if (parent && parent.alias.length) {
  1365. createRouteMap(
  1366. // $flow-disable-line route is defined if parent is
  1367. parent.alias.map(function (alias) { return ({ path: alias, children: [route] }); }),
  1368. pathList,
  1369. pathMap,
  1370. nameMap,
  1371. parent
  1372. );
  1373. }
  1374. }
  1375. function getRoutes () {
  1376. return pathList.map(function (path) { return pathMap[path]; })
  1377. }
  1378. function match (
  1379. raw,
  1380. currentRoute,
  1381. redirectedFrom
  1382. ) {
  1383. var location = normalizeLocation(raw, currentRoute, false, router);
  1384. var name = location.name;
  1385. if (name) {
  1386. var record = nameMap[name];
  1387. if (process.env.NODE_ENV !== 'production') {
  1388. warn(record, ("Route with name '" + name + "' does not exist"));
  1389. }
  1390. if (!record) { return _createRoute(null, location) }
  1391. var paramNames = record.regex.keys
  1392. .filter(function (key) { return !key.optional; })
  1393. .map(function (key) { return key.name; });
  1394. if (typeof location.params !== 'object') {
  1395. location.params = {};
  1396. }
  1397. if (currentRoute && typeof currentRoute.params === 'object') {
  1398. for (var key in currentRoute.params) {
  1399. if (!(key in location.params) && paramNames.indexOf(key) > -1) {
  1400. location.params[key] = currentRoute.params[key];
  1401. }
  1402. }
  1403. }
  1404. location.path = fillParams(record.path, location.params, ("named route \"" + name + "\""));
  1405. return _createRoute(record, location, redirectedFrom)
  1406. } else if (location.path) {
  1407. location.params = {};
  1408. for (var i = 0; i < pathList.length; i++) {
  1409. var path = pathList[i];
  1410. var record$1 = pathMap[path];
  1411. if (matchRoute(record$1.regex, location.path, location.params)) {
  1412. return _createRoute(record$1, location, redirectedFrom)
  1413. }
  1414. }
  1415. }
  1416. // no match
  1417. return _createRoute(null, location)
  1418. }
  1419. function redirect (
  1420. record,
  1421. location
  1422. ) {
  1423. var originalRedirect = record.redirect;
  1424. var redirect = typeof originalRedirect === 'function'
  1425. ? originalRedirect(createRoute(record, location, null, router))
  1426. : originalRedirect;
  1427. if (typeof redirect === 'string') {
  1428. redirect = { path: redirect };
  1429. }
  1430. if (!redirect || typeof redirect !== 'object') {
  1431. if (process.env.NODE_ENV !== 'production') {
  1432. warn(
  1433. false, ("invalid redirect option: " + (JSON.stringify(redirect)))
  1434. );
  1435. }
  1436. return _createRoute(null, location)
  1437. }
  1438. var re = redirect;
  1439. var name = re.name;
  1440. var path = re.path;
  1441. var query = location.query;
  1442. var hash = location.hash;
  1443. var params = location.params;
  1444. query = re.hasOwnProperty('query') ? re.query : query;
  1445. hash = re.hasOwnProperty('hash') ? re.hash : hash;
  1446. params = re.hasOwnProperty('params') ? re.params : params;
  1447. if (name) {
  1448. // resolved named direct
  1449. var targetRecord = nameMap[name];
  1450. if (process.env.NODE_ENV !== 'production') {
  1451. assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found."));
  1452. }
  1453. return match({
  1454. _normalized: true,
  1455. name: name,
  1456. query: query,
  1457. hash: hash,
  1458. params: params
  1459. }, undefined, location)
  1460. } else if (path) {
  1461. // 1. resolve relative redirect
  1462. var rawPath = resolveRecordPath(path, record);
  1463. // 2. resolve params
  1464. var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\""));
  1465. // 3. rematch with existing query and hash
  1466. return match({
  1467. _normalized: true,
  1468. path: resolvedPath,
  1469. query: query,
  1470. hash: hash
  1471. }, undefined, location)
  1472. } else {
  1473. if (process.env.NODE_ENV !== 'production') {
  1474. warn(false, ("invalid redirect option: " + (JSON.stringify(redirect))));
  1475. }
  1476. return _createRoute(null, location)
  1477. }
  1478. }
  1479. function alias (
  1480. record,
  1481. location,
  1482. matchAs
  1483. ) {
  1484. var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\""));
  1485. var aliasedMatch = match({
  1486. _normalized: true,
  1487. path: aliasedPath
  1488. });
  1489. if (aliasedMatch) {
  1490. var matched = aliasedMatch.matched;
  1491. var aliasedRecord = matched[matched.length - 1];
  1492. location.params = aliasedMatch.params;
  1493. return _createRoute(aliasedRecord, location)
  1494. }
  1495. return _createRoute(null, location)
  1496. }
  1497. function _createRoute (
  1498. record,
  1499. location,
  1500. redirectedFrom
  1501. ) {
  1502. if (record && record.redirect) {
  1503. return redirect(record, redirectedFrom || location)
  1504. }
  1505. if (record && record.matchAs) {
  1506. return alias(record, location, record.matchAs)
  1507. }
  1508. return createRoute(record, location, redirectedFrom, router)
  1509. }
  1510. return {
  1511. match: match,
  1512. addRoute: addRoute,
  1513. getRoutes: getRoutes,
  1514. addRoutes: addRoutes
  1515. }
  1516. }
  1517. function matchRoute (
  1518. regex,
  1519. path,
  1520. params
  1521. ) {
  1522. var m = path.match(regex);
  1523. if (!m) {
  1524. return false
  1525. } else if (!params) {
  1526. return true
  1527. }
  1528. for (var i = 1, len = m.length; i < len; ++i) {
  1529. var key = regex.keys[i - 1];
  1530. if (key) {
  1531. // Fix #1994: using * with props: true generates a param named 0
  1532. params[key.name || 'pathMatch'] = typeof m[i] === 'string' ? decode(m[i]) : m[i];
  1533. }
  1534. }
  1535. return true
  1536. }
  1537. function resolveRecordPath (path, record) {
  1538. return resolvePath(path, record.parent ? record.parent.path : '/', true)
  1539. }
  1540. /* */
  1541. // use User Timing api (if present) for more accurate key precision
  1542. var Time =
  1543. inBrowser && window.performance && window.performance.now
  1544. ? window.performance
  1545. : Date;
  1546. function genStateKey () {
  1547. return Time.now().toFixed(3)
  1548. }
  1549. var _key = genStateKey();
  1550. function getStateKey () {
  1551. return _key
  1552. }
  1553. function setStateKey (key) {
  1554. return (_key = key)
  1555. }
  1556. /* */
  1557. var positionStore = Object.create(null);
  1558. function setupScroll () {
  1559. // Prevent browser scroll behavior on History popstate
  1560. if ('scrollRestoration' in window.history) {
  1561. window.history.scrollRestoration = 'manual';
  1562. }
  1563. // Fix for #1585 for Firefox
  1564. // Fix for #2195 Add optional third attribute to workaround a bug in safari https://bugs.webkit.org/show_bug.cgi?id=182678
  1565. // Fix for #2774 Support for apps loaded from Windows file shares not mapped to network drives: replaced location.origin with
  1566. // window.location.protocol + '//' + window.location.host
  1567. // location.host contains the port and location.hostname doesn't
  1568. var protocolAndPath = window.location.protocol + '//' + window.location.host;
  1569. var absolutePath = window.location.href.replace(protocolAndPath, '');
  1570. // preserve existing history state as it could be overriden by the user
  1571. var stateCopy = extend({}, window.history.state);
  1572. stateCopy.key = getStateKey();
  1573. window.history.replaceState(stateCopy, '', absolutePath);
  1574. window.addEventListener('popstate', handlePopState);
  1575. return function () {
  1576. window.removeEventListener('popstate', handlePopState);
  1577. }
  1578. }
  1579. function handleScroll (
  1580. router,
  1581. to,
  1582. from,
  1583. isPop
  1584. ) {
  1585. if (!router.app) {
  1586. return
  1587. }
  1588. var behavior = router.options.scrollBehavior;
  1589. if (!behavior) {
  1590. return
  1591. }
  1592. if (process.env.NODE_ENV !== 'production') {
  1593. assert(typeof behavior === 'function', "scrollBehavior must be a function");
  1594. }
  1595. // wait until re-render finishes before scrolling
  1596. router.app.$nextTick(function () {
  1597. var position = getScrollPosition();
  1598. var shouldScroll = behavior.call(
  1599. router,
  1600. to,
  1601. from,
  1602. isPop ? position : null
  1603. );
  1604. if (!shouldScroll) {
  1605. return
  1606. }
  1607. if (typeof shouldScroll.then === 'function') {
  1608. shouldScroll
  1609. .then(function (shouldScroll) {
  1610. scrollToPosition((shouldScroll), position);
  1611. })
  1612. .catch(function (err) {
  1613. if (process.env.NODE_ENV !== 'production') {
  1614. assert(false, err.toString());
  1615. }
  1616. });
  1617. } else {
  1618. scrollToPosition(shouldScroll, position);
  1619. }
  1620. });
  1621. }
  1622. function saveScrollPosition () {
  1623. var key = getStateKey();
  1624. if (key) {
  1625. positionStore[key] = {
  1626. x: window.pageXOffset,
  1627. y: window.pageYOffset
  1628. };
  1629. }
  1630. }
  1631. function handlePopState (e) {
  1632. saveScrollPosition();
  1633. if (e.state && e.state.key) {
  1634. setStateKey(e.state.key);
  1635. }
  1636. }
  1637. function getScrollPosition () {
  1638. var key = getStateKey();
  1639. if (key) {
  1640. return positionStore[key]
  1641. }
  1642. }
  1643. function getElementPosition (el, offset) {
  1644. var docEl = document.documentElement;
  1645. var docRect = docEl.getBoundingClientRect();
  1646. var elRect = el.getBoundingClientRect();
  1647. return {
  1648. x: elRect.left - docRect.left - offset.x,
  1649. y: elRect.top - docRect.top - offset.y
  1650. }
  1651. }
  1652. function isValidPosition (obj) {
  1653. return isNumber(obj.x) || isNumber(obj.y)
  1654. }
  1655. function normalizePosition (obj) {
  1656. return {
  1657. x: isNumber(obj.x) ? obj.x : window.pageXOffset,
  1658. y: isNumber(obj.y) ? obj.y : window.pageYOffset
  1659. }
  1660. }
  1661. function normalizeOffset (obj) {
  1662. return {
  1663. x: isNumber(obj.x) ? obj.x : 0,
  1664. y: isNumber(obj.y) ? obj.y : 0
  1665. }
  1666. }
  1667. function isNumber (v) {
  1668. return typeof v === 'number'
  1669. }
  1670. var hashStartsWithNumberRE = /^#\d/;
  1671. function scrollToPosition (shouldScroll, position) {
  1672. var isObject = typeof shouldScroll === 'object';
  1673. if (isObject && typeof shouldScroll.selector === 'string') {
  1674. // getElementById would still fail if the selector contains a more complicated query like #main[data-attr]
  1675. // but at the same time, it doesn't make much sense to select an element with an id and an extra selector
  1676. var el = hashStartsWithNumberRE.test(shouldScroll.selector) // $flow-disable-line
  1677. ? document.getElementById(shouldScroll.selector.slice(1)) // $flow-disable-line
  1678. : document.querySelector(shouldScroll.selector);
  1679. if (el) {
  1680. var offset =
  1681. shouldScroll.offset && typeof shouldScroll.offset === 'object'
  1682. ? shouldScroll.offset
  1683. : {};
  1684. offset = normalizeOffset(offset);
  1685. position = getElementPosition(el, offset);
  1686. } else if (isValidPosition(shouldScroll)) {
  1687. position = normalizePosition(shouldScroll);
  1688. }
  1689. } else if (isObject && isValidPosition(shouldScroll)) {
  1690. position = normalizePosition(shouldScroll);
  1691. }
  1692. if (position) {
  1693. // $flow-disable-line
  1694. if ('scrollBehavior' in document.documentElement.style) {
  1695. window.scrollTo({
  1696. left: position.x,
  1697. top: position.y,
  1698. // $flow-disable-line
  1699. behavior: shouldScroll.behavior
  1700. });
  1701. } else {
  1702. window.scrollTo(position.x, position.y);
  1703. }
  1704. }
  1705. }
  1706. /* */
  1707. var supportsPushState =
  1708. inBrowser &&
  1709. (function () {
  1710. var ua = window.navigator.userAgent;
  1711. if (
  1712. (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) &&
  1713. ua.indexOf('Mobile Safari') !== -1 &&
  1714. ua.indexOf('Chrome') === -1 &&
  1715. ua.indexOf('Windows Phone') === -1
  1716. ) {
  1717. return false
  1718. }
  1719. return window.history && typeof window.history.pushState === 'function'
  1720. })();
  1721. function pushState (url, replace) {
  1722. saveScrollPosition();
  1723. // try...catch the pushState call to get around Safari
  1724. // DOM Exception 18 where it limits to 100 pushState calls
  1725. var history = window.history;
  1726. try {
  1727. if (replace) {
  1728. // preserve existing history state as it could be overriden by the user
  1729. var stateCopy = extend({}, history.state);
  1730. stateCopy.key = getStateKey();
  1731. history.replaceState(stateCopy, '', url);
  1732. } else {
  1733. history.pushState({ key: setStateKey(genStateKey()) }, '', url);
  1734. }
  1735. } catch (e) {
  1736. window.location[replace ? 'replace' : 'assign'](url);
  1737. }
  1738. }
  1739. function replaceState (url) {
  1740. pushState(url, true);
  1741. }
  1742. // When changing thing, also edit router.d.ts
  1743. var NavigationFailureType = {
  1744. redirected: 2,
  1745. aborted: 4,
  1746. cancelled: 8,
  1747. duplicated: 16
  1748. };
  1749. function createNavigationRedirectedError (from, to) {
  1750. return createRouterError(
  1751. from,
  1752. to,
  1753. NavigationFailureType.redirected,
  1754. ("Redirected when going from \"" + (from.fullPath) + "\" to \"" + (stringifyRoute(
  1755. to
  1756. )) + "\" via a navigation guard.")
  1757. )
  1758. }
  1759. function createNavigationDuplicatedError (from, to) {
  1760. var error = createRouterError(
  1761. from,
  1762. to,
  1763. NavigationFailureType.duplicated,
  1764. ("Avoided redundant navigation to current location: \"" + (from.fullPath) + "\".")
  1765. );
  1766. // backwards compatible with the first introduction of Errors
  1767. error.name = 'NavigationDuplicated';
  1768. return error
  1769. }
  1770. function createNavigationCancelledError (from, to) {
  1771. return createRouterError(
  1772. from,
  1773. to,
  1774. NavigationFailureType.cancelled,
  1775. ("Navigation cancelled from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" with a new navigation.")
  1776. )
  1777. }
  1778. function createNavigationAbortedError (from, to) {
  1779. return createRouterError(
  1780. from,
  1781. to,
  1782. NavigationFailureType.aborted,
  1783. ("Navigation aborted from \"" + (from.fullPath) + "\" to \"" + (to.fullPath) + "\" via a navigation guard.")
  1784. )
  1785. }
  1786. function createRouterError (from, to, type, message) {
  1787. var error = new Error(message);
  1788. error._isRouter = true;
  1789. error.from = from;
  1790. error.to = to;
  1791. error.type = type;
  1792. return error
  1793. }
  1794. var propertiesToLog = ['params', 'query', 'hash'];
  1795. function stringifyRoute (to) {
  1796. if (typeof to === 'string') { return to }
  1797. if ('path' in to) { return to.path }
  1798. var location = {};
  1799. propertiesToLog.forEach(function (key) {
  1800. if (key in to) { location[key] = to[key]; }
  1801. });
  1802. return JSON.stringify(location, null, 2)
  1803. }
  1804. function isError (err) {
  1805. return Object.prototype.toString.call(err).indexOf('Error') > -1
  1806. }
  1807. function isNavigationFailure (err, errorType) {
  1808. return (
  1809. isError(err) &&
  1810. err._isRouter &&
  1811. (errorType == null || err.type === errorType)
  1812. )
  1813. }
  1814. /* */
  1815. function runQueue (queue, fn, cb) {
  1816. var step = function (index) {
  1817. if (index >= queue.length) {
  1818. cb();
  1819. } else {
  1820. if (queue[index]) {
  1821. fn(queue[index], function () {
  1822. step(index + 1);
  1823. });
  1824. } else {
  1825. step(index + 1);
  1826. }
  1827. }
  1828. };
  1829. step(0);
  1830. }
  1831. /* */
  1832. function resolveAsyncComponents (matched) {
  1833. return function (to, from, next) {
  1834. var hasAsync = false;
  1835. var pending = 0;
  1836. var error = null;
  1837. flatMapComponents(matched, function (def, _, match, key) {
  1838. // if it's a function and doesn't have cid attached,
  1839. // assume it's an async component resolve function.
  1840. // we are not using Vue's default async resolving mechanism because
  1841. // we want to halt the navigation until the incoming component has been
  1842. // resolved.
  1843. if (typeof def === 'function' && def.cid === undefined) {
  1844. hasAsync = true;
  1845. pending++;
  1846. var resolve = once(function (resolvedDef) {
  1847. if (isESModule(resolvedDef)) {
  1848. resolvedDef = resolvedDef.default;
  1849. }
  1850. // save resolved on async factory in case it's used elsewhere
  1851. def.resolved = typeof resolvedDef === 'function'
  1852. ? resolvedDef
  1853. : _Vue.extend(resolvedDef);
  1854. match.components[key] = resolvedDef;
  1855. pending--;
  1856. if (pending <= 0) {
  1857. next();
  1858. }
  1859. });
  1860. var reject = once(function (reason) {
  1861. var msg = "Failed to resolve async component " + key + ": " + reason;
  1862. process.env.NODE_ENV !== 'production' && warn(false, msg);
  1863. if (!error) {
  1864. error = isError(reason)
  1865. ? reason
  1866. : new Error(msg);
  1867. next(error);
  1868. }
  1869. });
  1870. var res;
  1871. try {
  1872. res = def(resolve, reject);
  1873. } catch (e) {
  1874. reject(e);
  1875. }
  1876. if (res) {
  1877. if (typeof res.then === 'function') {
  1878. res.then(resolve, reject);
  1879. } else {
  1880. // new syntax in Vue 2.3
  1881. var comp = res.component;
  1882. if (comp && typeof comp.then === 'function') {
  1883. comp.then(resolve, reject);
  1884. }
  1885. }
  1886. }
  1887. }
  1888. });
  1889. if (!hasAsync) { next(); }
  1890. }
  1891. }
  1892. function flatMapComponents (
  1893. matched,
  1894. fn
  1895. ) {
  1896. return flatten(matched.map(function (m) {
  1897. return Object.keys(m.components).map(function (key) { return fn(
  1898. m.components[key],
  1899. m.instances[key],
  1900. m, key
  1901. ); })
  1902. }))
  1903. }
  1904. function flatten (arr) {
  1905. return Array.prototype.concat.apply([], arr)
  1906. }
  1907. var hasSymbol =
  1908. typeof Symbol === 'function' &&
  1909. typeof Symbol.toStringTag === 'symbol';
  1910. function isESModule (obj) {
  1911. return obj.__esModule || (hasSymbol && obj[Symbol.toStringTag] === 'Module')
  1912. }
  1913. // in Webpack 2, require.ensure now also returns a Promise
  1914. // so the resolve/reject functions may get called an extra time
  1915. // if the user uses an arrow function shorthand that happens to
  1916. // return that Promise.
  1917. function once (fn) {
  1918. var called = false;
  1919. return function () {
  1920. var args = [], len = arguments.length;
  1921. while ( len-- ) args[ len ] = arguments[ len ];
  1922. if (called) { return }
  1923. called = true;
  1924. return fn.apply(this, args)
  1925. }
  1926. }
  1927. /* */
  1928. var History = function History (router, base) {
  1929. this.router = router;
  1930. this.base = normalizeBase(base);
  1931. // start with a route object that stands for "nowhere"
  1932. this.current = START;
  1933. this.pending = null;
  1934. this.ready = false;
  1935. this.readyCbs = [];
  1936. this.readyErrorCbs = [];
  1937. this.errorCbs = [];
  1938. this.listeners = [];
  1939. };
  1940. History.prototype.listen = function listen (cb) {
  1941. this.cb = cb;
  1942. };
  1943. History.prototype.onReady = function onReady (cb, errorCb) {
  1944. if (this.ready) {
  1945. cb();
  1946. } else {
  1947. this.readyCbs.push(cb);
  1948. if (errorCb) {
  1949. this.readyErrorCbs.push(errorCb);
  1950. }
  1951. }
  1952. };
  1953. History.prototype.onError = function onError (errorCb) {
  1954. this.errorCbs.push(errorCb);
  1955. };
  1956. History.prototype.transitionTo = function transitionTo (
  1957. location,
  1958. onComplete,
  1959. onAbort
  1960. ) {
  1961. var this$1$1 = this;
  1962. var route;
  1963. // catch redirect option https://github.com/vuejs/vue-router/issues/3201
  1964. try {
  1965. route = this.router.match(location, this.current);
  1966. } catch (e) {
  1967. this.errorCbs.forEach(function (cb) {
  1968. cb(e);
  1969. });
  1970. // Exception should still be thrown
  1971. throw e
  1972. }
  1973. var prev = this.current;
  1974. this.confirmTransition(
  1975. route,
  1976. function () {
  1977. this$1$1.updateRoute(route);
  1978. onComplete && onComplete(route);
  1979. this$1$1.ensureURL();
  1980. this$1$1.router.afterHooks.forEach(function (hook) {
  1981. hook && hook(route, prev);
  1982. });
  1983. // fire ready cbs once
  1984. if (!this$1$1.ready) {
  1985. this$1$1.ready = true;
  1986. this$1$1.readyCbs.forEach(function (cb) {
  1987. cb(route);
  1988. });
  1989. }
  1990. },
  1991. function (err) {
  1992. if (onAbort) {
  1993. onAbort(err);
  1994. }
  1995. if (err && !this$1$1.ready) {
  1996. // Initial redirection should not mark the history as ready yet
  1997. // because it's triggered by the redirection instead
  1998. // https://github.com/vuejs/vue-router/issues/3225
  1999. // https://github.com/vuejs/vue-router/issues/3331
  2000. if (!isNavigationFailure(err, NavigationFailureType.redirected) || prev !== START) {
  2001. this$1$1.ready = true;
  2002. this$1$1.readyErrorCbs.forEach(function (cb) {
  2003. cb(err);
  2004. });
  2005. }
  2006. }
  2007. }
  2008. );
  2009. };
  2010. History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) {
  2011. var this$1$1 = this;
  2012. var current = this.current;
  2013. this.pending = route;
  2014. var abort = function (err) {
  2015. // changed after adding errors with
  2016. // https://github.com/vuejs/vue-router/pull/3047 before that change,
  2017. // redirect and aborted navigation would produce an err == null
  2018. if (!isNavigationFailure(err) && isError(err)) {
  2019. if (this$1$1.errorCbs.length) {
  2020. this$1$1.errorCbs.forEach(function (cb) {
  2021. cb(err);
  2022. });
  2023. } else {
  2024. if (process.env.NODE_ENV !== 'production') {
  2025. warn(false, 'uncaught error during route navigation:');
  2026. }
  2027. console.error(err);
  2028. }
  2029. }
  2030. onAbort && onAbort(err);
  2031. };
  2032. var lastRouteIndex = route.matched.length - 1;
  2033. var lastCurrentIndex = current.matched.length - 1;
  2034. if (
  2035. isSameRoute(route, current) &&
  2036. // in the case the route map has been dynamically appended to
  2037. lastRouteIndex === lastCurrentIndex &&
  2038. route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
  2039. ) {
  2040. this.ensureURL();
  2041. if (route.hash) {
  2042. handleScroll(this.router, current, route, false);
  2043. }
  2044. return abort(createNavigationDuplicatedError(current, route))
  2045. }
  2046. var ref = resolveQueue(
  2047. this.current.matched,
  2048. route.matched
  2049. );
  2050. var updated = ref.updated;
  2051. var deactivated = ref.deactivated;
  2052. var activated = ref.activated;
  2053. var queue = [].concat(
  2054. // in-component leave guards
  2055. extractLeaveGuards(deactivated),
  2056. // global before hooks
  2057. this.router.beforeHooks,
  2058. // in-component update hooks
  2059. extractUpdateHooks(updated),
  2060. // in-config enter guards
  2061. activated.map(function (m) { return m.beforeEnter; }),
  2062. // async components
  2063. resolveAsyncComponents(activated)
  2064. );
  2065. var iterator = function (hook, next) {
  2066. if (this$1$1.pending !== route) {
  2067. return abort(createNavigationCancelledError(current, route))
  2068. }
  2069. try {
  2070. hook(route, current, function (to) {
  2071. if (to === false) {
  2072. // next(false) -> abort navigation, ensure current URL
  2073. this$1$1.ensureURL(true);
  2074. abort(createNavigationAbortedError(current, route));
  2075. } else if (isError(to)) {
  2076. this$1$1.ensureURL(true);
  2077. abort(to);
  2078. } else if (
  2079. typeof to === 'string' ||
  2080. (typeof to === 'object' &&
  2081. (typeof to.path === 'string' || typeof to.name === 'string'))
  2082. ) {
  2083. // next('/') or next({ path: '/' }) -> redirect
  2084. abort(createNavigationRedirectedError(current, route));
  2085. if (typeof to === 'object' && to.replace) {
  2086. this$1$1.replace(to);
  2087. } else {
  2088. this$1$1.push(to);
  2089. }
  2090. } else {
  2091. // confirm transition and pass on the value
  2092. next(to);
  2093. }
  2094. });
  2095. } catch (e) {
  2096. abort(e);
  2097. }
  2098. };
  2099. runQueue(queue, iterator, function () {
  2100. // wait until async components are resolved before
  2101. // extracting in-component enter guards
  2102. var enterGuards = extractEnterGuards(activated);
  2103. var queue = enterGuards.concat(this$1$1.router.resolveHooks);
  2104. runQueue(queue, iterator, function () {
  2105. if (this$1$1.pending !== route) {
  2106. return abort(createNavigationCancelledError(current, route))
  2107. }
  2108. this$1$1.pending = null;
  2109. onComplete(route);
  2110. if (this$1$1.router.app) {
  2111. this$1$1.router.app.$nextTick(function () {
  2112. handleRouteEntered(route);
  2113. });
  2114. }
  2115. });
  2116. });
  2117. };
  2118. History.prototype.updateRoute = function updateRoute (route) {
  2119. this.current = route;
  2120. this.cb && this.cb(route);
  2121. };
  2122. History.prototype.setupListeners = function setupListeners () {
  2123. // Default implementation is empty
  2124. };
  2125. History.prototype.teardown = function teardown () {
  2126. // clean up event listeners
  2127. // https://github.com/vuejs/vue-router/issues/2341
  2128. this.listeners.forEach(function (cleanupListener) {
  2129. cleanupListener();
  2130. });
  2131. this.listeners = [];
  2132. // reset current history route
  2133. // https://github.com/vuejs/vue-router/issues/3294
  2134. this.current = START;
  2135. this.pending = null;
  2136. };
  2137. function normalizeBase (base) {
  2138. if (!base) {
  2139. if (inBrowser) {
  2140. // respect <base> tag
  2141. var baseEl = document.querySelector('base');
  2142. base = (baseEl && baseEl.getAttribute('href')) || '/';
  2143. // strip full URL origin
  2144. base = base.replace(/^https?:\/\/[^\/]+/, '');
  2145. } else {
  2146. base = '/';
  2147. }
  2148. }
  2149. // make sure there's the starting slash
  2150. if (base.charAt(0) !== '/') {
  2151. base = '/' + base;
  2152. }
  2153. // remove trailing slash
  2154. return base.replace(/\/$/, '')
  2155. }
  2156. function resolveQueue (
  2157. current,
  2158. next
  2159. ) {
  2160. var i;
  2161. var max = Math.max(current.length, next.length);
  2162. for (i = 0; i < max; i++) {
  2163. if (current[i] !== next[i]) {
  2164. break
  2165. }
  2166. }
  2167. return {
  2168. updated: next.slice(0, i),
  2169. activated: next.slice(i),
  2170. deactivated: current.slice(i)
  2171. }
  2172. }
  2173. function extractGuards (
  2174. records,
  2175. name,
  2176. bind,
  2177. reverse
  2178. ) {
  2179. var guards = flatMapComponents(records, function (def, instance, match, key) {
  2180. var guard = extractGuard(def, name);
  2181. if (guard) {
  2182. return Array.isArray(guard)
  2183. ? guard.map(function (guard) { return bind(guard, instance, match, key); })
  2184. : bind(guard, instance, match, key)
  2185. }
  2186. });
  2187. return flatten(reverse ? guards.reverse() : guards)
  2188. }
  2189. function extractGuard (
  2190. def,
  2191. key
  2192. ) {
  2193. if (typeof def !== 'function') {
  2194. // extend now so that global mixins are applied.
  2195. def = _Vue.extend(def);
  2196. }
  2197. return def.options[key]
  2198. }
  2199. function extractLeaveGuards (deactivated) {
  2200. return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true)
  2201. }
  2202. function extractUpdateHooks (updated) {
  2203. return extractGuards(updated, 'beforeRouteUpdate', bindGuard)
  2204. }
  2205. function bindGuard (guard, instance) {
  2206. if (instance) {
  2207. return function boundRouteGuard () {
  2208. return guard.apply(instance, arguments)
  2209. }
  2210. }
  2211. }
  2212. function extractEnterGuards (
  2213. activated
  2214. ) {
  2215. return extractGuards(
  2216. activated,
  2217. 'beforeRouteEnter',
  2218. function (guard, _, match, key) {
  2219. return bindEnterGuard(guard, match, key)
  2220. }
  2221. )
  2222. }
  2223. function bindEnterGuard (
  2224. guard,
  2225. match,
  2226. key
  2227. ) {
  2228. return function routeEnterGuard (to, from, next) {
  2229. return guard(to, from, function (cb) {
  2230. if (typeof cb === 'function') {
  2231. if (!match.enteredCbs[key]) {
  2232. match.enteredCbs[key] = [];
  2233. }
  2234. match.enteredCbs[key].push(cb);
  2235. }
  2236. next(cb);
  2237. })
  2238. }
  2239. }
  2240. /* */
  2241. var HTML5History = /*@__PURE__*/(function (History) {
  2242. function HTML5History (router, base) {
  2243. History.call(this, router, base);
  2244. this._startLocation = getLocation(this.base);
  2245. }
  2246. if ( History ) HTML5History.__proto__ = History;
  2247. HTML5History.prototype = Object.create( History && History.prototype );
  2248. HTML5History.prototype.constructor = HTML5History;
  2249. HTML5History.prototype.setupListeners = function setupListeners () {
  2250. var this$1$1 = this;
  2251. if (this.listeners.length > 0) {
  2252. return
  2253. }
  2254. var router = this.router;
  2255. var expectScroll = router.options.scrollBehavior;
  2256. var supportsScroll = supportsPushState && expectScroll;
  2257. if (supportsScroll) {
  2258. this.listeners.push(setupScroll());
  2259. }
  2260. var handleRoutingEvent = function () {
  2261. var current = this$1$1.current;
  2262. // Avoiding first `popstate` event dispatched in some browsers but first
  2263. // history route not updated since async guard at the same time.
  2264. var location = getLocation(this$1$1.base);
  2265. if (this$1$1.current === START && location === this$1$1._startLocation) {
  2266. return
  2267. }
  2268. this$1$1.transitionTo(location, function (route) {
  2269. if (supportsScroll) {
  2270. handleScroll(router, route, current, true);
  2271. }
  2272. });
  2273. };
  2274. window.addEventListener('popstate', handleRoutingEvent);
  2275. this.listeners.push(function () {
  2276. window.removeEventListener('popstate', handleRoutingEvent);
  2277. });
  2278. };
  2279. HTML5History.prototype.go = function go (n) {
  2280. window.history.go(n);
  2281. };
  2282. HTML5History.prototype.push = function push (location, onComplete, onAbort) {
  2283. var this$1$1 = this;
  2284. var ref = this;
  2285. var fromRoute = ref.current;
  2286. this.transitionTo(location, function (route) {
  2287. pushState(cleanPath(this$1$1.base + route.fullPath));
  2288. handleScroll(this$1$1.router, route, fromRoute, false);
  2289. onComplete && onComplete(route);
  2290. }, onAbort);
  2291. };
  2292. HTML5History.prototype.replace = function replace (location, onComplete, onAbort) {
  2293. var this$1$1 = this;
  2294. var ref = this;
  2295. var fromRoute = ref.current;
  2296. this.transitionTo(location, function (route) {
  2297. replaceState(cleanPath(this$1$1.base + route.fullPath));
  2298. handleScroll(this$1$1.router, route, fromRoute, false);
  2299. onComplete && onComplete(route);
  2300. }, onAbort);
  2301. };
  2302. HTML5History.prototype.ensureURL = function ensureURL (push) {
  2303. if (getLocation(this.base) !== this.current.fullPath) {
  2304. var current = cleanPath(this.base + this.current.fullPath);
  2305. push ? pushState(current) : replaceState(current);
  2306. }
  2307. };
  2308. HTML5History.prototype.getCurrentLocation = function getCurrentLocation () {
  2309. return getLocation(this.base)
  2310. };
  2311. return HTML5History;
  2312. }(History));
  2313. function getLocation (base) {
  2314. var path = window.location.pathname;
  2315. var pathLowerCase = path.toLowerCase();
  2316. var baseLowerCase = base.toLowerCase();
  2317. // base="/a" shouldn't turn path="/app" into "/a/pp"
  2318. // https://github.com/vuejs/vue-router/issues/3555
  2319. // so we ensure the trailing slash in the base
  2320. if (base && ((pathLowerCase === baseLowerCase) ||
  2321. (pathLowerCase.indexOf(cleanPath(baseLowerCase + '/')) === 0))) {
  2322. path = path.slice(base.length);
  2323. }
  2324. return (path || '/') + window.location.search + window.location.hash
  2325. }
  2326. /* */
  2327. var HashHistory = /*@__PURE__*/(function (History) {
  2328. function HashHistory (router, base, fallback) {
  2329. History.call(this, router, base);
  2330. // check history fallback deeplinking
  2331. if (fallback && checkFallback(this.base)) {
  2332. return
  2333. }
  2334. ensureSlash();
  2335. }
  2336. if ( History ) HashHistory.__proto__ = History;
  2337. HashHistory.prototype = Object.create( History && History.prototype );
  2338. HashHistory.prototype.constructor = HashHistory;
  2339. // this is delayed until the app mounts
  2340. // to avoid the hashchange listener being fired too early
  2341. HashHistory.prototype.setupListeners = function setupListeners () {
  2342. var this$1$1 = this;
  2343. if (this.listeners.length > 0) {
  2344. return
  2345. }
  2346. var router = this.router;
  2347. var expectScroll = router.options.scrollBehavior;
  2348. var supportsScroll = supportsPushState && expectScroll;
  2349. if (supportsScroll) {
  2350. this.listeners.push(setupScroll());
  2351. }
  2352. var handleRoutingEvent = function () {
  2353. var current = this$1$1.current;
  2354. if (!ensureSlash()) {
  2355. return
  2356. }
  2357. this$1$1.transitionTo(getHash(), function (route) {
  2358. if (supportsScroll) {
  2359. handleScroll(this$1$1.router, route, current, true);
  2360. }
  2361. if (!supportsPushState) {
  2362. replaceHash(route.fullPath);
  2363. }
  2364. });
  2365. };
  2366. var eventType = supportsPushState ? 'popstate' : 'hashchange';
  2367. window.addEventListener(
  2368. eventType,
  2369. handleRoutingEvent
  2370. );
  2371. this.listeners.push(function () {
  2372. window.removeEventListener(eventType, handleRoutingEvent);
  2373. });
  2374. };
  2375. HashHistory.prototype.push = function push (location, onComplete, onAbort) {
  2376. var this$1$1 = this;
  2377. var ref = this;
  2378. var fromRoute = ref.current;
  2379. this.transitionTo(
  2380. location,
  2381. function (route) {
  2382. pushHash(route.fullPath);
  2383. handleScroll(this$1$1.router, route, fromRoute, false);
  2384. onComplete && onComplete(route);
  2385. },
  2386. onAbort
  2387. );
  2388. };
  2389. HashHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2390. var this$1$1 = this;
  2391. var ref = this;
  2392. var fromRoute = ref.current;
  2393. this.transitionTo(
  2394. location,
  2395. function (route) {
  2396. replaceHash(route.fullPath);
  2397. handleScroll(this$1$1.router, route, fromRoute, false);
  2398. onComplete && onComplete(route);
  2399. },
  2400. onAbort
  2401. );
  2402. };
  2403. HashHistory.prototype.go = function go (n) {
  2404. window.history.go(n);
  2405. };
  2406. HashHistory.prototype.ensureURL = function ensureURL (push) {
  2407. var current = this.current.fullPath;
  2408. if (getHash() !== current) {
  2409. push ? pushHash(current) : replaceHash(current);
  2410. }
  2411. };
  2412. HashHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2413. return getHash()
  2414. };
  2415. return HashHistory;
  2416. }(History));
  2417. function checkFallback (base) {
  2418. var location = getLocation(base);
  2419. if (!/^\/#/.test(location)) {
  2420. window.location.replace(cleanPath(base + '/#' + location));
  2421. return true
  2422. }
  2423. }
  2424. function ensureSlash () {
  2425. var path = getHash();
  2426. if (path.charAt(0) === '/') {
  2427. return true
  2428. }
  2429. replaceHash('/' + path);
  2430. return false
  2431. }
  2432. function getHash () {
  2433. // We can't use window.location.hash here because it's not
  2434. // consistent across browsers - Firefox will pre-decode it!
  2435. var href = window.location.href;
  2436. var index = href.indexOf('#');
  2437. // empty path
  2438. if (index < 0) { return '' }
  2439. href = href.slice(index + 1);
  2440. return href
  2441. }
  2442. function getUrl (path) {
  2443. var href = window.location.href;
  2444. var i = href.indexOf('#');
  2445. var base = i >= 0 ? href.slice(0, i) : href;
  2446. return (base + "#" + path)
  2447. }
  2448. function pushHash (path) {
  2449. if (supportsPushState) {
  2450. pushState(getUrl(path));
  2451. } else {
  2452. window.location.hash = path;
  2453. }
  2454. }
  2455. function replaceHash (path) {
  2456. if (supportsPushState) {
  2457. replaceState(getUrl(path));
  2458. } else {
  2459. window.location.replace(getUrl(path));
  2460. }
  2461. }
  2462. /* */
  2463. var AbstractHistory = /*@__PURE__*/(function (History) {
  2464. function AbstractHistory (router, base) {
  2465. History.call(this, router, base);
  2466. this.stack = [];
  2467. this.index = -1;
  2468. }
  2469. if ( History ) AbstractHistory.__proto__ = History;
  2470. AbstractHistory.prototype = Object.create( History && History.prototype );
  2471. AbstractHistory.prototype.constructor = AbstractHistory;
  2472. AbstractHistory.prototype.push = function push (location, onComplete, onAbort) {
  2473. var this$1$1 = this;
  2474. this.transitionTo(
  2475. location,
  2476. function (route) {
  2477. this$1$1.stack = this$1$1.stack.slice(0, this$1$1.index + 1).concat(route);
  2478. this$1$1.index++;
  2479. onComplete && onComplete(route);
  2480. },
  2481. onAbort
  2482. );
  2483. };
  2484. AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) {
  2485. var this$1$1 = this;
  2486. this.transitionTo(
  2487. location,
  2488. function (route) {
  2489. this$1$1.stack = this$1$1.stack.slice(0, this$1$1.index).concat(route);
  2490. onComplete && onComplete(route);
  2491. },
  2492. onAbort
  2493. );
  2494. };
  2495. AbstractHistory.prototype.go = function go (n) {
  2496. var this$1$1 = this;
  2497. var targetIndex = this.index + n;
  2498. if (targetIndex < 0 || targetIndex >= this.stack.length) {
  2499. return
  2500. }
  2501. var route = this.stack[targetIndex];
  2502. this.confirmTransition(
  2503. route,
  2504. function () {
  2505. var prev = this$1$1.current;
  2506. this$1$1.index = targetIndex;
  2507. this$1$1.updateRoute(route);
  2508. this$1$1.router.afterHooks.forEach(function (hook) {
  2509. hook && hook(route, prev);
  2510. });
  2511. },
  2512. function (err) {
  2513. if (isNavigationFailure(err, NavigationFailureType.duplicated)) {
  2514. this$1$1.index = targetIndex;
  2515. }
  2516. }
  2517. );
  2518. };
  2519. AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () {
  2520. var current = this.stack[this.stack.length - 1];
  2521. return current ? current.fullPath : '/'
  2522. };
  2523. AbstractHistory.prototype.ensureURL = function ensureURL () {
  2524. // noop
  2525. };
  2526. return AbstractHistory;
  2527. }(History));
  2528. /* */
  2529. var VueRouter = function VueRouter (options) {
  2530. if ( options === void 0 ) options = {};
  2531. if (process.env.NODE_ENV !== 'production') {
  2532. warn(this instanceof VueRouter, "Router must be called with the new operator.");
  2533. }
  2534. this.app = null;
  2535. this.apps = [];
  2536. this.options = options;
  2537. this.beforeHooks = [];
  2538. this.resolveHooks = [];
  2539. this.afterHooks = [];
  2540. this.matcher = createMatcher(options.routes || [], this);
  2541. var mode = options.mode || 'hash';
  2542. this.fallback =
  2543. mode === 'history' && !supportsPushState && options.fallback !== false;
  2544. if (this.fallback) {
  2545. mode = 'hash';
  2546. }
  2547. if (!inBrowser) {
  2548. mode = 'abstract';
  2549. }
  2550. this.mode = mode;
  2551. switch (mode) {
  2552. case 'history':
  2553. this.history = new HTML5History(this, options.base);
  2554. break
  2555. case 'hash':
  2556. this.history = new HashHistory(this, options.base, this.fallback);
  2557. break
  2558. case 'abstract':
  2559. this.history = new AbstractHistory(this, options.base);
  2560. break
  2561. default:
  2562. if (process.env.NODE_ENV !== 'production') {
  2563. assert(false, ("invalid mode: " + mode));
  2564. }
  2565. }
  2566. };
  2567. var prototypeAccessors = { currentRoute: { configurable: true } };
  2568. VueRouter.prototype.match = function match (raw, current, redirectedFrom) {
  2569. return this.matcher.match(raw, current, redirectedFrom)
  2570. };
  2571. prototypeAccessors.currentRoute.get = function () {
  2572. return this.history && this.history.current
  2573. };
  2574. VueRouter.prototype.init = function init (app /* Vue component instance */) {
  2575. var this$1$1 = this;
  2576. process.env.NODE_ENV !== 'production' &&
  2577. assert(
  2578. install.installed,
  2579. "not installed. Make sure to call `Vue.use(VueRouter)` " +
  2580. "before creating root instance."
  2581. );
  2582. this.apps.push(app);
  2583. // set up app destroyed handler
  2584. // https://github.com/vuejs/vue-router/issues/2639
  2585. app.$once('hook:destroyed', function () {
  2586. // clean out app from this.apps array once destroyed
  2587. var index = this$1$1.apps.indexOf(app);
  2588. if (index > -1) { this$1$1.apps.splice(index, 1); }
  2589. // ensure we still have a main app or null if no apps
  2590. // we do not release the router so it can be reused
  2591. if (this$1$1.app === app) { this$1$1.app = this$1$1.apps[0] || null; }
  2592. if (!this$1$1.app) { this$1$1.history.teardown(); }
  2593. });
  2594. // main app previously initialized
  2595. // return as we don't need to set up new history listener
  2596. if (this.app) {
  2597. return
  2598. }
  2599. this.app = app;
  2600. var history = this.history;
  2601. if (history instanceof HTML5History || history instanceof HashHistory) {
  2602. var handleInitialScroll = function (routeOrError) {
  2603. var from = history.current;
  2604. var expectScroll = this$1$1.options.scrollBehavior;
  2605. var supportsScroll = supportsPushState && expectScroll;
  2606. if (supportsScroll && 'fullPath' in routeOrError) {
  2607. handleScroll(this$1$1, routeOrError, from, false);
  2608. }
  2609. };
  2610. var setupListeners = function (routeOrError) {
  2611. history.setupListeners();
  2612. handleInitialScroll(routeOrError);
  2613. };
  2614. history.transitionTo(
  2615. history.getCurrentLocation(),
  2616. setupListeners,
  2617. setupListeners
  2618. );
  2619. }
  2620. history.listen(function (route) {
  2621. this$1$1.apps.forEach(function (app) {
  2622. app._route = route;
  2623. });
  2624. });
  2625. };
  2626. VueRouter.prototype.beforeEach = function beforeEach (fn) {
  2627. return registerHook(this.beforeHooks, fn)
  2628. };
  2629. VueRouter.prototype.beforeResolve = function beforeResolve (fn) {
  2630. return registerHook(this.resolveHooks, fn)
  2631. };
  2632. VueRouter.prototype.afterEach = function afterEach (fn) {
  2633. return registerHook(this.afterHooks, fn)
  2634. };
  2635. VueRouter.prototype.onReady = function onReady (cb, errorCb) {
  2636. this.history.onReady(cb, errorCb);
  2637. };
  2638. VueRouter.prototype.onError = function onError (errorCb) {
  2639. this.history.onError(errorCb);
  2640. };
  2641. VueRouter.prototype.push = function push (location, onComplete, onAbort) {
  2642. var this$1$1 = this;
  2643. // $flow-disable-line
  2644. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2645. return new Promise(function (resolve, reject) {
  2646. this$1$1.history.push(location, resolve, reject);
  2647. })
  2648. } else {
  2649. this.history.push(location, onComplete, onAbort);
  2650. }
  2651. };
  2652. VueRouter.prototype.replace = function replace (location, onComplete, onAbort) {
  2653. var this$1$1 = this;
  2654. // $flow-disable-line
  2655. if (!onComplete && !onAbort && typeof Promise !== 'undefined') {
  2656. return new Promise(function (resolve, reject) {
  2657. this$1$1.history.replace(location, resolve, reject);
  2658. })
  2659. } else {
  2660. this.history.replace(location, onComplete, onAbort);
  2661. }
  2662. };
  2663. VueRouter.prototype.go = function go (n) {
  2664. this.history.go(n);
  2665. };
  2666. VueRouter.prototype.back = function back () {
  2667. this.go(-1);
  2668. };
  2669. VueRouter.prototype.forward = function forward () {
  2670. this.go(1);
  2671. };
  2672. VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) {
  2673. var route = to
  2674. ? to.matched
  2675. ? to
  2676. : this.resolve(to).route
  2677. : this.currentRoute;
  2678. if (!route) {
  2679. return []
  2680. }
  2681. return [].concat.apply(
  2682. [],
  2683. route.matched.map(function (m) {
  2684. return Object.keys(m.components).map(function (key) {
  2685. return m.components[key]
  2686. })
  2687. })
  2688. )
  2689. };
  2690. VueRouter.prototype.resolve = function resolve (
  2691. to,
  2692. current,
  2693. append
  2694. ) {
  2695. current = current || this.history.current;
  2696. var location = normalizeLocation(to, current, append, this);
  2697. var route = this.match(location, current);
  2698. var fullPath = route.redirectedFrom || route.fullPath;
  2699. var base = this.history.base;
  2700. var href = createHref(base, fullPath, this.mode);
  2701. return {
  2702. location: location,
  2703. route: route,
  2704. href: href,
  2705. // for backwards compat
  2706. normalizedTo: location,
  2707. resolved: route
  2708. }
  2709. };
  2710. VueRouter.prototype.getRoutes = function getRoutes () {
  2711. return this.matcher.getRoutes()
  2712. };
  2713. VueRouter.prototype.addRoute = function addRoute (parentOrRoute, route) {
  2714. this.matcher.addRoute(parentOrRoute, route);
  2715. if (this.history.current !== START) {
  2716. this.history.transitionTo(this.history.getCurrentLocation());
  2717. }
  2718. };
  2719. VueRouter.prototype.addRoutes = function addRoutes (routes) {
  2720. if (process.env.NODE_ENV !== 'production') {
  2721. warn(false, 'router.addRoutes() is deprecated and has been removed in Vue Router 4. Use router.addRoute() instead.');
  2722. }
  2723. this.matcher.addRoutes(routes);
  2724. if (this.history.current !== START) {
  2725. this.history.transitionTo(this.history.getCurrentLocation());
  2726. }
  2727. };
  2728. Object.defineProperties( VueRouter.prototype, prototypeAccessors );
  2729. var VueRouter$1 = VueRouter;
  2730. function registerHook (list, fn) {
  2731. list.push(fn);
  2732. return function () {
  2733. var i = list.indexOf(fn);
  2734. if (i > -1) { list.splice(i, 1); }
  2735. }
  2736. }
  2737. function createHref (base, fullPath, mode) {
  2738. var path = mode === 'hash' ? '#' + fullPath : fullPath;
  2739. return base ? cleanPath(base + '/' + path) : path
  2740. }
  2741. // We cannot remove this as it would be a breaking change
  2742. VueRouter.install = install;
  2743. VueRouter.version = '3.6.5';
  2744. VueRouter.isNavigationFailure = isNavigationFailure;
  2745. VueRouter.NavigationFailureType = NavigationFailureType;
  2746. VueRouter.START_LOCATION = START;
  2747. if (inBrowser && window.Vue) {
  2748. window.Vue.use(VueRouter);
  2749. }
  2750. module.exports = VueRouter$1;