UNPKG

45.2 kBJavaScriptView Raw
1/*!
2 * vuex v4.0.2
3 * (c) 2021 Evan You
4 * @license MIT
5 */
6var Vuex = (function (vue) {
7 'use strict';
8
9 var storeKey = 'store';
10
11 function useStore (key) {
12 if ( key === void 0 ) key = null;
13
14 return vue.inject(key !== null ? key : storeKey)
15 }
16
17 function getDevtoolsGlobalHook() {
18 return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
19 }
20 function getTarget() {
21 // @ts-ignore
22 return typeof navigator !== 'undefined'
23 ? window
24 : typeof global !== 'undefined'
25 ? global
26 : {};
27 }
28
29 var HOOK_SETUP = 'devtools-plugin:setup';
30
31 function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
32 var hook = getDevtoolsGlobalHook();
33 if (hook) {
34 hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
35 }
36 else {
37 var target = getTarget();
38 var list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
39 list.push({
40 pluginDescriptor: pluginDescriptor,
41 setupFn: setupFn
42 });
43 }
44 }
45
46 /**
47 * Get the first item that pass the test
48 * by second argument function
49 *
50 * @param {Array} list
51 * @param {Function} f
52 * @return {*}
53 */
54 function find (list, f) {
55 return list.filter(f)[0]
56 }
57
58 /**
59 * Deep copy the given object considering circular structure.
60 * This function caches all nested objects and its copies.
61 * If it detects circular structure, use cached copy to avoid infinite loop.
62 *
63 * @param {*} obj
64 * @param {Array<Object>} cache
65 * @return {*}
66 */
67 function deepCopy (obj, cache) {
68 if ( cache === void 0 ) cache = [];
69
70 // just return if obj is immutable value
71 if (obj === null || typeof obj !== 'object') {
72 return obj
73 }
74
75 // if obj is hit, it is in circular structure
76 var hit = find(cache, function (c) { return c.original === obj; });
77 if (hit) {
78 return hit.copy
79 }
80
81 var copy = Array.isArray(obj) ? [] : {};
82 // put the copy into cache at first
83 // because we want to refer it in recursive deepCopy
84 cache.push({
85 original: obj,
86 copy: copy
87 });
88
89 Object.keys(obj).forEach(function (key) {
90 copy[key] = deepCopy(obj[key], cache);
91 });
92
93 return copy
94 }
95
96 /**
97 * forEach for object
98 */
99 function forEachValue (obj, fn) {
100 Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
101 }
102
103 function isObject (obj) {
104 return obj !== null && typeof obj === 'object'
105 }
106
107 function isPromise (val) {
108 return val && typeof val.then === 'function'
109 }
110
111 function assert (condition, msg) {
112 if (!condition) { throw new Error(("[vuex] " + msg)) }
113 }
114
115 function partial (fn, arg) {
116 return function () {
117 return fn(arg)
118 }
119 }
120
121 function genericSubscribe (fn, subs, options) {
122 if (subs.indexOf(fn) < 0) {
123 options && options.prepend
124 ? subs.unshift(fn)
125 : subs.push(fn);
126 }
127 return function () {
128 var i = subs.indexOf(fn);
129 if (i > -1) {
130 subs.splice(i, 1);
131 }
132 }
133 }
134
135 function resetStore (store, hot) {
136 store._actions = Object.create(null);
137 store._mutations = Object.create(null);
138 store._wrappedGetters = Object.create(null);
139 store._modulesNamespaceMap = Object.create(null);
140 var state = store.state;
141 // init all modules
142 installModule(store, state, [], store._modules.root, true);
143 // reset state
144 resetStoreState(store, state, hot);
145 }
146
147 function resetStoreState (store, state, hot) {
148 var oldState = store._state;
149
150 // bind store public getters
151 store.getters = {};
152 // reset local getters cache
153 store._makeLocalGettersCache = Object.create(null);
154 var wrappedGetters = store._wrappedGetters;
155 var computedObj = {};
156 forEachValue(wrappedGetters, function (fn, key) {
157 // use computed to leverage its lazy-caching mechanism
158 // direct inline function use will lead to closure preserving oldState.
159 // using partial to return function with only arguments preserved in closure environment.
160 computedObj[key] = partial(fn, store);
161 Object.defineProperty(store.getters, key, {
162 // TODO: use `computed` when it's possible. at the moment we can't due to
163 // https://github.com/vuejs/vuex/pull/1883
164 get: function () { return computedObj[key](); },
165 enumerable: true // for local getters
166 });
167 });
168
169 store._state = vue.reactive({
170 data: state
171 });
172
173 // enable strict mode for new state
174 if (store.strict) {
175 enableStrictMode(store);
176 }
177
178 if (oldState) {
179 if (hot) {
180 // dispatch changes in all subscribed watchers
181 // to force getter re-evaluation for hot reloading.
182 store._withCommit(function () {
183 oldState.data = null;
184 });
185 }
186 }
187 }
188
189 function installModule (store, rootState, path, module, hot) {
190 var isRoot = !path.length;
191 var namespace = store._modules.getNamespace(path);
192
193 // register in namespace map
194 if (module.namespaced) {
195 if (store._modulesNamespaceMap[namespace] && true) {
196 console.error(("[vuex] duplicate namespace " + namespace + " for the namespaced module " + (path.join('/'))));
197 }
198 store._modulesNamespaceMap[namespace] = module;
199 }
200
201 // set state
202 if (!isRoot && !hot) {
203 var parentState = getNestedState(rootState, path.slice(0, -1));
204 var moduleName = path[path.length - 1];
205 store._withCommit(function () {
206 {
207 if (moduleName in parentState) {
208 console.warn(
209 ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
210 );
211 }
212 }
213 parentState[moduleName] = module.state;
214 });
215 }
216
217 var local = module.context = makeLocalContext(store, namespace, path);
218
219 module.forEachMutation(function (mutation, key) {
220 var namespacedType = namespace + key;
221 registerMutation(store, namespacedType, mutation, local);
222 });
223
224 module.forEachAction(function (action, key) {
225 var type = action.root ? key : namespace + key;
226 var handler = action.handler || action;
227 registerAction(store, type, handler, local);
228 });
229
230 module.forEachGetter(function (getter, key) {
231 var namespacedType = namespace + key;
232 registerGetter(store, namespacedType, getter, local);
233 });
234
235 module.forEachChild(function (child, key) {
236 installModule(store, rootState, path.concat(key), child, hot);
237 });
238 }
239
240 /**
241 * make localized dispatch, commit, getters and state
242 * if there is no namespace, just use root ones
243 */
244 function makeLocalContext (store, namespace, path) {
245 var noNamespace = namespace === '';
246
247 var local = {
248 dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
249 var args = unifyObjectStyle(_type, _payload, _options);
250 var payload = args.payload;
251 var options = args.options;
252 var type = args.type;
253
254 if (!options || !options.root) {
255 type = namespace + type;
256 if (!store._actions[type]) {
257 console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
258 return
259 }
260 }
261
262 return store.dispatch(type, payload)
263 },
264
265 commit: noNamespace ? store.commit : function (_type, _payload, _options) {
266 var args = unifyObjectStyle(_type, _payload, _options);
267 var payload = args.payload;
268 var options = args.options;
269 var type = args.type;
270
271 if (!options || !options.root) {
272 type = namespace + type;
273 if (!store._mutations[type]) {
274 console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
275 return
276 }
277 }
278
279 store.commit(type, payload, options);
280 }
281 };
282
283 // getters and state object must be gotten lazily
284 // because they will be changed by state update
285 Object.defineProperties(local, {
286 getters: {
287 get: noNamespace
288 ? function () { return store.getters; }
289 : function () { return makeLocalGetters(store, namespace); }
290 },
291 state: {
292 get: function () { return getNestedState(store.state, path); }
293 }
294 });
295
296 return local
297 }
298
299 function makeLocalGetters (store, namespace) {
300 if (!store._makeLocalGettersCache[namespace]) {
301 var gettersProxy = {};
302 var splitPos = namespace.length;
303 Object.keys(store.getters).forEach(function (type) {
304 // skip if the target getter is not match this namespace
305 if (type.slice(0, splitPos) !== namespace) { return }
306
307 // extract local getter type
308 var localType = type.slice(splitPos);
309
310 // Add a port to the getters proxy.
311 // Define as getter property because
312 // we do not want to evaluate the getters in this time.
313 Object.defineProperty(gettersProxy, localType, {
314 get: function () { return store.getters[type]; },
315 enumerable: true
316 });
317 });
318 store._makeLocalGettersCache[namespace] = gettersProxy;
319 }
320
321 return store._makeLocalGettersCache[namespace]
322 }
323
324 function registerMutation (store, type, handler, local) {
325 var entry = store._mutations[type] || (store._mutations[type] = []);
326 entry.push(function wrappedMutationHandler (payload) {
327 handler.call(store, local.state, payload);
328 });
329 }
330
331 function registerAction (store, type, handler, local) {
332 var entry = store._actions[type] || (store._actions[type] = []);
333 entry.push(function wrappedActionHandler (payload) {
334 var res = handler.call(store, {
335 dispatch: local.dispatch,
336 commit: local.commit,
337 getters: local.getters,
338 state: local.state,
339 rootGetters: store.getters,
340 rootState: store.state
341 }, payload);
342 if (!isPromise(res)) {
343 res = Promise.resolve(res);
344 }
345 if (store._devtoolHook) {
346 return res.catch(function (err) {
347 store._devtoolHook.emit('vuex:error', err);
348 throw err
349 })
350 } else {
351 return res
352 }
353 });
354 }
355
356 function registerGetter (store, type, rawGetter, local) {
357 if (store._wrappedGetters[type]) {
358 {
359 console.error(("[vuex] duplicate getter key: " + type));
360 }
361 return
362 }
363 store._wrappedGetters[type] = function wrappedGetter (store) {
364 return rawGetter(
365 local.state, // local state
366 local.getters, // local getters
367 store.state, // root state
368 store.getters // root getters
369 )
370 };
371 }
372
373 function enableStrictMode (store) {
374 vue.watch(function () { return store._state.data; }, function () {
375 {
376 assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
377 }
378 }, { deep: true, flush: 'sync' });
379 }
380
381 function getNestedState (state, path) {
382 return path.reduce(function (state, key) { return state[key]; }, state)
383 }
384
385 function unifyObjectStyle (type, payload, options) {
386 if (isObject(type) && type.type) {
387 options = payload;
388 payload = type;
389 type = type.type;
390 }
391
392 {
393 assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
394 }
395
396 return { type: type, payload: payload, options: options }
397 }
398
399 var LABEL_VUEX_BINDINGS = 'vuex bindings';
400 var MUTATIONS_LAYER_ID = 'vuex:mutations';
401 var ACTIONS_LAYER_ID = 'vuex:actions';
402 var INSPECTOR_ID = 'vuex';
403
404 var actionId = 0;
405
406 function addDevtools (app, store) {
407 setupDevtoolsPlugin(
408 {
409 id: 'org.vuejs.vuex',
410 app: app,
411 label: 'Vuex',
412 homepage: 'https://next.vuex.vuejs.org/',
413 logo: 'https://vuejs.org/images/icons/favicon-96x96.png',
414 packageName: 'vuex',
415 componentStateTypes: [LABEL_VUEX_BINDINGS]
416 },
417 function (api) {
418 api.addTimelineLayer({
419 id: MUTATIONS_LAYER_ID,
420 label: 'Vuex Mutations',
421 color: COLOR_LIME_500
422 });
423
424 api.addTimelineLayer({
425 id: ACTIONS_LAYER_ID,
426 label: 'Vuex Actions',
427 color: COLOR_LIME_500
428 });
429
430 api.addInspector({
431 id: INSPECTOR_ID,
432 label: 'Vuex',
433 icon: 'storage',
434 treeFilterPlaceholder: 'Filter stores...'
435 });
436
437 api.on.getInspectorTree(function (payload) {
438 if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
439 if (payload.filter) {
440 var nodes = [];
441 flattenStoreForInspectorTree(nodes, store._modules.root, payload.filter, '');
442 payload.rootNodes = nodes;
443 } else {
444 payload.rootNodes = [
445 formatStoreForInspectorTree(store._modules.root, '')
446 ];
447 }
448 }
449 });
450
451 api.on.getInspectorState(function (payload) {
452 if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
453 var modulePath = payload.nodeId;
454 makeLocalGetters(store, modulePath);
455 payload.state = formatStoreForInspectorState(
456 getStoreModule(store._modules, modulePath),
457 modulePath === 'root' ? store.getters : store._makeLocalGettersCache,
458 modulePath
459 );
460 }
461 });
462
463 api.on.editInspectorState(function (payload) {
464 if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
465 var modulePath = payload.nodeId;
466 var path = payload.path;
467 if (modulePath !== 'root') {
468 path = modulePath.split('/').filter(Boolean).concat( path);
469 }
470 store._withCommit(function () {
471 payload.set(store._state.data, path, payload.state.value);
472 });
473 }
474 });
475
476 store.subscribe(function (mutation, state) {
477 var data = {};
478
479 if (mutation.payload) {
480 data.payload = mutation.payload;
481 }
482
483 data.state = state;
484
485 api.notifyComponentUpdate();
486 api.sendInspectorTree(INSPECTOR_ID);
487 api.sendInspectorState(INSPECTOR_ID);
488
489 api.addTimelineEvent({
490 layerId: MUTATIONS_LAYER_ID,
491 event: {
492 time: Date.now(),
493 title: mutation.type,
494 data: data
495 }
496 });
497 });
498
499 store.subscribeAction({
500 before: function (action, state) {
501 var data = {};
502 if (action.payload) {
503 data.payload = action.payload;
504 }
505 action._id = actionId++;
506 action._time = Date.now();
507 data.state = state;
508
509 api.addTimelineEvent({
510 layerId: ACTIONS_LAYER_ID,
511 event: {
512 time: action._time,
513 title: action.type,
514 groupId: action._id,
515 subtitle: 'start',
516 data: data
517 }
518 });
519 },
520 after: function (action, state) {
521 var data = {};
522 var duration = Date.now() - action._time;
523 data.duration = {
524 _custom: {
525 type: 'duration',
526 display: (duration + "ms"),
527 tooltip: 'Action duration',
528 value: duration
529 }
530 };
531 if (action.payload) {
532 data.payload = action.payload;
533 }
534 data.state = state;
535
536 api.addTimelineEvent({
537 layerId: ACTIONS_LAYER_ID,
538 event: {
539 time: Date.now(),
540 title: action.type,
541 groupId: action._id,
542 subtitle: 'end',
543 data: data
544 }
545 });
546 }
547 });
548 }
549 );
550 }
551
552 // extracted from tailwind palette
553 var COLOR_LIME_500 = 0x84cc16;
554 var COLOR_DARK = 0x666666;
555 var COLOR_WHITE = 0xffffff;
556
557 var TAG_NAMESPACED = {
558 label: 'namespaced',
559 textColor: COLOR_WHITE,
560 backgroundColor: COLOR_DARK
561 };
562
563 /**
564 * @param {string} path
565 */
566 function extractNameFromPath (path) {
567 return path && path !== 'root' ? path.split('/').slice(-2, -1)[0] : 'Root'
568 }
569
570 /**
571 * @param {*} module
572 * @return {import('@vue/devtools-api').CustomInspectorNode}
573 */
574 function formatStoreForInspectorTree (module, path) {
575 return {
576 id: path || 'root',
577 // all modules end with a `/`, we want the last segment only
578 // cart/ -> cart
579 // nested/cart/ -> cart
580 label: extractNameFromPath(path),
581 tags: module.namespaced ? [TAG_NAMESPACED] : [],
582 children: Object.keys(module._children).map(function (moduleName) { return formatStoreForInspectorTree(
583 module._children[moduleName],
584 path + moduleName + '/'
585 ); }
586 )
587 }
588 }
589
590 /**
591 * @param {import('@vue/devtools-api').CustomInspectorNode[]} result
592 * @param {*} module
593 * @param {string} filter
594 * @param {string} path
595 */
596 function flattenStoreForInspectorTree (result, module, filter, path) {
597 if (path.includes(filter)) {
598 result.push({
599 id: path || 'root',
600 label: path.endsWith('/') ? path.slice(0, path.length - 1) : path || 'Root',
601 tags: module.namespaced ? [TAG_NAMESPACED] : []
602 });
603 }
604 Object.keys(module._children).forEach(function (moduleName) {
605 flattenStoreForInspectorTree(result, module._children[moduleName], filter, path + moduleName + '/');
606 });
607 }
608
609 /**
610 * @param {*} module
611 * @return {import('@vue/devtools-api').CustomInspectorState}
612 */
613 function formatStoreForInspectorState (module, getters, path) {
614 getters = path === 'root' ? getters : getters[path];
615 var gettersKeys = Object.keys(getters);
616 var storeState = {
617 state: Object.keys(module.state).map(function (key) { return ({
618 key: key,
619 editable: true,
620 value: module.state[key]
621 }); })
622 };
623
624 if (gettersKeys.length) {
625 var tree = transformPathsToObjectTree(getters);
626 storeState.getters = Object.keys(tree).map(function (key) { return ({
627 key: key.endsWith('/') ? extractNameFromPath(key) : key,
628 editable: false,
629 value: canThrow(function () { return tree[key]; })
630 }); });
631 }
632
633 return storeState
634 }
635
636 function transformPathsToObjectTree (getters) {
637 var result = {};
638 Object.keys(getters).forEach(function (key) {
639 var path = key.split('/');
640 if (path.length > 1) {
641 var target = result;
642 var leafKey = path.pop();
643 path.forEach(function (p) {
644 if (!target[p]) {
645 target[p] = {
646 _custom: {
647 value: {},
648 display: p,
649 tooltip: 'Module',
650 abstract: true
651 }
652 };
653 }
654 target = target[p]._custom.value;
655 });
656 target[leafKey] = canThrow(function () { return getters[key]; });
657 } else {
658 result[key] = canThrow(function () { return getters[key]; });
659 }
660 });
661 return result
662 }
663
664 function getStoreModule (moduleMap, path) {
665 var names = path.split('/').filter(function (n) { return n; });
666 return names.reduce(
667 function (module, moduleName, i) {
668 var child = module[moduleName];
669 if (!child) {
670 throw new Error(("Missing module \"" + moduleName + "\" for path \"" + path + "\"."))
671 }
672 return i === names.length - 1 ? child : child._children
673 },
674 path === 'root' ? moduleMap : moduleMap.root._children
675 )
676 }
677
678 function canThrow (cb) {
679 try {
680 return cb()
681 } catch (e) {
682 return e
683 }
684 }
685
686 // Base data struct for store's module, package with some attribute and method
687 var Module = function Module (rawModule, runtime) {
688 this.runtime = runtime;
689 // Store some children item
690 this._children = Object.create(null);
691 // Store the origin module object which passed by programmer
692 this._rawModule = rawModule;
693 var rawState = rawModule.state;
694
695 // Store the origin module's state
696 this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
697 };
698
699 var prototypeAccessors$1 = { namespaced: { configurable: true } };
700
701 prototypeAccessors$1.namespaced.get = function () {
702 return !!this._rawModule.namespaced
703 };
704
705 Module.prototype.addChild = function addChild (key, module) {
706 this._children[key] = module;
707 };
708
709 Module.prototype.removeChild = function removeChild (key) {
710 delete this._children[key];
711 };
712
713 Module.prototype.getChild = function getChild (key) {
714 return this._children[key]
715 };
716
717 Module.prototype.hasChild = function hasChild (key) {
718 return key in this._children
719 };
720
721 Module.prototype.update = function update (rawModule) {
722 this._rawModule.namespaced = rawModule.namespaced;
723 if (rawModule.actions) {
724 this._rawModule.actions = rawModule.actions;
725 }
726 if (rawModule.mutations) {
727 this._rawModule.mutations = rawModule.mutations;
728 }
729 if (rawModule.getters) {
730 this._rawModule.getters = rawModule.getters;
731 }
732 };
733
734 Module.prototype.forEachChild = function forEachChild (fn) {
735 forEachValue(this._children, fn);
736 };
737
738 Module.prototype.forEachGetter = function forEachGetter (fn) {
739 if (this._rawModule.getters) {
740 forEachValue(this._rawModule.getters, fn);
741 }
742 };
743
744 Module.prototype.forEachAction = function forEachAction (fn) {
745 if (this._rawModule.actions) {
746 forEachValue(this._rawModule.actions, fn);
747 }
748 };
749
750 Module.prototype.forEachMutation = function forEachMutation (fn) {
751 if (this._rawModule.mutations) {
752 forEachValue(this._rawModule.mutations, fn);
753 }
754 };
755
756 Object.defineProperties( Module.prototype, prototypeAccessors$1 );
757
758 var ModuleCollection = function ModuleCollection (rawRootModule) {
759 // register root module (Vuex.Store options)
760 this.register([], rawRootModule, false);
761 };
762
763 ModuleCollection.prototype.get = function get (path) {
764 return path.reduce(function (module, key) {
765 return module.getChild(key)
766 }, this.root)
767 };
768
769 ModuleCollection.prototype.getNamespace = function getNamespace (path) {
770 var module = this.root;
771 return path.reduce(function (namespace, key) {
772 module = module.getChild(key);
773 return namespace + (module.namespaced ? key + '/' : '')
774 }, '')
775 };
776
777 ModuleCollection.prototype.update = function update$1 (rawRootModule) {
778 update([], this.root, rawRootModule);
779 };
780
781 ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
782 var this$1$1 = this;
783 if ( runtime === void 0 ) runtime = true;
784
785 {
786 assertRawModule(path, rawModule);
787 }
788
789 var newModule = new Module(rawModule, runtime);
790 if (path.length === 0) {
791 this.root = newModule;
792 } else {
793 var parent = this.get(path.slice(0, -1));
794 parent.addChild(path[path.length - 1], newModule);
795 }
796
797 // register nested modules
798 if (rawModule.modules) {
799 forEachValue(rawModule.modules, function (rawChildModule, key) {
800 this$1$1.register(path.concat(key), rawChildModule, runtime);
801 });
802 }
803 };
804
805 ModuleCollection.prototype.unregister = function unregister (path) {
806 var parent = this.get(path.slice(0, -1));
807 var key = path[path.length - 1];
808 var child = parent.getChild(key);
809
810 if (!child) {
811 {
812 console.warn(
813 "[vuex] trying to unregister module '" + key + "', which is " +
814 "not registered"
815 );
816 }
817 return
818 }
819
820 if (!child.runtime) {
821 return
822 }
823
824 parent.removeChild(key);
825 };
826
827 ModuleCollection.prototype.isRegistered = function isRegistered (path) {
828 var parent = this.get(path.slice(0, -1));
829 var key = path[path.length - 1];
830
831 if (parent) {
832 return parent.hasChild(key)
833 }
834
835 return false
836 };
837
838 function update (path, targetModule, newModule) {
839 {
840 assertRawModule(path, newModule);
841 }
842
843 // update target module
844 targetModule.update(newModule);
845
846 // update nested modules
847 if (newModule.modules) {
848 for (var key in newModule.modules) {
849 if (!targetModule.getChild(key)) {
850 {
851 console.warn(
852 "[vuex] trying to add a new module '" + key + "' on hot reloading, " +
853 'manual reload is needed'
854 );
855 }
856 return
857 }
858 update(
859 path.concat(key),
860 targetModule.getChild(key),
861 newModule.modules[key]
862 );
863 }
864 }
865 }
866
867 var functionAssert = {
868 assert: function (value) { return typeof value === 'function'; },
869 expected: 'function'
870 };
871
872 var objectAssert = {
873 assert: function (value) { return typeof value === 'function' ||
874 (typeof value === 'object' && typeof value.handler === 'function'); },
875 expected: 'function or object with "handler" function'
876 };
877
878 var assertTypes = {
879 getters: functionAssert,
880 mutations: functionAssert,
881 actions: objectAssert
882 };
883
884 function assertRawModule (path, rawModule) {
885 Object.keys(assertTypes).forEach(function (key) {
886 if (!rawModule[key]) { return }
887
888 var assertOptions = assertTypes[key];
889
890 forEachValue(rawModule[key], function (value, type) {
891 assert(
892 assertOptions.assert(value),
893 makeAssertionMessage(path, key, type, value, assertOptions.expected)
894 );
895 });
896 });
897 }
898
899 function makeAssertionMessage (path, key, type, value, expected) {
900 var buf = key + " should be " + expected + " but \"" + key + "." + type + "\"";
901 if (path.length > 0) {
902 buf += " in module \"" + (path.join('.')) + "\"";
903 }
904 buf += " is " + (JSON.stringify(value)) + ".";
905 return buf
906 }
907
908 function createStore (options) {
909 return new Store(options)
910 }
911
912 var Store = function Store (options) {
913 var this$1$1 = this;
914 if ( options === void 0 ) options = {};
915
916 {
917 assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
918 assert(this instanceof Store, "store must be called with the new operator.");
919 }
920
921 var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
922 var strict = options.strict; if ( strict === void 0 ) strict = false;
923 var devtools = options.devtools;
924
925 // store internal state
926 this._committing = false;
927 this._actions = Object.create(null);
928 this._actionSubscribers = [];
929 this._mutations = Object.create(null);
930 this._wrappedGetters = Object.create(null);
931 this._modules = new ModuleCollection(options);
932 this._modulesNamespaceMap = Object.create(null);
933 this._subscribers = [];
934 this._makeLocalGettersCache = Object.create(null);
935 this._devtools = devtools;
936
937 // bind commit and dispatch to self
938 var store = this;
939 var ref = this;
940 var dispatch = ref.dispatch;
941 var commit = ref.commit;
942 this.dispatch = function boundDispatch (type, payload) {
943 return dispatch.call(store, type, payload)
944 };
945 this.commit = function boundCommit (type, payload, options) {
946 return commit.call(store, type, payload, options)
947 };
948
949 // strict mode
950 this.strict = strict;
951
952 var state = this._modules.root.state;
953
954 // init root module.
955 // this also recursively registers all sub-modules
956 // and collects all module getters inside this._wrappedGetters
957 installModule(this, state, [], this._modules.root);
958
959 // initialize the store state, which is responsible for the reactivity
960 // (also registers _wrappedGetters as computed properties)
961 resetStoreState(this, state);
962
963 // apply plugins
964 plugins.forEach(function (plugin) { return plugin(this$1$1); });
965 };
966
967 var prototypeAccessors = { state: { configurable: true } };
968
969 Store.prototype.install = function install (app, injectKey) {
970 app.provide(injectKey || storeKey, this);
971 app.config.globalProperties.$store = this;
972
973 var useDevtools = this._devtools !== undefined
974 ? this._devtools
975 : true ;
976
977 if (useDevtools) {
978 addDevtools(app, this);
979 }
980 };
981
982 prototypeAccessors.state.get = function () {
983 return this._state.data
984 };
985
986 prototypeAccessors.state.set = function (v) {
987 {
988 assert(false, "use store.replaceState() to explicit replace store state.");
989 }
990 };
991
992 Store.prototype.commit = function commit (_type, _payload, _options) {
993 var this$1$1 = this;
994
995 // check object-style commit
996 var ref = unifyObjectStyle(_type, _payload, _options);
997 var type = ref.type;
998 var payload = ref.payload;
999 var options = ref.options;
1000
1001 var mutation = { type: type, payload: payload };
1002 var entry = this._mutations[type];
1003 if (!entry) {
1004 {
1005 console.error(("[vuex] unknown mutation type: " + type));
1006 }
1007 return
1008 }
1009 this._withCommit(function () {
1010 entry.forEach(function commitIterator (handler) {
1011 handler(payload);
1012 });
1013 });
1014
1015 this._subscribers
1016 .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
1017 .forEach(function (sub) { return sub(mutation, this$1$1.state); });
1018
1019 if (
1020 options && options.silent
1021 ) {
1022 console.warn(
1023 "[vuex] mutation type: " + type + ". Silent option has been removed. " +
1024 'Use the filter functionality in the vue-devtools'
1025 );
1026 }
1027 };
1028
1029 Store.prototype.dispatch = function dispatch (_type, _payload) {
1030 var this$1$1 = this;
1031
1032 // check object-style dispatch
1033 var ref = unifyObjectStyle(_type, _payload);
1034 var type = ref.type;
1035 var payload = ref.payload;
1036
1037 var action = { type: type, payload: payload };
1038 var entry = this._actions[type];
1039 if (!entry) {
1040 {
1041 console.error(("[vuex] unknown action type: " + type));
1042 }
1043 return
1044 }
1045
1046 try {
1047 this._actionSubscribers
1048 .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
1049 .filter(function (sub) { return sub.before; })
1050 .forEach(function (sub) { return sub.before(action, this$1$1.state); });
1051 } catch (e) {
1052 {
1053 console.warn("[vuex] error in before action subscribers: ");
1054 console.error(e);
1055 }
1056 }
1057
1058 var result = entry.length > 1
1059 ? Promise.all(entry.map(function (handler) { return handler(payload); }))
1060 : entry[0](payload);
1061
1062 return new Promise(function (resolve, reject) {
1063 result.then(function (res) {
1064 try {
1065 this$1$1._actionSubscribers
1066 .filter(function (sub) { return sub.after; })
1067 .forEach(function (sub) { return sub.after(action, this$1$1.state); });
1068 } catch (e) {
1069 {
1070 console.warn("[vuex] error in after action subscribers: ");
1071 console.error(e);
1072 }
1073 }
1074 resolve(res);
1075 }, function (error) {
1076 try {
1077 this$1$1._actionSubscribers
1078 .filter(function (sub) { return sub.error; })
1079 .forEach(function (sub) { return sub.error(action, this$1$1.state, error); });
1080 } catch (e) {
1081 {
1082 console.warn("[vuex] error in error action subscribers: ");
1083 console.error(e);
1084 }
1085 }
1086 reject(error);
1087 });
1088 })
1089 };
1090
1091 Store.prototype.subscribe = function subscribe (fn, options) {
1092 return genericSubscribe(fn, this._subscribers, options)
1093 };
1094
1095 Store.prototype.subscribeAction = function subscribeAction (fn, options) {
1096 var subs = typeof fn === 'function' ? { before: fn } : fn;
1097 return genericSubscribe(subs, this._actionSubscribers, options)
1098 };
1099
1100 Store.prototype.watch = function watch$1 (getter, cb, options) {
1101 var this$1$1 = this;
1102
1103 {
1104 assert(typeof getter === 'function', "store.watch only accepts a function.");
1105 }
1106 return vue.watch(function () { return getter(this$1$1.state, this$1$1.getters); }, cb, Object.assign({}, options))
1107 };
1108
1109 Store.prototype.replaceState = function replaceState (state) {
1110 var this$1$1 = this;
1111
1112 this._withCommit(function () {
1113 this$1$1._state.data = state;
1114 });
1115 };
1116
1117 Store.prototype.registerModule = function registerModule (path, rawModule, options) {
1118 if ( options === void 0 ) options = {};
1119
1120 if (typeof path === 'string') { path = [path]; }
1121
1122 {
1123 assert(Array.isArray(path), "module path must be a string or an Array.");
1124 assert(path.length > 0, 'cannot register the root module by using registerModule.');
1125 }
1126
1127 this._modules.register(path, rawModule);
1128 installModule(this, this.state, path, this._modules.get(path), options.preserveState);
1129 // reset store to update getters...
1130 resetStoreState(this, this.state);
1131 };
1132
1133 Store.prototype.unregisterModule = function unregisterModule (path) {
1134 var this$1$1 = this;
1135
1136 if (typeof path === 'string') { path = [path]; }
1137
1138 {
1139 assert(Array.isArray(path), "module path must be a string or an Array.");
1140 }
1141
1142 this._modules.unregister(path);
1143 this._withCommit(function () {
1144 var parentState = getNestedState(this$1$1.state, path.slice(0, -1));
1145 delete parentState[path[path.length - 1]];
1146 });
1147 resetStore(this);
1148 };
1149
1150 Store.prototype.hasModule = function hasModule (path) {
1151 if (typeof path === 'string') { path = [path]; }
1152
1153 {
1154 assert(Array.isArray(path), "module path must be a string or an Array.");
1155 }
1156
1157 return this._modules.isRegistered(path)
1158 };
1159
1160 Store.prototype.hotUpdate = function hotUpdate (newOptions) {
1161 this._modules.update(newOptions);
1162 resetStore(this, true);
1163 };
1164
1165 Store.prototype._withCommit = function _withCommit (fn) {
1166 var committing = this._committing;
1167 this._committing = true;
1168 fn();
1169 this._committing = committing;
1170 };
1171
1172 Object.defineProperties( Store.prototype, prototypeAccessors );
1173
1174 /**
1175 * Reduce the code which written in Vue.js for getting the state.
1176 * @param {String} [namespace] - Module's namespace
1177 * @param {Object|Array} states # Object's item can be a function which accept state and getters for param, you can do something for state and getters in it.
1178 * @param {Object}
1179 */
1180 var mapState = normalizeNamespace(function (namespace, states) {
1181 var res = {};
1182 if (!isValidMap(states)) {
1183 console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
1184 }
1185 normalizeMap(states).forEach(function (ref) {
1186 var key = ref.key;
1187 var val = ref.val;
1188
1189 res[key] = function mappedState () {
1190 var state = this.$store.state;
1191 var getters = this.$store.getters;
1192 if (namespace) {
1193 var module = getModuleByNamespace(this.$store, 'mapState', namespace);
1194 if (!module) {
1195 return
1196 }
1197 state = module.context.state;
1198 getters = module.context.getters;
1199 }
1200 return typeof val === 'function'
1201 ? val.call(this, state, getters)
1202 : state[val]
1203 };
1204 // mark vuex getter for devtools
1205 res[key].vuex = true;
1206 });
1207 return res
1208 });
1209
1210 /**
1211 * Reduce the code which written in Vue.js for committing the mutation
1212 * @param {String} [namespace] - Module's namespace
1213 * @param {Object|Array} mutations # Object's item can be a function which accept `commit` function as the first param, it can accept another params. You can commit mutation and do any other things in this function. specially, You need to pass anthor params from the mapped function.
1214 * @return {Object}
1215 */
1216 var mapMutations = normalizeNamespace(function (namespace, mutations) {
1217 var res = {};
1218 if (!isValidMap(mutations)) {
1219 console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
1220 }
1221 normalizeMap(mutations).forEach(function (ref) {
1222 var key = ref.key;
1223 var val = ref.val;
1224
1225 res[key] = function mappedMutation () {
1226 var args = [], len = arguments.length;
1227 while ( len-- ) args[ len ] = arguments[ len ];
1228
1229 // Get the commit method from store
1230 var commit = this.$store.commit;
1231 if (namespace) {
1232 var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
1233 if (!module) {
1234 return
1235 }
1236 commit = module.context.commit;
1237 }
1238 return typeof val === 'function'
1239 ? val.apply(this, [commit].concat(args))
1240 : commit.apply(this.$store, [val].concat(args))
1241 };
1242 });
1243 return res
1244 });
1245
1246 /**
1247 * Reduce the code which written in Vue.js for getting the getters
1248 * @param {String} [namespace] - Module's namespace
1249 * @param {Object|Array} getters
1250 * @return {Object}
1251 */
1252 var mapGetters = normalizeNamespace(function (namespace, getters) {
1253 var res = {};
1254 if (!isValidMap(getters)) {
1255 console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
1256 }
1257 normalizeMap(getters).forEach(function (ref) {
1258 var key = ref.key;
1259 var val = ref.val;
1260
1261 // The namespace has been mutated by normalizeNamespace
1262 val = namespace + val;
1263 res[key] = function mappedGetter () {
1264 if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
1265 return
1266 }
1267 if (!(val in this.$store.getters)) {
1268 console.error(("[vuex] unknown getter: " + val));
1269 return
1270 }
1271 return this.$store.getters[val]
1272 };
1273 // mark vuex getter for devtools
1274 res[key].vuex = true;
1275 });
1276 return res
1277 });
1278
1279 /**
1280 * Reduce the code which written in Vue.js for dispatch the action
1281 * @param {String} [namespace] - Module's namespace
1282 * @param {Object|Array} actions # Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.
1283 * @return {Object}
1284 */
1285 var mapActions = normalizeNamespace(function (namespace, actions) {
1286 var res = {};
1287 if (!isValidMap(actions)) {
1288 console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
1289 }
1290 normalizeMap(actions).forEach(function (ref) {
1291 var key = ref.key;
1292 var val = ref.val;
1293
1294 res[key] = function mappedAction () {
1295 var args = [], len = arguments.length;
1296 while ( len-- ) args[ len ] = arguments[ len ];
1297
1298 // get dispatch function from store
1299 var dispatch = this.$store.dispatch;
1300 if (namespace) {
1301 var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
1302 if (!module) {
1303 return
1304 }
1305 dispatch = module.context.dispatch;
1306 }
1307 return typeof val === 'function'
1308 ? val.apply(this, [dispatch].concat(args))
1309 : dispatch.apply(this.$store, [val].concat(args))
1310 };
1311 });
1312 return res
1313 });
1314
1315 /**
1316 * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
1317 * @param {String} namespace
1318 * @return {Object}
1319 */
1320 var createNamespacedHelpers = function (namespace) { return ({
1321 mapState: mapState.bind(null, namespace),
1322 mapGetters: mapGetters.bind(null, namespace),
1323 mapMutations: mapMutations.bind(null, namespace),
1324 mapActions: mapActions.bind(null, namespace)
1325 }); };
1326
1327 /**
1328 * Normalize the map
1329 * normalizeMap([1, 2, 3]) => [ { key: 1, val: 1 }, { key: 2, val: 2 }, { key: 3, val: 3 } ]
1330 * normalizeMap({a: 1, b: 2, c: 3}) => [ { key: 'a', val: 1 }, { key: 'b', val: 2 }, { key: 'c', val: 3 } ]
1331 * @param {Array|Object} map
1332 * @return {Object}
1333 */
1334 function normalizeMap (map) {
1335 if (!isValidMap(map)) {
1336 return []
1337 }
1338 return Array.isArray(map)
1339 ? map.map(function (key) { return ({ key: key, val: key }); })
1340 : Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
1341 }
1342
1343 /**
1344 * Validate whether given map is valid or not
1345 * @param {*} map
1346 * @return {Boolean}
1347 */
1348 function isValidMap (map) {
1349 return Array.isArray(map) || isObject(map)
1350 }
1351
1352 /**
1353 * Return a function expect two param contains namespace and map. it will normalize the namespace and then the param's function will handle the new namespace and the map.
1354 * @param {Function} fn
1355 * @return {Function}
1356 */
1357 function normalizeNamespace (fn) {
1358 return function (namespace, map) {
1359 if (typeof namespace !== 'string') {
1360 map = namespace;
1361 namespace = '';
1362 } else if (namespace.charAt(namespace.length - 1) !== '/') {
1363 namespace += '/';
1364 }
1365 return fn(namespace, map)
1366 }
1367 }
1368
1369 /**
1370 * Search a special module from store by namespace. if module not exist, print error message.
1371 * @param {Object} store
1372 * @param {String} helper
1373 * @param {String} namespace
1374 * @return {Object}
1375 */
1376 function getModuleByNamespace (store, helper, namespace) {
1377 var module = store._modulesNamespaceMap[namespace];
1378 if (!module) {
1379 console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
1380 }
1381 return module
1382 }
1383
1384 // Credits: borrowed code from fcomb/redux-logger
1385
1386 function createLogger (ref) {
1387 if ( ref === void 0 ) ref = {};
1388 var collapsed = ref.collapsed; if ( collapsed === void 0 ) collapsed = true;
1389 var filter = ref.filter; if ( filter === void 0 ) filter = function (mutation, stateBefore, stateAfter) { return true; };
1390 var transformer = ref.transformer; if ( transformer === void 0 ) transformer = function (state) { return state; };
1391 var mutationTransformer = ref.mutationTransformer; if ( mutationTransformer === void 0 ) mutationTransformer = function (mut) { return mut; };
1392 var actionFilter = ref.actionFilter; if ( actionFilter === void 0 ) actionFilter = function (action, state) { return true; };
1393 var actionTransformer = ref.actionTransformer; if ( actionTransformer === void 0 ) actionTransformer = function (act) { return act; };
1394 var logMutations = ref.logMutations; if ( logMutations === void 0 ) logMutations = true;
1395 var logActions = ref.logActions; if ( logActions === void 0 ) logActions = true;
1396 var logger = ref.logger; if ( logger === void 0 ) logger = console;
1397
1398 return function (store) {
1399 var prevState = deepCopy(store.state);
1400
1401 if (typeof logger === 'undefined') {
1402 return
1403 }
1404
1405 if (logMutations) {
1406 store.subscribe(function (mutation, state) {
1407 var nextState = deepCopy(state);
1408
1409 if (filter(mutation, prevState, nextState)) {
1410 var formattedTime = getFormattedTime();
1411 var formattedMutation = mutationTransformer(mutation);
1412 var message = "mutation " + (mutation.type) + formattedTime;
1413
1414 startMessage(logger, message, collapsed);
1415 logger.log('%c prev state', 'color: #9E9E9E; font-weight: bold', transformer(prevState));
1416 logger.log('%c mutation', 'color: #03A9F4; font-weight: bold', formattedMutation);
1417 logger.log('%c next state', 'color: #4CAF50; font-weight: bold', transformer(nextState));
1418 endMessage(logger);
1419 }
1420
1421 prevState = nextState;
1422 });
1423 }
1424
1425 if (logActions) {
1426 store.subscribeAction(function (action, state) {
1427 if (actionFilter(action, state)) {
1428 var formattedTime = getFormattedTime();
1429 var formattedAction = actionTransformer(action);
1430 var message = "action " + (action.type) + formattedTime;
1431
1432 startMessage(logger, message, collapsed);
1433 logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
1434 endMessage(logger);
1435 }
1436 });
1437 }
1438 }
1439 }
1440
1441 function startMessage (logger, message, collapsed) {
1442 var startMessage = collapsed
1443 ? logger.groupCollapsed
1444 : logger.group;
1445
1446 // render
1447 try {
1448 startMessage.call(logger, message);
1449 } catch (e) {
1450 logger.log(message);
1451 }
1452 }
1453
1454 function endMessage (logger) {
1455 try {
1456 logger.groupEnd();
1457 } catch (e) {
1458 logger.log('—— log end ——');
1459 }
1460 }
1461
1462 function getFormattedTime () {
1463 var time = new Date();
1464 return (" @ " + (pad(time.getHours(), 2)) + ":" + (pad(time.getMinutes(), 2)) + ":" + (pad(time.getSeconds(), 2)) + "." + (pad(time.getMilliseconds(), 3)))
1465 }
1466
1467 function repeat (str, times) {
1468 return (new Array(times + 1)).join(str)
1469 }
1470
1471 function pad (num, maxLength) {
1472 return repeat('0', maxLength - num.toString().length) + num
1473 }
1474
1475 var index_cjs = {
1476 version: '4.0.2',
1477 Store: Store,
1478 storeKey: storeKey,
1479 createStore: createStore,
1480 useStore: useStore,
1481 mapState: mapState,
1482 mapMutations: mapMutations,
1483 mapGetters: mapGetters,
1484 mapActions: mapActions,
1485 createNamespacedHelpers: createNamespacedHelpers,
1486 createLogger: createLogger
1487 };
1488
1489 return index_cjs;
1490
1491}(Vue));