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