[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/js/dist/ -> core-data.js (source)

   1  (function() {
   2  "use strict";
   3  var wp;
   4  (wp ||= {}).coreData = (() => {
   5    var __create = Object.create;
   6    var __defProp = Object.defineProperty;
   7    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
   8    var __getOwnPropNames = Object.getOwnPropertyNames;
   9    var __getProtoOf = Object.getPrototypeOf;
  10    var __hasOwnProp = Object.prototype.hasOwnProperty;
  11    var __commonJS = (cb, mod) => function __require() {
  12      return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  13    };
  14    var __export = (target, all) => {
  15      for (var name in all)
  16        __defProp(target, name, { get: all[name], enumerable: true });
  17    };
  18    var __copyProps = (to, from, except, desc) => {
  19      if (from && typeof from === "object" || typeof from === "function") {
  20        for (let key of __getOwnPropNames(from))
  21          if (!__hasOwnProp.call(to, key) && key !== except)
  22            __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  23      }
  24      return to;
  25    };
  26    var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  27      // If the importer is in node compatibility mode or this is not an ESM
  28      // file that has been converted to a CommonJS file using a Babel-
  29      // compatible transform (i.e. "__esModule" has not been set), then set
  30      // "default" to the CommonJS "module.exports" for node compatibility.
  31      isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  32      mod
  33    ));
  34    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  35  
  36    // package-external:@wordpress/data
  37    var require_data = __commonJS({
  38      "package-external:@wordpress/data"(exports, module) {
  39        module.exports = window.wp.data;
  40      }
  41    });
  42  
  43    // node_modules/fast-deep-equal/es6/index.js
  44    var require_es6 = __commonJS({
  45      "node_modules/fast-deep-equal/es6/index.js"(exports, module) {
  46        "use strict";
  47        module.exports = function equal(a, b) {
  48          if (a === b) return true;
  49          if (a && b && typeof a == "object" && typeof b == "object") {
  50            if (a.constructor !== b.constructor) return false;
  51            var length, i, keys;
  52            if (Array.isArray(a)) {
  53              length = a.length;
  54              if (length != b.length) return false;
  55              for (i = length; i-- !== 0; )
  56                if (!equal(a[i], b[i])) return false;
  57              return true;
  58            }
  59            if (a instanceof Map && b instanceof Map) {
  60              if (a.size !== b.size) return false;
  61              for (i of a.entries())
  62                if (!b.has(i[0])) return false;
  63              for (i of a.entries())
  64                if (!equal(i[1], b.get(i[0]))) return false;
  65              return true;
  66            }
  67            if (a instanceof Set && b instanceof Set) {
  68              if (a.size !== b.size) return false;
  69              for (i of a.entries())
  70                if (!b.has(i[0])) return false;
  71              return true;
  72            }
  73            if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
  74              length = a.length;
  75              if (length != b.length) return false;
  76              for (i = length; i-- !== 0; )
  77                if (a[i] !== b[i]) return false;
  78              return true;
  79            }
  80            if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
  81            if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
  82            if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
  83            keys = Object.keys(a);
  84            length = keys.length;
  85            if (length !== Object.keys(b).length) return false;
  86            for (i = length; i-- !== 0; )
  87              if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
  88            for (i = length; i-- !== 0; ) {
  89              var key = keys[i];
  90              if (!equal(a[key], b[key])) return false;
  91            }
  92            return true;
  93          }
  94          return a !== a && b !== b;
  95        };
  96      }
  97    });
  98  
  99    // package-external:@wordpress/compose
 100    var require_compose = __commonJS({
 101      "package-external:@wordpress/compose"(exports, module) {
 102        module.exports = window.wp.compose;
 103      }
 104    });
 105  
 106    // package-external:@wordpress/undo-manager
 107    var require_undo_manager = __commonJS({
 108      "package-external:@wordpress/undo-manager"(exports, module) {
 109        module.exports = window.wp.undoManager;
 110      }
 111    });
 112  
 113    // package-external:@wordpress/api-fetch
 114    var require_api_fetch = __commonJS({
 115      "package-external:@wordpress/api-fetch"(exports, module) {
 116        module.exports = window.wp.apiFetch;
 117      }
 118    });
 119  
 120    // package-external:@wordpress/sync
 121    var require_sync = __commonJS({
 122      "package-external:@wordpress/sync"(exports, module) {
 123        module.exports = window.wp.sync;
 124      }
 125    });
 126  
 127    // package-external:@wordpress/private-apis
 128    var require_private_apis = __commonJS({
 129      "package-external:@wordpress/private-apis"(exports, module) {
 130        module.exports = window.wp.privateApis;
 131      }
 132    });
 133  
 134    // node_modules/equivalent-key-map/equivalent-key-map.js
 135    var require_equivalent_key_map = __commonJS({
 136      "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) {
 137        "use strict";
 138        function _typeof(obj) {
 139          if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
 140            _typeof = function(obj2) {
 141              return typeof obj2;
 142            };
 143          } else {
 144            _typeof = function(obj2) {
 145              return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
 146            };
 147          }
 148          return _typeof(obj);
 149        }
 150        function _classCallCheck(instance, Constructor) {
 151          if (!(instance instanceof Constructor)) {
 152            throw new TypeError("Cannot call a class as a function");
 153          }
 154        }
 155        function _defineProperties(target, props) {
 156          for (var i = 0; i < props.length; i++) {
 157            var descriptor = props[i];
 158            descriptor.enumerable = descriptor.enumerable || false;
 159            descriptor.configurable = true;
 160            if ("value" in descriptor) descriptor.writable = true;
 161            Object.defineProperty(target, descriptor.key, descriptor);
 162          }
 163        }
 164        function _createClass(Constructor, protoProps, staticProps) {
 165          if (protoProps) _defineProperties(Constructor.prototype, protoProps);
 166          if (staticProps) _defineProperties(Constructor, staticProps);
 167          return Constructor;
 168        }
 169        function getValuePair(instance, key) {
 170          var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap;
 171          if (_map.has(key)) {
 172            return _map.get(key);
 173          }
 174          var properties = Object.keys(key).sort();
 175          var map = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
 176          for (var i = 0; i < properties.length; i++) {
 177            var property = properties[i];
 178            map = map.get(property);
 179            if (map === void 0) {
 180              return;
 181            }
 182            var propertyValue = key[property];
 183            map = map.get(propertyValue);
 184            if (map === void 0) {
 185              return;
 186            }
 187          }
 188          var valuePair = map.get("_ekm_value");
 189          if (!valuePair) {
 190            return;
 191          }
 192          _map.delete(valuePair[0]);
 193          valuePair[0] = key;
 194          map.set("_ekm_value", valuePair);
 195          _map.set(key, valuePair);
 196          return valuePair;
 197        }
 198        var EquivalentKeyMap2 = /* @__PURE__ */ (function() {
 199          function EquivalentKeyMap3(iterable) {
 200            _classCallCheck(this, EquivalentKeyMap3);
 201            this.clear();
 202            if (iterable instanceof EquivalentKeyMap3) {
 203              var iterablePairs = [];
 204              iterable.forEach(function(value, key) {
 205                iterablePairs.push([key, value]);
 206              });
 207              iterable = iterablePairs;
 208            }
 209            if (iterable != null) {
 210              for (var i = 0; i < iterable.length; i++) {
 211                this.set(iterable[i][0], iterable[i][1]);
 212              }
 213            }
 214          }
 215          _createClass(EquivalentKeyMap3, [{
 216            key: "set",
 217            /**
 218             * Add or update an element with a specified key and value.
 219             *
 220             * @param {*} key   The key of the element to add.
 221             * @param {*} value The value of the element to add.
 222             *
 223             * @return {EquivalentKeyMap} Map instance.
 224             */
 225            value: function set(key, value) {
 226              if (key === null || _typeof(key) !== "object") {
 227                this._map.set(key, value);
 228                return this;
 229              }
 230              var properties = Object.keys(key).sort();
 231              var valuePair = [key, value];
 232              var map = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
 233              for (var i = 0; i < properties.length; i++) {
 234                var property = properties[i];
 235                if (!map.has(property)) {
 236                  map.set(property, new EquivalentKeyMap3());
 237                }
 238                map = map.get(property);
 239                var propertyValue = key[property];
 240                if (!map.has(propertyValue)) {
 241                  map.set(propertyValue, new EquivalentKeyMap3());
 242                }
 243                map = map.get(propertyValue);
 244              }
 245              var previousValuePair = map.get("_ekm_value");
 246              if (previousValuePair) {
 247                this._map.delete(previousValuePair[0]);
 248              }
 249              map.set("_ekm_value", valuePair);
 250              this._map.set(key, valuePair);
 251              return this;
 252            }
 253            /**
 254             * Returns a specified element.
 255             *
 256             * @param {*} key The key of the element to return.
 257             *
 258             * @return {?*} The element associated with the specified key or undefined
 259             *              if the key can't be found.
 260             */
 261          }, {
 262            key: "get",
 263            value: function get(key) {
 264              if (key === null || _typeof(key) !== "object") {
 265                return this._map.get(key);
 266              }
 267              var valuePair = getValuePair(this, key);
 268              if (valuePair) {
 269                return valuePair[1];
 270              }
 271            }
 272            /**
 273             * Returns a boolean indicating whether an element with the specified key
 274             * exists or not.
 275             *
 276             * @param {*} key The key of the element to test for presence.
 277             *
 278             * @return {boolean} Whether an element with the specified key exists.
 279             */
 280          }, {
 281            key: "has",
 282            value: function has(key) {
 283              if (key === null || _typeof(key) !== "object") {
 284                return this._map.has(key);
 285              }
 286              return getValuePair(this, key) !== void 0;
 287            }
 288            /**
 289             * Removes the specified element.
 290             *
 291             * @param {*} key The key of the element to remove.
 292             *
 293             * @return {boolean} Returns true if an element existed and has been
 294             *                   removed, or false if the element does not exist.
 295             */
 296          }, {
 297            key: "delete",
 298            value: function _delete(key) {
 299              if (!this.has(key)) {
 300                return false;
 301              }
 302              this.set(key, void 0);
 303              return true;
 304            }
 305            /**
 306             * Executes a provided function once per each key/value pair, in insertion
 307             * order.
 308             *
 309             * @param {Function} callback Function to execute for each element.
 310             * @param {*}        thisArg  Value to use as `this` when executing
 311             *                            `callback`.
 312             */
 313          }, {
 314            key: "forEach",
 315            value: function forEach(callback) {
 316              var _this = this;
 317              var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this;
 318              this._map.forEach(function(value, key) {
 319                if (key !== null && _typeof(key) === "object") {
 320                  value = value[1];
 321                }
 322                callback.call(thisArg, value, key, _this);
 323              });
 324            }
 325            /**
 326             * Removes all elements.
 327             */
 328          }, {
 329            key: "clear",
 330            value: function clear() {
 331              this._map = /* @__PURE__ */ new Map();
 332              this._arrayTreeMap = /* @__PURE__ */ new Map();
 333              this._objectTreeMap = /* @__PURE__ */ new Map();
 334            }
 335          }, {
 336            key: "size",
 337            get: function get() {
 338              return this._map.size;
 339            }
 340          }]);
 341          return EquivalentKeyMap3;
 342        })();
 343        module.exports = EquivalentKeyMap2;
 344      }
 345    });
 346  
 347    // package-external:@wordpress/url
 348    var require_url = __commonJS({
 349      "package-external:@wordpress/url"(exports, module) {
 350        module.exports = window.wp.url;
 351      }
 352    });
 353  
 354    // package-external:@wordpress/blocks
 355    var require_blocks = __commonJS({
 356      "package-external:@wordpress/blocks"(exports, module) {
 357        module.exports = window.wp.blocks;
 358      }
 359    });
 360  
 361    // package-external:@wordpress/i18n
 362    var require_i18n = __commonJS({
 363      "package-external:@wordpress/i18n"(exports, module) {
 364        module.exports = window.wp.i18n;
 365      }
 366    });
 367  
 368    // package-external:@wordpress/block-editor
 369    var require_block_editor = __commonJS({
 370      "package-external:@wordpress/block-editor"(exports, module) {
 371        module.exports = window.wp.blockEditor;
 372      }
 373    });
 374  
 375    // package-external:@wordpress/rich-text
 376    var require_rich_text = __commonJS({
 377      "package-external:@wordpress/rich-text"(exports, module) {
 378        module.exports = window.wp.richText;
 379      }
 380    });
 381  
 382    // package-external:@wordpress/deprecated
 383    var require_deprecated = __commonJS({
 384      "package-external:@wordpress/deprecated"(exports, module) {
 385        module.exports = window.wp.deprecated;
 386      }
 387    });
 388  
 389    // package-external:@wordpress/notices
 390    var require_notices = __commonJS({
 391      "package-external:@wordpress/notices"(exports, module) {
 392        module.exports = window.wp.notices;
 393      }
 394    });
 395  
 396    // package-external:@wordpress/html-entities
 397    var require_html_entities = __commonJS({
 398      "package-external:@wordpress/html-entities"(exports, module) {
 399        module.exports = window.wp.htmlEntities;
 400      }
 401    });
 402  
 403    // package-external:@wordpress/element
 404    var require_element = __commonJS({
 405      "package-external:@wordpress/element"(exports, module) {
 406        module.exports = window.wp.element;
 407      }
 408    });
 409  
 410    // vendor-external:react/jsx-runtime
 411    var require_jsx_runtime = __commonJS({
 412      "vendor-external:react/jsx-runtime"(exports, module) {
 413        module.exports = window.ReactJSXRuntime;
 414      }
 415    });
 416  
 417    // package-external:@wordpress/warning
 418    var require_warning = __commonJS({
 419      "package-external:@wordpress/warning"(exports, module) {
 420        module.exports = window.wp.warning;
 421      }
 422    });
 423  
 424    // package-external:@wordpress/primitives
 425    var require_primitives = __commonJS({
 426      "package-external:@wordpress/primitives"(exports, module) {
 427        module.exports = window.wp.primitives;
 428      }
 429    });
 430  
 431    // package-external:@wordpress/components
 432    var require_components = __commonJS({
 433      "package-external:@wordpress/components"(exports, module) {
 434        module.exports = window.wp.components;
 435      }
 436    });
 437  
 438    // packages/core-data/build-module/index.mjs
 439    var index_exports = {};
 440    __export(index_exports, {
 441      EntityProvider: () => EntityProvider,
 442      __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions,
 443      __experimentalFetchUrlData: () => experimental_fetch_url_data_default,
 444      __experimentalUseEntityRecord: () => useDeprecatedEntityRecord,
 445      __experimentalUseEntityRecords: () => useDeprecatedEntityRecords,
 446      __experimentalUseResourcePermissions: () => useDeprecatedResourcePermissions,
 447      fetchBlockPatterns: () => fetchBlockPatterns,
 448      privateApis: () => privateApis,
 449      store: () => store,
 450      useEntityBlockEditor: () => useEntityBlockEditor,
 451      useEntityId: () => useEntityId,
 452      useEntityProp: () => useEntityProp,
 453      useEntityRecord: () => useEntityRecord,
 454      useEntityRecords: () => useEntityRecords,
 455      useResourcePermissions: () => use_resource_permissions_default
 456    });
 457    var import_data20 = __toESM(require_data(), 1);
 458  
 459    // packages/core-data/build-module/reducer.mjs
 460    var import_es65 = __toESM(require_es6(), 1);
 461    var import_compose2 = __toESM(require_compose(), 1);
 462    var import_data7 = __toESM(require_data(), 1);
 463    var import_undo_manager = __toESM(require_undo_manager(), 1);
 464  
 465    // packages/core-data/build-module/utils/clear-unchanged-edits.mjs
 466    var import_es6 = __toESM(require_es6(), 1);
 467    function clearUnchangedEdits(edits, persistedRecord) {
 468      if (!persistedRecord) {
 469        return edits;
 470      }
 471      return Object.fromEntries(
 472        Object.entries(edits).map(([key, value]) => {
 473          const persisted = persistedRecord[key]?.raw ?? persistedRecord[key];
 474          return [
 475            key,
 476            (0, import_es6.default)(value, persisted) ? void 0 : value
 477          ];
 478        })
 479      );
 480    }
 481  
 482    // packages/core-data/build-module/utils/conservative-map-item.mjs
 483    var import_es62 = __toESM(require_es6(), 1);
 484    function conservativeMapItem(item, nextItem) {
 485      if (!item) {
 486        return nextItem;
 487      }
 488      let hasChanges = false;
 489      const result = {};
 490      for (const key in nextItem) {
 491        if ((0, import_es62.default)(item[key], nextItem[key])) {
 492          result[key] = item[key];
 493        } else {
 494          hasChanges = true;
 495          result[key] = nextItem[key];
 496        }
 497      }
 498      if (!hasChanges) {
 499        return item;
 500      }
 501      for (const key in item) {
 502        if (!result.hasOwnProperty(key)) {
 503          result[key] = item[key];
 504        }
 505      }
 506      return result;
 507    }
 508  
 509    // packages/core-data/build-module/utils/get-normalized-comma-separable.mjs
 510    function getNormalizedCommaSeparable(value) {
 511      if (typeof value === "string") {
 512        return value.split(",");
 513      } else if (Array.isArray(value)) {
 514        return value;
 515      }
 516      return null;
 517    }
 518    var get_normalized_comma_separable_default = getNormalizedCommaSeparable;
 519  
 520    // packages/core-data/build-module/utils/set-nested-value.mjs
 521    function setNestedValue(object, path, value) {
 522      if (!object || typeof object !== "object") {
 523        return object;
 524      }
 525      const normalizedPath = Array.isArray(path) ? path : path.split(".");
 526      normalizedPath.reduce((acc, key, idx) => {
 527        if (acc[key] === void 0) {
 528          if (Number.isInteger(normalizedPath[idx + 1])) {
 529            acc[key] = [];
 530          } else {
 531            acc[key] = {};
 532          }
 533        }
 534        if (idx === normalizedPath.length - 1) {
 535          acc[key] = value;
 536        }
 537        return acc[key];
 538      }, object);
 539      return object;
 540    }
 541  
 542    // packages/core-data/build-module/utils/get-filtered-item.mjs
 543    var filteredItemCache = /* @__PURE__ */ new WeakMap();
 544    function getFilteredItem(item, _fields) {
 545      const fields = get_normalized_comma_separable_default(_fields) ?? [];
 546      const fieldsKey = fields.join(",");
 547      let itemCache = filteredItemCache.get(item);
 548      if (itemCache) {
 549        const filtered = itemCache.get(fieldsKey);
 550        if (filtered !== void 0) {
 551          return filtered;
 552        }
 553      } else if (item !== null && typeof item === "object") {
 554        itemCache = /* @__PURE__ */ new Map();
 555        filteredItemCache.set(item, itemCache);
 556      }
 557      const filteredItem = {};
 558      for (let f = 0; f < fields.length; f++) {
 559        const field = fields[f].split(".");
 560        let value = item;
 561        field.forEach((fieldName) => {
 562          value = value?.[fieldName];
 563        });
 564        setNestedValue(filteredItem, field, value);
 565      }
 566      itemCache?.set(fieldsKey, filteredItem);
 567      return filteredItem;
 568    }
 569  
 570    // packages/core-data/build-module/utils/if-matching-action.mjs
 571    var ifMatchingAction = (isMatch) => (reducer) => (state, action) => {
 572      if (state === void 0 || isMatch(action)) {
 573        return reducer(state, action);
 574      }
 575      return state;
 576    };
 577    var if_matching_action_default = ifMatchingAction;
 578  
 579    // packages/core-data/build-module/utils/forward-resolver.mjs
 580    var forwardResolver = (resolverName) => (...args) => async ({ resolveSelect: resolveSelect2 }) => {
 581      await resolveSelect2[resolverName](...args);
 582    };
 583    var forward_resolver_default = forwardResolver;
 584  
 585    // packages/core-data/build-module/utils/replace-action.mjs
 586    var replaceAction = (replacer) => (reducer) => (state, action) => {
 587      return reducer(state, replacer(action));
 588    };
 589    var replace_action_default = replaceAction;
 590  
 591    // packages/core-data/build-module/utils/with-weak-map-cache.mjs
 592    function withWeakMapCache(fn) {
 593      const cache3 = /* @__PURE__ */ new WeakMap();
 594      return (key) => {
 595        let value;
 596        if (cache3.has(key)) {
 597          value = cache3.get(key);
 598        } else {
 599          value = fn(key);
 600          if (key !== null && typeof key === "object") {
 601            cache3.set(key, value);
 602          }
 603        }
 604        return value;
 605      };
 606    }
 607    var with_weak_map_cache_default = withWeakMapCache;
 608  
 609    // packages/core-data/build-module/utils/get-nested-value.mjs
 610    function getNestedValue(object, path, defaultValue) {
 611      if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) {
 612        return object;
 613      }
 614      const normalizedPath = Array.isArray(path) ? path : path.split(".");
 615      let value = object;
 616      normalizedPath.forEach((fieldName) => {
 617        value = value?.[fieldName];
 618      });
 619      return value !== void 0 ? value : defaultValue;
 620    }
 621  
 622    // packages/core-data/build-module/utils/is-numeric-id.mjs
 623    function isNumericID(id) {
 624      return /^\s*\d+\s*$/.test(id);
 625    }
 626  
 627    // packages/core-data/build-module/utils/user-permissions.mjs
 628    var ALLOWED_RESOURCE_ACTIONS = [
 629      "create",
 630      "read",
 631      "update",
 632      "delete"
 633    ];
 634    function getUserPermissionsFromAllowHeader(allowedMethods) {
 635      const permissions = {};
 636      const methods = {
 637        create: "POST",
 638        read: "GET",
 639        update: "PUT",
 640        delete: "DELETE"
 641      };
 642      for (const [actionName, methodName] of Object.entries(methods)) {
 643        permissions[actionName] = allowedMethods ? allowedMethods.includes(methodName) : false;
 644      }
 645      return permissions;
 646    }
 647    function getUserPermissionCacheKey(action, resource, id) {
 648      const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id]).filter(Boolean).join("/");
 649      return key;
 650    }
 651  
 652    // packages/core-data/build-module/utils/receive-intermediate-results.mjs
 653    var RECEIVE_INTERMEDIATE_RESULTS = /* @__PURE__ */ Symbol(
 654      "RECEIVE_INTERMEDIATE_RESULTS"
 655    );
 656  
 657    // packages/core-data/build-module/utils/normalize-query-for-resolution.mjs
 658    function normalizeQueryForResolution(query) {
 659      if (!query) {
 660        return void 0;
 661      }
 662      const entries = Object.entries(query).filter(
 663        ([k, v]) => (k === "context" || k === "_fields") && v !== void 0 && v !== null
 664      );
 665      return entries.length > 0 ? Object.fromEntries(entries) : void 0;
 666    }
 667  
 668    // packages/core-data/build-module/utils/save-crdt-doc.mjs
 669    var import_api_fetch = __toESM(require_api_fetch(), 1);
 670  
 671    // packages/core-data/build-module/sync.mjs
 672    var import_sync = __toESM(require_sync(), 1);
 673  
 674    // packages/core-data/build-module/lock-unlock.mjs
 675    var import_private_apis = __toESM(require_private_apis(), 1);
 676    var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
 677      "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
 678      "@wordpress/core-data"
 679    );
 680  
 681    // packages/core-data/build-module/sync.mjs
 682    var {
 683      ConnectionErrorCode,
 684      createSyncManager,
 685      Delta,
 686      CRDT_DOC_META_PERSISTENCE_KEY,
 687      CRDT_RECORD_MAP_KEY,
 688      LOCAL_EDITOR_ORIGIN,
 689      LOCAL_UNDO_IGNORED_ORIGIN,
 690      retrySyncConnection
 691    } = unlock(import_sync.privateApis);
 692    var CRDT_AUTOSAVE_SNAPSHOT_KEY = "crdt_snapshot";
 693    var syncManager;
 694    function getSyncManager() {
 695      if (syncManager) {
 696        return syncManager;
 697      }
 698      if (!globalThis.window?.__experimentalEnableRealTimeCollaboration) {
 699        return void 0;
 700      }
 701      syncManager = createSyncManager();
 702      return syncManager;
 703    }
 704    function hasSyncManager() {
 705      return Boolean(syncManager);
 706    }
 707    function getEntitySnapshot(kind, name, recordId) {
 708      if (!hasSyncManager()) {
 709        return void 0;
 710      }
 711      return getSyncManager()?.getEntitySnapshot(
 712        `$kind}/$name}`,
 713        `$recordId}`
 714      );
 715    }
 716    function entityContainsSnapshot(kind, name, recordId, encodedSnapshot) {
 717      if (!hasSyncManager()) {
 718        return false;
 719      }
 720      return getSyncManager()?.entityContainsSnapshot(
 721        `$kind}/$name}`,
 722        `$recordId}`,
 723        encodedSnapshot
 724      ) ?? false;
 725    }
 726  
 727    // packages/core-data/build-module/utils/save-crdt-doc.mjs
 728    var SYNC_SAVE_API_PATH = "/wp-sync/v1/save";
 729    var saveCRDTDocQueues = /* @__PURE__ */ new Map();
 730    async function serializeAndSaveCRDTDoc(objectType, objectId, room) {
 731      const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
 732        objectType,
 733        objectId
 734      );
 735      if (!serializedDoc) {
 736        return;
 737      }
 738      await (0, import_api_fetch.default)({
 739        path: SYNC_SAVE_API_PATH,
 740        method: "POST",
 741        data: {
 742          room,
 743          doc: serializedDoc
 744        }
 745      });
 746    }
 747    async function saveCRDTDoc(objectType, objectId) {
 748      const room = `$objectType}:$objectId}`;
 749      const previousSave = saveCRDTDocQueues.get(room) || Promise.resolve();
 750      const currentSave = previousSave.catch(() => {
 751      }).then(() => serializeAndSaveCRDTDoc(objectType, objectId, room));
 752      saveCRDTDocQueues.set(room, currentSave);
 753      try {
 754        await currentSave;
 755      } finally {
 756        if (saveCRDTDocQueues.get(room) === currentSave) {
 757          saveCRDTDocQueues.delete(room);
 758        }
 759      }
 760    }
 761  
 762    // packages/core-data/build-module/utils/get-pagination-meta.mjs
 763    function getPaginationMeta(headers) {
 764      const totalItems = parseInt(headers.get("X-WP-Total") ?? "");
 765      const totalPages = parseInt(headers.get("X-WP-TotalPages") ?? "");
 766      return {
 767        totalItems: Number.isFinite(totalItems) ? totalItems : null,
 768        totalPages: Number.isFinite(totalPages) ? totalPages : null
 769      };
 770    }
 771  
 772    // packages/core-data/build-module/queried-data/actions.mjs
 773    function receiveItems(items2, edits, meta) {
 774      return {
 775        type: "RECEIVE_ITEMS",
 776        items: items2,
 777        persistedEdits: edits,
 778        meta
 779      };
 780    }
 781    function removeItems(kind, name, records, invalidateCache = false) {
 782      return {
 783        type: "REMOVE_ITEMS",
 784        itemIds: Array.isArray(records) ? records : [records],
 785        kind,
 786        name,
 787        invalidateCache
 788      };
 789    }
 790    function receiveQueriedItems(items2, query = {}, edits, meta) {
 791      return {
 792        ...receiveItems(items2, edits, meta),
 793        query
 794      };
 795    }
 796  
 797    // packages/core-data/build-module/queried-data/selectors.mjs
 798    var import_equivalent_key_map = __toESM(require_equivalent_key_map(), 1);
 799  
 800    // packages/core-data/build-module/queried-data/get-query-parts.mjs
 801    var import_url = __toESM(require_url(), 1);
 802    function getQueryParts(query) {
 803      const parts = {
 804        stableKey: "",
 805        page: 1,
 806        perPage: 10,
 807        offset: null,
 808        fields: null,
 809        include: null,
 810        context: "default"
 811      };
 812      const keys = Object.keys(query).sort();
 813      for (let i = 0; i < keys.length; i++) {
 814        const key = keys[i];
 815        let value = query[key];
 816        switch (key) {
 817          case "page":
 818            parts[key] = Number(value);
 819            break;
 820          case "per_page":
 821            parts.perPage = Number(value);
 822            break;
 823          case "offset": {
 824            const numericOffset = Number(value);
 825            if (Number.isFinite(numericOffset)) {
 826              parts.offset = numericOffset;
 827            }
 828            break;
 829          }
 830          case "context":
 831            parts.context = value;
 832            break;
 833          default:
 834            if (key === "_fields") {
 835              parts.fields = get_normalized_comma_separable_default(value) ?? [];
 836              value = parts.fields.join();
 837            }
 838            if (key === "include") {
 839              if (typeof value === "number") {
 840                value = value.toString();
 841              }
 842              parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number);
 843              value = parts.include.join();
 844            }
 845            parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1);
 846        }
 847      }
 848      return parts;
 849    }
 850    var get_query_parts_default = with_weak_map_cache_default(getQueryParts);
 851  
 852    // packages/core-data/build-module/queried-data/selectors.mjs
 853    var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap();
 854    function getQueriedItemsUncached(state, query, options = {}) {
 855      const { supportsPagination = true } = options;
 856      const {
 857        stableKey,
 858        page,
 859        perPage,
 860        offset: queryOffset,
 861        include,
 862        fields,
 863        context
 864      } = get_query_parts_default(query);
 865      const itemIds = state.queries?.[context]?.[stableKey]?.itemIds;
 866      if (!itemIds) {
 867        return null;
 868      }
 869      const isPaginated = supportsPagination && perPage !== -1;
 870      const startOffset = isPaginated ? queryOffset ?? (page - 1) * perPage : 0;
 871      const endOffset = isPaginated ? Math.min(startOffset + perPage, itemIds.length) : itemIds.length;
 872      if (isPaginated && itemIds.length < startOffset + perPage) {
 873        const totalItems = state.queries[context][stableKey].meta?.totalItems;
 874        if (Number.isFinite(totalItems) && itemIds.length < totalItems) {
 875          return null;
 876        }
 877      }
 878      const items2 = [];
 879      for (let i = startOffset; i < endOffset; i++) {
 880        const itemId = itemIds[i];
 881        if (Array.isArray(include) && !include.includes(itemId)) {
 882          continue;
 883        }
 884        if (itemId === void 0) {
 885          continue;
 886        }
 887        if (!state.items[context]?.hasOwnProperty(itemId)) {
 888          return null;
 889        }
 890        const item = state.items[context][itemId];
 891        let filteredItem;
 892        if (Array.isArray(fields)) {
 893          filteredItem = {};
 894          for (let f = 0; f < fields.length; f++) {
 895            const field = fields[f].split(".");
 896            let value = item;
 897            field.forEach((fieldName) => {
 898              value = value?.[fieldName];
 899            });
 900            setNestedValue(filteredItem, field, value);
 901          }
 902        } else {
 903          if (!state.itemIsComplete[context]?.[itemId]) {
 904            return null;
 905          }
 906          filteredItem = item;
 907        }
 908        items2.push(filteredItem);
 909      }
 910      return items2;
 911    }
 912    function getQueriedItems(state, query = {}, options = {}) {
 913      let queriedItemsCache = queriedItemsCacheByState.get(state);
 914      if (queriedItemsCache) {
 915        const queriedItems = queriedItemsCache.get(query);
 916        if (queriedItems !== void 0) {
 917          return queriedItems;
 918        }
 919      } else {
 920        queriedItemsCache = new import_equivalent_key_map.default();
 921        queriedItemsCacheByState.set(state, queriedItemsCache);
 922      }
 923      const items2 = getQueriedItemsUncached(state, query, options);
 924      queriedItemsCache.set(query, items2);
 925      return items2;
 926    }
 927    function getQueriedTotalItems(state, query = {}) {
 928      const { stableKey, context } = get_query_parts_default(query);
 929      return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null;
 930    }
 931    function getQueriedTotalPages(state, query = {}) {
 932      const { stableKey, context } = get_query_parts_default(query);
 933      return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null;
 934    }
 935  
 936    // packages/core-data/build-module/queried-data/reducer.mjs
 937    var import_data6 = __toESM(require_data(), 1);
 938    var import_compose = __toESM(require_compose(), 1);
 939  
 940    // node_modules/tslib/tslib.es6.mjs
 941    var __assign = function() {
 942      __assign = Object.assign || function __assign2(t) {
 943        for (var s, i = 1, n = arguments.length; i < n; i++) {
 944          s = arguments[i];
 945          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
 946        }
 947        return t;
 948      };
 949      return __assign.apply(this, arguments);
 950    };
 951  
 952    // node_modules/lower-case/dist.es2015/index.js
 953    function lowerCase(str) {
 954      return str.toLowerCase();
 955    }
 956  
 957    // node_modules/no-case/dist.es2015/index.js
 958    var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
 959    var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
 960    function noCase(input, options) {
 961      if (options === void 0) {
 962        options = {};
 963      }
 964      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;
 965      var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
 966      var start = 0;
 967      var end = result.length;
 968      while (result.charAt(start) === "\0")
 969        start++;
 970      while (result.charAt(end - 1) === "\0")
 971        end--;
 972      return result.slice(start, end).split("\0").map(transform).join(delimiter);
 973    }
 974    function replace(input, re, value) {
 975      if (re instanceof RegExp)
 976        return input.replace(re, value);
 977      return re.reduce(function(input2, re2) {
 978        return input2.replace(re2, value);
 979      }, input);
 980    }
 981  
 982    // node_modules/pascal-case/dist.es2015/index.js
 983    function pascalCaseTransform(input, index) {
 984      var firstChar = input.charAt(0);
 985      var lowerChars = input.substr(1).toLowerCase();
 986      if (index > 0 && firstChar >= "0" && firstChar <= "9") {
 987        return "_" + firstChar + lowerChars;
 988      }
 989      return "" + firstChar.toUpperCase() + lowerChars;
 990    }
 991    function pascalCase(input, options) {
 992      if (options === void 0) {
 993        options = {};
 994      }
 995      return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
 996    }
 997  
 998    // node_modules/camel-case/dist.es2015/index.js
 999    function camelCaseTransform(input, index) {
1000      if (index === 0)
1001        return input.toLowerCase();
1002      return pascalCaseTransform(input, index);
1003    }
1004    function camelCase(input, options) {
1005      if (options === void 0) {
1006        options = {};
1007      }
1008      return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
1009    }
1010  
1011    // node_modules/upper-case-first/dist.es2015/index.js
1012    function upperCaseFirst(input) {
1013      return input.charAt(0).toUpperCase() + input.substr(1);
1014    }
1015  
1016    // node_modules/capital-case/dist.es2015/index.js
1017    function capitalCaseTransform(input) {
1018      return upperCaseFirst(input.toLowerCase());
1019    }
1020    function capitalCase(input, options) {
1021      if (options === void 0) {
1022        options = {};
1023      }
1024      return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
1025    }
1026  
1027    // packages/core-data/build-module/entities.mjs
1028    var import_api_fetch2 = __toESM(require_api_fetch(), 1);
1029    var import_blocks4 = __toESM(require_blocks(), 1);
1030    var import_i18n = __toESM(require_i18n(), 1);
1031  
1032    // packages/core-data/build-module/awareness/post-editor-awareness.mjs
1033    var import_data4 = __toESM(require_data(), 1);
1034    var import_sync9 = __toESM(require_sync(), 1);
1035    var import_block_editor3 = __toESM(require_block_editor(), 1);
1036  
1037    // packages/core-data/build-module/awareness/base-awareness.mjs
1038    var import_data = __toESM(require_data(), 1);
1039  
1040    // packages/core-data/build-module/awareness/config.mjs
1041    var AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS = 100;
1042    var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5;
1043    var REMOVAL_DELAY_IN_MS = 5e3;
1044  
1045    // packages/core-data/build-module/awareness/typed-awareness.mjs
1046    var import_sync3 = __toESM(require_sync(), 1);
1047  
1048    // packages/core-data/build-module/awareness/utils.mjs
1049    function getBrowserName() {
1050      const userAgent = window.navigator.userAgent;
1051      let browserName = "Unknown";
1052      if (userAgent.includes("Firefox")) {
1053        browserName = "Firefox";
1054      } else if (userAgent.includes("Edg")) {
1055        browserName = "Microsoft Edge";
1056      } else if (userAgent.includes("Chrome") && !userAgent.includes("Edg")) {
1057        browserName = "Chrome";
1058      } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) {
1059        browserName = "Safari";
1060      } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) {
1061        browserName = "Internet Explorer";
1062      } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) {
1063        browserName = "Opera";
1064      }
1065      return browserName;
1066    }
1067    function areMapsEqual(map1, map2, comparatorFn) {
1068      if (map1.size !== map2.size) {
1069        return false;
1070      }
1071      for (const [key, value1] of map1.entries()) {
1072        if (!map2.has(key)) {
1073          return false;
1074        }
1075        if (!comparatorFn(value1, map2.get(key))) {
1076          return false;
1077        }
1078      }
1079      return true;
1080    }
1081    function areCollaboratorInfosEqual(collaboratorInfo1, collaboratorInfo2) {
1082      if (!collaboratorInfo1 || !collaboratorInfo2) {
1083        return collaboratorInfo1 === collaboratorInfo2;
1084      }
1085      if (Object.keys(collaboratorInfo1).length !== Object.keys(collaboratorInfo2).length) {
1086        return false;
1087      }
1088      return Object.entries(collaboratorInfo1).every(([key, value]) => {
1089        return value === collaboratorInfo2[key];
1090      });
1091    }
1092    function hasValidAvatarUrls(value) {
1093      if ("object" !== typeof value || null === value || Array.isArray(value)) {
1094        return false;
1095      }
1096      return ["24", "48", "96"].every(
1097        (size) => !(size in value) || "string" === typeof value[size]
1098      );
1099    }
1100    function isCollaboratorInfo(value) {
1101      if ("object" !== typeof value || null === value) {
1102        return false;
1103      }
1104      return "id" in value && "name" in value && "slug" in value && "browserType" in value && "enteredAt" in value && (null === value.id || "number" === typeof value.id && Number.isInteger(value.id) && value.id > 0) && "string" === typeof value.name && "" !== value.name.trim() && "string" === typeof value.slug && (!("avatar_urls" in value) || hasValidAvatarUrls(value.avatar_urls)) && "string" === typeof value.browserType && "number" === typeof value.enteredAt && Number.isFinite(value.enteredAt);
1105    }
1106    function generateCollaboratorInfo(currentCollaborator, clientId) {
1107      const presentationInfo = {
1108        browserType: getBrowserName(),
1109        enteredAt: Date.now()
1110      };
1111      if ("object" === typeof currentCollaborator && currentCollaborator) {
1112        const user = currentCollaborator;
1113        if ("id" in user && "name" in user) {
1114          const collaboratorInfo = {
1115            ...presentationInfo,
1116            ..."avatar_urls" in user && hasValidAvatarUrls(user.avatar_urls) ? { avatar_urls: user.avatar_urls } : {},
1117            id: user.id,
1118            name: user.name,
1119            slug: "slug" in user && "string" === typeof user.slug ? user.slug : ""
1120          };
1121          if (isCollaboratorInfo(collaboratorInfo) && null !== collaboratorInfo.id) {
1122            return collaboratorInfo;
1123          }
1124        }
1125      }
1126      return {
1127        ...presentationInfo,
1128        id: null,
1129        // Keep shared awareness data language-neutral. The editor localizes this
1130        // fallback name for the viewer when it is displayed.
1131        name: "Anonymous User",
1132        slug: `anonymous-$clientId}`
1133      };
1134    }
1135    function getRecordValue(obj, key) {
1136      if ("object" === typeof obj && null !== obj && key in obj) {
1137        return obj[key];
1138      }
1139      return null;
1140    }
1141    function getTypedKeys(obj) {
1142      return Object.keys(obj);
1143    }
1144  
1145    // packages/core-data/build-module/awareness/typed-awareness.mjs
1146    var TypedAwareness = class extends import_sync3.Awareness {
1147      /**
1148       * Get the states from an awareness document.
1149       */
1150      getStates() {
1151        return super.getStates();
1152      }
1153      /**
1154       * Get a local state field from an awareness document.
1155       * @param field
1156       */
1157      getLocalStateField(field) {
1158        const state = this.getLocalState();
1159        return getRecordValue(state, field);
1160      }
1161      /**
1162       * Set a local state field on an awareness document.
1163       * @param field
1164       * @param value
1165       */
1166      setLocalStateField(field, value) {
1167        super.setLocalStateField(field, value);
1168      }
1169    };
1170  
1171    // packages/core-data/build-module/awareness/awareness-state.mjs
1172    var AwarenessWithEqualityChecks = class extends TypedAwareness {
1173      /** OVERRIDDEN METHODS */
1174      /**
1175       * Set a local state field on an awareness document. Calling this method may
1176       * trigger rerenders of any subscribed components.
1177       *
1178       * Equality checks are provided by the abstract `equalityFieldChecks` property.
1179       * @param field - The field to set.
1180       * @param value - The value to set.
1181       */
1182      setLocalStateField(field, value) {
1183        if (this.isFieldEqual(
1184          field,
1185          value,
1186          this.getLocalStateField(field) ?? void 0
1187        )) {
1188          return;
1189        }
1190        super.setLocalStateField(field, value);
1191      }
1192      /** CUSTOM METHODS */
1193      /**
1194       * Determine if a field value has changed using the provided equality checks.
1195       * @param field  - The field to check.
1196       * @param value1 - The first value to compare.
1197       * @param value2 - The second value to compare.
1198       */
1199      isFieldEqual(field, value1, value2) {
1200        if (["clientId", "isConnected", "isMe"].includes(field)) {
1201          return value1 === value2;
1202        }
1203        if (field in this.equalityFieldChecks) {
1204          const fn = this.equalityFieldChecks[field];
1205          return fn(value1, value2);
1206        }
1207        throw new Error(
1208          `No equality check implemented for awareness state field "$field.toString()}".`
1209        );
1210      }
1211      /**
1212       * Determine if two states are equal by comparing each field using the
1213       * provided equality checks.
1214       * @param state1 - The first state to compare.
1215       * @param state2 - The second state to compare.
1216       */
1217      isStateEqual(state1, state2) {
1218        return [
1219          .../* @__PURE__ */ new Set([
1220            ...getTypedKeys(state1),
1221            ...getTypedKeys(state2)
1222          ])
1223        ].every((field) => {
1224          const value1 = state1[field];
1225          const value2 = state2[field];
1226          return this.isFieldEqual(field, value1, value2);
1227        });
1228      }
1229    };
1230    var AwarenessState = class extends AwarenessWithEqualityChecks {
1231      /** CUSTOM PROPERTIES */
1232      /**
1233       * Whether the setUp method has been called, to avoid running it multiple
1234       * times.
1235       */
1236      hasSetupRun = false;
1237      /**
1238       * We keep track of all seen states during the current session for two reasons:
1239       *
1240       * 1. So that we can represent recently disconnected collaborators in our UI, even
1241       *    after they have been removed from the awareness document.
1242       * 2. So that we can provide debug information about all collaborators seen during
1243       *    the session.
1244       */
1245      disconnectedCollaborators = /* @__PURE__ */ new Set();
1246      seenStates = /* @__PURE__ */ new Map();
1247      /**
1248       * Hold a snapshot of the previous awareness state allows us to compare the
1249       * state values and avoid unnecessary updates to subscribers.
1250       */
1251      previousSnapshot = /* @__PURE__ */ new Map();
1252      stateSubscriptions = [];
1253      /**
1254       * In some cases, we may want to throttle setting local state fields to avoid
1255       * overwhelming the awareness document with rapid updates. At the same time, we
1256       * want to ensure that when we read our own state locally, we get the latest
1257       * value -- even if it hasn't yet been set on the awareness instance.
1258       */
1259      myThrottledState = {};
1260      throttleTimeouts = /* @__PURE__ */ new Map();
1261      /** CUSTOM METHODS */
1262      /**
1263       * Set up the awareness state. This method is idempotent and will only run
1264       * once. Subclasses should override `onSetUp()` instead of this method to
1265       * add their own setup logic.
1266       *
1267       * This is defined as a readonly arrow function property to prevent
1268       * subclasses from overriding it.
1269       */
1270      setUp = () => {
1271        if (this.hasSetupRun) {
1272          return;
1273        }
1274        this.hasSetupRun = true;
1275        this.onSetUp();
1276        this.on(
1277          "change",
1278          ({ added, removed, updated }) => {
1279            [...added, ...updated].forEach((id) => {
1280              this.disconnectedCollaborators.delete(id);
1281            });
1282            removed.forEach((id) => {
1283              this.disconnectedCollaborators.add(id);
1284              setTimeout(() => {
1285                this.disconnectedCollaborators.delete(id);
1286                this.updateSubscribers(
1287                  true
1288                  /* force update */
1289                );
1290              }, REMOVAL_DELAY_IN_MS);
1291            });
1292            this.updateSubscribers();
1293          }
1294        );
1295      };
1296      /**
1297       * Get the most recent state from the last processed change event.
1298       *
1299       * @return An array of EnhancedState< State >.
1300       */
1301      getCurrentState() {
1302        return Array.from(this.previousSnapshot.values());
1303      }
1304      /**
1305       * Get all seen states in this session to enable debug reporting.
1306       */
1307      getSeenStates() {
1308        return this.seenStates;
1309      }
1310      /**
1311       * Allow external code to subscribe to awareness state changes.
1312       * @param callback - The callback to subscribe to.
1313       */
1314      onStateChange(callback) {
1315        this.stateSubscriptions.push(callback);
1316        return () => {
1317          this.stateSubscriptions = this.stateSubscriptions.filter(
1318            (cb) => cb !== callback
1319          );
1320        };
1321      }
1322      /**
1323       * Set a local state field on an awareness document with throttle. See caveats
1324       * of this.setLocalStateField.
1325       * @param field - The field to set.
1326       * @param value - The value to set.
1327       * @param wait  - The wait time in milliseconds.
1328       */
1329      setThrottledLocalStateField(field, value, wait) {
1330        this.setLocalStateField(field, value);
1331        this.throttleTimeouts.set(
1332          field,
1333          setTimeout(() => {
1334            this.throttleTimeouts.delete(field);
1335            if (this.myThrottledState[field]) {
1336              this.setLocalStateField(
1337                field,
1338                this.myThrottledState[field]
1339              );
1340              delete this.myThrottledState[field];
1341            }
1342          }, wait)
1343        );
1344      }
1345      /**
1346       * Set the current collaborator's connection status as awareness state.
1347       * @param isConnected - The connection status.
1348       */
1349      setConnectionStatus(isConnected) {
1350        if (isConnected) {
1351          this.disconnectedCollaborators.delete(this.clientID);
1352        } else {
1353          this.disconnectedCollaborators.add(this.clientID);
1354        }
1355        this.updateSubscribers(
1356          true
1357          /* force update */
1358        );
1359      }
1360      /**
1361       * Update all subscribed listeners with the latest awareness state.
1362       * @param forceUpdate - Whether to force an update.
1363       */
1364      updateSubscribers(forceUpdate = false) {
1365        if (!this.stateSubscriptions.length) {
1366          return;
1367        }
1368        const states = this.getStates();
1369        this.seenStates = new Map([
1370          ...this.seenStates.entries(),
1371          ...states.entries()
1372        ]);
1373        const updatedStates = new Map(
1374          [...this.disconnectedCollaborators, ...states.keys()].filter((clientId) => {
1375            return Object.keys(this.seenStates.get(clientId) ?? {}).length > 0;
1376          }).map((clientId) => {
1377            const rawState = this.seenStates.get(clientId);
1378            const isConnected = !this.disconnectedCollaborators.has(clientId);
1379            const isMe = clientId === this.clientID;
1380            const myState = isMe ? this.myThrottledState : {};
1381            const state = {
1382              ...rawState,
1383              ...myState,
1384              clientId,
1385              isConnected,
1386              isMe
1387            };
1388            return [clientId, state];
1389          })
1390        );
1391        if (!forceUpdate) {
1392          if (areMapsEqual(
1393            this.previousSnapshot,
1394            updatedStates,
1395            this.isStateEqual.bind(this)
1396          )) {
1397            return;
1398          }
1399        }
1400        this.previousSnapshot = updatedStates;
1401        this.stateSubscriptions.forEach((callback) => {
1402          callback(Array.from(updatedStates.values()));
1403        });
1404      }
1405    };
1406  
1407    // packages/core-data/build-module/name.mjs
1408    var STORE_NAME = "core";
1409  
1410    // packages/core-data/build-module/awareness/base-awareness.mjs
1411    var BaseAwarenessState = class extends AwarenessState {
1412      onSetUp() {
1413        void this.setCurrentCollaboratorInfo();
1414      }
1415      /**
1416       * Set the current collaborator info in the local state.
1417       */
1418      async setCurrentCollaboratorInfo() {
1419        let currentUser2;
1420        try {
1421          currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser();
1422        } catch {
1423        }
1424        this.setLocalStateField(
1425          "collaboratorInfo",
1426          generateCollaboratorInfo(currentUser2, this.clientID)
1427        );
1428      }
1429    };
1430    var baseEqualityFieldChecks = {
1431      collaboratorInfo: areCollaboratorInfosEqual
1432    };
1433    var BaseAwareness = class extends BaseAwarenessState {
1434      equalityFieldChecks = baseEqualityFieldChecks;
1435    };
1436  
1437    // packages/core-data/build-module/awareness/block-lookup.mjs
1438    var import_data2 = __toESM(require_data(), 1);
1439    var import_sync4 = __toESM(require_sync(), 1);
1440    var import_block_editor = __toESM(require_block_editor(), 1);
1441    function getContainingBlockYMap(yType) {
1442      let current = yType;
1443      while (current) {
1444        const parent = current.parent;
1445        if (parent instanceof import_sync4.Y.Map && parent.parent instanceof import_sync4.Y.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof import_sync4.Y.Array) {
1446          return parent;
1447        }
1448        current = parent instanceof import_sync4.Y.AbstractType ? parent : null;
1449      }
1450      return null;
1451    }
1452    function getBlockPathInYdoc(yType) {
1453      const path = [];
1454      let current = yType;
1455      while (current) {
1456        const parentArray = current.parent;
1457        if (!parentArray || !(parentArray instanceof import_sync4.Y.Array)) {
1458          return null;
1459        }
1460        let index = -1;
1461        for (let i = 0; i < parentArray.length; i++) {
1462          if (parentArray.get(i) === current) {
1463            index = i;
1464            break;
1465          }
1466        }
1467        if (index === -1) {
1468          return null;
1469        }
1470        path.unshift(index);
1471        const grandparent = parentArray.parent;
1472        if (grandparent instanceof import_sync4.Y.Map && grandparent.get("clientId") !== void 0) {
1473          current = grandparent;
1474        } else {
1475          break;
1476        }
1477      }
1478      return path;
1479    }
1480    function resolveBlockClientIdByPath(path, blocks) {
1481      if (path.length === 0) {
1482        return null;
1483      }
1484      for (let i = 0; i < path.length; i++) {
1485        const block = blocks[path[i]];
1486        if (!block) {
1487          return null;
1488        }
1489        if (i === path.length - 1) {
1490          return block.clientId;
1491        }
1492        blocks = block.innerBlocks;
1493      }
1494      return null;
1495    }
1496    function usePostContentBlocks() {
1497      return (0, import_data2.useSelect)((select5) => {
1498        const { getBlocksByName, getClientIdsTree } = unlock(
1499          select5(import_block_editor.store)
1500        );
1501        const [postContentClientId] = getBlocksByName("core/post-content");
1502        return getClientIdsTree(postContentClientId ?? "");
1503      }, []);
1504    }
1505  
1506    // packages/core-data/build-module/utils/crdt-utils.mjs
1507    var import_sync5 = __toESM(require_sync(), 1);
1508    var import_rich_text = __toESM(require_rich_text(), 1);
1509    function getRootMap(doc, key) {
1510      return doc.getMap(key);
1511    }
1512    function createYMap(partial = {}) {
1513      return new import_sync5.Y.Map(Object.entries(partial));
1514    }
1515    function isYMap(value) {
1516      return value instanceof import_sync5.Y.Map;
1517    }
1518    function asRichTextOffset(offset) {
1519      return offset;
1520    }
1521    function asHtmlStringIndex(index) {
1522      return index;
1523    }
1524    function getYTextByAttributeKey(attributes, attributeKey) {
1525      const directValue = attributes.get(attributeKey);
1526      if (directValue instanceof import_sync5.Y.Text) {
1527        return directValue;
1528      }
1529      let value = attributes;
1530      for (const pathPart of attributeKey.split(".")) {
1531        if (value instanceof import_sync5.Y.Map) {
1532          value = value.get(pathPart);
1533        } else if (value instanceof import_sync5.Y.Array) {
1534          const index = Number.parseInt(pathPart, 10);
1535          if (!Number.isSafeInteger(index) || index < 0 || index.toString() !== pathPart) {
1536            return null;
1537          }
1538          value = value.get(index);
1539        } else {
1540          return null;
1541        }
1542      }
1543      return value instanceof import_sync5.Y.Text ? value : null;
1544    }
1545    function findBlockByClientIdInDoc(blockId, ydoc) {
1546      const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
1547      const blocks = ymap.get("blocks");
1548      if (!(blocks instanceof import_sync5.Y.Array)) {
1549        return null;
1550      }
1551      return findBlockByClientIdInBlocks(blockId, blocks);
1552    }
1553    var MARKER_START = 57344;
1554    function pickMarker(text) {
1555      const tryCount = 16;
1556      for (let code = MARKER_START; code < MARKER_START + tryCount; code++) {
1557        const candidate = String.fromCharCode(code);
1558        if (!text.includes(candidate)) {
1559          return candidate;
1560        }
1561      }
1562      return null;
1563    }
1564    function htmlIndexToRichTextOffset(html, htmlIndex) {
1565      if (!html.includes("<") && !html.includes("&")) {
1566        return asRichTextOffset(htmlIndex);
1567      }
1568      const marker = pickMarker(html);
1569      if (!marker) {
1570        return asRichTextOffset(htmlIndex);
1571      }
1572      const withMarker = html.slice(0, htmlIndex) + marker + html.slice(htmlIndex);
1573      const value = (0, import_rich_text.create)({ html: withMarker });
1574      const markerPos = value.text.indexOf(marker);
1575      return asRichTextOffset(markerPos === -1 ? htmlIndex : markerPos);
1576    }
1577    function richTextOffsetToHtmlIndex(html, richTextOffset) {
1578      if (!html.includes("<") && !html.includes("&")) {
1579        return asHtmlStringIndex(richTextOffset);
1580      }
1581      const marker = pickMarker(html);
1582      if (!marker) {
1583        return asHtmlStringIndex(richTextOffset);
1584      }
1585      const value = (0, import_rich_text.create)({ html });
1586      const markerValue = (0, import_rich_text.create)({ text: marker });
1587      if (value.formats[richTextOffset]) {
1588        markerValue.formats[0] = value.formats[richTextOffset];
1589      }
1590      const withMarker = (0, import_rich_text.insert)(
1591        value,
1592        markerValue,
1593        richTextOffset,
1594        richTextOffset
1595      );
1596      const htmlWithMarker = (0, import_rich_text.toHTMLString)({ value: withMarker });
1597      const markerIndex = htmlWithMarker.indexOf(marker);
1598      return asHtmlStringIndex(
1599        markerIndex === -1 ? richTextOffset : markerIndex
1600      );
1601    }
1602    function findBlockByClientIdInBlocks(blockId, blocks) {
1603      for (const block of blocks) {
1604        if (block.get("clientId") === blockId) {
1605          return block;
1606        }
1607        const innerBlocks = block.get("innerBlocks");
1608        if (innerBlocks && innerBlocks.length > 0) {
1609          const innerBlock = findBlockByClientIdInBlocks(
1610            blockId,
1611            innerBlocks
1612          );
1613          if (innerBlock) {
1614            return innerBlock;
1615          }
1616        }
1617      }
1618      return null;
1619    }
1620  
1621    // packages/core-data/build-module/utils/crdt-user-selections.mjs
1622    var import_data3 = __toESM(require_data(), 1);
1623    var import_sync7 = __toESM(require_sync(), 1);
1624    var import_block_editor2 = __toESM(require_block_editor(), 1);
1625    var SelectionType = /* @__PURE__ */ ((SelectionType2) => {
1626      SelectionType2["None"] = "none";
1627      SelectionType2["Cursor"] = "cursor";
1628      SelectionType2["SelectionInOneBlock"] = "selection-in-one-block";
1629      SelectionType2["SelectionInMultipleBlocks"] = "selection-in-multiple-blocks";
1630      SelectionType2["WholeBlock"] = "whole-block";
1631      return SelectionType2;
1632    })(SelectionType || {});
1633    var SelectionDirection = /* @__PURE__ */ ((SelectionDirection2) => {
1634      SelectionDirection2["Forward"] = "f";
1635      SelectionDirection2["Backward"] = "b";
1636      return SelectionDirection2;
1637    })(SelectionDirection || {});
1638    function getSelectionState(selectionStart, selectionEnd, yDoc, options) {
1639      const { selectionDirection } = options ?? {};
1640      const ymap = getRootMap(yDoc, CRDT_RECORD_MAP_KEY);
1641      const yBlocks = ymap.get("blocks");
1642      const isSelectionEmpty = Object.keys(selectionStart).length === 0;
1643      const noSelection = {
1644        type: "none"
1645        /* None */
1646      };
1647      if (isSelectionEmpty || !yBlocks) {
1648        return noSelection;
1649      }
1650      const isSelectionInOneBlock = selectionStart.clientId === selectionEnd.clientId;
1651      const isCursorOnly = isSelectionInOneBlock && selectionStart.offset === selectionEnd.offset;
1652      const isSelectionAWholeBlock = isSelectionInOneBlock && selectionStart.offset === void 0 && selectionEnd.offset === void 0;
1653      if (isSelectionAWholeBlock) {
1654        const path = getBlockPathForLocalClientId(selectionStart.clientId);
1655        const blockPosition = path ? createRelativePositionForBlockPath(path, yBlocks) : null;
1656        if (!blockPosition) {
1657          return noSelection;
1658        }
1659        return {
1660          type: "whole-block",
1661          blockPosition
1662        };
1663      } else if (isCursorOnly) {
1664        const cursorPosition = getCursorPosition(selectionStart, yBlocks);
1665        if (!cursorPosition) {
1666          return noSelection;
1667        }
1668        return {
1669          type: "cursor",
1670          cursorPosition
1671        };
1672      } else if (isSelectionInOneBlock) {
1673        const cursorStartPosition = getCursorPosition(
1674          selectionStart,
1675          yBlocks
1676        );
1677        const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks);
1678        if (!cursorStartPosition || !cursorEndPosition) {
1679          return noSelection;
1680        }
1681        return {
1682          type: "selection-in-one-block",
1683          cursorStartPosition,
1684          cursorEndPosition,
1685          selectionDirection
1686        };
1687      }
1688      const startEndpoint = getSelectionEndpoint(selectionStart, yBlocks);
1689      const endEndpoint = getSelectionEndpoint(selectionEnd, yBlocks);
1690      if (!startEndpoint || !endEndpoint) {
1691        return noSelection;
1692      }
1693      return {
1694        type: "selection-in-multiple-blocks",
1695        startEndpoint,
1696        endEndpoint,
1697        selectionDirection
1698      };
1699    }
1700    function getCursorPosition(selection, blocks) {
1701      const path = getBlockPathForLocalClientId(selection.clientId);
1702      const block = path ? findBlockByPath(path, blocks) : null;
1703      if (!block || !selection.attributeKey || void 0 === selection.offset) {
1704        return null;
1705      }
1706      const attributes = block.get("attributes");
1707      const currentYText = attributes ? getYTextByAttributeKey(attributes, selection.attributeKey) : null;
1708      if (!(currentYText instanceof import_sync7.Y.Text)) {
1709        return null;
1710      }
1711      const relativePosition = import_sync7.Y.createRelativePositionFromTypeIndex(
1712        currentYText,
1713        richTextOffsetToHtmlIndex(
1714          currentYText.toString(),
1715          asRichTextOffset(selection.offset)
1716        )
1717      );
1718      return {
1719        relativePosition,
1720        absoluteOffset: selection.offset,
1721        attributeKey: selection.attributeKey
1722      };
1723    }
1724    function getSelectionEndpoint(selection, blocks) {
1725      const cursorPosition = getCursorPosition(selection, blocks);
1726      if (cursorPosition) {
1727        return { type: "cursor", cursorPosition };
1728      }
1729      const path = getBlockPathForLocalClientId(selection.clientId);
1730      const blockPosition = path ? createRelativePositionForBlockPath(path, blocks) : null;
1731      if (blockPosition) {
1732        return { type: "whole-block", blockPosition };
1733      }
1734      return null;
1735    }
1736    function getBlockPathForLocalClientId(clientId) {
1737      const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data3.select)(import_block_editor2.store);
1738      const path = [];
1739      let current = clientId;
1740      while (current) {
1741        const index = getBlockIndex(current);
1742        if (index === -1) {
1743          return null;
1744        }
1745        path.unshift(index);
1746        const parent = getBlockRootClientId(current);
1747        if (!parent) {
1748          break;
1749        }
1750        const parentName = getBlockName(parent);
1751        if (parentName === "core/post-content") {
1752          break;
1753        }
1754        current = parent;
1755      }
1756      return path.length > 0 ? path : null;
1757    }
1758    function findBlockByPath(path, blocks) {
1759      let currentBlocks = blocks;
1760      for (let i = 0; i < path.length; i++) {
1761        if (path[i] >= currentBlocks.length) {
1762          return null;
1763        }
1764        const block = currentBlocks.get(path[i]);
1765        if (!block) {
1766          return null;
1767        }
1768        if (i === path.length - 1) {
1769          return block;
1770        }
1771        currentBlocks = block.get("innerBlocks") ?? new import_sync7.Y.Array();
1772      }
1773      return null;
1774    }
1775    function createRelativePositionForBlockPath(path, blocks) {
1776      let currentBlocks = blocks;
1777      for (let i = 0; i < path.length; i++) {
1778        if (path[i] >= currentBlocks.length) {
1779          return null;
1780        }
1781        if (i === path.length - 1) {
1782          return import_sync7.Y.createRelativePositionFromTypeIndex(
1783            currentBlocks,
1784            path[i]
1785          );
1786        }
1787        const block = currentBlocks.get(path[i]);
1788        currentBlocks = block?.get("innerBlocks") ?? new import_sync7.Y.Array();
1789      }
1790      return null;
1791    }
1792    function areSelectionsStatesEqual(selection1, selection2) {
1793      if (selection1.type !== selection2.type) {
1794        return false;
1795      }
1796      switch (selection1.type) {
1797        case "none":
1798          return true;
1799        case "cursor":
1800          return areCursorPositionsEqual(
1801            selection1.cursorPosition,
1802            selection2.cursorPosition
1803          );
1804        case "selection-in-one-block":
1805          return areCursorPositionsEqual(
1806            selection1.cursorStartPosition,
1807            selection2.cursorStartPosition
1808          ) && areCursorPositionsEqual(
1809            selection1.cursorEndPosition,
1810            selection2.cursorEndPosition
1811          ) && selection1.selectionDirection === selection2.selectionDirection;
1812        case "selection-in-multiple-blocks":
1813          return areEndpointsEqual(
1814            selection1.startEndpoint,
1815            selection2.startEndpoint
1816          ) && areEndpointsEqual(
1817            selection1.endEndpoint,
1818            selection2.endEndpoint
1819          ) && selection1.selectionDirection === selection2.selectionDirection;
1820        case "whole-block":
1821          return import_sync7.Y.compareRelativePositions(
1822            selection1.blockPosition,
1823            selection2.blockPosition
1824          );
1825        default:
1826          return false;
1827      }
1828    }
1829    function areEndpointsEqual(ep1, ep2) {
1830      if (ep1.type !== ep2.type) {
1831        return false;
1832      }
1833      if (ep1.type === "cursor" && ep2.type === "cursor") {
1834        return areCursorPositionsEqual(
1835          ep1.cursorPosition,
1836          ep2.cursorPosition
1837        );
1838      }
1839      return import_sync7.Y.compareRelativePositions(
1840        ep1.blockPosition,
1841        ep2.blockPosition
1842      );
1843    }
1844    function areCursorPositionsEqual(cursorPosition1, cursorPosition2) {
1845      const isRelativePositionEqual = import_sync7.Y.compareRelativePositions(
1846        cursorPosition1.relativePosition,
1847        cursorPosition2.relativePosition
1848      );
1849      const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset;
1850      return isRelativePositionEqual && isAbsoluteOffsetEqual;
1851    }
1852  
1853    // packages/core-data/build-module/awareness/post-editor-awareness.mjs
1854    var PostEditorAwareness = class extends BaseAwarenessState {
1855      constructor(doc, kind, name, postId) {
1856        super(doc);
1857        this.kind = kind;
1858        this.name = name;
1859        this.postId = postId;
1860      }
1861      equalityFieldChecks = {
1862        ...baseEqualityFieldChecks,
1863        editorState: this.areEditorStatesEqual
1864      };
1865      onSetUp() {
1866        super.onSetUp();
1867        this.subscribeToCollaboratorSelectionChanges();
1868      }
1869      /**
1870       * Subscribe to collaborator selection changes and update the selection state.
1871       */
1872      subscribeToCollaboratorSelectionChanges() {
1873        const {
1874          getSelectionStart,
1875          getSelectionEnd,
1876          getSelectedBlocksInitialCaretPosition
1877        } = (0, import_data4.select)(import_block_editor3.store);
1878        let selectionStart = getSelectionStart();
1879        let selectionEnd = getSelectionEnd();
1880        let localCursorTimeout = null;
1881        let selectionBeforeDebounce = null;
1882        (0, import_data4.subscribe)(() => {
1883          const newSelectionStart = getSelectionStart();
1884          const newSelectionEnd = getSelectionEnd();
1885          if (newSelectionStart === selectionStart && newSelectionEnd === selectionEnd) {
1886            return;
1887          }
1888          if (!selectionBeforeDebounce) {
1889            selectionBeforeDebounce = {
1890              start: selectionStart,
1891              end: selectionEnd
1892            };
1893          }
1894          selectionStart = newSelectionStart;
1895          selectionEnd = newSelectionEnd;
1896          const initialPosition = getSelectedBlocksInitialCaretPosition();
1897          void this.updateSelectionInEntityRecord(
1898            selectionStart,
1899            selectionEnd,
1900            initialPosition
1901          );
1902          if (localCursorTimeout) {
1903            clearTimeout(localCursorTimeout);
1904          }
1905          localCursorTimeout = setTimeout(() => {
1906            const selectionStateOptions = {};
1907            if (selectionBeforeDebounce) {
1908              selectionStateOptions.selectionDirection = detectSelectionDirection(
1909                selectionBeforeDebounce.start,
1910                selectionBeforeDebounce.end,
1911                selectionStart,
1912                selectionEnd
1913              );
1914              selectionBeforeDebounce = null;
1915            }
1916            const selectionState = getSelectionState(
1917              selectionStart,
1918              selectionEnd,
1919              this.doc,
1920              selectionStateOptions
1921            );
1922            this.setThrottledLocalStateField(
1923              "editorState",
1924              { selection: selectionState },
1925              AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS
1926            );
1927          }, LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS);
1928        });
1929      }
1930      /**
1931       * Update the entity record with the current collaborator's selection.
1932       *
1933       * @param selectionStart  - The start position of the selection.
1934       * @param selectionEnd    - The end position of the selection.
1935       * @param initialPosition - The initial position of the selection.
1936       */
1937      async updateSelectionInEntityRecord(selectionStart, selectionEnd, initialPosition) {
1938        const edits = {
1939          selection: { selectionStart, selectionEnd, initialPosition }
1940        };
1941        const options = {
1942          undoIgnore: true
1943        };
1944        (0, import_data4.dispatch)(STORE_NAME).editEntityRecord(
1945          this.kind,
1946          this.name,
1947          this.postId,
1948          edits,
1949          options
1950        );
1951      }
1952      /**
1953       * Check if two editor states are equal.
1954       *
1955       * @param state1 - The first editor state.
1956       * @param state2 - The second editor state.
1957       * @return True if the editor states are equal, false otherwise.
1958       */
1959      areEditorStatesEqual(state1, state2) {
1960        if (!state1 || !state2) {
1961          return state1 === state2;
1962        }
1963        if (!state1.selection || !state2.selection) {
1964          return state1.selection === state2.selection;
1965        }
1966        return areSelectionsStatesEqual(state1.selection, state2.selection);
1967      }
1968      /**
1969       * Resolve a selection state to a text index and block client ID.
1970       *
1971       * For text-based selections, navigates up from the resolved Y.Text via
1972       * AbstractType.parent to find the containing block, then resolves the
1973       * local clientId via the block's tree path.
1974       * For WholeBlock selections, resolves the block's relative position and
1975       * then finds the local clientId via tree path.
1976       *
1977       * Tree-path resolution is used instead of reading the clientId directly
1978       * from the Yjs block because the local block-editor store may use different
1979       * clientIds (e.g. in "Show Template" mode where blocks are cloned).
1980       *
1981       * @param selection - The selection state.
1982       * @param blocks    - The tree of block-editor store post content blocks.
1983       * @return The rich-text offset and block client ID, or nulls if not resolvable.
1984       */
1985      convertSelectionStateToAbsolute(selection, blocks) {
1986        if (selection.type === SelectionType.None) {
1987          return {
1988            richTextOffset: null,
1989            localClientId: null,
1990            attributeKey: null
1991          };
1992        }
1993        if (selection.type === SelectionType.WholeBlock) {
1994          const absolutePos = import_sync9.Y.createAbsolutePositionFromRelativePosition(
1995            selection.blockPosition,
1996            this.doc
1997          );
1998          let localClientId2 = null;
1999          if (absolutePos && absolutePos.type instanceof import_sync9.Y.Array) {
2000            const parentArray = absolutePos.type;
2001            const block = parentArray.get(absolutePos.index);
2002            if (block instanceof import_sync9.Y.Map) {
2003              const path2 = getBlockPathInYdoc(block);
2004              localClientId2 = path2 ? resolveBlockClientIdByPath(path2, blocks) : null;
2005            }
2006          }
2007          return {
2008            richTextOffset: null,
2009            localClientId: localClientId2,
2010            attributeKey: null
2011          };
2012        }
2013        if (selection.type === SelectionType.SelectionInMultipleBlocks) {
2014          return {
2015            richTextOffset: null,
2016            localClientId: null,
2017            attributeKey: null
2018          };
2019        }
2020        const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition;
2021        const absolutePosition = import_sync9.Y.createAbsolutePositionFromRelativePosition(
2022          cursorPos.relativePosition,
2023          this.doc
2024        );
2025        if (!absolutePosition) {
2026          return {
2027            richTextOffset: null,
2028            localClientId: null,
2029            attributeKey: null
2030          };
2031        }
2032        const yType = getContainingBlockYMap(absolutePosition.type);
2033        const path = yType ? getBlockPathInYdoc(yType) : null;
2034        const localClientId = path ? resolveBlockClientIdByPath(path, blocks) : null;
2035        return {
2036          richTextOffset: htmlIndexToRichTextOffset(
2037            absolutePosition.type.toString(),
2038            asHtmlStringIndex(absolutePosition.index)
2039          ),
2040          localClientId,
2041          attributeKey: cursorPos.attributeKey ?? null
2042        };
2043      }
2044      /**
2045       * Type guard to check if a struct is a Y.Item (not Y.GC)
2046       * @param struct - The struct to check.
2047       * @return True if the struct is a Y.Item, false otherwise.
2048       */
2049      isYItem(struct) {
2050        return "content" in struct;
2051      }
2052      /**
2053       * Get data for debugging, using the awareness state.
2054       *
2055       * @return {YDocDebugData} The debug data.
2056       */
2057      getDebugData() {
2058        const ydoc = this.doc;
2059        const docData = Object.fromEntries(
2060          Array.from(ydoc.share, ([key, value]) => [
2061            key,
2062            value.toJSON()
2063          ])
2064        );
2065        const collaboratorMapData = new Map(
2066          Array.from(this.getSeenStates().entries()).filter(
2067            ([, collaboratorState]) => isCollaboratorInfo(collaboratorState.collaboratorInfo)
2068          ).map(([clientId, collaboratorState]) => [
2069            String(clientId),
2070            {
2071              name: collaboratorState.collaboratorInfo.name,
2072              wpUserId: collaboratorState.collaboratorInfo.id
2073            }
2074          ])
2075        );
2076        const serializableClientItems = {};
2077        ydoc.store.clients.forEach((structs, clientId) => {
2078          const items2 = structs.filter(this.isYItem);
2079          serializableClientItems[clientId] = items2.map((item) => {
2080            const { left, right, ...rest } = item;
2081            return {
2082              ...rest,
2083              left: left ? {
2084                id: left.id,
2085                length: left.length,
2086                origin: left.origin,
2087                content: left.content
2088              } : null,
2089              right: right ? {
2090                id: right.id,
2091                length: right.length,
2092                origin: right.origin,
2093                content: right.content
2094              } : null
2095            };
2096          });
2097        });
2098        return {
2099          doc: docData,
2100          clients: serializableClientItems,
2101          collaboratorMap: Object.fromEntries(collaboratorMapData)
2102        };
2103      }
2104    };
2105    function detectSelectionDirection(prevStart, prevEnd, newStart, newEnd) {
2106      const startMoved = !areBlockSelectionsEqual(prevStart, newStart);
2107      const endMoved = !areBlockSelectionsEqual(prevEnd, newEnd);
2108      if (startMoved && !endMoved) {
2109        return SelectionDirection.Backward;
2110      }
2111      return SelectionDirection.Forward;
2112    }
2113    function areBlockSelectionsEqual(a, b) {
2114      return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset;
2115    }
2116  
2117    // packages/core-data/build-module/utils/crdt.mjs
2118    var import_es64 = __toESM(require_es6(), 1);
2119    var import_blocks3 = __toESM(require_blocks(), 1);
2120    var import_sync14 = __toESM(require_sync(), 1);
2121  
2122    // node_modules/uuid/dist/stringify.js
2123    var byteToHex = [];
2124    for (let i = 0; i < 256; ++i) {
2125      byteToHex.push((i + 256).toString(16).slice(1));
2126    }
2127    function unsafeStringify(arr, offset = 0) {
2128      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]]).toLowerCase();
2129    }
2130  
2131    // node_modules/uuid/dist/rng.js
2132    var rnds8 = new Uint8Array(16);
2133    function rng() {
2134      return crypto.getRandomValues(rnds8);
2135    }
2136  
2137    // node_modules/uuid/dist/v4.js
2138    function v4(options, buf, offset) {
2139      if (!buf && !options && crypto.randomUUID) {
2140        return crypto.randomUUID();
2141      }
2142      return _v4(options, buf, offset);
2143    }
2144    function _v4(options, buf, offset) {
2145      options = options || {};
2146      const rnds = options.random ?? options.rng?.() ?? rng();
2147      if (rnds.length < 16) {
2148        throw new Error("Random bytes length must be >= 16");
2149      }
2150      rnds[6] = rnds[6] & 15 | 64;
2151      rnds[8] = rnds[8] & 63 | 128;
2152      if (buf) {
2153        offset = offset || 0;
2154        if (offset < 0 || offset + 16 > buf.length) {
2155          throw new RangeError(`UUID byte range $offset}:$offset + 15} is out of buffer bounds`);
2156        }
2157        for (let i = 0; i < 16; ++i) {
2158          buf[offset + i] = rnds[i];
2159        }
2160        return buf;
2161      }
2162      return unsafeStringify(rnds);
2163    }
2164    var v4_default = v4;
2165  
2166    // packages/core-data/build-module/utils/crdt-blocks.mjs
2167    var import_es63 = __toESM(require_es6(), 1);
2168    var import_blocks = __toESM(require_blocks(), 1);
2169    var import_rich_text3 = __toESM(require_rich_text(), 1);
2170    var import_sync10 = __toESM(require_sync(), 1);
2171  
2172    // packages/core-data/build-module/utils/crdt-text.mjs
2173    var import_rich_text2 = __toESM(require_rich_text(), 1);
2174    var RICH_TEXT_CACHE_MAX_SIZE = 500;
2175    function createRichTextDataCache(maxSize) {
2176      const cache3 = /* @__PURE__ */ new Map();
2177      return function(value) {
2178        const cached = cache3.get(value);
2179        if (cached) {
2180          return cached;
2181        }
2182        const result = import_rich_text2.RichTextData.fromHTMLString(value);
2183        if (cache3.size >= maxSize) {
2184          cache3.delete(cache3.keys().next().value);
2185        }
2186        cache3.set(value, result);
2187        return result;
2188      };
2189    }
2190    var getCachedRichTextData = createRichTextDataCache(
2191      RICH_TEXT_CACHE_MAX_SIZE
2192    );
2193  
2194    // packages/core-data/build-module/utils/crdt-blocks.mjs
2195    var serializableBlocksCache = /* @__PURE__ */ new WeakMap();
2196    function serializeAttributeValue(value) {
2197      if (value instanceof import_rich_text3.RichTextData) {
2198        return value.valueOf();
2199      }
2200      if (Array.isArray(value)) {
2201        return value.map(serializeAttributeValue);
2202      }
2203      if (value && typeof value === "object") {
2204        const result = {};
2205        for (const [k, v] of Object.entries(value)) {
2206          result[k] = serializeAttributeValue(v);
2207        }
2208        return result;
2209      }
2210      return value;
2211    }
2212    function makeBlockAttributesSerializable(blockName, attributes) {
2213      const newAttributes = { ...attributes };
2214      for (const [key, value] of Object.entries(attributes)) {
2215        if (isLocalAttribute(blockName, key)) {
2216          delete newAttributes[key];
2217          continue;
2218        }
2219        newAttributes[key] = serializeAttributeValue(value);
2220      }
2221      return newAttributes;
2222    }
2223    function makeBlocksSerializable(blocks) {
2224      return blocks.map((block) => {
2225        const {
2226          name,
2227          innerBlocks,
2228          attributes,
2229          /*
2230           * Any validation issues discovered when loading a block are appended
2231           * to the block node with a logging function, which cannot be serialized.
2232           *
2233           * @see import("@wordpress/blocks/src/api/parser").parseRawBlock()
2234           */
2235          validationIssues,
2236          ...rest
2237        } = block;
2238        return {
2239          ...rest,
2240          name,
2241          attributes: makeBlockAttributesSerializable(name, attributes),
2242          innerBlocks: makeBlocksSerializable(innerBlocks)
2243        };
2244      });
2245    }
2246    function deserializeAttributeValue(schema, value) {
2247      if (schema?.type === "rich-text" && typeof value === "string") {
2248        return getCachedRichTextData(value);
2249      }
2250      if (Array.isArray(value)) {
2251        return value.map(
2252          (item) => deserializeAttributeValue(schema, item)
2253        );
2254      }
2255      if (value && typeof value === "object") {
2256        const result = {};
2257        for (const [key, innerValue] of Object.entries(
2258          value
2259        )) {
2260          result[key] = deserializeAttributeValue(
2261            schema?.query?.[key],
2262            innerValue
2263          );
2264        }
2265        return result;
2266      }
2267      return value;
2268    }
2269    function deserializeBlockAttributes(blocks) {
2270      return blocks.map((block) => {
2271        const { name, innerBlocks, attributes, ...rest } = block;
2272        const newAttributes = { ...attributes };
2273        for (const [key, value] of Object.entries(attributes)) {
2274          const schema = getBlockAttributeSchema(name, key);
2275          if (schema) {
2276            newAttributes[key] = deserializeAttributeValue(
2277              schema,
2278              value
2279            );
2280          }
2281        }
2282        return {
2283          ...rest,
2284          name,
2285          attributes: newAttributes,
2286          innerBlocks: deserializeBlockAttributes(innerBlocks ?? [])
2287        };
2288      });
2289    }
2290    function areBlocksEqual(gblock, yblock) {
2291      const yblockAsJson = yblock.toJSON();
2292      const overwrites = {
2293        innerBlocks: null,
2294        clientId: null
2295      };
2296      const res = (0, import_es63.default)(
2297        Object.assign({}, gblock, overwrites),
2298        Object.assign({}, yblockAsJson, overwrites)
2299      );
2300      const inners = gblock.innerBlocks || [];
2301      const yinners = yblock.get("innerBlocks");
2302      return res && inners.length === yinners?.length && inners.every(
2303        (block, i) => areBlocksEqual(block, yinners.get(i))
2304      );
2305    }
2306    function createNewYAttributeMap(blockName, attributes) {
2307      return new import_sync10.Y.Map(
2308        Object.entries(attributes).map(
2309          ([attributeName, attributeValue]) => {
2310            return [
2311              attributeName,
2312              createNewYAttributeValue(
2313                blockName,
2314                attributeName,
2315                attributeValue
2316              )
2317            ];
2318          }
2319        )
2320      );
2321    }
2322    function createNewYAttributeValue(blockName, attributeName, attributeValue) {
2323      const schema = getBlockAttributeSchema(blockName, attributeName);
2324      return createYValueFromSchema(schema, attributeValue);
2325    }
2326    function createYValueFromSchema(schema, value) {
2327      if (!schema) {
2328        return value;
2329      }
2330      if (schema.type === "rich-text") {
2331        return new import_sync10.Y.Text(value?.toString() ?? "");
2332      }
2333      if (schema.type === "array" && schema.query && Array.isArray(value)) {
2334        const query = schema.query;
2335        const yArray = new import_sync10.Y.Array();
2336        yArray.insert(
2337          0,
2338          value.map((item) => createYMapFromQuery(query, item))
2339        );
2340        return yArray;
2341      }
2342      if (schema.type === "object" && schema.query && isRecord(value)) {
2343        return createYMapFromQuery(schema.query, value);
2344      }
2345      return value;
2346    }
2347    function isRecord(value) {
2348      return !!value && typeof value === "object" && !Array.isArray(value);
2349    }
2350    function createYMapFromQuery(query, obj) {
2351      if (!isRecord(obj)) {
2352        return new import_sync10.Y.Map();
2353      }
2354      const entries = Object.entries(obj).map(
2355        ([key, val]) => {
2356          const subSchema = query[key];
2357          return [key, createYValueFromSchema(subSchema, val)];
2358        }
2359      );
2360      return new import_sync10.Y.Map(entries);
2361    }
2362    function createNewYBlock(block) {
2363      return createYMap(
2364        Object.fromEntries(
2365          Object.entries(block).map(([key, value]) => {
2366            switch (key) {
2367              case "attributes": {
2368                return [
2369                  key,
2370                  createNewYAttributeMap(block.name, value)
2371                ];
2372              }
2373              case "innerBlocks": {
2374                const innerBlocks = new import_sync10.Y.Array();
2375                if (!Array.isArray(value)) {
2376                  return [key, innerBlocks];
2377                }
2378                innerBlocks.insert(
2379                  0,
2380                  value.map(
2381                    (innerBlock) => createNewYBlock(innerBlock)
2382                  )
2383                );
2384                return [key, innerBlocks];
2385              }
2386              default:
2387                return [key, value];
2388            }
2389          })
2390        )
2391      );
2392    }
2393    function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor, options = {}) {
2394      if (!serializableBlocksCache.has(incomingBlocks)) {
2395        serializableBlocksCache.set(
2396          incomingBlocks,
2397          makeBlocksSerializable(incomingBlocks)
2398        );
2399      }
2400      const incomingBlocksToSync = serializableBlocksCache.get(incomingBlocks) ?? [];
2401      const numOfCommonEntries = Math.min(
2402        incomingBlocksToSync.length ?? 0,
2403        yblocks.length
2404      );
2405      let left = 0;
2406      let right = 0;
2407      for (; left < numOfCommonEntries && areBlocksEqual(incomingBlocksToSync[left], yblocks.get(left)); left++) {
2408      }
2409      for (; right < numOfCommonEntries - left && areBlocksEqual(
2410        incomingBlocksToSync[incomingBlocksToSync.length - right - 1],
2411        yblocks.get(yblocks.length - right - 1)
2412      ); right++) {
2413      }
2414      const numOfUpdatesNeeded = numOfCommonEntries - left - right;
2415      const numOfInsertionsNeeded = Math.max(
2416        0,
2417        incomingBlocksToSync.length - yblocks.length
2418      );
2419      const numOfDeletionsNeeded = Math.max(
2420        0,
2421        yblocks.length - incomingBlocksToSync.length
2422      );
2423      for (let i = 0; i < numOfUpdatesNeeded; i++, left++) {
2424        const incomingYBlock = incomingBlocksToSync[left];
2425        const localYBlock = yblocks.get(left);
2426        Object.entries(incomingYBlock).forEach(
2427          ([incomingBlockProperty, incomingBlockPropertyValue]) => {
2428            switch (incomingBlockProperty) {
2429              case "attributes": {
2430                const localAttributes = localYBlock.get(
2431                  incomingBlockProperty
2432                );
2433                const incomingAttributes = incomingBlockPropertyValue;
2434                if (!localAttributes) {
2435                  localYBlock.set(
2436                    incomingBlockProperty,
2437                    createNewYAttributeMap(
2438                      incomingYBlock.name,
2439                      incomingAttributes
2440                    )
2441                  );
2442                  break;
2443                }
2444                Object.entries(incomingAttributes).forEach(
2445                  ([
2446                    incomingAttributeName,
2447                    incomingAttributeValue
2448                  ]) => {
2449                    const currentAttribute = localAttributes?.get(
2450                      incomingAttributeName
2451                    );
2452                    const isExpectedType = isExpectedAttributeType(
2453                      incomingYBlock.name,
2454                      incomingAttributeName,
2455                      currentAttribute
2456                    );
2457                    const isYType = currentAttribute instanceof import_sync10.Y.AbstractType;
2458                    const isAttributeChanged = !isExpectedType || isYType || !(0, import_es63.default)(
2459                      currentAttribute,
2460                      incomingAttributeValue
2461                    );
2462                    if (isAttributeChanged) {
2463                      updateYBlockAttribute(
2464                        incomingYBlock.name,
2465                        incomingYBlock.clientId,
2466                        incomingAttributeName,
2467                        incomingAttributeValue,
2468                        localAttributes,
2469                        attributeCursor
2470                      );
2471                    }
2472                  }
2473                );
2474                localAttributes.forEach(
2475                  (_attrValue, attrName) => {
2476                    if (!incomingBlockPropertyValue.hasOwnProperty(
2477                      attrName
2478                    )) {
2479                      localAttributes.delete(attrName);
2480                    }
2481                  }
2482                );
2483                break;
2484              }
2485              case "innerBlocks": {
2486                let yInnerBlocks = localYBlock.get(
2487                  incomingBlockProperty
2488                );
2489                if (!(yInnerBlocks instanceof import_sync10.Y.Array)) {
2490                  yInnerBlocks = new import_sync10.Y.Array();
2491                  localYBlock.set(
2492                    incomingBlockProperty,
2493                    yInnerBlocks
2494                  );
2495                }
2496                mergeCrdtBlocks(
2497                  yInnerBlocks,
2498                  incomingBlockPropertyValue ?? [],
2499                  attributeCursor,
2500                  options
2501                );
2502                break;
2503              }
2504              case "clientId": {
2505                if (options.preserveClientIds) {
2506                  break;
2507                }
2508                if (incomingBlockPropertyValue !== localYBlock.get(incomingBlockProperty)) {
2509                  localYBlock.set(
2510                    incomingBlockProperty,
2511                    incomingBlockPropertyValue
2512                  );
2513                }
2514                break;
2515              }
2516              default:
2517                if (!(0, import_es63.default)(
2518                  incomingYBlock[incomingBlockProperty],
2519                  localYBlock.get(incomingBlockProperty)
2520                )) {
2521                  localYBlock.set(
2522                    incomingBlockProperty,
2523                    incomingBlockPropertyValue
2524                  );
2525                }
2526            }
2527          }
2528        );
2529        localYBlock.forEach((_v, k) => {
2530          if (!incomingYBlock.hasOwnProperty(k)) {
2531            localYBlock.delete(k);
2532          }
2533        });
2534      }
2535      yblocks.delete(left, numOfDeletionsNeeded);
2536      for (let i = 0; i < numOfInsertionsNeeded; i++, left++) {
2537        const newBlock = [createNewYBlock(incomingBlocksToSync[left])];
2538        yblocks.insert(left, newBlock);
2539      }
2540      const knownClientIds = /* @__PURE__ */ new Set();
2541      for (let j = 0; j < yblocks.length; j++) {
2542        const yblock = yblocks.get(j);
2543        let clientId = yblock.get("clientId");
2544        if (!clientId) {
2545          continue;
2546        }
2547        if (knownClientIds.has(clientId)) {
2548          clientId = v4_default();
2549          yblock.set("clientId", clientId);
2550        }
2551        knownClientIds.add(clientId);
2552      }
2553    }
2554    function areArrayElementsEqual(newElement, yElement) {
2555      if (yElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2556        return (0, import_es63.default)(newElement, yElement.toJSON());
2557      }
2558      return (0, import_es63.default)(newElement, yElement);
2559    }
2560    function mergeYArray(yArray, newValue, schema, cursorPosition, cursorScope) {
2561      if (!schema.query) {
2562        return;
2563      }
2564      const query = schema.query;
2565      const numOfCommonEntries = Math.min(newValue.length, yArray.length);
2566      let left = 0;
2567      let right = 0;
2568      for (; left < numOfCommonEntries && areArrayElementsEqual(newValue[left], yArray.get(left)); left++) {
2569      }
2570      for (; right < numOfCommonEntries - left && areArrayElementsEqual(
2571        newValue[newValue.length - right - 1],
2572        yArray.get(yArray.length - right - 1)
2573      ); right++) {
2574      }
2575      const numOfUpdatesNeeded = numOfCommonEntries - left - right;
2576      for (let i = 0; i < numOfUpdatesNeeded; i++) {
2577        const currentElement = yArray.get(left + i);
2578        const newElement = newValue[left + i];
2579        if (currentElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2580          mergeYMapValues(
2581            currentElement,
2582            newElement,
2583            query,
2584            cursorPosition,
2585            cursorScope
2586          );
2587        } else {
2588          yArray.delete(0, yArray.length);
2589          yArray.insert(
2590            0,
2591            newValue.map((item) => createYMapFromQuery(query, item))
2592          );
2593          return;
2594        }
2595      }
2596      const numOfDeletionsNeeded = Math.max(0, yArray.length - newValue.length);
2597      if (numOfDeletionsNeeded > 0) {
2598        yArray.delete(left + numOfUpdatesNeeded, numOfDeletionsNeeded);
2599      }
2600      const numOfInsertionsNeeded = Math.max(
2601        0,
2602        newValue.length - yArray.length
2603      );
2604      if (numOfInsertionsNeeded > 0) {
2605        const insertAt = left + numOfUpdatesNeeded;
2606        const itemsToInsert = new Array(
2607          numOfInsertionsNeeded
2608        );
2609        for (let i = 0; i < numOfInsertionsNeeded; i++) {
2610          itemsToInsert[i] = createYMapFromQuery(
2611            query,
2612            newValue[insertAt + i]
2613          );
2614        }
2615        yArray.insert(insertAt, itemsToInsert);
2616      }
2617    }
2618    function mergeYValue(schema, newVal, yMap, key, cursorPosition, cursorScope) {
2619      const currentVal = yMap.get(key);
2620      if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof import_sync10.Y.Text) {
2621        mergeRichTextUpdate(
2622          currentVal,
2623          newVal,
2624          resolveRichTextCursorPosition(cursorPosition, cursorScope, newVal)
2625        );
2626      } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof import_sync10.Y.Array) {
2627        mergeYArray(currentVal, newVal, schema, cursorPosition, cursorScope);
2628      } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof import_sync10.Y.Map) {
2629        mergeYMapValues(
2630          currentVal,
2631          newVal,
2632          schema.query,
2633          cursorPosition,
2634          cursorScope
2635        );
2636      } else {
2637        const newYValue = createYValueFromSchema(schema, newVal);
2638        if (newYValue !== newVal || !(0, import_es63.default)(currentVal, newVal)) {
2639          yMap.set(key, newYValue);
2640        }
2641      }
2642    }
2643    function mergeYMapValues(yMap, newObj, query, cursorPosition, cursorScope) {
2644      for (const [key, newVal] of Object.entries(newObj)) {
2645        mergeYValue(
2646          query[key],
2647          newVal,
2648          yMap,
2649          key,
2650          cursorPosition,
2651          cursorScope
2652        );
2653      }
2654      for (const key of yMap.keys()) {
2655        if (!Object.hasOwn(newObj, key)) {
2656          yMap.delete(key);
2657        }
2658      }
2659    }
2660    function updateYBlockAttribute(blockName, clientId, attributeName, attributeValue, currentAttributes, newCursorPosition) {
2661      const schema = getBlockAttributeSchema(blockName, attributeName);
2662      mergeYValue(
2663        schema,
2664        attributeValue,
2665        currentAttributes,
2666        attributeName,
2667        newCursorPosition,
2668        { attributeKey: attributeName, clientId }
2669      );
2670    }
2671    function resolveRichTextCursorPosition(cursorPosition, cursorScope, updatedValue) {
2672      return cursorPosition && cursorPosition.clientId === cursorScope.clientId && cursorPosition.attributeKey === cursorScope.attributeKey && "number" === typeof cursorPosition.offset && Number.isInteger(cursorPosition.offset) ? richTextOffsetToHtmlIndex(
2673        updatedValue,
2674        asRichTextOffset(cursorPosition.offset)
2675      ) : null;
2676    }
2677    var cachedBlockAttributeSchemas;
2678    function getBlockAttributeSchema(blockName, attributeName) {
2679      if (!cachedBlockAttributeSchemas) {
2680        cachedBlockAttributeSchemas = /* @__PURE__ */ new Map();
2681        for (const blockType of (0, import_blocks.getBlockTypes)()) {
2682          cachedBlockAttributeSchemas.set(
2683            blockType.name,
2684            new Map(
2685              Object.entries(blockType.attributes ?? {}).map(
2686                ([name, definition]) => {
2687                  const { role, type, query } = definition;
2688                  return [name, { role, type, query }];
2689                }
2690              )
2691            )
2692          );
2693        }
2694      }
2695      return cachedBlockAttributeSchemas.get(blockName)?.get(attributeName);
2696    }
2697    function isExpectedAttributeType(blockName, attributeName, attributeValue) {
2698      const schema = getBlockAttributeSchema(blockName, attributeName);
2699      if (schema?.type === "rich-text") {
2700        return attributeValue instanceof import_sync10.Y.Text;
2701      }
2702      if (schema?.type === "string") {
2703        return typeof attributeValue === "string";
2704      }
2705      if (schema?.type === "array" && schema.query) {
2706        return attributeValue instanceof import_sync10.Y.Array;
2707      }
2708      if (schema?.type === "object" && schema.query) {
2709        return attributeValue instanceof import_sync10.Y.Map;
2710      }
2711      return true;
2712    }
2713    function isLocalAttribute(blockName, attributeName) {
2714      return "local" === getBlockAttributeSchema(blockName, attributeName)?.role;
2715    }
2716    var localDoc;
2717    function mergeRichTextUpdate(blockYText, updatedValue, htmlCursorIndex = null) {
2718      const currentValueAsDelta = new Delta(blockYText.toDelta());
2719      const updatedValueAsDelta = new Delta([{ insert: updatedValue }]);
2720      const deltaDiff = currentValueAsDelta.diffWithCursor(
2721        updatedValueAsDelta,
2722        htmlCursorIndex
2723      );
2724      const safeDiff = htmlCursorIndex === null || isDeltaVerificationMatch(blockYText, deltaDiff, updatedValue) ? deltaDiff : currentValueAsDelta.diff(updatedValueAsDelta);
2725      blockYText.applyDelta(safeDiff.ops);
2726    }
2727    function isDeltaVerificationMatch(blockYText, delta, expectedValue) {
2728      if (!localDoc) {
2729        localDoc = new import_sync10.Y.Doc();
2730      }
2731      const verificationYText = localDoc.getText("verification-text");
2732      verificationYText.delete(0, verificationYText.length);
2733      verificationYText.insert(0, blockYText.toString());
2734      verificationYText.applyDelta(delta.ops);
2735      return verificationYText.toString() === expectedValue;
2736    }
2737  
2738    // packages/core-data/build-module/utils/crdt-selection.mjs
2739    var import_data5 = __toESM(require_data(), 1);
2740    var import_block_editor4 = __toESM(require_block_editor(), 1);
2741    var import_blocks2 = __toESM(require_blocks(), 1);
2742    var import_sync13 = __toESM(require_sync(), 1);
2743  
2744    // packages/core-data/build-module/utils/block-selection-history.mjs
2745    var import_sync12 = __toESM(require_sync(), 1);
2746    var SELECTION_HISTORY_DEFAULT_SIZE = 5;
2747    var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => {
2748      YSelectionType2["RelativeSelection"] = "RelativeSelection";
2749      YSelectionType2["BlockSelection"] = "BlockSelection";
2750      return YSelectionType2;
2751    })(YSelectionType || {});
2752    function createBlockSelectionHistory(ydoc, historySize = SELECTION_HISTORY_DEFAULT_SIZE) {
2753      let history = [];
2754      const getSelectionHistory2 = () => {
2755        return history.slice(0);
2756      };
2757      const updateSelection = (newSelection) => {
2758        if (!newSelection?.selectionStart?.clientId || !newSelection?.selectionEnd?.clientId) {
2759          return;
2760        }
2761        const { selectionStart, selectionEnd } = newSelection;
2762        const start = convertWPBlockSelectionToSelection(
2763          selectionStart,
2764          ydoc
2765        );
2766        const end = convertWPBlockSelectionToSelection(selectionEnd, ydoc);
2767        addToHistory({ start, end });
2768      };
2769      const addToHistory = (yFullSelection) => {
2770        const startClientId = yFullSelection.start.clientId;
2771        const endClientId = yFullSelection.end.clientId;
2772        history = history.filter((entry) => {
2773          const isSameBlockCombination = entry.start.clientId === startClientId && entry.end.clientId === endClientId;
2774          return !isSameBlockCombination;
2775        });
2776        history.unshift(yFullSelection);
2777        if (history.length > historySize + 1) {
2778          history = history.slice(0, historySize + 1);
2779        }
2780      };
2781      return {
2782        getSelectionHistory: getSelectionHistory2,
2783        updateSelection
2784      };
2785    }
2786    function convertWPBlockSelectionToSelection(selection, ydoc) {
2787      const clientId = selection.clientId;
2788      const block = findBlockByClientIdInDoc(clientId, ydoc);
2789      const attributes = block?.get("attributes");
2790      const attributeKey = selection.attributeKey;
2791      let changedYText = null;
2792      if (attributeKey && attributes) {
2793        changedYText = getYTextByAttributeKey(attributes, attributeKey);
2794      }
2795      if (!(changedYText instanceof import_sync12.Y.Text) || !attributeKey || !clientId) {
2796        return {
2797          type: "BlockSelection",
2798          clientId
2799        };
2800      }
2801      const offset = selection.offset ?? 0;
2802      const relativePosition = import_sync12.Y.createRelativePositionFromTypeIndex(
2803        changedYText,
2804        richTextOffsetToHtmlIndex(
2805          changedYText.toString(),
2806          asRichTextOffset(offset)
2807        )
2808      );
2809      return {
2810        type: "RelativeSelection",
2811        attributeKey,
2812        relativePosition,
2813        clientId,
2814        offset
2815      };
2816    }
2817  
2818    // packages/core-data/build-module/utils/crdt-selection.mjs
2819    var selectionHistoryMap = /* @__PURE__ */ new WeakMap();
2820    function getBlockSelectionHistory(ydoc) {
2821      let history = selectionHistoryMap.get(ydoc);
2822      if (!history) {
2823        history = createBlockSelectionHistory(ydoc);
2824        selectionHistoryMap.set(ydoc, history);
2825      }
2826      return history;
2827    }
2828    function getSelectionHistory(ydoc) {
2829      return getBlockSelectionHistory(ydoc).getSelectionHistory();
2830    }
2831    function updateSelectionHistory(ydoc, wpSelection) {
2832      return getBlockSelectionHistory(ydoc).updateSelection(wpSelection);
2833    }
2834    function convertYSelectionToBlockSelection(ySelection, ydoc) {
2835      if (ySelection.type === YSelectionType.RelativeSelection) {
2836        const { relativePosition, attributeKey, clientId } = ySelection;
2837        const absolutePosition = import_sync13.Y.createAbsolutePositionFromRelativePosition(
2838          relativePosition,
2839          ydoc
2840        );
2841        if (absolutePosition) {
2842          return {
2843            clientId,
2844            attributeKey,
2845            offset: htmlIndexToRichTextOffset(
2846              absolutePosition.type.toString(),
2847              asHtmlStringIndex(absolutePosition.index)
2848            )
2849          };
2850        }
2851      } else if (ySelection.type === YSelectionType.BlockSelection) {
2852        return {
2853          clientId: ySelection.clientId,
2854          attributeKey: void 0,
2855          offset: void 0
2856        };
2857      }
2858      return null;
2859    }
2860    function convertYFullSelectionToWPSelection(yFullSelection, ydoc) {
2861      const { start, end } = yFullSelection;
2862      const startBlock = findBlockByClientIdInDoc(start.clientId, ydoc);
2863      const endBlock = findBlockByClientIdInDoc(end.clientId, ydoc);
2864      if (!startBlock || !endBlock) {
2865        return null;
2866      }
2867      const startBlockSelection = convertYSelectionToBlockSelection(
2868        start,
2869        ydoc
2870      );
2871      const endBlockSelection = convertYSelectionToBlockSelection(end, ydoc);
2872      if (startBlockSelection === null || endBlockSelection === null) {
2873        return null;
2874      }
2875      return {
2876        selectionStart: startBlockSelection,
2877        selectionEnd: endBlockSelection
2878      };
2879    }
2880    function findSelectionFromHistory(ydoc, selectionHistory) {
2881      for (const positionToTry of selectionHistory) {
2882        const result = convertYFullSelectionToWPSelection(
2883          positionToTry,
2884          ydoc
2885        );
2886        if (result !== null) {
2887          return result;
2888        }
2889      }
2890      return null;
2891    }
2892    function restoreSelection(selectionHistory, ydoc) {
2893      const selectionToRestore = findSelectionFromHistory(
2894        ydoc,
2895        selectionHistory
2896      );
2897      if (selectionToRestore === null) {
2898        return;
2899      }
2900      const { getBlock } = (0, import_data5.select)(import_block_editor4.store);
2901      const { resetSelection } = (0, import_data5.dispatch)(import_block_editor4.store);
2902      const { selectionStart, selectionEnd } = selectionToRestore;
2903      const isSelectionInSameBlock = selectionStart.clientId === selectionEnd.clientId;
2904      if (isSelectionInSameBlock) {
2905        const block = getBlock(selectionStart.clientId);
2906        const isBlockEmpty = block && (0, import_blocks2.isUnmodifiedBlock)(block);
2907        const isBeginningOfEmptyBlock = 0 === selectionStart.offset && 0 === selectionEnd.offset && isBlockEmpty && !selectionStart.attributeKey && !selectionEnd.attributeKey;
2908        if (isBeginningOfEmptyBlock) {
2909          const selectionStartWithoutOffset = {
2910            clientId: selectionStart.clientId
2911          };
2912          const selectionEndWithoutOffset = {
2913            clientId: selectionEnd.clientId
2914          };
2915          resetSelection(
2916            selectionStartWithoutOffset,
2917            selectionEndWithoutOffset,
2918            0
2919          );
2920        } else {
2921          resetSelection(selectionStart, selectionEnd, 0);
2922        }
2923      } else {
2924        resetSelection(selectionEnd, selectionEnd, 0);
2925      }
2926    }
2927    function getShiftedSelection(ydoc, selectionHistory) {
2928      if (selectionHistory.length === 0) {
2929        return null;
2930      }
2931      const { start, end } = selectionHistory[0];
2932      if (start.type === YSelectionType.BlockSelection || end.type === YSelectionType.BlockSelection) {
2933        return null;
2934      }
2935      const selectionStart = convertYSelectionToBlockSelection(start, ydoc);
2936      const selectionEnd = convertYSelectionToBlockSelection(end, ydoc);
2937      if (!selectionStart || !selectionEnd) {
2938        return null;
2939      }
2940      const startShifted = selectionStart.offset !== start.offset;
2941      const endShifted = selectionEnd.offset !== end.offset;
2942      if (!startShifted && !endShifted) {
2943        return null;
2944      }
2945      return { selectionStart, selectionEnd };
2946    }
2947  
2948    // packages/core-data/build-module/utils/crdt.mjs
2949    var POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document";
2950    var disallowedPostMetaKeys = /* @__PURE__ */ new Set([
2951      POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE
2952    ]);
2953    function defaultApplyChangesToCRDTDoc(ydoc, changes) {
2954      const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2955      Object.entries(changes).forEach(([key, newValue]) => {
2956        if ("function" === typeof newValue) {
2957          return;
2958        }
2959        switch (key) {
2960          // Add support for additional data types here.
2961          default: {
2962            const currentValue = ymap.get(key);
2963            updateMapValue(ymap, key, currentValue, newValue);
2964          }
2965        }
2966      });
2967    }
2968    function applyPostChangesToCRDTDoc(ydoc, changes, syncedProperties) {
2969      const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2970      Object.keys(changes).forEach((key) => {
2971        if (!syncedProperties.has(key)) {
2972          return;
2973        }
2974        const newValue = changes[key];
2975        if ("function" === typeof newValue) {
2976          return;
2977        }
2978        switch (key) {
2979          case "blocks": {
2980            const newCursorPosition = parseCursorSelection(
2981              changes.selection
2982            );
2983            const rawContent = getRawValue(changes.content);
2984            if (!newValue && typeof rawContent === "string") {
2985              mergeContentWithoutBlocks(
2986                ymap,
2987                rawContent,
2988                newCursorPosition
2989              );
2990              break;
2991            } else if (!newValue) {
2992              ymap.set(key, void 0);
2993              break;
2994            }
2995            let currentBlocks = ymap.get(key);
2996            if (!(currentBlocks instanceof import_sync14.Y.Array)) {
2997              currentBlocks = new import_sync14.Y.Array();
2998              ymap.set(key, currentBlocks);
2999            }
3000            mergeCrdtBlocks(currentBlocks, newValue, newCursorPosition);
3001            break;
3002          }
3003          case "content":
3004          case "excerpt":
3005          case "title": {
3006            const currentValue = ymap.get(key);
3007            let rawValue = getRawValue(newValue);
3008            if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) {
3009              rawValue = "";
3010            }
3011            if (currentValue instanceof import_sync14.Y.Text) {
3012              mergeRichTextUpdate(currentValue, rawValue ?? "");
3013            } else {
3014              const newYText = new import_sync14.Y.Text(rawValue ?? "");
3015              ymap.set(key, newYText);
3016            }
3017            break;
3018          }
3019          // "Meta" is overloaded term; here, it refers to post meta.
3020          case "meta": {
3021            let metaMap = ymap.get("meta");
3022            if (!isYMap(metaMap)) {
3023              metaMap = createYMap();
3024              ymap.set("meta", metaMap);
3025            }
3026            Object.entries(newValue ?? {}).forEach(
3027              ([metaKey, metaValue]) => {
3028                if (disallowedPostMetaKeys.has(metaKey)) {
3029                  return;
3030                }
3031                updateMapValue(
3032                  metaMap,
3033                  metaKey,
3034                  metaMap.get(metaKey),
3035                  // current value in CRDT
3036                  metaValue
3037                  // new value from changes
3038                );
3039              }
3040            );
3041            break;
3042          }
3043          case "slug": {
3044            if (!newValue) {
3045              break;
3046            }
3047            const currentValue = ymap.get(key);
3048            updateMapValue(ymap, key, currentValue, newValue);
3049            break;
3050          }
3051          // Add support for additional properties here.
3052          default: {
3053            const currentValue = ymap.get(key);
3054            updateMapValue(ymap, key, currentValue, newValue);
3055          }
3056        }
3057      });
3058      if (changes.selection) {
3059        const selection = changes.selection;
3060        setTimeout(() => {
3061          updateSelectionHistory(ydoc, selection);
3062        }, 0);
3063      }
3064    }
3065    function mergeContentWithoutBlocks(ymap, rawContent, cursorPosition) {
3066      let currentBlocks = ymap.get("blocks");
3067      if (!(currentBlocks instanceof import_sync14.Y.Array)) {
3068        currentBlocks = new import_sync14.Y.Array();
3069        ymap.set("blocks", currentBlocks);
3070      }
3071      mergeCrdtBlocks(
3072        currentBlocks,
3073        (0, import_blocks3.parse)(rawContent),
3074        cursorPosition,
3075        { preserveClientIds: true }
3076      );
3077    }
3078    function parseCursorSelection(selection) {
3079      const selectionStart = selection?.selectionStart;
3080      return selectionStart?.clientId && selectionStart.attributeKey && "number" === typeof selectionStart.offset && Number.isInteger(selectionStart.offset) ? {
3081        attributeKey: selectionStart.attributeKey,
3082        clientId: selectionStart.clientId,
3083        offset: asRichTextOffset(selectionStart.offset)
3084      } : null;
3085    }
3086    function defaultGetChangesFromCRDTDoc(crdtDoc, editedRecord) {
3087      const docRecord = getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY).toJSON();
3088      return Object.fromEntries(
3089        Object.entries(docRecord).filter(
3090          ([key, newValue]) => haveValuesChanged(editedRecord?.[key], newValue)
3091        )
3092      );
3093    }
3094    function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) {
3095      const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
3096      let allowedMetaChanges = {};
3097      const changes = Object.fromEntries(
3098        Object.entries(ymap.toJSON()).filter(([key, newValue]) => {
3099          if (!syncedProperties.has(key)) {
3100            return false;
3101          }
3102          const currentValue = editedRecord[key];
3103          switch (key) {
3104            case "blocks": {
3105              if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY) && editedRecord.content) {
3106                const blocksJson = ymap.get("blocks")?.toJSON() ?? [];
3107                return (0, import_blocks3.__unstableSerializeAndClean)(blocksJson).trim() !== getRawValue(editedRecord.content);
3108              }
3109              return true;
3110            }
3111            case "date": {
3112              const currentDateIsFloating = null === currentValue || editedRecord.modified === currentValue;
3113              if (currentDateIsFloating) {
3114                return false;
3115              }
3116              return haveValuesChanged(currentValue, newValue);
3117            }
3118            case "meta": {
3119              const currentMeta = currentValue ?? {};
3120              allowedMetaChanges = Object.fromEntries(
3121                Object.entries(newValue ?? {}).filter(
3122                  ([metaKey]) => {
3123                    if (disallowedPostMetaKeys.has(metaKey)) {
3124                      return false;
3125                    }
3126                    return metaKey in currentMeta;
3127                  }
3128                )
3129              );
3130              const mergedValue = {
3131                ...currentMeta,
3132                ...allowedMetaChanges
3133              };
3134              return haveValuesChanged(currentValue, mergedValue);
3135            }
3136            case "status": {
3137              if ("auto-draft" === newValue) {
3138                return false;
3139              }
3140              return haveValuesChanged(currentValue, newValue);
3141            }
3142            case "content":
3143            case "excerpt":
3144            case "title": {
3145              return haveValuesChanged(
3146                getRawValue(currentValue),
3147                newValue
3148              );
3149            }
3150            // Add support for additional data types here.
3151            default: {
3152              return haveValuesChanged(currentValue, newValue);
3153            }
3154          }
3155        })
3156      );
3157      if (changes.blocks) {
3158        changes.blocks = deserializeBlockAttributes(
3159          changes.blocks
3160        );
3161      }
3162      if (changes.blocks && !changes.content) {
3163        const capturedBlocks = changes.blocks;
3164        changes.content = () => (0, import_blocks3.__unstableSerializeAndClean)(capturedBlocks);
3165      }
3166      if ("object" === typeof changes.meta) {
3167        changes.meta = {
3168          ...editedRecord.meta,
3169          ...allowedMetaChanges
3170        };
3171      }
3172      const selectionHistory = getSelectionHistory(ydoc);
3173      const shiftedSelection = getShiftedSelection(ydoc, selectionHistory);
3174      if (shiftedSelection) {
3175        changes.selection = {
3176          ...shiftedSelection,
3177          initialPosition: 0
3178        };
3179      }
3180      return changes;
3181    }
3182    var defaultSyncConfig = {
3183      applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc,
3184      createAwareness: (ydoc) => new BaseAwareness(ydoc),
3185      getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc
3186    };
3187    var defaultCollectionSyncConfig = {
3188      applyChangesToCRDTDoc: () => {
3189      },
3190      getChangesFromCRDTDoc: () => ({}),
3191      shouldSync: (_, objectId) => null === objectId
3192    };
3193    function getRawValue(value) {
3194      if ("string" === typeof value) {
3195        return value;
3196      }
3197      if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) {
3198        return value.raw;
3199      }
3200      return void 0;
3201    }
3202    function haveValuesChanged(currentValue, newValue) {
3203      return !(0, import_es64.default)(currentValue, newValue);
3204    }
3205    function updateMapValue(map, key, currentValue, newValue) {
3206      if (void 0 === newValue) {
3207        map.delete(key);
3208        return;
3209      }
3210      if (haveValuesChanged(currentValue, newValue)) {
3211        map.set(key, newValue);
3212      }
3213    }
3214  
3215    // packages/core-data/build-module/entities.mjs
3216    var DEFAULT_ENTITY_KEY = "id";
3217    var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"];
3218    var blocksTransientEdits = {
3219      blocks: {
3220        read: (record) => (0, import_blocks4.parse)(record.content?.raw ?? ""),
3221        write: (record) => ({
3222          content: (0, import_blocks4.__unstableSerializeAndClean)(record.blocks)
3223        })
3224      }
3225    };
3226    var rootEntitiesConfig = [
3227      {
3228        label: (0, import_i18n.__)("Base"),
3229        kind: "root",
3230        key: false,
3231        name: "__unstableBase",
3232        baseURL: "/",
3233        baseURLParams: {
3234          // Please also change the preload path when changing this.
3235          // @see lib/compat/wordpress-7.1/preload.php
3236          _fields: [
3237            "description",
3238            "gmt_offset",
3239            "home",
3240            "image_max_bit_depth",
3241            "image_sizes",
3242            "image_size_threshold",
3243            "image_strip_meta",
3244            "name",
3245            "site_icon",
3246            "site_icon_url",
3247            "site_logo",
3248            "timezone_string",
3249            "url",
3250            "page_for_posts",
3251            "page_on_front",
3252            "show_on_front"
3253          ].join(",")
3254        },
3255        // The entity doesn't support selecting multiple records.
3256        // The property is maintained for backward compatibility.
3257        plural: "__unstableBases",
3258        supportsPagination: false
3259      },
3260      {
3261        label: (0, import_i18n.__)("Post Type"),
3262        name: "postType",
3263        kind: "root",
3264        key: "slug",
3265        baseURL: "/wp/v2/types",
3266        baseURLParams: { context: "edit" },
3267        plural: "postTypes",
3268        supportsPagination: false
3269      },
3270      {
3271        name: "media",
3272        kind: "root",
3273        baseURL: "/wp/v2/media",
3274        baseURLParams: { context: "edit" },
3275        plural: "mediaItems",
3276        label: (0, import_i18n.__)("Media"),
3277        rawAttributes: ["caption", "title", "description"],
3278        supportsPagination: true
3279      },
3280      {
3281        name: "taxonomy",
3282        kind: "root",
3283        key: "slug",
3284        baseURL: "/wp/v2/taxonomies",
3285        baseURLParams: { context: "edit" },
3286        plural: "taxonomies",
3287        label: (0, import_i18n.__)("Taxonomy"),
3288        supportsPagination: false
3289      },
3290      {
3291        name: "sidebar",
3292        kind: "root",
3293        baseURL: "/wp/v2/sidebars",
3294        baseURLParams: { context: "edit" },
3295        plural: "sidebars",
3296        transientEdits: { blocks: true },
3297        label: (0, import_i18n.__)("Widget areas"),
3298        supportsPagination: false
3299      },
3300      {
3301        name: "widget",
3302        kind: "root",
3303        baseURL: "/wp/v2/widgets",
3304        baseURLParams: { context: "edit" },
3305        plural: "widgets",
3306        transientEdits: { blocks: true },
3307        label: (0, import_i18n.__)("Widgets"),
3308        supportsPagination: false
3309      },
3310      {
3311        name: "widgetType",
3312        kind: "root",
3313        baseURL: "/wp/v2/widget-types",
3314        baseURLParams: { context: "edit" },
3315        plural: "widgetTypes",
3316        label: (0, import_i18n.__)("Widget types"),
3317        supportsPagination: false
3318      },
3319      {
3320        label: (0, import_i18n.__)("User"),
3321        name: "user",
3322        kind: "root",
3323        baseURL: "/wp/v2/users",
3324        getTitle: (record) => record?.name || record?.slug,
3325        baseURLParams: { context: "edit" },
3326        plural: "users",
3327        supportsPagination: true
3328      },
3329      {
3330        name: "comment",
3331        kind: "root",
3332        baseURL: "/wp/v2/comments",
3333        baseURLParams: { context: "edit" },
3334        plural: "comments",
3335        label: (0, import_i18n.__)("Comment"),
3336        supportsPagination: true,
3337        ...globalThis.window?.__experimentalEnableRealTimeCollaboration ? { syncConfig: defaultCollectionSyncConfig } : {}
3338      },
3339      {
3340        name: "menu",
3341        kind: "root",
3342        baseURL: "/wp/v2/menus",
3343        baseURLParams: { context: "edit" },
3344        plural: "menus",
3345        label: (0, import_i18n.__)("Menu"),
3346        supportsPagination: true
3347      },
3348      {
3349        name: "menuItem",
3350        kind: "root",
3351        baseURL: "/wp/v2/menu-items",
3352        baseURLParams: { context: "edit" },
3353        plural: "menuItems",
3354        label: (0, import_i18n.__)("Menu Item"),
3355        rawAttributes: ["title"],
3356        supportsPagination: true
3357      },
3358      {
3359        name: "menuLocation",
3360        kind: "root",
3361        baseURL: "/wp/v2/menu-locations",
3362        baseURLParams: { context: "edit" },
3363        plural: "menuLocations",
3364        label: (0, import_i18n.__)("Menu Location"),
3365        key: "name",
3366        supportsPagination: false
3367      },
3368      {
3369        label: (0, import_i18n.__)("Global Styles"),
3370        name: "globalStyles",
3371        kind: "root",
3372        baseURL: "/wp/v2/global-styles",
3373        baseURLParams: { context: "edit" },
3374        plural: "globalStylesVariations",
3375        // Should be different from name.
3376        getTitle: () => (0, import_i18n.__)("Custom Styles"),
3377        getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/$parentId}/revisions$revisionId ? "/" + revisionId : ""}`,
3378        supportsPagination: true
3379      },
3380      {
3381        label: (0, import_i18n.__)("Themes"),
3382        name: "theme",
3383        kind: "root",
3384        baseURL: "/wp/v2/themes",
3385        baseURLParams: { context: "edit" },
3386        plural: "themes",
3387        key: "stylesheet",
3388        supportsPagination: false
3389      },
3390      {
3391        label: (0, import_i18n.__)("Plugins"),
3392        name: "plugin",
3393        kind: "root",
3394        baseURL: "/wp/v2/plugins",
3395        baseURLParams: { context: "edit" },
3396        plural: "plugins",
3397        key: "plugin",
3398        supportsPagination: false
3399      },
3400      {
3401        label: (0, import_i18n.__)("Status"),
3402        name: "status",
3403        kind: "root",
3404        baseURL: "/wp/v2/statuses",
3405        baseURLParams: { context: "edit" },
3406        plural: "statuses",
3407        key: "slug",
3408        supportsPagination: false
3409      },
3410      {
3411        label: (0, import_i18n.__)("Font Collections"),
3412        name: "fontCollection",
3413        kind: "root",
3414        baseURL: "/wp/v2/font-collections",
3415        baseURLParams: { context: "view" },
3416        plural: "fontCollections",
3417        key: "slug",
3418        supportsPagination: true
3419      },
3420      {
3421        label: (0, import_i18n.__)("Icons"),
3422        name: "icon",
3423        kind: "root",
3424        baseURL: "/wp/v2/icons",
3425        baseURLParams: { context: "view" },
3426        plural: "icons",
3427        key: "name",
3428        supportsPagination: false
3429      },
3430      {
3431        label: (0, import_i18n.__)("Icon Collections"),
3432        name: "iconCollection",
3433        kind: "root",
3434        baseURL: "/wp/v2/icon-collections",
3435        baseURLParams: { context: "view" },
3436        plural: "iconCollections",
3437        key: "slug",
3438        supportsPagination: false
3439      }
3440    ];
3441    var deprecatedEntities = {
3442      root: {
3443        media: {
3444          since: "6.9",
3445          alternative: {
3446            kind: "postType",
3447            name: "attachment"
3448          }
3449        }
3450      }
3451    };
3452    var additionalEntityConfigLoaders = [
3453      { kind: "postType", loadEntities: loadPostTypeEntities },
3454      { kind: "taxonomy", loadEntities: loadTaxonomyEntities },
3455      {
3456        kind: "root",
3457        name: "site",
3458        plural: "sites",
3459        loadEntities: loadSiteEntity
3460      }
3461    ];
3462    var prePersistPostType = async (persistedRecord, edits, name, isTemplate) => {
3463      const newEdits = {};
3464      if (!isTemplate && persistedRecord?.status === "auto-draft") {
3465        if (!edits.status && !newEdits.status) {
3466          newEdits.status = "draft";
3467        }
3468        if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) {
3469          newEdits.title = "";
3470        }
3471      }
3472      if (window.__experimentalEnableRealTimeCollaboration && persistedRecord) {
3473        const objectType = `postType/$name}`;
3474        const objectId = persistedRecord.id;
3475        const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
3476          objectType,
3477          objectId
3478        );
3479        if (serializedDoc) {
3480          newEdits.meta = {
3481            ...edits.meta,
3482            [POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializedDoc
3483          };
3484        }
3485      }
3486      return newEdits;
3487    };
3488    async function loadPostTypeEntities() {
3489      const postTypesPromise = (0, import_api_fetch2.default)({ path: "/wp/v2/types?context=view" });
3490      const taxonomiesPromise = window.__experimentalEnableRealTimeCollaboration ? (0, import_api_fetch2.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({});
3491      const [postTypes, taxonomies] = await Promise.all([
3492        postTypesPromise,
3493        taxonomiesPromise
3494      ]);
3495      return Object.entries(postTypes ?? {}).map(([name, postType]) => {
3496        const isTemplate = ["wp_template", "wp_template_part"].includes(
3497          name
3498        );
3499        const namespace = postType?.rest_namespace ?? "wp/v2";
3500        const syncedProperties = /* @__PURE__ */ new Set([
3501          "author",
3502          "blocks",
3503          "content",
3504          "comment_status",
3505          "date",
3506          "excerpt",
3507          "featured_media",
3508          "format",
3509          "meta",
3510          "ping_status",
3511          "slug",
3512          "status",
3513          "sticky",
3514          "template",
3515          "title",
3516          ...postType.taxonomies?.map((taxonomy) => taxonomies?.[taxonomy]?.rest_base)?.filter(Boolean) ?? []
3517        ]);
3518        const entity2 = {
3519          kind: "postType",
3520          baseURL: `/$namespace}/$postType.rest_base}`,
3521          baseURLParams: { context: "edit" },
3522          name,
3523          label: postType.name,
3524          transientEdits: {
3525            ...blocksTransientEdits,
3526            selection: true
3527          },
3528          mergedEdits: { meta: true },
3529          rawAttributes: POST_RAW_ATTRIBUTES,
3530          getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)),
3531          __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate),
3532          __unstable_rest_base: postType.rest_base,
3533          // The templates controller returns the whole collection and never
3534          // paginates.
3535          supportsPagination: !isTemplate,
3536          getRevisionsUrl: (parentId, revisionId) => `/$namespace}/$postType.rest_base}/$parentId}/revisions$revisionId ? "/" + revisionId : ""}`,
3537          revisionKey: isTemplate ? "wp_id" : DEFAULT_ENTITY_KEY
3538        };
3539        if (!window.__experimentalEnableRealTimeCollaboration) {
3540          return entity2;
3541        }
3542        entity2.syncConfig = {
3543          // Save a CRDT document with this entity
3544          supportsPersistence: true,
3545          /**
3546           * Apply changes from the local editor to the local CRDT document so
3547           * that those changes can be synced to other peers (via the provider).
3548           *
3549           * @param {import('@wordpress/sync').CRDTDoc}               crdtDoc
3550           * @param {Partial< import('@wordpress/sync').ObjectData >} changes
3551           * @return {void}
3552           */
3553          applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, syncedProperties),
3554          /**
3555           * Create the awareness instance for the entity's CRDT document.
3556           *
3557           * @param {import('@wordpress/sync').CRDTDoc}  ydoc
3558           * @param {import('@wordpress/sync').ObjectID} objectId
3559           * @return {import('@wordpress/sync').Awareness} Awareness instance
3560           */
3561          createAwareness: (ydoc, objectId) => {
3562            const kind = "postType";
3563            const id = parseInt(objectId, 10);
3564            return new PostEditorAwareness(ydoc, kind, name, id);
3565          },
3566          /**
3567           * Extract changes from a CRDT document that can be used to update the
3568           * local editor state.
3569           *
3570           * @param {import('@wordpress/sync').CRDTDoc}    crdtDoc
3571           * @param {import('@wordpress/sync').ObjectData} editedRecord
3572           * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
3573           */
3574          getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc(
3575            crdtDoc,
3576            editedRecord,
3577            syncedProperties
3578          ),
3579          /**
3580           * Extract changes from a CRDT document that can be used to update the
3581           * local editor state.
3582           *
3583           * @param {import('@wordpress/sync').ObjectData} record
3584           * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
3585           */
3586          getPersistedCRDTDoc: (record) => {
3587            return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null;
3588          },
3589          shouldSync: () => !(Array.isArray(window._wpCollaborationDisabledPostTypes) && window._wpCollaborationDisabledPostTypes.includes(name))
3590        };
3591        return entity2;
3592      });
3593    }
3594    async function loadTaxonomyEntities() {
3595      const taxonomies = await (0, import_api_fetch2.default)({
3596        path: "/wp/v2/taxonomies?context=view"
3597      });
3598      return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => {
3599        const namespace = taxonomy?.rest_namespace ?? "wp/v2";
3600        const entity2 = {
3601          kind: "taxonomy",
3602          baseURL: `/$namespace}/$taxonomy.rest_base}`,
3603          baseURLParams: { context: "edit" },
3604          name,
3605          label: taxonomy.name,
3606          getTitle: (record) => record?.name,
3607          supportsPagination: true
3608        };
3609        if (window.__experimentalEnableRealTimeCollaboration) {
3610          entity2.syncConfig = defaultSyncConfig;
3611        }
3612        return entity2;
3613      });
3614    }
3615    async function loadSiteEntity() {
3616      const entity2 = {
3617        label: (0, import_i18n.__)("Site"),
3618        name: "site",
3619        kind: "root",
3620        key: false,
3621        baseURL: "/wp/v2/settings",
3622        supportsPagination: false,
3623        meta: {}
3624      };
3625      const site = await (0, import_api_fetch2.default)({
3626        path: entity2.baseURL,
3627        method: "OPTIONS"
3628      });
3629      const labels = {};
3630      Object.entries(site?.schema?.properties ?? {}).forEach(
3631        ([key, value]) => {
3632          if (typeof value === "object" && value.title) {
3633            labels[key] = value.title;
3634          }
3635        }
3636      );
3637      return [{ ...entity2, meta: { labels } }];
3638    }
3639    var getMethodName = (kind, name, prefix = "get") => {
3640      const kindPrefix = kind === "root" ? "" : pascalCase(kind);
3641      const suffix = pascalCase(name);
3642      return `$prefix}$kindPrefix}$suffix}`;
3643    };
3644  
3645    // packages/core-data/build-module/queried-data/reducer.mjs
3646    function getContextFromAction(action) {
3647      const { query } = action;
3648      if (!query) {
3649        return "default";
3650      }
3651      const queryParts = get_query_parts_default(query);
3652      return queryParts.context;
3653    }
3654    function getMergedItemIds(itemIds = [], nextItemIds, { page = 1, offset, perPage = 10 } = {}) {
3655      if (perPage === -1) {
3656        return nextItemIds;
3657      }
3658      const nextItemIdsStartIndex = offset ?? (page - 1) * perPage;
3659      const nextItemIdsRange = Math.max(perPage, nextItemIds.length);
3660      const size = Math.max(
3661        itemIds.length,
3662        nextItemIdsStartIndex + nextItemIds.length
3663      );
3664      const mergedItemIds = new Array(size);
3665      for (let i = 0; i < size; i++) {
3666        const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIdsRange;
3667        if (isInNextItemsRange) {
3668          mergedItemIds[i] = nextItemIds[i - nextItemIdsStartIndex];
3669        } else {
3670          mergedItemIds[i] = itemIds[i];
3671        }
3672      }
3673      return mergedItemIds;
3674    }
3675    function removeEntitiesById(entities2, ids) {
3676      return Object.fromEntries(
3677        Object.entries(entities2).filter(
3678          ([id]) => !ids.some((itemId) => {
3679            if (Number.isInteger(itemId)) {
3680              return itemId === +id;
3681            }
3682            return itemId === id;
3683          })
3684        )
3685      );
3686    }
3687    function items(state = {}, action) {
3688      switch (action.type) {
3689        case "RECEIVE_ITEMS": {
3690          const context = getContextFromAction(action);
3691          const key = action.key || DEFAULT_ENTITY_KEY;
3692          const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3693          return {
3694            ...state,
3695            [context]: {
3696              ...state[context],
3697              ...Object.fromEntries(
3698                itemsList.map((item) => [
3699                  item?.[key],
3700                  conservativeMapItem(
3701                    state?.[context]?.[item?.[key]],
3702                    item
3703                  )
3704                ])
3705              )
3706            }
3707          };
3708        }
3709        case "REMOVE_ITEMS":
3710          return Object.fromEntries(
3711            Object.entries(state).map(([itemId, contextState]) => [
3712              itemId,
3713              removeEntitiesById(contextState, action.itemIds)
3714            ])
3715          );
3716      }
3717      return state;
3718    }
3719    function itemIsComplete(state = {}, action) {
3720      switch (action.type) {
3721        case "RECEIVE_ITEMS": {
3722          const context = getContextFromAction(action);
3723          const { query, key = DEFAULT_ENTITY_KEY } = action;
3724          const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3725          const queryParts = query ? get_query_parts_default(query) : {};
3726          const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
3727          return {
3728            ...state,
3729            [context]: {
3730              ...state[context],
3731              ...itemsList.reduce((result, item) => {
3732                const itemId = item?.[key];
3733                result[itemId] = state?.[context]?.[itemId] || isCompleteQuery;
3734                return result;
3735              }, {})
3736            }
3737          };
3738        }
3739        case "REMOVE_ITEMS":
3740          return Object.fromEntries(
3741            Object.entries(state).map(([itemId, contextState]) => [
3742              itemId,
3743              removeEntitiesById(contextState, action.itemIds)
3744            ])
3745          );
3746      }
3747      return state;
3748    }
3749    var receiveQueries = (0, import_compose.compose)([
3750      // Limit to matching action type so we don't attempt to replace action on
3751      // an unhandled action.
3752      if_matching_action_default((action) => "query" in action),
3753      // Inject query parts into action for use both in `keyedReducer` and reducer.
3754      replace_action_default((action) => {
3755        if (action.query) {
3756          return {
3757            ...action,
3758            ...get_query_parts_default(action.query)
3759          };
3760        }
3761        return action;
3762      }),
3763      (0, import_data6.keyedReducer)("context"),
3764      // Queries shape is shared, but keyed by query `stableKey` part. Original
3765      // reducer tracks only a single query object.
3766      (0, import_data6.keyedReducer)("stableKey")
3767    ])((state = {}, action) => {
3768      if (action.type !== "RECEIVE_ITEMS") {
3769        return state;
3770      }
3771      if (!Array.isArray(action.items)) {
3772        return state;
3773      }
3774      const key = action.key ?? DEFAULT_ENTITY_KEY;
3775      return {
3776        itemIds: getMergedItemIds(
3777          state.itemIds,
3778          action.items.map((item) => item?.[key]).filter(Boolean),
3779          {
3780            page: action.page,
3781            offset: action.offset,
3782            perPage: action.perPage
3783          }
3784        ),
3785        meta: action.meta
3786      };
3787    });
3788    function removeQueryItems(queryItems, removedItems) {
3789      const itemIds = queryItems.itemIds.filter(
3790        (itemId) => !removedItems[itemId]
3791      );
3792      const removedCount = queryItems.itemIds.length - itemIds.length;
3793      if (removedCount === 0) {
3794        return queryItems;
3795      }
3796      const nextQueryItems = { ...queryItems, itemIds };
3797      if (Number.isFinite(queryItems.meta?.totalItems)) {
3798        nextQueryItems.meta = {
3799          ...queryItems.meta,
3800          totalItems: Math.max(
3801            0,
3802            queryItems.meta.totalItems - removedCount
3803          ),
3804          totalPages: null
3805        };
3806      }
3807      return nextQueryItems;
3808    }
3809    var queries = (state = {}, action) => {
3810      switch (action.type) {
3811        case "RECEIVE_ITEMS":
3812          return receiveQueries(state, action);
3813        case "REMOVE_ITEMS":
3814          const removedItems = action.itemIds.reduce((result, itemId) => {
3815            result[itemId] = true;
3816            return result;
3817          }, {});
3818          return Object.fromEntries(
3819            Object.entries(state).map(
3820              ([queryGroup, contextQueries]) => [
3821                queryGroup,
3822                Object.fromEntries(
3823                  Object.entries(contextQueries).map(
3824                    ([query, queryItems]) => [
3825                      query,
3826                      removeQueryItems(
3827                        queryItems,
3828                        removedItems
3829                      )
3830                    ]
3831                  )
3832                )
3833              ]
3834            )
3835          );
3836        default:
3837          return state;
3838      }
3839    };
3840    var reducer_default = (0, import_data6.combineReducers)({
3841      items,
3842      itemIsComplete,
3843      queries
3844    });
3845  
3846    // packages/core-data/build-module/reducer.mjs
3847    function users(state = { byId: {}, queries: {} }, action) {
3848      switch (action.type) {
3849        case "RECEIVE_USER_QUERY":
3850          return {
3851            byId: {
3852              ...state.byId,
3853              // Key users by their ID.
3854              ...action.users.reduce(
3855                (newUsers, user) => ({
3856                  ...newUsers,
3857                  [user.id]: user
3858                }),
3859                {}
3860              )
3861            },
3862            queries: {
3863              ...state.queries,
3864              [action.queryID]: action.users.map((user) => user.id)
3865            }
3866          };
3867      }
3868      return state;
3869    }
3870    function currentUser(state = {}, action) {
3871      switch (action.type) {
3872        case "RECEIVE_CURRENT_USER":
3873          return action.currentUser;
3874      }
3875      return state;
3876    }
3877    function currentTheme(state = void 0, action) {
3878      switch (action.type) {
3879        case "RECEIVE_CURRENT_THEME":
3880          return action.currentTheme.stylesheet;
3881      }
3882      return state;
3883    }
3884    function currentGlobalStylesId(state = void 0, action) {
3885      switch (action.type) {
3886        case "RECEIVE_CURRENT_GLOBAL_STYLES_ID":
3887          return action.id;
3888      }
3889      return state;
3890    }
3891    function themeBaseGlobalStyles(state = {}, action) {
3892      switch (action.type) {
3893        case "RECEIVE_THEME_GLOBAL_STYLES":
3894          return {
3895            ...state,
3896            [action.stylesheet]: action.globalStyles
3897          };
3898      }
3899      return state;
3900    }
3901    function themeGlobalStyleVariations(state = {}, action) {
3902      switch (action.type) {
3903        case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS":
3904          return {
3905            ...state,
3906            [action.stylesheet]: action.variations
3907          };
3908      }
3909      return state;
3910    }
3911    var withMultiEntityRecordEdits = (reducer) => (state, action) => {
3912      if (action.type === "UNDO" || action.type === "REDO") {
3913        const { record } = action;
3914        let newState = state;
3915        record.forEach(({ id: { kind, name, recordId }, changes }) => {
3916          const persistedRecord = state?.queriedData?.items?.default?.[recordId];
3917          const edits = Object.fromEntries(
3918            Object.entries(changes).map(([key, value]) => [
3919              key,
3920              action.type === "UNDO" ? value.from : value.to
3921            ])
3922          );
3923          newState = reducer(newState, {
3924            type: "EDIT_ENTITY_RECORD",
3925            kind,
3926            name,
3927            recordId,
3928            // Clear edits matching the persisted record so the entity is
3929            // no longer dirty after undoing back to its saved state.
3930            edits: clearUnchangedEdits(edits, persistedRecord)
3931          });
3932        });
3933        return newState;
3934      }
3935      return reducer(state, action);
3936    };
3937    function entity(entityConfig) {
3938      return (0, import_compose2.compose)([
3939        withMultiEntityRecordEdits,
3940        // Limit to matching action type so we don't attempt to replace action on
3941        // an unhandled action.
3942        if_matching_action_default(
3943          (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind
3944        ),
3945        // Inject the entity config into the action.
3946        replace_action_default((action) => {
3947          return {
3948            key: entityConfig.key || DEFAULT_ENTITY_KEY,
3949            ...action
3950          };
3951        })
3952      ])(
3953        (0, import_data7.combineReducers)({
3954          queriedData: reducer_default,
3955          edits: (state = {}, action) => {
3956            switch (action.type) {
3957              case "RECEIVE_ITEMS":
3958                const context = action?.query?.context ?? "default";
3959                if (context !== "default") {
3960                  return state;
3961                }
3962                const nextState = { ...state };
3963                const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3964                for (const record of itemsList) {
3965                  const recordId = record?.[action.key];
3966                  const edits = nextState[recordId];
3967                  if (!edits) {
3968                    continue;
3969                  }
3970                  const nextEdits2 = Object.keys(edits).reduce(
3971                    (acc, key) => {
3972                      if (
3973                        // Edits are the "raw" attribute values, but records may have
3974                        // objects with more properties, so we use `get` here for the
3975                        // comparison.
3976                        !(0, import_es65.default)(
3977                          edits[key],
3978                          record[key]?.raw ?? record[key]
3979                        ) && // Sometimes the server alters the sent value which means
3980                        // we need to also remove the edits before the api request.
3981                        (!action.persistedEdits || !(0, import_es65.default)(
3982                          edits[key],
3983                          action.persistedEdits[key]
3984                        ))
3985                      ) {
3986                        acc[key] = edits[key];
3987                      }
3988                      return acc;
3989                    },
3990                    {}
3991                  );
3992                  if (Object.keys(nextEdits2).length) {
3993                    nextState[recordId] = nextEdits2;
3994                  } else {
3995                    delete nextState[recordId];
3996                  }
3997                }
3998                return nextState;
3999              case "EDIT_ENTITY_RECORD":
4000                const nextEdits = {
4001                  ...state[action.recordId],
4002                  ...action.edits
4003                };
4004                Object.keys(nextEdits).forEach((key) => {
4005                  if (nextEdits[key] === void 0) {
4006                    delete nextEdits[key];
4007                  }
4008                });
4009                return {
4010                  ...state,
4011                  [action.recordId]: nextEdits
4012                };
4013            }
4014            return state;
4015          },
4016          saving: (state = {}, action) => {
4017            switch (action.type) {
4018              case "SAVE_ENTITY_RECORD_START":
4019              case "SAVE_ENTITY_RECORD_FINISH":
4020                return {
4021                  ...state,
4022                  [action.recordId]: {
4023                    pending: action.type === "SAVE_ENTITY_RECORD_START",
4024                    error: action.error,
4025                    isAutosave: action.isAutosave
4026                  }
4027                };
4028            }
4029            return state;
4030          },
4031          deleting: (state = {}, action) => {
4032            switch (action.type) {
4033              case "DELETE_ENTITY_RECORD_START":
4034              case "DELETE_ENTITY_RECORD_FINISH":
4035                return {
4036                  ...state,
4037                  [action.recordId]: {
4038                    pending: action.type === "DELETE_ENTITY_RECORD_START",
4039                    error: action.error
4040                  }
4041                };
4042            }
4043            return state;
4044          },
4045          revisions: (state = {}, action) => {
4046            if (action.type === "RECEIVE_ITEM_REVISIONS") {
4047              const recordKey = action.recordKey;
4048              delete action.recordKey;
4049              const newState = reducer_default(state[recordKey], {
4050                ...action,
4051                type: "RECEIVE_ITEMS"
4052              });
4053              return {
4054                ...state,
4055                [recordKey]: newState
4056              };
4057            }
4058            if (action.type === "REMOVE_ITEMS") {
4059              return Object.fromEntries(
4060                Object.entries(state).filter(
4061                  ([id]) => !action.itemIds.some((itemId) => {
4062                    if (Number.isInteger(itemId)) {
4063                      return itemId === +id;
4064                    }
4065                    return itemId === id;
4066                  })
4067                )
4068              );
4069            }
4070            return state;
4071          }
4072        })
4073      );
4074    }
4075    function entitiesConfig(state = rootEntitiesConfig, action) {
4076      switch (action.type) {
4077        case "ADD_ENTITIES":
4078          return [...state, ...action.entities];
4079      }
4080      return state;
4081    }
4082    var entities = (state = {}, action) => {
4083      const newConfig = entitiesConfig(state.config, action);
4084      let entitiesDataReducer = state.reducer;
4085      if (!entitiesDataReducer || newConfig !== state.config) {
4086        const entitiesByKind = newConfig.reduce((acc, record) => {
4087          const { kind } = record;
4088          if (!acc[kind]) {
4089            acc[kind] = [];
4090          }
4091          acc[kind].push(record);
4092          return acc;
4093        }, {});
4094        entitiesDataReducer = (0, import_data7.combineReducers)(
4095          Object.fromEntries(
4096            Object.entries(entitiesByKind).map(
4097              ([kind, subEntities]) => {
4098                const kindReducer = (0, import_data7.combineReducers)(
4099                  Object.fromEntries(
4100                    subEntities.map((entityConfig) => [
4101                      entityConfig.name,
4102                      entity(entityConfig)
4103                    ])
4104                  )
4105                );
4106                return [kind, kindReducer];
4107              }
4108            )
4109          )
4110        );
4111      }
4112      const newData = entitiesDataReducer(state.records, action);
4113      if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
4114        return state;
4115      }
4116      return {
4117        reducer: entitiesDataReducer,
4118        records: newData,
4119        config: newConfig
4120      };
4121    };
4122    function undoManager(state = (0, import_undo_manager.createUndoManager)()) {
4123      return state;
4124    }
4125    function syncUndoManagerState(state = { hasRedo: false, hasUndo: false }, action) {
4126      switch (action.type) {
4127        case "SYNC_UNDO_MANAGER_CHANGE":
4128          return {
4129            hasRedo: action.hasRedo,
4130            hasUndo: action.hasUndo
4131          };
4132      }
4133      return state;
4134    }
4135    function editsReference(state = {}, action) {
4136      switch (action.type) {
4137        case "EDIT_ENTITY_RECORD":
4138        case "UNDO":
4139        case "REDO":
4140          return {};
4141      }
4142      return state;
4143    }
4144    function embedPreviews(state = {}, action) {
4145      switch (action.type) {
4146        case "RECEIVE_EMBED_PREVIEW":
4147          const { url, preview } = action;
4148          return {
4149            ...state,
4150            [url]: preview
4151          };
4152      }
4153      return state;
4154    }
4155    function userPermissions(state = {}, action) {
4156      switch (action.type) {
4157        case "RECEIVE_USER_PERMISSION":
4158          return {
4159            ...state,
4160            [action.key]: action.isAllowed
4161          };
4162        case "RECEIVE_USER_PERMISSIONS":
4163          return {
4164            ...state,
4165            ...action.permissions
4166          };
4167      }
4168      return state;
4169    }
4170    function autosaves(state = {}, action) {
4171      switch (action.type) {
4172        case "RECEIVE_AUTOSAVES":
4173          const { postId, autosaves: autosavesData } = action;
4174          return {
4175            ...state,
4176            [postId]: autosavesData
4177          };
4178      }
4179      return state;
4180    }
4181    function blockPatterns(state = [], action) {
4182      switch (action.type) {
4183        case "RECEIVE_BLOCK_PATTERNS":
4184          return action.patterns;
4185      }
4186      return state;
4187    }
4188    function blockPatternCategories(state = [], action) {
4189      switch (action.type) {
4190        case "RECEIVE_BLOCK_PATTERN_CATEGORIES":
4191          return action.categories;
4192      }
4193      return state;
4194    }
4195    function userPatternCategories(state = [], action) {
4196      switch (action.type) {
4197        case "RECEIVE_USER_PATTERN_CATEGORIES":
4198          return action.patternCategories;
4199      }
4200      return state;
4201    }
4202    function navigationFallbackId(state = null, action) {
4203      switch (action.type) {
4204        case "RECEIVE_NAVIGATION_FALLBACK_ID":
4205          return action.fallbackId;
4206      }
4207      return state;
4208    }
4209    function themeGlobalStyleRevisions(state = {}, action) {
4210      switch (action.type) {
4211        case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS":
4212          return {
4213            ...state,
4214            [action.currentId]: action.revisions
4215          };
4216      }
4217      return state;
4218    }
4219    function defaultTemplates(state = {}, action) {
4220      switch (action.type) {
4221        case "RECEIVE_DEFAULT_TEMPLATE":
4222          return {
4223            ...state,
4224            [JSON.stringify(action.query)]: action.templateId
4225          };
4226      }
4227      return state;
4228    }
4229    function registeredPostMeta(state = {}, action) {
4230      switch (action.type) {
4231        case "RECEIVE_REGISTERED_POST_META":
4232          return {
4233            ...state,
4234            [action.postType]: action.registeredPostMeta
4235          };
4236      }
4237      return state;
4238    }
4239    function editorSettings(state = null, action) {
4240      switch (action.type) {
4241        case "RECEIVE_EDITOR_SETTINGS":
4242          return action.settings;
4243      }
4244      return state;
4245    }
4246    function editorAssets(state = null, action) {
4247      switch (action.type) {
4248        case "RECEIVE_EDITOR_ASSETS":
4249          return action.assets;
4250      }
4251      return state;
4252    }
4253    function syncConnectionStatuses(state = {}, action) {
4254      switch (action.type) {
4255        case "SET_SYNC_CONNECTION_STATUS": {
4256          const key = `$action.kind}/$action.name}:$action.key}`;
4257          return {
4258            ...state,
4259            [key]: action.status
4260          };
4261        }
4262        case "CLEAR_SYNC_CONNECTION_STATUS": {
4263          const key = `$action.kind}/$action.name}:$action.key}`;
4264          const { [key]: _, ...rest } = state;
4265          return rest;
4266        }
4267      }
4268      return state;
4269    }
4270    function collaborationSupported(state = true, action) {
4271      switch (action.type) {
4272        case "SET_COLLABORATION_SUPPORTED":
4273          return action.supported;
4274        case "SET_SYNC_CONNECTION_STATUS":
4275          if (ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED === action.status?.error?.code) {
4276            return false;
4277          }
4278          return state;
4279      }
4280      return state;
4281    }
4282    function viewConfigs(state = {}, action) {
4283      switch (action.type) {
4284        case "RECEIVE_VIEW_CONFIG": {
4285          const key = `$action.kind}/$action.name}`;
4286          return {
4287            ...state,
4288            [key]: {
4289              ...state[key],
4290              ...action.config
4291            }
4292          };
4293        }
4294      }
4295      return state;
4296    }
4297    var reducer_default2 = (0, import_data7.combineReducers)({
4298      users,
4299      currentTheme,
4300      currentGlobalStylesId,
4301      currentUser,
4302      themeGlobalStyleVariations,
4303      themeBaseGlobalStyles,
4304      themeGlobalStyleRevisions,
4305      entities,
4306      editsReference,
4307      syncUndoManagerState,
4308      undoManager,
4309      embedPreviews,
4310      userPermissions,
4311      autosaves,
4312      blockPatterns,
4313      blockPatternCategories,
4314      userPatternCategories,
4315      navigationFallbackId,
4316      defaultTemplates,
4317      registeredPostMeta,
4318      editorSettings,
4319      editorAssets,
4320      syncConnectionStatuses,
4321      collaborationSupported,
4322      viewConfigs
4323    });
4324  
4325    // packages/core-data/build-module/selectors.mjs
4326    var selectors_exports = {};
4327    __export(selectors_exports, {
4328      __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId,
4329      __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles,
4330      __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations,
4331      __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords,
4332      __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved,
4333      __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver,
4334      canUser: () => canUser,
4335      canUserEditEntityRecord: () => canUserEditEntityRecord,
4336      getAuthors: () => getAuthors,
4337      getAutosave: () => getAutosave,
4338      getAutosaves: () => getAutosaves,
4339      getBlockPatternCategories: () => getBlockPatternCategories,
4340      getBlockPatterns: () => getBlockPatterns,
4341      getCurrentTheme: () => getCurrentTheme,
4342      getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions,
4343      getCurrentUser: () => getCurrentUser,
4344      getDefaultTemplateId: () => getDefaultTemplateId,
4345      getEditedEntityRecord: () => getEditedEntityRecord,
4346      getEmbedPreview: () => getEmbedPreview,
4347      getEntitiesByKind: () => getEntitiesByKind,
4348      getEntitiesConfig: () => getEntitiesConfig,
4349      getEntity: () => getEntity,
4350      getEntityConfig: () => getEntityConfig,
4351      getEntityRecord: () => getEntityRecord,
4352      getEntityRecordEdits: () => getEntityRecordEdits,
4353      getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits,
4354      getEntityRecords: () => getEntityRecords,
4355      getEntityRecordsTotalItems: () => getEntityRecordsTotalItems,
4356      getEntityRecordsTotalPages: () => getEntityRecordsTotalPages,
4357      getLastEntityDeleteError: () => getLastEntityDeleteError,
4358      getLastEntitySaveError: () => getLastEntitySaveError,
4359      getRawEntityRecord: () => getRawEntityRecord,
4360      getRedoEdit: () => getRedoEdit,
4361      getReferenceByDistinctEdits: () => getReferenceByDistinctEdits,
4362      getRevision: () => getRevision,
4363      getRevisions: () => getRevisions,
4364      getThemeSupports: () => getThemeSupports,
4365      getUndoEdit: () => getUndoEdit,
4366      getUserPatternCategories: () => getUserPatternCategories,
4367      getUserQueryResults: () => getUserQueryResults,
4368      hasEditsForEntityRecord: () => hasEditsForEntityRecord,
4369      hasEntityRecord: () => hasEntityRecord,
4370      hasEntityRecords: () => hasEntityRecords,
4371      hasFetchedAutosaves: () => hasFetchedAutosaves,
4372      hasRedo: () => hasRedo,
4373      hasRevision: () => hasRevision,
4374      hasUndo: () => hasUndo,
4375      isAutosavingEntityRecord: () => isAutosavingEntityRecord,
4376      isDeletingEntityRecord: () => isDeletingEntityRecord,
4377      isPreviewEmbedFallback: () => isPreviewEmbedFallback,
4378      isRequestingEmbedPreview: () => isRequestingEmbedPreview,
4379      isSavingEntityRecord: () => isSavingEntityRecord
4380    });
4381    var import_data9 = __toESM(require_data(), 1);
4382    var import_url2 = __toESM(require_url(), 1);
4383    var import_deprecated2 = __toESM(require_deprecated(), 1);
4384  
4385    // packages/core-data/build-module/private-selectors.mjs
4386    var private_selectors_exports = {};
4387    __export(private_selectors_exports, {
4388      getBlockPatternsForPostType: () => getBlockPatternsForPostType,
4389      getEditorAssets: () => getEditorAssets,
4390      getEditorSettings: () => getEditorSettings,
4391      getEntityRecordPermissions: () => getEntityRecordPermissions,
4392      getEntityRecordsPermissions: () => getEntityRecordsPermissions,
4393      getEntitySyncConnectionStatus: () => getEntitySyncConnectionStatus,
4394      getHomePage: () => getHomePage,
4395      getNavigationFallbackId: () => getNavigationFallbackId,
4396      getPostsPageId: () => getPostsPageId,
4397      getRegisteredPostMeta: () => getRegisteredPostMeta,
4398      getSyncConnectionStatus: () => getSyncConnectionStatus,
4399      getTemplateId: () => getTemplateId,
4400      getUndoManager: () => getUndoManager,
4401      getViewConfig: () => getViewConfig,
4402      isCollaborationSupported: () => isCollaborationSupported
4403    });
4404    var import_data8 = __toESM(require_data(), 1);
4405  
4406    // packages/core-data/build-module/utils/log-entity-deprecation.mjs
4407    var import_deprecated = __toESM(require_deprecated(), 1);
4408    var loggedAlready = false;
4409    function logEntityDeprecation(kind, name, functionName, {
4410      alternativeFunctionName,
4411      isShorthandSelector = false
4412    } = {}) {
4413      const deprecation = deprecatedEntities[kind]?.[name];
4414      if (!deprecation) {
4415        return;
4416      }
4417      if (!loggedAlready) {
4418        const { alternative } = deprecation;
4419        const message = isShorthandSelector ? `'$functionName}'` : `The '$kind}', '$name}' entity (used via '$functionName}')`;
4420        let alternativeMessage = `the '$alternative.kind}', '$alternative.name}' entity`;
4421        if (alternativeFunctionName) {
4422          alternativeMessage += ` via the '$alternativeFunctionName}' function`;
4423        }
4424        (0, import_deprecated.default)(message, {
4425          ...deprecation,
4426          alternative: alternativeMessage
4427        });
4428      }
4429      loggedAlready = true;
4430      setTimeout(() => {
4431        loggedAlready = false;
4432      }, 0);
4433    }
4434  
4435    // packages/core-data/build-module/private-selectors.mjs
4436    var EMPTY_OBJECT = {};
4437    function getUndoManager(state) {
4438      return getSyncManager()?.undoManager ?? state.undoManager;
4439    }
4440    function getNavigationFallbackId(state) {
4441      return state.navigationFallbackId;
4442    }
4443    var getBlockPatternsForPostType = (0, import_data8.createRegistrySelector)(
4444      (select5) => (0, import_data8.createSelector)(
4445        (state, postType) => select5(STORE_NAME).getBlockPatterns().filter(
4446          ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType)
4447        ),
4448        () => [select5(STORE_NAME).getBlockPatterns()]
4449      )
4450    );
4451    var getEntityRecordsPermissions = (0, import_data8.createRegistrySelector)(
4452      (select5) => (0, import_data8.createSelector)(
4453        (state, kind, name, ids) => {
4454          const normalizedIds = Array.isArray(ids) ? ids : [ids];
4455          return normalizedIds.map((id) => ({
4456            delete: select5(STORE_NAME).canUser("delete", {
4457              kind,
4458              name,
4459              id
4460            }),
4461            update: select5(STORE_NAME).canUser("update", {
4462              kind,
4463              name,
4464              id
4465            })
4466          }));
4467        },
4468        (state) => [state.userPermissions]
4469      )
4470    );
4471    function getEntityRecordPermissions(state, kind, name, id) {
4472      logEntityDeprecation(kind, name, "getEntityRecordPermissions");
4473      return getEntityRecordsPermissions(state, kind, name, id)[0];
4474    }
4475    function getRegisteredPostMeta(state, postType) {
4476      return state.registeredPostMeta?.[postType] ?? {};
4477    }
4478    function normalizePageId(value) {
4479      if (!value || !["number", "string"].includes(typeof value)) {
4480        return null;
4481      }
4482      if (Number(value) === 0) {
4483        return null;
4484      }
4485      return value.toString();
4486    }
4487    var getHomePage = (0, import_data8.createRegistrySelector)(
4488      (select5) => (0, import_data8.createSelector)(
4489        () => {
4490          const siteData = select5(STORE_NAME).getEntityRecord(
4491            "root",
4492            "__unstableBase"
4493          );
4494          if (!siteData) {
4495            return null;
4496          }
4497          const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null;
4498          if (homepageId) {
4499            return { postType: "page", postId: homepageId };
4500          }
4501          const frontPageTemplateId = select5(
4502            STORE_NAME
4503          ).getDefaultTemplateId({
4504            slug: "front-page"
4505          });
4506          if (frontPageTemplateId) {
4507            return {
4508              postType: "wp_template",
4509              postId: frontPageTemplateId
4510            };
4511          }
4512          if (frontPageTemplateId === "") {
4513            return EMPTY_OBJECT;
4514          }
4515          return null;
4516        },
4517        (state) => [
4518          // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes,
4519          // it doesn't seem to invalidate this cache, I'm not sure why.
4520          getEntityRecord(state, "root", "site"),
4521          getEntityRecord(state, "root", "__unstableBase"),
4522          getDefaultTemplateId(state, {
4523            slug: "front-page"
4524          })
4525        ]
4526      )
4527    );
4528    var getPostsPageId = (0, import_data8.createRegistrySelector)((select5) => () => {
4529      const siteData = select5(STORE_NAME).getEntityRecord(
4530        "root",
4531        "__unstableBase"
4532      );
4533      return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null;
4534    });
4535    var getTemplateId = (0, import_data8.createRegistrySelector)(
4536      (select5) => (state, postType, postId) => {
4537        const homepage = unlock(select5(STORE_NAME)).getHomePage();
4538        if (!homepage) {
4539          return;
4540        }
4541        if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) {
4542          const templates = select5(STORE_NAME).getEntityRecords(
4543            "postType",
4544            "wp_template",
4545            {
4546              per_page: -1
4547            }
4548          );
4549          if (!templates) {
4550            return;
4551          }
4552          const id = templates.find(
4553            ({ slug }) => slug === "front-page"
4554          )?.id;
4555          if (id) {
4556            return id;
4557          }
4558        }
4559        const editedEntity = select5(STORE_NAME).getEditedEntityRecord(
4560          "postType",
4561          postType,
4562          postId
4563        );
4564        if (!editedEntity) {
4565          return;
4566        }
4567        const postsPageId = unlock(select5(STORE_NAME)).getPostsPageId();
4568        if (postType === "page" && postsPageId === postId.toString()) {
4569          return select5(STORE_NAME).getDefaultTemplateId({
4570            slug: "home"
4571          });
4572        }
4573        const currentTemplateSlug = editedEntity.template;
4574        if (currentTemplateSlug) {
4575          const currentTemplate = select5(STORE_NAME).getEntityRecords("postType", "wp_template", {
4576            per_page: -1
4577          })?.find(({ slug }) => slug === currentTemplateSlug);
4578          if (currentTemplate) {
4579            return currentTemplate.id;
4580          }
4581        }
4582        let slugToCheck;
4583        if (editedEntity.slug) {
4584          slugToCheck = postType === "page" ? `$postType}-$editedEntity.slug}` : `single-$postType}-$editedEntity.slug}`;
4585        } else {
4586          slugToCheck = postType === "page" ? "page" : `single-$postType}`;
4587        }
4588        return select5(STORE_NAME).getDefaultTemplateId({
4589          slug: slugToCheck
4590        });
4591      }
4592    );
4593    function getEditorSettings(state) {
4594      return state.editorSettings;
4595    }
4596    function getEditorAssets(state) {
4597      return state.editorAssets;
4598    }
4599    function isCollaborationSupported(state) {
4600      return state.collaborationSupported;
4601    }
4602    function getViewConfig(state, kind, name) {
4603      return state.viewConfigs?.[`$kind}/$name}`] ?? {
4604        default_view: void 0,
4605        default_layouts: void 0,
4606        view_list: void 0,
4607        form: void 0
4608      };
4609    }
4610    function getSyncConnectionStatus(state) {
4611      if (!state.syncConnectionStatuses) {
4612        return void 0;
4613      }
4614      const PRIORITIZED_STATUSES = ["disconnected", "connecting", "connected"];
4615      let coalesced;
4616      for (const status of Object.values(state.syncConnectionStatuses)) {
4617        if (!coalesced || PRIORITIZED_STATUSES.indexOf(status.status) < PRIORITIZED_STATUSES.indexOf(coalesced.status)) {
4618          coalesced = status;
4619        }
4620      }
4621      return coalesced;
4622    }
4623    function getEntitySyncConnectionStatus(state, kind, name, recordId) {
4624      return state.syncConnectionStatuses?.[`$kind}/$name}:$recordId}`];
4625    }
4626  
4627    // packages/core-data/build-module/selectors.mjs
4628    var EMPTY_OBJECT2 = {};
4629    var isRequestingEmbedPreview = (0, import_data9.createRegistrySelector)(
4630      (select5) => (state, url) => {
4631        return select5(STORE_NAME).isResolving("getEmbedPreview", [
4632          url
4633        ]);
4634      }
4635    );
4636    function getAuthors(state, query) {
4637      (0, import_deprecated2.default)("select( 'core' ).getAuthors()", {
4638        since: "5.9",
4639        alternative: "select( 'core' ).getUsers({ who: 'authors' })"
4640      });
4641      const path = (0, import_url2.addQueryArgs)(
4642        "/wp/v2/users/?who=authors&per_page=100",
4643        query
4644      );
4645      return getUserQueryResults(state, path);
4646    }
4647    function getCurrentUser(state) {
4648      return state.currentUser;
4649    }
4650    var getUserQueryResults = (0, import_data9.createSelector)(
4651      (state, queryID) => {
4652        const queryResults = state.users.queries[queryID] ?? [];
4653        return queryResults.map((id) => state.users.byId[id]);
4654      },
4655      (state, queryID) => [
4656        state.users.queries[queryID],
4657        state.users.byId
4658      ]
4659    );
4660    function getEntitiesByKind(state, kind) {
4661      (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", {
4662        since: "6.0",
4663        alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
4664      });
4665      return getEntitiesConfig(state, kind);
4666    }
4667    var getEntitiesConfig = (0, import_data9.createSelector)(
4668      (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind),
4669      /* eslint-disable @typescript-eslint/no-unused-vars */
4670      (state, kind) => state.entities.config
4671      /* eslint-enable @typescript-eslint/no-unused-vars */
4672    );
4673    function getEntity(state, kind, name) {
4674      (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", {
4675        since: "6.0",
4676        alternative: "wp.data.select( 'core' ).getEntityConfig()"
4677      });
4678      return getEntityConfig(state, kind, name);
4679    }
4680    function getEntityConfig(state, kind, name) {
4681      logEntityDeprecation(kind, name, "getEntityConfig");
4682      return state.entities.config?.find(
4683        (config) => config.kind === kind && config.name === name
4684      );
4685    }
4686    var getEntityRecord = ((state, kind, name, recordId, query) => {
4687      logEntityDeprecation(kind, name, "getEntityRecord");
4688      const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4689      if (!queriedState) {
4690        return void 0;
4691      }
4692      const context = query?.context ?? "default";
4693      if (!query || !query._fields) {
4694        if (!queriedState.itemIsComplete[context]?.[recordId]) {
4695          return void 0;
4696        }
4697        return queriedState.items[context][recordId];
4698      }
4699      const item = queriedState.items[context]?.[recordId];
4700      if (!item) {
4701        return item;
4702      }
4703      return getFilteredItem(item, query._fields);
4704    });
4705    getEntityRecord.normalizeArgs = (args) => {
4706      const newArgs = [...args];
4707      const recordKey = newArgs?.[2];
4708      newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey;
4709      return newArgs;
4710    };
4711    function hasEntityRecord(state, kind, name, recordId, query) {
4712      const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4713      if (!queriedState) {
4714        return false;
4715      }
4716      const context = query?.context ?? "default";
4717      if (!query || !query._fields) {
4718        return !!queriedState.itemIsComplete[context]?.[recordId];
4719      }
4720      const item = queriedState.items[context]?.[recordId];
4721      if (!item) {
4722        return false;
4723      }
4724      const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4725      for (let i = 0; i < fields.length; i++) {
4726        const path = fields[i].split(".");
4727        let value = item;
4728        for (let p = 0; p < path.length; p++) {
4729          const part = path[p];
4730          if (!value || !Object.hasOwn(value, part)) {
4731            return false;
4732          }
4733          value = value[part];
4734        }
4735      }
4736      return true;
4737    }
4738    function __experimentalGetEntityRecordNoResolver(state, kind, name, recordId) {
4739      return getEntityRecord(state, kind, name, recordId);
4740    }
4741    var getRawEntityRecord = (0, import_data9.createSelector)(
4742      (state, kind, name, recordId) => {
4743        logEntityDeprecation(kind, name, "getRawEntityRecord");
4744        const record = getEntityRecord(
4745          state,
4746          kind,
4747          name,
4748          recordId
4749        );
4750        const config = getEntityConfig(state, kind, name);
4751        if (!record || !config?.rawAttributes?.length) {
4752          return record;
4753        }
4754        return Object.fromEntries(
4755          Object.keys(record).map((key) => {
4756            if (config.rawAttributes.includes(key)) {
4757              const rawValue = record[key]?.raw;
4758              return [
4759                key,
4760                rawValue !== void 0 ? rawValue : record[key]
4761              ];
4762            }
4763            return [key, record[key]];
4764          })
4765        );
4766      },
4767      (state, kind, name, recordId, query) => {
4768        const context = query?.context ?? "default";
4769        return [
4770          state.entities.config,
4771          state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId],
4772          state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId]
4773        ];
4774      }
4775    );
4776    function hasEntityRecords(state, kind, name, query) {
4777      logEntityDeprecation(kind, name, "hasEntityRecords");
4778      return Array.isArray(getEntityRecords(state, kind, name, query));
4779    }
4780    var getEntityRecords = ((state, kind, name, query) => {
4781      logEntityDeprecation(kind, name, "getEntityRecords");
4782      const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4783      if (!queriedState) {
4784        return null;
4785      }
4786      return getQueriedItems(queriedState, query, {
4787        supportsPagination: !!getEntityConfig(state, kind, name)?.supportsPagination
4788      });
4789    });
4790    var getEntityRecordsTotalItems = (state, kind, name, query) => {
4791      logEntityDeprecation(kind, name, "getEntityRecordsTotalItems");
4792      const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4793      if (!queriedState) {
4794        return null;
4795      }
4796      return getQueriedTotalItems(queriedState, query);
4797    };
4798    var getEntityRecordsTotalPages = (state, kind, name, query) => {
4799      logEntityDeprecation(kind, name, "getEntityRecordsTotalPages");
4800      const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4801      if (!queriedState) {
4802        return null;
4803      }
4804      if (!getEntityConfig(state, kind, name)?.supportsPagination || query?.per_page === -1) {
4805        return 1;
4806      }
4807      const totalItems = getQueriedTotalItems(queriedState, query);
4808      if (!totalItems) {
4809        return totalItems;
4810      }
4811      if (!query?.per_page) {
4812        return getQueriedTotalPages(queriedState, query);
4813      }
4814      return Math.ceil(totalItems / query.per_page);
4815    };
4816    var __experimentalGetDirtyEntityRecords = (0, import_data9.createSelector)(
4817      (state) => {
4818        const {
4819          entities: { records }
4820        } = state;
4821        const dirtyRecords = [];
4822        Object.keys(records).forEach((kind) => {
4823          Object.keys(records[kind]).forEach((name) => {
4824            const primaryKeys = Object.keys(records[kind][name].edits).filter(
4825              (primaryKey) => (
4826                // The entity record must exist (not be deleted),
4827                // and it must have edits.
4828                getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey)
4829              )
4830            );
4831            if (primaryKeys.length) {
4832              const entityConfig = getEntityConfig(state, kind, name);
4833              primaryKeys.forEach((primaryKey) => {
4834                const entityRecord = getEditedEntityRecord(
4835                  state,
4836                  kind,
4837                  name,
4838                  primaryKey
4839                );
4840                dirtyRecords.push({
4841                  // We avoid using primaryKey because it's transformed into a string
4842                  // when it's used as an object key.
4843                  key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
4844                  title: entityConfig?.getTitle?.(entityRecord) || "",
4845                  name,
4846                  kind
4847                });
4848              });
4849            }
4850          });
4851        });
4852        return dirtyRecords;
4853      },
4854      (state) => [state.entities.records]
4855    );
4856    var __experimentalGetEntitiesBeingSaved = (0, import_data9.createSelector)(
4857      (state) => {
4858        const {
4859          entities: { records }
4860        } = state;
4861        const recordsBeingSaved = [];
4862        Object.keys(records).forEach((kind) => {
4863          Object.keys(records[kind]).forEach((name) => {
4864            const primaryKeys = Object.keys(records[kind][name].saving).filter(
4865              (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey)
4866            );
4867            if (primaryKeys.length) {
4868              const entityConfig = getEntityConfig(state, kind, name);
4869              primaryKeys.forEach((primaryKey) => {
4870                const entityRecord = getEditedEntityRecord(
4871                  state,
4872                  kind,
4873                  name,
4874                  primaryKey
4875                );
4876                recordsBeingSaved.push({
4877                  // We avoid using primaryKey because it's transformed into a string
4878                  // when it's used as an object key.
4879                  key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
4880                  title: entityConfig?.getTitle?.(entityRecord) || "",
4881                  name,
4882                  kind
4883                });
4884              });
4885            }
4886          });
4887        });
4888        return recordsBeingSaved;
4889      },
4890      (state) => [state.entities.records]
4891    );
4892    function getEntityRecordEdits(state, kind, name, recordId) {
4893      logEntityDeprecation(kind, name, "getEntityRecordEdits");
4894      return state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)];
4895    }
4896    var getEntityRecordNonTransientEdits = (0, import_data9.createSelector)(
4897      (state, kind, name, recordId) => {
4898        logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits");
4899        const { transientEdits } = getEntityConfig(state, kind, name) || {};
4900        const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
4901        if (!transientEdits) {
4902          return edits;
4903        }
4904        return Object.keys(edits).reduce((acc, key) => {
4905          if (!transientEdits[key]) {
4906            acc[key] = edits[key];
4907          }
4908          return acc;
4909        }, {});
4910      },
4911      (state, kind, name, recordId) => [
4912        state.entities.config,
4913        state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)]
4914      ]
4915    );
4916    function hasEditsForEntityRecord(state, kind, name, recordId) {
4917      logEntityDeprecation(kind, name, "hasEditsForEntityRecord");
4918      return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(
4919        getEntityRecordNonTransientEdits(state, kind, name, recordId)
4920      ).length > 0;
4921    }
4922    var getEditedEntityRecord = (0, import_data9.createSelector)(
4923      (state, kind, name, recordId) => {
4924        logEntityDeprecation(kind, name, "getEditedEntityRecord");
4925        const raw = getRawEntityRecord(state, kind, name, recordId);
4926        const edited = getEntityRecordEdits(state, kind, name, recordId);
4927        if (!raw && !edited) {
4928          return false;
4929        }
4930        return {
4931          ...raw,
4932          ...edited
4933        };
4934      },
4935      (state, kind, name, recordId, query) => {
4936        const context = query?.context ?? "default";
4937        return [
4938          state.entities.config,
4939          state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId],
4940          state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId],
4941          state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)]
4942        ];
4943      }
4944    );
4945    function isAutosavingEntityRecord(state, kind, name, recordId) {
4946      logEntityDeprecation(kind, name, "isAutosavingEntityRecord");
4947      const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {};
4948      return Boolean(pending && isAutosave);
4949    }
4950    function isSavingEntityRecord(state, kind, name, recordId) {
4951      logEntityDeprecation(kind, name, "isSavingEntityRecord");
4952      return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.pending ?? false;
4953    }
4954    function isDeletingEntityRecord(state, kind, name, recordId) {
4955      logEntityDeprecation(kind, name, "isDeletingEntityRecord");
4956      return state.entities.records?.[kind]?.[name]?.deleting?.[String(recordId)]?.pending ?? false;
4957    }
4958    function getLastEntitySaveError(state, kind, name, recordId) {
4959      logEntityDeprecation(kind, name, "getLastEntitySaveError");
4960      return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.error;
4961    }
4962    function getLastEntityDeleteError(state, kind, name, recordId) {
4963      logEntityDeprecation(kind, name, "getLastEntityDeleteError");
4964      return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error;
4965    }
4966    function getUndoEdit(state) {
4967      (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", {
4968        since: "6.3"
4969      });
4970      return void 0;
4971    }
4972    function getRedoEdit(state) {
4973      (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", {
4974        since: "6.3"
4975      });
4976      return void 0;
4977    }
4978    function hasUndo(state) {
4979      if (getSyncManager()?.undoManager) {
4980        return state.syncUndoManagerState.hasUndo;
4981      }
4982      return getUndoManager(state).hasUndo();
4983    }
4984    function hasRedo(state) {
4985      if (getSyncManager()?.undoManager) {
4986        return state.syncUndoManagerState.hasRedo;
4987      }
4988      return getUndoManager(state).hasRedo();
4989    }
4990    function getCurrentTheme(state) {
4991      if (!state.currentTheme) {
4992        return null;
4993      }
4994      return getEntityRecord(state, "root", "theme", state.currentTheme);
4995    }
4996    function __experimentalGetCurrentGlobalStylesId(state) {
4997      return state.currentGlobalStylesId;
4998    }
4999    function getThemeSupports(state) {
5000      return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT2;
5001    }
5002    function getEmbedPreview(state, url) {
5003      return state.embedPreviews[url];
5004    }
5005    function isPreviewEmbedFallback(state, url) {
5006      const preview = state.embedPreviews[url];
5007      const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>";
5008      if (!preview) {
5009        return false;
5010      }
5011      return preview.html === oEmbedLinkCheck;
5012    }
5013    function canUser(state, action, resource, id) {
5014      const isEntity = typeof resource === "object";
5015      if (isEntity && (!resource.kind || !resource.name)) {
5016        return false;
5017      }
5018      if (isEntity) {
5019        logEntityDeprecation(resource.kind, resource.name, "canUser");
5020      }
5021      const key = getUserPermissionCacheKey(action, resource, id);
5022      return state.userPermissions[key];
5023    }
5024    function canUserEditEntityRecord(state, kind, name, recordId) {
5025      (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, {
5026        since: "6.7",
5027        alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )`
5028      });
5029      return canUser(state, "update", { kind, name, id: recordId });
5030    }
5031    function getAutosaves(state, postType, postId) {
5032      return state.autosaves[postId];
5033    }
5034    function getAutosave(state, postType, postId, authorId) {
5035      if (authorId === void 0) {
5036        return;
5037      }
5038      const autosaves2 = state.autosaves[postId];
5039      return autosaves2?.find(
5040        (autosave) => autosave.author === authorId
5041      );
5042    }
5043    var hasFetchedAutosaves = (0, import_data9.createRegistrySelector)(
5044      (select5) => (state, postType, postId) => {
5045        return select5(STORE_NAME).hasFinishedResolution("getAutosaves", [
5046          postType,
5047          postId
5048        ]);
5049      }
5050    );
5051    function getReferenceByDistinctEdits(state) {
5052      return state.editsReference;
5053    }
5054    function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
5055      const currentTheme2 = getCurrentTheme(state);
5056      if (!currentTheme2) {
5057        return null;
5058      }
5059      return state.themeBaseGlobalStyles[currentTheme2.stylesheet];
5060    }
5061    function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
5062      const currentTheme2 = getCurrentTheme(state);
5063      if (!currentTheme2) {
5064        return null;
5065      }
5066      return state.themeGlobalStyleVariations[currentTheme2.stylesheet];
5067    }
5068    function getBlockPatterns(state) {
5069      return state.blockPatterns;
5070    }
5071    function getBlockPatternCategories(state) {
5072      return state.blockPatternCategories;
5073    }
5074    function getUserPatternCategories(state) {
5075      return state.userPatternCategories;
5076    }
5077    function getCurrentThemeGlobalStylesRevisions(state) {
5078      (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", {
5079        since: "6.5.0",
5080        alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )"
5081      });
5082      const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state);
5083      if (!currentGlobalStylesId2) {
5084        return null;
5085      }
5086      return state.themeGlobalStyleRevisions[currentGlobalStylesId2];
5087    }
5088    function getDefaultTemplateId(state, query) {
5089      return state.defaultTemplates[JSON.stringify(query)];
5090    }
5091    var getRevisions = (state, kind, name, recordKey, query) => {
5092      logEntityDeprecation(kind, name, "getRevisions");
5093      const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
5094      if (!queriedStateRevisions) {
5095        return null;
5096      }
5097      return getQueriedItems(queriedStateRevisions, query);
5098    };
5099    function hasRevision(state, kind, name, recordKey, revisionKey, query) {
5100      const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
5101      if (!queriedState) {
5102        return false;
5103      }
5104      const context = query?.context ?? "default";
5105      if (!query || !query._fields) {
5106        return !!queriedState.itemIsComplete[context]?.[revisionKey];
5107      }
5108      const item = queriedState.items[context]?.[revisionKey];
5109      if (!item) {
5110        return false;
5111      }
5112      const fields = get_normalized_comma_separable_default(query._fields) ?? [];
5113      for (let i = 0; i < fields.length; i++) {
5114        const path = fields[i].split(".");
5115        let value = item;
5116        for (let p = 0; p < path.length; p++) {
5117          const part = path[p];
5118          if (!value || !Object.hasOwn(value, part)) {
5119            return false;
5120          }
5121          value = value[part];
5122        }
5123      }
5124      return true;
5125    }
5126    var getRevision = (state, kind, name, recordKey, revisionKey, query) => {
5127      logEntityDeprecation(kind, name, "getRevision");
5128      const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
5129      if (!queriedState) {
5130        return void 0;
5131      }
5132      const context = query?.context ?? "default";
5133      if (!query || !query._fields) {
5134        if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
5135          return void 0;
5136        }
5137        return queriedState.items[context][revisionKey];
5138      }
5139      const item = queriedState.items[context]?.[revisionKey];
5140      if (!item) {
5141        return item;
5142      }
5143      return getFilteredItem(item, query._fields);
5144    };
5145  
5146    // packages/core-data/build-module/actions.mjs
5147    var actions_exports = {};
5148    __export(actions_exports, {
5149      __experimentalBatch: () => __experimentalBatch,
5150      __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId,
5151      __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles,
5152      __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations,
5153      __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits,
5154      __unstableCreateUndoLevel: () => __unstableCreateUndoLevel,
5155      addEntities: () => addEntities,
5156      clearEntityRecordEdits: () => clearEntityRecordEdits,
5157      deleteEntityRecord: () => deleteEntityRecord,
5158      editEntityRecord: () => editEntityRecord,
5159      receiveAutosaves: () => receiveAutosaves,
5160      receiveCurrentTheme: () => receiveCurrentTheme,
5161      receiveCurrentUser: () => receiveCurrentUser,
5162      receiveDefaultTemplateId: () => receiveDefaultTemplateId,
5163      receiveEmbedPreview: () => receiveEmbedPreview,
5164      receiveEntityRecords: () => receiveEntityRecords,
5165      receiveNavigationFallbackId: () => receiveNavigationFallbackId,
5166      receiveRevisions: () => receiveRevisions,
5167      receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions,
5168      receiveThemeSupports: () => receiveThemeSupports,
5169      receiveUploadPermissions: () => receiveUploadPermissions,
5170      receiveUserPermission: () => receiveUserPermission,
5171      receiveUserPermissions: () => receiveUserPermissions,
5172      receiveUserQuery: () => receiveUserQuery,
5173      redo: () => redo,
5174      saveEditedEntityRecord: () => saveEditedEntityRecord,
5175      saveEntityRecord: () => saveEntityRecord,
5176      undo: () => undo
5177    });
5178    var import_es66 = __toESM(require_es6(), 1);
5179    var import_api_fetch4 = __toESM(require_api_fetch(), 1);
5180    var import_url3 = __toESM(require_url(), 1);
5181    var import_deprecated3 = __toESM(require_deprecated(), 1);
5182  
5183    // packages/core-data/build-module/batch/default-processor.mjs
5184    var import_api_fetch3 = __toESM(require_api_fetch(), 1);
5185    var maxItems = null;
5186    function chunk(arr, chunkSize) {
5187      const tmp = [...arr];
5188      const cache3 = [];
5189      while (tmp.length) {
5190        cache3.push(tmp.splice(0, chunkSize));
5191      }
5192      return cache3;
5193    }
5194    async function defaultProcessor(requests) {
5195      if (maxItems === null) {
5196        const preflightResponse = await (0, import_api_fetch3.default)({
5197          path: "/batch/v1",
5198          method: "OPTIONS"
5199        });
5200        maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
5201      }
5202      const results = [];
5203      for (const batchRequests of chunk(requests, maxItems)) {
5204        const batchResponse = await (0, import_api_fetch3.default)({
5205          path: "/batch/v1",
5206          method: "POST",
5207          data: {
5208            validation: "require-all-validate",
5209            requests: batchRequests.map((request) => ({
5210              path: request.path,
5211              body: request.data,
5212              // Rename 'data' to 'body'.
5213              method: request.method,
5214              headers: request.headers
5215            }))
5216          }
5217        });
5218        let batchResults;
5219        if (batchResponse.failed) {
5220          batchResults = batchResponse.responses.map((response) => ({
5221            error: response?.body
5222          }));
5223        } else {
5224          batchResults = batchResponse.responses.map((response) => {
5225            const result = {};
5226            if (response.status >= 200 && response.status < 300) {
5227              result.output = response.body;
5228            } else {
5229              result.error = response.body;
5230            }
5231            return result;
5232          });
5233        }
5234        results.push(...batchResults);
5235      }
5236      return results;
5237    }
5238  
5239    // packages/core-data/build-module/batch/create-batch.mjs
5240    function createBatch(processor = defaultProcessor) {
5241      let lastId = 0;
5242      let queue = [];
5243      const pending = new ObservableSet();
5244      return {
5245        /**
5246         * Adds an input to the batch and returns a promise that is resolved or
5247         * rejected when the input is processed by `batch.run()`.
5248         *
5249         * You may also pass a thunk which allows inputs to be added
5250         * asynchronously.
5251         *
5252         * ```
5253         * // Both are allowed:
5254         * batch.add( { path: '/v1/books', ... } );
5255         * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
5256         * ```
5257         *
5258         * If a thunk is passed, `batch.run()` will pause until either:
5259         *
5260         * - The thunk calls its `add` argument, or;
5261         * - The thunk returns a promise and that promise resolves, or;
5262         * - The thunk returns a non-promise.
5263         *
5264         * @param {any|Function} inputOrThunk Input to add or thunk to execute.
5265         *
5266         * @return {Promise|any} If given an input, returns a promise that
5267         *                       is resolved or rejected when the batch is
5268         *                       processed. If given a thunk, returns the return
5269         *                       value of that thunk.
5270         */
5271        add(inputOrThunk) {
5272          const id = ++lastId;
5273          pending.add(id);
5274          const add = (input) => new Promise((resolve, reject) => {
5275            queue.push({
5276              input,
5277              resolve,
5278              reject
5279            });
5280            pending.delete(id);
5281          });
5282          if (typeof inputOrThunk === "function") {
5283            return Promise.resolve(inputOrThunk(add)).finally(() => {
5284              pending.delete(id);
5285            });
5286          }
5287          return add(inputOrThunk);
5288        },
5289        /**
5290         * Runs the batch. This calls `batchProcessor` and resolves or rejects
5291         * all promises returned by `add()`.
5292         *
5293         * @return {Promise<boolean>} A promise that resolves to a boolean that is true
5294         *                   if the processor returned no errors.
5295         */
5296        async run() {
5297          if (pending.size) {
5298            await new Promise((resolve) => {
5299              const unsubscribe = pending.subscribe(() => {
5300                if (!pending.size) {
5301                  unsubscribe();
5302                  resolve(void 0);
5303                }
5304              });
5305            });
5306          }
5307          let results;
5308          try {
5309            results = await processor(
5310              queue.map(({ input }) => input)
5311            );
5312            if (results.length !== queue.length) {
5313              throw new Error(
5314                "run: Array returned by processor must be same size as input array."
5315              );
5316            }
5317          } catch (error) {
5318            for (const { reject } of queue) {
5319              reject(error);
5320            }
5321            throw error;
5322          }
5323          let isSuccess = true;
5324          results.forEach((result, key) => {
5325            const queueItem = queue[key];
5326            if (result?.error) {
5327              queueItem?.reject(result.error);
5328              isSuccess = false;
5329            } else {
5330              queueItem?.resolve(result?.output ?? result);
5331            }
5332          });
5333          queue = [];
5334          return isSuccess;
5335        }
5336      };
5337    }
5338    var ObservableSet = class {
5339      constructor(...args) {
5340        this.set = new Set(...args);
5341        this.subscribers = /* @__PURE__ */ new Set();
5342      }
5343      get size() {
5344        return this.set.size;
5345      }
5346      add(value) {
5347        this.set.add(value);
5348        this.subscribers.forEach((subscriber) => subscriber());
5349        return this;
5350      }
5351      delete(value) {
5352        const isSuccess = this.set.delete(value);
5353        this.subscribers.forEach((subscriber) => subscriber());
5354        return isSuccess;
5355      }
5356      subscribe(subscriber) {
5357        this.subscribers.add(subscriber);
5358        return () => {
5359          this.subscribers.delete(subscriber);
5360        };
5361      }
5362    };
5363  
5364    // packages/core-data/build-module/actions.mjs
5365    function addTitleToAutoDraft(record) {
5366      return record.status === "auto-draft" ? { ...record, title: "" } : record;
5367    }
5368    function getServerMutatedMetaFields(updatedMeta, persistedMeta, syncedMeta) {
5369      const baseline = { ...persistedMeta, ...syncedMeta };
5370      return Object.fromEntries(
5371        Object.entries(updatedMeta ?? {}).filter(([key, value]) => {
5372          if (key === POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE) {
5373            return false;
5374          }
5375          return !(0, import_es66.default)(value, baseline[key]);
5376        })
5377      );
5378    }
5379    function getServerMutatedFields(updatedRecord, persistedRecord, syncedChanges) {
5380      return Object.fromEntries(
5381        Object.entries(updatedRecord).flatMap(([key, value]) => {
5382          if (key === "meta") {
5383            const serverMutatedMeta = getServerMutatedMetaFields(
5384              value,
5385              persistedRecord.meta,
5386              syncedChanges.meta
5387            );
5388            return Object.keys(serverMutatedMeta).length ? [[key, serverMutatedMeta]] : [];
5389          }
5390          const baseline = key in syncedChanges ? syncedChanges[key] : persistedRecord[key];
5391          const wasServerMutated = !(0, import_es66.default)(
5392            getRawValue(value) ?? value,
5393            getRawValue(baseline) ?? baseline
5394          );
5395          return wasServerMutated ? [[key, value]] : [];
5396        })
5397      );
5398    }
5399    function receiveUserQuery(queryID, users2) {
5400      return {
5401        type: "RECEIVE_USER_QUERY",
5402        users: Array.isArray(users2) ? users2 : [users2],
5403        queryID
5404      };
5405    }
5406    function receiveCurrentUser(currentUser2) {
5407      return {
5408        type: "RECEIVE_CURRENT_USER",
5409        currentUser: currentUser2
5410      };
5411    }
5412    function addEntities(entities2) {
5413      return {
5414        type: "ADD_ENTITIES",
5415        entities: entities2
5416      };
5417    }
5418    function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) {
5419      if (kind === "postType") {
5420        records = Array.isArray(records) ? records.map(addTitleToAutoDraft) : addTitleToAutoDraft(records);
5421      }
5422      let action;
5423      if (query) {
5424        action = receiveQueriedItems(records, query, edits, meta);
5425      } else {
5426        action = receiveItems(records, edits, meta);
5427      }
5428      return {
5429        ...action,
5430        kind,
5431        name,
5432        invalidateCache
5433      };
5434    }
5435    function receiveCurrentTheme(currentTheme2) {
5436      return {
5437        type: "RECEIVE_CURRENT_THEME",
5438        currentTheme: currentTheme2
5439      };
5440    }
5441    function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) {
5442      return {
5443        type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID",
5444        id: currentGlobalStylesId2
5445      };
5446    }
5447    function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
5448      return {
5449        type: "RECEIVE_THEME_GLOBAL_STYLES",
5450        stylesheet,
5451        globalStyles
5452      };
5453    }
5454    function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
5455      return {
5456        type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS",
5457        stylesheet,
5458        variations
5459      };
5460    }
5461    function receiveThemeSupports() {
5462      (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", {
5463        since: "5.9"
5464      });
5465      return {
5466        type: "DO_NOTHING"
5467      };
5468    }
5469    function receiveThemeGlobalStyleRevisions(currentId, revisions) {
5470      (0, import_deprecated3.default)(
5471        "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()",
5472        {
5473          since: "6.5.0",
5474          alternative: "wp.data.dispatch( 'core' ).receiveRevisions"
5475        }
5476      );
5477      return {
5478        type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS",
5479        currentId,
5480        revisions
5481      };
5482    }
5483    function receiveEmbedPreview(url, preview) {
5484      return {
5485        type: "RECEIVE_EMBED_PREVIEW",
5486        url,
5487        preview
5488      };
5489    }
5490    var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5491      logEntityDeprecation(kind, name, "deleteEntityRecord");
5492      const configs = await resolveSelect2.getEntitiesConfig(kind);
5493      const entityConfig = configs.find(
5494        (config) => config.kind === kind && config.name === name
5495      );
5496      let error;
5497      let deletedRecord = false;
5498      if (!entityConfig) {
5499        return;
5500      }
5501      const lock2 = await dispatch3.__unstableAcquireStoreLock(
5502        STORE_NAME,
5503        ["entities", "records", kind, name, recordId],
5504        { exclusive: true }
5505      );
5506      try {
5507        dispatch3({
5508          type: "DELETE_ENTITY_RECORD_START",
5509          kind,
5510          name,
5511          recordId
5512        });
5513        let hasError = false;
5514        const { baseURL } = entityConfig;
5515        try {
5516          let path = `$baseURL}/$recordId}`;
5517          if (query) {
5518            path = (0, import_url3.addQueryArgs)(path, query);
5519          }
5520          deletedRecord = await __unstableFetch({
5521            path,
5522            method: "DELETE"
5523          });
5524          await dispatch3(removeItems(kind, name, recordId, true));
5525          if (entityConfig.syncConfig) {
5526            const objectType = `$kind}/$name}`;
5527            const objectId = recordId;
5528            getSyncManager()?.unload(objectType, objectId);
5529          }
5530        } catch (_error) {
5531          hasError = true;
5532          error = _error;
5533        }
5534        dispatch3({
5535          type: "DELETE_ENTITY_RECORD_FINISH",
5536          kind,
5537          name,
5538          recordId,
5539          error
5540        });
5541        if (hasError && throwOnError) {
5542          throw error;
5543        }
5544        return deletedRecord;
5545      } finally {
5546        dispatch3.__unstableReleaseStoreLock(lock2);
5547      }
5548    };
5549    var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select: select5, dispatch: dispatch3 }) => {
5550      logEntityDeprecation(kind, name, "editEntityRecord");
5551      const entityConfig = select5.getEntityConfig(kind, name);
5552      if (!entityConfig) {
5553        throw new Error(
5554          `The entity being edited ($kind}, $name}) does not have a loaded config.`
5555        );
5556      }
5557      const { mergedEdits = {} } = entityConfig;
5558      const record = select5.getRawEntityRecord(kind, name, recordId);
5559      const editedRecord = select5.getEditedEntityRecord(
5560        kind,
5561        name,
5562        recordId
5563      );
5564      const editsWithMerges = Object.keys(edits).reduce((acc, key) => {
5565        acc[key] = mergedEdits[key] ? { ...editedRecord[key], ...edits[key] } : edits[key];
5566        return acc;
5567      }, {});
5568      const edit = {
5569        kind,
5570        name,
5571        recordId,
5572        // Clear edits when they are equal to their persisted counterparts
5573        // so that the property is not considered dirty.
5574        edits: clearUnchangedEdits(editsWithMerges, record)
5575      };
5576      if (entityConfig.syncConfig) {
5577        const objectType = `$kind}/$name}`;
5578        const objectId = recordId;
5579        const isNewUndoLevel = options.undoIgnore ? false : !options.isCached;
5580        const origin = options.undoIgnore ? LOCAL_UNDO_IGNORED_ORIGIN : LOCAL_EDITOR_ORIGIN;
5581        getSyncManager()?.update(
5582          objectType,
5583          objectId,
5584          editsWithMerges,
5585          origin,
5586          { isNewUndoLevel }
5587        );
5588      }
5589      if (!options.undoIgnore) {
5590        select5.getUndoManager().addRecord(
5591          [
5592            {
5593              id: { kind, name, recordId },
5594              changes: Object.keys(edits).reduce((acc, key) => {
5595                acc[key] = {
5596                  from: editedRecord[key],
5597                  to: edits[key]
5598                };
5599                return acc;
5600              }, {})
5601            }
5602          ],
5603          options.isCached
5604        );
5605      }
5606      dispatch3({
5607        type: "EDIT_ENTITY_RECORD",
5608        ...edit
5609      });
5610    };
5611    var clearEntityRecordEdits = (kind, name, recordId) => ({ select: select5, dispatch: dispatch3 }) => {
5612      const entityConfig = select5.getEntityConfig(kind, name);
5613      logEntityDeprecation(kind, name, "clearEntityRecordEdits");
5614      if (!entityConfig) {
5615        throw new Error(
5616          `The entity being edited ($kind}, $name}) does not have a loaded config.`
5617        );
5618      }
5619      const currentEdits = select5.getEntityRecordEdits(
5620        kind,
5621        name,
5622        recordId
5623      );
5624      if (!currentEdits) {
5625        return;
5626      }
5627      const clearedEdits = Object.keys(currentEdits).reduce(
5628        (acc, key) => {
5629          acc[key] = void 0;
5630          return acc;
5631        },
5632        {}
5633      );
5634      dispatch3({
5635        type: "EDIT_ENTITY_RECORD",
5636        kind,
5637        name,
5638        recordId,
5639        edits: clearedEdits
5640      });
5641    };
5642    var undo = () => ({ select: select5, dispatch: dispatch3 }) => {
5643      const undoRecord = select5.getUndoManager().undo();
5644      if (!undoRecord) {
5645        return;
5646      }
5647      dispatch3({
5648        type: "UNDO",
5649        record: undoRecord
5650      });
5651    };
5652    var redo = () => ({ select: select5, dispatch: dispatch3 }) => {
5653      const redoRecord = select5.getUndoManager().redo();
5654      if (!redoRecord) {
5655        return;
5656      }
5657      dispatch3({
5658        type: "REDO",
5659        record: redoRecord
5660      });
5661    };
5662    var __unstableCreateUndoLevel = () => ({ select: select5 }) => {
5663      select5.getUndoManager().addRecord();
5664    };
5665    var saveEntityRecord = (kind, name, record, options = {}) => async ({ select: select5, resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
5666      const {
5667        isAutosave = false,
5668        __unstableFetch = import_api_fetch4.default,
5669        __unstableSkipSyncUpdate = false,
5670        throwOnError = false
5671      } = options;
5672      logEntityDeprecation(kind, name, "saveEntityRecord");
5673      const configs = await resolveSelect2.getEntitiesConfig(kind);
5674      const entityConfig = configs.find(
5675        (config) => config.kind === kind && config.name === name
5676      );
5677      if (!entityConfig) {
5678        return;
5679      }
5680      const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY;
5681      const recordId = record[entityIdKey];
5682      const isNewRecord = !!entityIdKey && !recordId;
5683      const lock2 = await dispatch3.__unstableAcquireStoreLock(
5684        STORE_NAME,
5685        ["entities", "records", kind, name, recordId || v4_default()],
5686        { exclusive: true }
5687      );
5688      try {
5689        for (const [key, value] of Object.entries(record)) {
5690          if (typeof value === "function") {
5691            const evaluatedValue = value(
5692              select5.getEditedEntityRecord(kind, name, recordId)
5693            );
5694            dispatch3.editEntityRecord(
5695              kind,
5696              name,
5697              recordId,
5698              {
5699                [key]: evaluatedValue
5700              },
5701              { undoIgnore: true }
5702            );
5703            record[key] = evaluatedValue;
5704          }
5705        }
5706        dispatch3({
5707          type: "SAVE_ENTITY_RECORD_START",
5708          kind,
5709          name,
5710          recordId,
5711          isAutosave
5712        });
5713        let updatedRecord;
5714        let error;
5715        let hasError = false;
5716        const { baseURL } = entityConfig;
5717        try {
5718          const path = `$baseURL}$recordId ? "/" + recordId : ""}`;
5719          const persistedRecord = !isNewRecord ? select5.getRawEntityRecord(kind, name, recordId) : {};
5720          if (entityConfig.syncConfig && !__unstableSkipSyncUpdate && !isNewRecord && persistedRecord) {
5721            getSyncManager()?.update(
5722              `$kind}/$name}`,
5723              recordId,
5724              record,
5725              LOCAL_UNDO_IGNORED_ORIGIN
5726            );
5727          }
5728          if (isAutosave) {
5729            const merged = { ...persistedRecord, ...record };
5730            const data = [
5731              "title",
5732              "excerpt",
5733              "content",
5734              "meta"
5735            ].reduce(
5736              (acc, key) => {
5737                if (key in merged) {
5738                  acc[key] = merged[key];
5739                }
5740                return acc;
5741              },
5742              {
5743                // Do not update the `status` if we have edited it when auto saving.
5744                // It's very important to let the user explicitly save this change,
5745                // because it can lead to unexpected results. An example would be to
5746                // have a draft post and change the status to publish.
5747                status: merged.status === "auto-draft" ? "draft" : void 0
5748              }
5749            );
5750            if (entityConfig.syncConfig) {
5751              const crdtSnapshot = getSyncManager()?.getEntitySnapshot(
5752                `$kind}/$name}`,
5753                recordId
5754              );
5755              if (crdtSnapshot) {
5756                data[CRDT_AUTOSAVE_SNAPSHOT_KEY] = crdtSnapshot;
5757              }
5758            }
5759            updatedRecord = await __unstableFetch({
5760              path: `$path}/autosaves`,
5761              method: "POST",
5762              data
5763            });
5764            if (persistedRecord.id === updatedRecord.id) {
5765              let newRecord = {
5766                ...persistedRecord,
5767                ...data,
5768                ...updatedRecord
5769              };
5770              newRecord = Object.keys(newRecord).reduce(
5771                (acc, key) => {
5772                  if ([
5773                    "title",
5774                    "excerpt",
5775                    "content",
5776                    "meta"
5777                  ].includes(key)) {
5778                    acc[key] = newRecord[key];
5779                  } else if (key === "status") {
5780                    acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status;
5781                  } else {
5782                    acc[key] = persistedRecord[key];
5783                  }
5784                  return acc;
5785                },
5786                {}
5787              );
5788              dispatch3.receiveEntityRecords(
5789                kind,
5790                name,
5791                newRecord,
5792                void 0,
5793                true
5794              );
5795            } else {
5796              dispatch3.receiveAutosaves(
5797                persistedRecord.id,
5798                updatedRecord
5799              );
5800            }
5801          } else {
5802            let edits = record;
5803            if (entityConfig.__unstablePrePersist) {
5804              edits = {
5805                ...edits,
5806                ...await entityConfig.__unstablePrePersist(
5807                  persistedRecord,
5808                  edits
5809                )
5810              };
5811            }
5812            updatedRecord = await __unstableFetch({
5813              path,
5814              method: recordId ? "PUT" : "POST",
5815              data: edits
5816            });
5817            dispatch3.receiveEntityRecords(
5818              kind,
5819              name,
5820              updatedRecord,
5821              void 0,
5822              true,
5823              record
5824            );
5825            if (entityConfig.syncConfig) {
5826              let syncChanges;
5827              if (__unstableSkipSyncUpdate) {
5828                syncChanges = {};
5829              } else if (isNewRecord || !persistedRecord) {
5830                syncChanges = updatedRecord;
5831              } else {
5832                syncChanges = getServerMutatedFields(
5833                  updatedRecord,
5834                  persistedRecord,
5835                  record
5836                );
5837              }
5838              getSyncManager()?.update(
5839                `$kind}/$name}`,
5840                recordId,
5841                syncChanges,
5842                LOCAL_UNDO_IGNORED_ORIGIN,
5843                { isSave: true }
5844              );
5845            }
5846          }
5847        } catch (_error) {
5848          hasError = true;
5849          error = _error;
5850        }
5851        dispatch3({
5852          type: "SAVE_ENTITY_RECORD_FINISH",
5853          kind,
5854          name,
5855          recordId,
5856          error,
5857          isAutosave
5858        });
5859        if (hasError && throwOnError) {
5860          throw error;
5861        }
5862        return updatedRecord;
5863      } finally {
5864        dispatch3.__unstableReleaseStoreLock(lock2);
5865      }
5866    };
5867    var __experimentalBatch = (requests) => async ({ dispatch: dispatch3 }) => {
5868      const batch = createBatch();
5869      const api = {
5870        saveEntityRecord(kind, name, record, options) {
5871          return batch.add(
5872            (add) => dispatch3.saveEntityRecord(kind, name, record, {
5873              ...options,
5874              __unstableFetch: add
5875            })
5876          );
5877        },
5878        saveEditedEntityRecord(kind, name, recordId, options) {
5879          return batch.add(
5880            (add) => dispatch3.saveEditedEntityRecord(kind, name, recordId, {
5881              ...options,
5882              __unstableFetch: add
5883            })
5884          );
5885        },
5886        deleteEntityRecord(kind, name, recordId, query, options) {
5887          return batch.add(
5888            (add) => dispatch3.deleteEntityRecord(kind, name, recordId, query, {
5889              ...options,
5890              __unstableFetch: add
5891            })
5892          );
5893        }
5894      };
5895      const resultPromises = requests.map((request) => request(api));
5896      const [, ...results] = await Promise.all([
5897        batch.run(),
5898        ...resultPromises
5899      ]);
5900      return results;
5901    };
5902    var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select: select5, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5903      logEntityDeprecation(kind, name, "saveEditedEntityRecord");
5904      if (!select5.hasEditsForEntityRecord(kind, name, recordId)) {
5905        return;
5906      }
5907      const configs = await resolveSelect2.getEntitiesConfig(kind);
5908      const entityConfig = configs.find(
5909        (config) => config.kind === kind && config.name === name
5910      );
5911      if (!entityConfig) {
5912        return;
5913      }
5914      const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
5915      const edits = select5.getEntityRecordNonTransientEdits(
5916        kind,
5917        name,
5918        recordId
5919      );
5920      const record = { [entityIdKey]: recordId, ...edits };
5921      return await dispatch3.saveEntityRecord(kind, name, record, options);
5922    };
5923    var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select: select5, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5924      logEntityDeprecation(
5925        kind,
5926        name,
5927        "__experimentalSaveSpecifiedEntityEdits"
5928      );
5929      if (!select5.hasEditsForEntityRecord(kind, name, recordId)) {
5930        return;
5931      }
5932      const edits = select5.getEntityRecordNonTransientEdits(
5933        kind,
5934        name,
5935        recordId
5936      );
5937      const editsToSave = {};
5938      for (const item of itemsToSave) {
5939        setNestedValue(editsToSave, item, getNestedValue(edits, item));
5940      }
5941      const configs = await resolveSelect2.getEntitiesConfig(kind);
5942      const entityConfig = configs.find(
5943        (config) => config.kind === kind && config.name === name
5944      );
5945      const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY;
5946      if (recordId) {
5947        editsToSave[entityIdKey] = recordId;
5948      }
5949      return await dispatch3.saveEntityRecord(
5950        kind,
5951        name,
5952        editsToSave,
5953        options
5954      );
5955    };
5956    function receiveUploadPermissions(hasUploadPermissions) {
5957      (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
5958        since: "5.9",
5959        alternative: "receiveUserPermission"
5960      });
5961      return receiveUserPermission("create/media", hasUploadPermissions);
5962    }
5963    function receiveUserPermission(key, isAllowed) {
5964      return {
5965        type: "RECEIVE_USER_PERMISSION",
5966        key,
5967        isAllowed
5968      };
5969    }
5970    function receiveUserPermissions(permissions) {
5971      return {
5972        type: "RECEIVE_USER_PERMISSIONS",
5973        permissions
5974      };
5975    }
5976    function receiveAutosaves(postId, autosaves2) {
5977      return {
5978        type: "RECEIVE_AUTOSAVES",
5979        postId,
5980        autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2]
5981      };
5982    }
5983    function receiveNavigationFallbackId(fallbackId) {
5984      return {
5985        type: "RECEIVE_NAVIGATION_FALLBACK_ID",
5986        fallbackId
5987      };
5988    }
5989    function receiveDefaultTemplateId(query, templateId) {
5990      return {
5991        type: "RECEIVE_DEFAULT_TEMPLATE",
5992        query,
5993        templateId
5994      };
5995    }
5996    var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5997      logEntityDeprecation(kind, name, "receiveRevisions");
5998      const configs = await resolveSelect2.getEntitiesConfig(kind);
5999      const entityConfig = configs.find(
6000        (config) => config.kind === kind && config.name === name
6001      );
6002      const key = entityConfig?.revisionKey ?? DEFAULT_ENTITY_KEY;
6003      dispatch3({
6004        type: "RECEIVE_ITEM_REVISIONS",
6005        key,
6006        items: records,
6007        recordKey,
6008        meta,
6009        query,
6010        kind,
6011        name,
6012        invalidateCache
6013      });
6014    };
6015  
6016    // packages/core-data/build-module/private-actions.mjs
6017    var private_actions_exports = {};
6018    __export(private_actions_exports, {
6019      __unstableNotifySyncUndoManagerChange: () => __unstableNotifySyncUndoManagerChange,
6020      editMediaEntity: () => editMediaEntity,
6021      receiveEditorAssets: () => receiveEditorAssets,
6022      receiveEditorSettings: () => receiveEditorSettings,
6023      receiveRegisteredPostMeta: () => receiveRegisteredPostMeta,
6024      receiveViewConfig: () => receiveViewConfig,
6025      saveDirtyEntities: () => saveDirtyEntities,
6026      setCollaborationSupported: () => setCollaborationSupported,
6027      setSyncConnectionStatus: () => setSyncConnectionStatus
6028    });
6029    var import_api_fetch5 = __toESM(require_api_fetch(), 1);
6030    var import_notices = __toESM(require_notices(), 1);
6031    var import_block_editor5 = __toESM(require_block_editor(), 1);
6032    var import_html_entities = __toESM(require_html_entities(), 1);
6033    var import_i18n2 = __toESM(require_i18n(), 1);
6034    function receiveRegisteredPostMeta(postType, registeredPostMeta2) {
6035      return {
6036        type: "RECEIVE_REGISTERED_POST_META",
6037        postType,
6038        registeredPostMeta: registeredPostMeta2
6039      };
6040    }
6041    var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6042      if (!recordId) {
6043        return;
6044      }
6045      const kind = "postType";
6046      const name = "attachment";
6047      const configs = await resolveSelect2.getEntitiesConfig(kind);
6048      const entityConfig = configs.find(
6049        (config) => config.kind === kind && config.name === name
6050      );
6051      if (!entityConfig) {
6052        return;
6053      }
6054      const lock2 = await dispatch3.__unstableAcquireStoreLock(
6055        STORE_NAME,
6056        ["entities", "records", kind, name, recordId],
6057        { exclusive: true }
6058      );
6059      let updatedRecord;
6060      let error;
6061      let hasError = false;
6062      try {
6063        dispatch3({
6064          type: "SAVE_ENTITY_RECORD_START",
6065          kind,
6066          name,
6067          recordId
6068        });
6069        try {
6070          const path = `$entityConfig.baseURL}/$recordId}/edit`;
6071          const newRecord = await __unstableFetch({
6072            path,
6073            method: "POST",
6074            data: {
6075              ...edits
6076            }
6077          });
6078          if (newRecord) {
6079            dispatch3.receiveEntityRecords(
6080              kind,
6081              name,
6082              newRecord,
6083              void 0,
6084              true,
6085              void 0,
6086              void 0
6087            );
6088            updatedRecord = newRecord;
6089          }
6090        } catch (e) {
6091          error = e;
6092          hasError = true;
6093        }
6094        dispatch3({
6095          type: "SAVE_ENTITY_RECORD_FINISH",
6096          kind,
6097          name,
6098          recordId,
6099          error
6100        });
6101        if (hasError && throwOnError) {
6102          throw error;
6103        }
6104        return updatedRecord;
6105      } finally {
6106        dispatch3.__unstableReleaseStoreLock(lock2);
6107      }
6108    };
6109    function receiveEditorSettings(settings) {
6110      return {
6111        type: "RECEIVE_EDITOR_SETTINGS",
6112        settings
6113      };
6114    }
6115    function receiveEditorAssets(assets) {
6116      return {
6117        type: "RECEIVE_EDITOR_ASSETS",
6118        assets
6119      };
6120    }
6121    var setCollaborationSupported = (supported) => ({ dispatch: dispatch3 }) => {
6122      dispatch3({ type: "SET_COLLABORATION_SUPPORTED", supported });
6123      if (!supported && hasSyncManager()) {
6124        getSyncManager().unloadAll();
6125        dispatch3.__unstableNotifySyncUndoManagerChange({
6126          hasUndo: false,
6127          hasRedo: false
6128        });
6129      }
6130    };
6131    function receiveViewConfig(kind, name, config) {
6132      return {
6133        type: "RECEIVE_VIEW_CONFIG",
6134        kind,
6135        name,
6136        config
6137      };
6138    }
6139    function __unstableNotifySyncUndoManagerChange(state) {
6140      return {
6141        type: "SYNC_UNDO_MANAGER_CHANGE",
6142        ...state
6143      };
6144    }
6145    function setSyncConnectionStatus(kind, name, key, status) {
6146      if (!status) {
6147        return {
6148          type: "CLEAR_SYNC_CONNECTION_STATUS",
6149          kind,
6150          name,
6151          key
6152        };
6153      }
6154      return {
6155        type: "SET_SYNC_CONNECTION_STATUS",
6156        kind,
6157        name,
6158        key,
6159        status
6160      };
6161    }
6162    var saveDirtyEntities = ({
6163      onSave,
6164      dirtyEntityRecords = [],
6165      entitiesToSkip = [],
6166      close,
6167      successNoticeContent
6168    } = {}) => ({ registry }) => {
6169      const PUBLISH_ON_SAVE_ENTITIES = [
6170        { kind: "postType", name: "wp_navigation" }
6171      ];
6172      const saveNoticeId = "site-editor-save-success";
6173      const homeUrl = registry.select(STORE_NAME).getEntityRecord("root", "__unstableBase")?.home;
6174      registry.dispatch(import_notices.store).removeNotice(saveNoticeId);
6175      const entitiesToSave = dirtyEntityRecords.filter(
6176        ({ kind, name, key, property }) => {
6177          return !entitiesToSkip.some(
6178            (elt) => elt.kind === kind && elt.name === name && elt.key === key && elt.property === property
6179          );
6180        }
6181      );
6182      close?.(entitiesToSave);
6183      const siteItemsToSave = [];
6184      const pendingSavedRecords = [];
6185      entitiesToSave.forEach(({ kind, name, key, property }) => {
6186        if ("root" === kind && "site" === name) {
6187          siteItemsToSave.push(property);
6188        } else {
6189          if (PUBLISH_ON_SAVE_ENTITIES.some(
6190            (typeToPublish) => typeToPublish.kind === kind && typeToPublish.name === name
6191          )) {
6192            registry.dispatch(STORE_NAME).editEntityRecord(kind, name, key, {
6193              status: "publish"
6194            });
6195          }
6196          pendingSavedRecords.push(
6197            registry.dispatch(STORE_NAME).saveEditedEntityRecord(kind, name, key, {
6198              throwOnError: true
6199            }).catch(ensureError)
6200          );
6201        }
6202      });
6203      if (siteItemsToSave.length) {
6204        pendingSavedRecords.push(
6205          registry.dispatch(STORE_NAME).__experimentalSaveSpecifiedEntityEdits(
6206            "root",
6207            "site",
6208            void 0,
6209            siteItemsToSave,
6210            {
6211              throwOnError: true
6212            }
6213          ).catch(ensureError)
6214        );
6215      }
6216      registry.dispatch(import_block_editor5.store).__unstableMarkLastChangeAsPersistent();
6217      return Promise.all(pendingSavedRecords).then(async (values) => {
6218        if (onSave) {
6219          await onSave();
6220        }
6221        return values;
6222      }).then((values) => {
6223        const errors = values.filter((v) => v instanceof Error);
6224        if (errors.length) {
6225          const firstMessage = errors.find(
6226            (e) => e.message
6227          )?.message;
6228          registry.dispatch(import_notices.store).createErrorNotice(
6229            (0, import_html_entities.decodeEntities)(
6230              firstMessage || (0, import_i18n2.__)("Saving failed.")
6231            ),
6232            {
6233              type: "snackbar",
6234              id: saveNoticeId
6235            }
6236          );
6237        } else {
6238          registry.dispatch(import_notices.store).createSuccessNotice(
6239            successNoticeContent || (0, import_i18n2.__)("Site updated."),
6240            {
6241              type: "snackbar",
6242              id: saveNoticeId,
6243              actions: [
6244                {
6245                  label: (0, import_i18n2.__)("View site"),
6246                  url: homeUrl,
6247                  openInNewTab: true
6248                }
6249              ]
6250            }
6251          );
6252        }
6253      }).catch(
6254        (error) => registry.dispatch(import_notices.store).createErrorNotice(
6255          (0, import_html_entities.decodeEntities)(
6256            error?.message || (0, import_i18n2.__)("Saving failed.")
6257          ),
6258          {
6259            type: "snackbar",
6260            id: saveNoticeId
6261          }
6262        )
6263      );
6264      function ensureError(error) {
6265        if (error instanceof Error) {
6266          return error;
6267        }
6268        let message;
6269        if (!error) {
6270        } else if (typeof error.message === "string") {
6271          message = error.message;
6272        } else if (typeof error === "string") {
6273          message = error;
6274        } else if (
6275          // Only consider own method, lest we erroneously end up calling
6276          // `Object#toString` at the end of the prototype chain, thereby
6277          // returning `"[object Object]"`.
6278          Object.hasOwn(error, "toString") && typeof error.toString === "function"
6279        ) {
6280          const result = error.toString();
6281          if (typeof result === "string") {
6282            message = result;
6283          }
6284        }
6285        return new Error(message, { cause: error });
6286      }
6287    };
6288  
6289    // packages/core-data/build-module/resolvers.mjs
6290    var resolvers_exports = {};
6291    __export(resolvers_exports, {
6292      __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2,
6293      __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2,
6294      __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2,
6295      canUser: () => canUser2,
6296      canUserEditEntityRecord: () => canUserEditEntityRecord2,
6297      getAuthors: () => getAuthors2,
6298      getAutosave: () => getAutosave2,
6299      getAutosaves: () => getAutosaves2,
6300      getBlockPatternCategories: () => getBlockPatternCategories2,
6301      getBlockPatterns: () => getBlockPatterns2,
6302      getCurrentTheme: () => getCurrentTheme2,
6303      getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2,
6304      getCurrentUser: () => getCurrentUser2,
6305      getDefaultTemplateId: () => getDefaultTemplateId2,
6306      getEditedEntityRecord: () => getEditedEntityRecord2,
6307      getEditorAssets: () => getEditorAssets2,
6308      getEditorSettings: () => getEditorSettings2,
6309      getEmbedPreview: () => getEmbedPreview2,
6310      getEntitiesConfig: () => getEntitiesConfig2,
6311      getEntityRecord: () => getEntityRecord2,
6312      getEntityRecords: () => getEntityRecords2,
6313      getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2,
6314      getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2,
6315      getNavigationFallbackId: () => getNavigationFallbackId2,
6316      getRawEntityRecord: () => getRawEntityRecord2,
6317      getRegisteredPostMeta: () => getRegisteredPostMeta2,
6318      getRevision: () => getRevision2,
6319      getRevisions: () => getRevisions2,
6320      getThemeSupports: () => getThemeSupports2,
6321      getUserPatternCategories: () => getUserPatternCategories2,
6322      getViewConfig: () => getViewConfig2
6323    });
6324    var import_url6 = __toESM(require_url(), 1);
6325    var import_html_entities3 = __toESM(require_html_entities(), 1);
6326    var import_api_fetch9 = __toESM(require_api_fetch(), 1);
6327  
6328    // packages/core-data/build-module/fetch/index.mjs
6329    var import_api_fetch8 = __toESM(require_api_fetch(), 1);
6330  
6331    // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs
6332    var import_api_fetch6 = __toESM(require_api_fetch(), 1);
6333    var import_url4 = __toESM(require_url(), 1);
6334    var import_html_entities2 = __toESM(require_html_entities(), 1);
6335    var import_i18n3 = __toESM(require_i18n(), 1);
6336    async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) {
6337      const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? {
6338        ...searchOptions,
6339        ...searchOptions.initialSuggestionsSearchOptions
6340      } : searchOptions;
6341      const {
6342        type,
6343        subtype,
6344        page,
6345        perPage = searchOptions.isInitialSuggestions ? 3 : 20
6346      } = searchOptionsToUse;
6347      const { disablePostFormats = false } = editorSettings2;
6348      const queries2 = [];
6349      if (!type || type === "post") {
6350        queries2.push(
6351          (0, import_api_fetch6.default)({
6352            path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
6353              search,
6354              page,
6355              per_page: perPage,
6356              type: "post",
6357              subtype
6358            })
6359          }).then((results2) => {
6360            return results2.map((result) => {
6361              return {
6362                id: result.id,
6363                url: result.url,
6364                title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
6365                type: result.subtype || result.type,
6366                kind: "post-type"
6367              };
6368            });
6369          }).catch(() => [])
6370          // Fail by returning no results.
6371        );
6372      }
6373      if (!type || type === "term") {
6374        queries2.push(
6375          (0, import_api_fetch6.default)({
6376            path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
6377              search,
6378              page,
6379              per_page: perPage,
6380              type: "term",
6381              subtype
6382            })
6383          }).then((results2) => {
6384            return results2.map((result) => {
6385              return {
6386                id: result.id,
6387                url: result.url,
6388                title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
6389                type: result.subtype || result.type,
6390                kind: "taxonomy"
6391              };
6392            });
6393          }).catch(() => [])
6394          // Fail by returning no results.
6395        );
6396      }
6397      if (!disablePostFormats && (!type || type === "post-format")) {
6398        queries2.push(
6399          (0, import_api_fetch6.default)({
6400            path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
6401              search,
6402              page,
6403              per_page: perPage,
6404              type: "post-format",
6405              subtype
6406            })
6407          }).then((results2) => {
6408            return results2.map((result) => {
6409              return {
6410                id: result.id,
6411                url: result.url,
6412                title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
6413                type: result.subtype || result.type,
6414                kind: "taxonomy"
6415              };
6416            });
6417          }).catch(() => [])
6418          // Fail by returning no results.
6419        );
6420      }
6421      if (!type || type === "attachment") {
6422        queries2.push(
6423          (0, import_api_fetch6.default)({
6424            path: (0, import_url4.addQueryArgs)("/wp/v2/media", {
6425              search,
6426              page,
6427              per_page: perPage
6428            })
6429          }).then((results2) => {
6430            return results2.map((result) => {
6431              return {
6432                id: result.id,
6433                url: result.source_url,
6434                title: (0, import_html_entities2.decodeEntities)(result.title.rendered || "") || (0, import_i18n3.__)("(no title)"),
6435                type: result.type,
6436                kind: "media"
6437              };
6438            });
6439          }).catch(() => [])
6440          // Fail by returning no results.
6441        );
6442      }
6443      const responses = await Promise.all(queries2);
6444      let results = responses.flat();
6445      results = results.filter((result) => !!result.id);
6446      results = sortResults(results, search);
6447      results = results.slice(0, perPage);
6448      return results;
6449    }
6450    function sortResults(results, search) {
6451      const searchTokens = tokenize(search);
6452      const scoreKey = (result) => `$result.kind}:$result.type}:$result.id}`;
6453      const scores = {};
6454      for (const result of results) {
6455        if (result.title) {
6456          const titleTokens = tokenize(result.title);
6457          const exactMatchingTokens = titleTokens.filter(
6458            (titleToken) => searchTokens.some(
6459              (searchToken) => titleToken === searchToken
6460            )
6461          );
6462          const subMatchingTokens = titleTokens.filter(
6463            (titleToken) => searchTokens.some(
6464              (searchToken) => titleToken !== searchToken && titleToken.includes(searchToken)
6465            )
6466          );
6467          const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10;
6468          const subMatchScore = subMatchingTokens.length / titleTokens.length;
6469          scores[scoreKey(result)] = exactMatchScore + subMatchScore;
6470        } else {
6471          scores[scoreKey(result)] = 0;
6472        }
6473      }
6474      return results.sort(
6475        (a, b) => scores[scoreKey(b)] - scores[scoreKey(a)]
6476      );
6477    }
6478    function tokenize(text) {
6479      return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
6480    }
6481  
6482    // packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs
6483    var import_api_fetch7 = __toESM(require_api_fetch(), 1);
6484    var import_url5 = __toESM(require_url(), 1);
6485    var CACHE = /* @__PURE__ */ new Map();
6486    var fetchUrlData = async (url, options = {}) => {
6487      const endpoint = "/wp-block-editor/v1/url-details";
6488      const args = {
6489        url: (0, import_url5.prependHTTP)(url)
6490      };
6491      if (!(0, import_url5.isURL)(url)) {
6492        return Promise.reject(`$url} is not a valid URL.`);
6493      }
6494      const protocol = (0, import_url5.getProtocol)(url);
6495      if (!protocol || !(0, import_url5.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) {
6496        return Promise.reject(
6497          `$url} does not have a valid protocol. URLs must be "http" based`
6498        );
6499      }
6500      if (CACHE.has(url)) {
6501        return CACHE.get(url);
6502      }
6503      return (0, import_api_fetch7.default)({
6504        path: (0, import_url5.addQueryArgs)(endpoint, args),
6505        ...options
6506      }).then((res) => {
6507        CACHE.set(url, res);
6508        return res;
6509      });
6510    };
6511    var experimental_fetch_url_data_default = fetchUrlData;
6512  
6513    // packages/core-data/build-module/fetch/index.mjs
6514    async function fetchBlockPatterns() {
6515      const restPatterns = await (0, import_api_fetch8.default)({
6516        path: "/wp/v2/block-patterns/patterns"
6517      });
6518      if (!restPatterns) {
6519        return [];
6520      }
6521      return restPatterns.map(
6522        (pattern) => Object.fromEntries(
6523          Object.entries(pattern).map(([key, value]) => [
6524            camelCase(key),
6525            value
6526          ])
6527        )
6528      );
6529    }
6530  
6531    // packages/core-data/build-module/parsed-blocks-cache.mjs
6532    var import_data10 = __toESM(require_data(), 1);
6533    var import_blocks5 = __toESM(require_blocks(), 1);
6534    var caches = /* @__PURE__ */ new WeakMap();
6535    function getCacheKey(kind, name, id) {
6536      return `$kind}:$name}:$id}`;
6537    }
6538    function getBlockTypes2() {
6539      return (0, import_data10.select)(import_blocks5.store).getBlockTypes();
6540    }
6541    function getCachedBlocks(kind, name, id, content) {
6542      const cached = caches.get(getBlockTypes2())?.get(getCacheKey(kind, name, id));
6543      if (cached && cached.content === content) {
6544        return cached.blocks;
6545      }
6546    }
6547    function setCachedBlocks(kind, name, id, content, blocks) {
6548      const blockTypes = getBlockTypes2();
6549      let cache3 = caches.get(blockTypes);
6550      if (!cache3) {
6551        cache3 = /* @__PURE__ */ new Map();
6552        caches.set(blockTypes, cache3);
6553      }
6554      cache3.set(getCacheKey(kind, name, id), { content, blocks });
6555    }
6556  
6557    // packages/core-data/build-module/resolvers.mjs
6558    var getAuthors2 = (query) => async ({ dispatch: dispatch3 }) => {
6559      const path = (0, import_url6.addQueryArgs)(
6560        "/wp/v2/users/?who=authors&per_page=100",
6561        query
6562      );
6563      const users2 = await (0, import_api_fetch9.default)({ path });
6564      dispatch3.receiveUserQuery(path, users2);
6565    };
6566    var getCurrentUser2 = () => async ({ dispatch: dispatch3 }) => {
6567      const currentUser2 = await (0, import_api_fetch9.default)({ path: "/wp/v2/users/me" });
6568      dispatch3.receiveCurrentUser(currentUser2);
6569    };
6570    var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select5, dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6571      const configs = await resolveSelect2.getEntitiesConfig(kind);
6572      const entityConfig = configs.find(
6573        (config) => config.name === name && config.kind === kind
6574      );
6575      if (!entityConfig) {
6576        return;
6577      }
6578      const lock2 = await dispatch3.__unstableAcquireStoreLock(
6579        STORE_NAME,
6580        ["entities", "records", kind, name, key],
6581        { exclusive: false }
6582      );
6583      try {
6584        if (query !== void 0 && query._fields) {
6585          query = {
6586            ...query,
6587            _fields: [
6588              .../* @__PURE__ */ new Set([
6589                ...get_normalized_comma_separable_default(query._fields) || [],
6590                entityConfig.key || DEFAULT_ENTITY_KEY
6591              ])
6592            ].join()
6593          };
6594        }
6595        if (query !== void 0 && query._fields) {
6596          const hasRecord = select5.hasEntityRecord(
6597            kind,
6598            name,
6599            key,
6600            query
6601          );
6602          if (hasRecord) {
6603            return;
6604          }
6605        }
6606        const { baseURL } = entityConfig;
6607        const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), {
6608          ...entityConfig.baseURLParams,
6609          ...query
6610        });
6611        const response = await (0, import_api_fetch9.default)({ path, parse: false });
6612        const record = await response.json();
6613        const permissions = getUserPermissionsFromAllowHeader(
6614          response.headers?.get("allow")
6615        );
6616        const receiveUserPermissionArgs = {};
6617        for (const action of ALLOWED_RESOURCE_ACTIONS) {
6618          receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6619            kind,
6620            name,
6621            id: key
6622          })] = permissions[action];
6623        }
6624        const canUserResolutionsArgs = [[{ kind, name, id: key }]];
6625        if (entityConfig.syncConfig && isNumericID(key) && !query) {
6626          const objectType = `$kind}/$name}`;
6627          const objectId = key;
6628          const recordWithTransients = { ...record };
6629          Object.entries(entityConfig.transientEdits ?? {}).filter(
6630            ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read
6631          ).forEach(([propName, transientConfig]) => {
6632            recordWithTransients[propName] = transientConfig.read(recordWithTransients);
6633          });
6634          if (recordWithTransients.blocks && typeof recordWithTransients.content?.raw === "string") {
6635            setCachedBlocks(
6636              kind,
6637              name,
6638              key,
6639              recordWithTransients.content.raw,
6640              recordWithTransients.blocks
6641            );
6642          }
6643          const syncManager2 = select5?.isCollaborationSupported?.() === false ? void 0 : getSyncManager();
6644          void syncManager2?.load(
6645            entityConfig.syncConfig,
6646            objectType,
6647            objectId,
6648            recordWithTransients,
6649            {
6650              // Handle edits sourced from the sync manager.
6651              editRecord: (edits, options = {}) => {
6652                if (!Object.keys(edits).length) {
6653                  return;
6654                }
6655                dispatch3({
6656                  type: "EDIT_ENTITY_RECORD",
6657                  kind,
6658                  name,
6659                  recordId: key,
6660                  edits,
6661                  meta: {
6662                    undo: void 0
6663                  },
6664                  options
6665                });
6666              },
6667              // Get the current entity record (with edits)
6668              getEditedRecord: async () => await resolveSelect2.getEditedEntityRecord(
6669                kind,
6670                name,
6671                key
6672              ),
6673              // Handle sync connection status changes.
6674              onStatusChange: (status) => {
6675                dispatch3.setSyncConnectionStatus(
6676                  kind,
6677                  name,
6678                  key,
6679                  status
6680                );
6681              },
6682              // Refetch the current entity record from the database.
6683              refetchRecord: async () => {
6684                dispatch3.receiveEntityRecords(
6685                  kind,
6686                  name,
6687                  await (0, import_api_fetch9.default)({ path, parse: true }),
6688                  query
6689                );
6690              },
6691              // Persist the CRDT document.
6692              //
6693              // TODO: Currently, persisted CRDT documents are stored in post meta.
6694              // This effectively means that only post entities support CRDT
6695              // persistence. As we add support for syncing additional entity,
6696              // we'll need to revisit where persisted CRDT documents are stored.
6697              persistCRDTDoc: () => {
6698                if (!entityConfig.syncConfig?.supportsPersistence) {
6699                  return;
6700                }
6701                return resolveSelect2.getEditedEntityRecord(kind, name, key).then(async (editedRecord) => {
6702                  const { meta, status } = editedRecord;
6703                  if ("auto-draft" === status || !meta) {
6704                    return;
6705                  }
6706                  const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
6707                  const entityId = editedRecord[entityIdKey];
6708                  await saveCRDTDoc(
6709                    `$kind}/$name}`,
6710                    entityId
6711                  );
6712                });
6713              },
6714              addUndoMeta: (ydoc, meta) => {
6715                const selectionHistory = getSelectionHistory(ydoc);
6716                if (selectionHistory) {
6717                  meta.set(
6718                    "selectionHistory",
6719                    selectionHistory
6720                  );
6721                }
6722              },
6723              onUndoStackChange: (undoState) => {
6724                dispatch3.__unstableNotifySyncUndoManagerChange(
6725                  undoState
6726                );
6727              },
6728              restoreUndoMeta: (ydoc, meta) => {
6729                const selectionHistory = meta.get("selectionHistory");
6730                if (selectionHistory) {
6731                  setTimeout(() => {
6732                    restoreSelection(selectionHistory, ydoc);
6733                  }, 0);
6734                }
6735              }
6736            }
6737          );
6738        }
6739        registry.batch(() => {
6740          dispatch3.receiveEntityRecords(kind, name, record, query);
6741          dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6742          dispatch3.finishResolutions("canUser", canUserResolutionsArgs);
6743        });
6744      } finally {
6745        dispatch3.__unstableReleaseStoreLock(lock2);
6746      }
6747    };
6748    getEntityRecord2.shouldInvalidate = (action, kind, name) => {
6749      return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of
6750      // knowing whether it's an update or fetch. Only an update would
6751      // have persistedEdits.
6752      action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template";
6753    };
6754    var getRawEntityRecord2 = forward_resolver_default("getEntityRecord");
6755    var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord");
6756    var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6757      const configs = await resolveSelect2.getEntitiesConfig(kind);
6758      const entityConfig = configs.find(
6759        (config) => config.name === name && config.kind === kind
6760      );
6761      if (!entityConfig) {
6762        return;
6763      }
6764      const lock2 = await dispatch3.__unstableAcquireStoreLock(
6765        STORE_NAME,
6766        ["entities", "records", kind, name],
6767        { exclusive: false }
6768      );
6769      const rawQuery = { ...query };
6770      const key = entityConfig.key || DEFAULT_ENTITY_KEY;
6771      function getResolutionsArgs(records, recordsQuery) {
6772        const normalizedQuery = normalizeQueryForResolution(recordsQuery);
6773        return records.filter((record) => record?.[key]).map((record) => [
6774          kind,
6775          name,
6776          record[key],
6777          normalizedQuery
6778        ]);
6779      }
6780      try {
6781        if (query._fields) {
6782          query = {
6783            ...query,
6784            _fields: [
6785              .../* @__PURE__ */ new Set([
6786                ...get_normalized_comma_separable_default(query._fields) || [],
6787                key
6788              ])
6789            ].join()
6790          };
6791        }
6792        const { baseURL } = entityConfig;
6793        const path = (0, import_url6.addQueryArgs)(baseURL, {
6794          ...entityConfig.baseURLParams,
6795          ...query
6796        });
6797        let records = [], meta;
6798        if (entityConfig.supportsPagination && query.per_page !== -1) {
6799          const response = await (0, import_api_fetch9.default)({ path, parse: false });
6800          records = Object.values(await response.json());
6801          meta = getPaginationMeta(response.headers);
6802        } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) {
6803          let page = 1;
6804          let totalPages;
6805          do {
6806            const response = await (0, import_api_fetch9.default)({
6807              path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }),
6808              parse: false
6809            });
6810            const pageRecords = Object.values(await response.json());
6811            const pageMeta = getPaginationMeta(response.headers);
6812            totalPages = pageMeta.totalPages ?? 1;
6813            if (!meta) {
6814              meta = {
6815                totalItems: pageMeta.totalItems,
6816                totalPages: 1
6817              };
6818            }
6819            records.push(...pageRecords);
6820            registry.batch(() => {
6821              dispatch3.receiveEntityRecords(
6822                kind,
6823                name,
6824                records,
6825                query,
6826                false,
6827                void 0,
6828                meta
6829              );
6830              dispatch3.finishResolutions(
6831                "getEntityRecord",
6832                getResolutionsArgs(pageRecords, rawQuery)
6833              );
6834            });
6835            page++;
6836          } while (page <= totalPages);
6837        } else {
6838          records = Object.values(await (0, import_api_fetch9.default)({ path }));
6839          meta = {
6840            totalItems: records.length,
6841            totalPages: 1
6842          };
6843        }
6844        if (entityConfig.syncConfig && -1 === query.per_page) {
6845          const objectType = `$kind}/$name}`;
6846          getSyncManager()?.loadCollection(
6847            entityConfig.syncConfig,
6848            objectType,
6849            {
6850              onStatusChange: (status) => {
6851                dispatch3.setSyncConnectionStatus(
6852                  kind,
6853                  name,
6854                  null,
6855                  status
6856                );
6857              },
6858              refetchRecords: async () => {
6859                dispatch3.receiveEntityRecords(
6860                  kind,
6861                  name,
6862                  await (0, import_api_fetch9.default)({ path, parse: true }),
6863                  query
6864                );
6865              }
6866            }
6867          );
6868        }
6869        if (query._fields) {
6870          records = records.map((record) => {
6871            query._fields.split(",").forEach((field) => {
6872              if (!record.hasOwnProperty(field)) {
6873                record[field] = void 0;
6874              }
6875            });
6876            return record;
6877          });
6878        }
6879        registry.batch(() => {
6880          dispatch3.receiveEntityRecords(
6881            kind,
6882            name,
6883            records,
6884            query,
6885            false,
6886            void 0,
6887            meta
6888          );
6889          const targetHints = records.filter(
6890            (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow
6891          ).map((record) => ({
6892            id: record[key],
6893            permissions: getUserPermissionsFromAllowHeader(
6894              record._links.self[0].targetHints.allow
6895            )
6896          }));
6897          const canUserResolutionsArgs = [];
6898          const receiveUserPermissionArgs = {};
6899          for (const targetHint of targetHints) {
6900            canUserResolutionsArgs.push([
6901              { kind, name, id: targetHint.id }
6902            ]);
6903            for (const action of ALLOWED_RESOURCE_ACTIONS) {
6904              receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6905                kind,
6906                name,
6907                id: targetHint.id
6908              })] = targetHint.permissions[action];
6909            }
6910          }
6911          if (targetHints.length > 0) {
6912            dispatch3.receiveUserPermissions(
6913              receiveUserPermissionArgs
6914            );
6915            dispatch3.finishResolutions(
6916              "canUser",
6917              canUserResolutionsArgs
6918            );
6919          }
6920          dispatch3.finishResolutions(
6921            "getEntityRecord",
6922            getResolutionsArgs(records, rawQuery)
6923          );
6924          dispatch3.__unstableReleaseStoreLock(lock2);
6925        });
6926      } catch {
6927        dispatch3.__unstableReleaseStoreLock(lock2);
6928      }
6929    };
6930    getEntityRecords2.shouldInvalidate = (action, kind, name) => {
6931      return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name;
6932    };
6933    var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords");
6934    var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords");
6935    var getCurrentTheme2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6936      const activeThemes = await resolveSelect2.getEntityRecords(
6937        "root",
6938        "theme",
6939        { status: "active" }
6940      );
6941      dispatch3.receiveCurrentTheme(activeThemes[0]);
6942    };
6943    var getThemeSupports2 = forward_resolver_default("getCurrentTheme");
6944    var getEmbedPreview2 = (url) => async ({ dispatch: dispatch3 }) => {
6945      try {
6946        const embedProxyResponse = await (0, import_api_fetch9.default)({
6947          path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url })
6948        });
6949        dispatch3.receiveEmbedPreview(url, embedProxyResponse);
6950      } catch {
6951        dispatch3.receiveEmbedPreview(url, false);
6952      }
6953    };
6954    var canUser2 = (resource, id) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6955      let resourcePath = null;
6956      if (typeof resource === "object") {
6957        if (!resource.kind || !resource.name) {
6958          throw new Error("The entity resource object is not valid.");
6959        }
6960        const configs = await resolveSelect2.getEntitiesConfig(
6961          resource.kind
6962        );
6963        const entityConfig = configs.find(
6964          (config) => config.name === resource.name && config.kind === resource.kind
6965        );
6966        if (!entityConfig) {
6967          return;
6968        }
6969        resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : "");
6970      } else {
6971        resourcePath = `/wp/v2/$resource}` + (id ? "/" + id : "");
6972      }
6973      let response;
6974      try {
6975        response = await (0, import_api_fetch9.default)({
6976          path: resourcePath,
6977          method: "OPTIONS",
6978          parse: false
6979        });
6980      } catch {
6981        return;
6982      }
6983      const permissions = getUserPermissionsFromAllowHeader(
6984        response.headers?.get("allow")
6985      );
6986      const receiveUserPermissionArgs = {};
6987      for (const action of ALLOWED_RESOURCE_ACTIONS) {
6988        receiveUserPermissionArgs[getUserPermissionCacheKey(action, resource, id)] = permissions[action];
6989      }
6990      dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6991    };
6992    canUser2.getResolutionArgs = (action, resource, id) => [resource, id];
6993    var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ resolveSelect: resolveSelect2 }) => {
6994      await resolveSelect2.canUser("update", { kind, name, id: recordId });
6995    };
6996    var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6997      const {
6998        rest_base: restBase,
6999        rest_namespace: restNamespace = "wp/v2",
7000        supports
7001      } = await resolveSelect2.getPostType(postType);
7002      if (!supports?.autosave) {
7003        return;
7004      }
7005      const autosaves2 = await (0, import_api_fetch9.default)({
7006        path: `/$restNamespace}/$restBase}/$postId}/autosaves?context=edit`
7007      });
7008      if (autosaves2 && autosaves2.length) {
7009        dispatch3.receiveAutosaves(postId, autosaves2);
7010      }
7011    };
7012    var getAutosave2 = (postType, postId) => async ({ resolveSelect: resolveSelect2 }) => {
7013      await resolveSelect2.getAutosaves(postType, postId);
7014    };
7015    var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
7016      const activeThemes = await resolveSelect2.getEntityRecords(
7017        "root",
7018        "theme",
7019        { status: "active" }
7020      );
7021      const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href;
7022      if (!globalStylesURL) {
7023        return;
7024      }
7025      const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/);
7026      const id = matches ? Number(matches[1]) : null;
7027      if (id) {
7028        dispatch3.__experimentalReceiveCurrentGlobalStylesId(id);
7029      }
7030    };
7031    var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
7032      const currentTheme2 = await resolveSelect2.getCurrentTheme();
7033      const themeGlobalStyles = await (0, import_api_fetch9.default)({
7034        path: `/wp/v2/global-styles/themes/$currentTheme2.stylesheet}?context=view`
7035      });
7036      dispatch3.__experimentalReceiveThemeBaseGlobalStyles(
7037        currentTheme2.stylesheet,
7038        themeGlobalStyles
7039      );
7040    };
7041    var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
7042      const currentTheme2 = await resolveSelect2.getCurrentTheme();
7043      const variations = await (0, import_api_fetch9.default)({
7044        path: `/wp/v2/global-styles/themes/$currentTheme2.stylesheet}/variations?context=view`
7045      });
7046      dispatch3.__experimentalReceiveThemeGlobalStyleVariations(
7047        currentTheme2.stylesheet,
7048        variations
7049      );
7050    };
7051    var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
7052      const globalStylesId = await resolveSelect2.__experimentalGetCurrentGlobalStylesId();
7053      const record = globalStylesId ? await resolveSelect2.getEntityRecord(
7054        "root",
7055        "globalStyles",
7056        globalStylesId
7057      ) : void 0;
7058      const revisionsURL = record?._links?.["version-history"]?.[0]?.href;
7059      if (revisionsURL) {
7060        const resetRevisions = await (0, import_api_fetch9.default)({
7061          url: revisionsURL
7062        });
7063        const revisions = resetRevisions?.map(
7064          (revision) => Object.fromEntries(
7065            Object.entries(revision).map(([key, value]) => [
7066              camelCase(key),
7067              value
7068            ])
7069          )
7070        );
7071        dispatch3.receiveThemeGlobalStyleRevisions(
7072          globalStylesId,
7073          revisions
7074        );
7075      }
7076    };
7077    getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => {
7078      return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles";
7079    };
7080    var getBlockPatterns2 = () => async ({ dispatch: dispatch3 }) => {
7081      const patterns = await fetchBlockPatterns();
7082      dispatch3({ type: "RECEIVE_BLOCK_PATTERNS", patterns });
7083    };
7084    var getBlockPatternCategories2 = () => async ({ dispatch: dispatch3 }) => {
7085      const categories = await (0, import_api_fetch9.default)({
7086        path: "/wp/v2/block-patterns/categories"
7087      });
7088      dispatch3({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories });
7089    };
7090    var getUserPatternCategories2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
7091      const patternCategories = await resolveSelect2.getEntityRecords(
7092        "taxonomy",
7093        "wp_pattern_category",
7094        {
7095          per_page: -1,
7096          _fields: "id,name,description,slug",
7097          context: "view"
7098        }
7099      );
7100      const mappedPatternCategories = patternCategories?.map((userCategory) => ({
7101        ...userCategory,
7102        label: (0, import_html_entities3.decodeEntities)(userCategory.name),
7103        name: userCategory.slug
7104      })) || [];
7105      dispatch3({
7106        type: "RECEIVE_USER_PATTERN_CATEGORIES",
7107        patternCategories: mappedPatternCategories
7108      });
7109    };
7110    var getNavigationFallbackId2 = () => async ({ dispatch: dispatch3, select: select5, registry }) => {
7111      const fallback = await (0, import_api_fetch9.default)({
7112        path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", {
7113          _embed: true
7114        })
7115      });
7116      const record = fallback?._embedded?.self;
7117      registry.batch(() => {
7118        dispatch3.receiveNavigationFallbackId(fallback?.id);
7119        if (!record) {
7120          return;
7121        }
7122        const existingFallbackEntityRecord = select5.getEntityRecord(
7123          "postType",
7124          "wp_navigation",
7125          fallback.id
7126        );
7127        const invalidateNavigationQueries = !existingFallbackEntityRecord;
7128        dispatch3.receiveEntityRecords(
7129          "postType",
7130          "wp_navigation",
7131          record,
7132          void 0,
7133          invalidateNavigationQueries
7134        );
7135        dispatch3.finishResolution("getEntityRecord", [
7136          "postType",
7137          "wp_navigation",
7138          fallback.id
7139        ]);
7140      });
7141    };
7142    var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
7143      const template = await (0, import_api_fetch9.default)({
7144        path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query)
7145      });
7146      await resolveSelect2.getEntitiesConfig("postType");
7147      const id = template?.id;
7148      registry.batch(() => {
7149        dispatch3.receiveDefaultTemplateId(query, id || "");
7150        if (id) {
7151          template.id = id;
7152          dispatch3.receiveEntityRecords(
7153            "postType",
7154            template.type,
7155            template
7156          );
7157          dispatch3.finishResolution("getEntityRecord", [
7158            "postType",
7159            template.type,
7160            id
7161          ]);
7162        }
7163      });
7164    };
7165    var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
7166      const configs = await resolveSelect2.getEntitiesConfig(kind);
7167      const entityConfig = configs.find(
7168        (config) => config.name === name && config.kind === kind
7169      );
7170      if (!entityConfig) {
7171        return;
7172      }
7173      const rawQuery = { ...query };
7174      const lock2 = await dispatch3.__unstableAcquireStoreLock(
7175        STORE_NAME,
7176        ["entities", "records", kind, name, recordKey, "revisions"],
7177        { exclusive: false }
7178      );
7179      try {
7180        if (query._fields) {
7181          query = {
7182            ...query,
7183            _fields: [
7184              .../* @__PURE__ */ new Set([
7185                ...get_normalized_comma_separable_default(query._fields) || [],
7186                entityConfig.revisionKey || DEFAULT_ENTITY_KEY
7187              ])
7188            ].join()
7189          };
7190        }
7191        const path = (0, import_url6.addQueryArgs)(
7192          entityConfig.getRevisionsUrl(recordKey),
7193          query
7194        );
7195        let records, response;
7196        const meta = {};
7197        const isPaginated = entityConfig.supportsPagination && query.per_page !== -1;
7198        try {
7199          response = await (0, import_api_fetch9.default)({ path, parse: !isPaginated });
7200        } catch {
7201          return;
7202        }
7203        if (response) {
7204          if (isPaginated) {
7205            records = Object.values(await response.json());
7206            meta.totalItems = getPaginationMeta(
7207              response.headers
7208            ).totalItems;
7209          } else {
7210            records = Object.values(response);
7211          }
7212          if (query._fields) {
7213            records = records.map((record) => {
7214              query._fields.split(",").forEach((field) => {
7215                if (!record.hasOwnProperty(field)) {
7216                  record[field] = void 0;
7217                }
7218              });
7219              return record;
7220            });
7221          }
7222          await dispatch3.receiveRevisions(
7223            kind,
7224            name,
7225            recordKey,
7226            records,
7227            query,
7228            false,
7229            meta
7230          );
7231          const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY;
7232          const normalizedQuery = normalizeQueryForResolution(rawQuery);
7233          const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
7234            kind,
7235            name,
7236            recordKey,
7237            record[key],
7238            normalizedQuery
7239          ]);
7240          dispatch3.finishResolutions("getRevision", resolutionsArgs);
7241        }
7242      } finally {
7243        dispatch3.__unstableReleaseStoreLock(lock2);
7244      }
7245    };
7246    getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId;
7247    var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ select: select5, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
7248      const configs = await resolveSelect2.getEntitiesConfig(kind);
7249      const entityConfig = configs.find(
7250        (config) => config.name === name && config.kind === kind
7251      );
7252      if (!entityConfig) {
7253        return;
7254      }
7255      if (query !== void 0 && query._fields) {
7256        query = {
7257          ...query,
7258          _fields: [
7259            .../* @__PURE__ */ new Set([
7260              ...get_normalized_comma_separable_default(query._fields) || [],
7261              entityConfig.revisionKey || DEFAULT_ENTITY_KEY
7262            ])
7263          ].join()
7264        };
7265      }
7266      const lock2 = await dispatch3.__unstableAcquireStoreLock(
7267        STORE_NAME,
7268        [
7269          "entities",
7270          "records",
7271          kind,
7272          name,
7273          recordKey,
7274          "revisions",
7275          revisionKey
7276        ],
7277        { exclusive: false }
7278      );
7279      try {
7280        if (select5.hasRevision(kind, name, recordKey, revisionKey, query)) {
7281          return;
7282        }
7283        const path = (0, import_url6.addQueryArgs)(
7284          entityConfig.getRevisionsUrl(recordKey, revisionKey),
7285          query
7286        );
7287        let record;
7288        try {
7289          record = await (0, import_api_fetch9.default)({ path });
7290        } catch {
7291          return;
7292        }
7293        if (record) {
7294          await dispatch3.receiveRevisions(
7295            kind,
7296            name,
7297            recordKey,
7298            record,
7299            query
7300          );
7301        }
7302      } finally {
7303        dispatch3.__unstableReleaseStoreLock(lock2);
7304      }
7305    };
7306    var getRegisteredPostMeta2 = (postType) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
7307      let options;
7308      try {
7309        const {
7310          rest_namespace: restNamespace = "wp/v2",
7311          rest_base: restBase
7312        } = await resolveSelect2.getPostType(postType) || {};
7313        options = await (0, import_api_fetch9.default)({
7314          path: `$restNamespace}/$restBase}/?context=edit`,
7315          method: "OPTIONS"
7316        });
7317      } catch {
7318        return;
7319      }
7320      if (options) {
7321        dispatch3.receiveRegisteredPostMeta(
7322          postType,
7323          options?.schema?.properties?.meta?.properties
7324        );
7325      }
7326    };
7327    var getEntitiesConfig2 = (kind) => async ({ dispatch: dispatch3 }) => {
7328      const loader = additionalEntityConfigLoaders.find(
7329        (l) => l.kind === kind
7330      );
7331      if (!loader) {
7332        return;
7333      }
7334      try {
7335        const configs = await loader.loadEntities();
7336        if (!configs.length) {
7337          return;
7338        }
7339        dispatch3.addEntities(configs);
7340      } catch {
7341      }
7342    };
7343    var getEditorSettings2 = () => async ({ dispatch: dispatch3 }) => {
7344      const settings = await (0, import_api_fetch9.default)({
7345        path: "/wp-block-editor/v1/settings"
7346      });
7347      dispatch3.receiveEditorSettings(settings);
7348    };
7349    var getEditorAssets2 = () => async ({ dispatch: dispatch3 }) => {
7350      const assets = await (0, import_api_fetch9.default)({
7351        path: "/wp-block-editor/v1/assets"
7352      });
7353      dispatch3.receiveEditorAssets(assets);
7354    };
7355    var getViewConfig2 = (kind, name, options = {}) => async ({ dispatch: dispatch3 }) => {
7356      const query = { kind, name };
7357      const fields = get_normalized_comma_separable_default(options.fields);
7358      if (fields?.length) {
7359        query._fields = fields.join(",");
7360      }
7361      const config = await (0, import_api_fetch9.default)({
7362        path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", query)
7363      });
7364      dispatch3.receiveViewConfig(kind, name, config);
7365    };
7366  
7367    // packages/core-data/build-module/locks/utils.mjs
7368    function deepCopyLocksTreePath(tree, path) {
7369      const newTree = { ...tree };
7370      let currentNode = newTree;
7371      for (const branchName of path) {
7372        currentNode.children = {
7373          ...currentNode.children,
7374          [branchName]: {
7375            locks: [],
7376            children: {},
7377            ...currentNode.children[branchName]
7378          }
7379        };
7380        currentNode = currentNode.children[branchName];
7381      }
7382      return newTree;
7383    }
7384    function getNode(tree, path) {
7385      let currentNode = tree;
7386      for (const branchName of path) {
7387        const nextNode = currentNode.children[branchName];
7388        if (!nextNode) {
7389          return null;
7390        }
7391        currentNode = nextNode;
7392      }
7393      return currentNode;
7394    }
7395    function* iteratePath(tree, path) {
7396      let currentNode = tree;
7397      yield currentNode;
7398      for (const branchName of path) {
7399        const nextNode = currentNode.children[branchName];
7400        if (!nextNode) {
7401          break;
7402        }
7403        yield nextNode;
7404        currentNode = nextNode;
7405      }
7406    }
7407    function* iterateDescendants(node) {
7408      const stack = Object.values(node.children);
7409      while (stack.length) {
7410        const childNode = stack.pop();
7411        yield childNode;
7412        stack.push(...Object.values(childNode.children));
7413      }
7414    }
7415    function hasConflictingLock({ exclusive }, locks2) {
7416      if (exclusive && locks2.length) {
7417        return true;
7418      }
7419      if (!exclusive && locks2.filter((lock2) => lock2.exclusive).length) {
7420        return true;
7421      }
7422      return false;
7423    }
7424  
7425    // packages/core-data/build-module/locks/reducer.mjs
7426    var DEFAULT_STATE = {
7427      requests: [],
7428      tree: {
7429        locks: [],
7430        children: {}
7431      }
7432    };
7433    function locks(state = DEFAULT_STATE, action) {
7434      switch (action.type) {
7435        case "ENQUEUE_LOCK_REQUEST": {
7436          const { request } = action;
7437          return {
7438            ...state,
7439            requests: [request, ...state.requests]
7440          };
7441        }
7442        case "GRANT_LOCK_REQUEST": {
7443          const { lock: lock2, request } = action;
7444          const { store: store2, path } = request;
7445          const storePath = [store2, ...path];
7446          const newTree = deepCopyLocksTreePath(state.tree, storePath);
7447          const node = getNode(newTree, storePath);
7448          node.locks = [...node.locks, lock2];
7449          return {
7450            ...state,
7451            requests: state.requests.filter((r2) => r2 !== request),
7452            tree: newTree
7453          };
7454        }
7455        case "RELEASE_LOCK": {
7456          const { lock: lock2 } = action;
7457          const storePath = [lock2.store, ...lock2.path];
7458          const newTree = deepCopyLocksTreePath(state.tree, storePath);
7459          const node = getNode(newTree, storePath);
7460          node.locks = node.locks.filter((l) => l !== lock2);
7461          return {
7462            ...state,
7463            tree: newTree
7464          };
7465        }
7466      }
7467      return state;
7468    }
7469  
7470    // packages/core-data/build-module/locks/selectors.mjs
7471    function getPendingLockRequests(state) {
7472      return state.requests;
7473    }
7474    function isLockAvailable(state, store2, path, { exclusive }) {
7475      const storePath = [store2, ...path];
7476      const locks2 = state.tree;
7477      for (const node2 of iteratePath(locks2, storePath)) {
7478        if (hasConflictingLock({ exclusive }, node2.locks)) {
7479          return false;
7480        }
7481      }
7482      const node = getNode(locks2, storePath);
7483      if (!node) {
7484        return true;
7485      }
7486      for (const descendant of iterateDescendants(node)) {
7487        if (hasConflictingLock({ exclusive }, descendant.locks)) {
7488          return false;
7489        }
7490      }
7491      return true;
7492    }
7493  
7494    // packages/core-data/build-module/locks/engine.mjs
7495    function createLocks() {
7496      let state = locks(void 0, { type: "@@INIT" });
7497      function processPendingLockRequests() {
7498        for (const request of getPendingLockRequests(state)) {
7499          const { store: store2, path, exclusive, notifyAcquired } = request;
7500          if (isLockAvailable(state, store2, path, { exclusive })) {
7501            const lock2 = { store: store2, path, exclusive };
7502            state = locks(state, {
7503              type: "GRANT_LOCK_REQUEST",
7504              lock: lock2,
7505              request
7506            });
7507            notifyAcquired(lock2);
7508          }
7509        }
7510      }
7511      function acquire(store2, path, exclusive) {
7512        return new Promise((resolve) => {
7513          state = locks(state, {
7514            type: "ENQUEUE_LOCK_REQUEST",
7515            request: { store: store2, path, exclusive, notifyAcquired: resolve }
7516          });
7517          processPendingLockRequests();
7518        });
7519      }
7520      function release(lock2) {
7521        state = locks(state, {
7522          type: "RELEASE_LOCK",
7523          lock: lock2
7524        });
7525        processPendingLockRequests();
7526      }
7527      return { acquire, release };
7528    }
7529  
7530    // packages/core-data/build-module/locks/actions.mjs
7531    function createLocksActions() {
7532      const locks2 = createLocks();
7533      function __unstableAcquireStoreLock(store2, path, { exclusive }) {
7534        return () => locks2.acquire(store2, path, exclusive);
7535      }
7536      function __unstableReleaseStoreLock(lock2) {
7537        return () => locks2.release(lock2);
7538      }
7539      return { __unstableAcquireStoreLock, __unstableReleaseStoreLock };
7540    }
7541  
7542    // packages/core-data/build-module/dynamic-entities.mjs
7543    var dynamicActions;
7544    var dynamicSelectors;
7545  
7546    // packages/core-data/build-module/entity-provider.mjs
7547    var import_element2 = __toESM(require_element(), 1);
7548  
7549    // packages/core-data/build-module/entity-context.mjs
7550    var import_element = __toESM(require_element(), 1);
7551    var EntityContext = (0, import_element.createContext)({});
7552    EntityContext.displayName = "EntityContext";
7553  
7554    // packages/core-data/build-module/entity-provider.mjs
7555    var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
7556    function EntityProvider({
7557      kind,
7558      type: name,
7559      id,
7560      revisionId,
7561      children
7562    }) {
7563      const parent = (0, import_element2.useContext)(EntityContext);
7564      const childContext = (0, import_element2.useMemo)(
7565        () => ({
7566          ...parent,
7567          ...kind && {
7568            [kind]: {
7569              ...parent?.[kind],
7570              [name]: id
7571            }
7572          },
7573          ...revisionId !== void 0 && kind && {
7574            revision: {
7575              ...parent?.revision,
7576              [kind]: {
7577                ...parent?.revision?.[kind],
7578                [name]: revisionId
7579              }
7580            }
7581          }
7582        }),
7583        [parent, kind, name, id, revisionId]
7584      );
7585      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children });
7586    }
7587  
7588    // packages/core-data/build-module/hooks/use-entity-record.mjs
7589    var import_data11 = __toESM(require_data(), 1);
7590    var import_deprecated4 = __toESM(require_deprecated(), 1);
7591    var import_element3 = __toESM(require_element(), 1);
7592  
7593    // packages/core-data/build-module/hooks/constants.mjs
7594    var Status = /* @__PURE__ */ ((Status2) => {
7595      Status2["Idle"] = "IDLE";
7596      Status2["Resolving"] = "RESOLVING";
7597      Status2["Error"] = "ERROR";
7598      Status2["Success"] = "SUCCESS";
7599      return Status2;
7600    })(Status || {});
7601  
7602    // packages/core-data/build-module/hooks/utils.mjs
7603    function getResolutionStatus(resolutionStatus) {
7604      let status;
7605      switch (resolutionStatus) {
7606        case "resolving":
7607          status = Status.Resolving;
7608          break;
7609        case "finished":
7610          status = Status.Success;
7611          break;
7612        case "error":
7613          status = Status.Error;
7614          break;
7615        default:
7616          status = Status.Idle;
7617      }
7618      return {
7619        status,
7620        isResolving: status === Status.Resolving,
7621        hasStarted: status !== Status.Idle,
7622        hasResolved: status === Status.Success || status === Status.Error
7623      };
7624    }
7625  
7626    // packages/core-data/build-module/hooks/use-entity-record.mjs
7627    var EMPTY_OBJECT3 = {};
7628    function useEntityRecord(kind, name, recordId, options = { enabled: true }) {
7629      const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data11.useDispatch)(store);
7630      const mutations = (0, import_element3.useMemo)(
7631        () => ({
7632          edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions),
7633          save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, {
7634            throwOnError: true,
7635            ...saveOptions
7636          })
7637        }),
7638        [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2]
7639      );
7640      const { record, editedRecord, hasEdits, edits, ...resolution } = (0, import_data11.useSelect)(
7641        (select5) => {
7642          if (!options.enabled) {
7643            return {
7644              record: null,
7645              editedRecord: EMPTY_OBJECT3,
7646              hasEdits: false,
7647              edits: EMPTY_OBJECT3,
7648              ...getResolutionStatus()
7649            };
7650          }
7651          const storeSelectors = select5(store);
7652          const resolutionStatus = storeSelectors.getResolutionState(
7653            "getEntityRecord",
7654            [kind, name, recordId]
7655          )?.status;
7656          return {
7657            record: storeSelectors.getEntityRecord(
7658              kind,
7659              name,
7660              recordId
7661            ) ?? null,
7662            editedRecord: storeSelectors.getEditedEntityRecord(
7663              kind,
7664              name,
7665              recordId
7666            ),
7667            hasEdits: storeSelectors.hasEditsForEntityRecord(
7668              kind,
7669              name,
7670              recordId
7671            ),
7672            edits: storeSelectors.getEntityRecordNonTransientEdits(
7673              kind,
7674              name,
7675              recordId
7676            ),
7677            ...getResolutionStatus(resolutionStatus)
7678          };
7679        },
7680        [kind, name, recordId, options.enabled]
7681      );
7682      return {
7683        record,
7684        editedRecord,
7685        hasEdits,
7686        edits,
7687        ...resolution,
7688        ...mutations
7689      };
7690    }
7691    function useDeprecatedEntityRecord(kind, name, recordId, options) {
7692      (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, {
7693        alternative: "wp.data.useEntityRecord",
7694        since: "6.1"
7695      });
7696      return useEntityRecord(kind, name, recordId, options);
7697    }
7698  
7699    // packages/core-data/build-module/hooks/use-entity-records.mjs
7700    var import_url7 = __toESM(require_url(), 1);
7701    var import_deprecated5 = __toESM(require_deprecated(), 1);
7702    var import_data12 = __toESM(require_data(), 1);
7703    var import_element4 = __toESM(require_element(), 1);
7704    var EMPTY_ARRAY = [];
7705    function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) {
7706      const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs);
7707      const { records, totalItems, totalPages, ...rest } = (0, import_data12.useSelect)(
7708        (select5) => {
7709          if (!options.enabled) {
7710            return {
7711              // Avoiding returning a new reference on every execution.
7712              records: EMPTY_ARRAY,
7713              totalItems: null,
7714              totalPages: null,
7715              ...getResolutionStatus()
7716            };
7717          }
7718          const storeSelectors = select5(store);
7719          const resolutionStatus = storeSelectors.getResolutionState(
7720            "getEntityRecords",
7721            [kind, name, queryArgs]
7722          )?.status;
7723          return {
7724            records: storeSelectors.getEntityRecords(
7725              kind,
7726              name,
7727              queryArgs
7728            ),
7729            totalItems: storeSelectors.getEntityRecordsTotalItems(
7730              kind,
7731              name,
7732              queryArgs
7733            ),
7734            totalPages: storeSelectors.getEntityRecordsTotalPages(
7735              kind,
7736              name,
7737              queryArgs
7738            ),
7739            ...getResolutionStatus(resolutionStatus)
7740          };
7741        },
7742        [kind, name, queryAsString, options.enabled]
7743      );
7744      return {
7745        records,
7746        totalItems,
7747        totalPages,
7748        ...rest
7749      };
7750    }
7751    function useDeprecatedEntityRecords(kind, name, queryArgs, options) {
7752      (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, {
7753        alternative: "wp.data.useEntityRecords",
7754        since: "6.1"
7755      });
7756      return useEntityRecords(kind, name, queryArgs, options);
7757    }
7758    function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) {
7759      const entityConfig = (0, import_data12.useSelect)(
7760        (select5) => select5(store).getEntityConfig(kind, name),
7761        [kind, name]
7762      );
7763      const { records: data, ...ret } = useEntityRecords(
7764        kind,
7765        name,
7766        {
7767          ...queryArgs,
7768          // If _fields is provided, we need to include _links in the request for permission caching to work.
7769          ...queryArgs._fields ? {
7770            _fields: [
7771              .../* @__PURE__ */ new Set([
7772                ...get_normalized_comma_separable_default(
7773                  queryArgs._fields
7774                ) || [],
7775                "_links"
7776              ])
7777            ].join()
7778          } : {}
7779        },
7780        options
7781      );
7782      const ids = (0, import_element4.useMemo)(
7783        () => data?.map(
7784          // @ts-expect-error `data` is `unknown[]`, so the callback signature does not line up.
7785          (record) => record[entityConfig?.key ?? "id"]
7786        ) ?? [],
7787        [data, entityConfig?.key]
7788      );
7789      const permissions = (0, import_data12.useSelect)(
7790        (select5) => {
7791          const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock(
7792            select5(store)
7793          );
7794          return getEntityRecordsPermissions2(kind, name, ids);
7795        },
7796        [ids, kind, name]
7797      );
7798      const dataWithPermissions = (0, import_element4.useMemo)(
7799        () => data?.map((record, index) => ({
7800          // @ts-expect-error `record` is `unknown`, which cannot be spread.
7801          ...record,
7802          permissions: permissions[index]
7803        })) ?? [],
7804        [data, permissions]
7805      );
7806      return { records: dataWithPermissions, ...ret };
7807    }
7808  
7809    // packages/core-data/build-module/hooks/use-resource-permissions.mjs
7810    var import_deprecated6 = __toESM(require_deprecated(), 1);
7811    var import_warning = __toESM(require_warning(), 1);
7812  
7813    // packages/core-data/build-module/hooks/use-query-select.mjs
7814    var import_data13 = __toESM(require_data(), 1);
7815  
7816    // node_modules/memize/dist/index.js
7817    function memize(fn, options) {
7818      var size = 0;
7819      var head;
7820      var tail;
7821      options = options || {};
7822      function memoized() {
7823        var node = head, len = arguments.length, args, i;
7824        searchCache: while (node) {
7825          if (node.args.length !== arguments.length) {
7826            node = node.next;
7827            continue;
7828          }
7829          for (i = 0; i < len; i++) {
7830            if (node.args[i] !== arguments[i]) {
7831              node = node.next;
7832              continue searchCache;
7833            }
7834          }
7835          if (node !== head) {
7836            if (node === tail) {
7837              tail = node.prev;
7838            }
7839            node.prev.next = node.next;
7840            if (node.next) {
7841              node.next.prev = node.prev;
7842            }
7843            node.next = head;
7844            node.prev = null;
7845            head.prev = node;
7846            head = node;
7847          }
7848          return node.val;
7849        }
7850        args = new Array(len);
7851        for (i = 0; i < len; i++) {
7852          args[i] = arguments[i];
7853        }
7854        node = {
7855          args,
7856          // Generate the result from original function
7857          val: fn.apply(null, args)
7858        };
7859        if (head) {
7860          head.prev = node;
7861          node.next = head;
7862        } else {
7863          tail = node;
7864        }
7865        if (size === /** @type {MemizeOptions} */
7866        options.maxSize) {
7867          tail = /** @type {MemizeCacheNode} */
7868          tail.prev;
7869          tail.next = null;
7870        } else {
7871          size++;
7872        }
7873        head = node;
7874        return node.val;
7875      }
7876      memoized.clear = function() {
7877        head = null;
7878        tail = null;
7879        size = 0;
7880      };
7881      return memoized;
7882    }
7883  
7884    // packages/core-data/build-module/hooks/use-query-select.mjs
7885    var META_SELECTORS = [
7886      "getIsResolving",
7887      "hasStartedResolution",
7888      "hasFinishedResolution",
7889      "isResolving",
7890      "getCachedResolvers"
7891    ];
7892    function useQuerySelect(mapQuerySelect, deps) {
7893      return (0, import_data13.useSelect)((select5, registry) => {
7894        const resolve = (store2) => enrichSelectors(select5(store2));
7895        return mapQuerySelect(resolve, registry);
7896      }, deps);
7897    }
7898    var enrichSelectors = memize(((selectors) => {
7899      const resolvers = {};
7900      for (const selectorName in selectors) {
7901        if (META_SELECTORS.includes(selectorName)) {
7902          continue;
7903        }
7904        Object.defineProperty(resolvers, selectorName, {
7905          get: () => (...args) => {
7906            const data = selectors[selectorName](...args);
7907            const resolutionStatus = selectors.getResolutionState(
7908              selectorName,
7909              args
7910            )?.status;
7911            return {
7912              data,
7913              ...getResolutionStatus(resolutionStatus)
7914            };
7915          }
7916        });
7917      }
7918      return resolvers;
7919    }));
7920  
7921    // packages/core-data/build-module/hooks/use-resource-permissions.mjs
7922    function useResourcePermissions(resource, id) {
7923      const isEntity = typeof resource === "object";
7924      const resourceAsString = isEntity ? JSON.stringify(resource) : resource;
7925      if (isEntity && typeof id !== "undefined") {
7926        (0, import_warning.default)(
7927          `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.`
7928        );
7929      }
7930      return useQuerySelect(
7931        (resolve) => {
7932          const hasId = isEntity ? !!resource.id : !!id;
7933          const { canUser: canUser3 } = resolve(store);
7934          const collectionResource = isEntity ? { kind: resource.kind, name: resource.name } : resource;
7935          const create3 = canUser3("create", collectionResource);
7936          if (!hasId) {
7937            const read2 = canUser3("read", collectionResource);
7938            const isResolving2 = create3.isResolving || read2.isResolving;
7939            const hasResolved2 = create3.hasResolved && read2.hasResolved;
7940            let status2 = Status.Idle;
7941            if (isResolving2) {
7942              status2 = Status.Resolving;
7943            } else if (hasResolved2) {
7944              status2 = Status.Success;
7945            }
7946            return {
7947              status: status2,
7948              isResolving: isResolving2,
7949              hasResolved: hasResolved2,
7950              canCreate: create3.hasResolved && create3.data,
7951              canRead: read2.hasResolved && read2.data
7952            };
7953          }
7954          const read = canUser3("read", resource, id);
7955          const update = canUser3("update", resource, id);
7956          const _delete = canUser3("delete", resource, id);
7957          const isResolving = read.isResolving || create3.isResolving || update.isResolving || _delete.isResolving;
7958          const hasResolved = read.hasResolved && create3.hasResolved && update.hasResolved && _delete.hasResolved;
7959          let status = Status.Idle;
7960          if (isResolving) {
7961            status = Status.Resolving;
7962          } else if (hasResolved) {
7963            status = Status.Success;
7964          }
7965          return {
7966            status,
7967            isResolving,
7968            hasResolved,
7969            canRead: hasResolved && read.data,
7970            canCreate: hasResolved && create3.data,
7971            canUpdate: hasResolved && update.data,
7972            canDelete: hasResolved && _delete.data
7973          };
7974        },
7975        [resourceAsString, id]
7976      );
7977    }
7978    var use_resource_permissions_default = useResourcePermissions;
7979    function useDeprecatedResourcePermissions(resource, id) {
7980      (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, {
7981        alternative: "wp.data.useResourcePermissions",
7982        since: "6.1"
7983      });
7984      return useResourcePermissions(resource, id);
7985    }
7986  
7987    // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
7988    var import_element6 = __toESM(require_element(), 1);
7989    var import_data14 = __toESM(require_data(), 1);
7990    var import_blocks6 = __toESM(require_blocks(), 1);
7991  
7992    // packages/core-data/build-module/hooks/use-entity-id.mjs
7993    var import_element5 = __toESM(require_element(), 1);
7994    function useEntityId(kind, name) {
7995      const context = (0, import_element5.useContext)(EntityContext);
7996      return context?.[kind]?.[name];
7997    }
7998  
7999    // packages/core-data/build-module/footnotes/index.mjs
8000    var import_rich_text4 = __toESM(require_rich_text(), 1);
8001    var import_warning2 = __toESM(require_warning(), 1);
8002  
8003    // packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs
8004    var import_block_editor6 = __toESM(require_block_editor(), 1);
8005    var unlockedApis;
8006    var cache = /* @__PURE__ */ new WeakMap();
8007    function getRichTextValuesCached(block) {
8008      if (!unlockedApis) {
8009        unlockedApis = unlock(import_block_editor6.privateApis);
8010      }
8011      if (!cache.has(block)) {
8012        const values = unlockedApis.getRichTextValues([block]);
8013        cache.set(block, values);
8014      }
8015      return cache.get(block);
8016    }
8017  
8018    // packages/core-data/build-module/footnotes/get-footnotes-order.mjs
8019    var cache2 = /* @__PURE__ */ new WeakMap();
8020    function getBlockFootnotesOrder(block) {
8021      if (!cache2.has(block)) {
8022        const order = [];
8023        for (const value of getRichTextValuesCached(block)) {
8024          if (!value) {
8025            continue;
8026          }
8027          value.replacements.forEach(({ type, attributes }) => {
8028            if (type === "core/footnote") {
8029              order.push(attributes["data-fn"]);
8030            }
8031          });
8032        }
8033        cache2.set(block, order);
8034      }
8035      return cache2.get(block);
8036    }
8037    function getFootnotesOrder(blocks) {
8038      return blocks.flatMap(getBlockFootnotesOrder);
8039    }
8040  
8041    // packages/core-data/build-module/footnotes/index.mjs
8042    var oldFootnotes = {};
8043    function updateFootnotesFromMeta(blocks, meta) {
8044      const output = { blocks };
8045      if (!meta) {
8046        return output;
8047      }
8048      if (meta.footnotes === void 0) {
8049        return output;
8050      }
8051      const newOrder = getFootnotesOrder(blocks);
8052      let parsed;
8053      try {
8054        parsed = JSON.parse(meta.footnotes || "[]");
8055      } catch {
8056      }
8057      let footnotes = [];
8058      if (Array.isArray(parsed)) {
8059        footnotes = parsed;
8060      } else {
8061        (0, import_warning2.default)("Footnotes post meta is not a JSON array; ignoring it.");
8062      }
8063      const currentOrder = footnotes.map((fn) => fn.id);
8064      if (currentOrder.join("") === newOrder.join("")) {
8065        return output;
8066      }
8067      const newFootnotes = newOrder.map(
8068        (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || {
8069          id: fnId,
8070          content: ""
8071        }
8072      );
8073      function updateAttributes(attributes) {
8074        if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
8075          return attributes;
8076        }
8077        attributes = { ...attributes };
8078        for (const key in attributes) {
8079          const value = attributes[key];
8080          if (Array.isArray(value)) {
8081            attributes[key] = value.map(updateAttributes);
8082            continue;
8083          }
8084          if (typeof value !== "string" && !(value instanceof import_rich_text4.RichTextData)) {
8085            continue;
8086          }
8087          const richTextValue = typeof value === "string" ? import_rich_text4.RichTextData.fromHTMLString(value) : new import_rich_text4.RichTextData(value);
8088          let hasFootnotes = false;
8089          richTextValue.replacements.forEach((replacement) => {
8090            if (replacement.type === "core/footnote") {
8091              const id = replacement.attributes["data-fn"];
8092              const index = newOrder.indexOf(id);
8093              const countValue = (0, import_rich_text4.create)({
8094                html: replacement.innerHTML
8095              });
8096              countValue.text = String(index + 1);
8097              countValue.formats = Array.from(
8098                { length: countValue.text.length },
8099                () => countValue.formats[0]
8100              );
8101              countValue.replacements = Array.from(
8102                { length: countValue.text.length },
8103                () => countValue.replacements[0]
8104              );
8105              replacement.innerHTML = (0, import_rich_text4.toHTMLString)({
8106                value: countValue
8107              });
8108              hasFootnotes = true;
8109            }
8110          });
8111          if (hasFootnotes) {
8112            attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue;
8113          }
8114        }
8115        return attributes;
8116      }
8117      function updateBlocksAttributes(__blocks) {
8118        return __blocks.map((block) => {
8119          return {
8120            ...block,
8121            attributes: updateAttributes(block.attributes),
8122            innerBlocks: updateBlocksAttributes(block.innerBlocks)
8123          };
8124        });
8125      }
8126      const newBlocks = updateBlocksAttributes(blocks);
8127      oldFootnotes = {
8128        ...oldFootnotes,
8129        ...footnotes.reduce((acc, fn) => {
8130          if (!newOrder.includes(fn.id)) {
8131            acc[fn.id] = fn;
8132          }
8133          return acc;
8134        }, {})
8135      };
8136      return {
8137        meta: {
8138          ...meta,
8139          footnotes: JSON.stringify(newFootnotes)
8140        },
8141        blocks: newBlocks
8142      };
8143    }
8144  
8145    // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
8146    var EMPTY_ARRAY2 = [];
8147    function useEntityBlockEditor(kind, name, { id: _id } = {}) {
8148      const providerId = useEntityId(kind, name);
8149      const id = _id ?? providerId;
8150      const { content, editedBlocks, meta } = (0, import_data14.useSelect)(
8151        (select5) => {
8152          if (!id) {
8153            return {};
8154          }
8155          const { getEditedEntityRecord: getEditedEntityRecord3 } = select5(STORE_NAME);
8156          const editedRecord = getEditedEntityRecord3(kind, name, id);
8157          return {
8158            editedBlocks: editedRecord.blocks,
8159            content: editedRecord.content,
8160            meta: editedRecord.meta
8161          };
8162        },
8163        [kind, name, id]
8164      );
8165      const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME);
8166      const blocks = (0, import_element6.useMemo)(() => {
8167        if (!id) {
8168          return void 0;
8169        }
8170        if (editedBlocks) {
8171          return editedBlocks;
8172        }
8173        if (!content || typeof content !== "string") {
8174          return EMPTY_ARRAY2;
8175        }
8176        let _blocks = getCachedBlocks(kind, name, id, content);
8177        if (!_blocks) {
8178          _blocks = (0, import_blocks6.parse)(content);
8179          setCachedBlocks(kind, name, id, content, _blocks);
8180        }
8181        return _blocks;
8182      }, [kind, name, id, editedBlocks, content]);
8183      const onChange = (0, import_element6.useCallback)(
8184        (newBlocks, options) => {
8185          const noChange = blocks === newBlocks;
8186          if (noChange) {
8187            return __unstableCreateUndoLevel2(kind, name, id);
8188          }
8189          const { selection, ...rest } = options;
8190          const edits = {
8191            selection,
8192            content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks6.__unstableSerializeAndClean)(blocksForSerialization),
8193            ...updateFootnotesFromMeta(newBlocks, meta)
8194          };
8195          editEntityRecord2(kind, name, id, edits, {
8196            isCached: false,
8197            ...rest
8198          });
8199        },
8200        [
8201          kind,
8202          name,
8203          id,
8204          blocks,
8205          meta,
8206          __unstableCreateUndoLevel2,
8207          editEntityRecord2
8208        ]
8209      );
8210      const onInput = (0, import_element6.useCallback)(
8211        (newBlocks, options) => {
8212          const { selection, ...rest } = options;
8213          const edits = {
8214            selection,
8215            ...updateFootnotesFromMeta(newBlocks, meta)
8216          };
8217          editEntityRecord2(kind, name, id, edits, {
8218            isCached: true,
8219            ...rest
8220          });
8221        },
8222        [kind, name, id, meta, editEntityRecord2]
8223      );
8224      return [blocks, onInput, onChange];
8225    }
8226  
8227    // packages/core-data/build-module/hooks/use-entity-prop.mjs
8228    var import_element7 = __toESM(require_element(), 1);
8229    var import_data15 = __toESM(require_data(), 1);
8230    var REVISION_QUERY = {
8231      context: "edit",
8232      _fields: "id,date,author,meta,title,excerpt,content.raw"
8233    };
8234    function useEntityProp(kind, name, prop, _id) {
8235      const providerId = useEntityId(kind, name);
8236      const id = _id ?? providerId;
8237      const context = (0, import_element7.useContext)(EntityContext);
8238      const revisionId = String(id) === String(providerId) ? context?.revision?.[kind]?.[name] : void 0;
8239      const { value, fullValue } = (0, import_data15.useSelect)(
8240        (select5) => {
8241          if (revisionId) {
8242            const revision = select5(STORE_NAME).getRevision(
8243              kind,
8244              name,
8245              id,
8246              revisionId,
8247              REVISION_QUERY
8248            );
8249            const propValue = revision?.[prop];
8250            if (propValue === void 0) {
8251              return {};
8252            }
8253            const isRawAttribute = propValue !== null && typeof propValue === "object" && "raw" in propValue;
8254            return {
8255              value: isRawAttribute ? propValue.raw : propValue,
8256              fullValue: propValue
8257            };
8258          }
8259          const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select5(STORE_NAME);
8260          const record = getEntityRecord3(kind, name, id);
8261          const editedRecord = getEditedEntityRecord3(kind, name, id);
8262          return record && editedRecord ? {
8263            value: editedRecord[prop],
8264            fullValue: record[prop]
8265          } : {};
8266        },
8267        [kind, name, id, prop, revisionId]
8268      );
8269      const { editEntityRecord: editEntityRecord2 } = (0, import_data15.useDispatch)(STORE_NAME);
8270      const setValue = (0, import_element7.useCallback)(
8271        (newValue) => {
8272          if (revisionId) {
8273            return;
8274          }
8275          editEntityRecord2(kind, name, id, {
8276            [prop]: newValue
8277          });
8278        },
8279        [editEntityRecord2, kind, name, id, prop, revisionId]
8280      );
8281      return [value, setValue, fullValue];
8282    }
8283  
8284    // packages/core-data/build-module/hooks/use-post-editor-awareness-state.mjs
8285    var import_compose3 = __toESM(require_compose(), 1);
8286    var import_element8 = __toESM(require_element(), 1);
8287    var defaultResolvedSelection = {
8288      richTextOffset: null,
8289      localClientId: null,
8290      attributeKey: null
8291    };
8292    var defaultState = {
8293      activeCollaborators: [],
8294      resolveSelection: () => defaultResolvedSelection,
8295      getDebugData: () => ({
8296        doc: {},
8297        clients: {},
8298        collaboratorMap: {}
8299      }),
8300      isCurrentCollaboratorDisconnected: false
8301    };
8302    function getAwarenessState(awareness, newState) {
8303      const activeCollaborators = (newState ?? awareness.getCurrentState()).filter(
8304        (collaborator) => isCollaboratorInfo(collaborator.collaboratorInfo)
8305      );
8306      return {
8307        activeCollaborators,
8308        resolveSelection: (selection, blocks) => awareness.convertSelectionStateToAbsolute(selection, blocks),
8309        getDebugData: () => awareness.getDebugData(),
8310        isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false
8311      };
8312    }
8313    function usePostEditorAwarenessState(postId, postType) {
8314      const [state, setState] = (0, import_element8.useState)(defaultState);
8315      (0, import_element8.useEffect)(() => {
8316        if (null === postId || null === postType) {
8317          setState(defaultState);
8318          return;
8319        }
8320        const objectType = `postType/$postType}`;
8321        const objectId = postId.toString();
8322        const awareness = getSyncManager()?.getAwareness(
8323          objectType,
8324          objectId
8325        );
8326        if (!awareness) {
8327          setState(defaultState);
8328          return;
8329        }
8330        awareness.setUp();
8331        setState(getAwarenessState(awareness));
8332        const unsubscribe = awareness?.onStateChange(
8333          (newState) => {
8334            setState(getAwarenessState(awareness, newState));
8335          }
8336        );
8337        return unsubscribe;
8338      }, [postId, postType]);
8339      return state;
8340    }
8341    function useActiveCollaborators(postId, postType) {
8342      return usePostEditorAwarenessState(postId, postType).activeCollaborators;
8343    }
8344    function useResolvedSelection(postId, postType) {
8345      const blocks = usePostContentBlocks();
8346      const awarenessState = usePostEditorAwarenessState(postId, postType);
8347      return (0, import_element8.useCallback)(
8348        (selection) => awarenessState.resolveSelection(selection, blocks),
8349        [blocks, awarenessState]
8350      );
8351    }
8352    function useLastPostSave(postId, postType) {
8353      const [lastSave, setLastSave] = (0, import_element8.useState)(null);
8354      (0, import_element8.useEffect)(() => {
8355        if (null === postId || null === postType) {
8356          setLastSave(null);
8357          return;
8358        }
8359        const awareness = getSyncManager()?.getAwareness(
8360          `postType/$postType}`,
8361          postId.toString()
8362        );
8363        if (!awareness) {
8364          setLastSave(null);
8365          return;
8366        }
8367        awareness.setUp();
8368        const stateMap = awareness.doc.getMap("state");
8369        const recordMap = awareness.doc.getMap("document");
8370        const setupTime = Date.now();
8371        const observer = (event) => {
8372          if (event.keysChanged.has("savedAt")) {
8373            const savedAt = stateMap.get("savedAt");
8374            const savedByClientId = stateMap.get("savedBy");
8375            if (typeof savedAt === "number" && typeof savedByClientId === "number" && savedAt > setupTime) {
8376              const postStatus = recordMap.get("status");
8377              setLastSave({ savedAt, savedByClientId, postStatus });
8378            }
8379          }
8380        };
8381        stateMap.observe(observer);
8382        return () => {
8383          stateMap.unobserve(observer);
8384        };
8385      }, [postId, postType]);
8386      return lastSave;
8387    }
8388    function useOnCollaboratorJoin(postId, postType, callback) {
8389      const { activeCollaborators } = usePostEditorAwarenessState(
8390        postId,
8391        postType
8392      );
8393      const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
8394      (0, import_element8.useEffect)(() => {
8395        if (!prevCollaborators || prevCollaborators.length === 0) {
8396          return;
8397        }
8398        const prevMap = new Map(
8399          prevCollaborators.map((collaborator) => [
8400            collaborator.clientId,
8401            collaborator
8402          ])
8403        );
8404        const me = activeCollaborators.find(
8405          (collaborator) => collaborator.isMe
8406        );
8407        for (const collaborator of activeCollaborators) {
8408          if (!prevMap.has(collaborator.clientId) && !collaborator.isMe) {
8409            callback(collaborator, me);
8410          }
8411        }
8412      }, [activeCollaborators, prevCollaborators, callback]);
8413    }
8414    function useOnCollaboratorLeave(postId, postType, callback) {
8415      const { activeCollaborators } = usePostEditorAwarenessState(
8416        postId,
8417        postType
8418      );
8419      const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
8420      (0, import_element8.useEffect)(() => {
8421        if (!prevCollaborators || prevCollaborators.length === 0) {
8422          return;
8423        }
8424        const newMap = new Map(
8425          activeCollaborators.map((collaborator) => [
8426            collaborator.clientId,
8427            collaborator
8428          ])
8429        );
8430        for (const prevCollab of prevCollaborators) {
8431          if (prevCollab.isMe || !prevCollab.isConnected) {
8432            continue;
8433          }
8434          const newCollab = newMap.get(prevCollab.clientId);
8435          if (!newCollab?.isConnected) {
8436            callback(prevCollab);
8437          }
8438        }
8439      }, [activeCollaborators, prevCollaborators, callback]);
8440    }
8441    function useOnPostSave(postId, postType, callback) {
8442      const { activeCollaborators } = usePostEditorAwarenessState(
8443        postId,
8444        postType
8445      );
8446      const lastPostSave = useLastPostSave(postId, postType);
8447      const prevPostSave = (0, import_compose3.usePrevious)(lastPostSave);
8448      (0, import_element8.useEffect)(() => {
8449        if (!lastPostSave) {
8450          return;
8451        }
8452        if (prevPostSave && lastPostSave.savedAt === prevPostSave.savedAt) {
8453          return;
8454        }
8455        const saver = activeCollaborators.find(
8456          (collaborator) => collaborator.clientId === lastPostSave.savedByClientId && !collaborator.isMe
8457        );
8458        if (!saver) {
8459          return;
8460        }
8461        callback(lastPostSave, saver, prevPostSave ?? null);
8462      }, [lastPostSave, prevPostSave, activeCollaborators, callback]);
8463    }
8464  
8465    // packages/icons/build-module/library/footer.mjs
8466    var import_primitives = __toESM(require_primitives(), 1);
8467    var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
8468    var footer_default = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8469      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M9.75 4.75H18C18.6904 4.75 19.25 5.30964 19.25 6V14.25M9.75 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V14.25M9.75 4.75V14.25M19.25 14.25V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V14.25M19.25 14.25H9.75M9.75 14.25H4.75", vectorEffect: "non-scaling-stroke" }),
8470      /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M19.25 15.5V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V15.5C4.75 14.8096 5.30964 14.25 6 14.25H18C18.6904 14.25 19.25 14.8096 19.25 15.5Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8471    ] });
8472  
8473    // packages/icons/build-module/library/header.mjs
8474    var import_primitives2 = __toESM(require_primitives(), 1);
8475    var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
8476    var header_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8477      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }),
8478      /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M19.25 8.5V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V8.5C4.75 9.19036 5.30964 9.75 6 9.75H18C18.6904 9.75 19.25 9.19036 19.25 8.5Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8479    ] });
8480  
8481    // packages/icons/build-module/library/layout.mjs
8482    var import_primitives3 = __toESM(require_primitives(), 1);
8483    var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
8484    var layout_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }) });
8485  
8486    // packages/icons/build-module/library/navigation-overlay.mjs
8487    var import_primitives4 = __toESM(require_primitives(), 1);
8488    var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
8489    var navigation_overlay_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8490      /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M4.75 9.25V16C4.75 16.6904 5.30964 17.25 6 17.25H8M4.75 9.25V6C4.75 5.30964 5.30964 4.75 6 4.75H16C16.6904 4.75 17.25 5.30964 17.25 6V8M4.75 9.25H8", vectorEffect: "non-scaling-stroke" }),
8491      /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M10.75 11.25C10.75 10.9739 10.9739 10.75 11.25 10.75H18.75C19.0261 10.75 19.25 10.9739 19.25 11.25V18.75C19.25 19.0261 19.0261 19.25 18.75 19.25H11.25C10.9739 19.25 10.75 19.0261 10.75 18.75V11.25Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8492    ] });
8493  
8494    // packages/icons/build-module/library/sidebar.mjs
8495    var import_primitives5 = __toESM(require_primitives(), 1);
8496    var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
8497    var sidebar_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8498      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }),
8499      /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M6 19.25H9.75V9.75H4.75V18C4.75 18.6904 5.30964 19.25 6 19.25Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8500    ] });
8501  
8502    // packages/icons/build-module/library/symbol-filled.mjs
8503    var import_primitives6 = __toESM(require_primitives(), 1);
8504    var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
8505    var symbol_filled_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8506      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M15.2071 6.20711L20.2929 11.2929C20.6834 11.6834 20.6834 12.3166 20.2929 12.7071L15.2071 17.7929C14.8166 18.1834 14.1834 18.1834 13.7929 17.7929L8.70711 12.7071C8.31658 12.3166 8.31658 11.6834 8.70711 11.2929L13.7929 6.20711C14.1834 5.81658 14.8166 5.81658 15.2071 6.20711Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" }),
8507      /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M9.5 5.5L3.70711 11.2929C3.31658 11.6834 3.31658 12.3166 3.70711 12.7071L9.5 18.5", vectorEffect: "non-scaling-stroke" })
8508    ] });
8509  
8510    // packages/core-data/build-module/utils/get-template-part-icon.mjs
8511    function getTemplatePartIcon(areaOrIconName) {
8512      if ("header" === areaOrIconName) {
8513        return header_default;
8514      } else if ("footer" === areaOrIconName) {
8515        return footer_default;
8516      } else if ("sidebar" === areaOrIconName) {
8517        return sidebar_default;
8518      } else if ("navigation-overlay" === areaOrIconName) {
8519        return navigation_overlay_default;
8520      }
8521      return symbol_filled_default;
8522    }
8523  
8524    // packages/core-data/build-module/utils/get-template-info.mjs
8525    var EMPTY_OBJECT4 = {};
8526    var getTemplateInfo = (params) => {
8527      if (!params) {
8528        return EMPTY_OBJECT4;
8529      }
8530      const { templateTypes, templateAreas, template } = params;
8531      const { description, slug, title, area } = template;
8532      const { title: defaultTitle, description: defaultDescription } = Object.values(templateTypes).find((type) => type.slug === slug) ?? EMPTY_OBJECT4;
8533      const templateTitle = typeof title === "string" ? title : title?.rendered;
8534      const templateDescription = typeof description === "string" ? description : description?.raw;
8535      const templateAreasWithIcon = templateAreas?.map((item) => ({
8536        ...item,
8537        icon: getTemplatePartIcon(item.icon)
8538      }));
8539      const templateIcon = templateAreasWithIcon?.find((item) => area === item.area)?.icon || layout_default;
8540      return {
8541        title: templateTitle && templateTitle !== slug ? templateTitle : defaultTitle || slug,
8542        description: templateDescription || defaultDescription,
8543        icon: templateIcon
8544      };
8545    };
8546  
8547    // node_modules/clsx/dist/clsx.mjs
8548    function r(e) {
8549      var t, f, n = "";
8550      if ("string" == typeof e || "number" == typeof e) n += e;
8551      else if ("object" == typeof e) if (Array.isArray(e)) {
8552        var o = e.length;
8553        for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
8554      } else for (f in e) e[f] && (n && (n += " "), n += f);
8555      return n;
8556    }
8557    function clsx() {
8558      for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
8559      return n;
8560    }
8561    var clsx_default = clsx;
8562  
8563    // packages/core-data/build-module/components/entities-saved-states/index.mjs
8564    var import_components3 = __toESM(require_components(), 1);
8565    var import_i18n7 = __toESM(require_i18n(), 1);
8566    var import_element10 = __toESM(require_element(), 1);
8567    var import_compose4 = __toESM(require_compose(), 1);
8568    var import_data19 = __toESM(require_data(), 1);
8569  
8570    // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs
8571    var import_i18n6 = __toESM(require_i18n(), 1);
8572    var import_data17 = __toESM(require_data(), 1);
8573    var import_components2 = __toESM(require_components(), 1);
8574  
8575    // packages/global-styles-engine/build-module/utils/get-global-styles-changes.mjs
8576    var import_i18n4 = __toESM(require_i18n(), 1);
8577    var import_blocks7 = __toESM(require_blocks(), 1);
8578    var globalStylesChangesCache = /* @__PURE__ */ new Map();
8579    var EMPTY_ARRAY3 = [];
8580    var translationMap = {
8581      caption: (0, import_i18n4.__)("Caption"),
8582      link: (0, import_i18n4.__)("Link"),
8583      button: (0, import_i18n4.__)("Button"),
8584      heading: (0, import_i18n4.__)("Heading"),
8585      h1: (0, import_i18n4.__)("H1"),
8586      h2: (0, import_i18n4.__)("H2"),
8587      h3: (0, import_i18n4.__)("H3"),
8588      h4: (0, import_i18n4.__)("H4"),
8589      h5: (0, import_i18n4.__)("H5"),
8590      h6: (0, import_i18n4.__)("H6"),
8591      "settings.color": (0, import_i18n4.__)("Color"),
8592      "settings.typography": (0, import_i18n4.__)("Typography"),
8593      "settings.shadow": (0, import_i18n4.__)("Shadow"),
8594      "settings.layout": (0, import_i18n4.__)("Layout"),
8595      "styles.color": (0, import_i18n4.__)("Colors"),
8596      "styles.spacing": (0, import_i18n4.__)("Spacing"),
8597      "styles.background": (0, import_i18n4.__)("Background"),
8598      "styles.typography": (0, import_i18n4.__)("Typography"),
8599      "styles.border": (0, import_i18n4.__)("Border"),
8600      "styles.shadow": (0, import_i18n4.__)("Shadow"),
8601      "styles.outline": (0, import_i18n4.__)("Outline"),
8602      "styles.filter": (0, import_i18n4.__)("Filter"),
8603      "styles.dimensions": (0, import_i18n4.__)("Dimensions")
8604    };
8605    var getBlockNames = memize(
8606      () => (0, import_blocks7.getBlockTypes)().reduce(
8607        (accumulator, {
8608          name,
8609          title
8610        }) => {
8611          accumulator[name] = title;
8612          return accumulator;
8613        },
8614        {}
8615      )
8616    );
8617    var isObject = (obj) => obj !== null && typeof obj === "object";
8618    function getTranslation(key) {
8619      if (translationMap[key]) {
8620        return translationMap[key];
8621      }
8622      const keyArray = key.split(".");
8623      if (keyArray?.[0] === "blocks") {
8624        const blockName = getBlockNames()?.[keyArray[1]];
8625        return blockName || keyArray[1];
8626      }
8627      if (keyArray?.[0] === "elements") {
8628        return translationMap[keyArray[1]] || keyArray[1];
8629      }
8630      return void 0;
8631    }
8632    function deepCompare(changedObject, originalObject, parentPath = "") {
8633      if (!isObject(changedObject) && !isObject(originalObject)) {
8634        return changedObject !== originalObject ? parentPath.split(".").slice(0, 2).join(".") : void 0;
8635      }
8636      changedObject = isObject(changedObject) ? changedObject : {};
8637      originalObject = isObject(originalObject) ? originalObject : {};
8638      const allKeys = /* @__PURE__ */ new Set([
8639        ...Object.keys(changedObject),
8640        ...Object.keys(originalObject)
8641      ]);
8642      let diffs = [];
8643      for (const key of allKeys) {
8644        const path = parentPath ? parentPath + "." + key : key;
8645        const changedPath = deepCompare(
8646          changedObject[key],
8647          originalObject[key],
8648          path
8649        );
8650        if (changedPath) {
8651          diffs = diffs.concat(changedPath);
8652        }
8653      }
8654      return diffs;
8655    }
8656    var COMPARED_STYLE_KEYS = [
8657      "background",
8658      "color",
8659      "typography",
8660      "spacing",
8661      "border",
8662      "shadow",
8663      "outline",
8664      "filter",
8665      "dimensions"
8666    ];
8667    function pickComparedStyles(config) {
8668      return Object.fromEntries(
8669        COMPARED_STYLE_KEYS.map((key) => [key, config?.styles?.[key]])
8670      );
8671    }
8672    function getGlobalStylesChangelist(next, previous) {
8673      const cacheKey = JSON.stringify({ next, previous });
8674      if (globalStylesChangesCache.has(cacheKey)) {
8675        return globalStylesChangesCache.get(cacheKey);
8676      }
8677      const changedValueTree = deepCompare(
8678        {
8679          styles: pickComparedStyles(next),
8680          blocks: next?.styles?.blocks,
8681          elements: next?.styles?.elements,
8682          settings: next?.settings
8683        },
8684        {
8685          styles: pickComparedStyles(previous),
8686          blocks: previous?.styles?.blocks,
8687          elements: previous?.styles?.elements,
8688          settings: previous?.settings
8689        }
8690      );
8691      if (!changedValueTree || Array.isArray(changedValueTree) && !changedValueTree.length) {
8692        globalStylesChangesCache.set(cacheKey, []);
8693        return [];
8694      }
8695      const changedValueArray = Array.isArray(changedValueTree) ? changedValueTree : [changedValueTree];
8696      const result = [...new Set(changedValueArray)].reduce((acc, curr) => {
8697        const translation = getTranslation(curr);
8698        if (translation) {
8699          acc.push([curr.split(".")[0], translation]);
8700        }
8701        return acc;
8702      }, []);
8703      globalStylesChangesCache.set(cacheKey, result);
8704      return result;
8705    }
8706    function getGlobalStylesChanges(next, previous, options = {}) {
8707      let changeList = getGlobalStylesChangelist(next, previous);
8708      const changesLength = changeList.length;
8709      const { maxResults } = options;
8710      if (changesLength) {
8711        if (!!maxResults && changesLength > maxResults) {
8712          changeList = changeList.slice(0, maxResults);
8713        }
8714        return Object.entries(
8715          changeList.reduce((acc, curr) => {
8716            const group = acc[curr[0]] || [];
8717            if (!group.includes(curr[1])) {
8718              acc[curr[0]] = [...group, curr[1]];
8719            }
8720            return acc;
8721          }, {})
8722        ).map(([key, changeValues]) => {
8723          const changeValuesLength = changeValues.length;
8724          const joinedChangesValue = changeValues.join(
8725            /* translators: Used between list items, there is a space after the comma. */
8726            (0, import_i18n4.__)(", ")
8727            // eslint-disable-line @wordpress/i18n-no-flanking-whitespace
8728          );
8729          switch (key) {
8730            case "blocks": {
8731              return (0, import_i18n4.sprintf)(
8732                // translators: %s: a list of block names separated by a comma.
8733                (0, import_i18n4._n)("%s block.", "%s blocks.", changeValuesLength),
8734                joinedChangesValue
8735              );
8736            }
8737            case "elements": {
8738              return (0, import_i18n4.sprintf)(
8739                // translators: %s: a list of element names separated by a comma.
8740                (0, import_i18n4._n)("%s element.", "%s elements.", changeValuesLength),
8741                joinedChangesValue
8742              );
8743            }
8744            case "settings": {
8745              return (0, import_i18n4.sprintf)(
8746                // translators: %s: a list of theme.json setting labels separated by a comma.
8747                (0, import_i18n4.__)("%s settings."),
8748                joinedChangesValue
8749              );
8750            }
8751            case "styles": {
8752              return (0, import_i18n4.sprintf)(
8753                // translators: %s: a list of theme.json top-level styles labels separated by a comma.
8754                (0, import_i18n4.__)("%s styles."),
8755                joinedChangesValue
8756              );
8757            }
8758            default: {
8759              return (0, import_i18n4.sprintf)(
8760                // translators: %s: a list of global styles changes separated by a comma.
8761                (0, import_i18n4.__)("%s."),
8762                joinedChangesValue
8763              );
8764            }
8765          }
8766        });
8767      }
8768      return EMPTY_ARRAY3;
8769    }
8770  
8771    // packages/core-data/build-module/components/entities-saved-states/entity-record-item.mjs
8772    var import_components = __toESM(require_components(), 1);
8773    var import_i18n5 = __toESM(require_i18n(), 1);
8774    var import_data16 = __toESM(require_data(), 1);
8775    var import_html_entities4 = __toESM(require_html_entities(), 1);
8776    var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
8777    function EntityRecordItem({ record, checked, onChange }) {
8778      const { name, kind, title, key } = record;
8779      const { entityRecordTitle } = (0, import_data16.useSelect)(
8780        (select5) => {
8781          if ("postType" !== kind || "wp_template" !== name) {
8782            return {
8783              entityRecordTitle: title
8784            };
8785          }
8786          const template = select5(STORE_NAME).getEditedEntityRecord(
8787            kind,
8788            name,
8789            key
8790          );
8791          const { default_template_types: templateTypes = [] } = select5(STORE_NAME).getCurrentTheme() ?? {};
8792          return {
8793            entityRecordTitle: getTemplateInfo({
8794              template,
8795              templateTypes
8796            }).title
8797          };
8798        },
8799        [name, kind, title, key]
8800      );
8801      return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_components.PanelRow, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
8802        import_components.CheckboxControl,
8803        {
8804          label: (0, import_html_entities4.decodeEntities)(entityRecordTitle) || (0, import_i18n5.__)("Untitled"),
8805          checked,
8806          onChange,
8807          className: "entities-saved-states__change-control"
8808        }
8809      ) }) });
8810    }
8811  
8812    // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs
8813    var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
8814    function getEntityDescription(entity2, count) {
8815      switch (entity2) {
8816        case "site":
8817          return 1 === count ? (0, import_i18n6.__)("This change will affect your whole site.") : (0, import_i18n6.__)("These changes will affect your whole site.");
8818        case "wp_template":
8819          return (0, import_i18n6.__)(
8820            "This change will affect other parts of your site that use this template."
8821          );
8822        case "page":
8823        case "post":
8824          return (0, import_i18n6.__)("The following has been modified.");
8825      }
8826    }
8827    function GlobalStylesDescription({ record }) {
8828      const { editedRecord, savedRecord } = (0, import_data17.useSelect)(
8829        (select5) => {
8830          const { getEditedEntityRecord: getEditedEntityRecord3, getEntityRecord: getEntityRecord3 } = select5(STORE_NAME);
8831          return {
8832            editedRecord: getEditedEntityRecord3(
8833              record.kind,
8834              record.name,
8835              record.key
8836            ),
8837            savedRecord: getEntityRecord3(
8838              record.kind,
8839              record.name,
8840              record.key
8841            )
8842          };
8843        },
8844        [record.kind, record.name, record.key]
8845      );
8846      const globalStylesChanges = getGlobalStylesChanges(
8847        editedRecord,
8848        savedRecord,
8849        {
8850          maxResults: 10
8851        }
8852      );
8853      return globalStylesChanges.length ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("ul", { className: "entities-saved-states__changes", children: globalStylesChanges.map((change) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("li", { children: change }, change)) }) : null;
8854    }
8855    function EntityDescription({ record, count }) {
8856      if ("globalStyles" === record?.name) {
8857        return null;
8858      }
8859      const description = getEntityDescription(record?.name, count);
8860      return description ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_components2.PanelRow, { children: description }) : null;
8861    }
8862    function EntityTypeList({
8863      list,
8864      unselectedEntities,
8865      setUnselectedEntities
8866    }) {
8867      const count = list.length;
8868      const firstRecord = list[0];
8869      const entityConfig = (0, import_data17.useSelect)(
8870        (select5) => select5(STORE_NAME).getEntityConfig(
8871          firstRecord.kind,
8872          firstRecord.name
8873        ),
8874        [firstRecord.kind, firstRecord.name]
8875      );
8876      let entityLabel = entityConfig.label;
8877      if (firstRecord?.name === "wp_template_part") {
8878        entityLabel = 1 === count ? (0, import_i18n6.__)("Template Part") : (0, import_i18n6.__)("Template Parts");
8879      }
8880      return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
8881        import_components2.PanelBody,
8882        {
8883          title: entityLabel,
8884          initialOpen: true,
8885          className: "entities-saved-states__panel-body",
8886          children: [
8887            /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(EntityDescription, { record: firstRecord, count }),
8888            list.map((record) => {
8889              return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
8890                EntityRecordItem,
8891                {
8892                  record,
8893                  checked: !unselectedEntities.some(
8894                    (elt) => elt.kind === record.kind && elt.name === record.name && elt.key === record.key && elt.property === record.property
8895                  ),
8896                  onChange: (value) => setUnselectedEntities(record, value)
8897                },
8898                record.key || record.property
8899              );
8900            }),
8901            "globalStyles" === firstRecord?.name && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(GlobalStylesDescription, { record: firstRecord })
8902          ]
8903        }
8904      );
8905    }
8906  
8907    // packages/core-data/build-module/components/entities-saved-states/hooks/use-is-dirty.mjs
8908    var import_data18 = __toESM(require_data(), 1);
8909    var import_element9 = __toESM(require_element(), 1);
8910    var useIsDirty = () => {
8911      const { editedEntities, siteEdits, siteEntityConfig } = (0, import_data18.useSelect)(
8912        (select5) => {
8913          const {
8914            __experimentalGetDirtyEntityRecords: __experimentalGetDirtyEntityRecords2,
8915            getEntityRecordEdits: getEntityRecordEdits2,
8916            getEntityConfig: getEntityConfig2
8917          } = select5(STORE_NAME);
8918          return {
8919            editedEntities: __experimentalGetDirtyEntityRecords2(),
8920            siteEdits: getEntityRecordEdits2("root", "site"),
8921            siteEntityConfig: getEntityConfig2("root", "site")
8922          };
8923        },
8924        []
8925      );
8926      const dirtyEntityRecords = (0, import_element9.useMemo)(() => {
8927        const editedEntitiesWithoutSite = editedEntities.filter(
8928          (record) => !(record.kind === "root" && record.name === "site")
8929        );
8930        const siteEntityLabels = siteEntityConfig?.meta?.labels ?? {};
8931        const {
8932          title: siteTitleEdit,
8933          description: siteDescriptionEdit,
8934          site_logo: siteLogoEdit,
8935          site_icon: siteIconEdit,
8936          ...otherSiteEdits
8937        } = siteEdits ?? {};
8938        const orderedSiteProperties = [
8939          siteTitleEdit !== void 0 && "title",
8940          siteDescriptionEdit !== void 0 && "description",
8941          siteLogoEdit !== void 0 && "site_logo",
8942          siteIconEdit !== void 0 && "site_icon",
8943          ...Object.keys(otherSiteEdits)
8944        ].filter(Boolean);
8945        const editedSiteEntities = orderedSiteProperties.map(
8946          (property) => ({
8947            kind: "root",
8948            name: "site",
8949            title: siteEntityLabels[property] || property,
8950            property
8951          })
8952        );
8953        return [...editedEntitiesWithoutSite, ...editedSiteEntities];
8954      }, [editedEntities, siteEdits, siteEntityConfig]);
8955      const [unselectedEntities, _setUnselectedEntities] = (0, import_element9.useState)([]);
8956      const setUnselectedEntities = ({ kind, name, key, property }, checked) => {
8957        if (checked) {
8958          _setUnselectedEntities(
8959            unselectedEntities.filter(
8960              (elt) => elt.kind !== kind || elt.name !== name || elt.key !== key || elt.property !== property
8961            )
8962          );
8963        } else {
8964          _setUnselectedEntities([
8965            ...unselectedEntities,
8966            { kind, name, key, property }
8967          ]);
8968        }
8969      };
8970      const isDirty = dirtyEntityRecords.length - unselectedEntities.length > 0;
8971      return {
8972        dirtyEntityRecords,
8973        isDirty,
8974        setUnselectedEntities,
8975        unselectedEntities
8976      };
8977    };
8978  
8979    // packages/core-data/build-module/components/entities-saved-states/index.mjs
8980    var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
8981    function EntitiesSavedStates({
8982      close,
8983      renderDialog,
8984      variant
8985    }) {
8986      const isDirtyProps = useIsDirty();
8987      return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
8988        EntitiesSavedStatesExtensible,
8989        {
8990          close,
8991          renderDialog,
8992          variant,
8993          ...isDirtyProps
8994        }
8995      );
8996    }
8997    function EntitiesSavedStatesExtensible({
8998      additionalPrompt = void 0,
8999      close,
9000      onSave = void 0,
9001      saveEnabled: saveEnabledProp = void 0,
9002      saveLabel = (0, import_i18n7.__)("Save"),
9003      renderDialog,
9004      dirtyEntityRecords,
9005      isDirty,
9006      setUnselectedEntities,
9007      unselectedEntities,
9008      variant = "default",
9009      successNoticeContent
9010    }) {
9011      const saveButtonRef = (0, import_element10.useRef)();
9012      const { saveDirtyEntities: saveDirtyEntities2 } = unlock((0, import_data19.useDispatch)(STORE_NAME));
9013      const partitionedSavables = dirtyEntityRecords.reduce((acc, record) => {
9014        const { name } = record;
9015        if (!acc[name]) {
9016          acc[name] = [];
9017        }
9018        acc[name].push(record);
9019        return acc;
9020      }, {});
9021      const {
9022        site: siteSavables,
9023        wp_template: templateSavables,
9024        wp_template_part: templatePartSavables,
9025        ...contentSavables
9026      } = partitionedSavables;
9027      const sortedPartitionedSavables = [
9028        siteSavables,
9029        templateSavables,
9030        templatePartSavables,
9031        ...Object.values(contentSavables)
9032      ].filter(Array.isArray);
9033      const saveEnabled = saveEnabledProp ?? isDirty;
9034      const dismissPanel = (0, import_element10.useCallback)(() => close(), [close]);
9035      const [saveDialogRef, saveDialogProps] = (0, import_compose4.__experimentalUseDialog)({
9036        onClose: () => dismissPanel()
9037      });
9038      const dialogLabelId = (0, import_compose4.useInstanceId)(
9039        EntitiesSavedStatesExtensible,
9040        "entities-saved-states__panel-label"
9041      );
9042      const dialogDescriptionId = (0, import_compose4.useInstanceId)(
9043        EntitiesSavedStatesExtensible,
9044        "entities-saved-states__panel-description"
9045      );
9046      const selectItemsToSaveDescription = !!dirtyEntityRecords.length ? (0, import_i18n7.__)("Select the items you want to save.") : void 0;
9047      const isInline = variant === "inline";
9048      const actionButtons = /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
9049        /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9050          import_components3.FlexItem,
9051          {
9052            isBlock: isInline ? false : true,
9053            as: import_components3.Button,
9054            variant: isInline ? "tertiary" : "secondary",
9055            size: isInline ? void 0 : "compact",
9056            onClick: dismissPanel,
9057            children: (0, import_i18n7.__)("Cancel")
9058          }
9059        ),
9060        /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9061          import_components3.FlexItem,
9062          {
9063            isBlock: isInline ? false : true,
9064            as: import_components3.Button,
9065            ref: saveButtonRef,
9066            variant: "primary",
9067            size: isInline ? void 0 : "compact",
9068            disabled: !saveEnabled,
9069            accessibleWhenDisabled: true,
9070            onClick: () => saveDirtyEntities2({
9071              onSave,
9072              dirtyEntityRecords,
9073              entitiesToSkip: unselectedEntities,
9074              close,
9075              successNoticeContent
9076            }),
9077            className: "entities-saved-states__save-button",
9078            children: saveLabel
9079          }
9080        )
9081      ] });
9082      return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
9083        "div",
9084        {
9085          ref: renderDialog ? saveDialogRef : void 0,
9086          ...renderDialog && saveDialogProps,
9087          className: clsx_default("entities-saved-states__panel", {
9088            "is-inline": isInline
9089          }),
9090          role: renderDialog ? "dialog" : void 0,
9091          "aria-labelledby": renderDialog ? dialogLabelId : void 0,
9092          "aria-describedby": renderDialog ? dialogDescriptionId : void 0,
9093          children: [
9094            !isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_components3.Flex, { className: "entities-saved-states__panel-header", gap: 2, children: actionButtons }),
9095            /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "entities-saved-states__text-prompt", children: [
9096              /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "entities-saved-states__text-prompt--header-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9097                "strong",
9098                {
9099                  id: renderDialog ? dialogLabelId : void 0,
9100                  className: "entities-saved-states__text-prompt--header",
9101                  children: (0, import_i18n7.__)("Are you ready to save?")
9102                }
9103              ) }),
9104              /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { id: renderDialog ? dialogDescriptionId : void 0, children: [
9105                additionalPrompt,
9106                /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("p", { className: "entities-saved-states__text-prompt--changes-count", children: isDirty ? (0, import_element10.createInterpolateElement)(
9107                  (0, import_i18n7.sprintf)(
9108                    /* translators: %d: number of site changes waiting to be saved. */
9109                    (0, import_i18n7._n)(
9110                      "There is <strong>%d site change</strong> waiting to be saved.",
9111                      "There are <strong>%d site changes</strong> waiting to be saved.",
9112                      dirtyEntityRecords.length
9113                    ),
9114                    dirtyEntityRecords.length
9115                  ),
9116                  { strong: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("strong", {}) }
9117                ) : selectItemsToSaveDescription })
9118              ] })
9119            ] }),
9120            sortedPartitionedSavables.map((list) => {
9121              return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9122                EntityTypeList,
9123                {
9124                  list,
9125                  unselectedEntities,
9126                  setUnselectedEntities
9127                },
9128                list[0].name
9129              );
9130            }),
9131            isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9132              import_components3.Flex,
9133              {
9134                direction: "row",
9135                justify: "flex-end",
9136                className: "entities-saved-states__panel-footer",
9137                children: actionButtons
9138              }
9139            )
9140          ]
9141        }
9142      );
9143    }
9144  
9145    // packages/core-data/build-module/private-apis.mjs
9146    var lockedApis = {
9147      EntitiesSavedStates,
9148      EntitiesSavedStatesExtensible,
9149      getTemplateInfo,
9150      getTemplatePartIcon,
9151      useEntitiesSavedStatesIsDirty: useIsDirty,
9152      useEntityRecordsWithPermissions,
9153      RECEIVE_INTERMEDIATE_RESULTS,
9154      CRDT_AUTOSAVE_SNAPSHOT_KEY,
9155      entityContainsSnapshot,
9156      getEntitySnapshot,
9157      retrySyncConnection,
9158      useActiveCollaborators,
9159      useResolvedSelection,
9160      useOnCollaboratorJoin,
9161      useOnCollaboratorLeave,
9162      useOnPostSave,
9163      SelectionType,
9164      SelectionDirection
9165    };
9166    var privateApis = {};
9167    lock(privateApis, lockedApis);
9168  
9169    // packages/core-data/build-module/index.mjs
9170    var entitiesConfig2 = [
9171      ...rootEntitiesConfig,
9172      ...additionalEntityConfigLoaders.filter((config) => !!config.name)
9173    ];
9174    var entitySelectors = entitiesConfig2.reduce((result, entity2) => {
9175      const { kind, name, plural } = entity2;
9176      const getEntityRecordMethodName = getMethodName(kind, name);
9177      result[getEntityRecordMethodName] = (state, key, query) => {
9178        logEntityDeprecation(kind, name, getEntityRecordMethodName, {
9179          isShorthandSelector: true,
9180          alternativeFunctionName: "getEntityRecord"
9181        });
9182        return getEntityRecord(state, kind, name, key, query);
9183      };
9184      if (plural) {
9185        const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
9186        result[getEntityRecordsMethodName] = (state, query) => {
9187          logEntityDeprecation(kind, name, getEntityRecordsMethodName, {
9188            isShorthandSelector: true,
9189            alternativeFunctionName: "getEntityRecords"
9190          });
9191          return getEntityRecords(state, kind, name, query);
9192        };
9193      }
9194      return result;
9195    }, {});
9196    var entityResolvers = entitiesConfig2.reduce((result, entity2) => {
9197      const { kind, name, plural } = entity2;
9198      const getEntityRecordMethodName = getMethodName(kind, name);
9199      result[getEntityRecordMethodName] = (key, query) => {
9200        logEntityDeprecation(kind, name, getEntityRecordMethodName, {
9201          isShorthandSelector: true,
9202          alternativeFunctionName: "getEntityRecord"
9203        });
9204        return getEntityRecord2(kind, name, key, query);
9205      };
9206      if (plural) {
9207        const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
9208        result[getEntityRecordsMethodName] = (...args) => {
9209          logEntityDeprecation(kind, plural, getEntityRecordsMethodName, {
9210            isShorthandSelector: true,
9211            alternativeFunctionName: "getEntityRecords"
9212          });
9213          return getEntityRecords2(kind, name, ...args);
9214        };
9215        result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name);
9216      }
9217      return result;
9218    }, {});
9219    var entityActions = entitiesConfig2.reduce((result, entity2) => {
9220      const { kind, name } = entity2;
9221      const saveEntityRecordMethodName = getMethodName(kind, name, "save");
9222      result[saveEntityRecordMethodName] = (record, options) => {
9223        logEntityDeprecation(kind, name, saveEntityRecordMethodName, {
9224          isShorthandSelector: true,
9225          alternativeFunctionName: "saveEntityRecord"
9226        });
9227        return saveEntityRecord(kind, name, record, options);
9228      };
9229      const deleteEntityRecordMethodName = getMethodName(kind, name, "delete");
9230      result[deleteEntityRecordMethodName] = (key, query, options) => {
9231        logEntityDeprecation(kind, name, deleteEntityRecordMethodName, {
9232          isShorthandSelector: true,
9233          alternativeFunctionName: "deleteEntityRecord"
9234        });
9235        return deleteEntityRecord(kind, name, key, query, options);
9236      };
9237      return result;
9238    }, {});
9239    var storeConfig = () => ({
9240      reducer: reducer_default2,
9241      actions: {
9242        ...dynamicActions,
9243        ...actions_exports,
9244        ...entityActions,
9245        ...createLocksActions()
9246      },
9247      selectors: {
9248        ...dynamicSelectors,
9249        ...selectors_exports,
9250        ...entitySelectors
9251      },
9252      resolvers: { ...resolvers_exports, ...entityResolvers }
9253    });
9254    var store = (0, import_data20.createReduxStore)(STORE_NAME, storeConfig());
9255    unlock(store).registerPrivateSelectors(private_selectors_exports);
9256    unlock(store).registerPrivateActions(private_actions_exports);
9257    (0, import_data20.register)(store);
9258    return __toCommonJS(index_exports);
9259  })();
9260  (window.wp ||= {}).coreData = wp.coreData;
9261  })();


Generated : Fri Oct 16 08:20:34 2026 Cross-referenced by PHPXref