vue-router.common.js 78 KB

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