PluginProbe
Gutenberg / 12.5.1
Gutenberg v12.5.1
24.0.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 All 403 releases
gutenberg / build / data / index.js

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

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