PluginProbe
Gutenberg / 23.5.3
Gutenberg v23.5.3
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.5.3, at build/scripts/core-data/index.js

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