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