UNPKG

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