UNPKG

24.5 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
7var $$observable = _interopDefault(require('symbol-observable'));
8
9/**
10 * These are private action types reserved by Redux.
11 * For any unknown actions, you must return the current state.
12 * If the current state is undefined, you must return the initial state.
13 * Do not reference these action types directly in your code.
14 */
15var randomString = function randomString() {
16 return Math.random().toString(36).substring(7).split('').join('.');
17};
18
19var ActionTypes = {
20 INIT: "@@redux/INIT" + randomString(),
21 REPLACE: "@@redux/REPLACE" + randomString(),
22 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
23 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
24 }
25};
26
27/**
28 * @param {any} obj The object to inspect.
29 * @returns {boolean} True if the argument appears to be a plain object.
30 */
31function isPlainObject(obj) {
32 if (typeof obj !== 'object' || obj === null) return false;
33 var proto = obj;
34
35 while (Object.getPrototypeOf(proto) !== null) {
36 proto = Object.getPrototypeOf(proto);
37 }
38
39 return Object.getPrototypeOf(obj) === proto;
40}
41
42/**
43 * Creates a Redux store that holds the state tree.
44 * The only way to change the data in the store is to call `dispatch()` on it.
45 *
46 * There should only be a single store in your app. To specify how different
47 * parts of the state tree respond to actions, you may combine several reducers
48 * into a single reducer function by using `combineReducers`.
49 *
50 * @param {Function} reducer A function that returns the next state tree, given
51 * the current state tree and the action to handle.
52 *
53 * @param {any} [preloadedState] The initial state. You may optionally specify it
54 * to hydrate the state from the server in universal apps, or to restore a
55 * previously serialized user session.
56 * If you use `combineReducers` to produce the root reducer function, this must be
57 * an object with the same shape as `combineReducers` keys.
58 *
59 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
60 * to enhance the store with third-party capabilities such as middleware,
61 * time travel, persistence, etc. The only store enhancer that ships with Redux
62 * is `applyMiddleware()`.
63 *
64 * @returns {Store} A Redux store that lets you read the state, dispatch actions
65 * and subscribe to changes.
66 */
67
68function createStore(reducer, preloadedState, enhancer) {
69 var _ref2;
70
71 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
72 throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function.');
73 }
74
75 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
76 enhancer = preloadedState;
77 preloadedState = undefined;
78 }
79
80 if (typeof enhancer !== 'undefined') {
81 if (typeof enhancer !== 'function') {
82 throw new Error('Expected the enhancer to be a function.');
83 }
84
85 return enhancer(createStore)(reducer, preloadedState);
86 }
87
88 if (typeof reducer !== 'function') {
89 throw new Error('Expected the reducer to be a function.');
90 }
91
92 var currentReducer = reducer;
93 var currentState = preloadedState;
94 var currentListeners = [];
95 var nextListeners = currentListeners;
96 var isDispatching = false;
97 /**
98 * This makes a shallow copy of currentListeners so we can use
99 * nextListeners as a temporary list while dispatching.
100 *
101 * This prevents any bugs around consumers calling
102 * subscribe/unsubscribe in the middle of a dispatch.
103 */
104
105 function ensureCanMutateNextListeners() {
106 if (nextListeners === currentListeners) {
107 nextListeners = currentListeners.slice();
108 }
109 }
110 /**
111 * Reads the state tree managed by the store.
112 *
113 * @returns {any} The current state tree of your application.
114 */
115
116
117 function getState() {
118 if (isDispatching) {
119 throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
120 }
121
122 return currentState;
123 }
124 /**
125 * Adds a change listener. It will be called any time an action is dispatched,
126 * and some part of the state tree may potentially have changed. You may then
127 * call `getState()` to read the current state tree inside the callback.
128 *
129 * You may call `dispatch()` from a change listener, with the following
130 * caveats:
131 *
132 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
133 * If you subscribe or unsubscribe while the listeners are being invoked, this
134 * will not have any effect on the `dispatch()` that is currently in progress.
135 * However, the next `dispatch()` call, whether nested or not, will use a more
136 * recent snapshot of the subscription list.
137 *
138 * 2. The listener should not expect to see all state changes, as the state
139 * might have been updated multiple times during a nested `dispatch()` before
140 * the listener is called. It is, however, guaranteed that all subscribers
141 * registered before the `dispatch()` started will be called with the latest
142 * state by the time it exits.
143 *
144 * @param {Function} listener A callback to be invoked on every dispatch.
145 * @returns {Function} A function to remove this change listener.
146 */
147
148
149 function subscribe(listener) {
150 if (typeof listener !== 'function') {
151 throw new Error('Expected the listener to be a function.');
152 }
153
154 if (isDispatching) {
155 throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
156 }
157
158 var isSubscribed = true;
159 ensureCanMutateNextListeners();
160 nextListeners.push(listener);
161 return function unsubscribe() {
162 if (!isSubscribed) {
163 return;
164 }
165
166 if (isDispatching) {
167 throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
168 }
169
170 isSubscribed = false;
171 ensureCanMutateNextListeners();
172 var index = nextListeners.indexOf(listener);
173 nextListeners.splice(index, 1);
174 currentListeners = null;
175 };
176 }
177 /**
178 * Dispatches an action. It is the only way to trigger a state change.
179 *
180 * The `reducer` function, used to create the store, will be called with the
181 * current state tree and the given `action`. Its return value will
182 * be considered the **next** state of the tree, and the change listeners
183 * will be notified.
184 *
185 * The base implementation only supports plain object actions. If you want to
186 * dispatch a Promise, an Observable, a thunk, or something else, you need to
187 * wrap your store creating function into the corresponding middleware. For
188 * example, see the documentation for the `redux-thunk` package. Even the
189 * middleware will eventually dispatch plain object actions using this method.
190 *
191 * @param {Object} action A plain object representing “what changed”. It is
192 * a good idea to keep actions serializable so you can record and replay user
193 * sessions, or use the time travelling `redux-devtools`. An action must have
194 * a `type` property which may not be `undefined`. It is a good idea to use
195 * string constants for action types.
196 *
197 * @returns {Object} For convenience, the same action object you dispatched.
198 *
199 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
200 * return something else (for example, a Promise you can await).
201 */
202
203
204 function dispatch(action) {
205 if (!isPlainObject(action)) {
206 throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
207 }
208
209 if (typeof action.type === 'undefined') {
210 throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
211 }
212
213 if (isDispatching) {
214 throw new Error('Reducers may not dispatch actions.');
215 }
216
217 try {
218 isDispatching = true;
219 currentState = currentReducer(currentState, action);
220 } finally {
221 isDispatching = false;
222 }
223
224 var listeners = currentListeners = nextListeners;
225
226 for (var i = 0; i < listeners.length; i++) {
227 var listener = listeners[i];
228 listener();
229 }
230
231 return action;
232 }
233 /**
234 * Replaces the reducer currently used by the store to calculate the state.
235 *
236 * You might need this if your app implements code splitting and you want to
237 * load some of the reducers dynamically. You might also need this if you
238 * implement a hot reloading mechanism for Redux.
239 *
240 * @param {Function} nextReducer The reducer for the store to use instead.
241 * @returns {void}
242 */
243
244
245 function replaceReducer(nextReducer) {
246 if (typeof nextReducer !== 'function') {
247 throw new Error('Expected the nextReducer to be a function.');
248 }
249
250 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
251 // Any reducers that existed in both the new and old rootReducer
252 // will receive the previous state. This effectively populates
253 // the new state tree with any relevant data from the old one.
254
255 dispatch({
256 type: ActionTypes.REPLACE
257 });
258 }
259 /**
260 * Interoperability point for observable/reactive libraries.
261 * @returns {observable} A minimal observable of state changes.
262 * For more information, see the observable proposal:
263 * https://github.com/tc39/proposal-observable
264 */
265
266
267 function observable() {
268 var _ref;
269
270 var outerSubscribe = subscribe;
271 return _ref = {
272 /**
273 * The minimal observable subscription method.
274 * @param {Object} observer Any object that can be used as an observer.
275 * The observer object should have a `next` method.
276 * @returns {subscription} An object with an `unsubscribe` method that can
277 * be used to unsubscribe the observable from the store, and prevent further
278 * emission of values from the observable.
279 */
280 subscribe: function subscribe(observer) {
281 if (typeof observer !== 'object' || observer === null) {
282 throw new TypeError('Expected the observer to be an object.');
283 }
284
285 function observeState() {
286 if (observer.next) {
287 observer.next(getState());
288 }
289 }
290
291 observeState();
292 var unsubscribe = outerSubscribe(observeState);
293 return {
294 unsubscribe: unsubscribe
295 };
296 }
297 }, _ref[$$observable] = function () {
298 return this;
299 }, _ref;
300 } // When a store is created, an "INIT" action is dispatched so that every
301 // reducer returns their initial state. This effectively populates
302 // the initial state tree.
303
304
305 dispatch({
306 type: ActionTypes.INIT
307 });
308 return _ref2 = {
309 dispatch: dispatch,
310 subscribe: subscribe,
311 getState: getState,
312 replaceReducer: replaceReducer
313 }, _ref2[$$observable] = observable, _ref2;
314}
315
316/**
317 * Prints a warning in the console if it exists.
318 *
319 * @param {String} message The warning message.
320 * @returns {void}
321 */
322function warning(message) {
323 /* eslint-disable no-console */
324 if (typeof console !== 'undefined' && typeof console.error === 'function') {
325 console.error(message);
326 }
327 /* eslint-enable no-console */
328
329
330 try {
331 // This error was thrown as a convenience so that if you enable
332 // "break on all exceptions" in your console,
333 // it would pause the execution at this line.
334 throw new Error(message);
335 } catch (e) {} // eslint-disable-line no-empty
336
337}
338
339function getUndefinedStateErrorMessage(key, action) {
340 var actionType = action && action.type;
341 var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action';
342 return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.";
343}
344
345function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
346 var reducerKeys = Object.keys(reducers);
347 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
348
349 if (reducerKeys.length === 0) {
350 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
351 }
352
353 if (!isPlainObject(inputState)) {
354 return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
355 }
356
357 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
358 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
359 });
360 unexpectedKeys.forEach(function (key) {
361 unexpectedKeyCache[key] = true;
362 });
363 if (action && action.type === ActionTypes.REPLACE) return;
364
365 if (unexpectedKeys.length > 0) {
366 return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
367 }
368}
369
370function assertReducerShape(reducers) {
371 Object.keys(reducers).forEach(function (key) {
372 var reducer = reducers[key];
373 var initialState = reducer(undefined, {
374 type: ActionTypes.INIT
375 });
376
377 if (typeof initialState === 'undefined') {
378 throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
379 }
380
381 if (typeof reducer(undefined, {
382 type: ActionTypes.PROBE_UNKNOWN_ACTION()
383 }) === 'undefined') {
384 throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
385 }
386 });
387}
388/**
389 * Turns an object whose values are different reducer functions, into a single
390 * reducer function. It will call every child reducer, and gather their results
391 * into a single state object, whose keys correspond to the keys of the passed
392 * reducer functions.
393 *
394 * @param {Object} reducers An object whose values correspond to different
395 * reducer functions that need to be combined into one. One handy way to obtain
396 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
397 * undefined for any action. Instead, they should return their initial state
398 * if the state passed to them was undefined, and the current state for any
399 * unrecognized action.
400 *
401 * @returns {Function} A reducer function that invokes every reducer inside the
402 * passed object, and builds a state object with the same shape.
403 */
404
405
406function combineReducers(reducers) {
407 var reducerKeys = Object.keys(reducers);
408 var finalReducers = {};
409
410 for (var i = 0; i < reducerKeys.length; i++) {
411 var key = reducerKeys[i];
412
413 if (process.env.NODE_ENV !== 'production') {
414 if (typeof reducers[key] === 'undefined') {
415 warning("No reducer provided for key \"" + key + "\"");
416 }
417 }
418
419 if (typeof reducers[key] === 'function') {
420 finalReducers[key] = reducers[key];
421 }
422 }
423
424 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
425 // keys multiple times.
426
427 var unexpectedKeyCache;
428
429 if (process.env.NODE_ENV !== 'production') {
430 unexpectedKeyCache = {};
431 }
432
433 var shapeAssertionError;
434
435 try {
436 assertReducerShape(finalReducers);
437 } catch (e) {
438 shapeAssertionError = e;
439 }
440
441 return function combination(state, action) {
442 if (state === void 0) {
443 state = {};
444 }
445
446 if (shapeAssertionError) {
447 throw shapeAssertionError;
448 }
449
450 if (process.env.NODE_ENV !== 'production') {
451 var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
452
453 if (warningMessage) {
454 warning(warningMessage);
455 }
456 }
457
458 var hasChanged = false;
459 var nextState = {};
460
461 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
462 var _key = finalReducerKeys[_i];
463 var reducer = finalReducers[_key];
464 var previousStateForKey = state[_key];
465 var nextStateForKey = reducer(previousStateForKey, action);
466
467 if (typeof nextStateForKey === 'undefined') {
468 var errorMessage = getUndefinedStateErrorMessage(_key, action);
469 throw new Error(errorMessage);
470 }
471
472 nextState[_key] = nextStateForKey;
473 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
474 }
475
476 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
477 return hasChanged ? nextState : state;
478 };
479}
480
481function bindActionCreator(actionCreator, dispatch) {
482 return function () {
483 return dispatch(actionCreator.apply(this, arguments));
484 };
485}
486/**
487 * Turns an object whose values are action creators, into an object with the
488 * same keys, but with every function wrapped into a `dispatch` call so they
489 * may be invoked directly. This is just a convenience method, as you can call
490 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
491 *
492 * For convenience, you can also pass an action creator as the first argument,
493 * and get a dispatch wrapped function in return.
494 *
495 * @param {Function|Object} actionCreators An object whose values are action
496 * creator functions. One handy way to obtain it is to use ES6 `import * as`
497 * syntax. You may also pass a single function.
498 *
499 * @param {Function} dispatch The `dispatch` function available on your Redux
500 * store.
501 *
502 * @returns {Function|Object} The object mimicking the original object, but with
503 * every action creator wrapped into the `dispatch` call. If you passed a
504 * function as `actionCreators`, the return value will also be a single
505 * function.
506 */
507
508
509function bindActionCreators(actionCreators, dispatch) {
510 if (typeof actionCreators === 'function') {
511 return bindActionCreator(actionCreators, dispatch);
512 }
513
514 if (typeof actionCreators !== 'object' || actionCreators === null) {
515 throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
516 }
517
518 var boundActionCreators = {};
519
520 for (var key in actionCreators) {
521 var actionCreator = actionCreators[key];
522
523 if (typeof actionCreator === 'function') {
524 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
525 }
526 }
527
528 return boundActionCreators;
529}
530
531function _defineProperty(obj, key, value) {
532 if (key in obj) {
533 Object.defineProperty(obj, key, {
534 value: value,
535 enumerable: true,
536 configurable: true,
537 writable: true
538 });
539 } else {
540 obj[key] = value;
541 }
542
543 return obj;
544}
545
546function ownKeys(object, enumerableOnly) {
547 var keys = Object.keys(object);
548
549 if (Object.getOwnPropertySymbols) {
550 keys.push.apply(keys, Object.getOwnPropertySymbols(object));
551 }
552
553 if (enumerableOnly) keys = keys.filter(function (sym) {
554 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
555 });
556 return keys;
557}
558
559function _objectSpread2(target) {
560 for (var i = 1; i < arguments.length; i++) {
561 var source = arguments[i] != null ? arguments[i] : {};
562
563 if (i % 2) {
564 ownKeys(source, true).forEach(function (key) {
565 _defineProperty(target, key, source[key]);
566 });
567 } else if (Object.getOwnPropertyDescriptors) {
568 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
569 } else {
570 ownKeys(source).forEach(function (key) {
571 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
572 });
573 }
574 }
575
576 return target;
577}
578
579/**
580 * Composes single-argument functions from right to left. The rightmost
581 * function can take multiple arguments as it provides the signature for
582 * the resulting composite function.
583 *
584 * @param {...Function} funcs The functions to compose.
585 * @returns {Function} A function obtained by composing the argument functions
586 * from right to left. For example, compose(f, g, h) is identical to doing
587 * (...args) => f(g(h(...args))).
588 */
589function compose() {
590 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
591 funcs[_key] = arguments[_key];
592 }
593
594 if (funcs.length === 0) {
595 return function (arg) {
596 return arg;
597 };
598 }
599
600 if (funcs.length === 1) {
601 return funcs[0];
602 }
603
604 return funcs.reduce(function (a, b) {
605 return function () {
606 return a(b.apply(void 0, arguments));
607 };
608 });
609}
610
611/**
612 * Creates a store enhancer that applies middleware to the dispatch method
613 * of the Redux store. This is handy for a variety of tasks, such as expressing
614 * asynchronous actions in a concise manner, or logging every action payload.
615 *
616 * See `redux-thunk` package as an example of the Redux middleware.
617 *
618 * Because middleware is potentially asynchronous, this should be the first
619 * store enhancer in the composition chain.
620 *
621 * Note that each middleware will be given the `dispatch` and `getState` functions
622 * as named arguments.
623 *
624 * @param {...Function} middlewares The middleware chain to be applied.
625 * @returns {Function} A store enhancer applying the middleware.
626 */
627
628function applyMiddleware() {
629 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
630 middlewares[_key] = arguments[_key];
631 }
632
633 return function (createStore) {
634 return function () {
635 var store = createStore.apply(void 0, arguments);
636
637 var _dispatch = function dispatch() {
638 throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
639 };
640
641 var middlewareAPI = {
642 getState: store.getState,
643 dispatch: function dispatch() {
644 return _dispatch.apply(void 0, arguments);
645 }
646 };
647 var chain = middlewares.map(function (middleware) {
648 return middleware(middlewareAPI);
649 });
650 _dispatch = compose.apply(void 0, chain)(store.dispatch);
651 return _objectSpread2({}, store, {
652 dispatch: _dispatch
653 });
654 };
655 };
656}
657
658/*
659 * This is a dummy function to check if the function name has been altered by minification.
660 * If the function has been minified and NODE_ENV !== 'production', warn the user.
661 */
662
663function isCrushed() {}
664
665if (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
666 warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
667}
668
669exports.__DO_NOT_USE__ActionTypes = ActionTypes;
670exports.applyMiddleware = applyMiddleware;
671exports.bindActionCreators = bindActionCreators;
672exports.combineReducers = combineReducers;
673exports.compose = compose;
674exports.createStore = createStore;