PluginProbe
Gutenberg / 12.1.0
Gutenberg v12.1.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / data / index.js

index.js in Gutenberg 12.1.0, at build/data/index.js

4,048 lines 125.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (function() { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ 3909:
5 /***/ (function(module) {
6
7 "use strict";
8
9
10 function _typeof(obj) {
11 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
12 _typeof = function (obj) {
13 return typeof obj;
14 };
15 } else {
16 _typeof = function (obj) {
17 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
18 };
19 }
20
21 return _typeof(obj);
22 }
23
24 function _classCallCheck(instance, Constructor) {
25 if (!(instance instanceof Constructor)) {
26 throw new TypeError("Cannot call a class as a function");
27 }
28 }
29
30 function _defineProperties(target, props) {
31 for (var i = 0; i < props.length; i++) {
32 var descriptor = props[i];
33 descriptor.enumerable = descriptor.enumerable || false;
34 descriptor.configurable = true;
35 if ("value" in descriptor) descriptor.writable = true;
36 Object.defineProperty(target, descriptor.key, descriptor);
37 }
38 }
39
40 function _createClass(Constructor, protoProps, staticProps) {
41 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
42 if (staticProps) _defineProperties(Constructor, staticProps);
43 return Constructor;
44 }
45
46 /**
47 * Given an instance of EquivalentKeyMap, returns its internal value pair tuple
48 * for a key, if one exists. The tuple members consist of the last reference
49 * value for the key (used in efficient subsequent lookups) and the value
50 * assigned for the key at the leaf node.
51 *
52 * @param {EquivalentKeyMap} instance EquivalentKeyMap instance.
53 * @param {*} key The key for which to return value pair.
54 *
55 * @return {?Array} Value pair, if exists.
56 */
57 function getValuePair(instance, key) {
58 var _map = instance._map,
59 _arrayTreeMap = instance._arrayTreeMap,
60 _objectTreeMap = instance._objectTreeMap; // Map keeps a reference to the last object-like key used to set the
61 // value, which can be used to shortcut immediately to the value.
62
63 if (_map.has(key)) {
64 return _map.get(key);
65 } // Sort keys to ensure stable retrieval from tree.
66
67
68 var properties = Object.keys(key).sort(); // Tree by type to avoid conflicts on numeric object keys, empty value.
69
70 var map = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
71
72 for (var i = 0; i < properties.length; i++) {
73 var property = properties[i];
74 map = map.get(property);
75
76 if (map === undefined) {
77 return;
78 }
79
80 var propertyValue = key[property];
81 map = map.get(propertyValue);
82
83 if (map === undefined) {
84 return;
85 }
86 }
87
88 var valuePair = map.get('_ekm_value');
89
90 if (!valuePair) {
91 return;
92 } // If reached, it implies that an object-like key was set with another
93 // reference, so delete the reference and replace with the current.
94
95
96 _map.delete(valuePair[0]);
97
98 valuePair[0] = key;
99 map.set('_ekm_value', valuePair);
100
101 _map.set(key, valuePair);
102
103 return valuePair;
104 }
105 /**
106 * Variant of a Map object which enables lookup by equivalent (deeply equal)
107 * object and array keys.
108 */
109
110
111 var EquivalentKeyMap =
112 /*#__PURE__*/
113 function () {
114 /**
115 * Constructs a new instance of EquivalentKeyMap.
116 *
117 * @param {Iterable.<*>} iterable Initial pair of key, value for map.
118 */
119 function EquivalentKeyMap(iterable) {
120 _classCallCheck(this, EquivalentKeyMap);
121
122 this.clear();
123
124 if (iterable instanceof EquivalentKeyMap) {
125 // Map#forEach is only means of iterating with support for IE11.
126 var iterablePairs = [];
127 iterable.forEach(function (value, key) {
128 iterablePairs.push([key, value]);
129 });
130 iterable = iterablePairs;
131 }
132
133 if (iterable != null) {
134 for (var i = 0; i < iterable.length; i++) {
135 this.set(iterable[i][0], iterable[i][1]);
136 }
137 }
138 }
139 /**
140 * Accessor property returning the number of elements.
141 *
142 * @return {number} Number of elements.
143 */
144
145
146 _createClass(EquivalentKeyMap, [{
147 key: "set",
148
149 /**
150 * Add or update an element with a specified key and value.
151 *
152 * @param {*} key The key of the element to add.
153 * @param {*} value The value of the element to add.
154 *
155 * @return {EquivalentKeyMap} Map instance.
156 */
157 value: function set(key, value) {
158 // Shortcut non-object-like to set on internal Map.
159 if (key === null || _typeof(key) !== 'object') {
160 this._map.set(key, value);
161
162 return this;
163 } // Sort keys to ensure stable assignment into tree.
164
165
166 var properties = Object.keys(key).sort();
167 var valuePair = [key, value]; // Tree by type to avoid conflicts on numeric object keys, empty value.
168
169 var map = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
170
171 for (var i = 0; i < properties.length; i++) {
172 var property = properties[i];
173
174 if (!map.has(property)) {
175 map.set(property, new EquivalentKeyMap());
176 }
177
178 map = map.get(property);
179 var propertyValue = key[property];
180
181 if (!map.has(propertyValue)) {
182 map.set(propertyValue, new EquivalentKeyMap());
183 }
184
185 map = map.get(propertyValue);
186 } // If an _ekm_value exists, there was already an equivalent key. Before
187 // overriding, ensure that the old key reference is removed from map to
188 // avoid memory leak of accumulating equivalent keys. This is, in a
189 // sense, a poor man's WeakMap, while still enabling iterability.
190
191
192 var previousValuePair = map.get('_ekm_value');
193
194 if (previousValuePair) {
195 this._map.delete(previousValuePair[0]);
196 }
197
198 map.set('_ekm_value', valuePair);
199
200 this._map.set(key, valuePair);
201
202 return this;
203 }
204 /**
205 * Returns a specified element.
206 *
207 * @param {*} key The key of the element to return.
208 *
209 * @return {?*} The element associated with the specified key or undefined
210 * if the key can't be found.
211 */
212
213 }, {
214 key: "get",
215 value: function get(key) {
216 // Shortcut non-object-like to get from internal Map.
217 if (key === null || _typeof(key) !== 'object') {
218 return this._map.get(key);
219 }
220
221 var valuePair = getValuePair(this, key);
222
223 if (valuePair) {
224 return valuePair[1];
225 }
226 }
227 /**
228 * Returns a boolean indicating whether an element with the specified key
229 * exists or not.
230 *
231 * @param {*} key The key of the element to test for presence.
232 *
233 * @return {boolean} Whether an element with the specified key exists.
234 */
235
236 }, {
237 key: "has",
238 value: function has(key) {
239 if (key === null || _typeof(key) !== 'object') {
240 return this._map.has(key);
241 } // Test on the _presence_ of the pair, not its value, as even undefined
242 // can be a valid member value for a key.
243
244
245 return getValuePair(this, key) !== undefined;
246 }
247 /**
248 * Removes the specified element.
249 *
250 * @param {*} key The key of the element to remove.
251 *
252 * @return {boolean} Returns true if an element existed and has been
253 * removed, or false if the element does not exist.
254 */
255
256 }, {
257 key: "delete",
258 value: function _delete(key) {
259 if (!this.has(key)) {
260 return false;
261 } // This naive implementation will leave orphaned child trees. A better
262 // implementation should traverse and remove orphans.
263
264
265 this.set(key, undefined);
266 return true;
267 }
268 /**
269 * Executes a provided function once per each key/value pair, in insertion
270 * order.
271 *
272 * @param {Function} callback Function to execute for each element.
273 * @param {*} thisArg Value to use as `this` when executing
274 * `callback`.
275 */
276
277 }, {
278 key: "forEach",
279 value: function forEach(callback) {
280 var _this = this;
281
282 var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
283
284 this._map.forEach(function (value, key) {
285 // Unwrap value from object-like value pair.
286 if (key !== null && _typeof(key) === 'object') {
287 value = value[1];
288 }
289
290 callback.call(thisArg, value, key, _this);
291 });
292 }
293 /**
294 * Removes all elements.
295 */
296
297 }, {
298 key: "clear",
299 value: function clear() {
300 this._map = new Map();
301 this._arrayTreeMap = new Map();
302 this._objectTreeMap = new Map();
303 }
304 }, {
305 key: "size",
306 get: function get() {
307 return this._map.size;
308 }
309 }]);
310
311 return EquivalentKeyMap;
312 }();
313
314 module.exports = EquivalentKeyMap;
315
316
317 /***/ }),
318
319 /***/ 9884:
320 /***/ (function(module) {
321
322 function combineReducers( reducers ) {
323 var keys = Object.keys( reducers ),
324 getNextState;
325
326 getNextState = ( function() {
327 var fn, i, key;
328
329 fn = 'return {';
330 for ( i = 0; i < keys.length; i++ ) {
331 // Rely on Quoted escaping of JSON.stringify with guarantee that
332 // each member of Object.keys is a string.
333 //
334 // "If Type(value) is String, then return the result of calling the
335 // abstract operation Quote with argument value. [...] The abstract
336 // operation Quote(value) wraps a String value in double quotes and
337 // escapes characters within it."
338 //
339 // https://www.ecma-international.org/ecma-262/5.1/#sec-15.12.3
340 key = JSON.stringify( keys[ i ] );
341
342 fn += key + ':r[' + key + '](s[' + key + '],a),';
343 }
344 fn += '}';
345
346 return new Function( 'r,s,a', fn );
347 } )();
348
349 return function combinedReducer( state, action ) {
350 var nextState, i, key;
351
352 // Assumed changed if initial state.
353 if ( state === undefined ) {
354 return getNextState( reducers, {}, action );
355 }
356
357 nextState = getNextState( reducers, state, action );
358
359 // Determine whether state has changed.
360 i = keys.length;
361 while ( i-- ) {
362 key = keys[ i ];
363 if ( state[ key ] !== nextState[ key ] ) {
364 // Return immediately if a changed value is encountered.
365 return nextState;
366 }
367 }
368
369 return state;
370 };
371 }
372
373 module.exports = combineReducers;
374
375
376 /***/ })
377
378 /******/ });
379 /************************************************************************/
380 /******/ // The module cache
381 /******/ var __webpack_module_cache__ = {};
382 /******/
383 /******/ // The require function
384 /******/ function __webpack_require__(moduleId) {
385 /******/ // Check if module is in cache
386 /******/ var cachedModule = __webpack_module_cache__[moduleId];
387 /******/ if (cachedModule !== undefined) {
388 /******/ return cachedModule.exports;
389 /******/ }
390 /******/ // Create a new module (and put it into the cache)
391 /******/ var module = __webpack_module_cache__[moduleId] = {
392 /******/ // no module.id needed
393 /******/ // no module.loaded needed
394 /******/ exports: {}
395 /******/ };
396 /******/
397 /******/ // Execute the module function
398 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
399 /******/
400 /******/ // Return the exports of the module
401 /******/ return module.exports;
402 /******/ }
403 /******/
404 /************************************************************************/
405 /******/ /* webpack/runtime/compat get default export */
406 /******/ !function() {
407 /******/ // getDefaultExport function for compatibility with non-harmony modules
408 /******/ __webpack_require__.n = function(module) {
409 /******/ var getter = module && module.__esModule ?
410 /******/ function() { return module['default']; } :
411 /******/ function() { return module; };
412 /******/ __webpack_require__.d(getter, { a: getter });
413 /******/ return getter;
414 /******/ };
415 /******/ }();
416 /******/
417 /******/ /* webpack/runtime/define property getters */
418 /******/ !function() {
419 /******/ // define getter functions for harmony exports
420 /******/ __webpack_require__.d = function(exports, definition) {
421 /******/ for(var key in definition) {
422 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
423 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
424 /******/ }
425 /******/ }
426 /******/ };
427 /******/ }();
428 /******/
429 /******/ /* webpack/runtime/hasOwnProperty shorthand */
430 /******/ !function() {
431 /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
432 /******/ }();
433 /******/
434 /******/ /* webpack/runtime/make namespace object */
435 /******/ !function() {
436 /******/ // define __esModule on exports
437 /******/ __webpack_require__.r = function(exports) {
438 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
439 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
440 /******/ }
441 /******/ Object.defineProperty(exports, '__esModule', { value: true });
442 /******/ };
443 /******/ }();
444 /******/
445 /************************************************************************/
446 var __webpack_exports__ = {};
447 // This entry need to be wrapped in an IIFE because it need to be in strict mode.
448 !function() {
449 "use strict";
450 // ESM COMPAT FLAG
451 __webpack_require__.r(__webpack_exports__);
452
453 // EXPORTS
454 __webpack_require__.d(__webpack_exports__, {
455 "AsyncModeProvider": function() { return /* reexport */ async_mode_provider_context; },
456 "RegistryConsumer": function() { return /* reexport */ RegistryConsumer; },
457 "RegistryProvider": function() { return /* reexport */ context; },
458 "combineReducers": function() { return /* reexport */ (turbo_combine_reducers_default()); },
459 "controls": function() { return /* reexport */ controls; },
460 "createReduxStore": function() { return /* reexport */ createReduxStore; },
461 "createRegistry": function() { return /* reexport */ createRegistry; },
462 "createRegistryControl": function() { return /* reexport */ createRegistryControl; },
463 "createRegistrySelector": function() { return /* reexport */ createRegistrySelector; },
464 "dispatch": function() { return /* binding */ build_module_dispatch; },
465 "plugins": function() { return /* reexport */ plugins_namespaceObject; },
466 "register": function() { return /* binding */ register; },
467 "registerGenericStore": function() { return /* binding */ registerGenericStore; },
468 "registerStore": function() { return /* binding */ registerStore; },
469 "resolveSelect": function() { return /* binding */ build_module_resolveSelect; },
470 "select": function() { return /* binding */ build_module_select; },
471 "subscribe": function() { return /* binding */ subscribe; },
472 "use": function() { return /* binding */ use; },
473 "useDispatch": function() { return /* reexport */ use_dispatch; },
474 "useRegistry": function() { return /* reexport */ useRegistry; },
475 "useSelect": function() { return /* reexport */ useSelect; },
476 "withDispatch": function() { return /* reexport */ with_dispatch; },
477 "withRegistry": function() { return /* reexport */ with_registry; },
478 "withSelect": function() { return /* reexport */ with_select; }
479 });
480
481 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/selectors.js
482 var selectors_namespaceObject = {};
483 __webpack_require__.r(selectors_namespaceObject);
484 __webpack_require__.d(selectors_namespaceObject, {
485 "getCachedResolvers": function() { return getCachedResolvers; },
486 "getIsResolving": function() { return getIsResolving; },
487 "hasFinishedResolution": function() { return hasFinishedResolution; },
488 "hasStartedResolution": function() { return hasStartedResolution; },
489 "isResolving": function() { return isResolving; }
490 });
491
492 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/actions.js
493 var actions_namespaceObject = {};
494 __webpack_require__.r(actions_namespaceObject);
495 __webpack_require__.d(actions_namespaceObject, {
496 "finishResolution": function() { return finishResolution; },
497 "finishResolutions": function() { return finishResolutions; },
498 "invalidateResolution": function() { return invalidateResolution; },
499 "invalidateResolutionForStore": function() { return invalidateResolutionForStore; },
500 "invalidateResolutionForStoreSelector": function() { return invalidateResolutionForStoreSelector; },
501 "startResolution": function() { return startResolution; },
502 "startResolutions": function() { return startResolutions; }
503 });
504
505 // NAMESPACE OBJECT: ./packages/data/build-module/plugins/index.js
506 var plugins_namespaceObject = {};
507 __webpack_require__.r(plugins_namespaceObject);
508 __webpack_require__.d(plugins_namespaceObject, {
509 "controls": function() { return plugins_controls; },
510 "persistence": function() { return persistence; }
511 });
512
513 // EXTERNAL MODULE: ./node_modules/turbo-combine-reducers/index.js
514 var turbo_combine_reducers = __webpack_require__(9884);
515 var turbo_combine_reducers_default = /*#__PURE__*/__webpack_require__.n(turbo_combine_reducers);
516 ;// CONCATENATED MODULE: external "lodash"
517 var external_lodash_namespaceObject = window["lodash"];
518 ;// CONCATENATED MODULE: external ["wp","deprecated"]
519 var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
520 var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
521 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
522 function _defineProperty(obj, key, value) {
523 if (key in obj) {
524 Object.defineProperty(obj, key, {
525 value: value,
526 enumerable: true,
527 configurable: true,
528 writable: true
529 });
530 } else {
531 obj[key] = value;
532 }
533
534 return obj;
535 }
536 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
537
538
539 function ownKeys(object, enumerableOnly) {
540 var keys = Object.keys(object);
541
542 if (Object.getOwnPropertySymbols) {
543 var symbols = Object.getOwnPropertySymbols(object);
544
545 if (enumerableOnly) {
546 symbols = symbols.filter(function (sym) {
547 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
548 });
549 }
550
551 keys.push.apply(keys, symbols);
552 }
553
554 return keys;
555 }
556
557 function _objectSpread2(target) {
558 for (var i = 1; i < arguments.length; i++) {
559 var source = arguments[i] != null ? arguments[i] : {};
560
561 if (i % 2) {
562 ownKeys(Object(source), true).forEach(function (key) {
563 _defineProperty(target, key, source[key]);
564 });
565 } else if (Object.getOwnPropertyDescriptors) {
566 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
567 } else {
568 ownKeys(Object(source)).forEach(function (key) {
569 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
570 });
571 }
572 }
573
574 return target;
575 }
576 ;// CONCATENATED MODULE: ./node_modules/redux/es/redux.js
577
578
579 /**
580 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
581 *
582 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
583 * during build.
584 * @param {number} code
585 */
586 function formatProdErrorMessage(code) {
587 return "Minified Redux error #" + code + "; visit https://redux.js.org/Errors?code=" + code + " for the full message or " + 'use the non-minified dev environment for full errors. ';
588 }
589
590 // Inlined version of the `symbol-observable` polyfill
591 var $$observable = (function () {
592 return typeof Symbol === 'function' && Symbol.observable || '@@observable';
593 })();
594
595 /**
596 * These are private action types reserved by Redux.
597 * For any unknown actions, you must return the current state.
598 * If the current state is undefined, you must return the initial state.
599 * Do not reference these action types directly in your code.
600 */
601 var randomString = function randomString() {
602 return Math.random().toString(36).substring(7).split('').join('.');
603 };
604
605 var ActionTypes = {
606 INIT: "@@redux/INIT" + randomString(),
607 REPLACE: "@@redux/REPLACE" + randomString(),
608 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
609 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
610 }
611 };
612
613 /**
614 * @param {any} obj The object to inspect.
615 * @returns {boolean} True if the argument appears to be a plain object.
616 */
617 function isPlainObject(obj) {
618 if (typeof obj !== 'object' || obj === null) return false;
619 var proto = obj;
620
621 while (Object.getPrototypeOf(proto) !== null) {
622 proto = Object.getPrototypeOf(proto);
623 }
624
625 return Object.getPrototypeOf(obj) === proto;
626 }
627
628 function kindOf(val) {
629 var typeOfVal = typeof val;
630
631 if (false) {}
632
633 return typeOfVal;
634 }
635
636 /**
637 * Creates a Redux store that holds the state tree.
638 * The only way to change the data in the store is to call `dispatch()` on it.
639 *
640 * There should only be a single store in your app. To specify how different
641 * parts of the state tree respond to actions, you may combine several reducers
642 * into a single reducer function by using `combineReducers`.
643 *
644 * @param {Function} reducer A function that returns the next state tree, given
645 * the current state tree and the action to handle.
646 *
647 * @param {any} [preloadedState] The initial state. You may optionally specify it
648 * to hydrate the state from the server in universal apps, or to restore a
649 * previously serialized user session.
650 * If you use `combineReducers` to produce the root reducer function, this must be
651 * an object with the same shape as `combineReducers` keys.
652 *
653 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
654 * to enhance the store with third-party capabilities such as middleware,
655 * time travel, persistence, etc. The only store enhancer that ships with Redux
656 * is `applyMiddleware()`.
657 *
658 * @returns {Store} A Redux store that lets you read the state, dispatch actions
659 * and subscribe to changes.
660 */
661
662 function createStore(reducer, preloadedState, enhancer) {
663 var _ref2;
664
665 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
666 throw new Error( true ? formatProdErrorMessage(0) : 0);
667 }
668
669 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
670 enhancer = preloadedState;
671 preloadedState = undefined;
672 }
673
674 if (typeof enhancer !== 'undefined') {
675 if (typeof enhancer !== 'function') {
676 throw new Error( true ? formatProdErrorMessage(1) : 0);
677 }
678
679 return enhancer(createStore)(reducer, preloadedState);
680 }
681
682 if (typeof reducer !== 'function') {
683 throw new Error( true ? formatProdErrorMessage(2) : 0);
684 }
685
686 var currentReducer = reducer;
687 var currentState = preloadedState;
688 var currentListeners = [];
689 var nextListeners = currentListeners;
690 var isDispatching = false;
691 /**
692 * This makes a shallow copy of currentListeners so we can use
693 * nextListeners as a temporary list while dispatching.
694 *
695 * This prevents any bugs around consumers calling
696 * subscribe/unsubscribe in the middle of a dispatch.
697 */
698
699 function ensureCanMutateNextListeners() {
700 if (nextListeners === currentListeners) {
701 nextListeners = currentListeners.slice();
702 }
703 }
704 /**
705 * Reads the state tree managed by the store.
706 *
707 * @returns {any} The current state tree of your application.
708 */
709
710
711 function getState() {
712 if (isDispatching) {
713 throw new Error( true ? formatProdErrorMessage(3) : 0);
714 }
715
716 return currentState;
717 }
718 /**
719 * Adds a change listener. It will be called any time an action is dispatched,
720 * and some part of the state tree may potentially have changed. You may then
721 * call `getState()` to read the current state tree inside the callback.
722 *
723 * You may call `dispatch()` from a change listener, with the following
724 * caveats:
725 *
726 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
727 * If you subscribe or unsubscribe while the listeners are being invoked, this
728 * will not have any effect on the `dispatch()` that is currently in progress.
729 * However, the next `dispatch()` call, whether nested or not, will use a more
730 * recent snapshot of the subscription list.
731 *
732 * 2. The listener should not expect to see all state changes, as the state
733 * might have been updated multiple times during a nested `dispatch()` before
734 * the listener is called. It is, however, guaranteed that all subscribers
735 * registered before the `dispatch()` started will be called with the latest
736 * state by the time it exits.
737 *
738 * @param {Function} listener A callback to be invoked on every dispatch.
739 * @returns {Function} A function to remove this change listener.
740 */
741
742
743 function subscribe(listener) {
744 if (typeof listener !== 'function') {
745 throw new Error( true ? formatProdErrorMessage(4) : 0);
746 }
747
748 if (isDispatching) {
749 throw new Error( true ? formatProdErrorMessage(5) : 0);
750 }
751
752 var isSubscribed = true;
753 ensureCanMutateNextListeners();
754 nextListeners.push(listener);
755 return function unsubscribe() {
756 if (!isSubscribed) {
757 return;
758 }
759
760 if (isDispatching) {
761 throw new Error( true ? formatProdErrorMessage(6) : 0);
762 }
763
764 isSubscribed = false;
765 ensureCanMutateNextListeners();
766 var index = nextListeners.indexOf(listener);
767 nextListeners.splice(index, 1);
768 currentListeners = null;
769 };
770 }
771 /**
772 * Dispatches an action. It is the only way to trigger a state change.
773 *
774 * The `reducer` function, used to create the store, will be called with the
775 * current state tree and the given `action`. Its return value will
776 * be considered the **next** state of the tree, and the change listeners
777 * will be notified.
778 *
779 * The base implementation only supports plain object actions. If you want to
780 * dispatch a Promise, an Observable, a thunk, or something else, you need to
781 * wrap your store creating function into the corresponding middleware. For
782 * example, see the documentation for the `redux-thunk` package. Even the
783 * middleware will eventually dispatch plain object actions using this method.
784 *
785 * @param {Object} action A plain object representing “what changed”. It is
786 * a good idea to keep actions serializable so you can record and replay user
787 * sessions, or use the time travelling `redux-devtools`. An action must have
788 * a `type` property which may not be `undefined`. It is a good idea to use
789 * string constants for action types.
790 *
791 * @returns {Object} For convenience, the same action object you dispatched.
792 *
793 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
794 * return something else (for example, a Promise you can await).
795 */
796
797
798 function dispatch(action) {
799 if (!isPlainObject(action)) {
800 throw new Error( true ? formatProdErrorMessage(7) : 0);
801 }
802
803 if (typeof action.type === 'undefined') {
804 throw new Error( true ? formatProdErrorMessage(8) : 0);
805 }
806
807 if (isDispatching) {
808 throw new Error( true ? formatProdErrorMessage(9) : 0);
809 }
810
811 try {
812 isDispatching = true;
813 currentState = currentReducer(currentState, action);
814 } finally {
815 isDispatching = false;
816 }
817
818 var listeners = currentListeners = nextListeners;
819
820 for (var i = 0; i < listeners.length; i++) {
821 var listener = listeners[i];
822 listener();
823 }
824
825 return action;
826 }
827 /**
828 * Replaces the reducer currently used by the store to calculate the state.
829 *
830 * You might need this if your app implements code splitting and you want to
831 * load some of the reducers dynamically. You might also need this if you
832 * implement a hot reloading mechanism for Redux.
833 *
834 * @param {Function} nextReducer The reducer for the store to use instead.
835 * @returns {void}
836 */
837
838
839 function replaceReducer(nextReducer) {
840 if (typeof nextReducer !== 'function') {
841 throw new Error( true ? formatProdErrorMessage(10) : 0);
842 }
843
844 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
845 // Any reducers that existed in both the new and old rootReducer
846 // will receive the previous state. This effectively populates
847 // the new state tree with any relevant data from the old one.
848
849 dispatch({
850 type: ActionTypes.REPLACE
851 });
852 }
853 /**
854 * Interoperability point for observable/reactive libraries.
855 * @returns {observable} A minimal observable of state changes.
856 * For more information, see the observable proposal:
857 * https://github.com/tc39/proposal-observable
858 */
859
860
861 function observable() {
862 var _ref;
863
864 var outerSubscribe = subscribe;
865 return _ref = {
866 /**
867 * The minimal observable subscription method.
868 * @param {Object} observer Any object that can be used as an observer.
869 * The observer object should have a `next` method.
870 * @returns {subscription} An object with an `unsubscribe` method that can
871 * be used to unsubscribe the observable from the store, and prevent further
872 * emission of values from the observable.
873 */
874 subscribe: function subscribe(observer) {
875 if (typeof observer !== 'object' || observer === null) {
876 throw new Error( true ? formatProdErrorMessage(11) : 0);
877 }
878
879 function observeState() {
880 if (observer.next) {
881 observer.next(getState());
882 }
883 }
884
885 observeState();
886 var unsubscribe = outerSubscribe(observeState);
887 return {
888 unsubscribe: unsubscribe
889 };
890 }
891 }, _ref[$$observable] = function () {
892 return this;
893 }, _ref;
894 } // When a store is created, an "INIT" action is dispatched so that every
895 // reducer returns their initial state. This effectively populates
896 // the initial state tree.
897
898
899 dispatch({
900 type: ActionTypes.INIT
901 });
902 return _ref2 = {
903 dispatch: dispatch,
904 subscribe: subscribe,
905 getState: getState,
906 replaceReducer: replaceReducer
907 }, _ref2[$$observable] = observable, _ref2;
908 }
909
910 /**
911 * Prints a warning in the console if it exists.
912 *
913 * @param {String} message The warning message.
914 * @returns {void}
915 */
916 function warning(message) {
917 /* eslint-disable no-console */
918 if (typeof console !== 'undefined' && typeof console.error === 'function') {
919 console.error(message);
920 }
921 /* eslint-enable no-console */
922
923
924 try {
925 // This error was thrown as a convenience so that if you enable
926 // "break on all exceptions" in your console,
927 // it would pause the execution at this line.
928 throw new Error(message);
929 } catch (e) {} // eslint-disable-line no-empty
930
931 }
932
933 function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
934 var reducerKeys = Object.keys(reducers);
935 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
936
937 if (reducerKeys.length === 0) {
938 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
939 }
940
941 if (!isPlainObject(inputState)) {
942 return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
943 }
944
945 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
946 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
947 });
948 unexpectedKeys.forEach(function (key) {
949 unexpectedKeyCache[key] = true;
950 });
951 if (action && action.type === ActionTypes.REPLACE) return;
952
953 if (unexpectedKeys.length > 0) {
954 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.");
955 }
956 }
957
958 function assertReducerShape(reducers) {
959 Object.keys(reducers).forEach(function (key) {
960 var reducer = reducers[key];
961 var initialState = reducer(undefined, {
962 type: ActionTypes.INIT
963 });
964
965 if (typeof initialState === 'undefined') {
966 throw new Error( true ? formatProdErrorMessage(12) : 0);
967 }
968
969 if (typeof reducer(undefined, {
970 type: ActionTypes.PROBE_UNKNOWN_ACTION()
971 }) === 'undefined') {
972 throw new Error( true ? formatProdErrorMessage(13) : 0);
973 }
974 });
975 }
976 /**
977 * Turns an object whose values are different reducer functions, into a single
978 * reducer function. It will call every child reducer, and gather their results
979 * into a single state object, whose keys correspond to the keys of the passed
980 * reducer functions.
981 *
982 * @param {Object} reducers An object whose values correspond to different
983 * reducer functions that need to be combined into one. One handy way to obtain
984 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
985 * undefined for any action. Instead, they should return their initial state
986 * if the state passed to them was undefined, and the current state for any
987 * unrecognized action.
988 *
989 * @returns {Function} A reducer function that invokes every reducer inside the
990 * passed object, and builds a state object with the same shape.
991 */
992
993
994 function combineReducers(reducers) {
995 var reducerKeys = Object.keys(reducers);
996 var finalReducers = {};
997
998 for (var i = 0; i < reducerKeys.length; i++) {
999 var key = reducerKeys[i];
1000
1001 if (false) {}
1002
1003 if (typeof reducers[key] === 'function') {
1004 finalReducers[key] = reducers[key];
1005 }
1006 }
1007
1008 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
1009 // keys multiple times.
1010
1011 var unexpectedKeyCache;
1012
1013 if (false) {}
1014
1015 var shapeAssertionError;
1016
1017 try {
1018 assertReducerShape(finalReducers);
1019 } catch (e) {
1020 shapeAssertionError = e;
1021 }
1022
1023 return function combination(state, action) {
1024 if (state === void 0) {
1025 state = {};
1026 }
1027
1028 if (shapeAssertionError) {
1029 throw shapeAssertionError;
1030 }
1031
1032 if (false) { var warningMessage; }
1033
1034 var hasChanged = false;
1035 var nextState = {};
1036
1037 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
1038 var _key = finalReducerKeys[_i];
1039 var reducer = finalReducers[_key];
1040 var previousStateForKey = state[_key];
1041 var nextStateForKey = reducer(previousStateForKey, action);
1042
1043 if (typeof nextStateForKey === 'undefined') {
1044 var actionType = action && action.type;
1045 throw new Error( true ? formatProdErrorMessage(14) : 0);
1046 }
1047
1048 nextState[_key] = nextStateForKey;
1049 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
1050 }
1051
1052 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
1053 return hasChanged ? nextState : state;
1054 };
1055 }
1056
1057 function bindActionCreator(actionCreator, dispatch) {
1058 return function () {
1059 return dispatch(actionCreator.apply(this, arguments));
1060 };
1061 }
1062 /**
1063 * Turns an object whose values are action creators, into an object with the
1064 * same keys, but with every function wrapped into a `dispatch` call so they
1065 * may be invoked directly. This is just a convenience method, as you can call
1066 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
1067 *
1068 * For convenience, you can also pass an action creator as the first argument,
1069 * and get a dispatch wrapped function in return.
1070 *
1071 * @param {Function|Object} actionCreators An object whose values are action
1072 * creator functions. One handy way to obtain it is to use ES6 `import * as`
1073 * syntax. You may also pass a single function.
1074 *
1075 * @param {Function} dispatch The `dispatch` function available on your Redux
1076 * store.
1077 *
1078 * @returns {Function|Object} The object mimicking the original object, but with
1079 * every action creator wrapped into the `dispatch` call. If you passed a
1080 * function as `actionCreators`, the return value will also be a single
1081 * function.
1082 */
1083
1084
1085 function bindActionCreators(actionCreators, dispatch) {
1086 if (typeof actionCreators === 'function') {
1087 return bindActionCreator(actionCreators, dispatch);
1088 }
1089
1090 if (typeof actionCreators !== 'object' || actionCreators === null) {
1091 throw new Error( true ? formatProdErrorMessage(16) : 0);
1092 }
1093
1094 var boundActionCreators = {};
1095
1096 for (var key in actionCreators) {
1097 var actionCreator = actionCreators[key];
1098
1099 if (typeof actionCreator === 'function') {
1100 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
1101 }
1102 }
1103
1104 return boundActionCreators;
1105 }
1106
1107 /**
1108 * Composes single-argument functions from right to left. The rightmost
1109 * function can take multiple arguments as it provides the signature for
1110 * the resulting composite function.
1111 *
1112 * @param {...Function} funcs The functions to compose.
1113 * @returns {Function} A function obtained by composing the argument functions
1114 * from right to left. For example, compose(f, g, h) is identical to doing
1115 * (...args) => f(g(h(...args))).
1116 */
1117 function compose() {
1118 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
1119 funcs[_key] = arguments[_key];
1120 }
1121
1122 if (funcs.length === 0) {
1123 return function (arg) {
1124 return arg;
1125 };
1126 }
1127
1128 if (funcs.length === 1) {
1129 return funcs[0];
1130 }
1131
1132 return funcs.reduce(function (a, b) {
1133 return function () {
1134 return a(b.apply(void 0, arguments));
1135 };
1136 });
1137 }
1138
1139 /**
1140 * Creates a store enhancer that applies middleware to the dispatch method
1141 * of the Redux store. This is handy for a variety of tasks, such as expressing
1142 * asynchronous actions in a concise manner, or logging every action payload.
1143 *
1144 * See `redux-thunk` package as an example of the Redux middleware.
1145 *
1146 * Because middleware is potentially asynchronous, this should be the first
1147 * store enhancer in the composition chain.
1148 *
1149 * Note that each middleware will be given the `dispatch` and `getState` functions
1150 * as named arguments.
1151 *
1152 * @param {...Function} middlewares The middleware chain to be applied.
1153 * @returns {Function} A store enhancer applying the middleware.
1154 */
1155
1156 function applyMiddleware() {
1157 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
1158 middlewares[_key] = arguments[_key];
1159 }
1160
1161 return function (createStore) {
1162 return function () {
1163 var store = createStore.apply(void 0, arguments);
1164
1165 var _dispatch = function dispatch() {
1166 throw new Error( true ? formatProdErrorMessage(15) : 0);
1167 };
1168
1169 var middlewareAPI = {
1170 getState: store.getState,
1171 dispatch: function dispatch() {
1172 return _dispatch.apply(void 0, arguments);
1173 }
1174 };
1175 var chain = middlewares.map(function (middleware) {
1176 return middleware(middlewareAPI);
1177 });
1178 _dispatch = compose.apply(void 0, chain)(store.dispatch);
1179 return _objectSpread2(_objectSpread2({}, store), {}, {
1180 dispatch: _dispatch
1181 });
1182 };
1183 };
1184 }
1185
1186 /*
1187 * This is a dummy function to check if the function name has been altered by minification.
1188 * If the function has been minified and NODE_ENV !== 'production', warn the user.
1189 */
1190
1191 function isCrushed() {}
1192
1193 if (false) {}
1194
1195
1196
1197 // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js
1198 var equivalent_key_map = __webpack_require__(3909);
1199 var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map);
1200 ;// CONCATENATED MODULE: external ["wp","reduxRoutine"]
1201 var external_wp_reduxRoutine_namespaceObject = window["wp"]["reduxRoutine"];
1202 var external_wp_reduxRoutine_default = /*#__PURE__*/__webpack_require__.n(external_wp_reduxRoutine_namespaceObject);
1203 ;// CONCATENATED MODULE: ./packages/data/build-module/factory.js
1204 /**
1205 * Creates a selector function that takes additional curried argument with the
1206 * registry `select` function. While a regular selector has signature
1207 * ```js
1208 * ( state, ...selectorArgs ) => ( result )
1209 * ```
1210 * that allows to select data from the store's `state`, a registry selector
1211 * has signature:
1212 * ```js
1213 * ( select ) => ( state, ...selectorArgs ) => ( result )
1214 * ```
1215 * that supports also selecting from other registered stores.
1216 *
1217 * @example
1218 * ```js
1219 * const getCurrentPostId = createRegistrySelector( ( select ) => ( state ) => {
1220 * return select( 'core/editor' ).getCurrentPostId();
1221 * } );
1222 *
1223 * const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
1224 * // calling another registry selector just like any other function
1225 * const postType = getCurrentPostType( state );
1226 * const postId = getCurrentPostId( state );
1227 * return select( 'core' ).getEntityRecordEdits( 'postType', postType, postId );
1228 * } );
1229 * ```
1230 *
1231 * Note how the `getCurrentPostId` selector can be called just like any other function,
1232 * (it works even inside a regular non-registry selector) and we don't need to pass the
1233 * registry as argument. The registry binding happens automatically when registering the selector
1234 * with a store.
1235 *
1236 * @param {Function} registrySelector Function receiving a registry `select`
1237 * function and returning a state selector.
1238 *
1239 * @return {Function} Registry selector that can be registered with a store.
1240 */
1241 function createRegistrySelector(registrySelector) {
1242 // create a selector function that is bound to the registry referenced by `selector.registry`
1243 // and that has the same API as a regular selector. Binding it in such a way makes it
1244 // possible to call the selector directly from another selector.
1245 const selector = function () {
1246 return registrySelector(selector.registry.select)(...arguments);
1247 };
1248 /**
1249 * Flag indicating that the selector is a registry selector that needs the correct registry
1250 * reference to be assigned to `selecto.registry` to make it work correctly.
1251 * be mapped as a registry selector.
1252 *
1253 * @type {boolean}
1254 */
1255
1256
1257 selector.isRegistrySelector = true;
1258 return selector;
1259 }
1260 /**
1261 * Creates a control function that takes additional curried argument with the `registry` object.
1262 * While a regular control has signature
1263 * ```js
1264 * ( action ) => ( iteratorOrPromise )
1265 * ```
1266 * where the control works with the `action` that it's bound to, a registry control has signature:
1267 * ```js
1268 * ( registry ) => ( action ) => ( iteratorOrPromise )
1269 * ```
1270 * A registry control is typically used to select data or dispatch an action to a registered
1271 * store.
1272 *
1273 * When registering a control created with `createRegistryControl` with a store, the store
1274 * knows which calling convention to use when executing the control.
1275 *
1276 * @param {Function} registryControl Function receiving a registry object and returning a control.
1277 *
1278 * @return {Function} Registry control that can be registered with a store.
1279 */
1280
1281 function createRegistryControl(registryControl) {
1282 registryControl.isRegistryControl = true;
1283 return registryControl;
1284 }
1285 //# sourceMappingURL=factory.js.map
1286 ;// CONCATENATED MODULE: ./packages/data/build-module/controls.js
1287 /**
1288 * External dependencies
1289 */
1290
1291 /**
1292 * Internal dependencies
1293 */
1294
1295
1296 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
1297
1298 const SELECT = '@@data/SELECT';
1299 const RESOLVE_SELECT = '@@data/RESOLVE_SELECT';
1300 const DISPATCH = '@@data/DISPATCH';
1301 /**
1302 * Dispatches a control action for triggering a synchronous registry select.
1303 *
1304 * Note: This control synchronously returns the current selector value, triggering the
1305 * resolution, but not waiting for it.
1306 *
1307 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1308 * @param {string} selectorName The name of the selector.
1309 * @param {Array} args Arguments for the selector.
1310 *
1311 * @example
1312 * ```js
1313 * import { controls } from '@wordpress/data';
1314 *
1315 * // Action generator using `select`.
1316 * export function* myAction() {
1317 * const isEditorSideBarOpened = yield controls.select( 'core/edit-post', 'isEditorSideBarOpened' );
1318 * // Do stuff with the result from the `select`.
1319 * }
1320 * ```
1321 *
1322 * @return {Object} The control descriptor.
1323 */
1324
1325 function controls_select(storeNameOrDescriptor, selectorName) {
1326 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1327 args[_key - 2] = arguments[_key];
1328 }
1329
1330 return {
1331 type: SELECT,
1332 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1333 selectorName,
1334 args
1335 };
1336 }
1337 /**
1338 * Dispatches a control action for triggering and resolving a registry select.
1339 *
1340 * Note: when this control action is handled, it automatically considers
1341 * selectors that may have a resolver. In such case, it will return a `Promise` that resolves
1342 * after the selector finishes resolving, with the final result value.
1343 *
1344 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1345 * @param {string} selectorName The name of the selector
1346 * @param {Array} args Arguments for the selector.
1347 *
1348 * @example
1349 * ```js
1350 * import { controls } from '@wordpress/data';
1351 *
1352 * // Action generator using resolveSelect
1353 * export function* myAction() {
1354 * const isSidebarOpened = yield controls.resolveSelect( 'core/edit-post', 'isEditorSideBarOpened' );
1355 * // do stuff with the result from the select.
1356 * }
1357 * ```
1358 *
1359 * @return {Object} The control descriptor.
1360 */
1361
1362
1363 function resolveSelect(storeNameOrDescriptor, selectorName) {
1364 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
1365 args[_key2 - 2] = arguments[_key2];
1366 }
1367
1368 return {
1369 type: RESOLVE_SELECT,
1370 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1371 selectorName,
1372 args
1373 };
1374 }
1375 /**
1376 * Dispatches a control action for triggering a registry dispatch.
1377 *
1378 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1379 * @param {string} actionName The name of the action to dispatch
1380 * @param {Array} args Arguments for the dispatch action.
1381 *
1382 * @example
1383 * ```js
1384 * import { controls } from '@wordpress/data-controls';
1385 *
1386 * // Action generator using dispatch
1387 * export function* myAction() {
1388 * yield controls.dispatch( 'core/edit-post', 'togglePublishSidebar' );
1389 * // do some other things.
1390 * }
1391 * ```
1392 *
1393 * @return {Object} The control descriptor.
1394 */
1395
1396
1397 function dispatch(storeNameOrDescriptor, actionName) {
1398 for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
1399 args[_key3 - 2] = arguments[_key3];
1400 }
1401
1402 return {
1403 type: DISPATCH,
1404 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1405 actionName,
1406 args
1407 };
1408 }
1409
1410 const controls = {
1411 select: controls_select,
1412 resolveSelect,
1413 dispatch
1414 };
1415 const builtinControls = {
1416 [SELECT]: createRegistryControl(registry => _ref => {
1417 let {
1418 storeKey,
1419 selectorName,
1420 args
1421 } = _ref;
1422 return registry.select(storeKey)[selectorName](...args);
1423 }),
1424 [RESOLVE_SELECT]: createRegistryControl(registry => _ref2 => {
1425 let {
1426 storeKey,
1427 selectorName,
1428 args
1429 } = _ref2;
1430 const method = registry.select(storeKey)[selectorName].hasResolver ? 'resolveSelect' : 'select';
1431 return registry[method](storeKey)[selectorName](...args);
1432 }),
1433 [DISPATCH]: createRegistryControl(registry => _ref3 => {
1434 let {
1435 storeKey,
1436 actionName,
1437 args
1438 } = _ref3;
1439 return registry.dispatch(storeKey)[actionName](...args);
1440 })
1441 };
1442 //# sourceMappingURL=controls.js.map
1443 ;// CONCATENATED MODULE: ./node_modules/is-promise/index.mjs
1444 function isPromise(obj) {
1445 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
1446 }
1447
1448 ;// CONCATENATED MODULE: ./packages/data/build-module/promise-middleware.js
1449 /**
1450 * External dependencies
1451 */
1452
1453 /**
1454 * Simplest possible promise redux middleware.
1455 *
1456 * @type {import('redux').Middleware}
1457 */
1458
1459 const promiseMiddleware = () => next => action => {
1460 if (isPromise(action)) {
1461 return action.then(resolvedAction => {
1462 if (resolvedAction) {
1463 return next(resolvedAction);
1464 }
1465 });
1466 }
1467
1468 return next(action);
1469 };
1470
1471 /* harmony default export */ var promise_middleware = (promiseMiddleware);
1472 //# sourceMappingURL=promise-middleware.js.map
1473 ;// CONCATENATED MODULE: ./packages/data/build-module/store/index.js
1474 const coreDataStore = {
1475 name: 'core/data',
1476
1477 instantiate(registry) {
1478 const getCoreDataSelector = selectorName => function (key) {
1479 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1480 args[_key - 1] = arguments[_key];
1481 }
1482
1483 return registry.select(key)[selectorName](...args);
1484 };
1485
1486 const getCoreDataAction = actionName => function (key) {
1487 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1488 args[_key2 - 1] = arguments[_key2];
1489 }
1490
1491 return registry.dispatch(key)[actionName](...args);
1492 };
1493
1494 return {
1495 getSelectors() {
1496 return Object.fromEntries(['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'].map(selectorName => [selectorName, getCoreDataSelector(selectorName)]));
1497 },
1498
1499 getActions() {
1500 return Object.fromEntries(['startResolution', 'finishResolution', 'invalidateResolution', 'invalidateResolutionForStore', 'invalidateResolutionForStoreSelector'].map(actionName => [actionName, getCoreDataAction(actionName)]));
1501 },
1502
1503 subscribe() {
1504 // There's no reasons to trigger any listener when we subscribe to this store
1505 // because there's no state stored in this store that need to retrigger selectors
1506 // if a change happens, the corresponding store where the tracking stated live
1507 // would have already triggered a "subscribe" call.
1508 return () => () => {};
1509 }
1510
1511 };
1512 }
1513
1514 };
1515 /* harmony default export */ var store = (coreDataStore);
1516 //# sourceMappingURL=index.js.map
1517 ;// CONCATENATED MODULE: ./packages/data/build-module/resolvers-cache-middleware.js
1518 /**
1519 * External dependencies
1520 */
1521
1522 /**
1523 * Internal dependencies
1524 */
1525
1526
1527 /** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */
1528
1529 /**
1530 * Creates a middleware handling resolvers cache invalidation.
1531 *
1532 * @param {WPDataRegistry} registry The registry reference for which to create
1533 * the middleware.
1534 * @param {string} reducerKey The namespace for which to create the
1535 * middleware.
1536 *
1537 * @return {Function} Middleware function.
1538 */
1539
1540 const createResolversCacheMiddleware = (registry, reducerKey) => () => next => action => {
1541 const resolvers = registry.select(store).getCachedResolvers(reducerKey);
1542 Object.entries(resolvers).forEach(_ref => {
1543 let [selectorName, resolversByArgs] = _ref;
1544 const resolver = (0,external_lodash_namespaceObject.get)(registry.stores, [reducerKey, 'resolvers', selectorName]);
1545
1546 if (!resolver || !resolver.shouldInvalidate) {
1547 return;
1548 }
1549
1550 resolversByArgs.forEach((value, args) => {
1551 // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.
1552 // If the value is false it means this resolver has finished its resolution which means we need to invalidate it,
1553 // if it's true it means it's inflight and the invalidation is not necessary.
1554 if (value !== false || !resolver.shouldInvalidate(action, ...args)) {
1555 return;
1556 } // Trigger cache invalidation
1557
1558
1559 registry.dispatch(store).invalidateResolution(reducerKey, selectorName, args);
1560 });
1561 });
1562 return next(action);
1563 };
1564
1565 /* harmony default export */ var resolvers_cache_middleware = (createResolversCacheMiddleware);
1566 //# sourceMappingURL=resolvers-cache-middleware.js.map
1567 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/thunk-middleware.js
1568 function createThunkMiddleware(args) {
1569 return () => next => action => {
1570 if (typeof action === 'function') {
1571 return action(args);
1572 }
1573
1574 return next(action);
1575 };
1576 }
1577 //# sourceMappingURL=thunk-middleware.js.map
1578 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/utils.js
1579 /**
1580 * Higher-order reducer creator which creates a combined reducer object, keyed
1581 * by a property on the action object.
1582 *
1583 * @template {any} TState
1584 * @template {import('redux').AnyAction} TAction
1585 *
1586 * @param {string} actionProperty Action property by which to key object.
1587 *
1588 * @return {(reducer: import('redux').Reducer<TState, TAction>) => import('redux').Reducer<Record<string, TState>, TAction>} Higher-order reducer.
1589 */
1590 const onSubKey = actionProperty => reducer => function () {
1591 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] :
1592 /** @type {Record<string, TState>} */
1593 {};
1594 let action = arguments.length > 1 ? arguments[1] : undefined;
1595 // Retrieve subkey from action. Do not track if undefined; useful for cases
1596 // where reducer is scoped by action shape.
1597
1598 /** @type {keyof state} */
1599
1600 /* eslint-enable jsdoc/no-undefined-types */
1601 const key = action[actionProperty];
1602
1603 if (key === undefined) {
1604 return state;
1605 } // Avoid updating state if unchanged. Note that this also accounts for a
1606 // reducer which returns undefined on a key which is not yet tracked.
1607
1608
1609 const nextKeyState = reducer(state[key], action);
1610
1611 if (nextKeyState === state[key]) {
1612 return state;
1613 }
1614
1615 return { ...state,
1616 [key]: nextKeyState
1617 };
1618 };
1619 //# sourceMappingURL=utils.js.map
1620 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/reducer.js
1621 /**
1622 * External dependencies
1623 */
1624
1625
1626
1627 /**
1628 * Internal dependencies
1629 */
1630
1631
1632 /**
1633 * Reducer function returning next state for selector resolution of
1634 * subkeys, object form:
1635 *
1636 * selectorName -> EquivalentKeyMap<Array,boolean>
1637 */
1638 const subKeysIsResolved = onSubKey('selectorName')(function () {
1639 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new (equivalent_key_map_default())();
1640 let action = arguments.length > 1 ? arguments[1] : undefined;
1641
1642 switch (action.type) {
1643 case 'START_RESOLUTION':
1644 case 'FINISH_RESOLUTION':
1645 {
1646 const isStarting = action.type === 'START_RESOLUTION';
1647 const nextState = new (equivalent_key_map_default())(state);
1648 nextState.set(action.args, isStarting);
1649 return nextState;
1650 }
1651
1652 case 'START_RESOLUTIONS':
1653 case 'FINISH_RESOLUTIONS':
1654 {
1655 const isStarting = action.type === 'START_RESOLUTIONS';
1656 const nextState = new (equivalent_key_map_default())(state);
1657
1658 for (const resolutionArgs of action.args) {
1659 nextState.set(resolutionArgs, isStarting);
1660 }
1661
1662 return nextState;
1663 }
1664
1665 case 'INVALIDATE_RESOLUTION':
1666 {
1667 const nextState = new (equivalent_key_map_default())(state);
1668 nextState.delete(action.args);
1669 return nextState;
1670 }
1671 }
1672
1673 return state;
1674 });
1675 /**
1676 * Reducer function returning next state for selector resolution, object form:
1677 *
1678 * selectorName -> EquivalentKeyMap<Array, boolean>
1679 *
1680 * @param state Current state.
1681 * @param action Dispatched action.
1682 *
1683 * @return Next state.
1684 */
1685
1686 const isResolved = function () {
1687 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1688 let action = arguments.length > 1 ? arguments[1] : undefined;
1689
1690 switch (action.type) {
1691 case 'INVALIDATE_RESOLUTION_FOR_STORE':
1692 return {};
1693
1694 case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR':
1695 return (0,external_lodash_namespaceObject.has)(state, [action.selectorName]) ? (0,external_lodash_namespaceObject.omit)(state, [action.selectorName]) : state;
1696
1697 case 'START_RESOLUTION':
1698 case 'FINISH_RESOLUTION':
1699 case 'START_RESOLUTIONS':
1700 case 'FINISH_RESOLUTIONS':
1701 case 'INVALIDATE_RESOLUTION':
1702 return subKeysIsResolved(state, action);
1703 }
1704
1705 return state;
1706 };
1707
1708 /* harmony default export */ var metadata_reducer = (isResolved);
1709 //# sourceMappingURL=reducer.js.map
1710 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/selectors.js
1711 /**
1712 * External dependencies
1713 */
1714
1715 /** @typedef {Record<string, import('./reducer').State>} State */
1716
1717 /**
1718 * Returns the raw `isResolving` value for a given selector name,
1719 * and arguments set. May be undefined if the selector has never been resolved
1720 * or not resolved for the given set of arguments, otherwise true or false for
1721 * resolution started and completed respectively.
1722 *
1723 * @param {State} state Data state.
1724 * @param {string} selectorName Selector name.
1725 * @param {unknown[]} args Arguments passed to selector.
1726 *
1727 * @return {boolean | undefined} isResolving value.
1728 */
1729
1730 function getIsResolving(state, selectorName, args) {
1731 const map = (0,external_lodash_namespaceObject.get)(state, [selectorName]);
1732
1733 if (!map) {
1734 return undefined;
1735 }
1736
1737 return map.get(args);
1738 }
1739 /**
1740 * Returns true if resolution has already been triggered for a given
1741 * selector name, and arguments set.
1742 *
1743 * @param {State} state Data state.
1744 * @param {string} selectorName Selector name.
1745 * @param {unknown[]} [args] Arguments passed to selector (default `[]`).
1746 *
1747 * @return {boolean} Whether resolution has been triggered.
1748 */
1749
1750 function hasStartedResolution(state, selectorName) {
1751 let args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
1752 return getIsResolving(state, selectorName, args) !== undefined;
1753 }
1754 /**
1755 * Returns true if resolution has completed for a given selector
1756 * name, and arguments set.
1757 *
1758 * @param {State} state Data state.
1759 * @param {string} selectorName Selector name.
1760 * @param {unknown[]} [args] Arguments passed to selector.
1761 *
1762 * @return {boolean} Whether resolution has completed.
1763 */
1764
1765 function hasFinishedResolution(state, selectorName) {
1766 let args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
1767 return getIsResolving(state, selectorName, args) === false;
1768 }
1769 /**
1770 * Returns true if resolution has been triggered but has not yet completed for
1771 * a given selector name, and arguments set.
1772 *
1773 * @param {State} state Data state.
1774 * @param {string} selectorName Selector name.
1775 * @param {unknown[]} [args] Arguments passed to selector.
1776 *
1777 * @return {boolean} Whether resolution is in progress.
1778 */
1779
1780 function isResolving(state, selectorName) {
1781 let args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
1782 return getIsResolving(state, selectorName, args) === true;
1783 }
1784 /**
1785 * Returns the list of the cached resolvers.
1786 *
1787 * @param {State} state Data state.
1788 *
1789 * @return {State} Resolvers mapped by args and selectorName.
1790 */
1791
1792 function getCachedResolvers(state) {
1793 return state;
1794 }
1795 //# sourceMappingURL=selectors.js.map
1796 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/actions.js
1797 /**
1798 * Returns an action object used in signalling that selector resolution has
1799 * started.
1800 *
1801 * @param {string} selectorName Name of selector for which resolver triggered.
1802 * @param {unknown[]} args Arguments to associate for uniqueness.
1803 *
1804 * @return {{ type: 'START_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
1805 */
1806 function startResolution(selectorName, args) {
1807 return {
1808 type: 'START_RESOLUTION',
1809 selectorName,
1810 args
1811 };
1812 }
1813 /**
1814 * Returns an action object used in signalling that selector resolution has
1815 * completed.
1816 *
1817 * @param {string} selectorName Name of selector for which resolver triggered.
1818 * @param {unknown[]} args Arguments to associate for uniqueness.
1819 *
1820 * @return {{ type: 'FINISH_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
1821 */
1822
1823 function finishResolution(selectorName, args) {
1824 return {
1825 type: 'FINISH_RESOLUTION',
1826 selectorName,
1827 args
1828 };
1829 }
1830 /**
1831 * Returns an action object used in signalling that a batch of selector resolutions has
1832 * started.
1833 *
1834 * @param {string} selectorName Name of selector for which resolver triggered.
1835 * @param {unknown[]} args Array of arguments to associate for uniqueness, each item
1836 * is associated to a resolution.
1837 *
1838 * @return {{ type: 'START_RESOLUTIONS', selectorName: string, args: unknown[] }} Action object.
1839 */
1840
1841 function startResolutions(selectorName, args) {
1842 return {
1843 type: 'START_RESOLUTIONS',
1844 selectorName,
1845 args
1846 };
1847 }
1848 /**
1849 * Returns an action object used in signalling that a batch of selector resolutions has
1850 * completed.
1851 *
1852 * @param {string} selectorName Name of selector for which resolver triggered.
1853 * @param {unknown[]} args Array of arguments to associate for uniqueness, each item
1854 * is associated to a resolution.
1855 *
1856 * @return {{ type: 'FINISH_RESOLUTIONS', selectorName: string, args: unknown[] }} Action object.
1857 */
1858
1859 function finishResolutions(selectorName, args) {
1860 return {
1861 type: 'FINISH_RESOLUTIONS',
1862 selectorName,
1863 args
1864 };
1865 }
1866 /**
1867 * Returns an action object used in signalling that we should invalidate the resolution cache.
1868 *
1869 * @param {string} selectorName Name of selector for which resolver should be invalidated.
1870 * @param {unknown[]} args Arguments to associate for uniqueness.
1871 *
1872 * @return {{ type: 'INVALIDATE_RESOLUTION', selectorName: string, args: any[] }} Action object.
1873 */
1874
1875 function invalidateResolution(selectorName, args) {
1876 return {
1877 type: 'INVALIDATE_RESOLUTION',
1878 selectorName,
1879 args
1880 };
1881 }
1882 /**
1883 * Returns an action object used in signalling that the resolution
1884 * should be invalidated.
1885 *
1886 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE' }} Action object.
1887 */
1888
1889 function invalidateResolutionForStore() {
1890 return {
1891 type: 'INVALIDATE_RESOLUTION_FOR_STORE'
1892 };
1893 }
1894 /**
1895 * Returns an action object used in signalling that the resolution cache for a
1896 * given selectorName should be invalidated.
1897 *
1898 * @param {string} selectorName Name of selector for which all resolvers should
1899 * be invalidated.
1900 *
1901 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR', selectorName: string }} Action object.
1902 */
1903
1904 function invalidateResolutionForStoreSelector(selectorName) {
1905 return {
1906 type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR',
1907 selectorName
1908 };
1909 }
1910 //# sourceMappingURL=actions.js.map
1911 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/index.js
1912 /**
1913 * External dependencies
1914 */
1915
1916
1917
1918
1919 /**
1920 * WordPress dependencies
1921 */
1922
1923
1924 /**
1925 * Internal dependencies
1926 */
1927
1928
1929
1930
1931
1932
1933
1934
1935 /** @typedef {import('../types').DataRegistry} DataRegistry */
1936
1937 /** @typedef {import('../types').StoreDescriptor} StoreDescriptor */
1938
1939 /** @typedef {import('../types').ReduxStoreConfig} ReduxStoreConfig */
1940
1941 const trimUndefinedValues = array => {
1942 const result = [...array];
1943
1944 for (let i = result.length - 1; i >= 0; i--) {
1945 if (result[i] === undefined) {
1946 result.splice(i, 1);
1947 }
1948 }
1949
1950 return result;
1951 };
1952 /**
1953 * Create a cache to track whether resolvers started running or not.
1954 *
1955 * @return {Object} Resolvers Cache.
1956 */
1957
1958
1959 function createResolversCache() {
1960 const cache = {};
1961 return {
1962 isRunning(selectorName, args) {
1963 return cache[selectorName] && cache[selectorName].get(trimUndefinedValues(args));
1964 },
1965
1966 clear(selectorName, args) {
1967 if (cache[selectorName]) {
1968 cache[selectorName].delete(trimUndefinedValues(args));
1969 }
1970 },
1971
1972 markAsRunning(selectorName, args) {
1973 if (!cache[selectorName]) {
1974 cache[selectorName] = new (equivalent_key_map_default())();
1975 }
1976
1977 cache[selectorName].set(trimUndefinedValues(args), true);
1978 }
1979
1980 };
1981 }
1982 /**
1983 * Creates a data store descriptor for the provided Redux store configuration containing
1984 * properties describing reducer, actions, selectors, controls and resolvers.
1985 *
1986 * @example
1987 * ```js
1988 * import { createReduxStore } from '@wordpress/data';
1989 *
1990 * const store = createReduxStore( 'demo', {
1991 * reducer: ( state = 'OK' ) => state,
1992 * selectors: {
1993 * getValue: ( state ) => state,
1994 * },
1995 * } );
1996 * ```
1997 *
1998 * @param {string} key Unique namespace identifier.
1999 * @param {ReduxStoreConfig} options Registered store options, with properties
2000 * describing reducer, actions, selectors,
2001 * and resolvers.
2002 *
2003 * @return {StoreDescriptor} Store Object.
2004 */
2005
2006
2007 function createReduxStore(key, options) {
2008 return {
2009 name: key,
2010 instantiate: registry => {
2011 const reducer = options.reducer;
2012 const thunkArgs = {
2013 registry,
2014
2015 get dispatch() {
2016 return Object.assign(action => store.dispatch(action), getActions());
2017 },
2018
2019 get select() {
2020 return Object.assign(selector => selector(store.__unstableOriginalGetState()), getSelectors());
2021 },
2022
2023 get resolveSelect() {
2024 return getResolveSelectors();
2025 }
2026
2027 };
2028 const store = instantiateReduxStore(key, options, registry, thunkArgs);
2029 const resolversCache = createResolversCache();
2030 let resolvers;
2031 const actions = mapActions({ ...actions_namespaceObject,
2032 ...options.actions
2033 }, store);
2034 let selectors = mapSelectors({ ...(0,external_lodash_namespaceObject.mapValues)(selectors_namespaceObject, selector => function (state) {
2035 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2036 args[_key - 1] = arguments[_key];
2037 }
2038
2039 return selector(state.metadata, ...args);
2040 }),
2041 ...(0,external_lodash_namespaceObject.mapValues)(options.selectors, selector => {
2042 if (selector.isRegistrySelector) {
2043 selector.registry = registry;
2044 }
2045
2046 return function (state) {
2047 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2048 args[_key2 - 1] = arguments[_key2];
2049 }
2050
2051 return selector(state.root, ...args);
2052 };
2053 })
2054 }, store);
2055
2056 if (options.resolvers) {
2057 const result = mapResolvers(options.resolvers, selectors, store, resolversCache);
2058 resolvers = result.resolvers;
2059 selectors = result.selectors;
2060 }
2061
2062 const resolveSelectors = mapResolveSelectors(selectors, store);
2063
2064 const getSelectors = () => selectors;
2065
2066 const getActions = () => actions;
2067
2068 const getResolveSelectors = () => resolveSelectors; // We have some modules monkey-patching the store object
2069 // It's wrong to do so but until we refactor all of our effects to controls
2070 // We need to keep the same "store" instance here.
2071
2072
2073 store.__unstableOriginalGetState = store.getState;
2074
2075 store.getState = () => store.__unstableOriginalGetState().root; // Customize subscribe behavior to call listeners only on effective change,
2076 // not on every dispatch.
2077
2078
2079 const subscribe = store && (listener => {
2080 let lastState = store.__unstableOriginalGetState();
2081
2082 return store.subscribe(() => {
2083 const state = store.__unstableOriginalGetState();
2084
2085 const hasChanged = state !== lastState;
2086 lastState = state;
2087
2088 if (hasChanged) {
2089 listener();
2090 }
2091 });
2092 }); // This can be simplified to just { subscribe, getSelectors, getActions }
2093 // Once we remove the use function.
2094
2095
2096 return {
2097 reducer,
2098 store,
2099 actions,
2100 selectors,
2101 resolvers,
2102 getSelectors,
2103 getResolveSelectors,
2104 getActions,
2105 subscribe
2106 };
2107 }
2108 };
2109 }
2110 /**
2111 * Creates a redux store for a namespace.
2112 *
2113 * @param {string} key Unique namespace identifier.
2114 * @param {Object} options Registered store options, with properties
2115 * describing reducer, actions, selectors,
2116 * and resolvers.
2117 * @param {DataRegistry} registry Registry reference.
2118 * @param {Object} thunkArgs Argument object for the thunk middleware.
2119 * @return {Object} Newly created redux store.
2120 */
2121
2122 function instantiateReduxStore(key, options, registry, thunkArgs) {
2123 const controls = { ...options.controls,
2124 ...builtinControls
2125 };
2126 const normalizedControls = (0,external_lodash_namespaceObject.mapValues)(controls, control => control.isRegistryControl ? control(registry) : control);
2127 const middlewares = [resolvers_cache_middleware(registry, key), promise_middleware, external_wp_reduxRoutine_default()(normalizedControls)];
2128
2129 if (options.__experimentalUseThunks) {
2130 middlewares.push(createThunkMiddleware(thunkArgs));
2131 }
2132
2133 const enhancers = [applyMiddleware(...middlewares)];
2134
2135 if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
2136 enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__({
2137 name: key,
2138 instanceId: key
2139 }));
2140 }
2141
2142 const {
2143 reducer,
2144 initialState
2145 } = options;
2146 const enhancedReducer = turbo_combine_reducers_default()({
2147 metadata: metadata_reducer,
2148 root: reducer
2149 });
2150 return createStore(enhancedReducer, {
2151 root: initialState
2152 }, (0,external_lodash_namespaceObject.flowRight)(enhancers));
2153 }
2154 /**
2155 * Maps selectors to a store.
2156 *
2157 * @param {Object} selectors Selectors to register. Keys will be used as the
2158 * public facing API. Selectors will get passed the
2159 * state as first argument.
2160 * @param {Object} store The store to which the selectors should be mapped.
2161 * @return {Object} Selectors mapped to the provided store.
2162 */
2163
2164
2165 function mapSelectors(selectors, store) {
2166 const createStateSelector = registrySelector => {
2167 const selector = function runSelector() {
2168 // This function is an optimized implementation of:
2169 //
2170 // selector( store.getState(), ...arguments )
2171 //
2172 // Where the above would incur an `Array#concat` in its application,
2173 // the logic here instead efficiently constructs an arguments array via
2174 // direct assignment.
2175 const argsLength = arguments.length;
2176 const args = new Array(argsLength + 1);
2177 args[0] = store.__unstableOriginalGetState();
2178
2179 for (let i = 0; i < argsLength; i++) {
2180 args[i + 1] = arguments[i];
2181 }
2182
2183 return registrySelector(...args);
2184 };
2185
2186 selector.hasResolver = false;
2187 return selector;
2188 };
2189
2190 return (0,external_lodash_namespaceObject.mapValues)(selectors, createStateSelector);
2191 }
2192 /**
2193 * Maps actions to dispatch from a given store.
2194 *
2195 * @param {Object} actions Actions to register.
2196 * @param {Object} store The redux store to which the actions should be mapped.
2197 *
2198 * @return {Object} Actions mapped to the redux store provided.
2199 */
2200
2201
2202 function mapActions(actions, store) {
2203 const createBoundAction = action => function () {
2204 return Promise.resolve(store.dispatch(action(...arguments)));
2205 };
2206
2207 return (0,external_lodash_namespaceObject.mapValues)(actions, createBoundAction);
2208 }
2209 /**
2210 * Maps selectors to functions that return a resolution promise for them
2211 *
2212 * @param {Object} selectors Selectors to map.
2213 * @param {Object} store The redux store the selectors select from.
2214 *
2215 * @return {Object} Selectors mapped to their resolution functions.
2216 */
2217
2218
2219 function mapResolveSelectors(selectors, store) {
2220 return (0,external_lodash_namespaceObject.mapValues)((0,external_lodash_namespaceObject.omit)(selectors, ['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers']), (selector, selectorName) => function () {
2221 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
2222 args[_key3] = arguments[_key3];
2223 }
2224
2225 return new Promise(resolve => {
2226 const hasFinished = () => selectors.hasFinishedResolution(selectorName, args);
2227
2228 const getResult = () => selector.apply(null, args); // trigger the selector (to trigger the resolver)
2229
2230
2231 const result = getResult();
2232
2233 if (hasFinished()) {
2234 return resolve(result);
2235 }
2236
2237 const unsubscribe = store.subscribe(() => {
2238 if (hasFinished()) {
2239 unsubscribe();
2240 resolve(getResult());
2241 }
2242 });
2243 });
2244 });
2245 }
2246 /**
2247 * Returns resolvers with matched selectors for a given namespace.
2248 * Resolvers are side effects invoked once per argument set of a given selector call,
2249 * used in ensuring that the data needs for the selector are satisfied.
2250 *
2251 * @param {Object} resolvers Resolvers to register.
2252 * @param {Object} selectors The current selectors to be modified.
2253 * @param {Object} store The redux store to which the resolvers should be mapped.
2254 * @param {Object} resolversCache Resolvers Cache.
2255 */
2256
2257
2258 function mapResolvers(resolvers, selectors, store, resolversCache) {
2259 // The `resolver` can be either a function that does the resolution, or, in more advanced
2260 // cases, an object with a `fullfill` method and other optional methods like `isFulfilled`.
2261 // Here we normalize the `resolver` function to an object with `fulfill` method.
2262 const mappedResolvers = (0,external_lodash_namespaceObject.mapValues)(resolvers, resolver => {
2263 if (resolver.fulfill) {
2264 return resolver;
2265 }
2266
2267 return { ...resolver,
2268 // copy the enumerable properties of the resolver function
2269 fulfill: resolver // add the fulfill method
2270
2271 };
2272 });
2273
2274 const mapSelector = (selector, selectorName) => {
2275 const resolver = resolvers[selectorName];
2276
2277 if (!resolver) {
2278 selector.hasResolver = false;
2279 return selector;
2280 }
2281
2282 const selectorResolver = function () {
2283 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
2284 args[_key4] = arguments[_key4];
2285 }
2286
2287 async function fulfillSelector() {
2288 const state = store.getState();
2289
2290 if (resolversCache.isRunning(selectorName, args) || typeof resolver.isFulfilled === 'function' && resolver.isFulfilled(state, ...args)) {
2291 return;
2292 }
2293
2294 const {
2295 metadata
2296 } = store.__unstableOriginalGetState();
2297
2298 if (hasStartedResolution(metadata, selectorName, args)) {
2299 return;
2300 }
2301
2302 resolversCache.markAsRunning(selectorName, args);
2303 setTimeout(async () => {
2304 resolversCache.clear(selectorName, args);
2305 store.dispatch(startResolution(selectorName, args));
2306 await fulfillResolver(store, mappedResolvers, selectorName, ...args);
2307 store.dispatch(finishResolution(selectorName, args));
2308 });
2309 }
2310
2311 fulfillSelector(...args);
2312 return selector(...args);
2313 };
2314
2315 selectorResolver.hasResolver = true;
2316 return selectorResolver;
2317 };
2318
2319 return {
2320 resolvers: mappedResolvers,
2321 selectors: (0,external_lodash_namespaceObject.mapValues)(selectors, mapSelector)
2322 };
2323 }
2324 /**
2325 * Calls a resolver given arguments
2326 *
2327 * @param {Object} store Store reference, for fulfilling via resolvers
2328 * @param {Object} resolvers Store Resolvers
2329 * @param {string} selectorName Selector name to fulfill.
2330 * @param {Array} args Selector Arguments.
2331 */
2332
2333
2334 async function fulfillResolver(store, resolvers, selectorName) {
2335 const resolver = (0,external_lodash_namespaceObject.get)(resolvers, [selectorName]);
2336
2337 if (!resolver) {
2338 return;
2339 }
2340
2341 for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key5 = 3; _key5 < _len5; _key5++) {
2342 args[_key5 - 3] = arguments[_key5];
2343 }
2344
2345 const action = resolver.fulfill(...args);
2346
2347 if (action) {
2348 await store.dispatch(action);
2349 }
2350 }
2351 //# sourceMappingURL=index.js.map
2352 ;// CONCATENATED MODULE: ./packages/data/build-module/utils/emitter.js
2353 /**
2354 * Create an event emitter.
2355 *
2356 * @return {import("../types").DataEmitter} Emitter.
2357 */
2358 function createEmitter() {
2359 let isPaused = false;
2360 let isPending = false;
2361 const listeners = new Set();
2362
2363 const notifyListeners = () => // We use Array.from to clone the listeners Set
2364 // This ensures that we don't run a listener
2365 // that was added as a response to another listener.
2366 Array.from(listeners).forEach(listener => listener());
2367
2368 return {
2369 get isPaused() {
2370 return isPaused;
2371 },
2372
2373 subscribe(listener) {
2374 listeners.add(listener);
2375 return () => listeners.delete(listener);
2376 },
2377
2378 pause() {
2379 isPaused = true;
2380 },
2381
2382 resume() {
2383 isPaused = false;
2384
2385 if (isPending) {
2386 isPending = false;
2387 notifyListeners();
2388 }
2389 },
2390
2391 emit() {
2392 if (isPaused) {
2393 isPending = true;
2394 return;
2395 }
2396
2397 notifyListeners();
2398 }
2399
2400 };
2401 }
2402 //# sourceMappingURL=emitter.js.map
2403 ;// CONCATENATED MODULE: ./packages/data/build-module/registry.js
2404 /**
2405 * External dependencies
2406 */
2407
2408 /**
2409 * WordPress dependencies
2410 */
2411
2412
2413 /**
2414 * Internal dependencies
2415 */
2416
2417
2418
2419
2420 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
2421
2422 /**
2423 * @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
2424 *
2425 * @property {Function} registerGenericStore Given a namespace key and settings
2426 * object, registers a new generic
2427 * store.
2428 * @property {Function} registerStore Given a namespace key and settings
2429 * object, registers a new namespace
2430 * store.
2431 * @property {Function} subscribe Given a function callback, invokes
2432 * the callback on any change to state
2433 * within any registered store.
2434 * @property {Function} select Given a namespace key, returns an
2435 * object of the store's registered
2436 * selectors.
2437 * @property {Function} dispatch Given a namespace key, returns an
2438 * object of the store's registered
2439 * action dispatchers.
2440 */
2441
2442 /**
2443 * @typedef {Object} WPDataPlugin An object of registry function overrides.
2444 *
2445 * @property {Function} registerStore registers store.
2446 */
2447
2448 /**
2449 * Creates a new store registry, given an optional object of initial store
2450 * configurations.
2451 *
2452 * @param {Object} storeConfigs Initial store configurations.
2453 * @param {Object?} parent Parent registry.
2454 *
2455 * @return {WPDataRegistry} Data registry.
2456 */
2457
2458 function createRegistry() {
2459 let storeConfigs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2460 let parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2461 const stores = {};
2462 const emitter = createEmitter();
2463
2464 const __experimentalListeningStores = new Set();
2465 /**
2466 * Global listener called for each store's update.
2467 */
2468
2469
2470 function globalListener() {
2471 emitter.emit();
2472 }
2473 /**
2474 * Subscribe to changes to any data.
2475 *
2476 * @param {Function} listener Listener function.
2477 *
2478 * @return {Function} Unsubscribe function.
2479 */
2480
2481
2482 const subscribe = listener => {
2483 return emitter.subscribe(listener);
2484 };
2485 /**
2486 * Calls a selector given the current state and extra arguments.
2487 *
2488 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2489 * or the store descriptor.
2490 *
2491 * @return {*} The selector's returned value.
2492 */
2493
2494
2495 function select(storeNameOrDescriptor) {
2496 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2497
2498 __experimentalListeningStores.add(storeName);
2499
2500 const store = stores[storeName];
2501
2502 if (store) {
2503 return store.getSelectors();
2504 }
2505
2506 return parent && parent.select(storeName);
2507 }
2508
2509 function __experimentalMarkListeningStores(callback, ref) {
2510 __experimentalListeningStores.clear();
2511
2512 const result = callback.call(this);
2513 ref.current = Array.from(__experimentalListeningStores);
2514 return result;
2515 }
2516 /**
2517 * Given the name of a registered store, returns an object containing the store's
2518 * selectors pre-bound to state so that you only need to supply additional arguments,
2519 * and modified so that they return promises that resolve to their eventual values,
2520 * after any resolvers have ran.
2521 *
2522 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2523 * or the store descriptor.
2524 *
2525 * @return {Object} Each key of the object matches the name of a selector.
2526 */
2527
2528
2529 function resolveSelect(storeNameOrDescriptor) {
2530 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2531
2532 __experimentalListeningStores.add(storeName);
2533
2534 const store = stores[storeName];
2535
2536 if (store) {
2537 return store.getResolveSelectors();
2538 }
2539
2540 return parent && parent.resolveSelect(storeName);
2541 }
2542 /**
2543 * Returns the available actions for a part of the state.
2544 *
2545 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2546 * or the store descriptor.
2547 *
2548 * @return {*} The action's returned value.
2549 */
2550
2551
2552 function dispatch(storeNameOrDescriptor) {
2553 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2554 const store = stores[storeName];
2555
2556 if (store) {
2557 return store.getActions();
2558 }
2559
2560 return parent && parent.dispatch(storeName);
2561 } //
2562 // Deprecated
2563 // TODO: Remove this after `use()` is removed.
2564 //
2565
2566
2567 function withPlugins(attributes) {
2568 return (0,external_lodash_namespaceObject.mapValues)(attributes, (attribute, key) => {
2569 if (typeof attribute !== 'function') {
2570 return attribute;
2571 }
2572
2573 return function () {
2574 return registry[key].apply(null, arguments);
2575 };
2576 });
2577 }
2578 /**
2579 * Registers a store instance.
2580 *
2581 * @param {string} name Store registry name.
2582 * @param {Object} store Store instance object (getSelectors, getActions, subscribe).
2583 */
2584
2585
2586 function registerStoreInstance(name, store) {
2587 if (typeof store.getSelectors !== 'function') {
2588 throw new TypeError('store.getSelectors must be a function');
2589 }
2590
2591 if (typeof store.getActions !== 'function') {
2592 throw new TypeError('store.getActions must be a function');
2593 }
2594
2595 if (typeof store.subscribe !== 'function') {
2596 throw new TypeError('store.subscribe must be a function');
2597 } // The emitter is used to keep track of active listeners when the registry
2598 // get paused, that way, when resumed we should be able to call all these
2599 // pending listeners.
2600
2601
2602 store.emitter = createEmitter();
2603 const currentSubscribe = store.subscribe;
2604
2605 store.subscribe = listener => {
2606 const unsubscribeFromEmitter = store.emitter.subscribe(listener);
2607 const unsubscribeFromStore = currentSubscribe(() => {
2608 if (store.emitter.isPaused) {
2609 store.emitter.emit();
2610 return;
2611 }
2612
2613 listener();
2614 });
2615 return () => {
2616 unsubscribeFromStore === null || unsubscribeFromStore === void 0 ? void 0 : unsubscribeFromStore();
2617 unsubscribeFromEmitter === null || unsubscribeFromEmitter === void 0 ? void 0 : unsubscribeFromEmitter();
2618 };
2619 };
2620
2621 stores[name] = store;
2622 store.subscribe(globalListener);
2623 }
2624 /**
2625 * Registers a new store given a store descriptor.
2626 *
2627 * @param {StoreDescriptor} store Store descriptor.
2628 */
2629
2630
2631 function register(store) {
2632 registerStoreInstance(store.name, store.instantiate(registry));
2633 }
2634
2635 function registerGenericStore(name, store) {
2636 external_wp_deprecated_default()('wp.data.registerGenericStore', {
2637 since: '5.9',
2638 alternative: 'wp.data.register( storeDescriptor )'
2639 });
2640 registerStoreInstance(name, store);
2641 }
2642 /**
2643 * Registers a standard `@wordpress/data` store.
2644 *
2645 * @param {string} storeName Unique namespace identifier.
2646 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
2647 *
2648 * @return {Object} Registered store object.
2649 */
2650
2651
2652 function registerStore(storeName, options) {
2653 if (!options.reducer) {
2654 throw new TypeError('Must specify store reducer');
2655 }
2656
2657 const store = createReduxStore(storeName, options).instantiate(registry);
2658 registerStoreInstance(storeName, store);
2659 return store.store;
2660 }
2661 /**
2662 * Subscribe handler to a store.
2663 *
2664 * @param {string[]} storeName The store name.
2665 * @param {Function} handler The function subscribed to the store.
2666 * @return {Function} A function to unsubscribe the handler.
2667 */
2668
2669
2670 function __experimentalSubscribeStore(storeName, handler) {
2671 if (storeName in stores) {
2672 return stores[storeName].subscribe(handler);
2673 } // Trying to access a store that hasn't been registered,
2674 // this is a pattern rarely used but seen in some places.
2675 // We fallback to regular `subscribe` here for backward-compatibility for now.
2676 // See https://github.com/WordPress/gutenberg/pull/27466 for more info.
2677
2678
2679 if (!parent) {
2680 return subscribe(handler);
2681 }
2682
2683 return parent.__experimentalSubscribeStore(storeName, handler);
2684 }
2685
2686 function batch(callback) {
2687 emitter.pause();
2688 (0,external_lodash_namespaceObject.forEach)(stores, store => store.emitter.pause());
2689 callback();
2690 emitter.resume();
2691 (0,external_lodash_namespaceObject.forEach)(stores, store => store.emitter.resume());
2692 }
2693
2694 let registry = {
2695 batch,
2696 stores,
2697 namespaces: stores,
2698 // TODO: Deprecate/remove this.
2699 subscribe,
2700 select,
2701 resolveSelect,
2702 dispatch,
2703 use,
2704 register,
2705 registerGenericStore,
2706 registerStore,
2707 __experimentalMarkListeningStores,
2708 __experimentalSubscribeStore
2709 }; //
2710 // TODO:
2711 // This function will be deprecated as soon as it is no longer internally referenced.
2712 //
2713
2714 function use(plugin, options) {
2715 registry = { ...registry,
2716 ...plugin(registry, options)
2717 };
2718 return registry;
2719 }
2720
2721 registry.register(store);
2722
2723 for (const [name, config] of Object.entries(storeConfigs)) {
2724 registry.register(createReduxStore(name, config));
2725 }
2726
2727 if (parent) {
2728 parent.subscribe(globalListener);
2729 }
2730
2731 return withPlugins(registry);
2732 }
2733 //# sourceMappingURL=registry.js.map
2734 ;// CONCATENATED MODULE: ./packages/data/build-module/default-registry.js
2735 /**
2736 * Internal dependencies
2737 */
2738
2739 /* harmony default export */ var default_registry = (createRegistry());
2740 //# sourceMappingURL=default-registry.js.map
2741 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/controls/index.js
2742 /**
2743 * WordPress dependencies
2744 */
2745
2746 /* harmony default export */ var plugins_controls = (registry => {
2747 external_wp_deprecated_default()('wp.data.plugins.controls', {
2748 since: '5.4',
2749 hint: 'The controls plugins is now baked-in.'
2750 });
2751 return registry;
2752 });
2753 //# sourceMappingURL=index.js.map
2754 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/object.js
2755 let objectStorage;
2756 const storage = {
2757 getItem(key) {
2758 if (!objectStorage || !objectStorage[key]) {
2759 return null;
2760 }
2761
2762 return objectStorage[key];
2763 },
2764
2765 setItem(key, value) {
2766 if (!objectStorage) {
2767 storage.clear();
2768 }
2769
2770 objectStorage[key] = String(value);
2771 },
2772
2773 clear() {
2774 objectStorage = Object.create(null);
2775 }
2776
2777 };
2778 /* harmony default export */ var object = (storage);
2779 //# sourceMappingURL=object.js.map
2780 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/default.js
2781 /**
2782 * Internal dependencies
2783 */
2784
2785 let default_storage;
2786
2787 try {
2788 // Private Browsing in Safari 10 and earlier will throw an error when
2789 // attempting to set into localStorage. The test here is intentional in
2790 // causing a thrown error as condition for using fallback object storage.
2791 default_storage = window.localStorage;
2792 default_storage.setItem('__wpDataTestLocalStorage', '');
2793 default_storage.removeItem('__wpDataTestLocalStorage');
2794 } catch (error) {
2795 default_storage = object;
2796 }
2797
2798 /* harmony default export */ var storage_default = (default_storage);
2799 //# sourceMappingURL=default.js.map
2800 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/index.js
2801 /**
2802 * External dependencies
2803 */
2804
2805 /**
2806 * Internal dependencies
2807 */
2808
2809
2810
2811 /** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
2812
2813 /** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
2814
2815 /**
2816 * @typedef {Object} WPDataPersistencePluginOptions Persistence plugin options.
2817 *
2818 * @property {Storage} storage Persistent storage implementation. This must
2819 * at least implement `getItem` and `setItem` of
2820 * the Web Storage API.
2821 * @property {string} storageKey Key on which to set in persistent storage.
2822 *
2823 */
2824
2825 /**
2826 * Default plugin storage.
2827 *
2828 * @type {Storage}
2829 */
2830
2831 const DEFAULT_STORAGE = storage_default;
2832 /**
2833 * Default plugin storage key.
2834 *
2835 * @type {string}
2836 */
2837
2838 const DEFAULT_STORAGE_KEY = 'WP_DATA';
2839 /**
2840 * Higher-order reducer which invokes the original reducer only if state is
2841 * inequal from that of the action's `nextState` property, otherwise returning
2842 * the original state reference.
2843 *
2844 * @param {Function} reducer Original reducer.
2845 *
2846 * @return {Function} Enhanced reducer.
2847 */
2848
2849 const withLazySameState = reducer => (state, action) => {
2850 if (action.nextState === state) {
2851 return state;
2852 }
2853
2854 return reducer(state, action);
2855 };
2856 /**
2857 * Creates a persistence interface, exposing getter and setter methods (`get`
2858 * and `set` respectively).
2859 *
2860 * @param {WPDataPersistencePluginOptions} options Plugin options.
2861 *
2862 * @return {Object} Persistence interface.
2863 */
2864
2865 function createPersistenceInterface(options) {
2866 const {
2867 storage = DEFAULT_STORAGE,
2868 storageKey = DEFAULT_STORAGE_KEY
2869 } = options;
2870 let data;
2871 /**
2872 * Returns the persisted data as an object, defaulting to an empty object.
2873 *
2874 * @return {Object} Persisted data.
2875 */
2876
2877 function getData() {
2878 if (data === undefined) {
2879 // If unset, getItem is expected to return null. Fall back to
2880 // empty object.
2881 const persisted = storage.getItem(storageKey);
2882
2883 if (persisted === null) {
2884 data = {};
2885 } else {
2886 try {
2887 data = JSON.parse(persisted);
2888 } catch (error) {
2889 // Similarly, should any error be thrown during parse of
2890 // the string (malformed JSON), fall back to empty object.
2891 data = {};
2892 }
2893 }
2894 }
2895
2896 return data;
2897 }
2898 /**
2899 * Merges an updated reducer state into the persisted data.
2900 *
2901 * @param {string} key Key to update.
2902 * @param {*} value Updated value.
2903 */
2904
2905
2906 function setData(key, value) {
2907 data = { ...data,
2908 [key]: value
2909 };
2910 storage.setItem(storageKey, JSON.stringify(data));
2911 }
2912
2913 return {
2914 get: getData,
2915 set: setData
2916 };
2917 }
2918 /**
2919 * Data plugin to persist store state into a single storage key.
2920 *
2921 * @param {WPDataRegistry} registry Data registry.
2922 * @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
2923 *
2924 * @return {WPDataPlugin} Data plugin.
2925 */
2926
2927 function persistencePlugin(registry, pluginOptions) {
2928 const persistence = createPersistenceInterface(pluginOptions);
2929 /**
2930 * Creates an enhanced store dispatch function, triggering the state of the
2931 * given store name to be persisted when changed.
2932 *
2933 * @param {Function} getState Function which returns current state.
2934 * @param {string} storeName Store name.
2935 * @param {?Array<string>} keys Optional subset of keys to save.
2936 *
2937 * @return {Function} Enhanced dispatch function.
2938 */
2939
2940 function createPersistOnChange(getState, storeName, keys) {
2941 let getPersistedState;
2942
2943 if (Array.isArray(keys)) {
2944 // Given keys, the persisted state should by produced as an object
2945 // of the subset of keys. This implementation uses combineReducers
2946 // to leverage its behavior of returning the same object when none
2947 // of the property values changes. This allows a strict reference
2948 // equality to bypass a persistence set on an unchanging state.
2949 const reducers = keys.reduce((accumulator, key) => Object.assign(accumulator, {
2950 [key]: (state, action) => action.nextState[key]
2951 }), {});
2952 getPersistedState = withLazySameState(turbo_combine_reducers_default()(reducers));
2953 } else {
2954 getPersistedState = (state, action) => action.nextState;
2955 }
2956
2957 let lastState = getPersistedState(undefined, {
2958 nextState: getState()
2959 });
2960 return () => {
2961 const state = getPersistedState(lastState, {
2962 nextState: getState()
2963 });
2964
2965 if (state !== lastState) {
2966 persistence.set(storeName, state);
2967 lastState = state;
2968 }
2969 };
2970 }
2971
2972 return {
2973 registerStore(storeName, options) {
2974 if (!options.persist) {
2975 return registry.registerStore(storeName, options);
2976 } // Load from persistence to use as initial state.
2977
2978
2979 const persistedState = persistence.get()[storeName];
2980
2981 if (persistedState !== undefined) {
2982 let initialState = options.reducer(options.initialState, {
2983 type: '@@WP/PERSISTENCE_RESTORE'
2984 });
2985
2986 if ((0,external_lodash_namespaceObject.isPlainObject)(initialState) && (0,external_lodash_namespaceObject.isPlainObject)(persistedState)) {
2987 // If state is an object, ensure that:
2988 // - Other keys are left intact when persisting only a
2989 // subset of keys.
2990 // - New keys in what would otherwise be used as initial
2991 // state are deeply merged as base for persisted value.
2992 initialState = (0,external_lodash_namespaceObject.merge)({}, initialState, persistedState);
2993 } else {
2994 // If there is a mismatch in object-likeness of default
2995 // initial or persisted state, defer to persisted value.
2996 initialState = persistedState;
2997 }
2998
2999 options = { ...options,
3000 initialState
3001 };
3002 }
3003
3004 const store = registry.registerStore(storeName, options);
3005 store.subscribe(createPersistOnChange(store.getState, storeName, options.persist));
3006 return store;
3007 }
3008
3009 };
3010 }
3011 /**
3012 * Move the 'features' object in local storage from the sourceStoreName to the
3013 * interface store.
3014 *
3015 * @param {Object} persistence The persistence interface.
3016 * @param {string} sourceStoreName The name of the store that has persisted
3017 * preferences to migrate to the interface
3018 * package.
3019 */
3020
3021
3022 function migrateFeaturePreferencesToInterfaceStore(persistence, sourceStoreName) {
3023 var _state$sourceStoreNam;
3024
3025 const interfaceStoreName = 'core/interface';
3026 const state = persistence.get();
3027 const sourcePreferences = (_state$sourceStoreNam = state[sourceStoreName]) === null || _state$sourceStoreNam === void 0 ? void 0 : _state$sourceStoreNam.preferences;
3028 const sourceFeatures = sourcePreferences === null || sourcePreferences === void 0 ? void 0 : sourcePreferences.features;
3029
3030 if (sourceFeatures) {
3031 var _state$interfaceStore, _state$interfaceStore2;
3032
3033 const targetFeatures = (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : (_state$interfaceStore2 = _state$interfaceStore.preferences) === null || _state$interfaceStore2 === void 0 ? void 0 : _state$interfaceStore2.features; // Avoid migrating features again if they've previously been migrated.
3034
3035 if (!(targetFeatures !== null && targetFeatures !== void 0 && targetFeatures[sourceStoreName])) {
3036 // Set the feature values in the interface store, the features
3037 // object is keyed by 'scope', which matches the store name for
3038 // the source.
3039 persistence.set(interfaceStoreName, {
3040 preferences: {
3041 features: { ...targetFeatures,
3042 [sourceStoreName]: sourceFeatures
3043 }
3044 }
3045 }); // Remove feature preferences from the source.
3046
3047 persistence.set(sourceStoreName, {
3048 preferences: { ...sourcePreferences,
3049 features: undefined
3050 }
3051 });
3052 }
3053 }
3054 }
3055 /**
3056 * Deprecated: Remove this function and the code in WordPress Core that calls
3057 * it once WordPress 6.0 is released.
3058 */
3059
3060 persistencePlugin.__unstableMigrate = pluginOptions => {
3061 const persistence = createPersistenceInterface(pluginOptions);
3062 migrateFeaturePreferencesToInterfaceStore(persistence, 'core/edit-widgets');
3063 migrateFeaturePreferencesToInterfaceStore(persistence, 'core/customize-widgets');
3064 migrateFeaturePreferencesToInterfaceStore(persistence, 'core/edit-post');
3065 };
3066
3067 /* harmony default export */ var persistence = (persistencePlugin);
3068 //# sourceMappingURL=index.js.map
3069 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/index.js
3070
3071
3072 //# sourceMappingURL=index.js.map
3073 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
3074 function _extends() {
3075 _extends = Object.assign || function (target) {
3076 for (var i = 1; i < arguments.length; i++) {
3077 var source = arguments[i];
3078
3079 for (var key in source) {
3080 if (Object.prototype.hasOwnProperty.call(source, key)) {
3081 target[key] = source[key];
3082 }
3083 }
3084 }
3085
3086 return target;
3087 };
3088
3089 return _extends.apply(this, arguments);
3090 }
3091 ;// CONCATENATED MODULE: external ["wp","element"]
3092 var external_wp_element_namespaceObject = window["wp"]["element"];
3093 ;// CONCATENATED MODULE: external ["wp","compose"]
3094 var external_wp_compose_namespaceObject = window["wp"]["compose"];
3095 ;// CONCATENATED MODULE: external "React"
3096 var external_React_namespaceObject = window["React"];
3097 ;// CONCATENATED MODULE: ./node_modules/use-memo-one/dist/use-memo-one.esm.js
3098
3099
3100 function areInputsEqual(newInputs, lastInputs) {
3101 if (newInputs.length !== lastInputs.length) {
3102 return false;
3103 }
3104
3105 for (var i = 0; i < newInputs.length; i++) {
3106 if (newInputs[i] !== lastInputs[i]) {
3107 return false;
3108 }
3109 }
3110
3111 return true;
3112 }
3113
3114 function useMemoOne(getResult, inputs) {
3115 var initial = (0,external_React_namespaceObject.useState)(function () {
3116 return {
3117 inputs: inputs,
3118 result: getResult()
3119 };
3120 })[0];
3121 var committed = (0,external_React_namespaceObject.useRef)(initial);
3122 var isInputMatch = Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs));
3123 var cache = isInputMatch ? committed.current : {
3124 inputs: inputs,
3125 result: getResult()
3126 };
3127 (0,external_React_namespaceObject.useEffect)(function () {
3128 committed.current = cache;
3129 }, [cache]);
3130 return cache.result;
3131 }
3132 function useCallbackOne(callback, inputs) {
3133 return useMemoOne(function () {
3134 return callback;
3135 }, inputs);
3136 }
3137 var useMemo = (/* unused pure expression or super */ null && (useMemoOne));
3138 var useCallback = (/* unused pure expression or super */ null && (useCallbackOne));
3139
3140
3141
3142 ;// CONCATENATED MODULE: external ["wp","priorityQueue"]
3143 var external_wp_priorityQueue_namespaceObject = window["wp"]["priorityQueue"];
3144 ;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
3145 var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
3146 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
3147 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/context.js
3148 /**
3149 * WordPress dependencies
3150 */
3151
3152 /**
3153 * Internal dependencies
3154 */
3155
3156
3157 const Context = (0,external_wp_element_namespaceObject.createContext)(default_registry);
3158 const {
3159 Consumer,
3160 Provider
3161 } = Context;
3162 /**
3163 * A custom react Context consumer exposing the provided `registry` to
3164 * children components. Used along with the RegistryProvider.
3165 *
3166 * You can read more about the react context api here:
3167 * https://reactjs.org/docs/context.html#contextprovider
3168 *
3169 * @example
3170 * ```js
3171 * import {
3172 * RegistryProvider,
3173 * RegistryConsumer,
3174 * createRegistry
3175 * } from '@wordpress/data';
3176 *
3177 * const registry = createRegistry( {} );
3178 *
3179 * const App = ( { props } ) => {
3180 * return <RegistryProvider value={ registry }>
3181 * <div>Hello There</div>
3182 * <RegistryConsumer>
3183 * { ( registry ) => (
3184 * <ComponentUsingRegistry
3185 * { ...props }
3186 * registry={ registry }
3187 * ) }
3188 * </RegistryConsumer>
3189 * </RegistryProvider>
3190 * }
3191 * ```
3192 */
3193
3194 const RegistryConsumer = Consumer;
3195 /**
3196 * A custom Context provider for exposing the provided `registry` to children
3197 * components via a consumer.
3198 *
3199 * See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
3200 * example.
3201 */
3202
3203 /* harmony default export */ var context = (Provider);
3204 //# sourceMappingURL=context.js.map
3205 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/use-registry.js
3206 /**
3207 * WordPress dependencies
3208 */
3209
3210 /**
3211 * Internal dependencies
3212 */
3213
3214
3215 /**
3216 * A custom react hook exposing the registry context for use.
3217 *
3218 * This exposes the `registry` value provided via the
3219 * <a href="#RegistryProvider">Registry Provider</a> to a component implementing
3220 * this hook.
3221 *
3222 * It acts similarly to the `useContext` react hook.
3223 *
3224 * Note: Generally speaking, `useRegistry` is a low level hook that in most cases
3225 * won't be needed for implementation. Most interactions with the `@wordpress/data`
3226 * API can be performed via the `useSelect` hook, or the `withSelect` and
3227 * `withDispatch` higher order components.
3228 *
3229 * @example
3230 * ```js
3231 * import {
3232 * RegistryProvider,
3233 * createRegistry,
3234 * useRegistry,
3235 * } from '@wordpress/data';
3236 *
3237 * const registry = createRegistry( {} );
3238 *
3239 * const SomeChildUsingRegistry = ( props ) => {
3240 * const registry = useRegistry();
3241 * // ...logic implementing the registry in other react hooks.
3242 * };
3243 *
3244 *
3245 * const ParentProvidingRegistry = ( props ) => {
3246 * return <RegistryProvider value={ registry }>
3247 * <SomeChildUsingRegistry { ...props } />
3248 * </RegistryProvider>
3249 * };
3250 * ```
3251 *
3252 * @return {Function} A custom react hook exposing the registry context value.
3253 */
3254
3255 function useRegistry() {
3256 return (0,external_wp_element_namespaceObject.useContext)(Context);
3257 }
3258 //# sourceMappingURL=use-registry.js.map
3259 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/context.js
3260 /**
3261 * WordPress dependencies
3262 */
3263
3264 const context_Context = (0,external_wp_element_namespaceObject.createContext)(false);
3265 const {
3266 Consumer: context_Consumer,
3267 Provider: context_Provider
3268 } = context_Context;
3269 const AsyncModeConsumer = (/* unused pure expression or super */ null && (context_Consumer));
3270 /**
3271 * Context Provider Component used to switch the data module component rerendering
3272 * between Sync and Async modes.
3273 *
3274 * @example
3275 *
3276 * ```js
3277 * import { useSelect, AsyncModeProvider } from '@wordpress/data';
3278 *
3279 * function BlockCount() {
3280 * const count = useSelect( ( select ) => {
3281 * return select( 'core/block-editor' ).getBlockCount()
3282 * }, [] );
3283 *
3284 * return count;
3285 * }
3286 *
3287 * function App() {
3288 * return (
3289 * <AsyncModeProvider value={ true }>
3290 * <BlockCount />
3291 * </AsyncModeProvider>
3292 * );
3293 * }
3294 * ```
3295 *
3296 * In this example, the BlockCount component is rerendered asynchronously.
3297 * It means if a more critical task is being performed (like typing in an input),
3298 * the rerendering is delayed until the browser becomes IDLE.
3299 * It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.
3300 *
3301 * @param {boolean} props.value Enable Async Mode.
3302 * @return {WPComponent} The component to be rendered.
3303 */
3304
3305 /* harmony default export */ var async_mode_provider_context = (context_Provider);
3306 //# sourceMappingURL=context.js.map
3307 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/use-async-mode.js
3308 /**
3309 * WordPress dependencies
3310 */
3311
3312 /**
3313 * Internal dependencies
3314 */
3315
3316
3317 function useAsyncMode() {
3318 return (0,external_wp_element_namespaceObject.useContext)(context_Context);
3319 }
3320 //# sourceMappingURL=use-async-mode.js.map
3321 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-select/index.js
3322 /**
3323 * External dependencies
3324 */
3325
3326 /**
3327 * WordPress dependencies
3328 */
3329
3330
3331
3332
3333
3334 /**
3335 * Internal dependencies
3336 */
3337
3338
3339
3340 const renderQueue = (0,external_wp_priorityQueue_namespaceObject.createQueue)();
3341 /** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */
3342
3343 /**
3344 * Custom react hook for retrieving props from registered selectors.
3345 *
3346 * In general, this custom React hook follows the
3347 * [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
3348 *
3349 * @param {Function|StoreDescriptor|string} _mapSelect Function called on every state change. The
3350 * returned value is exposed to the component
3351 * implementing this hook. The function receives
3352 * the `registry.select` method on the first
3353 * argument and the `registry` on the second
3354 * argument.
3355 * When a store key is passed, all selectors for
3356 * the store will be returned. This is only meant
3357 * for usage of these selectors in event
3358 * callbacks, not for data needed to create the
3359 * element tree.
3360 * @param {Array} deps If provided, this memoizes the mapSelect so the
3361 * same `mapSelect` is invoked on every state
3362 * change unless the dependencies change.
3363 *
3364 * @example
3365 * ```js
3366 * import { useSelect } from '@wordpress/data';
3367 *
3368 * function HammerPriceDisplay( { currency } ) {
3369 * const price = useSelect( ( select ) => {
3370 * return select( 'my-shop' ).getPrice( 'hammer', currency )
3371 * }, [ currency ] );
3372 * return new Intl.NumberFormat( 'en-US', {
3373 * style: 'currency',
3374 * currency,
3375 * } ).format( price );
3376 * }
3377 *
3378 * // Rendered in the application:
3379 * // <HammerPriceDisplay currency="USD" />
3380 * ```
3381 *
3382 * In the above example, when `HammerPriceDisplay` is rendered into an
3383 * application, the price will be retrieved from the store state using the
3384 * `mapSelect` callback on `useSelect`. If the currency prop changes then
3385 * any price in the state for that currency is retrieved. If the currency prop
3386 * doesn't change and other props are passed in that do change, the price will
3387 * not change because the dependency is just the currency.
3388 *
3389 * When data is only used in an event callback, the data should not be retrieved
3390 * on render, so it may be useful to get the selectors function instead.
3391 *
3392 * **Don't use `useSelect` this way when calling the selectors in the render
3393 * function because your component won't re-render on a data change.**
3394 *
3395 * ```js
3396 * import { useSelect } from '@wordpress/data';
3397 *
3398 * function Paste( { children } ) {
3399 * const { getSettings } = useSelect( 'my-shop' );
3400 * function onPaste() {
3401 * // Do something with the settings.
3402 * const settings = getSettings();
3403 * }
3404 * return <div onPaste={ onPaste }>{ children }</div>;
3405 * }
3406 * ```
3407 *
3408 * @return {Function} A custom react hook.
3409 */
3410
3411 function useSelect(_mapSelect, deps) {
3412 const isWithoutMapping = typeof _mapSelect !== 'function';
3413
3414 if (isWithoutMapping) {
3415 deps = [];
3416 }
3417
3418 const mapSelect = (0,external_wp_element_namespaceObject.useCallback)(_mapSelect, deps);
3419 const registry = useRegistry();
3420 const isAsync = useAsyncMode(); // React can sometimes clear the `useMemo` cache.
3421 // We use the cache-stable `useMemoOne` to avoid
3422 // losing queues.
3423
3424 const queueContext = useMemoOne(() => ({
3425 queue: true
3426 }), [registry]);
3427 const [, forceRender] = (0,external_wp_element_namespaceObject.useReducer)(s => s + 1, 0);
3428 const latestMapSelect = (0,external_wp_element_namespaceObject.useRef)();
3429 const latestIsAsync = (0,external_wp_element_namespaceObject.useRef)(isAsync);
3430 const latestMapOutput = (0,external_wp_element_namespaceObject.useRef)();
3431 const latestMapOutputError = (0,external_wp_element_namespaceObject.useRef)();
3432 const isMountedAndNotUnsubscribing = (0,external_wp_element_namespaceObject.useRef)(); // Keep track of the stores being selected in the mapSelect function,
3433 // and only subscribe to those stores later.
3434
3435 const listeningStores = (0,external_wp_element_namespaceObject.useRef)([]);
3436 const trapSelect = (0,external_wp_element_namespaceObject.useCallback)(callback => registry.__experimentalMarkListeningStores(callback, listeningStores), [registry]); // Generate a "flag" for used in the effect dependency array.
3437 // It's different than just using `mapSelect` since deps could be undefined,
3438 // in that case, we would still want to memoize it.
3439
3440 const depsChangedFlag = (0,external_wp_element_namespaceObject.useMemo)(() => ({}), deps || []);
3441 let mapOutput;
3442
3443 if (!isWithoutMapping) {
3444 try {
3445 if (latestMapSelect.current !== mapSelect || latestMapOutputError.current) {
3446 mapOutput = trapSelect(() => mapSelect(registry.select, registry));
3447 } else {
3448 mapOutput = latestMapOutput.current;
3449 }
3450 } catch (error) {
3451 let errorMessage = `An error occurred while running 'mapSelect': ${error.message}`;
3452
3453 if (latestMapOutputError.current) {
3454 errorMessage += `\nThe error may be correlated with this previous error:\n`;
3455 errorMessage += `${latestMapOutputError.current.stack}\n\n`;
3456 errorMessage += 'Original stack trace:';
3457 } // eslint-disable-next-line no-console
3458
3459
3460 console.error(errorMessage);
3461 mapOutput = latestMapOutput.current;
3462 }
3463 }
3464
3465 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3466 if (isWithoutMapping) {
3467 return;
3468 }
3469
3470 latestMapSelect.current = mapSelect;
3471 latestMapOutput.current = mapOutput;
3472 latestMapOutputError.current = undefined;
3473 isMountedAndNotUnsubscribing.current = true; // This has to run after the other ref updates
3474 // to avoid using stale values in the flushed
3475 // callbacks or potentially overwriting a
3476 // changed `latestMapOutput.current`.
3477
3478 if (latestIsAsync.current !== isAsync) {
3479 latestIsAsync.current = isAsync;
3480 renderQueue.flush(queueContext);
3481 }
3482 });
3483 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3484 if (isWithoutMapping) {
3485 return;
3486 }
3487
3488 const onStoreChange = () => {
3489 if (isMountedAndNotUnsubscribing.current) {
3490 try {
3491 const newMapOutput = trapSelect(() => latestMapSelect.current(registry.select, registry));
3492
3493 if (external_wp_isShallowEqual_default()(latestMapOutput.current, newMapOutput)) {
3494 return;
3495 }
3496
3497 latestMapOutput.current = newMapOutput;
3498 } catch (error) {
3499 latestMapOutputError.current = error;
3500 }
3501
3502 forceRender();
3503 }
3504 }; // catch any possible state changes during mount before the subscription
3505 // could be set.
3506
3507
3508 if (latestIsAsync.current) {
3509 renderQueue.add(queueContext, onStoreChange);
3510 } else {
3511 onStoreChange();
3512 }
3513
3514 const onChange = () => {
3515 if (latestIsAsync.current) {
3516 renderQueue.add(queueContext, onStoreChange);
3517 } else {
3518 onStoreChange();
3519 }
3520 };
3521
3522 const unsubscribers = listeningStores.current.map(storeName => registry.__experimentalSubscribeStore(storeName, onChange));
3523 return () => {
3524 isMountedAndNotUnsubscribing.current = false; // The return value of the subscribe function could be undefined if the store is a custom generic store.
3525
3526 unsubscribers.forEach(unsubscribe => unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
3527 renderQueue.flush(queueContext);
3528 };
3529 }, [registry, trapSelect, depsChangedFlag, isWithoutMapping]);
3530 return isWithoutMapping ? registry.select(_mapSelect) : mapOutput;
3531 }
3532 //# sourceMappingURL=index.js.map
3533 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-select/index.js
3534
3535
3536
3537 /**
3538 * WordPress dependencies
3539 */
3540
3541 /**
3542 * Internal dependencies
3543 */
3544
3545
3546 /**
3547 * Higher-order component used to inject state-derived props using registered
3548 * selectors.
3549 *
3550 * @param {Function} mapSelectToProps Function called on every state change,
3551 * expected to return object of props to
3552 * merge with the component's own props.
3553 *
3554 * @example
3555 * ```js
3556 * import { withSelect } from '@wordpress/data';
3557 *
3558 * function PriceDisplay( { price, currency } ) {
3559 * return new Intl.NumberFormat( 'en-US', {
3560 * style: 'currency',
3561 * currency,
3562 * } ).format( price );
3563 * }
3564 *
3565 * const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
3566 * const { getPrice } = select( 'my-shop' );
3567 * const { currency } = ownProps;
3568 *
3569 * return {
3570 * price: getPrice( 'hammer', currency ),
3571 * };
3572 * } )( PriceDisplay );
3573 *
3574 * // Rendered in the application:
3575 * //
3576 * // <HammerPriceDisplay currency="USD" />
3577 * ```
3578 * In the above example, when `HammerPriceDisplay` is rendered into an
3579 * application, it will pass the price into the underlying `PriceDisplay`
3580 * component and update automatically if the price of a hammer ever changes in
3581 * the store.
3582 *
3583 * @return {WPComponent} Enhanced component with merged state data props.
3584 */
3585
3586 const withSelect = mapSelectToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => (0,external_wp_compose_namespaceObject.pure)(ownProps => {
3587 const mapSelect = (select, registry) => mapSelectToProps(select, ownProps, registry);
3588
3589 const mergeProps = useSelect(mapSelect);
3590 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, mergeProps));
3591 }), 'withSelect');
3592
3593 /* harmony default export */ var with_select = (withSelect);
3594 //# sourceMappingURL=index.js.map
3595 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch-with-map.js
3596 /**
3597 * External dependencies
3598 */
3599
3600 /**
3601 * WordPress dependencies
3602 */
3603
3604
3605
3606 /**
3607 * Internal dependencies
3608 */
3609
3610
3611 /**
3612 * Custom react hook for returning aggregate dispatch actions using the provided
3613 * dispatchMap.
3614 *
3615 * Currently this is an internal api only and is implemented by `withDispatch`
3616 *
3617 * @param {Function} dispatchMap Receives the `registry.dispatch` function as
3618 * the first argument and the `registry` object
3619 * as the second argument. Should return an
3620 * object mapping props to functions.
3621 * @param {Array} deps An array of dependencies for the hook.
3622 * @return {Object} An object mapping props to functions created by the passed
3623 * in dispatchMap.
3624 */
3625
3626 const useDispatchWithMap = (dispatchMap, deps) => {
3627 const registry = useRegistry();
3628 const currentDispatchMap = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
3629 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3630 currentDispatchMap.current = dispatchMap;
3631 });
3632 return (0,external_wp_element_namespaceObject.useMemo)(() => {
3633 const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
3634 return (0,external_lodash_namespaceObject.mapValues)(currentDispatchProps, (dispatcher, propName) => {
3635 if (typeof dispatcher !== 'function') {
3636 // eslint-disable-next-line no-console
3637 console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
3638 }
3639
3640 return function () {
3641 return currentDispatchMap.current(registry.dispatch, registry)[propName](...arguments);
3642 };
3643 });
3644 }, [registry, ...deps]);
3645 };
3646
3647 /* harmony default export */ var use_dispatch_with_map = (useDispatchWithMap);
3648 //# sourceMappingURL=use-dispatch-with-map.js.map
3649 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-dispatch/index.js
3650
3651
3652
3653 /**
3654 * WordPress dependencies
3655 */
3656
3657 /**
3658 * Internal dependencies
3659 */
3660
3661
3662 /**
3663 * Higher-order component used to add dispatch props using registered action
3664 * creators.
3665 *
3666 * @param {Function} mapDispatchToProps A function of returning an object of
3667 * prop names where value is a
3668 * dispatch-bound action creator, or a
3669 * function to be called with the
3670 * component's props and returning an
3671 * action creator.
3672 *
3673 * @example
3674 * ```jsx
3675 * function Button( { onClick, children } ) {
3676 * return <button type="button" onClick={ onClick }>{ children }</button>;
3677 * }
3678 *
3679 * import { withDispatch } from '@wordpress/data';
3680 *
3681 * const SaleButton = withDispatch( ( dispatch, ownProps ) => {
3682 * const { startSale } = dispatch( 'my-shop' );
3683 * const { discountPercent } = ownProps;
3684 *
3685 * return {
3686 * onClick() {
3687 * startSale( discountPercent );
3688 * },
3689 * };
3690 * } )( Button );
3691 *
3692 * // Rendered in the application:
3693 * //
3694 * // <SaleButton discountPercent="20">Start Sale!</SaleButton>
3695 * ```
3696 *
3697 * @example
3698 * In the majority of cases, it will be sufficient to use only two first params
3699 * passed to `mapDispatchToProps` as illustrated in the previous example.
3700 * However, there might be some very advanced use cases where using the
3701 * `registry` object might be used as a tool to optimize the performance of
3702 * your component. Using `select` function from the registry might be useful
3703 * when you need to fetch some dynamic data from the store at the time when the
3704 * event is fired, but at the same time, you never use it to render your
3705 * component. In such scenario, you can avoid using the `withSelect` higher
3706 * order component to compute such prop, which might lead to unnecessary
3707 * re-renders of your component caused by its frequent value change.
3708 * Keep in mind, that `mapDispatchToProps` must return an object with functions
3709 * only.
3710 *
3711 * ```jsx
3712 * function Button( { onClick, children } ) {
3713 * return <button type="button" onClick={ onClick }>{ children }</button>;
3714 * }
3715 *
3716 * import { withDispatch } from '@wordpress/data';
3717 *
3718 * const SaleButton = withDispatch( ( dispatch, ownProps, { select } ) => {
3719 * // Stock number changes frequently.
3720 * const { getStockNumber } = select( 'my-shop' );
3721 * const { startSale } = dispatch( 'my-shop' );
3722 * return {
3723 * onClick() {
3724 * const discountPercent = getStockNumber() > 50 ? 10 : 20;
3725 * startSale( discountPercent );
3726 * },
3727 * };
3728 * } )( Button );
3729 *
3730 * // Rendered in the application:
3731 * //
3732 * // <SaleButton>Start Sale!</SaleButton>
3733 * ```
3734 *
3735 * _Note:_ It is important that the `mapDispatchToProps` function always
3736 * returns an object with the same keys. For example, it should not contain
3737 * conditions under which a different value would be returned.
3738 *
3739 * @return {WPComponent} Enhanced component with merged dispatcher props.
3740 */
3741
3742 const withDispatch = mapDispatchToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => ownProps => {
3743 const mapDispatch = (dispatch, registry) => mapDispatchToProps(dispatch, ownProps, registry);
3744
3745 const dispatchProps = use_dispatch_with_map(mapDispatch, []);
3746 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, dispatchProps));
3747 }, 'withDispatch');
3748
3749 /* harmony default export */ var with_dispatch = (withDispatch);
3750 //# sourceMappingURL=index.js.map
3751 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-registry/index.js
3752
3753
3754
3755 /**
3756 * WordPress dependencies
3757 */
3758
3759 /**
3760 * Internal dependencies
3761 */
3762
3763
3764 /**
3765 * Higher-order component which renders the original component with the current
3766 * registry context passed as its `registry` prop.
3767 *
3768 * @param {WPComponent} OriginalComponent Original component.
3769 *
3770 * @return {WPComponent} Enhanced component.
3771 */
3772
3773 const withRegistry = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => props => (0,external_wp_element_namespaceObject.createElement)(RegistryConsumer, null, registry => (0,external_wp_element_namespaceObject.createElement)(OriginalComponent, _extends({}, props, {
3774 registry: registry
3775 }))), 'withRegistry');
3776 /* harmony default export */ var with_registry = (withRegistry);
3777 //# sourceMappingURL=index.js.map
3778 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch.js
3779 /**
3780 * Internal dependencies
3781 */
3782
3783 /** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */
3784
3785 /**
3786 * A custom react hook returning the current registry dispatch actions creators.
3787 *
3788 * Note: The component using this hook must be within the context of a
3789 * RegistryProvider.
3790 *
3791 * @param {string|StoreDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
3792 * store or its descriptor from which to
3793 * retrieve action creators. If not
3794 * provided, the registry.dispatch
3795 * function is returned instead.
3796 *
3797 * @example
3798 * This illustrates a pattern where you may need to retrieve dynamic data from
3799 * the server via the `useSelect` hook to use in combination with the dispatch
3800 * action.
3801 *
3802 * ```jsx
3803 * import { useDispatch, useSelect } from '@wordpress/data';
3804 * import { useCallback } from '@wordpress/element';
3805 *
3806 * function Button( { onClick, children } ) {
3807 * return <button type="button" onClick={ onClick }>{ children }</button>
3808 * }
3809 *
3810 * const SaleButton = ( { children } ) => {
3811 * const { stockNumber } = useSelect(
3812 * ( select ) => select( 'my-shop' ).getStockNumber(),
3813 * []
3814 * );
3815 * const { startSale } = useDispatch( 'my-shop' );
3816 * const onClick = useCallback( () => {
3817 * const discountPercent = stockNumber > 50 ? 10: 20;
3818 * startSale( discountPercent );
3819 * }, [ stockNumber ] );
3820 * return <Button onClick={ onClick }>{ children }</Button>
3821 * }
3822 *
3823 * // Rendered somewhere in the application:
3824 * //
3825 * // <SaleButton>Start Sale!</SaleButton>
3826 * ```
3827 * @return {Function} A custom react hook.
3828 */
3829
3830 const useDispatch = storeNameOrDescriptor => {
3831 const {
3832 dispatch
3833 } = useRegistry();
3834 return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor);
3835 };
3836
3837 /* harmony default export */ var use_dispatch = (useDispatch);
3838 //# sourceMappingURL=use-dispatch.js.map
3839 ;// CONCATENATED MODULE: ./packages/data/build-module/index.js
3840 /**
3841 * External dependencies
3842 */
3843
3844 /**
3845 * Internal dependencies
3846 */
3847
3848
3849
3850 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863 /**
3864 * Object of available plugins to use with a registry.
3865 *
3866 * @see [use](#use)
3867 *
3868 * @type {Object}
3869 */
3870
3871
3872 /**
3873 * The combineReducers helper function turns an object whose values are different
3874 * reducing functions into a single reducing function you can pass to registerReducer.
3875 *
3876 * @param {Object} reducers An object whose values correspond to different reducing
3877 * functions that need to be combined into one.
3878 *
3879 * @example
3880 * ```js
3881 * import { combineReducers, createReduxStore, register } from '@wordpress/data';
3882 *
3883 * const prices = ( state = {}, action ) => {
3884 * return action.type === 'SET_PRICE' ?
3885 * {
3886 * ...state,
3887 * [ action.item ]: action.price,
3888 * } :
3889 * state;
3890 * };
3891 *
3892 * const discountPercent = ( state = 0, action ) => {
3893 * return action.type === 'START_SALE' ?
3894 * action.discountPercent :
3895 * state;
3896 * };
3897 *
3898 * const store = createReduxStore( 'my-shop', {
3899 * reducer: combineReducers( {
3900 * prices,
3901 * discountPercent,
3902 * } ),
3903 * } );
3904 * register( store );
3905 * ```
3906 *
3907 * @return {Function} A reducer that invokes every reducer inside the reducers
3908 * object, and constructs a state object with the same shape.
3909 */
3910
3911
3912 /**
3913 * Given the name or descriptor of a registered store, returns an object of the store's selectors.
3914 * The selector functions are been pre-bound to pass the current state automatically.
3915 * As a consumer, you need only pass arguments of the selector, if applicable.
3916 *
3917 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
3918 * or the store descriptor.
3919 *
3920 * @example
3921 * ```js
3922 * import { select } from '@wordpress/data';
3923 *
3924 * select( 'my-shop' ).getPrice( 'hammer' );
3925 * ```
3926 *
3927 * @return {Object} Object containing the store's selectors.
3928 */
3929
3930 const build_module_select = default_registry.select;
3931 /**
3932 * Given the name of a registered store, returns an object containing the store's
3933 * selectors pre-bound to state so that you only need to supply additional arguments,
3934 * and modified so that they return promises that resolve to their eventual values,
3935 * after any resolvers have ran.
3936 *
3937 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
3938 * or the store descriptor.
3939 *
3940 * @example
3941 * ```js
3942 * import { resolveSelect } from '@wordpress/data';
3943 *
3944 * resolveSelect( 'my-shop' ).getPrice( 'hammer' ).then(console.log)
3945 * ```
3946 *
3947 * @return {Object} Object containing the store's promise-wrapped selectors.
3948 */
3949
3950 const build_module_resolveSelect = default_registry.resolveSelect;
3951 /**
3952 * Given the name of a registered store, returns an object of the store's action creators.
3953 * Calling an action creator will cause it to be dispatched, updating the state value accordingly.
3954 *
3955 * Note: Action creators returned by the dispatch will return a promise when
3956 * they are called.
3957 *
3958 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
3959 * or the store descriptor.
3960 *
3961 * @example
3962 * ```js
3963 * import { dispatch } from '@wordpress/data';
3964 *
3965 * dispatch( 'my-shop' ).setPrice( 'hammer', 9.75 );
3966 * ```
3967 * @return {Object} Object containing the action creators.
3968 */
3969
3970 const build_module_dispatch = default_registry.dispatch;
3971 /**
3972 * Given a listener function, the function will be called any time the state value
3973 * of one of the registered stores has changed. This function returns a `unsubscribe`
3974 * function used to stop the subscription.
3975 *
3976 * @param {Function} listener Callback function.
3977 *
3978 * @example
3979 * ```js
3980 * import { subscribe } from '@wordpress/data';
3981 *
3982 * const unsubscribe = subscribe( () => {
3983 * // You could use this opportunity to test whether the derived result of a
3984 * // selector has subsequently changed as the result of a state update.
3985 * } );
3986 *
3987 * // Later, if necessary...
3988 * unsubscribe();
3989 * ```
3990 */
3991
3992 const subscribe = default_registry.subscribe;
3993 /**
3994 * Registers a generic store instance.
3995 *
3996 * @deprecated Use `register( storeDescriptor )` instead.
3997 *
3998 * @param {string} name Store registry name.
3999 * @param {Object} store Store instance (`{ getSelectors, getActions, subscribe }`).
4000 */
4001
4002 const registerGenericStore = default_registry.registerGenericStore;
4003 /**
4004 * Registers a standard `@wordpress/data` store.
4005 *
4006 * @deprecated Use `register` instead.
4007 *
4008 * @param {string} storeName Unique namespace identifier for the store.
4009 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
4010 *
4011 * @return {Object} Registered store object.
4012 */
4013
4014 const registerStore = default_registry.registerStore;
4015 /**
4016 * Extends a registry to inherit functionality provided by a given plugin. A
4017 * plugin is an object with properties aligning to that of a registry, merged
4018 * to extend the default registry behavior.
4019 *
4020 * @param {Object} plugin Plugin object.
4021 */
4022
4023 const use = default_registry.use;
4024 /**
4025 * Registers a standard `@wordpress/data` store descriptor.
4026 *
4027 * @example
4028 * ```js
4029 * import { createReduxStore, register } from '@wordpress/data';
4030 *
4031 * const store = createReduxStore( 'demo', {
4032 * reducer: ( state = 'OK' ) => state,
4033 * selectors: {
4034 * getValue: ( state ) => state,
4035 * },
4036 * } );
4037 * register( store );
4038 * ```
4039 *
4040 * @param {StoreDescriptor} store Store descriptor.
4041 */
4042
4043 const register = default_registry.register;
4044 //# sourceMappingURL=index.js.map
4045 }();
4046 (window.wp = window.wp || {}).data = __webpack_exports__;
4047 /******/ })()
4048 ;