UNPKG

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