vue-router.esm.js 66 KB

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