vue-router.js 86 KB

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