6 var Vuex = (function (vue) {
9 var storeKey = 'store';
11 function useStore (key) {
12 if ( key === void 0 ) key = null;
14 return vue.inject(key !== null ? key : storeKey)
17 function getDevtoolsGlobalHook() {
18 return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
20 function getTarget() {
22 return typeof navigator !== 'undefined'
24 : typeof global !== 'undefined'
29 var HOOK_SETUP = 'devtools-plugin:setup';
31 function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
32 var hook = getDevtoolsGlobalHook();
34 hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
37 var target = getTarget();
38 var list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
40 pluginDescriptor: pluginDescriptor,
47 * Get the first item that pass the test
48 * by second argument function
54 function find (list, f) {
55 return list.filter(f)[0]
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.
64 * @param {Array<Object>} cache
67 function deepCopy (obj, cache) {
68 if ( cache === void 0 ) cache = [];
70 // just return if obj is immutable value
71 if (obj === null || typeof obj !== 'object') {
75 // if obj is hit, it is in circular structure
76 var hit = find(cache, function (c) { return c.original === obj; });
81 var copy = Array.isArray(obj) ? [] : {};
82 // put the copy into cache at first
83 // because we want to refer it in recursive deepCopy
89 Object.keys(obj).forEach(function (key) {
90 copy[key] = deepCopy(obj[key], cache);
99 function forEachValue (obj, fn) {
100 Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
103 function isObject (obj) {
104 return obj !== null && typeof obj === 'object'
107 function isPromise (val) {
108 return val && typeof val.then === 'function'
111 function assert (condition, msg) {
112 if (!condition) { throw new Error(("[vuex] " + msg)) }
115 function partial (fn, arg) {
121 function genericSubscribe (fn, subs, options) {
122 if (subs.indexOf(fn) < 0) {
123 options && options.prepend
128 var i = subs.indexOf(fn);
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;
142 installModule(store, state, [], store._modules.root, true);
144 resetStoreState(store, state, hot);
147 function resetStoreState (store, state, hot) {
148 var oldState = store._state;
150 // bind store public 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
169 store._state = vue.reactive({
173 // enable strict mode for new state
175 enableStrictMode(store);
180 // dispatch changes in all subscribed watchers
181 // to force getter re-evaluation for hot reloading.
182 store._withCommit(function () {
183 oldState.data = null;
189 function installModule (store, rootState, path, module, hot) {
190 var isRoot = !path.length;
191 var namespace = store._modules.getNamespace(path);
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('/'))));
198 store._modulesNamespaceMap[namespace] = module;
202 if (!isRoot && !hot) {
203 var parentState = getNestedState(rootState, path.slice(0, -1));
204 var moduleName = path[path.length - 1];
205 store._withCommit(function () {
207 if (moduleName in parentState) {
209 ("[vuex] state field \"" + moduleName + "\" was overridden by a module with the same name at \"" + (path.join('.')) + "\"")
213 parentState[moduleName] = module.state;
217 var local = module.context = makeLocalContext(store, namespace, path);
219 module.forEachMutation(function (mutation, key) {
220 var namespacedType = namespace + key;
221 registerMutation(store, namespacedType, mutation, local);
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);
230 module.forEachGetter(function (getter, key) {
231 var namespacedType = namespace + key;
232 registerGetter(store, namespacedType, getter, local);
235 module.forEachChild(function (child, key) {
236 installModule(store, rootState, path.concat(key), child, hot);
241 * make localized dispatch, commit, getters and state
242 * if there is no namespace, just use root ones
244 function makeLocalContext (store, namespace, path) {
245 var noNamespace = namespace === '';
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;
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));
262 return store.dispatch(type, payload)
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;
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));
279 store.commit(type, payload, options);
283 // getters and state object must be gotten lazily
284 // because they will be changed by state update
285 Object.defineProperties(local, {
288 ? function () { return store.getters; }
289 : function () { return makeLocalGetters(store, namespace); }
292 get: function () { return getNestedState(store.state, path); }
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 }
307 // extract local getter type
308 var localType = type.slice(splitPos);
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]; },
318 store._makeLocalGettersCache[namespace] = gettersProxy;
321 return store._makeLocalGettersCache[namespace]
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);
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,
339 rootGetters: store.getters,
340 rootState: store.state
342 if (!isPromise(res)) {
343 res = Promise.resolve(res);
345 if (store._devtoolHook) {
346 return res.catch(function (err) {
347 store._devtoolHook.emit('vuex:error', err);
356 function registerGetter (store, type, rawGetter, local) {
357 if (store._wrappedGetters[type]) {
359 console.error(("[vuex] duplicate getter key: " + type));
363 store._wrappedGetters[type] = function wrappedGetter (store) {
365 local.state, // local state
366 local.getters, // local getters
367 store.state, // root state
368 store.getters // root getters
373 function enableStrictMode (store) {
374 vue.watch(function () { return store._state.data; }, function () {
376 assert(store._committing, "do not mutate vuex store state outside mutation handlers.");
378 }, { deep: true, flush: 'sync' });
381 function getNestedState (state, path) {
382 return path.reduce(function (state, key) { return state[key]; }, state)
385 function unifyObjectStyle (type, payload, options) {
386 if (isObject(type) && type.type) {
393 assert(typeof type === 'string', ("expects string as the type, but found " + (typeof type) + "."));
396 return { type: type, payload: payload, options: options }
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';
406 function addDevtools (app, store) {
409 id: 'org.vuejs.vuex',
412 homepage: 'https://next.vuex.vuejs.org/',
413 logo: 'https://vuejs.org/images/icons/favicon-96x96.png',
415 componentStateTypes: [LABEL_VUEX_BINDINGS]
418 api.addTimelineLayer({
419 id: MUTATIONS_LAYER_ID,
420 label: 'Vuex Mutations',
421 color: COLOR_LIME_500
424 api.addTimelineLayer({
425 id: ACTIONS_LAYER_ID,
426 label: 'Vuex Actions',
427 color: COLOR_LIME_500
434 treeFilterPlaceholder: 'Filter stores...'
437 api.on.getInspectorTree(function (payload) {
438 if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
439 if (payload.filter) {
441 flattenStoreForInspectorTree(nodes, store._modules.root, payload.filter, '');
442 payload.rootNodes = nodes;
444 payload.rootNodes = [
445 formatStoreForInspectorTree(store._modules.root, '')
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,
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);
470 store._withCommit(function () {
471 payload.set(store._state.data, path, payload.state.value);
476 store.subscribe(function (mutation, state) {
479 if (mutation.payload) {
480 data.payload = mutation.payload;
485 api.notifyComponentUpdate();
486 api.sendInspectorTree(INSPECTOR_ID);
487 api.sendInspectorState(INSPECTOR_ID);
489 api.addTimelineEvent({
490 layerId: MUTATIONS_LAYER_ID,
493 title: mutation.type,
499 store.subscribeAction({
500 before: function (action, state) {
502 if (action.payload) {
503 data.payload = action.payload;
505 action._id = actionId++;
506 action._time = Date.now();
509 api.addTimelineEvent({
510 layerId: ACTIONS_LAYER_ID,
520 after: function (action, state) {
522 var duration = Date.now() - action._time;
526 display: (duration + "ms"),
527 tooltip: 'Action duration',
531 if (action.payload) {
532 data.payload = action.payload;
536 api.addTimelineEvent({
537 layerId: ACTIONS_LAYER_ID,
552 // extracted from tailwind palette
553 var COLOR_LIME_500 = 0x84cc16;
554 var COLOR_DARK = 0x666666;
555 var COLOR_WHITE = 0xffffff;
557 var TAG_NAMESPACED = {
559 textColor: COLOR_WHITE,
560 backgroundColor: COLOR_DARK
564 * @param {string} path
566 function extractNameFromPath (path) {
567 return path && path !== 'root' ? path.split('/').slice(-2, -1)[0] : 'Root'
572 * @return {import('@vue/devtools-api').CustomInspectorNode}
574 function formatStoreForInspectorTree (module, path) {
577 // all modules end with a `/`, we want the last segment only
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 + '/'
591 * @param {import('@vue/devtools-api').CustomInspectorNode[]} result
593 * @param {string} filter
594 * @param {string} path
596 function flattenStoreForInspectorTree (result, module, filter, path) {
597 if (path.includes(filter)) {
600 label: path.endsWith('/') ? path.slice(0, path.length - 1) : path || 'Root',
601 tags: module.namespaced ? [TAG_NAMESPACED] : []
604 Object.keys(module._children).forEach(function (moduleName) {
605 flattenStoreForInspectorTree(result, module._children[moduleName], filter, path + moduleName + '/');
611 * @return {import('@vue/devtools-api').CustomInspectorState}
613 function formatStoreForInspectorState (module, getters, path) {
614 getters = path === 'root' ? getters : getters[path];
615 var gettersKeys = Object.keys(getters);
617 state: Object.keys(module.state).map(function (key) { return ({
620 value: module.state[key]
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,
629 value: canThrow(function () { return tree[key]; })
636 function transformPathsToObjectTree (getters) {
638 Object.keys(getters).forEach(function (key) {
639 var path = key.split('/');
640 if (path.length > 1) {
642 var leafKey = path.pop();
643 path.forEach(function (p) {
654 target = target[p]._custom.value;
656 target[leafKey] = canThrow(function () { return getters[key]; });
658 result[key] = canThrow(function () { return getters[key]; });
664 function getStoreModule (moduleMap, path) {
665 var names = path.split('/').filter(function (n) { return n; });
667 function (module, moduleName, i) {
668 var child = module[moduleName];
670 throw new Error(("Missing module \"" + moduleName + "\" for path \"" + path + "\"."))
672 return i === names.length - 1 ? child : child._children
674 path === 'root' ? moduleMap : moduleMap.root._children
678 function canThrow (cb) {
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;
695 // Store the origin module's state
696 this.state = (typeof rawState === 'function' ? rawState() : rawState) || {};
699 var prototypeAccessors$1 = { namespaced: { configurable: true } };
701 prototypeAccessors$1.namespaced.get = function () {
702 return !!this._rawModule.namespaced
705 Module.prototype.addChild = function addChild (key, module) {
706 this._children[key] = module;
709 Module.prototype.removeChild = function removeChild (key) {
710 delete this._children[key];
713 Module.prototype.getChild = function getChild (key) {
714 return this._children[key]
717 Module.prototype.hasChild = function hasChild (key) {
718 return key in this._children
721 Module.prototype.update = function update (rawModule) {
722 this._rawModule.namespaced = rawModule.namespaced;
723 if (rawModule.actions) {
724 this._rawModule.actions = rawModule.actions;
726 if (rawModule.mutations) {
727 this._rawModule.mutations = rawModule.mutations;
729 if (rawModule.getters) {
730 this._rawModule.getters = rawModule.getters;
734 Module.prototype.forEachChild = function forEachChild (fn) {
735 forEachValue(this._children, fn);
738 Module.prototype.forEachGetter = function forEachGetter (fn) {
739 if (this._rawModule.getters) {
740 forEachValue(this._rawModule.getters, fn);
744 Module.prototype.forEachAction = function forEachAction (fn) {
745 if (this._rawModule.actions) {
746 forEachValue(this._rawModule.actions, fn);
750 Module.prototype.forEachMutation = function forEachMutation (fn) {
751 if (this._rawModule.mutations) {
752 forEachValue(this._rawModule.mutations, fn);
756 Object.defineProperties( Module.prototype, prototypeAccessors$1 );
758 var ModuleCollection = function ModuleCollection (rawRootModule) {
759 // register root module (Vuex.Store options)
760 this.register([], rawRootModule, false);
763 ModuleCollection.prototype.get = function get (path) {
764 return path.reduce(function (module, key) {
765 return module.getChild(key)
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 + '/' : '')
777 ModuleCollection.prototype.update = function update$1 (rawRootModule) {
778 update([], this.root, rawRootModule);
781 ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
783 if ( runtime === void 0 ) runtime = true;
786 assertRawModule(path, rawModule);
789 var newModule = new Module(rawModule, runtime);
790 if (path.length === 0) {
791 this.root = newModule;
793 var parent = this.get(path.slice(0, -1));
794 parent.addChild(path[path.length - 1], newModule);
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);
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);
813 "[vuex] trying to unregister module '" + key + "', which is " +
820 if (!child.runtime) {
824 parent.removeChild(key);
827 ModuleCollection.prototype.isRegistered = function isRegistered (path) {
828 var parent = this.get(path.slice(0, -1));
829 var key = path[path.length - 1];
832 return parent.hasChild(key)
838 function update (path, targetModule, newModule) {
840 assertRawModule(path, newModule);
843 // update target module
844 targetModule.update(newModule);
846 // update nested modules
847 if (newModule.modules) {
848 for (var key in newModule.modules) {
849 if (!targetModule.getChild(key)) {
852 "[vuex] trying to add a new module '" + key + "' on hot reloading, " +
853 'manual reload is needed'
860 targetModule.getChild(key),
861 newModule.modules[key]
867 var functionAssert = {
868 assert: function (value) { return typeof value === 'function'; },
873 assert: function (value) { return typeof value === 'function' ||
874 (typeof value === 'object' && typeof value.handler === 'function'); },
875 expected: 'function or object with "handler" function'
879 getters: functionAssert,
880 mutations: functionAssert,
881 actions: objectAssert
884 function assertRawModule (path, rawModule) {
885 Object.keys(assertTypes).forEach(function (key) {
886 if (!rawModule[key]) { return }
888 var assertOptions = assertTypes[key];
890 forEachValue(rawModule[key], function (value, type) {
892 assertOptions.assert(value),
893 makeAssertionMessage(path, key, type, value, assertOptions.expected)
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('.')) + "\"";
904 buf += " is " + (JSON.stringify(value)) + ".";
908 function createStore (options) {
909 return new Store(options)
912 var Store = function Store (options) {
914 if ( options === void 0 ) options = {};
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.");
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;
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;
937 // bind commit and dispatch to self
940 var dispatch = ref.dispatch;
941 var commit = ref.commit;
942 this.dispatch = function boundDispatch (type, payload) {
943 return dispatch.call(store, type, payload)
945 this.commit = function boundCommit (type, payload, options) {
946 return commit.call(store, type, payload, options)
950 this.strict = strict;
952 var state = this._modules.root.state;
955 // this also recursively registers all sub-modules
956 // and collects all module getters inside this._wrappedGetters
957 installModule(this, state, [], this._modules.root);
959 // initialize the store state, which is responsible for the reactivity
960 // (also registers _wrappedGetters as computed properties)
961 resetStoreState(this, state);
964 plugins.forEach(function (plugin) { return plugin(this$1$1); });
967 var prototypeAccessors = { state: { configurable: true } };
969 Store.prototype.install = function install (app, injectKey) {
970 app.provide(injectKey || storeKey, this);
971 app.config.globalProperties.$store = this;
973 var useDevtools = this._devtools !== undefined
978 addDevtools(app, this);
982 prototypeAccessors.state.get = function () {
983 return this._state.data
986 prototypeAccessors.state.set = function (v) {
988 assert(false, "use store.replaceState() to explicit replace store state.");
992 Store.prototype.commit = function commit (_type, _payload, _options) {
995 // check object-style commit
996 var ref = unifyObjectStyle(_type, _payload, _options);
998 var payload = ref.payload;
999 var options = ref.options;
1001 var mutation = { type: type, payload: payload };
1002 var entry = this._mutations[type];
1005 console.error(("[vuex] unknown mutation type: " + type));
1009 this._withCommit(function () {
1010 entry.forEach(function commitIterator (handler) {
1016 .slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
1017 .forEach(function (sub) { return sub(mutation, this$1$1.state); });
1020 options && options.silent
1023 "[vuex] mutation type: " + type + ". Silent option has been removed. " +
1024 'Use the filter functionality in the vue-devtools'
1029 Store.prototype.dispatch = function dispatch (_type, _payload) {
1030 var this$1$1 = this;
1032 // check object-style dispatch
1033 var ref = unifyObjectStyle(_type, _payload);
1034 var type = ref.type;
1035 var payload = ref.payload;
1037 var action = { type: type, payload: payload };
1038 var entry = this._actions[type];
1041 console.error(("[vuex] unknown action type: " + type));
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); });
1053 console.warn("[vuex] error in before action subscribers: ");
1058 var result = entry.length > 1
1059 ? Promise.all(entry.map(function (handler) { return handler(payload); }))
1060 : entry[0](payload);
1062 return new Promise(function (resolve, reject) {
1063 result.then(function (res) {
1065 this$1$1._actionSubscribers
1066 .filter(function (sub) { return sub.after; })
1067 .forEach(function (sub) { return sub.after(action, this$1$1.state); });
1070 console.warn("[vuex] error in after action subscribers: ");
1075 }, function (error) {
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); });
1082 console.warn("[vuex] error in error action subscribers: ");
1091 Store.prototype.subscribe = function subscribe (fn, options) {
1092 return genericSubscribe(fn, this._subscribers, options)
1095 Store.prototype.subscribeAction = function subscribeAction (fn, options) {
1096 var subs = typeof fn === 'function' ? { before: fn } : fn;
1097 return genericSubscribe(subs, this._actionSubscribers, options)
1100 Store.prototype.watch = function watch$1 (getter, cb, options) {
1101 var this$1$1 = this;
1104 assert(typeof getter === 'function', "store.watch only accepts a function.");
1106 return vue.watch(function () { return getter(this$1$1.state, this$1$1.getters); }, cb, Object.assign({}, options))
1109 Store.prototype.replaceState = function replaceState (state) {
1110 var this$1$1 = this;
1112 this._withCommit(function () {
1113 this$1$1._state.data = state;
1117 Store.prototype.registerModule = function registerModule (path, rawModule, options) {
1118 if ( options === void 0 ) options = {};
1120 if (typeof path === 'string') { path = [path]; }
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.');
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);
1133 Store.prototype.unregisterModule = function unregisterModule (path) {
1134 var this$1$1 = this;
1136 if (typeof path === 'string') { path = [path]; }
1139 assert(Array.isArray(path), "module path must be a string or an Array.");
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]];
1150 Store.prototype.hasModule = function hasModule (path) {
1151 if (typeof path === 'string') { path = [path]; }
1154 assert(Array.isArray(path), "module path must be a string or an Array.");
1157 return this._modules.isRegistered(path)
1160 Store.prototype.hotUpdate = function hotUpdate (newOptions) {
1161 this._modules.update(newOptions);
1162 resetStore(this, true);
1165 Store.prototype._withCommit = function _withCommit (fn) {
1166 var committing = this._committing;
1167 this._committing = true;
1169 this._committing = committing;
1172 Object.defineProperties( Store.prototype, prototypeAccessors );
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.
1180 var mapState = normalizeNamespace(function (namespace, states) {
1182 if (!isValidMap(states)) {
1183 console.error('[vuex] mapState: mapper parameter must be either an Array or an Object');
1185 normalizeMap(states).forEach(function (ref) {
1189 res[key] = function mappedState () {
1190 var state = this.$store.state;
1191 var getters = this.$store.getters;
1193 var module = getModuleByNamespace(this.$store, 'mapState', namespace);
1197 state = module.context.state;
1198 getters = module.context.getters;
1200 return typeof val === 'function'
1201 ? val.call(this, state, getters)
1204 // mark vuex getter for devtools
1205 res[key].vuex = true;
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.
1216 var mapMutations = normalizeNamespace(function (namespace, mutations) {
1218 if (!isValidMap(mutations)) {
1219 console.error('[vuex] mapMutations: mapper parameter must be either an Array or an Object');
1221 normalizeMap(mutations).forEach(function (ref) {
1225 res[key] = function mappedMutation () {
1226 var args = [], len = arguments.length;
1227 while ( len-- ) args[ len ] = arguments[ len ];
1229 // Get the commit method from store
1230 var commit = this.$store.commit;
1232 var module = getModuleByNamespace(this.$store, 'mapMutations', namespace);
1236 commit = module.context.commit;
1238 return typeof val === 'function'
1239 ? val.apply(this, [commit].concat(args))
1240 : commit.apply(this.$store, [val].concat(args))
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
1252 var mapGetters = normalizeNamespace(function (namespace, getters) {
1254 if (!isValidMap(getters)) {
1255 console.error('[vuex] mapGetters: mapper parameter must be either an Array or an Object');
1257 normalizeMap(getters).forEach(function (ref) {
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)) {
1267 if (!(val in this.$store.getters)) {
1268 console.error(("[vuex] unknown getter: " + val));
1271 return this.$store.getters[val]
1273 // mark vuex getter for devtools
1274 res[key].vuex = true;
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.
1285 var mapActions = normalizeNamespace(function (namespace, actions) {
1287 if (!isValidMap(actions)) {
1288 console.error('[vuex] mapActions: mapper parameter must be either an Array or an Object');
1290 normalizeMap(actions).forEach(function (ref) {
1294 res[key] = function mappedAction () {
1295 var args = [], len = arguments.length;
1296 while ( len-- ) args[ len ] = arguments[ len ];
1298 // get dispatch function from store
1299 var dispatch = this.$store.dispatch;
1301 var module = getModuleByNamespace(this.$store, 'mapActions', namespace);
1305 dispatch = module.context.dispatch;
1307 return typeof val === 'function'
1308 ? val.apply(this, [dispatch].concat(args))
1309 : dispatch.apply(this.$store, [val].concat(args))
1316 * Rebinding namespace param for mapXXX function in special scoped, and return them by simple object
1317 * @param {String} namespace
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)
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
1334 function normalizeMap (map) {
1335 if (!isValidMap(map)) {
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] }); })
1344 * Validate whether given map is valid or not
1348 function isValidMap (map) {
1349 return Array.isArray(map) || isObject(map)
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}
1357 function normalizeNamespace (fn) {
1358 return function (namespace, map) {
1359 if (typeof namespace !== 'string') {
1362 } else if (namespace.charAt(namespace.length - 1) !== '/') {
1365 return fn(namespace, map)
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
1376 function getModuleByNamespace (store, helper, namespace) {
1377 var module = store._modulesNamespaceMap[namespace];
1379 console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
1384 // Credits: borrowed code from fcomb/redux-logger
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;
1398 return function (store) {
1399 var prevState = deepCopy(store.state);
1401 if (typeof logger === 'undefined') {
1406 store.subscribe(function (mutation, state) {
1407 var nextState = deepCopy(state);
1409 if (filter(mutation, prevState, nextState)) {
1410 var formattedTime = getFormattedTime();
1411 var formattedMutation = mutationTransformer(mutation);
1412 var message = "mutation " + (mutation.type) + formattedTime;
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));
1421 prevState = nextState;
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;
1432 startMessage(logger, message, collapsed);
1433 logger.log('%c action', 'color: #03A9F4; font-weight: bold', formattedAction);
1441 function startMessage (logger, message, collapsed) {
1442 var startMessage = collapsed
1443 ? logger.groupCollapsed
1448 startMessage.call(logger, message);
1450 logger.log(message);
1454 function endMessage (logger) {
1458 logger.log('—— log end ——');
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)))
1467 function repeat (str, times) {
1468 return (new Array(times + 1)).join(str)
1471 function pad (num, maxLength) {
1472 return repeat('0', maxLength - num.toString().length) + num
1479 createStore: createStore,
1482 mapMutations: mapMutations,
1483 mapGetters: mapGetters,
1484 mapActions: mapActions,
1485 createNamespacedHelpers: createNamespacedHelpers,
1486 createLogger: createLogger