PluginProbe
Gutenberg / 14.7.0
Gutenberg v14.7.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 12.6.0 All 403 releases
gutenberg / build / core-data / index.js

index.js in Gutenberg 14.7.0, at build/core-data/index.js

7,141 lines 214.5 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 /***/ 9756:
320 /***/ (function(module) {
321
322 /**
323 * Memize options object.
324 *
325 * @typedef MemizeOptions
326 *
327 * @property {number} [maxSize] Maximum size of the cache.
328 */
329
330 /**
331 * Internal cache entry.
332 *
333 * @typedef MemizeCacheNode
334 *
335 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
336 * @property {?MemizeCacheNode|undefined} [next] Next node.
337 * @property {Array<*>} args Function arguments for cache
338 * entry.
339 * @property {*} val Function result.
340 */
341
342 /**
343 * Properties of the enhanced function for controlling cache.
344 *
345 * @typedef MemizeMemoizedFunction
346 *
347 * @property {()=>void} clear Clear the cache.
348 */
349
350 /**
351 * Accepts a function to be memoized, and returns a new memoized function, with
352 * optional options.
353 *
354 * @template {Function} F
355 *
356 * @param {F} fn Function to memoize.
357 * @param {MemizeOptions} [options] Options object.
358 *
359 * @return {F & MemizeMemoizedFunction} Memoized function.
360 */
361 function memize( fn, options ) {
362 var size = 0;
363
364 /** @type {?MemizeCacheNode|undefined} */
365 var head;
366
367 /** @type {?MemizeCacheNode|undefined} */
368 var tail;
369
370 options = options || {};
371
372 function memoized( /* ...args */ ) {
373 var node = head,
374 len = arguments.length,
375 args, i;
376
377 searchCache: while ( node ) {
378 // Perform a shallow equality test to confirm that whether the node
379 // under test is a candidate for the arguments passed. Two arrays
380 // are shallowly equal if their length matches and each entry is
381 // strictly equal between the two sets. Avoid abstracting to a
382 // function which could incur an arguments leaking deoptimization.
383
384 // Check whether node arguments match arguments length
385 if ( node.args.length !== arguments.length ) {
386 node = node.next;
387 continue;
388 }
389
390 // Check whether node arguments match arguments values
391 for ( i = 0; i < len; i++ ) {
392 if ( node.args[ i ] !== arguments[ i ] ) {
393 node = node.next;
394 continue searchCache;
395 }
396 }
397
398 // At this point we can assume we've found a match
399
400 // Surface matched node to head if not already
401 if ( node !== head ) {
402 // As tail, shift to previous. Must only shift if not also
403 // head, since if both head and tail, there is no previous.
404 if ( node === tail ) {
405 tail = node.prev;
406 }
407
408 // Adjust siblings to point to each other. If node was tail,
409 // this also handles new tail's empty `next` assignment.
410 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
411 if ( node.next ) {
412 node.next.prev = node.prev;
413 }
414
415 node.next = head;
416 node.prev = null;
417 /** @type {MemizeCacheNode} */ ( head ).prev = node;
418 head = node;
419 }
420
421 // Return immediately
422 return node.val;
423 }
424
425 // No cached value found. Continue to insertion phase:
426
427 // Create a copy of arguments (avoid leaking deoptimization)
428 args = new Array( len );
429 for ( i = 0; i < len; i++ ) {
430 args[ i ] = arguments[ i ];
431 }
432
433 node = {
434 args: args,
435
436 // Generate the result from original function
437 val: fn.apply( null, args ),
438 };
439
440 // Don't need to check whether node is already head, since it would
441 // have been returned above already if it was
442
443 // Shift existing head down list
444 if ( head ) {
445 head.prev = node;
446 node.next = head;
447 } else {
448 // If no head, follows that there's no tail (at initial or reset)
449 tail = node;
450 }
451
452 // Trim tail if we're reached max size and are pending cache insertion
453 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
454 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
455 /** @type {MemizeCacheNode} */ ( tail ).next = null;
456 } else {
457 size++;
458 }
459
460 head = node;
461
462 return node.val;
463 }
464
465 memoized.clear = function() {
466 head = null;
467 tail = null;
468 size = 0;
469 };
470
471 if ( false ) {}
472
473 // Ignore reason: There's not a clear solution to create an intersection of
474 // the function with additional properties, where the goal is to retain the
475 // function signature of the incoming argument and add control properties
476 // on the return value.
477
478 // @ts-ignore
479 return memoized;
480 }
481
482 module.exports = memize;
483
484
485 /***/ })
486
487 /******/ });
488 /************************************************************************/
489 /******/ // The module cache
490 /******/ var __webpack_module_cache__ = {};
491 /******/
492 /******/ // The require function
493 /******/ function __webpack_require__(moduleId) {
494 /******/ // Check if module is in cache
495 /******/ var cachedModule = __webpack_module_cache__[moduleId];
496 /******/ if (cachedModule !== undefined) {
497 /******/ return cachedModule.exports;
498 /******/ }
499 /******/ // Create a new module (and put it into the cache)
500 /******/ var module = __webpack_module_cache__[moduleId] = {
501 /******/ // no module.id needed
502 /******/ // no module.loaded needed
503 /******/ exports: {}
504 /******/ };
505 /******/
506 /******/ // Execute the module function
507 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
508 /******/
509 /******/ // Return the exports of the module
510 /******/ return module.exports;
511 /******/ }
512 /******/
513 /************************************************************************/
514 /******/ /* webpack/runtime/compat get default export */
515 /******/ !function() {
516 /******/ // getDefaultExport function for compatibility with non-harmony modules
517 /******/ __webpack_require__.n = function(module) {
518 /******/ var getter = module && module.__esModule ?
519 /******/ function() { return module['default']; } :
520 /******/ function() { return module; };
521 /******/ __webpack_require__.d(getter, { a: getter });
522 /******/ return getter;
523 /******/ };
524 /******/ }();
525 /******/
526 /******/ /* webpack/runtime/define property getters */
527 /******/ !function() {
528 /******/ // define getter functions for harmony exports
529 /******/ __webpack_require__.d = function(exports, definition) {
530 /******/ for(var key in definition) {
531 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
532 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
533 /******/ }
534 /******/ }
535 /******/ };
536 /******/ }();
537 /******/
538 /******/ /* webpack/runtime/hasOwnProperty shorthand */
539 /******/ !function() {
540 /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
541 /******/ }();
542 /******/
543 /******/ /* webpack/runtime/make namespace object */
544 /******/ !function() {
545 /******/ // define __esModule on exports
546 /******/ __webpack_require__.r = function(exports) {
547 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
548 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
549 /******/ }
550 /******/ Object.defineProperty(exports, '__esModule', { value: true });
551 /******/ };
552 /******/ }();
553 /******/
554 /************************************************************************/
555 var __webpack_exports__ = {};
556 // This entry need to be wrapped in an IIFE because it need to be in strict mode.
557 !function() {
558 "use strict";
559 // ESM COMPAT FLAG
560 __webpack_require__.r(__webpack_exports__);
561
562 // EXPORTS
563 __webpack_require__.d(__webpack_exports__, {
564 "EntityProvider": function() { return /* reexport */ EntityProvider; },
565 "__experimentalFetchLinkSuggestions": function() { return /* reexport */ _experimental_fetch_link_suggestions; },
566 "__experimentalFetchMedia": function() { return /* reexport */ fetchMedia; },
567 "__experimentalFetchUrlData": function() { return /* reexport */ _experimental_fetch_url_data; },
568 "__experimentalUseEntityRecord": function() { return /* reexport */ __experimentalUseEntityRecord; },
569 "__experimentalUseEntityRecords": function() { return /* reexport */ __experimentalUseEntityRecords; },
570 "__experimentalUseResourcePermissions": function() { return /* reexport */ __experimentalUseResourcePermissions; },
571 "store": function() { return /* binding */ store; },
572 "useEntityBlockEditor": function() { return /* reexport */ useEntityBlockEditor; },
573 "useEntityId": function() { return /* reexport */ useEntityId; },
574 "useEntityProp": function() { return /* reexport */ useEntityProp; },
575 "useEntityRecord": function() { return /* reexport */ useEntityRecord; },
576 "useEntityRecords": function() { return /* reexport */ useEntityRecords; },
577 "useResourcePermissions": function() { return /* reexport */ useResourcePermissions; }
578 });
579
580 // NAMESPACE OBJECT: ./packages/core-data/build-module/actions.js
581 var build_module_actions_namespaceObject = {};
582 __webpack_require__.r(build_module_actions_namespaceObject);
583 __webpack_require__.d(build_module_actions_namespaceObject, {
584 "__experimentalBatch": function() { return __experimentalBatch; },
585 "__experimentalReceiveCurrentGlobalStylesId": function() { return __experimentalReceiveCurrentGlobalStylesId; },
586 "__experimentalReceiveThemeBaseGlobalStyles": function() { return __experimentalReceiveThemeBaseGlobalStyles; },
587 "__experimentalReceiveThemeGlobalStyleVariations": function() { return __experimentalReceiveThemeGlobalStyleVariations; },
588 "__experimentalSaveSpecifiedEntityEdits": function() { return __experimentalSaveSpecifiedEntityEdits; },
589 "__unstableCreateUndoLevel": function() { return __unstableCreateUndoLevel; },
590 "addEntities": function() { return addEntities; },
591 "deleteEntityRecord": function() { return deleteEntityRecord; },
592 "editEntityRecord": function() { return editEntityRecord; },
593 "receiveAutosaves": function() { return receiveAutosaves; },
594 "receiveCurrentTheme": function() { return receiveCurrentTheme; },
595 "receiveCurrentUser": function() { return receiveCurrentUser; },
596 "receiveEmbedPreview": function() { return receiveEmbedPreview; },
597 "receiveEntityRecords": function() { return receiveEntityRecords; },
598 "receiveThemeSupports": function() { return receiveThemeSupports; },
599 "receiveUploadPermissions": function() { return receiveUploadPermissions; },
600 "receiveUserPermission": function() { return receiveUserPermission; },
601 "receiveUserQuery": function() { return receiveUserQuery; },
602 "redo": function() { return redo; },
603 "saveEditedEntityRecord": function() { return saveEditedEntityRecord; },
604 "saveEntityRecord": function() { return saveEntityRecord; },
605 "undo": function() { return undo; }
606 });
607
608 // NAMESPACE OBJECT: ./packages/core-data/build-module/selectors.js
609 var build_module_selectors_namespaceObject = {};
610 __webpack_require__.r(build_module_selectors_namespaceObject);
611 __webpack_require__.d(build_module_selectors_namespaceObject, {
612 "__experimentalGetCurrentGlobalStylesId": function() { return __experimentalGetCurrentGlobalStylesId; },
613 "__experimentalGetCurrentThemeBaseGlobalStyles": function() { return __experimentalGetCurrentThemeBaseGlobalStyles; },
614 "__experimentalGetCurrentThemeGlobalStylesVariations": function() { return __experimentalGetCurrentThemeGlobalStylesVariations; },
615 "__experimentalGetDirtyEntityRecords": function() { return __experimentalGetDirtyEntityRecords; },
616 "__experimentalGetEntitiesBeingSaved": function() { return __experimentalGetEntitiesBeingSaved; },
617 "__experimentalGetEntityRecordNoResolver": function() { return __experimentalGetEntityRecordNoResolver; },
618 "__experimentalGetTemplateForLink": function() { return __experimentalGetTemplateForLink; },
619 "canUser": function() { return canUser; },
620 "canUserEditEntityRecord": function() { return canUserEditEntityRecord; },
621 "getAuthors": function() { return getAuthors; },
622 "getAutosave": function() { return getAutosave; },
623 "getAutosaves": function() { return getAutosaves; },
624 "getBlockPatternCategories": function() { return getBlockPatternCategories; },
625 "getBlockPatterns": function() { return getBlockPatterns; },
626 "getCurrentTheme": function() { return getCurrentTheme; },
627 "getCurrentUser": function() { return getCurrentUser; },
628 "getEditedEntityRecord": function() { return getEditedEntityRecord; },
629 "getEmbedPreview": function() { return getEmbedPreview; },
630 "getEntitiesByKind": function() { return getEntitiesByKind; },
631 "getEntitiesConfig": function() { return getEntitiesConfig; },
632 "getEntity": function() { return getEntity; },
633 "getEntityConfig": function() { return getEntityConfig; },
634 "getEntityRecord": function() { return getEntityRecord; },
635 "getEntityRecordEdits": function() { return getEntityRecordEdits; },
636 "getEntityRecordNonTransientEdits": function() { return getEntityRecordNonTransientEdits; },
637 "getEntityRecords": function() { return getEntityRecords; },
638 "getLastEntityDeleteError": function() { return getLastEntityDeleteError; },
639 "getLastEntitySaveError": function() { return getLastEntitySaveError; },
640 "getRawEntityRecord": function() { return getRawEntityRecord; },
641 "getRedoEdit": function() { return getRedoEdit; },
642 "getReferenceByDistinctEdits": function() { return getReferenceByDistinctEdits; },
643 "getThemeSupports": function() { return getThemeSupports; },
644 "getUndoEdit": function() { return getUndoEdit; },
645 "getUserQueryResults": function() { return getUserQueryResults; },
646 "hasEditsForEntityRecord": function() { return hasEditsForEntityRecord; },
647 "hasEntityRecords": function() { return hasEntityRecords; },
648 "hasFetchedAutosaves": function() { return hasFetchedAutosaves; },
649 "hasRedo": function() { return hasRedo; },
650 "hasUndo": function() { return hasUndo; },
651 "isAutosavingEntityRecord": function() { return isAutosavingEntityRecord; },
652 "isDeletingEntityRecord": function() { return isDeletingEntityRecord; },
653 "isPreviewEmbedFallback": function() { return isPreviewEmbedFallback; },
654 "isRequestingEmbedPreview": function() { return isRequestingEmbedPreview; },
655 "isSavingEntityRecord": function() { return isSavingEntityRecord; }
656 });
657
658 // NAMESPACE OBJECT: ./packages/core-data/build-module/resolvers.js
659 var resolvers_namespaceObject = {};
660 __webpack_require__.r(resolvers_namespaceObject);
661 __webpack_require__.d(resolvers_namespaceObject, {
662 "__experimentalGetCurrentGlobalStylesId": function() { return resolvers_experimentalGetCurrentGlobalStylesId; },
663 "__experimentalGetCurrentThemeBaseGlobalStyles": function() { return resolvers_experimentalGetCurrentThemeBaseGlobalStyles; },
664 "__experimentalGetCurrentThemeGlobalStylesVariations": function() { return resolvers_experimentalGetCurrentThemeGlobalStylesVariations; },
665 "__experimentalGetTemplateForLink": function() { return resolvers_experimentalGetTemplateForLink; },
666 "canUser": function() { return resolvers_canUser; },
667 "canUserEditEntityRecord": function() { return resolvers_canUserEditEntityRecord; },
668 "getAuthors": function() { return resolvers_getAuthors; },
669 "getAutosave": function() { return resolvers_getAutosave; },
670 "getAutosaves": function() { return resolvers_getAutosaves; },
671 "getBlockPatternCategories": function() { return resolvers_getBlockPatternCategories; },
672 "getBlockPatterns": function() { return resolvers_getBlockPatterns; },
673 "getCurrentTheme": function() { return resolvers_getCurrentTheme; },
674 "getCurrentUser": function() { return resolvers_getCurrentUser; },
675 "getEditedEntityRecord": function() { return resolvers_getEditedEntityRecord; },
676 "getEmbedPreview": function() { return resolvers_getEmbedPreview; },
677 "getEntityRecord": function() { return resolvers_getEntityRecord; },
678 "getEntityRecords": function() { return resolvers_getEntityRecords; },
679 "getRawEntityRecord": function() { return resolvers_getRawEntityRecord; },
680 "getThemeSupports": function() { return resolvers_getThemeSupports; }
681 });
682
683 ;// CONCATENATED MODULE: external ["wp","data"]
684 var external_wp_data_namespaceObject = window["wp"]["data"];
685 ;// CONCATENATED MODULE: external "lodash"
686 var external_lodash_namespaceObject = window["lodash"];
687 ;// CONCATENATED MODULE: external ["wp","compose"]
688 var external_wp_compose_namespaceObject = window["wp"]["compose"];
689 ;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
690 var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
691 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
692 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/if-matching-action.js
693 /** @typedef {import('../types').AnyFunction} AnyFunction */
694
695 /**
696 * A higher-order reducer creator which invokes the original reducer only if
697 * the dispatching action matches the given predicate, **OR** if state is
698 * initializing (undefined).
699 *
700 * @param {AnyFunction} isMatch Function predicate for allowing reducer call.
701 *
702 * @return {AnyFunction} Higher-order reducer.
703 */
704 const ifMatchingAction = isMatch => reducer => (state, action) => {
705 if (state === undefined || isMatch(action)) {
706 return reducer(state, action);
707 }
708
709 return state;
710 };
711
712 /* harmony default export */ var if_matching_action = (ifMatchingAction);
713
714 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/replace-action.js
715 /** @typedef {import('../types').AnyFunction} AnyFunction */
716
717 /**
718 * Higher-order reducer creator which substitutes the action object before
719 * passing to the original reducer.
720 *
721 * @param {AnyFunction} replacer Function mapping original action to replacement.
722 *
723 * @return {AnyFunction} Higher-order reducer.
724 */
725 const replaceAction = replacer => reducer => (state, action) => {
726 return reducer(state, replacer(action));
727 };
728
729 /* harmony default export */ var replace_action = (replaceAction);
730
731 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/conservative-map-item.js
732 /**
733 * External dependencies
734 */
735
736 /**
737 * Given the current and next item entity record, returns the minimally "modified"
738 * result of the next item, preferring value references from the original item
739 * if equal. If all values match, the original item is returned.
740 *
741 * @param {Object} item Original item.
742 * @param {Object} nextItem Next item.
743 *
744 * @return {Object} Minimally modified merged item.
745 */
746
747 function conservativeMapItem(item, nextItem) {
748 // Return next item in its entirety if there is no original item.
749 if (!item) {
750 return nextItem;
751 }
752
753 let hasChanges = false;
754 const result = {};
755
756 for (const key in nextItem) {
757 if ((0,external_lodash_namespaceObject.isEqual)(item[key], nextItem[key])) {
758 result[key] = item[key];
759 } else {
760 hasChanges = true;
761 result[key] = nextItem[key];
762 }
763 }
764
765 if (!hasChanges) {
766 return item;
767 } // Only at this point, backfill properties from the original item which
768 // weren't explicitly set into the result above. This is an optimization
769 // to allow `hasChanges` to return early.
770
771
772 for (const key in item) {
773 if (!result.hasOwnProperty(key)) {
774 result[key] = item[key];
775 }
776 }
777
778 return result;
779 }
780
781 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/on-sub-key.js
782 /** @typedef {import('../types').AnyFunction} AnyFunction */
783
784 /**
785 * Higher-order reducer creator which creates a combined reducer object, keyed
786 * by a property on the action object.
787 *
788 * @param {string} actionProperty Action property by which to key object.
789 *
790 * @return {AnyFunction} Higher-order reducer.
791 */
792 const onSubKey = actionProperty => reducer => function () {
793 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
794 let action = arguments.length > 1 ? arguments[1] : undefined;
795 // Retrieve subkey from action. Do not track if undefined; useful for cases
796 // where reducer is scoped by action shape.
797 const key = action[actionProperty];
798
799 if (key === undefined) {
800 return state;
801 } // Avoid updating state if unchanged. Note that this also accounts for a
802 // reducer which returns undefined on a key which is not yet tracked.
803
804
805 const nextKeyState = reducer(state[key], action);
806
807 if (nextKeyState === state[key]) {
808 return state;
809 }
810
811 return { ...state,
812 [key]: nextKeyState
813 };
814 };
815 /* harmony default export */ var on_sub_key = (onSubKey);
816
817 ;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
818 /*! *****************************************************************************
819 Copyright (c) Microsoft Corporation.
820
821 Permission to use, copy, modify, and/or distribute this software for any
822 purpose with or without fee is hereby granted.
823
824 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
825 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
826 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
827 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
828 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
829 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
830 PERFORMANCE OF THIS SOFTWARE.
831 ***************************************************************************** */
832 /* global Reflect, Promise */
833
834 var extendStatics = function(d, b) {
835 extendStatics = Object.setPrototypeOf ||
836 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
837 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
838 return extendStatics(d, b);
839 };
840
841 function __extends(d, b) {
842 if (typeof b !== "function" && b !== null)
843 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
844 extendStatics(d, b);
845 function __() { this.constructor = d; }
846 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
847 }
848
849 var __assign = function() {
850 __assign = Object.assign || function __assign(t) {
851 for (var s, i = 1, n = arguments.length; i < n; i++) {
852 s = arguments[i];
853 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
854 }
855 return t;
856 }
857 return __assign.apply(this, arguments);
858 }
859
860 function __rest(s, e) {
861 var t = {};
862 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
863 t[p] = s[p];
864 if (s != null && typeof Object.getOwnPropertySymbols === "function")
865 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
866 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
867 t[p[i]] = s[p[i]];
868 }
869 return t;
870 }
871
872 function __decorate(decorators, target, key, desc) {
873 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
874 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
875 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
876 return c > 3 && r && Object.defineProperty(target, key, r), r;
877 }
878
879 function __param(paramIndex, decorator) {
880 return function (target, key) { decorator(target, key, paramIndex); }
881 }
882
883 function __metadata(metadataKey, metadataValue) {
884 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
885 }
886
887 function __awaiter(thisArg, _arguments, P, generator) {
888 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
889 return new (P || (P = Promise))(function (resolve, reject) {
890 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
891 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
892 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
893 step((generator = generator.apply(thisArg, _arguments || [])).next());
894 });
895 }
896
897 function __generator(thisArg, body) {
898 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
899 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
900 function verb(n) { return function (v) { return step([n, v]); }; }
901 function step(op) {
902 if (f) throw new TypeError("Generator is already executing.");
903 while (_) try {
904 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
905 if (y = 0, t) op = [op[0] & 2, t.value];
906 switch (op[0]) {
907 case 0: case 1: t = op; break;
908 case 4: _.label++; return { value: op[1], done: false };
909 case 5: _.label++; y = op[1]; op = [0]; continue;
910 case 7: op = _.ops.pop(); _.trys.pop(); continue;
911 default:
912 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
913 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
914 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
915 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
916 if (t[2]) _.ops.pop();
917 _.trys.pop(); continue;
918 }
919 op = body.call(thisArg, _);
920 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
921 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
922 }
923 }
924
925 var __createBinding = Object.create ? (function(o, m, k, k2) {
926 if (k2 === undefined) k2 = k;
927 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
928 }) : (function(o, m, k, k2) {
929 if (k2 === undefined) k2 = k;
930 o[k2] = m[k];
931 });
932
933 function __exportStar(m, o) {
934 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
935 }
936
937 function __values(o) {
938 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
939 if (m) return m.call(o);
940 if (o && typeof o.length === "number") return {
941 next: function () {
942 if (o && i >= o.length) o = void 0;
943 return { value: o && o[i++], done: !o };
944 }
945 };
946 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
947 }
948
949 function __read(o, n) {
950 var m = typeof Symbol === "function" && o[Symbol.iterator];
951 if (!m) return o;
952 var i = m.call(o), r, ar = [], e;
953 try {
954 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
955 }
956 catch (error) { e = { error: error }; }
957 finally {
958 try {
959 if (r && !r.done && (m = i["return"])) m.call(i);
960 }
961 finally { if (e) throw e.error; }
962 }
963 return ar;
964 }
965
966 /** @deprecated */
967 function __spread() {
968 for (var ar = [], i = 0; i < arguments.length; i++)
969 ar = ar.concat(__read(arguments[i]));
970 return ar;
971 }
972
973 /** @deprecated */
974 function __spreadArrays() {
975 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
976 for (var r = Array(s), k = 0, i = 0; i < il; i++)
977 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
978 r[k] = a[j];
979 return r;
980 }
981
982 function __spreadArray(to, from, pack) {
983 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
984 if (ar || !(i in from)) {
985 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
986 ar[i] = from[i];
987 }
988 }
989 return to.concat(ar || from);
990 }
991
992 function __await(v) {
993 return this instanceof __await ? (this.v = v, this) : new __await(v);
994 }
995
996 function __asyncGenerator(thisArg, _arguments, generator) {
997 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
998 var g = generator.apply(thisArg, _arguments || []), i, q = [];
999 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
1000 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
1001 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
1002 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
1003 function fulfill(value) { resume("next", value); }
1004 function reject(value) { resume("throw", value); }
1005 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
1006 }
1007
1008 function __asyncDelegator(o) {
1009 var i, p;
1010 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
1011 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
1012 }
1013
1014 function __asyncValues(o) {
1015 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1016 var m = o[Symbol.asyncIterator], i;
1017 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
1018 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
1019 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
1020 }
1021
1022 function __makeTemplateObject(cooked, raw) {
1023 if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
1024 return cooked;
1025 };
1026
1027 var __setModuleDefault = Object.create ? (function(o, v) {
1028 Object.defineProperty(o, "default", { enumerable: true, value: v });
1029 }) : function(o, v) {
1030 o["default"] = v;
1031 };
1032
1033 function __importStar(mod) {
1034 if (mod && mod.__esModule) return mod;
1035 var result = {};
1036 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1037 __setModuleDefault(result, mod);
1038 return result;
1039 }
1040
1041 function __importDefault(mod) {
1042 return (mod && mod.__esModule) ? mod : { default: mod };
1043 }
1044
1045 function __classPrivateFieldGet(receiver, state, kind, f) {
1046 if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1047 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1048 return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1049 }
1050
1051 function __classPrivateFieldSet(receiver, state, value, kind, f) {
1052 if (kind === "m") throw new TypeError("Private method is not writable");
1053 if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1054 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1055 return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1056 }
1057
1058 ;// CONCATENATED MODULE: ./node_modules/lower-case/dist.es2015/index.js
1059 /**
1060 * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1061 */
1062 var SUPPORTED_LOCALE = {
1063 tr: {
1064 regexp: /\u0130|\u0049|\u0049\u0307/g,
1065 map: {
1066 İ: "\u0069",
1067 I: "\u0131",
1068 : "\u0069",
1069 },
1070 },
1071 az: {
1072 regexp: /\u0130/g,
1073 map: {
1074 İ: "\u0069",
1075 I: "\u0131",
1076 : "\u0069",
1077 },
1078 },
1079 lt: {
1080 regexp: /\u0049|\u004A|\u012E|\u00CC|\u00CD|\u0128/g,
1081 map: {
1082 I: "\u0069\u0307",
1083 J: "\u006A\u0307",
1084 Į: "\u012F\u0307",
1085 Ì: "\u0069\u0307\u0300",
1086 Í: "\u0069\u0307\u0301",
1087 Ĩ: "\u0069\u0307\u0303",
1088 },
1089 },
1090 };
1091 /**
1092 * Localized lower case.
1093 */
1094 function localeLowerCase(str, locale) {
1095 var lang = SUPPORTED_LOCALE[locale.toLowerCase()];
1096 if (lang)
1097 return lowerCase(str.replace(lang.regexp, function (m) { return lang.map[m]; }));
1098 return lowerCase(str);
1099 }
1100 /**
1101 * Lower case as a function.
1102 */
1103 function lowerCase(str) {
1104 return str.toLowerCase();
1105 }
1106
1107 ;// CONCATENATED MODULE: ./node_modules/no-case/dist.es2015/index.js
1108
1109 // Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
1110 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
1111 // Remove all non-word characters.
1112 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
1113 /**
1114 * Normalize the string into something other libraries can manipulate easier.
1115 */
1116 function noCase(input, options) {
1117 if (options === void 0) { options = {}; }
1118 var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
1119 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
1120 var start = 0;
1121 var end = result.length;
1122 // Trim the delimiter from around the output string.
1123 while (result.charAt(start) === "\0")
1124 start++;
1125 while (result.charAt(end - 1) === "\0")
1126 end--;
1127 // Transform each token independently.
1128 return result.slice(start, end).split("\0").map(transform).join(delimiter);
1129 }
1130 /**
1131 * Replace `re` in the input string with the replacement value.
1132 */
1133 function replace(input, re, value) {
1134 if (re instanceof RegExp)
1135 return input.replace(re, value);
1136 return re.reduce(function (input, re) { return input.replace(re, value); }, input);
1137 }
1138
1139 ;// CONCATENATED MODULE: ./node_modules/upper-case-first/dist.es2015/index.js
1140 /**
1141 * Upper case the first character of an input string.
1142 */
1143 function upperCaseFirst(input) {
1144 return input.charAt(0).toUpperCase() + input.substr(1);
1145 }
1146
1147 ;// CONCATENATED MODULE: ./node_modules/capital-case/dist.es2015/index.js
1148
1149
1150
1151 function capitalCaseTransform(input) {
1152 return upperCaseFirst(input.toLowerCase());
1153 }
1154 function capitalCase(input, options) {
1155 if (options === void 0) { options = {}; }
1156 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
1157 }
1158
1159 ;// CONCATENATED MODULE: ./node_modules/pascal-case/dist.es2015/index.js
1160
1161
1162 function pascalCaseTransform(input, index) {
1163 var firstChar = input.charAt(0);
1164 var lowerChars = input.substr(1).toLowerCase();
1165 if (index > 0 && firstChar >= "0" && firstChar <= "9") {
1166 return "_" + firstChar + lowerChars;
1167 }
1168 return "" + firstChar.toUpperCase() + lowerChars;
1169 }
1170 function dist_es2015_pascalCaseTransformMerge(input) {
1171 return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
1172 }
1173 function pascalCase(input, options) {
1174 if (options === void 0) { options = {}; }
1175 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
1176 }
1177
1178 ;// CONCATENATED MODULE: external ["wp","apiFetch"]
1179 var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
1180 var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
1181 ;// CONCATENATED MODULE: external ["wp","i18n"]
1182 var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
1183 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/rng.js
1184 // Unique ID creation requires a high quality random # generator. In the browser we therefore
1185 // require the crypto API and do not support built-in fallback to lower quality random number
1186 // generators (like Math.random()).
1187 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
1188 // find the complete implementation of crypto (msCrypto) on IE11.
1189 var getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
1190 var rnds8 = new Uint8Array(16);
1191 function rng() {
1192 if (!getRandomValues) {
1193 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
1194 }
1195
1196 return getRandomValues(rnds8);
1197 }
1198 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/regex.js
1199 /* harmony default export */ var regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
1200 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/validate.js
1201
1202
1203 function validate(uuid) {
1204 return typeof uuid === 'string' && regex.test(uuid);
1205 }
1206
1207 /* harmony default export */ var esm_browser_validate = (validate);
1208 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/stringify.js
1209
1210 /**
1211 * Convert array of 16 byte values to UUID string format of the form:
1212 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1213 */
1214
1215 var byteToHex = [];
1216
1217 for (var i = 0; i < 256; ++i) {
1218 byteToHex.push((i + 0x100).toString(16).substr(1));
1219 }
1220
1221 function stringify(arr) {
1222 var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1223 // Note: Be careful editing this code! It's been tuned for performance
1224 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
1225 var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
1226 // of the following:
1227 // - One or more input array values don't map to a hex octet (leading to
1228 // "undefined" in the uuid)
1229 // - Invalid input values for the RFC `version` or `variant` fields
1230
1231 if (!esm_browser_validate(uuid)) {
1232 throw TypeError('Stringified UUID is invalid');
1233 }
1234
1235 return uuid;
1236 }
1237
1238 /* harmony default export */ var esm_browser_stringify = (stringify);
1239 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/v4.js
1240
1241
1242
1243 function v4(options, buf, offset) {
1244 options = options || {};
1245 var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1246
1247 rnds[6] = rnds[6] & 0x0f | 0x40;
1248 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
1249
1250 if (buf) {
1251 offset = offset || 0;
1252
1253 for (var i = 0; i < 16; ++i) {
1254 buf[offset + i] = rnds[i];
1255 }
1256
1257 return buf;
1258 }
1259
1260 return esm_browser_stringify(rnds);
1261 }
1262
1263 /* harmony default export */ var esm_browser_v4 = (v4);
1264 ;// CONCATENATED MODULE: external ["wp","url"]
1265 var external_wp_url_namespaceObject = window["wp"]["url"];
1266 ;// CONCATENATED MODULE: external ["wp","deprecated"]
1267 var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
1268 var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
1269 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/actions.js
1270 /**
1271 * Returns an action object used in signalling that items have been received.
1272 *
1273 * @param {Array} items Items received.
1274 * @param {?Object} edits Optional edits to reset.
1275 *
1276 * @return {Object} Action object.
1277 */
1278 function receiveItems(items, edits) {
1279 return {
1280 type: 'RECEIVE_ITEMS',
1281 items: Array.isArray(items) ? items : [items],
1282 persistedEdits: edits
1283 };
1284 }
1285 /**
1286 * Returns an action object used in signalling that entity records have been
1287 * deleted and they need to be removed from entities state.
1288 *
1289 * @param {string} kind Kind of the removed entities.
1290 * @param {string} name Name of the removed entities.
1291 * @param {Array|number|string} records Record IDs of the removed entities.
1292 * @param {boolean} invalidateCache Controls whether we want to invalidate the cache.
1293 * @return {Object} Action object.
1294 */
1295
1296 function removeItems(kind, name, records) {
1297 let invalidateCache = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
1298 return {
1299 type: 'REMOVE_ITEMS',
1300 itemIds: Array.isArray(records) ? records : [records],
1301 kind,
1302 name,
1303 invalidateCache
1304 };
1305 }
1306 /**
1307 * Returns an action object used in signalling that queried data has been
1308 * received.
1309 *
1310 * @param {Array} items Queried items received.
1311 * @param {?Object} query Optional query object.
1312 * @param {?Object} edits Optional edits to reset.
1313 *
1314 * @return {Object} Action object.
1315 */
1316
1317 function receiveQueriedItems(items) {
1318 let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1319 let edits = arguments.length > 2 ? arguments[2] : undefined;
1320 return { ...receiveItems(items, edits),
1321 query
1322 };
1323 }
1324
1325 ;// CONCATENATED MODULE: ./packages/core-data/build-module/batch/default-processor.js
1326 /**
1327 * WordPress dependencies
1328 */
1329
1330 /**
1331 * Maximum number of requests to place in a single batch request. Obtained by
1332 * sending a preflight OPTIONS request to /batch/v1/.
1333 *
1334 * @type {number?}
1335 */
1336
1337 let maxItems = null;
1338
1339 function chunk(arr, chunkSize) {
1340 const tmp = [...arr];
1341 const cache = [];
1342
1343 while (tmp.length) {
1344 cache.push(tmp.splice(0, chunkSize));
1345 }
1346
1347 return cache;
1348 }
1349 /**
1350 * Default batch processor. Sends its input requests to /batch/v1.
1351 *
1352 * @param {Array} requests List of API requests to perform at once.
1353 *
1354 * @return {Promise} Promise that resolves to a list of objects containing
1355 * either `output` (if that request was successful) or `error`
1356 * (if not ).
1357 */
1358
1359
1360 async function defaultProcessor(requests) {
1361 if (maxItems === null) {
1362 const preflightResponse = await external_wp_apiFetch_default()({
1363 path: '/batch/v1',
1364 method: 'OPTIONS'
1365 });
1366 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
1367 }
1368
1369 const results = []; // @ts-ignore We would have crashed or never gotten to this point if we hadn't received the maxItems count.
1370
1371 for (const batchRequests of chunk(requests, maxItems)) {
1372 const batchResponse = await external_wp_apiFetch_default()({
1373 path: '/batch/v1',
1374 method: 'POST',
1375 data: {
1376 validation: 'require-all-validate',
1377 requests: batchRequests.map(request => ({
1378 path: request.path,
1379 body: request.data,
1380 // Rename 'data' to 'body'.
1381 method: request.method,
1382 headers: request.headers
1383 }))
1384 }
1385 });
1386 let batchResults;
1387
1388 if (batchResponse.failed) {
1389 batchResults = batchResponse.responses.map(response => ({
1390 error: response === null || response === void 0 ? void 0 : response.body
1391 }));
1392 } else {
1393 batchResults = batchResponse.responses.map(response => {
1394 const result = {};
1395
1396 if (response.status >= 200 && response.status < 300) {
1397 result.output = response.body;
1398 } else {
1399 result.error = response.body;
1400 }
1401
1402 return result;
1403 });
1404 }
1405
1406 results.push(...batchResults);
1407 }
1408
1409 return results;
1410 }
1411
1412 ;// CONCATENATED MODULE: ./packages/core-data/build-module/batch/create-batch.js
1413 /**
1414 * Internal dependencies
1415 */
1416
1417 /**
1418 * Creates a batch, which can be used to combine multiple API requests into one
1419 * API request using the WordPress batch processing API (/v1/batch).
1420 *
1421 * ```
1422 * const batch = createBatch();
1423 * const dunePromise = batch.add( {
1424 * path: '/v1/books',
1425 * method: 'POST',
1426 * data: { title: 'Dune' }
1427 * } );
1428 * const lotrPromise = batch.add( {
1429 * path: '/v1/books',
1430 * method: 'POST',
1431 * data: { title: 'Lord of the Rings' }
1432 * } );
1433 * const isSuccess = await batch.run(); // Sends one POST to /v1/batch.
1434 * if ( isSuccess ) {
1435 * console.log(
1436 * 'Saved two books:',
1437 * await dunePromise,
1438 * await lotrPromise
1439 * );
1440 * }
1441 * ```
1442 *
1443 * @param {Function} [processor] Processor function. Can be used to replace the
1444 * default functionality which is to send an API
1445 * request to /v1/batch. Is given an array of
1446 * inputs and must return a promise that
1447 * resolves to an array of objects containing
1448 * either `output` or `error`.
1449 */
1450
1451 function createBatch() {
1452 let processor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultProcessor;
1453 let lastId = 0;
1454 /** @type {Array<{ input: any; resolve: ( value: any ) => void; reject: ( error: any ) => void }>} */
1455
1456 let queue = [];
1457 const pending = new ObservableSet();
1458 return {
1459 /**
1460 * Adds an input to the batch and returns a promise that is resolved or
1461 * rejected when the input is processed by `batch.run()`.
1462 *
1463 * You may also pass a thunk which allows inputs to be added
1464 * asychronously.
1465 *
1466 * ```
1467 * // Both are allowed:
1468 * batch.add( { path: '/v1/books', ... } );
1469 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
1470 * ```
1471 *
1472 * If a thunk is passed, `batch.run()` will pause until either:
1473 *
1474 * - The thunk calls its `add` argument, or;
1475 * - The thunk returns a promise and that promise resolves, or;
1476 * - The thunk returns a non-promise.
1477 *
1478 * @param {any|Function} inputOrThunk Input to add or thunk to execute.
1479 *
1480 * @return {Promise|any} If given an input, returns a promise that
1481 * is resolved or rejected when the batch is
1482 * processed. If given a thunk, returns the return
1483 * value of that thunk.
1484 */
1485 add(inputOrThunk) {
1486 const id = ++lastId;
1487 pending.add(id);
1488
1489 const add = input => new Promise((resolve, reject) => {
1490 queue.push({
1491 input,
1492 resolve,
1493 reject
1494 });
1495 pending.delete(id);
1496 });
1497
1498 if (typeof inputOrThunk === 'function') {
1499 return Promise.resolve(inputOrThunk(add)).finally(() => {
1500 pending.delete(id);
1501 });
1502 }
1503
1504 return add(inputOrThunk);
1505 },
1506
1507 /**
1508 * Runs the batch. This calls `batchProcessor` and resolves or rejects
1509 * all promises returned by `add()`.
1510 *
1511 * @return {Promise<boolean>} A promise that resolves to a boolean that is true
1512 * if the processor returned no errors.
1513 */
1514 async run() {
1515 if (pending.size) {
1516 await new Promise(resolve => {
1517 const unsubscribe = pending.subscribe(() => {
1518 if (!pending.size) {
1519 unsubscribe();
1520 resolve(undefined);
1521 }
1522 });
1523 });
1524 }
1525
1526 let results;
1527
1528 try {
1529 results = await processor(queue.map(_ref => {
1530 let {
1531 input
1532 } = _ref;
1533 return input;
1534 }));
1535
1536 if (results.length !== queue.length) {
1537 throw new Error('run: Array returned by processor must be same size as input array.');
1538 }
1539 } catch (error) {
1540 for (const {
1541 reject
1542 } of queue) {
1543 reject(error);
1544 }
1545
1546 throw error;
1547 }
1548
1549 let isSuccess = true;
1550 results.forEach((result, key) => {
1551 const queueItem = queue[key];
1552
1553 if (result !== null && result !== void 0 && result.error) {
1554 queueItem === null || queueItem === void 0 ? void 0 : queueItem.reject(result.error);
1555 isSuccess = false;
1556 } else {
1557 var _result$output;
1558
1559 queueItem === null || queueItem === void 0 ? void 0 : queueItem.resolve((_result$output = result === null || result === void 0 ? void 0 : result.output) !== null && _result$output !== void 0 ? _result$output : result);
1560 }
1561 });
1562 queue = [];
1563 return isSuccess;
1564 }
1565
1566 };
1567 }
1568
1569 class ObservableSet {
1570 constructor() {
1571 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1572 args[_key] = arguments[_key];
1573 }
1574
1575 this.set = new Set(...args);
1576 this.subscribers = new Set();
1577 }
1578
1579 get size() {
1580 return this.set.size;
1581 }
1582
1583 add(value) {
1584 this.set.add(value);
1585 this.subscribers.forEach(subscriber => subscriber());
1586 return this;
1587 }
1588
1589 delete(value) {
1590 const isSuccess = this.set.delete(value);
1591 this.subscribers.forEach(subscriber => subscriber());
1592 return isSuccess;
1593 }
1594
1595 subscribe(subscriber) {
1596 this.subscribers.add(subscriber);
1597 return () => {
1598 this.subscribers.delete(subscriber);
1599 };
1600 }
1601
1602 }
1603
1604 ;// CONCATENATED MODULE: ./packages/core-data/build-module/name.js
1605 /**
1606 * The reducer key used by core data in store registration.
1607 * This is defined in a separate file to avoid cycle-dependency
1608 *
1609 * @type {string}
1610 */
1611 const STORE_NAME = 'core';
1612
1613 ;// CONCATENATED MODULE: ./packages/core-data/build-module/actions.js
1614 /**
1615 * External dependencies
1616 */
1617
1618
1619 /**
1620 * WordPress dependencies
1621 */
1622
1623
1624
1625
1626 /**
1627 * Internal dependencies
1628 */
1629
1630
1631
1632
1633
1634 /**
1635 * Returns an action object used in signalling that authors have been received.
1636 * Ignored from documentation as it's internal to the data store.
1637 *
1638 * @ignore
1639 *
1640 * @param {string} queryID Query ID.
1641 * @param {Array|Object} users Users received.
1642 *
1643 * @return {Object} Action object.
1644 */
1645
1646 function receiveUserQuery(queryID, users) {
1647 return {
1648 type: 'RECEIVE_USER_QUERY',
1649 users: Array.isArray(users) ? users : [users],
1650 queryID
1651 };
1652 }
1653 /**
1654 * Returns an action used in signalling that the current user has been received.
1655 * Ignored from documentation as it's internal to the data store.
1656 *
1657 * @ignore
1658 *
1659 * @param {Object} currentUser Current user object.
1660 *
1661 * @return {Object} Action object.
1662 */
1663
1664 function receiveCurrentUser(currentUser) {
1665 return {
1666 type: 'RECEIVE_CURRENT_USER',
1667 currentUser
1668 };
1669 }
1670 /**
1671 * Returns an action object used in adding new entities.
1672 *
1673 * @param {Array} entities Entities received.
1674 *
1675 * @return {Object} Action object.
1676 */
1677
1678 function addEntities(entities) {
1679 return {
1680 type: 'ADD_ENTITIES',
1681 entities
1682 };
1683 }
1684 /**
1685 * Returns an action object used in signalling that entity records have been received.
1686 *
1687 * @param {string} kind Kind of the received entity record.
1688 * @param {string} name Name of the received entity record.
1689 * @param {Array|Object} records Records received.
1690 * @param {?Object} query Query Object.
1691 * @param {?boolean} invalidateCache Should invalidate query caches.
1692 * @param {?Object} edits Edits to reset.
1693 * @return {Object} Action object.
1694 */
1695
1696 function receiveEntityRecords(kind, name, records, query) {
1697 let invalidateCache = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
1698 let edits = arguments.length > 5 ? arguments[5] : undefined;
1699
1700 // Auto drafts should not have titles, but some plugins rely on them so we can't filter this
1701 // on the server.
1702 if (kind === 'postType') {
1703 records = (Array.isArray(records) ? records : [records]).map(record => record.status === 'auto-draft' ? { ...record,
1704 title: ''
1705 } : record);
1706 }
1707
1708 let action;
1709
1710 if (query) {
1711 action = receiveQueriedItems(records, query, edits);
1712 } else {
1713 action = receiveItems(records, edits);
1714 }
1715
1716 return { ...action,
1717 kind,
1718 name,
1719 invalidateCache
1720 };
1721 }
1722 /**
1723 * Returns an action object used in signalling that the current theme has been received.
1724 * Ignored from documentation as it's internal to the data store.
1725 *
1726 * @ignore
1727 *
1728 * @param {Object} currentTheme The current theme.
1729 *
1730 * @return {Object} Action object.
1731 */
1732
1733 function receiveCurrentTheme(currentTheme) {
1734 return {
1735 type: 'RECEIVE_CURRENT_THEME',
1736 currentTheme
1737 };
1738 }
1739 /**
1740 * Returns an action object used in signalling that the current global styles id has been received.
1741 * Ignored from documentation as it's internal to the data store.
1742 *
1743 * @ignore
1744 *
1745 * @param {string} currentGlobalStylesId The current global styles id.
1746 *
1747 * @return {Object} Action object.
1748 */
1749
1750 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId) {
1751 return {
1752 type: 'RECEIVE_CURRENT_GLOBAL_STYLES_ID',
1753 id: currentGlobalStylesId
1754 };
1755 }
1756 /**
1757 * Returns an action object used in signalling that the theme base global styles have been received
1758 * Ignored from documentation as it's internal to the data store.
1759 *
1760 * @ignore
1761 *
1762 * @param {string} stylesheet The theme's identifier
1763 * @param {Object} globalStyles The global styles object.
1764 *
1765 * @return {Object} Action object.
1766 */
1767
1768 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
1769 return {
1770 type: 'RECEIVE_THEME_GLOBAL_STYLES',
1771 stylesheet,
1772 globalStyles
1773 };
1774 }
1775 /**
1776 * Returns an action object used in signalling that the theme global styles variations have been received.
1777 * Ignored from documentation as it's internal to the data store.
1778 *
1779 * @ignore
1780 *
1781 * @param {string} stylesheet The theme's identifier
1782 * @param {Array} variations The global styles variations.
1783 *
1784 * @return {Object} Action object.
1785 */
1786
1787 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
1788 return {
1789 type: 'RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS',
1790 stylesheet,
1791 variations
1792 };
1793 }
1794 /**
1795 * Returns an action object used in signalling that the index has been received.
1796 *
1797 * @deprecated since WP 5.9, this is not useful anymore, use the selector direclty.
1798 *
1799 * @return {Object} Action object.
1800 */
1801
1802 function receiveThemeSupports() {
1803 external_wp_deprecated_default()("wp.data.dispatch( 'core' ).receiveThemeSupports", {
1804 since: '5.9'
1805 });
1806 return {
1807 type: 'DO_NOTHING'
1808 };
1809 }
1810 /**
1811 * Returns an action object used in signalling that the preview data for
1812 * a given URl has been received.
1813 * Ignored from documentation as it's internal to the data store.
1814 *
1815 * @ignore
1816 *
1817 * @param {string} url URL to preview the embed for.
1818 * @param {*} preview Preview data.
1819 *
1820 * @return {Object} Action object.
1821 */
1822
1823 function receiveEmbedPreview(url, preview) {
1824 return {
1825 type: 'RECEIVE_EMBED_PREVIEW',
1826 url,
1827 preview
1828 };
1829 }
1830 /**
1831 * Action triggered to delete an entity record.
1832 *
1833 * @param {string} kind Kind of the deleted entity.
1834 * @param {string} name Name of the deleted entity.
1835 * @param {string} recordId Record ID of the deleted entity.
1836 * @param {?Object} query Special query parameters for the
1837 * DELETE API call.
1838 * @param {Object} [options] Delete options.
1839 * @param {Function} [options.__unstableFetch] Internal use only. Function to
1840 * call instead of `apiFetch()`.
1841 * Must return a promise.
1842 * @param {boolean} [options.throwOnError=false] If false, this action suppresses all
1843 * the exceptions. Defaults to false.
1844 */
1845
1846 const deleteEntityRecord = function (kind, name, recordId, query) {
1847 let {
1848 __unstableFetch = (external_wp_apiFetch_default()),
1849 throwOnError = false
1850 } = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1851 return async _ref => {
1852 let {
1853 dispatch
1854 } = _ref;
1855 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
1856 const entityConfig = (0,external_lodash_namespaceObject.find)(configs, {
1857 kind,
1858 name
1859 });
1860 let error;
1861 let deletedRecord = false;
1862
1863 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
1864 return;
1865 }
1866
1867 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, recordId], {
1868 exclusive: true
1869 });
1870
1871 try {
1872 dispatch({
1873 type: 'DELETE_ENTITY_RECORD_START',
1874 kind,
1875 name,
1876 recordId
1877 });
1878 let hasError = false;
1879
1880 try {
1881 let path = `${entityConfig.baseURL}/${recordId}`;
1882
1883 if (query) {
1884 path = (0,external_wp_url_namespaceObject.addQueryArgs)(path, query);
1885 }
1886
1887 deletedRecord = await __unstableFetch({
1888 path,
1889 method: 'DELETE'
1890 });
1891 await dispatch(removeItems(kind, name, recordId, true));
1892 } catch (_error) {
1893 hasError = true;
1894 error = _error;
1895 }
1896
1897 dispatch({
1898 type: 'DELETE_ENTITY_RECORD_FINISH',
1899 kind,
1900 name,
1901 recordId,
1902 error
1903 });
1904
1905 if (hasError && throwOnError) {
1906 throw error;
1907 }
1908
1909 return deletedRecord;
1910 } finally {
1911 dispatch.__unstableReleaseStoreLock(lock);
1912 }
1913 };
1914 };
1915 /**
1916 * Returns an action object that triggers an
1917 * edit to an entity record.
1918 *
1919 * @param {string} kind Kind of the edited entity record.
1920 * @param {string} name Name of the edited entity record.
1921 * @param {number} recordId Record ID of the edited entity record.
1922 * @param {Object} edits The edits.
1923 * @param {Object} options Options for the edit.
1924 * @param {boolean} [options.undoIgnore] Whether to ignore the edit in undo history or not.
1925 *
1926 * @return {Object} Action object.
1927 */
1928
1929 const editEntityRecord = function (kind, name, recordId, edits) {
1930 let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1931 return _ref2 => {
1932 let {
1933 select,
1934 dispatch
1935 } = _ref2;
1936 const entityConfig = select.getEntityConfig(kind, name);
1937
1938 if (!entityConfig) {
1939 throw new Error(`The entity being edited (${kind}, ${name}) does not have a loaded config.`);
1940 }
1941
1942 const {
1943 transientEdits = {},
1944 mergedEdits = {}
1945 } = entityConfig;
1946 const record = select.getRawEntityRecord(kind, name, recordId);
1947 const editedRecord = select.getEditedEntityRecord(kind, name, recordId);
1948 const edit = {
1949 kind,
1950 name,
1951 recordId,
1952 // Clear edits when they are equal to their persisted counterparts
1953 // so that the property is not considered dirty.
1954 edits: Object.keys(edits).reduce((acc, key) => {
1955 const recordValue = record[key];
1956 const editedRecordValue = editedRecord[key];
1957 const value = mergedEdits[key] ? { ...editedRecordValue,
1958 ...edits[key]
1959 } : edits[key];
1960 acc[key] = (0,external_lodash_namespaceObject.isEqual)(recordValue, value) ? undefined : value;
1961 return acc;
1962 }, {}),
1963 transientEdits
1964 };
1965 dispatch({
1966 type: 'EDIT_ENTITY_RECORD',
1967 ...edit,
1968 meta: {
1969 undo: !options.undoIgnore && { ...edit,
1970 // Send the current values for things like the first undo stack entry.
1971 edits: Object.keys(edits).reduce((acc, key) => {
1972 acc[key] = editedRecord[key];
1973 return acc;
1974 }, {})
1975 }
1976 }
1977 });
1978 };
1979 };
1980 /**
1981 * Action triggered to undo the last edit to
1982 * an entity record, if any.
1983 */
1984
1985 const undo = () => _ref3 => {
1986 let {
1987 select,
1988 dispatch
1989 } = _ref3;
1990 const undoEdit = select.getUndoEdit();
1991
1992 if (!undoEdit) {
1993 return;
1994 }
1995
1996 dispatch({
1997 type: 'EDIT_ENTITY_RECORD',
1998 ...undoEdit,
1999 meta: {
2000 isUndo: true
2001 }
2002 });
2003 };
2004 /**
2005 * Action triggered to redo the last undoed
2006 * edit to an entity record, if any.
2007 */
2008
2009 const redo = () => _ref4 => {
2010 let {
2011 select,
2012 dispatch
2013 } = _ref4;
2014 const redoEdit = select.getRedoEdit();
2015
2016 if (!redoEdit) {
2017 return;
2018 }
2019
2020 dispatch({
2021 type: 'EDIT_ENTITY_RECORD',
2022 ...redoEdit,
2023 meta: {
2024 isRedo: true
2025 }
2026 });
2027 };
2028 /**
2029 * Forces the creation of a new undo level.
2030 *
2031 * @return {Object} Action object.
2032 */
2033
2034 function __unstableCreateUndoLevel() {
2035 return {
2036 type: 'CREATE_UNDO_LEVEL'
2037 };
2038 }
2039 /**
2040 * Action triggered to save an entity record.
2041 *
2042 * @param {string} kind Kind of the received entity.
2043 * @param {string} name Name of the received entity.
2044 * @param {Object} record Record to be saved.
2045 * @param {Object} options Saving options.
2046 * @param {boolean} [options.isAutosave=false] Whether this is an autosave.
2047 * @param {Function} [options.__unstableFetch] Internal use only. Function to
2048 * call instead of `apiFetch()`.
2049 * Must return a promise.
2050 * @param {boolean} [options.throwOnError=false] If false, this action suppresses all
2051 * the exceptions. Defaults to false.
2052 */
2053
2054 const saveEntityRecord = function (kind, name, record) {
2055 let {
2056 isAutosave = false,
2057 __unstableFetch = (external_wp_apiFetch_default()),
2058 throwOnError = false
2059 } = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2060 return async _ref5 => {
2061 let {
2062 select,
2063 resolveSelect,
2064 dispatch
2065 } = _ref5;
2066 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
2067 const entityConfig = (0,external_lodash_namespaceObject.find)(configs, {
2068 kind,
2069 name
2070 });
2071
2072 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
2073 return;
2074 }
2075
2076 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
2077 const recordId = record[entityIdKey];
2078 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, recordId || esm_browser_v4()], {
2079 exclusive: true
2080 });
2081
2082 try {
2083 // Evaluate optimized edits.
2084 // (Function edits that should be evaluated on save to avoid expensive computations on every edit.)
2085 for (const [key, value] of Object.entries(record)) {
2086 if (typeof value === 'function') {
2087 const evaluatedValue = value(select.getEditedEntityRecord(kind, name, recordId));
2088 dispatch.editEntityRecord(kind, name, recordId, {
2089 [key]: evaluatedValue
2090 }, {
2091 undoIgnore: true
2092 });
2093 record[key] = evaluatedValue;
2094 }
2095 }
2096
2097 dispatch({
2098 type: 'SAVE_ENTITY_RECORD_START',
2099 kind,
2100 name,
2101 recordId,
2102 isAutosave
2103 });
2104 let updatedRecord;
2105 let error;
2106 let hasError = false;
2107
2108 try {
2109 const path = `${entityConfig.baseURL}${recordId ? '/' + recordId : ''}`;
2110 const persistedRecord = select.getRawEntityRecord(kind, name, recordId);
2111
2112 if (isAutosave) {
2113 // Most of this autosave logic is very specific to posts.
2114 // This is fine for now as it is the only supported autosave,
2115 // but ideally this should all be handled in the back end,
2116 // so the client just sends and receives objects.
2117 const currentUser = select.getCurrentUser();
2118 const currentUserId = currentUser ? currentUser.id : undefined;
2119 const autosavePost = await resolveSelect.getAutosave(persistedRecord.type, persistedRecord.id, currentUserId); // Autosaves need all expected fields to be present.
2120 // So we fallback to the previous autosave and then
2121 // to the actual persisted entity if the edits don't
2122 // have a value.
2123
2124 let data = { ...persistedRecord,
2125 ...autosavePost,
2126 ...record
2127 };
2128 data = Object.keys(data).reduce((acc, key) => {
2129 if (['title', 'excerpt', 'content'].includes(key)) {
2130 acc[key] = data[key];
2131 }
2132
2133 return acc;
2134 }, {
2135 status: data.status === 'auto-draft' ? 'draft' : data.status
2136 });
2137 updatedRecord = await __unstableFetch({
2138 path: `${path}/autosaves`,
2139 method: 'POST',
2140 data
2141 }); // An autosave may be processed by the server as a regular save
2142 // when its update is requested by the author and the post had
2143 // draft or auto-draft status.
2144
2145 if (persistedRecord.id === updatedRecord.id) {
2146 let newRecord = { ...persistedRecord,
2147 ...data,
2148 ...updatedRecord
2149 };
2150 newRecord = Object.keys(newRecord).reduce((acc, key) => {
2151 // These properties are persisted in autosaves.
2152 if (['title', 'excerpt', 'content'].includes(key)) {
2153 acc[key] = newRecord[key];
2154 } else if (key === 'status') {
2155 // Status is only persisted in autosaves when going from
2156 // "auto-draft" to "draft".
2157 acc[key] = persistedRecord.status === 'auto-draft' && newRecord.status === 'draft' ? newRecord.status : persistedRecord.status;
2158 } else {
2159 // These properties are not persisted in autosaves.
2160 acc[key] = persistedRecord[key];
2161 }
2162
2163 return acc;
2164 }, {});
2165 dispatch.receiveEntityRecords(kind, name, newRecord, undefined, true);
2166 } else {
2167 dispatch.receiveAutosaves(persistedRecord.id, updatedRecord);
2168 }
2169 } else {
2170 let edits = record;
2171
2172 if (entityConfig.__unstablePrePersist) {
2173 edits = { ...edits,
2174 ...entityConfig.__unstablePrePersist(persistedRecord, edits)
2175 };
2176 }
2177
2178 updatedRecord = await __unstableFetch({
2179 path,
2180 method: recordId ? 'PUT' : 'POST',
2181 data: edits
2182 });
2183 dispatch.receiveEntityRecords(kind, name, updatedRecord, undefined, true, edits);
2184 }
2185 } catch (_error) {
2186 hasError = true;
2187 error = _error;
2188 }
2189
2190 dispatch({
2191 type: 'SAVE_ENTITY_RECORD_FINISH',
2192 kind,
2193 name,
2194 recordId,
2195 error,
2196 isAutosave
2197 });
2198
2199 if (hasError && throwOnError) {
2200 throw error;
2201 }
2202
2203 return updatedRecord;
2204 } finally {
2205 dispatch.__unstableReleaseStoreLock(lock);
2206 }
2207 };
2208 };
2209 /**
2210 * Runs multiple core-data actions at the same time using one API request.
2211 *
2212 * Example:
2213 *
2214 * ```
2215 * const [ savedRecord, updatedRecord, deletedRecord ] =
2216 * await dispatch( 'core' ).__experimentalBatch( [
2217 * ( { saveEntityRecord } ) => saveEntityRecord( 'root', 'widget', widget ),
2218 * ( { saveEditedEntityRecord } ) => saveEntityRecord( 'root', 'widget', 123 ),
2219 * ( { deleteEntityRecord } ) => deleteEntityRecord( 'root', 'widget', 123, null ),
2220 * ] );
2221 * ```
2222 *
2223 * @param {Array} requests Array of functions which are invoked simultaneously.
2224 * Each function is passed an object containing
2225 * `saveEntityRecord`, `saveEditedEntityRecord`, and
2226 * `deleteEntityRecord`.
2227 *
2228 * @return {(thunkArgs: Object) => Promise} A promise that resolves to an array containing the return
2229 * values of each function given in `requests`.
2230 */
2231
2232 const __experimentalBatch = requests => async _ref6 => {
2233 let {
2234 dispatch
2235 } = _ref6;
2236 const batch = createBatch();
2237 const api = {
2238 saveEntityRecord(kind, name, record, options) {
2239 return batch.add(add => dispatch.saveEntityRecord(kind, name, record, { ...options,
2240 __unstableFetch: add
2241 }));
2242 },
2243
2244 saveEditedEntityRecord(kind, name, recordId, options) {
2245 return batch.add(add => dispatch.saveEditedEntityRecord(kind, name, recordId, { ...options,
2246 __unstableFetch: add
2247 }));
2248 },
2249
2250 deleteEntityRecord(kind, name, recordId, query, options) {
2251 return batch.add(add => dispatch.deleteEntityRecord(kind, name, recordId, query, { ...options,
2252 __unstableFetch: add
2253 }));
2254 }
2255
2256 };
2257 const resultPromises = requests.map(request => request(api));
2258 const [, ...results] = await Promise.all([batch.run(), ...resultPromises]);
2259 return results;
2260 };
2261 /**
2262 * Action triggered to save an entity record's edits.
2263 *
2264 * @param {string} kind Kind of the entity.
2265 * @param {string} name Name of the entity.
2266 * @param {Object} recordId ID of the record.
2267 * @param {Object} options Saving options.
2268 */
2269
2270 const saveEditedEntityRecord = (kind, name, recordId, options) => async _ref7 => {
2271 let {
2272 select,
2273 dispatch
2274 } = _ref7;
2275
2276 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
2277 return;
2278 }
2279
2280 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
2281 const entityConfig = (0,external_lodash_namespaceObject.find)(configs, {
2282 kind,
2283 name
2284 });
2285
2286 if (!entityConfig) {
2287 return;
2288 }
2289
2290 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
2291 const edits = select.getEntityRecordNonTransientEdits(kind, name, recordId);
2292 const record = {
2293 [entityIdKey]: recordId,
2294 ...edits
2295 };
2296 return await dispatch.saveEntityRecord(kind, name, record, options);
2297 };
2298 /**
2299 * Action triggered to save only specified properties for the entity.
2300 *
2301 * @param {string} kind Kind of the entity.
2302 * @param {string} name Name of the entity.
2303 * @param {Object} recordId ID of the record.
2304 * @param {Array} itemsToSave List of entity properties to save.
2305 * @param {Object} options Saving options.
2306 */
2307
2308 const __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async _ref8 => {
2309 let {
2310 select,
2311 dispatch
2312 } = _ref8;
2313
2314 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
2315 return;
2316 }
2317
2318 const edits = select.getEntityRecordNonTransientEdits(kind, name, recordId);
2319 const editsToSave = {};
2320
2321 for (const edit in edits) {
2322 if (itemsToSave.some(item => item === edit)) {
2323 editsToSave[edit] = edits[edit];
2324 }
2325 }
2326
2327 return await dispatch.saveEntityRecord(kind, name, editsToSave, options);
2328 };
2329 /**
2330 * Returns an action object used in signalling that Upload permissions have been received.
2331 *
2332 * @deprecated since WP 5.9, use receiveUserPermission instead.
2333 *
2334 * @param {boolean} hasUploadPermissions Does the user have permission to upload files?
2335 *
2336 * @return {Object} Action object.
2337 */
2338
2339 function receiveUploadPermissions(hasUploadPermissions) {
2340 external_wp_deprecated_default()("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
2341 since: '5.9',
2342 alternative: 'receiveUserPermission'
2343 });
2344 return receiveUserPermission('create/media', hasUploadPermissions);
2345 }
2346 /**
2347 * Returns an action object used in signalling that the current user has
2348 * permission to perform an action on a REST resource.
2349 * Ignored from documentation as it's internal to the data store.
2350 *
2351 * @ignore
2352 *
2353 * @param {string} key A key that represents the action and REST resource.
2354 * @param {boolean} isAllowed Whether or not the user can perform the action.
2355 *
2356 * @return {Object} Action object.
2357 */
2358
2359 function receiveUserPermission(key, isAllowed) {
2360 return {
2361 type: 'RECEIVE_USER_PERMISSION',
2362 key,
2363 isAllowed
2364 };
2365 }
2366 /**
2367 * Returns an action object used in signalling that the autosaves for a
2368 * post have been received.
2369 * Ignored from documentation as it's internal to the data store.
2370 *
2371 * @ignore
2372 *
2373 * @param {number} postId The id of the post that is parent to the autosave.
2374 * @param {Array|Object} autosaves An array of autosaves or singular autosave object.
2375 *
2376 * @return {Object} Action object.
2377 */
2378
2379 function receiveAutosaves(postId, autosaves) {
2380 return {
2381 type: 'RECEIVE_AUTOSAVES',
2382 postId,
2383 autosaves: Array.isArray(autosaves) ? autosaves : [autosaves]
2384 };
2385 }
2386
2387 ;// CONCATENATED MODULE: ./packages/core-data/build-module/entities.js
2388 /**
2389 * External dependencies
2390 */
2391
2392
2393 /**
2394 * WordPress dependencies
2395 */
2396
2397
2398
2399 /**
2400 * Internal dependencies
2401 */
2402
2403
2404 const DEFAULT_ENTITY_KEY = 'id';
2405 const POST_RAW_ATTRIBUTES = ['title', 'excerpt', 'content'];
2406 const rootEntitiesConfig = [{
2407 label: (0,external_wp_i18n_namespaceObject.__)('Base'),
2408 kind: 'root',
2409 name: '__unstableBase',
2410 baseURL: '/',
2411 baseURLParams: {
2412 _fields: ['description', 'gmt_offset', 'home', 'name', 'site_icon', 'site_icon_url', 'site_logo', 'timezone_string', 'url'].join(',')
2413 }
2414 }, {
2415 label: (0,external_wp_i18n_namespaceObject.__)('Site'),
2416 name: 'site',
2417 kind: 'root',
2418 baseURL: '/wp/v2/settings',
2419 getTitle: record => {
2420 return (0,external_lodash_namespaceObject.get)(record, ['title'], (0,external_wp_i18n_namespaceObject.__)('Site Title'));
2421 }
2422 }, {
2423 label: (0,external_wp_i18n_namespaceObject.__)('Post Type'),
2424 name: 'postType',
2425 kind: 'root',
2426 key: 'slug',
2427 baseURL: '/wp/v2/types',
2428 baseURLParams: {
2429 context: 'edit'
2430 }
2431 }, {
2432 name: 'media',
2433 kind: 'root',
2434 baseURL: '/wp/v2/media',
2435 baseURLParams: {
2436 context: 'edit'
2437 },
2438 plural: 'mediaItems',
2439 label: (0,external_wp_i18n_namespaceObject.__)('Media'),
2440 rawAttributes: ['caption', 'title', 'description']
2441 }, {
2442 name: 'taxonomy',
2443 kind: 'root',
2444 key: 'slug',
2445 baseURL: '/wp/v2/taxonomies',
2446 baseURLParams: {
2447 context: 'edit'
2448 },
2449 plural: 'taxonomies',
2450 label: (0,external_wp_i18n_namespaceObject.__)('Taxonomy')
2451 }, {
2452 name: 'sidebar',
2453 kind: 'root',
2454 baseURL: '/wp/v2/sidebars',
2455 baseURLParams: {
2456 context: 'edit'
2457 },
2458 plural: 'sidebars',
2459 transientEdits: {
2460 blocks: true
2461 },
2462 label: (0,external_wp_i18n_namespaceObject.__)('Widget areas')
2463 }, {
2464 name: 'widget',
2465 kind: 'root',
2466 baseURL: '/wp/v2/widgets',
2467 baseURLParams: {
2468 context: 'edit'
2469 },
2470 plural: 'widgets',
2471 transientEdits: {
2472 blocks: true
2473 },
2474 label: (0,external_wp_i18n_namespaceObject.__)('Widgets')
2475 }, {
2476 name: 'widgetType',
2477 kind: 'root',
2478 baseURL: '/wp/v2/widget-types',
2479 baseURLParams: {
2480 context: 'edit'
2481 },
2482 plural: 'widgetTypes',
2483 label: (0,external_wp_i18n_namespaceObject.__)('Widget types')
2484 }, {
2485 label: (0,external_wp_i18n_namespaceObject.__)('User'),
2486 name: 'user',
2487 kind: 'root',
2488 baseURL: '/wp/v2/users',
2489 baseURLParams: {
2490 context: 'edit'
2491 },
2492 plural: 'users'
2493 }, {
2494 name: 'comment',
2495 kind: 'root',
2496 baseURL: '/wp/v2/comments',
2497 baseURLParams: {
2498 context: 'edit'
2499 },
2500 plural: 'comments',
2501 label: (0,external_wp_i18n_namespaceObject.__)('Comment')
2502 }, {
2503 name: 'menu',
2504 kind: 'root',
2505 baseURL: '/wp/v2/menus',
2506 baseURLParams: {
2507 context: 'edit'
2508 },
2509 plural: 'menus',
2510 label: (0,external_wp_i18n_namespaceObject.__)('Menu')
2511 }, {
2512 name: 'menuItem',
2513 kind: 'root',
2514 baseURL: '/wp/v2/menu-items',
2515 baseURLParams: {
2516 context: 'edit'
2517 },
2518 plural: 'menuItems',
2519 label: (0,external_wp_i18n_namespaceObject.__)('Menu Item'),
2520 rawAttributes: ['title']
2521 }, {
2522 name: 'menuLocation',
2523 kind: 'root',
2524 baseURL: '/wp/v2/menu-locations',
2525 baseURLParams: {
2526 context: 'edit'
2527 },
2528 plural: 'menuLocations',
2529 label: (0,external_wp_i18n_namespaceObject.__)('Menu Location'),
2530 key: 'name'
2531 }, {
2532 label: (0,external_wp_i18n_namespaceObject.__)('Global Styles'),
2533 name: 'globalStyles',
2534 kind: 'root',
2535 baseURL: '/wp/v2/global-styles',
2536 baseURLParams: {
2537 context: 'edit'
2538 },
2539 plural: 'globalStylesVariations',
2540 // Should be different than name.
2541 getTitle: record => {
2542 var _record$title;
2543
2544 return (record === null || record === void 0 ? void 0 : (_record$title = record.title) === null || _record$title === void 0 ? void 0 : _record$title.rendered) || (record === null || record === void 0 ? void 0 : record.title);
2545 }
2546 }, {
2547 label: (0,external_wp_i18n_namespaceObject.__)('Themes'),
2548 name: 'theme',
2549 kind: 'root',
2550 baseURL: '/wp/v2/themes',
2551 baseURLParams: {
2552 context: 'edit'
2553 },
2554 key: 'stylesheet'
2555 }, {
2556 label: (0,external_wp_i18n_namespaceObject.__)('Plugins'),
2557 name: 'plugin',
2558 kind: 'root',
2559 baseURL: '/wp/v2/plugins',
2560 baseURLParams: {
2561 context: 'edit'
2562 },
2563 key: 'plugin'
2564 }];
2565 const additionalEntityConfigLoaders = [{
2566 kind: 'postType',
2567 loadEntities: loadPostTypeEntities
2568 }, {
2569 kind: 'taxonomy',
2570 loadEntities: loadTaxonomyEntities
2571 }];
2572 /**
2573 * Returns a function to be used to retrieve extra edits to apply before persisting a post type.
2574 *
2575 * @param {Object} persistedRecord Already persisted Post
2576 * @param {Object} edits Edits.
2577 * @return {Object} Updated edits.
2578 */
2579
2580 const prePersistPostType = (persistedRecord, edits) => {
2581 const newEdits = {};
2582
2583 if ((persistedRecord === null || persistedRecord === void 0 ? void 0 : persistedRecord.status) === 'auto-draft') {
2584 // Saving an auto-draft should create a draft by default.
2585 if (!edits.status && !newEdits.status) {
2586 newEdits.status = 'draft';
2587 } // Fix the auto-draft default title.
2588
2589
2590 if ((!edits.title || edits.title === 'Auto Draft') && !newEdits.title && (!(persistedRecord !== null && persistedRecord !== void 0 && persistedRecord.title) || (persistedRecord === null || persistedRecord === void 0 ? void 0 : persistedRecord.title) === 'Auto Draft')) {
2591 newEdits.title = '';
2592 }
2593 }
2594
2595 return newEdits;
2596 };
2597 /**
2598 * Returns the list of post type entities.
2599 *
2600 * @return {Promise} Entities promise
2601 */
2602
2603 async function loadPostTypeEntities() {
2604 const postTypes = await external_wp_apiFetch_default()({
2605 path: '/wp/v2/types?context=view'
2606 });
2607 return (0,external_lodash_namespaceObject.map)(postTypes, (postType, name) => {
2608 var _postType$rest_namesp;
2609
2610 const isTemplate = ['wp_template', 'wp_template_part'].includes(name);
2611 const namespace = (_postType$rest_namesp = postType === null || postType === void 0 ? void 0 : postType.rest_namespace) !== null && _postType$rest_namesp !== void 0 ? _postType$rest_namesp : 'wp/v2';
2612 return {
2613 kind: 'postType',
2614 baseURL: `/${namespace}/${postType.rest_base}`,
2615 baseURLParams: {
2616 context: 'edit'
2617 },
2618 name,
2619 label: postType.name,
2620 transientEdits: {
2621 blocks: true,
2622 selection: true
2623 },
2624 mergedEdits: {
2625 meta: true
2626 },
2627 rawAttributes: POST_RAW_ATTRIBUTES,
2628 getTitle: record => {
2629 var _record$title2, _record$slug;
2630
2631 return (record === null || record === void 0 ? void 0 : (_record$title2 = record.title) === null || _record$title2 === void 0 ? void 0 : _record$title2.rendered) || (record === null || record === void 0 ? void 0 : record.title) || (isTemplate ? capitalCase((_record$slug = record.slug) !== null && _record$slug !== void 0 ? _record$slug : '') : String(record.id));
2632 },
2633 __unstablePrePersist: isTemplate ? undefined : prePersistPostType,
2634 __unstable_rest_base: postType.rest_base
2635 };
2636 });
2637 }
2638 /**
2639 * Returns the list of the taxonomies entities.
2640 *
2641 * @return {Promise} Entities promise
2642 */
2643
2644
2645 async function loadTaxonomyEntities() {
2646 const taxonomies = await external_wp_apiFetch_default()({
2647 path: '/wp/v2/taxonomies?context=view'
2648 });
2649 return (0,external_lodash_namespaceObject.map)(taxonomies, (taxonomy, name) => {
2650 var _taxonomy$rest_namesp;
2651
2652 const namespace = (_taxonomy$rest_namesp = taxonomy === null || taxonomy === void 0 ? void 0 : taxonomy.rest_namespace) !== null && _taxonomy$rest_namesp !== void 0 ? _taxonomy$rest_namesp : 'wp/v2';
2653 return {
2654 kind: 'taxonomy',
2655 baseURL: `/${namespace}/${taxonomy.rest_base}`,
2656 baseURLParams: {
2657 context: 'edit'
2658 },
2659 name,
2660 label: taxonomy.name
2661 };
2662 });
2663 }
2664 /**
2665 * Returns the entity's getter method name given its kind and name.
2666 *
2667 * @example
2668 * ```js
2669 * const nameSingular = getMethodName( 'root', 'theme', 'get' );
2670 * // nameSingular is getRootTheme
2671 *
2672 * const namePlural = getMethodName( 'root', 'theme', 'set' );
2673 * // namePlural is setRootThemes
2674 * ```
2675 *
2676 * @param {string} kind Entity kind.
2677 * @param {string} name Entity name.
2678 * @param {string} prefix Function prefix.
2679 * @param {boolean} usePlural Whether to use the plural form or not.
2680 *
2681 * @return {string} Method name
2682 */
2683
2684
2685 const getMethodName = function (kind, name) {
2686 let prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
2687 let usePlural = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
2688 const entityConfig = (0,external_lodash_namespaceObject.find)(rootEntitiesConfig, {
2689 kind,
2690 name
2691 });
2692 const kindPrefix = kind === 'root' ? '' : pascalCase(kind);
2693 const nameSuffix = pascalCase(name) + (usePlural ? 's' : '');
2694 const suffix = usePlural && 'plural' in entityConfig && entityConfig !== null && entityConfig !== void 0 && entityConfig.plural ? pascalCase(entityConfig.plural) : nameSuffix;
2695 return `${prefix}${kindPrefix}${suffix}`;
2696 };
2697 /**
2698 * Loads the kind entities into the store.
2699 *
2700 * @param {string} kind Kind
2701 *
2702 * @return {(thunkArgs: object) => Promise<Array>} Entities
2703 */
2704
2705 const getOrLoadEntitiesConfig = kind => async _ref => {
2706 let {
2707 select,
2708 dispatch
2709 } = _ref;
2710 let configs = select.getEntitiesConfig(kind);
2711
2712 if (configs && configs.length !== 0) {
2713 return configs;
2714 }
2715
2716 const loader = (0,external_lodash_namespaceObject.find)(additionalEntityConfigLoaders, {
2717 kind
2718 });
2719
2720 if (!loader) {
2721 return [];
2722 }
2723
2724 configs = await loader.loadEntities();
2725 dispatch(addEntities(configs));
2726 return configs;
2727 };
2728
2729 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/get-normalized-comma-separable.js
2730 /**
2731 * Given a value which can be specified as one or the other of a comma-separated
2732 * string or an array, returns a value normalized to an array of strings, or
2733 * null if the value cannot be interpreted as either.
2734 *
2735 * @param {string|string[]|*} value
2736 *
2737 * @return {?(string[])} Normalized field value.
2738 */
2739 function getNormalizedCommaSeparable(value) {
2740 if (typeof value === 'string') {
2741 return value.split(',');
2742 } else if (Array.isArray(value)) {
2743 return value;
2744 }
2745
2746 return null;
2747 }
2748
2749 /* harmony default export */ var get_normalized_comma_separable = (getNormalizedCommaSeparable);
2750
2751 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/with-weak-map-cache.js
2752 /**
2753 * Given a function, returns an enhanced function which caches the result and
2754 * tracks in WeakMap. The result is only cached if the original function is
2755 * passed a valid object-like argument (requirement for WeakMap key).
2756 *
2757 * @param {Function} fn Original function.
2758 *
2759 * @return {Function} Enhanced caching function.
2760 */
2761 function withWeakMapCache(fn) {
2762 const cache = new WeakMap();
2763 return key => {
2764 let value;
2765
2766 if (cache.has(key)) {
2767 value = cache.get(key);
2768 } else {
2769 value = fn(key); // Can reach here if key is not valid for WeakMap, since `has`
2770 // will return false for invalid key. Since `set` will throw,
2771 // ensure that key is valid before setting into cache.
2772
2773 if (key !== null && typeof key === 'object') {
2774 cache.set(key, value);
2775 }
2776 }
2777
2778 return value;
2779 };
2780 }
2781
2782 /* harmony default export */ var with_weak_map_cache = (withWeakMapCache);
2783
2784 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/get-query-parts.js
2785 /**
2786 * WordPress dependencies
2787 */
2788
2789 /**
2790 * Internal dependencies
2791 */
2792
2793
2794 /**
2795 * An object of properties describing a specific query.
2796 *
2797 * @typedef {Object} WPQueriedDataQueryParts
2798 *
2799 * @property {number} page The query page (1-based index, default 1).
2800 * @property {number} perPage Items per page for query (default 10).
2801 * @property {string} stableKey An encoded stable string of all non-
2802 * pagination, non-fields query parameters.
2803 * @property {?(string[])} fields Target subset of fields to derive from
2804 * item objects.
2805 * @property {?(number[])} include Specific item IDs to include.
2806 * @property {string} context Scope under which the request is made;
2807 * determines returned fields in response.
2808 */
2809
2810 /**
2811 * Given a query object, returns an object of parts, including pagination
2812 * details (`page` and `perPage`, or default values). All other properties are
2813 * encoded into a stable (idempotent) `stableKey` value.
2814 *
2815 * @param {Object} query Optional query object.
2816 *
2817 * @return {WPQueriedDataQueryParts} Query parts.
2818 */
2819
2820 function getQueryParts(query) {
2821 /**
2822 * @type {WPQueriedDataQueryParts}
2823 */
2824 const parts = {
2825 stableKey: '',
2826 page: 1,
2827 perPage: 10,
2828 fields: null,
2829 include: null,
2830 context: 'default'
2831 }; // Ensure stable key by sorting keys. Also more efficient for iterating.
2832
2833 const keys = Object.keys(query).sort();
2834
2835 for (let i = 0; i < keys.length; i++) {
2836 const key = keys[i];
2837 let value = query[key];
2838
2839 switch (key) {
2840 case 'page':
2841 parts[key] = Number(value);
2842 break;
2843
2844 case 'per_page':
2845 parts.perPage = Number(value);
2846 break;
2847
2848 case 'context':
2849 parts.context = value;
2850 break;
2851
2852 default:
2853 // While in theory, we could exclude "_fields" from the stableKey
2854 // because two request with different fields have the same results
2855 // We're not able to ensure that because the server can decide to omit
2856 // fields from the response even if we explicitly asked for it.
2857 // Example: Asking for titles in posts without title support.
2858 if (key === '_fields') {
2859 var _getNormalizedCommaSe;
2860
2861 parts.fields = (_getNormalizedCommaSe = get_normalized_comma_separable(value)) !== null && _getNormalizedCommaSe !== void 0 ? _getNormalizedCommaSe : []; // Make sure to normalize value for `stableKey`
2862
2863 value = parts.fields.join();
2864 } // Two requests with different include values cannot have same results.
2865
2866
2867 if (key === 'include') {
2868 var _getNormalizedCommaSe2;
2869
2870 if (typeof value === 'number') {
2871 value = value.toString();
2872 }
2873
2874 parts.include = ((_getNormalizedCommaSe2 = get_normalized_comma_separable(value)) !== null && _getNormalizedCommaSe2 !== void 0 ? _getNormalizedCommaSe2 : []).map(Number); // Normalize value for `stableKey`.
2875
2876 value = parts.include.join();
2877 } // While it could be any deterministic string, for simplicity's
2878 // sake mimic querystring encoding for stable key.
2879 //
2880 // TODO: For consistency with PHP implementation, addQueryArgs
2881 // should accept a key value pair, which may optimize its
2882 // implementation for our use here, vs. iterating an object
2883 // with only a single key.
2884
2885
2886 parts.stableKey += (parts.stableKey ? '&' : '') + (0,external_wp_url_namespaceObject.addQueryArgs)('', {
2887 [key]: value
2888 }).slice(1);
2889 }
2890 }
2891
2892 return parts;
2893 }
2894 /* harmony default export */ var get_query_parts = (with_weak_map_cache(getQueryParts));
2895
2896 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/reducer.js
2897 /**
2898 * External dependencies
2899 */
2900
2901 /**
2902 * WordPress dependencies
2903 */
2904
2905
2906
2907 /**
2908 * Internal dependencies
2909 */
2910
2911
2912
2913
2914
2915 function getContextFromAction(action) {
2916 const {
2917 query
2918 } = action;
2919
2920 if (!query) {
2921 return 'default';
2922 }
2923
2924 const queryParts = get_query_parts(query);
2925 return queryParts.context;
2926 }
2927 /**
2928 * Returns a merged array of item IDs, given details of the received paginated
2929 * items. The array is sparse-like with `undefined` entries where holes exist.
2930 *
2931 * @param {?Array<number>} itemIds Original item IDs (default empty array).
2932 * @param {number[]} nextItemIds Item IDs to merge.
2933 * @param {number} page Page of items merged.
2934 * @param {number} perPage Number of items per page.
2935 *
2936 * @return {number[]} Merged array of item IDs.
2937 */
2938
2939
2940 function getMergedItemIds(itemIds, nextItemIds, page, perPage) {
2941 var _itemIds$length;
2942
2943 const receivedAllIds = page === 1 && perPage === -1;
2944
2945 if (receivedAllIds) {
2946 return nextItemIds;
2947 }
2948
2949 const nextItemIdsStartIndex = (page - 1) * perPage; // If later page has already been received, default to the larger known
2950 // size of the existing array, else calculate as extending the existing.
2951
2952 const size = Math.max((_itemIds$length = itemIds === null || itemIds === void 0 ? void 0 : itemIds.length) !== null && _itemIds$length !== void 0 ? _itemIds$length : 0, nextItemIdsStartIndex + nextItemIds.length); // Preallocate array since size is known.
2953
2954 const mergedItemIds = new Array(size);
2955
2956 for (let i = 0; i < size; i++) {
2957 // Preserve existing item ID except for subset of range of next items.
2958 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIds.length;
2959 mergedItemIds[i] = isInNextItemsRange ? nextItemIds[i - nextItemIdsStartIndex] : itemIds === null || itemIds === void 0 ? void 0 : itemIds[i];
2960 }
2961
2962 return mergedItemIds;
2963 }
2964 /**
2965 * Reducer tracking items state, keyed by ID. Items are assumed to be normal,
2966 * where identifiers are common across all queries.
2967 *
2968 * @param {Object} state Current state.
2969 * @param {Object} action Dispatched action.
2970 *
2971 * @return {Object} Next state.
2972 */
2973
2974 function items() {
2975 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2976 let action = arguments.length > 1 ? arguments[1] : undefined;
2977
2978 switch (action.type) {
2979 case 'RECEIVE_ITEMS':
2980 {
2981 const context = getContextFromAction(action);
2982 const key = action.key || DEFAULT_ENTITY_KEY;
2983 return { ...state,
2984 [context]: { ...state[context],
2985 ...action.items.reduce((accumulator, value) => {
2986 var _state$context;
2987
2988 const itemId = value[key];
2989 accumulator[itemId] = conservativeMapItem(state === null || state === void 0 ? void 0 : (_state$context = state[context]) === null || _state$context === void 0 ? void 0 : _state$context[itemId], value);
2990 return accumulator;
2991 }, {})
2992 }
2993 };
2994 }
2995
2996 case 'REMOVE_ITEMS':
2997 return (0,external_lodash_namespaceObject.mapValues)(state, contextState => (0,external_lodash_namespaceObject.omit)(contextState, action.itemIds));
2998 }
2999
3000 return state;
3001 }
3002 /**
3003 * Reducer tracking item completeness, keyed by ID. A complete item is one for
3004 * which all fields are known. This is used in supporting `_fields` queries,
3005 * where not all properties associated with an entity are necessarily returned.
3006 * In such cases, completeness is used as an indication of whether it would be
3007 * safe to use queried data for a non-`_fields`-limited request.
3008 *
3009 * @param {Object<string,Object<string,boolean>>} state Current state.
3010 * @param {Object} action Dispatched action.
3011 *
3012 * @return {Object<string,Object<string,boolean>>} Next state.
3013 */
3014
3015 function itemIsComplete() {
3016 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3017 let action = arguments.length > 1 ? arguments[1] : undefined;
3018
3019 switch (action.type) {
3020 case 'RECEIVE_ITEMS':
3021 {
3022 const context = getContextFromAction(action);
3023 const {
3024 query,
3025 key = DEFAULT_ENTITY_KEY
3026 } = action; // An item is considered complete if it is received without an associated
3027 // fields query. Ideally, this would be implemented in such a way where the
3028 // complete aggregate of all fields would satisfy completeness. Since the
3029 // fields are not consistent across all entities, this would require
3030 // introspection on the REST schema for each entity to know which fields
3031 // compose a complete item for that entity.
3032
3033 const queryParts = query ? get_query_parts(query) : {};
3034 const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
3035 return { ...state,
3036 [context]: { ...state[context],
3037 ...action.items.reduce((result, item) => {
3038 var _state$context2;
3039
3040 const itemId = item[key]; // Defer to completeness if already assigned. Technically the
3041 // data may be outdated if receiving items for a field subset.
3042
3043 result[itemId] = (state === null || state === void 0 ? void 0 : (_state$context2 = state[context]) === null || _state$context2 === void 0 ? void 0 : _state$context2[itemId]) || isCompleteQuery;
3044 return result;
3045 }, {})
3046 }
3047 };
3048 }
3049
3050 case 'REMOVE_ITEMS':
3051 return (0,external_lodash_namespaceObject.mapValues)(state, contextState => (0,external_lodash_namespaceObject.omit)(contextState, action.itemIds));
3052 }
3053
3054 return state;
3055 }
3056 /**
3057 * Reducer tracking queries state, keyed by stable query key. Each reducer
3058 * query object includes `itemIds` and `requestingPageByPerPage`.
3059 *
3060 * @param {Object} state Current state.
3061 * @param {Object} action Dispatched action.
3062 *
3063 * @return {Object} Next state.
3064 */
3065
3066 const receiveQueries = (0,external_wp_compose_namespaceObject.compose)([// Limit to matching action type so we don't attempt to replace action on
3067 // an unhandled action.
3068 if_matching_action(action => 'query' in action), // Inject query parts into action for use both in `onSubKey` and reducer.
3069 replace_action(action => {
3070 // `ifMatchingAction` still passes on initialization, where state is
3071 // undefined and a query is not assigned. Avoid attempting to parse
3072 // parts. `onSubKey` will omit by lack of `stableKey`.
3073 if (action.query) {
3074 return { ...action,
3075 ...get_query_parts(action.query)
3076 };
3077 }
3078
3079 return action;
3080 }), on_sub_key('context'), // Queries shape is shared, but keyed by query `stableKey` part. Original
3081 // reducer tracks only a single query object.
3082 on_sub_key('stableKey')])(function () {
3083 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
3084 let action = arguments.length > 1 ? arguments[1] : undefined;
3085 const {
3086 type,
3087 page,
3088 perPage,
3089 key = DEFAULT_ENTITY_KEY
3090 } = action;
3091
3092 if (type !== 'RECEIVE_ITEMS') {
3093 return state;
3094 }
3095
3096 return getMergedItemIds(state || [], (0,external_lodash_namespaceObject.map)(action.items, key), page, perPage);
3097 });
3098 /**
3099 * Reducer tracking queries state.
3100 *
3101 * @param {Object} state Current state.
3102 * @param {Object} action Dispatched action.
3103 *
3104 * @return {Object} Next state.
3105 */
3106
3107 const queries = function () {
3108 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3109 let action = arguments.length > 1 ? arguments[1] : undefined;
3110
3111 switch (action.type) {
3112 case 'RECEIVE_ITEMS':
3113 return receiveQueries(state, action);
3114
3115 case 'REMOVE_ITEMS':
3116 const removedItems = action.itemIds.reduce((result, itemId) => {
3117 result[itemId] = true;
3118 return result;
3119 }, {});
3120 return (0,external_lodash_namespaceObject.mapValues)(state, contextQueries => {
3121 return (0,external_lodash_namespaceObject.mapValues)(contextQueries, queryItems => {
3122 return queryItems.filter(queryId => {
3123 return !removedItems[queryId];
3124 });
3125 });
3126 });
3127
3128 default:
3129 return state;
3130 }
3131 };
3132
3133 /* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
3134 items,
3135 itemIsComplete,
3136 queries
3137 }));
3138
3139 ;// CONCATENATED MODULE: ./packages/core-data/build-module/reducer.js
3140 /**
3141 * External dependencies
3142 */
3143
3144 /**
3145 * WordPress dependencies
3146 */
3147
3148
3149
3150
3151 /**
3152 * Internal dependencies
3153 */
3154
3155
3156
3157
3158 /** @typedef {import('./types').AnyFunction} AnyFunction */
3159
3160 /**
3161 * Reducer managing terms state. Keyed by taxonomy slug, the value is either
3162 * undefined (if no request has been made for given taxonomy), null (if a
3163 * request is in-flight for given taxonomy), or the array of terms for the
3164 * taxonomy.
3165 *
3166 * @param {Object} state Current state.
3167 * @param {Object} action Dispatched action.
3168 *
3169 * @return {Object} Updated state.
3170 */
3171
3172 function terms() {
3173 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3174 let action = arguments.length > 1 ? arguments[1] : undefined;
3175
3176 switch (action.type) {
3177 case 'RECEIVE_TERMS':
3178 return { ...state,
3179 [action.taxonomy]: action.terms
3180 };
3181 }
3182
3183 return state;
3184 }
3185 /**
3186 * Reducer managing authors state. Keyed by id.
3187 *
3188 * @param {Object} state Current state.
3189 * @param {Object} action Dispatched action.
3190 *
3191 * @return {Object} Updated state.
3192 */
3193
3194 function users() {
3195 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
3196 byId: {},
3197 queries: {}
3198 };
3199 let action = arguments.length > 1 ? arguments[1] : undefined;
3200
3201 switch (action.type) {
3202 case 'RECEIVE_USER_QUERY':
3203 return {
3204 byId: { ...state.byId,
3205 // Key users by their ID.
3206 ...action.users.reduce((newUsers, user) => ({ ...newUsers,
3207 [user.id]: user
3208 }), {})
3209 },
3210 queries: { ...state.queries,
3211 [action.queryID]: (0,external_lodash_namespaceObject.map)(action.users, user => user.id)
3212 }
3213 };
3214 }
3215
3216 return state;
3217 }
3218 /**
3219 * Reducer managing current user state.
3220 *
3221 * @param {Object} state Current state.
3222 * @param {Object} action Dispatched action.
3223 *
3224 * @return {Object} Updated state.
3225 */
3226
3227 function currentUser() {
3228 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3229 let action = arguments.length > 1 ? arguments[1] : undefined;
3230
3231 switch (action.type) {
3232 case 'RECEIVE_CURRENT_USER':
3233 return action.currentUser;
3234 }
3235
3236 return state;
3237 }
3238 /**
3239 * Reducer managing taxonomies.
3240 *
3241 * @param {Object} state Current state.
3242 * @param {Object} action Dispatched action.
3243 *
3244 * @return {Object} Updated state.
3245 */
3246
3247 function taxonomies() {
3248 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3249 let action = arguments.length > 1 ? arguments[1] : undefined;
3250
3251 switch (action.type) {
3252 case 'RECEIVE_TAXONOMIES':
3253 return action.taxonomies;
3254 }
3255
3256 return state;
3257 }
3258 /**
3259 * Reducer managing the current theme.
3260 *
3261 * @param {string|undefined} state Current state.
3262 * @param {Object} action Dispatched action.
3263 *
3264 * @return {string|undefined} Updated state.
3265 */
3266
3267 function currentTheme() {
3268 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
3269 let action = arguments.length > 1 ? arguments[1] : undefined;
3270
3271 switch (action.type) {
3272 case 'RECEIVE_CURRENT_THEME':
3273 return action.currentTheme.stylesheet;
3274 }
3275
3276 return state;
3277 }
3278 /**
3279 * Reducer managing the current global styles id.
3280 *
3281 * @param {string|undefined} state Current state.
3282 * @param {Object} action Dispatched action.
3283 *
3284 * @return {string|undefined} Updated state.
3285 */
3286
3287 function currentGlobalStylesId() {
3288 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
3289 let action = arguments.length > 1 ? arguments[1] : undefined;
3290
3291 switch (action.type) {
3292 case 'RECEIVE_CURRENT_GLOBAL_STYLES_ID':
3293 return action.id;
3294 }
3295
3296 return state;
3297 }
3298 /**
3299 * Reducer managing the theme base global styles.
3300 *
3301 * @param {Record<string, object>} state Current state.
3302 * @param {Object} action Dispatched action.
3303 *
3304 * @return {Record<string, object>} Updated state.
3305 */
3306
3307 function themeBaseGlobalStyles() {
3308 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3309 let action = arguments.length > 1 ? arguments[1] : undefined;
3310
3311 switch (action.type) {
3312 case 'RECEIVE_THEME_GLOBAL_STYLES':
3313 return { ...state,
3314 [action.stylesheet]: action.globalStyles
3315 };
3316 }
3317
3318 return state;
3319 }
3320 /**
3321 * Reducer managing the theme global styles variations.
3322 *
3323 * @param {Record<string, object>} state Current state.
3324 * @param {Object} action Dispatched action.
3325 *
3326 * @return {Record<string, object>} Updated state.
3327 */
3328
3329 function themeGlobalStyleVariations() {
3330 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3331 let action = arguments.length > 1 ? arguments[1] : undefined;
3332
3333 switch (action.type) {
3334 case 'RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS':
3335 return { ...state,
3336 [action.stylesheet]: action.variations
3337 };
3338 }
3339
3340 return state;
3341 }
3342 /**
3343 * Higher Order Reducer for a given entity config. It supports:
3344 *
3345 * - Fetching
3346 * - Editing
3347 * - Saving
3348 *
3349 * @param {Object} entityConfig Entity config.
3350 *
3351 * @return {AnyFunction} Reducer.
3352 */
3353
3354 function entity(entityConfig) {
3355 return (0,external_wp_compose_namespaceObject.compose)([// Limit to matching action type so we don't attempt to replace action on
3356 // an unhandled action.
3357 if_matching_action(action => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind), // Inject the entity config into the action.
3358 replace_action(action => {
3359 return { ...action,
3360 key: entityConfig.key || DEFAULT_ENTITY_KEY
3361 };
3362 })])((0,external_wp_data_namespaceObject.combineReducers)({
3363 queriedData: reducer,
3364 edits: function () {
3365 var _action$query$context, _action$query;
3366
3367 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3368 let action = arguments.length > 1 ? arguments[1] : undefined;
3369
3370 switch (action.type) {
3371 case 'RECEIVE_ITEMS':
3372 const context = (_action$query$context = action === null || action === void 0 ? void 0 : (_action$query = action.query) === null || _action$query === void 0 ? void 0 : _action$query.context) !== null && _action$query$context !== void 0 ? _action$query$context : 'default';
3373
3374 if (context !== 'default') {
3375 return state;
3376 }
3377
3378 const nextState = { ...state
3379 };
3380
3381 for (const record of action.items) {
3382 const recordId = record[action.key];
3383 const edits = nextState[recordId];
3384
3385 if (!edits) {
3386 continue;
3387 }
3388
3389 const nextEdits = Object.keys(edits).reduce((acc, key) => {
3390 // If the edited value is still different to the persisted value,
3391 // keep the edited value in edits.
3392 if ( // Edits are the "raw" attribute values, but records may have
3393 // objects with more properties, so we use `get` here for the
3394 // comparison.
3395 !(0,external_lodash_namespaceObject.isEqual)(edits[key], (0,external_lodash_namespaceObject.get)(record[key], 'raw', record[key])) && ( // Sometimes the server alters the sent value which means
3396 // we need to also remove the edits before the api request.
3397 !action.persistedEdits || !(0,external_lodash_namespaceObject.isEqual)(edits[key], action.persistedEdits[key]))) {
3398 acc[key] = edits[key];
3399 }
3400
3401 return acc;
3402 }, {});
3403
3404 if (Object.keys(nextEdits).length) {
3405 nextState[recordId] = nextEdits;
3406 } else {
3407 delete nextState[recordId];
3408 }
3409 }
3410
3411 return nextState;
3412
3413 case 'EDIT_ENTITY_RECORD':
3414 const nextEdits = { ...state[action.recordId],
3415 ...action.edits
3416 };
3417 Object.keys(nextEdits).forEach(key => {
3418 // Delete cleared edits so that the properties
3419 // are not considered dirty.
3420 if (nextEdits[key] === undefined) {
3421 delete nextEdits[key];
3422 }
3423 });
3424 return { ...state,
3425 [action.recordId]: nextEdits
3426 };
3427 }
3428
3429 return state;
3430 },
3431 saving: function () {
3432 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3433 let action = arguments.length > 1 ? arguments[1] : undefined;
3434
3435 switch (action.type) {
3436 case 'SAVE_ENTITY_RECORD_START':
3437 case 'SAVE_ENTITY_RECORD_FINISH':
3438 return { ...state,
3439 [action.recordId]: {
3440 pending: action.type === 'SAVE_ENTITY_RECORD_START',
3441 error: action.error,
3442 isAutosave: action.isAutosave
3443 }
3444 };
3445 }
3446
3447 return state;
3448 },
3449 deleting: function () {
3450 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3451 let action = arguments.length > 1 ? arguments[1] : undefined;
3452
3453 switch (action.type) {
3454 case 'DELETE_ENTITY_RECORD_START':
3455 case 'DELETE_ENTITY_RECORD_FINISH':
3456 return { ...state,
3457 [action.recordId]: {
3458 pending: action.type === 'DELETE_ENTITY_RECORD_START',
3459 error: action.error
3460 }
3461 };
3462 }
3463
3464 return state;
3465 }
3466 }));
3467 }
3468 /**
3469 * Reducer keeping track of the registered entities.
3470 *
3471 * @param {Object} state Current state.
3472 * @param {Object} action Dispatched action.
3473 *
3474 * @return {Object} Updated state.
3475 */
3476
3477
3478 function entitiesConfig() {
3479 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : rootEntitiesConfig;
3480 let action = arguments.length > 1 ? arguments[1] : undefined;
3481
3482 switch (action.type) {
3483 case 'ADD_ENTITIES':
3484 return [...state, ...action.entities];
3485 }
3486
3487 return state;
3488 }
3489 /**
3490 * Reducer keeping track of the registered entities config and data.
3491 *
3492 * @param {Object} state Current state.
3493 * @param {Object} action Dispatched action.
3494 *
3495 * @return {Object} Updated state.
3496 */
3497
3498 const entities = function () {
3499 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3500 let action = arguments.length > 1 ? arguments[1] : undefined;
3501 const newConfig = entitiesConfig(state.config, action); // Generates a dynamic reducer for the entities.
3502
3503 let entitiesDataReducer = state.reducer;
3504
3505 if (!entitiesDataReducer || newConfig !== state.config) {
3506 const entitiesByKind = (0,external_lodash_namespaceObject.groupBy)(newConfig, 'kind');
3507 entitiesDataReducer = (0,external_wp_data_namespaceObject.combineReducers)(Object.entries(entitiesByKind).reduce((memo, _ref) => {
3508 let [kind, subEntities] = _ref;
3509 const kindReducer = (0,external_wp_data_namespaceObject.combineReducers)(subEntities.reduce((kindMemo, entityConfig) => ({ ...kindMemo,
3510 [entityConfig.name]: entity(entityConfig)
3511 }), {}));
3512 memo[kind] = kindReducer;
3513 return memo;
3514 }, {}));
3515 }
3516
3517 const newData = entitiesDataReducer(state.records, action);
3518
3519 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
3520 return state;
3521 }
3522
3523 return {
3524 reducer: entitiesDataReducer,
3525 records: newData,
3526 config: newConfig
3527 };
3528 };
3529 /**
3530 * @typedef {Object} UndoStateMeta
3531 *
3532 * @property {number} offset Where in the undo stack we are.
3533 * @property {Object} [flattenedUndo] Flattened form of undo stack.
3534 */
3535
3536 /** @typedef {Array<Object> & UndoStateMeta} UndoState */
3537
3538 /**
3539 * @type {UndoState}
3540 *
3541 * @todo Given how we use this we might want to make a custom class for it.
3542 */
3543
3544 const UNDO_INITIAL_STATE = Object.assign([], {
3545 offset: 0
3546 });
3547 /** @type {Object} */
3548
3549 let lastEditAction;
3550 /**
3551 * Reducer keeping track of entity edit undo history.
3552 *
3553 * @param {UndoState} state Current state.
3554 * @param {Object} action Dispatched action.
3555 *
3556 * @return {UndoState} Updated state.
3557 */
3558
3559 function reducer_undo() {
3560 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UNDO_INITIAL_STATE;
3561 let action = arguments.length > 1 ? arguments[1] : undefined;
3562
3563 switch (action.type) {
3564 case 'EDIT_ENTITY_RECORD':
3565 case 'CREATE_UNDO_LEVEL':
3566 let isCreateUndoLevel = action.type === 'CREATE_UNDO_LEVEL';
3567 const isUndoOrRedo = !isCreateUndoLevel && (action.meta.isUndo || action.meta.isRedo);
3568
3569 if (isCreateUndoLevel) {
3570 action = lastEditAction;
3571 } else if (!isUndoOrRedo) {
3572 // Don't lose the last edit cache if the new one only has transient edits.
3573 // Transient edits don't create new levels so updating the cache would make
3574 // us skip an edit later when creating levels explicitly.
3575 if (Object.keys(action.edits).some(key => !action.transientEdits[key])) {
3576 lastEditAction = action;
3577 } else {
3578 lastEditAction = { ...action,
3579 edits: { ...(lastEditAction && lastEditAction.edits),
3580 ...action.edits
3581 }
3582 };
3583 }
3584 }
3585 /** @type {UndoState} */
3586
3587
3588 let nextState;
3589
3590 if (isUndoOrRedo) {
3591 // @ts-ignore we might consider using Object.assign({}, state)
3592 nextState = [...state];
3593 nextState.offset = state.offset + (action.meta.isUndo ? -1 : 1);
3594
3595 if (state.flattenedUndo) {
3596 // The first undo in a sequence of undos might happen while we have
3597 // flattened undos in state. If this is the case, we want execution
3598 // to continue as if we were creating an explicit undo level. This
3599 // will result in an extra undo level being appended with the flattened
3600 // undo values.
3601 // We also have to take into account if the `lastEditAction` had opted out
3602 // of being tracked in undo history, like the action that persists the latest
3603 // content right before saving. In that case we have to update the `lastEditAction`
3604 // to avoid returning early before applying the existing flattened undos.
3605 isCreateUndoLevel = true;
3606
3607 if (!lastEditAction.meta.undo) {
3608 lastEditAction.meta.undo = {
3609 edits: {}
3610 };
3611 }
3612
3613 action = lastEditAction;
3614 } else {
3615 return nextState;
3616 }
3617 }
3618
3619 if (!action.meta.undo) {
3620 return state;
3621 } // Transient edits don't create an undo level, but are
3622 // reachable in the next meaningful edit to which they
3623 // are merged. They are defined in the entity's config.
3624
3625
3626 if (!isCreateUndoLevel && !Object.keys(action.edits).some(key => !action.transientEdits[key])) {
3627 // @ts-ignore we might consider using Object.assign({}, state)
3628 nextState = [...state];
3629 nextState.flattenedUndo = { ...state.flattenedUndo,
3630 ...action.edits
3631 };
3632 nextState.offset = state.offset;
3633 return nextState;
3634 } // Clear potential redos, because this only supports linear history.
3635
3636
3637 nextState = // @ts-ignore this needs additional cleanup, probably involving code-level changes
3638 nextState || state.slice(0, state.offset || undefined);
3639 nextState.offset = nextState.offset || 0;
3640 nextState.pop();
3641
3642 if (!isCreateUndoLevel) {
3643 nextState.push({
3644 kind: action.meta.undo.kind,
3645 name: action.meta.undo.name,
3646 recordId: action.meta.undo.recordId,
3647 edits: { ...state.flattenedUndo,
3648 ...action.meta.undo.edits
3649 }
3650 });
3651 } // When an edit is a function it's an optimization to avoid running some expensive operation.
3652 // We can't rely on the function references being the same so we opt out of comparing them here.
3653
3654
3655 const comparisonUndoEdits = Object.values(action.meta.undo.edits).filter(edit => typeof edit !== 'function');
3656 const comparisonEdits = Object.values(action.edits).filter(edit => typeof edit !== 'function');
3657
3658 if (!external_wp_isShallowEqual_default()(comparisonUndoEdits, comparisonEdits)) {
3659 nextState.push({
3660 kind: action.kind,
3661 name: action.name,
3662 recordId: action.recordId,
3663 edits: isCreateUndoLevel ? { ...state.flattenedUndo,
3664 ...action.edits
3665 } : action.edits
3666 });
3667 }
3668
3669 return nextState;
3670 }
3671
3672 return state;
3673 }
3674 /**
3675 * Reducer managing embed preview data.
3676 *
3677 * @param {Object} state Current state.
3678 * @param {Object} action Dispatched action.
3679 *
3680 * @return {Object} Updated state.
3681 */
3682
3683 function embedPreviews() {
3684 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3685 let action = arguments.length > 1 ? arguments[1] : undefined;
3686
3687 switch (action.type) {
3688 case 'RECEIVE_EMBED_PREVIEW':
3689 const {
3690 url,
3691 preview
3692 } = action;
3693 return { ...state,
3694 [url]: preview
3695 };
3696 }
3697
3698 return state;
3699 }
3700 /**
3701 * State which tracks whether the user can perform an action on a REST
3702 * resource.
3703 *
3704 * @param {Object} state Current state.
3705 * @param {Object} action Dispatched action.
3706 *
3707 * @return {Object} Updated state.
3708 */
3709
3710 function userPermissions() {
3711 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3712 let action = arguments.length > 1 ? arguments[1] : undefined;
3713
3714 switch (action.type) {
3715 case 'RECEIVE_USER_PERMISSION':
3716 return { ...state,
3717 [action.key]: action.isAllowed
3718 };
3719 }
3720
3721 return state;
3722 }
3723 /**
3724 * Reducer returning autosaves keyed by their parent's post id.
3725 *
3726 * @param {Object} state Current state.
3727 * @param {Object} action Dispatched action.
3728 *
3729 * @return {Object} Updated state.
3730 */
3731
3732 function autosaves() {
3733 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3734 let action = arguments.length > 1 ? arguments[1] : undefined;
3735
3736 switch (action.type) {
3737 case 'RECEIVE_AUTOSAVES':
3738 const {
3739 postId,
3740 autosaves: autosavesData
3741 } = action;
3742 return { ...state,
3743 [postId]: autosavesData
3744 };
3745 }
3746
3747 return state;
3748 }
3749 function blockPatterns() {
3750 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3751 let action = arguments.length > 1 ? arguments[1] : undefined;
3752
3753 switch (action.type) {
3754 case 'RECEIVE_BLOCK_PATTERNS':
3755 return action.patterns;
3756 }
3757
3758 return state;
3759 }
3760 function blockPatternCategories() {
3761 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3762 let action = arguments.length > 1 ? arguments[1] : undefined;
3763
3764 switch (action.type) {
3765 case 'RECEIVE_BLOCK_PATTERN_CATEGORIES':
3766 return action.categories;
3767 }
3768
3769 return state;
3770 }
3771 /* harmony default export */ var build_module_reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
3772 terms,
3773 users,
3774 currentTheme,
3775 currentGlobalStylesId,
3776 currentUser,
3777 themeGlobalStyleVariations,
3778 themeBaseGlobalStyles,
3779 taxonomies,
3780 entities,
3781 undo: reducer_undo,
3782 embedPreviews,
3783 userPermissions,
3784 autosaves,
3785 blockPatterns,
3786 blockPatternCategories
3787 }));
3788
3789 ;// CONCATENATED MODULE: ./node_modules/rememo/es/rememo.js
3790
3791
3792 /** @typedef {(...args: any[]) => *[]} GetDependants */
3793
3794 /** @typedef {() => void} Clear */
3795
3796 /**
3797 * @typedef {{
3798 * getDependants: GetDependants,
3799 * clear: Clear
3800 * }} EnhancedSelector
3801 */
3802
3803 /**
3804 * Internal cache entry.
3805 *
3806 * @typedef CacheNode
3807 *
3808 * @property {?CacheNode|undefined} [prev] Previous node.
3809 * @property {?CacheNode|undefined} [next] Next node.
3810 * @property {*[]} args Function arguments for cache entry.
3811 * @property {*} val Function result.
3812 */
3813
3814 /**
3815 * @typedef Cache
3816 *
3817 * @property {Clear} clear Function to clear cache.
3818 * @property {boolean} [isUniqueByDependants] Whether dependants are valid in
3819 * considering cache uniqueness. A cache is unique if dependents are all arrays
3820 * or objects.
3821 * @property {CacheNode?} [head] Cache head.
3822 * @property {*[]} [lastDependants] Dependants from previous invocation.
3823 */
3824
3825 /**
3826 * Arbitrary value used as key for referencing cache object in WeakMap tree.
3827 *
3828 * @type {{}}
3829 */
3830 var LEAF_KEY = {};
3831
3832 /**
3833 * Returns the first argument as the sole entry in an array.
3834 *
3835 * @template T
3836 *
3837 * @param {T} value Value to return.
3838 *
3839 * @return {[T]} Value returned as entry in array.
3840 */
3841 function arrayOf(value) {
3842 return [value];
3843 }
3844
3845 /**
3846 * Returns true if the value passed is object-like, or false otherwise. A value
3847 * is object-like if it can support property assignment, e.g. object or array.
3848 *
3849 * @param {*} value Value to test.
3850 *
3851 * @return {boolean} Whether value is object-like.
3852 */
3853 function isObjectLike(value) {
3854 return !!value && 'object' === typeof value;
3855 }
3856
3857 /**
3858 * Creates and returns a new cache object.
3859 *
3860 * @return {Cache} Cache object.
3861 */
3862 function createCache() {
3863 /** @type {Cache} */
3864 var cache = {
3865 clear: function () {
3866 cache.head = null;
3867 },
3868 };
3869
3870 return cache;
3871 }
3872
3873 /**
3874 * Returns true if entries within the two arrays are strictly equal by
3875 * reference from a starting index.
3876 *
3877 * @param {*[]} a First array.
3878 * @param {*[]} b Second array.
3879 * @param {number} fromIndex Index from which to start comparison.
3880 *
3881 * @return {boolean} Whether arrays are shallowly equal.
3882 */
3883 function isShallowEqual(a, b, fromIndex) {
3884 var i;
3885
3886 if (a.length !== b.length) {
3887 return false;
3888 }
3889
3890 for (i = fromIndex; i < a.length; i++) {
3891 if (a[i] !== b[i]) {
3892 return false;
3893 }
3894 }
3895
3896 return true;
3897 }
3898
3899 /**
3900 * Returns a memoized selector function. The getDependants function argument is
3901 * called before the memoized selector and is expected to return an immutable
3902 * reference or array of references on which the selector depends for computing
3903 * its own return value. The memoize cache is preserved only as long as those
3904 * dependant references remain the same. If getDependants returns a different
3905 * reference(s), the cache is cleared and the selector value regenerated.
3906 *
3907 * @template {(...args: *[]) => *} S
3908 *
3909 * @param {S} selector Selector function.
3910 * @param {GetDependants=} getDependants Dependant getter returning an array of
3911 * references used in cache bust consideration.
3912 */
3913 /* harmony default export */ function rememo(selector, getDependants) {
3914 /** @type {WeakMap<*,*>} */
3915 var rootCache;
3916
3917 /** @type {GetDependants} */
3918 var normalizedGetDependants = getDependants ? getDependants : arrayOf;
3919
3920 /**
3921 * Returns the cache for a given dependants array. When possible, a WeakMap
3922 * will be used to create a unique cache for each set of dependants. This
3923 * is feasible due to the nature of WeakMap in allowing garbage collection
3924 * to occur on entries where the key object is no longer referenced. Since
3925 * WeakMap requires the key to be an object, this is only possible when the
3926 * dependant is object-like. The root cache is created as a hierarchy where
3927 * each top-level key is the first entry in a dependants set, the value a
3928 * WeakMap where each key is the next dependant, and so on. This continues
3929 * so long as the dependants are object-like. If no dependants are object-
3930 * like, then the cache is shared across all invocations.
3931 *
3932 * @see isObjectLike
3933 *
3934 * @param {*[]} dependants Selector dependants.
3935 *
3936 * @return {Cache} Cache object.
3937 */
3938 function getCache(dependants) {
3939 var caches = rootCache,
3940 isUniqueByDependants = true,
3941 i,
3942 dependant,
3943 map,
3944 cache;
3945
3946 for (i = 0; i < dependants.length; i++) {
3947 dependant = dependants[i];
3948
3949 // Can only compose WeakMap from object-like key.
3950 if (!isObjectLike(dependant)) {
3951 isUniqueByDependants = false;
3952 break;
3953 }
3954
3955 // Does current segment of cache already have a WeakMap?
3956 if (caches.has(dependant)) {
3957 // Traverse into nested WeakMap.
3958 caches = caches.get(dependant);
3959 } else {
3960 // Create, set, and traverse into a new one.
3961 map = new WeakMap();
3962 caches.set(dependant, map);
3963 caches = map;
3964 }
3965 }
3966
3967 // We use an arbitrary (but consistent) object as key for the last item
3968 // in the WeakMap to serve as our running cache.
3969 if (!caches.has(LEAF_KEY)) {
3970 cache = createCache();
3971 cache.isUniqueByDependants = isUniqueByDependants;
3972 caches.set(LEAF_KEY, cache);
3973 }
3974
3975 return caches.get(LEAF_KEY);
3976 }
3977
3978 /**
3979 * Resets root memoization cache.
3980 */
3981 function clear() {
3982 rootCache = new WeakMap();
3983 }
3984
3985 /* eslint-disable jsdoc/check-param-names */
3986 /**
3987 * The augmented selector call, considering first whether dependants have
3988 * changed before passing it to underlying memoize function.
3989 *
3990 * @param {*} source Source object for derivation.
3991 * @param {...*} extraArgs Additional arguments to pass to selector.
3992 *
3993 * @return {*} Selector result.
3994 */
3995 /* eslint-enable jsdoc/check-param-names */
3996 function callSelector(/* source, ...extraArgs */) {
3997 var len = arguments.length,
3998 cache,
3999 node,
4000 i,
4001 args,
4002 dependants;
4003
4004 // Create copy of arguments (avoid leaking deoptimization).
4005 args = new Array(len);
4006 for (i = 0; i < len; i++) {
4007 args[i] = arguments[i];
4008 }
4009
4010 dependants = normalizedGetDependants.apply(null, args);
4011 cache = getCache(dependants);
4012
4013 // If not guaranteed uniqueness by dependants (primitive type), shallow
4014 // compare against last dependants and, if references have changed,
4015 // destroy cache to recalculate result.
4016 if (!cache.isUniqueByDependants) {
4017 if (
4018 cache.lastDependants &&
4019 !isShallowEqual(dependants, cache.lastDependants, 0)
4020 ) {
4021 cache.clear();
4022 }
4023
4024 cache.lastDependants = dependants;
4025 }
4026
4027 node = cache.head;
4028 while (node) {
4029 // Check whether node arguments match arguments
4030 if (!isShallowEqual(node.args, args, 1)) {
4031 node = node.next;
4032 continue;
4033 }
4034
4035 // At this point we can assume we've found a match
4036
4037 // Surface matched node to head if not already
4038 if (node !== cache.head) {
4039 // Adjust siblings to point to each other.
4040 /** @type {CacheNode} */ (node.prev).next = node.next;
4041 if (node.next) {
4042 node.next.prev = node.prev;
4043 }
4044
4045 node.next = cache.head;
4046 node.prev = null;
4047 /** @type {CacheNode} */ (cache.head).prev = node;
4048 cache.head = node;
4049 }
4050
4051 // Return immediately
4052 return node.val;
4053 }
4054
4055 // No cached value found. Continue to insertion phase:
4056
4057 node = /** @type {CacheNode} */ ({
4058 // Generate the result from original function
4059 val: selector.apply(null, args),
4060 });
4061
4062 // Avoid including the source object in the cache.
4063 args[0] = null;
4064 node.args = args;
4065
4066 // Don't need to check whether node is already head, since it would
4067 // have been returned above already if it was
4068
4069 // Shift existing head down list
4070 if (cache.head) {
4071 cache.head.prev = node;
4072 node.next = cache.head;
4073 }
4074
4075 cache.head = node;
4076
4077 return node.val;
4078 }
4079
4080 callSelector.getDependants = normalizedGetDependants;
4081 callSelector.clear = clear;
4082 clear();
4083
4084 return /** @type {S & EnhancedSelector} */ (callSelector);
4085 }
4086
4087 // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js
4088 var equivalent_key_map = __webpack_require__(2167);
4089 var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map);
4090 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/selectors.js
4091 /**
4092 * External dependencies
4093 */
4094
4095
4096
4097 /**
4098 * Internal dependencies
4099 */
4100
4101
4102 /**
4103 * Cache of state keys to EquivalentKeyMap where the inner map tracks queries
4104 * to their resulting items set. WeakMap allows garbage collection on expired
4105 * state references.
4106 *
4107 * @type {WeakMap<Object,EquivalentKeyMap>}
4108 */
4109
4110 const queriedItemsCacheByState = new WeakMap();
4111 /**
4112 * Returns items for a given query, or null if the items are not known.
4113 *
4114 * @param {Object} state State object.
4115 * @param {?Object} query Optional query.
4116 *
4117 * @return {?Array} Query items.
4118 */
4119
4120 function getQueriedItemsUncached(state, query) {
4121 var _state$queries, _state$queries$contex;
4122
4123 const {
4124 stableKey,
4125 page,
4126 perPage,
4127 include,
4128 fields,
4129 context
4130 } = get_query_parts(query);
4131 let itemIds;
4132
4133 if ((_state$queries = state.queries) !== null && _state$queries !== void 0 && (_state$queries$contex = _state$queries[context]) !== null && _state$queries$contex !== void 0 && _state$queries$contex[stableKey]) {
4134 itemIds = state.queries[context][stableKey];
4135 }
4136
4137 if (!itemIds) {
4138 return null;
4139 }
4140
4141 const startOffset = perPage === -1 ? 0 : (page - 1) * perPage;
4142 const endOffset = perPage === -1 ? itemIds.length : Math.min(startOffset + perPage, itemIds.length);
4143 const items = [];
4144
4145 for (let i = startOffset; i < endOffset; i++) {
4146 var _state$items$context;
4147
4148 const itemId = itemIds[i];
4149
4150 if (Array.isArray(include) && !include.includes(itemId)) {
4151 continue;
4152 } // Having a target item ID doesn't guarantee that this object has been queried.
4153
4154
4155 if (!((_state$items$context = state.items[context]) !== null && _state$items$context !== void 0 && _state$items$context.hasOwnProperty(itemId))) {
4156 return null;
4157 }
4158
4159 const item = state.items[context][itemId];
4160 let filteredItem;
4161
4162 if (Array.isArray(fields)) {
4163 filteredItem = {};
4164
4165 for (let f = 0; f < fields.length; f++) {
4166 const field = fields[f].split('.');
4167 const value = (0,external_lodash_namespaceObject.get)(item, field);
4168 (0,external_lodash_namespaceObject.set)(filteredItem, field, value);
4169 }
4170 } else {
4171 var _state$itemIsComplete;
4172
4173 // If expecting a complete item, validate that completeness, or
4174 // otherwise abort.
4175 if (!((_state$itemIsComplete = state.itemIsComplete[context]) !== null && _state$itemIsComplete !== void 0 && _state$itemIsComplete[itemId])) {
4176 return null;
4177 }
4178
4179 filteredItem = item;
4180 }
4181
4182 items.push(filteredItem);
4183 }
4184
4185 return items;
4186 }
4187 /**
4188 * Returns items for a given query, or null if the items are not known. Caches
4189 * result both per state (by reference) and per query (by deep equality).
4190 * The caching approach is intended to be durable to query objects which are
4191 * deeply but not referentially equal, since otherwise:
4192 *
4193 * `getQueriedItems( state, {} ) !== getQueriedItems( state, {} )`
4194 *
4195 * @param {Object} state State object.
4196 * @param {?Object} query Optional query.
4197 *
4198 * @return {?Array} Query items.
4199 */
4200
4201
4202 const getQueriedItems = rememo(function (state) {
4203 let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4204 let queriedItemsCache = queriedItemsCacheByState.get(state);
4205
4206 if (queriedItemsCache) {
4207 const queriedItems = queriedItemsCache.get(query);
4208
4209 if (queriedItems !== undefined) {
4210 return queriedItems;
4211 }
4212 } else {
4213 queriedItemsCache = new (equivalent_key_map_default())();
4214 queriedItemsCacheByState.set(state, queriedItemsCache);
4215 }
4216
4217 const items = getQueriedItemsUncached(state, query);
4218 queriedItemsCache.set(query, items);
4219 return items;
4220 });
4221
4222 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/is-raw-attribute.js
4223 /**
4224 * Checks whether the attribute is a "raw" attribute or not.
4225 *
4226 * @param {Object} entity Entity record.
4227 * @param {string} attribute Attribute name.
4228 *
4229 * @return {boolean} Is the attribute raw
4230 */
4231 function isRawAttribute(entity, attribute) {
4232 return (entity.rawAttributes || []).includes(attribute);
4233 }
4234
4235 ;// CONCATENATED MODULE: ./packages/core-data/build-module/selectors.js
4236 /**
4237 * External dependencies
4238 */
4239
4240
4241 /**
4242 * WordPress dependencies
4243 */
4244
4245
4246
4247
4248 /**
4249 * Internal dependencies
4250 */
4251
4252
4253
4254
4255
4256
4257 /**
4258 * Shared reference to an empty object for cases where it is important to avoid
4259 * returning a new object reference on every invocation, as in a connected or
4260 * other pure component which performs `shouldComponentUpdate` check on props.
4261 * This should be used as a last resort, since the normalized data should be
4262 * maintained by the reducer result in state.
4263 */
4264 const EMPTY_OBJECT = {};
4265 /**
4266 * Returns true if a request is in progress for embed preview data, or false
4267 * otherwise.
4268 *
4269 * @param state Data state.
4270 * @param url URL the preview would be for.
4271 *
4272 * @return Whether a request is in progress for an embed preview.
4273 */
4274
4275 const isRequestingEmbedPreview = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, url) => {
4276 return select(STORE_NAME).isResolving('getEmbedPreview', [url]);
4277 });
4278 /**
4279 * Returns all available authors.
4280 *
4281 * @deprecated since 11.3. Callers should use `select( 'core' ).getUsers({ who: 'authors' })` instead.
4282 *
4283 * @param state Data state.
4284 * @param query Optional object of query parameters to
4285 * include with request.
4286 * @return Authors list.
4287 */
4288
4289 function getAuthors(state, query) {
4290 external_wp_deprecated_default()("select( 'core' ).getAuthors()", {
4291 since: '5.9',
4292 alternative: "select( 'core' ).getUsers({ who: 'authors' })"
4293 });
4294 const path = (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/users/?who=authors&per_page=100', query);
4295 return getUserQueryResults(state, path);
4296 }
4297 /**
4298 * Returns the current user.
4299 *
4300 * @param state Data state.
4301 *
4302 * @return Current user object.
4303 */
4304
4305 function getCurrentUser(state) {
4306 return state.currentUser;
4307 }
4308 /**
4309 * Returns all the users returned by a query ID.
4310 *
4311 * @param state Data state.
4312 * @param queryID Query ID.
4313 *
4314 * @return Users list.
4315 */
4316
4317 const getUserQueryResults = rememo((state, queryID) => {
4318 const queryResults = state.users.queries[queryID];
4319 return (0,external_lodash_namespaceObject.map)(queryResults, id => state.users.byId[id]);
4320 }, (state, queryID) => [state.users.queries[queryID], state.users.byId]);
4321 /**
4322 * Returns the loaded entities for the given kind.
4323 *
4324 * @deprecated since WordPress 6.0. Use getEntitiesConfig instead
4325 * @param state Data state.
4326 * @param kind Entity kind.
4327 *
4328 * @return Array of entities with config matching kind.
4329 */
4330
4331 function getEntitiesByKind(state, kind) {
4332 external_wp_deprecated_default()("wp.data.select( 'core' ).getEntitiesByKind()", {
4333 since: '6.0',
4334 alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
4335 });
4336 return getEntitiesConfig(state, kind);
4337 }
4338 /**
4339 * Returns the loaded entities for the given kind.
4340 *
4341 * @param state Data state.
4342 * @param kind Entity kind.
4343 *
4344 * @return Array of entities with config matching kind.
4345 */
4346
4347 function getEntitiesConfig(state, kind) {
4348 return state.entities.config.filter(entity => entity.kind === kind);
4349 }
4350 /**
4351 * Returns the entity config given its kind and name.
4352 *
4353 * @deprecated since WordPress 6.0. Use getEntityConfig instead
4354 * @param state Data state.
4355 * @param kind Entity kind.
4356 * @param name Entity name.
4357 *
4358 * @return Entity config
4359 */
4360
4361 function getEntity(state, kind, name) {
4362 external_wp_deprecated_default()("wp.data.select( 'core' ).getEntity()", {
4363 since: '6.0',
4364 alternative: "wp.data.select( 'core' ).getEntityConfig()"
4365 });
4366 return getEntityConfig(state, kind, name);
4367 }
4368 /**
4369 * Returns the entity config given its kind and name.
4370 *
4371 * @param state Data state.
4372 * @param kind Entity kind.
4373 * @param name Entity name.
4374 *
4375 * @return Entity config
4376 */
4377
4378 function getEntityConfig(state, kind, name) {
4379 return (0,external_lodash_namespaceObject.find)(state.entities.config, {
4380 kind,
4381 name
4382 });
4383 }
4384 /**
4385 * GetEntityRecord is declared as a *callable interface* with
4386 * two signatures to work around the fact that TypeScript doesn't
4387 * allow currying generic functions:
4388 *
4389 * ```ts
4390 * type CurriedState = F extends ( state: any, ...args: infer P ) => infer R
4391 * ? ( ...args: P ) => R
4392 * : F;
4393 * type Selector = <K extends string | number>(
4394 * state: any,
4395 * kind: K,
4396 * key: K extends string ? 'string value' : false
4397 * ) => K;
4398 * type BadlyInferredSignature = CurriedState< Selector >
4399 * // BadlyInferredSignature evaluates to:
4400 * // (kind: string number, key: false | "string value") => string number
4401 * ```
4402 *
4403 * The signature without the state parameter shipped as CurriedSignature
4404 * is used in the return value of `select( coreStore )`.
4405 *
4406 * See https://github.com/WordPress/gutenberg/pull/41578 for more details.
4407 */
4408
4409 /**
4410 * Returns the Entity's record object by key. Returns `null` if the value is not
4411 * yet received, undefined if the value entity is known to not exist, or the
4412 * entity object if it exists and is received.
4413 *
4414 * @param state State tree
4415 * @param kind Entity kind.
4416 * @param name Entity name.
4417 * @param key Record's key
4418 * @param query Optional query. If requesting specific
4419 * fields, fields must always include the ID.
4420 *
4421 * @return Record.
4422 */
4423 const getEntityRecord = rememo((state, kind, name, key, query) => {
4424 var _query$context, _queriedState$items$c;
4425
4426 const queriedState = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData']);
4427
4428 if (!queriedState) {
4429 return undefined;
4430 }
4431
4432 const context = (_query$context = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context !== void 0 ? _query$context : 'default';
4433
4434 if (query === undefined) {
4435 var _queriedState$itemIsC;
4436
4437 // If expecting a complete item, validate that completeness.
4438 if (!((_queriedState$itemIsC = queriedState.itemIsComplete[context]) !== null && _queriedState$itemIsC !== void 0 && _queriedState$itemIsC[key])) {
4439 return undefined;
4440 }
4441
4442 return queriedState.items[context][key];
4443 }
4444
4445 const item = (_queriedState$items$c = queriedState.items[context]) === null || _queriedState$items$c === void 0 ? void 0 : _queriedState$items$c[key];
4446
4447 if (item && query._fields) {
4448 var _getNormalizedCommaSe;
4449
4450 const filteredItem = {};
4451 const fields = (_getNormalizedCommaSe = get_normalized_comma_separable(query._fields)) !== null && _getNormalizedCommaSe !== void 0 ? _getNormalizedCommaSe : [];
4452
4453 for (let f = 0; f < fields.length; f++) {
4454 const field = fields[f].split('.');
4455 const value = (0,external_lodash_namespaceObject.get)(item, field);
4456 (0,external_lodash_namespaceObject.set)(filteredItem, field, value);
4457 }
4458
4459 return filteredItem;
4460 }
4461
4462 return item;
4463 }, (state, kind, name, recordId, query) => {
4464 var _query$context2;
4465
4466 const context = (_query$context2 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context2 !== void 0 ? _query$context2 : 'default';
4467 return [(0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId])];
4468 });
4469 /**
4470 * Returns the Entity's record object by key. Doesn't trigger a resolver nor requests the entity records from the API if the entity record isn't available in the local state.
4471 *
4472 * @param state State tree
4473 * @param kind Entity kind.
4474 * @param name Entity name.
4475 * @param key Record's key
4476 *
4477 * @return Record.
4478 */
4479
4480 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
4481 return getEntityRecord(state, kind, name, key);
4482 }
4483 /**
4484 * Returns the entity's record object by key,
4485 * with its attributes mapped to their raw values.
4486 *
4487 * @param state State tree.
4488 * @param kind Entity kind.
4489 * @param name Entity name.
4490 * @param key Record's key.
4491 *
4492 * @return Object with the entity's raw attributes.
4493 */
4494
4495 const getRawEntityRecord = rememo((state, kind, name, key) => {
4496 const record = getEntityRecord(state, kind, name, key);
4497 return record && Object.keys(record).reduce((accumulator, _key) => {
4498 if (isRawAttribute(getEntityConfig(state, kind, name), _key)) {
4499 // Because edits are the "raw" attribute values,
4500 // we return those from record selectors to make rendering,
4501 // comparisons, and joins with edits easier.
4502 accumulator[_key] = (0,external_lodash_namespaceObject.get)(record[_key], 'raw', record[_key]);
4503 } else {
4504 accumulator[_key] = record[_key];
4505 }
4506
4507 return accumulator;
4508 }, {});
4509 }, (state, kind, name, recordId, query) => {
4510 var _query$context3;
4511
4512 const context = (_query$context3 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context3 !== void 0 ? _query$context3 : 'default';
4513 return [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId])];
4514 });
4515 /**
4516 * Returns true if records have been received for the given set of parameters,
4517 * or false otherwise.
4518 *
4519 * @param state State tree
4520 * @param kind Entity kind.
4521 * @param name Entity name.
4522 * @param query Optional terms query.
4523 *
4524 * @return Whether entity records have been received.
4525 */
4526
4527 function hasEntityRecords(state, kind, name, query) {
4528 return Array.isArray(getEntityRecords(state, kind, name, query));
4529 }
4530 /**
4531 * GetEntityRecord is declared as a *callable interface* with
4532 * two signatures to work around the fact that TypeScript doesn't
4533 * allow currying generic functions.
4534 *
4535 * @see GetEntityRecord
4536 * @see https://github.com/WordPress/gutenberg/pull/41578
4537 */
4538
4539 /**
4540 * Returns the Entity's records.
4541 *
4542 * @param state State tree
4543 * @param kind Entity kind.
4544 * @param name Entity name.
4545 * @param query Optional terms query. If requesting specific
4546 * fields, fields must always include the ID.
4547 *
4548 * @return Records.
4549 */
4550 const getEntityRecords = (state, kind, name, query) => {
4551 // Queried data state is prepopulated for all known entities. If this is not
4552 // assigned for the given parameters, then it is known to not exist.
4553 const queriedState = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData']);
4554
4555 if (!queriedState) {
4556 return null;
4557 }
4558
4559 return getQueriedItems(queriedState, query);
4560 };
4561
4562 /**
4563 * Returns the list of dirty entity records.
4564 *
4565 * @param state State tree.
4566 *
4567 * @return The list of updated records
4568 */
4569 const __experimentalGetDirtyEntityRecords = rememo(state => {
4570 const {
4571 entities: {
4572 records
4573 }
4574 } = state;
4575 const dirtyRecords = [];
4576 Object.keys(records).forEach(kind => {
4577 Object.keys(records[kind]).forEach(name => {
4578 const primaryKeys = Object.keys(records[kind][name].edits).filter(primaryKey => // The entity record must exist (not be deleted),
4579 // and it must have edits.
4580 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey));
4581
4582 if (primaryKeys.length) {
4583 const entityConfig = getEntityConfig(state, kind, name);
4584 primaryKeys.forEach(primaryKey => {
4585 var _entityConfig$getTitl;
4586
4587 const entityRecord = getEditedEntityRecord(state, kind, name, primaryKey);
4588 dirtyRecords.push({
4589 // We avoid using primaryKey because it's transformed into a string
4590 // when it's used as an object key.
4591 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : undefined,
4592 title: (entityConfig === null || entityConfig === void 0 ? void 0 : (_entityConfig$getTitl = entityConfig.getTitle) === null || _entityConfig$getTitl === void 0 ? void 0 : _entityConfig$getTitl.call(entityConfig, entityRecord)) || '',
4593 name,
4594 kind
4595 });
4596 });
4597 }
4598 });
4599 });
4600 return dirtyRecords;
4601 }, state => [state.entities.records]);
4602 /**
4603 * Returns the list of entities currently being saved.
4604 *
4605 * @param state State tree.
4606 *
4607 * @return The list of records being saved.
4608 */
4609
4610 const __experimentalGetEntitiesBeingSaved = rememo(state => {
4611 const {
4612 entities: {
4613 records
4614 }
4615 } = state;
4616 const recordsBeingSaved = [];
4617 Object.keys(records).forEach(kind => {
4618 Object.keys(records[kind]).forEach(name => {
4619 const primaryKeys = Object.keys(records[kind][name].saving).filter(primaryKey => isSavingEntityRecord(state, kind, name, primaryKey));
4620
4621 if (primaryKeys.length) {
4622 const entityConfig = getEntityConfig(state, kind, name);
4623 primaryKeys.forEach(primaryKey => {
4624 var _entityConfig$getTitl2;
4625
4626 const entityRecord = getEditedEntityRecord(state, kind, name, primaryKey);
4627 recordsBeingSaved.push({
4628 // We avoid using primaryKey because it's transformed into a string
4629 // when it's used as an object key.
4630 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : undefined,
4631 title: (entityConfig === null || entityConfig === void 0 ? void 0 : (_entityConfig$getTitl2 = entityConfig.getTitle) === null || _entityConfig$getTitl2 === void 0 ? void 0 : _entityConfig$getTitl2.call(entityConfig, entityRecord)) || '',
4632 name,
4633 kind
4634 });
4635 });
4636 }
4637 });
4638 });
4639 return recordsBeingSaved;
4640 }, state => [state.entities.records]);
4641 /**
4642 * Returns the specified entity record's edits.
4643 *
4644 * @param state State tree.
4645 * @param kind Entity kind.
4646 * @param name Entity name.
4647 * @param recordId Record ID.
4648 *
4649 * @return The entity record's edits.
4650 */
4651
4652 function getEntityRecordEdits(state, kind, name, recordId) {
4653 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId]);
4654 }
4655 /**
4656 * Returns the specified entity record's non transient edits.
4657 *
4658 * Transient edits don't create an undo level, and
4659 * are not considered for change detection.
4660 * They are defined in the entity's config.
4661 *
4662 * @param state State tree.
4663 * @param kind Entity kind.
4664 * @param name Entity name.
4665 * @param recordId Record ID.
4666 *
4667 * @return The entity record's non transient edits.
4668 */
4669
4670 const getEntityRecordNonTransientEdits = rememo((state, kind, name, recordId) => {
4671 const {
4672 transientEdits
4673 } = getEntityConfig(state, kind, name) || {};
4674 const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
4675
4676 if (!transientEdits) {
4677 return edits;
4678 }
4679
4680 return Object.keys(edits).reduce((acc, key) => {
4681 if (!transientEdits[key]) {
4682 acc[key] = edits[key];
4683 }
4684
4685 return acc;
4686 }, {});
4687 }, (state, kind, name, recordId) => [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId])]);
4688 /**
4689 * Returns true if the specified entity record has edits,
4690 * and false otherwise.
4691 *
4692 * @param state State tree.
4693 * @param kind Entity kind.
4694 * @param name Entity name.
4695 * @param recordId Record ID.
4696 *
4697 * @return Whether the entity record has edits or not.
4698 */
4699
4700 function hasEditsForEntityRecord(state, kind, name, recordId) {
4701 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(getEntityRecordNonTransientEdits(state, kind, name, recordId)).length > 0;
4702 }
4703 /**
4704 * Returns the specified entity record, merged with its edits.
4705 *
4706 * @param state State tree.
4707 * @param kind Entity kind.
4708 * @param name Entity name.
4709 * @param recordId Record ID.
4710 *
4711 * @return The entity record, merged with its edits.
4712 */
4713
4714 const getEditedEntityRecord = rememo((state, kind, name, recordId) => ({ ...getRawEntityRecord(state, kind, name, recordId),
4715 ...getEntityRecordEdits(state, kind, name, recordId)
4716 }), (state, kind, name, recordId, query) => {
4717 var _query$context4;
4718
4719 const context = (_query$context4 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context4 !== void 0 ? _query$context4 : 'default';
4720 return [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId])];
4721 });
4722 /**
4723 * Returns true if the specified entity record is autosaving, and false otherwise.
4724 *
4725 * @param state State tree.
4726 * @param kind Entity kind.
4727 * @param name Entity name.
4728 * @param recordId Record ID.
4729 *
4730 * @return Whether the entity record is autosaving or not.
4731 */
4732
4733 function isAutosavingEntityRecord(state, kind, name, recordId) {
4734 const {
4735 pending,
4736 isAutosave
4737 } = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId], {});
4738 return Boolean(pending && isAutosave);
4739 }
4740 /**
4741 * Returns true if the specified entity record is saving, and false otherwise.
4742 *
4743 * @param state State tree.
4744 * @param kind Entity kind.
4745 * @param name Entity name.
4746 * @param recordId Record ID.
4747 *
4748 * @return Whether the entity record is saving or not.
4749 */
4750
4751 function isSavingEntityRecord(state, kind, name, recordId) {
4752 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId, 'pending'], false);
4753 }
4754 /**
4755 * Returns true if the specified entity record is deleting, and false otherwise.
4756 *
4757 * @param state State tree.
4758 * @param kind Entity kind.
4759 * @param name Entity name.
4760 * @param recordId Record ID.
4761 *
4762 * @return Whether the entity record is deleting or not.
4763 */
4764
4765 function isDeletingEntityRecord(state, kind, name, recordId) {
4766 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'deleting', recordId, 'pending'], false);
4767 }
4768 /**
4769 * Returns the specified entity record's last save error.
4770 *
4771 * @param state State tree.
4772 * @param kind Entity kind.
4773 * @param name Entity name.
4774 * @param recordId Record ID.
4775 *
4776 * @return The entity record's save error.
4777 */
4778
4779 function getLastEntitySaveError(state, kind, name, recordId) {
4780 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId, 'error']);
4781 }
4782 /**
4783 * Returns the specified entity record's last delete error.
4784 *
4785 * @param state State tree.
4786 * @param kind Entity kind.
4787 * @param name Entity name.
4788 * @param recordId Record ID.
4789 *
4790 * @return The entity record's save error.
4791 */
4792
4793 function getLastEntityDeleteError(state, kind, name, recordId) {
4794 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'deleting', recordId, 'error']);
4795 }
4796 /**
4797 * Returns the current undo offset for the
4798 * entity records edits history. The offset
4799 * represents how many items from the end
4800 * of the history stack we are at. 0 is the
4801 * last edit, -1 is the second last, and so on.
4802 *
4803 * @param state State tree.
4804 *
4805 * @return The current undo offset.
4806 */
4807
4808 function getCurrentUndoOffset(state) {
4809 return state.undo.offset;
4810 }
4811 /**
4812 * Returns the previous edit from the current undo offset
4813 * for the entity records edits history, if any.
4814 *
4815 * @param state State tree.
4816 *
4817 * @return The edit.
4818 */
4819
4820
4821 function getUndoEdit(state) {
4822 return state.undo[state.undo.length - 2 + getCurrentUndoOffset(state)];
4823 }
4824 /**
4825 * Returns the next edit from the current undo offset
4826 * for the entity records edits history, if any.
4827 *
4828 * @param state State tree.
4829 *
4830 * @return The edit.
4831 */
4832
4833 function getRedoEdit(state) {
4834 return state.undo[state.undo.length + getCurrentUndoOffset(state)];
4835 }
4836 /**
4837 * Returns true if there is a previous edit from the current undo offset
4838 * for the entity records edits history, and false otherwise.
4839 *
4840 * @param state State tree.
4841 *
4842 * @return Whether there is a previous edit or not.
4843 */
4844
4845 function hasUndo(state) {
4846 return Boolean(getUndoEdit(state));
4847 }
4848 /**
4849 * Returns true if there is a next edit from the current undo offset
4850 * for the entity records edits history, and false otherwise.
4851 *
4852 * @param state State tree.
4853 *
4854 * @return Whether there is a next edit or not.
4855 */
4856
4857 function hasRedo(state) {
4858 return Boolean(getRedoEdit(state));
4859 }
4860 /**
4861 * Return the current theme.
4862 *
4863 * @param state Data state.
4864 *
4865 * @return The current theme.
4866 */
4867
4868 function getCurrentTheme(state) {
4869 return getEntityRecord(state, 'root', 'theme', state.currentTheme);
4870 }
4871 /**
4872 * Return the ID of the current global styles object.
4873 *
4874 * @param state Data state.
4875 *
4876 * @return The current global styles ID.
4877 */
4878
4879 function __experimentalGetCurrentGlobalStylesId(state) {
4880 return state.currentGlobalStylesId;
4881 }
4882 /**
4883 * Return theme supports data in the index.
4884 *
4885 * @param state Data state.
4886 *
4887 * @return Index data.
4888 */
4889
4890 function getThemeSupports(state) {
4891 var _getCurrentTheme$them, _getCurrentTheme;
4892
4893 return (_getCurrentTheme$them = (_getCurrentTheme = getCurrentTheme(state)) === null || _getCurrentTheme === void 0 ? void 0 : _getCurrentTheme.theme_supports) !== null && _getCurrentTheme$them !== void 0 ? _getCurrentTheme$them : EMPTY_OBJECT;
4894 }
4895 /**
4896 * Returns the embed preview for the given URL.
4897 *
4898 * @param state Data state.
4899 * @param url Embedded URL.
4900 *
4901 * @return Undefined if the preview has not been fetched, otherwise, the preview fetched from the embed preview API.
4902 */
4903
4904 function getEmbedPreview(state, url) {
4905 return state.embedPreviews[url];
4906 }
4907 /**
4908 * Determines if the returned preview is an oEmbed link fallback.
4909 *
4910 * WordPress can be configured to return a simple link to a URL if it is not embeddable.
4911 * We need to be able to determine if a URL is embeddable or not, based on what we
4912 * get back from the oEmbed preview API.
4913 *
4914 * @param state Data state.
4915 * @param url Embedded URL.
4916 *
4917 * @return Is the preview for the URL an oEmbed link fallback.
4918 */
4919
4920 function isPreviewEmbedFallback(state, url) {
4921 const preview = state.embedPreviews[url];
4922 const oEmbedLinkCheck = '<a href="' + url + '">' + url + '</a>';
4923
4924 if (!preview) {
4925 return false;
4926 }
4927
4928 return preview.html === oEmbedLinkCheck;
4929 }
4930 /**
4931 * Returns whether the current user can perform the given action on the given
4932 * REST resource.
4933 *
4934 * Calling this may trigger an OPTIONS request to the REST API via the
4935 * `canUser()` resolver.
4936 *
4937 * https://developer.wordpress.org/rest-api/reference/
4938 *
4939 * @param state Data state.
4940 * @param action Action to check. One of: 'create', 'read', 'update', 'delete'.
4941 * @param resource REST resource to check, e.g. 'media' or 'posts'.
4942 * @param id Optional ID of the rest resource to check.
4943 *
4944 * @return Whether or not the user can perform the action,
4945 * or `undefined` if the OPTIONS request is still being made.
4946 */
4947
4948 function canUser(state, action, resource, id) {
4949 const key = [action, resource, id].filter(Boolean).join('/');
4950 return (0,external_lodash_namespaceObject.get)(state, ['userPermissions', key]);
4951 }
4952 /**
4953 * Returns whether the current user can edit the given entity.
4954 *
4955 * Calling this may trigger an OPTIONS request to the REST API via the
4956 * `canUser()` resolver.
4957 *
4958 * https://developer.wordpress.org/rest-api/reference/
4959 *
4960 * @param state Data state.
4961 * @param kind Entity kind.
4962 * @param name Entity name.
4963 * @param recordId Record's id.
4964 * @return Whether or not the user can edit,
4965 * or `undefined` if the OPTIONS request is still being made.
4966 */
4967
4968 function canUserEditEntityRecord(state, kind, name, recordId) {
4969 const entityConfig = getEntityConfig(state, kind, name);
4970
4971 if (!entityConfig) {
4972 return false;
4973 }
4974
4975 const resource = entityConfig.__unstable_rest_base;
4976 return canUser(state, 'update', resource, recordId);
4977 }
4978 /**
4979 * Returns the latest autosaves for the post.
4980 *
4981 * May return multiple autosaves since the backend stores one autosave per
4982 * author for each post.
4983 *
4984 * @param state State tree.
4985 * @param postType The type of the parent post.
4986 * @param postId The id of the parent post.
4987 *
4988 * @return An array of autosaves for the post, or undefined if there is none.
4989 */
4990
4991 function getAutosaves(state, postType, postId) {
4992 return state.autosaves[postId];
4993 }
4994 /**
4995 * Returns the autosave for the post and author.
4996 *
4997 * @param state State tree.
4998 * @param postType The type of the parent post.
4999 * @param postId The id of the parent post.
5000 * @param authorId The id of the author.
5001 *
5002 * @return The autosave for the post and author.
5003 */
5004
5005 function getAutosave(state, postType, postId, authorId) {
5006 if (authorId === undefined) {
5007 return;
5008 }
5009
5010 const autosaves = state.autosaves[postId];
5011 return (0,external_lodash_namespaceObject.find)(autosaves, {
5012 author: authorId
5013 });
5014 }
5015 /**
5016 * Returns true if the REST request for autosaves has completed.
5017 *
5018 * @param state State tree.
5019 * @param postType The type of the parent post.
5020 * @param postId The id of the parent post.
5021 *
5022 * @return True if the REST request was completed. False otherwise.
5023 */
5024
5025 const hasFetchedAutosaves = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, postType, postId) => {
5026 return select(STORE_NAME).hasFinishedResolution('getAutosaves', [postType, postId]);
5027 });
5028 /**
5029 * Returns a new reference when edited values have changed. This is useful in
5030 * inferring where an edit has been made between states by comparison of the
5031 * return values using strict equality.
5032 *
5033 * @example
5034 *
5035 * ```
5036 * const hasEditOccurred = (
5037 * getReferenceByDistinctEdits( beforeState ) !==
5038 * getReferenceByDistinctEdits( afterState )
5039 * );
5040 * ```
5041 *
5042 * @param state Editor state.
5043 *
5044 * @return A value whose reference will change only when an edit occurs.
5045 */
5046
5047 const getReferenceByDistinctEdits = rememo( // This unused state argument is listed here for the documentation generating tool (docgen).
5048 state => [], state => [state.undo.length, state.undo.offset, state.undo.flattenedUndo]);
5049 /**
5050 * Retrieve the frontend template used for a given link.
5051 *
5052 * @param state Editor state.
5053 * @param link Link.
5054 *
5055 * @return The template record.
5056 */
5057
5058 function __experimentalGetTemplateForLink(state, link) {
5059 const records = getEntityRecords(state, 'postType', 'wp_template', {
5060 'find-template': link
5061 });
5062
5063 if (records !== null && records !== void 0 && records.length) {
5064 return getEditedEntityRecord(state, 'postType', 'wp_template', records[0].id);
5065 }
5066
5067 return null;
5068 }
5069 /**
5070 * Retrieve the current theme's base global styles
5071 *
5072 * @param state Editor state.
5073 *
5074 * @return The Global Styles object.
5075 */
5076
5077 function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
5078 const currentTheme = getCurrentTheme(state);
5079
5080 if (!currentTheme) {
5081 return null;
5082 }
5083
5084 return state.themeBaseGlobalStyles[currentTheme.stylesheet];
5085 }
5086 /**
5087 * Return the ID of the current global styles object.
5088 *
5089 * @param state Data state.
5090 *
5091 * @return The current global styles ID.
5092 */
5093
5094 function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
5095 const currentTheme = getCurrentTheme(state);
5096
5097 if (!currentTheme) {
5098 return null;
5099 }
5100
5101 return state.themeGlobalStyleVariations[currentTheme.stylesheet];
5102 }
5103 /**
5104 * Retrieve the list of registered block patterns.
5105 *
5106 * @param state Data state.
5107 *
5108 * @return Block pattern list.
5109 */
5110
5111 function getBlockPatterns(state) {
5112 return state.blockPatterns;
5113 }
5114 /**
5115 * Retrieve the list of registered block pattern categories.
5116 *
5117 * @param state Data state.
5118 *
5119 * @return Block pattern category list.
5120 */
5121
5122 function getBlockPatternCategories(state) {
5123 return state.blockPatternCategories;
5124 }
5125
5126 ;// CONCATENATED MODULE: ./node_modules/camel-case/dist.es2015/index.js
5127
5128
5129 function camelCaseTransform(input, index) {
5130 if (index === 0)
5131 return input.toLowerCase();
5132 return pascalCaseTransform(input, index);
5133 }
5134 function camelCaseTransformMerge(input, index) {
5135 if (index === 0)
5136 return input.toLowerCase();
5137 return pascalCaseTransformMerge(input);
5138 }
5139 function camelCase(input, options) {
5140 if (options === void 0) { options = {}; }
5141 return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
5142 }
5143
5144 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/forward-resolver.js
5145 /**
5146 * Higher-order function which forward the resolution to another resolver with the same arguments.
5147 *
5148 * @param {string} resolverName forwarded resolver.
5149 *
5150 * @return {Function} Enhanced resolver.
5151 */
5152 const forwardResolver = resolverName => function () {
5153 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5154 args[_key] = arguments[_key];
5155 }
5156
5157 return async _ref => {
5158 let {
5159 resolveSelect
5160 } = _ref;
5161 await resolveSelect[resolverName](...args);
5162 };
5163 };
5164
5165 /* harmony default export */ var forward_resolver = (forwardResolver);
5166
5167 ;// CONCATENATED MODULE: ./packages/core-data/build-module/resolvers.js
5168 /**
5169 * External dependencies
5170 */
5171
5172 /**
5173 * WordPress dependencies
5174 */
5175
5176
5177
5178 /**
5179 * Internal dependencies
5180 */
5181
5182
5183
5184
5185 /**
5186 * Requests authors from the REST API.
5187 *
5188 * @param {Object|undefined} query Optional object of query parameters to
5189 * include with request.
5190 */
5191
5192 const resolvers_getAuthors = query => async _ref => {
5193 let {
5194 dispatch
5195 } = _ref;
5196 const path = (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/users/?who=authors&per_page=100', query);
5197 const users = await external_wp_apiFetch_default()({
5198 path
5199 });
5200 dispatch.receiveUserQuery(path, users);
5201 };
5202 /**
5203 * Requests the current user from the REST API.
5204 */
5205
5206 const resolvers_getCurrentUser = () => async _ref2 => {
5207 let {
5208 dispatch
5209 } = _ref2;
5210 const currentUser = await external_wp_apiFetch_default()({
5211 path: '/wp/v2/users/me'
5212 });
5213 dispatch.receiveCurrentUser(currentUser);
5214 };
5215 /**
5216 * Requests an entity's record from the REST API.
5217 *
5218 * @param {string} kind Entity kind.
5219 * @param {string} name Entity name.
5220 * @param {number|string} key Record's key
5221 * @param {Object|undefined} query Optional object of query parameters to
5222 * include with request. If requesting specific
5223 * fields, fields must always include the ID.
5224 */
5225
5226 const resolvers_getEntityRecord = function (kind, name) {
5227 let key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
5228 let query = arguments.length > 3 ? arguments[3] : undefined;
5229 return async _ref3 => {
5230 let {
5231 select,
5232 dispatch
5233 } = _ref3;
5234 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5235 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5236
5237 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
5238 return;
5239 }
5240
5241 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, key], {
5242 exclusive: false
5243 });
5244
5245 try {
5246 if (query !== undefined && query._fields) {
5247 // If requesting specific fields, items and query association to said
5248 // records are stored by ID reference. Thus, fields must always include
5249 // the ID.
5250 query = { ...query,
5251 _fields: [...new Set([...(get_normalized_comma_separable(query._fields) || []), entityConfig.key || DEFAULT_ENTITY_KEY])].join()
5252 };
5253 } // Disable reason: While true that an early return could leave `path`
5254 // unused, it's important that path is derived using the query prior to
5255 // additional query modifications in the condition below, since those
5256 // modifications are relevant to how the data is tracked in state, and not
5257 // for how the request is made to the REST API.
5258 // eslint-disable-next-line @wordpress/no-unused-vars-before-return
5259
5260
5261 const path = (0,external_wp_url_namespaceObject.addQueryArgs)(entityConfig.baseURL + (key ? '/' + key : ''), { ...entityConfig.baseURLParams,
5262 ...query
5263 });
5264
5265 if (query !== undefined) {
5266 query = { ...query,
5267 include: [key]
5268 }; // The resolution cache won't consider query as reusable based on the
5269 // fields, so it's tested here, prior to initiating the REST request,
5270 // and without causing `getEntityRecords` resolution to occur.
5271
5272 const hasRecords = select.hasEntityRecords(kind, name, query);
5273
5274 if (hasRecords) {
5275 return;
5276 }
5277 }
5278
5279 const record = await external_wp_apiFetch_default()({
5280 path
5281 });
5282 dispatch.receiveEntityRecords(kind, name, record, query);
5283 } finally {
5284 dispatch.__unstableReleaseStoreLock(lock);
5285 }
5286 };
5287 };
5288 /**
5289 * Requests an entity's record from the REST API.
5290 */
5291
5292 const resolvers_getRawEntityRecord = forward_resolver('getEntityRecord');
5293 /**
5294 * Requests an entity's record from the REST API.
5295 */
5296
5297 const resolvers_getEditedEntityRecord = forward_resolver('getEntityRecord');
5298 /**
5299 * Requests the entity's records from the REST API.
5300 *
5301 * @param {string} kind Entity kind.
5302 * @param {string} name Entity name.
5303 * @param {Object?} query Query Object. If requesting specific fields, fields
5304 * must always include the ID.
5305 */
5306
5307 const resolvers_getEntityRecords = function (kind, name) {
5308 let query = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5309 return async _ref4 => {
5310 let {
5311 dispatch
5312 } = _ref4;
5313 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5314 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5315
5316 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
5317 return;
5318 }
5319
5320 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name], {
5321 exclusive: false
5322 });
5323
5324 try {
5325 var _query;
5326
5327 if (query._fields) {
5328 // If requesting specific fields, items and query association to said
5329 // records are stored by ID reference. Thus, fields must always include
5330 // the ID.
5331 query = { ...query,
5332 _fields: [...new Set([...(get_normalized_comma_separable(query._fields) || []), entityConfig.key || DEFAULT_ENTITY_KEY])].join()
5333 };
5334 }
5335
5336 const path = (0,external_wp_url_namespaceObject.addQueryArgs)(entityConfig.baseURL, { ...entityConfig.baseURLParams,
5337 ...query
5338 });
5339 let records = Object.values(await external_wp_apiFetch_default()({
5340 path
5341 })); // If we request fields but the result doesn't contain the fields,
5342 // explicitely set these fields as "undefined"
5343 // that way we consider the query "fullfilled".
5344
5345 if (query._fields) {
5346 records = records.map(record => {
5347 query._fields.split(',').forEach(field => {
5348 if (!record.hasOwnProperty(field)) {
5349 record[field] = undefined;
5350 }
5351 });
5352
5353 return record;
5354 });
5355 }
5356
5357 dispatch.receiveEntityRecords(kind, name, records, query); // When requesting all fields, the list of results can be used to
5358 // resolve the `getEntityRecord` selector in addition to `getEntityRecords`.
5359 // See https://github.com/WordPress/gutenberg/pull/26575
5360
5361 if (!((_query = query) !== null && _query !== void 0 && _query._fields) && !query.context) {
5362 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
5363 const resolutionsArgs = records.filter(record => record[key]).map(record => [kind, name, record[key]]);
5364 dispatch({
5365 type: 'START_RESOLUTIONS',
5366 selectorName: 'getEntityRecord',
5367 args: resolutionsArgs
5368 });
5369 dispatch({
5370 type: 'FINISH_RESOLUTIONS',
5371 selectorName: 'getEntityRecord',
5372 args: resolutionsArgs
5373 });
5374 }
5375 } finally {
5376 dispatch.__unstableReleaseStoreLock(lock);
5377 }
5378 };
5379 };
5380
5381 resolvers_getEntityRecords.shouldInvalidate = (action, kind, name) => {
5382 return (action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS') && action.invalidateCache && kind === action.kind && name === action.name;
5383 };
5384 /**
5385 * Requests the current theme.
5386 */
5387
5388
5389 const resolvers_getCurrentTheme = () => async _ref5 => {
5390 let {
5391 dispatch,
5392 resolveSelect
5393 } = _ref5;
5394 const activeThemes = await resolveSelect.getEntityRecords('root', 'theme', {
5395 status: 'active'
5396 });
5397 dispatch.receiveCurrentTheme(activeThemes[0]);
5398 };
5399 /**
5400 * Requests theme supports data from the index.
5401 */
5402
5403 const resolvers_getThemeSupports = forward_resolver('getCurrentTheme');
5404 /**
5405 * Requests a preview from the from the Embed API.
5406 *
5407 * @param {string} url URL to get the preview for.
5408 */
5409
5410 const resolvers_getEmbedPreview = url => async _ref6 => {
5411 let {
5412 dispatch
5413 } = _ref6;
5414
5415 try {
5416 const embedProxyResponse = await external_wp_apiFetch_default()({
5417 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/oembed/1.0/proxy', {
5418 url
5419 })
5420 });
5421 dispatch.receiveEmbedPreview(url, embedProxyResponse);
5422 } catch (error) {
5423 // Embed API 404s if the URL cannot be embedded, so we have to catch the error from the apiRequest here.
5424 dispatch.receiveEmbedPreview(url, false);
5425 }
5426 };
5427 /**
5428 * Checks whether the current user can perform the given action on the given
5429 * REST resource.
5430 *
5431 * @param {string} requestedAction Action to check. One of: 'create', 'read', 'update',
5432 * 'delete'.
5433 * @param {string} resource REST resource to check, e.g. 'media' or 'posts'.
5434 * @param {?string} id ID of the rest resource to check.
5435 */
5436
5437 const resolvers_canUser = (requestedAction, resource, id) => async _ref7 => {
5438 var _response$headers;
5439
5440 let {
5441 dispatch,
5442 registry
5443 } = _ref7;
5444 const {
5445 hasStartedResolution
5446 } = registry.select(STORE_NAME);
5447 const resourcePath = id ? `${resource}/${id}` : resource;
5448 const retrievedActions = ['create', 'read', 'update', 'delete'];
5449
5450 if (!retrievedActions.includes(requestedAction)) {
5451 throw new Error(`'${requestedAction}' is not a valid action.`);
5452 } // Prevent resolving the same resource twice.
5453
5454
5455 for (const relatedAction of retrievedActions) {
5456 if (relatedAction === requestedAction) {
5457 continue;
5458 }
5459
5460 const isAlreadyResolving = hasStartedResolution('canUser', [relatedAction, resource, id]);
5461
5462 if (isAlreadyResolving) {
5463 return;
5464 }
5465 }
5466
5467 let response;
5468
5469 try {
5470 response = await external_wp_apiFetch_default()({
5471 path: `/wp/v2/${resourcePath}`,
5472 method: 'OPTIONS',
5473 parse: false
5474 });
5475 } catch (error) {
5476 // Do nothing if our OPTIONS request comes back with an API error (4xx or
5477 // 5xx). The previously determined isAllowed value will remain in the store.
5478 return;
5479 } // Optional chaining operator is used here because the API requests don't
5480 // return the expected result in the native version. Instead, API requests
5481 // only return the result, without including response properties like the headers.
5482
5483
5484 const allowHeader = (_response$headers = response.headers) === null || _response$headers === void 0 ? void 0 : _response$headers.get('allow');
5485 const allowedMethods = (allowHeader === null || allowHeader === void 0 ? void 0 : allowHeader.allow) || allowHeader || '';
5486 const permissions = {};
5487 const methods = {
5488 create: 'POST',
5489 read: 'GET',
5490 update: 'PUT',
5491 delete: 'DELETE'
5492 };
5493
5494 for (const [actionName, methodName] of Object.entries(methods)) {
5495 permissions[actionName] = allowedMethods.includes(methodName);
5496 }
5497
5498 for (const action of retrievedActions) {
5499 dispatch.receiveUserPermission(`${action}/${resourcePath}`, permissions[action]);
5500 }
5501 };
5502 /**
5503 * Checks whether the current user can perform the given action on the given
5504 * REST resource.
5505 *
5506 * @param {string} kind Entity kind.
5507 * @param {string} name Entity name.
5508 * @param {string} recordId Record's id.
5509 */
5510
5511 const resolvers_canUserEditEntityRecord = (kind, name, recordId) => async _ref8 => {
5512 let {
5513 dispatch
5514 } = _ref8;
5515 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5516 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5517
5518 if (!entityConfig) {
5519 return;
5520 }
5521
5522 const resource = entityConfig.__unstable_rest_base;
5523 await dispatch(resolvers_canUser('update', resource, recordId));
5524 };
5525 /**
5526 * Request autosave data from the REST API.
5527 *
5528 * @param {string} postType The type of the parent post.
5529 * @param {number} postId The id of the parent post.
5530 */
5531
5532 const resolvers_getAutosaves = (postType, postId) => async _ref9 => {
5533 let {
5534 dispatch,
5535 resolveSelect
5536 } = _ref9;
5537 const {
5538 rest_base: restBase,
5539 rest_namespace: restNamespace = 'wp/v2'
5540 } = await resolveSelect.getPostType(postType);
5541 const autosaves = await external_wp_apiFetch_default()({
5542 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
5543 });
5544
5545 if (autosaves && autosaves.length) {
5546 dispatch.receiveAutosaves(postId, autosaves);
5547 }
5548 };
5549 /**
5550 * Request autosave data from the REST API.
5551 *
5552 * This resolver exists to ensure the underlying autosaves are fetched via
5553 * `getAutosaves` when a call to the `getAutosave` selector is made.
5554 *
5555 * @param {string} postType The type of the parent post.
5556 * @param {number} postId The id of the parent post.
5557 */
5558
5559 const resolvers_getAutosave = (postType, postId) => async _ref10 => {
5560 let {
5561 resolveSelect
5562 } = _ref10;
5563 await resolveSelect.getAutosaves(postType, postId);
5564 };
5565 /**
5566 * Retrieve the frontend template used for a given link.
5567 *
5568 * @param {string} link Link.
5569 */
5570
5571 const resolvers_experimentalGetTemplateForLink = link => async _ref11 => {
5572 let {
5573 dispatch,
5574 resolveSelect
5575 } = _ref11;
5576 // Ideally this should be using an apiFetch call
5577 // We could potentially do so by adding a "filter" to the `wp_template` end point.
5578 // Also it seems the returned object is not a regular REST API post type.
5579 let template;
5580
5581 try {
5582 template = await window.fetch((0,external_wp_url_namespaceObject.addQueryArgs)(link, {
5583 '_wp-find-template': true
5584 })).then(res => res.json()).then(_ref12 => {
5585 let {
5586 data
5587 } = _ref12;
5588 return data;
5589 });
5590 } catch (e) {// For non-FSE themes, it is possible that this request returns an error.
5591 }
5592
5593 if (!template) {
5594 return;
5595 }
5596
5597 const record = await resolveSelect.getEntityRecord('postType', 'wp_template', template.id);
5598
5599 if (record) {
5600 dispatch.receiveEntityRecords('postType', 'wp_template', [record], {
5601 'find-template': link
5602 });
5603 }
5604 };
5605
5606 resolvers_experimentalGetTemplateForLink.shouldInvalidate = action => {
5607 return (action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS') && action.invalidateCache && action.kind === 'postType' && action.name === 'wp_template';
5608 };
5609
5610 const resolvers_experimentalGetCurrentGlobalStylesId = () => async _ref13 => {
5611 var _activeThemes$, _activeThemes$$_links, _activeThemes$$_links2, _activeThemes$$_links3;
5612
5613 let {
5614 dispatch,
5615 resolveSelect
5616 } = _ref13;
5617 const activeThemes = await resolveSelect.getEntityRecords('root', 'theme', {
5618 status: 'active'
5619 });
5620 const globalStylesURL = activeThemes === null || activeThemes === void 0 ? void 0 : (_activeThemes$ = activeThemes[0]) === null || _activeThemes$ === void 0 ? void 0 : (_activeThemes$$_links = _activeThemes$._links) === null || _activeThemes$$_links === void 0 ? void 0 : (_activeThemes$$_links2 = _activeThemes$$_links['wp:user-global-styles']) === null || _activeThemes$$_links2 === void 0 ? void 0 : (_activeThemes$$_links3 = _activeThemes$$_links2[0]) === null || _activeThemes$$_links3 === void 0 ? void 0 : _activeThemes$$_links3.href;
5621
5622 if (globalStylesURL) {
5623 const globalStylesObject = await external_wp_apiFetch_default()({
5624 url: globalStylesURL
5625 });
5626
5627 dispatch.__experimentalReceiveCurrentGlobalStylesId(globalStylesObject.id);
5628 }
5629 };
5630 const resolvers_experimentalGetCurrentThemeBaseGlobalStyles = () => async _ref14 => {
5631 let {
5632 resolveSelect,
5633 dispatch
5634 } = _ref14;
5635 const currentTheme = await resolveSelect.getCurrentTheme();
5636 const themeGlobalStyles = await external_wp_apiFetch_default()({
5637 path: `/wp/v2/global-styles/themes/${currentTheme.stylesheet}`
5638 });
5639
5640 dispatch.__experimentalReceiveThemeBaseGlobalStyles(currentTheme.stylesheet, themeGlobalStyles);
5641 };
5642 const resolvers_experimentalGetCurrentThemeGlobalStylesVariations = () => async _ref15 => {
5643 let {
5644 resolveSelect,
5645 dispatch
5646 } = _ref15;
5647 const currentTheme = await resolveSelect.getCurrentTheme();
5648 const variations = await external_wp_apiFetch_default()({
5649 path: `/wp/v2/global-styles/themes/${currentTheme.stylesheet}/variations`
5650 });
5651
5652 dispatch.__experimentalReceiveThemeGlobalStyleVariations(currentTheme.stylesheet, variations);
5653 };
5654 const resolvers_getBlockPatterns = () => async _ref16 => {
5655 let {
5656 dispatch
5657 } = _ref16;
5658 const restPatterns = await external_wp_apiFetch_default()({
5659 path: '/wp/v2/block-patterns/patterns'
5660 });
5661 const patterns = restPatterns === null || restPatterns === void 0 ? void 0 : restPatterns.map(pattern => Object.fromEntries(Object.entries(pattern).map(_ref17 => {
5662 let [key, value] = _ref17;
5663 return [camelCase(key), value];
5664 })));
5665 dispatch({
5666 type: 'RECEIVE_BLOCK_PATTERNS',
5667 patterns
5668 });
5669 };
5670 const resolvers_getBlockPatternCategories = () => async _ref18 => {
5671 let {
5672 dispatch
5673 } = _ref18;
5674 const categories = await external_wp_apiFetch_default()({
5675 path: '/wp/v2/block-patterns/categories'
5676 });
5677 dispatch({
5678 type: 'RECEIVE_BLOCK_PATTERN_CATEGORIES',
5679 categories
5680 });
5681 };
5682
5683 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/utils.js
5684 function deepCopyLocksTreePath(tree, path) {
5685 const newTree = { ...tree
5686 };
5687 let currentNode = newTree;
5688
5689 for (const branchName of path) {
5690 currentNode.children = { ...currentNode.children,
5691 [branchName]: {
5692 locks: [],
5693 children: {},
5694 ...currentNode.children[branchName]
5695 }
5696 };
5697 currentNode = currentNode.children[branchName];
5698 }
5699
5700 return newTree;
5701 }
5702 function getNode(tree, path) {
5703 let currentNode = tree;
5704
5705 for (const branchName of path) {
5706 const nextNode = currentNode.children[branchName];
5707
5708 if (!nextNode) {
5709 return null;
5710 }
5711
5712 currentNode = nextNode;
5713 }
5714
5715 return currentNode;
5716 }
5717 function* iteratePath(tree, path) {
5718 let currentNode = tree;
5719 yield currentNode;
5720
5721 for (const branchName of path) {
5722 const nextNode = currentNode.children[branchName];
5723
5724 if (!nextNode) {
5725 break;
5726 }
5727
5728 yield nextNode;
5729 currentNode = nextNode;
5730 }
5731 }
5732 function* iterateDescendants(node) {
5733 const stack = Object.values(node.children);
5734
5735 while (stack.length) {
5736 const childNode = stack.pop();
5737 yield childNode;
5738 stack.push(...Object.values(childNode.children));
5739 }
5740 }
5741 function hasConflictingLock(_ref, locks) {
5742 let {
5743 exclusive
5744 } = _ref;
5745
5746 if (exclusive && locks.length) {
5747 return true;
5748 }
5749
5750 if (!exclusive && locks.filter(lock => lock.exclusive).length) {
5751 return true;
5752 }
5753
5754 return false;
5755 }
5756
5757 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/reducer.js
5758 /**
5759 * Internal dependencies
5760 */
5761
5762 const DEFAULT_STATE = {
5763 requests: [],
5764 tree: {
5765 locks: [],
5766 children: {}
5767 }
5768 };
5769 /**
5770 * Reducer returning locks.
5771 *
5772 * @param {Object} state Current state.
5773 * @param {Object} action Dispatched action.
5774 *
5775 * @return {Object} Updated state.
5776 */
5777
5778 function locks() {
5779 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_STATE;
5780 let action = arguments.length > 1 ? arguments[1] : undefined;
5781
5782 switch (action.type) {
5783 case 'ENQUEUE_LOCK_REQUEST':
5784 {
5785 const {
5786 request
5787 } = action;
5788 return { ...state,
5789 requests: [request, ...state.requests]
5790 };
5791 }
5792
5793 case 'GRANT_LOCK_REQUEST':
5794 {
5795 const {
5796 lock,
5797 request
5798 } = action;
5799 const {
5800 store,
5801 path
5802 } = request;
5803 const storePath = [store, ...path];
5804 const newTree = deepCopyLocksTreePath(state.tree, storePath);
5805 const node = getNode(newTree, storePath);
5806 node.locks = [...node.locks, lock];
5807 return { ...state,
5808 requests: state.requests.filter(r => r !== request),
5809 tree: newTree
5810 };
5811 }
5812
5813 case 'RELEASE_LOCK':
5814 {
5815 const {
5816 lock
5817 } = action;
5818 const storePath = [lock.store, ...lock.path];
5819 const newTree = deepCopyLocksTreePath(state.tree, storePath);
5820 const node = getNode(newTree, storePath);
5821 node.locks = node.locks.filter(l => l !== lock);
5822 return { ...state,
5823 tree: newTree
5824 };
5825 }
5826 }
5827
5828 return state;
5829 }
5830
5831 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/selectors.js
5832 /**
5833 * Internal dependencies
5834 */
5835
5836 function getPendingLockRequests(state) {
5837 return state.requests;
5838 }
5839 function isLockAvailable(state, store, path, _ref) {
5840 let {
5841 exclusive
5842 } = _ref;
5843 const storePath = [store, ...path];
5844 const locks = state.tree; // Validate all parents and the node itself
5845
5846 for (const node of iteratePath(locks, storePath)) {
5847 if (hasConflictingLock({
5848 exclusive
5849 }, node.locks)) {
5850 return false;
5851 }
5852 } // iteratePath terminates early if path is unreachable, let's
5853 // re-fetch the node and check it exists in the tree.
5854
5855
5856 const node = getNode(locks, storePath);
5857
5858 if (!node) {
5859 return true;
5860 } // Validate all nested nodes
5861
5862
5863 for (const descendant of iterateDescendants(node)) {
5864 if (hasConflictingLock({
5865 exclusive
5866 }, descendant.locks)) {
5867 return false;
5868 }
5869 }
5870
5871 return true;
5872 }
5873
5874 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/engine.js
5875 /**
5876 * Internal dependencies
5877 */
5878
5879
5880 function createLocks() {
5881 let state = locks(undefined, {
5882 type: '@@INIT'
5883 });
5884
5885 function processPendingLockRequests() {
5886 for (const request of getPendingLockRequests(state)) {
5887 const {
5888 store,
5889 path,
5890 exclusive,
5891 notifyAcquired
5892 } = request;
5893
5894 if (isLockAvailable(state, store, path, {
5895 exclusive
5896 })) {
5897 const lock = {
5898 store,
5899 path,
5900 exclusive
5901 };
5902 state = locks(state, {
5903 type: 'GRANT_LOCK_REQUEST',
5904 lock,
5905 request
5906 });
5907 notifyAcquired(lock);
5908 }
5909 }
5910 }
5911
5912 function acquire(store, path, exclusive) {
5913 return new Promise(resolve => {
5914 state = locks(state, {
5915 type: 'ENQUEUE_LOCK_REQUEST',
5916 request: {
5917 store,
5918 path,
5919 exclusive,
5920 notifyAcquired: resolve
5921 }
5922 });
5923 processPendingLockRequests();
5924 });
5925 }
5926
5927 function release(lock) {
5928 state = locks(state, {
5929 type: 'RELEASE_LOCK',
5930 lock
5931 });
5932 processPendingLockRequests();
5933 }
5934
5935 return {
5936 acquire,
5937 release
5938 };
5939 }
5940
5941 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/actions.js
5942 /**
5943 * Internal dependencies
5944 */
5945
5946 function createLocksActions() {
5947 const locks = createLocks();
5948
5949 function __unstableAcquireStoreLock(store, path, _ref) {
5950 let {
5951 exclusive
5952 } = _ref;
5953 return () => locks.acquire(store, path, exclusive);
5954 }
5955
5956 function __unstableReleaseStoreLock(lock) {
5957 return () => locks.release(lock);
5958 }
5959
5960 return {
5961 __unstableAcquireStoreLock,
5962 __unstableReleaseStoreLock
5963 };
5964 }
5965
5966 ;// CONCATENATED MODULE: external ["wp","element"]
5967 var external_wp_element_namespaceObject = window["wp"]["element"];
5968 ;// CONCATENATED MODULE: external ["wp","blocks"]
5969 var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
5970 ;// CONCATENATED MODULE: ./packages/core-data/build-module/entity-provider.js
5971
5972
5973 /**
5974 * WordPress dependencies
5975 */
5976
5977
5978
5979 /**
5980 * Internal dependencies
5981 */
5982
5983
5984 /** @typedef {import('@wordpress/blocks').WPBlock} WPBlock */
5985
5986 const EMPTY_ARRAY = [];
5987 /**
5988 * Internal dependencies
5989 */
5990
5991
5992 const entityContexts = { ...rootEntitiesConfig.reduce((acc, loader) => {
5993 if (!acc[loader.kind]) {
5994 acc[loader.kind] = {};
5995 }
5996
5997 acc[loader.kind][loader.name] = {
5998 context: (0,external_wp_element_namespaceObject.createContext)(undefined)
5999 };
6000 return acc;
6001 }, {}),
6002 ...additionalEntityConfigLoaders.reduce((acc, loader) => {
6003 acc[loader.kind] = {};
6004 return acc;
6005 }, {})
6006 };
6007
6008 const getEntityContext = (kind, name) => {
6009 if (!entityContexts[kind]) {
6010 throw new Error(`Missing entity config for kind: ${kind}.`);
6011 }
6012
6013 if (!entityContexts[kind][name]) {
6014 entityContexts[kind][name] = {
6015 context: (0,external_wp_element_namespaceObject.createContext)(undefined)
6016 };
6017 }
6018
6019 return entityContexts[kind][name].context;
6020 };
6021 /**
6022 * Context provider component for providing
6023 * an entity for a specific entity.
6024 *
6025 * @param {Object} props The component's props.
6026 * @param {string} props.kind The entity kind.
6027 * @param {string} props.type The entity name.
6028 * @param {number} props.id The entity ID.
6029 * @param {*} props.children The children to wrap.
6030 *
6031 * @return {Object} The provided children, wrapped with
6032 * the entity's context provider.
6033 */
6034
6035
6036 function EntityProvider(_ref) {
6037 let {
6038 kind,
6039 type: name,
6040 id,
6041 children
6042 } = _ref;
6043 const Provider = getEntityContext(kind, name).Provider;
6044 return (0,external_wp_element_namespaceObject.createElement)(Provider, {
6045 value: id
6046 }, children);
6047 }
6048 /**
6049 * Hook that returns the ID for the nearest
6050 * provided entity of the specified type.
6051 *
6052 * @param {string} kind The entity kind.
6053 * @param {string} name The entity name.
6054 */
6055
6056 function useEntityId(kind, name) {
6057 return (0,external_wp_element_namespaceObject.useContext)(getEntityContext(kind, name));
6058 }
6059 /**
6060 * Hook that returns the value and a setter for the
6061 * specified property of the nearest provided
6062 * entity of the specified type.
6063 *
6064 * @param {string} kind The entity kind.
6065 * @param {string} name The entity name.
6066 * @param {string} prop The property name.
6067 * @param {string} [_id] An entity ID to use instead of the context-provided one.
6068 *
6069 * @return {[*, Function, *]} An array where the first item is the
6070 * property value, the second is the
6071 * setter and the third is the full value
6072 * object from REST API containing more
6073 * information like `raw`, `rendered` and
6074 * `protected` props.
6075 */
6076
6077 function useEntityProp(kind, name, prop, _id) {
6078 const providerId = useEntityId(kind, name);
6079 const id = _id !== null && _id !== void 0 ? _id : providerId;
6080 const {
6081 value,
6082 fullValue
6083 } = (0,external_wp_data_namespaceObject.useSelect)(select => {
6084 const {
6085 getEntityRecord,
6086 getEditedEntityRecord
6087 } = select(STORE_NAME);
6088 const record = getEntityRecord(kind, name, id); // Trigger resolver.
6089
6090 const editedRecord = getEditedEntityRecord(kind, name, id);
6091 return record && editedRecord ? {
6092 value: editedRecord[prop],
6093 fullValue: record[prop]
6094 } : {};
6095 }, [kind, name, id, prop]);
6096 const {
6097 editEntityRecord
6098 } = (0,external_wp_data_namespaceObject.useDispatch)(STORE_NAME);
6099 const setValue = (0,external_wp_element_namespaceObject.useCallback)(newValue => {
6100 editEntityRecord(kind, name, id, {
6101 [prop]: newValue
6102 });
6103 }, [kind, name, id, prop]);
6104 return [value, setValue, fullValue];
6105 }
6106 /**
6107 * Hook that returns block content getters and setters for
6108 * the nearest provided entity of the specified type.
6109 *
6110 * The return value has the shape `[ blocks, onInput, onChange ]`.
6111 * `onInput` is for block changes that don't create undo levels
6112 * or dirty the post, non-persistent changes, and `onChange` is for
6113 * peristent changes. They map directly to the props of a
6114 * `BlockEditorProvider` and are intended to be used with it,
6115 * or similar components or hooks.
6116 *
6117 * @param {string} kind The entity kind.
6118 * @param {string} name The entity name.
6119 * @param {Object} options
6120 * @param {string} [options.id] An entity ID to use instead of the context-provided one.
6121 *
6122 * @return {[WPBlock[], Function, Function]} The block array and setters.
6123 */
6124
6125 function useEntityBlockEditor(kind, name) {
6126 let {
6127 id: _id
6128 } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6129 const providerId = useEntityId(kind, name);
6130 const id = _id !== null && _id !== void 0 ? _id : providerId;
6131 const {
6132 content,
6133 blocks
6134 } = (0,external_wp_data_namespaceObject.useSelect)(select => {
6135 const {
6136 getEditedEntityRecord
6137 } = select(STORE_NAME);
6138 const editedRecord = getEditedEntityRecord(kind, name, id);
6139 return {
6140 blocks: editedRecord.blocks,
6141 content: editedRecord.content
6142 };
6143 }, [kind, name, id]);
6144 const {
6145 __unstableCreateUndoLevel,
6146 editEntityRecord
6147 } = (0,external_wp_data_namespaceObject.useDispatch)(STORE_NAME);
6148 (0,external_wp_element_namespaceObject.useEffect)(() => {
6149 // Load the blocks from the content if not already in state
6150 // Guard against other instances that might have
6151 // set content to a function already or the blocks are already in state.
6152 if (content && typeof content !== 'function' && !blocks) {
6153 const parsedContent = (0,external_wp_blocks_namespaceObject.parse)(content);
6154 editEntityRecord(kind, name, id, {
6155 blocks: parsedContent
6156 }, {
6157 undoIgnore: true
6158 });
6159 }
6160 }, [content]);
6161 const onChange = (0,external_wp_element_namespaceObject.useCallback)((newBlocks, options) => {
6162 const {
6163 selection
6164 } = options;
6165 const edits = {
6166 blocks: newBlocks,
6167 selection
6168 };
6169 const noChange = blocks === edits.blocks;
6170
6171 if (noChange) {
6172 return __unstableCreateUndoLevel(kind, name, id);
6173 } // We create a new function here on every persistent edit
6174 // to make sure the edit makes the post dirty and creates
6175 // a new undo level.
6176
6177
6178 edits.content = _ref2 => {
6179 let {
6180 blocks: blocksForSerialization = []
6181 } = _ref2;
6182 return (0,external_wp_blocks_namespaceObject.__unstableSerializeAndClean)(blocksForSerialization);
6183 };
6184
6185 editEntityRecord(kind, name, id, edits);
6186 }, [kind, name, id, blocks]);
6187 const onInput = (0,external_wp_element_namespaceObject.useCallback)((newBlocks, options) => {
6188 const {
6189 selection
6190 } = options;
6191 const edits = {
6192 blocks: newBlocks,
6193 selection
6194 };
6195 editEntityRecord(kind, name, id, edits);
6196 }, [kind, name, id]);
6197 return [blocks !== null && blocks !== void 0 ? blocks : EMPTY_ARRAY, onInput, onChange];
6198 }
6199
6200 ;// CONCATENATED MODULE: external ["wp","htmlEntities"]
6201 var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
6202 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.js
6203 /**
6204 * WordPress dependencies
6205 */
6206
6207
6208
6209
6210 /**
6211 * Filters the search by type
6212 *
6213 * @typedef { 'attachment' | 'post' | 'term' | 'post-format' } WPLinkSearchType
6214 */
6215
6216 /**
6217 * A link with an id may be of kind post-type or taxonomy
6218 *
6219 * @typedef { 'post-type' | 'taxonomy' } WPKind
6220 */
6221
6222 /**
6223 * @typedef WPLinkSearchOptions
6224 *
6225 * @property {boolean} [isInitialSuggestions] Displays initial search suggestions, when true.
6226 * @property {WPLinkSearchType} [type] Filters by search type.
6227 * @property {string} [subtype] Slug of the post-type or taxonomy.
6228 * @property {number} [page] Which page of results to return.
6229 * @property {number} [perPage] Search results per page.
6230 */
6231
6232 /**
6233 * @typedef WPLinkSearchResult
6234 *
6235 * @property {number} id Post or term id.
6236 * @property {string} url Link url.
6237 * @property {string} title Title of the link.
6238 * @property {string} type The taxonomy or post type slug or type URL.
6239 * @property {WPKind} [kind] Link kind of post-type or taxonomy
6240 */
6241
6242 /**
6243 * @typedef WPLinkSearchResultAugments
6244 *
6245 * @property {{kind: WPKind}} [meta] Contains kind information.
6246 * @property {WPKind} [subtype] Optional subtype if it exists.
6247 */
6248
6249 /**
6250 * @typedef {WPLinkSearchResult & WPLinkSearchResultAugments} WPLinkSearchResultAugmented
6251 */
6252
6253 /**
6254 * @typedef WPEditorSettings
6255 *
6256 * @property {boolean} [ disablePostFormats ] Disables post formats, when true.
6257 */
6258
6259 /**
6260 * Fetches link suggestions from the API.
6261 *
6262 * @async
6263 * @param {string} search
6264 * @param {WPLinkSearchOptions} [searchOptions]
6265 * @param {WPEditorSettings} [settings]
6266 *
6267 * @example
6268 * ```js
6269 * import { __experimentalFetchLinkSuggestions as fetchLinkSuggestions } from '@wordpress/core-data';
6270 *
6271 * //...
6272 *
6273 * export function initialize( id, settings ) {
6274 *
6275 * settings.__experimentalFetchLinkSuggestions = (
6276 * search,
6277 * searchOptions
6278 * ) => fetchLinkSuggestions( search, searchOptions, settings );
6279 * ```
6280 * @return {Promise< WPLinkSearchResult[] >} List of search suggestions
6281 */
6282
6283 const fetchLinkSuggestions = async function (search) {
6284 let searchOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
6285 let settings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6286 const {
6287 isInitialSuggestions = false,
6288 type = undefined,
6289 subtype = undefined,
6290 page = undefined,
6291 perPage = isInitialSuggestions ? 3 : 20
6292 } = searchOptions;
6293 const {
6294 disablePostFormats = false
6295 } = settings;
6296 /** @type {Promise<WPLinkSearchResult>[]} */
6297
6298 const queries = [];
6299
6300 if (!type || type === 'post') {
6301 queries.push(external_wp_apiFetch_default()({
6302 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6303 search,
6304 page,
6305 per_page: perPage,
6306 type: 'post',
6307 subtype
6308 })
6309 }).then(results => {
6310 return results.map(result => {
6311 return { ...result,
6312 meta: {
6313 kind: 'post-type',
6314 subtype
6315 }
6316 };
6317 });
6318 }).catch(() => []) // Fail by returning no results.
6319 );
6320 }
6321
6322 if (!type || type === 'term') {
6323 queries.push(external_wp_apiFetch_default()({
6324 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6325 search,
6326 page,
6327 per_page: perPage,
6328 type: 'term',
6329 subtype
6330 })
6331 }).then(results => {
6332 return results.map(result => {
6333 return { ...result,
6334 meta: {
6335 kind: 'taxonomy',
6336 subtype
6337 }
6338 };
6339 });
6340 }).catch(() => []) // Fail by returning no results.
6341 );
6342 }
6343
6344 if (!disablePostFormats && (!type || type === 'post-format')) {
6345 queries.push(external_wp_apiFetch_default()({
6346 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6347 search,
6348 page,
6349 per_page: perPage,
6350 type: 'post-format',
6351 subtype
6352 })
6353 }).then(results => {
6354 return results.map(result => {
6355 return { ...result,
6356 meta: {
6357 kind: 'taxonomy',
6358 subtype
6359 }
6360 };
6361 });
6362 }).catch(() => []) // Fail by returning no results.
6363 );
6364 }
6365
6366 if (!type || type === 'attachment') {
6367 queries.push(external_wp_apiFetch_default()({
6368 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/media', {
6369 search,
6370 page,
6371 per_page: perPage
6372 })
6373 }).then(results => {
6374 return results.map(result => {
6375 return { ...result,
6376 meta: {
6377 kind: 'media'
6378 }
6379 };
6380 });
6381 }).catch(() => []) // Fail by returning no results.
6382 );
6383 }
6384
6385 return Promise.all(queries).then(results => {
6386 return results.reduce((
6387 /** @type {WPLinkSearchResult[]} */
6388 accumulator, current) => accumulator.concat(current), // Flatten list.
6389 []).filter(
6390 /**
6391 * @param {{ id: number }} result
6392 */
6393 result => {
6394 return !!result.id;
6395 }).slice(0, perPage).map((
6396 /** @type {WPLinkSearchResultAugmented} */
6397 result) => {
6398 var _result$meta;
6399
6400 const isMedia = result.type === 'attachment';
6401 return {
6402 id: result.id,
6403 // @ts-ignore fix when we make this a TS file
6404 url: isMedia ? result.source_url : result.url,
6405 title: (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(isMedia ? // @ts-ignore fix when we make this a TS file
6406 result.title.rendered : result.title || '') || (0,external_wp_i18n_namespaceObject.__)('(no title)'),
6407 type: result.subtype || result.type,
6408 kind: result === null || result === void 0 ? void 0 : (_result$meta = result.meta) === null || _result$meta === void 0 ? void 0 : _result$meta.kind
6409 };
6410 });
6411 });
6412 };
6413
6414 /* harmony default export */ var _experimental_fetch_link_suggestions = (fetchLinkSuggestions);
6415
6416 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/__experimental-fetch-url-data.js
6417 /**
6418 * WordPress dependencies
6419 */
6420
6421
6422 /**
6423 * A simple in-memory cache for requests.
6424 * This avoids repeat HTTP requests which may be beneficial
6425 * for those wishing to preserve low-bandwidth.
6426 */
6427
6428 const CACHE = new Map();
6429 /**
6430 * @typedef WPRemoteUrlData
6431 *
6432 * @property {string} title contents of the remote URL's `<title>` tag.
6433 */
6434
6435 /**
6436 * Fetches data about a remote URL.
6437 * eg: <title> tag, favicon...etc.
6438 *
6439 * @async
6440 * @param {string} url the URL to request details from.
6441 * @param {Object?} options any options to pass to the underlying fetch.
6442 * @example
6443 * ```js
6444 * import { __experimentalFetchUrlData as fetchUrlData } from '@wordpress/core-data';
6445 *
6446 * //...
6447 *
6448 * export function initialize( id, settings ) {
6449 *
6450 * settings.__experimentalFetchUrlData = (
6451 * url
6452 * ) => fetchUrlData( url );
6453 * ```
6454 * @return {Promise< WPRemoteUrlData[] >} Remote URL data.
6455 */
6456
6457 const fetchUrlData = async function (url) {
6458 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
6459 const endpoint = '/wp-block-editor/v1/url-details';
6460 const args = {
6461 url: (0,external_wp_url_namespaceObject.prependHTTP)(url)
6462 };
6463
6464 if (!(0,external_wp_url_namespaceObject.isURL)(url)) {
6465 return Promise.reject(`${url} is not a valid URL.`);
6466 } // Test for "http" based URL as it is possible for valid
6467 // yet unusable URLs such as `tel:123456` to be passed.
6468
6469
6470 const protocol = (0,external_wp_url_namespaceObject.getProtocol)(url);
6471
6472 if (!protocol || !(0,external_wp_url_namespaceObject.isValidProtocol)(protocol) || !protocol.startsWith('http') || !/^https?:\/\/[^\/\s]/i.test(url)) {
6473 return Promise.reject(`${url} does not have a valid protocol. URLs must be "http" based`);
6474 }
6475
6476 if (CACHE.has(url)) {
6477 return CACHE.get(url);
6478 }
6479
6480 return external_wp_apiFetch_default()({
6481 path: (0,external_wp_url_namespaceObject.addQueryArgs)(endpoint, args),
6482 ...options
6483 }).then(res => {
6484 CACHE.set(url, res);
6485 return res;
6486 });
6487 };
6488
6489 /* harmony default export */ var _experimental_fetch_url_data = (fetchUrlData);
6490
6491 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/fetch-media.js
6492 /**
6493 * WordPress dependencies
6494 */
6495
6496 /**
6497 * Internal dependencies
6498 */
6499
6500
6501 async function fetchMedia() {
6502 let settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
6503 return (0,external_wp_data_namespaceObject.resolveSelect)(STORE_NAME).getMediaItems(settings);
6504 }
6505
6506 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/index.js
6507
6508
6509
6510
6511 // EXTERNAL MODULE: ./node_modules/memize/index.js
6512 var memize = __webpack_require__(9756);
6513 var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
6514 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/memoize.js
6515 /**
6516 * External dependencies
6517 */
6518 // re-export due to restrictive esModuleInterop setting
6519
6520 /* harmony default export */ var memoize = ((memize_default()));
6521
6522 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/constants.js
6523 let Status;
6524
6525 (function (Status) {
6526 Status["Idle"] = "IDLE";
6527 Status["Resolving"] = "RESOLVING";
6528 Status["Error"] = "ERROR";
6529 Status["Success"] = "SUCCESS";
6530 })(Status || (Status = {}));
6531
6532 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-query-select.js
6533 /**
6534 * WordPress dependencies
6535 */
6536
6537 /**
6538 * Internal dependencies
6539 */
6540
6541
6542
6543 const META_SELECTORS = ['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'];
6544
6545 /**
6546 * Like useSelect, but the selectors return objects containing
6547 * both the original data AND the resolution info.
6548 *
6549 * @since 6.1.0 Introduced in WordPress core.
6550 * @private
6551 *
6552 * @param {Function} mapQuerySelect see useSelect
6553 * @param {Array} deps see useSelect
6554 *
6555 * @example
6556 * ```js
6557 * import { useQuerySelect } from '@wordpress/data';
6558 * import { store as coreDataStore } from '@wordpress/core-data';
6559 *
6560 * function PageTitleDisplay( { id } ) {
6561 * const { data: page, isResolving } = useQuerySelect( ( query ) => {
6562 * return query( coreDataStore ).getEntityRecord( 'postType', 'page', id )
6563 * }, [ id ] );
6564 *
6565 * if ( isResolving ) {
6566 * return 'Loading...';
6567 * }
6568 *
6569 * return page.title;
6570 * }
6571 *
6572 * // Rendered in the application:
6573 * // <PageTitleDisplay id={ 10 } />
6574 * ```
6575 *
6576 * In the above example, when `PageTitleDisplay` is rendered into an
6577 * application, the page and the resolution details will be retrieved from
6578 * the store state using the `mapSelect` callback on `useQuerySelect`.
6579 *
6580 * If the id prop changes then any page in the state for that id is
6581 * retrieved. If the id prop doesn't change and other props are passed in
6582 * that do change, the title will not change because the dependency is just
6583 * the id.
6584 * @see useSelect
6585 *
6586 * @return {QuerySelectResponse} Queried data.
6587 */
6588 function useQuerySelect(mapQuerySelect, deps) {
6589 return (0,external_wp_data_namespaceObject.useSelect)((select, registry) => {
6590 const resolve = store => enrichSelectors(select(store));
6591
6592 return mapQuerySelect(resolve, registry);
6593 }, deps);
6594 }
6595
6596 /**
6597 * Transform simple selectors into ones that return an object with the
6598 * original return value AND the resolution info.
6599 *
6600 * @param {Object} selectors Selectors to enrich
6601 * @return {EnrichedSelectors} Enriched selectors
6602 */
6603 const enrichSelectors = memoize(selectors => {
6604 const resolvers = {};
6605
6606 for (const selectorName in selectors) {
6607 if (META_SELECTORS.includes(selectorName)) {
6608 continue;
6609 }
6610
6611 Object.defineProperty(resolvers, selectorName, {
6612 get: () => function () {
6613 const {
6614 getIsResolving,
6615 hasFinishedResolution
6616 } = selectors;
6617
6618 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
6619 args[_key] = arguments[_key];
6620 }
6621
6622 const isResolving = !!getIsResolving(selectorName, args);
6623 const hasResolved = !isResolving && hasFinishedResolution(selectorName, args);
6624 const data = selectors[selectorName](...args);
6625 let status;
6626
6627 if (isResolving) {
6628 status = Status.Resolving;
6629 } else if (hasResolved) {
6630 if (data) {
6631 status = Status.Success;
6632 } else {
6633 status = Status.Error;
6634 }
6635 } else {
6636 status = Status.Idle;
6637 }
6638
6639 return {
6640 data,
6641 status,
6642 isResolving,
6643 hasResolved
6644 };
6645 }
6646 });
6647 }
6648
6649 return resolvers;
6650 });
6651
6652 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-entity-record.js
6653 /**
6654 * WordPress dependencies
6655 */
6656
6657
6658
6659 /**
6660 * Internal dependencies
6661 */
6662
6663
6664
6665
6666 /**
6667 * Resolves the specified entity record.
6668 *
6669 * @since 6.1.0 Introduced in WordPress core.
6670 *
6671 * @param kind Kind of the entity, e.g. `root` or a `postType`. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
6672 * @param name Name of the entity, e.g. `plugin` or a `post`. See rootEntitiesConfig in ../entities.ts for a list of available names.
6673 * @param recordId ID of the requested entity record.
6674 * @param options Optional hook options.
6675 * @example
6676 * ```js
6677 * import { useEntityRecord } from '@wordpress/core-data';
6678 *
6679 * function PageTitleDisplay( { id } ) {
6680 * const { record, isResolving } = useEntityRecord( 'postType', 'page', id );
6681 *
6682 * if ( isResolving ) {
6683 * return 'Loading...';
6684 * }
6685 *
6686 * return record.title;
6687 * }
6688 *
6689 * // Rendered in the application:
6690 * // <PageTitleDisplay id={ 1 } />
6691 * ```
6692 *
6693 * In the above example, when `PageTitleDisplay` is rendered into an
6694 * application, the page and the resolution details will be retrieved from
6695 * the store state using `getEntityRecord()`, or resolved if missing.
6696 *
6697 * @example
6698 * ```js
6699 * import { useDispatch } from '@wordpress/data';
6700 * import { useCallback } from '@wordpress/element';
6701 * import { __ } from '@wordpress/i18n';
6702 * import { TextControl } from '@wordpress/components';
6703 * import { store as noticeStore } from '@wordpress/notices';
6704 * import { useEntityRecord } from '@wordpress/core-data';
6705 *
6706 * function PageRenameForm( { id } ) {
6707 * const page = useEntityRecord( 'postType', 'page', id );
6708 * const { createSuccessNotice, createErrorNotice } =
6709 * useDispatch( noticeStore );
6710 *
6711 * const setTitle = useCallback( ( title ) => {
6712 * page.edit( { title } );
6713 * }, [ page.edit ] );
6714 *
6715 * if ( page.isResolving ) {
6716 * return 'Loading...';
6717 * }
6718 *
6719 * async function onRename( event ) {
6720 * event.preventDefault();
6721 * try {
6722 * await page.save();
6723 * createSuccessNotice( __( 'Page renamed.' ), {
6724 * type: 'snackbar',
6725 * } );
6726 * } catch ( error ) {
6727 * createErrorNotice( error.message, { type: 'snackbar' } );
6728 * }
6729 * }
6730 *
6731 * return (
6732 * <form onSubmit={ onRename }>
6733 * <TextControl
6734 * label={ __( 'Name' ) }
6735 * value={ page.editedRecord.title }
6736 * onChange={ setTitle }
6737 * />
6738 * <button type="submit">{ __( 'Save' ) }</button>
6739 * </form>
6740 * );
6741 * }
6742 *
6743 * // Rendered in the application:
6744 * // <PageRenameForm id={ 1 } />
6745 * ```
6746 *
6747 * In the above example, updating and saving the page title is handled
6748 * via the `edit()` and `save()` mutation helpers provided by
6749 * `useEntityRecord()`;
6750 *
6751 * @return Entity record data.
6752 * @template RecordType
6753 */
6754 function useEntityRecord(kind, name, recordId) {
6755 let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
6756 enabled: true
6757 };
6758 const {
6759 editEntityRecord,
6760 saveEditedEntityRecord
6761 } = (0,external_wp_data_namespaceObject.useDispatch)(store);
6762 const mutations = (0,external_wp_element_namespaceObject.useMemo)(() => ({
6763 edit: record => editEntityRecord(kind, name, recordId, record),
6764 save: function () {
6765 let saveOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
6766 return saveEditedEntityRecord(kind, name, recordId, {
6767 throwOnError: true,
6768 ...saveOptions
6769 });
6770 }
6771 }), [recordId]);
6772 const {
6773 editedRecord,
6774 hasEdits
6775 } = (0,external_wp_data_namespaceObject.useSelect)(select => ({
6776 editedRecord: select(store).getEditedEntityRecord(kind, name, recordId),
6777 hasEdits: select(store).hasEditsForEntityRecord(kind, name, recordId)
6778 }), [kind, name, recordId]);
6779 const {
6780 data: record,
6781 ...querySelectRest
6782 } = useQuerySelect(query => {
6783 if (!options.enabled) {
6784 return null;
6785 }
6786
6787 return query(store).getEntityRecord(kind, name, recordId);
6788 }, [kind, name, recordId, options.enabled]);
6789 return {
6790 record,
6791 editedRecord,
6792 hasEdits,
6793 ...querySelectRest,
6794 ...mutations
6795 };
6796 }
6797 function __experimentalUseEntityRecord(kind, name, recordId, options) {
6798 external_wp_deprecated_default()(`wp.data.__experimentalUseEntityRecord`, {
6799 alternative: 'wp.data.useEntityRecord',
6800 since: '6.1'
6801 });
6802 return useEntityRecord(kind, name, recordId, options);
6803 }
6804
6805 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-entity-records.js
6806 /**
6807 * WordPress dependencies
6808 */
6809
6810
6811 /**
6812 * Internal dependencies
6813 */
6814
6815
6816
6817 const use_entity_records_EMPTY_ARRAY = [];
6818 /**
6819 * Resolves the specified entity records.
6820 *
6821 * @since 6.1.0 Introduced in WordPress core.
6822 *
6823 * @param kind Kind of the entity, e.g. `root` or a `postType`. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
6824 * @param name Name of the entity, e.g. `plugin` or a `post`. See rootEntitiesConfig in ../entities.ts for a list of available names.
6825 * @param queryArgs Optional HTTP query description for how to fetch the data, passed to the requested API endpoint.
6826 * @param options Optional hook options.
6827 * @example
6828 * ```js
6829 * import { useEntityRecord } from '@wordpress/core-data';
6830 *
6831 * function PageTitlesList() {
6832 * const { records, isResolving } = useEntityRecords( 'postType', 'page' );
6833 *
6834 * if ( isResolving ) {
6835 * return 'Loading...';
6836 * }
6837 *
6838 * return (
6839 * <ul>
6840 * {records.map(( page ) => (
6841 * <li>{ page.title }</li>
6842 * ))}
6843 * </ul>
6844 * );
6845 * }
6846 *
6847 * // Rendered in the application:
6848 * // <PageTitlesList />
6849 * ```
6850 *
6851 * In the above example, when `PageTitlesList` is rendered into an
6852 * application, the list of records and the resolution details will be retrieved from
6853 * the store state using `getEntityRecords()`, or resolved if missing.
6854 *
6855 * @return Entity records data.
6856 * @template RecordType
6857 */
6858
6859 function useEntityRecords(kind, name) {
6860 let queryArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6861 let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
6862 enabled: true
6863 };
6864 // Serialize queryArgs to a string that can be safely used as a React dep.
6865 // We can't just pass queryArgs as one of the deps, because if it is passed
6866 // as an object literal, then it will be a different object on each call even
6867 // if the values remain the same.
6868 const queryAsString = (0,external_wp_url_namespaceObject.addQueryArgs)('', queryArgs);
6869 const {
6870 data: records,
6871 ...rest
6872 } = useQuerySelect(query => {
6873 if (!options.enabled) {
6874 return {
6875 // Avoiding returning a new reference on every execution.
6876 data: use_entity_records_EMPTY_ARRAY
6877 };
6878 }
6879
6880 return query(store).getEntityRecords(kind, name, queryArgs);
6881 }, [kind, name, queryAsString, options.enabled]);
6882 return {
6883 records,
6884 ...rest
6885 };
6886 }
6887 function __experimentalUseEntityRecords(kind, name, queryArgs, options) {
6888 external_wp_deprecated_default()(`wp.data.__experimentalUseEntityRecords`, {
6889 alternative: 'wp.data.useEntityRecords',
6890 since: '6.1'
6891 });
6892 return useEntityRecords(kind, name, queryArgs, options);
6893 }
6894
6895 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-resource-permissions.js
6896 /**
6897 * WordPress dependencies
6898 */
6899
6900 /**
6901 * Internal dependencies
6902 */
6903
6904
6905
6906
6907
6908 /**
6909 * Resolves resource permissions.
6910 *
6911 * @since 6.1.0 Introduced in WordPress core.
6912 *
6913 * @param resource The resource in question, e.g. media.
6914 * @param id ID of a specific resource entry, if needed, e.g. 10.
6915 *
6916 * @example
6917 * ```js
6918 * import { useResourcePermissions } from '@wordpress/core-data';
6919 *
6920 * function PagesList() {
6921 * const { canCreate, isResolving } = useResourcePermissions( 'pages' );
6922 *
6923 * if ( isResolving ) {
6924 * return 'Loading ...';
6925 * }
6926 *
6927 * return (
6928 * <div>
6929 * {canCreate ? (<button>+ Create a new page</button>) : false}
6930 * // ...
6931 * </div>
6932 * );
6933 * }
6934 *
6935 * // Rendered in the application:
6936 * // <PagesList />
6937 * ```
6938 *
6939 * @example
6940 * ```js
6941 * import { useResourcePermissions } from '@wordpress/core-data';
6942 *
6943 * function Page({ pageId }) {
6944 * const {
6945 * canCreate,
6946 * canUpdate,
6947 * canDelete,
6948 * isResolving
6949 * } = useResourcePermissions( 'pages', pageId );
6950 *
6951 * if ( isResolving ) {
6952 * return 'Loading ...';
6953 * }
6954 *
6955 * return (
6956 * <div>
6957 * {canCreate ? (<button>+ Create a new page</button>) : false}
6958 * {canUpdate ? (<button>Edit page</button>) : false}
6959 * {canDelete ? (<button>Delete page</button>) : false}
6960 * // ...
6961 * </div>
6962 * );
6963 * }
6964 *
6965 * // Rendered in the application:
6966 * // <Page pageId={ 15 } />
6967 * ```
6968 *
6969 * In the above example, when `PagesList` is rendered into an
6970 * application, the appropriate permissions and the resolution details will be retrieved from
6971 * the store state using `canUser()`, or resolved if missing.
6972 *
6973 * @return Entity records data.
6974 * @template IdType
6975 */
6976 function useResourcePermissions(resource, id) {
6977 return useQuerySelect(resolve => {
6978 const {
6979 canUser
6980 } = resolve(store);
6981 const create = canUser('create', resource);
6982
6983 if (!id) {
6984 const read = canUser('read', resource);
6985 const isResolving = create.isResolving || read.isResolving;
6986 const hasResolved = create.hasResolved && read.hasResolved;
6987 let status = Status.Idle;
6988
6989 if (isResolving) {
6990 status = Status.Resolving;
6991 } else if (hasResolved) {
6992 status = Status.Success;
6993 }
6994
6995 return {
6996 status,
6997 isResolving,
6998 hasResolved,
6999 canCreate: create.hasResolved && create.data,
7000 canRead: read.hasResolved && read.data
7001 };
7002 }
7003
7004 const read = canUser('read', resource, id);
7005 const update = canUser('update', resource, id);
7006
7007 const _delete = canUser('delete', resource, id);
7008
7009 const isResolving = read.isResolving || create.isResolving || update.isResolving || _delete.isResolving;
7010 const hasResolved = read.hasResolved && create.hasResolved && update.hasResolved && _delete.hasResolved;
7011 let status = Status.Idle;
7012
7013 if (isResolving) {
7014 status = Status.Resolving;
7015 } else if (hasResolved) {
7016 status = Status.Success;
7017 }
7018
7019 return {
7020 status,
7021 isResolving,
7022 hasResolved,
7023 canRead: hasResolved && read.data,
7024 canCreate: hasResolved && create.data,
7025 canUpdate: hasResolved && update.data,
7026 canDelete: hasResolved && _delete.data
7027 };
7028 }, [resource, id]);
7029 }
7030 function __experimentalUseResourcePermissions(resource, id) {
7031 external_wp_deprecated_default()(`wp.data.__experimentalUseResourcePermissions`, {
7032 alternative: 'wp.data.useResourcePermissions',
7033 since: '6.1'
7034 });
7035 return useResourcePermissions(resource, id);
7036 }
7037
7038 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/index.js
7039
7040
7041
7042
7043 ;// CONCATENATED MODULE: ./packages/core-data/build-module/index.js
7044 /**
7045 * WordPress dependencies
7046 */
7047
7048 /**
7049 * Internal dependencies
7050 */
7051
7052
7053
7054
7055
7056
7057
7058 // The entity selectors/resolvers and actions are shortcuts to their generic equivalents
7059 // (getEntityRecord, getEntityRecords, updateEntityRecord, updateEntityRecords)
7060 // Instead of getEntityRecord, the consumer could use more user-friendly named selector: getPostType, getTaxonomy...
7061 // The "kind" and the "name" of the entity are combined to generate these shortcuts.
7062
7063 const entitySelectors = rootEntitiesConfig.reduce((result, entity) => {
7064 const {
7065 kind,
7066 name
7067 } = entity;
7068
7069 result[getMethodName(kind, name)] = (state, key, query) => getEntityRecord(state, kind, name, key, query);
7070
7071 result[getMethodName(kind, name, 'get', true)] = (state, query) => getEntityRecords(state, kind, name, query);
7072
7073 return result;
7074 }, {});
7075 const entityResolvers = rootEntitiesConfig.reduce((result, entity) => {
7076 const {
7077 kind,
7078 name
7079 } = entity;
7080
7081 result[getMethodName(kind, name)] = (key, query) => resolvers_getEntityRecord(kind, name, key, query);
7082
7083 const pluralMethodName = getMethodName(kind, name, 'get', true);
7084
7085 result[pluralMethodName] = function () {
7086 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
7087 args[_key] = arguments[_key];
7088 }
7089
7090 return resolvers_getEntityRecords(kind, name, ...args);
7091 };
7092
7093 result[pluralMethodName].shouldInvalidate = action => resolvers_getEntityRecords.shouldInvalidate(action, kind, name);
7094
7095 return result;
7096 }, {});
7097 const entityActions = rootEntitiesConfig.reduce((result, entity) => {
7098 const {
7099 kind,
7100 name
7101 } = entity;
7102
7103 result[getMethodName(kind, name, 'save')] = key => saveEntityRecord(kind, name, key);
7104
7105 result[getMethodName(kind, name, 'delete')] = (key, query) => deleteEntityRecord(kind, name, key, query);
7106
7107 return result;
7108 }, {});
7109
7110 const storeConfig = () => ({
7111 reducer: build_module_reducer,
7112 actions: { ...build_module_actions_namespaceObject,
7113 ...entityActions,
7114 ...createLocksActions()
7115 },
7116 selectors: { ...build_module_selectors_namespaceObject,
7117 ...entitySelectors
7118 },
7119 resolvers: { ...resolvers_namespaceObject,
7120 ...entityResolvers
7121 }
7122 });
7123 /**
7124 * Store definition for the code data namespace.
7125 *
7126 * @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
7127 */
7128
7129
7130 const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, storeConfig());
7131 (0,external_wp_data_namespaceObject.register)(store);
7132
7133
7134
7135
7136
7137
7138 }();
7139 (window.wp = window.wp || {}).coreData = __webpack_exports__;
7140 /******/ })()
7141 ;