vue-router.common.js 65 KB

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