PluginProbe
Gutenberg / 23.2.2
Gutenberg v23.2.2
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / scripts / core-data / index.js

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

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