vue-router.common.js 81 KB

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