vue-router.esm.js 73 KB

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