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