PluginProbe
Gutenberg / 15.5.0
Gutenberg v15.5.0
24.1.0 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 All 404 releases
gutenberg / build / data / index.js

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

4,707 lines 145.6 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 /***/ 2167:
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 /***/ 9125:
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 /***/ 1879:
379 /***/ (function(module) {
380
381 "use strict";
382
383
384 var isMergeableObject = function isMergeableObject(value) {
385 return isNonNullObject(value)
386 && !isSpecial(value)
387 };
388
389 function isNonNullObject(value) {
390 return !!value && typeof value === 'object'
391 }
392
393 function isSpecial(value) {
394 var stringValue = Object.prototype.toString.call(value);
395
396 return stringValue === '[object RegExp]'
397 || stringValue === '[object Date]'
398 || isReactElement(value)
399 }
400
401 // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
402 var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
403 var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
404
405 function isReactElement(value) {
406 return value.$$typeof === REACT_ELEMENT_TYPE
407 }
408
409 function emptyTarget(val) {
410 return Array.isArray(val) ? [] : {}
411 }
412
413 function cloneUnlessOtherwiseSpecified(value, options) {
414 return (options.clone !== false && options.isMergeableObject(value))
415 ? deepmerge(emptyTarget(value), value, options)
416 : value
417 }
418
419 function defaultArrayMerge(target, source, options) {
420 return target.concat(source).map(function(element) {
421 return cloneUnlessOtherwiseSpecified(element, options)
422 })
423 }
424
425 function getMergeFunction(key, options) {
426 if (!options.customMerge) {
427 return deepmerge
428 }
429 var customMerge = options.customMerge(key);
430 return typeof customMerge === 'function' ? customMerge : deepmerge
431 }
432
433 function getEnumerableOwnPropertySymbols(target) {
434 return Object.getOwnPropertySymbols
435 ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
436 return Object.propertyIsEnumerable.call(target, symbol)
437 })
438 : []
439 }
440
441 function getKeys(target) {
442 return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
443 }
444
445 function propertyIsOnObject(object, property) {
446 try {
447 return property in object
448 } catch(_) {
449 return false
450 }
451 }
452
453 // Protects from prototype poisoning and unexpected merging up the prototype chain.
454 function propertyIsUnsafe(target, key) {
455 return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
456 && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
457 && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
458 }
459
460 function mergeObject(target, source, options) {
461 var destination = {};
462 if (options.isMergeableObject(target)) {
463 getKeys(target).forEach(function(key) {
464 destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
465 });
466 }
467 getKeys(source).forEach(function(key) {
468 if (propertyIsUnsafe(target, key)) {
469 return
470 }
471
472 if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
473 destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
474 } else {
475 destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
476 }
477 });
478 return destination
479 }
480
481 function deepmerge(target, source, options) {
482 options = options || {};
483 options.arrayMerge = options.arrayMerge || defaultArrayMerge;
484 options.isMergeableObject = options.isMergeableObject || isMergeableObject;
485 // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
486 // implementations can use it. The caller may not replace it.
487 options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
488
489 var sourceIsArray = Array.isArray(source);
490 var targetIsArray = Array.isArray(target);
491 var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
492
493 if (!sourceAndTargetTypesMatch) {
494 return cloneUnlessOtherwiseSpecified(source, options)
495 } else if (sourceIsArray) {
496 return options.arrayMerge(target, source, options)
497 } else {
498 return mergeObject(target, source, options)
499 }
500 }
501
502 deepmerge.all = function deepmergeAll(array, options) {
503 if (!Array.isArray(array)) {
504 throw new Error('first argument should be an array')
505 }
506
507 return array.reduce(function(prev, next) {
508 return deepmerge(prev, next, options)
509 }, {})
510 };
511
512 var deepmerge_1 = deepmerge;
513
514 module.exports = deepmerge_1;
515
516
517 /***/ })
518
519 /******/ });
520 /************************************************************************/
521 /******/ // The module cache
522 /******/ var __webpack_module_cache__ = {};
523 /******/
524 /******/ // The require function
525 /******/ function __webpack_require__(moduleId) {
526 /******/ // Check if module is in cache
527 /******/ var cachedModule = __webpack_module_cache__[moduleId];
528 /******/ if (cachedModule !== undefined) {
529 /******/ return cachedModule.exports;
530 /******/ }
531 /******/ // Create a new module (and put it into the cache)
532 /******/ var module = __webpack_module_cache__[moduleId] = {
533 /******/ // no module.id needed
534 /******/ // no module.loaded needed
535 /******/ exports: {}
536 /******/ };
537 /******/
538 /******/ // Execute the module function
539 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
540 /******/
541 /******/ // Return the exports of the module
542 /******/ return module.exports;
543 /******/ }
544 /******/
545 /************************************************************************/
546 /******/ /* webpack/runtime/compat get default export */
547 /******/ !function() {
548 /******/ // getDefaultExport function for compatibility with non-harmony modules
549 /******/ __webpack_require__.n = function(module) {
550 /******/ var getter = module && module.__esModule ?
551 /******/ function() { return module['default']; } :
552 /******/ function() { return module; };
553 /******/ __webpack_require__.d(getter, { a: getter });
554 /******/ return getter;
555 /******/ };
556 /******/ }();
557 /******/
558 /******/ /* webpack/runtime/define property getters */
559 /******/ !function() {
560 /******/ // define getter functions for harmony exports
561 /******/ __webpack_require__.d = function(exports, definition) {
562 /******/ for(var key in definition) {
563 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
564 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
565 /******/ }
566 /******/ }
567 /******/ };
568 /******/ }();
569 /******/
570 /******/ /* webpack/runtime/hasOwnProperty shorthand */
571 /******/ !function() {
572 /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
573 /******/ }();
574 /******/
575 /******/ /* webpack/runtime/make namespace object */
576 /******/ !function() {
577 /******/ // define __esModule on exports
578 /******/ __webpack_require__.r = function(exports) {
579 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
580 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
581 /******/ }
582 /******/ Object.defineProperty(exports, '__esModule', { value: true });
583 /******/ };
584 /******/ }();
585 /******/
586 /************************************************************************/
587 var __webpack_exports__ = {};
588 // This entry need to be wrapped in an IIFE because it need to be in strict mode.
589 !function() {
590 "use strict";
591 // ESM COMPAT FLAG
592 __webpack_require__.r(__webpack_exports__);
593
594 // EXPORTS
595 __webpack_require__.d(__webpack_exports__, {
596 "AsyncModeProvider": function() { return /* reexport */ async_mode_provider_context; },
597 "RegistryConsumer": function() { return /* reexport */ RegistryConsumer; },
598 "RegistryProvider": function() { return /* reexport */ context; },
599 "combineReducers": function() { return /* binding */ build_module_combineReducers; },
600 "controls": function() { return /* reexport */ controls; },
601 "createReduxStore": function() { return /* reexport */ createReduxStore; },
602 "createRegistry": function() { return /* reexport */ createRegistry; },
603 "createRegistryControl": function() { return /* reexport */ createRegistryControl; },
604 "createRegistrySelector": function() { return /* reexport */ createRegistrySelector; },
605 "dispatch": function() { return /* binding */ build_module_dispatch; },
606 "plugins": function() { return /* reexport */ plugins_namespaceObject; },
607 "register": function() { return /* binding */ register; },
608 "registerGenericStore": function() { return /* binding */ registerGenericStore; },
609 "registerStore": function() { return /* binding */ registerStore; },
610 "resolveSelect": function() { return /* binding */ build_module_resolveSelect; },
611 "select": function() { return /* binding */ build_module_select; },
612 "subscribe": function() { return /* binding */ subscribe; },
613 "suspendSelect": function() { return /* binding */ suspendSelect; },
614 "use": function() { return /* binding */ use; },
615 "useDispatch": function() { return /* reexport */ use_dispatch; },
616 "useRegistry": function() { return /* reexport */ useRegistry; },
617 "useSelect": function() { return /* reexport */ useSelect; },
618 "useSuspenseSelect": function() { return /* reexport */ useSuspenseSelect; },
619 "withDispatch": function() { return /* reexport */ with_dispatch; },
620 "withRegistry": function() { return /* reexport */ with_registry; },
621 "withSelect": function() { return /* reexport */ with_select; }
622 });
623
624 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/selectors.js
625 var selectors_namespaceObject = {};
626 __webpack_require__.r(selectors_namespaceObject);
627 __webpack_require__.d(selectors_namespaceObject, {
628 "getCachedResolvers": function() { return getCachedResolvers; },
629 "getIsResolving": function() { return getIsResolving; },
630 "getResolutionError": function() { return getResolutionError; },
631 "getResolutionState": function() { return getResolutionState; },
632 "hasFinishedResolution": function() { return hasFinishedResolution; },
633 "hasResolutionFailed": function() { return hasResolutionFailed; },
634 "hasStartedResolution": function() { return hasStartedResolution; },
635 "isResolving": function() { return isResolving; }
636 });
637
638 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/actions.js
639 var actions_namespaceObject = {};
640 __webpack_require__.r(actions_namespaceObject);
641 __webpack_require__.d(actions_namespaceObject, {
642 "failResolution": function() { return failResolution; },
643 "failResolutions": function() { return failResolutions; },
644 "finishResolution": function() { return finishResolution; },
645 "finishResolutions": function() { return finishResolutions; },
646 "invalidateResolution": function() { return invalidateResolution; },
647 "invalidateResolutionForStore": function() { return invalidateResolutionForStore; },
648 "invalidateResolutionForStoreSelector": function() { return invalidateResolutionForStoreSelector; },
649 "startResolution": function() { return startResolution; },
650 "startResolutions": function() { return startResolutions; }
651 });
652
653 // NAMESPACE OBJECT: ./packages/data/build-module/plugins/index.js
654 var plugins_namespaceObject = {};
655 __webpack_require__.r(plugins_namespaceObject);
656 __webpack_require__.d(plugins_namespaceObject, {
657 "persistence": function() { return persistence; }
658 });
659
660 // EXTERNAL MODULE: ./node_modules/turbo-combine-reducers/index.js
661 var turbo_combine_reducers = __webpack_require__(9125);
662 var turbo_combine_reducers_default = /*#__PURE__*/__webpack_require__.n(turbo_combine_reducers);
663 ;// CONCATENATED MODULE: external ["wp","deprecated"]
664 var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
665 var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
666 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js
667 function _defineProperty(obj, key, value) {
668 if (key in obj) {
669 Object.defineProperty(obj, key, {
670 value: value,
671 enumerable: true,
672 configurable: true,
673 writable: true
674 });
675 } else {
676 obj[key] = value;
677 }
678
679 return obj;
680 }
681 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread2.js
682
683
684 function ownKeys(object, enumerableOnly) {
685 var keys = Object.keys(object);
686
687 if (Object.getOwnPropertySymbols) {
688 var symbols = Object.getOwnPropertySymbols(object);
689
690 if (enumerableOnly) {
691 symbols = symbols.filter(function (sym) {
692 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
693 });
694 }
695
696 keys.push.apply(keys, symbols);
697 }
698
699 return keys;
700 }
701
702 function _objectSpread2(target) {
703 for (var i = 1; i < arguments.length; i++) {
704 var source = arguments[i] != null ? arguments[i] : {};
705
706 if (i % 2) {
707 ownKeys(Object(source), true).forEach(function (key) {
708 _defineProperty(target, key, source[key]);
709 });
710 } else if (Object.getOwnPropertyDescriptors) {
711 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
712 } else {
713 ownKeys(Object(source)).forEach(function (key) {
714 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
715 });
716 }
717 }
718
719 return target;
720 }
721 ;// CONCATENATED MODULE: ./node_modules/redux/es/redux.js
722
723
724 /**
725 * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js
726 *
727 * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes
728 * during build.
729 * @param {number} code
730 */
731 function formatProdErrorMessage(code) {
732 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. ';
733 }
734
735 // Inlined version of the `symbol-observable` polyfill
736 var $$observable = (function () {
737 return typeof Symbol === 'function' && Symbol.observable || '@@observable';
738 })();
739
740 /**
741 * These are private action types reserved by Redux.
742 * For any unknown actions, you must return the current state.
743 * If the current state is undefined, you must return the initial state.
744 * Do not reference these action types directly in your code.
745 */
746 var randomString = function randomString() {
747 return Math.random().toString(36).substring(7).split('').join('.');
748 };
749
750 var ActionTypes = {
751 INIT: "@@redux/INIT" + randomString(),
752 REPLACE: "@@redux/REPLACE" + randomString(),
753 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
754 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
755 }
756 };
757
758 /**
759 * @param {any} obj The object to inspect.
760 * @returns {boolean} True if the argument appears to be a plain object.
761 */
762 function isPlainObject(obj) {
763 if (typeof obj !== 'object' || obj === null) return false;
764 var proto = obj;
765
766 while (Object.getPrototypeOf(proto) !== null) {
767 proto = Object.getPrototypeOf(proto);
768 }
769
770 return Object.getPrototypeOf(obj) === proto;
771 }
772
773 // Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
774 function miniKindOf(val) {
775 if (val === void 0) return 'undefined';
776 if (val === null) return 'null';
777 var type = typeof val;
778
779 switch (type) {
780 case 'boolean':
781 case 'string':
782 case 'number':
783 case 'symbol':
784 case 'function':
785 {
786 return type;
787 }
788 }
789
790 if (Array.isArray(val)) return 'array';
791 if (isDate(val)) return 'date';
792 if (isError(val)) return 'error';
793 var constructorName = ctorName(val);
794
795 switch (constructorName) {
796 case 'Symbol':
797 case 'Promise':
798 case 'WeakMap':
799 case 'WeakSet':
800 case 'Map':
801 case 'Set':
802 return constructorName;
803 } // other
804
805
806 return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
807 }
808
809 function ctorName(val) {
810 return typeof val.constructor === 'function' ? val.constructor.name : null;
811 }
812
813 function isError(val) {
814 return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';
815 }
816
817 function isDate(val) {
818 if (val instanceof Date) return true;
819 return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';
820 }
821
822 function kindOf(val) {
823 var typeOfVal = typeof val;
824
825 if (false) {}
826
827 return typeOfVal;
828 }
829
830 /**
831 * Creates a Redux store that holds the state tree.
832 * The only way to change the data in the store is to call `dispatch()` on it.
833 *
834 * There should only be a single store in your app. To specify how different
835 * parts of the state tree respond to actions, you may combine several reducers
836 * into a single reducer function by using `combineReducers`.
837 *
838 * @param {Function} reducer A function that returns the next state tree, given
839 * the current state tree and the action to handle.
840 *
841 * @param {any} [preloadedState] The initial state. You may optionally specify it
842 * to hydrate the state from the server in universal apps, or to restore a
843 * previously serialized user session.
844 * If you use `combineReducers` to produce the root reducer function, this must be
845 * an object with the same shape as `combineReducers` keys.
846 *
847 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
848 * to enhance the store with third-party capabilities such as middleware,
849 * time travel, persistence, etc. The only store enhancer that ships with Redux
850 * is `applyMiddleware()`.
851 *
852 * @returns {Store} A Redux store that lets you read the state, dispatch actions
853 * and subscribe to changes.
854 */
855
856 function createStore(reducer, preloadedState, enhancer) {
857 var _ref2;
858
859 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
860 throw new Error( true ? formatProdErrorMessage(0) : 0);
861 }
862
863 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
864 enhancer = preloadedState;
865 preloadedState = undefined;
866 }
867
868 if (typeof enhancer !== 'undefined') {
869 if (typeof enhancer !== 'function') {
870 throw new Error( true ? formatProdErrorMessage(1) : 0);
871 }
872
873 return enhancer(createStore)(reducer, preloadedState);
874 }
875
876 if (typeof reducer !== 'function') {
877 throw new Error( true ? formatProdErrorMessage(2) : 0);
878 }
879
880 var currentReducer = reducer;
881 var currentState = preloadedState;
882 var currentListeners = [];
883 var nextListeners = currentListeners;
884 var isDispatching = false;
885 /**
886 * This makes a shallow copy of currentListeners so we can use
887 * nextListeners as a temporary list while dispatching.
888 *
889 * This prevents any bugs around consumers calling
890 * subscribe/unsubscribe in the middle of a dispatch.
891 */
892
893 function ensureCanMutateNextListeners() {
894 if (nextListeners === currentListeners) {
895 nextListeners = currentListeners.slice();
896 }
897 }
898 /**
899 * Reads the state tree managed by the store.
900 *
901 * @returns {any} The current state tree of your application.
902 */
903
904
905 function getState() {
906 if (isDispatching) {
907 throw new Error( true ? formatProdErrorMessage(3) : 0);
908 }
909
910 return currentState;
911 }
912 /**
913 * Adds a change listener. It will be called any time an action is dispatched,
914 * and some part of the state tree may potentially have changed. You may then
915 * call `getState()` to read the current state tree inside the callback.
916 *
917 * You may call `dispatch()` from a change listener, with the following
918 * caveats:
919 *
920 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
921 * If you subscribe or unsubscribe while the listeners are being invoked, this
922 * will not have any effect on the `dispatch()` that is currently in progress.
923 * However, the next `dispatch()` call, whether nested or not, will use a more
924 * recent snapshot of the subscription list.
925 *
926 * 2. The listener should not expect to see all state changes, as the state
927 * might have been updated multiple times during a nested `dispatch()` before
928 * the listener is called. It is, however, guaranteed that all subscribers
929 * registered before the `dispatch()` started will be called with the latest
930 * state by the time it exits.
931 *
932 * @param {Function} listener A callback to be invoked on every dispatch.
933 * @returns {Function} A function to remove this change listener.
934 */
935
936
937 function subscribe(listener) {
938 if (typeof listener !== 'function') {
939 throw new Error( true ? formatProdErrorMessage(4) : 0);
940 }
941
942 if (isDispatching) {
943 throw new Error( true ? formatProdErrorMessage(5) : 0);
944 }
945
946 var isSubscribed = true;
947 ensureCanMutateNextListeners();
948 nextListeners.push(listener);
949 return function unsubscribe() {
950 if (!isSubscribed) {
951 return;
952 }
953
954 if (isDispatching) {
955 throw new Error( true ? formatProdErrorMessage(6) : 0);
956 }
957
958 isSubscribed = false;
959 ensureCanMutateNextListeners();
960 var index = nextListeners.indexOf(listener);
961 nextListeners.splice(index, 1);
962 currentListeners = null;
963 };
964 }
965 /**
966 * Dispatches an action. It is the only way to trigger a state change.
967 *
968 * The `reducer` function, used to create the store, will be called with the
969 * current state tree and the given `action`. Its return value will
970 * be considered the **next** state of the tree, and the change listeners
971 * will be notified.
972 *
973 * The base implementation only supports plain object actions. If you want to
974 * dispatch a Promise, an Observable, a thunk, or something else, you need to
975 * wrap your store creating function into the corresponding middleware. For
976 * example, see the documentation for the `redux-thunk` package. Even the
977 * middleware will eventually dispatch plain object actions using this method.
978 *
979 * @param {Object} action A plain object representing “what changed”. It is
980 * a good idea to keep actions serializable so you can record and replay user
981 * sessions, or use the time travelling `redux-devtools`. An action must have
982 * a `type` property which may not be `undefined`. It is a good idea to use
983 * string constants for action types.
984 *
985 * @returns {Object} For convenience, the same action object you dispatched.
986 *
987 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
988 * return something else (for example, a Promise you can await).
989 */
990
991
992 function dispatch(action) {
993 if (!isPlainObject(action)) {
994 throw new Error( true ? formatProdErrorMessage(7) : 0);
995 }
996
997 if (typeof action.type === 'undefined') {
998 throw new Error( true ? formatProdErrorMessage(8) : 0);
999 }
1000
1001 if (isDispatching) {
1002 throw new Error( true ? formatProdErrorMessage(9) : 0);
1003 }
1004
1005 try {
1006 isDispatching = true;
1007 currentState = currentReducer(currentState, action);
1008 } finally {
1009 isDispatching = false;
1010 }
1011
1012 var listeners = currentListeners = nextListeners;
1013
1014 for (var i = 0; i < listeners.length; i++) {
1015 var listener = listeners[i];
1016 listener();
1017 }
1018
1019 return action;
1020 }
1021 /**
1022 * Replaces the reducer currently used by the store to calculate the state.
1023 *
1024 * You might need this if your app implements code splitting and you want to
1025 * load some of the reducers dynamically. You might also need this if you
1026 * implement a hot reloading mechanism for Redux.
1027 *
1028 * @param {Function} nextReducer The reducer for the store to use instead.
1029 * @returns {void}
1030 */
1031
1032
1033 function replaceReducer(nextReducer) {
1034 if (typeof nextReducer !== 'function') {
1035 throw new Error( true ? formatProdErrorMessage(10) : 0);
1036 }
1037
1038 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
1039 // Any reducers that existed in both the new and old rootReducer
1040 // will receive the previous state. This effectively populates
1041 // the new state tree with any relevant data from the old one.
1042
1043 dispatch({
1044 type: ActionTypes.REPLACE
1045 });
1046 }
1047 /**
1048 * Interoperability point for observable/reactive libraries.
1049 * @returns {observable} A minimal observable of state changes.
1050 * For more information, see the observable proposal:
1051 * https://github.com/tc39/proposal-observable
1052 */
1053
1054
1055 function observable() {
1056 var _ref;
1057
1058 var outerSubscribe = subscribe;
1059 return _ref = {
1060 /**
1061 * The minimal observable subscription method.
1062 * @param {Object} observer Any object that can be used as an observer.
1063 * The observer object should have a `next` method.
1064 * @returns {subscription} An object with an `unsubscribe` method that can
1065 * be used to unsubscribe the observable from the store, and prevent further
1066 * emission of values from the observable.
1067 */
1068 subscribe: function subscribe(observer) {
1069 if (typeof observer !== 'object' || observer === null) {
1070 throw new Error( true ? formatProdErrorMessage(11) : 0);
1071 }
1072
1073 function observeState() {
1074 if (observer.next) {
1075 observer.next(getState());
1076 }
1077 }
1078
1079 observeState();
1080 var unsubscribe = outerSubscribe(observeState);
1081 return {
1082 unsubscribe: unsubscribe
1083 };
1084 }
1085 }, _ref[$$observable] = function () {
1086 return this;
1087 }, _ref;
1088 } // When a store is created, an "INIT" action is dispatched so that every
1089 // reducer returns their initial state. This effectively populates
1090 // the initial state tree.
1091
1092
1093 dispatch({
1094 type: ActionTypes.INIT
1095 });
1096 return _ref2 = {
1097 dispatch: dispatch,
1098 subscribe: subscribe,
1099 getState: getState,
1100 replaceReducer: replaceReducer
1101 }, _ref2[$$observable] = observable, _ref2;
1102 }
1103
1104 /**
1105 * Prints a warning in the console if it exists.
1106 *
1107 * @param {String} message The warning message.
1108 * @returns {void}
1109 */
1110 function warning(message) {
1111 /* eslint-disable no-console */
1112 if (typeof console !== 'undefined' && typeof console.error === 'function') {
1113 console.error(message);
1114 }
1115 /* eslint-enable no-console */
1116
1117
1118 try {
1119 // This error was thrown as a convenience so that if you enable
1120 // "break on all exceptions" in your console,
1121 // it would pause the execution at this line.
1122 throw new Error(message);
1123 } catch (e) {} // eslint-disable-line no-empty
1124
1125 }
1126
1127 function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
1128 var reducerKeys = Object.keys(reducers);
1129 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
1130
1131 if (reducerKeys.length === 0) {
1132 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
1133 }
1134
1135 if (!isPlainObject(inputState)) {
1136 return "The " + argumentName + " has unexpected type of \"" + kindOf(inputState) + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
1137 }
1138
1139 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
1140 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
1141 });
1142 unexpectedKeys.forEach(function (key) {
1143 unexpectedKeyCache[key] = true;
1144 });
1145 if (action && action.type === ActionTypes.REPLACE) return;
1146
1147 if (unexpectedKeys.length > 0) {
1148 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.");
1149 }
1150 }
1151
1152 function assertReducerShape(reducers) {
1153 Object.keys(reducers).forEach(function (key) {
1154 var reducer = reducers[key];
1155 var initialState = reducer(undefined, {
1156 type: ActionTypes.INIT
1157 });
1158
1159 if (typeof initialState === 'undefined') {
1160 throw new Error( true ? formatProdErrorMessage(12) : 0);
1161 }
1162
1163 if (typeof reducer(undefined, {
1164 type: ActionTypes.PROBE_UNKNOWN_ACTION()
1165 }) === 'undefined') {
1166 throw new Error( true ? formatProdErrorMessage(13) : 0);
1167 }
1168 });
1169 }
1170 /**
1171 * Turns an object whose values are different reducer functions, into a single
1172 * reducer function. It will call every child reducer, and gather their results
1173 * into a single state object, whose keys correspond to the keys of the passed
1174 * reducer functions.
1175 *
1176 * @param {Object} reducers An object whose values correspond to different
1177 * reducer functions that need to be combined into one. One handy way to obtain
1178 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
1179 * undefined for any action. Instead, they should return their initial state
1180 * if the state passed to them was undefined, and the current state for any
1181 * unrecognized action.
1182 *
1183 * @returns {Function} A reducer function that invokes every reducer inside the
1184 * passed object, and builds a state object with the same shape.
1185 */
1186
1187
1188 function combineReducers(reducers) {
1189 var reducerKeys = Object.keys(reducers);
1190 var finalReducers = {};
1191
1192 for (var i = 0; i < reducerKeys.length; i++) {
1193 var key = reducerKeys[i];
1194
1195 if (false) {}
1196
1197 if (typeof reducers[key] === 'function') {
1198 finalReducers[key] = reducers[key];
1199 }
1200 }
1201
1202 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
1203 // keys multiple times.
1204
1205 var unexpectedKeyCache;
1206
1207 if (false) {}
1208
1209 var shapeAssertionError;
1210
1211 try {
1212 assertReducerShape(finalReducers);
1213 } catch (e) {
1214 shapeAssertionError = e;
1215 }
1216
1217 return function combination(state, action) {
1218 if (state === void 0) {
1219 state = {};
1220 }
1221
1222 if (shapeAssertionError) {
1223 throw shapeAssertionError;
1224 }
1225
1226 if (false) { var warningMessage; }
1227
1228 var hasChanged = false;
1229 var nextState = {};
1230
1231 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
1232 var _key = finalReducerKeys[_i];
1233 var reducer = finalReducers[_key];
1234 var previousStateForKey = state[_key];
1235 var nextStateForKey = reducer(previousStateForKey, action);
1236
1237 if (typeof nextStateForKey === 'undefined') {
1238 var actionType = action && action.type;
1239 throw new Error( true ? formatProdErrorMessage(14) : 0);
1240 }
1241
1242 nextState[_key] = nextStateForKey;
1243 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
1244 }
1245
1246 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
1247 return hasChanged ? nextState : state;
1248 };
1249 }
1250
1251 function bindActionCreator(actionCreator, dispatch) {
1252 return function () {
1253 return dispatch(actionCreator.apply(this, arguments));
1254 };
1255 }
1256 /**
1257 * Turns an object whose values are action creators, into an object with the
1258 * same keys, but with every function wrapped into a `dispatch` call so they
1259 * may be invoked directly. This is just a convenience method, as you can call
1260 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
1261 *
1262 * For convenience, you can also pass an action creator as the first argument,
1263 * and get a dispatch wrapped function in return.
1264 *
1265 * @param {Function|Object} actionCreators An object whose values are action
1266 * creator functions. One handy way to obtain it is to use ES6 `import * as`
1267 * syntax. You may also pass a single function.
1268 *
1269 * @param {Function} dispatch The `dispatch` function available on your Redux
1270 * store.
1271 *
1272 * @returns {Function|Object} The object mimicking the original object, but with
1273 * every action creator wrapped into the `dispatch` call. If you passed a
1274 * function as `actionCreators`, the return value will also be a single
1275 * function.
1276 */
1277
1278
1279 function bindActionCreators(actionCreators, dispatch) {
1280 if (typeof actionCreators === 'function') {
1281 return bindActionCreator(actionCreators, dispatch);
1282 }
1283
1284 if (typeof actionCreators !== 'object' || actionCreators === null) {
1285 throw new Error( true ? formatProdErrorMessage(16) : 0);
1286 }
1287
1288 var boundActionCreators = {};
1289
1290 for (var key in actionCreators) {
1291 var actionCreator = actionCreators[key];
1292
1293 if (typeof actionCreator === 'function') {
1294 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
1295 }
1296 }
1297
1298 return boundActionCreators;
1299 }
1300
1301 /**
1302 * Composes single-argument functions from right to left. The rightmost
1303 * function can take multiple arguments as it provides the signature for
1304 * the resulting composite function.
1305 *
1306 * @param {...Function} funcs The functions to compose.
1307 * @returns {Function} A function obtained by composing the argument functions
1308 * from right to left. For example, compose(f, g, h) is identical to doing
1309 * (...args) => f(g(h(...args))).
1310 */
1311 function compose() {
1312 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
1313 funcs[_key] = arguments[_key];
1314 }
1315
1316 if (funcs.length === 0) {
1317 return function (arg) {
1318 return arg;
1319 };
1320 }
1321
1322 if (funcs.length === 1) {
1323 return funcs[0];
1324 }
1325
1326 return funcs.reduce(function (a, b) {
1327 return function () {
1328 return a(b.apply(void 0, arguments));
1329 };
1330 });
1331 }
1332
1333 /**
1334 * Creates a store enhancer that applies middleware to the dispatch method
1335 * of the Redux store. This is handy for a variety of tasks, such as expressing
1336 * asynchronous actions in a concise manner, or logging every action payload.
1337 *
1338 * See `redux-thunk` package as an example of the Redux middleware.
1339 *
1340 * Because middleware is potentially asynchronous, this should be the first
1341 * store enhancer in the composition chain.
1342 *
1343 * Note that each middleware will be given the `dispatch` and `getState` functions
1344 * as named arguments.
1345 *
1346 * @param {...Function} middlewares The middleware chain to be applied.
1347 * @returns {Function} A store enhancer applying the middleware.
1348 */
1349
1350 function applyMiddleware() {
1351 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
1352 middlewares[_key] = arguments[_key];
1353 }
1354
1355 return function (createStore) {
1356 return function () {
1357 var store = createStore.apply(void 0, arguments);
1358
1359 var _dispatch = function dispatch() {
1360 throw new Error( true ? formatProdErrorMessage(15) : 0);
1361 };
1362
1363 var middlewareAPI = {
1364 getState: store.getState,
1365 dispatch: function dispatch() {
1366 return _dispatch.apply(void 0, arguments);
1367 }
1368 };
1369 var chain = middlewares.map(function (middleware) {
1370 return middleware(middlewareAPI);
1371 });
1372 _dispatch = compose.apply(void 0, chain)(store.dispatch);
1373 return _objectSpread2(_objectSpread2({}, store), {}, {
1374 dispatch: _dispatch
1375 });
1376 };
1377 };
1378 }
1379
1380 /*
1381 * This is a dummy function to check if the function name has been altered by minification.
1382 * If the function has been minified and NODE_ENV !== 'production', warn the user.
1383 */
1384
1385 function isCrushed() {}
1386
1387 if (false) {}
1388
1389
1390
1391 // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js
1392 var equivalent_key_map = __webpack_require__(2167);
1393 var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map);
1394 ;// CONCATENATED MODULE: external ["wp","reduxRoutine"]
1395 var external_wp_reduxRoutine_namespaceObject = window["wp"]["reduxRoutine"];
1396 var external_wp_reduxRoutine_default = /*#__PURE__*/__webpack_require__.n(external_wp_reduxRoutine_namespaceObject);
1397 ;// CONCATENATED MODULE: external ["wp","compose"]
1398 var external_wp_compose_namespaceObject = window["wp"]["compose"];
1399 ;// CONCATENATED MODULE: ./packages/data/build-module/factory.js
1400 /**
1401 * Creates a selector function that takes additional curried argument with the
1402 * registry `select` function. While a regular selector has signature
1403 * ```js
1404 * ( state, ...selectorArgs ) => ( result )
1405 * ```
1406 * that allows to select data from the store's `state`, a registry selector
1407 * has signature:
1408 * ```js
1409 * ( select ) => ( state, ...selectorArgs ) => ( result )
1410 * ```
1411 * that supports also selecting from other registered stores.
1412 *
1413 * @example
1414 * ```js
1415 * import { store as coreStore } from '@wordpress/core-data';
1416 * import { store as editorStore } from '@wordpress/editor';
1417 *
1418 * const getCurrentPostId = createRegistrySelector( ( select ) => ( state ) => {
1419 * return select( editorStore ).getCurrentPostId();
1420 * } );
1421 *
1422 * const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
1423 * // calling another registry selector just like any other function
1424 * const postType = getCurrentPostType( state );
1425 * const postId = getCurrentPostId( state );
1426 * return select( coreStore ).getEntityRecordEdits( 'postType', postType, postId );
1427 * } );
1428 * ```
1429 *
1430 * Note how the `getCurrentPostId` selector can be called just like any other function,
1431 * (it works even inside a regular non-registry selector) and we don't need to pass the
1432 * registry as argument. The registry binding happens automatically when registering the selector
1433 * with a store.
1434 *
1435 * @param {Function} registrySelector Function receiving a registry `select`
1436 * function and returning a state selector.
1437 *
1438 * @return {Function} Registry selector that can be registered with a store.
1439 */
1440 function createRegistrySelector(registrySelector) {
1441 // Create a selector function that is bound to the registry referenced by `selector.registry`
1442 // and that has the same API as a regular selector. Binding it in such a way makes it
1443 // possible to call the selector directly from another selector.
1444 const selector = function () {
1445 return registrySelector(selector.registry.select)(...arguments);
1446 };
1447 /**
1448 * Flag indicating that the selector is a registry selector that needs the correct registry
1449 * reference to be assigned to `selecto.registry` to make it work correctly.
1450 * be mapped as a registry selector.
1451 *
1452 * @type {boolean}
1453 */
1454
1455
1456 selector.isRegistrySelector = true;
1457 return selector;
1458 }
1459 /**
1460 * Creates a control function that takes additional curried argument with the `registry` object.
1461 * While a regular control has signature
1462 * ```js
1463 * ( action ) => ( iteratorOrPromise )
1464 * ```
1465 * where the control works with the `action` that it's bound to, a registry control has signature:
1466 * ```js
1467 * ( registry ) => ( action ) => ( iteratorOrPromise )
1468 * ```
1469 * A registry control is typically used to select data or dispatch an action to a registered
1470 * store.
1471 *
1472 * When registering a control created with `createRegistryControl` with a store, the store
1473 * knows which calling convention to use when executing the control.
1474 *
1475 * @param {Function} registryControl Function receiving a registry object and returning a control.
1476 *
1477 * @return {Function} Registry control that can be registered with a store.
1478 */
1479
1480 function createRegistryControl(registryControl) {
1481 registryControl.isRegistryControl = true;
1482 return registryControl;
1483 }
1484
1485 ;// CONCATENATED MODULE: ./packages/data/build-module/controls.js
1486 /**
1487 * Internal dependencies
1488 */
1489
1490 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
1491
1492 const SELECT = '@@data/SELECT';
1493 const RESOLVE_SELECT = '@@data/RESOLVE_SELECT';
1494 const DISPATCH = '@@data/DISPATCH';
1495
1496 function isObject(object) {
1497 return object !== null && typeof object === 'object';
1498 }
1499 /**
1500 * Dispatches a control action for triggering a synchronous registry select.
1501 *
1502 * Note: This control synchronously returns the current selector value, triggering the
1503 * resolution, but not waiting for it.
1504 *
1505 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1506 * @param {string} selectorName The name of the selector.
1507 * @param {Array} args Arguments for the selector.
1508 *
1509 * @example
1510 * ```js
1511 * import { controls } from '@wordpress/data';
1512 *
1513 * // Action generator using `select`.
1514 * export function* myAction() {
1515 * const isEditorSideBarOpened = yield controls.select( 'core/edit-post', 'isEditorSideBarOpened' );
1516 * // Do stuff with the result from the `select`.
1517 * }
1518 * ```
1519 *
1520 * @return {Object} The control descriptor.
1521 */
1522
1523
1524 function controls_select(storeNameOrDescriptor, selectorName) {
1525 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1526 args[_key - 2] = arguments[_key];
1527 }
1528
1529 return {
1530 type: SELECT,
1531 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1532 selectorName,
1533 args
1534 };
1535 }
1536 /**
1537 * Dispatches a control action for triggering and resolving a registry select.
1538 *
1539 * Note: when this control action is handled, it automatically considers
1540 * selectors that may have a resolver. In such case, it will return a `Promise` that resolves
1541 * after the selector finishes resolving, with the final result value.
1542 *
1543 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1544 * @param {string} selectorName The name of the selector
1545 * @param {Array} args Arguments for the selector.
1546 *
1547 * @example
1548 * ```js
1549 * import { controls } from '@wordpress/data';
1550 *
1551 * // Action generator using resolveSelect
1552 * export function* myAction() {
1553 * const isSidebarOpened = yield controls.resolveSelect( 'core/edit-post', 'isEditorSideBarOpened' );
1554 * // do stuff with the result from the select.
1555 * }
1556 * ```
1557 *
1558 * @return {Object} The control descriptor.
1559 */
1560
1561
1562 function resolveSelect(storeNameOrDescriptor, selectorName) {
1563 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
1564 args[_key2 - 2] = arguments[_key2];
1565 }
1566
1567 return {
1568 type: RESOLVE_SELECT,
1569 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1570 selectorName,
1571 args
1572 };
1573 }
1574 /**
1575 * Dispatches a control action for triggering a registry dispatch.
1576 *
1577 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1578 * @param {string} actionName The name of the action to dispatch
1579 * @param {Array} args Arguments for the dispatch action.
1580 *
1581 * @example
1582 * ```js
1583 * import { controls } from '@wordpress/data-controls';
1584 *
1585 * // Action generator using dispatch
1586 * export function* myAction() {
1587 * yield controls.dispatch( 'core/edit-post', 'togglePublishSidebar' );
1588 * // do some other things.
1589 * }
1590 * ```
1591 *
1592 * @return {Object} The control descriptor.
1593 */
1594
1595
1596 function dispatch(storeNameOrDescriptor, actionName) {
1597 for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
1598 args[_key3 - 2] = arguments[_key3];
1599 }
1600
1601 return {
1602 type: DISPATCH,
1603 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1604 actionName,
1605 args
1606 };
1607 }
1608
1609 const controls = {
1610 select: controls_select,
1611 resolveSelect,
1612 dispatch
1613 };
1614 const builtinControls = {
1615 [SELECT]: createRegistryControl(registry => _ref => {
1616 let {
1617 storeKey,
1618 selectorName,
1619 args
1620 } = _ref;
1621 return registry.select(storeKey)[selectorName](...args);
1622 }),
1623 [RESOLVE_SELECT]: createRegistryControl(registry => _ref2 => {
1624 let {
1625 storeKey,
1626 selectorName,
1627 args
1628 } = _ref2;
1629 const method = registry.select(storeKey)[selectorName].hasResolver ? 'resolveSelect' : 'select';
1630 return registry[method](storeKey)[selectorName](...args);
1631 }),
1632 [DISPATCH]: createRegistryControl(registry => _ref3 => {
1633 let {
1634 storeKey,
1635 actionName,
1636 args
1637 } = _ref3;
1638 return registry.dispatch(storeKey)[actionName](...args);
1639 })
1640 };
1641
1642 ;// CONCATENATED MODULE: external ["wp","privateApis"]
1643 var external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
1644 ;// CONCATENATED MODULE: ./packages/data/build-module/private-apis.js
1645 /**
1646 * WordPress dependencies
1647 */
1648
1649 const {
1650 lock,
1651 unlock
1652 } = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I know using unstable features means my plugin or theme will inevitably break on the next WordPress release.', '@wordpress/data');
1653
1654 ;// CONCATENATED MODULE: ./node_modules/is-promise/index.mjs
1655 function isPromise(obj) {
1656 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
1657 }
1658
1659 ;// CONCATENATED MODULE: ./packages/data/build-module/promise-middleware.js
1660 /**
1661 * External dependencies
1662 */
1663
1664 /**
1665 * Simplest possible promise redux middleware.
1666 *
1667 * @type {import('redux').Middleware}
1668 */
1669
1670 const promiseMiddleware = () => next => action => {
1671 if (isPromise(action)) {
1672 return action.then(resolvedAction => {
1673 if (resolvedAction) {
1674 return next(resolvedAction);
1675 }
1676 });
1677 }
1678
1679 return next(action);
1680 };
1681
1682 /* harmony default export */ var promise_middleware = (promiseMiddleware);
1683
1684 ;// CONCATENATED MODULE: ./packages/data/build-module/store/index.js
1685 const coreDataStore = {
1686 name: 'core/data',
1687
1688 instantiate(registry) {
1689 const getCoreDataSelector = selectorName => function (key) {
1690 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1691 args[_key - 1] = arguments[_key];
1692 }
1693
1694 return registry.select(key)[selectorName](...args);
1695 };
1696
1697 const getCoreDataAction = actionName => function (key) {
1698 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1699 args[_key2 - 1] = arguments[_key2];
1700 }
1701
1702 return registry.dispatch(key)[actionName](...args);
1703 };
1704
1705 return {
1706 getSelectors() {
1707 return Object.fromEntries(['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'].map(selectorName => [selectorName, getCoreDataSelector(selectorName)]));
1708 },
1709
1710 getActions() {
1711 return Object.fromEntries(['startResolution', 'finishResolution', 'invalidateResolution', 'invalidateResolutionForStore', 'invalidateResolutionForStoreSelector'].map(actionName => [actionName, getCoreDataAction(actionName)]));
1712 },
1713
1714 subscribe() {
1715 // There's no reasons to trigger any listener when we subscribe to this store
1716 // because there's no state stored in this store that need to retrigger selectors
1717 // if a change happens, the corresponding store where the tracking stated live
1718 // would have already triggered a "subscribe" call.
1719 return () => () => {};
1720 }
1721
1722 };
1723 }
1724
1725 };
1726 /* harmony default export */ var store = (coreDataStore);
1727
1728 ;// CONCATENATED MODULE: ./packages/data/build-module/resolvers-cache-middleware.js
1729 /**
1730 * Internal dependencies
1731 */
1732
1733 /** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */
1734
1735 /**
1736 * Creates a middleware handling resolvers cache invalidation.
1737 *
1738 * @param {WPDataRegistry} registry The registry reference for which to create
1739 * the middleware.
1740 * @param {string} reducerKey The namespace for which to create the
1741 * middleware.
1742 *
1743 * @return {Function} Middleware function.
1744 */
1745
1746 const createResolversCacheMiddleware = (registry, reducerKey) => () => next => action => {
1747 const resolvers = registry.select(store).getCachedResolvers(reducerKey);
1748 Object.entries(resolvers).forEach(_ref => {
1749 var _registry$stores, _registry$stores$redu, _registry$stores$redu2;
1750
1751 let [selectorName, resolversByArgs] = _ref;
1752 const resolver = (_registry$stores = registry.stores) === null || _registry$stores === void 0 ? void 0 : (_registry$stores$redu = _registry$stores[reducerKey]) === null || _registry$stores$redu === void 0 ? void 0 : (_registry$stores$redu2 = _registry$stores$redu.resolvers) === null || _registry$stores$redu2 === void 0 ? void 0 : _registry$stores$redu2[selectorName];
1753
1754 if (!resolver || !resolver.shouldInvalidate) {
1755 return;
1756 }
1757
1758 resolversByArgs.forEach((value, args) => {
1759 // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.
1760 // If the value is "finished" or "error" it means this resolver has finished its resolution which means we need
1761 // to invalidate it, if it's true it means it's inflight and the invalidation is not necessary.
1762 if ((value === null || value === void 0 ? void 0 : value.status) !== 'finished' && (value === null || value === void 0 ? void 0 : value.status) !== 'error' || !resolver.shouldInvalidate(action, ...args)) {
1763 return;
1764 } // Trigger cache invalidation
1765
1766
1767 registry.dispatch(store).invalidateResolution(reducerKey, selectorName, args);
1768 });
1769 });
1770 return next(action);
1771 };
1772
1773 /* harmony default export */ var resolvers_cache_middleware = (createResolversCacheMiddleware);
1774
1775 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/thunk-middleware.js
1776 function createThunkMiddleware(args) {
1777 return () => next => action => {
1778 if (typeof action === 'function') {
1779 return action(args);
1780 }
1781
1782 return next(action);
1783 };
1784 }
1785
1786 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/utils.js
1787 /**
1788 * External dependencies
1789 */
1790
1791 /**
1792 * Higher-order reducer creator which creates a combined reducer object, keyed
1793 * by a property on the action object.
1794 *
1795 * @param actionProperty Action property by which to key object.
1796 * @return Higher-order reducer.
1797 */
1798 const onSubKey = actionProperty => reducer => function () {
1799 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1800 let action = arguments.length > 1 ? arguments[1] : undefined;
1801 // Retrieve subkey from action. Do not track if undefined; useful for cases
1802 // where reducer is scoped by action shape.
1803 const key = action[actionProperty];
1804
1805 if (key === undefined) {
1806 return state;
1807 } // Avoid updating state if unchanged. Note that this also accounts for a
1808 // reducer which returns undefined on a key which is not yet tracked.
1809
1810
1811 const nextKeyState = reducer(state[key], action);
1812
1813 if (nextKeyState === state[key]) {
1814 return state;
1815 }
1816
1817 return { ...state,
1818 [key]: nextKeyState
1819 };
1820 };
1821 /**
1822 * Normalize selector argument array by defaulting `undefined` value to an empty array
1823 * and removing trailing `undefined` values.
1824 *
1825 * @param args Selector argument array
1826 * @return Normalized state key array
1827 */
1828
1829 function selectorArgsToStateKey(args) {
1830 if (args === undefined || args === null) {
1831 return [];
1832 }
1833
1834 const len = args.length;
1835 let idx = len;
1836
1837 while (idx > 0 && args[idx - 1] === undefined) {
1838 idx--;
1839 }
1840
1841 return idx === len ? args : args.slice(0, idx);
1842 }
1843
1844 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/reducer.js
1845 /**
1846 * External dependencies
1847 */
1848
1849
1850 /**
1851 * Internal dependencies
1852 */
1853
1854
1855 /**
1856 * Reducer function returning next state for selector resolution of
1857 * subkeys, object form:
1858 *
1859 * selectorName -> EquivalentKeyMap<Array,boolean>
1860 */
1861 const subKeysIsResolved = onSubKey('selectorName')(function () {
1862 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new (equivalent_key_map_default())();
1863 let action = arguments.length > 1 ? arguments[1] : undefined;
1864
1865 switch (action.type) {
1866 case 'START_RESOLUTION':
1867 {
1868 const nextState = new (equivalent_key_map_default())(state);
1869 nextState.set(selectorArgsToStateKey(action.args), {
1870 status: 'resolving'
1871 });
1872 return nextState;
1873 }
1874
1875 case 'FINISH_RESOLUTION':
1876 {
1877 const nextState = new (equivalent_key_map_default())(state);
1878 nextState.set(selectorArgsToStateKey(action.args), {
1879 status: 'finished'
1880 });
1881 return nextState;
1882 }
1883
1884 case 'FAIL_RESOLUTION':
1885 {
1886 const nextState = new (equivalent_key_map_default())(state);
1887 nextState.set(selectorArgsToStateKey(action.args), {
1888 status: 'error',
1889 error: action.error
1890 });
1891 return nextState;
1892 }
1893
1894 case 'START_RESOLUTIONS':
1895 {
1896 const nextState = new (equivalent_key_map_default())(state);
1897
1898 for (const resolutionArgs of action.args) {
1899 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1900 status: 'resolving'
1901 });
1902 }
1903
1904 return nextState;
1905 }
1906
1907 case 'FINISH_RESOLUTIONS':
1908 {
1909 const nextState = new (equivalent_key_map_default())(state);
1910
1911 for (const resolutionArgs of action.args) {
1912 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1913 status: 'finished'
1914 });
1915 }
1916
1917 return nextState;
1918 }
1919
1920 case 'FAIL_RESOLUTIONS':
1921 {
1922 const nextState = new (equivalent_key_map_default())(state);
1923 action.args.forEach((resolutionArgs, idx) => {
1924 const resolutionState = {
1925 status: 'error',
1926 error: undefined
1927 };
1928 const error = action.errors[idx];
1929
1930 if (error) {
1931 resolutionState.error = error;
1932 }
1933
1934 nextState.set(selectorArgsToStateKey(resolutionArgs), resolutionState);
1935 });
1936 return nextState;
1937 }
1938
1939 case 'INVALIDATE_RESOLUTION':
1940 {
1941 const nextState = new (equivalent_key_map_default())(state);
1942 nextState.delete(selectorArgsToStateKey(action.args));
1943 return nextState;
1944 }
1945 }
1946
1947 return state;
1948 });
1949 /**
1950 * Reducer function returning next state for selector resolution, object form:
1951 *
1952 * selectorName -> EquivalentKeyMap<Array, boolean>
1953 *
1954 * @param state Current state.
1955 * @param action Dispatched action.
1956 *
1957 * @return Next state.
1958 */
1959
1960 const isResolved = function () {
1961 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1962 let action = arguments.length > 1 ? arguments[1] : undefined;
1963
1964 switch (action.type) {
1965 case 'INVALIDATE_RESOLUTION_FOR_STORE':
1966 return {};
1967
1968 case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR':
1969 {
1970 if (action.selectorName in state) {
1971 const {
1972 [action.selectorName]: removedSelector,
1973 ...restState
1974 } = state;
1975 return restState;
1976 }
1977
1978 return state;
1979 }
1980
1981 case 'START_RESOLUTION':
1982 case 'FINISH_RESOLUTION':
1983 case 'FAIL_RESOLUTION':
1984 case 'START_RESOLUTIONS':
1985 case 'FINISH_RESOLUTIONS':
1986 case 'FAIL_RESOLUTIONS':
1987 case 'INVALIDATE_RESOLUTION':
1988 return subKeysIsResolved(state, action);
1989 }
1990
1991 return state;
1992 };
1993
1994 /* harmony default export */ var metadata_reducer = (isResolved);
1995
1996 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/selectors.js
1997 /**
1998 * Internal dependencies
1999 */
2000
2001 /** @typedef {Record<string, import('./reducer').State>} State */
2002
2003 /** @typedef {import('./reducer').StateValue} StateValue */
2004
2005 /** @typedef {import('./reducer').Status} Status */
2006
2007 /**
2008 * Returns the raw resolution state value for a given selector name,
2009 * and arguments set. May be undefined if the selector has never been resolved
2010 * or not resolved for the given set of arguments, otherwise true or false for
2011 * resolution started and completed respectively.
2012 *
2013 * @param {State} state Data state.
2014 * @param {string} selectorName Selector name.
2015 * @param {unknown[]?} args Arguments passed to selector.
2016 *
2017 * @return {StateValue|undefined} isResolving value.
2018 */
2019
2020 function getResolutionState(state, selectorName, args) {
2021 const map = state[selectorName];
2022
2023 if (!map) {
2024 return;
2025 }
2026
2027 return map.get(selectorArgsToStateKey(args));
2028 }
2029 /**
2030 * Returns the raw `isResolving` value for a given selector name,
2031 * and arguments set. May be undefined if the selector has never been resolved
2032 * or not resolved for the given set of arguments, otherwise true or false for
2033 * resolution started and completed respectively.
2034 *
2035 * @param {State} state Data state.
2036 * @param {string} selectorName Selector name.
2037 * @param {unknown[]?} args Arguments passed to selector.
2038 *
2039 * @return {boolean | undefined} isResolving value.
2040 */
2041
2042 function getIsResolving(state, selectorName, args) {
2043 const resolutionState = getResolutionState(state, selectorName, args);
2044 return resolutionState && resolutionState.status === 'resolving';
2045 }
2046 /**
2047 * Returns true if resolution has already been triggered for a given
2048 * selector name, and arguments set.
2049 *
2050 * @param {State} state Data state.
2051 * @param {string} selectorName Selector name.
2052 * @param {unknown[]?} args Arguments passed to selector.
2053 *
2054 * @return {boolean} Whether resolution has been triggered.
2055 */
2056
2057 function hasStartedResolution(state, selectorName, args) {
2058 return getResolutionState(state, selectorName, args) !== undefined;
2059 }
2060 /**
2061 * Returns true if resolution has completed for a given selector
2062 * name, and arguments set.
2063 *
2064 * @param {State} state Data state.
2065 * @param {string} selectorName Selector name.
2066 * @param {unknown[]?} args Arguments passed to selector.
2067 *
2068 * @return {boolean} Whether resolution has completed.
2069 */
2070
2071 function hasFinishedResolution(state, selectorName, args) {
2072 var _getResolutionState;
2073
2074 const status = (_getResolutionState = getResolutionState(state, selectorName, args)) === null || _getResolutionState === void 0 ? void 0 : _getResolutionState.status;
2075 return status === 'finished' || status === 'error';
2076 }
2077 /**
2078 * Returns true if resolution has failed for a given selector
2079 * name, and arguments set.
2080 *
2081 * @param {State} state Data state.
2082 * @param {string} selectorName Selector name.
2083 * @param {unknown[]?} args Arguments passed to selector.
2084 *
2085 * @return {boolean} Has resolution failed
2086 */
2087
2088 function hasResolutionFailed(state, selectorName, args) {
2089 var _getResolutionState2;
2090
2091 return ((_getResolutionState2 = getResolutionState(state, selectorName, args)) === null || _getResolutionState2 === void 0 ? void 0 : _getResolutionState2.status) === 'error';
2092 }
2093 /**
2094 * Returns the resolution error for a given selector name, and arguments set.
2095 * Note it may be of an Error type, but may also be null, undefined, or anything else
2096 * that can be `throw`-n.
2097 *
2098 * @param {State} state Data state.
2099 * @param {string} selectorName Selector name.
2100 * @param {unknown[]?} args Arguments passed to selector.
2101 *
2102 * @return {Error|unknown} Last resolution error
2103 */
2104
2105 function getResolutionError(state, selectorName, args) {
2106 const resolutionState = getResolutionState(state, selectorName, args);
2107 return (resolutionState === null || resolutionState === void 0 ? void 0 : resolutionState.status) === 'error' ? resolutionState.error : null;
2108 }
2109 /**
2110 * Returns true if resolution has been triggered but has not yet completed for
2111 * a given selector name, and arguments set.
2112 *
2113 * @param {State} state Data state.
2114 * @param {string} selectorName Selector name.
2115 * @param {unknown[]?} args Arguments passed to selector.
2116 *
2117 * @return {boolean} Whether resolution is in progress.
2118 */
2119
2120 function isResolving(state, selectorName, args) {
2121 var _getResolutionState3;
2122
2123 return ((_getResolutionState3 = getResolutionState(state, selectorName, args)) === null || _getResolutionState3 === void 0 ? void 0 : _getResolutionState3.status) === 'resolving';
2124 }
2125 /**
2126 * Returns the list of the cached resolvers.
2127 *
2128 * @param {State} state Data state.
2129 *
2130 * @return {State} Resolvers mapped by args and selectorName.
2131 */
2132
2133 function getCachedResolvers(state) {
2134 return state;
2135 }
2136
2137 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/actions.js
2138 /**
2139 * Returns an action object used in signalling that selector resolution has
2140 * started.
2141 *
2142 * @param {string} selectorName Name of selector for which resolver triggered.
2143 * @param {unknown[]} args Arguments to associate for uniqueness.
2144 *
2145 * @return {{ type: 'START_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
2146 */
2147 function startResolution(selectorName, args) {
2148 return {
2149 type: 'START_RESOLUTION',
2150 selectorName,
2151 args
2152 };
2153 }
2154 /**
2155 * Returns an action object used in signalling that selector resolution has
2156 * completed.
2157 *
2158 * @param {string} selectorName Name of selector for which resolver triggered.
2159 * @param {unknown[]} args Arguments to associate for uniqueness.
2160 *
2161 * @return {{ type: 'FINISH_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
2162 */
2163
2164 function finishResolution(selectorName, args) {
2165 return {
2166 type: 'FINISH_RESOLUTION',
2167 selectorName,
2168 args
2169 };
2170 }
2171 /**
2172 * Returns an action object used in signalling that selector resolution has
2173 * failed.
2174 *
2175 * @param {string} selectorName Name of selector for which resolver triggered.
2176 * @param {unknown[]} args Arguments to associate for uniqueness.
2177 * @param {Error|unknown} error The error that caused the failure.
2178 *
2179 * @return {{ type: 'FAIL_RESOLUTION', selectorName: string, args: unknown[], error: Error|unknown }} Action object.
2180 */
2181
2182 function failResolution(selectorName, args, error) {
2183 return {
2184 type: 'FAIL_RESOLUTION',
2185 selectorName,
2186 args,
2187 error
2188 };
2189 }
2190 /**
2191 * Returns an action object used in signalling that a batch of selector resolutions has
2192 * started.
2193 *
2194 * @param {string} selectorName Name of selector for which resolver triggered.
2195 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2196 * is associated to a resolution.
2197 *
2198 * @return {{ type: 'START_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2199 */
2200
2201 function startResolutions(selectorName, args) {
2202 return {
2203 type: 'START_RESOLUTIONS',
2204 selectorName,
2205 args
2206 };
2207 }
2208 /**
2209 * Returns an action object used in signalling that a batch of selector resolutions has
2210 * completed.
2211 *
2212 * @param {string} selectorName Name of selector for which resolver triggered.
2213 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2214 * is associated to a resolution.
2215 *
2216 * @return {{ type: 'FINISH_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2217 */
2218
2219 function finishResolutions(selectorName, args) {
2220 return {
2221 type: 'FINISH_RESOLUTIONS',
2222 selectorName,
2223 args
2224 };
2225 }
2226 /**
2227 * Returns an action object used in signalling that a batch of selector resolutions has
2228 * completed and at least one of them has failed.
2229 *
2230 * @param {string} selectorName Name of selector for which resolver triggered.
2231 * @param {unknown[]} args Array of arguments to associate for uniqueness, each item
2232 * is associated to a resolution.
2233 * @param {(Error|unknown)[]} errors Array of errors to associate for uniqueness, each item
2234 * is associated to a resolution.
2235 * @return {{ type: 'FAIL_RESOLUTIONS', selectorName: string, args: unknown[], errors: Array<Error|unknown> }} Action object.
2236 */
2237
2238 function failResolutions(selectorName, args, errors) {
2239 return {
2240 type: 'FAIL_RESOLUTIONS',
2241 selectorName,
2242 args,
2243 errors
2244 };
2245 }
2246 /**
2247 * Returns an action object used in signalling that we should invalidate the resolution cache.
2248 *
2249 * @param {string} selectorName Name of selector for which resolver should be invalidated.
2250 * @param {unknown[]} args Arguments to associate for uniqueness.
2251 *
2252 * @return {{ type: 'INVALIDATE_RESOLUTION', selectorName: string, args: any[] }} Action object.
2253 */
2254
2255 function invalidateResolution(selectorName, args) {
2256 return {
2257 type: 'INVALIDATE_RESOLUTION',
2258 selectorName,
2259 args
2260 };
2261 }
2262 /**
2263 * Returns an action object used in signalling that the resolution
2264 * should be invalidated.
2265 *
2266 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE' }} Action object.
2267 */
2268
2269 function invalidateResolutionForStore() {
2270 return {
2271 type: 'INVALIDATE_RESOLUTION_FOR_STORE'
2272 };
2273 }
2274 /**
2275 * Returns an action object used in signalling that the resolution cache for a
2276 * given selectorName should be invalidated.
2277 *
2278 * @param {string} selectorName Name of selector for which all resolvers should
2279 * be invalidated.
2280 *
2281 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR', selectorName: string }} Action object.
2282 */
2283
2284 function invalidateResolutionForStoreSelector(selectorName) {
2285 return {
2286 type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR',
2287 selectorName
2288 };
2289 }
2290
2291 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/index.js
2292 /**
2293 * External dependencies
2294 */
2295
2296
2297
2298 /**
2299 * WordPress dependencies
2300 */
2301
2302
2303
2304 /**
2305 * Internal dependencies
2306 */
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316 /** @typedef {import('../types').DataRegistry} DataRegistry */
2317
2318 /**
2319 * @typedef {import('../types').StoreDescriptor<C>} StoreDescriptor
2320 * @template {import('../types').AnyConfig} C
2321 */
2322
2323 /**
2324 * @typedef {import('../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
2325 * @template State
2326 * @template {Record<string,import('../../types').ActionCreator>} Actions
2327 * @template Selectors
2328 */
2329
2330 const trimUndefinedValues = array => {
2331 const result = [...array];
2332
2333 for (let i = result.length - 1; i >= 0; i--) {
2334 if (result[i] === undefined) {
2335 result.splice(i, 1);
2336 }
2337 }
2338
2339 return result;
2340 };
2341 /**
2342 * Creates a new object with the same keys, but with `callback()` called as
2343 * a transformer function on each of the values.
2344 *
2345 * @param {Object} obj The object to transform.
2346 * @param {Function} callback The function to transform each object value.
2347 * @return {Array} Transformed object.
2348 */
2349
2350
2351 const mapValues = (obj, callback) => Object.entries(obj !== null && obj !== void 0 ? obj : {}).reduce((acc, _ref) => {
2352 let [key, value] = _ref;
2353 return { ...acc,
2354 [key]: callback(value, key)
2355 };
2356 }, {}); // Convert Map objects to plain objects
2357
2358
2359 const mapToObject = (key, state) => {
2360 if (state instanceof Map) {
2361 return Object.fromEntries(state);
2362 }
2363
2364 return state;
2365 };
2366 /**
2367 * Create a cache to track whether resolvers started running or not.
2368 *
2369 * @return {Object} Resolvers Cache.
2370 */
2371
2372
2373 function createResolversCache() {
2374 const cache = {};
2375 return {
2376 isRunning(selectorName, args) {
2377 return cache[selectorName] && cache[selectorName].get(trimUndefinedValues(args));
2378 },
2379
2380 clear(selectorName, args) {
2381 if (cache[selectorName]) {
2382 cache[selectorName].delete(trimUndefinedValues(args));
2383 }
2384 },
2385
2386 markAsRunning(selectorName, args) {
2387 if (!cache[selectorName]) {
2388 cache[selectorName] = new (equivalent_key_map_default())();
2389 }
2390
2391 cache[selectorName].set(trimUndefinedValues(args), true);
2392 }
2393
2394 };
2395 }
2396 /**
2397 * Creates a data store descriptor for the provided Redux store configuration containing
2398 * properties describing reducer, actions, selectors, controls and resolvers.
2399 *
2400 * @example
2401 * ```js
2402 * import { createReduxStore } from '@wordpress/data';
2403 *
2404 * const store = createReduxStore( 'demo', {
2405 * reducer: ( state = 'OK' ) => state,
2406 * selectors: {
2407 * getValue: ( state ) => state,
2408 * },
2409 * } );
2410 * ```
2411 *
2412 * @template State
2413 * @template {Record<string,import('../../types').ActionCreator>} Actions
2414 * @template Selectors
2415 * @param {string} key Unique namespace identifier.
2416 * @param {ReduxStoreConfig<State,Actions,Selectors>} options Registered store options, with properties
2417 * describing reducer, actions, selectors,
2418 * and resolvers.
2419 *
2420 * @return {StoreDescriptor<ReduxStoreConfig<State,Actions,Selectors>>} Store Object.
2421 */
2422
2423
2424 function createReduxStore(key, options) {
2425 const privateActions = {};
2426 const privateSelectors = {};
2427 const privateRegistrationFunctions = {
2428 privateActions,
2429 registerPrivateActions: actions => {
2430 Object.assign(privateActions, actions);
2431 },
2432 privateSelectors,
2433 registerPrivateSelectors: selectors => {
2434 Object.assign(privateSelectors, selectors);
2435 }
2436 };
2437 const storeDescriptor = {
2438 name: key,
2439 instantiate: registry => {
2440 const reducer = options.reducer;
2441 const thunkArgs = {
2442 registry,
2443
2444 get dispatch() {
2445 return Object.assign(action => store.dispatch(action), getActions());
2446 },
2447
2448 get select() {
2449 return Object.assign(selector => selector(store.__unstableOriginalGetState()), getSelectors());
2450 },
2451
2452 get resolveSelect() {
2453 return getResolveSelectors();
2454 }
2455
2456 };
2457 const store = instantiateReduxStore(key, options, registry, thunkArgs); // Expose the private registration functions on the store
2458 // so they can be copied to a sub registry in registry.js.
2459
2460 lock(store, privateRegistrationFunctions);
2461 const resolversCache = createResolversCache();
2462 let resolvers;
2463 const actions = mapActions({ ...actions_namespaceObject,
2464 ...options.actions
2465 }, store);
2466 lock(actions, new Proxy(privateActions, {
2467 get: (target, prop) => {
2468 return mapActions(privateActions, store)[prop] || actions[prop];
2469 }
2470 }));
2471 let selectors = mapSelectors({ ...mapValues(selectors_namespaceObject, selector => function (state) {
2472 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2473 args[_key - 1] = arguments[_key];
2474 }
2475
2476 return selector(state.metadata, ...args);
2477 }),
2478 ...mapValues(options.selectors, selector => {
2479 if (selector.isRegistrySelector) {
2480 selector.registry = registry;
2481 }
2482
2483 return function (state) {
2484 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2485 args[_key2 - 1] = arguments[_key2];
2486 }
2487
2488 return selector(state.root, ...args);
2489 };
2490 })
2491 }, store);
2492 lock(selectors, new Proxy(privateSelectors, {
2493 get: (target, prop) => {
2494 return mapSelectors(mapValues(privateSelectors, selector => function (state) {
2495 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
2496 args[_key3 - 1] = arguments[_key3];
2497 }
2498
2499 return selector(state.root, ...args);
2500 }), store)[prop] || selectors[prop];
2501 }
2502 }));
2503
2504 if (options.resolvers) {
2505 const result = mapResolvers(options.resolvers, selectors, store, resolversCache);
2506 resolvers = result.resolvers;
2507 selectors = result.selectors;
2508 }
2509
2510 const resolveSelectors = mapResolveSelectors(selectors, store);
2511 const suspendSelectors = mapSuspendSelectors(selectors, store);
2512
2513 const getSelectors = () => selectors;
2514
2515 const getActions = () => actions;
2516
2517 const getResolveSelectors = () => resolveSelectors;
2518
2519 const getSuspendSelectors = () => suspendSelectors; // We have some modules monkey-patching the store object
2520 // It's wrong to do so but until we refactor all of our effects to controls
2521 // We need to keep the same "store" instance here.
2522
2523
2524 store.__unstableOriginalGetState = store.getState;
2525
2526 store.getState = () => store.__unstableOriginalGetState().root; // Customize subscribe behavior to call listeners only on effective change,
2527 // not on every dispatch.
2528
2529
2530 const subscribe = store && (listener => {
2531 let lastState = store.__unstableOriginalGetState();
2532
2533 return store.subscribe(() => {
2534 const state = store.__unstableOriginalGetState();
2535
2536 const hasChanged = state !== lastState;
2537 lastState = state;
2538
2539 if (hasChanged) {
2540 listener();
2541 }
2542 });
2543 }); // This can be simplified to just { subscribe, getSelectors, getActions }
2544 // Once we remove the use function.
2545
2546
2547 return {
2548 reducer,
2549 store,
2550 actions,
2551 selectors,
2552 resolvers,
2553 getSelectors,
2554 getResolveSelectors,
2555 getSuspendSelectors,
2556 getActions,
2557 subscribe
2558 };
2559 }
2560 }; // Expose the private registration functions on the store
2561 // descriptor. That's a natural choice since that's where the
2562 // public actions and selectors are stored .
2563
2564 lock(storeDescriptor, privateRegistrationFunctions);
2565 return storeDescriptor;
2566 }
2567 /**
2568 * Creates a redux store for a namespace.
2569 *
2570 * @param {string} key Unique namespace identifier.
2571 * @param {Object} options Registered store options, with properties
2572 * describing reducer, actions, selectors,
2573 * and resolvers.
2574 * @param {DataRegistry} registry Registry reference.
2575 * @param {Object} thunkArgs Argument object for the thunk middleware.
2576 * @return {Object} Newly created redux store.
2577 */
2578
2579 function instantiateReduxStore(key, options, registry, thunkArgs) {
2580 const controls = { ...options.controls,
2581 ...builtinControls
2582 };
2583 const normalizedControls = mapValues(controls, control => control.isRegistryControl ? control(registry) : control);
2584 const middlewares = [resolvers_cache_middleware(registry, key), promise_middleware, external_wp_reduxRoutine_default()(normalizedControls), createThunkMiddleware(thunkArgs)];
2585 const enhancers = [applyMiddleware(...middlewares)];
2586
2587 if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
2588 enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__({
2589 name: key,
2590 instanceId: key,
2591 serialize: {
2592 replacer: mapToObject
2593 }
2594 }));
2595 }
2596
2597 const {
2598 reducer,
2599 initialState
2600 } = options;
2601 const enhancedReducer = turbo_combine_reducers_default()({
2602 metadata: metadata_reducer,
2603 root: reducer
2604 });
2605 return createStore(enhancedReducer, {
2606 root: initialState
2607 }, (0,external_wp_compose_namespaceObject.compose)(enhancers));
2608 }
2609 /**
2610 * Maps selectors to a store.
2611 *
2612 * @param {Object} selectors Selectors to register. Keys will be used as the
2613 * public facing API. Selectors will get passed the
2614 * state as first argument.
2615 * @param {Object} store The store to which the selectors should be mapped.
2616 * @return {Object} Selectors mapped to the provided store.
2617 */
2618
2619
2620 function mapSelectors(selectors, store) {
2621 const createStateSelector = registrySelector => {
2622 const selector = function runSelector() {
2623 // This function is an optimized implementation of:
2624 //
2625 // selector( store.getState(), ...arguments )
2626 //
2627 // Where the above would incur an `Array#concat` in its application,
2628 // the logic here instead efficiently constructs an arguments array via
2629 // direct assignment.
2630 const argsLength = arguments.length;
2631 const args = new Array(argsLength + 1);
2632 args[0] = store.__unstableOriginalGetState();
2633
2634 for (let i = 0; i < argsLength; i++) {
2635 args[i + 1] = arguments[i];
2636 }
2637
2638 return registrySelector(...args);
2639 };
2640
2641 selector.hasResolver = false;
2642 return selector;
2643 };
2644
2645 return mapValues(selectors, createStateSelector);
2646 }
2647 /**
2648 * Maps actions to dispatch from a given store.
2649 *
2650 * @param {Object} actions Actions to register.
2651 * @param {Object} store The redux store to which the actions should be mapped.
2652 *
2653 * @return {Object} Actions mapped to the redux store provided.
2654 */
2655
2656
2657 function mapActions(actions, store) {
2658 const createBoundAction = action => function () {
2659 return Promise.resolve(store.dispatch(action(...arguments)));
2660 };
2661
2662 return mapValues(actions, createBoundAction);
2663 }
2664 /**
2665 * Maps selectors to functions that return a resolution promise for them
2666 *
2667 * @param {Object} selectors Selectors to map.
2668 * @param {Object} store The redux store the selectors select from.
2669 *
2670 * @return {Object} Selectors mapped to their resolution functions.
2671 */
2672
2673
2674 function mapResolveSelectors(selectors, store) {
2675 const {
2676 getIsResolving,
2677 hasStartedResolution,
2678 hasFinishedResolution,
2679 hasResolutionFailed,
2680 isResolving,
2681 getCachedResolvers,
2682 getResolutionState,
2683 getResolutionError,
2684 ...storeSelectors
2685 } = selectors;
2686 return mapValues(storeSelectors, (selector, selectorName) => {
2687 // If the selector doesn't have a resolver, just convert the return value
2688 // (including exceptions) to a Promise, no additional extra behavior is needed.
2689 if (!selector.hasResolver) {
2690 return async function () {
2691 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
2692 args[_key4] = arguments[_key4];
2693 }
2694
2695 return selector.apply(null, args);
2696 };
2697 }
2698
2699 return function () {
2700 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
2701 args[_key5] = arguments[_key5];
2702 }
2703
2704 return new Promise((resolve, reject) => {
2705 const hasFinished = () => selectors.hasFinishedResolution(selectorName, args);
2706
2707 const finalize = result => {
2708 const hasFailed = selectors.hasResolutionFailed(selectorName, args);
2709
2710 if (hasFailed) {
2711 const error = selectors.getResolutionError(selectorName, args);
2712 reject(error);
2713 } else {
2714 resolve(result);
2715 }
2716 };
2717
2718 const getResult = () => selector.apply(null, args); // Trigger the selector (to trigger the resolver)
2719
2720
2721 const result = getResult();
2722
2723 if (hasFinished()) {
2724 return finalize(result);
2725 }
2726
2727 const unsubscribe = store.subscribe(() => {
2728 if (hasFinished()) {
2729 unsubscribe();
2730 finalize(getResult());
2731 }
2732 });
2733 });
2734 };
2735 });
2736 }
2737 /**
2738 * Maps selectors to functions that throw a suspense promise if not yet resolved.
2739 *
2740 * @param {Object} selectors Selectors to map.
2741 * @param {Object} store The redux store the selectors select from.
2742 *
2743 * @return {Object} Selectors mapped to their suspense functions.
2744 */
2745
2746
2747 function mapSuspendSelectors(selectors, store) {
2748 return mapValues(selectors, (selector, selectorName) => {
2749 // Selector without a resolver doesn't have any extra suspense behavior.
2750 if (!selector.hasResolver) {
2751 return selector;
2752 }
2753
2754 return function () {
2755 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
2756 args[_key6] = arguments[_key6];
2757 }
2758
2759 const result = selector.apply(null, args);
2760
2761 if (selectors.hasFinishedResolution(selectorName, args)) {
2762 if (selectors.hasResolutionFailed(selectorName, args)) {
2763 throw selectors.getResolutionError(selectorName, args);
2764 }
2765
2766 return result;
2767 }
2768
2769 throw new Promise(resolve => {
2770 const unsubscribe = store.subscribe(() => {
2771 if (selectors.hasFinishedResolution(selectorName, args)) {
2772 resolve();
2773 unsubscribe();
2774 }
2775 });
2776 });
2777 };
2778 });
2779 }
2780 /**
2781 * Returns resolvers with matched selectors for a given namespace.
2782 * Resolvers are side effects invoked once per argument set of a given selector call,
2783 * used in ensuring that the data needs for the selector are satisfied.
2784 *
2785 * @param {Object} resolvers Resolvers to register.
2786 * @param {Object} selectors The current selectors to be modified.
2787 * @param {Object} store The redux store to which the resolvers should be mapped.
2788 * @param {Object} resolversCache Resolvers Cache.
2789 */
2790
2791
2792 function mapResolvers(resolvers, selectors, store, resolversCache) {
2793 // The `resolver` can be either a function that does the resolution, or, in more advanced
2794 // cases, an object with a `fullfill` method and other optional methods like `isFulfilled`.
2795 // Here we normalize the `resolver` function to an object with `fulfill` method.
2796 const mappedResolvers = mapValues(resolvers, resolver => {
2797 if (resolver.fulfill) {
2798 return resolver;
2799 }
2800
2801 return { ...resolver,
2802 // Copy the enumerable properties of the resolver function.
2803 fulfill: resolver // Add the fulfill method.
2804
2805 };
2806 });
2807
2808 const mapSelector = (selector, selectorName) => {
2809 const resolver = resolvers[selectorName];
2810
2811 if (!resolver) {
2812 selector.hasResolver = false;
2813 return selector;
2814 }
2815
2816 const selectorResolver = function () {
2817 for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
2818 args[_key7] = arguments[_key7];
2819 }
2820
2821 async function fulfillSelector() {
2822 const state = store.getState();
2823
2824 if (resolversCache.isRunning(selectorName, args) || typeof resolver.isFulfilled === 'function' && resolver.isFulfilled(state, ...args)) {
2825 return;
2826 }
2827
2828 const {
2829 metadata
2830 } = store.__unstableOriginalGetState();
2831
2832 if (hasStartedResolution(metadata, selectorName, args)) {
2833 return;
2834 }
2835
2836 resolversCache.markAsRunning(selectorName, args);
2837 setTimeout(async () => {
2838 resolversCache.clear(selectorName, args);
2839 store.dispatch(startResolution(selectorName, args));
2840
2841 try {
2842 await fulfillResolver(store, mappedResolvers, selectorName, ...args);
2843 store.dispatch(finishResolution(selectorName, args));
2844 } catch (error) {
2845 store.dispatch(failResolution(selectorName, args, error));
2846 }
2847 });
2848 }
2849
2850 fulfillSelector(...args);
2851 return selector(...args);
2852 };
2853
2854 selectorResolver.hasResolver = true;
2855 return selectorResolver;
2856 };
2857
2858 return {
2859 resolvers: mappedResolvers,
2860 selectors: mapValues(selectors, mapSelector)
2861 };
2862 }
2863 /**
2864 * Calls a resolver given arguments
2865 *
2866 * @param {Object} store Store reference, for fulfilling via resolvers
2867 * @param {Object} resolvers Store Resolvers
2868 * @param {string} selectorName Selector name to fulfill.
2869 * @param {Array} args Selector Arguments.
2870 */
2871
2872
2873 async function fulfillResolver(store, resolvers, selectorName) {
2874 const resolver = resolvers[selectorName];
2875
2876 if (!resolver) {
2877 return;
2878 }
2879
2880 for (var _len8 = arguments.length, args = new Array(_len8 > 3 ? _len8 - 3 : 0), _key8 = 3; _key8 < _len8; _key8++) {
2881 args[_key8 - 3] = arguments[_key8];
2882 }
2883
2884 const action = resolver.fulfill(...args);
2885
2886 if (action) {
2887 await store.dispatch(action);
2888 }
2889 }
2890
2891 ;// CONCATENATED MODULE: ./packages/data/build-module/utils/emitter.js
2892 /**
2893 * Create an event emitter.
2894 *
2895 * @return {import("../types").DataEmitter} Emitter.
2896 */
2897 function createEmitter() {
2898 let isPaused = false;
2899 let isPending = false;
2900 const listeners = new Set();
2901
2902 const notifyListeners = () => // We use Array.from to clone the listeners Set
2903 // This ensures that we don't run a listener
2904 // that was added as a response to another listener.
2905 Array.from(listeners).forEach(listener => listener());
2906
2907 return {
2908 get isPaused() {
2909 return isPaused;
2910 },
2911
2912 subscribe(listener) {
2913 listeners.add(listener);
2914 return () => listeners.delete(listener);
2915 },
2916
2917 pause() {
2918 isPaused = true;
2919 },
2920
2921 resume() {
2922 isPaused = false;
2923
2924 if (isPending) {
2925 isPending = false;
2926 notifyListeners();
2927 }
2928 },
2929
2930 emit() {
2931 if (isPaused) {
2932 isPending = true;
2933 return;
2934 }
2935
2936 notifyListeners();
2937 }
2938
2939 };
2940 }
2941
2942 ;// CONCATENATED MODULE: ./packages/data/build-module/registry.js
2943 /**
2944 * WordPress dependencies
2945 */
2946
2947 /**
2948 * Internal dependencies
2949 */
2950
2951
2952
2953
2954
2955 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
2956
2957 /**
2958 * @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
2959 *
2960 * @property {Function} registerGenericStore Given a namespace key and settings
2961 * object, registers a new generic
2962 * store.
2963 * @property {Function} registerStore Given a namespace key and settings
2964 * object, registers a new namespace
2965 * store.
2966 * @property {Function} subscribe Given a function callback, invokes
2967 * the callback on any change to state
2968 * within any registered store.
2969 * @property {Function} select Given a namespace key, returns an
2970 * object of the store's registered
2971 * selectors.
2972 * @property {Function} dispatch Given a namespace key, returns an
2973 * object of the store's registered
2974 * action dispatchers.
2975 */
2976
2977 /**
2978 * @typedef {Object} WPDataPlugin An object of registry function overrides.
2979 *
2980 * @property {Function} registerStore registers store.
2981 */
2982
2983 function getStoreName(storeNameOrDescriptor) {
2984 return typeof storeNameOrDescriptor === 'string' ? storeNameOrDescriptor : storeNameOrDescriptor.name;
2985 }
2986 /**
2987 * Creates a new store registry, given an optional object of initial store
2988 * configurations.
2989 *
2990 * @param {Object} storeConfigs Initial store configurations.
2991 * @param {Object?} parent Parent registry.
2992 *
2993 * @return {WPDataRegistry} Data registry.
2994 */
2995
2996
2997 function createRegistry() {
2998 let storeConfigs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2999 let parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
3000 const stores = {};
3001 const emitter = createEmitter();
3002 let listeningStores = null;
3003 /**
3004 * Global listener called for each store's update.
3005 */
3006
3007 function globalListener() {
3008 emitter.emit();
3009 }
3010 /**
3011 * Subscribe to changes to any data, either in all stores in registry, or
3012 * in one specific store.
3013 *
3014 * @param {Function} listener Listener function.
3015 * @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
3016 *
3017 * @return {Function} Unsubscribe function.
3018 */
3019
3020
3021 const subscribe = (listener, storeNameOrDescriptor) => {
3022 // subscribe to all stores
3023 if (!storeNameOrDescriptor) {
3024 return emitter.subscribe(listener);
3025 } // subscribe to one store
3026
3027
3028 const storeName = getStoreName(storeNameOrDescriptor);
3029 const store = stores[storeName];
3030
3031 if (store) {
3032 return store.subscribe(listener);
3033 } // Trying to access a store that hasn't been registered,
3034 // this is a pattern rarely used but seen in some places.
3035 // We fallback to global `subscribe` here for backward-compatibility for now.
3036 // See https://github.com/WordPress/gutenberg/pull/27466 for more info.
3037
3038
3039 if (!parent) {
3040 return emitter.subscribe(listener);
3041 }
3042
3043 return parent.subscribe(listener, storeNameOrDescriptor);
3044 };
3045 /**
3046 * Calls a selector given the current state and extra arguments.
3047 *
3048 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
3049 * or the store descriptor.
3050 *
3051 * @return {*} The selector's returned value.
3052 */
3053
3054
3055 function select(storeNameOrDescriptor) {
3056 var _listeningStores;
3057
3058 const storeName = getStoreName(storeNameOrDescriptor);
3059 (_listeningStores = listeningStores) === null || _listeningStores === void 0 ? void 0 : _listeningStores.add(storeName);
3060 const store = stores[storeName];
3061
3062 if (store) {
3063 return store.getSelectors();
3064 }
3065
3066 return parent === null || parent === void 0 ? void 0 : parent.select(storeName);
3067 }
3068
3069 function __unstableMarkListeningStores(callback, ref) {
3070 listeningStores = new Set();
3071
3072 try {
3073 return callback.call(this);
3074 } finally {
3075 ref.current = Array.from(listeningStores);
3076 listeningStores = null;
3077 }
3078 }
3079 /**
3080 * Given a store descriptor, returns an object containing the store's selectors pre-bound to
3081 * state so that you only need to supply additional arguments, and modified so that they return
3082 * promises that resolve to their eventual values, after any resolvers have ran.
3083 *
3084 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
3085 * convention of passing the store name is
3086 * also supported.
3087 *
3088 * @return {Object} Each key of the object matches the name of a selector.
3089 */
3090
3091
3092 function resolveSelect(storeNameOrDescriptor) {
3093 var _listeningStores2;
3094
3095 const storeName = getStoreName(storeNameOrDescriptor);
3096 (_listeningStores2 = listeningStores) === null || _listeningStores2 === void 0 ? void 0 : _listeningStores2.add(storeName);
3097 const store = stores[storeName];
3098
3099 if (store) {
3100 return store.getResolveSelectors();
3101 }
3102
3103 return parent && parent.resolveSelect(storeName);
3104 }
3105 /**
3106 * Given a store descriptor, returns an object containing the store's selectors pre-bound to
3107 * state so that you only need to supply additional arguments, and modified so that they throw
3108 * promises in case the selector is not resolved yet.
3109 *
3110 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
3111 * convention of passing the store name is
3112 * also supported.
3113 *
3114 * @return {Object} Object containing the store's suspense-wrapped selectors.
3115 */
3116
3117
3118 function suspendSelect(storeNameOrDescriptor) {
3119 var _listeningStores3;
3120
3121 const storeName = getStoreName(storeNameOrDescriptor);
3122 (_listeningStores3 = listeningStores) === null || _listeningStores3 === void 0 ? void 0 : _listeningStores3.add(storeName);
3123 const store = stores[storeName];
3124
3125 if (store) {
3126 return store.getSuspendSelectors();
3127 }
3128
3129 return parent && parent.suspendSelect(storeName);
3130 }
3131 /**
3132 * Returns the available actions for a part of the state.
3133 *
3134 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
3135 * or the store descriptor.
3136 *
3137 * @return {*} The action's returned value.
3138 */
3139
3140
3141 function dispatch(storeNameOrDescriptor) {
3142 const storeName = getStoreName(storeNameOrDescriptor);
3143 const store = stores[storeName];
3144
3145 if (store) {
3146 return store.getActions();
3147 }
3148
3149 return parent && parent.dispatch(storeName);
3150 } //
3151 // Deprecated
3152 // TODO: Remove this after `use()` is removed.
3153
3154
3155 function withPlugins(attributes) {
3156 return Object.fromEntries(Object.entries(attributes).map(_ref => {
3157 let [key, attribute] = _ref;
3158
3159 if (typeof attribute !== 'function') {
3160 return [key, attribute];
3161 }
3162
3163 return [key, function () {
3164 return registry[key].apply(null, arguments);
3165 }];
3166 }));
3167 }
3168 /**
3169 * Registers a store instance.
3170 *
3171 * @param {string} name Store registry name.
3172 * @param {Function} createStore Function that creates a store object (getSelectors, getActions, subscribe).
3173 */
3174
3175
3176 function registerStoreInstance(name, createStore) {
3177 if (stores[name]) {
3178 // eslint-disable-next-line no-console
3179 console.error('Store "' + name + '" is already registered.');
3180 return stores[name];
3181 }
3182
3183 const store = createStore();
3184
3185 if (typeof store.getSelectors !== 'function') {
3186 throw new TypeError('store.getSelectors must be a function');
3187 }
3188
3189 if (typeof store.getActions !== 'function') {
3190 throw new TypeError('store.getActions must be a function');
3191 }
3192
3193 if (typeof store.subscribe !== 'function') {
3194 throw new TypeError('store.subscribe must be a function');
3195 } // The emitter is used to keep track of active listeners when the registry
3196 // get paused, that way, when resumed we should be able to call all these
3197 // pending listeners.
3198
3199
3200 store.emitter = createEmitter();
3201 const currentSubscribe = store.subscribe;
3202
3203 store.subscribe = listener => {
3204 const unsubscribeFromEmitter = store.emitter.subscribe(listener);
3205 const unsubscribeFromStore = currentSubscribe(() => {
3206 if (store.emitter.isPaused) {
3207 store.emitter.emit();
3208 return;
3209 }
3210
3211 listener();
3212 });
3213 return () => {
3214 unsubscribeFromStore === null || unsubscribeFromStore === void 0 ? void 0 : unsubscribeFromStore();
3215 unsubscribeFromEmitter === null || unsubscribeFromEmitter === void 0 ? void 0 : unsubscribeFromEmitter();
3216 };
3217 };
3218
3219 stores[name] = store;
3220 store.subscribe(globalListener); // Copy private actions and selectors from the parent store.
3221
3222 if (parent) {
3223 try {
3224 unlock(store.store).registerPrivateActions(unlock(parent).privateActionsOf(name));
3225 unlock(store.store).registerPrivateSelectors(unlock(parent).privateSelectorsOf(name));
3226 } catch (e) {// unlock() throws if store.store was not locked.
3227 // The error indicates there's nothing to do here so let's
3228 // ignore it.
3229 }
3230 }
3231
3232 return store;
3233 }
3234 /**
3235 * Registers a new store given a store descriptor.
3236 *
3237 * @param {StoreDescriptor} store Store descriptor.
3238 */
3239
3240
3241 function register(store) {
3242 registerStoreInstance(store.name, () => store.instantiate(registry));
3243 }
3244
3245 function registerGenericStore(name, store) {
3246 external_wp_deprecated_default()('wp.data.registerGenericStore', {
3247 since: '5.9',
3248 alternative: 'wp.data.register( storeDescriptor )'
3249 });
3250 registerStoreInstance(name, () => store);
3251 }
3252 /**
3253 * Registers a standard `@wordpress/data` store.
3254 *
3255 * @param {string} storeName Unique namespace identifier.
3256 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
3257 *
3258 * @return {Object} Registered store object.
3259 */
3260
3261
3262 function registerStore(storeName, options) {
3263 if (!options.reducer) {
3264 throw new TypeError('Must specify store reducer');
3265 }
3266
3267 const store = registerStoreInstance(storeName, () => createReduxStore(storeName, options).instantiate(registry));
3268 return store.store;
3269 }
3270
3271 function batch(callback) {
3272 emitter.pause();
3273 Object.values(stores).forEach(store => store.emitter.pause());
3274 callback();
3275 emitter.resume();
3276 Object.values(stores).forEach(store => store.emitter.resume());
3277 }
3278
3279 let registry = {
3280 batch,
3281 stores,
3282 namespaces: stores,
3283 // TODO: Deprecate/remove this.
3284 subscribe,
3285 select,
3286 resolveSelect,
3287 suspendSelect,
3288 dispatch,
3289 use,
3290 register,
3291 registerGenericStore,
3292 registerStore,
3293 __unstableMarkListeningStores
3294 }; //
3295 // TODO:
3296 // This function will be deprecated as soon as it is no longer internally referenced.
3297
3298 function use(plugin, options) {
3299 if (!plugin) {
3300 return;
3301 }
3302
3303 registry = { ...registry,
3304 ...plugin(registry, options)
3305 };
3306 return registry;
3307 }
3308
3309 registry.register(store);
3310
3311 for (const [name, config] of Object.entries(storeConfigs)) {
3312 registry.register(createReduxStore(name, config));
3313 }
3314
3315 if (parent) {
3316 parent.subscribe(globalListener);
3317 }
3318
3319 const registryWithPlugins = withPlugins(registry);
3320 lock(registryWithPlugins, {
3321 privateActionsOf: name => {
3322 try {
3323 return unlock(stores[name].store).privateActions;
3324 } catch (e) {
3325 // unlock() throws an error the store was not locked – this means
3326 // there no private actions are available
3327 return {};
3328 }
3329 },
3330 privateSelectorsOf: name => {
3331 try {
3332 return unlock(stores[name].store).privateSelectors;
3333 } catch (e) {
3334 return {};
3335 }
3336 }
3337 });
3338 return registryWithPlugins;
3339 }
3340
3341 ;// CONCATENATED MODULE: ./packages/data/build-module/default-registry.js
3342 /**
3343 * Internal dependencies
3344 */
3345
3346 /* harmony default export */ var default_registry = (createRegistry());
3347
3348 ;// CONCATENATED MODULE: ./node_modules/is-plain-object/dist/is-plain-object.mjs
3349 /*!
3350 * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
3351 *
3352 * Copyright (c) 2014-2017, Jon Schlinkert.
3353 * Released under the MIT License.
3354 */
3355
3356 function is_plain_object_isObject(o) {
3357 return Object.prototype.toString.call(o) === '[object Object]';
3358 }
3359
3360 function is_plain_object_isPlainObject(o) {
3361 var ctor,prot;
3362
3363 if (is_plain_object_isObject(o) === false) return false;
3364
3365 // If has modified constructor
3366 ctor = o.constructor;
3367 if (ctor === undefined) return true;
3368
3369 // If has modified prototype
3370 prot = ctor.prototype;
3371 if (is_plain_object_isObject(prot) === false) return false;
3372
3373 // If constructor does not have an Object-specific method
3374 if (prot.hasOwnProperty('isPrototypeOf') === false) {
3375 return false;
3376 }
3377
3378 // Most likely a plain Object
3379 return true;
3380 }
3381
3382
3383
3384 // EXTERNAL MODULE: ./packages/data/node_modules/deepmerge/dist/cjs.js
3385 var cjs = __webpack_require__(1879);
3386 var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);
3387 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/object.js
3388 let objectStorage;
3389 const storage = {
3390 getItem(key) {
3391 if (!objectStorage || !objectStorage[key]) {
3392 return null;
3393 }
3394
3395 return objectStorage[key];
3396 },
3397
3398 setItem(key, value) {
3399 if (!objectStorage) {
3400 storage.clear();
3401 }
3402
3403 objectStorage[key] = String(value);
3404 },
3405
3406 clear() {
3407 objectStorage = Object.create(null);
3408 }
3409
3410 };
3411 /* harmony default export */ var object = (storage);
3412
3413 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/default.js
3414 /**
3415 * Internal dependencies
3416 */
3417
3418 let default_storage;
3419
3420 try {
3421 // Private Browsing in Safari 10 and earlier will throw an error when
3422 // attempting to set into localStorage. The test here is intentional in
3423 // causing a thrown error as condition for using fallback object storage.
3424 default_storage = window.localStorage;
3425 default_storage.setItem('__wpDataTestLocalStorage', '');
3426 default_storage.removeItem('__wpDataTestLocalStorage');
3427 } catch (error) {
3428 default_storage = object;
3429 }
3430
3431 /* harmony default export */ var storage_default = (default_storage);
3432
3433 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/index.js
3434 /**
3435 * External dependencies
3436 */
3437
3438
3439 /**
3440 * Internal dependencies
3441 */
3442
3443
3444
3445 /** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
3446
3447 /** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
3448
3449 /**
3450 * @typedef {Object} WPDataPersistencePluginOptions Persistence plugin options.
3451 *
3452 * @property {Storage} storage Persistent storage implementation. This must
3453 * at least implement `getItem` and `setItem` of
3454 * the Web Storage API.
3455 * @property {string} storageKey Key on which to set in persistent storage.
3456 *
3457 */
3458
3459 /**
3460 * Default plugin storage.
3461 *
3462 * @type {Storage}
3463 */
3464
3465 const DEFAULT_STORAGE = storage_default;
3466 /**
3467 * Default plugin storage key.
3468 *
3469 * @type {string}
3470 */
3471
3472 const DEFAULT_STORAGE_KEY = 'WP_DATA';
3473 /**
3474 * Higher-order reducer which invokes the original reducer only if state is
3475 * inequal from that of the action's `nextState` property, otherwise returning
3476 * the original state reference.
3477 *
3478 * @param {Function} reducer Original reducer.
3479 *
3480 * @return {Function} Enhanced reducer.
3481 */
3482
3483 const withLazySameState = reducer => (state, action) => {
3484 if (action.nextState === state) {
3485 return state;
3486 }
3487
3488 return reducer(state, action);
3489 };
3490 /**
3491 * Creates a persistence interface, exposing getter and setter methods (`get`
3492 * and `set` respectively).
3493 *
3494 * @param {WPDataPersistencePluginOptions} options Plugin options.
3495 *
3496 * @return {Object} Persistence interface.
3497 */
3498
3499 function createPersistenceInterface(options) {
3500 const {
3501 storage = DEFAULT_STORAGE,
3502 storageKey = DEFAULT_STORAGE_KEY
3503 } = options;
3504 let data;
3505 /**
3506 * Returns the persisted data as an object, defaulting to an empty object.
3507 *
3508 * @return {Object} Persisted data.
3509 */
3510
3511 function getData() {
3512 if (data === undefined) {
3513 // If unset, getItem is expected to return null. Fall back to
3514 // empty object.
3515 const persisted = storage.getItem(storageKey);
3516
3517 if (persisted === null) {
3518 data = {};
3519 } else {
3520 try {
3521 data = JSON.parse(persisted);
3522 } catch (error) {
3523 // Similarly, should any error be thrown during parse of
3524 // the string (malformed JSON), fall back to empty object.
3525 data = {};
3526 }
3527 }
3528 }
3529
3530 return data;
3531 }
3532 /**
3533 * Merges an updated reducer state into the persisted data.
3534 *
3535 * @param {string} key Key to update.
3536 * @param {*} value Updated value.
3537 */
3538
3539
3540 function setData(key, value) {
3541 data = { ...data,
3542 [key]: value
3543 };
3544 storage.setItem(storageKey, JSON.stringify(data));
3545 }
3546
3547 return {
3548 get: getData,
3549 set: setData
3550 };
3551 }
3552 /**
3553 * Data plugin to persist store state into a single storage key.
3554 *
3555 * @param {WPDataRegistry} registry Data registry.
3556 * @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
3557 *
3558 * @return {WPDataPlugin} Data plugin.
3559 */
3560
3561 function persistencePlugin(registry, pluginOptions) {
3562 const persistence = createPersistenceInterface(pluginOptions);
3563 /**
3564 * Creates an enhanced store dispatch function, triggering the state of the
3565 * given store name to be persisted when changed.
3566 *
3567 * @param {Function} getState Function which returns current state.
3568 * @param {string} storeName Store name.
3569 * @param {?Array<string>} keys Optional subset of keys to save.
3570 *
3571 * @return {Function} Enhanced dispatch function.
3572 */
3573
3574 function createPersistOnChange(getState, storeName, keys) {
3575 let getPersistedState;
3576
3577 if (Array.isArray(keys)) {
3578 // Given keys, the persisted state should by produced as an object
3579 // of the subset of keys. This implementation uses combineReducers
3580 // to leverage its behavior of returning the same object when none
3581 // of the property values changes. This allows a strict reference
3582 // equality to bypass a persistence set on an unchanging state.
3583 const reducers = keys.reduce((accumulator, key) => Object.assign(accumulator, {
3584 [key]: (state, action) => action.nextState[key]
3585 }), {});
3586 getPersistedState = withLazySameState(build_module_combineReducers(reducers));
3587 } else {
3588 getPersistedState = (state, action) => action.nextState;
3589 }
3590
3591 let lastState = getPersistedState(undefined, {
3592 nextState: getState()
3593 });
3594 return () => {
3595 const state = getPersistedState(lastState, {
3596 nextState: getState()
3597 });
3598
3599 if (state !== lastState) {
3600 persistence.set(storeName, state);
3601 lastState = state;
3602 }
3603 };
3604 }
3605
3606 return {
3607 registerStore(storeName, options) {
3608 if (!options.persist) {
3609 return registry.registerStore(storeName, options);
3610 } // Load from persistence to use as initial state.
3611
3612
3613 const persistedState = persistence.get()[storeName];
3614
3615 if (persistedState !== undefined) {
3616 let initialState = options.reducer(options.initialState, {
3617 type: '@@WP/PERSISTENCE_RESTORE'
3618 });
3619
3620 if (is_plain_object_isPlainObject(initialState) && is_plain_object_isPlainObject(persistedState)) {
3621 // If state is an object, ensure that:
3622 // - Other keys are left intact when persisting only a
3623 // subset of keys.
3624 // - New keys in what would otherwise be used as initial
3625 // state are deeply merged as base for persisted value.
3626 initialState = cjs_default()(initialState, persistedState, {
3627 isMergeableObject: is_plain_object_isPlainObject
3628 });
3629 } else {
3630 // If there is a mismatch in object-likeness of default
3631 // initial or persisted state, defer to persisted value.
3632 initialState = persistedState;
3633 }
3634
3635 options = { ...options,
3636 initialState
3637 };
3638 }
3639
3640 const store = registry.registerStore(storeName, options);
3641 store.subscribe(createPersistOnChange(store.getState, storeName, options.persist));
3642 return store;
3643 }
3644
3645 };
3646 }
3647
3648 persistencePlugin.__unstableMigrate = () => {};
3649
3650 /* harmony default export */ var persistence = (persistencePlugin);
3651
3652 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/index.js
3653
3654
3655 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
3656 function _extends() {
3657 _extends = Object.assign || function (target) {
3658 for (var i = 1; i < arguments.length; i++) {
3659 var source = arguments[i];
3660
3661 for (var key in source) {
3662 if (Object.prototype.hasOwnProperty.call(source, key)) {
3663 target[key] = source[key];
3664 }
3665 }
3666 }
3667
3668 return target;
3669 };
3670
3671 return _extends.apply(this, arguments);
3672 }
3673 ;// CONCATENATED MODULE: external ["wp","element"]
3674 var external_wp_element_namespaceObject = window["wp"]["element"];
3675 ;// CONCATENATED MODULE: external ["wp","priorityQueue"]
3676 var external_wp_priorityQueue_namespaceObject = window["wp"]["priorityQueue"];
3677 ;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
3678 var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
3679 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
3680 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/context.js
3681 /**
3682 * WordPress dependencies
3683 */
3684
3685 /**
3686 * Internal dependencies
3687 */
3688
3689
3690 const Context = (0,external_wp_element_namespaceObject.createContext)(default_registry);
3691 const {
3692 Consumer,
3693 Provider
3694 } = Context;
3695 /**
3696 * A custom react Context consumer exposing the provided `registry` to
3697 * children components. Used along with the RegistryProvider.
3698 *
3699 * You can read more about the react context api here:
3700 * https://reactjs.org/docs/context.html#contextprovider
3701 *
3702 * @example
3703 * ```js
3704 * import {
3705 * RegistryProvider,
3706 * RegistryConsumer,
3707 * createRegistry
3708 * } from '@wordpress/data';
3709 *
3710 * const registry = createRegistry( {} );
3711 *
3712 * const App = ( { props } ) => {
3713 * return <RegistryProvider value={ registry }>
3714 * <div>Hello There</div>
3715 * <RegistryConsumer>
3716 * { ( registry ) => (
3717 * <ComponentUsingRegistry
3718 * { ...props }
3719 * registry={ registry }
3720 * ) }
3721 * </RegistryConsumer>
3722 * </RegistryProvider>
3723 * }
3724 * ```
3725 */
3726
3727 const RegistryConsumer = Consumer;
3728 /**
3729 * A custom Context provider for exposing the provided `registry` to children
3730 * components via a consumer.
3731 *
3732 * See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
3733 * example.
3734 */
3735
3736 /* harmony default export */ var context = (Provider);
3737
3738 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/use-registry.js
3739 /**
3740 * WordPress dependencies
3741 */
3742
3743 /**
3744 * Internal dependencies
3745 */
3746
3747
3748 /**
3749 * A custom react hook exposing the registry context for use.
3750 *
3751 * This exposes the `registry` value provided via the
3752 * <a href="#RegistryProvider">Registry Provider</a> to a component implementing
3753 * this hook.
3754 *
3755 * It acts similarly to the `useContext` react hook.
3756 *
3757 * Note: Generally speaking, `useRegistry` is a low level hook that in most cases
3758 * won't be needed for implementation. Most interactions with the `@wordpress/data`
3759 * API can be performed via the `useSelect` hook, or the `withSelect` and
3760 * `withDispatch` higher order components.
3761 *
3762 * @example
3763 * ```js
3764 * import {
3765 * RegistryProvider,
3766 * createRegistry,
3767 * useRegistry,
3768 * } from '@wordpress/data';
3769 *
3770 * const registry = createRegistry( {} );
3771 *
3772 * const SomeChildUsingRegistry = ( props ) => {
3773 * const registry = useRegistry();
3774 * // ...logic implementing the registry in other react hooks.
3775 * };
3776 *
3777 *
3778 * const ParentProvidingRegistry = ( props ) => {
3779 * return <RegistryProvider value={ registry }>
3780 * <SomeChildUsingRegistry { ...props } />
3781 * </RegistryProvider>
3782 * };
3783 * ```
3784 *
3785 * @return {Function} A custom react hook exposing the registry context value.
3786 */
3787
3788 function useRegistry() {
3789 return (0,external_wp_element_namespaceObject.useContext)(Context);
3790 }
3791
3792 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/context.js
3793 /**
3794 * WordPress dependencies
3795 */
3796
3797 const context_Context = (0,external_wp_element_namespaceObject.createContext)(false);
3798 const {
3799 Consumer: context_Consumer,
3800 Provider: context_Provider
3801 } = context_Context;
3802 const AsyncModeConsumer = (/* unused pure expression or super */ null && (context_Consumer));
3803 /**
3804 * Context Provider Component used to switch the data module component rerendering
3805 * between Sync and Async modes.
3806 *
3807 * @example
3808 *
3809 * ```js
3810 * import { useSelect, AsyncModeProvider } from '@wordpress/data';
3811 * import { store as blockEditorStore } from '@wordpress/block-editor';
3812 *
3813 * function BlockCount() {
3814 * const count = useSelect( ( select ) => {
3815 * return select( blockEditorStore ).getBlockCount()
3816 * }, [] );
3817 *
3818 * return count;
3819 * }
3820 *
3821 * function App() {
3822 * return (
3823 * <AsyncModeProvider value={ true }>
3824 * <BlockCount />
3825 * </AsyncModeProvider>
3826 * );
3827 * }
3828 * ```
3829 *
3830 * In this example, the BlockCount component is rerendered asynchronously.
3831 * It means if a more critical task is being performed (like typing in an input),
3832 * the rerendering is delayed until the browser becomes IDLE.
3833 * It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.
3834 *
3835 * @param {boolean} props.value Enable Async Mode.
3836 * @return {WPComponent} The component to be rendered.
3837 */
3838
3839 /* harmony default export */ var async_mode_provider_context = (context_Provider);
3840
3841 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/use-async-mode.js
3842 /**
3843 * WordPress dependencies
3844 */
3845
3846 /**
3847 * Internal dependencies
3848 */
3849
3850
3851 function useAsyncMode() {
3852 return (0,external_wp_element_namespaceObject.useContext)(context_Context);
3853 }
3854
3855 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-select/index.js
3856 /**
3857 * WordPress dependencies
3858 */
3859
3860
3861
3862 /**
3863 * Internal dependencies
3864 */
3865
3866
3867
3868 const renderQueue = (0,external_wp_priorityQueue_namespaceObject.createQueue)();
3869 /**
3870 * @typedef {import('../../types').StoreDescriptor<C>} StoreDescriptor
3871 * @template {import('../../types').AnyConfig} C
3872 */
3873
3874 /**
3875 * @typedef {import('../../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
3876 * @template State
3877 * @template {Record<string,import('../../types').ActionCreator>} Actions
3878 * @template Selectors
3879 */
3880
3881 /** @typedef {import('../../types').MapSelect} MapSelect */
3882
3883 /**
3884 * @typedef {import('../../types').UseSelectReturn<T>} UseSelectReturn
3885 * @template {MapSelect|StoreDescriptor<any>} T
3886 */
3887
3888 function Store(registry, suspense) {
3889 const select = suspense ? registry.suspendSelect : registry.select;
3890 const queueContext = {};
3891 let lastMapSelect;
3892 let lastMapResult;
3893 let lastMapResultValid = false;
3894 let lastIsAsync;
3895 let subscriber;
3896
3897 const createSubscriber = stores => {
3898 // The set of stores the `subscribe` function is supposed to subscribe to. Here it is
3899 // initialized, and then the `updateStores` function can add new stores to it.
3900 const activeStores = [...stores]; // The `subscribe` function, which is passed to the `useSyncExternalStore` hook, could
3901 // be called multiple times to establish multiple subscriptions. That's why we need to
3902 // keep a set of active subscriptions;
3903
3904 const activeSubscriptions = new Set();
3905
3906 function subscribe(listener) {
3907 // Invalidate the value right after subscription was created. React will
3908 // call `getValue` after subscribing, to detect store updates that happened
3909 // in the interval between the `getValue` call during render and creating
3910 // the subscription, which is slightly delayed. We need to ensure that this
3911 // second `getValue` call will compute a fresh value.
3912 lastMapResultValid = false;
3913
3914 const onStoreChange = () => {
3915 // Invalidate the value on store update, so that a fresh value is computed.
3916 lastMapResultValid = false;
3917 listener();
3918 };
3919
3920 const onChange = () => {
3921 if (lastIsAsync) {
3922 renderQueue.add(queueContext, onStoreChange);
3923 } else {
3924 onStoreChange();
3925 }
3926 };
3927
3928 const unsubs = [];
3929
3930 function subscribeStore(storeName) {
3931 unsubs.push(registry.subscribe(onChange, storeName));
3932 }
3933
3934 for (const storeName of activeStores) {
3935 subscribeStore(storeName);
3936 }
3937
3938 activeSubscriptions.add(subscribeStore);
3939 return () => {
3940 activeSubscriptions.delete(subscribeStore);
3941
3942 for (const unsub of unsubs.values()) {
3943 // The return value of the subscribe function could be undefined if the store is a custom generic store.
3944 unsub === null || unsub === void 0 ? void 0 : unsub();
3945 } // Cancel existing store updates that were already scheduled.
3946
3947
3948 renderQueue.cancel(queueContext);
3949 };
3950 } // Check if `newStores` contains some stores we're not subscribed to yet, and add them.
3951
3952
3953 function updateStores(newStores) {
3954 for (const newStore of newStores) {
3955 if (activeStores.includes(newStore)) {
3956 continue;
3957 } // New `subscribe` calls will subscribe to `newStore`, too.
3958
3959
3960 activeStores.push(newStore); // Add `newStore` to existing subscriptions.
3961
3962 for (const subscription of activeSubscriptions) {
3963 subscription(newStore);
3964 }
3965 }
3966 }
3967
3968 return {
3969 subscribe,
3970 updateStores
3971 };
3972 };
3973
3974 return (mapSelect, isAsync) => {
3975 function updateValue() {
3976 // If the last value is valid, and the `mapSelect` callback hasn't changed,
3977 // then we can safely return the cached value. The value can change only on
3978 // store update, and in that case value will be invalidated by the listener.
3979 if (lastMapResultValid && mapSelect === lastMapSelect) {
3980 return lastMapResult;
3981 }
3982
3983 const listeningStores = {
3984 current: null
3985 };
3986
3987 const mapResult = registry.__unstableMarkListeningStores(() => mapSelect(select, registry), listeningStores);
3988
3989 if (!subscriber) {
3990 subscriber = createSubscriber(listeningStores.current);
3991 } else {
3992 subscriber.updateStores(listeningStores.current);
3993 } // If the new value is shallow-equal to the old one, keep the old one so
3994 // that we don't trigger unwanted updates that do a `===` check.
3995
3996
3997 if (!external_wp_isShallowEqual_default()(lastMapResult, mapResult)) {
3998 lastMapResult = mapResult;
3999 }
4000
4001 lastMapSelect = mapSelect;
4002 lastMapResultValid = true;
4003 }
4004
4005 function getValue() {
4006 // Update the value in case it's been invalidated or `mapSelect` has changed.
4007 updateValue();
4008 return lastMapResult;
4009 } // When transitioning from async to sync mode, cancel existing store updates
4010 // that have been scheduled, and invalidate the value so that it's freshly
4011 // computed. It might have been changed by the update we just cancelled.
4012
4013
4014 if (lastIsAsync && !isAsync) {
4015 lastMapResultValid = false;
4016 renderQueue.cancel(queueContext);
4017 }
4018
4019 updateValue();
4020 lastIsAsync = isAsync; // Return a pair of functions that can be passed to `useSyncExternalStore`.
4021
4022 return {
4023 subscribe: subscriber.subscribe,
4024 getValue
4025 };
4026 };
4027 }
4028
4029 function useStaticSelect(storeName) {
4030 return useRegistry().select(storeName);
4031 }
4032
4033 function useMappingSelect(suspense, mapSelect, deps) {
4034 const registry = useRegistry();
4035 const isAsync = useAsyncMode();
4036 const store = (0,external_wp_element_namespaceObject.useMemo)(() => Store(registry, suspense), [registry]);
4037 const selector = (0,external_wp_element_namespaceObject.useCallback)(mapSelect, deps);
4038 const {
4039 subscribe,
4040 getValue
4041 } = store(selector, isAsync);
4042 const result = (0,external_wp_element_namespaceObject.useSyncExternalStore)(subscribe, getValue, getValue);
4043 (0,external_wp_element_namespaceObject.useDebugValue)(result);
4044 return result;
4045 }
4046 /**
4047 * Custom react hook for retrieving props from registered selectors.
4048 *
4049 * In general, this custom React hook follows the
4050 * [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
4051 *
4052 * @template {MapSelect | StoreDescriptor<any>} T
4053 * @param {T} mapSelect Function called on every state change. The returned value is
4054 * exposed to the component implementing this hook. The function
4055 * receives the `registry.select` method on the first argument
4056 * and the `registry` on the second argument.
4057 * When a store key is passed, all selectors for the store will be
4058 * returned. This is only meant for usage of these selectors in event
4059 * callbacks, not for data needed to create the element tree.
4060 * @param {unknown[]} deps If provided, this memoizes the mapSelect so the same `mapSelect` is
4061 * invoked on every state change unless the dependencies change.
4062 *
4063 * @example
4064 * ```js
4065 * import { useSelect } from '@wordpress/data';
4066 * import { store as myCustomStore } from 'my-custom-store';
4067 *
4068 * function HammerPriceDisplay( { currency } ) {
4069 * const price = useSelect( ( select ) => {
4070 * return select( myCustomStore ).getPrice( 'hammer', currency );
4071 * }, [ currency ] );
4072 * return new Intl.NumberFormat( 'en-US', {
4073 * style: 'currency',
4074 * currency,
4075 * } ).format( price );
4076 * }
4077 *
4078 * // Rendered in the application:
4079 * // <HammerPriceDisplay currency="USD" />
4080 * ```
4081 *
4082 * In the above example, when `HammerPriceDisplay` is rendered into an
4083 * application, the price will be retrieved from the store state using the
4084 * `mapSelect` callback on `useSelect`. If the currency prop changes then
4085 * any price in the state for that currency is retrieved. If the currency prop
4086 * doesn't change and other props are passed in that do change, the price will
4087 * not change because the dependency is just the currency.
4088 *
4089 * When data is only used in an event callback, the data should not be retrieved
4090 * on render, so it may be useful to get the selectors function instead.
4091 *
4092 * **Don't use `useSelect` this way when calling the selectors in the render
4093 * function because your component won't re-render on a data change.**
4094 *
4095 * ```js
4096 * import { useSelect } from '@wordpress/data';
4097 * import { store as myCustomStore } from 'my-custom-store';
4098 *
4099 * function Paste( { children } ) {
4100 * const { getSettings } = useSelect( myCustomStore );
4101 * function onPaste() {
4102 * // Do something with the settings.
4103 * const settings = getSettings();
4104 * }
4105 * return <div onPaste={ onPaste }>{ children }</div>;
4106 * }
4107 * ```
4108 * @return {UseSelectReturn<T>} A custom react hook.
4109 */
4110
4111
4112 function useSelect(mapSelect, deps) {
4113 // On initial call, on mount, determine the mode of this `useSelect` call
4114 // and then never allow it to change on subsequent updates.
4115 const staticSelectMode = typeof mapSelect !== 'function';
4116 const staticSelectModeRef = (0,external_wp_element_namespaceObject.useRef)(staticSelectMode);
4117
4118 if (staticSelectMode !== staticSelectModeRef.current) {
4119 const prevMode = staticSelectModeRef.current ? 'static' : 'mapping';
4120 const nextMode = staticSelectMode ? 'static' : 'mapping';
4121 throw new Error(`Switching useSelect from ${prevMode} to ${nextMode} is not allowed`);
4122 }
4123 /* eslint-disable react-hooks/rules-of-hooks */
4124 // `staticSelectMode` is not allowed to change during the hook instance's,
4125 // lifetime, so the rules of hooks are not really violated.
4126
4127
4128 return staticSelectMode ? useStaticSelect(mapSelect) : useMappingSelect(false, mapSelect, deps);
4129 /* eslint-enable react-hooks/rules-of-hooks */
4130 }
4131 /**
4132 * A variant of the `useSelect` hook that has the same API, but will throw a
4133 * suspense Promise if any of the called selectors is in an unresolved state.
4134 *
4135 * @param {Function} mapSelect Function called on every state change. The
4136 * returned value is exposed to the component
4137 * using this hook. The function receives the
4138 * `registry.suspendSelect` method as the first
4139 * argument and the `registry` as the second one.
4140 * @param {Array} deps A dependency array used to memoize the `mapSelect`
4141 * so that the same `mapSelect` is invoked on every
4142 * state change unless the dependencies change.
4143 *
4144 * @return {Object} Data object returned by the `mapSelect` function.
4145 */
4146
4147 function useSuspenseSelect(mapSelect, deps) {
4148 return useMappingSelect(true, mapSelect, deps);
4149 }
4150
4151 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-select/index.js
4152
4153
4154
4155 /**
4156 * WordPress dependencies
4157 */
4158
4159 /**
4160 * Internal dependencies
4161 */
4162
4163
4164 /** @typedef {import('@wordpress/element').WPComponent} WPComponent */
4165
4166 /**
4167 * Higher-order component used to inject state-derived props using registered
4168 * selectors.
4169 *
4170 * @param {Function} mapSelectToProps Function called on every state change,
4171 * expected to return object of props to
4172 * merge with the component's own props.
4173 *
4174 * @example
4175 * ```js
4176 * import { withSelect } from '@wordpress/data';
4177 * import { store as myCustomStore } from 'my-custom-store';
4178 *
4179 * function PriceDisplay( { price, currency } ) {
4180 * return new Intl.NumberFormat( 'en-US', {
4181 * style: 'currency',
4182 * currency,
4183 * } ).format( price );
4184 * }
4185 *
4186 * const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
4187 * const { getPrice } = select( myCustomStore );
4188 * const { currency } = ownProps;
4189 *
4190 * return {
4191 * price: getPrice( 'hammer', currency ),
4192 * };
4193 * } )( PriceDisplay );
4194 *
4195 * // Rendered in the application:
4196 * //
4197 * // <HammerPriceDisplay currency="USD" />
4198 * ```
4199 * In the above example, when `HammerPriceDisplay` is rendered into an
4200 * application, it will pass the price into the underlying `PriceDisplay`
4201 * component and update automatically if the price of a hammer ever changes in
4202 * the store.
4203 *
4204 * @return {WPComponent} Enhanced component with merged state data props.
4205 */
4206
4207 const withSelect = mapSelectToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => (0,external_wp_compose_namespaceObject.pure)(ownProps => {
4208 const mapSelect = (select, registry) => mapSelectToProps(select, ownProps, registry);
4209
4210 const mergeProps = useSelect(mapSelect);
4211 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, mergeProps));
4212 }), 'withSelect');
4213
4214 /* harmony default export */ var with_select = (withSelect);
4215
4216 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch-with-map.js
4217 /**
4218 * WordPress dependencies
4219 */
4220
4221
4222 /**
4223 * Internal dependencies
4224 */
4225
4226
4227 /**
4228 * Custom react hook for returning aggregate dispatch actions using the provided
4229 * dispatchMap.
4230 *
4231 * Currently this is an internal api only and is implemented by `withDispatch`
4232 *
4233 * @param {Function} dispatchMap Receives the `registry.dispatch` function as
4234 * the first argument and the `registry` object
4235 * as the second argument. Should return an
4236 * object mapping props to functions.
4237 * @param {Array} deps An array of dependencies for the hook.
4238 * @return {Object} An object mapping props to functions created by the passed
4239 * in dispatchMap.
4240 */
4241
4242 const useDispatchWithMap = (dispatchMap, deps) => {
4243 const registry = useRegistry();
4244 const currentDispatchMap = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
4245 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
4246 currentDispatchMap.current = dispatchMap;
4247 });
4248 return (0,external_wp_element_namespaceObject.useMemo)(() => {
4249 const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
4250 return Object.fromEntries(Object.entries(currentDispatchProps).map(_ref => {
4251 let [propName, dispatcher] = _ref;
4252
4253 if (typeof dispatcher !== 'function') {
4254 // eslint-disable-next-line no-console
4255 console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
4256 }
4257
4258 return [propName, function () {
4259 return currentDispatchMap.current(registry.dispatch, registry)[propName](...arguments);
4260 }];
4261 }));
4262 }, [registry, ...deps]);
4263 };
4264
4265 /* harmony default export */ var use_dispatch_with_map = (useDispatchWithMap);
4266
4267 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-dispatch/index.js
4268
4269
4270
4271 /**
4272 * WordPress dependencies
4273 */
4274
4275 /**
4276 * Internal dependencies
4277 */
4278
4279
4280 /** @typedef {import('@wordpress/element').WPComponent} WPComponent */
4281
4282 /**
4283 * Higher-order component used to add dispatch props using registered action
4284 * creators.
4285 *
4286 * @param {Function} mapDispatchToProps A function of returning an object of
4287 * prop names where value is a
4288 * dispatch-bound action creator, or a
4289 * function to be called with the
4290 * component's props and returning an
4291 * action creator.
4292 *
4293 * @example
4294 * ```jsx
4295 * function Button( { onClick, children } ) {
4296 * return <button type="button" onClick={ onClick }>{ children }</button>;
4297 * }
4298 *
4299 * import { withDispatch } from '@wordpress/data';
4300 * import { store as myCustomStore } from 'my-custom-store';
4301 *
4302 * const SaleButton = withDispatch( ( dispatch, ownProps ) => {
4303 * const { startSale } = dispatch( myCustomStore );
4304 * const { discountPercent } = ownProps;
4305 *
4306 * return {
4307 * onClick() {
4308 * startSale( discountPercent );
4309 * },
4310 * };
4311 * } )( Button );
4312 *
4313 * // Rendered in the application:
4314 * //
4315 * // <SaleButton discountPercent="20">Start Sale!</SaleButton>
4316 * ```
4317 *
4318 * @example
4319 * In the majority of cases, it will be sufficient to use only two first params
4320 * passed to `mapDispatchToProps` as illustrated in the previous example.
4321 * However, there might be some very advanced use cases where using the
4322 * `registry` object might be used as a tool to optimize the performance of
4323 * your component. Using `select` function from the registry might be useful
4324 * when you need to fetch some dynamic data from the store at the time when the
4325 * event is fired, but at the same time, you never use it to render your
4326 * component. In such scenario, you can avoid using the `withSelect` higher
4327 * order component to compute such prop, which might lead to unnecessary
4328 * re-renders of your component caused by its frequent value change.
4329 * Keep in mind, that `mapDispatchToProps` must return an object with functions
4330 * only.
4331 *
4332 * ```jsx
4333 * function Button( { onClick, children } ) {
4334 * return <button type="button" onClick={ onClick }>{ children }</button>;
4335 * }
4336 *
4337 * import { withDispatch } from '@wordpress/data';
4338 * import { store as myCustomStore } from 'my-custom-store';
4339 *
4340 * const SaleButton = withDispatch( ( dispatch, ownProps, { select } ) => {
4341 * // Stock number changes frequently.
4342 * const { getStockNumber } = select( myCustomStore );
4343 * const { startSale } = dispatch( myCustomStore );
4344 * return {
4345 * onClick() {
4346 * const discountPercent = getStockNumber() > 50 ? 10 : 20;
4347 * startSale( discountPercent );
4348 * },
4349 * };
4350 * } )( Button );
4351 *
4352 * // Rendered in the application:
4353 * //
4354 * // <SaleButton>Start Sale!</SaleButton>
4355 * ```
4356 *
4357 * _Note:_ It is important that the `mapDispatchToProps` function always
4358 * returns an object with the same keys. For example, it should not contain
4359 * conditions under which a different value would be returned.
4360 *
4361 * @return {WPComponent} Enhanced component with merged dispatcher props.
4362 */
4363
4364 const withDispatch = mapDispatchToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => ownProps => {
4365 const mapDispatch = (dispatch, registry) => mapDispatchToProps(dispatch, ownProps, registry);
4366
4367 const dispatchProps = use_dispatch_with_map(mapDispatch, []);
4368 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, dispatchProps));
4369 }, 'withDispatch');
4370
4371 /* harmony default export */ var with_dispatch = (withDispatch);
4372
4373 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-registry/index.js
4374
4375
4376
4377 /**
4378 * WordPress dependencies
4379 */
4380
4381 /**
4382 * Internal dependencies
4383 */
4384
4385
4386 /**
4387 * Higher-order component which renders the original component with the current
4388 * registry context passed as its `registry` prop.
4389 *
4390 * @param {WPComponent} OriginalComponent Original component.
4391 *
4392 * @return {WPComponent} Enhanced component.
4393 */
4394
4395 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, {
4396 registry: registry
4397 }))), 'withRegistry');
4398 /* harmony default export */ var with_registry = (withRegistry);
4399
4400 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch.js
4401 /**
4402 * Internal dependencies
4403 */
4404
4405 /**
4406 * @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor
4407 * @template {import('../../types').AnyConfig} StoreConfig
4408 */
4409
4410 /**
4411 * @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn
4412 * @template StoreNameOrDescriptor
4413 */
4414
4415 /**
4416 * A custom react hook returning the current registry dispatch actions creators.
4417 *
4418 * Note: The component using this hook must be within the context of a
4419 * RegistryProvider.
4420 *
4421 * @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor
4422 * @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
4423 * store or its descriptor from which to
4424 * retrieve action creators. If not
4425 * provided, the registry.dispatch
4426 * function is returned instead.
4427 *
4428 * @example
4429 * This illustrates a pattern where you may need to retrieve dynamic data from
4430 * the server via the `useSelect` hook to use in combination with the dispatch
4431 * action.
4432 *
4433 * ```jsx
4434 * import { useDispatch, useSelect } from '@wordpress/data';
4435 * import { useCallback } from '@wordpress/element';
4436 * import { store as myCustomStore } from 'my-custom-store';
4437 *
4438 * function Button( { onClick, children } ) {
4439 * return <button type="button" onClick={ onClick }>{ children }</button>
4440 * }
4441 *
4442 * const SaleButton = ( { children } ) => {
4443 * const { stockNumber } = useSelect(
4444 * ( select ) => select( myCustomStore ).getStockNumber(),
4445 * []
4446 * );
4447 * const { startSale } = useDispatch( myCustomStore );
4448 * const onClick = useCallback( () => {
4449 * const discountPercent = stockNumber > 50 ? 10: 20;
4450 * startSale( discountPercent );
4451 * }, [ stockNumber ] );
4452 * return <Button onClick={ onClick }>{ children }</Button>
4453 * }
4454 *
4455 * // Rendered somewhere in the application:
4456 * //
4457 * // <SaleButton>Start Sale!</SaleButton>
4458 * ```
4459 * @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.
4460 */
4461
4462 const useDispatch = storeNameOrDescriptor => {
4463 const {
4464 dispatch
4465 } = useRegistry();
4466 return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor);
4467 };
4468
4469 /* harmony default export */ var use_dispatch = (useDispatch);
4470
4471 ;// CONCATENATED MODULE: ./packages/data/build-module/index.js
4472 /**
4473 * External dependencies
4474 */
4475
4476 /**
4477 * Internal dependencies
4478 */
4479
4480
4481
4482 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495 /**
4496 * Object of available plugins to use with a registry.
4497 *
4498 * @see [use](#use)
4499 *
4500 * @type {Object}
4501 */
4502
4503
4504 /**
4505 * The combineReducers helper function turns an object whose values are different
4506 * reducing functions into a single reducing function you can pass to registerReducer.
4507 *
4508 * @type {import('./types').combineReducers}
4509 * @param {Object} reducers An object whose values correspond to different reducing
4510 * functions that need to be combined into one.
4511 *
4512 * @example
4513 * ```js
4514 * import { combineReducers, createReduxStore, register } from '@wordpress/data';
4515 *
4516 * const prices = ( state = {}, action ) => {
4517 * return action.type === 'SET_PRICE' ?
4518 * {
4519 * ...state,
4520 * [ action.item ]: action.price,
4521 * } :
4522 * state;
4523 * };
4524 *
4525 * const discountPercent = ( state = 0, action ) => {
4526 * return action.type === 'START_SALE' ?
4527 * action.discountPercent :
4528 * state;
4529 * };
4530 *
4531 * const store = createReduxStore( 'my-shop', {
4532 * reducer: combineReducers( {
4533 * prices,
4534 * discountPercent,
4535 * } ),
4536 * } );
4537 * register( store );
4538 * ```
4539 *
4540 * @return {Function} A reducer that invokes every reducer inside the reducers
4541 * object, and constructs a state object with the same shape.
4542 */
4543
4544 const build_module_combineReducers = (turbo_combine_reducers_default());
4545 /**
4546 * Given a store descriptor, returns an object of the store's selectors.
4547 * The selector functions are been pre-bound to pass the current state automatically.
4548 * As a consumer, you need only pass arguments of the selector, if applicable.
4549 *
4550 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4551 * convention of passing the store name is
4552 * also supported.
4553 *
4554 * @example
4555 * ```js
4556 * import { select } from '@wordpress/data';
4557 * import { store as myCustomStore } from 'my-custom-store';
4558 *
4559 * select( myCustomStore ).getPrice( 'hammer' );
4560 * ```
4561 *
4562 * @return {Object} Object containing the store's selectors.
4563 */
4564
4565 function build_module_select(storeNameOrDescriptor) {
4566 return default_registry.select(storeNameOrDescriptor);
4567 }
4568 /**
4569 * Given a store descriptor, returns an object containing the store's selectors pre-bound to state
4570 * so that you only need to supply additional arguments, and modified so that they return promises
4571 * that resolve to their eventual values, after any resolvers have ran.
4572 *
4573 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4574 * convention of passing the store name is
4575 * also supported.
4576 *
4577 * @example
4578 * ```js
4579 * import { resolveSelect } from '@wordpress/data';
4580 * import { store as myCustomStore } from 'my-custom-store';
4581 *
4582 * resolveSelect( myCustomStore ).getPrice( 'hammer' ).then(console.log)
4583 * ```
4584 *
4585 * @return {Object} Object containing the store's promise-wrapped selectors.
4586 */
4587
4588 const build_module_resolveSelect = default_registry.resolveSelect;
4589 /**
4590 * Given a store descriptor, returns an object containing the store's selectors pre-bound to state
4591 * so that you only need to supply additional arguments, and modified so that they throw promises
4592 * in case the selector is not resolved yet.
4593 *
4594 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4595 * convention of passing the store name is
4596 * also supported.
4597 *
4598 * @return {Object} Object containing the store's suspense-wrapped selectors.
4599 */
4600
4601 const suspendSelect = default_registry.suspendSelect;
4602 /**
4603 * Given a store descriptor, returns an object of the store's action creators.
4604 * Calling an action creator will cause it to be dispatched, updating the state value accordingly.
4605 *
4606 * Note: Action creators returned by the dispatch will return a promise when
4607 * they are called.
4608 *
4609 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4610 * convention of passing the store name is
4611 * also supported.
4612 *
4613 * @example
4614 * ```js
4615 * import { dispatch } from '@wordpress/data';
4616 * import { store as myCustomStore } from 'my-custom-store';
4617 *
4618 * dispatch( myCustomStore ).setPrice( 'hammer', 9.75 );
4619 * ```
4620 * @return {Object} Object containing the action creators.
4621 */
4622
4623 function build_module_dispatch(storeNameOrDescriptor) {
4624 return default_registry.dispatch(storeNameOrDescriptor);
4625 }
4626 /**
4627 * Given a listener function, the function will be called any time the state value
4628 * of one of the registered stores has changed. If you specify the optional
4629 * `storeNameOrDescriptor` parameter, the listener function will be called only
4630 * on updates on that one specific registered store.
4631 *
4632 * This function returns an `unsubscribe` function used to stop the subscription.
4633 *
4634 * @param {Function} listener Callback function.
4635 * @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
4636 *
4637 * @example
4638 * ```js
4639 * import { subscribe } from '@wordpress/data';
4640 *
4641 * const unsubscribe = subscribe( () => {
4642 * // You could use this opportunity to test whether the derived result of a
4643 * // selector has subsequently changed as the result of a state update.
4644 * } );
4645 *
4646 * // Later, if necessary...
4647 * unsubscribe();
4648 * ```
4649 */
4650
4651 const subscribe = default_registry.subscribe;
4652 /**
4653 * Registers a generic store instance.
4654 *
4655 * @deprecated Use `register( storeDescriptor )` instead.
4656 *
4657 * @param {string} name Store registry name.
4658 * @param {Object} store Store instance (`{ getSelectors, getActions, subscribe }`).
4659 */
4660
4661 const registerGenericStore = default_registry.registerGenericStore;
4662 /**
4663 * Registers a standard `@wordpress/data` store.
4664 *
4665 * @deprecated Use `register` instead.
4666 *
4667 * @param {string} storeName Unique namespace identifier for the store.
4668 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
4669 *
4670 * @return {Object} Registered store object.
4671 */
4672
4673 const registerStore = default_registry.registerStore;
4674 /**
4675 * Extends a registry to inherit functionality provided by a given plugin. A
4676 * plugin is an object with properties aligning to that of a registry, merged
4677 * to extend the default registry behavior.
4678 *
4679 * @param {Object} plugin Plugin object.
4680 */
4681
4682 const use = default_registry.use;
4683 /**
4684 * Registers a standard `@wordpress/data` store descriptor.
4685 *
4686 * @example
4687 * ```js
4688 * import { createReduxStore, register } from '@wordpress/data';
4689 *
4690 * const store = createReduxStore( 'demo', {
4691 * reducer: ( state = 'OK' ) => state,
4692 * selectors: {
4693 * getValue: ( state ) => state,
4694 * },
4695 * } );
4696 * register( store );
4697 * ```
4698 *
4699 * @param {StoreDescriptor} store Store descriptor.
4700 */
4701
4702 const register = default_registry.register;
4703
4704 }();
4705 (window.wp = window.wp || {}).data = __webpack_exports__;
4706 /******/ })()
4707 ;