| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 (function() { 2 "use strict"; 3 var wp; 4 (wp ||= {}).coreData = (() => { 5 var __create = Object.create; 6 var __defProp = Object.defineProperty; 7 var __getOwnPropDesc = Object.getOwnPropertyDescriptor; 8 var __getOwnPropNames = Object.getOwnPropertyNames; 9 var __getProtoOf = Object.getPrototypeOf; 10 var __hasOwnProp = Object.prototype.hasOwnProperty; 11 var __commonJS = (cb, mod) => function __require() { 12 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; 13 }; 14 var __export = (target, all2) => { 15 for (var name in all2) 16 __defProp(target, name, { get: all2[name], enumerable: true }); 17 }; 18 var __copyProps = (to, from2, except, desc) => { 19 if (from2 && typeof from2 === "object" || typeof from2 === "function") { 20 for (let key of __getOwnPropNames(from2)) 21 if (!__hasOwnProp.call(to, key) && key !== except) 22 __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable }); 23 } 24 return to; 25 }; 26 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( 27 // If the importer is in node compatibility mode or this is not an ESM 28 // file that has been converted to a CommonJS file using a Babel- 29 // compatible transform (i.e. "__esModule" has not been set), then set 30 // "default" to the CommonJS "module.exports" for node compatibility. 31 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, 32 mod 33 )); 34 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); 35 36 // package-external:@wordpress/data 37 var require_data = __commonJS({ 38 "package-external:@wordpress/data"(exports, module) { 39 module.exports = window.wp.data; 40 } 41 }); 42 43 // node_modules/.store/fast-deep-equal@3.1.3-Dk0kpzcWCOUHE1bkOO2LLA/node_modules/fast-deep-equal/es6/index.js 44 var require_es6 = __commonJS({ 45 "node_modules/.store/fast-deep-equal@3.1.3-Dk0kpzcWCOUHE1bkOO2LLA/node_modules/fast-deep-equal/es6/index.js"(exports, module) { 46 "use strict"; 47 module.exports = function equal(a, b) { 48 if (a === b) return true; 49 if (a && b && typeof a == "object" && typeof b == "object") { 50 if (a.constructor !== b.constructor) return false; 51 var length2, i, keys2; 52 if (Array.isArray(a)) { 53 length2 = a.length; 54 if (length2 != b.length) return false; 55 for (i = length2; i-- !== 0; ) 56 if (!equal(a[i], b[i])) return false; 57 return true; 58 } 59 if (a instanceof Map && b instanceof Map) { 60 if (a.size !== b.size) return false; 61 for (i of a.entries()) 62 if (!b.has(i[0])) return false; 63 for (i of a.entries()) 64 if (!equal(i[1], b.get(i[0]))) return false; 65 return true; 66 } 67 if (a instanceof Set && b instanceof Set) { 68 if (a.size !== b.size) return false; 69 for (i of a.entries()) 70 if (!b.has(i[0])) return false; 71 return true; 72 } 73 if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { 74 length2 = a.length; 75 if (length2 != b.length) return false; 76 for (i = length2; i-- !== 0; ) 77 if (a[i] !== b[i]) return false; 78 return true; 79 } 80 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; 81 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); 82 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); 83 keys2 = Object.keys(a); 84 length2 = keys2.length; 85 if (length2 !== Object.keys(b).length) return false; 86 for (i = length2; i-- !== 0; ) 87 if (!Object.prototype.hasOwnProperty.call(b, keys2[i])) return false; 88 for (i = length2; i-- !== 0; ) { 89 var key = keys2[i]; 90 if (!equal(a[key], b[key])) return false; 91 } 92 return true; 93 } 94 return a !== a && b !== b; 95 }; 96 } 97 }); 98 99 // package-external:@wordpress/compose 100 var require_compose = __commonJS({ 101 "package-external:@wordpress/compose"(exports, module) { 102 module.exports = window.wp.compose; 103 } 104 }); 105 106 // package-external:@wordpress/undo-manager 107 var require_undo_manager = __commonJS({ 108 "package-external:@wordpress/undo-manager"(exports, module) { 109 module.exports = window.wp.undoManager; 110 } 111 }); 112 113 // package-external:@wordpress/api-fetch 114 var require_api_fetch = __commonJS({ 115 "package-external:@wordpress/api-fetch"(exports, module) { 116 module.exports = window.wp.apiFetch; 117 } 118 }); 119 120 // package-external:@wordpress/hooks 121 var require_hooks = __commonJS({ 122 "package-external:@wordpress/hooks"(exports, module) { 123 module.exports = window.wp.hooks; 124 } 125 }); 126 127 // package-external:@wordpress/warning 128 var require_warning = __commonJS({ 129 "package-external:@wordpress/warning"(exports, module) { 130 module.exports = window.wp.warning; 131 } 132 }); 133 134 // package-external:@wordpress/blocks 135 var require_blocks = __commonJS({ 136 "package-external:@wordpress/blocks"(exports, module) { 137 module.exports = window.wp.blocks; 138 } 139 }); 140 141 // package-external:@wordpress/i18n 142 var require_i18n = __commonJS({ 143 "package-external:@wordpress/i18n"(exports, module) { 144 module.exports = window.wp.i18n; 145 } 146 }); 147 148 // package-external:@wordpress/block-editor 149 var require_block_editor = __commonJS({ 150 "package-external:@wordpress/block-editor"(exports, module) { 151 module.exports = window.wp.blockEditor; 152 } 153 }); 154 155 // package-external:@wordpress/private-apis 156 var require_private_apis = __commonJS({ 157 "package-external:@wordpress/private-apis"(exports, module) { 158 module.exports = window.wp.privateApis; 159 } 160 }); 161 162 // package-external:@wordpress/rich-text 163 var require_rich_text = __commonJS({ 164 "package-external:@wordpress/rich-text"(exports, module) { 165 module.exports = window.wp.richText; 166 } 167 }); 168 169 // node_modules/.store/equivalent-key-map@0.2.2-x2CcnsHOWgXkLrIdkTeNmg/node_modules/equivalent-key-map/equivalent-key-map.js 170 var require_equivalent_key_map = __commonJS({ 171 "node_modules/.store/equivalent-key-map@0.2.2-x2CcnsHOWgXkLrIdkTeNmg/node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) { 172 "use strict"; 173 function _typeof(obj) { 174 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { 175 _typeof = function(obj2) { 176 return typeof obj2; 177 }; 178 } else { 179 _typeof = function(obj2) { 180 return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; 181 }; 182 } 183 return _typeof(obj); 184 } 185 function _classCallCheck(instance, Constructor) { 186 if (!(instance instanceof Constructor)) { 187 throw new TypeError("Cannot call a class as a function"); 188 } 189 } 190 function _defineProperties(target, props) { 191 for (var i = 0; i < props.length; i++) { 192 var descriptor = props[i]; 193 descriptor.enumerable = descriptor.enumerable || false; 194 descriptor.configurable = true; 195 if ("value" in descriptor) descriptor.writable = true; 196 Object.defineProperty(target, descriptor.key, descriptor); 197 } 198 } 199 function _createClass(Constructor, protoProps, staticProps) { 200 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 201 if (staticProps) _defineProperties(Constructor, staticProps); 202 return Constructor; 203 } 204 function getValuePair(instance, key) { 205 var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap; 206 if (_map.has(key)) { 207 return _map.get(key); 208 } 209 var properties = Object.keys(key).sort(); 210 var map2 = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap; 211 for (var i = 0; i < properties.length; i++) { 212 var property = properties[i]; 213 map2 = map2.get(property); 214 if (map2 === void 0) { 215 return; 216 } 217 var propertyValue = key[property]; 218 map2 = map2.get(propertyValue); 219 if (map2 === void 0) { 220 return; 221 } 222 } 223 var valuePair = map2.get("_ekm_value"); 224 if (!valuePair) { 225 return; 226 } 227 _map.delete(valuePair[0]); 228 valuePair[0] = key; 229 map2.set("_ekm_value", valuePair); 230 _map.set(key, valuePair); 231 return valuePair; 232 } 233 var EquivalentKeyMap2 = /* @__PURE__ */ (function() { 234 function EquivalentKeyMap3(iterable) { 235 _classCallCheck(this, EquivalentKeyMap3); 236 this.clear(); 237 if (iterable instanceof EquivalentKeyMap3) { 238 var iterablePairs = []; 239 iterable.forEach(function(value, key) { 240 iterablePairs.push([key, value]); 241 }); 242 iterable = iterablePairs; 243 } 244 if (iterable != null) { 245 for (var i = 0; i < iterable.length; i++) { 246 this.set(iterable[i][0], iterable[i][1]); 247 } 248 } 249 } 250 _createClass(EquivalentKeyMap3, [{ 251 key: "set", 252 /** 253 * Add or update an element with a specified key and value. 254 * 255 * @param {*} key The key of the element to add. 256 * @param {*} value The value of the element to add. 257 * 258 * @return {EquivalentKeyMap} Map instance. 259 */ 260 value: function set(key, value) { 261 if (key === null || _typeof(key) !== "object") { 262 this._map.set(key, value); 263 return this; 264 } 265 var properties = Object.keys(key).sort(); 266 var valuePair = [key, value]; 267 var map2 = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap; 268 for (var i = 0; i < properties.length; i++) { 269 var property = properties[i]; 270 if (!map2.has(property)) { 271 map2.set(property, new EquivalentKeyMap3()); 272 } 273 map2 = map2.get(property); 274 var propertyValue = key[property]; 275 if (!map2.has(propertyValue)) { 276 map2.set(propertyValue, new EquivalentKeyMap3()); 277 } 278 map2 = map2.get(propertyValue); 279 } 280 var previousValuePair = map2.get("_ekm_value"); 281 if (previousValuePair) { 282 this._map.delete(previousValuePair[0]); 283 } 284 map2.set("_ekm_value", valuePair); 285 this._map.set(key, valuePair); 286 return this; 287 } 288 /** 289 * Returns a specified element. 290 * 291 * @param {*} key The key of the element to return. 292 * 293 * @return {?*} The element associated with the specified key or undefined 294 * if the key can't be found. 295 */ 296 }, { 297 key: "get", 298 value: function get(key) { 299 if (key === null || _typeof(key) !== "object") { 300 return this._map.get(key); 301 } 302 var valuePair = getValuePair(this, key); 303 if (valuePair) { 304 return valuePair[1]; 305 } 306 } 307 /** 308 * Returns a boolean indicating whether an element with the specified key 309 * exists or not. 310 * 311 * @param {*} key The key of the element to test for presence. 312 * 313 * @return {boolean} Whether an element with the specified key exists. 314 */ 315 }, { 316 key: "has", 317 value: function has(key) { 318 if (key === null || _typeof(key) !== "object") { 319 return this._map.has(key); 320 } 321 return getValuePair(this, key) !== void 0; 322 } 323 /** 324 * Removes the specified element. 325 * 326 * @param {*} key The key of the element to remove. 327 * 328 * @return {boolean} Returns true if an element existed and has been 329 * removed, or false if the element does not exist. 330 */ 331 }, { 332 key: "delete", 333 value: function _delete(key) { 334 if (!this.has(key)) { 335 return false; 336 } 337 this.set(key, void 0); 338 return true; 339 } 340 /** 341 * Executes a provided function once per each key/value pair, in insertion 342 * order. 343 * 344 * @param {Function} callback Function to execute for each element. 345 * @param {*} thisArg Value to use as `this` when executing 346 * `callback`. 347 */ 348 }, { 349 key: "forEach", 350 value: function forEach2(callback) { 351 var _this = this; 352 var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this; 353 this._map.forEach(function(value, key) { 354 if (key !== null && _typeof(key) === "object") { 355 value = value[1]; 356 } 357 callback.call(thisArg, value, key, _this); 358 }); 359 } 360 /** 361 * Removes all elements. 362 */ 363 }, { 364 key: "clear", 365 value: function clear() { 366 this._map = /* @__PURE__ */ new Map(); 367 this._arrayTreeMap = /* @__PURE__ */ new Map(); 368 this._objectTreeMap = /* @__PURE__ */ new Map(); 369 } 370 }, { 371 key: "size", 372 get: function get() { 373 return this._map.size; 374 } 375 }]); 376 return EquivalentKeyMap3; 377 })(); 378 module.exports = EquivalentKeyMap2; 379 } 380 }); 381 382 // package-external:@wordpress/url 383 var require_url = __commonJS({ 384 "package-external:@wordpress/url"(exports, module) { 385 module.exports = window.wp.url; 386 } 387 }); 388 389 // package-external:@wordpress/deprecated 390 var require_deprecated = __commonJS({ 391 "package-external:@wordpress/deprecated"(exports, module) { 392 module.exports = window.wp.deprecated; 393 } 394 }); 395 396 // package-external:@wordpress/notices 397 var require_notices = __commonJS({ 398 "package-external:@wordpress/notices"(exports, module) { 399 module.exports = window.wp.notices; 400 } 401 }); 402 403 // package-external:@wordpress/html-entities 404 var require_html_entities = __commonJS({ 405 "package-external:@wordpress/html-entities"(exports, module) { 406 module.exports = window.wp.htmlEntities; 407 } 408 }); 409 410 // package-external:@wordpress/element 411 var require_element = __commonJS({ 412 "package-external:@wordpress/element"(exports, module) { 413 module.exports = window.wp.element; 414 } 415 }); 416 417 // vendor-external:react/jsx-runtime 418 var require_jsx_runtime = __commonJS({ 419 "vendor-external:react/jsx-runtime"(exports, module) { 420 module.exports = window.ReactJSXRuntime; 421 } 422 }); 423 424 // package-external:@wordpress/primitives 425 var require_primitives = __commonJS({ 426 "package-external:@wordpress/primitives"(exports, module) { 427 module.exports = window.wp.primitives; 428 } 429 }); 430 431 // package-external:@wordpress/components 432 var require_components = __commonJS({ 433 "package-external:@wordpress/components"(exports, module) { 434 module.exports = window.wp.components; 435 } 436 }); 437 438 // packages/core-data/build-module/index.mjs 439 var index_exports = {}; 440 __export(index_exports, { 441 EntityProvider: () => EntityProvider, 442 PrivateEntityProvider: () => PrivateEntityProvider, 443 __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions, 444 __experimentalFetchUrlData: () => experimental_fetch_url_data_default, 445 __experimentalUseEntityRecord: () => useDeprecatedEntityRecord, 446 __experimentalUseEntityRecords: () => useDeprecatedEntityRecords, 447 __experimentalUseResourcePermissions: () => useDeprecatedResourcePermissions, 448 fetchBlockPatterns: () => fetchBlockPatterns, 449 privateApis: () => privateApis, 450 store: () => store, 451 useEntityBlockEditor: () => useEntityBlockEditor, 452 useEntityId: () => useEntityId, 453 useEntityProp: () => useEntityProp, 454 useEntityRecord: () => useEntityRecord, 455 useEntityRecords: () => useEntityRecords, 456 useResourcePermissions: () => use_resource_permissions_default 457 }); 458 var import_data21 = __toESM(require_data(), 1); 459 460 // packages/core-data/build-module/reducer.mjs 461 var import_es68 = __toESM(require_es6(), 1); 462 var import_compose2 = __toESM(require_compose(), 1); 463 var import_data8 = __toESM(require_data(), 1); 464 var import_undo_manager2 = __toESM(require_undo_manager(), 1); 465 466 // packages/core-data/build-module/utils/clear-unchanged-edits.mjs 467 var import_es6 = __toESM(require_es6(), 1); 468 function clearUnchangedEdits(edits, persistedRecord) { 469 if (!persistedRecord) { 470 return edits; 471 } 472 return Object.fromEntries( 473 Object.entries(edits).map(([key, value]) => { 474 const persisted = persistedRecord[key]?.raw ?? persistedRecord[key]; 475 return [ 476 key, 477 (0, import_es6.default)(value, persisted) ? void 0 : value 478 ]; 479 }) 480 ); 481 } 482 483 // packages/core-data/build-module/utils/conservative-map-item.mjs 484 var import_es62 = __toESM(require_es6(), 1); 485 function conservativeMapItem(item, nextItem) { 486 if (!item) { 487 return nextItem; 488 } 489 let hasChanges = false; 490 const result = {}; 491 for (const key in nextItem) { 492 if ((0, import_es62.default)(item[key], nextItem[key])) { 493 result[key] = item[key]; 494 } else { 495 hasChanges = true; 496 result[key] = nextItem[key]; 497 } 498 } 499 if (!hasChanges) { 500 return item; 501 } 502 for (const key in item) { 503 if (!result.hasOwnProperty(key)) { 504 result[key] = item[key]; 505 } 506 } 507 return result; 508 } 509 510 // packages/core-data/build-module/utils/get-normalized-comma-separable.mjs 511 function getNormalizedCommaSeparable(value) { 512 if (typeof value === "string") { 513 return value.split(","); 514 } else if (Array.isArray(value)) { 515 return value; 516 } 517 return null; 518 } 519 var get_normalized_comma_separable_default = getNormalizedCommaSeparable; 520 521 // packages/core-data/build-module/utils/set-nested-value.mjs 522 function setNestedValue(object, path, value) { 523 if (!object || typeof object !== "object") { 524 return object; 525 } 526 const normalizedPath = Array.isArray(path) ? path : path.split("."); 527 normalizedPath.reduce((acc, key, idx) => { 528 if (acc[key] === void 0) { 529 if (Number.isInteger(normalizedPath[idx + 1])) { 530 acc[key] = []; 531 } else { 532 acc[key] = {}; 533 } 534 } 535 if (idx === normalizedPath.length - 1) { 536 acc[key] = value; 537 } 538 return acc[key]; 539 }, object); 540 return object; 541 } 542 543 // packages/core-data/build-module/utils/get-filtered-item.mjs 544 var filteredItemCache = /* @__PURE__ */ new WeakMap(); 545 function getFilteredItem(item, _fields) { 546 const fields = get_normalized_comma_separable_default(_fields) ?? []; 547 const fieldsKey = fields.join(","); 548 let itemCache = filteredItemCache.get(item); 549 if (itemCache) { 550 const filtered = itemCache.get(fieldsKey); 551 if (filtered !== void 0) { 552 return filtered; 553 } 554 } else if (item !== null && typeof item === "object") { 555 itemCache = /* @__PURE__ */ new Map(); 556 filteredItemCache.set(item, itemCache); 557 } 558 const filteredItem = {}; 559 for (let f = 0; f < fields.length; f++) { 560 const field = fields[f].split("."); 561 let value = item; 562 field.forEach((fieldName) => { 563 value = value?.[fieldName]; 564 }); 565 setNestedValue(filteredItem, field, value); 566 } 567 itemCache?.set(fieldsKey, filteredItem); 568 return filteredItem; 569 } 570 571 // packages/core-data/build-module/utils/if-matching-action.mjs 572 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => { 573 if (state === void 0 || isMatch(action)) { 574 return reducer(state, action); 575 } 576 return state; 577 }; 578 var if_matching_action_default = ifMatchingAction; 579 580 // packages/core-data/build-module/utils/forward-resolver.mjs 581 var forwardResolver = (resolverName) => (...args2) => async ({ resolveSelect: resolveSelect3 }) => { 582 await resolveSelect3[resolverName](...args2); 583 }; 584 var forward_resolver_default = forwardResolver; 585 586 // packages/core-data/build-module/utils/replace-action.mjs 587 var replaceAction = (replacer) => (reducer) => (state, action) => { 588 return reducer(state, replacer(action)); 589 }; 590 var replace_action_default = replaceAction; 591 592 // packages/core-data/build-module/utils/with-weak-map-cache.mjs 593 function withWeakMapCache(fn) { 594 const cache3 = /* @__PURE__ */ new WeakMap(); 595 return (key) => { 596 let value; 597 if (cache3.has(key)) { 598 value = cache3.get(key); 599 } else { 600 value = fn(key); 601 if (key !== null && typeof key === "object") { 602 cache3.set(key, value); 603 } 604 } 605 return value; 606 }; 607 } 608 var with_weak_map_cache_default = withWeakMapCache; 609 610 // packages/core-data/build-module/utils/get-nested-value.mjs 611 function getNestedValue(object, path, defaultValue) { 612 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) { 613 return object; 614 } 615 const normalizedPath = Array.isArray(path) ? path : path.split("."); 616 let value = object; 617 normalizedPath.forEach((fieldName) => { 618 value = value?.[fieldName]; 619 }); 620 return value !== void 0 ? value : defaultValue; 621 } 622 623 // packages/core-data/build-module/utils/is-numeric-id.mjs 624 function isNumericID(id2) { 625 return /^\s*\d+\s*$/.test(id2); 626 } 627 628 // packages/core-data/build-module/utils/is-safe-entity-key.mjs 629 var UNSAFE_CHARACTERS = /[?#&\\\x00-\x1f\x7f]/; 630 function isSafeEntityKey(key) { 631 if (key === null || key === void 0 || typeof key === "number") { 632 return true; 633 } 634 if (typeof key !== "string") { 635 return false; 636 } 637 if (/%2f/i.test(key)) { 638 return false; 639 } 640 const decoded = key.replace( 641 /%([0-7][0-9a-f])/gi, 642 (match2, hex) => String.fromCharCode(parseInt(hex, 16)) 643 ); 644 if (UNSAFE_CHARACTERS.test(decoded)) { 645 return false; 646 } 647 return decoded.split("/").every((segment) => segment !== "." && segment !== ".."); 648 } 649 650 // packages/core-data/build-module/utils/user-permissions.mjs 651 var ALLOWED_RESOURCE_ACTIONS = [ 652 "create", 653 "read", 654 "update", 655 "delete" 656 ]; 657 function getUserPermissionsFromAllowHeader(allowedMethods) { 658 const permissions = {}; 659 const methods = { 660 create: "POST", 661 read: "GET", 662 update: "PUT", 663 delete: "DELETE" 664 }; 665 for (const [actionName, methodName] of Object.entries(methods)) { 666 permissions[actionName] = allowedMethods ? allowedMethods.includes(methodName) : false; 667 } 668 return permissions; 669 } 670 function getUserPermissionCacheKey(action, resource, id2) { 671 const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id2]).filter(Boolean).join("/"); 672 return key; 673 } 674 675 // packages/core-data/build-module/utils/receive-intermediate-results.mjs 676 var RECEIVE_INTERMEDIATE_RESULTS = /* @__PURE__ */ Symbol( 677 "RECEIVE_INTERMEDIATE_RESULTS" 678 ); 679 680 // packages/core-data/build-module/utils/normalize-query-for-resolution.mjs 681 function normalizeQueryForResolution(query) { 682 if (!query) { 683 return void 0; 684 } 685 const entries = Object.entries(query).filter( 686 ([k, v]) => (k === "context" || k === "_fields") && v !== void 0 && v !== null 687 ); 688 return entries.length > 0 ? Object.fromEntries(entries) : void 0; 689 } 690 691 // packages/core-data/build-module/utils/save-crdt-doc.mjs 692 var import_api_fetch3 = __toESM(require_api_fetch(), 1); 693 694 // packages/core-data/build-module/sync.mjs 695 var import_es67 = __toESM(require_es6(), 1); 696 var import_data6 = __toESM(require_data(), 1); 697 698 // node_modules/.store/yjs@13.6.29-TJYJpNVE3l2_hFsy5BI5FA/node_modules/yjs/dist/yjs.mjs 699 var yjs_exports = {}; 700 __export(yjs_exports, { 701 AbsolutePosition: () => AbsolutePosition, 702 AbstractConnector: () => AbstractConnector, 703 AbstractStruct: () => AbstractStruct, 704 AbstractType: () => AbstractType, 705 Array: () => YArray, 706 ContentAny: () => ContentAny, 707 ContentBinary: () => ContentBinary, 708 ContentDeleted: () => ContentDeleted, 709 ContentDoc: () => ContentDoc, 710 ContentEmbed: () => ContentEmbed, 711 ContentFormat: () => ContentFormat, 712 ContentJSON: () => ContentJSON, 713 ContentString: () => ContentString, 714 ContentType: () => ContentType, 715 Doc: () => Doc, 716 GC: () => GC, 717 ID: () => ID, 718 Item: () => Item, 719 Map: () => YMap, 720 PermanentUserData: () => PermanentUserData, 721 RelativePosition: () => RelativePosition, 722 Skip: () => Skip, 723 Snapshot: () => Snapshot, 724 Text: () => YText, 725 Transaction: () => Transaction, 726 UndoManager: () => UndoManager, 727 UpdateDecoderV1: () => UpdateDecoderV1, 728 UpdateDecoderV2: () => UpdateDecoderV2, 729 UpdateEncoderV1: () => UpdateEncoderV1, 730 UpdateEncoderV2: () => UpdateEncoderV2, 731 XmlElement: () => YXmlElement, 732 XmlFragment: () => YXmlFragment, 733 XmlHook: () => YXmlHook, 734 XmlText: () => YXmlText, 735 YArrayEvent: () => YArrayEvent, 736 YEvent: () => YEvent, 737 YMapEvent: () => YMapEvent, 738 YTextEvent: () => YTextEvent, 739 YXmlEvent: () => YXmlEvent, 740 applyUpdate: () => applyUpdate, 741 applyUpdateV2: () => applyUpdateV2, 742 cleanupYTextFormatting: () => cleanupYTextFormatting, 743 compareIDs: () => compareIDs, 744 compareRelativePositions: () => compareRelativePositions, 745 convertUpdateFormatV1ToV2: () => convertUpdateFormatV1ToV2, 746 convertUpdateFormatV2ToV1: () => convertUpdateFormatV2ToV1, 747 createAbsolutePositionFromRelativePosition: () => createAbsolutePositionFromRelativePosition, 748 createDeleteSet: () => createDeleteSet, 749 createDeleteSetFromStructStore: () => createDeleteSetFromStructStore, 750 createDocFromSnapshot: () => createDocFromSnapshot, 751 createID: () => createID, 752 createRelativePositionFromJSON: () => createRelativePositionFromJSON, 753 createRelativePositionFromTypeIndex: () => createRelativePositionFromTypeIndex, 754 createSnapshot: () => createSnapshot, 755 decodeRelativePosition: () => decodeRelativePosition, 756 decodeSnapshot: () => decodeSnapshot, 757 decodeSnapshotV2: () => decodeSnapshotV2, 758 decodeStateVector: () => decodeStateVector, 759 decodeUpdate: () => decodeUpdate, 760 decodeUpdateV2: () => decodeUpdateV2, 761 diffUpdate: () => diffUpdate, 762 diffUpdateV2: () => diffUpdateV2, 763 emptySnapshot: () => emptySnapshot, 764 encodeRelativePosition: () => encodeRelativePosition, 765 encodeSnapshot: () => encodeSnapshot, 766 encodeSnapshotV2: () => encodeSnapshotV2, 767 encodeStateAsUpdate: () => encodeStateAsUpdate, 768 encodeStateAsUpdateV2: () => encodeStateAsUpdateV2, 769 encodeStateVector: () => encodeStateVector, 770 encodeStateVectorFromUpdate: () => encodeStateVectorFromUpdate, 771 encodeStateVectorFromUpdateV2: () => encodeStateVectorFromUpdateV2, 772 equalDeleteSets: () => equalDeleteSets, 773 equalSnapshots: () => equalSnapshots, 774 findIndexSS: () => findIndexSS, 775 findRootTypeKey: () => findRootTypeKey, 776 getItem: () => getItem, 777 getItemCleanEnd: () => getItemCleanEnd, 778 getItemCleanStart: () => getItemCleanStart, 779 getState: () => getState, 780 getTypeChildren: () => getTypeChildren, 781 isDeleted: () => isDeleted, 782 isParentOf: () => isParentOf, 783 iterateDeletedStructs: () => iterateDeletedStructs, 784 logType: () => logType, 785 logUpdate: () => logUpdate, 786 logUpdateV2: () => logUpdateV2, 787 mergeDeleteSets: () => mergeDeleteSets, 788 mergeUpdates: () => mergeUpdates, 789 mergeUpdatesV2: () => mergeUpdatesV2, 790 obfuscateUpdate: () => obfuscateUpdate, 791 obfuscateUpdateV2: () => obfuscateUpdateV2, 792 parseUpdateMeta: () => parseUpdateMeta, 793 parseUpdateMetaV2: () => parseUpdateMetaV2, 794 readUpdate: () => readUpdate, 795 readUpdateV2: () => readUpdateV2, 796 relativePositionToJSON: () => relativePositionToJSON, 797 snapshot: () => snapshot, 798 snapshotContainsUpdate: () => snapshotContainsUpdate, 799 transact: () => transact, 800 tryGc: () => tryGc, 801 typeListToArraySnapshot: () => typeListToArraySnapshot, 802 typeMapGetAllSnapshot: () => typeMapGetAllSnapshot, 803 typeMapGetSnapshot: () => typeMapGetSnapshot 804 }); 805 806 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/map.js 807 var create = () => /* @__PURE__ */ new Map(); 808 var copy = (m) => { 809 const r2 = create(); 810 m.forEach((v, k) => { 811 r2.set(k, v); 812 }); 813 return r2; 814 }; 815 var setIfUndefined = (map2, key, createT) => { 816 let set = map2.get(key); 817 if (set === void 0) { 818 map2.set(key, set = createT()); 819 } 820 return set; 821 }; 822 var map = (m, f) => { 823 const res = []; 824 for (const [key, value] of m) { 825 res.push(f(value, key)); 826 } 827 return res; 828 }; 829 var any = (m, f) => { 830 for (const [key, value] of m) { 831 if (f(value, key)) { 832 return true; 833 } 834 } 835 return false; 836 }; 837 838 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/set.js 839 var create2 = () => /* @__PURE__ */ new Set(); 840 841 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/array.js 842 var last = (arr) => arr[arr.length - 1]; 843 var appendTo = (dest, src) => { 844 for (let i = 0; i < src.length; i++) { 845 dest.push(src[i]); 846 } 847 }; 848 var from = Array.from; 849 var every = (arr, f) => { 850 for (let i = 0; i < arr.length; i++) { 851 if (!f(arr[i], i, arr)) { 852 return false; 853 } 854 } 855 return true; 856 }; 857 var some = (arr, f) => { 858 for (let i = 0; i < arr.length; i++) { 859 if (f(arr[i], i, arr)) { 860 return true; 861 } 862 } 863 return false; 864 }; 865 var unfold = (len, f) => { 866 const array = new Array(len); 867 for (let i = 0; i < len; i++) { 868 array[i] = f(i, array); 869 } 870 return array; 871 }; 872 var isArray = Array.isArray; 873 874 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/observable.js 875 var ObservableV2 = class { 876 constructor() { 877 this._observers = create(); 878 } 879 /** 880 * @template {keyof EVENTS & string} NAME 881 * @param {NAME} name 882 * @param {EVENTS[NAME]} f 883 */ 884 on(name, f) { 885 setIfUndefined( 886 this._observers, 887 /** @type {string} */ 888 name, 889 create2 890 ).add(f); 891 return f; 892 } 893 /** 894 * @template {keyof EVENTS & string} NAME 895 * @param {NAME} name 896 * @param {EVENTS[NAME]} f 897 */ 898 once(name, f) { 899 const _f = (...args2) => { 900 this.off( 901 name, 902 /** @type {any} */ 903 _f 904 ); 905 f(...args2); 906 }; 907 this.on( 908 name, 909 /** @type {any} */ 910 _f 911 ); 912 } 913 /** 914 * @template {keyof EVENTS & string} NAME 915 * @param {NAME} name 916 * @param {EVENTS[NAME]} f 917 */ 918 off(name, f) { 919 const observers = this._observers.get(name); 920 if (observers !== void 0) { 921 observers.delete(f); 922 if (observers.size === 0) { 923 this._observers.delete(name); 924 } 925 } 926 } 927 /** 928 * Emit a named event. All registered event listeners that listen to the 929 * specified name will receive the event. 930 * 931 * @todo This should catch exceptions 932 * 933 * @template {keyof EVENTS & string} NAME 934 * @param {NAME} name The event name. 935 * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener. 936 */ 937 emit(name, args2) { 938 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2)); 939 } 940 destroy() { 941 this._observers = create(); 942 } 943 }; 944 var Observable = class { 945 constructor() { 946 this._observers = create(); 947 } 948 /** 949 * @param {N} name 950 * @param {function} f 951 */ 952 on(name, f) { 953 setIfUndefined(this._observers, name, create2).add(f); 954 } 955 /** 956 * @param {N} name 957 * @param {function} f 958 */ 959 once(name, f) { 960 const _f = (...args2) => { 961 this.off(name, _f); 962 f(...args2); 963 }; 964 this.on(name, _f); 965 } 966 /** 967 * @param {N} name 968 * @param {function} f 969 */ 970 off(name, f) { 971 const observers = this._observers.get(name); 972 if (observers !== void 0) { 973 observers.delete(f); 974 if (observers.size === 0) { 975 this._observers.delete(name); 976 } 977 } 978 } 979 /** 980 * Emit a named event. All registered event listeners that listen to the 981 * specified name will receive the event. 982 * 983 * @todo This should catch exceptions 984 * 985 * @param {N} name The event name. 986 * @param {Array<any>} args The arguments that are applied to the event listener. 987 */ 988 emit(name, args2) { 989 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2)); 990 } 991 destroy() { 992 this._observers = create(); 993 } 994 }; 995 996 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/math.js 997 var floor = Math.floor; 998 var abs = Math.abs; 999 var min = (a, b) => a < b ? a : b; 1000 var max = (a, b) => a > b ? a : b; 1001 var isNaN2 = Number.isNaN; 1002 var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0; 1003 1004 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/binary.js 1005 var BIT1 = 1; 1006 var BIT2 = 2; 1007 var BIT3 = 4; 1008 var BIT4 = 8; 1009 var BIT6 = 32; 1010 var BIT7 = 64; 1011 var BIT8 = 128; 1012 var BIT18 = 1 << 17; 1013 var BIT19 = 1 << 18; 1014 var BIT20 = 1 << 19; 1015 var BIT21 = 1 << 20; 1016 var BIT22 = 1 << 21; 1017 var BIT23 = 1 << 22; 1018 var BIT24 = 1 << 23; 1019 var BIT25 = 1 << 24; 1020 var BIT26 = 1 << 25; 1021 var BIT27 = 1 << 26; 1022 var BIT28 = 1 << 27; 1023 var BIT29 = 1 << 28; 1024 var BIT30 = 1 << 29; 1025 var BIT31 = 1 << 30; 1026 var BIT32 = 1 << 31; 1027 var BITS5 = 31; 1028 var BITS6 = 63; 1029 var BITS7 = 127; 1030 var BITS17 = BIT18 - 1; 1031 var BITS18 = BIT19 - 1; 1032 var BITS19 = BIT20 - 1; 1033 var BITS20 = BIT21 - 1; 1034 var BITS21 = BIT22 - 1; 1035 var BITS22 = BIT23 - 1; 1036 var BITS23 = BIT24 - 1; 1037 var BITS24 = BIT25 - 1; 1038 var BITS25 = BIT26 - 1; 1039 var BITS26 = BIT27 - 1; 1040 var BITS27 = BIT28 - 1; 1041 var BITS28 = BIT29 - 1; 1042 var BITS29 = BIT30 - 1; 1043 var BITS30 = BIT31 - 1; 1044 var BITS31 = 2147483647; 1045 1046 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/number.js 1047 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; 1048 var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; 1049 var LOWEST_INT32 = 1 << 31; 1050 var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num); 1051 var isNaN3 = Number.isNaN; 1052 var parseInt2 = Number.parseInt; 1053 1054 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/string.js 1055 var fromCharCode = String.fromCharCode; 1056 var fromCodePoint = String.fromCodePoint; 1057 var MAX_UTF16_CHARACTER = fromCharCode(65535); 1058 var toLowerCase = (s) => s.toLowerCase(); 1059 var trimLeftRegex = /^\s*/g; 1060 var trimLeft = (s) => s.replace(trimLeftRegex, ""); 1061 var fromCamelCaseRegex = /([A-Z])/g; 1062 var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match2) => `$separator}$toLowerCase(match2)}`)); 1063 var _encodeUtf8Polyfill = (str) => { 1064 const encodedString = unescape(encodeURIComponent(str)); 1065 const len = encodedString.length; 1066 const buf = new Uint8Array(len); 1067 for (let i = 0; i < len; i++) { 1068 buf[i] = /** @type {number} */ 1069 encodedString.codePointAt(i); 1070 } 1071 return buf; 1072 }; 1073 var utf8TextEncoder = ( 1074 /** @type {TextEncoder} */ 1075 typeof TextEncoder !== "undefined" ? new TextEncoder() : null 1076 ); 1077 var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str); 1078 var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; 1079 var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); 1080 if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { 1081 utf8TextDecoder = null; 1082 } 1083 var repeat = (source, n) => unfold(n, () => source).join(""); 1084 1085 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/encoding.js 1086 var Encoder = class { 1087 constructor() { 1088 this.cpos = 0; 1089 this.cbuf = new Uint8Array(100); 1090 this.bufs = []; 1091 } 1092 }; 1093 var createEncoder = () => new Encoder(); 1094 var length = (encoder) => { 1095 let len = encoder.cpos; 1096 for (let i = 0; i < encoder.bufs.length; i++) { 1097 len += encoder.bufs[i].length; 1098 } 1099 return len; 1100 }; 1101 var toUint8Array = (encoder) => { 1102 const uint8arr = new Uint8Array(length(encoder)); 1103 let curPos = 0; 1104 for (let i = 0; i < encoder.bufs.length; i++) { 1105 const d = encoder.bufs[i]; 1106 uint8arr.set(d, curPos); 1107 curPos += d.length; 1108 } 1109 uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos); 1110 return uint8arr; 1111 }; 1112 var verifyLen = (encoder, len) => { 1113 const bufferLen = encoder.cbuf.length; 1114 if (bufferLen - encoder.cpos < len) { 1115 encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)); 1116 encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); 1117 encoder.cpos = 0; 1118 } 1119 }; 1120 var write = (encoder, num) => { 1121 const bufferLen = encoder.cbuf.length; 1122 if (encoder.cpos === bufferLen) { 1123 encoder.bufs.push(encoder.cbuf); 1124 encoder.cbuf = new Uint8Array(bufferLen * 2); 1125 encoder.cpos = 0; 1126 } 1127 encoder.cbuf[encoder.cpos++] = num; 1128 }; 1129 var writeUint8 = write; 1130 var writeVarUint = (encoder, num) => { 1131 while (num > BITS7) { 1132 write(encoder, BIT8 | BITS7 & num); 1133 num = floor(num / 128); 1134 } 1135 write(encoder, BITS7 & num); 1136 }; 1137 var writeVarInt = (encoder, num) => { 1138 const isNegative = isNegativeZero(num); 1139 if (isNegative) { 1140 num = -num; 1141 } 1142 write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num); 1143 num = floor(num / 64); 1144 while (num > 0) { 1145 write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num); 1146 num = floor(num / 128); 1147 } 1148 }; 1149 var _strBuffer = new Uint8Array(3e4); 1150 var _maxStrBSize = _strBuffer.length / 3; 1151 var _writeVarStringNative = (encoder, str) => { 1152 if (str.length < _maxStrBSize) { 1153 const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; 1154 writeVarUint(encoder, written); 1155 for (let i = 0; i < written; i++) { 1156 write(encoder, _strBuffer[i]); 1157 } 1158 } else { 1159 writeVarUint8Array(encoder, encodeUtf8(str)); 1160 } 1161 }; 1162 var _writeVarStringPolyfill = (encoder, str) => { 1163 const encodedString = unescape(encodeURIComponent(str)); 1164 const len = encodedString.length; 1165 writeVarUint(encoder, len); 1166 for (let i = 0; i < len; i++) { 1167 write( 1168 encoder, 1169 /** @type {number} */ 1170 encodedString.codePointAt(i) 1171 ); 1172 } 1173 }; 1174 var writeVarString = utf8TextEncoder && /** @type {any} */ 1175 utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill; 1176 var writeBinaryEncoder = (encoder, append2) => writeUint8Array(encoder, toUint8Array(append2)); 1177 var writeUint8Array = (encoder, uint8Array) => { 1178 const bufferLen = encoder.cbuf.length; 1179 const cpos = encoder.cpos; 1180 const leftCopyLen = min(bufferLen - cpos, uint8Array.length); 1181 const rightCopyLen = uint8Array.length - leftCopyLen; 1182 encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); 1183 encoder.cpos += leftCopyLen; 1184 if (rightCopyLen > 0) { 1185 encoder.bufs.push(encoder.cbuf); 1186 encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); 1187 encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); 1188 encoder.cpos = rightCopyLen; 1189 } 1190 }; 1191 var writeVarUint8Array = (encoder, uint8Array) => { 1192 writeVarUint(encoder, uint8Array.byteLength); 1193 writeUint8Array(encoder, uint8Array); 1194 }; 1195 var writeOnDataView = (encoder, len) => { 1196 verifyLen(encoder, len); 1197 const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); 1198 encoder.cpos += len; 1199 return dview; 1200 }; 1201 var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); 1202 var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); 1203 var writeBigInt64 = (encoder, num) => ( 1204 /** @type {any} */ 1205 writeOnDataView(encoder, 8).setBigInt64(0, num, false) 1206 ); 1207 var floatTestBed = new DataView(new ArrayBuffer(4)); 1208 var isFloat32 = (num) => { 1209 floatTestBed.setFloat32(0, num); 1210 return floatTestBed.getFloat32(0) === num; 1211 }; 1212 var writeAny = (encoder, data) => { 1213 switch (typeof data) { 1214 case "string": 1215 write(encoder, 119); 1216 writeVarString(encoder, data); 1217 break; 1218 case "number": 1219 if (isInteger(data) && abs(data) <= BITS31) { 1220 write(encoder, 125); 1221 writeVarInt(encoder, data); 1222 } else if (isFloat32(data)) { 1223 write(encoder, 124); 1224 writeFloat32(encoder, data); 1225 } else { 1226 write(encoder, 123); 1227 writeFloat64(encoder, data); 1228 } 1229 break; 1230 case "bigint": 1231 write(encoder, 122); 1232 writeBigInt64(encoder, data); 1233 break; 1234 case "object": 1235 if (data === null) { 1236 write(encoder, 126); 1237 } else if (isArray(data)) { 1238 write(encoder, 117); 1239 writeVarUint(encoder, data.length); 1240 for (let i = 0; i < data.length; i++) { 1241 writeAny(encoder, data[i]); 1242 } 1243 } else if (data instanceof Uint8Array) { 1244 write(encoder, 116); 1245 writeVarUint8Array(encoder, data); 1246 } else { 1247 write(encoder, 118); 1248 const keys2 = Object.keys(data); 1249 writeVarUint(encoder, keys2.length); 1250 for (let i = 0; i < keys2.length; i++) { 1251 const key = keys2[i]; 1252 writeVarString(encoder, key); 1253 writeAny(encoder, data[key]); 1254 } 1255 } 1256 break; 1257 case "boolean": 1258 write(encoder, data ? 120 : 121); 1259 break; 1260 default: 1261 write(encoder, 127); 1262 } 1263 }; 1264 var RleEncoder = class extends Encoder { 1265 /** 1266 * @param {function(Encoder, T):void} writer 1267 */ 1268 constructor(writer) { 1269 super(); 1270 this.w = writer; 1271 this.s = null; 1272 this.count = 0; 1273 } 1274 /** 1275 * @param {T} v 1276 */ 1277 write(v) { 1278 if (this.s === v) { 1279 this.count++; 1280 } else { 1281 if (this.count > 0) { 1282 writeVarUint(this, this.count - 1); 1283 } 1284 this.count = 1; 1285 this.w(this, v); 1286 this.s = v; 1287 } 1288 } 1289 }; 1290 var flushUintOptRleEncoder = (encoder) => { 1291 if (encoder.count > 0) { 1292 writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); 1293 if (encoder.count > 1) { 1294 writeVarUint(encoder.encoder, encoder.count - 2); 1295 } 1296 } 1297 }; 1298 var UintOptRleEncoder = class { 1299 constructor() { 1300 this.encoder = new Encoder(); 1301 this.s = 0; 1302 this.count = 0; 1303 } 1304 /** 1305 * @param {number} v 1306 */ 1307 write(v) { 1308 if (this.s === v) { 1309 this.count++; 1310 } else { 1311 flushUintOptRleEncoder(this); 1312 this.count = 1; 1313 this.s = v; 1314 } 1315 } 1316 /** 1317 * Flush the encoded state and transform this to a Uint8Array. 1318 * 1319 * Note that this should only be called once. 1320 */ 1321 toUint8Array() { 1322 flushUintOptRleEncoder(this); 1323 return toUint8Array(this.encoder); 1324 } 1325 }; 1326 var flushIntDiffOptRleEncoder = (encoder) => { 1327 if (encoder.count > 0) { 1328 const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); 1329 writeVarInt(encoder.encoder, encodedDiff); 1330 if (encoder.count > 1) { 1331 writeVarUint(encoder.encoder, encoder.count - 2); 1332 } 1333 } 1334 }; 1335 var IntDiffOptRleEncoder = class { 1336 constructor() { 1337 this.encoder = new Encoder(); 1338 this.s = 0; 1339 this.count = 0; 1340 this.diff = 0; 1341 } 1342 /** 1343 * @param {number} v 1344 */ 1345 write(v) { 1346 if (this.diff === v - this.s) { 1347 this.s = v; 1348 this.count++; 1349 } else { 1350 flushIntDiffOptRleEncoder(this); 1351 this.count = 1; 1352 this.diff = v - this.s; 1353 this.s = v; 1354 } 1355 } 1356 /** 1357 * Flush the encoded state and transform this to a Uint8Array. 1358 * 1359 * Note that this should only be called once. 1360 */ 1361 toUint8Array() { 1362 flushIntDiffOptRleEncoder(this); 1363 return toUint8Array(this.encoder); 1364 } 1365 }; 1366 var StringEncoder = class { 1367 constructor() { 1368 this.sarr = []; 1369 this.s = ""; 1370 this.lensE = new UintOptRleEncoder(); 1371 } 1372 /** 1373 * @param {string} string 1374 */ 1375 write(string) { 1376 this.s += string; 1377 if (this.s.length > 19) { 1378 this.sarr.push(this.s); 1379 this.s = ""; 1380 } 1381 this.lensE.write(string.length); 1382 } 1383 toUint8Array() { 1384 const encoder = new Encoder(); 1385 this.sarr.push(this.s); 1386 this.s = ""; 1387 writeVarString(encoder, this.sarr.join("")); 1388 writeUint8Array(encoder, this.lensE.toUint8Array()); 1389 return toUint8Array(encoder); 1390 } 1391 }; 1392 1393 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/error.js 1394 var create3 = (s) => new Error(s); 1395 var methodUnimplemented = () => { 1396 throw create3("Method unimplemented"); 1397 }; 1398 var unexpectedCase = () => { 1399 throw create3("Unexpected case"); 1400 }; 1401 1402 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/decoding.js 1403 var errorUnexpectedEndOfArray = create3("Unexpected end of array"); 1404 var errorIntegerOutOfRange = create3("Integer out of Range"); 1405 var Decoder = class { 1406 /** 1407 * @param {Uint8Array<Buf>} uint8Array Binary data to decode 1408 */ 1409 constructor(uint8Array) { 1410 this.arr = uint8Array; 1411 this.pos = 0; 1412 } 1413 }; 1414 var createDecoder = (uint8Array) => new Decoder(uint8Array); 1415 var hasContent = (decoder) => decoder.pos !== decoder.arr.length; 1416 var readUint8Array = (decoder, len) => { 1417 const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); 1418 decoder.pos += len; 1419 return view; 1420 }; 1421 var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder)); 1422 var readUint8 = (decoder) => decoder.arr[decoder.pos++]; 1423 var readVarUint = (decoder) => { 1424 let num = 0; 1425 let mult = 1; 1426 const len = decoder.arr.length; 1427 while (decoder.pos < len) { 1428 const r2 = decoder.arr[decoder.pos++]; 1429 num = num + (r2 & BITS7) * mult; 1430 mult *= 128; 1431 if (r2 < BIT8) { 1432 return num; 1433 } 1434 if (num > MAX_SAFE_INTEGER) { 1435 throw errorIntegerOutOfRange; 1436 } 1437 } 1438 throw errorUnexpectedEndOfArray; 1439 }; 1440 var readVarInt = (decoder) => { 1441 let r2 = decoder.arr[decoder.pos++]; 1442 let num = r2 & BITS6; 1443 let mult = 64; 1444 const sign = (r2 & BIT7) > 0 ? -1 : 1; 1445 if ((r2 & BIT8) === 0) { 1446 return sign * num; 1447 } 1448 const len = decoder.arr.length; 1449 while (decoder.pos < len) { 1450 r2 = decoder.arr[decoder.pos++]; 1451 num = num + (r2 & BITS7) * mult; 1452 mult *= 128; 1453 if (r2 < BIT8) { 1454 return sign * num; 1455 } 1456 if (num > MAX_SAFE_INTEGER) { 1457 throw errorIntegerOutOfRange; 1458 } 1459 } 1460 throw errorUnexpectedEndOfArray; 1461 }; 1462 var _readVarStringPolyfill = (decoder) => { 1463 let remainingLen = readVarUint(decoder); 1464 if (remainingLen === 0) { 1465 return ""; 1466 } else { 1467 let encodedString = String.fromCodePoint(readUint8(decoder)); 1468 if (--remainingLen < 100) { 1469 while (remainingLen--) { 1470 encodedString += String.fromCodePoint(readUint8(decoder)); 1471 } 1472 } else { 1473 while (remainingLen > 0) { 1474 const nextLen = remainingLen < 1e4 ? remainingLen : 1e4; 1475 const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); 1476 decoder.pos += nextLen; 1477 encodedString += String.fromCodePoint.apply( 1478 null, 1479 /** @type {any} */ 1480 bytes 1481 ); 1482 remainingLen -= nextLen; 1483 } 1484 } 1485 return decodeURIComponent(escape(encodedString)); 1486 } 1487 }; 1488 var _readVarStringNative = (decoder) => ( 1489 /** @type any */ 1490 utf8TextDecoder.decode(readVarUint8Array(decoder)) 1491 ); 1492 var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; 1493 var readFromDataView = (decoder, len) => { 1494 const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); 1495 decoder.pos += len; 1496 return dv; 1497 }; 1498 var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false); 1499 var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false); 1500 var readBigInt64 = (decoder) => ( 1501 /** @type {any} */ 1502 readFromDataView(decoder, 8).getBigInt64(0, false) 1503 ); 1504 var readAnyLookupTable = [ 1505 (decoder) => void 0, 1506 // CASE 127: undefined 1507 (decoder) => null, 1508 // CASE 126: null 1509 readVarInt, 1510 // CASE 125: integer 1511 readFloat32, 1512 // CASE 124: float32 1513 readFloat64, 1514 // CASE 123: float64 1515 readBigInt64, 1516 // CASE 122: bigint 1517 (decoder) => false, 1518 // CASE 121: boolean (false) 1519 (decoder) => true, 1520 // CASE 120: boolean (true) 1521 readVarString, 1522 // CASE 119: string 1523 (decoder) => { 1524 const len = readVarUint(decoder); 1525 const obj = {}; 1526 for (let i = 0; i < len; i++) { 1527 const key = readVarString(decoder); 1528 obj[key] = readAny(decoder); 1529 } 1530 return obj; 1531 }, 1532 (decoder) => { 1533 const len = readVarUint(decoder); 1534 const arr = []; 1535 for (let i = 0; i < len; i++) { 1536 arr.push(readAny(decoder)); 1537 } 1538 return arr; 1539 }, 1540 readVarUint8Array 1541 // CASE 116: Uint8Array 1542 ]; 1543 var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder); 1544 var RleDecoder = class extends Decoder { 1545 /** 1546 * @param {Uint8Array} uint8Array 1547 * @param {function(Decoder):T} reader 1548 */ 1549 constructor(uint8Array, reader) { 1550 super(uint8Array); 1551 this.reader = reader; 1552 this.s = null; 1553 this.count = 0; 1554 } 1555 read() { 1556 if (this.count === 0) { 1557 this.s = this.reader(this); 1558 if (hasContent(this)) { 1559 this.count = readVarUint(this) + 1; 1560 } else { 1561 this.count = -1; 1562 } 1563 } 1564 this.count--; 1565 return ( 1566 /** @type {T} */ 1567 this.s 1568 ); 1569 } 1570 }; 1571 var UintOptRleDecoder = class extends Decoder { 1572 /** 1573 * @param {Uint8Array} uint8Array 1574 */ 1575 constructor(uint8Array) { 1576 super(uint8Array); 1577 this.s = 0; 1578 this.count = 0; 1579 } 1580 read() { 1581 if (this.count === 0) { 1582 this.s = readVarInt(this); 1583 const isNegative = isNegativeZero(this.s); 1584 this.count = 1; 1585 if (isNegative) { 1586 this.s = -this.s; 1587 this.count = readVarUint(this) + 2; 1588 } 1589 } 1590 this.count--; 1591 return ( 1592 /** @type {number} */ 1593 this.s 1594 ); 1595 } 1596 }; 1597 var IntDiffOptRleDecoder = class extends Decoder { 1598 /** 1599 * @param {Uint8Array} uint8Array 1600 */ 1601 constructor(uint8Array) { 1602 super(uint8Array); 1603 this.s = 0; 1604 this.count = 0; 1605 this.diff = 0; 1606 } 1607 /** 1608 * @return {number} 1609 */ 1610 read() { 1611 if (this.count === 0) { 1612 const diff = readVarInt(this); 1613 const hasCount = diff & 1; 1614 this.diff = floor(diff / 2); 1615 this.count = 1; 1616 if (hasCount) { 1617 this.count = readVarUint(this) + 2; 1618 } 1619 } 1620 this.s += this.diff; 1621 this.count--; 1622 return this.s; 1623 } 1624 }; 1625 var StringDecoder = class { 1626 /** 1627 * @param {Uint8Array} uint8Array 1628 */ 1629 constructor(uint8Array) { 1630 this.decoder = new UintOptRleDecoder(uint8Array); 1631 this.str = readVarString(this.decoder); 1632 this.spos = 0; 1633 } 1634 /** 1635 * @return {string} 1636 */ 1637 read() { 1638 const end = this.spos + this.decoder.read(); 1639 const res = this.str.slice(this.spos, end); 1640 this.spos = end; 1641 return res; 1642 } 1643 }; 1644 1645 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/webcrypto.js 1646 var subtle = crypto.subtle; 1647 var getRandomValues = crypto.getRandomValues.bind(crypto); 1648 1649 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/random.js 1650 var uint32 = () => getRandomValues(new Uint32Array(1))[0]; 1651 var uuidv4Template = "10000000-1000-4000-8000" + -1e11; 1652 var uuidv4 = () => uuidv4Template.replace( 1653 /[018]/g, 1654 /** @param {number} c */ 1655 (c) => (c ^ uint32() & 15 >> c / 4).toString(16) 1656 ); 1657 1658 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/time.js 1659 var getUnixTime = Date.now; 1660 1661 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/promise.js 1662 var create4 = (f) => ( 1663 /** @type {Promise<T>} */ 1664 new Promise(f) 1665 ); 1666 var all = Promise.all.bind(Promise); 1667 1668 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/conditions.js 1669 var undefinedToNull = (v) => v === void 0 ? null : v; 1670 1671 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/storage.js 1672 var VarStoragePolyfill = class { 1673 constructor() { 1674 this.map = /* @__PURE__ */ new Map(); 1675 } 1676 /** 1677 * @param {string} key 1678 * @param {any} newValue 1679 */ 1680 setItem(key, newValue) { 1681 this.map.set(key, newValue); 1682 } 1683 /** 1684 * @param {string} key 1685 */ 1686 getItem(key) { 1687 return this.map.get(key); 1688 } 1689 }; 1690 var _localStorage = new VarStoragePolyfill(); 1691 var usePolyfill = true; 1692 try { 1693 if (typeof localStorage !== "undefined" && localStorage) { 1694 _localStorage = localStorage; 1695 usePolyfill = false; 1696 } 1697 } catch (e) { 1698 } 1699 var varStorage = _localStorage; 1700 1701 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/trait/equality.js 1702 var EqualityTraitSymbol = /* @__PURE__ */ Symbol("Equality"); 1703 var equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false; 1704 1705 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/object.js 1706 var isObject = (o) => typeof o === "object"; 1707 var assign = Object.assign; 1708 var keys = Object.keys; 1709 var forEach = (obj, f) => { 1710 for (const key in obj) { 1711 f(obj[key], key); 1712 } 1713 }; 1714 var size = (obj) => keys(obj).length; 1715 var isEmpty = (obj) => { 1716 for (const _k in obj) { 1717 return false; 1718 } 1719 return true; 1720 }; 1721 var every2 = (obj, f) => { 1722 for (const key in obj) { 1723 if (!f(obj[key], key)) { 1724 return false; 1725 } 1726 } 1727 return true; 1728 }; 1729 var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); 1730 var equalFlat = (a, b) => a === b || size(a) === size(b) && every2(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && equals(b[key], val)); 1731 var freeze = Object.freeze; 1732 var deepFreeze = (o) => { 1733 for (const key in o) { 1734 const c = o[key]; 1735 if (typeof c === "object" || typeof c === "function") { 1736 deepFreeze(o[key]); 1737 } 1738 } 1739 return freeze(o); 1740 }; 1741 1742 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/function.js 1743 var callAll = (fs, args2, i = 0) => { 1744 try { 1745 for (; i < fs.length; i++) { 1746 fs[i](...args2); 1747 } 1748 } finally { 1749 if (i < fs.length) { 1750 callAll(fs, args2, i + 1); 1751 } 1752 } 1753 }; 1754 var id = (a) => a; 1755 var equalityDeep = (a, b) => { 1756 if (a === b) { 1757 return true; 1758 } 1759 if (a == null || b == null || a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object)) { 1760 return false; 1761 } 1762 if (a[EqualityTraitSymbol] != null) { 1763 return a[EqualityTraitSymbol](b); 1764 } 1765 switch (a.constructor) { 1766 case ArrayBuffer: 1767 a = new Uint8Array(a); 1768 b = new Uint8Array(b); 1769 // eslint-disable-next-line no-fallthrough 1770 case Uint8Array: { 1771 if (a.byteLength !== b.byteLength) { 1772 return false; 1773 } 1774 for (let i = 0; i < a.length; i++) { 1775 if (a[i] !== b[i]) { 1776 return false; 1777 } 1778 } 1779 break; 1780 } 1781 case Set: { 1782 if (a.size !== b.size) { 1783 return false; 1784 } 1785 for (const value of a) { 1786 if (!b.has(value)) { 1787 return false; 1788 } 1789 } 1790 break; 1791 } 1792 case Map: { 1793 if (a.size !== b.size) { 1794 return false; 1795 } 1796 for (const key of a.keys()) { 1797 if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) { 1798 return false; 1799 } 1800 } 1801 break; 1802 } 1803 case void 0: 1804 case Object: 1805 if (size(a) !== size(b)) { 1806 return false; 1807 } 1808 for (const key in a) { 1809 if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) { 1810 return false; 1811 } 1812 } 1813 break; 1814 case Array: 1815 if (a.length !== b.length) { 1816 return false; 1817 } 1818 for (let i = 0; i < a.length; i++) { 1819 if (!equalityDeep(a[i], b[i])) { 1820 return false; 1821 } 1822 } 1823 break; 1824 default: 1825 return false; 1826 } 1827 return true; 1828 }; 1829 var isOneOf = (value, options) => options.includes(value); 1830 1831 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/environment.js 1832 var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; 1833 var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode; 1834 var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; 1835 var params; 1836 var args = []; 1837 var computeParams = () => { 1838 if (params === void 0) { 1839 if (isNode) { 1840 params = create(); 1841 const pargs = process.argv; 1842 let currParamName = null; 1843 for (let i = 0; i < pargs.length; i++) { 1844 const parg = pargs[i]; 1845 if (parg[0] === "-") { 1846 if (currParamName !== null) { 1847 params.set(currParamName, ""); 1848 } 1849 currParamName = parg; 1850 } else { 1851 if (currParamName !== null) { 1852 params.set(currParamName, parg); 1853 currParamName = null; 1854 } else { 1855 args.push(parg); 1856 } 1857 } 1858 } 1859 if (currParamName !== null) { 1860 params.set(currParamName, ""); 1861 } 1862 } else if (typeof location === "object") { 1863 params = create(); 1864 (location.search || "?").slice(1).split("&").forEach((kv) => { 1865 if (kv.length !== 0) { 1866 const [key, value] = kv.split("="); 1867 params.set(`--$fromCamelCase(key, "-")}`, value); 1868 params.set(`-$fromCamelCase(key, "-")}`, value); 1869 } 1870 }); 1871 } else { 1872 params = create(); 1873 } 1874 } 1875 return params; 1876 }; 1877 var hasParam = (name) => computeParams().has(name); 1878 var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name)); 1879 var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null; 1880 var production = hasConf("production"); 1881 var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]); 1882 var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors 1883 !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color")); 1884 1885 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/buffer.js 1886 var createUint8ArrayFromLen = (len) => new Uint8Array(len); 1887 var createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length2) => new Uint8Array(buffer, byteOffset, length2); 1888 var toBase64Browser = (bytes) => { 1889 let s = ""; 1890 for (let i = 0; i < bytes.byteLength; i++) { 1891 s += fromCharCode(bytes[i]); 1892 } 1893 return btoa(s); 1894 }; 1895 var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"); 1896 var fromBase64Browser = (s) => { 1897 const a = atob(s); 1898 const bytes = createUint8ArrayFromLen(a.length); 1899 for (let i = 0; i < a.length; i++) { 1900 bytes[i] = a.charCodeAt(i); 1901 } 1902 return bytes; 1903 }; 1904 var fromBase64Node = (s) => { 1905 const buf = Buffer.from(s, "base64"); 1906 return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength); 1907 }; 1908 var toBase64 = isBrowser ? toBase64Browser : toBase64Node; 1909 var fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node; 1910 var copyUint8Array = (uint8Array) => { 1911 const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); 1912 newBuf.set(uint8Array); 1913 return newBuf; 1914 }; 1915 1916 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/pair.js 1917 var Pair = class { 1918 /** 1919 * @param {L} left 1920 * @param {R} right 1921 */ 1922 constructor(left, right) { 1923 this.left = left; 1924 this.right = right; 1925 } 1926 }; 1927 var create5 = (left, right) => new Pair(left, right); 1928 1929 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/prng.js 1930 var bool = (gen) => gen.next() >= 0.5; 1931 var int53 = (gen, min2, max2) => floor(gen.next() * (max2 + 1 - min2) + min2); 1932 var int32 = (gen, min2, max2) => floor(gen.next() * (max2 + 1 - min2) + min2); 1933 var int31 = (gen, min2, max2) => int32(gen, min2, max2); 1934 var letter = (gen) => fromCharCode(int31(gen, 97, 122)); 1935 var word = (gen, minLen = 0, maxLen = 20) => { 1936 const len = int31(gen, minLen, maxLen); 1937 let str = ""; 1938 for (let i = 0; i < len; i++) { 1939 str += letter(gen); 1940 } 1941 return str; 1942 }; 1943 var oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]; 1944 1945 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/schema.js 1946 var schemaSymbol = /* @__PURE__ */ Symbol("0schema"); 1947 var ValidationError = class { 1948 constructor() { 1949 this._rerrs = []; 1950 } 1951 /** 1952 * @param {string?} path 1953 * @param {string} expected 1954 * @param {string} has 1955 * @param {string?} message 1956 */ 1957 extend(path, expected, has, message = null) { 1958 this._rerrs.push({ path, expected, has, message }); 1959 } 1960 toString() { 1961 const s = []; 1962 for (let i = this._rerrs.length - 1; i > 0; i--) { 1963 const r2 = this._rerrs[i]; 1964 s.push(repeat(" ", (this._rerrs.length - i) * 2) + `$r2.path != null ? `[$r2.path}] ` : ""}$r2.has} doesn't match $r2.expected}. $r2.message}`); 1965 } 1966 return s.join("\n"); 1967 } 1968 }; 1969 var shapeExtends = (a, b) => { 1970 if (a === b) return true; 1971 if (a == null || b == null || a.constructor !== b.constructor) return false; 1972 if (a[EqualityTraitSymbol]) return equals(a, b); 1973 if (isArray(a)) { 1974 return every( 1975 a, 1976 (aitem) => some(b, (bitem) => shapeExtends(aitem, bitem)) 1977 ); 1978 } else if (isObject(a)) { 1979 return every2( 1980 a, 1981 (aitem, akey) => shapeExtends(aitem, b[akey]) 1982 ); 1983 } 1984 return false; 1985 }; 1986 var Schema = class { 1987 // this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore 1988 /** 1989 * If true, the more things are added to the shape the more objects this schema will accept (e.g. 1990 * union). By default, the more objects are added, the the fewer objects this schema will accept. 1991 * @protected 1992 */ 1993 static _dilutes = false; 1994 /** 1995 * @param {Schema<any>} other 1996 */ 1997 extends(other) { 1998 let [a, b] = [ 1999 /** @type {any} */ 2000 this.shape, 2001 /** @type {any} */ 2002 other.shape 2003 ]; 2004 if ( 2005 /** @type {typeof Schema<any>} */ 2006 this.constructor._dilutes 2007 ) [b, a] = [a, b]; 2008 return shapeExtends(a, b); 2009 } 2010 /** 2011 * Overwrite this when necessary. By default, we only check the `shape` property which every shape 2012 * should have. 2013 * @param {Schema<any>} other 2014 */ 2015 equals(other) { 2016 return this.constructor === other.constructor && equalityDeep(this.shape, other.shape); 2017 } 2018 [schemaSymbol]() { 2019 return true; 2020 } 2021 /** 2022 * @param {object} other 2023 */ 2024 [EqualityTraitSymbol](other) { 2025 return this.equals( 2026 /** @type {any} */ 2027 other 2028 ); 2029 } 2030 /** 2031 * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of 2032 * Schema. Validate will check the structure of the parameter and return true iff the instance 2033 * really is an instance of Schema. 2034 * 2035 * @param {T} o 2036 * @return {boolean} 2037 */ 2038 validate(o) { 2039 return this.check(o); 2040 } 2041 /* c8 ignore start */ 2042 /** 2043 * Similar to validate, but this method accepts untyped parameters. 2044 * 2045 * @param {any} _o 2046 * @param {ValidationError} [_err] 2047 * @return {_o is T} 2048 */ 2049 check(_o, _err) { 2050 methodUnimplemented(); 2051 } 2052 /* c8 ignore stop */ 2053 /** 2054 * @type {Schema<T?>} 2055 */ 2056 get nullable() { 2057 return $union(this, $null); 2058 } 2059 /** 2060 * @type {$Optional<Schema<T>>} 2061 */ 2062 get optional() { 2063 return new $Optional( 2064 /** @type {Schema<T>} */ 2065 this 2066 ); 2067 } 2068 /** 2069 * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise. 2070 * Use this if you know that the type is of a specific type and you just want to convince the type 2071 * system. 2072 * 2073 * **Do not rely on these error messages!** 2074 * Performs an assertion check only if not in a production environment. 2075 * 2076 * @template OO 2077 * @param {OO} o 2078 * @return {Extract<OO, T> extends never ? T : (OO extends Array<never> ? T : Extract<OO,T>)} 2079 */ 2080 cast(o) { 2081 assert(o, this); 2082 return ( 2083 /** @type {any} */ 2084 o 2085 ); 2086 } 2087 /** 2088 * EXPECTO PATRONUM!! 🪄 2089 * This function protects against type errors. Though it may not work in the real world. 2090 * 2091 * "After all this time?" 2092 * "Always." - Snape, talking about type safety 2093 * 2094 * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed. 2095 * Use this if you know that the type is of a specific type and you just want to convince the type 2096 * system. 2097 * 2098 * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)` 2099 * 2100 * **Do not rely on these error messages!** 2101 * Performs an assertion check if not in a production environment. 2102 * 2103 * @param {T} o 2104 * @return {o extends T ? T : never} 2105 */ 2106 expect(o) { 2107 assert(o, this); 2108 return o; 2109 } 2110 }; 2111 var $ConstructedBy = class extends Schema { 2112 /** 2113 * @param {C} c 2114 * @param {((o:Instance<C>)=>boolean)|null} check 2115 */ 2116 constructor(c, check) { 2117 super(); 2118 this.shape = c; 2119 this._c = check; 2120 } 2121 /** 2122 * @param {any} o 2123 * @param {ValidationError} [err] 2124 * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType<C> : never)} o 2125 */ 2126 check(o, err = void 0) { 2127 const c = o?.constructor === this.shape && (this._c == null || this._c(o)); 2128 !c && err?.extend(null, this.shape.name, o?.constructor.name, o?.constructor !== this.shape ? "Constructor match failed" : "Check failed"); 2129 return c; 2130 } 2131 }; 2132 var $constructedBy = (c, check = null) => new $ConstructedBy(c, check); 2133 var $$constructedBy = $constructedBy($ConstructedBy); 2134 var $Custom = class extends Schema { 2135 /** 2136 * @param {(o:any) => boolean} check 2137 */ 2138 constructor(check) { 2139 super(); 2140 this.shape = check; 2141 } 2142 /** 2143 * @param {any} o 2144 * @param {ValidationError} err 2145 * @return {o is any} 2146 */ 2147 check(o, err) { 2148 const c = this.shape(o); 2149 !c && err?.extend(null, "custom prop", o?.constructor.name, "failed to check custom prop"); 2150 return c; 2151 } 2152 }; 2153 var $custom = (check) => new $Custom(check); 2154 var $$custom = $constructedBy($Custom); 2155 var $Literal = class extends Schema { 2156 /** 2157 * @param {Array<T>} literals 2158 */ 2159 constructor(literals) { 2160 super(); 2161 this.shape = literals; 2162 } 2163 /** 2164 * 2165 * @param {any} o 2166 * @param {ValidationError} [err] 2167 * @return {o is T} 2168 */ 2169 check(o, err) { 2170 const c = this.shape.some((a) => a === o); 2171 !c && err?.extend(null, this.shape.join(" | "), o.toString()); 2172 return c; 2173 } 2174 }; 2175 var $literal = (...literals) => new $Literal(literals); 2176 var $$literal = $constructedBy($Literal); 2177 var _regexEscape = ( 2178 /** @type {any} */ 2179 RegExp.escape || /** @type {(str:string) => string} */ 2180 ((str) => str.replace(/[().|&,$^[\]]/g, (s) => "\\" + s)) 2181 ); 2182 var _schemaStringTemplateToRegex = (s) => { 2183 if ($string.check(s)) { 2184 return [_regexEscape(s)]; 2185 } 2186 if ($$literal.check(s)) { 2187 return ( 2188 /** @type {Array<string|number>} */ 2189 s.shape.map((v) => v + "") 2190 ); 2191 } 2192 if ($$number.check(s)) { 2193 return ["[+-]?\\d+.?\\d*"]; 2194 } 2195 if ($$string.check(s)) { 2196 return [".*"]; 2197 } 2198 if ($$union.check(s)) { 2199 return s.shape.map(_schemaStringTemplateToRegex).flat(1); 2200 } 2201 unexpectedCase(); 2202 }; 2203 var $StringTemplate = class extends Schema { 2204 /** 2205 * @param {T} shape 2206 */ 2207 constructor(shape) { 2208 super(); 2209 this.shape = shape; 2210 this._r = new RegExp("^" + shape.map(_schemaStringTemplateToRegex).map((opts) => `($opts.join("|")})`).join("") + "$"); 2211 } 2212 /** 2213 * @param {any} o 2214 * @param {ValidationError} [err] 2215 * @return {o is CastStringTemplateArgsToTemplate<T>} 2216 */ 2217 check(o, err) { 2218 const c = this._r.exec(o) != null; 2219 !c && err?.extend(null, this._r.toString(), o.toString(), "String doesn't match string template."); 2220 return c; 2221 } 2222 }; 2223 var $$stringTemplate = $constructedBy($StringTemplate); 2224 var isOptionalSymbol = /* @__PURE__ */ Symbol("optional"); 2225 var $Optional = class extends Schema { 2226 /** 2227 * @param {S} shape 2228 */ 2229 constructor(shape) { 2230 super(); 2231 this.shape = shape; 2232 } 2233 /** 2234 * @param {any} o 2235 * @param {ValidationError} [err] 2236 * @return {o is (Unwrap<S>|undefined)} 2237 */ 2238 check(o, err) { 2239 const c = o === void 0 || this.shape.check(o); 2240 !c && err?.extend(null, "undefined (optional)", "()"); 2241 return c; 2242 } 2243 get [isOptionalSymbol]() { 2244 return true; 2245 } 2246 }; 2247 var $$optional = $constructedBy($Optional); 2248 var $Never = class extends Schema { 2249 /** 2250 * @param {any} _o 2251 * @param {ValidationError} [err] 2252 * @return {_o is never} 2253 */ 2254 check(_o, err) { 2255 err?.extend(null, "never", typeof _o); 2256 return false; 2257 } 2258 }; 2259 var $never = new $Never(); 2260 var $$never = $constructedBy($Never); 2261 var $Object = class _$Object extends Schema { 2262 /** 2263 * @param {S} shape 2264 * @param {boolean} partial 2265 */ 2266 constructor(shape, partial = false) { 2267 super(); 2268 this.shape = shape; 2269 this._isPartial = partial; 2270 } 2271 static _dilutes = true; 2272 /** 2273 * @type {Schema<Partial<$ObjectToType<S>>>} 2274 */ 2275 get partial() { 2276 return new _$Object(this.shape, true); 2277 } 2278 /** 2279 * @param {any} o 2280 * @param {ValidationError} err 2281 * @return {o is $ObjectToType<S>} 2282 */ 2283 check(o, err) { 2284 if (o == null) { 2285 err?.extend(null, "object", "null"); 2286 return false; 2287 } 2288 return every2(this.shape, (vv, vk) => { 2289 const c = this._isPartial && !hasProperty(o, vk) || vv.check(o[vk], err); 2290 !c && err?.extend(vk.toString(), vv.toString(), typeof o[vk], "Object property does not match"); 2291 return c; 2292 }); 2293 } 2294 }; 2295 var $object = (def) => ( 2296 /** @type {any} */ 2297 new $Object(def) 2298 ); 2299 var $$object = $constructedBy($Object); 2300 var $objectAny = $custom((o) => o != null && (o.constructor === Object || o.constructor == null)); 2301 var $Record = class extends Schema { 2302 /** 2303 * @param {Keys} keys 2304 * @param {Values} values 2305 */ 2306 constructor(keys2, values) { 2307 super(); 2308 this.shape = { 2309 keys: keys2, 2310 values 2311 }; 2312 } 2313 /** 2314 * @param {any} o 2315 * @param {ValidationError} err 2316 * @return {o is { [key in Unwrap<Keys>]: Unwrap<Values> }} 2317 */ 2318 check(o, err) { 2319 return o != null && every2(o, (vv, vk) => { 2320 const ck = this.shape.keys.check(vk, err); 2321 !ck && err?.extend(vk + "", "Record", typeof o, ck ? "Key doesn't match schema" : "Value doesn't match value"); 2322 return ck && this.shape.values.check(vv, err); 2323 }); 2324 } 2325 }; 2326 var $record = (keys2, values) => new $Record(keys2, values); 2327 var $$record = $constructedBy($Record); 2328 var $Tuple = class extends Schema { 2329 /** 2330 * @param {S} shape 2331 */ 2332 constructor(shape) { 2333 super(); 2334 this.shape = shape; 2335 } 2336 /** 2337 * @param {any} o 2338 * @param {ValidationError} err 2339 * @return {o is { [K in keyof S]: S[K] extends Schema<infer Type> ? Type : never }} 2340 */ 2341 check(o, err) { 2342 return o != null && every2(this.shape, (vv, vk) => { 2343 const c = ( 2344 /** @type {Schema<any>} */ 2345 vv.check(o[vk], err) 2346 ); 2347 !c && err?.extend(vk.toString(), "Tuple", typeof vv); 2348 return c; 2349 }); 2350 } 2351 }; 2352 var $tuple = (...def) => new $Tuple(def); 2353 var $$tuple = $constructedBy($Tuple); 2354 var $Array = class extends Schema { 2355 /** 2356 * @param {Array<S>} v 2357 */ 2358 constructor(v) { 2359 super(); 2360 this.shape = v.length === 1 ? v[0] : new $Union(v); 2361 } 2362 /** 2363 * @param {any} o 2364 * @param {ValidationError} [err] 2365 * @return {o is Array<S extends Schema<infer T> ? T : never>} o 2366 */ 2367 check(o, err) { 2368 const c = isArray(o) && every(o, (oi) => this.shape.check(oi)); 2369 !c && err?.extend(null, "Array", ""); 2370 return c; 2371 } 2372 }; 2373 var $array = (...def) => new $Array(def); 2374 var $$array = $constructedBy($Array); 2375 var $arrayAny = $custom((o) => isArray(o)); 2376 var $InstanceOf = class extends Schema { 2377 /** 2378 * @param {new (...args:any) => T} constructor 2379 * @param {((o:T) => boolean)|null} check 2380 */ 2381 constructor(constructor, check) { 2382 super(); 2383 this.shape = constructor; 2384 this._c = check; 2385 } 2386 /** 2387 * @param {any} o 2388 * @param {ValidationError} err 2389 * @return {o is T} 2390 */ 2391 check(o, err) { 2392 const c = o instanceof this.shape && (this._c == null || this._c(o)); 2393 !c && err?.extend(null, this.shape.name, o?.constructor.name); 2394 return c; 2395 } 2396 }; 2397 var $instanceOf = (c, check = null) => new $InstanceOf(c, check); 2398 var $$instanceOf = $constructedBy($InstanceOf); 2399 var $$schema = $instanceOf(Schema); 2400 var $Lambda = class extends Schema { 2401 /** 2402 * @param {Args} args 2403 */ 2404 constructor(args2) { 2405 super(); 2406 this.len = args2.length - 1; 2407 this.args = $tuple(...args2.slice(-1)); 2408 this.res = args2[this.len]; 2409 } 2410 /** 2411 * @param {any} f 2412 * @param {ValidationError} err 2413 * @return {f is _LArgsToLambdaDef<Args>} 2414 */ 2415 check(f, err) { 2416 const c = f.constructor === Function && f.length <= this.len; 2417 !c && err?.extend(null, "function", typeof f); 2418 return c; 2419 } 2420 }; 2421 var $$lambda = $constructedBy($Lambda); 2422 var $function = $custom((o) => typeof o === "function"); 2423 var $Intersection = class extends Schema { 2424 /** 2425 * @param {T} v 2426 */ 2427 constructor(v) { 2428 super(); 2429 this.shape = v; 2430 } 2431 /** 2432 * @param {any} o 2433 * @param {ValidationError} [err] 2434 * @return {o is Intersect<UnwrapArray<T>>} 2435 */ 2436 check(o, err) { 2437 const c = every(this.shape, (check) => check.check(o, err)); 2438 !c && err?.extend(null, "Intersectinon", typeof o); 2439 return c; 2440 } 2441 }; 2442 var $$intersect = $constructedBy($Intersection, (o) => o.shape.length > 0); 2443 var $Union = class extends Schema { 2444 static _dilutes = true; 2445 /** 2446 * @param {Array<Schema<S>>} v 2447 */ 2448 constructor(v) { 2449 super(); 2450 this.shape = v; 2451 } 2452 /** 2453 * @param {any} o 2454 * @param {ValidationError} [err] 2455 * @return {o is S} 2456 */ 2457 check(o, err) { 2458 const c = some(this.shape, (vv) => vv.check(o, err)); 2459 err?.extend(null, "Union", typeof o); 2460 return c; 2461 } 2462 }; 2463 var $union = (...schemas) => schemas.findIndex(($s) => $$union.check($s)) >= 0 ? $union(...schemas.map(($s) => $($s)).map(($s) => $$union.check($s) ? $s.shape : [$s]).flat(1)) : schemas.length === 1 ? schemas[0] : new $Union(schemas); 2464 var $$union = ( 2465 /** @type {Schema<$Union<any>>} */ 2466 $constructedBy($Union) 2467 ); 2468 var _t = () => true; 2469 var $any = $custom(_t); 2470 var $$any = ( 2471 /** @type {Schema<Schema<any>>} */ 2472 $constructedBy($Custom, (o) => o.shape === _t) 2473 ); 2474 var $bigint = $custom((o) => typeof o === "bigint"); 2475 var $$bigint = ( 2476 /** @type {Schema<Schema<BigInt>>} */ 2477 $custom((o) => o === $bigint) 2478 ); 2479 var $symbol = $custom((o) => typeof o === "symbol"); 2480 var $$symbol = ( 2481 /** @type {Schema<Schema<Symbol>>} */ 2482 $custom((o) => o === $symbol) 2483 ); 2484 var $number = $custom((o) => typeof o === "number"); 2485 var $$number = ( 2486 /** @type {Schema<Schema<number>>} */ 2487 $custom((o) => o === $number) 2488 ); 2489 var $string = $custom((o) => typeof o === "string"); 2490 var $$string = ( 2491 /** @type {Schema<Schema<string>>} */ 2492 $custom((o) => o === $string) 2493 ); 2494 var $boolean = $custom((o) => typeof o === "boolean"); 2495 var $$boolean = ( 2496 /** @type {Schema<Schema<Boolean>>} */ 2497 $custom((o) => o === $boolean) 2498 ); 2499 var $undefined = $literal(void 0); 2500 var $$undefined = ( 2501 /** @type {Schema<Schema<undefined>>} */ 2502 $constructedBy($Literal, (o) => o.shape.length === 1 && o.shape[0] === void 0) 2503 ); 2504 var $void = $literal(void 0); 2505 var $null = $literal(null); 2506 var $$null = ( 2507 /** @type {Schema<Schema<null>>} */ 2508 $constructedBy($Literal, (o) => o.shape.length === 1 && o.shape[0] === null) 2509 ); 2510 var $uint8Array = $constructedBy(Uint8Array); 2511 var $$uint8Array = ( 2512 /** @type {Schema<Schema<Uint8Array>>} */ 2513 $constructedBy($ConstructedBy, (o) => o.shape === Uint8Array) 2514 ); 2515 var $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol); 2516 var $json = (() => { 2517 const $jsonArr = ( 2518 /** @type {$Array<$any>} */ 2519 $array($any) 2520 ); 2521 const $jsonRecord = ( 2522 /** @type {$Record<$string,$any>} */ 2523 $record($string, $any) 2524 ); 2525 const $json2 = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord); 2526 $jsonArr.shape = $json2; 2527 $jsonRecord.shape.values = $json2; 2528 return $json2; 2529 })(); 2530 var $ = (o) => { 2531 if ($$schema.check(o)) { 2532 return ( 2533 /** @type {any} */ 2534 o 2535 ); 2536 } else if ($objectAny.check(o)) { 2537 const o2 = {}; 2538 for (const k in o) { 2539 o2[k] = $(o[k]); 2540 } 2541 return ( 2542 /** @type {any} */ 2543 $object(o2) 2544 ); 2545 } else if ($arrayAny.check(o)) { 2546 return ( 2547 /** @type {any} */ 2548 $union(...o.map($)) 2549 ); 2550 } else if ($primitive.check(o)) { 2551 return ( 2552 /** @type {any} */ 2553 $literal(o) 2554 ); 2555 } else if ($function.check(o)) { 2556 return ( 2557 /** @type {any} */ 2558 $constructedBy( 2559 /** @type {any} */ 2560 o 2561 ) 2562 ); 2563 } 2564 unexpectedCase(); 2565 }; 2566 var assert = production ? () => { 2567 } : (o, schema) => { 2568 const err = new ValidationError(); 2569 if (!schema.check(o, err)) { 2570 throw create3(`Expected value to be of type $schema.constructor.name}. 2571 $err.toString()}`); 2572 } 2573 }; 2574 var PatternMatcher = class { 2575 /** 2576 * @param {Schema<State>} [$state] 2577 */ 2578 constructor($state) { 2579 this.patterns = []; 2580 this.$state = $state; 2581 } 2582 /** 2583 * @template P 2584 * @template R 2585 * @param {P} pattern 2586 * @param {(o:NoInfer<Unwrap<ReadSchema<P>>>,s:State)=>R} handler 2587 * @return {PatternMatcher<State,Patterns|Pattern<Unwrap<ReadSchema<P>>,R>>} 2588 */ 2589 if(pattern, handler) { 2590 this.patterns.push({ if: $(pattern), h: handler }); 2591 return this; 2592 } 2593 /** 2594 * @template R 2595 * @param {(o:any,s:State)=>R} h 2596 */ 2597 else(h) { 2598 return this.if($any, h); 2599 } 2600 /** 2601 * @return {State extends undefined 2602 * ? <In extends Unwrap<Patterns['if']>>(o:In,state?:undefined)=>PatternMatchResult<Patterns,In> 2603 * : <In extends Unwrap<Patterns['if']>>(o:In,state:State)=>PatternMatchResult<Patterns,In>} 2604 */ 2605 done() { 2606 return ( 2607 /** @type {any} */ 2608 (o, s) => { 2609 for (let i = 0; i < this.patterns.length; i++) { 2610 const p = this.patterns[i]; 2611 if (p.if.check(o)) { 2612 return p.h(o, s); 2613 } 2614 } 2615 throw create3("Unhandled pattern"); 2616 } 2617 ); 2618 } 2619 }; 2620 var match = (state) => new PatternMatcher( 2621 /** @type {any} */ 2622 state 2623 ); 2624 var _random = ( 2625 /** @type {any} */ 2626 match( 2627 /** @type {Schema<prng.PRNG>} */ 2628 $any 2629 ).if($$number, (_o, gen) => int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER)).if($$string, (_o, gen) => word(gen)).if($$boolean, (_o, gen) => bool(gen)).if($$bigint, (_o, gen) => BigInt(int53(gen, MIN_SAFE_INTEGER, MAX_SAFE_INTEGER))).if($$union, (o, gen) => random(gen, oneOf(gen, o.shape))).if($$object, (o, gen) => { 2630 const res = {}; 2631 for (const k in o.shape) { 2632 let prop = o.shape[k]; 2633 if ($$optional.check(prop)) { 2634 if (bool(gen)) { 2635 continue; 2636 } 2637 prop = prop.shape; 2638 } 2639 res[k] = _random(prop, gen); 2640 } 2641 return res; 2642 }).if($$array, (o, gen) => { 2643 const arr = []; 2644 const n = int32(gen, 0, 42); 2645 for (let i = 0; i < n; i++) { 2646 arr.push(random(gen, o.shape)); 2647 } 2648 return arr; 2649 }).if($$literal, (o, gen) => { 2650 return oneOf(gen, o.shape); 2651 }).if($$null, (o, gen) => { 2652 return null; 2653 }).if($$lambda, (o, gen) => { 2654 const res = random(gen, o.res); 2655 return () => res; 2656 }).if($$any, (o, gen) => random(gen, oneOf(gen, [ 2657 $number, 2658 $string, 2659 $null, 2660 $undefined, 2661 $bigint, 2662 $boolean, 2663 $array($number), 2664 $record($union("a", "b", "c"), $number) 2665 ]))).if($$record, (o, gen) => { 2666 const res = {}; 2667 const keysN = int53(gen, 0, 3); 2668 for (let i = 0; i < keysN; i++) { 2669 const key = random(gen, o.shape.keys); 2670 const val = random(gen, o.shape.values); 2671 res[key] = val; 2672 } 2673 return res; 2674 }).done() 2675 ); 2676 var random = (gen, schema) => ( 2677 /** @type {any} */ 2678 _random($(schema), gen) 2679 ); 2680 2681 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/dom.js 2682 var doc = ( 2683 /** @type {Document} */ 2684 typeof document !== "undefined" ? document : {} 2685 ); 2686 var $fragment = $custom((el) => el.nodeType === DOCUMENT_FRAGMENT_NODE); 2687 var domParser = ( 2688 /** @type {DOMParser} */ 2689 typeof DOMParser !== "undefined" ? new DOMParser() : null 2690 ); 2691 var $element = $custom((el) => el.nodeType === ELEMENT_NODE); 2692 var $text = $custom((el) => el.nodeType === TEXT_NODE); 2693 var mapToStyleString = (m) => map(m, (value, key) => `$key}:$value};`).join(""); 2694 var ELEMENT_NODE = doc.ELEMENT_NODE; 2695 var TEXT_NODE = doc.TEXT_NODE; 2696 var CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE; 2697 var COMMENT_NODE = doc.COMMENT_NODE; 2698 var DOCUMENT_NODE = doc.DOCUMENT_NODE; 2699 var DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE; 2700 var DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE; 2701 var $node = $custom((el) => el.nodeType === DOCUMENT_NODE); 2702 2703 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/symbol.js 2704 var create6 = Symbol; 2705 2706 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/logging.common.js 2707 var BOLD = create6(); 2708 var UNBOLD = create6(); 2709 var BLUE = create6(); 2710 var GREY = create6(); 2711 var GREEN = create6(); 2712 var RED = create6(); 2713 var PURPLE = create6(); 2714 var ORANGE = create6(); 2715 var UNCOLOR = create6(); 2716 var computeNoColorLoggingArgs = (args2) => { 2717 if (args2.length === 1 && args2[0]?.constructor === Function) { 2718 args2 = /** @type {Array<string|Symbol|Object|number>} */ 2719 /** @type {[function]} */ 2720 args2[0](); 2721 } 2722 const strBuilder = []; 2723 const logArgs = []; 2724 let i = 0; 2725 for (; i < args2.length; i++) { 2726 const arg = args2[i]; 2727 if (arg === void 0) { 2728 break; 2729 } else if (arg.constructor === String || arg.constructor === Number) { 2730 strBuilder.push(arg); 2731 } else if (arg.constructor === Object) { 2732 break; 2733 } 2734 } 2735 if (i > 0) { 2736 logArgs.push(strBuilder.join("")); 2737 } 2738 for (; i < args2.length; i++) { 2739 const arg = args2[i]; 2740 if (!(arg instanceof Symbol)) { 2741 logArgs.push(arg); 2742 } 2743 } 2744 return logArgs; 2745 }; 2746 var lastLoggingTime = getUnixTime(); 2747 2748 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/logging.js 2749 var _browserStyleMap = { 2750 [BOLD]: create5("font-weight", "bold"), 2751 [UNBOLD]: create5("font-weight", "normal"), 2752 [BLUE]: create5("color", "blue"), 2753 [GREEN]: create5("color", "green"), 2754 [GREY]: create5("color", "grey"), 2755 [RED]: create5("color", "red"), 2756 [PURPLE]: create5("color", "purple"), 2757 [ORANGE]: create5("color", "orange"), 2758 // not well supported in chrome when debugging node with inspector - TODO: deprecate 2759 [UNCOLOR]: create5("color", "black") 2760 }; 2761 var computeBrowserLoggingArgs = (args2) => { 2762 if (args2.length === 1 && args2[0]?.constructor === Function) { 2763 args2 = /** @type {Array<string|Symbol|Object|number>} */ 2764 /** @type {[function]} */ 2765 args2[0](); 2766 } 2767 const strBuilder = []; 2768 const styles = []; 2769 const currentStyle = create(); 2770 let logArgs = []; 2771 let i = 0; 2772 for (; i < args2.length; i++) { 2773 const arg = args2[i]; 2774 const style = _browserStyleMap[arg]; 2775 if (style !== void 0) { 2776 currentStyle.set(style.left, style.right); 2777 } else { 2778 if (arg === void 0) { 2779 break; 2780 } 2781 if (arg.constructor === String || arg.constructor === Number) { 2782 const style2 = mapToStyleString(currentStyle); 2783 if (i > 0 || style2.length > 0) { 2784 strBuilder.push("%c" + arg); 2785 styles.push(style2); 2786 } else { 2787 strBuilder.push(arg); 2788 } 2789 } else { 2790 break; 2791 } 2792 } 2793 } 2794 if (i > 0) { 2795 logArgs = styles; 2796 logArgs.unshift(strBuilder.join("")); 2797 } 2798 for (; i < args2.length; i++) { 2799 const arg = args2[i]; 2800 if (!(arg instanceof Symbol)) { 2801 logArgs.push(arg); 2802 } 2803 } 2804 return logArgs; 2805 }; 2806 var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs; 2807 var print = (...args2) => { 2808 console.log(...computeLoggingArgs(args2)); 2809 vconsoles.forEach((vc) => vc.print(args2)); 2810 }; 2811 var warn = (...args2) => { 2812 console.warn(...computeLoggingArgs(args2)); 2813 args2.unshift(ORANGE); 2814 vconsoles.forEach((vc) => vc.print(args2)); 2815 }; 2816 var vconsoles = create2(); 2817 2818 // node_modules/.store/lib0@0.2.117-AWthJenbqlRhwK8dg2Xkww/node_modules/lib0/iterator.js 2819 var createIterator = (next) => ({ 2820 /** 2821 * @return {IterableIterator<T>} 2822 */ 2823 [Symbol.iterator]() { 2824 return this; 2825 }, 2826 // @ts-ignore 2827 next 2828 }); 2829 var iteratorFilter = (iterator, filter) => createIterator(() => { 2830 let res; 2831 do { 2832 res = iterator.next(); 2833 } while (!res.done && !filter(res.value)); 2834 return res; 2835 }); 2836 var iteratorMap = (iterator, fmap) => createIterator(() => { 2837 const { done, value } = iterator.next(); 2838 return { done, value: done ? void 0 : fmap(value) }; 2839 }); 2840 2841 // node_modules/.store/yjs@13.6.29-TJYJpNVE3l2_hFsy5BI5FA/node_modules/yjs/dist/yjs.mjs 2842 var AbstractConnector = class extends ObservableV2 { 2843 /** 2844 * @param {Doc} ydoc 2845 * @param {any} awareness 2846 */ 2847 constructor(ydoc, awareness) { 2848 super(); 2849 this.doc = ydoc; 2850 this.awareness = awareness; 2851 } 2852 }; 2853 var DeleteItem = class { 2854 /** 2855 * @param {number} clock 2856 * @param {number} len 2857 */ 2858 constructor(clock, len) { 2859 this.clock = clock; 2860 this.len = len; 2861 } 2862 }; 2863 var DeleteSet = class { 2864 constructor() { 2865 this.clients = /* @__PURE__ */ new Map(); 2866 } 2867 }; 2868 var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => { 2869 const structs = ( 2870 /** @type {Array<GC|Item>} */ 2871 transaction.doc.store.clients.get(clientid) 2872 ); 2873 if (structs != null) { 2874 const lastStruct = structs[structs.length - 1]; 2875 const clockState = lastStruct.id.clock + lastStruct.length; 2876 for (let i = 0, del = deletes[i]; i < deletes.length && del.clock < clockState; del = deletes[++i]) { 2877 iterateStructs(transaction, structs, del.clock, del.len, f); 2878 } 2879 } 2880 }); 2881 var findIndexDS = (dis, clock) => { 2882 let left = 0; 2883 let right = dis.length - 1; 2884 while (left <= right) { 2885 const midindex = floor((left + right) / 2); 2886 const mid = dis[midindex]; 2887 const midclock = mid.clock; 2888 if (midclock <= clock) { 2889 if (clock < midclock + mid.len) { 2890 return midindex; 2891 } 2892 left = midindex + 1; 2893 } else { 2894 right = midindex - 1; 2895 } 2896 } 2897 return null; 2898 }; 2899 var isDeleted = (ds, id2) => { 2900 const dis = ds.clients.get(id2.client); 2901 return dis !== void 0 && findIndexDS(dis, id2.clock) !== null; 2902 }; 2903 var sortAndMergeDeleteSet = (ds) => { 2904 ds.clients.forEach((dels) => { 2905 dels.sort((a, b) => a.clock - b.clock); 2906 let i, j; 2907 for (i = 1, j = 1; i < dels.length; i++) { 2908 const left = dels[j - 1]; 2909 const right = dels[i]; 2910 if (left.clock + left.len >= right.clock) { 2911 left.len = max(left.len, right.clock + right.len - left.clock); 2912 } else { 2913 if (j < i) { 2914 dels[j] = right; 2915 } 2916 j++; 2917 } 2918 } 2919 dels.length = j; 2920 }); 2921 }; 2922 var mergeDeleteSets = (dss) => { 2923 const merged = new DeleteSet(); 2924 for (let dssI = 0; dssI < dss.length; dssI++) { 2925 dss[dssI].clients.forEach((delsLeft, client) => { 2926 if (!merged.clients.has(client)) { 2927 const dels = delsLeft.slice(); 2928 for (let i = dssI + 1; i < dss.length; i++) { 2929 appendTo(dels, dss[i].clients.get(client) || []); 2930 } 2931 merged.clients.set(client, dels); 2932 } 2933 }); 2934 } 2935 sortAndMergeDeleteSet(merged); 2936 return merged; 2937 }; 2938 var addToDeleteSet = (ds, client, clock, length2) => { 2939 setIfUndefined(ds.clients, client, () => ( 2940 /** @type {Array<DeleteItem>} */ 2941 [] 2942 )).push(new DeleteItem(clock, length2)); 2943 }; 2944 var createDeleteSet = () => new DeleteSet(); 2945 var createDeleteSetFromStructStore = (ss) => { 2946 const ds = createDeleteSet(); 2947 ss.clients.forEach((structs, client) => { 2948 const dsitems = []; 2949 for (let i = 0; i < structs.length; i++) { 2950 const struct = structs[i]; 2951 if (struct.deleted) { 2952 const clock = struct.id.clock; 2953 let len = struct.length; 2954 if (i + 1 < structs.length) { 2955 for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) { 2956 len += next.length; 2957 } 2958 } 2959 dsitems.push(new DeleteItem(clock, len)); 2960 } 2961 } 2962 if (dsitems.length > 0) { 2963 ds.clients.set(client, dsitems); 2964 } 2965 }); 2966 return ds; 2967 }; 2968 var writeDeleteSet = (encoder, ds) => { 2969 writeVarUint(encoder.restEncoder, ds.clients.size); 2970 from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => { 2971 encoder.resetDsCurVal(); 2972 writeVarUint(encoder.restEncoder, client); 2973 const len = dsitems.length; 2974 writeVarUint(encoder.restEncoder, len); 2975 for (let i = 0; i < len; i++) { 2976 const item = dsitems[i]; 2977 encoder.writeDsClock(item.clock); 2978 encoder.writeDsLen(item.len); 2979 } 2980 }); 2981 }; 2982 var readDeleteSet = (decoder) => { 2983 const ds = new DeleteSet(); 2984 const numClients = readVarUint(decoder.restDecoder); 2985 for (let i = 0; i < numClients; i++) { 2986 decoder.resetDsCurVal(); 2987 const client = readVarUint(decoder.restDecoder); 2988 const numberOfDeletes = readVarUint(decoder.restDecoder); 2989 if (numberOfDeletes > 0) { 2990 const dsField = setIfUndefined(ds.clients, client, () => ( 2991 /** @type {Array<DeleteItem>} */ 2992 [] 2993 )); 2994 for (let i2 = 0; i2 < numberOfDeletes; i2++) { 2995 dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); 2996 } 2997 } 2998 } 2999 return ds; 3000 }; 3001 var readAndApplyDeleteSet = (decoder, transaction, store2) => { 3002 const unappliedDS = new DeleteSet(); 3003 const numClients = readVarUint(decoder.restDecoder); 3004 for (let i = 0; i < numClients; i++) { 3005 decoder.resetDsCurVal(); 3006 const client = readVarUint(decoder.restDecoder); 3007 const numberOfDeletes = readVarUint(decoder.restDecoder); 3008 const structs = store2.clients.get(client) || []; 3009 const state = getState(store2, client); 3010 for (let i2 = 0; i2 < numberOfDeletes; i2++) { 3011 const clock = decoder.readDsClock(); 3012 const clockEnd = clock + decoder.readDsLen(); 3013 if (clock < state) { 3014 if (state < clockEnd) { 3015 addToDeleteSet(unappliedDS, client, state, clockEnd - state); 3016 } 3017 let index = findIndexSS(structs, clock); 3018 let struct = structs[index]; 3019 if (!struct.deleted && struct.id.clock < clock) { 3020 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); 3021 index++; 3022 } 3023 while (index < structs.length) { 3024 struct = structs[index++]; 3025 if (struct.id.clock < clockEnd) { 3026 if (!struct.deleted) { 3027 if (clockEnd < struct.id.clock + struct.length) { 3028 structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); 3029 } 3030 struct.delete(transaction); 3031 } 3032 } else { 3033 break; 3034 } 3035 } 3036 } else { 3037 addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); 3038 } 3039 } 3040 } 3041 if (unappliedDS.clients.size > 0) { 3042 const ds = new UpdateEncoderV2(); 3043 writeVarUint(ds.restEncoder, 0); 3044 writeDeleteSet(ds, unappliedDS); 3045 return ds.toUint8Array(); 3046 } 3047 return null; 3048 }; 3049 var equalDeleteSets = (ds1, ds2) => { 3050 if (ds1.clients.size !== ds2.clients.size) return false; 3051 for (const [client, deleteItems1] of ds1.clients.entries()) { 3052 const deleteItems2 = ( 3053 /** @type {Array<import('../internals.js').DeleteItem>} */ 3054 ds2.clients.get(client) 3055 ); 3056 if (deleteItems2 === void 0 || deleteItems1.length !== deleteItems2.length) return false; 3057 for (let i = 0; i < deleteItems1.length; i++) { 3058 const di1 = deleteItems1[i]; 3059 const di2 = deleteItems2[i]; 3060 if (di1.clock !== di2.clock || di1.len !== di2.len) { 3061 return false; 3062 } 3063 } 3064 } 3065 return true; 3066 }; 3067 var generateNewClientId = uint32; 3068 var Doc = class _Doc extends ObservableV2 { 3069 /** 3070 * @param {DocOpts} opts configuration 3071 */ 3072 constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) { 3073 super(); 3074 this.gc = gc; 3075 this.gcFilter = gcFilter; 3076 this.clientID = generateNewClientId(); 3077 this.guid = guid; 3078 this.collectionid = collectionid; 3079 this.share = /* @__PURE__ */ new Map(); 3080 this.store = new StructStore(); 3081 this._transaction = null; 3082 this._transactionCleanups = []; 3083 this.subdocs = /* @__PURE__ */ new Set(); 3084 this._item = null; 3085 this.shouldLoad = shouldLoad; 3086 this.autoLoad = autoLoad; 3087 this.meta = meta; 3088 this.isLoaded = false; 3089 this.isSynced = false; 3090 this.isDestroyed = false; 3091 this.whenLoaded = create4((resolve) => { 3092 this.on("load", () => { 3093 this.isLoaded = true; 3094 resolve(this); 3095 }); 3096 }); 3097 const provideSyncedPromise = () => create4((resolve) => { 3098 const eventHandler = (isSynced) => { 3099 if (isSynced === void 0 || isSynced === true) { 3100 this.off("sync", eventHandler); 3101 resolve(); 3102 } 3103 }; 3104 this.on("sync", eventHandler); 3105 }); 3106 this.on("sync", (isSynced) => { 3107 if (isSynced === false && this.isSynced) { 3108 this.whenSynced = provideSyncedPromise(); 3109 } 3110 this.isSynced = isSynced === void 0 || isSynced === true; 3111 if (this.isSynced && !this.isLoaded) { 3112 this.emit("load", [this]); 3113 } 3114 }); 3115 this.whenSynced = provideSyncedPromise(); 3116 } 3117 /** 3118 * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). 3119 * 3120 * `load()` might be used in the future to request any provider to load the most current data. 3121 * 3122 * It is safe to call `load()` multiple times. 3123 */ 3124 load() { 3125 const item = this._item; 3126 if (item !== null && !this.shouldLoad) { 3127 transact( 3128 /** @type {any} */ 3129 item.parent.doc, 3130 (transaction) => { 3131 transaction.subdocsLoaded.add(this); 3132 }, 3133 null, 3134 true 3135 ); 3136 } 3137 this.shouldLoad = true; 3138 } 3139 getSubdocs() { 3140 return this.subdocs; 3141 } 3142 getSubdocGuids() { 3143 return new Set(from(this.subdocs).map((doc2) => doc2.guid)); 3144 } 3145 /** 3146 * Changes that happen inside of a transaction are bundled. This means that 3147 * the observer fires _after_ the transaction is finished and that all changes 3148 * that happened inside of the transaction are sent as one message to the 3149 * other peers. 3150 * 3151 * @template T 3152 * @param {function(Transaction):T} f The function that should be executed as a transaction 3153 * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin 3154 * @return T 3155 * 3156 * @public 3157 */ 3158 transact(f, origin2 = null) { 3159 return transact(this, f, origin2); 3160 } 3161 /** 3162 * Define a shared data type. 3163 * 3164 * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result 3165 * and do not overwrite each other. I.e. 3166 * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)` 3167 * 3168 * After this method is called, the type is also available on `ydoc.share.get(name)`. 3169 * 3170 * *Best Practices:* 3171 * Define all types right after the Y.Doc instance is created and store them in a separate object. 3172 * Also use the typed methods `getText(name)`, `getArray(name)`, .. 3173 * 3174 * @template {typeof AbstractType<any>} Type 3175 * @example 3176 * const ydoc = new Y.Doc(..) 3177 * const appState = { 3178 * document: ydoc.getText('document') 3179 * comments: ydoc.getArray('comments') 3180 * } 3181 * 3182 * @param {string} name 3183 * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... 3184 * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor 3185 * 3186 * @public 3187 */ 3188 get(name, TypeConstructor = ( 3189 /** @type {any} */ 3190 AbstractType 3191 )) { 3192 const type = setIfUndefined(this.share, name, () => { 3193 const t = new TypeConstructor(); 3194 t._integrate(this, null); 3195 return t; 3196 }); 3197 const Constr = type.constructor; 3198 if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { 3199 if (Constr === AbstractType) { 3200 const t = new TypeConstructor(); 3201 t._map = type._map; 3202 type._map.forEach( 3203 /** @param {Item?} n */ 3204 (n) => { 3205 for (; n !== null; n = n.left) { 3206 n.parent = t; 3207 } 3208 } 3209 ); 3210 t._start = type._start; 3211 for (let n = t._start; n !== null; n = n.right) { 3212 n.parent = t; 3213 } 3214 t._length = type._length; 3215 this.share.set(name, t); 3216 t._integrate(this, null); 3217 return ( 3218 /** @type {InstanceType<Type>} */ 3219 t 3220 ); 3221 } else { 3222 throw new Error(`Type with the name $name} has already been defined with a different constructor`); 3223 } 3224 } 3225 return ( 3226 /** @type {InstanceType<Type>} */ 3227 type 3228 ); 3229 } 3230 /** 3231 * @template T 3232 * @param {string} [name] 3233 * @return {YArray<T>} 3234 * 3235 * @public 3236 */ 3237 getArray(name = "") { 3238 return ( 3239 /** @type {YArray<T>} */ 3240 this.get(name, YArray) 3241 ); 3242 } 3243 /** 3244 * @param {string} [name] 3245 * @return {YText} 3246 * 3247 * @public 3248 */ 3249 getText(name = "") { 3250 return this.get(name, YText); 3251 } 3252 /** 3253 * @template T 3254 * @param {string} [name] 3255 * @return {YMap<T>} 3256 * 3257 * @public 3258 */ 3259 getMap(name = "") { 3260 return ( 3261 /** @type {YMap<T>} */ 3262 this.get(name, YMap) 3263 ); 3264 } 3265 /** 3266 * @param {string} [name] 3267 * @return {YXmlElement} 3268 * 3269 * @public 3270 */ 3271 getXmlElement(name = "") { 3272 return ( 3273 /** @type {YXmlElement<{[key:string]:string}>} */ 3274 this.get(name, YXmlElement) 3275 ); 3276 } 3277 /** 3278 * @param {string} [name] 3279 * @return {YXmlFragment} 3280 * 3281 * @public 3282 */ 3283 getXmlFragment(name = "") { 3284 return this.get(name, YXmlFragment); 3285 } 3286 /** 3287 * Converts the entire document into a js object, recursively traversing each yjs type 3288 * Doesn't log types that have not been defined (using ydoc.getType(..)). 3289 * 3290 * @deprecated Do not use this method and rather call toJSON directly on the shared types. 3291 * 3292 * @return {Object<string, any>} 3293 */ 3294 toJSON() { 3295 const doc2 = {}; 3296 this.share.forEach((value, key) => { 3297 doc2[key] = value.toJSON(); 3298 }); 3299 return doc2; 3300 } 3301 /** 3302 * Emit `destroy` event and unregister all event handlers. 3303 */ 3304 destroy() { 3305 this.isDestroyed = true; 3306 from(this.subdocs).forEach((subdoc) => subdoc.destroy()); 3307 const item = this._item; 3308 if (item !== null) { 3309 this._item = null; 3310 const content = ( 3311 /** @type {ContentDoc} */ 3312 item.content 3313 ); 3314 content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false }); 3315 content.doc._item = item; 3316 transact( 3317 /** @type {any} */ 3318 item.parent.doc, 3319 (transaction) => { 3320 const doc2 = content.doc; 3321 if (!item.deleted) { 3322 transaction.subdocsAdded.add(doc2); 3323 } 3324 transaction.subdocsRemoved.add(this); 3325 }, 3326 null, 3327 true 3328 ); 3329 } 3330 this.emit("destroyed", [true]); 3331 this.emit("destroy", [this]); 3332 super.destroy(); 3333 } 3334 }; 3335 var DSDecoderV1 = class { 3336 /** 3337 * @param {decoding.Decoder} decoder 3338 */ 3339 constructor(decoder) { 3340 this.restDecoder = decoder; 3341 } 3342 resetDsCurVal() { 3343 } 3344 /** 3345 * @return {number} 3346 */ 3347 readDsClock() { 3348 return readVarUint(this.restDecoder); 3349 } 3350 /** 3351 * @return {number} 3352 */ 3353 readDsLen() { 3354 return readVarUint(this.restDecoder); 3355 } 3356 }; 3357 var UpdateDecoderV1 = class extends DSDecoderV1 { 3358 /** 3359 * @return {ID} 3360 */ 3361 readLeftID() { 3362 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); 3363 } 3364 /** 3365 * @return {ID} 3366 */ 3367 readRightID() { 3368 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); 3369 } 3370 /** 3371 * Read the next client id. 3372 * Use this in favor of readID whenever possible to reduce the number of objects created. 3373 */ 3374 readClient() { 3375 return readVarUint(this.restDecoder); 3376 } 3377 /** 3378 * @return {number} info An unsigned 8-bit integer 3379 */ 3380 readInfo() { 3381 return readUint8(this.restDecoder); 3382 } 3383 /** 3384 * @return {string} 3385 */ 3386 readString() { 3387 return readVarString(this.restDecoder); 3388 } 3389 /** 3390 * @return {boolean} isKey 3391 */ 3392 readParentInfo() { 3393 return readVarUint(this.restDecoder) === 1; 3394 } 3395 /** 3396 * @return {number} info An unsigned 8-bit integer 3397 */ 3398 readTypeRef() { 3399 return readVarUint(this.restDecoder); 3400 } 3401 /** 3402 * Write len of a struct - well suited for Opt RLE encoder. 3403 * 3404 * @return {number} len 3405 */ 3406 readLen() { 3407 return readVarUint(this.restDecoder); 3408 } 3409 /** 3410 * @return {any} 3411 */ 3412 readAny() { 3413 return readAny(this.restDecoder); 3414 } 3415 /** 3416 * @return {Uint8Array} 3417 */ 3418 readBuf() { 3419 return copyUint8Array(readVarUint8Array(this.restDecoder)); 3420 } 3421 /** 3422 * Legacy implementation uses JSON parse. We use any-decoding in v2. 3423 * 3424 * @return {any} 3425 */ 3426 readJSON() { 3427 return JSON.parse(readVarString(this.restDecoder)); 3428 } 3429 /** 3430 * @return {string} 3431 */ 3432 readKey() { 3433 return readVarString(this.restDecoder); 3434 } 3435 }; 3436 var DSDecoderV2 = class { 3437 /** 3438 * @param {decoding.Decoder} decoder 3439 */ 3440 constructor(decoder) { 3441 this.dsCurrVal = 0; 3442 this.restDecoder = decoder; 3443 } 3444 resetDsCurVal() { 3445 this.dsCurrVal = 0; 3446 } 3447 /** 3448 * @return {number} 3449 */ 3450 readDsClock() { 3451 this.dsCurrVal += readVarUint(this.restDecoder); 3452 return this.dsCurrVal; 3453 } 3454 /** 3455 * @return {number} 3456 */ 3457 readDsLen() { 3458 const diff = readVarUint(this.restDecoder) + 1; 3459 this.dsCurrVal += diff; 3460 return diff; 3461 } 3462 }; 3463 var UpdateDecoderV2 = class extends DSDecoderV2 { 3464 /** 3465 * @param {decoding.Decoder} decoder 3466 */ 3467 constructor(decoder) { 3468 super(decoder); 3469 this.keys = []; 3470 readVarUint(decoder); 3471 this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3472 this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3473 this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3474 this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3475 this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); 3476 this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); 3477 this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); 3478 this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3479 this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3480 } 3481 /** 3482 * @return {ID} 3483 */ 3484 readLeftID() { 3485 return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()); 3486 } 3487 /** 3488 * @return {ID} 3489 */ 3490 readRightID() { 3491 return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()); 3492 } 3493 /** 3494 * Read the next client id. 3495 * Use this in favor of readID whenever possible to reduce the number of objects created. 3496 */ 3497 readClient() { 3498 return this.clientDecoder.read(); 3499 } 3500 /** 3501 * @return {number} info An unsigned 8-bit integer 3502 */ 3503 readInfo() { 3504 return ( 3505 /** @type {number} */ 3506 this.infoDecoder.read() 3507 ); 3508 } 3509 /** 3510 * @return {string} 3511 */ 3512 readString() { 3513 return this.stringDecoder.read(); 3514 } 3515 /** 3516 * @return {boolean} 3517 */ 3518 readParentInfo() { 3519 return this.parentInfoDecoder.read() === 1; 3520 } 3521 /** 3522 * @return {number} An unsigned 8-bit integer 3523 */ 3524 readTypeRef() { 3525 return this.typeRefDecoder.read(); 3526 } 3527 /** 3528 * Write len of a struct - well suited for Opt RLE encoder. 3529 * 3530 * @return {number} 3531 */ 3532 readLen() { 3533 return this.lenDecoder.read(); 3534 } 3535 /** 3536 * @return {any} 3537 */ 3538 readAny() { 3539 return readAny(this.restDecoder); 3540 } 3541 /** 3542 * @return {Uint8Array} 3543 */ 3544 readBuf() { 3545 return readVarUint8Array(this.restDecoder); 3546 } 3547 /** 3548 * This is mainly here for legacy purposes. 3549 * 3550 * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. 3551 * 3552 * @return {any} 3553 */ 3554 readJSON() { 3555 return readAny(this.restDecoder); 3556 } 3557 /** 3558 * @return {string} 3559 */ 3560 readKey() { 3561 const keyClock = this.keyClockDecoder.read(); 3562 if (keyClock < this.keys.length) { 3563 return this.keys[keyClock]; 3564 } else { 3565 const key = this.stringDecoder.read(); 3566 this.keys.push(key); 3567 return key; 3568 } 3569 } 3570 }; 3571 var DSEncoderV1 = class { 3572 constructor() { 3573 this.restEncoder = createEncoder(); 3574 } 3575 toUint8Array() { 3576 return toUint8Array(this.restEncoder); 3577 } 3578 resetDsCurVal() { 3579 } 3580 /** 3581 * @param {number} clock 3582 */ 3583 writeDsClock(clock) { 3584 writeVarUint(this.restEncoder, clock); 3585 } 3586 /** 3587 * @param {number} len 3588 */ 3589 writeDsLen(len) { 3590 writeVarUint(this.restEncoder, len); 3591 } 3592 }; 3593 var UpdateEncoderV1 = class extends DSEncoderV1 { 3594 /** 3595 * @param {ID} id 3596 */ 3597 writeLeftID(id2) { 3598 writeVarUint(this.restEncoder, id2.client); 3599 writeVarUint(this.restEncoder, id2.clock); 3600 } 3601 /** 3602 * @param {ID} id 3603 */ 3604 writeRightID(id2) { 3605 writeVarUint(this.restEncoder, id2.client); 3606 writeVarUint(this.restEncoder, id2.clock); 3607 } 3608 /** 3609 * Use writeClient and writeClock instead of writeID if possible. 3610 * @param {number} client 3611 */ 3612 writeClient(client) { 3613 writeVarUint(this.restEncoder, client); 3614 } 3615 /** 3616 * @param {number} info An unsigned 8-bit integer 3617 */ 3618 writeInfo(info) { 3619 writeUint8(this.restEncoder, info); 3620 } 3621 /** 3622 * @param {string} s 3623 */ 3624 writeString(s) { 3625 writeVarString(this.restEncoder, s); 3626 } 3627 /** 3628 * @param {boolean} isYKey 3629 */ 3630 writeParentInfo(isYKey) { 3631 writeVarUint(this.restEncoder, isYKey ? 1 : 0); 3632 } 3633 /** 3634 * @param {number} info An unsigned 8-bit integer 3635 */ 3636 writeTypeRef(info) { 3637 writeVarUint(this.restEncoder, info); 3638 } 3639 /** 3640 * Write len of a struct - well suited for Opt RLE encoder. 3641 * 3642 * @param {number} len 3643 */ 3644 writeLen(len) { 3645 writeVarUint(this.restEncoder, len); 3646 } 3647 /** 3648 * @param {any} any 3649 */ 3650 writeAny(any2) { 3651 writeAny(this.restEncoder, any2); 3652 } 3653 /** 3654 * @param {Uint8Array} buf 3655 */ 3656 writeBuf(buf) { 3657 writeVarUint8Array(this.restEncoder, buf); 3658 } 3659 /** 3660 * @param {any} embed 3661 */ 3662 writeJSON(embed) { 3663 writeVarString(this.restEncoder, JSON.stringify(embed)); 3664 } 3665 /** 3666 * @param {string} key 3667 */ 3668 writeKey(key) { 3669 writeVarString(this.restEncoder, key); 3670 } 3671 }; 3672 var DSEncoderV2 = class { 3673 constructor() { 3674 this.restEncoder = createEncoder(); 3675 this.dsCurrVal = 0; 3676 } 3677 toUint8Array() { 3678 return toUint8Array(this.restEncoder); 3679 } 3680 resetDsCurVal() { 3681 this.dsCurrVal = 0; 3682 } 3683 /** 3684 * @param {number} clock 3685 */ 3686 writeDsClock(clock) { 3687 const diff = clock - this.dsCurrVal; 3688 this.dsCurrVal = clock; 3689 writeVarUint(this.restEncoder, diff); 3690 } 3691 /** 3692 * @param {number} len 3693 */ 3694 writeDsLen(len) { 3695 if (len === 0) { 3696 unexpectedCase(); 3697 } 3698 writeVarUint(this.restEncoder, len - 1); 3699 this.dsCurrVal += len; 3700 } 3701 }; 3702 var UpdateEncoderV2 = class extends DSEncoderV2 { 3703 constructor() { 3704 super(); 3705 this.keyMap = /* @__PURE__ */ new Map(); 3706 this.keyClock = 0; 3707 this.keyClockEncoder = new IntDiffOptRleEncoder(); 3708 this.clientEncoder = new UintOptRleEncoder(); 3709 this.leftClockEncoder = new IntDiffOptRleEncoder(); 3710 this.rightClockEncoder = new IntDiffOptRleEncoder(); 3711 this.infoEncoder = new RleEncoder(writeUint8); 3712 this.stringEncoder = new StringEncoder(); 3713 this.parentInfoEncoder = new RleEncoder(writeUint8); 3714 this.typeRefEncoder = new UintOptRleEncoder(); 3715 this.lenEncoder = new UintOptRleEncoder(); 3716 } 3717 toUint8Array() { 3718 const encoder = createEncoder(); 3719 writeVarUint(encoder, 0); 3720 writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); 3721 writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); 3722 writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); 3723 writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); 3724 writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); 3725 writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); 3726 writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); 3727 writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); 3728 writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); 3729 writeUint8Array(encoder, toUint8Array(this.restEncoder)); 3730 return toUint8Array(encoder); 3731 } 3732 /** 3733 * @param {ID} id 3734 */ 3735 writeLeftID(id2) { 3736 this.clientEncoder.write(id2.client); 3737 this.leftClockEncoder.write(id2.clock); 3738 } 3739 /** 3740 * @param {ID} id 3741 */ 3742 writeRightID(id2) { 3743 this.clientEncoder.write(id2.client); 3744 this.rightClockEncoder.write(id2.clock); 3745 } 3746 /** 3747 * @param {number} client 3748 */ 3749 writeClient(client) { 3750 this.clientEncoder.write(client); 3751 } 3752 /** 3753 * @param {number} info An unsigned 8-bit integer 3754 */ 3755 writeInfo(info) { 3756 this.infoEncoder.write(info); 3757 } 3758 /** 3759 * @param {string} s 3760 */ 3761 writeString(s) { 3762 this.stringEncoder.write(s); 3763 } 3764 /** 3765 * @param {boolean} isYKey 3766 */ 3767 writeParentInfo(isYKey) { 3768 this.parentInfoEncoder.write(isYKey ? 1 : 0); 3769 } 3770 /** 3771 * @param {number} info An unsigned 8-bit integer 3772 */ 3773 writeTypeRef(info) { 3774 this.typeRefEncoder.write(info); 3775 } 3776 /** 3777 * Write len of a struct - well suited for Opt RLE encoder. 3778 * 3779 * @param {number} len 3780 */ 3781 writeLen(len) { 3782 this.lenEncoder.write(len); 3783 } 3784 /** 3785 * @param {any} any 3786 */ 3787 writeAny(any2) { 3788 writeAny(this.restEncoder, any2); 3789 } 3790 /** 3791 * @param {Uint8Array} buf 3792 */ 3793 writeBuf(buf) { 3794 writeVarUint8Array(this.restEncoder, buf); 3795 } 3796 /** 3797 * This is mainly here for legacy purposes. 3798 * 3799 * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder. 3800 * 3801 * @param {any} embed 3802 */ 3803 writeJSON(embed) { 3804 writeAny(this.restEncoder, embed); 3805 } 3806 /** 3807 * Property keys are often reused. For example, in y-prosemirror the key `bold` might 3808 * occur very often. For a 3d application, the key `position` might occur very often. 3809 * 3810 * We cache these keys in a Map and refer to them via a unique number. 3811 * 3812 * @param {string} key 3813 */ 3814 writeKey(key) { 3815 const clock = this.keyMap.get(key); 3816 if (clock === void 0) { 3817 this.keyClockEncoder.write(this.keyClock++); 3818 this.stringEncoder.write(key); 3819 } else { 3820 this.keyClockEncoder.write(clock); 3821 } 3822 } 3823 }; 3824 var writeStructs = (encoder, structs, client, clock) => { 3825 clock = max(clock, structs[0].id.clock); 3826 const startNewStructs = findIndexSS(structs, clock); 3827 writeVarUint(encoder.restEncoder, structs.length - startNewStructs); 3828 encoder.writeClient(client); 3829 writeVarUint(encoder.restEncoder, clock); 3830 const firstStruct = structs[startNewStructs]; 3831 firstStruct.write(encoder, clock - firstStruct.id.clock); 3832 for (let i = startNewStructs + 1; i < structs.length; i++) { 3833 structs[i].write(encoder, 0); 3834 } 3835 }; 3836 var writeClientsStructs = (encoder, store2, _sm) => { 3837 const sm = /* @__PURE__ */ new Map(); 3838 _sm.forEach((clock, client) => { 3839 if (getState(store2, client) > clock) { 3840 sm.set(client, clock); 3841 } 3842 }); 3843 getStateVector(store2).forEach((_clock, client) => { 3844 if (!_sm.has(client)) { 3845 sm.set(client, 0); 3846 } 3847 }); 3848 writeVarUint(encoder.restEncoder, sm.size); 3849 from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { 3850 writeStructs( 3851 encoder, 3852 /** @type {Array<GC|Item>} */ 3853 store2.clients.get(client), 3854 client, 3855 clock 3856 ); 3857 }); 3858 }; 3859 var readClientsStructRefs = (decoder, doc2) => { 3860 const clientRefs = create(); 3861 const numOfStateUpdates = readVarUint(decoder.restDecoder); 3862 for (let i = 0; i < numOfStateUpdates; i++) { 3863 const numberOfStructs = readVarUint(decoder.restDecoder); 3864 const refs = new Array(numberOfStructs); 3865 const client = decoder.readClient(); 3866 let clock = readVarUint(decoder.restDecoder); 3867 clientRefs.set(client, { i: 0, refs }); 3868 for (let i2 = 0; i2 < numberOfStructs; i2++) { 3869 const info = decoder.readInfo(); 3870 switch (BITS5 & info) { 3871 case 0: { 3872 const len = decoder.readLen(); 3873 refs[i2] = new GC(createID(client, clock), len); 3874 clock += len; 3875 break; 3876 } 3877 case 10: { 3878 const len = readVarUint(decoder.restDecoder); 3879 refs[i2] = new Skip(createID(client, clock), len); 3880 clock += len; 3881 break; 3882 } 3883 default: { 3884 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; 3885 const struct = new Item( 3886 createID(client, clock), 3887 null, 3888 // left 3889 (info & BIT8) === BIT8 ? decoder.readLeftID() : null, 3890 // origin 3891 null, 3892 // right 3893 (info & BIT7) === BIT7 ? decoder.readRightID() : null, 3894 // right origin 3895 cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null, 3896 // parent 3897 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, 3898 // parentSub 3899 readItemContent(decoder, info) 3900 // item content 3901 ); 3902 refs[i2] = struct; 3903 clock += struct.length; 3904 } 3905 } 3906 } 3907 } 3908 return clientRefs; 3909 }; 3910 var integrateStructs = (transaction, store2, clientsStructRefs) => { 3911 const stack = []; 3912 let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b); 3913 if (clientsStructRefsIds.length === 0) { 3914 return null; 3915 } 3916 const getNextStructTarget = () => { 3917 if (clientsStructRefsIds.length === 0) { 3918 return null; 3919 } 3920 let nextStructsTarget = ( 3921 /** @type {{i:number,refs:Array<GC|Item>}} */ 3922 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]) 3923 ); 3924 while (nextStructsTarget.refs.length === nextStructsTarget.i) { 3925 clientsStructRefsIds.pop(); 3926 if (clientsStructRefsIds.length > 0) { 3927 nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */ 3928 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]); 3929 } else { 3930 return null; 3931 } 3932 } 3933 return nextStructsTarget; 3934 }; 3935 let curStructsTarget = getNextStructTarget(); 3936 if (curStructsTarget === null) { 3937 return null; 3938 } 3939 const restStructs = new StructStore(); 3940 const missingSV = /* @__PURE__ */ new Map(); 3941 const updateMissingSv = (client, clock) => { 3942 const mclock = missingSV.get(client); 3943 if (mclock == null || mclock > clock) { 3944 missingSV.set(client, clock); 3945 } 3946 }; 3947 let stackHead = ( 3948 /** @type {any} */ 3949 curStructsTarget.refs[ 3950 /** @type {any} */ 3951 curStructsTarget.i++ 3952 ] 3953 ); 3954 const state = /* @__PURE__ */ new Map(); 3955 const addStackToRestSS = () => { 3956 for (const item of stack) { 3957 const client = item.id.client; 3958 const inapplicableItems = clientsStructRefs.get(client); 3959 if (inapplicableItems) { 3960 inapplicableItems.i--; 3961 restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i)); 3962 clientsStructRefs.delete(client); 3963 inapplicableItems.i = 0; 3964 inapplicableItems.refs = []; 3965 } else { 3966 restStructs.clients.set(client, [item]); 3967 } 3968 clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client); 3969 } 3970 stack.length = 0; 3971 }; 3972 while (true) { 3973 if (stackHead.constructor !== Skip) { 3974 const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store2, stackHead.id.client)); 3975 const offset = localClock - stackHead.id.clock; 3976 if (offset < 0) { 3977 stack.push(stackHead); 3978 updateMissingSv(stackHead.id.client, stackHead.id.clock - 1); 3979 addStackToRestSS(); 3980 } else { 3981 const missing = stackHead.getMissing(transaction, store2); 3982 if (missing !== null) { 3983 stack.push(stackHead); 3984 const structRefs = clientsStructRefs.get( 3985 /** @type {number} */ 3986 missing 3987 ) || { refs: [], i: 0 }; 3988 if (structRefs.refs.length === structRefs.i) { 3989 updateMissingSv( 3990 /** @type {number} */ 3991 missing, 3992 getState(store2, missing) 3993 ); 3994 addStackToRestSS(); 3995 } else { 3996 stackHead = structRefs.refs[structRefs.i++]; 3997 continue; 3998 } 3999 } else if (offset === 0 || offset < stackHead.length) { 4000 stackHead.integrate(transaction, offset); 4001 state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); 4002 } 4003 } 4004 } 4005 if (stack.length > 0) { 4006 stackHead = /** @type {GC|Item} */ 4007 stack.pop(); 4008 } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { 4009 stackHead = /** @type {GC|Item} */ 4010 curStructsTarget.refs[curStructsTarget.i++]; 4011 } else { 4012 curStructsTarget = getNextStructTarget(); 4013 if (curStructsTarget === null) { 4014 break; 4015 } else { 4016 stackHead = /** @type {GC|Item} */ 4017 curStructsTarget.refs[curStructsTarget.i++]; 4018 } 4019 } 4020 } 4021 if (restStructs.clients.size > 0) { 4022 const encoder = new UpdateEncoderV2(); 4023 writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map()); 4024 writeVarUint(encoder.restEncoder, 0); 4025 return { missing: missingSV, update: encoder.toUint8Array() }; 4026 } 4027 return null; 4028 }; 4029 var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); 4030 var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => { 4031 transaction.local = false; 4032 let retry = false; 4033 const doc2 = transaction.doc; 4034 const store2 = doc2.store; 4035 const ss = readClientsStructRefs(structDecoder, doc2); 4036 const restStructs = integrateStructs(transaction, store2, ss); 4037 const pending = store2.pendingStructs; 4038 if (pending) { 4039 for (const [client, clock] of pending.missing) { 4040 if (clock < getState(store2, client)) { 4041 retry = true; 4042 break; 4043 } 4044 } 4045 if (restStructs) { 4046 for (const [client, clock] of restStructs.missing) { 4047 const mclock = pending.missing.get(client); 4048 if (mclock == null || mclock > clock) { 4049 pending.missing.set(client, clock); 4050 } 4051 } 4052 pending.update = mergeUpdatesV2([pending.update, restStructs.update]); 4053 } 4054 } else { 4055 store2.pendingStructs = restStructs; 4056 } 4057 const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store2); 4058 if (store2.pendingDs) { 4059 const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store2.pendingDs)); 4060 readVarUint(pendingDSUpdate.restDecoder); 4061 const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store2); 4062 if (dsRest && dsRest2) { 4063 store2.pendingDs = mergeUpdatesV2([dsRest, dsRest2]); 4064 } else { 4065 store2.pendingDs = dsRest || dsRest2; 4066 } 4067 } else { 4068 store2.pendingDs = dsRest; 4069 } 4070 if (retry) { 4071 const update = ( 4072 /** @type {{update: Uint8Array}} */ 4073 store2.pendingStructs.update 4074 ); 4075 store2.pendingStructs = null; 4076 applyUpdateV2(transaction.doc, update); 4077 } 4078 }, transactionOrigin, false); 4079 var readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder)); 4080 var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { 4081 const decoder = createDecoder(update); 4082 readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); 4083 }; 4084 var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1); 4085 var writeStateAsUpdate = (encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => { 4086 writeClientsStructs(encoder, doc2.store, targetStateVector); 4087 writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store)); 4088 }; 4089 var encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => { 4090 const targetStateVector = decodeStateVector(encodedTargetStateVector); 4091 writeStateAsUpdate(encoder, doc2, targetStateVector); 4092 const updates = [encoder.toUint8Array()]; 4093 if (doc2.store.pendingDs) { 4094 updates.push(doc2.store.pendingDs); 4095 } 4096 if (doc2.store.pendingStructs) { 4097 updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector)); 4098 } 4099 if (updates.length > 1) { 4100 if (encoder.constructor === UpdateEncoderV1) { 4101 return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update))); 4102 } else if (encoder.constructor === UpdateEncoderV2) { 4103 return mergeUpdatesV2(updates); 4104 } 4105 } 4106 return updates[0]; 4107 }; 4108 var encodeStateAsUpdate = (doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1()); 4109 var readStateVector = (decoder) => { 4110 const ss = /* @__PURE__ */ new Map(); 4111 const ssLength = readVarUint(decoder.restDecoder); 4112 for (let i = 0; i < ssLength; i++) { 4113 const client = readVarUint(decoder.restDecoder); 4114 const clock = readVarUint(decoder.restDecoder); 4115 ss.set(client, clock); 4116 } 4117 return ss; 4118 }; 4119 var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))); 4120 var writeStateVector = (encoder, sv) => { 4121 writeVarUint(encoder.restEncoder, sv.size); 4122 from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { 4123 writeVarUint(encoder.restEncoder, client); 4124 writeVarUint(encoder.restEncoder, clock); 4125 }); 4126 return encoder; 4127 }; 4128 var writeDocumentStateVector = (encoder, doc2) => writeStateVector(encoder, getStateVector(doc2.store)); 4129 var encodeStateVectorV2 = (doc2, encoder = new DSEncoderV2()) => { 4130 if (doc2 instanceof Map) { 4131 writeStateVector(encoder, doc2); 4132 } else { 4133 writeDocumentStateVector(encoder, doc2); 4134 } 4135 return encoder.toUint8Array(); 4136 }; 4137 var encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1()); 4138 var EventHandler = class { 4139 constructor() { 4140 this.l = []; 4141 } 4142 }; 4143 var createEventHandler = () => new EventHandler(); 4144 var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f); 4145 var removeEventHandlerListener = (eventHandler, f) => { 4146 const l = eventHandler.l; 4147 const len = l.length; 4148 eventHandler.l = l.filter((g) => f !== g); 4149 if (len === eventHandler.l.length) { 4150 console.error("[yjs] Tried to remove event handler that doesn't exist."); 4151 } 4152 }; 4153 var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]); 4154 var ID = class { 4155 /** 4156 * @param {number} client client id 4157 * @param {number} clock unique per client id, continuous number 4158 */ 4159 constructor(client, clock) { 4160 this.client = client; 4161 this.clock = clock; 4162 } 4163 }; 4164 var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock; 4165 var createID = (client, clock) => new ID(client, clock); 4166 var writeID = (encoder, id2) => { 4167 writeVarUint(encoder, id2.client); 4168 writeVarUint(encoder, id2.clock); 4169 }; 4170 var readID = (decoder) => createID(readVarUint(decoder), readVarUint(decoder)); 4171 var findRootTypeKey = (type) => { 4172 for (const [key, value] of type.doc.share.entries()) { 4173 if (value === type) { 4174 return key; 4175 } 4176 } 4177 throw unexpectedCase(); 4178 }; 4179 var isParentOf = (parent, child) => { 4180 while (child !== null) { 4181 if (child.parent === parent) { 4182 return true; 4183 } 4184 child = /** @type {AbstractType<any>} */ 4185 child.parent._item; 4186 } 4187 return false; 4188 }; 4189 var logType = (type) => { 4190 const res = []; 4191 let n = type._start; 4192 while (n) { 4193 res.push(n); 4194 n = n.right; 4195 } 4196 console.log("Children: ", res); 4197 console.log("Children content: ", res.filter((m) => !m.deleted).map((m) => m.content)); 4198 }; 4199 var PermanentUserData = class { 4200 /** 4201 * @param {Doc} doc 4202 * @param {YMap<any>} [storeType] 4203 */ 4204 constructor(doc2, storeType = doc2.getMap("users")) { 4205 const dss = /* @__PURE__ */ new Map(); 4206 this.yusers = storeType; 4207 this.doc = doc2; 4208 this.clients = /* @__PURE__ */ new Map(); 4209 this.dss = dss; 4210 const initUser = (user, userDescription) => { 4211 const ds = user.get("ds"); 4212 const ids = user.get("ids"); 4213 const addClientId = ( 4214 /** @param {number} clientid */ 4215 (clientid) => this.clients.set(clientid, userDescription) 4216 ); 4217 ds.observe( 4218 /** @param {YArrayEvent<any>} event */ 4219 (event) => { 4220 event.changes.added.forEach((item) => { 4221 item.content.getContent().forEach((encodedDs) => { 4222 if (encodedDs instanceof Uint8Array) { 4223 this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))])); 4224 } 4225 }); 4226 }); 4227 } 4228 ); 4229 this.dss.set(userDescription, mergeDeleteSets(ds.map((encodedDs) => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))))); 4230 ids.observe( 4231 /** @param {YArrayEvent<any>} event */ 4232 (event) => event.changes.added.forEach((item) => item.content.getContent().forEach(addClientId)) 4233 ); 4234 ids.forEach(addClientId); 4235 }; 4236 storeType.observe((event) => { 4237 event.keysChanged.forEach( 4238 (userDescription) => initUser(storeType.get(userDescription), userDescription) 4239 ); 4240 }); 4241 storeType.forEach(initUser); 4242 } 4243 /** 4244 * @param {Doc} doc 4245 * @param {number} clientid 4246 * @param {string} userDescription 4247 * @param {Object} conf 4248 * @param {function(Transaction, DeleteSet):boolean} [conf.filter] 4249 */ 4250 setUserMapping(doc2, clientid, userDescription, { filter = () => true } = {}) { 4251 const users2 = this.yusers; 4252 let user = users2.get(userDescription); 4253 if (!user) { 4254 user = new YMap(); 4255 user.set("ids", new YArray()); 4256 user.set("ds", new YArray()); 4257 users2.set(userDescription, user); 4258 } 4259 user.get("ids").push([clientid]); 4260 users2.observe((_event) => { 4261 setTimeout(() => { 4262 const userOverwrite = users2.get(userDescription); 4263 if (userOverwrite !== user) { 4264 user = userOverwrite; 4265 this.clients.forEach((_userDescription, clientid2) => { 4266 if (userDescription === _userDescription) { 4267 user.get("ids").push([clientid2]); 4268 } 4269 }); 4270 const encoder = new DSEncoderV1(); 4271 const ds = this.dss.get(userDescription); 4272 if (ds) { 4273 writeDeleteSet(encoder, ds); 4274 user.get("ds").push([encoder.toUint8Array()]); 4275 } 4276 } 4277 }, 0); 4278 }); 4279 doc2.on( 4280 "afterTransaction", 4281 /** @param {Transaction} transaction */ 4282 (transaction) => { 4283 setTimeout(() => { 4284 const yds = user.get("ds"); 4285 const ds = transaction.deleteSet; 4286 if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) { 4287 const encoder = new DSEncoderV1(); 4288 writeDeleteSet(encoder, ds); 4289 yds.push([encoder.toUint8Array()]); 4290 } 4291 }); 4292 } 4293 ); 4294 } 4295 /** 4296 * @param {number} clientid 4297 * @return {any} 4298 */ 4299 getUserByClientId(clientid) { 4300 return this.clients.get(clientid) || null; 4301 } 4302 /** 4303 * @param {ID} id 4304 * @return {string | null} 4305 */ 4306 getUserByDeletedId(id2) { 4307 for (const [userDescription, ds] of this.dss.entries()) { 4308 if (isDeleted(ds, id2)) { 4309 return userDescription; 4310 } 4311 } 4312 return null; 4313 } 4314 }; 4315 var RelativePosition = class { 4316 /** 4317 * @param {ID|null} type 4318 * @param {string|null} tname 4319 * @param {ID|null} item 4320 * @param {number} assoc 4321 */ 4322 constructor(type, tname, item, assoc = 0) { 4323 this.type = type; 4324 this.tname = tname; 4325 this.item = item; 4326 this.assoc = assoc; 4327 } 4328 }; 4329 var relativePositionToJSON = (rpos) => { 4330 const json = {}; 4331 if (rpos.type) { 4332 json.type = rpos.type; 4333 } 4334 if (rpos.tname) { 4335 json.tname = rpos.tname; 4336 } 4337 if (rpos.item) { 4338 json.item = rpos.item; 4339 } 4340 if (rpos.assoc != null) { 4341 json.assoc = rpos.assoc; 4342 } 4343 return json; 4344 }; 4345 var createRelativePositionFromJSON = (json) => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc); 4346 var AbsolutePosition = class { 4347 /** 4348 * @param {AbstractType<any>} type 4349 * @param {number} index 4350 * @param {number} [assoc] 4351 */ 4352 constructor(type, index, assoc = 0) { 4353 this.type = type; 4354 this.index = index; 4355 this.assoc = assoc; 4356 } 4357 }; 4358 var createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc); 4359 var createRelativePosition = (type, item, assoc) => { 4360 let typeid = null; 4361 let tname = null; 4362 if (type._item === null) { 4363 tname = findRootTypeKey(type); 4364 } else { 4365 typeid = createID(type._item.id.client, type._item.id.clock); 4366 } 4367 return new RelativePosition(typeid, tname, item, assoc); 4368 }; 4369 var createRelativePositionFromTypeIndex = (type, index, assoc = 0) => { 4370 let t = type._start; 4371 if (assoc < 0) { 4372 if (index === 0) { 4373 return createRelativePosition(type, null, assoc); 4374 } 4375 index--; 4376 } 4377 while (t !== null) { 4378 if (!t.deleted && t.countable) { 4379 if (t.length > index) { 4380 return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc); 4381 } 4382 index -= t.length; 4383 } 4384 if (t.right === null && assoc < 0) { 4385 return createRelativePosition(type, t.lastId, assoc); 4386 } 4387 t = t.right; 4388 } 4389 return createRelativePosition(type, null, assoc); 4390 }; 4391 var writeRelativePosition = (encoder, rpos) => { 4392 const { type, tname, item, assoc } = rpos; 4393 if (item !== null) { 4394 writeVarUint(encoder, 0); 4395 writeID(encoder, item); 4396 } else if (tname !== null) { 4397 writeUint8(encoder, 1); 4398 writeVarString(encoder, tname); 4399 } else if (type !== null) { 4400 writeUint8(encoder, 2); 4401 writeID(encoder, type); 4402 } else { 4403 throw unexpectedCase(); 4404 } 4405 writeVarInt(encoder, assoc); 4406 return encoder; 4407 }; 4408 var encodeRelativePosition = (rpos) => { 4409 const encoder = createEncoder(); 4410 writeRelativePosition(encoder, rpos); 4411 return toUint8Array(encoder); 4412 }; 4413 var readRelativePosition = (decoder) => { 4414 let type = null; 4415 let tname = null; 4416 let itemID = null; 4417 switch (readVarUint(decoder)) { 4418 case 0: 4419 itemID = readID(decoder); 4420 break; 4421 case 1: 4422 tname = readVarString(decoder); 4423 break; 4424 case 2: { 4425 type = readID(decoder); 4426 } 4427 } 4428 const assoc = hasContent(decoder) ? readVarInt(decoder) : 0; 4429 return new RelativePosition(type, tname, itemID, assoc); 4430 }; 4431 var decodeRelativePosition = (uint8Array) => readRelativePosition(createDecoder(uint8Array)); 4432 var getItemWithOffset = (store2, id2) => { 4433 const item = getItem(store2, id2); 4434 const diff = id2.clock - item.id.clock; 4435 return { 4436 item, 4437 diff 4438 }; 4439 }; 4440 var createAbsolutePositionFromRelativePosition = (rpos, doc2, followUndoneDeletions = true) => { 4441 const store2 = doc2.store; 4442 const rightID = rpos.item; 4443 const typeID = rpos.type; 4444 const tname = rpos.tname; 4445 const assoc = rpos.assoc; 4446 let type = null; 4447 let index = 0; 4448 if (rightID !== null) { 4449 if (getState(store2, rightID.client) <= rightID.clock) { 4450 return null; 4451 } 4452 const res = followUndoneDeletions ? followRedone(store2, rightID) : getItemWithOffset(store2, rightID); 4453 const right = res.item; 4454 if (!(right instanceof Item)) { 4455 return null; 4456 } 4457 type = /** @type {AbstractType<any>} */ 4458 right.parent; 4459 if (type._item === null || !type._item.deleted) { 4460 index = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1); 4461 let n = right.left; 4462 while (n !== null) { 4463 if (!n.deleted && n.countable) { 4464 index += n.length; 4465 } 4466 n = n.left; 4467 } 4468 } 4469 } else { 4470 if (tname !== null) { 4471 type = doc2.get(tname); 4472 } else if (typeID !== null) { 4473 if (getState(store2, typeID.client) <= typeID.clock) { 4474 return null; 4475 } 4476 const { item } = followUndoneDeletions ? followRedone(store2, typeID) : { item: getItem(store2, typeID) }; 4477 if (item instanceof Item && item.content instanceof ContentType) { 4478 type = item.content.type; 4479 } else { 4480 return null; 4481 } 4482 } else { 4483 throw unexpectedCase(); 4484 } 4485 if (assoc >= 0) { 4486 index = type._length; 4487 } else { 4488 index = 0; 4489 } 4490 } 4491 return createAbsolutePosition(type, index, rpos.assoc); 4492 }; 4493 var compareRelativePositions = (a, b) => a === b || a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc; 4494 var Snapshot = class { 4495 /** 4496 * @param {DeleteSet} ds 4497 * @param {Map<number,number>} sv state map 4498 */ 4499 constructor(ds, sv) { 4500 this.ds = ds; 4501 this.sv = sv; 4502 } 4503 }; 4504 var equalSnapshots = (snap1, snap2) => { 4505 const ds1 = snap1.ds.clients; 4506 const ds2 = snap2.ds.clients; 4507 const sv1 = snap1.sv; 4508 const sv2 = snap2.sv; 4509 if (sv1.size !== sv2.size || ds1.size !== ds2.size) { 4510 return false; 4511 } 4512 for (const [key, value] of sv1.entries()) { 4513 if (sv2.get(key) !== value) { 4514 return false; 4515 } 4516 } 4517 for (const [client, dsitems1] of ds1.entries()) { 4518 const dsitems2 = ds2.get(client) || []; 4519 if (dsitems1.length !== dsitems2.length) { 4520 return false; 4521 } 4522 for (let i = 0; i < dsitems1.length; i++) { 4523 const dsitem1 = dsitems1[i]; 4524 const dsitem2 = dsitems2[i]; 4525 if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) { 4526 return false; 4527 } 4528 } 4529 } 4530 return true; 4531 }; 4532 var encodeSnapshotV2 = (snapshot2, encoder = new DSEncoderV2()) => { 4533 writeDeleteSet(encoder, snapshot2.ds); 4534 writeStateVector(encoder, snapshot2.sv); 4535 return encoder.toUint8Array(); 4536 }; 4537 var encodeSnapshot = (snapshot2) => encodeSnapshotV2(snapshot2, new DSEncoderV1()); 4538 var decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => { 4539 return new Snapshot(readDeleteSet(decoder), readStateVector(decoder)); 4540 }; 4541 var decodeSnapshot = (buf) => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf))); 4542 var createSnapshot = (ds, sm) => new Snapshot(ds, sm); 4543 var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map()); 4544 var snapshot = (doc2) => createSnapshot(createDeleteSetFromStructStore(doc2.store), getStateVector(doc2.store)); 4545 var isVisible = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && (snapshot2.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot2.ds, item.id); 4546 var splitSnapshotAffectedStructs = (transaction, snapshot2) => { 4547 const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2); 4548 const store2 = transaction.doc.store; 4549 if (!meta.has(snapshot2)) { 4550 snapshot2.sv.forEach((clock, client) => { 4551 if (clock < getState(store2, client)) { 4552 getItemCleanStart(transaction, createID(client, clock)); 4553 } 4554 }); 4555 iterateDeletedStructs(transaction, snapshot2.ds, (_item) => { 4556 }); 4557 meta.add(snapshot2); 4558 } 4559 }; 4560 var createDocFromSnapshot = (originDoc, snapshot2, newDoc = new Doc()) => { 4561 if (originDoc.gc) { 4562 throw new Error("Garbage-collection must be disabled in `originDoc`!"); 4563 } 4564 const { sv, ds } = snapshot2; 4565 const encoder = new UpdateEncoderV2(); 4566 originDoc.transact((transaction) => { 4567 let size2 = 0; 4568 sv.forEach((clock) => { 4569 if (clock > 0) { 4570 size2++; 4571 } 4572 }); 4573 writeVarUint(encoder.restEncoder, size2); 4574 for (const [client, clock] of sv) { 4575 if (clock === 0) { 4576 continue; 4577 } 4578 if (clock < getState(originDoc.store, client)) { 4579 getItemCleanStart(transaction, createID(client, clock)); 4580 } 4581 const structs = originDoc.store.clients.get(client) || []; 4582 const lastStructIndex = findIndexSS(structs, clock - 1); 4583 writeVarUint(encoder.restEncoder, lastStructIndex + 1); 4584 encoder.writeClient(client); 4585 writeVarUint(encoder.restEncoder, 0); 4586 for (let i = 0; i <= lastStructIndex; i++) { 4587 structs[i].write(encoder, 0); 4588 } 4589 } 4590 writeDeleteSet(encoder, ds); 4591 }); 4592 applyUpdateV2(newDoc, encoder.toUint8Array(), "snapshot"); 4593 return newDoc; 4594 }; 4595 var snapshotContainsUpdateV2 = (snapshot2, update, YDecoder = UpdateDecoderV2) => { 4596 const updateDecoder = new YDecoder(createDecoder(update)); 4597 const lazyDecoder = new LazyStructReader(updateDecoder, false); 4598 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 4599 if ((snapshot2.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) { 4600 return false; 4601 } 4602 } 4603 const mergedDS = mergeDeleteSets([snapshot2.ds, readDeleteSet(updateDecoder)]); 4604 return equalDeleteSets(snapshot2.ds, mergedDS); 4605 }; 4606 var snapshotContainsUpdate = (snapshot2, update) => snapshotContainsUpdateV2(snapshot2, update, UpdateDecoderV1); 4607 var StructStore = class { 4608 constructor() { 4609 this.clients = /* @__PURE__ */ new Map(); 4610 this.pendingStructs = null; 4611 this.pendingDs = null; 4612 } 4613 }; 4614 var getStateVector = (store2) => { 4615 const sm = /* @__PURE__ */ new Map(); 4616 store2.clients.forEach((structs, client) => { 4617 const struct = structs[structs.length - 1]; 4618 sm.set(client, struct.id.clock + struct.length); 4619 }); 4620 return sm; 4621 }; 4622 var getState = (store2, client) => { 4623 const structs = store2.clients.get(client); 4624 if (structs === void 0) { 4625 return 0; 4626 } 4627 const lastStruct = structs[structs.length - 1]; 4628 return lastStruct.id.clock + lastStruct.length; 4629 }; 4630 var addStruct = (store2, struct) => { 4631 let structs = store2.clients.get(struct.id.client); 4632 if (structs === void 0) { 4633 structs = []; 4634 store2.clients.set(struct.id.client, structs); 4635 } else { 4636 const lastStruct = structs[structs.length - 1]; 4637 if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { 4638 throw unexpectedCase(); 4639 } 4640 } 4641 structs.push(struct); 4642 }; 4643 var findIndexSS = (structs, clock) => { 4644 let left = 0; 4645 let right = structs.length - 1; 4646 let mid = structs[right]; 4647 let midclock = mid.id.clock; 4648 if (midclock === clock) { 4649 return right; 4650 } 4651 let midindex = floor(clock / (midclock + mid.length - 1) * right); 4652 while (left <= right) { 4653 mid = structs[midindex]; 4654 midclock = mid.id.clock; 4655 if (midclock <= clock) { 4656 if (clock < midclock + mid.length) { 4657 return midindex; 4658 } 4659 left = midindex + 1; 4660 } else { 4661 right = midindex - 1; 4662 } 4663 midindex = floor((left + right) / 2); 4664 } 4665 throw unexpectedCase(); 4666 }; 4667 var find = (store2, id2) => { 4668 const structs = store2.clients.get(id2.client); 4669 return structs[findIndexSS(structs, id2.clock)]; 4670 }; 4671 var getItem = ( 4672 /** @type {function(StructStore,ID):Item} */ 4673 find 4674 ); 4675 var findIndexCleanStart = (transaction, structs, clock) => { 4676 const index = findIndexSS(structs, clock); 4677 const struct = structs[index]; 4678 if (struct.id.clock < clock && struct instanceof Item) { 4679 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); 4680 return index + 1; 4681 } 4682 return index; 4683 }; 4684 var getItemCleanStart = (transaction, id2) => { 4685 const structs = ( 4686 /** @type {Array<Item>} */ 4687 transaction.doc.store.clients.get(id2.client) 4688 ); 4689 return structs[findIndexCleanStart(transaction, structs, id2.clock)]; 4690 }; 4691 var getItemCleanEnd = (transaction, store2, id2) => { 4692 const structs = store2.clients.get(id2.client); 4693 const index = findIndexSS(structs, id2.clock); 4694 const struct = structs[index]; 4695 if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { 4696 structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1)); 4697 } 4698 return struct; 4699 }; 4700 var replaceStruct = (store2, struct, newStruct) => { 4701 const structs = ( 4702 /** @type {Array<GC|Item>} */ 4703 store2.clients.get(struct.id.client) 4704 ); 4705 structs[findIndexSS(structs, struct.id.clock)] = newStruct; 4706 }; 4707 var iterateStructs = (transaction, structs, clockStart, len, f) => { 4708 if (len === 0) { 4709 return; 4710 } 4711 const clockEnd = clockStart + len; 4712 let index = findIndexCleanStart(transaction, structs, clockStart); 4713 let struct; 4714 do { 4715 struct = structs[index++]; 4716 if (clockEnd < struct.id.clock + struct.length) { 4717 findIndexCleanStart(transaction, structs, clockEnd); 4718 } 4719 f(struct); 4720 } while (index < structs.length && structs[index].id.clock < clockEnd); 4721 }; 4722 var Transaction = class { 4723 /** 4724 * @param {Doc} doc 4725 * @param {any} origin 4726 * @param {boolean} local 4727 */ 4728 constructor(doc2, origin2, local) { 4729 this.doc = doc2; 4730 this.deleteSet = new DeleteSet(); 4731 this.beforeState = getStateVector(doc2.store); 4732 this.afterState = /* @__PURE__ */ new Map(); 4733 this.changed = /* @__PURE__ */ new Map(); 4734 this.changedParentTypes = /* @__PURE__ */ new Map(); 4735 this._mergeStructs = []; 4736 this.origin = origin2; 4737 this.meta = /* @__PURE__ */ new Map(); 4738 this.local = local; 4739 this.subdocsAdded = /* @__PURE__ */ new Set(); 4740 this.subdocsRemoved = /* @__PURE__ */ new Set(); 4741 this.subdocsLoaded = /* @__PURE__ */ new Set(); 4742 this._needFormattingCleanup = false; 4743 } 4744 }; 4745 var writeUpdateMessageFromTransaction = (encoder, transaction) => { 4746 if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { 4747 return false; 4748 } 4749 sortAndMergeDeleteSet(transaction.deleteSet); 4750 writeStructsFromTransaction(encoder, transaction); 4751 writeDeleteSet(encoder, transaction.deleteSet); 4752 return true; 4753 }; 4754 var addChangedTypeToTransaction = (transaction, type, parentSub) => { 4755 const item = type._item; 4756 if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) { 4757 setIfUndefined(transaction.changed, type, create2).add(parentSub); 4758 } 4759 }; 4760 var tryToMergeWithLefts = (structs, pos) => { 4761 let right = structs[pos]; 4762 let left = structs[pos - 1]; 4763 let i = pos; 4764 for (; i > 0; right = left, left = structs[--i - 1]) { 4765 if (left.deleted === right.deleted && left.constructor === right.constructor) { 4766 if (left.mergeWith(right)) { 4767 if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */ 4768 right.parent._map.get(right.parentSub) === right) { 4769 right.parent._map.set( 4770 right.parentSub, 4771 /** @type {Item} */ 4772 left 4773 ); 4774 } 4775 continue; 4776 } 4777 } 4778 break; 4779 } 4780 const merged = pos - i; 4781 if (merged) { 4782 structs.splice(pos + 1 - merged, merged); 4783 } 4784 return merged; 4785 }; 4786 var tryGcDeleteSet = (ds, store2, gcFilter) => { 4787 for (const [client, deleteItems] of ds.clients.entries()) { 4788 const structs = ( 4789 /** @type {Array<GC|Item>} */ 4790 store2.clients.get(client) 4791 ); 4792 for (let di = deleteItems.length - 1; di >= 0; di--) { 4793 const deleteItem = deleteItems[di]; 4794 const endDeleteItemClock = deleteItem.clock + deleteItem.len; 4795 for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) { 4796 const struct2 = structs[si]; 4797 if (deleteItem.clock + deleteItem.len <= struct2.id.clock) { 4798 break; 4799 } 4800 if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) { 4801 struct2.gc(store2, false); 4802 } 4803 } 4804 } 4805 } 4806 }; 4807 var tryMergeDeleteSet = (ds, store2) => { 4808 ds.clients.forEach((deleteItems, client) => { 4809 const structs = ( 4810 /** @type {Array<GC|Item>} */ 4811 store2.clients.get(client) 4812 ); 4813 for (let di = deleteItems.length - 1; di >= 0; di--) { 4814 const deleteItem = deleteItems[di]; 4815 const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); 4816 for (let si = mostRightIndexToCheck, struct = structs[si]; si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) { 4817 si -= 1 + tryToMergeWithLefts(structs, si); 4818 } 4819 } 4820 }); 4821 }; 4822 var tryGc = (ds, store2, gcFilter) => { 4823 tryGcDeleteSet(ds, store2, gcFilter); 4824 tryMergeDeleteSet(ds, store2); 4825 }; 4826 var cleanupTransactions = (transactionCleanups, i) => { 4827 if (i < transactionCleanups.length) { 4828 const transaction = transactionCleanups[i]; 4829 const doc2 = transaction.doc; 4830 const store2 = doc2.store; 4831 const ds = transaction.deleteSet; 4832 const mergeStructs = transaction._mergeStructs; 4833 try { 4834 sortAndMergeDeleteSet(ds); 4835 transaction.afterState = getStateVector(transaction.doc.store); 4836 doc2.emit("beforeObserverCalls", [transaction, doc2]); 4837 const fs = []; 4838 transaction.changed.forEach( 4839 (subs, itemtype) => fs.push(() => { 4840 if (itemtype._item === null || !itemtype._item.deleted) { 4841 itemtype._callObserver(transaction, subs); 4842 } 4843 }) 4844 ); 4845 fs.push(() => { 4846 transaction.changedParentTypes.forEach((events, type) => { 4847 if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) { 4848 events = events.filter( 4849 (event) => event.target._item === null || !event.target._item.deleted 4850 ); 4851 events.forEach((event) => { 4852 event.currentTarget = type; 4853 event._path = null; 4854 }); 4855 events.sort((event1, event2) => event1.path.length - event2.path.length); 4856 fs.push(() => { 4857 callEventHandlerListeners(type._dEH, events, transaction); 4858 }); 4859 } 4860 }); 4861 fs.push(() => doc2.emit("afterTransaction", [transaction, doc2])); 4862 fs.push(() => { 4863 if (transaction._needFormattingCleanup) { 4864 cleanupYTextAfterTransaction(transaction); 4865 } 4866 }); 4867 }); 4868 callAll(fs, []); 4869 } finally { 4870 if (doc2.gc) { 4871 tryGcDeleteSet(ds, store2, doc2.gcFilter); 4872 } 4873 tryMergeDeleteSet(ds, store2); 4874 transaction.afterState.forEach((clock, client) => { 4875 const beforeClock = transaction.beforeState.get(client) || 0; 4876 if (beforeClock !== clock) { 4877 const structs = ( 4878 /** @type {Array<GC|Item>} */ 4879 store2.clients.get(client) 4880 ); 4881 const firstChangePos = max(findIndexSS(structs, beforeClock), 1); 4882 for (let i2 = structs.length - 1; i2 >= firstChangePos; ) { 4883 i2 -= 1 + tryToMergeWithLefts(structs, i2); 4884 } 4885 } 4886 }); 4887 for (let i2 = mergeStructs.length - 1; i2 >= 0; i2--) { 4888 const { client, clock } = mergeStructs[i2].id; 4889 const structs = ( 4890 /** @type {Array<GC|Item>} */ 4891 store2.clients.get(client) 4892 ); 4893 const replacedStructPos = findIndexSS(structs, clock); 4894 if (replacedStructPos + 1 < structs.length) { 4895 if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) { 4896 continue; 4897 } 4898 } 4899 if (replacedStructPos > 0) { 4900 tryToMergeWithLefts(structs, replacedStructPos); 4901 } 4902 } 4903 if (!transaction.local && transaction.afterState.get(doc2.clientID) !== transaction.beforeState.get(doc2.clientID)) { 4904 print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it."); 4905 doc2.clientID = generateNewClientId(); 4906 } 4907 doc2.emit("afterTransactionCleanup", [transaction, doc2]); 4908 if (doc2._observers.has("update")) { 4909 const encoder = new UpdateEncoderV1(); 4910 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); 4911 if (hasContent2) { 4912 doc2.emit("update", [encoder.toUint8Array(), transaction.origin, doc2, transaction]); 4913 } 4914 } 4915 if (doc2._observers.has("updateV2")) { 4916 const encoder = new UpdateEncoderV2(); 4917 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); 4918 if (hasContent2) { 4919 doc2.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc2, transaction]); 4920 } 4921 } 4922 const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction; 4923 if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) { 4924 subdocsAdded.forEach((subdoc) => { 4925 subdoc.clientID = doc2.clientID; 4926 if (subdoc.collectionid == null) { 4927 subdoc.collectionid = doc2.collectionid; 4928 } 4929 doc2.subdocs.add(subdoc); 4930 }); 4931 subdocsRemoved.forEach((subdoc) => doc2.subdocs.delete(subdoc)); 4932 doc2.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc2, transaction]); 4933 subdocsRemoved.forEach((subdoc) => subdoc.destroy()); 4934 } 4935 if (transactionCleanups.length <= i + 1) { 4936 doc2._transactionCleanups = []; 4937 doc2.emit("afterAllTransactions", [doc2, transactionCleanups]); 4938 } else { 4939 cleanupTransactions(transactionCleanups, i + 1); 4940 } 4941 } 4942 } 4943 }; 4944 var transact = (doc2, f, origin2 = null, local = true) => { 4945 const transactionCleanups = doc2._transactionCleanups; 4946 let initialCall = false; 4947 let result = null; 4948 if (doc2._transaction === null) { 4949 initialCall = true; 4950 doc2._transaction = new Transaction(doc2, origin2, local); 4951 transactionCleanups.push(doc2._transaction); 4952 if (transactionCleanups.length === 1) { 4953 doc2.emit("beforeAllTransactions", [doc2]); 4954 } 4955 doc2.emit("beforeTransaction", [doc2._transaction, doc2]); 4956 } 4957 try { 4958 result = f(doc2._transaction); 4959 } finally { 4960 if (initialCall) { 4961 const finishCleanup = doc2._transaction === transactionCleanups[0]; 4962 doc2._transaction = null; 4963 if (finishCleanup) { 4964 cleanupTransactions(transactionCleanups, 0); 4965 } 4966 } 4967 } 4968 return result; 4969 }; 4970 var StackItem = class { 4971 /** 4972 * @param {DeleteSet} deletions 4973 * @param {DeleteSet} insertions 4974 */ 4975 constructor(deletions, insertions) { 4976 this.insertions = insertions; 4977 this.deletions = deletions; 4978 this.meta = /* @__PURE__ */ new Map(); 4979 } 4980 }; 4981 var clearUndoManagerStackItem = (tr, um, stackItem) => { 4982 iterateDeletedStructs(tr, stackItem.deletions, (item) => { 4983 if (item instanceof Item && um.scope.some((type) => type === tr.doc || isParentOf( 4984 /** @type {AbstractType<any>} */ 4985 type, 4986 item 4987 ))) { 4988 keepItem(item, false); 4989 } 4990 }); 4991 }; 4992 var popStackItem = (undoManager2, stack, eventType) => { 4993 let _tr = null; 4994 const doc2 = undoManager2.doc; 4995 const scope = undoManager2.scope; 4996 transact(doc2, (transaction) => { 4997 while (stack.length > 0 && undoManager2.currStackItem === null) { 4998 const store2 = doc2.store; 4999 const stackItem = ( 5000 /** @type {StackItem} */ 5001 stack.pop() 5002 ); 5003 const itemsToRedo = /* @__PURE__ */ new Set(); 5004 const itemsToDelete = []; 5005 let performedChange = false; 5006 iterateDeletedStructs(transaction, stackItem.insertions, (struct) => { 5007 if (struct instanceof Item) { 5008 if (struct.redone !== null) { 5009 let { item, diff } = followRedone(store2, struct.id); 5010 if (diff > 0) { 5011 item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); 5012 } 5013 struct = item; 5014 } 5015 if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf( 5016 /** @type {AbstractType<any>} */ 5017 type, 5018 /** @type {Item} */ 5019 struct 5020 ))) { 5021 itemsToDelete.push(struct); 5022 } 5023 } 5024 }); 5025 iterateDeletedStructs(transaction, stackItem.deletions, (struct) => { 5026 if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf( 5027 /** @type {AbstractType<any>} */ 5028 type, 5029 struct 5030 )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval. 5031 !isDeleted(stackItem.insertions, struct.id)) { 5032 itemsToRedo.add(struct); 5033 } 5034 }); 5035 itemsToRedo.forEach((struct) => { 5036 performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager2.ignoreRemoteMapChanges, undoManager2) !== null || performedChange; 5037 }); 5038 for (let i = itemsToDelete.length - 1; i >= 0; i--) { 5039 const item = itemsToDelete[i]; 5040 if (undoManager2.deleteFilter(item)) { 5041 item.delete(transaction); 5042 performedChange = true; 5043 } 5044 } 5045 undoManager2.currStackItem = performedChange ? stackItem : null; 5046 } 5047 transaction.changed.forEach((subProps, type) => { 5048 if (subProps.has(null) && type._searchMarker) { 5049 type._searchMarker.length = 0; 5050 } 5051 }); 5052 _tr = transaction; 5053 }, undoManager2); 5054 const res = undoManager2.currStackItem; 5055 if (res != null) { 5056 const changedParentTypes = _tr.changedParentTypes; 5057 undoManager2.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager2 }, undoManager2]); 5058 undoManager2.currStackItem = null; 5059 } 5060 return res; 5061 }; 5062 var UndoManager = class extends ObservableV2 { 5063 /** 5064 * @param {Doc|AbstractType<any>|Array<AbstractType<any>>} typeScope Limits the scope of the UndoManager. If this is set to a ydoc instance, all changes on that ydoc will be undone. If set to a specific type, only changes on that type or its children will be undone. Also accepts an array of types. 5065 * @param {UndoManagerOptions} options 5066 */ 5067 constructor(typeScope, { 5068 captureTimeout = 500, 5069 captureTransaction = (_tr) => true, 5070 deleteFilter = () => true, 5071 trackedOrigins = /* @__PURE__ */ new Set([null]), 5072 ignoreRemoteMapChanges = false, 5073 doc: doc2 = ( 5074 /** @type {Doc} */ 5075 isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc 5076 ) 5077 } = {}) { 5078 super(); 5079 this.scope = []; 5080 this.doc = doc2; 5081 this.addToScope(typeScope); 5082 this.deleteFilter = deleteFilter; 5083 trackedOrigins.add(this); 5084 this.trackedOrigins = trackedOrigins; 5085 this.captureTransaction = captureTransaction; 5086 this.undoStack = []; 5087 this.redoStack = []; 5088 this.undoing = false; 5089 this.redoing = false; 5090 this.currStackItem = null; 5091 this.lastChange = 0; 5092 this.ignoreRemoteMapChanges = ignoreRemoteMapChanges; 5093 this.captureTimeout = captureTimeout; 5094 this.afterTransactionHandler = (transaction) => { 5095 if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has( 5096 /** @type {AbstractType<any>} */ 5097 type 5098 ) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) { 5099 return; 5100 } 5101 const undoing = this.undoing; 5102 const redoing = this.redoing; 5103 const stack = undoing ? this.redoStack : this.undoStack; 5104 if (undoing) { 5105 this.stopCapturing(); 5106 } else if (!redoing) { 5107 this.clear(false, true); 5108 } 5109 const insertions = new DeleteSet(); 5110 transaction.afterState.forEach((endClock, client) => { 5111 const startClock = transaction.beforeState.get(client) || 0; 5112 const len = endClock - startClock; 5113 if (len > 0) { 5114 addToDeleteSet(insertions, client, startClock, len); 5115 } 5116 }); 5117 const now = getUnixTime(); 5118 let didAdd = false; 5119 if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) { 5120 const lastOp = stack[stack.length - 1]; 5121 lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]); 5122 lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]); 5123 } else { 5124 stack.push(new StackItem(transaction.deleteSet, insertions)); 5125 didAdd = true; 5126 } 5127 if (!undoing && !redoing) { 5128 this.lastChange = now; 5129 } 5130 iterateDeletedStructs( 5131 transaction, 5132 transaction.deleteSet, 5133 /** @param {Item|GC} item */ 5134 (item) => { 5135 if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf( 5136 /** @type {AbstractType<any>} */ 5137 type, 5138 item 5139 ))) { 5140 keepItem(item, true); 5141 } 5142 } 5143 ); 5144 const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this]; 5145 if (didAdd) { 5146 this.emit("stack-item-added", changeEvent); 5147 } else { 5148 this.emit("stack-item-updated", changeEvent); 5149 } 5150 }; 5151 this.doc.on("afterTransaction", this.afterTransactionHandler); 5152 this.doc.on("destroy", () => { 5153 this.destroy(); 5154 }); 5155 } 5156 /** 5157 * Extend the scope. 5158 * 5159 * @param {Array<AbstractType<any> | Doc> | AbstractType<any> | Doc} ytypes 5160 */ 5161 addToScope(ytypes) { 5162 const tmpSet = new Set(this.scope); 5163 ytypes = isArray(ytypes) ? ytypes : [ytypes]; 5164 ytypes.forEach((ytype) => { 5165 if (!tmpSet.has(ytype)) { 5166 tmpSet.add(ytype); 5167 if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) warn("[yjs#509] Not same Y.Doc"); 5168 this.scope.push(ytype); 5169 } 5170 }); 5171 } 5172 /** 5173 * @param {any} origin 5174 */ 5175 addTrackedOrigin(origin2) { 5176 this.trackedOrigins.add(origin2); 5177 } 5178 /** 5179 * @param {any} origin 5180 */ 5181 removeTrackedOrigin(origin2) { 5182 this.trackedOrigins.delete(origin2); 5183 } 5184 clear(clearUndoStack = true, clearRedoStack = true) { 5185 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) { 5186 this.doc.transact((tr) => { 5187 if (clearUndoStack) { 5188 this.undoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item)); 5189 this.undoStack = []; 5190 } 5191 if (clearRedoStack) { 5192 this.redoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item)); 5193 this.redoStack = []; 5194 } 5195 this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]); 5196 }); 5197 } 5198 } 5199 /** 5200 * UndoManager merges Undo-StackItem if they are created within time-gap 5201 * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next 5202 * StackItem won't be merged. 5203 * 5204 * 5205 * @example 5206 * // without stopCapturing 5207 * ytext.insert(0, 'a') 5208 * ytext.insert(1, 'b') 5209 * um.undo() 5210 * ytext.toString() // => '' (note that 'ab' was removed) 5211 * // with stopCapturing 5212 * ytext.insert(0, 'a') 5213 * um.stopCapturing() 5214 * ytext.insert(0, 'b') 5215 * um.undo() 5216 * ytext.toString() // => 'a' (note that only 'b' was removed) 5217 * 5218 */ 5219 stopCapturing() { 5220 this.lastChange = 0; 5221 } 5222 /** 5223 * Undo last changes on type. 5224 * 5225 * @return {StackItem?} Returns StackItem if a change was applied 5226 */ 5227 undo() { 5228 this.undoing = true; 5229 let res; 5230 try { 5231 res = popStackItem(this, this.undoStack, "undo"); 5232 } finally { 5233 this.undoing = false; 5234 } 5235 return res; 5236 } 5237 /** 5238 * Redo last undo operation. 5239 * 5240 * @return {StackItem?} Returns StackItem if a change was applied 5241 */ 5242 redo() { 5243 this.redoing = true; 5244 let res; 5245 try { 5246 res = popStackItem(this, this.redoStack, "redo"); 5247 } finally { 5248 this.redoing = false; 5249 } 5250 return res; 5251 } 5252 /** 5253 * Are undo steps available? 5254 * 5255 * @return {boolean} `true` if undo is possible 5256 */ 5257 canUndo() { 5258 return this.undoStack.length > 0; 5259 } 5260 /** 5261 * Are redo steps available? 5262 * 5263 * @return {boolean} `true` if redo is possible 5264 */ 5265 canRedo() { 5266 return this.redoStack.length > 0; 5267 } 5268 destroy() { 5269 this.trackedOrigins.delete(this); 5270 this.doc.off("afterTransaction", this.afterTransactionHandler); 5271 super.destroy(); 5272 } 5273 }; 5274 function* lazyStructReaderGenerator(decoder) { 5275 const numOfStateUpdates = readVarUint(decoder.restDecoder); 5276 for (let i = 0; i < numOfStateUpdates; i++) { 5277 const numberOfStructs = readVarUint(decoder.restDecoder); 5278 const client = decoder.readClient(); 5279 let clock = readVarUint(decoder.restDecoder); 5280 for (let i2 = 0; i2 < numberOfStructs; i2++) { 5281 const info = decoder.readInfo(); 5282 if (info === 10) { 5283 const len = readVarUint(decoder.restDecoder); 5284 yield new Skip(createID(client, clock), len); 5285 clock += len; 5286 } else if ((BITS5 & info) !== 0) { 5287 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; 5288 const struct = new Item( 5289 createID(client, clock), 5290 null, 5291 // left 5292 (info & BIT8) === BIT8 ? decoder.readLeftID() : null, 5293 // origin 5294 null, 5295 // right 5296 (info & BIT7) === BIT7 ? decoder.readRightID() : null, 5297 // right origin 5298 // @ts-ignore Force writing a string here. 5299 cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null, 5300 // parent 5301 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, 5302 // parentSub 5303 readItemContent(decoder, info) 5304 // item content 5305 ); 5306 yield struct; 5307 clock += struct.length; 5308 } else { 5309 const len = decoder.readLen(); 5310 yield new GC(createID(client, clock), len); 5311 clock += len; 5312 } 5313 } 5314 } 5315 } 5316 var LazyStructReader = class { 5317 /** 5318 * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder 5319 * @param {boolean} filterSkips 5320 */ 5321 constructor(decoder, filterSkips) { 5322 this.gen = lazyStructReaderGenerator(decoder); 5323 this.curr = null; 5324 this.done = false; 5325 this.filterSkips = filterSkips; 5326 this.next(); 5327 } 5328 /** 5329 * @return {Item | GC | Skip |null} 5330 */ 5331 next() { 5332 do { 5333 this.curr = this.gen.next().value || null; 5334 } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip); 5335 return this.curr; 5336 } 5337 }; 5338 var logUpdate = (update) => logUpdateV2(update, UpdateDecoderV1); 5339 var logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => { 5340 const structs = []; 5341 const updateDecoder = new YDecoder(createDecoder(update)); 5342 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5343 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5344 structs.push(curr); 5345 } 5346 print("Structs: ", structs); 5347 const ds = readDeleteSet(updateDecoder); 5348 print("DeleteSet: ", ds); 5349 }; 5350 var decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1); 5351 var decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => { 5352 const structs = []; 5353 const updateDecoder = new YDecoder(createDecoder(update)); 5354 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5355 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5356 structs.push(curr); 5357 } 5358 return { 5359 structs, 5360 ds: readDeleteSet(updateDecoder) 5361 }; 5362 }; 5363 var LazyStructWriter = class { 5364 /** 5365 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 5366 */ 5367 constructor(encoder) { 5368 this.currClient = 0; 5369 this.startClock = 0; 5370 this.written = 0; 5371 this.encoder = encoder; 5372 this.clientStructs = []; 5373 } 5374 }; 5375 var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1); 5376 var encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => { 5377 const encoder = new YEncoder(); 5378 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false); 5379 let curr = updateDecoder.curr; 5380 if (curr !== null) { 5381 let size2 = 0; 5382 let currClient = curr.id.client; 5383 let stopCounting = curr.id.clock !== 0; 5384 let currClock = stopCounting ? 0 : curr.id.clock + curr.length; 5385 for (; curr !== null; curr = updateDecoder.next()) { 5386 if (currClient !== curr.id.client) { 5387 if (currClock !== 0) { 5388 size2++; 5389 writeVarUint(encoder.restEncoder, currClient); 5390 writeVarUint(encoder.restEncoder, currClock); 5391 } 5392 currClient = curr.id.client; 5393 currClock = 0; 5394 stopCounting = curr.id.clock !== 0; 5395 } 5396 if (curr.constructor === Skip) { 5397 stopCounting = true; 5398 } 5399 if (!stopCounting) { 5400 currClock = curr.id.clock + curr.length; 5401 } 5402 } 5403 if (currClock !== 0) { 5404 size2++; 5405 writeVarUint(encoder.restEncoder, currClient); 5406 writeVarUint(encoder.restEncoder, currClock); 5407 } 5408 const enc = createEncoder(); 5409 writeVarUint(enc, size2); 5410 writeBinaryEncoder(enc, encoder.restEncoder); 5411 encoder.restEncoder = enc; 5412 return encoder.toUint8Array(); 5413 } else { 5414 writeVarUint(encoder.restEncoder, 0); 5415 return encoder.toUint8Array(); 5416 } 5417 }; 5418 var encodeStateVectorFromUpdate = (update) => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1); 5419 var parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => { 5420 const from2 = /* @__PURE__ */ new Map(); 5421 const to = /* @__PURE__ */ new Map(); 5422 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false); 5423 let curr = updateDecoder.curr; 5424 if (curr !== null) { 5425 let currClient = curr.id.client; 5426 let currClock = curr.id.clock; 5427 from2.set(currClient, currClock); 5428 for (; curr !== null; curr = updateDecoder.next()) { 5429 if (currClient !== curr.id.client) { 5430 to.set(currClient, currClock); 5431 from2.set(curr.id.client, curr.id.clock); 5432 currClient = curr.id.client; 5433 } 5434 currClock = curr.id.clock + curr.length; 5435 } 5436 to.set(currClient, currClock); 5437 } 5438 return { from: from2, to }; 5439 }; 5440 var parseUpdateMeta = (update) => parseUpdateMetaV2(update, UpdateDecoderV1); 5441 var sliceStruct = (left, diff) => { 5442 if (left.constructor === GC) { 5443 const { client, clock } = left.id; 5444 return new GC(createID(client, clock + diff), left.length - diff); 5445 } else if (left.constructor === Skip) { 5446 const { client, clock } = left.id; 5447 return new Skip(createID(client, clock + diff), left.length - diff); 5448 } else { 5449 const leftItem = ( 5450 /** @type {Item} */ 5451 left 5452 ); 5453 const { client, clock } = leftItem.id; 5454 return new Item( 5455 createID(client, clock + diff), 5456 null, 5457 createID(client, clock + diff - 1), 5458 null, 5459 leftItem.rightOrigin, 5460 leftItem.parent, 5461 leftItem.parentSub, 5462 leftItem.content.splice(diff) 5463 ); 5464 } 5465 }; 5466 var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { 5467 if (updates.length === 1) { 5468 return updates[0]; 5469 } 5470 const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update))); 5471 let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true)); 5472 let currWrite = null; 5473 const updateEncoder = new YEncoder(); 5474 const lazyStructEncoder = new LazyStructWriter(updateEncoder); 5475 while (true) { 5476 lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null); 5477 lazyStructDecoders.sort( 5478 /** @type {function(any,any):number} */ 5479 (dec1, dec2) => { 5480 if (dec1.curr.id.client === dec2.curr.id.client) { 5481 const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock; 5482 if (clockDiff === 0) { 5483 return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1; 5484 } else { 5485 return clockDiff; 5486 } 5487 } else { 5488 return dec2.curr.id.client - dec1.curr.id.client; 5489 } 5490 } 5491 ); 5492 if (lazyStructDecoders.length === 0) { 5493 break; 5494 } 5495 const currDecoder = lazyStructDecoders[0]; 5496 const firstClient = ( 5497 /** @type {Item | GC} */ 5498 currDecoder.curr.id.client 5499 ); 5500 if (currWrite !== null) { 5501 let curr = ( 5502 /** @type {Item | GC | null} */ 5503 currDecoder.curr 5504 ); 5505 let iterated = false; 5506 while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) { 5507 curr = currDecoder.next(); 5508 iterated = true; 5509 } 5510 if (curr === null || // current decoder is empty 5511 curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient` 5512 iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) { 5513 continue; 5514 } 5515 if (firstClient !== currWrite.struct.id.client) { 5516 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5517 currWrite = { struct: curr, offset: 0 }; 5518 currDecoder.next(); 5519 } else { 5520 if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) { 5521 if (currWrite.struct.constructor === Skip) { 5522 currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock; 5523 } else { 5524 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5525 const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length; 5526 const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff); 5527 currWrite = { struct, offset: 0 }; 5528 } 5529 } else { 5530 const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock; 5531 if (diff > 0) { 5532 if (currWrite.struct.constructor === Skip) { 5533 currWrite.struct.length -= diff; 5534 } else { 5535 curr = sliceStruct(curr, diff); 5536 } 5537 } 5538 if (!currWrite.struct.mergeWith( 5539 /** @type {any} */ 5540 curr 5541 )) { 5542 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5543 currWrite = { struct: curr, offset: 0 }; 5544 currDecoder.next(); 5545 } 5546 } 5547 } 5548 } else { 5549 currWrite = { struct: ( 5550 /** @type {Item | GC} */ 5551 currDecoder.curr 5552 ), offset: 0 }; 5553 currDecoder.next(); 5554 } 5555 for (let next = currDecoder.curr; next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip; next = currDecoder.next()) { 5556 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5557 currWrite = { struct: next, offset: 0 }; 5558 } 5559 } 5560 if (currWrite !== null) { 5561 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5562 currWrite = null; 5563 } 5564 finishLazyStructWriting(lazyStructEncoder); 5565 const dss = updateDecoders.map((decoder) => readDeleteSet(decoder)); 5566 const ds = mergeDeleteSets(dss); 5567 writeDeleteSet(updateEncoder, ds); 5568 return updateEncoder.toUint8Array(); 5569 }; 5570 var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { 5571 const state = decodeStateVector(sv); 5572 const encoder = new YEncoder(); 5573 const lazyStructWriter = new LazyStructWriter(encoder); 5574 const decoder = new YDecoder(createDecoder(update)); 5575 const reader = new LazyStructReader(decoder, false); 5576 while (reader.curr) { 5577 const curr = reader.curr; 5578 const currClient = curr.id.client; 5579 const svClock = state.get(currClient) || 0; 5580 if (reader.curr.constructor === Skip) { 5581 reader.next(); 5582 continue; 5583 } 5584 if (curr.id.clock + curr.length > svClock) { 5585 writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0)); 5586 reader.next(); 5587 while (reader.curr && reader.curr.id.client === currClient) { 5588 writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0); 5589 reader.next(); 5590 } 5591 } else { 5592 while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) { 5593 reader.next(); 5594 } 5595 } 5596 } 5597 finishLazyStructWriting(lazyStructWriter); 5598 const ds = readDeleteSet(decoder); 5599 writeDeleteSet(encoder, ds); 5600 return encoder.toUint8Array(); 5601 }; 5602 var diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1); 5603 var flushLazyStructWriter = (lazyWriter) => { 5604 if (lazyWriter.written > 0) { 5605 lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) }); 5606 lazyWriter.encoder.restEncoder = createEncoder(); 5607 lazyWriter.written = 0; 5608 } 5609 }; 5610 var writeStructToLazyStructWriter = (lazyWriter, struct, offset) => { 5611 if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) { 5612 flushLazyStructWriter(lazyWriter); 5613 } 5614 if (lazyWriter.written === 0) { 5615 lazyWriter.currClient = struct.id.client; 5616 lazyWriter.encoder.writeClient(struct.id.client); 5617 writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset); 5618 } 5619 struct.write(lazyWriter.encoder, offset); 5620 lazyWriter.written++; 5621 }; 5622 var finishLazyStructWriting = (lazyWriter) => { 5623 flushLazyStructWriter(lazyWriter); 5624 const restEncoder = lazyWriter.encoder.restEncoder; 5625 writeVarUint(restEncoder, lazyWriter.clientStructs.length); 5626 for (let i = 0; i < lazyWriter.clientStructs.length; i++) { 5627 const partStructs = lazyWriter.clientStructs[i]; 5628 writeVarUint(restEncoder, partStructs.written); 5629 writeUint8Array(restEncoder, partStructs.restEncoder); 5630 } 5631 }; 5632 var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => { 5633 const updateDecoder = new YDecoder(createDecoder(update)); 5634 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5635 const updateEncoder = new YEncoder(); 5636 const lazyWriter = new LazyStructWriter(updateEncoder); 5637 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5638 writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0); 5639 } 5640 finishLazyStructWriting(lazyWriter); 5641 const ds = readDeleteSet(updateDecoder); 5642 writeDeleteSet(updateEncoder, ds); 5643 return updateEncoder.toUint8Array(); 5644 }; 5645 var createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => { 5646 let i = 0; 5647 const mapKeyCache = create(); 5648 const nodeNameCache = create(); 5649 const formattingKeyCache = create(); 5650 const formattingValueCache = create(); 5651 formattingValueCache.set(null, null); 5652 return (block) => { 5653 switch (block.constructor) { 5654 case GC: 5655 case Skip: 5656 return block; 5657 case Item: { 5658 const item = ( 5659 /** @type {Item} */ 5660 block 5661 ); 5662 const content = item.content; 5663 switch (content.constructor) { 5664 case ContentDeleted: 5665 break; 5666 case ContentType: { 5667 if (yxml) { 5668 const type = ( 5669 /** @type {ContentType} */ 5670 content.type 5671 ); 5672 if (type instanceof YXmlElement) { 5673 type.nodeName = setIfUndefined(nodeNameCache, type.nodeName, () => "node-" + i); 5674 } 5675 if (type instanceof YXmlHook) { 5676 type.hookName = setIfUndefined(nodeNameCache, type.hookName, () => "hook-" + i); 5677 } 5678 } 5679 break; 5680 } 5681 case ContentAny: { 5682 const c = ( 5683 /** @type {ContentAny} */ 5684 content 5685 ); 5686 c.arr = c.arr.map(() => i); 5687 break; 5688 } 5689 case ContentBinary: { 5690 const c = ( 5691 /** @type {ContentBinary} */ 5692 content 5693 ); 5694 c.content = new Uint8Array([i]); 5695 break; 5696 } 5697 case ContentDoc: { 5698 const c = ( 5699 /** @type {ContentDoc} */ 5700 content 5701 ); 5702 if (subdocs) { 5703 c.opts = {}; 5704 c.doc.guid = i + ""; 5705 } 5706 break; 5707 } 5708 case ContentEmbed: { 5709 const c = ( 5710 /** @type {ContentEmbed} */ 5711 content 5712 ); 5713 c.embed = {}; 5714 break; 5715 } 5716 case ContentFormat: { 5717 const c = ( 5718 /** @type {ContentFormat} */ 5719 content 5720 ); 5721 if (formatting) { 5722 c.key = setIfUndefined(formattingKeyCache, c.key, () => i + ""); 5723 c.value = setIfUndefined(formattingValueCache, c.value, () => ({ i })); 5724 } 5725 break; 5726 } 5727 case ContentJSON: { 5728 const c = ( 5729 /** @type {ContentJSON} */ 5730 content 5731 ); 5732 c.arr = c.arr.map(() => i); 5733 break; 5734 } 5735 case ContentString: { 5736 const c = ( 5737 /** @type {ContentString} */ 5738 content 5739 ); 5740 c.str = repeat(i % 10 + "", c.str.length); 5741 break; 5742 } 5743 default: 5744 unexpectedCase(); 5745 } 5746 if (item.parentSub) { 5747 item.parentSub = setIfUndefined(mapKeyCache, item.parentSub, () => i + ""); 5748 } 5749 i++; 5750 return block; 5751 } 5752 default: 5753 unexpectedCase(); 5754 } 5755 }; 5756 }; 5757 var obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1); 5758 var obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2); 5759 var convertUpdateFormatV1ToV2 = (update) => convertUpdateFormat(update, id, UpdateDecoderV1, UpdateEncoderV2); 5760 var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1); 5761 var errorComputeChanges = "You must not compute changes after the event-handler fired."; 5762 var YEvent = class { 5763 /** 5764 * @param {T} target The changed type. 5765 * @param {Transaction} transaction 5766 */ 5767 constructor(target, transaction) { 5768 this.target = target; 5769 this.currentTarget = target; 5770 this.transaction = transaction; 5771 this._changes = null; 5772 this._keys = null; 5773 this._delta = null; 5774 this._path = null; 5775 } 5776 /** 5777 * Computes the path from `y` to the changed type. 5778 * 5779 * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with. 5780 * 5781 * The following property holds: 5782 * @example 5783 * let type = y 5784 * event.path.forEach(dir => { 5785 * type = type.get(dir) 5786 * }) 5787 * type === event.target // => true 5788 */ 5789 get path() { 5790 return this._path || (this._path = getPathTo(this.currentTarget, this.target)); 5791 } 5792 /** 5793 * Check if a struct is deleted by this event. 5794 * 5795 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. 5796 * 5797 * @param {AbstractStruct} struct 5798 * @return {boolean} 5799 */ 5800 deletes(struct) { 5801 return isDeleted(this.transaction.deleteSet, struct.id); 5802 } 5803 /** 5804 * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>} 5805 */ 5806 get keys() { 5807 if (this._keys === null) { 5808 if (this.transaction.doc._transactionCleanups.length === 0) { 5809 throw create3(errorComputeChanges); 5810 } 5811 const keys2 = /* @__PURE__ */ new Map(); 5812 const target = this.target; 5813 const changed = ( 5814 /** @type Set<string|null> */ 5815 this.transaction.changed.get(target) 5816 ); 5817 changed.forEach((key) => { 5818 if (key !== null) { 5819 const item = ( 5820 /** @type {Item} */ 5821 target._map.get(key) 5822 ); 5823 let action; 5824 let oldValue; 5825 if (this.adds(item)) { 5826 let prev = item.left; 5827 while (prev !== null && this.adds(prev)) { 5828 prev = prev.left; 5829 } 5830 if (this.deletes(item)) { 5831 if (prev !== null && this.deletes(prev)) { 5832 action = "delete"; 5833 oldValue = last(prev.content.getContent()); 5834 } else { 5835 return; 5836 } 5837 } else { 5838 if (prev !== null && this.deletes(prev)) { 5839 action = "update"; 5840 oldValue = last(prev.content.getContent()); 5841 } else { 5842 action = "add"; 5843 oldValue = void 0; 5844 } 5845 } 5846 } else { 5847 if (this.deletes(item)) { 5848 action = "delete"; 5849 oldValue = last( 5850 /** @type {Item} */ 5851 item.content.getContent() 5852 ); 5853 } else { 5854 return; 5855 } 5856 } 5857 keys2.set(key, { action, oldValue }); 5858 } 5859 }); 5860 this._keys = keys2; 5861 } 5862 return this._keys; 5863 } 5864 /** 5865 * This is a computed property. Note that this can only be safely computed during the 5866 * event call. Computing this property after other changes happened might result in 5867 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes 5868 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. 5869 * 5870 * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>} 5871 */ 5872 get delta() { 5873 return this.changes.delta; 5874 } 5875 /** 5876 * Check if a struct is added by this event. 5877 * 5878 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. 5879 * 5880 * @param {AbstractStruct} struct 5881 * @return {boolean} 5882 */ 5883 adds(struct) { 5884 return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0); 5885 } 5886 /** 5887 * This is a computed property. Note that this can only be safely computed during the 5888 * event call. Computing this property after other changes happened might result in 5889 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes 5890 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. 5891 * 5892 * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}} 5893 */ 5894 get changes() { 5895 let changes = this._changes; 5896 if (changes === null) { 5897 if (this.transaction.doc._transactionCleanups.length === 0) { 5898 throw create3(errorComputeChanges); 5899 } 5900 const target = this.target; 5901 const added = create2(); 5902 const deleted = create2(); 5903 const delta = []; 5904 changes = { 5905 added, 5906 deleted, 5907 delta, 5908 keys: this.keys 5909 }; 5910 const changed = ( 5911 /** @type Set<string|null> */ 5912 this.transaction.changed.get(target) 5913 ); 5914 if (changed.has(null)) { 5915 let lastOp = null; 5916 const packOp = () => { 5917 if (lastOp) { 5918 delta.push(lastOp); 5919 } 5920 }; 5921 for (let item = target._start; item !== null; item = item.right) { 5922 if (item.deleted) { 5923 if (this.deletes(item) && !this.adds(item)) { 5924 if (lastOp === null || lastOp.delete === void 0) { 5925 packOp(); 5926 lastOp = { delete: 0 }; 5927 } 5928 lastOp.delete += item.length; 5929 deleted.add(item); 5930 } 5931 } else { 5932 if (this.adds(item)) { 5933 if (lastOp === null || lastOp.insert === void 0) { 5934 packOp(); 5935 lastOp = { insert: [] }; 5936 } 5937 lastOp.insert = lastOp.insert.concat(item.content.getContent()); 5938 added.add(item); 5939 } else { 5940 if (lastOp === null || lastOp.retain === void 0) { 5941 packOp(); 5942 lastOp = { retain: 0 }; 5943 } 5944 lastOp.retain += item.length; 5945 } 5946 } 5947 } 5948 if (lastOp !== null && lastOp.retain === void 0) { 5949 packOp(); 5950 } 5951 } 5952 this._changes = changes; 5953 } 5954 return ( 5955 /** @type {any} */ 5956 changes 5957 ); 5958 } 5959 }; 5960 var getPathTo = (parent, child) => { 5961 const path = []; 5962 while (child._item !== null && child !== parent) { 5963 if (child._item.parentSub !== null) { 5964 path.unshift(child._item.parentSub); 5965 } else { 5966 let i = 0; 5967 let c = ( 5968 /** @type {AbstractType<any>} */ 5969 child._item.parent._start 5970 ); 5971 while (c !== child._item && c !== null) { 5972 if (!c.deleted && c.countable) { 5973 i += c.length; 5974 } 5975 c = c.right; 5976 } 5977 path.unshift(i); 5978 } 5979 child = /** @type {AbstractType<any>} */ 5980 child._item.parent; 5981 } 5982 return path; 5983 }; 5984 var warnPrematureAccess = () => { 5985 warn("Invalid access: Add Yjs type to a document before reading data."); 5986 }; 5987 var maxSearchMarker = 80; 5988 var globalSearchMarkerTimestamp = 0; 5989 var ArraySearchMarker = class { 5990 /** 5991 * @param {Item} p 5992 * @param {number} index 5993 */ 5994 constructor(p, index) { 5995 p.marker = true; 5996 this.p = p; 5997 this.index = index; 5998 this.timestamp = globalSearchMarkerTimestamp++; 5999 } 6000 }; 6001 var refreshMarkerTimestamp = (marker) => { 6002 marker.timestamp = globalSearchMarkerTimestamp++; 6003 }; 6004 var overwriteMarker = (marker, p, index) => { 6005 marker.p.marker = false; 6006 marker.p = p; 6007 p.marker = true; 6008 marker.index = index; 6009 marker.timestamp = globalSearchMarkerTimestamp++; 6010 }; 6011 var markPosition = (searchMarker, p, index) => { 6012 if (searchMarker.length >= maxSearchMarker) { 6013 const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); 6014 overwriteMarker(marker, p, index); 6015 return marker; 6016 } else { 6017 const pm = new ArraySearchMarker(p, index); 6018 searchMarker.push(pm); 6019 return pm; 6020 } 6021 }; 6022 var findMarker = (yarray, index) => { 6023 if (yarray._start === null || index === 0 || yarray._searchMarker === null) { 6024 return null; 6025 } 6026 const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b); 6027 let p = yarray._start; 6028 let pindex = 0; 6029 if (marker !== null) { 6030 p = marker.p; 6031 pindex = marker.index; 6032 refreshMarkerTimestamp(marker); 6033 } 6034 while (p.right !== null && pindex < index) { 6035 if (!p.deleted && p.countable) { 6036 if (index < pindex + p.length) { 6037 break; 6038 } 6039 pindex += p.length; 6040 } 6041 p = p.right; 6042 } 6043 while (p.left !== null && pindex > index) { 6044 p = p.left; 6045 if (!p.deleted && p.countable) { 6046 pindex -= p.length; 6047 } 6048 } 6049 while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { 6050 p = p.left; 6051 if (!p.deleted && p.countable) { 6052 pindex -= p.length; 6053 } 6054 } 6055 if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */ 6056 p.parent.length / maxSearchMarker) { 6057 overwriteMarker(marker, p, pindex); 6058 return marker; 6059 } else { 6060 return markPosition(yarray._searchMarker, p, pindex); 6061 } 6062 }; 6063 var updateMarkerChanges = (searchMarker, index, len) => { 6064 for (let i = searchMarker.length - 1; i >= 0; i--) { 6065 const m = searchMarker[i]; 6066 if (len > 0) { 6067 let p = m.p; 6068 p.marker = false; 6069 while (p && (p.deleted || !p.countable)) { 6070 p = p.left; 6071 if (p && !p.deleted && p.countable) { 6072 m.index -= p.length; 6073 } 6074 } 6075 if (p === null || p.marker === true) { 6076 searchMarker.splice(i, 1); 6077 continue; 6078 } 6079 m.p = p; 6080 p.marker = true; 6081 } 6082 if (index < m.index || len > 0 && index === m.index) { 6083 m.index = max(index, m.index + len); 6084 } 6085 } 6086 }; 6087 var getTypeChildren = (t) => { 6088 t.doc ?? warnPrematureAccess(); 6089 let s = t._start; 6090 const arr = []; 6091 while (s) { 6092 arr.push(s); 6093 s = s.right; 6094 } 6095 return arr; 6096 }; 6097 var callTypeObservers = (type, transaction, event) => { 6098 const changedType = type; 6099 const changedParentTypes = transaction.changedParentTypes; 6100 while (true) { 6101 setIfUndefined(changedParentTypes, type, () => []).push(event); 6102 if (type._item === null) { 6103 break; 6104 } 6105 type = /** @type {AbstractType<any>} */ 6106 type._item.parent; 6107 } 6108 callEventHandlerListeners(changedType._eH, event, transaction); 6109 }; 6110 var AbstractType = class { 6111 constructor() { 6112 this._item = null; 6113 this._map = /* @__PURE__ */ new Map(); 6114 this._start = null; 6115 this.doc = null; 6116 this._length = 0; 6117 this._eH = createEventHandler(); 6118 this._dEH = createEventHandler(); 6119 this._searchMarker = null; 6120 } 6121 /** 6122 * @return {AbstractType<any>|null} 6123 */ 6124 get parent() { 6125 return this._item ? ( 6126 /** @type {AbstractType<any>} */ 6127 this._item.parent 6128 ) : null; 6129 } 6130 /** 6131 * Integrate this type into the Yjs instance. 6132 * 6133 * * Save this struct in the os 6134 * * This type is sent to other client 6135 * * Observer functions are fired 6136 * 6137 * @param {Doc} y The Yjs instance 6138 * @param {Item|null} item 6139 */ 6140 _integrate(y, item) { 6141 this.doc = y; 6142 this._item = item; 6143 } 6144 /** 6145 * @return {AbstractType<EventType>} 6146 */ 6147 _copy() { 6148 throw methodUnimplemented(); 6149 } 6150 /** 6151 * Makes a copy of this data type that can be included somewhere else. 6152 * 6153 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6154 * 6155 * @return {AbstractType<EventType>} 6156 */ 6157 clone() { 6158 throw methodUnimplemented(); 6159 } 6160 /** 6161 * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder 6162 */ 6163 _write(_encoder) { 6164 } 6165 /** 6166 * The first non-deleted item 6167 */ 6168 get _first() { 6169 let n = this._start; 6170 while (n !== null && n.deleted) { 6171 n = n.right; 6172 } 6173 return n; 6174 } 6175 /** 6176 * Creates YEvent and calls all type observers. 6177 * Must be implemented by each type. 6178 * 6179 * @param {Transaction} transaction 6180 * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified. 6181 */ 6182 _callObserver(transaction, _parentSubs) { 6183 if (!transaction.local && this._searchMarker) { 6184 this._searchMarker.length = 0; 6185 } 6186 } 6187 /** 6188 * Observe all events that are created on this type. 6189 * 6190 * @param {function(EventType, Transaction):void} f Observer function 6191 */ 6192 observe(f) { 6193 addEventHandlerListener(this._eH, f); 6194 } 6195 /** 6196 * Observe all events that are created by this type and its children. 6197 * 6198 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function 6199 */ 6200 observeDeep(f) { 6201 addEventHandlerListener(this._dEH, f); 6202 } 6203 /** 6204 * Unregister an observer function. 6205 * 6206 * @param {function(EventType,Transaction):void} f Observer function 6207 */ 6208 unobserve(f) { 6209 removeEventHandlerListener(this._eH, f); 6210 } 6211 /** 6212 * Unregister an observer function. 6213 * 6214 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function 6215 */ 6216 unobserveDeep(f) { 6217 removeEventHandlerListener(this._dEH, f); 6218 } 6219 /** 6220 * @abstract 6221 * @return {any} 6222 */ 6223 toJSON() { 6224 } 6225 }; 6226 var typeListSlice = (type, start, end) => { 6227 type.doc ?? warnPrematureAccess(); 6228 if (start < 0) { 6229 start = type._length + start; 6230 } 6231 if (end < 0) { 6232 end = type._length + end; 6233 } 6234 let len = end - start; 6235 const cs = []; 6236 let n = type._start; 6237 while (n !== null && len > 0) { 6238 if (n.countable && !n.deleted) { 6239 const c = n.content.getContent(); 6240 if (c.length <= start) { 6241 start -= c.length; 6242 } else { 6243 for (let i = start; i < c.length && len > 0; i++) { 6244 cs.push(c[i]); 6245 len--; 6246 } 6247 start = 0; 6248 } 6249 } 6250 n = n.right; 6251 } 6252 return cs; 6253 }; 6254 var typeListToArray = (type) => { 6255 type.doc ?? warnPrematureAccess(); 6256 const cs = []; 6257 let n = type._start; 6258 while (n !== null) { 6259 if (n.countable && !n.deleted) { 6260 const c = n.content.getContent(); 6261 for (let i = 0; i < c.length; i++) { 6262 cs.push(c[i]); 6263 } 6264 } 6265 n = n.right; 6266 } 6267 return cs; 6268 }; 6269 var typeListToArraySnapshot = (type, snapshot2) => { 6270 const cs = []; 6271 let n = type._start; 6272 while (n !== null) { 6273 if (n.countable && isVisible(n, snapshot2)) { 6274 const c = n.content.getContent(); 6275 for (let i = 0; i < c.length; i++) { 6276 cs.push(c[i]); 6277 } 6278 } 6279 n = n.right; 6280 } 6281 return cs; 6282 }; 6283 var typeListForEach = (type, f) => { 6284 let index = 0; 6285 let n = type._start; 6286 type.doc ?? warnPrematureAccess(); 6287 while (n !== null) { 6288 if (n.countable && !n.deleted) { 6289 const c = n.content.getContent(); 6290 for (let i = 0; i < c.length; i++) { 6291 f(c[i], index++, type); 6292 } 6293 } 6294 n = n.right; 6295 } 6296 }; 6297 var typeListMap = (type, f) => { 6298 const result = []; 6299 typeListForEach(type, (c, i) => { 6300 result.push(f(c, i, type)); 6301 }); 6302 return result; 6303 }; 6304 var typeListCreateIterator = (type) => { 6305 let n = type._start; 6306 let currentContent = null; 6307 let currentContentIndex = 0; 6308 return { 6309 [Symbol.iterator]() { 6310 return this; 6311 }, 6312 next: () => { 6313 if (currentContent === null) { 6314 while (n !== null && n.deleted) { 6315 n = n.right; 6316 } 6317 if (n === null) { 6318 return { 6319 done: true, 6320 value: void 0 6321 }; 6322 } 6323 currentContent = n.content.getContent(); 6324 currentContentIndex = 0; 6325 n = n.right; 6326 } 6327 const value = currentContent[currentContentIndex++]; 6328 if (currentContent.length <= currentContentIndex) { 6329 currentContent = null; 6330 } 6331 return { 6332 done: false, 6333 value 6334 }; 6335 } 6336 }; 6337 }; 6338 var typeListGet = (type, index) => { 6339 type.doc ?? warnPrematureAccess(); 6340 const marker = findMarker(type, index); 6341 let n = type._start; 6342 if (marker !== null) { 6343 n = marker.p; 6344 index -= marker.index; 6345 } 6346 for (; n !== null; n = n.right) { 6347 if (!n.deleted && n.countable) { 6348 if (index < n.length) { 6349 return n.content.getContent()[index]; 6350 } 6351 index -= n.length; 6352 } 6353 } 6354 }; 6355 var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { 6356 let left = referenceItem; 6357 const doc2 = transaction.doc; 6358 const ownClientId = doc2.clientID; 6359 const store2 = doc2.store; 6360 const right = referenceItem === null ? parent._start : referenceItem.right; 6361 let jsonContent = []; 6362 const packJsonContent = () => { 6363 if (jsonContent.length > 0) { 6364 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); 6365 left.integrate(transaction, 0); 6366 jsonContent = []; 6367 } 6368 }; 6369 content.forEach((c) => { 6370 if (c === null) { 6371 jsonContent.push(c); 6372 } else { 6373 switch (c.constructor) { 6374 case Number: 6375 case Object: 6376 case Boolean: 6377 case Array: 6378 case String: 6379 jsonContent.push(c); 6380 break; 6381 default: 6382 packJsonContent(); 6383 switch (c.constructor) { 6384 case Uint8Array: 6385 case ArrayBuffer: 6386 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array( 6387 /** @type {Uint8Array} */ 6388 c 6389 ))); 6390 left.integrate(transaction, 0); 6391 break; 6392 case Doc: 6393 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc( 6394 /** @type {Doc} */ 6395 c 6396 )); 6397 left.integrate(transaction, 0); 6398 break; 6399 default: 6400 if (c instanceof AbstractType) { 6401 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); 6402 left.integrate(transaction, 0); 6403 } else { 6404 throw new Error("Unexpected content type in insert operation"); 6405 } 6406 } 6407 } 6408 } 6409 }); 6410 packJsonContent(); 6411 }; 6412 var lengthExceeded = () => create3("Length exceeded!"); 6413 var typeListInsertGenerics = (transaction, parent, index, content) => { 6414 if (index > parent._length) { 6415 throw lengthExceeded(); 6416 } 6417 if (index === 0) { 6418 if (parent._searchMarker) { 6419 updateMarkerChanges(parent._searchMarker, index, content.length); 6420 } 6421 return typeListInsertGenericsAfter(transaction, parent, null, content); 6422 } 6423 const startIndex = index; 6424 const marker = findMarker(parent, index); 6425 let n = parent._start; 6426 if (marker !== null) { 6427 n = marker.p; 6428 index -= marker.index; 6429 if (index === 0) { 6430 n = n.prev; 6431 index += n && n.countable && !n.deleted ? n.length : 0; 6432 } 6433 } 6434 for (; n !== null; n = n.right) { 6435 if (!n.deleted && n.countable) { 6436 if (index <= n.length) { 6437 if (index < n.length) { 6438 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); 6439 } 6440 break; 6441 } 6442 index -= n.length; 6443 } 6444 } 6445 if (parent._searchMarker) { 6446 updateMarkerChanges(parent._searchMarker, startIndex, content.length); 6447 } 6448 return typeListInsertGenericsAfter(transaction, parent, n, content); 6449 }; 6450 var typeListPushGenerics = (transaction, parent, content) => { 6451 const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start }); 6452 let n = marker.p; 6453 if (n) { 6454 while (n.right) { 6455 n = n.right; 6456 } 6457 } 6458 return typeListInsertGenericsAfter(transaction, parent, n, content); 6459 }; 6460 var typeListDelete = (transaction, parent, index, length2) => { 6461 if (length2 === 0) { 6462 return; 6463 } 6464 const startIndex = index; 6465 const startLength = length2; 6466 const marker = findMarker(parent, index); 6467 let n = parent._start; 6468 if (marker !== null) { 6469 n = marker.p; 6470 index -= marker.index; 6471 } 6472 for (; n !== null && index > 0; n = n.right) { 6473 if (!n.deleted && n.countable) { 6474 if (index < n.length) { 6475 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); 6476 } 6477 index -= n.length; 6478 } 6479 } 6480 while (length2 > 0 && n !== null) { 6481 if (!n.deleted) { 6482 if (length2 < n.length) { 6483 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2)); 6484 } 6485 n.delete(transaction); 6486 length2 -= n.length; 6487 } 6488 n = n.right; 6489 } 6490 if (length2 > 0) { 6491 throw lengthExceeded(); 6492 } 6493 if (parent._searchMarker) { 6494 updateMarkerChanges( 6495 parent._searchMarker, 6496 startIndex, 6497 -startLength + length2 6498 /* in case we remove the above exception */ 6499 ); 6500 } 6501 }; 6502 var typeMapDelete = (transaction, parent, key) => { 6503 const c = parent._map.get(key); 6504 if (c !== void 0) { 6505 c.delete(transaction); 6506 } 6507 }; 6508 var typeMapSet = (transaction, parent, key, value) => { 6509 const left = parent._map.get(key) || null; 6510 const doc2 = transaction.doc; 6511 const ownClientId = doc2.clientID; 6512 let content; 6513 if (value == null) { 6514 content = new ContentAny([value]); 6515 } else { 6516 switch (value.constructor) { 6517 case Number: 6518 case Object: 6519 case Boolean: 6520 case Array: 6521 case String: 6522 case Date: 6523 case BigInt: 6524 content = new ContentAny([value]); 6525 break; 6526 case Uint8Array: 6527 content = new ContentBinary( 6528 /** @type {Uint8Array} */ 6529 value 6530 ); 6531 break; 6532 case Doc: 6533 content = new ContentDoc( 6534 /** @type {Doc} */ 6535 value 6536 ); 6537 break; 6538 default: 6539 if (value instanceof AbstractType) { 6540 content = new ContentType(value); 6541 } else { 6542 throw new Error("Unexpected content type"); 6543 } 6544 } 6545 } 6546 new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); 6547 }; 6548 var typeMapGet = (parent, key) => { 6549 parent.doc ?? warnPrematureAccess(); 6550 const val = parent._map.get(key); 6551 return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0; 6552 }; 6553 var typeMapGetAll = (parent) => { 6554 const res = {}; 6555 parent.doc ?? warnPrematureAccess(); 6556 parent._map.forEach((value, key) => { 6557 if (!value.deleted) { 6558 res[key] = value.content.getContent()[value.length - 1]; 6559 } 6560 }); 6561 return res; 6562 }; 6563 var typeMapHas = (parent, key) => { 6564 parent.doc ?? warnPrematureAccess(); 6565 const val = parent._map.get(key); 6566 return val !== void 0 && !val.deleted; 6567 }; 6568 var typeMapGetSnapshot = (parent, key, snapshot2) => { 6569 let v = parent._map.get(key) || null; 6570 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) { 6571 v = v.left; 6572 } 6573 return v !== null && isVisible(v, snapshot2) ? v.content.getContent()[v.length - 1] : void 0; 6574 }; 6575 var typeMapGetAllSnapshot = (parent, snapshot2) => { 6576 const res = {}; 6577 parent._map.forEach((value, key) => { 6578 let v = value; 6579 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) { 6580 v = v.left; 6581 } 6582 if (v !== null && isVisible(v, snapshot2)) { 6583 res[key] = v.content.getContent()[v.length - 1]; 6584 } 6585 }); 6586 return res; 6587 }; 6588 var createMapIterator = (type) => { 6589 type.doc ?? warnPrematureAccess(); 6590 return iteratorFilter( 6591 type._map.entries(), 6592 /** @param {any} entry */ 6593 (entry) => !entry[1].deleted 6594 ); 6595 }; 6596 var YArrayEvent = class extends YEvent { 6597 }; 6598 var YArray = class _YArray extends AbstractType { 6599 constructor() { 6600 super(); 6601 this._prelimContent = []; 6602 this._searchMarker = []; 6603 } 6604 /** 6605 * Construct a new YArray containing the specified items. 6606 * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T 6607 * @param {Array<T>} items 6608 * @return {YArray<T>} 6609 */ 6610 static from(items2) { 6611 const a = new _YArray(); 6612 a.push(items2); 6613 return a; 6614 } 6615 /** 6616 * Integrate this type into the Yjs instance. 6617 * 6618 * * Save this struct in the os 6619 * * This type is sent to other client 6620 * * Observer functions are fired 6621 * 6622 * @param {Doc} y The Yjs instance 6623 * @param {Item} item 6624 */ 6625 _integrate(y, item) { 6626 super._integrate(y, item); 6627 this.insert( 6628 0, 6629 /** @type {Array<any>} */ 6630 this._prelimContent 6631 ); 6632 this._prelimContent = null; 6633 } 6634 /** 6635 * @return {YArray<T>} 6636 */ 6637 _copy() { 6638 return new _YArray(); 6639 } 6640 /** 6641 * Makes a copy of this data type that can be included somewhere else. 6642 * 6643 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6644 * 6645 * @return {YArray<T>} 6646 */ 6647 clone() { 6648 const arr = new _YArray(); 6649 arr.insert(0, this.toArray().map( 6650 (el) => el instanceof AbstractType ? ( 6651 /** @type {typeof el} */ 6652 el.clone() 6653 ) : el 6654 )); 6655 return arr; 6656 } 6657 get length() { 6658 this.doc ?? warnPrematureAccess(); 6659 return this._length; 6660 } 6661 /** 6662 * Creates YArrayEvent and calls observers. 6663 * 6664 * @param {Transaction} transaction 6665 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 6666 */ 6667 _callObserver(transaction, parentSubs) { 6668 super._callObserver(transaction, parentSubs); 6669 callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); 6670 } 6671 /** 6672 * Inserts new content at an index. 6673 * 6674 * Important: This function expects an array of content. Not just a content 6675 * object. The reason for this "weirdness" is that inserting several elements 6676 * is very efficient when it is done as a single operation. 6677 * 6678 * @example 6679 * // Insert character 'a' at position 0 6680 * yarray.insert(0, ['a']) 6681 * // Insert numbers 1, 2 at position 1 6682 * yarray.insert(1, [1, 2]) 6683 * 6684 * @param {number} index The index to insert content at. 6685 * @param {Array<T>} content The array of content 6686 */ 6687 insert(index, content) { 6688 if (this.doc !== null) { 6689 transact(this.doc, (transaction) => { 6690 typeListInsertGenerics( 6691 transaction, 6692 this, 6693 index, 6694 /** @type {any} */ 6695 content 6696 ); 6697 }); 6698 } else { 6699 this._prelimContent.splice(index, 0, ...content); 6700 } 6701 } 6702 /** 6703 * Appends content to this YArray. 6704 * 6705 * @param {Array<T>} content Array of content to append. 6706 * 6707 * @todo Use the following implementation in all types. 6708 */ 6709 push(content) { 6710 if (this.doc !== null) { 6711 transact(this.doc, (transaction) => { 6712 typeListPushGenerics( 6713 transaction, 6714 this, 6715 /** @type {any} */ 6716 content 6717 ); 6718 }); 6719 } else { 6720 this._prelimContent.push(...content); 6721 } 6722 } 6723 /** 6724 * Prepends content to this YArray. 6725 * 6726 * @param {Array<T>} content Array of content to prepend. 6727 */ 6728 unshift(content) { 6729 this.insert(0, content); 6730 } 6731 /** 6732 * Deletes elements starting from an index. 6733 * 6734 * @param {number} index Index at which to start deleting elements 6735 * @param {number} length The number of elements to remove. Defaults to 1. 6736 */ 6737 delete(index, length2 = 1) { 6738 if (this.doc !== null) { 6739 transact(this.doc, (transaction) => { 6740 typeListDelete(transaction, this, index, length2); 6741 }); 6742 } else { 6743 this._prelimContent.splice(index, length2); 6744 } 6745 } 6746 /** 6747 * Returns the i-th element from a YArray. 6748 * 6749 * @param {number} index The index of the element to return from the YArray 6750 * @return {T} 6751 */ 6752 get(index) { 6753 return typeListGet(this, index); 6754 } 6755 /** 6756 * Transforms this YArray to a JavaScript Array. 6757 * 6758 * @return {Array<T>} 6759 */ 6760 toArray() { 6761 return typeListToArray(this); 6762 } 6763 /** 6764 * Returns a portion of this YArray into a JavaScript Array selected 6765 * from start to end (end not included). 6766 * 6767 * @param {number} [start] 6768 * @param {number} [end] 6769 * @return {Array<T>} 6770 */ 6771 slice(start = 0, end = this.length) { 6772 return typeListSlice(this, start, end); 6773 } 6774 /** 6775 * Transforms this Shared Type to a JSON object. 6776 * 6777 * @return {Array<any>} 6778 */ 6779 toJSON() { 6780 return this.map((c) => c instanceof AbstractType ? c.toJSON() : c); 6781 } 6782 /** 6783 * Returns an Array with the result of calling a provided function on every 6784 * element of this YArray. 6785 * 6786 * @template M 6787 * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array 6788 * @return {Array<M>} A new array with each element being the result of the 6789 * callback function 6790 */ 6791 map(f) { 6792 return typeListMap( 6793 this, 6794 /** @type {any} */ 6795 f 6796 ); 6797 } 6798 /** 6799 * Executes a provided function once on every element of this YArray. 6800 * 6801 * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray. 6802 */ 6803 forEach(f) { 6804 typeListForEach(this, f); 6805 } 6806 /** 6807 * @return {IterableIterator<T>} 6808 */ 6809 [Symbol.iterator]() { 6810 return typeListCreateIterator(this); 6811 } 6812 /** 6813 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 6814 */ 6815 _write(encoder) { 6816 encoder.writeTypeRef(YArrayRefID); 6817 } 6818 }; 6819 var readYArray = (_decoder) => new YArray(); 6820 var YMapEvent = class extends YEvent { 6821 /** 6822 * @param {YMap<T>} ymap The YArray that changed. 6823 * @param {Transaction} transaction 6824 * @param {Set<any>} subs The keys that changed. 6825 */ 6826 constructor(ymap, transaction, subs) { 6827 super(ymap, transaction); 6828 this.keysChanged = subs; 6829 } 6830 }; 6831 var YMap = class _YMap extends AbstractType { 6832 /** 6833 * 6834 * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap 6835 */ 6836 constructor(entries) { 6837 super(); 6838 this._prelimContent = null; 6839 if (entries === void 0) { 6840 this._prelimContent = /* @__PURE__ */ new Map(); 6841 } else { 6842 this._prelimContent = new Map(entries); 6843 } 6844 } 6845 /** 6846 * Integrate this type into the Yjs instance. 6847 * 6848 * * Save this struct in the os 6849 * * This type is sent to other client 6850 * * Observer functions are fired 6851 * 6852 * @param {Doc} y The Yjs instance 6853 * @param {Item} item 6854 */ 6855 _integrate(y, item) { 6856 super._integrate(y, item); 6857 this._prelimContent.forEach((value, key) => { 6858 this.set(key, value); 6859 }); 6860 this._prelimContent = null; 6861 } 6862 /** 6863 * @return {YMap<MapType>} 6864 */ 6865 _copy() { 6866 return new _YMap(); 6867 } 6868 /** 6869 * Makes a copy of this data type that can be included somewhere else. 6870 * 6871 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6872 * 6873 * @return {YMap<MapType>} 6874 */ 6875 clone() { 6876 const map2 = new _YMap(); 6877 this.forEach((value, key) => { 6878 map2.set(key, value instanceof AbstractType ? ( 6879 /** @type {typeof value} */ 6880 value.clone() 6881 ) : value); 6882 }); 6883 return map2; 6884 } 6885 /** 6886 * Creates YMapEvent and calls observers. 6887 * 6888 * @param {Transaction} transaction 6889 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 6890 */ 6891 _callObserver(transaction, parentSubs) { 6892 callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); 6893 } 6894 /** 6895 * Transforms this Shared Type to a JSON object. 6896 * 6897 * @return {Object<string,any>} 6898 */ 6899 toJSON() { 6900 this.doc ?? warnPrematureAccess(); 6901 const map2 = {}; 6902 this._map.forEach((item, key) => { 6903 if (!item.deleted) { 6904 const v = item.content.getContent()[item.length - 1]; 6905 map2[key] = v instanceof AbstractType ? v.toJSON() : v; 6906 } 6907 }); 6908 return map2; 6909 } 6910 /** 6911 * Returns the size of the YMap (count of key/value pairs) 6912 * 6913 * @return {number} 6914 */ 6915 get size() { 6916 return [...createMapIterator(this)].length; 6917 } 6918 /** 6919 * Returns the keys for each element in the YMap Type. 6920 * 6921 * @return {IterableIterator<string>} 6922 */ 6923 keys() { 6924 return iteratorMap( 6925 createMapIterator(this), 6926 /** @param {any} v */ 6927 (v) => v[0] 6928 ); 6929 } 6930 /** 6931 * Returns the values for each element in the YMap Type. 6932 * 6933 * @return {IterableIterator<MapType>} 6934 */ 6935 values() { 6936 return iteratorMap( 6937 createMapIterator(this), 6938 /** @param {any} v */ 6939 (v) => v[1].content.getContent()[v[1].length - 1] 6940 ); 6941 } 6942 /** 6943 * Returns an Iterator of [key, value] pairs 6944 * 6945 * @return {IterableIterator<[string, MapType]>} 6946 */ 6947 entries() { 6948 return iteratorMap( 6949 createMapIterator(this), 6950 /** @param {any} v */ 6951 (v) => ( 6952 /** @type {any} */ 6953 [v[0], v[1].content.getContent()[v[1].length - 1]] 6954 ) 6955 ); 6956 } 6957 /** 6958 * Executes a provided function on once on every key-value pair. 6959 * 6960 * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray. 6961 */ 6962 forEach(f) { 6963 this.doc ?? warnPrematureAccess(); 6964 this._map.forEach((item, key) => { 6965 if (!item.deleted) { 6966 f(item.content.getContent()[item.length - 1], key, this); 6967 } 6968 }); 6969 } 6970 /** 6971 * Returns an Iterator of [key, value] pairs 6972 * 6973 * @return {IterableIterator<[string, MapType]>} 6974 */ 6975 [Symbol.iterator]() { 6976 return this.entries(); 6977 } 6978 /** 6979 * Remove a specified element from this YMap. 6980 * 6981 * @param {string} key The key of the element to remove. 6982 */ 6983 delete(key) { 6984 if (this.doc !== null) { 6985 transact(this.doc, (transaction) => { 6986 typeMapDelete(transaction, this, key); 6987 }); 6988 } else { 6989 this._prelimContent.delete(key); 6990 } 6991 } 6992 /** 6993 * Adds or updates an element with a specified key and value. 6994 * @template {MapType} VAL 6995 * 6996 * @param {string} key The key of the element to add to this YMap 6997 * @param {VAL} value The value of the element to add 6998 * @return {VAL} 6999 */ 7000 set(key, value) { 7001 if (this.doc !== null) { 7002 transact(this.doc, (transaction) => { 7003 typeMapSet( 7004 transaction, 7005 this, 7006 key, 7007 /** @type {any} */ 7008 value 7009 ); 7010 }); 7011 } else { 7012 this._prelimContent.set(key, value); 7013 } 7014 return value; 7015 } 7016 /** 7017 * Returns a specified element from this YMap. 7018 * 7019 * @param {string} key 7020 * @return {MapType|undefined} 7021 */ 7022 get(key) { 7023 return ( 7024 /** @type {any} */ 7025 typeMapGet(this, key) 7026 ); 7027 } 7028 /** 7029 * Returns a boolean indicating whether the specified key exists or not. 7030 * 7031 * @param {string} key The key to test. 7032 * @return {boolean} 7033 */ 7034 has(key) { 7035 return typeMapHas(this, key); 7036 } 7037 /** 7038 * Removes all elements from this YMap. 7039 */ 7040 clear() { 7041 if (this.doc !== null) { 7042 transact(this.doc, (transaction) => { 7043 this.forEach(function(_value, key, map2) { 7044 typeMapDelete(transaction, map2, key); 7045 }); 7046 }); 7047 } else { 7048 this._prelimContent.clear(); 7049 } 7050 } 7051 /** 7052 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 7053 */ 7054 _write(encoder) { 7055 encoder.writeTypeRef(YMapRefID); 7056 } 7057 }; 7058 var readYMap = (_decoder) => new YMap(); 7059 var equalAttrs = (a, b) => a === b || typeof a === "object" && typeof b === "object" && a && b && equalFlat(a, b); 7060 var ItemTextListPosition = class { 7061 /** 7062 * @param {Item|null} left 7063 * @param {Item|null} right 7064 * @param {number} index 7065 * @param {Map<string,any>} currentAttributes 7066 */ 7067 constructor(left, right, index, currentAttributes) { 7068 this.left = left; 7069 this.right = right; 7070 this.index = index; 7071 this.currentAttributes = currentAttributes; 7072 } 7073 /** 7074 * Only call this if you know that this.right is defined 7075 */ 7076 forward() { 7077 if (this.right === null) { 7078 unexpectedCase(); 7079 } 7080 switch (this.right.content.constructor) { 7081 case ContentFormat: 7082 if (!this.right.deleted) { 7083 updateCurrentAttributes( 7084 this.currentAttributes, 7085 /** @type {ContentFormat} */ 7086 this.right.content 7087 ); 7088 } 7089 break; 7090 default: 7091 if (!this.right.deleted) { 7092 this.index += this.right.length; 7093 } 7094 break; 7095 } 7096 this.left = this.right; 7097 this.right = this.right.right; 7098 } 7099 }; 7100 var findNextPosition = (transaction, pos, count) => { 7101 while (pos.right !== null && count > 0) { 7102 switch (pos.right.content.constructor) { 7103 case ContentFormat: 7104 if (!pos.right.deleted) { 7105 updateCurrentAttributes( 7106 pos.currentAttributes, 7107 /** @type {ContentFormat} */ 7108 pos.right.content 7109 ); 7110 } 7111 break; 7112 default: 7113 if (!pos.right.deleted) { 7114 if (count < pos.right.length) { 7115 getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); 7116 } 7117 pos.index += pos.right.length; 7118 count -= pos.right.length; 7119 } 7120 break; 7121 } 7122 pos.left = pos.right; 7123 pos.right = pos.right.right; 7124 } 7125 return pos; 7126 }; 7127 var findPosition = (transaction, parent, index, useSearchMarker) => { 7128 const currentAttributes = /* @__PURE__ */ new Map(); 7129 const marker = useSearchMarker ? findMarker(parent, index) : null; 7130 if (marker) { 7131 const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); 7132 return findNextPosition(transaction, pos, index - marker.index); 7133 } else { 7134 const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); 7135 return findNextPosition(transaction, pos, index); 7136 } 7137 }; 7138 var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { 7139 while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs( 7140 negatedAttributes.get( 7141 /** @type {ContentFormat} */ 7142 currPos.right.content.key 7143 ), 7144 /** @type {ContentFormat} */ 7145 currPos.right.content.value 7146 ))) { 7147 if (!currPos.right.deleted) { 7148 negatedAttributes.delete( 7149 /** @type {ContentFormat} */ 7150 currPos.right.content.key 7151 ); 7152 } 7153 currPos.forward(); 7154 } 7155 const doc2 = transaction.doc; 7156 const ownClientId = doc2.clientID; 7157 negatedAttributes.forEach((val, key) => { 7158 const left = currPos.left; 7159 const right = currPos.right; 7160 const nextFormat = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); 7161 nextFormat.integrate(transaction, 0); 7162 currPos.right = nextFormat; 7163 currPos.forward(); 7164 }); 7165 }; 7166 var updateCurrentAttributes = (currentAttributes, format) => { 7167 const { key, value } = format; 7168 if (value === null) { 7169 currentAttributes.delete(key); 7170 } else { 7171 currentAttributes.set(key, value); 7172 } 7173 }; 7174 var minimizeAttributeChanges = (currPos, attributes) => { 7175 while (true) { 7176 if (currPos.right === null) { 7177 break; 7178 } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs( 7179 attributes[ 7180 /** @type {ContentFormat} */ 7181 currPos.right.content.key 7182 ] ?? null, 7183 /** @type {ContentFormat} */ 7184 currPos.right.content.value 7185 )) ; 7186 else { 7187 break; 7188 } 7189 currPos.forward(); 7190 } 7191 }; 7192 var insertAttributes = (transaction, parent, currPos, attributes) => { 7193 const doc2 = transaction.doc; 7194 const ownClientId = doc2.clientID; 7195 const negatedAttributes = /* @__PURE__ */ new Map(); 7196 for (const key in attributes) { 7197 const val = attributes[key]; 7198 const currentVal = currPos.currentAttributes.get(key) ?? null; 7199 if (!equalAttrs(currentVal, val)) { 7200 negatedAttributes.set(key, currentVal); 7201 const { left, right } = currPos; 7202 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); 7203 currPos.right.integrate(transaction, 0); 7204 currPos.forward(); 7205 } 7206 } 7207 return negatedAttributes; 7208 }; 7209 var insertText = (transaction, parent, currPos, text2, attributes) => { 7210 currPos.currentAttributes.forEach((_val, key) => { 7211 if (attributes[key] === void 0) { 7212 attributes[key] = null; 7213 } 7214 }); 7215 const doc2 = transaction.doc; 7216 const ownClientId = doc2.clientID; 7217 minimizeAttributeChanges(currPos, attributes); 7218 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); 7219 const content = text2.constructor === String ? new ContentString( 7220 /** @type {string} */ 7221 text2 7222 ) : text2 instanceof AbstractType ? new ContentType(text2) : new ContentEmbed(text2); 7223 let { left, right, index } = currPos; 7224 if (parent._searchMarker) { 7225 updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); 7226 } 7227 right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); 7228 right.integrate(transaction, 0); 7229 currPos.right = right; 7230 currPos.index = index; 7231 currPos.forward(); 7232 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); 7233 }; 7234 var formatText = (transaction, parent, currPos, length2, attributes) => { 7235 const doc2 = transaction.doc; 7236 const ownClientId = doc2.clientID; 7237 minimizeAttributeChanges(currPos, attributes); 7238 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); 7239 iterationLoop: while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) { 7240 if (!currPos.right.deleted) { 7241 switch (currPos.right.content.constructor) { 7242 case ContentFormat: { 7243 const { key, value } = ( 7244 /** @type {ContentFormat} */ 7245 currPos.right.content 7246 ); 7247 const attr = attributes[key]; 7248 if (attr !== void 0) { 7249 if (equalAttrs(attr, value)) { 7250 negatedAttributes.delete(key); 7251 } else { 7252 if (length2 === 0) { 7253 break iterationLoop; 7254 } 7255 negatedAttributes.set(key, value); 7256 } 7257 currPos.right.delete(transaction); 7258 } else { 7259 currPos.currentAttributes.set(key, value); 7260 } 7261 break; 7262 } 7263 default: 7264 if (length2 < currPos.right.length) { 7265 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); 7266 } 7267 length2 -= currPos.right.length; 7268 break; 7269 } 7270 } 7271 currPos.forward(); 7272 } 7273 if (length2 > 0) { 7274 let newlines = ""; 7275 for (; length2 > 0; length2--) { 7276 newlines += "\n"; 7277 } 7278 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines)); 7279 currPos.right.integrate(transaction, 0); 7280 currPos.forward(); 7281 } 7282 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); 7283 }; 7284 var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => { 7285 let end = start; 7286 const endFormats = create(); 7287 while (end && (!end.countable || end.deleted)) { 7288 if (!end.deleted && end.content.constructor === ContentFormat) { 7289 const cf = ( 7290 /** @type {ContentFormat} */ 7291 end.content 7292 ); 7293 endFormats.set(cf.key, cf); 7294 } 7295 end = end.right; 7296 } 7297 let cleanups = 0; 7298 let reachedCurr = false; 7299 while (start !== end) { 7300 if (curr === start) { 7301 reachedCurr = true; 7302 } 7303 if (!start.deleted) { 7304 const content = start.content; 7305 switch (content.constructor) { 7306 case ContentFormat: { 7307 const { key, value } = ( 7308 /** @type {ContentFormat} */ 7309 content 7310 ); 7311 const startAttrValue = startAttributes.get(key) ?? null; 7312 if (endFormats.get(key) !== content || startAttrValue === value) { 7313 start.delete(transaction); 7314 cleanups++; 7315 if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) { 7316 if (startAttrValue === null) { 7317 currAttributes.delete(key); 7318 } else { 7319 currAttributes.set(key, startAttrValue); 7320 } 7321 } 7322 } 7323 if (!reachedCurr && !start.deleted) { 7324 updateCurrentAttributes( 7325 currAttributes, 7326 /** @type {ContentFormat} */ 7327 content 7328 ); 7329 } 7330 break; 7331 } 7332 } 7333 } 7334 start = /** @type {Item} */ 7335 start.right; 7336 } 7337 return cleanups; 7338 }; 7339 var cleanupContextlessFormattingGap = (transaction, item) => { 7340 while (item && item.right && (item.right.deleted || !item.right.countable)) { 7341 item = item.right; 7342 } 7343 const attrs = /* @__PURE__ */ new Set(); 7344 while (item && (item.deleted || !item.countable)) { 7345 if (!item.deleted && item.content.constructor === ContentFormat) { 7346 const key = ( 7347 /** @type {ContentFormat} */ 7348 item.content.key 7349 ); 7350 if (attrs.has(key)) { 7351 item.delete(transaction); 7352 } else { 7353 attrs.add(key); 7354 } 7355 } 7356 item = item.left; 7357 } 7358 }; 7359 var cleanupYTextFormatting = (type) => { 7360 let res = 0; 7361 transact( 7362 /** @type {Doc} */ 7363 type.doc, 7364 (transaction) => { 7365 let start = ( 7366 /** @type {Item} */ 7367 type._start 7368 ); 7369 let end = type._start; 7370 let startAttributes = create(); 7371 const currentAttributes = copy(startAttributes); 7372 while (end) { 7373 if (end.deleted === false) { 7374 switch (end.content.constructor) { 7375 case ContentFormat: 7376 updateCurrentAttributes( 7377 currentAttributes, 7378 /** @type {ContentFormat} */ 7379 end.content 7380 ); 7381 break; 7382 default: 7383 res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); 7384 startAttributes = copy(currentAttributes); 7385 start = end; 7386 break; 7387 } 7388 } 7389 end = end.right; 7390 } 7391 } 7392 ); 7393 return res; 7394 }; 7395 var cleanupYTextAfterTransaction = (transaction) => { 7396 const needFullCleanup = /* @__PURE__ */ new Set(); 7397 const doc2 = transaction.doc; 7398 for (const [client, afterClock] of transaction.afterState.entries()) { 7399 const clock = transaction.beforeState.get(client) || 0; 7400 if (afterClock === clock) { 7401 continue; 7402 } 7403 iterateStructs( 7404 transaction, 7405 /** @type {Array<Item|GC>} */ 7406 doc2.store.clients.get(client), 7407 clock, 7408 afterClock, 7409 (item) => { 7410 if (!item.deleted && /** @type {Item} */ 7411 item.content.constructor === ContentFormat && item.constructor !== GC) { 7412 needFullCleanup.add( 7413 /** @type {any} */ 7414 item.parent 7415 ); 7416 } 7417 } 7418 ); 7419 } 7420 transact(doc2, (t) => { 7421 iterateDeletedStructs(transaction, transaction.deleteSet, (item) => { 7422 if (item instanceof GC || !/** @type {YText} */ 7423 item.parent._hasFormatting || needFullCleanup.has( 7424 /** @type {YText} */ 7425 item.parent 7426 )) { 7427 return; 7428 } 7429 const parent = ( 7430 /** @type {YText} */ 7431 item.parent 7432 ); 7433 if (item.content.constructor === ContentFormat) { 7434 needFullCleanup.add(parent); 7435 } else { 7436 cleanupContextlessFormattingGap(t, item); 7437 } 7438 }); 7439 for (const yText of needFullCleanup) { 7440 cleanupYTextFormatting(yText); 7441 } 7442 }); 7443 }; 7444 var deleteText = (transaction, currPos, length2) => { 7445 const startLength = length2; 7446 const startAttrs = copy(currPos.currentAttributes); 7447 const start = currPos.right; 7448 while (length2 > 0 && currPos.right !== null) { 7449 if (currPos.right.deleted === false) { 7450 switch (currPos.right.content.constructor) { 7451 case ContentType: 7452 case ContentEmbed: 7453 case ContentString: 7454 if (length2 < currPos.right.length) { 7455 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); 7456 } 7457 length2 -= currPos.right.length; 7458 currPos.right.delete(transaction); 7459 break; 7460 } 7461 } 7462 currPos.forward(); 7463 } 7464 if (start) { 7465 cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes); 7466 } 7467 const parent = ( 7468 /** @type {AbstractType<any>} */ 7469 /** @type {Item} */ 7470 (currPos.left || currPos.right).parent 7471 ); 7472 if (parent._searchMarker) { 7473 updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length2); 7474 } 7475 return currPos; 7476 }; 7477 var YTextEvent = class extends YEvent { 7478 /** 7479 * @param {YText} ytext 7480 * @param {Transaction} transaction 7481 * @param {Set<any>} subs The keys that changed 7482 */ 7483 constructor(ytext, transaction, subs) { 7484 super(ytext, transaction); 7485 this.childListChanged = false; 7486 this.keysChanged = /* @__PURE__ */ new Set(); 7487 subs.forEach((sub) => { 7488 if (sub === null) { 7489 this.childListChanged = true; 7490 } else { 7491 this.keysChanged.add(sub); 7492 } 7493 }); 7494 } 7495 /** 7496 * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}} 7497 */ 7498 get changes() { 7499 if (this._changes === null) { 7500 const changes = { 7501 keys: this.keys, 7502 delta: this.delta, 7503 added: /* @__PURE__ */ new Set(), 7504 deleted: /* @__PURE__ */ new Set() 7505 }; 7506 this._changes = changes; 7507 } 7508 return ( 7509 /** @type {any} */ 7510 this._changes 7511 ); 7512 } 7513 /** 7514 * Compute the changes in the delta format. 7515 * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. 7516 * 7517 * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>} 7518 * 7519 * @public 7520 */ 7521 get delta() { 7522 if (this._delta === null) { 7523 const y = ( 7524 /** @type {Doc} */ 7525 this.target.doc 7526 ); 7527 const delta = []; 7528 transact(y, (transaction) => { 7529 const currentAttributes = /* @__PURE__ */ new Map(); 7530 const oldAttributes = /* @__PURE__ */ new Map(); 7531 let item = this.target._start; 7532 let action = null; 7533 const attributes = {}; 7534 let insert2 = ""; 7535 let retain = 0; 7536 let deleteLen = 0; 7537 const addOp = () => { 7538 if (action !== null) { 7539 let op = null; 7540 switch (action) { 7541 case "delete": 7542 if (deleteLen > 0) { 7543 op = { delete: deleteLen }; 7544 } 7545 deleteLen = 0; 7546 break; 7547 case "insert": 7548 if (typeof insert2 === "object" || insert2.length > 0) { 7549 op = { insert: insert2 }; 7550 if (currentAttributes.size > 0) { 7551 op.attributes = {}; 7552 currentAttributes.forEach((value, key) => { 7553 if (value !== null) { 7554 op.attributes[key] = value; 7555 } 7556 }); 7557 } 7558 } 7559 insert2 = ""; 7560 break; 7561 case "retain": 7562 if (retain > 0) { 7563 op = { retain }; 7564 if (!isEmpty(attributes)) { 7565 op.attributes = assign({}, attributes); 7566 } 7567 } 7568 retain = 0; 7569 break; 7570 } 7571 if (op) delta.push(op); 7572 action = null; 7573 } 7574 }; 7575 while (item !== null) { 7576 switch (item.content.constructor) { 7577 case ContentType: 7578 case ContentEmbed: 7579 if (this.adds(item)) { 7580 if (!this.deletes(item)) { 7581 addOp(); 7582 action = "insert"; 7583 insert2 = item.content.getContent()[0]; 7584 addOp(); 7585 } 7586 } else if (this.deletes(item)) { 7587 if (action !== "delete") { 7588 addOp(); 7589 action = "delete"; 7590 } 7591 deleteLen += 1; 7592 } else if (!item.deleted) { 7593 if (action !== "retain") { 7594 addOp(); 7595 action = "retain"; 7596 } 7597 retain += 1; 7598 } 7599 break; 7600 case ContentString: 7601 if (this.adds(item)) { 7602 if (!this.deletes(item)) { 7603 if (action !== "insert") { 7604 addOp(); 7605 action = "insert"; 7606 } 7607 insert2 += /** @type {ContentString} */ 7608 item.content.str; 7609 } 7610 } else if (this.deletes(item)) { 7611 if (action !== "delete") { 7612 addOp(); 7613 action = "delete"; 7614 } 7615 deleteLen += item.length; 7616 } else if (!item.deleted) { 7617 if (action !== "retain") { 7618 addOp(); 7619 action = "retain"; 7620 } 7621 retain += item.length; 7622 } 7623 break; 7624 case ContentFormat: { 7625 const { key, value } = ( 7626 /** @type {ContentFormat} */ 7627 item.content 7628 ); 7629 if (this.adds(item)) { 7630 if (!this.deletes(item)) { 7631 const curVal = currentAttributes.get(key) ?? null; 7632 if (!equalAttrs(curVal, value)) { 7633 if (action === "retain") { 7634 addOp(); 7635 } 7636 if (equalAttrs(value, oldAttributes.get(key) ?? null)) { 7637 delete attributes[key]; 7638 } else { 7639 attributes[key] = value; 7640 } 7641 } else if (value !== null) { 7642 item.delete(transaction); 7643 } 7644 } 7645 } else if (this.deletes(item)) { 7646 oldAttributes.set(key, value); 7647 const curVal = currentAttributes.get(key) ?? null; 7648 if (!equalAttrs(curVal, value)) { 7649 if (action === "retain") { 7650 addOp(); 7651 } 7652 attributes[key] = curVal; 7653 } 7654 } else if (!item.deleted) { 7655 oldAttributes.set(key, value); 7656 const attr = attributes[key]; 7657 if (attr !== void 0) { 7658 if (!equalAttrs(attr, value)) { 7659 if (action === "retain") { 7660 addOp(); 7661 } 7662 if (value === null) { 7663 delete attributes[key]; 7664 } else { 7665 attributes[key] = value; 7666 } 7667 } else if (attr !== null) { 7668 item.delete(transaction); 7669 } 7670 } 7671 } 7672 if (!item.deleted) { 7673 if (action === "insert") { 7674 addOp(); 7675 } 7676 updateCurrentAttributes( 7677 currentAttributes, 7678 /** @type {ContentFormat} */ 7679 item.content 7680 ); 7681 } 7682 break; 7683 } 7684 } 7685 item = item.right; 7686 } 7687 addOp(); 7688 while (delta.length > 0) { 7689 const lastOp = delta[delta.length - 1]; 7690 if (lastOp.retain !== void 0 && lastOp.attributes === void 0) { 7691 delta.pop(); 7692 } else { 7693 break; 7694 } 7695 } 7696 }); 7697 this._delta = delta; 7698 } 7699 return ( 7700 /** @type {any} */ 7701 this._delta 7702 ); 7703 } 7704 }; 7705 var YText = class _YText extends AbstractType { 7706 /** 7707 * @param {String} [string] The initial value of the YText. 7708 */ 7709 constructor(string) { 7710 super(); 7711 this._pending = string !== void 0 ? [() => this.insert(0, string)] : []; 7712 this._searchMarker = []; 7713 this._hasFormatting = false; 7714 } 7715 /** 7716 * Number of characters of this text type. 7717 * 7718 * @type {number} 7719 */ 7720 get length() { 7721 this.doc ?? warnPrematureAccess(); 7722 return this._length; 7723 } 7724 /** 7725 * @param {Doc} y 7726 * @param {Item} item 7727 */ 7728 _integrate(y, item) { 7729 super._integrate(y, item); 7730 try { 7731 this._pending.forEach((f) => f()); 7732 } catch (e) { 7733 console.error(e); 7734 } 7735 this._pending = null; 7736 } 7737 _copy() { 7738 return new _YText(); 7739 } 7740 /** 7741 * Makes a copy of this data type that can be included somewhere else. 7742 * 7743 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 7744 * 7745 * @return {YText} 7746 */ 7747 clone() { 7748 const text2 = new _YText(); 7749 text2.applyDelta(this.toDelta()); 7750 return text2; 7751 } 7752 /** 7753 * Creates YTextEvent and calls observers. 7754 * 7755 * @param {Transaction} transaction 7756 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 7757 */ 7758 _callObserver(transaction, parentSubs) { 7759 super._callObserver(transaction, parentSubs); 7760 const event = new YTextEvent(this, transaction, parentSubs); 7761 callTypeObservers(this, transaction, event); 7762 if (!transaction.local && this._hasFormatting) { 7763 transaction._needFormattingCleanup = true; 7764 } 7765 } 7766 /** 7767 * Returns the unformatted string representation of this YText type. 7768 * 7769 * @public 7770 */ 7771 toString() { 7772 this.doc ?? warnPrematureAccess(); 7773 let str = ""; 7774 let n = this._start; 7775 while (n !== null) { 7776 if (!n.deleted && n.countable && n.content.constructor === ContentString) { 7777 str += /** @type {ContentString} */ 7778 n.content.str; 7779 } 7780 n = n.right; 7781 } 7782 return str; 7783 } 7784 /** 7785 * Returns the unformatted string representation of this YText type. 7786 * 7787 * @return {string} 7788 * @public 7789 */ 7790 toJSON() { 7791 return this.toString(); 7792 } 7793 /** 7794 * Apply a {@link Delta} on this shared YText type. 7795 * 7796 * @param {Array<any>} delta The changes to apply on this element. 7797 * @param {object} opts 7798 * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. 7799 * 7800 * 7801 * @public 7802 */ 7803 applyDelta(delta, { sanitize = true } = {}) { 7804 if (this.doc !== null) { 7805 transact(this.doc, (transaction) => { 7806 const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map()); 7807 for (let i = 0; i < delta.length; i++) { 7808 const op = delta[i]; 7809 if (op.insert !== void 0) { 7810 const ins = !sanitize && typeof op.insert === "string" && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === "\n" ? op.insert.slice(0, -1) : op.insert; 7811 if (typeof ins !== "string" || ins.length > 0) { 7812 insertText(transaction, this, currPos, ins, op.attributes || {}); 7813 } 7814 } else if (op.retain !== void 0) { 7815 formatText(transaction, this, currPos, op.retain, op.attributes || {}); 7816 } else if (op.delete !== void 0) { 7817 deleteText(transaction, currPos, op.delete); 7818 } 7819 } 7820 }); 7821 } else { 7822 this._pending.push(() => this.applyDelta(delta)); 7823 } 7824 } 7825 /** 7826 * Returns the Delta representation of this YText type. 7827 * 7828 * @param {Snapshot} [snapshot] 7829 * @param {Snapshot} [prevSnapshot] 7830 * @param {function('removed' | 'added', ID):any} [computeYChange] 7831 * @return {any} The Delta representation of this type. 7832 * 7833 * @public 7834 */ 7835 toDelta(snapshot2, prevSnapshot, computeYChange) { 7836 this.doc ?? warnPrematureAccess(); 7837 const ops = []; 7838 const currentAttributes = /* @__PURE__ */ new Map(); 7839 const doc2 = ( 7840 /** @type {Doc} */ 7841 this.doc 7842 ); 7843 let str = ""; 7844 let n = this._start; 7845 function packStr() { 7846 if (str.length > 0) { 7847 const attributes = {}; 7848 let addAttributes = false; 7849 currentAttributes.forEach((value, key) => { 7850 addAttributes = true; 7851 attributes[key] = value; 7852 }); 7853 const op = { insert: str }; 7854 if (addAttributes) { 7855 op.attributes = attributes; 7856 } 7857 ops.push(op); 7858 str = ""; 7859 } 7860 } 7861 const computeDelta = () => { 7862 while (n !== null) { 7863 if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) { 7864 switch (n.content.constructor) { 7865 case ContentString: { 7866 const cur = currentAttributes.get("ychange"); 7867 if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) { 7868 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") { 7869 packStr(); 7870 currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" }); 7871 } 7872 } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) { 7873 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") { 7874 packStr(); 7875 currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" }); 7876 } 7877 } else if (cur !== void 0) { 7878 packStr(); 7879 currentAttributes.delete("ychange"); 7880 } 7881 str += /** @type {ContentString} */ 7882 n.content.str; 7883 break; 7884 } 7885 case ContentType: 7886 case ContentEmbed: { 7887 packStr(); 7888 const op = { 7889 insert: n.content.getContent()[0] 7890 }; 7891 if (currentAttributes.size > 0) { 7892 const attrs = ( 7893 /** @type {Object<string,any>} */ 7894 {} 7895 ); 7896 op.attributes = attrs; 7897 currentAttributes.forEach((value, key) => { 7898 attrs[key] = value; 7899 }); 7900 } 7901 ops.push(op); 7902 break; 7903 } 7904 case ContentFormat: 7905 if (isVisible(n, snapshot2)) { 7906 packStr(); 7907 updateCurrentAttributes( 7908 currentAttributes, 7909 /** @type {ContentFormat} */ 7910 n.content 7911 ); 7912 } 7913 break; 7914 } 7915 } 7916 n = n.right; 7917 } 7918 packStr(); 7919 }; 7920 if (snapshot2 || prevSnapshot) { 7921 transact(doc2, (transaction) => { 7922 if (snapshot2) { 7923 splitSnapshotAffectedStructs(transaction, snapshot2); 7924 } 7925 if (prevSnapshot) { 7926 splitSnapshotAffectedStructs(transaction, prevSnapshot); 7927 } 7928 computeDelta(); 7929 }, "cleanup"); 7930 } else { 7931 computeDelta(); 7932 } 7933 return ops; 7934 } 7935 /** 7936 * Insert text at a given index. 7937 * 7938 * @param {number} index The index at which to start inserting. 7939 * @param {String} text The text to insert at the specified position. 7940 * @param {TextAttributes} [attributes] Optionally define some formatting 7941 * information to apply on the inserted 7942 * Text. 7943 * @public 7944 */ 7945 insert(index, text2, attributes) { 7946 if (text2.length <= 0) { 7947 return; 7948 } 7949 const y = this.doc; 7950 if (y !== null) { 7951 transact(y, (transaction) => { 7952 const pos = findPosition(transaction, this, index, !attributes); 7953 if (!attributes) { 7954 attributes = {}; 7955 pos.currentAttributes.forEach((v, k) => { 7956 attributes[k] = v; 7957 }); 7958 } 7959 insertText(transaction, this, pos, text2, attributes); 7960 }); 7961 } else { 7962 this._pending.push(() => this.insert(index, text2, attributes)); 7963 } 7964 } 7965 /** 7966 * Inserts an embed at a index. 7967 * 7968 * @param {number} index The index to insert the embed at. 7969 * @param {Object | AbstractType<any>} embed The Object that represents the embed. 7970 * @param {TextAttributes} [attributes] Attribute information to apply on the 7971 * embed 7972 * 7973 * @public 7974 */ 7975 insertEmbed(index, embed, attributes) { 7976 const y = this.doc; 7977 if (y !== null) { 7978 transact(y, (transaction) => { 7979 const pos = findPosition(transaction, this, index, !attributes); 7980 insertText(transaction, this, pos, embed, attributes || {}); 7981 }); 7982 } else { 7983 this._pending.push(() => this.insertEmbed(index, embed, attributes || {})); 7984 } 7985 } 7986 /** 7987 * Deletes text starting from an index. 7988 * 7989 * @param {number} index Index at which to start deleting. 7990 * @param {number} length The number of characters to remove. Defaults to 1. 7991 * 7992 * @public 7993 */ 7994 delete(index, length2) { 7995 if (length2 === 0) { 7996 return; 7997 } 7998 const y = this.doc; 7999 if (y !== null) { 8000 transact(y, (transaction) => { 8001 deleteText(transaction, findPosition(transaction, this, index, true), length2); 8002 }); 8003 } else { 8004 this._pending.push(() => this.delete(index, length2)); 8005 } 8006 } 8007 /** 8008 * Assigns properties to a range of text. 8009 * 8010 * @param {number} index The position where to start formatting. 8011 * @param {number} length The amount of characters to assign properties to. 8012 * @param {TextAttributes} attributes Attribute information to apply on the 8013 * text. 8014 * 8015 * @public 8016 */ 8017 format(index, length2, attributes) { 8018 if (length2 === 0) { 8019 return; 8020 } 8021 const y = this.doc; 8022 if (y !== null) { 8023 transact(y, (transaction) => { 8024 const pos = findPosition(transaction, this, index, false); 8025 if (pos.right === null) { 8026 return; 8027 } 8028 formatText(transaction, this, pos, length2, attributes); 8029 }); 8030 } else { 8031 this._pending.push(() => this.format(index, length2, attributes)); 8032 } 8033 } 8034 /** 8035 * Removes an attribute. 8036 * 8037 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 8038 * 8039 * @param {String} attributeName The attribute name that is to be removed. 8040 * 8041 * @public 8042 */ 8043 removeAttribute(attributeName) { 8044 if (this.doc !== null) { 8045 transact(this.doc, (transaction) => { 8046 typeMapDelete(transaction, this, attributeName); 8047 }); 8048 } else { 8049 this._pending.push(() => this.removeAttribute(attributeName)); 8050 } 8051 } 8052 /** 8053 * Sets or updates an attribute. 8054 * 8055 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 8056 * 8057 * @param {String} attributeName The attribute name that is to be set. 8058 * @param {any} attributeValue The attribute value that is to be set. 8059 * 8060 * @public 8061 */ 8062 setAttribute(attributeName, attributeValue) { 8063 if (this.doc !== null) { 8064 transact(this.doc, (transaction) => { 8065 typeMapSet(transaction, this, attributeName, attributeValue); 8066 }); 8067 } else { 8068 this._pending.push(() => this.setAttribute(attributeName, attributeValue)); 8069 } 8070 } 8071 /** 8072 * Returns an attribute value that belongs to the attribute name. 8073 * 8074 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 8075 * 8076 * @param {String} attributeName The attribute name that identifies the 8077 * queried value. 8078 * @return {any} The queried attribute value. 8079 * 8080 * @public 8081 */ 8082 getAttribute(attributeName) { 8083 return ( 8084 /** @type {any} */ 8085 typeMapGet(this, attributeName) 8086 ); 8087 } 8088 /** 8089 * Returns all attribute name/value pairs in a JSON Object. 8090 * 8091 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 8092 * 8093 * @return {Object<string, any>} A JSON Object that describes the attributes. 8094 * 8095 * @public 8096 */ 8097 getAttributes() { 8098 return typeMapGetAll(this); 8099 } 8100 /** 8101 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8102 */ 8103 _write(encoder) { 8104 encoder.writeTypeRef(YTextRefID); 8105 } 8106 }; 8107 var readYText = (_decoder) => new YText(); 8108 var YXmlTreeWalker = class { 8109 /** 8110 * @param {YXmlFragment | YXmlElement} root 8111 * @param {function(AbstractType<any>):boolean} [f] 8112 */ 8113 constructor(root, f = () => true) { 8114 this._filter = f; 8115 this._root = root; 8116 this._currentNode = /** @type {Item} */ 8117 root._start; 8118 this._firstCall = true; 8119 root.doc ?? warnPrematureAccess(); 8120 } 8121 [Symbol.iterator]() { 8122 return this; 8123 } 8124 /** 8125 * Get the next node. 8126 * 8127 * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node. 8128 * 8129 * @public 8130 */ 8131 next() { 8132 let n = this._currentNode; 8133 let type = n && n.content && /** @type {any} */ 8134 n.content.type; 8135 if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { 8136 do { 8137 type = /** @type {any} */ 8138 n.content.type; 8139 if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { 8140 n = type._start; 8141 } else { 8142 while (n !== null) { 8143 const nxt = n.next; 8144 if (nxt !== null) { 8145 n = nxt; 8146 break; 8147 } else if (n.parent === this._root) { 8148 n = null; 8149 } else { 8150 n = /** @type {AbstractType<any>} */ 8151 n.parent._item; 8152 } 8153 } 8154 } 8155 } while (n !== null && (n.deleted || !this._filter( 8156 /** @type {ContentType} */ 8157 n.content.type 8158 ))); 8159 } 8160 this._firstCall = false; 8161 if (n === null) { 8162 return { value: void 0, done: true }; 8163 } 8164 this._currentNode = n; 8165 return { value: ( 8166 /** @type {any} */ 8167 n.content.type 8168 ), done: false }; 8169 } 8170 }; 8171 var YXmlFragment = class _YXmlFragment extends AbstractType { 8172 constructor() { 8173 super(); 8174 this._prelimContent = []; 8175 } 8176 /** 8177 * @type {YXmlElement|YXmlText|null} 8178 */ 8179 get firstChild() { 8180 const first = this._first; 8181 return first ? first.content.getContent()[0] : null; 8182 } 8183 /** 8184 * Integrate this type into the Yjs instance. 8185 * 8186 * * Save this struct in the os 8187 * * This type is sent to other client 8188 * * Observer functions are fired 8189 * 8190 * @param {Doc} y The Yjs instance 8191 * @param {Item} item 8192 */ 8193 _integrate(y, item) { 8194 super._integrate(y, item); 8195 this.insert( 8196 0, 8197 /** @type {Array<any>} */ 8198 this._prelimContent 8199 ); 8200 this._prelimContent = null; 8201 } 8202 _copy() { 8203 return new _YXmlFragment(); 8204 } 8205 /** 8206 * Makes a copy of this data type that can be included somewhere else. 8207 * 8208 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8209 * 8210 * @return {YXmlFragment} 8211 */ 8212 clone() { 8213 const el = new _YXmlFragment(); 8214 el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item)); 8215 return el; 8216 } 8217 get length() { 8218 this.doc ?? warnPrematureAccess(); 8219 return this._prelimContent === null ? this._length : this._prelimContent.length; 8220 } 8221 /** 8222 * Create a subtree of childNodes. 8223 * 8224 * @example 8225 * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') 8226 * for (let node in walker) { 8227 * // `node` is a div node 8228 * nop(node) 8229 * } 8230 * 8231 * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and 8232 * returns a Boolean indicating whether the child 8233 * is to be included in the subtree. 8234 * @return {YXmlTreeWalker} A subtree and a position within it. 8235 * 8236 * @public 8237 */ 8238 createTreeWalker(filter) { 8239 return new YXmlTreeWalker(this, filter); 8240 } 8241 /** 8242 * Returns the first YXmlElement that matches the query. 8243 * Similar to DOM's {@link querySelector}. 8244 * 8245 * Query support: 8246 * - tagname 8247 * TODO: 8248 * - id 8249 * - attribute 8250 * 8251 * @param {CSS_Selector} query The query on the children. 8252 * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. 8253 * 8254 * @public 8255 */ 8256 querySelector(query) { 8257 query = query.toUpperCase(); 8258 const iterator = new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query); 8259 const next = iterator.next(); 8260 if (next.done) { 8261 return null; 8262 } else { 8263 return next.value; 8264 } 8265 } 8266 /** 8267 * Returns all YXmlElements that match the query. 8268 * Similar to Dom's {@link querySelectorAll}. 8269 * 8270 * @todo Does not yet support all queries. Currently only query by tagName. 8271 * 8272 * @param {CSS_Selector} query The query on the children 8273 * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query. 8274 * 8275 * @public 8276 */ 8277 querySelectorAll(query) { 8278 query = query.toUpperCase(); 8279 return from(new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query)); 8280 } 8281 /** 8282 * Creates YXmlEvent and calls observers. 8283 * 8284 * @param {Transaction} transaction 8285 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 8286 */ 8287 _callObserver(transaction, parentSubs) { 8288 callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); 8289 } 8290 /** 8291 * Get the string representation of all the children of this YXmlFragment. 8292 * 8293 * @return {string} The string representation of all children. 8294 */ 8295 toString() { 8296 return typeListMap(this, (xml) => xml.toString()).join(""); 8297 } 8298 /** 8299 * @return {string} 8300 */ 8301 toJSON() { 8302 return this.toString(); 8303 } 8304 /** 8305 * Creates a Dom Element that mirrors this YXmlElement. 8306 * 8307 * @param {Document} [_document=document] The document object (you must define 8308 * this when calling this method in 8309 * nodejs) 8310 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks 8311 * are presented in the DOM 8312 * @param {any} [binding] You should not set this property. This is 8313 * used if DomBinding wants to create a 8314 * association to the created DOM type. 8315 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8316 * 8317 * @public 8318 */ 8319 toDOM(_document = document, hooks = {}, binding) { 8320 const fragment = _document.createDocumentFragment(); 8321 if (binding !== void 0) { 8322 binding._createAssociation(fragment, this); 8323 } 8324 typeListForEach(this, (xmlType) => { 8325 fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); 8326 }); 8327 return fragment; 8328 } 8329 /** 8330 * Inserts new content at an index. 8331 * 8332 * @example 8333 * // Insert character 'a' at position 0 8334 * xml.insert(0, [new Y.XmlText('text')]) 8335 * 8336 * @param {number} index The index to insert content at 8337 * @param {Array<YXmlElement|YXmlText>} content The array of content 8338 */ 8339 insert(index, content) { 8340 if (this.doc !== null) { 8341 transact(this.doc, (transaction) => { 8342 typeListInsertGenerics(transaction, this, index, content); 8343 }); 8344 } else { 8345 this._prelimContent.splice(index, 0, ...content); 8346 } 8347 } 8348 /** 8349 * Inserts new content at an index. 8350 * 8351 * @example 8352 * // Insert character 'a' at position 0 8353 * xml.insert(0, [new Y.XmlText('text')]) 8354 * 8355 * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at 8356 * @param {Array<YXmlElement|YXmlText>} content The array of content 8357 */ 8358 insertAfter(ref, content) { 8359 if (this.doc !== null) { 8360 transact(this.doc, (transaction) => { 8361 const refItem = ref && ref instanceof AbstractType ? ref._item : ref; 8362 typeListInsertGenericsAfter(transaction, this, refItem, content); 8363 }); 8364 } else { 8365 const pc = ( 8366 /** @type {Array<any>} */ 8367 this._prelimContent 8368 ); 8369 const index = ref === null ? 0 : pc.findIndex((el) => el === ref) + 1; 8370 if (index === 0 && ref !== null) { 8371 throw create3("Reference item not found"); 8372 } 8373 pc.splice(index, 0, ...content); 8374 } 8375 } 8376 /** 8377 * Deletes elements starting from an index. 8378 * 8379 * @param {number} index Index at which to start deleting elements 8380 * @param {number} [length=1] The number of elements to remove. Defaults to 1. 8381 */ 8382 delete(index, length2 = 1) { 8383 if (this.doc !== null) { 8384 transact(this.doc, (transaction) => { 8385 typeListDelete(transaction, this, index, length2); 8386 }); 8387 } else { 8388 this._prelimContent.splice(index, length2); 8389 } 8390 } 8391 /** 8392 * Transforms this YArray to a JavaScript Array. 8393 * 8394 * @return {Array<YXmlElement|YXmlText|YXmlHook>} 8395 */ 8396 toArray() { 8397 return typeListToArray(this); 8398 } 8399 /** 8400 * Appends content to this YArray. 8401 * 8402 * @param {Array<YXmlElement|YXmlText>} content Array of content to append. 8403 */ 8404 push(content) { 8405 this.insert(this.length, content); 8406 } 8407 /** 8408 * Prepends content to this YArray. 8409 * 8410 * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend. 8411 */ 8412 unshift(content) { 8413 this.insert(0, content); 8414 } 8415 /** 8416 * Returns the i-th element from a YArray. 8417 * 8418 * @param {number} index The index of the element to return from the YArray 8419 * @return {YXmlElement|YXmlText} 8420 */ 8421 get(index) { 8422 return typeListGet(this, index); 8423 } 8424 /** 8425 * Returns a portion of this YXmlFragment into a JavaScript Array selected 8426 * from start to end (end not included). 8427 * 8428 * @param {number} [start] 8429 * @param {number} [end] 8430 * @return {Array<YXmlElement|YXmlText>} 8431 */ 8432 slice(start = 0, end = this.length) { 8433 return typeListSlice(this, start, end); 8434 } 8435 /** 8436 * Executes a provided function on once on every child element. 8437 * 8438 * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray. 8439 */ 8440 forEach(f) { 8441 typeListForEach(this, f); 8442 } 8443 /** 8444 * Transform the properties of this type to binary and write it to an 8445 * BinaryEncoder. 8446 * 8447 * This is called when this Item is sent to a remote peer. 8448 * 8449 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8450 */ 8451 _write(encoder) { 8452 encoder.writeTypeRef(YXmlFragmentRefID); 8453 } 8454 }; 8455 var readYXmlFragment = (_decoder) => new YXmlFragment(); 8456 var YXmlElement = class _YXmlElement extends YXmlFragment { 8457 constructor(nodeName = "UNDEFINED") { 8458 super(); 8459 this.nodeName = nodeName; 8460 this._prelimAttrs = /* @__PURE__ */ new Map(); 8461 } 8462 /** 8463 * @type {YXmlElement|YXmlText|null} 8464 */ 8465 get nextSibling() { 8466 const n = this._item ? this._item.next : null; 8467 return n ? ( 8468 /** @type {YXmlElement|YXmlText} */ 8469 /** @type {ContentType} */ 8470 n.content.type 8471 ) : null; 8472 } 8473 /** 8474 * @type {YXmlElement|YXmlText|null} 8475 */ 8476 get prevSibling() { 8477 const n = this._item ? this._item.prev : null; 8478 return n ? ( 8479 /** @type {YXmlElement|YXmlText} */ 8480 /** @type {ContentType} */ 8481 n.content.type 8482 ) : null; 8483 } 8484 /** 8485 * Integrate this type into the Yjs instance. 8486 * 8487 * * Save this struct in the os 8488 * * This type is sent to other client 8489 * * Observer functions are fired 8490 * 8491 * @param {Doc} y The Yjs instance 8492 * @param {Item} item 8493 */ 8494 _integrate(y, item) { 8495 super._integrate(y, item); 8496 /** @type {Map<string, any>} */ 8497 this._prelimAttrs.forEach((value, key) => { 8498 this.setAttribute(key, value); 8499 }); 8500 this._prelimAttrs = null; 8501 } 8502 /** 8503 * Creates an Item with the same effect as this Item (without position effect) 8504 * 8505 * @return {YXmlElement} 8506 */ 8507 _copy() { 8508 return new _YXmlElement(this.nodeName); 8509 } 8510 /** 8511 * Makes a copy of this data type that can be included somewhere else. 8512 * 8513 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8514 * 8515 * @return {YXmlElement<KV>} 8516 */ 8517 clone() { 8518 const el = new _YXmlElement(this.nodeName); 8519 const attrs = this.getAttributes(); 8520 forEach(attrs, (value, key) => { 8521 el.setAttribute( 8522 key, 8523 /** @type {any} */ 8524 value 8525 ); 8526 }); 8527 el.insert(0, this.toArray().map((v) => v instanceof AbstractType ? v.clone() : v)); 8528 return el; 8529 } 8530 /** 8531 * Returns the XML serialization of this YXmlElement. 8532 * The attributes are ordered by attribute-name, so you can easily use this 8533 * method to compare YXmlElements 8534 * 8535 * @return {string} The string representation of this type. 8536 * 8537 * @public 8538 */ 8539 toString() { 8540 const attrs = this.getAttributes(); 8541 const stringBuilder = []; 8542 const keys2 = []; 8543 for (const key in attrs) { 8544 keys2.push(key); 8545 } 8546 keys2.sort(); 8547 const keysLen = keys2.length; 8548 for (let i = 0; i < keysLen; i++) { 8549 const key = keys2[i]; 8550 stringBuilder.push(key + '="' + attrs[key] + '"'); 8551 } 8552 const nodeName = this.nodeName.toLocaleLowerCase(); 8553 const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : ""; 8554 return `<$nodeName}$attrsString}>$super.toString()}</$nodeName}>`; 8555 } 8556 /** 8557 * Removes an attribute from this YXmlElement. 8558 * 8559 * @param {string} attributeName The attribute name that is to be removed. 8560 * 8561 * @public 8562 */ 8563 removeAttribute(attributeName) { 8564 if (this.doc !== null) { 8565 transact(this.doc, (transaction) => { 8566 typeMapDelete(transaction, this, attributeName); 8567 }); 8568 } else { 8569 this._prelimAttrs.delete(attributeName); 8570 } 8571 } 8572 /** 8573 * Sets or updates an attribute. 8574 * 8575 * @template {keyof KV & string} KEY 8576 * 8577 * @param {KEY} attributeName The attribute name that is to be set. 8578 * @param {KV[KEY]} attributeValue The attribute value that is to be set. 8579 * 8580 * @public 8581 */ 8582 setAttribute(attributeName, attributeValue) { 8583 if (this.doc !== null) { 8584 transact(this.doc, (transaction) => { 8585 typeMapSet(transaction, this, attributeName, attributeValue); 8586 }); 8587 } else { 8588 this._prelimAttrs.set(attributeName, attributeValue); 8589 } 8590 } 8591 /** 8592 * Returns an attribute value that belongs to the attribute name. 8593 * 8594 * @template {keyof KV & string} KEY 8595 * 8596 * @param {KEY} attributeName The attribute name that identifies the 8597 * queried value. 8598 * @return {KV[KEY]|undefined} The queried attribute value. 8599 * 8600 * @public 8601 */ 8602 getAttribute(attributeName) { 8603 return ( 8604 /** @type {any} */ 8605 typeMapGet(this, attributeName) 8606 ); 8607 } 8608 /** 8609 * Returns whether an attribute exists 8610 * 8611 * @param {string} attributeName The attribute name to check for existence. 8612 * @return {boolean} whether the attribute exists. 8613 * 8614 * @public 8615 */ 8616 hasAttribute(attributeName) { 8617 return ( 8618 /** @type {any} */ 8619 typeMapHas(this, attributeName) 8620 ); 8621 } 8622 /** 8623 * Returns all attribute name/value pairs in a JSON Object. 8624 * 8625 * @param {Snapshot} [snapshot] 8626 * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes. 8627 * 8628 * @public 8629 */ 8630 getAttributes(snapshot2) { 8631 return ( 8632 /** @type {any} */ 8633 snapshot2 ? typeMapGetAllSnapshot(this, snapshot2) : typeMapGetAll(this) 8634 ); 8635 } 8636 /** 8637 * Creates a Dom Element that mirrors this YXmlElement. 8638 * 8639 * @param {Document} [_document=document] The document object (you must define 8640 * this when calling this method in 8641 * nodejs) 8642 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks 8643 * are presented in the DOM 8644 * @param {any} [binding] You should not set this property. This is 8645 * used if DomBinding wants to create a 8646 * association to the created DOM type. 8647 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8648 * 8649 * @public 8650 */ 8651 toDOM(_document = document, hooks = {}, binding) { 8652 const dom = _document.createElement(this.nodeName); 8653 const attrs = this.getAttributes(); 8654 for (const key in attrs) { 8655 const value = attrs[key]; 8656 if (typeof value === "string") { 8657 dom.setAttribute(key, value); 8658 } 8659 } 8660 typeListForEach(this, (yxml) => { 8661 dom.appendChild(yxml.toDOM(_document, hooks, binding)); 8662 }); 8663 if (binding !== void 0) { 8664 binding._createAssociation(dom, this); 8665 } 8666 return dom; 8667 } 8668 /** 8669 * Transform the properties of this type to binary and write it to an 8670 * BinaryEncoder. 8671 * 8672 * This is called when this Item is sent to a remote peer. 8673 * 8674 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8675 */ 8676 _write(encoder) { 8677 encoder.writeTypeRef(YXmlElementRefID); 8678 encoder.writeKey(this.nodeName); 8679 } 8680 }; 8681 var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey()); 8682 var YXmlEvent = class extends YEvent { 8683 /** 8684 * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created. 8685 * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the 8686 * child list changed. 8687 * @param {Transaction} transaction The transaction instance with which the 8688 * change was created. 8689 */ 8690 constructor(target, subs, transaction) { 8691 super(target, transaction); 8692 this.childListChanged = false; 8693 this.attributesChanged = /* @__PURE__ */ new Set(); 8694 subs.forEach((sub) => { 8695 if (sub === null) { 8696 this.childListChanged = true; 8697 } else { 8698 this.attributesChanged.add(sub); 8699 } 8700 }); 8701 } 8702 }; 8703 var YXmlHook = class _YXmlHook extends YMap { 8704 /** 8705 * @param {string} hookName nodeName of the Dom Node. 8706 */ 8707 constructor(hookName) { 8708 super(); 8709 this.hookName = hookName; 8710 } 8711 /** 8712 * Creates an Item with the same effect as this Item (without position effect) 8713 */ 8714 _copy() { 8715 return new _YXmlHook(this.hookName); 8716 } 8717 /** 8718 * Makes a copy of this data type that can be included somewhere else. 8719 * 8720 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8721 * 8722 * @return {YXmlHook} 8723 */ 8724 clone() { 8725 const el = new _YXmlHook(this.hookName); 8726 this.forEach((value, key) => { 8727 el.set(key, value); 8728 }); 8729 return el; 8730 } 8731 /** 8732 * Creates a Dom Element that mirrors this YXmlElement. 8733 * 8734 * @param {Document} [_document=document] The document object (you must define 8735 * this when calling this method in 8736 * nodejs) 8737 * @param {Object.<string, any>} [hooks] Optional property to customize how hooks 8738 * are presented in the DOM 8739 * @param {any} [binding] You should not set this property. This is 8740 * used if DomBinding wants to create a 8741 * association to the created DOM type 8742 * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8743 * 8744 * @public 8745 */ 8746 toDOM(_document = document, hooks = {}, binding) { 8747 const hook = hooks[this.hookName]; 8748 let dom; 8749 if (hook !== void 0) { 8750 dom = hook.createDom(this); 8751 } else { 8752 dom = document.createElement(this.hookName); 8753 } 8754 dom.setAttribute("data-yjs-hook", this.hookName); 8755 if (binding !== void 0) { 8756 binding._createAssociation(dom, this); 8757 } 8758 return dom; 8759 } 8760 /** 8761 * Transform the properties of this type to binary and write it to an 8762 * BinaryEncoder. 8763 * 8764 * This is called when this Item is sent to a remote peer. 8765 * 8766 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8767 */ 8768 _write(encoder) { 8769 encoder.writeTypeRef(YXmlHookRefID); 8770 encoder.writeKey(this.hookName); 8771 } 8772 }; 8773 var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey()); 8774 var YXmlText = class _YXmlText extends YText { 8775 /** 8776 * @type {YXmlElement|YXmlText|null} 8777 */ 8778 get nextSibling() { 8779 const n = this._item ? this._item.next : null; 8780 return n ? ( 8781 /** @type {YXmlElement|YXmlText} */ 8782 /** @type {ContentType} */ 8783 n.content.type 8784 ) : null; 8785 } 8786 /** 8787 * @type {YXmlElement|YXmlText|null} 8788 */ 8789 get prevSibling() { 8790 const n = this._item ? this._item.prev : null; 8791 return n ? ( 8792 /** @type {YXmlElement|YXmlText} */ 8793 /** @type {ContentType} */ 8794 n.content.type 8795 ) : null; 8796 } 8797 _copy() { 8798 return new _YXmlText(); 8799 } 8800 /** 8801 * Makes a copy of this data type that can be included somewhere else. 8802 * 8803 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8804 * 8805 * @return {YXmlText} 8806 */ 8807 clone() { 8808 const text2 = new _YXmlText(); 8809 text2.applyDelta(this.toDelta()); 8810 return text2; 8811 } 8812 /** 8813 * Creates a Dom Element that mirrors this YXmlText. 8814 * 8815 * @param {Document} [_document=document] The document object (you must define 8816 * this when calling this method in 8817 * nodejs) 8818 * @param {Object<string, any>} [hooks] Optional property to customize how hooks 8819 * are presented in the DOM 8820 * @param {any} [binding] You should not set this property. This is 8821 * used if DomBinding wants to create a 8822 * association to the created DOM type. 8823 * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8824 * 8825 * @public 8826 */ 8827 toDOM(_document = document, hooks, binding) { 8828 const dom = _document.createTextNode(this.toString()); 8829 if (binding !== void 0) { 8830 binding._createAssociation(dom, this); 8831 } 8832 return dom; 8833 } 8834 toString() { 8835 return this.toDelta().map((delta) => { 8836 const nestedNodes = []; 8837 for (const nodeName in delta.attributes) { 8838 const attrs = []; 8839 for (const key in delta.attributes[nodeName]) { 8840 attrs.push({ key, value: delta.attributes[nodeName][key] }); 8841 } 8842 attrs.sort((a, b) => a.key < b.key ? -1 : 1); 8843 nestedNodes.push({ nodeName, attrs }); 8844 } 8845 nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); 8846 let str = ""; 8847 for (let i = 0; i < nestedNodes.length; i++) { 8848 const node = nestedNodes[i]; 8849 str += `<$node.nodeName}`; 8850 for (let j = 0; j < node.attrs.length; j++) { 8851 const attr = node.attrs[j]; 8852 str += ` $attr.key}="$attr.value}"`; 8853 } 8854 str += ">"; 8855 } 8856 str += delta.insert; 8857 for (let i = nestedNodes.length - 1; i >= 0; i--) { 8858 str += `</$nestedNodes[i].nodeName}>`; 8859 } 8860 return str; 8861 }).join(""); 8862 } 8863 /** 8864 * @return {string} 8865 */ 8866 toJSON() { 8867 return this.toString(); 8868 } 8869 /** 8870 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8871 */ 8872 _write(encoder) { 8873 encoder.writeTypeRef(YXmlTextRefID); 8874 } 8875 }; 8876 var readYXmlText = (decoder) => new YXmlText(); 8877 var AbstractStruct = class { 8878 /** 8879 * @param {ID} id 8880 * @param {number} length 8881 */ 8882 constructor(id2, length2) { 8883 this.id = id2; 8884 this.length = length2; 8885 } 8886 /** 8887 * @type {boolean} 8888 */ 8889 get deleted() { 8890 throw methodUnimplemented(); 8891 } 8892 /** 8893 * Merge this struct with the item to the right. 8894 * This method is already assuming that `this.id.clock + this.length === this.id.clock`. 8895 * Also this method does *not* remove right from StructStore! 8896 * @param {AbstractStruct} right 8897 * @return {boolean} whether this merged with right 8898 */ 8899 mergeWith(right) { 8900 return false; 8901 } 8902 /** 8903 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8904 * @param {number} offset 8905 * @param {number} encodingRef 8906 */ 8907 write(encoder, offset, encodingRef) { 8908 throw methodUnimplemented(); 8909 } 8910 /** 8911 * @param {Transaction} transaction 8912 * @param {number} offset 8913 */ 8914 integrate(transaction, offset) { 8915 throw methodUnimplemented(); 8916 } 8917 }; 8918 var structGCRefNumber = 0; 8919 var GC = class extends AbstractStruct { 8920 get deleted() { 8921 return true; 8922 } 8923 delete() { 8924 } 8925 /** 8926 * @param {GC} right 8927 * @return {boolean} 8928 */ 8929 mergeWith(right) { 8930 if (this.constructor !== right.constructor) { 8931 return false; 8932 } 8933 this.length += right.length; 8934 return true; 8935 } 8936 /** 8937 * @param {Transaction} transaction 8938 * @param {number} offset 8939 */ 8940 integrate(transaction, offset) { 8941 if (offset > 0) { 8942 this.id.clock += offset; 8943 this.length -= offset; 8944 } 8945 addStruct(transaction.doc.store, this); 8946 } 8947 /** 8948 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8949 * @param {number} offset 8950 */ 8951 write(encoder, offset) { 8952 encoder.writeInfo(structGCRefNumber); 8953 encoder.writeLen(this.length - offset); 8954 } 8955 /** 8956 * @param {Transaction} transaction 8957 * @param {StructStore} store 8958 * @return {null | number} 8959 */ 8960 getMissing(transaction, store2) { 8961 return null; 8962 } 8963 }; 8964 var ContentBinary = class _ContentBinary { 8965 /** 8966 * @param {Uint8Array} content 8967 */ 8968 constructor(content) { 8969 this.content = content; 8970 } 8971 /** 8972 * @return {number} 8973 */ 8974 getLength() { 8975 return 1; 8976 } 8977 /** 8978 * @return {Array<any>} 8979 */ 8980 getContent() { 8981 return [this.content]; 8982 } 8983 /** 8984 * @return {boolean} 8985 */ 8986 isCountable() { 8987 return true; 8988 } 8989 /** 8990 * @return {ContentBinary} 8991 */ 8992 copy() { 8993 return new _ContentBinary(this.content); 8994 } 8995 /** 8996 * @param {number} offset 8997 * @return {ContentBinary} 8998 */ 8999 splice(offset) { 9000 throw methodUnimplemented(); 9001 } 9002 /** 9003 * @param {ContentBinary} right 9004 * @return {boolean} 9005 */ 9006 mergeWith(right) { 9007 return false; 9008 } 9009 /** 9010 * @param {Transaction} transaction 9011 * @param {Item} item 9012 */ 9013 integrate(transaction, item) { 9014 } 9015 /** 9016 * @param {Transaction} transaction 9017 */ 9018 delete(transaction) { 9019 } 9020 /** 9021 * @param {StructStore} store 9022 */ 9023 gc(store2) { 9024 } 9025 /** 9026 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9027 * @param {number} offset 9028 */ 9029 write(encoder, offset) { 9030 encoder.writeBuf(this.content); 9031 } 9032 /** 9033 * @return {number} 9034 */ 9035 getRef() { 9036 return 3; 9037 } 9038 }; 9039 var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf()); 9040 var ContentDeleted = class _ContentDeleted { 9041 /** 9042 * @param {number} len 9043 */ 9044 constructor(len) { 9045 this.len = len; 9046 } 9047 /** 9048 * @return {number} 9049 */ 9050 getLength() { 9051 return this.len; 9052 } 9053 /** 9054 * @return {Array<any>} 9055 */ 9056 getContent() { 9057 return []; 9058 } 9059 /** 9060 * @return {boolean} 9061 */ 9062 isCountable() { 9063 return false; 9064 } 9065 /** 9066 * @return {ContentDeleted} 9067 */ 9068 copy() { 9069 return new _ContentDeleted(this.len); 9070 } 9071 /** 9072 * @param {number} offset 9073 * @return {ContentDeleted} 9074 */ 9075 splice(offset) { 9076 const right = new _ContentDeleted(this.len - offset); 9077 this.len = offset; 9078 return right; 9079 } 9080 /** 9081 * @param {ContentDeleted} right 9082 * @return {boolean} 9083 */ 9084 mergeWith(right) { 9085 this.len += right.len; 9086 return true; 9087 } 9088 /** 9089 * @param {Transaction} transaction 9090 * @param {Item} item 9091 */ 9092 integrate(transaction, item) { 9093 addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); 9094 item.markDeleted(); 9095 } 9096 /** 9097 * @param {Transaction} transaction 9098 */ 9099 delete(transaction) { 9100 } 9101 /** 9102 * @param {StructStore} store 9103 */ 9104 gc(store2) { 9105 } 9106 /** 9107 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9108 * @param {number} offset 9109 */ 9110 write(encoder, offset) { 9111 encoder.writeLen(this.len - offset); 9112 } 9113 /** 9114 * @return {number} 9115 */ 9116 getRef() { 9117 return 1; 9118 } 9119 }; 9120 var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen()); 9121 var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false }); 9122 var ContentDoc = class _ContentDoc { 9123 /** 9124 * @param {Doc} doc 9125 */ 9126 constructor(doc2) { 9127 if (doc2._item) { 9128 console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."); 9129 } 9130 this.doc = doc2; 9131 const opts = {}; 9132 this.opts = opts; 9133 if (!doc2.gc) { 9134 opts.gc = false; 9135 } 9136 if (doc2.autoLoad) { 9137 opts.autoLoad = true; 9138 } 9139 if (doc2.meta !== null) { 9140 opts.meta = doc2.meta; 9141 } 9142 } 9143 /** 9144 * @return {number} 9145 */ 9146 getLength() { 9147 return 1; 9148 } 9149 /** 9150 * @return {Array<any>} 9151 */ 9152 getContent() { 9153 return [this.doc]; 9154 } 9155 /** 9156 * @return {boolean} 9157 */ 9158 isCountable() { 9159 return true; 9160 } 9161 /** 9162 * @return {ContentDoc} 9163 */ 9164 copy() { 9165 return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts)); 9166 } 9167 /** 9168 * @param {number} offset 9169 * @return {ContentDoc} 9170 */ 9171 splice(offset) { 9172 throw methodUnimplemented(); 9173 } 9174 /** 9175 * @param {ContentDoc} right 9176 * @return {boolean} 9177 */ 9178 mergeWith(right) { 9179 return false; 9180 } 9181 /** 9182 * @param {Transaction} transaction 9183 * @param {Item} item 9184 */ 9185 integrate(transaction, item) { 9186 this.doc._item = item; 9187 transaction.subdocsAdded.add(this.doc); 9188 if (this.doc.shouldLoad) { 9189 transaction.subdocsLoaded.add(this.doc); 9190 } 9191 } 9192 /** 9193 * @param {Transaction} transaction 9194 */ 9195 delete(transaction) { 9196 if (transaction.subdocsAdded.has(this.doc)) { 9197 transaction.subdocsAdded.delete(this.doc); 9198 } else { 9199 transaction.subdocsRemoved.add(this.doc); 9200 } 9201 } 9202 /** 9203 * @param {StructStore} store 9204 */ 9205 gc(store2) { 9206 } 9207 /** 9208 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9209 * @param {number} offset 9210 */ 9211 write(encoder, offset) { 9212 encoder.writeString(this.doc.guid); 9213 encoder.writeAny(this.opts); 9214 } 9215 /** 9216 * @return {number} 9217 */ 9218 getRef() { 9219 return 9; 9220 } 9221 }; 9222 var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny())); 9223 var ContentEmbed = class _ContentEmbed { 9224 /** 9225 * @param {Object} embed 9226 */ 9227 constructor(embed) { 9228 this.embed = embed; 9229 } 9230 /** 9231 * @return {number} 9232 */ 9233 getLength() { 9234 return 1; 9235 } 9236 /** 9237 * @return {Array<any>} 9238 */ 9239 getContent() { 9240 return [this.embed]; 9241 } 9242 /** 9243 * @return {boolean} 9244 */ 9245 isCountable() { 9246 return true; 9247 } 9248 /** 9249 * @return {ContentEmbed} 9250 */ 9251 copy() { 9252 return new _ContentEmbed(this.embed); 9253 } 9254 /** 9255 * @param {number} offset 9256 * @return {ContentEmbed} 9257 */ 9258 splice(offset) { 9259 throw methodUnimplemented(); 9260 } 9261 /** 9262 * @param {ContentEmbed} right 9263 * @return {boolean} 9264 */ 9265 mergeWith(right) { 9266 return false; 9267 } 9268 /** 9269 * @param {Transaction} transaction 9270 * @param {Item} item 9271 */ 9272 integrate(transaction, item) { 9273 } 9274 /** 9275 * @param {Transaction} transaction 9276 */ 9277 delete(transaction) { 9278 } 9279 /** 9280 * @param {StructStore} store 9281 */ 9282 gc(store2) { 9283 } 9284 /** 9285 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9286 * @param {number} offset 9287 */ 9288 write(encoder, offset) { 9289 encoder.writeJSON(this.embed); 9290 } 9291 /** 9292 * @return {number} 9293 */ 9294 getRef() { 9295 return 5; 9296 } 9297 }; 9298 var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON()); 9299 var ContentFormat = class _ContentFormat { 9300 /** 9301 * @param {string} key 9302 * @param {Object} value 9303 */ 9304 constructor(key, value) { 9305 this.key = key; 9306 this.value = value; 9307 } 9308 /** 9309 * @return {number} 9310 */ 9311 getLength() { 9312 return 1; 9313 } 9314 /** 9315 * @return {Array<any>} 9316 */ 9317 getContent() { 9318 return []; 9319 } 9320 /** 9321 * @return {boolean} 9322 */ 9323 isCountable() { 9324 return false; 9325 } 9326 /** 9327 * @return {ContentFormat} 9328 */ 9329 copy() { 9330 return new _ContentFormat(this.key, this.value); 9331 } 9332 /** 9333 * @param {number} _offset 9334 * @return {ContentFormat} 9335 */ 9336 splice(_offset) { 9337 throw methodUnimplemented(); 9338 } 9339 /** 9340 * @param {ContentFormat} _right 9341 * @return {boolean} 9342 */ 9343 mergeWith(_right) { 9344 return false; 9345 } 9346 /** 9347 * @param {Transaction} _transaction 9348 * @param {Item} item 9349 */ 9350 integrate(_transaction, item) { 9351 const p = ( 9352 /** @type {YText} */ 9353 item.parent 9354 ); 9355 p._searchMarker = null; 9356 p._hasFormatting = true; 9357 } 9358 /** 9359 * @param {Transaction} transaction 9360 */ 9361 delete(transaction) { 9362 } 9363 /** 9364 * @param {StructStore} store 9365 */ 9366 gc(store2) { 9367 } 9368 /** 9369 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9370 * @param {number} offset 9371 */ 9372 write(encoder, offset) { 9373 encoder.writeKey(this.key); 9374 encoder.writeJSON(this.value); 9375 } 9376 /** 9377 * @return {number} 9378 */ 9379 getRef() { 9380 return 6; 9381 } 9382 }; 9383 var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON()); 9384 var ContentJSON = class _ContentJSON { 9385 /** 9386 * @param {Array<any>} arr 9387 */ 9388 constructor(arr) { 9389 this.arr = arr; 9390 } 9391 /** 9392 * @return {number} 9393 */ 9394 getLength() { 9395 return this.arr.length; 9396 } 9397 /** 9398 * @return {Array<any>} 9399 */ 9400 getContent() { 9401 return this.arr; 9402 } 9403 /** 9404 * @return {boolean} 9405 */ 9406 isCountable() { 9407 return true; 9408 } 9409 /** 9410 * @return {ContentJSON} 9411 */ 9412 copy() { 9413 return new _ContentJSON(this.arr); 9414 } 9415 /** 9416 * @param {number} offset 9417 * @return {ContentJSON} 9418 */ 9419 splice(offset) { 9420 const right = new _ContentJSON(this.arr.slice(offset)); 9421 this.arr = this.arr.slice(0, offset); 9422 return right; 9423 } 9424 /** 9425 * @param {ContentJSON} right 9426 * @return {boolean} 9427 */ 9428 mergeWith(right) { 9429 this.arr = this.arr.concat(right.arr); 9430 return true; 9431 } 9432 /** 9433 * @param {Transaction} transaction 9434 * @param {Item} item 9435 */ 9436 integrate(transaction, item) { 9437 } 9438 /** 9439 * @param {Transaction} transaction 9440 */ 9441 delete(transaction) { 9442 } 9443 /** 9444 * @param {StructStore} store 9445 */ 9446 gc(store2) { 9447 } 9448 /** 9449 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9450 * @param {number} offset 9451 */ 9452 write(encoder, offset) { 9453 const len = this.arr.length; 9454 encoder.writeLen(len - offset); 9455 for (let i = offset; i < len; i++) { 9456 const c = this.arr[i]; 9457 encoder.writeString(c === void 0 ? "undefined" : JSON.stringify(c)); 9458 } 9459 } 9460 /** 9461 * @return {number} 9462 */ 9463 getRef() { 9464 return 2; 9465 } 9466 }; 9467 var readContentJSON = (decoder) => { 9468 const len = decoder.readLen(); 9469 const cs = []; 9470 for (let i = 0; i < len; i++) { 9471 const c = decoder.readString(); 9472 if (c === "undefined") { 9473 cs.push(void 0); 9474 } else { 9475 cs.push(JSON.parse(c)); 9476 } 9477 } 9478 return new ContentJSON(cs); 9479 }; 9480 var isDevMode = getVariable("node_env") === "development"; 9481 var ContentAny = class _ContentAny { 9482 /** 9483 * @param {Array<any>} arr 9484 */ 9485 constructor(arr) { 9486 this.arr = arr; 9487 isDevMode && deepFreeze(arr); 9488 } 9489 /** 9490 * @return {number} 9491 */ 9492 getLength() { 9493 return this.arr.length; 9494 } 9495 /** 9496 * @return {Array<any>} 9497 */ 9498 getContent() { 9499 return this.arr; 9500 } 9501 /** 9502 * @return {boolean} 9503 */ 9504 isCountable() { 9505 return true; 9506 } 9507 /** 9508 * @return {ContentAny} 9509 */ 9510 copy() { 9511 return new _ContentAny(this.arr); 9512 } 9513 /** 9514 * @param {number} offset 9515 * @return {ContentAny} 9516 */ 9517 splice(offset) { 9518 const right = new _ContentAny(this.arr.slice(offset)); 9519 this.arr = this.arr.slice(0, offset); 9520 return right; 9521 } 9522 /** 9523 * @param {ContentAny} right 9524 * @return {boolean} 9525 */ 9526 mergeWith(right) { 9527 this.arr = this.arr.concat(right.arr); 9528 return true; 9529 } 9530 /** 9531 * @param {Transaction} transaction 9532 * @param {Item} item 9533 */ 9534 integrate(transaction, item) { 9535 } 9536 /** 9537 * @param {Transaction} transaction 9538 */ 9539 delete(transaction) { 9540 } 9541 /** 9542 * @param {StructStore} store 9543 */ 9544 gc(store2) { 9545 } 9546 /** 9547 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9548 * @param {number} offset 9549 */ 9550 write(encoder, offset) { 9551 const len = this.arr.length; 9552 encoder.writeLen(len - offset); 9553 for (let i = offset; i < len; i++) { 9554 const c = this.arr[i]; 9555 encoder.writeAny(c); 9556 } 9557 } 9558 /** 9559 * @return {number} 9560 */ 9561 getRef() { 9562 return 8; 9563 } 9564 }; 9565 var readContentAny = (decoder) => { 9566 const len = decoder.readLen(); 9567 const cs = []; 9568 for (let i = 0; i < len; i++) { 9569 cs.push(decoder.readAny()); 9570 } 9571 return new ContentAny(cs); 9572 }; 9573 var ContentString = class _ContentString { 9574 /** 9575 * @param {string} str 9576 */ 9577 constructor(str) { 9578 this.str = str; 9579 } 9580 /** 9581 * @return {number} 9582 */ 9583 getLength() { 9584 return this.str.length; 9585 } 9586 /** 9587 * @return {Array<any>} 9588 */ 9589 getContent() { 9590 return this.str.split(""); 9591 } 9592 /** 9593 * @return {boolean} 9594 */ 9595 isCountable() { 9596 return true; 9597 } 9598 /** 9599 * @return {ContentString} 9600 */ 9601 copy() { 9602 return new _ContentString(this.str); 9603 } 9604 /** 9605 * @param {number} offset 9606 * @return {ContentString} 9607 */ 9608 splice(offset) { 9609 const right = new _ContentString(this.str.slice(offset)); 9610 this.str = this.str.slice(0, offset); 9611 const firstCharCode = this.str.charCodeAt(offset - 1); 9612 if (firstCharCode >= 55296 && firstCharCode <= 56319) { 9613 this.str = this.str.slice(0, offset - 1) + "\uFFFD"; 9614 right.str = "\uFFFD" + right.str.slice(1); 9615 } 9616 return right; 9617 } 9618 /** 9619 * @param {ContentString} right 9620 * @return {boolean} 9621 */ 9622 mergeWith(right) { 9623 this.str += right.str; 9624 return true; 9625 } 9626 /** 9627 * @param {Transaction} transaction 9628 * @param {Item} item 9629 */ 9630 integrate(transaction, item) { 9631 } 9632 /** 9633 * @param {Transaction} transaction 9634 */ 9635 delete(transaction) { 9636 } 9637 /** 9638 * @param {StructStore} store 9639 */ 9640 gc(store2) { 9641 } 9642 /** 9643 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9644 * @param {number} offset 9645 */ 9646 write(encoder, offset) { 9647 encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); 9648 } 9649 /** 9650 * @return {number} 9651 */ 9652 getRef() { 9653 return 4; 9654 } 9655 }; 9656 var readContentString = (decoder) => new ContentString(decoder.readString()); 9657 var typeRefs = [ 9658 readYArray, 9659 readYMap, 9660 readYText, 9661 readYXmlElement, 9662 readYXmlFragment, 9663 readYXmlHook, 9664 readYXmlText 9665 ]; 9666 var YArrayRefID = 0; 9667 var YMapRefID = 1; 9668 var YTextRefID = 2; 9669 var YXmlElementRefID = 3; 9670 var YXmlFragmentRefID = 4; 9671 var YXmlHookRefID = 5; 9672 var YXmlTextRefID = 6; 9673 var ContentType = class _ContentType { 9674 /** 9675 * @param {AbstractType<any>} type 9676 */ 9677 constructor(type) { 9678 this.type = type; 9679 } 9680 /** 9681 * @return {number} 9682 */ 9683 getLength() { 9684 return 1; 9685 } 9686 /** 9687 * @return {Array<any>} 9688 */ 9689 getContent() { 9690 return [this.type]; 9691 } 9692 /** 9693 * @return {boolean} 9694 */ 9695 isCountable() { 9696 return true; 9697 } 9698 /** 9699 * @return {ContentType} 9700 */ 9701 copy() { 9702 return new _ContentType(this.type._copy()); 9703 } 9704 /** 9705 * @param {number} offset 9706 * @return {ContentType} 9707 */ 9708 splice(offset) { 9709 throw methodUnimplemented(); 9710 } 9711 /** 9712 * @param {ContentType} right 9713 * @return {boolean} 9714 */ 9715 mergeWith(right) { 9716 return false; 9717 } 9718 /** 9719 * @param {Transaction} transaction 9720 * @param {Item} item 9721 */ 9722 integrate(transaction, item) { 9723 this.type._integrate(transaction.doc, item); 9724 } 9725 /** 9726 * @param {Transaction} transaction 9727 */ 9728 delete(transaction) { 9729 let item = this.type._start; 9730 while (item !== null) { 9731 if (!item.deleted) { 9732 item.delete(transaction); 9733 } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) { 9734 transaction._mergeStructs.push(item); 9735 } 9736 item = item.right; 9737 } 9738 this.type._map.forEach((item2) => { 9739 if (!item2.deleted) { 9740 item2.delete(transaction); 9741 } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) { 9742 transaction._mergeStructs.push(item2); 9743 } 9744 }); 9745 transaction.changed.delete(this.type); 9746 } 9747 /** 9748 * @param {StructStore} store 9749 */ 9750 gc(store2) { 9751 let item = this.type._start; 9752 while (item !== null) { 9753 item.gc(store2, true); 9754 item = item.right; 9755 } 9756 this.type._start = null; 9757 this.type._map.forEach( 9758 /** @param {Item | null} item */ 9759 (item2) => { 9760 while (item2 !== null) { 9761 item2.gc(store2, true); 9762 item2 = item2.left; 9763 } 9764 } 9765 ); 9766 this.type._map = /* @__PURE__ */ new Map(); 9767 } 9768 /** 9769 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9770 * @param {number} offset 9771 */ 9772 write(encoder, offset) { 9773 this.type._write(encoder); 9774 } 9775 /** 9776 * @return {number} 9777 */ 9778 getRef() { 9779 return 7; 9780 } 9781 }; 9782 var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); 9783 var followRedone = (store2, id2) => { 9784 let nextID = id2; 9785 let diff = 0; 9786 let item; 9787 do { 9788 if (diff > 0) { 9789 nextID = createID(nextID.client, nextID.clock + diff); 9790 } 9791 item = getItem(store2, nextID); 9792 diff = nextID.clock - item.id.clock; 9793 nextID = item.redone; 9794 } while (nextID !== null && item instanceof Item); 9795 return { 9796 item, 9797 diff 9798 }; 9799 }; 9800 var keepItem = (item, keep) => { 9801 while (item !== null && item.keep !== keep) { 9802 item.keep = keep; 9803 item = /** @type {AbstractType<any>} */ 9804 item.parent._item; 9805 } 9806 }; 9807 var splitItem = (transaction, leftItem, diff) => { 9808 const { client, clock } = leftItem.id; 9809 const rightItem = new Item( 9810 createID(client, clock + diff), 9811 leftItem, 9812 createID(client, clock + diff - 1), 9813 leftItem.right, 9814 leftItem.rightOrigin, 9815 leftItem.parent, 9816 leftItem.parentSub, 9817 leftItem.content.splice(diff) 9818 ); 9819 if (leftItem.deleted) { 9820 rightItem.markDeleted(); 9821 } 9822 if (leftItem.keep) { 9823 rightItem.keep = true; 9824 } 9825 if (leftItem.redone !== null) { 9826 rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); 9827 } 9828 leftItem.right = rightItem; 9829 if (rightItem.right !== null) { 9830 rightItem.right.left = rightItem; 9831 } 9832 transaction._mergeStructs.push(rightItem); 9833 if (rightItem.parentSub !== null && rightItem.right === null) { 9834 rightItem.parent._map.set(rightItem.parentSub, rightItem); 9835 } 9836 leftItem.length = diff; 9837 return rightItem; 9838 }; 9839 var isDeletedByUndoStack = (stack, id2) => some( 9840 stack, 9841 /** @param {StackItem} s */ 9842 (s) => isDeleted(s.deletions, id2) 9843 ); 9844 var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => { 9845 const doc2 = transaction.doc; 9846 const store2 = doc2.store; 9847 const ownClientID = doc2.clientID; 9848 const redone = item.redone; 9849 if (redone !== null) { 9850 return getItemCleanStart(transaction, redone); 9851 } 9852 let parentItem = ( 9853 /** @type {AbstractType<any>} */ 9854 item.parent._item 9855 ); 9856 let left = null; 9857 let right; 9858 if (parentItem !== null && parentItem.deleted === true) { 9859 if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) { 9860 return null; 9861 } 9862 while (parentItem.redone !== null) { 9863 parentItem = getItemCleanStart(transaction, parentItem.redone); 9864 } 9865 } 9866 const parentType = parentItem === null ? ( 9867 /** @type {AbstractType<any>} */ 9868 item.parent 9869 ) : ( 9870 /** @type {ContentType} */ 9871 parentItem.content.type 9872 ); 9873 if (item.parentSub === null) { 9874 left = item.left; 9875 right = item; 9876 while (left !== null) { 9877 let leftTrace = left; 9878 while (leftTrace !== null && /** @type {AbstractType<any>} */ 9879 leftTrace.parent._item !== parentItem) { 9880 leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); 9881 } 9882 if (leftTrace !== null && /** @type {AbstractType<any>} */ 9883 leftTrace.parent._item === parentItem) { 9884 left = leftTrace; 9885 break; 9886 } 9887 left = left.left; 9888 } 9889 while (right !== null) { 9890 let rightTrace = right; 9891 while (rightTrace !== null && /** @type {AbstractType<any>} */ 9892 rightTrace.parent._item !== parentItem) { 9893 rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); 9894 } 9895 if (rightTrace !== null && /** @type {AbstractType<any>} */ 9896 rightTrace.parent._item === parentItem) { 9897 right = rightTrace; 9898 break; 9899 } 9900 right = right.right; 9901 } 9902 } else { 9903 right = null; 9904 if (item.right && !ignoreRemoteMapChanges) { 9905 left = item; 9906 while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) { 9907 left = left.right; 9908 while (left.redone) left = getItemCleanStart(transaction, left.redone); 9909 } 9910 if (left && left.right !== null) { 9911 return null; 9912 } 9913 } else { 9914 left = parentType._map.get(item.parentSub) || null; 9915 } 9916 } 9917 const nextClock = getState(store2, ownClientID); 9918 const nextId = createID(ownClientID, nextClock); 9919 const redoneItem = new Item( 9920 nextId, 9921 left, 9922 left && left.lastId, 9923 right, 9924 right && right.id, 9925 parentType, 9926 item.parentSub, 9927 item.content.copy() 9928 ); 9929 item.redone = nextId; 9930 keepItem(redoneItem, true); 9931 redoneItem.integrate(transaction, 0); 9932 return redoneItem; 9933 }; 9934 var Item = class _Item extends AbstractStruct { 9935 /** 9936 * @param {ID} id 9937 * @param {Item | null} left 9938 * @param {ID | null} origin 9939 * @param {Item | null} right 9940 * @param {ID | null} rightOrigin 9941 * @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it. 9942 * @param {string | null} parentSub 9943 * @param {AbstractContent} content 9944 */ 9945 constructor(id2, left, origin2, right, rightOrigin, parent, parentSub, content) { 9946 super(id2, content.getLength()); 9947 this.origin = origin2; 9948 this.left = left; 9949 this.right = right; 9950 this.rightOrigin = rightOrigin; 9951 this.parent = parent; 9952 this.parentSub = parentSub; 9953 this.redone = null; 9954 this.content = content; 9955 this.info = this.content.isCountable() ? BIT2 : 0; 9956 } 9957 /** 9958 * This is used to mark the item as an indexed fast-search marker 9959 * 9960 * @type {boolean} 9961 */ 9962 set marker(isMarked) { 9963 if ((this.info & BIT4) > 0 !== isMarked) { 9964 this.info ^= BIT4; 9965 } 9966 } 9967 get marker() { 9968 return (this.info & BIT4) > 0; 9969 } 9970 /** 9971 * If true, do not garbage collect this Item. 9972 */ 9973 get keep() { 9974 return (this.info & BIT1) > 0; 9975 } 9976 set keep(doKeep) { 9977 if (this.keep !== doKeep) { 9978 this.info ^= BIT1; 9979 } 9980 } 9981 get countable() { 9982 return (this.info & BIT2) > 0; 9983 } 9984 /** 9985 * Whether this item was deleted or not. 9986 * @type {Boolean} 9987 */ 9988 get deleted() { 9989 return (this.info & BIT3) > 0; 9990 } 9991 set deleted(doDelete) { 9992 if (this.deleted !== doDelete) { 9993 this.info ^= BIT3; 9994 } 9995 } 9996 markDeleted() { 9997 this.info |= BIT3; 9998 } 9999 /** 10000 * Return the creator clientID of the missing op or define missing items and return null. 10001 * 10002 * @param {Transaction} transaction 10003 * @param {StructStore} store 10004 * @return {null | number} 10005 */ 10006 getMissing(transaction, store2) { 10007 if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store2, this.origin.client)) { 10008 return this.origin.client; 10009 } 10010 if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store2, this.rightOrigin.client)) { 10011 return this.rightOrigin.client; 10012 } 10013 if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store2, this.parent.client)) { 10014 return this.parent.client; 10015 } 10016 if (this.origin) { 10017 this.left = getItemCleanEnd(transaction, store2, this.origin); 10018 this.origin = this.left.lastId; 10019 } 10020 if (this.rightOrigin) { 10021 this.right = getItemCleanStart(transaction, this.rightOrigin); 10022 this.rightOrigin = this.right.id; 10023 } 10024 if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) { 10025 this.parent = null; 10026 } else if (!this.parent) { 10027 if (this.left && this.left.constructor === _Item) { 10028 this.parent = this.left.parent; 10029 this.parentSub = this.left.parentSub; 10030 } else if (this.right && this.right.constructor === _Item) { 10031 this.parent = this.right.parent; 10032 this.parentSub = this.right.parentSub; 10033 } 10034 } else if (this.parent.constructor === ID) { 10035 const parentItem = getItem(store2, this.parent); 10036 if (parentItem.constructor === GC) { 10037 this.parent = null; 10038 } else { 10039 this.parent = /** @type {ContentType} */ 10040 parentItem.content.type; 10041 } 10042 } 10043 return null; 10044 } 10045 /** 10046 * @param {Transaction} transaction 10047 * @param {number} offset 10048 */ 10049 integrate(transaction, offset) { 10050 if (offset > 0) { 10051 this.id.clock += offset; 10052 this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); 10053 this.origin = this.left.lastId; 10054 this.content = this.content.splice(offset); 10055 this.length -= offset; 10056 } 10057 if (this.parent) { 10058 if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) { 10059 let left = this.left; 10060 let o; 10061 if (left !== null) { 10062 o = left.right; 10063 } else if (this.parentSub !== null) { 10064 o = /** @type {AbstractType<any>} */ 10065 this.parent._map.get(this.parentSub) || null; 10066 while (o !== null && o.left !== null) { 10067 o = o.left; 10068 } 10069 } else { 10070 o = /** @type {AbstractType<any>} */ 10071 this.parent._start; 10072 } 10073 const conflictingItems = /* @__PURE__ */ new Set(); 10074 const itemsBeforeOrigin = /* @__PURE__ */ new Set(); 10075 while (o !== null && o !== this.right) { 10076 itemsBeforeOrigin.add(o); 10077 conflictingItems.add(o); 10078 if (compareIDs(this.origin, o.origin)) { 10079 if (o.id.client < this.id.client) { 10080 left = o; 10081 conflictingItems.clear(); 10082 } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { 10083 break; 10084 } 10085 } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { 10086 if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { 10087 left = o; 10088 conflictingItems.clear(); 10089 } 10090 } else { 10091 break; 10092 } 10093 o = o.right; 10094 } 10095 this.left = left; 10096 } 10097 if (this.left !== null) { 10098 const right = this.left.right; 10099 this.right = right; 10100 this.left.right = this; 10101 } else { 10102 let r2; 10103 if (this.parentSub !== null) { 10104 r2 = /** @type {AbstractType<any>} */ 10105 this.parent._map.get(this.parentSub) || null; 10106 while (r2 !== null && r2.left !== null) { 10107 r2 = r2.left; 10108 } 10109 } else { 10110 r2 = /** @type {AbstractType<any>} */ 10111 this.parent._start; 10112 this.parent._start = this; 10113 } 10114 this.right = r2; 10115 } 10116 if (this.right !== null) { 10117 this.right.left = this; 10118 } else if (this.parentSub !== null) { 10119 this.parent._map.set(this.parentSub, this); 10120 if (this.left !== null) { 10121 this.left.delete(transaction); 10122 } 10123 } 10124 if (this.parentSub === null && this.countable && !this.deleted) { 10125 this.parent._length += this.length; 10126 } 10127 addStruct(transaction.doc.store, this); 10128 this.content.integrate(transaction, this); 10129 addChangedTypeToTransaction( 10130 transaction, 10131 /** @type {AbstractType<any>} */ 10132 this.parent, 10133 this.parentSub 10134 ); 10135 if ( 10136 /** @type {AbstractType<any>} */ 10137 this.parent._item !== null && /** @type {AbstractType<any>} */ 10138 this.parent._item.deleted || this.parentSub !== null && this.right !== null 10139 ) { 10140 this.delete(transaction); 10141 } 10142 } else { 10143 new GC(this.id, this.length).integrate(transaction, 0); 10144 } 10145 } 10146 /** 10147 * Returns the next non-deleted item 10148 */ 10149 get next() { 10150 let n = this.right; 10151 while (n !== null && n.deleted) { 10152 n = n.right; 10153 } 10154 return n; 10155 } 10156 /** 10157 * Returns the previous non-deleted item 10158 */ 10159 get prev() { 10160 let n = this.left; 10161 while (n !== null && n.deleted) { 10162 n = n.left; 10163 } 10164 return n; 10165 } 10166 /** 10167 * Computes the last content address of this Item. 10168 */ 10169 get lastId() { 10170 return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1); 10171 } 10172 /** 10173 * Try to merge two items 10174 * 10175 * @param {Item} right 10176 * @return {boolean} 10177 */ 10178 mergeWith(right) { 10179 if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) { 10180 const searchMarker = ( 10181 /** @type {AbstractType<any>} */ 10182 this.parent._searchMarker 10183 ); 10184 if (searchMarker) { 10185 searchMarker.forEach((marker) => { 10186 if (marker.p === right) { 10187 marker.p = this; 10188 if (!this.deleted && this.countable) { 10189 marker.index -= this.length; 10190 } 10191 } 10192 }); 10193 } 10194 if (right.keep) { 10195 this.keep = true; 10196 } 10197 this.right = right.right; 10198 if (this.right !== null) { 10199 this.right.left = this; 10200 } 10201 this.length += right.length; 10202 return true; 10203 } 10204 return false; 10205 } 10206 /** 10207 * Mark this Item as deleted. 10208 * 10209 * @param {Transaction} transaction 10210 */ 10211 delete(transaction) { 10212 if (!this.deleted) { 10213 const parent = ( 10214 /** @type {AbstractType<any>} */ 10215 this.parent 10216 ); 10217 if (this.countable && this.parentSub === null) { 10218 parent._length -= this.length; 10219 } 10220 this.markDeleted(); 10221 addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); 10222 addChangedTypeToTransaction(transaction, parent, this.parentSub); 10223 this.content.delete(transaction); 10224 } 10225 } 10226 /** 10227 * @param {StructStore} store 10228 * @param {boolean} parentGCd 10229 */ 10230 gc(store2, parentGCd) { 10231 if (!this.deleted) { 10232 throw unexpectedCase(); 10233 } 10234 this.content.gc(store2); 10235 if (parentGCd) { 10236 replaceStruct(store2, this, new GC(this.id, this.length)); 10237 } else { 10238 this.content = new ContentDeleted(this.length); 10239 } 10240 } 10241 /** 10242 * Transform the properties of this type to binary and write it to an 10243 * BinaryEncoder. 10244 * 10245 * This is called when this Item is sent to a remote peer. 10246 * 10247 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 10248 * @param {number} offset 10249 */ 10250 write(encoder, offset) { 10251 const origin2 = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; 10252 const rightOrigin = this.rightOrigin; 10253 const parentSub = this.parentSub; 10254 const info = this.content.getRef() & BITS5 | (origin2 === null ? 0 : BIT8) | // origin is defined 10255 (rightOrigin === null ? 0 : BIT7) | // right origin is defined 10256 (parentSub === null ? 0 : BIT6); 10257 encoder.writeInfo(info); 10258 if (origin2 !== null) { 10259 encoder.writeLeftID(origin2); 10260 } 10261 if (rightOrigin !== null) { 10262 encoder.writeRightID(rightOrigin); 10263 } 10264 if (origin2 === null && rightOrigin === null) { 10265 const parent = ( 10266 /** @type {AbstractType<any>} */ 10267 this.parent 10268 ); 10269 if (parent._item !== void 0) { 10270 const parentItem = parent._item; 10271 if (parentItem === null) { 10272 const ykey = findRootTypeKey(parent); 10273 encoder.writeParentInfo(true); 10274 encoder.writeString(ykey); 10275 } else { 10276 encoder.writeParentInfo(false); 10277 encoder.writeLeftID(parentItem.id); 10278 } 10279 } else if (parent.constructor === String) { 10280 encoder.writeParentInfo(true); 10281 encoder.writeString(parent); 10282 } else if (parent.constructor === ID) { 10283 encoder.writeParentInfo(false); 10284 encoder.writeLeftID(parent); 10285 } else { 10286 unexpectedCase(); 10287 } 10288 if (parentSub !== null) { 10289 encoder.writeString(parentSub); 10290 } 10291 } 10292 this.content.write(encoder, offset); 10293 } 10294 }; 10295 var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); 10296 var contentRefs = [ 10297 () => { 10298 unexpectedCase(); 10299 }, 10300 // GC is not ItemContent 10301 readContentDeleted, 10302 // 1 10303 readContentJSON, 10304 // 2 10305 readContentBinary, 10306 // 3 10307 readContentString, 10308 // 4 10309 readContentEmbed, 10310 // 5 10311 readContentFormat, 10312 // 6 10313 readContentType, 10314 // 7 10315 readContentAny, 10316 // 8 10317 readContentDoc, 10318 // 9 10319 () => { 10320 unexpectedCase(); 10321 } 10322 // 10 - Skip is not ItemContent 10323 ]; 10324 var structSkipRefNumber = 10; 10325 var Skip = class extends AbstractStruct { 10326 get deleted() { 10327 return true; 10328 } 10329 delete() { 10330 } 10331 /** 10332 * @param {Skip} right 10333 * @return {boolean} 10334 */ 10335 mergeWith(right) { 10336 if (this.constructor !== right.constructor) { 10337 return false; 10338 } 10339 this.length += right.length; 10340 return true; 10341 } 10342 /** 10343 * @param {Transaction} transaction 10344 * @param {number} offset 10345 */ 10346 integrate(transaction, offset) { 10347 unexpectedCase(); 10348 } 10349 /** 10350 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 10351 * @param {number} offset 10352 */ 10353 write(encoder, offset) { 10354 encoder.writeInfo(structSkipRefNumber); 10355 writeVarUint(encoder.restEncoder, this.length - offset); 10356 } 10357 /** 10358 * @param {Transaction} transaction 10359 * @param {StructStore} store 10360 * @return {null | number} 10361 */ 10362 getMissing(transaction, store2) { 10363 return null; 10364 } 10365 }; 10366 var glo = ( 10367 /** @type {any} */ 10368 typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {} 10369 ); 10370 var importIdentifier = "__ $YJS$ __"; 10371 if (glo[importIdentifier] === true) { 10372 console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"); 10373 } 10374 glo[importIdentifier] = true; 10375 10376 // node_modules/.store/y-protocols@1.0.7-LCrc4ked9I2BIv1vBZfNXw/node_modules/y-protocols/awareness.js 10377 var outdatedTimeout = 3e4; 10378 var Awareness = class extends Observable { 10379 /** 10380 * @param {Y.Doc} doc 10381 */ 10382 constructor(doc2) { 10383 super(); 10384 this.doc = doc2; 10385 this.clientID = doc2.clientID; 10386 this.states = /* @__PURE__ */ new Map(); 10387 this.meta = /* @__PURE__ */ new Map(); 10388 this._checkInterval = /** @type {any} */ 10389 setInterval(() => { 10390 const now = getUnixTime(); 10391 if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ 10392 this.meta.get(this.clientID).lastUpdated) { 10393 this.setLocalState(this.getLocalState()); 10394 } 10395 const remove = []; 10396 this.meta.forEach((meta, clientid) => { 10397 if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) { 10398 remove.push(clientid); 10399 } 10400 }); 10401 if (remove.length > 0) { 10402 removeAwarenessStates(this, remove, "timeout"); 10403 } 10404 }, floor(outdatedTimeout / 10)); 10405 doc2.on("destroy", () => { 10406 this.destroy(); 10407 }); 10408 this.setLocalState({}); 10409 } 10410 destroy() { 10411 this.emit("destroy", [this]); 10412 this.setLocalState(null); 10413 super.destroy(); 10414 clearInterval(this._checkInterval); 10415 } 10416 /** 10417 * @return {Object<string,any>|null} 10418 */ 10419 getLocalState() { 10420 return this.states.get(this.clientID) || null; 10421 } 10422 /** 10423 * @param {Object<string,any>|null} state 10424 */ 10425 setLocalState(state) { 10426 const clientID = this.clientID; 10427 const currLocalMeta = this.meta.get(clientID); 10428 const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1; 10429 const prevState = this.states.get(clientID); 10430 if (state === null) { 10431 this.states.delete(clientID); 10432 } else { 10433 this.states.set(clientID, state); 10434 } 10435 this.meta.set(clientID, { 10436 clock, 10437 lastUpdated: getUnixTime() 10438 }); 10439 const added = []; 10440 const updated = []; 10441 const filteredUpdated = []; 10442 const removed = []; 10443 if (state === null) { 10444 removed.push(clientID); 10445 } else if (prevState == null) { 10446 if (state != null) { 10447 added.push(clientID); 10448 } 10449 } else { 10450 updated.push(clientID); 10451 if (!equalityDeep(prevState, state)) { 10452 filteredUpdated.push(clientID); 10453 } 10454 } 10455 if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) { 10456 this.emit("change", [{ added, updated: filteredUpdated, removed }, "local"]); 10457 } 10458 this.emit("update", [{ added, updated, removed }, "local"]); 10459 } 10460 /** 10461 * @param {string} field 10462 * @param {any} value 10463 */ 10464 setLocalStateField(field, value) { 10465 const state = this.getLocalState(); 10466 if (state !== null) { 10467 this.setLocalState({ 10468 ...state, 10469 [field]: value 10470 }); 10471 } 10472 } 10473 /** 10474 * @return {Map<number,Object<string,any>>} 10475 */ 10476 getStates() { 10477 return this.states; 10478 } 10479 }; 10480 var removeAwarenessStates = (awareness, clients, origin2) => { 10481 const removed = []; 10482 for (let i = 0; i < clients.length; i++) { 10483 const clientID = clients[i]; 10484 if (awareness.states.has(clientID)) { 10485 awareness.states.delete(clientID); 10486 if (clientID === awareness.clientID) { 10487 const curMeta = ( 10488 /** @type {MetaClientState} */ 10489 awareness.meta.get(clientID) 10490 ); 10491 awareness.meta.set(clientID, { 10492 clock: curMeta.clock + 1, 10493 lastUpdated: getUnixTime() 10494 }); 10495 } 10496 removed.push(clientID); 10497 } 10498 } 10499 if (removed.length > 0) { 10500 awareness.emit("change", [{ added: [], updated: [], removed }, origin2]); 10501 awareness.emit("update", [{ added: [], updated: [], removed }, origin2]); 10502 } 10503 }; 10504 10505 // packages/sync/build-module/config.mjs 10506 var CRDT_DOC_VERSION = 1; 10507 var CRDT_DOC_META_PERSISTENCE_KEY = "fromPersistence"; 10508 var CRDT_RECORD_MAP_KEY = "document"; 10509 var CRDT_STATE_MAP_KEY = "state"; 10510 var CRDT_STATE_MAP_SAVED_AT_KEY = "savedAt"; 10511 var CRDT_STATE_MAP_SAVED_BY_KEY = "savedBy"; 10512 var CRDT_STATE_MAP_VERSION_KEY = "version"; 10513 var LOCAL_EDITOR_ORIGIN = "gutenberg"; 10514 var LOCAL_SYNC_MANAGER_ORIGIN = "syncManager"; 10515 var LOCAL_UNDO_IGNORED_ORIGIN = "gutenberg-undo-ignored"; 10516 10517 // packages/sync/build-module/errors.mjs 10518 var ConnectionErrorCode = /* @__PURE__ */ ((ConnectionErrorCode2) => { 10519 ConnectionErrorCode2["AUTHENTICATION_FAILED"] = "authentication-failed"; 10520 ConnectionErrorCode2["CONNECTION_EXPIRED"] = "connection-expired"; 10521 ConnectionErrorCode2["CONNECTION_LIMIT_EXCEEDED"] = "connection-limit-exceeded"; 10522 ConnectionErrorCode2["DOCUMENT_SIZE_LIMIT_EXCEEDED"] = "document-size-limit-exceeded"; 10523 ConnectionErrorCode2["PROTOCOL_MISMATCH"] = "protocol-mismatch"; 10524 ConnectionErrorCode2["UNKNOWN_ERROR"] = "unknown-error"; 10525 return ConnectionErrorCode2; 10526 })(ConnectionErrorCode || {}); 10527 var ConnectionError = class extends Error { 10528 constructor(code = "unknown-error", message) { 10529 super(message); 10530 this.code = code; 10531 this.name = "ConnectionError"; 10532 } 10533 }; 10534 10535 // packages/sync/build-module/performance.mjs 10536 function logPerformanceTiming(fn) { 10537 return function(...args2) { 10538 const start = performance.now(); 10539 const result = fn.apply(this, args2); 10540 const end = performance.now(); 10541 console.log( 10542 `[SyncManager][performance]: $fn.name} took ${(end - start).toFixed(2)} ms` 10543 ); 10544 return result; 10545 }; 10546 } 10547 function passThru(fn) { 10548 return ((...args2) => fn(...args2)); 10549 } 10550 10551 // packages/sync/build-module/providers/index.mjs 10552 var import_hooks3 = __toESM(require_hooks(), 1); 10553 10554 // packages/sync/build-module/providers/http-polling/polling-manager.mjs 10555 var import_hooks2 = __toESM(require_hooks(), 1); 10556 10557 // node_modules/.store/y-protocols@1.0.7-LCrc4ked9I2BIv1vBZfNXw/node_modules/y-protocols/sync.js 10558 var messageYjsSyncStep1 = 0; 10559 var messageYjsSyncStep2 = 1; 10560 var messageYjsUpdate = 2; 10561 var writeSyncStep1 = (encoder, doc2) => { 10562 writeVarUint(encoder, messageYjsSyncStep1); 10563 const sv = encodeStateVector(doc2); 10564 writeVarUint8Array(encoder, sv); 10565 }; 10566 var writeSyncStep2 = (encoder, doc2, encodedStateVector) => { 10567 writeVarUint(encoder, messageYjsSyncStep2); 10568 writeVarUint8Array(encoder, encodeStateAsUpdate(doc2, encodedStateVector)); 10569 }; 10570 var readSyncStep1 = (decoder, encoder, doc2) => writeSyncStep2(encoder, doc2, readVarUint8Array(decoder)); 10571 var readSyncStep2 = (decoder, doc2, transactionOrigin, errorHandler) => { 10572 try { 10573 applyUpdate(doc2, readVarUint8Array(decoder), transactionOrigin); 10574 } catch (error) { 10575 if (errorHandler != null) errorHandler( 10576 /** @type {Error} */ 10577 error 10578 ); 10579 console.error("Caught error while handling a Yjs update", error); 10580 } 10581 }; 10582 var readUpdate2 = readSyncStep2; 10583 var readSyncMessage = (decoder, encoder, doc2, transactionOrigin, errorHandler) => { 10584 const messageType = readVarUint(decoder); 10585 switch (messageType) { 10586 case messageYjsSyncStep1: 10587 readSyncStep1(decoder, encoder, doc2); 10588 break; 10589 case messageYjsSyncStep2: 10590 readSyncStep2(decoder, doc2, transactionOrigin, errorHandler); 10591 break; 10592 case messageYjsUpdate: 10593 readUpdate2(decoder, doc2, transactionOrigin, errorHandler); 10594 break; 10595 default: 10596 throw new Error("Unknown message type"); 10597 } 10598 return messageType; 10599 }; 10600 10601 // packages/sync/build-module/providers/http-polling/config.mjs 10602 var import_hooks = __toESM(require_hooks(), 1); 10603 var DEFAULT_CLIENT_LIMIT_PER_ROOM = 3; 10604 var ERROR_RETRY_DELAYS_SOLO_MS = [ 10605 2e3, 10606 4e3, 10607 8e3, 10608 12e3 10609 // Solo: 26s total retry time solo before dialog 10610 ]; 10611 var ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS = [ 10612 1e3, 10613 2e3, 10614 4e3, 10615 8e3 10616 // With collaborators: 15s total retry time before dialog 10617 ]; 10618 var DISCONNECT_DIALOG_RETRY_MS = 3e4; 10619 var MANUAL_RETRY_INTERVAL_MS = 15e3; 10620 var MAX_ENCODED_UPDATE_SIZE_IN_BYTES = 1 * 1024 * 1024; 10621 var MAX_UPDATE_SIZE_IN_BYTES = Math.floor(MAX_ENCODED_UPDATE_SIZE_IN_BYTES / 4) * 3; 10622 var MAX_ROOMS_PER_REQUEST = 50; 10623 var MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES = 15 * 1024 * 1024; 10624 var MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES = 2 * 1024 * 1024; 10625 var DEFAULT_POLLING_INTERVAL_IN_MS = 4e3; 10626 var DEFAULT_POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS = 1e3; 10627 function getFilteredPollingInterval(hookName, defaultInterval) { 10628 const filteredInterval = (0, import_hooks.applyFilters)(hookName, defaultInterval); 10629 if (typeof filteredInterval !== "number" || !Number.isFinite(filteredInterval) || filteredInterval <= 0) { 10630 return defaultInterval; 10631 } 10632 return Math.min(filteredInterval, defaultInterval); 10633 } 10634 var POLLING_INTERVAL_IN_MS = getFilteredPollingInterval( 10635 "sync.pollingManager.pollingInterval", 10636 DEFAULT_POLLING_INTERVAL_IN_MS 10637 ); 10638 var POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS = getFilteredPollingInterval( 10639 "sync.pollingManager.pollingIntervalWithCollaborators", 10640 DEFAULT_POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS 10641 ); 10642 var POLLING_INTERVAL_BACKGROUND_TAB_IN_MS = 25 * 1e3; 10643 10644 // packages/sync/build-module/providers/http-polling/types.mjs 10645 var SyncUpdateType = /* @__PURE__ */ ((SyncUpdateType2) => { 10646 SyncUpdateType2["COMPACTION"] = "compaction"; 10647 SyncUpdateType2["SYNC_STEP_1"] = "sync_step1"; 10648 SyncUpdateType2["SYNC_STEP_2"] = "sync_step2"; 10649 SyncUpdateType2["UPDATE"] = "update"; 10650 return SyncUpdateType2; 10651 })(SyncUpdateType || {}); 10652 10653 // packages/sync/build-module/providers/http-polling/utils.mjs 10654 var import_api_fetch = __toESM(require_api_fetch(), 1); 10655 var SYNC_API_PATH = "/wp-sync/v1/updates"; 10656 function uint8ArrayToBase64(data) { 10657 let binary = ""; 10658 const len = data.byteLength; 10659 for (let i = 0; i < len; i++) { 10660 binary += String.fromCharCode(data[i]); 10661 } 10662 return globalThis.btoa(binary); 10663 } 10664 function base64ToUint8Array(base64) { 10665 const binaryString = globalThis.atob(base64); 10666 const len = binaryString.length; 10667 const bytes = new Uint8Array(len); 10668 for (let i = 0; i < len; i++) { 10669 bytes[i] = binaryString.charCodeAt(i); 10670 } 10671 return bytes; 10672 } 10673 function createSyncUpdate(data, type) { 10674 return { 10675 data: uint8ArrayToBase64(data), 10676 type 10677 }; 10678 } 10679 function createUpdateQueue(initial = [], paused = true) { 10680 let isPaused = paused; 10681 const updates = [...initial]; 10682 return { 10683 add(update) { 10684 updates.push(update); 10685 }, 10686 addBulk(bulkUpdates) { 10687 if (0 === bulkUpdates.length) { 10688 return; 10689 } 10690 updates.push(...bulkUpdates); 10691 }, 10692 clear() { 10693 updates.splice(0, updates.length); 10694 }, 10695 get() { 10696 if (isPaused) { 10697 return []; 10698 } 10699 return updates.splice(0, updates.length); 10700 }, 10701 pause() { 10702 isPaused = true; 10703 }, 10704 peek() { 10705 if (isPaused) { 10706 return []; 10707 } 10708 return [...updates]; 10709 }, 10710 restore(restoredUpdates) { 10711 const filtered = restoredUpdates.filter( 10712 (u) => u.type !== SyncUpdateType.COMPACTION 10713 ); 10714 if (0 === filtered.length) { 10715 return; 10716 } 10717 updates.unshift(...filtered); 10718 }, 10719 restoreExact(restoredUpdates) { 10720 if (0 === restoredUpdates.length) { 10721 return; 10722 } 10723 updates.unshift(...restoredUpdates); 10724 }, 10725 resume() { 10726 isPaused = false; 10727 }, 10728 size() { 10729 return updates.length; 10730 }, 10731 take(count) { 10732 if (isPaused || count <= 0) { 10733 return []; 10734 } 10735 return updates.splice(0, count); 10736 } 10737 }; 10738 } 10739 function postSyncUpdate(payload) { 10740 return (0, import_api_fetch.default)({ 10741 method: "POST", 10742 path: SYNC_API_PATH, 10743 data: payload 10744 }); 10745 } 10746 function postSyncUpdateNonBlocking(payload) { 10747 if (payload.rooms.length === 0) { 10748 return; 10749 } 10750 (0, import_api_fetch.default)({ 10751 method: "POST", 10752 path: SYNC_API_PATH, 10753 data: payload, 10754 keepalive: true 10755 }).catch(() => { 10756 }); 10757 } 10758 function intValueOrDefault(value, defaultValue) { 10759 const intValue = parseInt(String(value), 10); 10760 return isNaN(intValue) ? defaultValue : intValue; 10761 } 10762 function rotateWindow(items2, offset, size2) { 10763 if (items2.length === 0) { 10764 return { window: [], nextOffset: 0 }; 10765 } 10766 const start = (offset % items2.length + items2.length) % items2.length; 10767 const wrapped = [...items2.slice(start), ...items2.slice(0, start)]; 10768 return { 10769 window: wrapped.slice(0, Math.max(0, size2)), 10770 nextOffset: (start + Math.max(0, size2)) % items2.length 10771 }; 10772 } 10773 10774 // packages/sync/build-module/providers/http-polling/polling-manager.mjs 10775 var POLLING_MANAGER_ORIGIN = "polling-manager"; 10776 function isForbiddenError(error) { 10777 return error?.data?.status === 403; 10778 } 10779 function isRequestBodyTooLargeError(error) { 10780 return error?.data?.status === 413 && error?.code === "rest_sync_body_too_large"; 10781 } 10782 function isProtocolMismatchError(error) { 10783 return error?.code === "rest_sync_protocol_mismatch"; 10784 } 10785 function handleForbiddenError(error, requestedRooms) { 10786 const requestedRoomNames = new Set( 10787 requestedRooms.map((room) => room.room) 10788 ); 10789 const forbiddenRooms = Array.isArray(error.data.rooms) ? error.data.rooms.filter((room) => requestedRoomNames.has(room)) : []; 10790 if (forbiddenRooms.length > 0) { 10791 for (const room of forbiddenRooms) { 10792 const state = roomStates.get(room); 10793 if (state) { 10794 state.log( 10795 "Permission denied, unregistering room", 10796 { error }, 10797 "error", 10798 true 10799 // force 10800 ); 10801 unregisterRoom(room, { sendDisconnectSignal: false }); 10802 } 10803 } 10804 for (const room of requestedRooms) { 10805 if (forbiddenRooms.includes(room.room)) { 10806 continue; 10807 } 10808 if (!roomStates.has(room.room)) { 10809 continue; 10810 } 10811 const remainingState = roomStates.get(room.room); 10812 if (room.updates.length > 0) { 10813 remainingState.updateQueue.restore(room.updates); 10814 } 10815 } 10816 } else { 10817 const rooms = [...roomStates.keys()]; 10818 for (const room of rooms) { 10819 const state = roomStates.get(room); 10820 if (state) { 10821 state.log( 10822 "Permission denied, unregistering room", 10823 { error }, 10824 "error", 10825 true 10826 // force 10827 ); 10828 unregisterRoom(room, { sendDisconnectSignal: false }); 10829 } 10830 } 10831 } 10832 } 10833 var roomStates = /* @__PURE__ */ new Map(); 10834 function createDeprecatedCompactionUpdate(updates) { 10835 const mergeable = updates.filter( 10836 (u) => [SyncUpdateType.COMPACTION, SyncUpdateType.UPDATE].includes( 10837 u.type 10838 ) 10839 ).map((u) => base64ToUint8Array(u.data)); 10840 return createSyncUpdate( 10841 mergeUpdatesV2(mergeable), 10842 SyncUpdateType.COMPACTION 10843 ); 10844 } 10845 function createSyncStep1Update(doc2) { 10846 const encoder = createEncoder(); 10847 writeSyncStep1(encoder, doc2); 10848 return createSyncUpdate( 10849 toUint8Array(encoder), 10850 SyncUpdateType.SYNC_STEP_1 10851 ); 10852 } 10853 function createSyncStep2Update(doc2, step1) { 10854 const decoder = createDecoder(step1); 10855 const encoder = createEncoder(); 10856 readSyncMessage( 10857 decoder, 10858 encoder, 10859 doc2, 10860 POLLING_MANAGER_ORIGIN 10861 ); 10862 return createSyncUpdate( 10863 toUint8Array(encoder), 10864 SyncUpdateType.SYNC_STEP_2 10865 ); 10866 } 10867 function processAwarenessUpdate(state, awareness) { 10868 const currentStates = awareness.getStates(); 10869 const added = /* @__PURE__ */ new Set(); 10870 const updated = /* @__PURE__ */ new Set(); 10871 const removed = new Set( 10872 Array.from(currentStates.keys()).filter( 10873 (clientId) => !state[clientId] 10874 ) 10875 ); 10876 Object.entries(state).forEach(([clientIdString, awarenessState]) => { 10877 const clientId = Number(clientIdString); 10878 if (clientId === awareness.clientID) { 10879 return; 10880 } 10881 if (null === awarenessState) { 10882 currentStates.delete(clientId); 10883 removed.add(clientId); 10884 return; 10885 } 10886 if (!currentStates.has(clientId)) { 10887 currentStates.set(clientId, awarenessState); 10888 added.add(clientId); 10889 return; 10890 } 10891 const currentState = currentStates.get(clientId); 10892 if (JSON.stringify(currentState) !== JSON.stringify(awarenessState)) { 10893 currentStates.set(clientId, awarenessState); 10894 updated.add(clientId); 10895 } 10896 }); 10897 if (added.size + updated.size > 0) { 10898 awareness.emit("change", [ 10899 { 10900 added: Array.from(added), 10901 updated: Array.from(updated), 10902 // Left blank on purpose, as the removal of clients is handled in the if condition below. 10903 removed: [] 10904 } 10905 ]); 10906 } 10907 if (removed.size > 0) { 10908 removeAwarenessStates( 10909 awareness, 10910 Array.from(removed), 10911 POLLING_MANAGER_ORIGIN 10912 ); 10913 } 10914 } 10915 function processDocUpdate(update, doc2) { 10916 const data = base64ToUint8Array(update.data); 10917 switch (update.type) { 10918 case SyncUpdateType.SYNC_STEP_1: { 10919 return createSyncStep2Update(doc2, data); 10920 } 10921 case SyncUpdateType.SYNC_STEP_2: { 10922 const decoder = createDecoder(data); 10923 const encoder = createEncoder(); 10924 readSyncMessage( 10925 decoder, 10926 encoder, 10927 doc2, 10928 POLLING_MANAGER_ORIGIN 10929 ); 10930 return; 10931 } 10932 case SyncUpdateType.COMPACTION: 10933 case SyncUpdateType.UPDATE: { 10934 applyUpdateV2(doc2, data, POLLING_MANAGER_ORIGIN); 10935 } 10936 } 10937 } 10938 function checkConnectionLimit(awareness, roomState) { 10939 if (!roomState.isPrimaryRoom || hasCheckedConnectionLimit) { 10940 return false; 10941 } 10942 hasCheckedConnectionLimit = true; 10943 const maxClientsPerRoom = (0, import_hooks2.applyFilters)( 10944 "sync.pollingProvider.maxClientsPerRoom", 10945 DEFAULT_CLIENT_LIMIT_PER_ROOM, 10946 roomState.room 10947 ); 10948 const clientCount = Object.keys(awareness).length; 10949 const validatedLimit = intValueOrDefault( 10950 maxClientsPerRoom, 10951 DEFAULT_CLIENT_LIMIT_PER_ROOM 10952 ); 10953 if (clientCount > validatedLimit) { 10954 roomState.log("Connection limit exceeded", { 10955 clientCount, 10956 maxClientsPerRoom: validatedLimit, 10957 room: roomState.room 10958 }); 10959 return true; 10960 } 10961 return false; 10962 } 10963 var areListenersRegistered = false; 10964 var consecutiveFailures = 0; 10965 var hasCheckedConnectionLimit = false; 10966 var isManualRetry = false; 10967 var hasCollaborators = false; 10968 var isActiveBrowser = "visible" === document.visibilityState; 10969 var isPolling = false; 10970 var isUnloadPending = false; 10971 var pollInterval = POLLING_INTERVAL_IN_MS; 10972 var pollingTimeoutId = null; 10973 var syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 10974 var roomOverflowOffset = 0; 10975 function handleBeforeUnload() { 10976 isUnloadPending = true; 10977 } 10978 function handlePageHide() { 10979 const rooms = Array.from(roomStates.entries()).map( 10980 ([room, state]) => ({ 10981 after: 0, 10982 awareness: null, 10983 client_id: state.clientId, 10984 room, 10985 updates: [] 10986 }) 10987 ); 10988 for (let i = 0; i < rooms.length; i += MAX_ROOMS_PER_REQUEST) { 10989 postSyncUpdateNonBlocking({ 10990 rooms: rooms.slice(i, i + MAX_ROOMS_PER_REQUEST) 10991 }); 10992 } 10993 } 10994 function handleVisibilityChange() { 10995 const wasActive = isActiveBrowser; 10996 isActiveBrowser = document.visibilityState === "visible"; 10997 if (isActiveBrowser && !wasActive) { 10998 if (pollingTimeoutId) { 10999 clearTimeout(pollingTimeoutId); 11000 pollingTimeoutId = null; 11001 poll(); 11002 } 11003 } 11004 } 11005 function selectRoomsForRequest() { 11006 const allRooms = Array.from(roomStates.values()); 11007 if (allRooms.length <= MAX_ROOMS_PER_REQUEST) { 11008 return allRooms; 11009 } 11010 const primaryRoom = allRooms.find((state) => state.isPrimaryRoom); 11011 const overflowRooms = allRooms.filter((state) => state !== primaryRoom); 11012 const overflowSlotsPerRequest = MAX_ROOMS_PER_REQUEST - (primaryRoom ? 1 : 0); 11013 const { window: overflowSlice, nextOffset } = rotateWindow( 11014 overflowRooms, 11015 roomOverflowOffset, 11016 overflowSlotsPerRequest 11017 ); 11018 roomOverflowOffset = nextOffset; 11019 if (primaryRoom) { 11020 return [primaryRoom, ...overflowSlice]; 11021 } 11022 return overflowSlice; 11023 } 11024 var textEncoder = new TextEncoder(); 11025 function getJsonByteLength(value) { 11026 return textEncoder.encode(JSON.stringify(value)).byteLength; 11027 } 11028 function createPayloadRoom(state, updates = []) { 11029 return { 11030 after: state.endCursor ?? 0, 11031 awareness: state.localAwarenessState, 11032 client_id: state.clientId, 11033 room: state.room, 11034 updates 11035 }; 11036 } 11037 function getUpdatePayloadSizeDelta(existingUpdateCount, update) { 11038 const commaSize = existingUpdateCount === 0 ? 0 : 1; 11039 return commaSize + getJsonByteLength(update); 11040 } 11041 function buildPayloadForRequest(selectedRoomStates) { 11042 const payload = { rooms: [] }; 11043 const roomsInRequest = []; 11044 for (const state of selectedRoomStates) { 11045 const room = createPayloadRoom(state); 11046 const candidate = { rooms: [...payload.rooms, room] }; 11047 if (payload.rooms.length > 0 && getJsonByteLength(candidate) > syncRequestBodySizeLimit) { 11048 break; 11049 } 11050 payload.rooms.push(room); 11051 roomsInRequest.push(state); 11052 } 11053 const pendingUpdates = roomsInRequest.map( 11054 (state) => state.updateQueue.peek() 11055 ); 11056 const sentUpdateCounts = roomsInRequest.map(() => 0); 11057 let payloadSize = getJsonByteLength(payload); 11058 let addedUpdate = true; 11059 while (addedUpdate) { 11060 addedUpdate = false; 11061 for (let i = 0; i < roomsInRequest.length; i++) { 11062 const update = pendingUpdates[i][sentUpdateCounts[i]]; 11063 if (!update) { 11064 continue; 11065 } 11066 const sizeDelta = getUpdatePayloadSizeDelta( 11067 sentUpdateCounts[i], 11068 update 11069 ); 11070 if (payloadSize + sizeDelta > syncRequestBodySizeLimit) { 11071 continue; 11072 } 11073 sentUpdateCounts[i]++; 11074 payloadSize += sizeDelta; 11075 addedUpdate = true; 11076 } 11077 } 11078 for (let i = 0; i < roomsInRequest.length; i++) { 11079 payload.rooms[i].updates = roomsInRequest[i].updateQueue.take( 11080 sentUpdateCounts[i] 11081 ); 11082 } 11083 return { payload, roomsInRequest }; 11084 } 11085 function restoreExactUpdates(payload) { 11086 for (const room of payload.rooms) { 11087 if (!roomStates.has(room.room) || room.updates.length === 0) { 11088 continue; 11089 } 11090 roomStates.get(room.room).updateQueue.restoreExact(room.updates); 11091 } 11092 } 11093 function poll() { 11094 isPolling = true; 11095 pollingTimeoutId = null; 11096 async function start() { 11097 if (0 === roomStates.size) { 11098 isPolling = false; 11099 return; 11100 } 11101 isUnloadPending = false; 11102 const { payload, roomsInRequest } = buildPayloadForRequest( 11103 selectRoomsForRequest() 11104 ); 11105 roomsInRequest.forEach((state) => { 11106 state.onStatusChange({ status: "connecting" }); 11107 }); 11108 try { 11109 const { rooms } = await postSyncUpdate(payload); 11110 consecutiveFailures = 0; 11111 isManualRetry = false; 11112 syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 11113 roomsInRequest.forEach((state) => { 11114 if (roomStates.get(state.room) !== state) { 11115 return; 11116 } 11117 state.onStatusChange({ status: "connected" }); 11118 }); 11119 hasCollaborators = false; 11120 rooms.forEach((room) => { 11121 if (!roomStates.has(room.room)) { 11122 return; 11123 } 11124 const roomState = roomStates.get(room.room); 11125 roomState.endCursor = room.end_cursor; 11126 if (checkConnectionLimit(room.awareness, roomState)) { 11127 roomState.onStatusChange({ 11128 status: "disconnected", 11129 error: new ConnectionError( 11130 ConnectionErrorCode.CONNECTION_LIMIT_EXCEEDED, 11131 "Connection limit exceeded" 11132 ) 11133 }); 11134 unregisterRoom(room.room); 11135 return; 11136 } 11137 roomState.processAwarenessUpdate(room.awareness); 11138 if (roomState.isPrimaryRoom && Object.keys(room.awareness).length > 1) { 11139 hasCollaborators = true; 11140 roomStates.forEach((state) => { 11141 state.updateQueue.resume(); 11142 }); 11143 } 11144 const responseUpdates = []; 11145 for (const update of room.updates) { 11146 try { 11147 const response = roomState.processDocUpdate(update); 11148 if (response) { 11149 responseUpdates.push(response); 11150 } 11151 } catch (error) { 11152 roomState.log( 11153 "Failed to apply sync update", 11154 { error, update }, 11155 "error", 11156 true 11157 // force 11158 ); 11159 } 11160 } 11161 roomState.updateQueue.addBulk(responseUpdates); 11162 if (room.should_compact) { 11163 roomState.log("Server requested compaction update"); 11164 roomState.updateQueue.clear(); 11165 roomState.updateQueue.add( 11166 roomState.createCompactionUpdate() 11167 ); 11168 } else if (room.compaction_request) { 11169 roomState.log("Server requested (old) compaction update"); 11170 roomState.updateQueue.add( 11171 createDeprecatedCompactionUpdate( 11172 room.compaction_request 11173 ) 11174 ); 11175 } 11176 }); 11177 if (isActiveBrowser && hasCollaborators) { 11178 pollInterval = POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS; 11179 } else if (isActiveBrowser) { 11180 pollInterval = POLLING_INTERVAL_IN_MS; 11181 } else { 11182 pollInterval = POLLING_INTERVAL_BACKGROUND_TAB_IN_MS; 11183 } 11184 } catch (error) { 11185 if (isForbiddenError(error)) { 11186 handleForbiddenError(error, payload.rooms); 11187 if (roomStates.size === 0) { 11188 isPolling = false; 11189 return; 11190 } 11191 } else if (isRequestBodyTooLargeError(error)) { 11192 syncRequestBodySizeLimit = Math.max( 11193 MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES, 11194 Math.floor(syncRequestBodySizeLimit / 2) 11195 ); 11196 pollInterval = hasCollaborators ? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS[0] : ERROR_RETRY_DELAYS_SOLO_MS[0]; 11197 restoreExactUpdates(payload); 11198 for (const room of payload.rooms) { 11199 if (!roomStates.has(room.room)) { 11200 continue; 11201 } 11202 roomStates.get(room.room).log( 11203 "Sync request body too large, retrying with smaller batches", 11204 { 11205 error, 11206 nextPoll: pollInterval, 11207 syncRequestBodySizeLimit 11208 }, 11209 "error", 11210 true 11211 // force 11212 ); 11213 } 11214 } else if (isProtocolMismatchError(error)) { 11215 const affectedRooms = [...roomStates.entries()]; 11216 for (const [, state] of affectedRooms) { 11217 state.onStatusChange({ 11218 status: "disconnected", 11219 error: new ConnectionError( 11220 ConnectionErrorCode.PROTOCOL_MISMATCH, 11221 "Protocol mismatch between client and server" 11222 ) 11223 }); 11224 } 11225 for (const [room] of affectedRooms) { 11226 unregisterRoom(room, { sendDisconnectSignal: false }); 11227 } 11228 isPolling = false; 11229 return; 11230 } else { 11231 consecutiveFailures++; 11232 const retrySchedule = hasCollaborators ? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS : ERROR_RETRY_DELAYS_SOLO_MS; 11233 if (consecutiveFailures <= retrySchedule.length) { 11234 pollInterval = retrySchedule[consecutiveFailures - 1]; 11235 } else { 11236 pollInterval = DISCONNECT_DIALOG_RETRY_MS; 11237 } 11238 if (isManualRetry) { 11239 pollInterval = MANUAL_RETRY_INTERVAL_MS; 11240 isManualRetry = false; 11241 } 11242 for (const room of payload.rooms) { 11243 if (!roomStates.has(room.room)) { 11244 continue; 11245 } 11246 const state = roomStates.get(room.room); 11247 if (room.updates.length > 0 && state.endCursor > 0) { 11248 state.updateQueue.clear(); 11249 state.updateQueue.add(state.createCompactionUpdate()); 11250 } else if (room.updates.length > 0) { 11251 state.updateQueue.restore(room.updates); 11252 } 11253 state.log( 11254 "Error posting sync update, will retry with backoff", 11255 { error, nextPoll: pollInterval }, 11256 "error", 11257 true 11258 // force 11259 ); 11260 } 11261 if (!isUnloadPending) { 11262 const backgroundRetriesFailed = consecutiveFailures > retrySchedule.length; 11263 roomsInRequest.forEach((state) => { 11264 if (roomStates.get(state.room) !== state) { 11265 return; 11266 } 11267 state.onStatusChange({ 11268 status: "disconnected", 11269 canManuallyRetry: true, 11270 consecutiveFailures, 11271 backgroundRetriesFailed, 11272 willAutoRetryInMs: pollInterval 11273 }); 11274 }); 11275 } 11276 } 11277 } 11278 pollingTimeoutId = setTimeout(poll, pollInterval); 11279 } 11280 void start(); 11281 } 11282 function registerRoom({ 11283 room, 11284 doc: doc2, 11285 awareness, 11286 log, 11287 onStatusChange 11288 }) { 11289 if (roomStates.has(room)) { 11290 return; 11291 } 11292 const updateQueue = createUpdateQueue([createSyncStep1Update(doc2)]); 11293 const isPrimaryRoom = 0 === roomStates.size; 11294 function onAwarenessUpdate() { 11295 roomState.localAwarenessState = awareness.getLocalState() ?? {}; 11296 } 11297 function onDocUpdate(update, origin2) { 11298 if (POLLING_MANAGER_ORIGIN === origin2) { 11299 return; 11300 } 11301 if (update.byteLength > MAX_UPDATE_SIZE_IN_BYTES) { 11302 const state = roomStates.get(room); 11303 if (!state) { 11304 return; 11305 } 11306 state.log("Document size limit exceeded", { 11307 maxUpdateSizeInBytes: MAX_UPDATE_SIZE_IN_BYTES, 11308 updateSizeInBytes: update.byteLength 11309 }); 11310 state.onStatusChange({ 11311 status: "disconnected", 11312 error: new ConnectionError( 11313 ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED, 11314 "Document size limit exceeded" 11315 ) 11316 }); 11317 unregisterRoom(room); 11318 return; 11319 } 11320 updateQueue.add(createSyncUpdate(update, SyncUpdateType.UPDATE)); 11321 } 11322 function unregister() { 11323 doc2.off("updateV2", onDocUpdate); 11324 awareness.off("change", onAwarenessUpdate); 11325 updateQueue.clear(); 11326 } 11327 const roomState = { 11328 clientId: doc2.clientID, 11329 createCompactionUpdate: () => createSyncUpdate( 11330 encodeStateAsUpdateV2(doc2), 11331 SyncUpdateType.COMPACTION 11332 ), 11333 endCursor: 0, 11334 isPrimaryRoom, 11335 localAwarenessState: awareness.getLocalState() ?? {}, 11336 log, 11337 onStatusChange, 11338 processAwarenessUpdate: (state) => processAwarenessUpdate(state, awareness), 11339 processDocUpdate: (update) => processDocUpdate(update, doc2), 11340 room, 11341 unregister, 11342 updateQueue 11343 }; 11344 doc2.on("updateV2", onDocUpdate); 11345 awareness.on("change", onAwarenessUpdate); 11346 roomStates.set(room, roomState); 11347 if (!areListenersRegistered) { 11348 window.addEventListener("beforeunload", handleBeforeUnload); 11349 window.addEventListener("pagehide", handlePageHide); 11350 document.addEventListener("visibilitychange", handleVisibilityChange); 11351 areListenersRegistered = true; 11352 } 11353 if (!isPolling) { 11354 poll(); 11355 } 11356 } 11357 function unregisterRoom(room, { sendDisconnectSignal = true } = {}) { 11358 const state = roomStates.get(room); 11359 if (state) { 11360 if (sendDisconnectSignal) { 11361 const rooms = [ 11362 { 11363 after: 0, 11364 awareness: null, 11365 client_id: state.clientId, 11366 room, 11367 updates: [] 11368 } 11369 ]; 11370 postSyncUpdateNonBlocking({ rooms }); 11371 } 11372 state.unregister(); 11373 roomStates.delete(room); 11374 } 11375 if (0 === roomStates.size && areListenersRegistered) { 11376 window.removeEventListener("beforeunload", handleBeforeUnload); 11377 window.removeEventListener("pagehide", handlePageHide); 11378 document.removeEventListener( 11379 "visibilitychange", 11380 handleVisibilityChange 11381 ); 11382 areListenersRegistered = false; 11383 hasCheckedConnectionLimit = false; 11384 consecutiveFailures = 0; 11385 roomOverflowOffset = 0; 11386 syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 11387 } 11388 } 11389 function retryNow() { 11390 isManualRetry = true; 11391 if (pollingTimeoutId) { 11392 clearTimeout(pollingTimeoutId); 11393 pollingTimeoutId = null; 11394 poll(); 11395 } 11396 } 11397 function retrySyncConnection() { 11398 pollingManager.retryNow(); 11399 } 11400 var pollingManager = { 11401 registerRoom, 11402 retryNow, 11403 unregisterRoom 11404 }; 11405 11406 // packages/sync/build-module/providers/http-polling/http-polling-provider.mjs 11407 var HttpPollingProvider = class extends ObservableV2 { 11408 constructor(options) { 11409 super(); 11410 this.options = options; 11411 this.log("Initializing", { room: options.room }); 11412 this.awareness = options.awareness ?? new Awareness(options.ydoc); 11413 this.connect(); 11414 } 11415 awareness; 11416 status = "disconnected"; 11417 /** 11418 * Connect to the endpoint and initialize sync. 11419 */ 11420 connect() { 11421 this.log("Connecting"); 11422 pollingManager.registerRoom({ 11423 room: this.options.room, 11424 doc: this.options.ydoc, 11425 awareness: this.awareness, 11426 log: this.log, 11427 onStatusChange: this.emitStatus 11428 }); 11429 } 11430 /** 11431 * Destroy the provider and cleanup resources. 11432 */ 11433 destroy() { 11434 this.disconnect(); 11435 super.destroy(); 11436 } 11437 /** 11438 * Disconnect the provider and allow reconnection later. 11439 */ 11440 disconnect() { 11441 this.log("Disconnecting"); 11442 pollingManager.unregisterRoom(this.options.room); 11443 this.emitStatus({ status: "disconnected" }); 11444 } 11445 /** 11446 * Emit connection status, passing the full object through so that 11447 * additional fields (e.g. `willAutoRetryInMs`) are preserved for consumers. 11448 * 11449 * @param connectionStatus The connection status object 11450 */ 11451 emitStatus = (connectionStatus) => { 11452 const { status } = connectionStatus; 11453 const error = status === "disconnected" ? connectionStatus.error : void 0; 11454 if (this.status === status && !error) { 11455 return; 11456 } 11457 if (status === "connecting" && this.status !== "disconnected") { 11458 return; 11459 } 11460 this.log("Status change", { status, error }); 11461 this.status = status; 11462 this.emit("status", [connectionStatus]); 11463 }; 11464 /** 11465 * Log debug messages if debugging is enabled. 11466 * 11467 * @param message The debug message 11468 * @param debug Additional debug information 11469 * @param errorLevel The console method to use for logging 11470 * @param force Whether to force logging regardless of debug setting 11471 */ 11472 log = (message, debug = {}, errorLevel = "log", force = false) => { 11473 if (!this.options.debug && !force) { 11474 return; 11475 } 11476 const logFn = console[errorLevel] || console.log; 11477 logFn(`[$this.constructor.name}]: $message}`, { 11478 room: this.options.room, 11479 ...debug 11480 }); 11481 }; 11482 }; 11483 function createHttpPollingProvider() { 11484 return async ({ 11485 awareness, 11486 objectType, 11487 objectId, 11488 ydoc 11489 }) => { 11490 const room = objectId ? `$objectType}:$objectId}` : objectType; 11491 const provider = new HttpPollingProvider({ 11492 awareness, 11493 // debug: true, 11494 room, 11495 ydoc 11496 }); 11497 return { 11498 destroy: () => provider.destroy(), 11499 // Adapter: ObservableV2.on is compatible with ProviderOn 11500 // The callback receives data as the first parameter 11501 on: (event, callback) => { 11502 provider.on(event, callback); 11503 } 11504 }; 11505 }; 11506 } 11507 11508 // packages/sync/build-module/providers/index.mjs 11509 var providerCreators = null; 11510 function getDefaultProviderCreators() { 11511 return window.__experimentalEnableRealTimeCollaboration ? [createHttpPollingProvider()] : []; 11512 } 11513 function isProviderCreator(creator) { 11514 return "function" === typeof creator; 11515 } 11516 function getProviderCreators() { 11517 if (providerCreators) { 11518 return providerCreators; 11519 } 11520 if (!window.__experimentalEnableRealTimeCollaboration) { 11521 return []; 11522 } 11523 const filteredProviderCreators = (0, import_hooks3.applyFilters)( 11524 "sync.providers", 11525 getDefaultProviderCreators() 11526 ); 11527 if (!Array.isArray(filteredProviderCreators)) { 11528 providerCreators = []; 11529 return providerCreators; 11530 } 11531 providerCreators = filteredProviderCreators.filter(isProviderCreator); 11532 return providerCreators; 11533 } 11534 11535 // packages/sync/build-module/undo-manager.mjs 11536 function createEntityUndoManager(ydoc, ymap, handlers) { 11537 let isApplyingHistory = false; 11538 const yUndoManager = new UndoManager(ymap, { 11539 // Throttle undo/redo captures after 500ms of inactivity. 11540 // 500 was selected from subjective local UX testing, shorter timeouts 11541 // may cause mid-word undo stack items. 11542 captureTimeout: 500, 11543 // Ensure that we only scope the undo/redo to the current editor. 11544 trackedOrigins: /* @__PURE__ */ new Set([LOCAL_EDITOR_ORIGIN]) 11545 }); 11546 yUndoManager.on("stack-item-added", (event) => { 11547 handlers.addUndoMeta(ydoc, event.stackItem.meta); 11548 if ("undo" === event.type && !isApplyingHistory) { 11549 handlers.onUndoLevelOpened?.(); 11550 } 11551 }); 11552 yUndoManager.on("stack-item-popped", (event) => { 11553 handlers.restoreUndoMeta(ydoc, event.stackItem.meta); 11554 }); 11555 const applyHistory = (type) => { 11556 isApplyingHistory = true; 11557 try { 11558 const stackItem = "undo" === type ? yUndoManager.undo() : yUndoManager.redo(); 11559 return null !== stackItem; 11560 } finally { 11561 isApplyingHistory = false; 11562 } 11563 }; 11564 return { 11565 clearRedo: () => yUndoManager.clear(false, true), 11566 hasRedo: () => yUndoManager.canRedo(), 11567 hasUndo: () => yUndoManager.canUndo(), 11568 redo: () => applyHistory("redo"), 11569 stopCapturing: () => yUndoManager.stopCapturing(), 11570 undo: () => applyHistory("undo") 11571 }; 11572 } 11573 11574 // packages/sync/build-module/crdt-snapshot.mjs 11575 function encodeDocSnapshot(ydoc) { 11576 return toBase64(encodeSnapshotV2(snapshot(ydoc))); 11577 } 11578 function docContainsSnapshot(ydoc, encodedSnapshot) { 11579 let snapshot2; 11580 try { 11581 snapshot2 = decodeSnapshotV2(fromBase64(encodedSnapshot)); 11582 } catch { 11583 return false; 11584 } 11585 const localSnapshot = snapshot(ydoc); 11586 for (const [client, clock] of snapshot2.sv) { 11587 if ((localSnapshot.sv.get(client) ?? 0) < clock) { 11588 return false; 11589 } 11590 } 11591 const copiedDeleteSet = snapshot(ydoc).ds; 11592 const mergedDeleteSet = mergeDeleteSets([ 11593 copiedDeleteSet, 11594 snapshot2.ds 11595 ]); 11596 return equalDeleteSets(localSnapshot.ds, mergedDeleteSet); 11597 } 11598 11599 // packages/sync/build-module/utils.mjs 11600 function createYjsDoc(documentMeta = {}) { 11601 const metaMap = new Map( 11602 Object.entries(documentMeta) 11603 ); 11604 return new Doc({ meta: metaMap }); 11605 } 11606 function initializeYjsDoc(ydoc) { 11607 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11608 stateMap.set(CRDT_STATE_MAP_VERSION_KEY, CRDT_DOC_VERSION); 11609 } 11610 function markEntityAsSaved(ydoc) { 11611 const recordMeta = ydoc.getMap(CRDT_STATE_MAP_KEY); 11612 recordMeta.set(CRDT_STATE_MAP_SAVED_AT_KEY, Date.now()); 11613 recordMeta.set(CRDT_STATE_MAP_SAVED_BY_KEY, ydoc.clientID); 11614 } 11615 function pseudoRandomID() { 11616 return Math.floor(Math.random() * 1e9); 11617 } 11618 function serializeCrdtDoc(crdtDoc) { 11619 const tempDoc = createYjsDoc(); 11620 applyUpdateV2(tempDoc, encodeStateAsUpdateV2(crdtDoc)); 11621 const compactedUpdate = encodeStateAsUpdateV2(tempDoc); 11622 tempDoc.destroy(); 11623 return JSON.stringify({ 11624 document: toBase64(compactedUpdate), 11625 updateId: pseudoRandomID() 11626 // helps with debugging 11627 }); 11628 } 11629 function deserializeCrdtDoc(serializedCrdtDoc) { 11630 try { 11631 const { document: document2 } = JSON.parse(serializedCrdtDoc); 11632 const docMeta = { 11633 [CRDT_DOC_META_PERSISTENCE_KEY]: true 11634 }; 11635 const ydoc = createYjsDoc(docMeta); 11636 const yupdate = fromBase64(document2); 11637 applyUpdateV2(ydoc, yupdate); 11638 ydoc.clientID = pseudoRandomID(); 11639 return ydoc; 11640 } catch { 11641 return null; 11642 } 11643 } 11644 11645 // packages/sync/build-module/manager.mjs 11646 function getEntityId(objectType, objectId) { 11647 return `$objectType}_$objectId}`; 11648 } 11649 function createSyncManager(debug = false) { 11650 const debugWrap = debug ? logPerformanceTiming : passThru; 11651 const collectionStates = /* @__PURE__ */ new Map(); 11652 const entityStates = /* @__PURE__ */ new Map(); 11653 const undoManager2 = { 11654 undo(objectType, objectId) { 11655 flushPendingCRDTDocUpdates(); 11656 const entityState = entityStates.get( 11657 getEntityId(objectType, objectId) 11658 ); 11659 return entityState?.undoManager.undo() ?? false; 11660 }, 11661 redo(objectType, objectId) { 11662 flushPendingCRDTDocUpdates(); 11663 const entityState = entityStates.get( 11664 getEntityId(objectType, objectId) 11665 ); 11666 return entityState?.undoManager.redo() ?? false; 11667 }, 11668 hasUndo() { 11669 return [...entityStates.values()].some( 11670 (entityState) => entityState.undoManager.hasUndo() 11671 ); 11672 }, 11673 hasRedo() { 11674 return [...entityStates.values()].some( 11675 (entityState) => entityState.undoManager.hasRedo() 11676 ); 11677 }, 11678 stopCapturing() { 11679 flushPendingCRDTDocUpdates(); 11680 entityStates.forEach( 11681 (entityState) => entityState.undoManager.stopCapturing() 11682 ); 11683 }, 11684 clearRedo() { 11685 flushPendingCRDTDocUpdates(); 11686 entityStates.forEach( 11687 (entityState) => entityState.undoManager.clearRedo() 11688 ); 11689 } 11690 }; 11691 function log(component, message, entityId, context = {}) { 11692 if (!debug) { 11693 return; 11694 } 11695 console.log(`[SyncManager][$component}]: $message}`, { 11696 ...context, 11697 entityId 11698 }); 11699 } 11700 async function loadEntity(syncConfig, objectType, objectId, record, handlers) { 11701 const providerCreators2 = getProviderCreators(); 11702 const entityId = getEntityId(objectType, objectId); 11703 if (0 === providerCreators2.length) { 11704 log("loadEntity", "no providers, skipping", entityId); 11705 return; 11706 } 11707 if (entityStates.has(entityId)) { 11708 log("loadEntity", "already loaded", entityId); 11709 return; 11710 } 11711 if (false === syncConfig.shouldSync?.(objectType, objectId)) { 11712 log("loadEntity", "shouldSync false, skipping", entityId); 11713 return; 11714 } 11715 log("loadEntity", "loading", entityId); 11716 handlers = { 11717 addUndoMeta: debugWrap(handlers.addUndoMeta), 11718 editRecord: debugWrap(handlers.editRecord), 11719 getEditedRecord: debugWrap(handlers.getEditedRecord), 11720 onStatusChange: debugWrap(handlers.onStatusChange), 11721 persistCRDTDoc: debugWrap(handlers.persistCRDTDoc), 11722 refetchRecord: debugWrap(handlers.refetchRecord), 11723 restoreUndoMeta: debugWrap(handlers.restoreUndoMeta), 11724 onUndoLevelOpened: handlers.onUndoLevelOpened ? debugWrap(handlers.onUndoLevelOpened) : void 0 11725 }; 11726 const ydoc = createYjsDoc({ objectType }); 11727 const recordMap = ydoc.getMap(CRDT_RECORD_MAP_KEY); 11728 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11729 const now = Date.now(); 11730 let hasObserversAttached = false; 11731 let isEntityUnloaded = false; 11732 const unload = () => { 11733 log("loadEntity", "unloading", entityId); 11734 isEntityUnloaded = true; 11735 providerResults?.forEach((result) => result.destroy()); 11736 handlers.onStatusChange(null); 11737 if (hasObserversAttached) { 11738 recordMap.unobserveDeep(onRecordUpdate); 11739 stateMap.unobserve(onStateMapUpdate); 11740 } 11741 ydoc.destroy(); 11742 entityStates.delete(entityId); 11743 }; 11744 const awareness = syncConfig.createAwareness?.(ydoc, objectId); 11745 const onRecordUpdate = (_events, transaction) => { 11746 if (transaction.local && !(transaction.origin instanceof UndoManager)) { 11747 return; 11748 } 11749 void internal.updateEntityRecord(objectType, objectId); 11750 }; 11751 const onStateMapUpdate = (event, transaction) => { 11752 if (transaction.local) { 11753 return; 11754 } 11755 event.keysChanged.forEach((key) => { 11756 switch (key) { 11757 case CRDT_STATE_MAP_SAVED_AT_KEY: 11758 const savedAt = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY); 11759 if ("number" === typeof savedAt && savedAt > now) { 11760 log("loadEntity", "refetching record", entityId); 11761 void handlers.refetchRecord().catch(() => { 11762 }); 11763 } 11764 break; 11765 } 11766 }); 11767 }; 11768 const { addUndoMeta, onUndoLevelOpened, restoreUndoMeta } = handlers; 11769 const entityUndoManager = createEntityUndoManager(ydoc, recordMap, { 11770 addUndoMeta, 11771 restoreUndoMeta, 11772 onUndoLevelOpened: () => { 11773 entityStates.forEach((other) => { 11774 if (other.undoManager !== entityUndoManager) { 11775 other.undoManager.stopCapturing(); 11776 other.undoManager.clearRedo(); 11777 } 11778 }); 11779 onUndoLevelOpened?.(); 11780 } 11781 }); 11782 let providerResults; 11783 const entityState = { 11784 awareness, 11785 handlers, 11786 objectId, 11787 objectType, 11788 syncConfig, 11789 undoManager: entityUndoManager, 11790 unload, 11791 ydoc 11792 }; 11793 entityStates.set(entityId, entityState); 11794 log("loadEntity", "connecting", entityId); 11795 providerResults = await Promise.all( 11796 providerCreators2.map(async (create9) => { 11797 const provider = await create9({ 11798 objectType, 11799 objectId, 11800 ydoc, 11801 awareness, 11802 Y: yjs_exports 11803 }); 11804 provider.on("status", handlers.onStatusChange); 11805 return provider; 11806 }) 11807 ); 11808 if (isEntityUnloaded) { 11809 log("loadEntity", "unloaded during connect, aborting", entityId); 11810 providerResults.forEach((result) => result.destroy()); 11811 return; 11812 } 11813 initializeYjsDoc(ydoc); 11814 internal.applyPersistedCrdtDoc(objectType, objectId, record); 11815 recordMap.observeDeep(onRecordUpdate); 11816 stateMap.observe(onStateMapUpdate); 11817 hasObserversAttached = true; 11818 } 11819 async function loadCollection(syncConfig, objectType, handlers) { 11820 const providerCreators2 = getProviderCreators(); 11821 const entityId = getEntityId(objectType, null); 11822 if (0 === providerCreators2.length) { 11823 log("loadCollection", "no providers, skipping", entityId); 11824 return; 11825 } 11826 if (collectionStates.has(objectType)) { 11827 log("loadCollection", "already loaded", entityId); 11828 return; 11829 } 11830 if (false === syncConfig.shouldSync?.(objectType, null)) { 11831 log("loadCollection", "shouldSync false, skipping", entityId); 11832 return; 11833 } 11834 log("loadCollection", "loading", entityId); 11835 const ydoc = createYjsDoc({ collection: true, objectType }); 11836 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11837 const now = Date.now(); 11838 let hasObserversAttached = false; 11839 let isCollectionUnloaded = false; 11840 const unload = () => { 11841 log("loadCollection", "unloading", entityId); 11842 isCollectionUnloaded = true; 11843 providerResults?.forEach((result) => result.destroy()); 11844 handlers.onStatusChange(null); 11845 if (hasObserversAttached) { 11846 stateMap.unobserve(onStateMapUpdate); 11847 } 11848 ydoc.destroy(); 11849 collectionStates.delete(objectType); 11850 }; 11851 const onStateMapUpdate = (event, transaction) => { 11852 if (transaction.local) { 11853 return; 11854 } 11855 event.keysChanged.forEach((key) => { 11856 switch (key) { 11857 case CRDT_STATE_MAP_SAVED_AT_KEY: 11858 const newValue = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY); 11859 if ("number" === typeof newValue && newValue > now) { 11860 void handlers.refetchRecords().catch(() => { 11861 }); 11862 } 11863 break; 11864 } 11865 }); 11866 }; 11867 const awareness = syncConfig.createAwareness?.(ydoc); 11868 let providerResults; 11869 const collectionState = { 11870 awareness, 11871 handlers, 11872 syncConfig, 11873 unload, 11874 ydoc 11875 }; 11876 collectionStates.set(objectType, collectionState); 11877 log("loadCollection", "connecting", entityId); 11878 providerResults = await Promise.all( 11879 providerCreators2.map(async (create9) => { 11880 const provider = await create9({ 11881 awareness, 11882 objectType, 11883 objectId: null, 11884 ydoc, 11885 Y: yjs_exports 11886 }); 11887 provider.on("status", handlers.onStatusChange); 11888 return provider; 11889 }) 11890 ); 11891 if (isCollectionUnloaded) { 11892 log( 11893 "loadCollection", 11894 "unloaded during connect, aborting", 11895 entityId 11896 ); 11897 providerResults.forEach((result) => result.destroy()); 11898 return; 11899 } 11900 stateMap.observe(onStateMapUpdate); 11901 hasObserversAttached = true; 11902 initializeYjsDoc(ydoc); 11903 } 11904 function isLoaded(objectType, objectId) { 11905 return entityStates.has(getEntityId(objectType, objectId)); 11906 } 11907 function unloadEntity(objectType, objectId) { 11908 const entityId = getEntityId(objectType, objectId); 11909 log("unloadEntity", "unloading", entityId); 11910 entityStates.get(entityId)?.unload(); 11911 updateCRDTDoc(objectType, null, {}, origin, { 11912 isSave: true 11913 }); 11914 } 11915 function unloadAll() { 11916 log("unloadAll", "unloading all entities", "all"); 11917 for (const [, entityState] of [...entityStates]) { 11918 entityState.unload(); 11919 } 11920 entityStates.clear(); 11921 for (const [, collectionState] of [...collectionStates]) { 11922 collectionState.unload(); 11923 } 11924 collectionStates.clear(); 11925 } 11926 function getAwareness(objectType, objectId) { 11927 const entityId = getEntityId(objectType, objectId); 11928 const entityState = entityStates.get(entityId); 11929 if (!entityState || !entityState.awareness) { 11930 return void 0; 11931 } 11932 return entityState.awareness; 11933 } 11934 function _applyPersistedCrdtDoc(objectType, objectId, record) { 11935 const entityId = getEntityId(objectType, objectId); 11936 const entityState = entityStates.get(entityId); 11937 if (!entityState) { 11938 log("applyPersistedCrdtDoc", "no entity state", entityId); 11939 return; 11940 } 11941 const { 11942 handlers, 11943 syncConfig: { 11944 applyChangesToCRDTDoc, 11945 getChangesFromCRDTDoc, 11946 getPersistedCRDTDoc 11947 }, 11948 ydoc: targetDoc 11949 } = entityState; 11950 const serialized = getPersistedCRDTDoc?.(record); 11951 const tempDoc = serialized ? deserializeCrdtDoc(serialized) : null; 11952 if (!tempDoc) { 11953 log("applyPersistedCrdtDoc", "no persisted doc", entityId); 11954 targetDoc.transact(() => { 11955 applyChangesToCRDTDoc(targetDoc, record); 11956 handlers.persistCRDTDoc(); 11957 }, LOCAL_SYNC_MANAGER_ORIGIN); 11958 return; 11959 } 11960 const update = encodeStateAsUpdateV2(tempDoc); 11961 applyUpdateV2(targetDoc, update); 11962 const invalidations = getChangesFromCRDTDoc(tempDoc, record); 11963 const invalidatedKeys = Object.keys(invalidations); 11964 tempDoc.destroy(); 11965 if (0 === invalidatedKeys.length) { 11966 log("applyPersistedCrdtDoc", "valid persisted doc", entityId); 11967 return; 11968 } 11969 log("applyPersistedCrdtDoc", "invalidated keys", entityId, { 11970 invalidatedKeys 11971 }); 11972 const changes = invalidatedKeys.reduce( 11973 (acc, key) => Object.assign(acc, { 11974 [key]: record[key] 11975 }), 11976 {} 11977 ); 11978 targetDoc.transact(() => { 11979 applyChangesToCRDTDoc(targetDoc, changes); 11980 handlers.persistCRDTDoc(); 11981 }, LOCAL_SYNC_MANAGER_ORIGIN); 11982 } 11983 function updateCRDTDoc(objectType, objectId, changes, origin2, options = {}) { 11984 const { isSave = false, isNewUndoLevel: isNewUndoLevel2 = false } = options; 11985 const entityId = getEntityId(objectType, objectId); 11986 const entityState = entityStates.get(entityId); 11987 const collectionState = collectionStates.get(objectType); 11988 if (entityState) { 11989 const { syncConfig, ydoc } = entityState; 11990 if (isNewUndoLevel2) { 11991 undoManager2.stopCapturing(); 11992 } 11993 ydoc.transact(() => { 11994 log("updateCRDTDoc", "applying changes", entityId, { 11995 changedKeys: Object.keys(changes) 11996 }); 11997 syncConfig.applyChangesToCRDTDoc(ydoc, changes); 11998 if (isSave) { 11999 markEntityAsSaved(ydoc); 12000 } 12001 }, origin2); 12002 } 12003 if (collectionState && isSave) { 12004 collectionState.ydoc.transact(() => { 12005 markEntityAsSaved(collectionState.ydoc); 12006 }, origin2); 12007 } 12008 } 12009 const pendingCRDTDocUpdates = []; 12010 let isFlushingCRDTDocUpdates = false; 12011 function flushPendingCRDTDocUpdates() { 12012 if (isFlushingCRDTDocUpdates) { 12013 return; 12014 } 12015 isFlushingCRDTDocUpdates = true; 12016 try { 12017 while (pendingCRDTDocUpdates.length > 0) { 12018 const args2 = pendingCRDTDocUpdates.shift(); 12019 if (args2) { 12020 updateCRDTDoc(...args2); 12021 } 12022 } 12023 } finally { 12024 isFlushingCRDTDocUpdates = false; 12025 } 12026 } 12027 function deferUpdateCRDTDoc(...args2) { 12028 pendingCRDTDocUpdates.push(args2); 12029 setTimeout(flushPendingCRDTDocUpdates, 0); 12030 } 12031 function updateOrDefer(objectType, objectId, changes, origin2, options = {}) { 12032 const hasRemotePeers = (getAwareness(objectType, objectId)?.getStates().size ?? 0) > 1; 12033 if (hasRemotePeers) { 12034 flushPendingCRDTDocUpdates(); 12035 updateCRDTDoc(objectType, objectId, changes, origin2, options); 12036 return; 12037 } 12038 deferUpdateCRDTDoc(objectType, objectId, changes, origin2, options); 12039 } 12040 function getEntitySnapshot2(objectType, objectId) { 12041 const entityId = getEntityId(objectType, objectId); 12042 const entityState = entityStates.get(entityId); 12043 if (!entityState) { 12044 log("getEntitySnapshot", "no entity state", entityId); 12045 return void 0; 12046 } 12047 flushPendingCRDTDocUpdates(); 12048 return encodeDocSnapshot(entityState.ydoc); 12049 } 12050 function entityContainsSnapshot2(objectType, objectId, encodedSnapshot) { 12051 const entityId = getEntityId(objectType, objectId); 12052 const entityState = entityStates.get(entityId); 12053 if (!entityState) { 12054 return false; 12055 } 12056 flushPendingCRDTDocUpdates(); 12057 return docContainsSnapshot(entityState.ydoc, encodedSnapshot); 12058 } 12059 async function _updateEntityRecord(objectType, objectId) { 12060 const entityId = getEntityId(objectType, objectId); 12061 const entityState = entityStates.get(entityId); 12062 if (!entityState) { 12063 log("updateEntityRecord", "no entity state", entityId); 12064 return; 12065 } 12066 const { handlers, syncConfig, ydoc } = entityState; 12067 const changes = syncConfig.getChangesFromCRDTDoc( 12068 ydoc, 12069 await handlers.getEditedRecord() 12070 ); 12071 const changedKeys = Object.keys(changes); 12072 if (0 === changedKeys.length) { 12073 return; 12074 } 12075 log("updateEntityRecord", "changes", entityId, { 12076 changedKeys 12077 }); 12078 handlers.editRecord(changes); 12079 } 12080 async function createPersistedCRDTDoc(objectType, objectId) { 12081 const entityId = getEntityId(objectType, objectId); 12082 const entityState = entityStates.get(entityId); 12083 if (!entityState?.ydoc) { 12084 return null; 12085 } 12086 flushPendingCRDTDocUpdates(); 12087 return serializeCrdtDoc(entityState.ydoc); 12088 } 12089 const internal = { 12090 applyPersistedCrdtDoc: debugWrap(_applyPersistedCrdtDoc), 12091 updateEntityRecord: debugWrap(_updateEntityRecord) 12092 }; 12093 return { 12094 createPersistedCRDTDoc: debugWrap(createPersistedCRDTDoc), 12095 entityContainsSnapshot: debugWrap(entityContainsSnapshot2), 12096 getAwareness, 12097 getEntitySnapshot: debugWrap(getEntitySnapshot2), 12098 isLoaded, 12099 load: debugWrap(loadEntity), 12100 loadCollection: debugWrap(loadCollection), 12101 undoManager: undoManager2, 12102 unload: debugWrap(unloadEntity), 12103 unloadAll: debugWrap(unloadAll), 12104 update: debugWrap(updateOrDefer) 12105 }; 12106 } 12107 12108 // node_modules/.store/diff@8.0.4-eS1ZVYhaFC9fHfWvV2-kIQ/node_modules/diff/libesm/diff/base.js 12109 var Diff = class { 12110 diff(oldStr, newStr, options = {}) { 12111 let callback; 12112 if (typeof options === "function") { 12113 callback = options; 12114 options = {}; 12115 } else if ("callback" in options) { 12116 callback = options.callback; 12117 } 12118 const oldString = this.castInput(oldStr, options); 12119 const newString = this.castInput(newStr, options); 12120 const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); 12121 const newTokens = this.removeEmpty(this.tokenize(newString, options)); 12122 return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); 12123 } 12124 diffWithOptionsObj(oldTokens, newTokens, options, callback) { 12125 var _a; 12126 const done = (value) => { 12127 value = this.postProcess(value, options); 12128 if (callback) { 12129 setTimeout(function() { 12130 callback(value); 12131 }, 0); 12132 return void 0; 12133 } else { 12134 return value; 12135 } 12136 }; 12137 const newLen = newTokens.length, oldLen = oldTokens.length; 12138 let editLength = 1; 12139 let maxEditLength = newLen + oldLen; 12140 if (options.maxEditLength != null) { 12141 maxEditLength = Math.min(maxEditLength, options.maxEditLength); 12142 } 12143 const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity; 12144 const abortAfterTimestamp = Date.now() + maxExecutionTime; 12145 const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; 12146 let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); 12147 if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { 12148 return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); 12149 } 12150 let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; 12151 const execEditLength = () => { 12152 for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { 12153 let basePath; 12154 const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; 12155 if (removePath) { 12156 bestPath[diagonalPath - 1] = void 0; 12157 } 12158 let canAdd = false; 12159 if (addPath) { 12160 const addPathNewPos = addPath.oldPos - diagonalPath; 12161 canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; 12162 } 12163 const canRemove = removePath && removePath.oldPos + 1 < oldLen; 12164 if (!canAdd && !canRemove) { 12165 bestPath[diagonalPath] = void 0; 12166 continue; 12167 } 12168 if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { 12169 basePath = this.addToPath(addPath, true, false, 0, options); 12170 } else { 12171 basePath = this.addToPath(removePath, false, true, 1, options); 12172 } 12173 newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); 12174 if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { 12175 return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; 12176 } else { 12177 bestPath[diagonalPath] = basePath; 12178 if (basePath.oldPos + 1 >= oldLen) { 12179 maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); 12180 } 12181 if (newPos + 1 >= newLen) { 12182 minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); 12183 } 12184 } 12185 } 12186 editLength++; 12187 }; 12188 if (callback) { 12189 (function exec() { 12190 setTimeout(function() { 12191 if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { 12192 return callback(void 0); 12193 } 12194 if (!execEditLength()) { 12195 exec(); 12196 } 12197 }, 0); 12198 })(); 12199 } else { 12200 while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { 12201 const ret = execEditLength(); 12202 if (ret) { 12203 return ret; 12204 } 12205 } 12206 } 12207 } 12208 addToPath(path, added, removed, oldPosInc, options) { 12209 const last2 = path.lastComponent; 12210 if (last2 && !options.oneChangePerToken && last2.added === added && last2.removed === removed) { 12211 return { 12212 oldPos: path.oldPos + oldPosInc, 12213 lastComponent: { count: last2.count + 1, added, removed, previousComponent: last2.previousComponent } 12214 }; 12215 } else { 12216 return { 12217 oldPos: path.oldPos + oldPosInc, 12218 lastComponent: { count: 1, added, removed, previousComponent: last2 } 12219 }; 12220 } 12221 } 12222 extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { 12223 const newLen = newTokens.length, oldLen = oldTokens.length; 12224 let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; 12225 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { 12226 newPos++; 12227 oldPos++; 12228 commonCount++; 12229 if (options.oneChangePerToken) { 12230 basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; 12231 } 12232 } 12233 if (commonCount && !options.oneChangePerToken) { 12234 basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; 12235 } 12236 basePath.oldPos = oldPos; 12237 return newPos; 12238 } 12239 equals(left, right, options) { 12240 if (options.comparator) { 12241 return options.comparator(left, right); 12242 } else { 12243 return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); 12244 } 12245 } 12246 removeEmpty(array) { 12247 const ret = []; 12248 for (let i = 0; i < array.length; i++) { 12249 if (array[i]) { 12250 ret.push(array[i]); 12251 } 12252 } 12253 return ret; 12254 } 12255 // eslint-disable-next-line @typescript-eslint/no-unused-vars 12256 castInput(value, options) { 12257 return value; 12258 } 12259 // eslint-disable-next-line @typescript-eslint/no-unused-vars 12260 tokenize(value, options) { 12261 return Array.from(value); 12262 } 12263 join(chars) { 12264 return chars.join(""); 12265 } 12266 postProcess(changeObjects, options) { 12267 return changeObjects; 12268 } 12269 get useLongestToken() { 12270 return false; 12271 } 12272 buildValues(lastComponent, newTokens, oldTokens) { 12273 const components = []; 12274 let nextComponent; 12275 while (lastComponent) { 12276 components.push(lastComponent); 12277 nextComponent = lastComponent.previousComponent; 12278 delete lastComponent.previousComponent; 12279 lastComponent = nextComponent; 12280 } 12281 components.reverse(); 12282 const componentLen = components.length; 12283 let componentPos = 0, newPos = 0, oldPos = 0; 12284 for (; componentPos < componentLen; componentPos++) { 12285 const component = components[componentPos]; 12286 if (!component.removed) { 12287 if (!component.added && this.useLongestToken) { 12288 let value = newTokens.slice(newPos, newPos + component.count); 12289 value = value.map(function(value2, i) { 12290 const oldValue = oldTokens[oldPos + i]; 12291 return oldValue.length > value2.length ? oldValue : value2; 12292 }); 12293 component.value = this.join(value); 12294 } else { 12295 component.value = this.join(newTokens.slice(newPos, newPos + component.count)); 12296 } 12297 newPos += component.count; 12298 if (!component.added) { 12299 oldPos += component.count; 12300 } 12301 } else { 12302 component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); 12303 oldPos += component.count; 12304 } 12305 } 12306 return components; 12307 } 12308 }; 12309 12310 // node_modules/.store/diff@8.0.4-eS1ZVYhaFC9fHfWvV2-kIQ/node_modules/diff/libesm/diff/character.js 12311 var CharacterDiff = class extends Diff { 12312 }; 12313 var characterDiff = new CharacterDiff(); 12314 function diffChars(oldStr, newStr, options) { 12315 return characterDiff.diff(oldStr, newStr, options); 12316 } 12317 12318 // node_modules/.store/diff@8.0.4-eS1ZVYhaFC9fHfWvV2-kIQ/node_modules/diff/libesm/diff/line.js 12319 var LineDiff = class extends Diff { 12320 constructor() { 12321 super(...arguments); 12322 this.tokenize = tokenize; 12323 } 12324 equals(left, right, options) { 12325 if (options.ignoreWhitespace) { 12326 if (!options.newlineIsToken || !left.includes("\n")) { 12327 left = left.trim(); 12328 } 12329 if (!options.newlineIsToken || !right.includes("\n")) { 12330 right = right.trim(); 12331 } 12332 } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { 12333 if (left.endsWith("\n")) { 12334 left = left.slice(0, -1); 12335 } 12336 if (right.endsWith("\n")) { 12337 right = right.slice(0, -1); 12338 } 12339 } 12340 return super.equals(left, right, options); 12341 } 12342 }; 12343 var lineDiff = new LineDiff(); 12344 function diffLines(oldStr, newStr, options) { 12345 return lineDiff.diff(oldStr, newStr, options); 12346 } 12347 function tokenize(value, options) { 12348 if (options.stripTrailingCr) { 12349 value = value.replace(/\r\n/g, "\n"); 12350 } 12351 const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); 12352 if (!linesAndNewlines[linesAndNewlines.length - 1]) { 12353 linesAndNewlines.pop(); 12354 } 12355 for (let i = 0; i < linesAndNewlines.length; i++) { 12356 const line = linesAndNewlines[i]; 12357 if (i % 2 && !options.newlineIsToken) { 12358 retLines[retLines.length - 1] += line; 12359 } else { 12360 retLines.push(line); 12361 } 12362 } 12363 return retLines; 12364 } 12365 12366 // packages/sync/build-module/quill-delta/Delta.mjs 12367 var import_es64 = __toESM(require_es6(), 1); 12368 12369 // packages/sync/build-module/quill-delta/AttributeMap.mjs 12370 var import_es63 = __toESM(require_es6(), 1); 12371 function cloneDeep(value) { 12372 return JSON.parse(JSON.stringify(value)); 12373 } 12374 var AttributeMap; 12375 ((AttributeMap2) => { 12376 function compose3(a = {}, b = {}, keepNull = false) { 12377 if (typeof a !== "object") { 12378 a = {}; 12379 } 12380 if (typeof b !== "object") { 12381 b = {}; 12382 } 12383 let attributes = cloneDeep(b); 12384 if (!keepNull) { 12385 attributes = Object.keys(attributes).reduce( 12386 (copy2, key) => { 12387 if (attributes[key] !== null || attributes[key] !== void 0) { 12388 copy2[key] = attributes[key]; 12389 } 12390 return copy2; 12391 }, 12392 {} 12393 ); 12394 } 12395 for (const key in a) { 12396 if (a[key] !== void 0 && b[key] === void 0) { 12397 attributes[key] = a[key]; 12398 } 12399 } 12400 return Object.keys(attributes).length > 0 ? attributes : void 0; 12401 } 12402 AttributeMap2.compose = compose3; 12403 function diff(a = {}, b = {}) { 12404 if (typeof a !== "object") { 12405 a = {}; 12406 } 12407 if (typeof b !== "object") { 12408 b = {}; 12409 } 12410 const attributes = Object.keys(a).concat(Object.keys(b)).reduce((attrs, key) => { 12411 if (!(0, import_es63.default)(a[key], b[key])) { 12412 attrs[key] = b[key] === void 0 ? null : b[key]; 12413 } 12414 return attrs; 12415 }, {}); 12416 return Object.keys(attributes).length > 0 ? attributes : void 0; 12417 } 12418 AttributeMap2.diff = diff; 12419 function invert(attr = {}, base = {}) { 12420 attr = attr || {}; 12421 const baseInverted = Object.keys(base).reduce( 12422 (memo, key) => { 12423 if (base[key] !== attr[key] && attr[key] !== void 0) { 12424 memo[key] = base[key]; 12425 } 12426 return memo; 12427 }, 12428 {} 12429 ); 12430 return Object.keys(attr).reduce((memo, key) => { 12431 if (attr[key] !== base[key] && base[key] === void 0) { 12432 memo[key] = null; 12433 } 12434 return memo; 12435 }, baseInverted); 12436 } 12437 AttributeMap2.invert = invert; 12438 function transform(a, b, priority = false) { 12439 if (typeof a !== "object") { 12440 return b; 12441 } 12442 if (typeof b !== "object") { 12443 return void 0; 12444 } 12445 if (!priority) { 12446 return b; 12447 } 12448 const attributes = Object.keys(b).reduce( 12449 (attrs, key) => { 12450 if (a[key] === void 0) { 12451 attrs[key] = b[key]; 12452 } 12453 return attrs; 12454 }, 12455 {} 12456 ); 12457 return Object.keys(attributes).length > 0 ? attributes : void 0; 12458 } 12459 AttributeMap2.transform = transform; 12460 })(AttributeMap || (AttributeMap = {})); 12461 var AttributeMap_default = AttributeMap; 12462 12463 // packages/sync/build-module/quill-delta/Op.mjs 12464 var Op; 12465 ((Op2) => { 12466 function length2(op) { 12467 if (typeof op.delete === "number") { 12468 return op.delete; 12469 } else if (typeof op.retain === "number") { 12470 return op.retain; 12471 } else if (typeof op.retain === "object" && op.retain !== null) { 12472 return 1; 12473 } 12474 return typeof op.insert === "string" ? op.insert.length : 1; 12475 } 12476 Op2.length = length2; 12477 })(Op || (Op = {})); 12478 var Op_default = Op; 12479 12480 // packages/sync/build-module/quill-delta/OpIterator.mjs 12481 var Iterator2 = class { 12482 ops; 12483 index; 12484 offset; 12485 constructor(ops) { 12486 this.ops = ops; 12487 this.index = 0; 12488 this.offset = 0; 12489 } 12490 hasNext() { 12491 return this.peekLength() < Infinity; 12492 } 12493 next(length2) { 12494 if (!length2) { 12495 length2 = Infinity; 12496 } 12497 const nextOp = this.ops[this.index]; 12498 if (nextOp) { 12499 const offset = this.offset; 12500 const opLength = Op_default.length(nextOp); 12501 if (length2 >= opLength - offset) { 12502 length2 = opLength - offset; 12503 this.index += 1; 12504 this.offset = 0; 12505 } else { 12506 this.offset += length2; 12507 } 12508 if (typeof nextOp.delete === "number") { 12509 return { delete: length2 }; 12510 } 12511 const retOp = {}; 12512 if (nextOp.attributes) { 12513 retOp.attributes = nextOp.attributes; 12514 } 12515 if (typeof nextOp.retain === "number") { 12516 retOp.retain = length2; 12517 } else if (typeof nextOp.retain === "object" && nextOp.retain !== null) { 12518 retOp.retain = nextOp.retain; 12519 } else if (typeof nextOp.insert === "string") { 12520 retOp.insert = nextOp.insert.substr(offset, length2); 12521 } else { 12522 retOp.insert = nextOp.insert; 12523 } 12524 return retOp; 12525 } 12526 return { retain: Infinity }; 12527 } 12528 peek() { 12529 return this.ops[this.index]; 12530 } 12531 peekLength() { 12532 if (this.ops[this.index]) { 12533 return Op_default.length(this.ops[this.index]) - this.offset; 12534 } 12535 return Infinity; 12536 } 12537 peekType() { 12538 const op = this.ops[this.index]; 12539 if (op) { 12540 if (typeof op.delete === "number") { 12541 return "delete"; 12542 } else if (typeof op.retain === "number" || typeof op.retain === "object" && op.retain !== null) { 12543 return "retain"; 12544 } 12545 return "insert"; 12546 } 12547 return "retain"; 12548 } 12549 rest() { 12550 if (!this.hasNext()) { 12551 return []; 12552 } else if (this.offset === 0) { 12553 return this.ops.slice(this.index); 12554 } 12555 const offset = this.offset; 12556 const index = this.index; 12557 const next = this.next(); 12558 const rest = this.ops.slice(this.index); 12559 this.offset = offset; 12560 this.index = index; 12561 return [next].concat(rest); 12562 } 12563 }; 12564 12565 // packages/sync/build-module/quill-delta/Delta.mjs 12566 function cloneDeep2(value) { 12567 return JSON.parse(JSON.stringify(value)); 12568 } 12569 var NULL_CHARACTER = String.fromCharCode(0); 12570 var STRING_TOO_LARGE_THRESHOLD = 1e4; 12571 function normalizeChangeCounts(changes) { 12572 return changes.map((change) => ({ 12573 ...change, 12574 count: change.value.length 12575 })); 12576 } 12577 var getEmbedTypeAndData = (a, b) => { 12578 if (typeof a !== "object" || a === null) { 12579 throw new Error(`cannot retain a $typeof a}`); 12580 } 12581 if (typeof b !== "object" || b === null) { 12582 throw new Error(`cannot retain a $typeof b}`); 12583 } 12584 const embedType = Object.keys(a)[0]; 12585 if (!embedType || embedType !== Object.keys(b)[0]) { 12586 throw new Error( 12587 `embed types not matched: $embedType} != $Object.keys(b)[0]}` 12588 ); 12589 } 12590 return [embedType, a[embedType], b[embedType]]; 12591 }; 12592 var Delta = class _Delta { 12593 static Op = Op_default; 12594 static OpIterator = Iterator2; 12595 static AttributeMap = AttributeMap_default; 12596 static handlers = {}; 12597 static registerEmbed(embedType, handler) { 12598 this.handlers[embedType] = handler; 12599 } 12600 static unregisterEmbed(embedType) { 12601 delete this.handlers[embedType]; 12602 } 12603 static getHandler(embedType) { 12604 const handler = this.handlers[embedType]; 12605 if (!handler) { 12606 throw new Error(`no handlers for embed type "$embedType}"`); 12607 } 12608 return handler; 12609 } 12610 ops; 12611 constructor(ops) { 12612 if (Array.isArray(ops)) { 12613 this.ops = ops; 12614 } else if (ops !== null && ops !== void 0 && Array.isArray(ops.ops)) { 12615 this.ops = ops.ops; 12616 } else { 12617 this.ops = []; 12618 } 12619 } 12620 insert(arg, attributes) { 12621 const newOp = {}; 12622 if (typeof arg === "string" && arg.length === 0) { 12623 return this; 12624 } 12625 newOp.insert = arg; 12626 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) { 12627 newOp.attributes = attributes; 12628 } 12629 return this.push(newOp); 12630 } 12631 delete(length2) { 12632 if (length2 <= 0) { 12633 return this; 12634 } 12635 return this.push({ delete: length2 }); 12636 } 12637 retain(length2, attributes) { 12638 if (typeof length2 === "number" && length2 <= 0) { 12639 return this; 12640 } 12641 const newOp = { retain: length2 }; 12642 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) { 12643 newOp.attributes = attributes; 12644 } 12645 return this.push(newOp); 12646 } 12647 push(newOp) { 12648 let index = this.ops.length; 12649 let lastOp = this.ops[index - 1]; 12650 newOp = cloneDeep2(newOp); 12651 if (typeof lastOp === "object") { 12652 if (typeof newOp.delete === "number" && typeof lastOp.delete === "number") { 12653 this.ops[index - 1] = { 12654 delete: lastOp.delete + newOp.delete 12655 }; 12656 return this; 12657 } 12658 if (typeof lastOp.delete === "number" && newOp.insert !== null && newOp.insert !== void 0) { 12659 index -= 1; 12660 lastOp = this.ops[index - 1]; 12661 if (typeof lastOp !== "object") { 12662 this.ops.unshift(newOp); 12663 return this; 12664 } 12665 } 12666 if ((0, import_es64.default)(newOp.attributes, lastOp.attributes)) { 12667 if (typeof newOp.insert === "string" && typeof lastOp.insert === "string") { 12668 this.ops[index - 1] = { 12669 insert: lastOp.insert + newOp.insert 12670 }; 12671 if (typeof newOp.attributes === "object") { 12672 this.ops[index - 1].attributes = newOp.attributes; 12673 } 12674 return this; 12675 } else if (typeof newOp.retain === "number" && typeof lastOp.retain === "number") { 12676 this.ops[index - 1] = { 12677 retain: lastOp.retain + newOp.retain 12678 }; 12679 if (typeof newOp.attributes === "object") { 12680 this.ops[index - 1].attributes = newOp.attributes; 12681 } 12682 return this; 12683 } 12684 } 12685 } 12686 if (index === this.ops.length) { 12687 this.ops.push(newOp); 12688 } else { 12689 this.ops.splice(index, 0, newOp); 12690 } 12691 return this; 12692 } 12693 chop() { 12694 const lastOp = this.ops[this.ops.length - 1]; 12695 if (lastOp && typeof lastOp.retain === "number" && !lastOp.attributes) { 12696 this.ops.pop(); 12697 } 12698 return this; 12699 } 12700 filter(predicate) { 12701 return this.ops.filter(predicate); 12702 } 12703 forEach(predicate) { 12704 this.ops.forEach(predicate); 12705 } 12706 map(predicate) { 12707 return this.ops.map(predicate); 12708 } 12709 partition(predicate) { 12710 const passed = []; 12711 const failed = []; 12712 this.forEach((op) => { 12713 const target = predicate(op) ? passed : failed; 12714 target.push(op); 12715 }); 12716 return [passed, failed]; 12717 } 12718 reduce(predicate, initialValue) { 12719 return this.ops.reduce(predicate, initialValue); 12720 } 12721 changeLength() { 12722 return this.reduce((length2, elem) => { 12723 if (elem.insert) { 12724 return length2 + Op_default.length(elem); 12725 } else if (elem.delete) { 12726 return length2 - elem.delete; 12727 } 12728 return length2; 12729 }, 0); 12730 } 12731 length() { 12732 return this.reduce((length2, elem) => { 12733 return length2 + Op_default.length(elem); 12734 }, 0); 12735 } 12736 slice(start = 0, end = Infinity) { 12737 const ops = []; 12738 const iter = new Iterator2(this.ops); 12739 let index = 0; 12740 while (index < end && iter.hasNext()) { 12741 let nextOp; 12742 if (index < start) { 12743 nextOp = iter.next(start - index); 12744 } else { 12745 nextOp = iter.next(end - index); 12746 ops.push(nextOp); 12747 } 12748 index += Op_default.length(nextOp); 12749 } 12750 return new _Delta(ops); 12751 } 12752 compose(other) { 12753 const thisIter = new Iterator2(this.ops); 12754 const otherIter = new Iterator2(other.ops); 12755 const ops = []; 12756 const firstOther = otherIter.peek(); 12757 if (firstOther !== null && firstOther !== void 0 && typeof firstOther.retain === "number" && (firstOther.attributes === null || firstOther.attributes === void 0)) { 12758 let firstLeft = firstOther.retain; 12759 while (thisIter.peekType() === "insert" && thisIter.peekLength() <= firstLeft) { 12760 firstLeft -= thisIter.peekLength(); 12761 ops.push(thisIter.next()); 12762 } 12763 if (firstOther.retain - firstLeft > 0) { 12764 otherIter.next(firstOther.retain - firstLeft); 12765 } 12766 } 12767 const delta = new _Delta(ops); 12768 while (thisIter.hasNext() || otherIter.hasNext()) { 12769 if (otherIter.peekType() === "insert") { 12770 delta.push(otherIter.next()); 12771 } else if (thisIter.peekType() === "delete") { 12772 delta.push(thisIter.next()); 12773 } else { 12774 const length2 = Math.min( 12775 thisIter.peekLength(), 12776 otherIter.peekLength() 12777 ); 12778 const thisOp = thisIter.next(length2); 12779 const otherOp = otherIter.next(length2); 12780 if (otherOp.retain) { 12781 const newOp = {}; 12782 if (typeof thisOp.retain === "number") { 12783 newOp.retain = typeof otherOp.retain === "number" ? length2 : otherOp.retain; 12784 } else if (typeof otherOp.retain === "number") { 12785 if (thisOp.retain === null || thisOp.retain === void 0) { 12786 newOp.insert = thisOp.insert; 12787 } else { 12788 newOp.retain = thisOp.retain; 12789 } 12790 } else { 12791 const action = thisOp.retain === null || thisOp.retain === void 0 ? "insert" : "retain"; 12792 const [embedType, thisData, otherData] = getEmbedTypeAndData( 12793 thisOp[action], 12794 otherOp.retain 12795 ); 12796 const handler = _Delta.getHandler(embedType); 12797 newOp[action] = { 12798 [embedType]: handler.compose( 12799 thisData, 12800 otherData, 12801 action === "retain" 12802 ) 12803 }; 12804 } 12805 const attributes = AttributeMap_default.compose( 12806 thisOp.attributes, 12807 otherOp.attributes, 12808 typeof thisOp.retain === "number" 12809 ); 12810 if (attributes) { 12811 newOp.attributes = attributes; 12812 } 12813 delta.push(newOp); 12814 if (!otherIter.hasNext() && (0, import_es64.default)(delta.ops[delta.ops.length - 1], newOp)) { 12815 const rest = new _Delta(thisIter.rest()); 12816 return delta.concat(rest).chop(); 12817 } 12818 } else if (typeof otherOp.delete === "number" && (typeof thisOp.retain === "number" || typeof thisOp.retain === "object" && thisOp.retain !== null)) { 12819 delta.push(otherOp); 12820 } 12821 } 12822 } 12823 return delta.chop(); 12824 } 12825 concat(other) { 12826 const delta = new _Delta(this.ops.slice()); 12827 if (other.ops.length > 0) { 12828 delta.push(other.ops[0]); 12829 delta.ops = delta.ops.concat(other.ops.slice(1)); 12830 } 12831 return delta; 12832 } 12833 diff(other) { 12834 if (this.ops === other.ops) { 12835 return new _Delta(); 12836 } 12837 const strings = this.deltasToStrings(other); 12838 const diffResult = normalizeChangeCounts( 12839 diffChars(strings[0], strings[1]) 12840 ); 12841 const thisIter = new Iterator2(this.ops); 12842 const otherIter = new Iterator2(other.ops); 12843 const retDelta = this.convertChangesToDelta( 12844 diffResult, 12845 thisIter, 12846 otherIter 12847 ); 12848 return retDelta.chop(); 12849 } 12850 eachLine(predicate, newline = "\n") { 12851 const iter = new Iterator2(this.ops); 12852 let line = new _Delta(); 12853 let i = 0; 12854 while (iter.hasNext()) { 12855 if (iter.peekType() !== "insert") { 12856 return; 12857 } 12858 const thisOp = iter.peek(); 12859 const start = Op_default.length(thisOp) - iter.peekLength(); 12860 const index = typeof thisOp.insert === "string" ? thisOp.insert.indexOf(newline, start) - start : -1; 12861 if (index < 0) { 12862 line.push(iter.next()); 12863 } else if (index > 0) { 12864 line.push(iter.next(index)); 12865 } else { 12866 if (predicate(line, iter.next(1).attributes || {}, i) === false) { 12867 return; 12868 } 12869 i += 1; 12870 line = new _Delta(); 12871 } 12872 } 12873 if (line.length() > 0) { 12874 predicate(line, {}, i); 12875 } 12876 } 12877 invert(base) { 12878 const inverted = new _Delta(); 12879 this.reduce((baseIndex, op) => { 12880 if (op.insert) { 12881 inverted.delete(Op_default.length(op)); 12882 } else if (typeof op.retain === "number" && (op.attributes === null || op.attributes === void 0)) { 12883 inverted.retain(op.retain); 12884 return baseIndex + op.retain; 12885 } else if (op.delete || typeof op.retain === "number") { 12886 const length2 = op.delete || op.retain; 12887 const slice = base.slice(baseIndex, baseIndex + length2); 12888 slice.forEach((baseOp) => { 12889 if (op.delete) { 12890 inverted.push(baseOp); 12891 } else if (op.retain && op.attributes) { 12892 inverted.retain( 12893 Op_default.length(baseOp), 12894 AttributeMap_default.invert( 12895 op.attributes, 12896 baseOp.attributes 12897 ) 12898 ); 12899 } 12900 }); 12901 return baseIndex + length2; 12902 } else if (typeof op.retain === "object" && op.retain !== null) { 12903 const slice = base.slice(baseIndex, baseIndex + 1); 12904 const baseOp = new Iterator2(slice.ops).next(); 12905 const [embedType, opData, baseOpData] = getEmbedTypeAndData( 12906 op.retain, 12907 baseOp.insert 12908 ); 12909 const handler = _Delta.getHandler(embedType); 12910 inverted.retain( 12911 { [embedType]: handler.invert(opData, baseOpData) }, 12912 AttributeMap_default.invert(op.attributes, baseOp.attributes) 12913 ); 12914 return baseIndex + 1; 12915 } 12916 return baseIndex; 12917 }, 0); 12918 return inverted.chop(); 12919 } 12920 transform(arg, priority = false) { 12921 priority = !!priority; 12922 if (typeof arg === "number") { 12923 return this.transformPosition(arg, priority); 12924 } 12925 const other = arg; 12926 const thisIter = new Iterator2(this.ops); 12927 const otherIter = new Iterator2(other.ops); 12928 const delta = new _Delta(); 12929 while (thisIter.hasNext() || otherIter.hasNext()) { 12930 if (thisIter.peekType() === "insert" && (priority || otherIter.peekType() !== "insert")) { 12931 delta.retain(Op_default.length(thisIter.next())); 12932 } else if (otherIter.peekType() === "insert") { 12933 delta.push(otherIter.next()); 12934 } else { 12935 const length2 = Math.min( 12936 thisIter.peekLength(), 12937 otherIter.peekLength() 12938 ); 12939 const thisOp = thisIter.next(length2); 12940 const otherOp = otherIter.next(length2); 12941 if (thisOp.delete) { 12942 continue; 12943 } else if (otherOp.delete) { 12944 delta.push(otherOp); 12945 } else { 12946 const thisData = thisOp.retain; 12947 const otherData = otherOp.retain; 12948 let transformedData = typeof otherData === "object" && otherData !== null ? otherData : length2; 12949 if (typeof thisData === "object" && thisData !== null && typeof otherData === "object" && otherData !== null) { 12950 const embedType = Object.keys(thisData)[0]; 12951 if (embedType === Object.keys(otherData)[0]) { 12952 const handler = _Delta.getHandler(embedType); 12953 if (handler) { 12954 transformedData = { 12955 [embedType]: handler.transform( 12956 thisData[embedType], 12957 otherData[embedType], 12958 priority 12959 ) 12960 }; 12961 } 12962 } 12963 } 12964 delta.retain( 12965 transformedData, 12966 AttributeMap_default.transform( 12967 thisOp.attributes, 12968 otherOp.attributes, 12969 priority 12970 ) 12971 ); 12972 } 12973 } 12974 } 12975 return delta.chop(); 12976 } 12977 transformPosition(index, priority = false) { 12978 priority = !!priority; 12979 const thisIter = new Iterator2(this.ops); 12980 let offset = 0; 12981 while (thisIter.hasNext() && offset <= index) { 12982 const length2 = thisIter.peekLength(); 12983 const nextType = thisIter.peekType(); 12984 thisIter.next(); 12985 if (nextType === "delete") { 12986 index -= Math.min(length2, index - offset); 12987 continue; 12988 } else if (nextType === "insert" && (offset < index || !priority)) { 12989 index += length2; 12990 } 12991 offset += length2; 12992 } 12993 return index; 12994 } 12995 /** 12996 * Given a Delta and a cursor position, do a diff and attempt to adjust 12997 * the diff to place insertions or deletions at the cursor position. 12998 * 12999 * @todo There are at least a few known cases where this produces a corrupted 13000 * diff. When this is fixed, it should not be necessary to verify that the 13001 * transformed diff applies cleanly. 13002 * 13003 * @see import("@wordpress/core-data/src/utils/crdt-blocks").mergeRichTextUpdate() 13004 * 13005 * @param other - The other Delta to diff against. 13006 * @param cursorAfterChange - The cursor position index after the change. 13007 * @return A Delta that attempts to place insertions or deletions at the cursor position. 13008 */ 13009 diffWithCursor(other, cursorAfterChange) { 13010 if (this.ops === other.ops) { 13011 return new _Delta(); 13012 } 13013 const strings = this.deltasToStrings(other); 13014 const maxStringLength = Math.max( 13015 ...strings.map((str) => str.length) 13016 ); 13017 if (maxStringLength > STRING_TOO_LARGE_THRESHOLD) { 13018 const diffResult = normalizeChangeCounts( 13019 diffLines(strings[0], strings[1]) 13020 ); 13021 const thisIterLarge = new Iterator2(this.ops); 13022 const otherIterLarge = new Iterator2(other.ops); 13023 return this.convertChangesToDelta( 13024 diffResult, 13025 thisIterLarge, 13026 otherIterLarge 13027 ).chop(); 13028 } else if (cursorAfterChange === null) { 13029 return this.diff(other); 13030 } 13031 let diffs = normalizeChangeCounts( 13032 diffChars(strings[0], strings[1]) 13033 ); 13034 let lastDiffPosition = 0; 13035 const adjustedDiffs = []; 13036 for (let i = 0; i < diffs.length; i++) { 13037 const diff = diffs[i]; 13038 const segmentStart = lastDiffPosition; 13039 const segmentEnd = lastDiffPosition + (diff.count ?? 0); 13040 const isCursorInSegment = cursorAfterChange > segmentStart && cursorAfterChange <= segmentEnd; 13041 const isUnchangedSegment = !diff.added && !diff.removed; 13042 const isRemovalSegment = diff.removed && !diff.added; 13043 const nextDiff = diffs[i + 1]; 13044 const isNextDiffAnInsert = nextDiff && nextDiff.added && !nextDiff.removed; 13045 if (isUnchangedSegment && isCursorInSegment && isNextDiffAnInsert) { 13046 const movedSegments = this.tryMoveInsertionToCursor( 13047 diff, 13048 nextDiff, 13049 cursorAfterChange, 13050 segmentStart 13051 ); 13052 if (movedSegments) { 13053 adjustedDiffs.push(...movedSegments); 13054 i++; 13055 lastDiffPosition = segmentEnd; 13056 continue; 13057 } 13058 } 13059 if (isRemovalSegment) { 13060 const movedSegments = this.tryMoveDeletionToCursor( 13061 diff, 13062 adjustedDiffs, 13063 cursorAfterChange, 13064 lastDiffPosition 13065 ); 13066 if (movedSegments) { 13067 adjustedDiffs.pop(); 13068 adjustedDiffs.push(...movedSegments); 13069 lastDiffPosition += diff.count ?? 0; 13070 continue; 13071 } 13072 } 13073 adjustedDiffs.push(diff); 13074 if (!diff.added) { 13075 lastDiffPosition += diff.count ?? 0; 13076 } 13077 } 13078 diffs = adjustedDiffs; 13079 const thisIter = new Iterator2(this.ops); 13080 const otherIter = new Iterator2(other.ops); 13081 const retDelta = this.convertChangesToDelta( 13082 diffs, 13083 thisIter, 13084 otherIter 13085 ); 13086 return retDelta.chop(); 13087 } 13088 /** 13089 * Try to move an insertion operation from after an unchanged segment to the cursor position within it. 13090 * This is a "look-ahead" strategy. 13091 * 13092 * @param diff - The current unchanged diff segment. 13093 * @param nextDiff - The next diff segment (expected to be an insertion). 13094 * @param cursorAfterChange - The cursor position after the change. 13095 * @param segmentStart - The start position of the current segment. 13096 * @return An array of adjusted diff segments if the insertion was successfully moved, null otherwise. 13097 */ 13098 tryMoveInsertionToCursor(diff, nextDiff, cursorAfterChange, segmentStart) { 13099 const nextDiffInsert = nextDiff.value; 13100 const insertLength = nextDiffInsert.length; 13101 const insertOffset = cursorAfterChange - segmentStart - insertLength; 13102 const textAtCursor = diff.value.substring( 13103 insertOffset, 13104 insertOffset + nextDiffInsert.length 13105 ); 13106 const isInsertMoveable = textAtCursor === nextDiffInsert; 13107 if (!isInsertMoveable) { 13108 return null; 13109 } 13110 const beforeCursor = diff.value.substring(0, insertOffset); 13111 const afterCursor = diff.value.substring(insertOffset); 13112 const result = []; 13113 if (beforeCursor.length > 0) { 13114 result.push({ 13115 value: beforeCursor, 13116 count: beforeCursor.length, 13117 added: false, 13118 removed: false 13119 }); 13120 } 13121 result.push(nextDiff); 13122 if (afterCursor.length > 0) { 13123 result.push({ 13124 value: afterCursor, 13125 count: afterCursor.length, 13126 added: false, 13127 removed: false 13128 }); 13129 } 13130 return result; 13131 } 13132 /** 13133 * Try to move a deletion operation to the cursor position by looking back at the previous unchanged segment. 13134 * This is a "look-back" strategy. 13135 * 13136 * @param diff - The current deletion diff segment. 13137 * @param adjustedDiffs - The array of previously processed diff segments. 13138 * @param cursorAfterChange - The cursor position after the change. 13139 * @param lastDiffPosition - The position in the document up to (but not including) the current diff. 13140 * @return An array of adjusted diff segments if the deletion was successfully moved, null otherwise. 13141 */ 13142 tryMoveDeletionToCursor(diff, adjustedDiffs, cursorAfterChange, lastDiffPosition) { 13143 const prevDiff = adjustedDiffs[adjustedDiffs.length - 1]; 13144 if (!prevDiff || prevDiff.added || prevDiff.removed) { 13145 return null; 13146 } 13147 const prevSegmentStart = lastDiffPosition - (prevDiff.count ?? 0); 13148 const prevSegmentEnd = lastDiffPosition; 13149 if (cursorAfterChange < prevSegmentStart || cursorAfterChange >= prevSegmentEnd) { 13150 return null; 13151 } 13152 const deletedChars = diff.value; 13153 const deleteOffset = cursorAfterChange - prevSegmentStart; 13154 const textAtCursor = prevDiff.value.substring( 13155 deleteOffset, 13156 deleteOffset + deletedChars.length 13157 ); 13158 const canBePlacedHere = textAtCursor === deletedChars; 13159 if (!canBePlacedHere) { 13160 return null; 13161 } 13162 const beforeCursor = prevDiff.value.substring(0, deleteOffset); 13163 const atAndAfterCursor = prevDiff.value.substring(deleteOffset); 13164 const deletionLength = diff.count ?? 0; 13165 const afterDeletion = atAndAfterCursor.substring(deletionLength); 13166 const result = []; 13167 if (beforeCursor.length > 0) { 13168 result.push({ 13169 value: beforeCursor, 13170 count: beforeCursor.length, 13171 added: false, 13172 removed: false 13173 }); 13174 } 13175 result.push(diff); 13176 if (afterDeletion.length > 0) { 13177 result.push({ 13178 value: afterDeletion, 13179 count: afterDeletion.length, 13180 added: false, 13181 removed: false 13182 }); 13183 } 13184 return result; 13185 } 13186 /** 13187 * Convert two Deltas to string representations for diffing. 13188 * 13189 * @param other - The other Delta to convert. 13190 * @return A tuple of [thisString, otherString]. 13191 */ 13192 deltasToStrings(other) { 13193 return [this, other].map((delta) => { 13194 return delta.map((op) => { 13195 if (op.insert !== null || op.insert !== void 0) { 13196 return typeof op.insert === "string" ? op.insert : NULL_CHARACTER; 13197 } 13198 const prep = delta === other ? "on" : "with"; 13199 throw new Error( 13200 "diff() called " + prep + " non-document" 13201 ); 13202 }).join(""); 13203 }); 13204 } 13205 /** 13206 * Process diff changes and convert them to Delta operations. 13207 * 13208 * @param changes - The array of changes from the diff algorithm. 13209 * @param thisIter - Iterator for this Delta's operations. 13210 * @param otherIter - Iterator for the other Delta's operations. 13211 * @return A Delta containing the processed diff operations. 13212 */ 13213 convertChangesToDelta(changes, thisIter, otherIter) { 13214 const retDelta = new _Delta(); 13215 changes.forEach((component) => { 13216 let length2 = component.count ?? 0; 13217 while (length2 > 0) { 13218 let opLength = 0; 13219 if (component.added) { 13220 opLength = Math.min(otherIter.peekLength(), length2); 13221 retDelta.push(otherIter.next(opLength)); 13222 } else if (component.removed) { 13223 opLength = Math.min(length2, thisIter.peekLength()); 13224 thisIter.next(opLength); 13225 retDelta.delete(opLength); 13226 } else { 13227 opLength = Math.min( 13228 thisIter.peekLength(), 13229 otherIter.peekLength(), 13230 length2 13231 ); 13232 const thisOp = thisIter.next(opLength); 13233 const otherOp = otherIter.next(opLength); 13234 if ((0, import_es64.default)(thisOp.insert, otherOp.insert)) { 13235 retDelta.retain( 13236 opLength, 13237 AttributeMap_default.diff( 13238 thisOp.attributes, 13239 otherOp.attributes 13240 ) 13241 ); 13242 } else { 13243 retDelta.push(otherOp).delete(opLength); 13244 } 13245 } 13246 length2 -= opLength; 13247 } 13248 }); 13249 return retDelta; 13250 } 13251 }; 13252 var Delta_default = Delta; 13253 13254 // packages/core-data/build-module/entity-sync.mjs 13255 var import_warning = __toESM(require_warning(), 1); 13256 var registeredManager; 13257 function registerEntitySyncManager(manager) { 13258 if (registeredManager && registeredManager !== manager) { 13259 (0, import_warning.default)( 13260 "registerEntitySyncManager: an entity sync manager is already registered. The new manager was ignored." 13261 ); 13262 return () => { 13263 }; 13264 } 13265 registeredManager = manager; 13266 return () => { 13267 if (registeredManager === manager) { 13268 registeredManager = void 0; 13269 } 13270 }; 13271 } 13272 function getEntitySyncManager() { 13273 return registeredManager; 13274 } 13275 13276 // node_modules/.store/tslib@2.8.1-LT-dxu1EkVy7OUDyVf5glQ/node_modules/tslib/tslib.es6.mjs 13277 var __assign = function() { 13278 __assign = Object.assign || function __assign2(t) { 13279 for (var s, i = 1, n = arguments.length; i < n; i++) { 13280 s = arguments[i]; 13281 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; 13282 } 13283 return t; 13284 }; 13285 return __assign.apply(this, arguments); 13286 }; 13287 13288 // node_modules/.store/lower-case@2.0.2-5YZP5nczP5_f_8Vt5KBPjA/node_modules/lower-case/dist.es2015/index.js 13289 function lowerCase(str) { 13290 return str.toLowerCase(); 13291 } 13292 13293 // node_modules/.store/no-case@3.0.4-R4Hzt6qn-erEsTak7ojDpg/node_modules/no-case/dist.es2015/index.js 13294 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g]; 13295 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi; 13296 function noCase(input, options) { 13297 if (options === void 0) { 13298 options = {}; 13299 } 13300 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; 13301 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0"); 13302 var start = 0; 13303 var end = result.length; 13304 while (result.charAt(start) === "\0") 13305 start++; 13306 while (result.charAt(end - 1) === "\0") 13307 end--; 13308 return result.slice(start, end).split("\0").map(transform).join(delimiter); 13309 } 13310 function replace(input, re, value) { 13311 if (re instanceof RegExp) 13312 return input.replace(re, value); 13313 return re.reduce(function(input2, re2) { 13314 return input2.replace(re2, value); 13315 }, input); 13316 } 13317 13318 // node_modules/.store/pascal-case@3.1.2-khtSA9hpCTEVLYfMgyRdoA/node_modules/pascal-case/dist.es2015/index.js 13319 function pascalCaseTransform(input, index) { 13320 var firstChar = input.charAt(0); 13321 var lowerChars = input.substr(1).toLowerCase(); 13322 if (index > 0 && firstChar >= "0" && firstChar <= "9") { 13323 return "_" + firstChar + lowerChars; 13324 } 13325 return "" + firstChar.toUpperCase() + lowerChars; 13326 } 13327 function pascalCase(input, options) { 13328 if (options === void 0) { 13329 options = {}; 13330 } 13331 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options)); 13332 } 13333 13334 // node_modules/.store/camel-case@4.1.2-5Gz5buNb7xjdcDcS4uJ7xw/node_modules/camel-case/dist.es2015/index.js 13335 function camelCaseTransform(input, index) { 13336 if (index === 0) 13337 return input.toLowerCase(); 13338 return pascalCaseTransform(input, index); 13339 } 13340 function camelCase(input, options) { 13341 if (options === void 0) { 13342 options = {}; 13343 } 13344 return pascalCase(input, __assign({ transform: camelCaseTransform }, options)); 13345 } 13346 13347 // node_modules/.store/upper-case-first@2.0.2-gj8G2jcL821LJ7crhULHjQ/node_modules/upper-case-first/dist.es2015/index.js 13348 function upperCaseFirst(input) { 13349 return input.charAt(0).toUpperCase() + input.substr(1); 13350 } 13351 13352 // node_modules/.store/capital-case@1.0.4-EVMMP2kRcoYmFbV1LUR_-w/node_modules/capital-case/dist.es2015/index.js 13353 function capitalCaseTransform(input) { 13354 return upperCaseFirst(input.toLowerCase()); 13355 } 13356 function capitalCase(input, options) { 13357 if (options === void 0) { 13358 options = {}; 13359 } 13360 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options)); 13361 } 13362 13363 // packages/core-data/build-module/entities.mjs 13364 var import_api_fetch2 = __toESM(require_api_fetch(), 1); 13365 var import_blocks4 = __toESM(require_blocks(), 1); 13366 var import_i18n = __toESM(require_i18n(), 1); 13367 13368 // packages/core-data/build-module/awareness/post-editor-awareness.mjs 13369 var import_data4 = __toESM(require_data(), 1); 13370 var import_block_editor3 = __toESM(require_block_editor(), 1); 13371 13372 // packages/core-data/build-module/awareness/base-awareness.mjs 13373 var import_data = __toESM(require_data(), 1); 13374 13375 // packages/core-data/build-module/awareness/config.mjs 13376 var AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS = 100; 13377 var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5; 13378 var REMOVAL_DELAY_IN_MS = 5e3; 13379 13380 // packages/core-data/build-module/awareness/utils.mjs 13381 function getBrowserName() { 13382 const userAgent = window.navigator.userAgent; 13383 let browserName = "Unknown"; 13384 if (userAgent.includes("Firefox")) { 13385 browserName = "Firefox"; 13386 } else if (userAgent.includes("Edg")) { 13387 browserName = "Microsoft Edge"; 13388 } else if (userAgent.includes("Chrome") && !userAgent.includes("Edg")) { 13389 browserName = "Chrome"; 13390 } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) { 13391 browserName = "Safari"; 13392 } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) { 13393 browserName = "Internet Explorer"; 13394 } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) { 13395 browserName = "Opera"; 13396 } 13397 return browserName; 13398 } 13399 function areMapsEqual(map1, map2, comparatorFn) { 13400 if (map1.size !== map2.size) { 13401 return false; 13402 } 13403 for (const [key, value1] of map1.entries()) { 13404 if (!map2.has(key)) { 13405 return false; 13406 } 13407 if (!comparatorFn(value1, map2.get(key))) { 13408 return false; 13409 } 13410 } 13411 return true; 13412 } 13413 function areCollaboratorInfosEqual(collaboratorInfo1, collaboratorInfo2) { 13414 if (!collaboratorInfo1 || !collaboratorInfo2) { 13415 return collaboratorInfo1 === collaboratorInfo2; 13416 } 13417 if (Object.keys(collaboratorInfo1).length !== Object.keys(collaboratorInfo2).length) { 13418 return false; 13419 } 13420 return Object.entries(collaboratorInfo1).every(([key, value]) => { 13421 return value === collaboratorInfo2[key]; 13422 }); 13423 } 13424 function hasValidAvatarUrls(value) { 13425 if ("object" !== typeof value || null === value || Array.isArray(value)) { 13426 return false; 13427 } 13428 return ["24", "48", "96"].every( 13429 (size2) => !(size2 in value) || "string" === typeof value[size2] 13430 ); 13431 } 13432 function isCollaboratorInfo(value) { 13433 if ("object" !== typeof value || null === value) { 13434 return false; 13435 } 13436 return "id" in value && "name" in value && "slug" in value && "browserType" in value && "enteredAt" in value && (null === value.id || "number" === typeof value.id && Number.isInteger(value.id) && value.id > 0) && "string" === typeof value.name && "" !== value.name.trim() && "string" === typeof value.slug && (!("avatar_urls" in value) || hasValidAvatarUrls(value.avatar_urls)) && "string" === typeof value.browserType && "number" === typeof value.enteredAt && Number.isFinite(value.enteredAt); 13437 } 13438 function generateCollaboratorInfo(currentCollaborator, clientId) { 13439 const presentationInfo = { 13440 browserType: getBrowserName(), 13441 enteredAt: Date.now() 13442 }; 13443 if ("object" === typeof currentCollaborator && currentCollaborator) { 13444 const user = currentCollaborator; 13445 if ("id" in user && "name" in user) { 13446 const collaboratorInfo = { 13447 ...presentationInfo, 13448 ..."avatar_urls" in user && hasValidAvatarUrls(user.avatar_urls) ? { avatar_urls: user.avatar_urls } : {}, 13449 id: user.id, 13450 name: user.name, 13451 slug: "slug" in user && "string" === typeof user.slug ? user.slug : "" 13452 }; 13453 if (isCollaboratorInfo(collaboratorInfo) && null !== collaboratorInfo.id) { 13454 return collaboratorInfo; 13455 } 13456 } 13457 } 13458 return { 13459 ...presentationInfo, 13460 id: null, 13461 // Keep shared awareness data language-neutral. The editor localizes this 13462 // fallback name for the viewer when it is displayed. 13463 name: "Anonymous User", 13464 slug: `anonymous-$clientId}` 13465 }; 13466 } 13467 function getRecordValue(obj, key) { 13468 if ("object" === typeof obj && null !== obj && key in obj) { 13469 return obj[key]; 13470 } 13471 return null; 13472 } 13473 function getTypedKeys(obj) { 13474 return Object.keys(obj); 13475 } 13476 13477 // packages/core-data/build-module/awareness/typed-awareness.mjs 13478 var TypedAwareness = class extends Awareness { 13479 /** 13480 * Get the states from an awareness document. 13481 */ 13482 getStates() { 13483 return super.getStates(); 13484 } 13485 /** 13486 * Get a local state field from an awareness document. 13487 * @param field 13488 */ 13489 getLocalStateField(field) { 13490 const state = this.getLocalState(); 13491 return getRecordValue(state, field); 13492 } 13493 /** 13494 * Set a local state field on an awareness document. 13495 * @param field 13496 * @param value 13497 */ 13498 setLocalStateField(field, value) { 13499 super.setLocalStateField(field, value); 13500 } 13501 }; 13502 13503 // packages/core-data/build-module/awareness/awareness-state.mjs 13504 var AwarenessWithEqualityChecks = class extends TypedAwareness { 13505 /** OVERRIDDEN METHODS */ 13506 /** 13507 * Set a local state field on an awareness document. Calling this method may 13508 * trigger rerenders of any subscribed components. 13509 * 13510 * Equality checks are provided by the abstract `equalityFieldChecks` property. 13511 * @param field - The field to set. 13512 * @param value - The value to set. 13513 */ 13514 setLocalStateField(field, value) { 13515 if (this.isFieldEqual( 13516 field, 13517 value, 13518 this.getLocalStateField(field) ?? void 0 13519 )) { 13520 return; 13521 } 13522 super.setLocalStateField(field, value); 13523 } 13524 /** CUSTOM METHODS */ 13525 /** 13526 * Determine if a field value has changed using the provided equality checks. 13527 * @param field - The field to check. 13528 * @param value1 - The first value to compare. 13529 * @param value2 - The second value to compare. 13530 */ 13531 isFieldEqual(field, value1, value2) { 13532 if (["clientId", "isConnected", "isMe"].includes(field)) { 13533 return value1 === value2; 13534 } 13535 if (field in this.equalityFieldChecks) { 13536 const fn = this.equalityFieldChecks[field]; 13537 return fn(value1, value2); 13538 } 13539 throw new Error( 13540 `No equality check implemented for awareness state field "$field.toString()}".` 13541 ); 13542 } 13543 /** 13544 * Determine if two states are equal by comparing each field using the 13545 * provided equality checks. 13546 * @param state1 - The first state to compare. 13547 * @param state2 - The second state to compare. 13548 */ 13549 isStateEqual(state1, state2) { 13550 return [ 13551 .../* @__PURE__ */ new Set([ 13552 ...getTypedKeys(state1), 13553 ...getTypedKeys(state2) 13554 ]) 13555 ].every((field) => { 13556 const value1 = state1[field]; 13557 const value2 = state2[field]; 13558 return this.isFieldEqual(field, value1, value2); 13559 }); 13560 } 13561 }; 13562 var AwarenessState = class extends AwarenessWithEqualityChecks { 13563 /** CUSTOM PROPERTIES */ 13564 /** 13565 * Whether the setUp method has been called, to avoid running it multiple 13566 * times. 13567 */ 13568 hasSetupRun = false; 13569 /** 13570 * We keep track of all seen states during the current session for two reasons: 13571 * 13572 * 1. So that we can represent recently disconnected collaborators in our UI, even 13573 * after they have been removed from the awareness document. 13574 * 2. So that we can provide debug information about all collaborators seen during 13575 * the session. 13576 */ 13577 disconnectedCollaborators = /* @__PURE__ */ new Set(); 13578 seenStates = /* @__PURE__ */ new Map(); 13579 /** 13580 * Hold a snapshot of the previous awareness state allows us to compare the 13581 * state values and avoid unnecessary updates to subscribers. 13582 */ 13583 previousSnapshot = /* @__PURE__ */ new Map(); 13584 stateSubscriptions = []; 13585 /** 13586 * In some cases, we may want to throttle setting local state fields to avoid 13587 * overwhelming the awareness document with rapid updates. At the same time, we 13588 * want to ensure that when we read our own state locally, we get the latest 13589 * value -- even if it hasn't yet been set on the awareness instance. 13590 */ 13591 myThrottledState = {}; 13592 throttleTimeouts = /* @__PURE__ */ new Map(); 13593 /** CUSTOM METHODS */ 13594 /** 13595 * Set up the awareness state. This method is idempotent and will only run 13596 * once. Subclasses should override `onSetUp()` instead of this method to 13597 * add their own setup logic. 13598 * 13599 * This is defined as a readonly arrow function property to prevent 13600 * subclasses from overriding it. 13601 */ 13602 setUp = () => { 13603 if (this.hasSetupRun) { 13604 return; 13605 } 13606 this.hasSetupRun = true; 13607 this.onSetUp(); 13608 this.on( 13609 "change", 13610 ({ added, removed, updated }) => { 13611 [...added, ...updated].forEach((id2) => { 13612 this.disconnectedCollaborators.delete(id2); 13613 }); 13614 removed.forEach((id2) => { 13615 this.disconnectedCollaborators.add(id2); 13616 setTimeout(() => { 13617 this.disconnectedCollaborators.delete(id2); 13618 this.updateSubscribers( 13619 true 13620 /* force update */ 13621 ); 13622 }, REMOVAL_DELAY_IN_MS); 13623 }); 13624 this.updateSubscribers(); 13625 } 13626 ); 13627 }; 13628 /** 13629 * Get the most recent state from the last processed change event. 13630 * 13631 * @return An array of EnhancedState< State >. 13632 */ 13633 getCurrentState() { 13634 return Array.from(this.previousSnapshot.values()); 13635 } 13636 /** 13637 * Get all seen states in this session to enable debug reporting. 13638 */ 13639 getSeenStates() { 13640 return this.seenStates; 13641 } 13642 /** 13643 * Allow external code to subscribe to awareness state changes. 13644 * @param callback - The callback to subscribe to. 13645 */ 13646 onStateChange(callback) { 13647 this.stateSubscriptions.push(callback); 13648 return () => { 13649 this.stateSubscriptions = this.stateSubscriptions.filter( 13650 (cb) => cb !== callback 13651 ); 13652 }; 13653 } 13654 /** 13655 * Set a local state field on an awareness document with throttle. See caveats 13656 * of this.setLocalStateField. 13657 * @param field - The field to set. 13658 * @param value - The value to set. 13659 * @param wait - The wait time in milliseconds. 13660 */ 13661 setThrottledLocalStateField(field, value, wait) { 13662 this.setLocalStateField(field, value); 13663 this.throttleTimeouts.set( 13664 field, 13665 setTimeout(() => { 13666 this.throttleTimeouts.delete(field); 13667 if (this.myThrottledState[field]) { 13668 this.setLocalStateField( 13669 field, 13670 this.myThrottledState[field] 13671 ); 13672 delete this.myThrottledState[field]; 13673 } 13674 }, wait) 13675 ); 13676 } 13677 /** 13678 * Set the current collaborator's connection status as awareness state. 13679 * @param isConnected - The connection status. 13680 */ 13681 setConnectionStatus(isConnected) { 13682 if (isConnected) { 13683 this.disconnectedCollaborators.delete(this.clientID); 13684 } else { 13685 this.disconnectedCollaborators.add(this.clientID); 13686 } 13687 this.updateSubscribers( 13688 true 13689 /* force update */ 13690 ); 13691 } 13692 /** 13693 * Update all subscribed listeners with the latest awareness state. 13694 * @param forceUpdate - Whether to force an update. 13695 */ 13696 updateSubscribers(forceUpdate = false) { 13697 if (!this.stateSubscriptions.length) { 13698 return; 13699 } 13700 const states = this.getStates(); 13701 this.seenStates = new Map([ 13702 ...this.seenStates.entries(), 13703 ...states.entries() 13704 ]); 13705 const updatedStates = new Map( 13706 [...this.disconnectedCollaborators, ...states.keys()].filter((clientId) => { 13707 return Object.keys(this.seenStates.get(clientId) ?? {}).length > 0; 13708 }).map((clientId) => { 13709 const rawState = this.seenStates.get(clientId); 13710 const isConnected = !this.disconnectedCollaborators.has(clientId); 13711 const isMe = clientId === this.clientID; 13712 const myState = isMe ? this.myThrottledState : {}; 13713 const state = { 13714 ...rawState, 13715 ...myState, 13716 clientId, 13717 isConnected, 13718 isMe 13719 }; 13720 return [clientId, state]; 13721 }) 13722 ); 13723 if (!forceUpdate) { 13724 if (areMapsEqual( 13725 this.previousSnapshot, 13726 updatedStates, 13727 this.isStateEqual.bind(this) 13728 )) { 13729 return; 13730 } 13731 } 13732 this.previousSnapshot = updatedStates; 13733 this.stateSubscriptions.forEach((callback) => { 13734 callback(Array.from(updatedStates.values())); 13735 }); 13736 } 13737 }; 13738 13739 // packages/core-data/build-module/name.mjs 13740 var STORE_NAME = "core"; 13741 13742 // packages/core-data/build-module/awareness/base-awareness.mjs 13743 var BaseAwarenessState = class extends AwarenessState { 13744 onSetUp() { 13745 void this.setCurrentCollaboratorInfo(); 13746 } 13747 /** 13748 * Set the current collaborator info in the local state. 13749 */ 13750 async setCurrentCollaboratorInfo() { 13751 let currentUser2; 13752 try { 13753 currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser(); 13754 } catch { 13755 } 13756 this.setLocalStateField( 13757 "collaboratorInfo", 13758 generateCollaboratorInfo(currentUser2, this.clientID) 13759 ); 13760 } 13761 }; 13762 var baseEqualityFieldChecks = { 13763 collaboratorInfo: areCollaboratorInfosEqual 13764 }; 13765 var BaseAwareness = class extends BaseAwarenessState { 13766 equalityFieldChecks = baseEqualityFieldChecks; 13767 }; 13768 13769 // packages/core-data/build-module/awareness/block-lookup.mjs 13770 var import_data2 = __toESM(require_data(), 1); 13771 var import_block_editor = __toESM(require_block_editor(), 1); 13772 13773 // packages/core-data/build-module/lock-unlock.mjs 13774 var import_private_apis = __toESM(require_private_apis(), 1); 13775 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)( 13776 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.", 13777 "@wordpress/core-data" 13778 ); 13779 13780 // packages/core-data/build-module/awareness/block-lookup.mjs 13781 function getContainingBlockYMap(yType) { 13782 let current = yType; 13783 while (current) { 13784 const parent = current.parent; 13785 if (parent instanceof yjs_exports.Map && parent.parent instanceof yjs_exports.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof yjs_exports.Array) { 13786 return parent; 13787 } 13788 current = parent instanceof yjs_exports.AbstractType ? parent : null; 13789 } 13790 return null; 13791 } 13792 function getBlockPathInYdoc(yType) { 13793 const path = []; 13794 let current = yType; 13795 while (current) { 13796 const parentArray = current.parent; 13797 if (!parentArray || !(parentArray instanceof yjs_exports.Array)) { 13798 return null; 13799 } 13800 let index = -1; 13801 for (let i = 0; i < parentArray.length; i++) { 13802 if (parentArray.get(i) === current) { 13803 index = i; 13804 break; 13805 } 13806 } 13807 if (index === -1) { 13808 return null; 13809 } 13810 path.unshift(index); 13811 const grandparent = parentArray.parent; 13812 if (grandparent instanceof yjs_exports.Map && grandparent.get("clientId") !== void 0) { 13813 current = grandparent; 13814 } else { 13815 break; 13816 } 13817 } 13818 return path; 13819 } 13820 function resolveBlockClientIdByPath(path, blocks) { 13821 if (path.length === 0) { 13822 return null; 13823 } 13824 for (let i = 0; i < path.length; i++) { 13825 const block = blocks[path[i]]; 13826 if (!block) { 13827 return null; 13828 } 13829 if (i === path.length - 1) { 13830 return block.clientId; 13831 } 13832 blocks = block.innerBlocks; 13833 } 13834 return null; 13835 } 13836 function usePostContentBlocks() { 13837 return (0, import_data2.useSelect)((select6) => { 13838 const { getBlocksByName, getClientIdsTree } = unlock( 13839 select6(import_block_editor.store) 13840 ); 13841 const [postContentClientId] = getBlocksByName("core/post-content"); 13842 return getClientIdsTree(postContentClientId ?? ""); 13843 }, []); 13844 } 13845 13846 // packages/core-data/build-module/utils/crdt-utils.mjs 13847 var import_rich_text = __toESM(require_rich_text(), 1); 13848 function getRootMap(doc2, key) { 13849 return doc2.getMap(key); 13850 } 13851 function createYMap(partial = {}) { 13852 return new yjs_exports.Map(Object.entries(partial)); 13853 } 13854 function isYMap(value) { 13855 return value instanceof yjs_exports.Map; 13856 } 13857 function asRichTextOffset(offset) { 13858 return offset; 13859 } 13860 function asHtmlStringIndex(index) { 13861 return index; 13862 } 13863 function getYTextByAttributeKey(attributes, attributeKey) { 13864 const directValue = attributes.get(attributeKey); 13865 if (directValue instanceof yjs_exports.Text) { 13866 return directValue; 13867 } 13868 let value = attributes; 13869 for (const pathPart of attributeKey.split(".")) { 13870 if (value instanceof yjs_exports.Map) { 13871 value = value.get(pathPart); 13872 } else if (value instanceof yjs_exports.Array) { 13873 const index = Number.parseInt(pathPart, 10); 13874 if (!Number.isSafeInteger(index) || index < 0 || index.toString() !== pathPart) { 13875 return null; 13876 } 13877 value = value.get(index); 13878 } else { 13879 return null; 13880 } 13881 } 13882 return value instanceof yjs_exports.Text ? value : null; 13883 } 13884 function findBlockByClientIdInDoc(blockId, ydoc) { 13885 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY); 13886 const blocks = ymap.get("blocks"); 13887 if (!(blocks instanceof yjs_exports.Array)) { 13888 return null; 13889 } 13890 return findBlockByClientIdInBlocks(blockId, blocks); 13891 } 13892 var MARKER_START = 57344; 13893 function pickMarker(text2) { 13894 const tryCount = 16; 13895 for (let code = MARKER_START; code < MARKER_START + tryCount; code++) { 13896 const candidate = String.fromCharCode(code); 13897 if (!text2.includes(candidate)) { 13898 return candidate; 13899 } 13900 } 13901 return null; 13902 } 13903 function htmlIndexToRichTextOffset(html, htmlIndex) { 13904 if (!html.includes("<") && !html.includes("&")) { 13905 return asRichTextOffset(htmlIndex); 13906 } 13907 const marker = pickMarker(html); 13908 if (!marker) { 13909 return asRichTextOffset(htmlIndex); 13910 } 13911 const withMarker = html.slice(0, htmlIndex) + marker + html.slice(htmlIndex); 13912 const value = (0, import_rich_text.create)({ html: withMarker }); 13913 const markerPos = value.text.indexOf(marker); 13914 return asRichTextOffset(markerPos === -1 ? htmlIndex : markerPos); 13915 } 13916 function richTextOffsetToHtmlIndex(html, richTextOffset) { 13917 if (!html.includes("<") && !html.includes("&")) { 13918 return asHtmlStringIndex(richTextOffset); 13919 } 13920 const marker = pickMarker(html); 13921 if (!marker) { 13922 return asHtmlStringIndex(richTextOffset); 13923 } 13924 const value = (0, import_rich_text.create)({ html }); 13925 const markerValue = (0, import_rich_text.create)({ text: marker }); 13926 if (value.formats[richTextOffset]) { 13927 markerValue.formats[0] = value.formats[richTextOffset]; 13928 } 13929 const withMarker = (0, import_rich_text.insert)( 13930 value, 13931 markerValue, 13932 richTextOffset, 13933 richTextOffset 13934 ); 13935 const htmlWithMarker = (0, import_rich_text.toHTMLString)({ value: withMarker }); 13936 const markerIndex = htmlWithMarker.indexOf(marker); 13937 return asHtmlStringIndex( 13938 markerIndex === -1 ? richTextOffset : markerIndex 13939 ); 13940 } 13941 function findBlockByClientIdInBlocks(blockId, blocks) { 13942 for (const block of blocks) { 13943 if (block.get("clientId") === blockId) { 13944 return block; 13945 } 13946 const innerBlocks = block.get("innerBlocks"); 13947 if (innerBlocks && innerBlocks.length > 0) { 13948 const innerBlock = findBlockByClientIdInBlocks( 13949 blockId, 13950 innerBlocks 13951 ); 13952 if (innerBlock) { 13953 return innerBlock; 13954 } 13955 } 13956 } 13957 return null; 13958 } 13959 13960 // packages/core-data/build-module/utils/crdt-user-selections.mjs 13961 var import_data3 = __toESM(require_data(), 1); 13962 var import_block_editor2 = __toESM(require_block_editor(), 1); 13963 var SelectionType = /* @__PURE__ */ ((SelectionType2) => { 13964 SelectionType2["None"] = "none"; 13965 SelectionType2["Cursor"] = "cursor"; 13966 SelectionType2["SelectionInOneBlock"] = "selection-in-one-block"; 13967 SelectionType2["SelectionInMultipleBlocks"] = "selection-in-multiple-blocks"; 13968 SelectionType2["WholeBlock"] = "whole-block"; 13969 return SelectionType2; 13970 })(SelectionType || {}); 13971 var SelectionDirection = /* @__PURE__ */ ((SelectionDirection2) => { 13972 SelectionDirection2["Forward"] = "f"; 13973 SelectionDirection2["Backward"] = "b"; 13974 return SelectionDirection2; 13975 })(SelectionDirection || {}); 13976 function getSelectionState(selectionStart, selectionEnd, yDoc, options) { 13977 const { selectionDirection } = options ?? {}; 13978 const ymap = getRootMap(yDoc, CRDT_RECORD_MAP_KEY); 13979 const yBlocks = ymap.get("blocks"); 13980 const isSelectionEmpty = Object.keys(selectionStart).length === 0; 13981 const noSelection = { 13982 type: "none" 13983 /* None */ 13984 }; 13985 if (isSelectionEmpty || !yBlocks) { 13986 return noSelection; 13987 } 13988 const isSelectionInOneBlock = selectionStart.clientId === selectionEnd.clientId; 13989 const isCursorOnly = isSelectionInOneBlock && selectionStart.offset === selectionEnd.offset; 13990 const isSelectionAWholeBlock = isSelectionInOneBlock && selectionStart.offset === void 0 && selectionEnd.offset === void 0; 13991 if (isSelectionAWholeBlock) { 13992 const path = getBlockPathForLocalClientId(selectionStart.clientId); 13993 const blockPosition = path ? createRelativePositionForBlockPath(path, yBlocks) : null; 13994 if (!blockPosition) { 13995 return noSelection; 13996 } 13997 return { 13998 type: "whole-block", 13999 blockPosition 14000 }; 14001 } else if (isCursorOnly) { 14002 const cursorPosition = getCursorPosition(selectionStart, yBlocks); 14003 if (!cursorPosition) { 14004 return noSelection; 14005 } 14006 return { 14007 type: "cursor", 14008 cursorPosition 14009 }; 14010 } else if (isSelectionInOneBlock) { 14011 const cursorStartPosition = getCursorPosition( 14012 selectionStart, 14013 yBlocks 14014 ); 14015 const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks); 14016 if (!cursorStartPosition || !cursorEndPosition) { 14017 return noSelection; 14018 } 14019 return { 14020 type: "selection-in-one-block", 14021 cursorStartPosition, 14022 cursorEndPosition, 14023 selectionDirection 14024 }; 14025 } 14026 const startEndpoint = getSelectionEndpoint(selectionStart, yBlocks); 14027 const endEndpoint = getSelectionEndpoint(selectionEnd, yBlocks); 14028 if (!startEndpoint || !endEndpoint) { 14029 return noSelection; 14030 } 14031 return { 14032 type: "selection-in-multiple-blocks", 14033 startEndpoint, 14034 endEndpoint, 14035 selectionDirection 14036 }; 14037 } 14038 function getCursorPosition(selection, blocks) { 14039 const path = getBlockPathForLocalClientId(selection.clientId); 14040 const block = path ? findBlockByPath(path, blocks) : null; 14041 if (!block || !selection.attributeKey || void 0 === selection.offset) { 14042 return null; 14043 } 14044 const attributes = block.get("attributes"); 14045 const currentYText = attributes ? getYTextByAttributeKey(attributes, selection.attributeKey) : null; 14046 if (!(currentYText instanceof yjs_exports.Text)) { 14047 return null; 14048 } 14049 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex( 14050 currentYText, 14051 richTextOffsetToHtmlIndex( 14052 currentYText.toString(), 14053 asRichTextOffset(selection.offset) 14054 ) 14055 ); 14056 return { 14057 relativePosition, 14058 absoluteOffset: selection.offset, 14059 attributeKey: selection.attributeKey 14060 }; 14061 } 14062 function getSelectionEndpoint(selection, blocks) { 14063 const cursorPosition = getCursorPosition(selection, blocks); 14064 if (cursorPosition) { 14065 return { type: "cursor", cursorPosition }; 14066 } 14067 const path = getBlockPathForLocalClientId(selection.clientId); 14068 const blockPosition = path ? createRelativePositionForBlockPath(path, blocks) : null; 14069 if (blockPosition) { 14070 return { type: "whole-block", blockPosition }; 14071 } 14072 return null; 14073 } 14074 function getBlockPathForLocalClientId(clientId) { 14075 const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data3.select)(import_block_editor2.store); 14076 const path = []; 14077 let current = clientId; 14078 while (current) { 14079 const index = getBlockIndex(current); 14080 if (index === -1) { 14081 return null; 14082 } 14083 path.unshift(index); 14084 const parent = getBlockRootClientId(current); 14085 if (!parent) { 14086 break; 14087 } 14088 const parentName = getBlockName(parent); 14089 if (parentName === "core/post-content") { 14090 break; 14091 } 14092 current = parent; 14093 } 14094 return path.length > 0 ? path : null; 14095 } 14096 function findBlockByPath(path, blocks) { 14097 let currentBlocks = blocks; 14098 for (let i = 0; i < path.length; i++) { 14099 if (path[i] >= currentBlocks.length) { 14100 return null; 14101 } 14102 const block = currentBlocks.get(path[i]); 14103 if (!block) { 14104 return null; 14105 } 14106 if (i === path.length - 1) { 14107 return block; 14108 } 14109 currentBlocks = block.get("innerBlocks") ?? new yjs_exports.Array(); 14110 } 14111 return null; 14112 } 14113 function createRelativePositionForBlockPath(path, blocks) { 14114 let currentBlocks = blocks; 14115 for (let i = 0; i < path.length; i++) { 14116 if (path[i] >= currentBlocks.length) { 14117 return null; 14118 } 14119 if (i === path.length - 1) { 14120 return yjs_exports.createRelativePositionFromTypeIndex( 14121 currentBlocks, 14122 path[i] 14123 ); 14124 } 14125 const block = currentBlocks.get(path[i]); 14126 currentBlocks = block?.get("innerBlocks") ?? new yjs_exports.Array(); 14127 } 14128 return null; 14129 } 14130 function areSelectionsStatesEqual(selection1, selection2) { 14131 if (selection1.type !== selection2.type) { 14132 return false; 14133 } 14134 switch (selection1.type) { 14135 case "none": 14136 return true; 14137 case "cursor": 14138 return areCursorPositionsEqual( 14139 selection1.cursorPosition, 14140 selection2.cursorPosition 14141 ); 14142 case "selection-in-one-block": 14143 return areCursorPositionsEqual( 14144 selection1.cursorStartPosition, 14145 selection2.cursorStartPosition 14146 ) && areCursorPositionsEqual( 14147 selection1.cursorEndPosition, 14148 selection2.cursorEndPosition 14149 ) && selection1.selectionDirection === selection2.selectionDirection; 14150 case "selection-in-multiple-blocks": 14151 return areEndpointsEqual( 14152 selection1.startEndpoint, 14153 selection2.startEndpoint 14154 ) && areEndpointsEqual( 14155 selection1.endEndpoint, 14156 selection2.endEndpoint 14157 ) && selection1.selectionDirection === selection2.selectionDirection; 14158 case "whole-block": 14159 return yjs_exports.compareRelativePositions( 14160 selection1.blockPosition, 14161 selection2.blockPosition 14162 ); 14163 default: 14164 return false; 14165 } 14166 } 14167 function areEndpointsEqual(ep1, ep2) { 14168 if (ep1.type !== ep2.type) { 14169 return false; 14170 } 14171 if (ep1.type === "cursor" && ep2.type === "cursor") { 14172 return areCursorPositionsEqual( 14173 ep1.cursorPosition, 14174 ep2.cursorPosition 14175 ); 14176 } 14177 return yjs_exports.compareRelativePositions( 14178 ep1.blockPosition, 14179 ep2.blockPosition 14180 ); 14181 } 14182 function areCursorPositionsEqual(cursorPosition1, cursorPosition2) { 14183 const isRelativePositionEqual = yjs_exports.compareRelativePositions( 14184 cursorPosition1.relativePosition, 14185 cursorPosition2.relativePosition 14186 ); 14187 const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset; 14188 return isRelativePositionEqual && isAbsoluteOffsetEqual; 14189 } 14190 14191 // packages/core-data/build-module/awareness/post-editor-awareness.mjs 14192 var PostEditorAwareness = class extends BaseAwarenessState { 14193 constructor(doc2, kind, name, postId) { 14194 super(doc2); 14195 this.kind = kind; 14196 this.name = name; 14197 this.postId = postId; 14198 } 14199 equalityFieldChecks = { 14200 ...baseEqualityFieldChecks, 14201 editorState: this.areEditorStatesEqual 14202 }; 14203 onSetUp() { 14204 super.onSetUp(); 14205 this.subscribeToCollaboratorSelectionChanges(); 14206 } 14207 /** 14208 * Subscribe to collaborator selection changes and update the selection state. 14209 */ 14210 subscribeToCollaboratorSelectionChanges() { 14211 const { 14212 getSelectionStart, 14213 getSelectionEnd, 14214 getSelectedBlocksInitialCaretPosition 14215 } = (0, import_data4.select)(import_block_editor3.store); 14216 let selectionStart = getSelectionStart(); 14217 let selectionEnd = getSelectionEnd(); 14218 let localCursorTimeout = null; 14219 let selectionBeforeDebounce = null; 14220 (0, import_data4.subscribe)(() => { 14221 const newSelectionStart = getSelectionStart(); 14222 const newSelectionEnd = getSelectionEnd(); 14223 if (newSelectionStart === selectionStart && newSelectionEnd === selectionEnd) { 14224 return; 14225 } 14226 if (!selectionBeforeDebounce) { 14227 selectionBeforeDebounce = { 14228 start: selectionStart, 14229 end: selectionEnd 14230 }; 14231 } 14232 selectionStart = newSelectionStart; 14233 selectionEnd = newSelectionEnd; 14234 const initialPosition = getSelectedBlocksInitialCaretPosition(); 14235 void this.updateSelectionInEntityRecord( 14236 selectionStart, 14237 selectionEnd, 14238 initialPosition 14239 ); 14240 if (localCursorTimeout) { 14241 clearTimeout(localCursorTimeout); 14242 } 14243 localCursorTimeout = setTimeout(() => { 14244 const selectionStateOptions = {}; 14245 if (selectionBeforeDebounce) { 14246 selectionStateOptions.selectionDirection = detectSelectionDirection( 14247 selectionBeforeDebounce.start, 14248 selectionBeforeDebounce.end, 14249 selectionStart, 14250 selectionEnd 14251 ); 14252 selectionBeforeDebounce = null; 14253 } 14254 const selectionState = getSelectionState( 14255 selectionStart, 14256 selectionEnd, 14257 this.doc, 14258 selectionStateOptions 14259 ); 14260 this.setThrottledLocalStateField( 14261 "editorState", 14262 { selection: selectionState }, 14263 AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS 14264 ); 14265 }, LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS); 14266 }); 14267 } 14268 /** 14269 * Update the entity record with the current collaborator's selection. 14270 * 14271 * @param selectionStart - The start position of the selection. 14272 * @param selectionEnd - The end position of the selection. 14273 * @param initialPosition - The initial position of the selection. 14274 */ 14275 async updateSelectionInEntityRecord(selectionStart, selectionEnd, initialPosition) { 14276 const edits = { 14277 selection: { selectionStart, selectionEnd, initialPosition } 14278 }; 14279 const options = { 14280 undoIgnore: true 14281 }; 14282 (0, import_data4.dispatch)(STORE_NAME).editEntityRecord( 14283 this.kind, 14284 this.name, 14285 this.postId, 14286 edits, 14287 options 14288 ); 14289 } 14290 /** 14291 * Check if two editor states are equal. 14292 * 14293 * @param state1 - The first editor state. 14294 * @param state2 - The second editor state. 14295 * @return True if the editor states are equal, false otherwise. 14296 */ 14297 areEditorStatesEqual(state1, state2) { 14298 if (!state1 || !state2) { 14299 return state1 === state2; 14300 } 14301 if (!state1.selection || !state2.selection) { 14302 return state1.selection === state2.selection; 14303 } 14304 return areSelectionsStatesEqual(state1.selection, state2.selection); 14305 } 14306 /** 14307 * Resolve a selection state to a text index and block client ID. 14308 * 14309 * For text-based selections, navigates up from the resolved Y.Text via 14310 * AbstractType.parent to find the containing block, then resolves the 14311 * local clientId via the block's tree path. 14312 * For WholeBlock selections, resolves the block's relative position and 14313 * then finds the local clientId via tree path. 14314 * 14315 * Tree-path resolution is used instead of reading the clientId directly 14316 * from the Yjs block because the local block-editor store may use different 14317 * clientIds (e.g. in "Show Template" mode where blocks are cloned). 14318 * 14319 * @param selection - The selection state. 14320 * @param blocks - The tree of block-editor store post content blocks. 14321 * @return The rich-text offset and block client ID, or nulls if not resolvable. 14322 */ 14323 convertSelectionStateToAbsolute(selection, blocks) { 14324 if (selection.type === SelectionType.None) { 14325 return { 14326 richTextOffset: null, 14327 localClientId: null, 14328 attributeKey: null 14329 }; 14330 } 14331 if (selection.type === SelectionType.WholeBlock) { 14332 const absolutePos = yjs_exports.createAbsolutePositionFromRelativePosition( 14333 selection.blockPosition, 14334 this.doc 14335 ); 14336 let localClientId2 = null; 14337 if (absolutePos && absolutePos.type instanceof yjs_exports.Array) { 14338 const parentArray = absolutePos.type; 14339 const block = parentArray.get(absolutePos.index); 14340 if (block instanceof yjs_exports.Map) { 14341 const path2 = getBlockPathInYdoc(block); 14342 localClientId2 = path2 ? resolveBlockClientIdByPath(path2, blocks) : null; 14343 } 14344 } 14345 return { 14346 richTextOffset: null, 14347 localClientId: localClientId2, 14348 attributeKey: null 14349 }; 14350 } 14351 if (selection.type === SelectionType.SelectionInMultipleBlocks) { 14352 return { 14353 richTextOffset: null, 14354 localClientId: null, 14355 attributeKey: null 14356 }; 14357 } 14358 const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition; 14359 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition( 14360 cursorPos.relativePosition, 14361 this.doc 14362 ); 14363 if (!absolutePosition) { 14364 return { 14365 richTextOffset: null, 14366 localClientId: null, 14367 attributeKey: null 14368 }; 14369 } 14370 const yType = getContainingBlockYMap(absolutePosition.type); 14371 const path = yType ? getBlockPathInYdoc(yType) : null; 14372 const localClientId = path ? resolveBlockClientIdByPath(path, blocks) : null; 14373 return { 14374 richTextOffset: htmlIndexToRichTextOffset( 14375 absolutePosition.type.toString(), 14376 asHtmlStringIndex(absolutePosition.index) 14377 ), 14378 localClientId, 14379 attributeKey: cursorPos.attributeKey ?? null 14380 }; 14381 } 14382 /** 14383 * Type guard to check if a struct is a Y.Item (not Y.GC) 14384 * @param struct - The struct to check. 14385 * @return True if the struct is a Y.Item, false otherwise. 14386 */ 14387 isYItem(struct) { 14388 return "content" in struct; 14389 } 14390 /** 14391 * Get data for debugging, using the awareness state. 14392 * 14393 * @return {YDocDebugData} The debug data. 14394 */ 14395 getDebugData() { 14396 const ydoc = this.doc; 14397 const docData = Object.fromEntries( 14398 Array.from(ydoc.share, ([key, value]) => [ 14399 key, 14400 value.toJSON() 14401 ]) 14402 ); 14403 const collaboratorMapData = new Map( 14404 Array.from(this.getSeenStates().entries()).filter( 14405 ([, collaboratorState]) => isCollaboratorInfo(collaboratorState.collaboratorInfo) 14406 ).map(([clientId, collaboratorState]) => [ 14407 String(clientId), 14408 { 14409 name: collaboratorState.collaboratorInfo.name, 14410 wpUserId: collaboratorState.collaboratorInfo.id 14411 } 14412 ]) 14413 ); 14414 const serializableClientItems = {}; 14415 ydoc.store.clients.forEach((structs, clientId) => { 14416 const items2 = structs.filter(this.isYItem); 14417 serializableClientItems[clientId] = items2.map((item) => { 14418 const { left, right, ...rest } = item; 14419 return { 14420 ...rest, 14421 left: left ? { 14422 id: left.id, 14423 length: left.length, 14424 origin: left.origin, 14425 content: left.content 14426 } : null, 14427 right: right ? { 14428 id: right.id, 14429 length: right.length, 14430 origin: right.origin, 14431 content: right.content 14432 } : null 14433 }; 14434 }); 14435 }); 14436 return { 14437 doc: docData, 14438 clients: serializableClientItems, 14439 collaboratorMap: Object.fromEntries(collaboratorMapData) 14440 }; 14441 } 14442 }; 14443 function detectSelectionDirection(prevStart, prevEnd, newStart, newEnd) { 14444 const startMoved = !areBlockSelectionsEqual(prevStart, newStart); 14445 const endMoved = !areBlockSelectionsEqual(prevEnd, newEnd); 14446 if (startMoved && !endMoved) { 14447 return SelectionDirection.Backward; 14448 } 14449 return SelectionDirection.Forward; 14450 } 14451 function areBlockSelectionsEqual(a, b) { 14452 return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset; 14453 } 14454 14455 // packages/core-data/build-module/utils/crdt.mjs 14456 var import_es66 = __toESM(require_es6(), 1); 14457 var import_blocks3 = __toESM(require_blocks(), 1); 14458 14459 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/stringify.js 14460 var byteToHex = []; 14461 for (let i = 0; i < 256; ++i) { 14462 byteToHex.push((i + 256).toString(16).slice(1)); 14463 } 14464 function unsafeStringify(arr, offset = 0) { 14465 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(); 14466 } 14467 14468 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/rng.js 14469 var rnds8 = new Uint8Array(16); 14470 function rng() { 14471 return crypto.getRandomValues(rnds8); 14472 } 14473 14474 // node_modules/.store/uuid@14.0.2-ALlTd6-Rf9bZs703d7TIjQ/node_modules/uuid/dist/v4.js 14475 function v4(options, buf, offset) { 14476 if (!buf && !options && crypto.randomUUID) { 14477 return crypto.randomUUID(); 14478 } 14479 return _v4(options, buf, offset); 14480 } 14481 function _v4(options, buf, offset) { 14482 options = options || {}; 14483 const rnds = options.random ?? options.rng?.() ?? rng(); 14484 if (rnds.length < 16) { 14485 throw new Error("Random bytes length must be >= 16"); 14486 } 14487 rnds[6] = rnds[6] & 15 | 64; 14488 rnds[8] = rnds[8] & 63 | 128; 14489 if (buf) { 14490 offset = offset || 0; 14491 if (offset < 0 || offset + 16 > buf.length) { 14492 throw new RangeError(`UUID byte range $offset}:$offset + 15} is out of buffer bounds`); 14493 } 14494 for (let i = 0; i < 16; ++i) { 14495 buf[offset + i] = rnds[i]; 14496 } 14497 return buf; 14498 } 14499 return unsafeStringify(rnds); 14500 } 14501 var v4_default = v4; 14502 14503 // packages/core-data/build-module/utils/crdt-blocks.mjs 14504 var import_es65 = __toESM(require_es6(), 1); 14505 var import_blocks = __toESM(require_blocks(), 1); 14506 var import_rich_text3 = __toESM(require_rich_text(), 1); 14507 14508 // packages/core-data/build-module/utils/crdt-text.mjs 14509 var import_rich_text2 = __toESM(require_rich_text(), 1); 14510 var RICH_TEXT_CACHE_MAX_SIZE = 500; 14511 function createRichTextDataCache(maxSize) { 14512 const cache3 = /* @__PURE__ */ new Map(); 14513 return function(value) { 14514 const cached = cache3.get(value); 14515 if (cached) { 14516 return cached; 14517 } 14518 const result = import_rich_text2.RichTextData.fromHTMLString(value); 14519 if (cache3.size >= maxSize) { 14520 cache3.delete(cache3.keys().next().value); 14521 } 14522 cache3.set(value, result); 14523 return result; 14524 }; 14525 } 14526 var getCachedRichTextData = createRichTextDataCache( 14527 RICH_TEXT_CACHE_MAX_SIZE 14528 ); 14529 14530 // packages/core-data/build-module/utils/crdt-blocks.mjs 14531 var serializableBlocksCache = /* @__PURE__ */ new WeakMap(); 14532 function serializeAttributeValue(value) { 14533 if (value instanceof import_rich_text3.RichTextData) { 14534 return value.valueOf(); 14535 } 14536 if (Array.isArray(value)) { 14537 return value.map(serializeAttributeValue); 14538 } 14539 if (value && typeof value === "object") { 14540 const result = {}; 14541 for (const [k, v] of Object.entries(value)) { 14542 result[k] = serializeAttributeValue(v); 14543 } 14544 return result; 14545 } 14546 return value; 14547 } 14548 function makeBlockAttributesSerializable(blockName, attributes) { 14549 const newAttributes = { ...attributes }; 14550 for (const [key, value] of Object.entries(attributes)) { 14551 if (isLocalAttribute(blockName, key)) { 14552 delete newAttributes[key]; 14553 continue; 14554 } 14555 newAttributes[key] = serializeAttributeValue(value); 14556 } 14557 return newAttributes; 14558 } 14559 function makeBlocksSerializable(blocks) { 14560 return blocks.map((block) => { 14561 const { 14562 name, 14563 innerBlocks, 14564 attributes, 14565 /* 14566 * Any validation issues discovered when loading a block are appended 14567 * to the block node with a logging function, which cannot be serialized. 14568 * 14569 * @see import("@wordpress/blocks/src/api/parser").parseRawBlock() 14570 */ 14571 validationIssues, 14572 ...rest 14573 } = block; 14574 return { 14575 ...rest, 14576 name, 14577 attributes: makeBlockAttributesSerializable(name, attributes), 14578 innerBlocks: makeBlocksSerializable(innerBlocks) 14579 }; 14580 }); 14581 } 14582 function deserializeAttributeValue(schema, value) { 14583 if (schema?.type === "rich-text" && typeof value === "string") { 14584 return getCachedRichTextData(value); 14585 } 14586 if (Array.isArray(value)) { 14587 return value.map( 14588 (item) => deserializeAttributeValue(schema, item) 14589 ); 14590 } 14591 if (value && typeof value === "object") { 14592 const result = {}; 14593 for (const [key, innerValue] of Object.entries( 14594 value 14595 )) { 14596 result[key] = deserializeAttributeValue( 14597 schema?.query?.[key], 14598 innerValue 14599 ); 14600 } 14601 return result; 14602 } 14603 return value; 14604 } 14605 function deserializeBlockAttributes(blocks) { 14606 return blocks.map((block) => { 14607 const { name, innerBlocks, attributes, ...rest } = block; 14608 const newAttributes = { ...attributes }; 14609 for (const [key, value] of Object.entries(attributes)) { 14610 const schema = getBlockAttributeSchema(name, key); 14611 if (schema) { 14612 newAttributes[key] = deserializeAttributeValue( 14613 schema, 14614 value 14615 ); 14616 } 14617 } 14618 return { 14619 ...rest, 14620 name, 14621 attributes: newAttributes, 14622 innerBlocks: deserializeBlockAttributes(innerBlocks ?? []) 14623 }; 14624 }); 14625 } 14626 function areBlocksEqual(gblock, yblock) { 14627 const yblockAsJson = yblock.toJSON(); 14628 const overwrites = { 14629 innerBlocks: null, 14630 clientId: null 14631 }; 14632 const res = (0, import_es65.default)( 14633 Object.assign({}, gblock, overwrites), 14634 Object.assign({}, yblockAsJson, overwrites) 14635 ); 14636 const inners = gblock.innerBlocks || []; 14637 const yinners = yblock.get("innerBlocks"); 14638 return res && inners.length === yinners?.length && inners.every( 14639 (block, i) => areBlocksEqual(block, yinners.get(i)) 14640 ); 14641 } 14642 function createNewYAttributeMap(blockName, attributes) { 14643 return new yjs_exports.Map( 14644 Object.entries(attributes).map( 14645 ([attributeName, attributeValue]) => { 14646 return [ 14647 attributeName, 14648 createNewYAttributeValue( 14649 blockName, 14650 attributeName, 14651 attributeValue 14652 ) 14653 ]; 14654 } 14655 ) 14656 ); 14657 } 14658 function createNewYAttributeValue(blockName, attributeName, attributeValue) { 14659 const schema = getBlockAttributeSchema(blockName, attributeName); 14660 return createYValueFromSchema(schema, attributeValue); 14661 } 14662 function createYValueFromSchema(schema, value) { 14663 if (!schema) { 14664 return value; 14665 } 14666 if (schema.type === "rich-text") { 14667 return new yjs_exports.Text(value?.toString() ?? ""); 14668 } 14669 if (schema.type === "array" && schema.query && Array.isArray(value)) { 14670 const query = schema.query; 14671 const yArray = new yjs_exports.Array(); 14672 yArray.insert( 14673 0, 14674 value.map((item) => createYMapFromQuery(query, item)) 14675 ); 14676 return yArray; 14677 } 14678 if (schema.type === "object" && schema.query && isRecord(value)) { 14679 return createYMapFromQuery(schema.query, value); 14680 } 14681 return value; 14682 } 14683 function isRecord(value) { 14684 return !!value && typeof value === "object" && !Array.isArray(value); 14685 } 14686 function createYMapFromQuery(query, obj) { 14687 if (!isRecord(obj)) { 14688 return new yjs_exports.Map(); 14689 } 14690 const entries = Object.entries(obj).map( 14691 ([key, val]) => { 14692 const subSchema = query[key]; 14693 return [key, createYValueFromSchema(subSchema, val)]; 14694 } 14695 ); 14696 return new yjs_exports.Map(entries); 14697 } 14698 function createNewYBlock(block) { 14699 return createYMap( 14700 Object.fromEntries( 14701 Object.entries(block).map(([key, value]) => { 14702 switch (key) { 14703 case "attributes": { 14704 return [ 14705 key, 14706 createNewYAttributeMap(block.name, value) 14707 ]; 14708 } 14709 case "innerBlocks": { 14710 const innerBlocks = new yjs_exports.Array(); 14711 if (!Array.isArray(value)) { 14712 return [key, innerBlocks]; 14713 } 14714 innerBlocks.insert( 14715 0, 14716 value.map( 14717 (innerBlock) => createNewYBlock(innerBlock) 14718 ) 14719 ); 14720 return [key, innerBlocks]; 14721 } 14722 default: 14723 return [key, value]; 14724 } 14725 }) 14726 ) 14727 ); 14728 } 14729 function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor, options = {}) { 14730 if (!serializableBlocksCache.has(incomingBlocks)) { 14731 serializableBlocksCache.set( 14732 incomingBlocks, 14733 makeBlocksSerializable(incomingBlocks) 14734 ); 14735 } 14736 const incomingBlocksToSync = serializableBlocksCache.get(incomingBlocks) ?? []; 14737 const numOfCommonEntries = Math.min( 14738 incomingBlocksToSync.length ?? 0, 14739 yblocks.length 14740 ); 14741 let left = 0; 14742 let right = 0; 14743 for (; left < numOfCommonEntries && areBlocksEqual(incomingBlocksToSync[left], yblocks.get(left)); left++) { 14744 } 14745 for (; right < numOfCommonEntries - left && areBlocksEqual( 14746 incomingBlocksToSync[incomingBlocksToSync.length - right - 1], 14747 yblocks.get(yblocks.length - right - 1) 14748 ); right++) { 14749 } 14750 const numOfUpdatesNeeded = numOfCommonEntries - left - right; 14751 const numOfInsertionsNeeded = Math.max( 14752 0, 14753 incomingBlocksToSync.length - yblocks.length 14754 ); 14755 const numOfDeletionsNeeded = Math.max( 14756 0, 14757 yblocks.length - incomingBlocksToSync.length 14758 ); 14759 for (let i = 0; i < numOfUpdatesNeeded; i++, left++) { 14760 const incomingYBlock = incomingBlocksToSync[left]; 14761 const localYBlock = yblocks.get(left); 14762 Object.entries(incomingYBlock).forEach( 14763 ([incomingBlockProperty, incomingBlockPropertyValue]) => { 14764 switch (incomingBlockProperty) { 14765 case "attributes": { 14766 const localAttributes = localYBlock.get( 14767 incomingBlockProperty 14768 ); 14769 const incomingAttributes = incomingBlockPropertyValue; 14770 if (!localAttributes) { 14771 localYBlock.set( 14772 incomingBlockProperty, 14773 createNewYAttributeMap( 14774 incomingYBlock.name, 14775 incomingAttributes 14776 ) 14777 ); 14778 break; 14779 } 14780 Object.entries(incomingAttributes).forEach( 14781 ([ 14782 incomingAttributeName, 14783 incomingAttributeValue 14784 ]) => { 14785 const currentAttribute = localAttributes?.get( 14786 incomingAttributeName 14787 ); 14788 const isExpectedType = isExpectedAttributeType( 14789 incomingYBlock.name, 14790 incomingAttributeName, 14791 currentAttribute 14792 ); 14793 const isYType = currentAttribute instanceof yjs_exports.AbstractType; 14794 const isAttributeChanged = !isExpectedType || isYType || !(0, import_es65.default)( 14795 currentAttribute, 14796 incomingAttributeValue 14797 ); 14798 if (isAttributeChanged) { 14799 updateYBlockAttribute( 14800 incomingYBlock.name, 14801 incomingYBlock.clientId, 14802 incomingAttributeName, 14803 incomingAttributeValue, 14804 localAttributes, 14805 attributeCursor 14806 ); 14807 } 14808 } 14809 ); 14810 localAttributes.forEach( 14811 (_attrValue, attrName) => { 14812 if (!incomingBlockPropertyValue.hasOwnProperty( 14813 attrName 14814 )) { 14815 localAttributes.delete(attrName); 14816 } 14817 } 14818 ); 14819 break; 14820 } 14821 case "innerBlocks": { 14822 let yInnerBlocks = localYBlock.get( 14823 incomingBlockProperty 14824 ); 14825 if (!(yInnerBlocks instanceof yjs_exports.Array)) { 14826 yInnerBlocks = new yjs_exports.Array(); 14827 localYBlock.set( 14828 incomingBlockProperty, 14829 yInnerBlocks 14830 ); 14831 } 14832 mergeCrdtBlocks( 14833 yInnerBlocks, 14834 incomingBlockPropertyValue ?? [], 14835 attributeCursor, 14836 options 14837 ); 14838 break; 14839 } 14840 case "clientId": { 14841 if (options.preserveClientIds) { 14842 break; 14843 } 14844 if (incomingBlockPropertyValue !== localYBlock.get(incomingBlockProperty)) { 14845 localYBlock.set( 14846 incomingBlockProperty, 14847 incomingBlockPropertyValue 14848 ); 14849 } 14850 break; 14851 } 14852 default: 14853 if (!(0, import_es65.default)( 14854 incomingYBlock[incomingBlockProperty], 14855 localYBlock.get(incomingBlockProperty) 14856 )) { 14857 localYBlock.set( 14858 incomingBlockProperty, 14859 incomingBlockPropertyValue 14860 ); 14861 } 14862 } 14863 } 14864 ); 14865 localYBlock.forEach((_v, k) => { 14866 if (!incomingYBlock.hasOwnProperty(k)) { 14867 localYBlock.delete(k); 14868 } 14869 }); 14870 } 14871 yblocks.delete(left, numOfDeletionsNeeded); 14872 for (let i = 0; i < numOfInsertionsNeeded; i++, left++) { 14873 const newBlock = [createNewYBlock(incomingBlocksToSync[left])]; 14874 yblocks.insert(left, newBlock); 14875 } 14876 const knownClientIds = /* @__PURE__ */ new Set(); 14877 for (let j = 0; j < yblocks.length; j++) { 14878 const yblock = yblocks.get(j); 14879 let clientId = yblock.get("clientId"); 14880 if (!clientId) { 14881 continue; 14882 } 14883 if (knownClientIds.has(clientId)) { 14884 clientId = v4_default(); 14885 yblock.set("clientId", clientId); 14886 } 14887 knownClientIds.add(clientId); 14888 } 14889 } 14890 function areArrayElementsEqual(newElement, yElement) { 14891 if (yElement instanceof yjs_exports.Map && isRecord(newElement)) { 14892 return (0, import_es65.default)(newElement, yElement.toJSON()); 14893 } 14894 return (0, import_es65.default)(newElement, yElement); 14895 } 14896 function mergeYArray(yArray, newValue, schema, cursorPosition, cursorScope) { 14897 if (!schema.query) { 14898 return; 14899 } 14900 const query = schema.query; 14901 const numOfCommonEntries = Math.min(newValue.length, yArray.length); 14902 let left = 0; 14903 let right = 0; 14904 for (; left < numOfCommonEntries && areArrayElementsEqual(newValue[left], yArray.get(left)); left++) { 14905 } 14906 for (; right < numOfCommonEntries - left && areArrayElementsEqual( 14907 newValue[newValue.length - right - 1], 14908 yArray.get(yArray.length - right - 1) 14909 ); right++) { 14910 } 14911 const numOfUpdatesNeeded = numOfCommonEntries - left - right; 14912 for (let i = 0; i < numOfUpdatesNeeded; i++) { 14913 const currentElement = yArray.get(left + i); 14914 const newElement = newValue[left + i]; 14915 if (currentElement instanceof yjs_exports.Map && isRecord(newElement)) { 14916 mergeYMapValues( 14917 currentElement, 14918 newElement, 14919 query, 14920 cursorPosition, 14921 cursorScope 14922 ); 14923 } else { 14924 yArray.delete(0, yArray.length); 14925 yArray.insert( 14926 0, 14927 newValue.map((item) => createYMapFromQuery(query, item)) 14928 ); 14929 return; 14930 } 14931 } 14932 const numOfDeletionsNeeded = Math.max(0, yArray.length - newValue.length); 14933 if (numOfDeletionsNeeded > 0) { 14934 yArray.delete(left + numOfUpdatesNeeded, numOfDeletionsNeeded); 14935 } 14936 const numOfInsertionsNeeded = Math.max( 14937 0, 14938 newValue.length - yArray.length 14939 ); 14940 if (numOfInsertionsNeeded > 0) { 14941 const insertAt = left + numOfUpdatesNeeded; 14942 const itemsToInsert = new Array( 14943 numOfInsertionsNeeded 14944 ); 14945 for (let i = 0; i < numOfInsertionsNeeded; i++) { 14946 itemsToInsert[i] = createYMapFromQuery( 14947 query, 14948 newValue[insertAt + i] 14949 ); 14950 } 14951 yArray.insert(insertAt, itemsToInsert); 14952 } 14953 } 14954 function mergeYValue(schema, newVal, yMap, key, cursorPosition, cursorScope) { 14955 const currentVal = yMap.get(key); 14956 if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof yjs_exports.Text) { 14957 mergeRichTextUpdate( 14958 currentVal, 14959 newVal, 14960 resolveRichTextCursorPosition(cursorPosition, cursorScope, newVal) 14961 ); 14962 } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof yjs_exports.Array) { 14963 mergeYArray(currentVal, newVal, schema, cursorPosition, cursorScope); 14964 } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof yjs_exports.Map) { 14965 mergeYMapValues( 14966 currentVal, 14967 newVal, 14968 schema.query, 14969 cursorPosition, 14970 cursorScope 14971 ); 14972 } else { 14973 const newYValue = createYValueFromSchema(schema, newVal); 14974 if (newYValue !== newVal || !(0, import_es65.default)(currentVal, newVal)) { 14975 yMap.set(key, newYValue); 14976 } 14977 } 14978 } 14979 function mergeYMapValues(yMap, newObj, query, cursorPosition, cursorScope) { 14980 for (const [key, newVal] of Object.entries(newObj)) { 14981 mergeYValue( 14982 query[key], 14983 newVal, 14984 yMap, 14985 key, 14986 cursorPosition, 14987 cursorScope 14988 ); 14989 } 14990 for (const key of yMap.keys()) { 14991 if (!Object.hasOwn(newObj, key)) { 14992 yMap.delete(key); 14993 } 14994 } 14995 } 14996 function updateYBlockAttribute(blockName, clientId, attributeName, attributeValue, currentAttributes, newCursorPosition) { 14997 const schema = getBlockAttributeSchema(blockName, attributeName); 14998 mergeYValue( 14999 schema, 15000 attributeValue, 15001 currentAttributes, 15002 attributeName, 15003 newCursorPosition, 15004 { attributeKey: attributeName, clientId } 15005 ); 15006 } 15007 function resolveRichTextCursorPosition(cursorPosition, cursorScope, updatedValue) { 15008 return cursorPosition && cursorPosition.clientId === cursorScope.clientId && cursorPosition.attributeKey === cursorScope.attributeKey && "number" === typeof cursorPosition.offset && Number.isInteger(cursorPosition.offset) ? richTextOffsetToHtmlIndex( 15009 updatedValue, 15010 asRichTextOffset(cursorPosition.offset) 15011 ) : null; 15012 } 15013 var cachedBlockAttributeSchemas; 15014 function getBlockAttributeSchema(blockName, attributeName) { 15015 if (!cachedBlockAttributeSchemas) { 15016 cachedBlockAttributeSchemas = /* @__PURE__ */ new Map(); 15017 for (const blockType of (0, import_blocks.getBlockTypes)()) { 15018 cachedBlockAttributeSchemas.set( 15019 blockType.name, 15020 new Map( 15021 Object.entries(blockType.attributes ?? {}).map( 15022 ([name, definition]) => { 15023 const { role, type, query } = definition; 15024 return [name, { role, type, query }]; 15025 } 15026 ) 15027 ) 15028 ); 15029 } 15030 } 15031 return cachedBlockAttributeSchemas.get(blockName)?.get(attributeName); 15032 } 15033 function isExpectedAttributeType(blockName, attributeName, attributeValue) { 15034 const schema = getBlockAttributeSchema(blockName, attributeName); 15035 if (schema?.type === "rich-text") { 15036 return attributeValue instanceof yjs_exports.Text; 15037 } 15038 if (schema?.type === "string") { 15039 return typeof attributeValue === "string"; 15040 } 15041 if (schema?.type === "array" && schema.query) { 15042 return attributeValue instanceof yjs_exports.Array; 15043 } 15044 if (schema?.type === "object" && schema.query) { 15045 return attributeValue instanceof yjs_exports.Map; 15046 } 15047 return true; 15048 } 15049 function isLocalAttribute(blockName, attributeName) { 15050 return "local" === getBlockAttributeSchema(blockName, attributeName)?.role; 15051 } 15052 var localDoc; 15053 function mergeRichTextUpdate(blockYText, updatedValue, htmlCursorIndex = null) { 15054 const currentValueAsDelta = new Delta_default(blockYText.toDelta()); 15055 const updatedValueAsDelta = new Delta_default([{ insert: updatedValue }]); 15056 const deltaDiff = currentValueAsDelta.diffWithCursor( 15057 updatedValueAsDelta, 15058 htmlCursorIndex 15059 ); 15060 const safeDiff = htmlCursorIndex === null || isDeltaVerificationMatch(blockYText, deltaDiff, updatedValue) ? deltaDiff : currentValueAsDelta.diff(updatedValueAsDelta); 15061 blockYText.applyDelta(safeDiff.ops); 15062 } 15063 function isDeltaVerificationMatch(blockYText, delta, expectedValue) { 15064 if (!localDoc) { 15065 localDoc = new yjs_exports.Doc(); 15066 } 15067 const verificationYText = localDoc.getText("verification-text"); 15068 verificationYText.delete(0, verificationYText.length); 15069 verificationYText.insert(0, blockYText.toString()); 15070 verificationYText.applyDelta(delta.ops); 15071 return verificationYText.toString() === expectedValue; 15072 } 15073 15074 // packages/core-data/build-module/utils/crdt-selection.mjs 15075 var import_data5 = __toESM(require_data(), 1); 15076 var import_block_editor4 = __toESM(require_block_editor(), 1); 15077 var import_blocks2 = __toESM(require_blocks(), 1); 15078 15079 // packages/core-data/build-module/utils/block-selection-history.mjs 15080 var SELECTION_HISTORY_DEFAULT_SIZE = 5; 15081 var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => { 15082 YSelectionType2["RelativeSelection"] = "RelativeSelection"; 15083 YSelectionType2["BlockSelection"] = "BlockSelection"; 15084 return YSelectionType2; 15085 })(YSelectionType || {}); 15086 function createBlockSelectionHistory(ydoc, historySize = SELECTION_HISTORY_DEFAULT_SIZE) { 15087 let history = []; 15088 const getSelectionHistory2 = () => { 15089 return history.slice(0); 15090 }; 15091 const updateSelection = (newSelection) => { 15092 if (!newSelection?.selectionStart?.clientId || !newSelection?.selectionEnd?.clientId) { 15093 return; 15094 } 15095 const { selectionStart, selectionEnd } = newSelection; 15096 const start = convertWPBlockSelectionToSelection( 15097 selectionStart, 15098 ydoc 15099 ); 15100 const end = convertWPBlockSelectionToSelection(selectionEnd, ydoc); 15101 addToHistory({ start, end }); 15102 }; 15103 const addToHistory = (yFullSelection) => { 15104 const startClientId = yFullSelection.start.clientId; 15105 const endClientId = yFullSelection.end.clientId; 15106 history = history.filter((entry) => { 15107 const isSameBlockCombination = entry.start.clientId === startClientId && entry.end.clientId === endClientId; 15108 return !isSameBlockCombination; 15109 }); 15110 history.unshift(yFullSelection); 15111 if (history.length > historySize + 1) { 15112 history = history.slice(0, historySize + 1); 15113 } 15114 }; 15115 return { 15116 getSelectionHistory: getSelectionHistory2, 15117 updateSelection 15118 }; 15119 } 15120 function convertWPBlockSelectionToSelection(selection, ydoc) { 15121 const clientId = selection.clientId; 15122 const block = findBlockByClientIdInDoc(clientId, ydoc); 15123 const attributes = block?.get("attributes"); 15124 const attributeKey = selection.attributeKey; 15125 let changedYText = null; 15126 if (attributeKey && attributes) { 15127 changedYText = getYTextByAttributeKey(attributes, attributeKey); 15128 } 15129 if (!(changedYText instanceof yjs_exports.Text) || !attributeKey || !clientId) { 15130 return { 15131 type: "BlockSelection", 15132 clientId 15133 }; 15134 } 15135 const offset = selection.offset ?? 0; 15136 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex( 15137 changedYText, 15138 richTextOffsetToHtmlIndex( 15139 changedYText.toString(), 15140 asRichTextOffset(offset) 15141 ) 15142 ); 15143 return { 15144 type: "RelativeSelection", 15145 attributeKey, 15146 relativePosition, 15147 clientId, 15148 offset 15149 }; 15150 } 15151 15152 // packages/core-data/build-module/utils/crdt-selection.mjs 15153 var selectionHistoryMap = /* @__PURE__ */ new WeakMap(); 15154 function getBlockSelectionHistory(ydoc) { 15155 let history = selectionHistoryMap.get(ydoc); 15156 if (!history) { 15157 history = createBlockSelectionHistory(ydoc); 15158 selectionHistoryMap.set(ydoc, history); 15159 } 15160 return history; 15161 } 15162 function getSelectionHistory(ydoc) { 15163 return getBlockSelectionHistory(ydoc).getSelectionHistory(); 15164 } 15165 function updateSelectionHistory(ydoc, wpSelection) { 15166 return getBlockSelectionHistory(ydoc).updateSelection(wpSelection); 15167 } 15168 function convertYSelectionToBlockSelection(ySelection, ydoc) { 15169 if (ySelection.type === YSelectionType.RelativeSelection) { 15170 const { relativePosition, attributeKey, clientId } = ySelection; 15171 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition( 15172 relativePosition, 15173 ydoc 15174 ); 15175 if (absolutePosition) { 15176 return { 15177 clientId, 15178 attributeKey, 15179 offset: htmlIndexToRichTextOffset( 15180 absolutePosition.type.toString(), 15181 asHtmlStringIndex(absolutePosition.index) 15182 ) 15183 }; 15184 } 15185 } else if (ySelection.type === YSelectionType.BlockSelection) { 15186 return { 15187 clientId: ySelection.clientId, 15188 attributeKey: void 0, 15189 offset: void 0 15190 }; 15191 } 15192 return null; 15193 } 15194 function convertYFullSelectionToWPSelection(yFullSelection, ydoc) { 15195 const { start, end } = yFullSelection; 15196 const startBlock = findBlockByClientIdInDoc(start.clientId, ydoc); 15197 const endBlock = findBlockByClientIdInDoc(end.clientId, ydoc); 15198 if (!startBlock || !endBlock) { 15199 return null; 15200 } 15201 const startBlockSelection = convertYSelectionToBlockSelection( 15202 start, 15203 ydoc 15204 ); 15205 const endBlockSelection = convertYSelectionToBlockSelection(end, ydoc); 15206 if (startBlockSelection === null || endBlockSelection === null) { 15207 return null; 15208 } 15209 return { 15210 selectionStart: startBlockSelection, 15211 selectionEnd: endBlockSelection 15212 }; 15213 } 15214 function findSelectionFromHistory(ydoc, selectionHistory) { 15215 for (const positionToTry of selectionHistory) { 15216 const result = convertYFullSelectionToWPSelection( 15217 positionToTry, 15218 ydoc 15219 ); 15220 if (result !== null) { 15221 return result; 15222 } 15223 } 15224 return null; 15225 } 15226 function restoreSelection(selectionHistory, ydoc) { 15227 const selectionToRestore = findSelectionFromHistory( 15228 ydoc, 15229 selectionHistory 15230 ); 15231 if (selectionToRestore === null) { 15232 return; 15233 } 15234 const { getBlock } = (0, import_data5.select)(import_block_editor4.store); 15235 const { resetSelection } = (0, import_data5.dispatch)(import_block_editor4.store); 15236 const { selectionStart, selectionEnd } = selectionToRestore; 15237 const isSelectionInSameBlock = selectionStart.clientId === selectionEnd.clientId; 15238 if (isSelectionInSameBlock) { 15239 const block = getBlock(selectionStart.clientId); 15240 const isBlockEmpty = block && (0, import_blocks2.isUnmodifiedBlock)(block); 15241 const isBeginningOfEmptyBlock = 0 === selectionStart.offset && 0 === selectionEnd.offset && isBlockEmpty && !selectionStart.attributeKey && !selectionEnd.attributeKey; 15242 if (isBeginningOfEmptyBlock) { 15243 const selectionStartWithoutOffset = { 15244 clientId: selectionStart.clientId 15245 }; 15246 const selectionEndWithoutOffset = { 15247 clientId: selectionEnd.clientId 15248 }; 15249 resetSelection( 15250 selectionStartWithoutOffset, 15251 selectionEndWithoutOffset, 15252 0 15253 ); 15254 } else { 15255 resetSelection(selectionStart, selectionEnd, 0); 15256 } 15257 } else { 15258 resetSelection(selectionEnd, selectionEnd, 0); 15259 } 15260 } 15261 function getShiftedSelection(ydoc, selectionHistory) { 15262 if (selectionHistory.length === 0) { 15263 return null; 15264 } 15265 const { start, end } = selectionHistory[0]; 15266 if (start.type === YSelectionType.BlockSelection || end.type === YSelectionType.BlockSelection) { 15267 return null; 15268 } 15269 const selectionStart = convertYSelectionToBlockSelection(start, ydoc); 15270 const selectionEnd = convertYSelectionToBlockSelection(end, ydoc); 15271 if (!selectionStart || !selectionEnd) { 15272 return null; 15273 } 15274 const startShifted = selectionStart.offset !== start.offset; 15275 const endShifted = selectionEnd.offset !== end.offset; 15276 if (!startShifted && !endShifted) { 15277 return null; 15278 } 15279 return { selectionStart, selectionEnd }; 15280 } 15281 15282 // packages/core-data/build-module/utils/crdt.mjs 15283 var POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document"; 15284 var disallowedPostMetaKeys = /* @__PURE__ */ new Set([ 15285 POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE 15286 ]); 15287 var unsyncedTaxonomyProperties = /* @__PURE__ */ new Set([ 15288 "id", 15289 "count", 15290 "link", 15291 "taxonomy", 15292 "_links", 15293 "_embedded" 15294 ]); 15295 function applyTaxonomyChangesToCRDTDoc(ydoc, changes) { 15296 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY); 15297 Object.entries(changes).forEach(([key, newValue]) => { 15298 if (unsyncedTaxonomyProperties.has(key)) { 15299 return; 15300 } 15301 if ("function" === typeof newValue) { 15302 return; 15303 } 15304 const currentValue = ymap.get(key); 15305 updateMapValue(ymap, key, currentValue, newValue); 15306 }); 15307 } 15308 function applyPostChangesToCRDTDoc(ydoc, changes, syncedProperties) { 15309 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY); 15310 Object.keys(changes).forEach((key) => { 15311 if (!syncedProperties.has(key)) { 15312 return; 15313 } 15314 const newValue = changes[key]; 15315 if ("function" === typeof newValue) { 15316 return; 15317 } 15318 switch (key) { 15319 case "blocks": { 15320 const newCursorPosition = parseCursorSelection( 15321 changes.selection 15322 ); 15323 const rawContent = getRawValue(changes.content); 15324 if (!newValue && typeof rawContent === "string") { 15325 mergeContentWithoutBlocks( 15326 ymap, 15327 rawContent, 15328 newCursorPosition 15329 ); 15330 break; 15331 } else if (!newValue) { 15332 ymap.set(key, void 0); 15333 break; 15334 } 15335 let currentBlocks = ymap.get(key); 15336 if (!(currentBlocks instanceof yjs_exports.Array)) { 15337 currentBlocks = new yjs_exports.Array(); 15338 ymap.set(key, currentBlocks); 15339 } 15340 mergeCrdtBlocks(currentBlocks, newValue, newCursorPosition); 15341 break; 15342 } 15343 case "content": 15344 case "excerpt": 15345 case "title": { 15346 const currentValue = ymap.get(key); 15347 let rawValue = getRawValue(newValue); 15348 if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) { 15349 rawValue = ""; 15350 } 15351 if (currentValue instanceof yjs_exports.Text) { 15352 mergeRichTextUpdate(currentValue, rawValue ?? ""); 15353 } else { 15354 const newYText = new yjs_exports.Text(rawValue ?? ""); 15355 ymap.set(key, newYText); 15356 } 15357 break; 15358 } 15359 // "Meta" is overloaded term; here, it refers to post meta. 15360 case "meta": { 15361 let metaMap = ymap.get("meta"); 15362 if (!isYMap(metaMap)) { 15363 metaMap = createYMap(); 15364 ymap.set("meta", metaMap); 15365 } 15366 Object.entries(newValue ?? {}).forEach( 15367 ([metaKey, metaValue]) => { 15368 if (disallowedPostMetaKeys.has(metaKey)) { 15369 return; 15370 } 15371 updateMapValue( 15372 metaMap, 15373 metaKey, 15374 metaMap.get(metaKey), 15375 // current value in CRDT 15376 metaValue 15377 // new value from changes 15378 ); 15379 } 15380 ); 15381 break; 15382 } 15383 case "slug": { 15384 if (!newValue) { 15385 break; 15386 } 15387 const currentValue = ymap.get(key); 15388 updateMapValue(ymap, key, currentValue, newValue); 15389 break; 15390 } 15391 // Add support for additional properties here. 15392 default: { 15393 const currentValue = ymap.get(key); 15394 updateMapValue(ymap, key, currentValue, newValue); 15395 } 15396 } 15397 }); 15398 if (changes.selection) { 15399 const selection = changes.selection; 15400 setTimeout(() => { 15401 updateSelectionHistory(ydoc, selection); 15402 }, 0); 15403 } 15404 } 15405 function mergeContentWithoutBlocks(ymap, rawContent, cursorPosition) { 15406 let currentBlocks = ymap.get("blocks"); 15407 if (!(currentBlocks instanceof yjs_exports.Array)) { 15408 currentBlocks = new yjs_exports.Array(); 15409 ymap.set("blocks", currentBlocks); 15410 } 15411 mergeCrdtBlocks( 15412 currentBlocks, 15413 (0, import_blocks3.parse)(rawContent), 15414 cursorPosition, 15415 { preserveClientIds: true } 15416 ); 15417 } 15418 function parseCursorSelection(selection) { 15419 const selectionStart = selection?.selectionStart; 15420 return selectionStart?.clientId && selectionStart.attributeKey && "number" === typeof selectionStart.offset && Number.isInteger(selectionStart.offset) ? { 15421 attributeKey: selectionStart.attributeKey, 15422 clientId: selectionStart.clientId, 15423 offset: asRichTextOffset(selectionStart.offset) 15424 } : null; 15425 } 15426 function getTaxonomyChangesFromCRDTDoc(crdtDoc, editedRecord) { 15427 const docRecord = getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY).toJSON(); 15428 return Object.fromEntries( 15429 Object.entries(docRecord).filter( 15430 ([key, newValue]) => !unsyncedTaxonomyProperties.has(key) && haveValuesChanged(editedRecord?.[key], newValue) 15431 ) 15432 ); 15433 } 15434 function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) { 15435 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY); 15436 let allowedMetaChanges = {}; 15437 const changes = Object.fromEntries( 15438 Object.entries(ymap.toJSON()).filter(([key, newValue]) => { 15439 if (!syncedProperties.has(key)) { 15440 return false; 15441 } 15442 const currentValue = editedRecord[key]; 15443 switch (key) { 15444 case "blocks": { 15445 if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY) && editedRecord.content) { 15446 const blocksJson = ymap.get("blocks")?.toJSON() ?? []; 15447 return (0, import_blocks3.__unstableSerializeAndClean)(blocksJson).trim() !== getRawValue(editedRecord.content); 15448 } 15449 return true; 15450 } 15451 case "date": { 15452 const currentDateIsFloating = null === currentValue || editedRecord.modified === currentValue; 15453 if (currentDateIsFloating) { 15454 return false; 15455 } 15456 return haveValuesChanged(currentValue, newValue); 15457 } 15458 case "meta": { 15459 const currentMeta = currentValue ?? {}; 15460 allowedMetaChanges = Object.fromEntries( 15461 Object.entries(newValue ?? {}).filter( 15462 ([metaKey]) => { 15463 if (disallowedPostMetaKeys.has(metaKey)) { 15464 return false; 15465 } 15466 return metaKey in currentMeta; 15467 } 15468 ) 15469 ); 15470 const mergedValue = { 15471 ...currentMeta, 15472 ...allowedMetaChanges 15473 }; 15474 return haveValuesChanged(currentValue, mergedValue); 15475 } 15476 case "status": { 15477 if ("auto-draft" === newValue) { 15478 return false; 15479 } 15480 return haveValuesChanged(currentValue, newValue); 15481 } 15482 case "content": 15483 case "excerpt": 15484 case "title": { 15485 return haveValuesChanged( 15486 getRawValue(currentValue), 15487 newValue 15488 ); 15489 } 15490 // Add support for additional data types here. 15491 default: { 15492 return haveValuesChanged(currentValue, newValue); 15493 } 15494 } 15495 }) 15496 ); 15497 if (changes.blocks) { 15498 changes.blocks = deserializeBlockAttributes( 15499 changes.blocks 15500 ); 15501 } 15502 if (changes.blocks && !changes.content) { 15503 const capturedBlocks = changes.blocks; 15504 changes.content = () => (0, import_blocks3.__unstableSerializeAndClean)(capturedBlocks); 15505 } 15506 if ("object" === typeof changes.meta) { 15507 changes.meta = { 15508 ...editedRecord.meta, 15509 ...allowedMetaChanges 15510 }; 15511 } 15512 const selectionHistory = getSelectionHistory(ydoc); 15513 const shiftedSelection = getShiftedSelection(ydoc, selectionHistory); 15514 if (shiftedSelection) { 15515 changes.selection = { 15516 ...shiftedSelection, 15517 initialPosition: 0 15518 }; 15519 } 15520 return changes; 15521 } 15522 var taxonomySyncConfig = { 15523 applyChangesToCRDTDoc: applyTaxonomyChangesToCRDTDoc, 15524 createAwareness: (ydoc) => new BaseAwareness(ydoc), 15525 getChangesFromCRDTDoc: getTaxonomyChangesFromCRDTDoc 15526 }; 15527 var defaultCollectionSyncConfig = { 15528 applyChangesToCRDTDoc: () => { 15529 }, 15530 getChangesFromCRDTDoc: () => ({}), 15531 shouldSync: (_, objectId) => null === objectId 15532 }; 15533 function getRawValue(value) { 15534 if ("string" === typeof value) { 15535 return value; 15536 } 15537 if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) { 15538 return value.raw; 15539 } 15540 return void 0; 15541 } 15542 function haveValuesChanged(currentValue, newValue) { 15543 return !(0, import_es66.default)(currentValue, newValue); 15544 } 15545 function updateMapValue(map2, key, currentValue, newValue) { 15546 if (void 0 === newValue) { 15547 map2.delete(key); 15548 return; 15549 } 15550 if (haveValuesChanged(currentValue, newValue)) { 15551 map2.set(key, newValue); 15552 } 15553 } 15554 15555 // packages/core-data/build-module/entities.mjs 15556 var DEFAULT_ENTITY_KEY = "id"; 15557 var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"]; 15558 var blocksTransientEdits = { 15559 blocks: { 15560 read: (record) => (0, import_blocks4.parse)(record.content?.raw ?? ""), 15561 write: (record) => ({ 15562 content: (0, import_blocks4.__unstableSerializeAndClean)(record.blocks) 15563 }) 15564 } 15565 }; 15566 var rootEntitiesConfig = [ 15567 { 15568 label: (0, import_i18n.__)("Base"), 15569 kind: "root", 15570 key: false, 15571 name: "__unstableBase", 15572 baseURL: "/", 15573 baseURLParams: { 15574 // Please also change the preload path when changing this. 15575 // @see lib/compat/wordpress-7.2/preload.php 15576 _fields: [ 15577 "description", 15578 "generate_animated_image_subsizes", 15579 "gmt_offset", 15580 "home", 15581 "image_max_bit_depth", 15582 "image_sizes", 15583 "image_size_threshold", 15584 "image_strip_meta", 15585 "name", 15586 "site_icon", 15587 "site_icon_url", 15588 "site_logo", 15589 "timezone_string", 15590 "url", 15591 "page_for_posts", 15592 "page_on_front", 15593 "show_on_front" 15594 ].join(",") 15595 }, 15596 // The entity doesn't support selecting multiple records. 15597 // The property is maintained for backward compatibility. 15598 plural: "__unstableBases", 15599 supportsPagination: false 15600 }, 15601 { 15602 label: (0, import_i18n.__)("Post Type"), 15603 name: "postType", 15604 kind: "root", 15605 key: "slug", 15606 baseURL: "/wp/v2/types", 15607 baseURLParams: { context: "edit" }, 15608 plural: "postTypes", 15609 supportsPagination: false 15610 }, 15611 { 15612 name: "media", 15613 kind: "root", 15614 baseURL: "/wp/v2/media", 15615 baseURLParams: { context: "edit" }, 15616 plural: "mediaItems", 15617 label: (0, import_i18n.__)("Media"), 15618 rawAttributes: ["caption", "title", "description"], 15619 supportsPagination: true 15620 }, 15621 { 15622 name: "taxonomy", 15623 kind: "root", 15624 key: "slug", 15625 baseURL: "/wp/v2/taxonomies", 15626 baseURLParams: { context: "edit" }, 15627 plural: "taxonomies", 15628 label: (0, import_i18n.__)("Taxonomy"), 15629 supportsPagination: false 15630 }, 15631 { 15632 name: "sidebar", 15633 kind: "root", 15634 baseURL: "/wp/v2/sidebars", 15635 baseURLParams: { context: "edit" }, 15636 plural: "sidebars", 15637 transientEdits: { blocks: true }, 15638 label: (0, import_i18n.__)("Widget areas"), 15639 supportsPagination: false 15640 }, 15641 { 15642 name: "widget", 15643 kind: "root", 15644 baseURL: "/wp/v2/widgets", 15645 baseURLParams: { context: "edit" }, 15646 plural: "widgets", 15647 transientEdits: { blocks: true }, 15648 label: (0, import_i18n.__)("Widgets"), 15649 supportsPagination: false 15650 }, 15651 { 15652 name: "widgetType", 15653 kind: "root", 15654 baseURL: "/wp/v2/widget-types", 15655 baseURLParams: { context: "edit" }, 15656 plural: "widgetTypes", 15657 label: (0, import_i18n.__)("Widget types"), 15658 supportsPagination: false 15659 }, 15660 { 15661 label: (0, import_i18n.__)("User"), 15662 name: "user", 15663 kind: "root", 15664 baseURL: "/wp/v2/users", 15665 getTitle: (record) => record?.name || record?.slug, 15666 baseURLParams: { context: "edit" }, 15667 plural: "users", 15668 supportsPagination: true 15669 }, 15670 { 15671 name: "comment", 15672 kind: "root", 15673 baseURL: "/wp/v2/comments", 15674 baseURLParams: { context: "edit" }, 15675 plural: "comments", 15676 label: (0, import_i18n.__)("Comment"), 15677 supportsPagination: true, 15678 ...globalThis.window?.__experimentalEnableRealTimeCollaboration ? { syncConfig: defaultCollectionSyncConfig } : {} 15679 }, 15680 { 15681 name: "menu", 15682 kind: "root", 15683 baseURL: "/wp/v2/menus", 15684 baseURLParams: { context: "edit" }, 15685 plural: "menus", 15686 label: (0, import_i18n.__)("Menu"), 15687 supportsPagination: true 15688 }, 15689 { 15690 name: "menuItem", 15691 kind: "root", 15692 baseURL: "/wp/v2/menu-items", 15693 baseURLParams: { context: "edit" }, 15694 plural: "menuItems", 15695 label: (0, import_i18n.__)("Menu Item"), 15696 rawAttributes: ["title"], 15697 supportsPagination: true 15698 }, 15699 { 15700 name: "menuLocation", 15701 kind: "root", 15702 baseURL: "/wp/v2/menu-locations", 15703 baseURLParams: { context: "edit" }, 15704 plural: "menuLocations", 15705 label: (0, import_i18n.__)("Menu Location"), 15706 key: "name", 15707 supportsPagination: false 15708 }, 15709 { 15710 label: (0, import_i18n.__)("Global Styles"), 15711 name: "globalStyles", 15712 kind: "root", 15713 baseURL: "/wp/v2/global-styles", 15714 baseURLParams: { context: "edit" }, 15715 plural: "globalStylesVariations", 15716 // Should be different from name. 15717 getTitle: () => (0, import_i18n.__)("Custom Styles"), 15718 getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/$parentId}/revisions$revisionId ? "/" + revisionId : ""}`, 15719 supportsPagination: true 15720 }, 15721 { 15722 label: (0, import_i18n.__)("Themes"), 15723 name: "theme", 15724 kind: "root", 15725 baseURL: "/wp/v2/themes", 15726 baseURLParams: { context: "edit" }, 15727 plural: "themes", 15728 key: "stylesheet", 15729 supportsPagination: false 15730 }, 15731 { 15732 label: (0, import_i18n.__)("Plugins"), 15733 name: "plugin", 15734 kind: "root", 15735 baseURL: "/wp/v2/plugins", 15736 baseURLParams: { context: "edit" }, 15737 plural: "plugins", 15738 key: "plugin", 15739 supportsPagination: false 15740 }, 15741 { 15742 label: (0, import_i18n.__)("Status"), 15743 name: "status", 15744 kind: "root", 15745 baseURL: "/wp/v2/statuses", 15746 baseURLParams: { context: "edit" }, 15747 plural: "statuses", 15748 key: "slug", 15749 supportsPagination: false 15750 }, 15751 { 15752 label: (0, import_i18n.__)("Font Collections"), 15753 name: "fontCollection", 15754 kind: "root", 15755 baseURL: "/wp/v2/font-collections", 15756 baseURLParams: { context: "view" }, 15757 plural: "fontCollections", 15758 key: "slug", 15759 supportsPagination: true 15760 }, 15761 { 15762 label: (0, import_i18n.__)("Icons"), 15763 name: "icon", 15764 kind: "root", 15765 baseURL: "/wp/v2/icons", 15766 baseURLParams: { context: "view" }, 15767 plural: "icons", 15768 key: "name", 15769 supportsPagination: false 15770 }, 15771 { 15772 label: (0, import_i18n.__)("Icon Collections"), 15773 name: "iconCollection", 15774 kind: "root", 15775 baseURL: "/wp/v2/icon-collections", 15776 baseURLParams: { context: "view" }, 15777 plural: "iconCollections", 15778 key: "slug", 15779 supportsPagination: false 15780 } 15781 ]; 15782 var deprecatedEntities = { 15783 root: { 15784 media: { 15785 since: "6.9", 15786 alternative: { 15787 kind: "postType", 15788 name: "attachment" 15789 } 15790 } 15791 } 15792 }; 15793 var additionalEntityConfigLoaders = [ 15794 { kind: "postType", loadEntities: loadPostTypeEntities }, 15795 { kind: "taxonomy", loadEntities: loadTaxonomyEntities }, 15796 { 15797 kind: "root", 15798 name: "site", 15799 plural: "sites", 15800 loadEntities: loadSiteEntity 15801 } 15802 ]; 15803 var prePersistPostType = async (persistedRecord, edits, name, isTemplate) => { 15804 const newEdits = {}; 15805 if (!isTemplate && persistedRecord?.status === "auto-draft") { 15806 if (!edits.status && !newEdits.status) { 15807 newEdits.status = "draft"; 15808 } 15809 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) { 15810 newEdits.title = ""; 15811 } 15812 } 15813 return newEdits; 15814 }; 15815 async function loadPostTypeEntities() { 15816 const postTypesPromise = (0, import_api_fetch2.default)({ path: "/wp/v2/types?context=view" }); 15817 const taxonomiesPromise = window.__experimentalEnableRealTimeCollaboration ? (0, import_api_fetch2.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({}); 15818 const [postTypes, taxonomies] = await Promise.all([ 15819 postTypesPromise, 15820 taxonomiesPromise 15821 ]); 15822 return Object.entries(postTypes ?? {}).map(([name, postType]) => { 15823 const isTemplate = ["wp_template", "wp_template_part"].includes( 15824 name 15825 ); 15826 const namespace = postType?.rest_namespace ?? "wp/v2"; 15827 const syncedProperties = /* @__PURE__ */ new Set([ 15828 "author", 15829 "blocks", 15830 "content", 15831 "comment_status", 15832 "date", 15833 "excerpt", 15834 "featured_media", 15835 "format", 15836 "meta", 15837 "ping_status", 15838 "slug", 15839 "status", 15840 "sticky", 15841 "template", 15842 "title", 15843 ...postType.taxonomies?.map((taxonomy) => taxonomies?.[taxonomy]?.rest_base)?.filter(Boolean) ?? [] 15844 ]); 15845 const entity2 = { 15846 kind: "postType", 15847 baseURL: `/$namespace}/$postType.rest_base}`, 15848 baseURLParams: { context: "edit" }, 15849 name, 15850 label: postType.name, 15851 transientEdits: { 15852 ...blocksTransientEdits, 15853 selection: true 15854 }, 15855 mergedEdits: { meta: true }, 15856 rawAttributes: POST_RAW_ATTRIBUTES, 15857 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)), 15858 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate), 15859 __unstable_rest_base: postType.rest_base, 15860 // The templates controller returns the whole collection and never 15861 // paginates. 15862 supportsPagination: !isTemplate, 15863 getRevisionsUrl: (parentId, revisionId) => `/$namespace}/$postType.rest_base}/$parentId}/revisions$revisionId ? "/" + revisionId : ""}`, 15864 revisionKey: isTemplate ? "wp_id" : DEFAULT_ENTITY_KEY 15865 }; 15866 if (!window.__experimentalEnableRealTimeCollaboration) { 15867 return entity2; 15868 } 15869 entity2.syncConfig = { 15870 // Save a CRDT document with this entity 15871 supportsPersistence: true, 15872 /** 15873 * Apply changes from the local editor to the local CRDT document so 15874 * that those changes can be synced to other peers (via the provider). 15875 * 15876 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc 15877 * @param {Partial< import('@wordpress/sync').ObjectData >} changes 15878 * @return {void} 15879 */ 15880 applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, syncedProperties), 15881 /** 15882 * Create the awareness instance for the entity's CRDT document. 15883 * 15884 * @param {import('@wordpress/sync').CRDTDoc} ydoc 15885 * @param {import('@wordpress/sync').ObjectID} objectId 15886 * @return {import('@wordpress/sync').Awareness} Awareness instance 15887 */ 15888 createAwareness: (ydoc, objectId) => { 15889 const kind = "postType"; 15890 const id2 = parseInt(objectId, 10); 15891 return new PostEditorAwareness(ydoc, kind, name, id2); 15892 }, 15893 /** 15894 * Extract changes from a CRDT document that can be used to update the 15895 * local editor state. 15896 * 15897 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc 15898 * @param {import('@wordpress/sync').ObjectData} editedRecord 15899 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record 15900 */ 15901 getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc( 15902 crdtDoc, 15903 editedRecord, 15904 syncedProperties 15905 ), 15906 /** 15907 * Extract changes from a CRDT document that can be used to update the 15908 * local editor state. 15909 * 15910 * @param {import('@wordpress/sync').ObjectData} record 15911 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record 15912 */ 15913 getPersistedCRDTDoc: (record) => { 15914 return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null; 15915 }, 15916 shouldSync: () => !(Array.isArray(window._wpCollaborationDisabledPostTypes) && window._wpCollaborationDisabledPostTypes.includes(name)) 15917 }; 15918 return entity2; 15919 }); 15920 } 15921 async function loadTaxonomyEntities() { 15922 const taxonomies = await (0, import_api_fetch2.default)({ 15923 path: "/wp/v2/taxonomies?context=view" 15924 }); 15925 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => { 15926 const namespace = taxonomy?.rest_namespace ?? "wp/v2"; 15927 const entity2 = { 15928 kind: "taxonomy", 15929 baseURL: `/$namespace}/$taxonomy.rest_base}`, 15930 baseURLParams: { context: "edit" }, 15931 name, 15932 label: taxonomy.name, 15933 getTitle: (record) => record?.name, 15934 supportsPagination: true 15935 }; 15936 if (window.__experimentalEnableRealTimeCollaboration) { 15937 entity2.syncConfig = taxonomySyncConfig; 15938 } 15939 return entity2; 15940 }); 15941 } 15942 async function loadSiteEntity() { 15943 const entity2 = { 15944 label: (0, import_i18n.__)("Site"), 15945 name: "site", 15946 kind: "root", 15947 key: false, 15948 baseURL: "/wp/v2/settings", 15949 supportsPagination: false, 15950 meta: {} 15951 }; 15952 const site = await (0, import_api_fetch2.default)({ 15953 path: entity2.baseURL, 15954 method: "OPTIONS" 15955 }); 15956 const labels = {}; 15957 Object.entries(site?.schema?.properties ?? {}).forEach( 15958 ([key, value]) => { 15959 if (typeof value === "object" && value.title) { 15960 labels[key] = value.title; 15961 } 15962 } 15963 ); 15964 return [{ ...entity2, meta: { labels } }]; 15965 } 15966 var getMethodName = (kind, name, prefix = "get") => { 15967 const kindPrefix = kind === "root" ? "" : pascalCase(kind); 15968 const suffix = pascalCase(name); 15969 return `$prefix}$kindPrefix}$suffix}`; 15970 }; 15971 15972 // packages/core-data/build-module/sync.mjs 15973 var CRDT_AUTOSAVE_SNAPSHOT_KEY = "crdt_snapshot"; 15974 var syncManager; 15975 function getSyncManager() { 15976 if (syncManager) { 15977 return syncManager; 15978 } 15979 if (!globalThis.window?.__experimentalEnableRealTimeCollaboration) { 15980 return void 0; 15981 } 15982 syncManager = createSyncManager(); 15983 return syncManager; 15984 } 15985 function hasSyncManager() { 15986 return Boolean(syncManager); 15987 } 15988 function getEntitySnapshot(kind, name, recordId) { 15989 if (!hasSyncManager()) { 15990 return void 0; 15991 } 15992 return getSyncManager()?.getEntitySnapshot( 15993 `$kind}/$name}`, 15994 `$recordId}` 15995 ); 15996 } 15997 function entityContainsSnapshot(kind, name, recordId, encodedSnapshot) { 15998 if (!hasSyncManager()) { 15999 return false; 16000 } 16001 return getSyncManager()?.entityContainsSnapshot( 16002 `$kind}/$name}`, 16003 `$recordId}`, 16004 encodedSnapshot 16005 ) ?? false; 16006 } 16007 function getServerMutatedMetaFields(updatedMeta, persistedMeta, syncedMeta) { 16008 const baseline = { ...persistedMeta, ...syncedMeta }; 16009 return Object.fromEntries( 16010 Object.entries(updatedMeta ?? {}).filter(([key, value]) => { 16011 if (key === POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE) { 16012 return false; 16013 } 16014 return !(0, import_es67.default)(value, baseline[key]); 16015 }) 16016 ); 16017 } 16018 function getServerMutatedFields(updatedRecord, persistedRecord, syncedChanges) { 16019 return Object.fromEntries( 16020 Object.entries(updatedRecord).flatMap(([key, value]) => { 16021 if (key === "meta") { 16022 const serverMutatedMeta = getServerMutatedMetaFields( 16023 value, 16024 persistedRecord.meta, 16025 syncedChanges.meta 16026 ); 16027 return Object.keys(serverMutatedMeta).length ? [[key, serverMutatedMeta]] : []; 16028 } 16029 const baseline = key in syncedChanges ? syncedChanges[key] : persistedRecord[key]; 16030 const wasServerMutated = !(0, import_es67.default)( 16031 getRawValue(value) ?? value, 16032 getRawValue(baseline) ?? baseline 16033 ); 16034 return wasServerMutated ? [[key, value]] : []; 16035 }) 16036 ); 16037 } 16038 var defaultDataAccess = { select: import_data6.select, dispatch: import_data6.dispatch, resolveSelect: import_data6.resolveSelect }; 16039 function toObjectId(recordId) { 16040 return recordId; 16041 } 16042 function createDefaultEntitySyncManager(data = defaultDataAccess) { 16043 const getSyncConfig = (kind, name) => data.select(STORE_NAME).getEntityConfig(kind, name)?.syncConfig; 16044 return { 16045 shouldSync(kind, name) { 16046 return Boolean(getSyncManager() && getSyncConfig(kind, name)); 16047 }, 16048 isLoaded(kind, name, recordId) { 16049 if (!hasSyncManager()) { 16050 return false; 16051 } 16052 return Boolean( 16053 getSyncManager()?.isLoaded( 16054 `$kind}/$name}`, 16055 toObjectId(recordId) 16056 ) 16057 ); 16058 }, 16059 load(kind, name, recordId, record, handlers) { 16060 const syncConfig = getSyncConfig(kind, name); 16061 const manager = getSyncManager(); 16062 if (!syncConfig || !manager) { 16063 return; 16064 } 16065 return manager.load( 16066 syncConfig, 16067 `$kind}/$name}`, 16068 toObjectId(recordId), 16069 record, 16070 createRecordHandlers( 16071 data, 16072 kind, 16073 name, 16074 recordId, 16075 syncConfig, 16076 handlers 16077 ) 16078 ); 16079 }, 16080 loadCollection(kind, name, handlers) { 16081 const syncConfig = getSyncConfig(kind, name); 16082 const manager = getSyncManager(); 16083 if (!syncConfig || !manager) { 16084 return; 16085 } 16086 return manager.loadCollection( 16087 syncConfig, 16088 `$kind}/$name}`, 16089 createCollectionHandlers(data, kind, name, handlers) 16090 ); 16091 }, 16092 update(kind, name, recordId, edits, options) { 16093 if (!getSyncConfig(kind, name)) { 16094 return; 16095 } 16096 getSyncManager()?.update( 16097 `$kind}/$name}`, 16098 toObjectId(recordId), 16099 edits, 16100 getEditOrigin(options), 16101 { isNewUndoLevel: isNewUndoLevel(options) } 16102 ); 16103 }, 16104 beforeSave(kind, name, recordId, edits, context) { 16105 if (!getSyncConfig(kind, name)) { 16106 return; 16107 } 16108 return beforeSave(kind, name, recordId, edits, context); 16109 }, 16110 afterSave(kind, name, recordId, context) { 16111 if (!getSyncConfig(kind, name)) { 16112 return; 16113 } 16114 const { savedRecord, persistedRecord, edits } = context; 16115 const syncChanges = persistedRecord ? getServerMutatedFields(savedRecord, persistedRecord, edits) : savedRecord; 16116 getSyncManager()?.update( 16117 `$kind}/$name}`, 16118 void 0 === recordId ? null : toObjectId(recordId), 16119 syncChanges, 16120 LOCAL_UNDO_IGNORED_ORIGIN, 16121 { isSave: true } 16122 ); 16123 }, 16124 unload(kind, name, recordId) { 16125 if (!getSyncConfig(kind, name)) { 16126 return; 16127 } 16128 getSyncManager()?.unload( 16129 `$kind}/$name}`, 16130 toObjectId(recordId) 16131 ); 16132 }, 16133 unloadAll() { 16134 if (hasSyncManager()) { 16135 getSyncManager()?.unloadAll(); 16136 } 16137 }, 16138 // A getter, so the value is read when core-data asks. There is no 16139 // history before a sync manager exists, and asking must not create 16140 // one. 16141 get undoHistory() { 16142 if (!hasSyncManager()) { 16143 return void 0; 16144 } 16145 const undoManager2 = getSyncManager()?.undoManager; 16146 if (!undoManager2) { 16147 return void 0; 16148 } 16149 return { 16150 undo: (kind, name, recordId) => undoManager2.undo( 16151 `$kind}/$name}`, 16152 toObjectId(recordId) 16153 ), 16154 redo: (kind, name, recordId) => undoManager2.redo( 16155 `$kind}/$name}`, 16156 toObjectId(recordId) 16157 ), 16158 stopCapturing: () => undoManager2.stopCapturing(), 16159 clearRedo: () => undoManager2.clearRedo() 16160 }; 16161 } 16162 }; 16163 } 16164 function getEditOrigin(options) { 16165 return options.undoIgnore ? LOCAL_UNDO_IGNORED_ORIGIN : LOCAL_EDITOR_ORIGIN; 16166 } 16167 function isNewUndoLevel(options) { 16168 return options.undoIgnore ? false : !options.isCached; 16169 } 16170 async function beforeSave(kind, name, recordId, edits, { persistedRecord, isAutosave }) { 16171 const manager = getSyncManager(); 16172 if (!manager) { 16173 return; 16174 } 16175 const objectType = `$kind}/$name}`; 16176 const objectId = toObjectId(recordId); 16177 if (persistedRecord) { 16178 manager.update( 16179 objectType, 16180 objectId, 16181 edits, 16182 LOCAL_UNDO_IGNORED_ORIGIN 16183 ); 16184 } 16185 if (isAutosave) { 16186 const snapshot2 = manager.getEntitySnapshot(objectType, objectId); 16187 return snapshot2 ? { [CRDT_AUTOSAVE_SNAPSHOT_KEY]: snapshot2 } : void 0; 16188 } 16189 if ("postType" !== kind || !persistedRecord) { 16190 return; 16191 } 16192 const serializedDoc = await manager.createPersistedCRDTDoc( 16193 objectType, 16194 toObjectId(persistedRecord.id) 16195 ); 16196 if (!serializedDoc) { 16197 return; 16198 } 16199 return { 16200 meta: { 16201 ...edits.meta, 16202 [POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializedDoc 16203 } 16204 }; 16205 } 16206 function createRecordHandlers(data, kind, name, recordId, syncConfig, handlers) { 16207 return { 16208 editRecord: handlers.editRecord, 16209 getEditedRecord: handlers.getEditedRecord, 16210 refetchRecord: handlers.refetchRecord, 16211 onUndoLevelOpened: handlers.onUndoLevelOpened, 16212 // Handle sync connection status changes. 16213 onStatusChange: (status) => { 16214 unlock(data.dispatch(STORE_NAME)).setSyncConnectionStatus( 16215 kind, 16216 name, 16217 recordId, 16218 status 16219 ); 16220 }, 16221 // Persist the CRDT document. 16222 // 16223 // TODO: Currently, persisted CRDT documents are stored in post meta. 16224 // This effectively means that only post entities support CRDT 16225 // persistence. As we add support for syncing additional entity, 16226 // we'll need to revisit where persisted CRDT documents are stored. 16227 persistCRDTDoc: () => { 16228 if (!syncConfig.supportsPersistence) { 16229 return; 16230 } 16231 return data.resolveSelect(STORE_NAME).getEditedEntityRecord(kind, name, recordId).then(async (editedRecord) => { 16232 const { meta, status } = editedRecord; 16233 if ("auto-draft" === status || !meta) { 16234 return; 16235 } 16236 const entityConfig = data.select(STORE_NAME).getEntityConfig(kind, name); 16237 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY; 16238 const entityId = editedRecord[entityIdKey]; 16239 await saveCRDTDoc( 16240 `$kind}/$name}`, 16241 toObjectId(entityId) 16242 ); 16243 }); 16244 }, 16245 addUndoMeta: (ydoc, meta) => { 16246 const selectionHistory = getSelectionHistory(ydoc); 16247 if (selectionHistory) { 16248 meta.set("selectionHistory", selectionHistory); 16249 } 16250 }, 16251 restoreUndoMeta: (ydoc, meta) => { 16252 const selectionHistory = meta.get("selectionHistory"); 16253 if (selectionHistory) { 16254 setTimeout(() => { 16255 restoreSelection(selectionHistory, ydoc); 16256 }, 0); 16257 } 16258 } 16259 }; 16260 } 16261 function createCollectionHandlers(data, kind, name, handlers) { 16262 return { 16263 refetchRecords: handlers.refetchRecords, 16264 onStatusChange: (status) => { 16265 unlock(data.dispatch(STORE_NAME)).setSyncConnectionStatus( 16266 kind, 16267 name, 16268 null, 16269 status 16270 ); 16271 } 16272 }; 16273 } 16274 if (globalThis.window?.__experimentalEnableRealTimeCollaboration) { 16275 registerEntitySyncManager(createDefaultEntitySyncManager()); 16276 } 16277 16278 // packages/core-data/build-module/utils/save-crdt-doc.mjs 16279 var SYNC_SAVE_API_PATH = "/wp-sync/v1/save"; 16280 var saveCRDTDocQueues = /* @__PURE__ */ new Map(); 16281 async function serializeAndSaveCRDTDoc(objectType, objectId, room) { 16282 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc( 16283 objectType, 16284 objectId 16285 ); 16286 if (!serializedDoc) { 16287 return; 16288 } 16289 await (0, import_api_fetch3.default)({ 16290 path: SYNC_SAVE_API_PATH, 16291 method: "POST", 16292 data: { 16293 room, 16294 doc: serializedDoc 16295 } 16296 }); 16297 } 16298 async function saveCRDTDoc(objectType, objectId) { 16299 const room = `$objectType}:$objectId}`; 16300 const previousSave = saveCRDTDocQueues.get(room) || Promise.resolve(); 16301 const currentSave = previousSave.catch(() => { 16302 }).then(() => serializeAndSaveCRDTDoc(objectType, objectId, room)); 16303 saveCRDTDocQueues.set(room, currentSave); 16304 try { 16305 await currentSave; 16306 } finally { 16307 if (saveCRDTDocQueues.get(room) === currentSave) { 16308 saveCRDTDocQueues.delete(room); 16309 } 16310 } 16311 } 16312 16313 // packages/core-data/build-module/utils/get-pagination-meta.mjs 16314 function getPaginationMeta(headers) { 16315 const totalItems = parseInt(headers.get("X-WP-Total") ?? ""); 16316 const totalPages = parseInt(headers.get("X-WP-TotalPages") ?? ""); 16317 return { 16318 totalItems: Number.isFinite(totalItems) ? totalItems : null, 16319 totalPages: Number.isFinite(totalPages) ? totalPages : null 16320 }; 16321 } 16322 16323 // packages/core-data/build-module/queried-data/actions.mjs 16324 function receiveItems(items2, edits, meta) { 16325 return { 16326 type: "RECEIVE_ITEMS", 16327 items: items2, 16328 persistedEdits: edits, 16329 meta 16330 }; 16331 } 16332 function removeItems(kind, name, records, invalidateCache = false) { 16333 return { 16334 type: "REMOVE_ITEMS", 16335 itemIds: Array.isArray(records) ? records : [records], 16336 kind, 16337 name, 16338 invalidateCache 16339 }; 16340 } 16341 function receiveQueriedItems(items2, query = {}, edits, meta) { 16342 return { 16343 ...receiveItems(items2, edits, meta), 16344 query 16345 }; 16346 } 16347 16348 // packages/core-data/build-module/queried-data/selectors.mjs 16349 var import_equivalent_key_map = __toESM(require_equivalent_key_map(), 1); 16350 16351 // packages/core-data/build-module/queried-data/get-query-parts.mjs 16352 var import_url = __toESM(require_url(), 1); 16353 function getQueryParts(query) { 16354 const parts = { 16355 stableKey: "", 16356 page: 1, 16357 perPage: 10, 16358 offset: null, 16359 fields: null, 16360 include: null, 16361 context: "default" 16362 }; 16363 const keys2 = Object.keys(query).sort(); 16364 for (let i = 0; i < keys2.length; i++) { 16365 const key = keys2[i]; 16366 let value = query[key]; 16367 switch (key) { 16368 case "page": 16369 parts[key] = Number(value); 16370 break; 16371 case "per_page": 16372 parts.perPage = Number(value); 16373 break; 16374 case "offset": { 16375 const numericOffset = Number(value); 16376 if (Number.isFinite(numericOffset)) { 16377 parts.offset = numericOffset; 16378 } 16379 break; 16380 } 16381 case "context": 16382 parts.context = value; 16383 break; 16384 default: 16385 if (key === "_fields") { 16386 parts.fields = get_normalized_comma_separable_default(value) ?? []; 16387 value = parts.fields.join(); 16388 } 16389 if (key === "include") { 16390 if (typeof value === "number") { 16391 value = value.toString(); 16392 } 16393 parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number); 16394 value = parts.include.join(); 16395 } 16396 parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1); 16397 } 16398 } 16399 return parts; 16400 } 16401 var get_query_parts_default = with_weak_map_cache_default(getQueryParts); 16402 16403 // packages/core-data/build-module/queried-data/selectors.mjs 16404 var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap(); 16405 function getQueriedItemsUncached(state, query, options = {}) { 16406 const { supportsPagination = true } = options; 16407 const { 16408 stableKey, 16409 page, 16410 perPage, 16411 offset: queryOffset, 16412 include, 16413 fields, 16414 context 16415 } = get_query_parts_default(query); 16416 const itemIds = state.queries?.[context]?.[stableKey]?.itemIds; 16417 if (!itemIds) { 16418 return null; 16419 } 16420 const isPaginated = supportsPagination && perPage !== -1; 16421 const startOffset = isPaginated ? queryOffset ?? (page - 1) * perPage : 0; 16422 const endOffset = isPaginated ? Math.min(startOffset + perPage, itemIds.length) : itemIds.length; 16423 if (isPaginated && itemIds.length < startOffset + perPage) { 16424 const totalItems = state.queries[context][stableKey].meta?.totalItems; 16425 if (Number.isFinite(totalItems) && itemIds.length < totalItems) { 16426 return null; 16427 } 16428 } 16429 const items2 = []; 16430 for (let i = startOffset; i < endOffset; i++) { 16431 const itemId = itemIds[i]; 16432 if (Array.isArray(include) && !include.includes(itemId)) { 16433 continue; 16434 } 16435 if (itemId === void 0) { 16436 continue; 16437 } 16438 if (!state.items[context]?.hasOwnProperty(itemId)) { 16439 return null; 16440 } 16441 const item = state.items[context][itemId]; 16442 let filteredItem; 16443 if (Array.isArray(fields)) { 16444 filteredItem = {}; 16445 for (let f = 0; f < fields.length; f++) { 16446 const field = fields[f].split("."); 16447 let value = item; 16448 field.forEach((fieldName) => { 16449 value = value?.[fieldName]; 16450 }); 16451 setNestedValue(filteredItem, field, value); 16452 } 16453 } else { 16454 if (!state.itemIsComplete[context]?.[itemId]) { 16455 return null; 16456 } 16457 filteredItem = item; 16458 } 16459 items2.push(filteredItem); 16460 } 16461 return items2; 16462 } 16463 function getQueriedItems(state, query = {}, options = {}) { 16464 let queriedItemsCache = queriedItemsCacheByState.get(state); 16465 if (queriedItemsCache) { 16466 const queriedItems = queriedItemsCache.get(query); 16467 if (queriedItems !== void 0) { 16468 return queriedItems; 16469 } 16470 } else { 16471 queriedItemsCache = new import_equivalent_key_map.default(); 16472 queriedItemsCacheByState.set(state, queriedItemsCache); 16473 } 16474 const items2 = getQueriedItemsUncached(state, query, options); 16475 queriedItemsCache.set(query, items2); 16476 return items2; 16477 } 16478 function getQueriedTotalItems(state, query = {}) { 16479 const { stableKey, context } = get_query_parts_default(query); 16480 return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null; 16481 } 16482 function getQueriedTotalPages(state, query = {}) { 16483 const { stableKey, context } = get_query_parts_default(query); 16484 return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null; 16485 } 16486 16487 // packages/core-data/build-module/queried-data/reducer.mjs 16488 var import_data7 = __toESM(require_data(), 1); 16489 var import_compose = __toESM(require_compose(), 1); 16490 function getContextFromAction(action) { 16491 const { query } = action; 16492 if (!query) { 16493 return "default"; 16494 } 16495 const queryParts = get_query_parts_default(query); 16496 return queryParts.context; 16497 } 16498 function getMergedItemIds(itemIds = [], nextItemIds, { page = 1, offset, perPage = 10 } = {}) { 16499 if (perPage === -1) { 16500 return nextItemIds; 16501 } 16502 const nextItemIdsStartIndex = offset ?? (page - 1) * perPage; 16503 const nextItemIdsRange = Math.max(perPage, nextItemIds.length); 16504 const size2 = Math.max( 16505 itemIds.length, 16506 nextItemIdsStartIndex + nextItemIds.length 16507 ); 16508 const mergedItemIds = new Array(size2); 16509 for (let i = 0; i < size2; i++) { 16510 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIdsRange; 16511 if (isInNextItemsRange) { 16512 mergedItemIds[i] = nextItemIds[i - nextItemIdsStartIndex]; 16513 } else { 16514 mergedItemIds[i] = itemIds[i]; 16515 } 16516 } 16517 return mergedItemIds; 16518 } 16519 function removeEntitiesById(entities2, ids) { 16520 return Object.fromEntries( 16521 Object.entries(entities2).filter( 16522 ([id2]) => !ids.some((itemId) => { 16523 if (Number.isInteger(itemId)) { 16524 return itemId === +id2; 16525 } 16526 return itemId === id2; 16527 }) 16528 ) 16529 ); 16530 } 16531 function items(state = {}, action) { 16532 switch (action.type) { 16533 case "RECEIVE_ITEMS": { 16534 const context = getContextFromAction(action); 16535 const key = action.key || DEFAULT_ENTITY_KEY; 16536 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16537 return { 16538 ...state, 16539 [context]: { 16540 ...state[context], 16541 ...Object.fromEntries( 16542 itemsList.map((item) => [ 16543 item?.[key], 16544 conservativeMapItem( 16545 state?.[context]?.[item?.[key]], 16546 item 16547 ) 16548 ]) 16549 ) 16550 } 16551 }; 16552 } 16553 case "REMOVE_ITEMS": 16554 return Object.fromEntries( 16555 Object.entries(state).map(([itemId, contextState]) => [ 16556 itemId, 16557 removeEntitiesById(contextState, action.itemIds) 16558 ]) 16559 ); 16560 } 16561 return state; 16562 } 16563 function itemIsComplete(state = {}, action) { 16564 switch (action.type) { 16565 case "RECEIVE_ITEMS": { 16566 const context = getContextFromAction(action); 16567 const { query, key = DEFAULT_ENTITY_KEY } = action; 16568 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16569 const queryParts = query ? get_query_parts_default(query) : {}; 16570 const isCompleteQuery = !query || !Array.isArray(queryParts.fields); 16571 return { 16572 ...state, 16573 [context]: { 16574 ...state[context], 16575 ...itemsList.reduce((result, item) => { 16576 const itemId = item?.[key]; 16577 result[itemId] = state?.[context]?.[itemId] || isCompleteQuery; 16578 return result; 16579 }, {}) 16580 } 16581 }; 16582 } 16583 case "REMOVE_ITEMS": 16584 return Object.fromEntries( 16585 Object.entries(state).map(([itemId, contextState]) => [ 16586 itemId, 16587 removeEntitiesById(contextState, action.itemIds) 16588 ]) 16589 ); 16590 } 16591 return state; 16592 } 16593 var receiveQueries = (0, import_compose.compose)([ 16594 // Limit to matching action type so we don't attempt to replace action on 16595 // an unhandled action. 16596 if_matching_action_default((action) => "query" in action), 16597 // Inject query parts into action for use both in `keyedReducer` and reducer. 16598 replace_action_default((action) => { 16599 if (action.query) { 16600 return { 16601 ...action, 16602 ...get_query_parts_default(action.query) 16603 }; 16604 } 16605 return action; 16606 }), 16607 (0, import_data7.keyedReducer)("context"), 16608 // Queries shape is shared, but keyed by query `stableKey` part. Original 16609 // reducer tracks only a single query object. 16610 (0, import_data7.keyedReducer)("stableKey") 16611 ])((state = {}, action) => { 16612 if (action.type !== "RECEIVE_ITEMS") { 16613 return state; 16614 } 16615 if (!Array.isArray(action.items)) { 16616 return state; 16617 } 16618 const key = action.key ?? DEFAULT_ENTITY_KEY; 16619 return { 16620 itemIds: getMergedItemIds( 16621 state.itemIds, 16622 action.items.map((item) => item?.[key]).filter(Boolean), 16623 { 16624 page: action.page, 16625 offset: action.offset, 16626 perPage: action.perPage 16627 } 16628 ), 16629 meta: action.meta 16630 }; 16631 }); 16632 function removeQueryItems(queryItems, removedItems) { 16633 const itemIds = queryItems.itemIds.filter( 16634 (itemId) => !removedItems[itemId] 16635 ); 16636 const removedCount = queryItems.itemIds.length - itemIds.length; 16637 if (removedCount === 0) { 16638 return queryItems; 16639 } 16640 const nextQueryItems = { ...queryItems, itemIds }; 16641 if (Number.isFinite(queryItems.meta?.totalItems)) { 16642 nextQueryItems.meta = { 16643 ...queryItems.meta, 16644 totalItems: Math.max( 16645 0, 16646 queryItems.meta.totalItems - removedCount 16647 ), 16648 totalPages: null 16649 }; 16650 } 16651 return nextQueryItems; 16652 } 16653 var queries = (state = {}, action) => { 16654 switch (action.type) { 16655 case "RECEIVE_ITEMS": 16656 return receiveQueries(state, action); 16657 case "REMOVE_ITEMS": 16658 const removedItems = action.itemIds.reduce((result, itemId) => { 16659 result[itemId] = true; 16660 return result; 16661 }, {}); 16662 return Object.fromEntries( 16663 Object.entries(state).map( 16664 ([queryGroup, contextQueries]) => [ 16665 queryGroup, 16666 Object.fromEntries( 16667 Object.entries(contextQueries).map( 16668 ([query, queryItems]) => [ 16669 query, 16670 removeQueryItems( 16671 queryItems, 16672 removedItems 16673 ) 16674 ] 16675 ) 16676 ) 16677 ] 16678 ) 16679 ); 16680 default: 16681 return state; 16682 } 16683 }; 16684 var reducer_default = (0, import_data7.combineReducers)({ 16685 items, 16686 itemIsComplete, 16687 queries 16688 }); 16689 16690 // packages/core-data/build-module/reducer.mjs 16691 function users(state = { byId: {}, queries: {} }, action) { 16692 switch (action.type) { 16693 case "RECEIVE_USER_QUERY": 16694 return { 16695 byId: { 16696 ...state.byId, 16697 // Key users by their ID. 16698 ...action.users.reduce( 16699 (newUsers, user) => ({ 16700 ...newUsers, 16701 [user.id]: user 16702 }), 16703 {} 16704 ) 16705 }, 16706 queries: { 16707 ...state.queries, 16708 [action.queryID]: action.users.map((user) => user.id) 16709 } 16710 }; 16711 } 16712 return state; 16713 } 16714 function currentUser(state = {}, action) { 16715 switch (action.type) { 16716 case "RECEIVE_CURRENT_USER": 16717 return action.currentUser; 16718 } 16719 return state; 16720 } 16721 function currentTheme(state = void 0, action) { 16722 switch (action.type) { 16723 case "RECEIVE_CURRENT_THEME": 16724 return action.currentTheme.stylesheet; 16725 } 16726 return state; 16727 } 16728 function currentGlobalStylesId(state = void 0, action) { 16729 switch (action.type) { 16730 case "RECEIVE_CURRENT_GLOBAL_STYLES_ID": 16731 return action.id; 16732 } 16733 return state; 16734 } 16735 function themeBaseGlobalStyles(state = {}, action) { 16736 switch (action.type) { 16737 case "RECEIVE_THEME_GLOBAL_STYLES": 16738 return { 16739 ...state, 16740 [action.stylesheet]: action.globalStyles 16741 }; 16742 } 16743 return state; 16744 } 16745 function themeGlobalStyleVariations(state = {}, action) { 16746 switch (action.type) { 16747 case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS": 16748 return { 16749 ...state, 16750 [action.stylesheet]: action.variations 16751 }; 16752 } 16753 return state; 16754 } 16755 var withMultiEntityRecordEdits = (reducer) => (state, action) => { 16756 if (action.type === "UNDO" || action.type === "REDO") { 16757 const { record } = action; 16758 let newState = state; 16759 record.forEach(({ id: { kind, name, recordId }, changes }) => { 16760 const persistedRecord = state?.queriedData?.items?.default?.[recordId]; 16761 const edits = Object.fromEntries( 16762 Object.entries(changes).map(([key, value]) => [ 16763 key, 16764 action.type === "UNDO" ? value.from : value.to 16765 ]) 16766 ); 16767 newState = reducer(newState, { 16768 type: "EDIT_ENTITY_RECORD", 16769 kind, 16770 name, 16771 recordId, 16772 // Clear edits matching the persisted record so the entity is 16773 // no longer dirty after undoing back to its saved state. 16774 edits: clearUnchangedEdits(edits, persistedRecord) 16775 }); 16776 }); 16777 return newState; 16778 } 16779 return reducer(state, action); 16780 }; 16781 function entity(entityConfig) { 16782 return (0, import_compose2.compose)([ 16783 withMultiEntityRecordEdits, 16784 // Limit to matching action type so we don't attempt to replace action on 16785 // an unhandled action. 16786 if_matching_action_default( 16787 (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind 16788 ), 16789 // Inject the entity config into the action. 16790 replace_action_default((action) => { 16791 return { 16792 key: entityConfig.key || DEFAULT_ENTITY_KEY, 16793 ...action 16794 }; 16795 }) 16796 ])( 16797 (0, import_data8.combineReducers)({ 16798 queriedData: reducer_default, 16799 edits: (state = {}, action) => { 16800 switch (action.type) { 16801 case "RECEIVE_ITEMS": 16802 const context = action?.query?.context ?? "default"; 16803 if (context !== "default") { 16804 return state; 16805 } 16806 const nextState = { ...state }; 16807 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16808 for (const record of itemsList) { 16809 const recordId = record?.[action.key]; 16810 const edits = nextState[recordId]; 16811 if (!edits) { 16812 continue; 16813 } 16814 const nextEdits2 = Object.keys(edits).reduce( 16815 (acc, key) => { 16816 if ( 16817 // Edits are the "raw" attribute values, but records may have 16818 // objects with more properties, so we use `get` here for the 16819 // comparison. 16820 !(0, import_es68.default)( 16821 edits[key], 16822 record[key]?.raw ?? record[key] 16823 ) && // Sometimes the server alters the sent value which means 16824 // we need to also remove the edits before the api request. 16825 (!action.persistedEdits || !(0, import_es68.default)( 16826 edits[key], 16827 action.persistedEdits[key] 16828 )) 16829 ) { 16830 acc[key] = edits[key]; 16831 } 16832 return acc; 16833 }, 16834 {} 16835 ); 16836 if (Object.keys(nextEdits2).length) { 16837 nextState[recordId] = nextEdits2; 16838 } else { 16839 delete nextState[recordId]; 16840 } 16841 } 16842 return nextState; 16843 case "EDIT_ENTITY_RECORD": 16844 const nextEdits = { 16845 ...state[action.recordId], 16846 ...action.edits 16847 }; 16848 Object.keys(nextEdits).forEach((key) => { 16849 if (nextEdits[key] === void 0) { 16850 delete nextEdits[key]; 16851 } 16852 }); 16853 return { 16854 ...state, 16855 [action.recordId]: nextEdits 16856 }; 16857 } 16858 return state; 16859 }, 16860 saving: (state = {}, action) => { 16861 switch (action.type) { 16862 case "SAVE_ENTITY_RECORD_START": 16863 case "SAVE_ENTITY_RECORD_FINISH": 16864 return { 16865 ...state, 16866 [action.recordId]: { 16867 pending: action.type === "SAVE_ENTITY_RECORD_START", 16868 error: action.error, 16869 isAutosave: action.isAutosave 16870 } 16871 }; 16872 } 16873 return state; 16874 }, 16875 deleting: (state = {}, action) => { 16876 switch (action.type) { 16877 case "DELETE_ENTITY_RECORD_START": 16878 case "DELETE_ENTITY_RECORD_FINISH": 16879 return { 16880 ...state, 16881 [action.recordId]: { 16882 pending: action.type === "DELETE_ENTITY_RECORD_START", 16883 error: action.error 16884 } 16885 }; 16886 } 16887 return state; 16888 }, 16889 revisions: (state = {}, action) => { 16890 if (action.type === "RECEIVE_ITEM_REVISIONS") { 16891 const recordKey = action.recordKey; 16892 delete action.recordKey; 16893 const newState = reducer_default(state[recordKey], { 16894 ...action, 16895 type: "RECEIVE_ITEMS" 16896 }); 16897 return { 16898 ...state, 16899 [recordKey]: newState 16900 }; 16901 } 16902 if (action.type === "REMOVE_ITEMS") { 16903 return Object.fromEntries( 16904 Object.entries(state).filter( 16905 ([id2]) => !action.itemIds.some((itemId) => { 16906 if (Number.isInteger(itemId)) { 16907 return itemId === +id2; 16908 } 16909 return itemId === id2; 16910 }) 16911 ) 16912 ); 16913 } 16914 return state; 16915 } 16916 }) 16917 ); 16918 } 16919 function entitiesConfig(state = rootEntitiesConfig, action) { 16920 switch (action.type) { 16921 case "ADD_ENTITIES": 16922 return [...state, ...action.entities]; 16923 } 16924 return state; 16925 } 16926 var entities = (state = {}, action) => { 16927 const newConfig = entitiesConfig(state.config, action); 16928 let entitiesDataReducer = state.reducer; 16929 if (!entitiesDataReducer || newConfig !== state.config) { 16930 const entitiesByKind = newConfig.reduce((acc, record) => { 16931 const { kind } = record; 16932 if (!acc[kind]) { 16933 acc[kind] = []; 16934 } 16935 acc[kind].push(record); 16936 return acc; 16937 }, {}); 16938 entitiesDataReducer = (0, import_data8.combineReducers)( 16939 Object.fromEntries( 16940 Object.entries(entitiesByKind).map( 16941 ([kind, subEntities]) => { 16942 const kindReducer = (0, import_data8.combineReducers)( 16943 Object.fromEntries( 16944 subEntities.map((entityConfig) => [ 16945 entityConfig.name, 16946 entity(entityConfig) 16947 ]) 16948 ) 16949 ); 16950 return [kind, kindReducer]; 16951 } 16952 ) 16953 ) 16954 ); 16955 } 16956 const newData = entitiesDataReducer(state.records, action); 16957 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) { 16958 return state; 16959 } 16960 return { 16961 reducer: entitiesDataReducer, 16962 records: newData, 16963 config: newConfig 16964 }; 16965 }; 16966 function undoManager(state = (0, import_undo_manager2.createUndoManager)()) { 16967 return state; 16968 } 16969 function undoManagerReference(state = {}, action) { 16970 switch (action.type) { 16971 case "RECORD_SYNC_UNDO_LEVEL": 16972 return {}; 16973 } 16974 return state; 16975 } 16976 function editsReference(state = {}, action) { 16977 switch (action.type) { 16978 case "EDIT_ENTITY_RECORD": 16979 case "UNDO": 16980 case "REDO": 16981 return {}; 16982 } 16983 return state; 16984 } 16985 function embedPreviews(state = {}, action) { 16986 switch (action.type) { 16987 case "RECEIVE_EMBED_PREVIEW": 16988 const { url, preview } = action; 16989 return { 16990 ...state, 16991 [url]: preview 16992 }; 16993 } 16994 return state; 16995 } 16996 function userPermissions(state = {}, action) { 16997 switch (action.type) { 16998 case "RECEIVE_USER_PERMISSION": 16999 return { 17000 ...state, 17001 [action.key]: action.isAllowed 17002 }; 17003 case "RECEIVE_USER_PERMISSIONS": 17004 return { 17005 ...state, 17006 ...action.permissions 17007 }; 17008 } 17009 return state; 17010 } 17011 function autosaves(state = {}, action) { 17012 switch (action.type) { 17013 case "RECEIVE_AUTOSAVES": 17014 const { postId, autosaves: autosavesData } = action; 17015 return { 17016 ...state, 17017 [postId]: autosavesData 17018 }; 17019 } 17020 return state; 17021 } 17022 function blockPatterns(state = [], action) { 17023 switch (action.type) { 17024 case "RECEIVE_BLOCK_PATTERNS": 17025 return action.patterns; 17026 } 17027 return state; 17028 } 17029 function blockPatternCategories(state = [], action) { 17030 switch (action.type) { 17031 case "RECEIVE_BLOCK_PATTERN_CATEGORIES": 17032 return action.categories; 17033 } 17034 return state; 17035 } 17036 function userPatternCategories(state = [], action) { 17037 switch (action.type) { 17038 case "RECEIVE_USER_PATTERN_CATEGORIES": 17039 return action.patternCategories; 17040 } 17041 return state; 17042 } 17043 function navigationFallbackId(state = null, action) { 17044 switch (action.type) { 17045 case "RECEIVE_NAVIGATION_FALLBACK_ID": 17046 return action.fallbackId; 17047 } 17048 return state; 17049 } 17050 function themeGlobalStyleRevisions(state = {}, action) { 17051 switch (action.type) { 17052 case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS": 17053 return { 17054 ...state, 17055 [action.currentId]: action.revisions 17056 }; 17057 } 17058 return state; 17059 } 17060 function defaultTemplates(state = {}, action) { 17061 switch (action.type) { 17062 case "RECEIVE_DEFAULT_TEMPLATE": 17063 return { 17064 ...state, 17065 [JSON.stringify(action.query)]: action.templateId 17066 }; 17067 } 17068 return state; 17069 } 17070 function registeredPostMeta(state = {}, action) { 17071 switch (action.type) { 17072 case "RECEIVE_REGISTERED_POST_META": 17073 return { 17074 ...state, 17075 [action.postType]: action.registeredPostMeta 17076 }; 17077 } 17078 return state; 17079 } 17080 function editorSettings(state = null, action) { 17081 switch (action.type) { 17082 case "RECEIVE_EDITOR_SETTINGS": 17083 return action.settings; 17084 } 17085 return state; 17086 } 17087 function editorAssets(state = null, action) { 17088 switch (action.type) { 17089 case "RECEIVE_EDITOR_ASSETS": 17090 return action.assets; 17091 } 17092 return state; 17093 } 17094 function syncConnectionStatuses(state = {}, action) { 17095 switch (action.type) { 17096 case "SET_SYNC_CONNECTION_STATUS": { 17097 const key = `$action.kind}/$action.name}:$action.key}`; 17098 return { 17099 ...state, 17100 [key]: action.status 17101 }; 17102 } 17103 case "CLEAR_SYNC_CONNECTION_STATUS": { 17104 const key = `$action.kind}/$action.name}:$action.key}`; 17105 const { [key]: _, ...rest } = state; 17106 return rest; 17107 } 17108 } 17109 return state; 17110 } 17111 function collaborationSupported(state = true, action) { 17112 switch (action.type) { 17113 case "SET_COLLABORATION_SUPPORTED": 17114 return action.supported; 17115 case "SET_SYNC_CONNECTION_STATUS": 17116 if (ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED === action.status?.error?.code) { 17117 return false; 17118 } 17119 return state; 17120 } 17121 return state; 17122 } 17123 function viewConfigs(state = {}, action) { 17124 switch (action.type) { 17125 case "RECEIVE_VIEW_CONFIG": { 17126 const key = `$action.kind}/$action.name}`; 17127 return { 17128 ...state, 17129 [key]: { 17130 ...state[key], 17131 ...action.config 17132 } 17133 }; 17134 } 17135 } 17136 return state; 17137 } 17138 function fieldsConfigs(state = {}, action) { 17139 switch (action.type) { 17140 case "RECEIVE_FIELDS_CONFIG": 17141 return { 17142 ...state, 17143 [action.kind]: { 17144 ...state[action.kind], 17145 [action.name]: action.config 17146 } 17147 }; 17148 } 17149 return state; 17150 } 17151 function entityActionsConfigs(state = {}, action) { 17152 switch (action.type) { 17153 case "RECEIVE_ENTITY_ACTIONS_CONFIG": 17154 return { 17155 ...state, 17156 [action.kind]: { 17157 ...state[action.kind], 17158 [action.name]: action.config 17159 } 17160 }; 17161 } 17162 return state; 17163 } 17164 var reducer_default2 = (0, import_data8.combineReducers)({ 17165 users, 17166 currentTheme, 17167 currentGlobalStylesId, 17168 currentUser, 17169 themeGlobalStyleVariations, 17170 themeBaseGlobalStyles, 17171 themeGlobalStyleRevisions, 17172 entities, 17173 editsReference, 17174 undoManagerReference, 17175 undoManager, 17176 embedPreviews, 17177 userPermissions, 17178 autosaves, 17179 blockPatterns, 17180 blockPatternCategories, 17181 userPatternCategories, 17182 navigationFallbackId, 17183 defaultTemplates, 17184 registeredPostMeta, 17185 editorSettings, 17186 editorAssets, 17187 syncConnectionStatuses, 17188 collaborationSupported, 17189 viewConfigs, 17190 fieldsConfigs, 17191 entityActionsConfigs 17192 }); 17193 17194 // packages/core-data/build-module/selectors.mjs 17195 var selectors_exports = {}; 17196 __export(selectors_exports, { 17197 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId, 17198 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles, 17199 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations, 17200 __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords, 17201 __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved, 17202 __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver, 17203 canUser: () => canUser, 17204 canUserEditEntityRecord: () => canUserEditEntityRecord, 17205 getAuthors: () => getAuthors, 17206 getAutosave: () => getAutosave, 17207 getAutosaves: () => getAutosaves, 17208 getBlockPatternCategories: () => getBlockPatternCategories, 17209 getBlockPatterns: () => getBlockPatterns, 17210 getCurrentTheme: () => getCurrentTheme, 17211 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions, 17212 getCurrentUser: () => getCurrentUser, 17213 getDefaultTemplateId: () => getDefaultTemplateId, 17214 getEditedEntityRecord: () => getEditedEntityRecord, 17215 getEmbedPreview: () => getEmbedPreview, 17216 getEntitiesByKind: () => getEntitiesByKind, 17217 getEntitiesConfig: () => getEntitiesConfig, 17218 getEntity: () => getEntity, 17219 getEntityConfig: () => getEntityConfig, 17220 getEntityRecord: () => getEntityRecord, 17221 getEntityRecordEdits: () => getEntityRecordEdits, 17222 getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits, 17223 getEntityRecords: () => getEntityRecords, 17224 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems, 17225 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages, 17226 getLastEntityDeleteError: () => getLastEntityDeleteError, 17227 getLastEntitySaveError: () => getLastEntitySaveError, 17228 getRawEntityRecord: () => getRawEntityRecord, 17229 getRedoEdit: () => getRedoEdit, 17230 getReferenceByDistinctEdits: () => getReferenceByDistinctEdits, 17231 getRevision: () => getRevision, 17232 getRevisions: () => getRevisions, 17233 getThemeSupports: () => getThemeSupports, 17234 getUndoEdit: () => getUndoEdit, 17235 getUserPatternCategories: () => getUserPatternCategories, 17236 getUserQueryResults: () => getUserQueryResults, 17237 hasEditsForEntityRecord: () => hasEditsForEntityRecord, 17238 hasEntityRecord: () => hasEntityRecord, 17239 hasEntityRecords: () => hasEntityRecords, 17240 hasFetchedAutosaves: () => hasFetchedAutosaves, 17241 hasRedo: () => hasRedo, 17242 hasRevision: () => hasRevision, 17243 hasUndo: () => hasUndo, 17244 isAutosavingEntityRecord: () => isAutosavingEntityRecord, 17245 isDeletingEntityRecord: () => isDeletingEntityRecord, 17246 isPreviewEmbedFallback: () => isPreviewEmbedFallback, 17247 isRequestingEmbedPreview: () => isRequestingEmbedPreview, 17248 isSavingEntityRecord: () => isSavingEntityRecord 17249 }); 17250 var import_data10 = __toESM(require_data(), 1); 17251 var import_url2 = __toESM(require_url(), 1); 17252 var import_deprecated2 = __toESM(require_deprecated(), 1); 17253 17254 // packages/core-data/build-module/private-selectors.mjs 17255 var private_selectors_exports = {}; 17256 __export(private_selectors_exports, { 17257 getBlockPatternsForPostType: () => getBlockPatternsForPostType, 17258 getEditorAssets: () => getEditorAssets, 17259 getEditorSettings: () => getEditorSettings, 17260 getEntityActionsConfig: () => getEntityActionsConfig, 17261 getEntityRecordPermissions: () => getEntityRecordPermissions, 17262 getEntityRecordsPermissions: () => getEntityRecordsPermissions, 17263 getEntitySyncConnectionStatus: () => getEntitySyncConnectionStatus, 17264 getFieldsConfig: () => getFieldsConfig, 17265 getHomePage: () => getHomePage, 17266 getNavigationFallbackId: () => getNavigationFallbackId, 17267 getPostsPageId: () => getPostsPageId, 17268 getRegisteredPostMeta: () => getRegisteredPostMeta, 17269 getSyncConnectionStatus: () => getSyncConnectionStatus, 17270 getTemplateId: () => getTemplateId, 17271 getUndoManager: () => getUndoManager, 17272 getViewConfig: () => getViewConfig, 17273 isCollaborationSupported: () => isCollaborationSupported 17274 }); 17275 var import_data9 = __toESM(require_data(), 1); 17276 17277 // packages/core-data/build-module/utils/log-entity-deprecation.mjs 17278 var import_deprecated = __toESM(require_deprecated(), 1); 17279 var loggedAlready = false; 17280 function logEntityDeprecation(kind, name, functionName, { 17281 alternativeFunctionName, 17282 isShorthandSelector = false 17283 } = {}) { 17284 const deprecation = deprecatedEntities[kind]?.[name]; 17285 if (!deprecation) { 17286 return; 17287 } 17288 if (!loggedAlready) { 17289 const { alternative } = deprecation; 17290 const message = isShorthandSelector ? `'$functionName}'` : `The '$kind}', '$name}' entity (used via '$functionName}')`; 17291 let alternativeMessage = `the '$alternative.kind}', '$alternative.name}' entity`; 17292 if (alternativeFunctionName) { 17293 alternativeMessage += ` via the '$alternativeFunctionName}' function`; 17294 } 17295 (0, import_deprecated.default)(message, { 17296 ...deprecation, 17297 alternative: alternativeMessage 17298 }); 17299 } 17300 loggedAlready = true; 17301 setTimeout(() => { 17302 loggedAlready = false; 17303 }, 0); 17304 } 17305 17306 // packages/core-data/build-module/private-selectors.mjs 17307 var EMPTY_OBJECT = {}; 17308 function getUndoManager(state) { 17309 return state.undoManager; 17310 } 17311 function getNavigationFallbackId(state) { 17312 return state.navigationFallbackId; 17313 } 17314 var getBlockPatternsForPostType = (0, import_data9.createRegistrySelector)( 17315 (select6) => (0, import_data9.createSelector)( 17316 (state, postType) => select6(STORE_NAME).getBlockPatterns().filter( 17317 ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType) 17318 ), 17319 () => [select6(STORE_NAME).getBlockPatterns()] 17320 ) 17321 ); 17322 var getEntityRecordsPermissions = (0, import_data9.createRegistrySelector)( 17323 (select6) => (0, import_data9.createSelector)( 17324 (state, kind, name, ids) => { 17325 const normalizedIds = Array.isArray(ids) ? ids : [ids]; 17326 return normalizedIds.map((id2) => ({ 17327 delete: select6(STORE_NAME).canUser("delete", { 17328 kind, 17329 name, 17330 id: id2 17331 }), 17332 update: select6(STORE_NAME).canUser("update", { 17333 kind, 17334 name, 17335 id: id2 17336 }) 17337 })); 17338 }, 17339 (state) => [state.userPermissions] 17340 ) 17341 ); 17342 function getEntityRecordPermissions(state, kind, name, id2) { 17343 logEntityDeprecation(kind, name, "getEntityRecordPermissions"); 17344 return getEntityRecordsPermissions(state, kind, name, id2)[0]; 17345 } 17346 function getRegisteredPostMeta(state, postType) { 17347 return state.registeredPostMeta?.[postType] ?? {}; 17348 } 17349 function normalizePageId(value) { 17350 if (!value || !["number", "string"].includes(typeof value)) { 17351 return null; 17352 } 17353 if (Number(value) === 0) { 17354 return null; 17355 } 17356 return value.toString(); 17357 } 17358 var getHomePage = (0, import_data9.createRegistrySelector)( 17359 (select6) => (0, import_data9.createSelector)( 17360 () => { 17361 const siteData = select6(STORE_NAME).getEntityRecord( 17362 "root", 17363 "__unstableBase" 17364 ); 17365 if (!siteData) { 17366 return null; 17367 } 17368 const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null; 17369 if (homepageId) { 17370 return { postType: "page", postId: homepageId }; 17371 } 17372 const frontPageTemplateId = select6( 17373 STORE_NAME 17374 ).getDefaultTemplateId({ 17375 slug: "front-page" 17376 }); 17377 if (frontPageTemplateId) { 17378 return { 17379 postType: "wp_template", 17380 postId: frontPageTemplateId 17381 }; 17382 } 17383 if (frontPageTemplateId === "") { 17384 return EMPTY_OBJECT; 17385 } 17386 return null; 17387 }, 17388 (state) => [ 17389 // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes, 17390 // it doesn't seem to invalidate this cache, I'm not sure why. 17391 getEntityRecord(state, "root", "site"), 17392 getEntityRecord(state, "root", "__unstableBase"), 17393 getDefaultTemplateId(state, { 17394 slug: "front-page" 17395 }) 17396 ] 17397 ) 17398 ); 17399 var getPostsPageId = (0, import_data9.createRegistrySelector)((select6) => () => { 17400 const siteData = select6(STORE_NAME).getEntityRecord( 17401 "root", 17402 "__unstableBase" 17403 ); 17404 return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null; 17405 }); 17406 var getTemplateId = (0, import_data9.createRegistrySelector)( 17407 (select6) => (state, postType, postId) => { 17408 const homepage = unlock(select6(STORE_NAME)).getHomePage(); 17409 if (!homepage) { 17410 return; 17411 } 17412 if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) { 17413 const templates = select6(STORE_NAME).getEntityRecords( 17414 "postType", 17415 "wp_template", 17416 { 17417 per_page: -1 17418 } 17419 ); 17420 if (!templates) { 17421 return; 17422 } 17423 const id2 = templates.find( 17424 ({ slug }) => slug === "front-page" 17425 )?.id; 17426 if (id2) { 17427 return id2; 17428 } 17429 } 17430 const editedEntity = select6(STORE_NAME).getEditedEntityRecord( 17431 "postType", 17432 postType, 17433 postId 17434 ); 17435 if (!editedEntity) { 17436 return; 17437 } 17438 const postsPageId = unlock(select6(STORE_NAME)).getPostsPageId(); 17439 if (postType === "page" && postsPageId === postId.toString()) { 17440 return select6(STORE_NAME).getDefaultTemplateId({ 17441 slug: "home" 17442 }); 17443 } 17444 const currentTemplateSlug = editedEntity.template; 17445 if (currentTemplateSlug) { 17446 const currentTemplate = select6(STORE_NAME).getEntityRecords("postType", "wp_template", { 17447 per_page: -1 17448 })?.find(({ slug }) => slug === currentTemplateSlug); 17449 if (currentTemplate) { 17450 return currentTemplate.id; 17451 } 17452 } 17453 let slugToCheck; 17454 if (editedEntity.slug) { 17455 slugToCheck = postType === "page" ? `$postType}-$editedEntity.slug}` : `single-$postType}-$editedEntity.slug}`; 17456 } else { 17457 slugToCheck = postType === "page" ? "page" : `single-$postType}`; 17458 } 17459 return select6(STORE_NAME).getDefaultTemplateId({ 17460 slug: slugToCheck 17461 }); 17462 } 17463 ); 17464 function getEditorSettings(state) { 17465 return state.editorSettings; 17466 } 17467 function getEditorAssets(state) { 17468 return state.editorAssets; 17469 } 17470 function isCollaborationSupported(state) { 17471 return state.collaborationSupported; 17472 } 17473 function getViewConfig(state, kind, name) { 17474 return state.viewConfigs?.[`$kind}/$name}`] ?? { 17475 default_view: void 0, 17476 default_layouts: void 0, 17477 view_list: void 0, 17478 form: void 0 17479 }; 17480 } 17481 function getFieldsConfig(state, kind, name) { 17482 return state.fieldsConfigs?.[kind]?.[name]; 17483 } 17484 function getEntityActionsConfig(state, kind, name) { 17485 return state.entityActionsConfigs?.[kind]?.[name]; 17486 } 17487 function getSyncConnectionStatus(state) { 17488 if (!state.syncConnectionStatuses) { 17489 return void 0; 17490 } 17491 const PRIORITIZED_STATUSES = ["disconnected", "connecting", "connected"]; 17492 let coalesced; 17493 for (const status of Object.values(state.syncConnectionStatuses)) { 17494 if (!coalesced || PRIORITIZED_STATUSES.indexOf(status.status) < PRIORITIZED_STATUSES.indexOf(coalesced.status)) { 17495 coalesced = status; 17496 } 17497 } 17498 return coalesced; 17499 } 17500 function getEntitySyncConnectionStatus(state, kind, name, recordId) { 17501 return state.syncConnectionStatuses?.[`$kind}/$name}:$recordId}`]; 17502 } 17503 17504 // packages/core-data/build-module/selectors.mjs 17505 var EMPTY_OBJECT2 = {}; 17506 var isRequestingEmbedPreview = (0, import_data10.createRegistrySelector)( 17507 (select6) => (state, url) => { 17508 return select6(STORE_NAME).isResolving("getEmbedPreview", [ 17509 url 17510 ]); 17511 } 17512 ); 17513 function getAuthors(state, query) { 17514 (0, import_deprecated2.default)("select( 'core' ).getAuthors()", { 17515 since: "5.9", 17516 alternative: "select( 'core' ).getUsers({ who: 'authors' })" 17517 }); 17518 const path = (0, import_url2.addQueryArgs)( 17519 "/wp/v2/users/?who=authors&per_page=100", 17520 query 17521 ); 17522 return getUserQueryResults(state, path); 17523 } 17524 function getCurrentUser(state) { 17525 return state.currentUser; 17526 } 17527 var getUserQueryResults = (0, import_data10.createSelector)( 17528 (state, queryID) => { 17529 const queryResults = state.users.queries[queryID] ?? []; 17530 return queryResults.map((id2) => state.users.byId[id2]); 17531 }, 17532 (state, queryID) => [ 17533 state.users.queries[queryID], 17534 state.users.byId 17535 ] 17536 ); 17537 function getEntitiesByKind(state, kind) { 17538 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", { 17539 since: "6.0", 17540 alternative: "wp.data.select( 'core' ).getEntitiesConfig()" 17541 }); 17542 return getEntitiesConfig(state, kind); 17543 } 17544 var getEntitiesConfig = (0, import_data10.createSelector)( 17545 (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind), 17546 /* eslint-disable @typescript-eslint/no-unused-vars */ 17547 (state, kind) => state.entities.config 17548 /* eslint-enable @typescript-eslint/no-unused-vars */ 17549 ); 17550 function getEntity(state, kind, name) { 17551 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", { 17552 since: "6.0", 17553 alternative: "wp.data.select( 'core' ).getEntityConfig()" 17554 }); 17555 return getEntityConfig(state, kind, name); 17556 } 17557 function getEntityConfig(state, kind, name) { 17558 logEntityDeprecation(kind, name, "getEntityConfig"); 17559 return state.entities.config?.find( 17560 (config) => config.kind === kind && config.name === name 17561 ); 17562 } 17563 var getEntityRecord = ((state, kind, name, recordId, query) => { 17564 logEntityDeprecation(kind, name, "getEntityRecord"); 17565 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17566 if (!queriedState) { 17567 return void 0; 17568 } 17569 const context = query?.context ?? "default"; 17570 if (!query || !query._fields) { 17571 if (!queriedState.itemIsComplete[context]?.[recordId]) { 17572 return void 0; 17573 } 17574 return queriedState.items[context][recordId]; 17575 } 17576 const item = queriedState.items[context]?.[recordId]; 17577 if (!item) { 17578 return item; 17579 } 17580 return getFilteredItem(item, query._fields); 17581 }); 17582 getEntityRecord.normalizeArgs = (args2) => { 17583 const newArgs = [...args2]; 17584 const recordKey = newArgs?.[2]; 17585 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey; 17586 return newArgs; 17587 }; 17588 function hasEntityRecord(state, kind, name, recordId, query) { 17589 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17590 if (!queriedState) { 17591 return false; 17592 } 17593 const context = query?.context ?? "default"; 17594 if (!query || !query._fields) { 17595 return !!queriedState.itemIsComplete[context]?.[recordId]; 17596 } 17597 const item = queriedState.items[context]?.[recordId]; 17598 if (!item) { 17599 return false; 17600 } 17601 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17602 for (let i = 0; i < fields.length; i++) { 17603 const path = fields[i].split("."); 17604 let value = item; 17605 for (let p = 0; p < path.length; p++) { 17606 const part = path[p]; 17607 if (!value || !Object.hasOwn(value, part)) { 17608 return false; 17609 } 17610 value = value[part]; 17611 } 17612 } 17613 return true; 17614 } 17615 function __experimentalGetEntityRecordNoResolver(state, kind, name, recordId) { 17616 return getEntityRecord(state, kind, name, recordId); 17617 } 17618 var getRawEntityRecord = (0, import_data10.createSelector)( 17619 (state, kind, name, recordId) => { 17620 logEntityDeprecation(kind, name, "getRawEntityRecord"); 17621 const record = getEntityRecord( 17622 state, 17623 kind, 17624 name, 17625 recordId 17626 ); 17627 const config = getEntityConfig(state, kind, name); 17628 if (!record || !config?.rawAttributes?.length) { 17629 return record; 17630 } 17631 return Object.fromEntries( 17632 Object.keys(record).map((key) => { 17633 if (config.rawAttributes.includes(key)) { 17634 const rawValue = record[key]?.raw; 17635 return [ 17636 key, 17637 rawValue !== void 0 ? rawValue : record[key] 17638 ]; 17639 } 17640 return [key, record[key]]; 17641 }) 17642 ); 17643 }, 17644 (state, kind, name, recordId, query) => { 17645 const context = query?.context ?? "default"; 17646 return [ 17647 state.entities.config, 17648 state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId], 17649 state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId] 17650 ]; 17651 } 17652 ); 17653 function hasEntityRecords(state, kind, name, query) { 17654 logEntityDeprecation(kind, name, "hasEntityRecords"); 17655 return Array.isArray(getEntityRecords(state, kind, name, query)); 17656 } 17657 var getEntityRecords = ((state, kind, name, query) => { 17658 logEntityDeprecation(kind, name, "getEntityRecords"); 17659 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17660 if (!queriedState) { 17661 return null; 17662 } 17663 return getQueriedItems(queriedState, query, { 17664 supportsPagination: !!getEntityConfig(state, kind, name)?.supportsPagination 17665 }); 17666 }); 17667 var getEntityRecordsTotalItems = (state, kind, name, query) => { 17668 logEntityDeprecation(kind, name, "getEntityRecordsTotalItems"); 17669 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17670 if (!queriedState) { 17671 return null; 17672 } 17673 return getQueriedTotalItems(queriedState, query); 17674 }; 17675 var getEntityRecordsTotalPages = (state, kind, name, query) => { 17676 logEntityDeprecation(kind, name, "getEntityRecordsTotalPages"); 17677 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17678 if (!queriedState) { 17679 return null; 17680 } 17681 if (!getEntityConfig(state, kind, name)?.supportsPagination || query?.per_page === -1) { 17682 return 1; 17683 } 17684 const totalItems = getQueriedTotalItems(queriedState, query); 17685 if (!totalItems) { 17686 return totalItems; 17687 } 17688 if (!query?.per_page) { 17689 return getQueriedTotalPages(queriedState, query); 17690 } 17691 return Math.ceil(totalItems / query.per_page); 17692 }; 17693 var __experimentalGetDirtyEntityRecords = (0, import_data10.createSelector)( 17694 (state) => { 17695 const { 17696 entities: { records } 17697 } = state; 17698 const dirtyRecords = []; 17699 Object.keys(records).forEach((kind) => { 17700 Object.keys(records[kind]).forEach((name) => { 17701 const primaryKeys = Object.keys(records[kind][name].edits).filter( 17702 (primaryKey) => ( 17703 // The entity record must exist (not be deleted), 17704 // and it must have edits. 17705 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey) 17706 ) 17707 ); 17708 if (primaryKeys.length) { 17709 const entityConfig = getEntityConfig(state, kind, name); 17710 primaryKeys.forEach((primaryKey) => { 17711 const entityRecord = getEditedEntityRecord( 17712 state, 17713 kind, 17714 name, 17715 primaryKey 17716 ); 17717 dirtyRecords.push({ 17718 // We avoid using primaryKey because it's transformed into a string 17719 // when it's used as an object key. 17720 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0, 17721 title: entityConfig?.getTitle?.(entityRecord) || "", 17722 name, 17723 kind 17724 }); 17725 }); 17726 } 17727 }); 17728 }); 17729 return dirtyRecords; 17730 }, 17731 (state) => [state.entities.records] 17732 ); 17733 var __experimentalGetEntitiesBeingSaved = (0, import_data10.createSelector)( 17734 (state) => { 17735 const { 17736 entities: { records } 17737 } = state; 17738 const recordsBeingSaved = []; 17739 Object.keys(records).forEach((kind) => { 17740 Object.keys(records[kind]).forEach((name) => { 17741 const primaryKeys = Object.keys(records[kind][name].saving).filter( 17742 (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey) 17743 ); 17744 if (primaryKeys.length) { 17745 const entityConfig = getEntityConfig(state, kind, name); 17746 primaryKeys.forEach((primaryKey) => { 17747 const entityRecord = getEditedEntityRecord( 17748 state, 17749 kind, 17750 name, 17751 primaryKey 17752 ); 17753 recordsBeingSaved.push({ 17754 // We avoid using primaryKey because it's transformed into a string 17755 // when it's used as an object key. 17756 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0, 17757 title: entityConfig?.getTitle?.(entityRecord) || "", 17758 name, 17759 kind 17760 }); 17761 }); 17762 } 17763 }); 17764 }); 17765 return recordsBeingSaved; 17766 }, 17767 (state) => [state.entities.records] 17768 ); 17769 function getEntityRecordEdits(state, kind, name, recordId) { 17770 logEntityDeprecation(kind, name, "getEntityRecordEdits"); 17771 return state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)]; 17772 } 17773 var getEntityRecordNonTransientEdits = (0, import_data10.createSelector)( 17774 (state, kind, name, recordId) => { 17775 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits"); 17776 const { transientEdits } = getEntityConfig(state, kind, name) || {}; 17777 const edits = getEntityRecordEdits(state, kind, name, recordId) || {}; 17778 if (!transientEdits) { 17779 return edits; 17780 } 17781 return Object.keys(edits).reduce((acc, key) => { 17782 if (!transientEdits[key]) { 17783 acc[key] = edits[key]; 17784 } 17785 return acc; 17786 }, {}); 17787 }, 17788 (state, kind, name, recordId) => [ 17789 state.entities.config, 17790 state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)] 17791 ] 17792 ); 17793 function hasEditsForEntityRecord(state, kind, name, recordId) { 17794 logEntityDeprecation(kind, name, "hasEditsForEntityRecord"); 17795 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys( 17796 getEntityRecordNonTransientEdits(state, kind, name, recordId) 17797 ).length > 0; 17798 } 17799 var getEditedEntityRecord = (0, import_data10.createSelector)( 17800 (state, kind, name, recordId) => { 17801 logEntityDeprecation(kind, name, "getEditedEntityRecord"); 17802 const raw = getRawEntityRecord(state, kind, name, recordId); 17803 const edited = getEntityRecordEdits(state, kind, name, recordId); 17804 if (!raw && !edited) { 17805 return false; 17806 } 17807 return { 17808 ...raw, 17809 ...edited 17810 }; 17811 }, 17812 (state, kind, name, recordId, query) => { 17813 const context = query?.context ?? "default"; 17814 return [ 17815 state.entities.config, 17816 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId], 17817 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId], 17818 state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)] 17819 ]; 17820 } 17821 ); 17822 function isAutosavingEntityRecord(state, kind, name, recordId) { 17823 logEntityDeprecation(kind, name, "isAutosavingEntityRecord"); 17824 const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {}; 17825 return Boolean(pending && isAutosave); 17826 } 17827 function isSavingEntityRecord(state, kind, name, recordId) { 17828 logEntityDeprecation(kind, name, "isSavingEntityRecord"); 17829 return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.pending ?? false; 17830 } 17831 function isDeletingEntityRecord(state, kind, name, recordId) { 17832 logEntityDeprecation(kind, name, "isDeletingEntityRecord"); 17833 return state.entities.records?.[kind]?.[name]?.deleting?.[String(recordId)]?.pending ?? false; 17834 } 17835 function getLastEntitySaveError(state, kind, name, recordId) { 17836 logEntityDeprecation(kind, name, "getLastEntitySaveError"); 17837 return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.error; 17838 } 17839 function getLastEntityDeleteError(state, kind, name, recordId) { 17840 logEntityDeprecation(kind, name, "getLastEntityDeleteError"); 17841 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error; 17842 } 17843 function getUndoEdit(state) { 17844 (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", { 17845 since: "6.3" 17846 }); 17847 return void 0; 17848 } 17849 function getRedoEdit(state) { 17850 (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", { 17851 since: "6.3" 17852 }); 17853 return void 0; 17854 } 17855 function hasUndo(state) { 17856 return getUndoManager(state).hasUndo(); 17857 } 17858 function hasRedo(state) { 17859 return getUndoManager(state).hasRedo(); 17860 } 17861 function getCurrentTheme(state) { 17862 if (!state.currentTheme) { 17863 return null; 17864 } 17865 return getEntityRecord(state, "root", "theme", state.currentTheme); 17866 } 17867 function __experimentalGetCurrentGlobalStylesId(state) { 17868 return state.currentGlobalStylesId; 17869 } 17870 function getThemeSupports(state) { 17871 return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT2; 17872 } 17873 function getEmbedPreview(state, url) { 17874 return state.embedPreviews[url]; 17875 } 17876 function isPreviewEmbedFallback(state, url) { 17877 const preview = state.embedPreviews[url]; 17878 const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>"; 17879 if (!preview) { 17880 return false; 17881 } 17882 return preview.html === oEmbedLinkCheck; 17883 } 17884 function canUser(state, action, resource, id2) { 17885 const isEntity = typeof resource === "object"; 17886 if (isEntity && (!resource.kind || !resource.name)) { 17887 return false; 17888 } 17889 if (isEntity) { 17890 logEntityDeprecation(resource.kind, resource.name, "canUser"); 17891 } 17892 const key = getUserPermissionCacheKey(action, resource, id2); 17893 return state.userPermissions[key]; 17894 } 17895 function canUserEditEntityRecord(state, kind, name, recordId) { 17896 (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, { 17897 since: "6.7", 17898 alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )` 17899 }); 17900 return canUser(state, "update", { kind, name, id: recordId }); 17901 } 17902 function getAutosaves(state, postType, postId) { 17903 return state.autosaves[postId]; 17904 } 17905 function getAutosave(state, postType, postId, authorId) { 17906 if (authorId === void 0) { 17907 return; 17908 } 17909 const autosaves2 = state.autosaves[postId]; 17910 return autosaves2?.find( 17911 (autosave) => autosave.author === authorId 17912 ); 17913 } 17914 var hasFetchedAutosaves = (0, import_data10.createRegistrySelector)( 17915 (select6) => (state, postType, postId) => { 17916 return select6(STORE_NAME).hasFinishedResolution("getAutosaves", [ 17917 postType, 17918 postId 17919 ]); 17920 } 17921 ); 17922 function getReferenceByDistinctEdits(state) { 17923 return state.editsReference; 17924 } 17925 function __experimentalGetCurrentThemeBaseGlobalStyles(state) { 17926 const currentTheme2 = getCurrentTheme(state); 17927 if (!currentTheme2) { 17928 return null; 17929 } 17930 return state.themeBaseGlobalStyles[currentTheme2.stylesheet]; 17931 } 17932 function __experimentalGetCurrentThemeGlobalStylesVariations(state) { 17933 const currentTheme2 = getCurrentTheme(state); 17934 if (!currentTheme2) { 17935 return null; 17936 } 17937 return state.themeGlobalStyleVariations[currentTheme2.stylesheet]; 17938 } 17939 function getBlockPatterns(state) { 17940 return state.blockPatterns; 17941 } 17942 function getBlockPatternCategories(state) { 17943 return state.blockPatternCategories; 17944 } 17945 function getUserPatternCategories(state) { 17946 return state.userPatternCategories; 17947 } 17948 function getCurrentThemeGlobalStylesRevisions(state) { 17949 (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", { 17950 since: "6.5.0", 17951 alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )" 17952 }); 17953 const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state); 17954 if (!currentGlobalStylesId2) { 17955 return null; 17956 } 17957 return state.themeGlobalStyleRevisions[currentGlobalStylesId2]; 17958 } 17959 function getDefaultTemplateId(state, query) { 17960 return state.defaultTemplates[JSON.stringify(query)]; 17961 } 17962 var getRevisions = (state, kind, name, recordKey, query) => { 17963 logEntityDeprecation(kind, name, "getRevisions"); 17964 const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17965 if (!queriedStateRevisions) { 17966 return null; 17967 } 17968 return getQueriedItems(queriedStateRevisions, query); 17969 }; 17970 function hasRevision(state, kind, name, recordKey, revisionKey, query) { 17971 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17972 if (!queriedState) { 17973 return false; 17974 } 17975 const context = query?.context ?? "default"; 17976 if (!query || !query._fields) { 17977 return !!queriedState.itemIsComplete[context]?.[revisionKey]; 17978 } 17979 const item = queriedState.items[context]?.[revisionKey]; 17980 if (!item) { 17981 return false; 17982 } 17983 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17984 for (let i = 0; i < fields.length; i++) { 17985 const path = fields[i].split("."); 17986 let value = item; 17987 for (let p = 0; p < path.length; p++) { 17988 const part = path[p]; 17989 if (!value || !Object.hasOwn(value, part)) { 17990 return false; 17991 } 17992 value = value[part]; 17993 } 17994 } 17995 return true; 17996 } 17997 var getRevision = (state, kind, name, recordKey, revisionKey, query) => { 17998 logEntityDeprecation(kind, name, "getRevision"); 17999 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 18000 if (!queriedState) { 18001 return void 0; 18002 } 18003 const context = query?.context ?? "default"; 18004 if (!query || !query._fields) { 18005 if (!queriedState.itemIsComplete[context]?.[revisionKey]) { 18006 return void 0; 18007 } 18008 return queriedState.items[context][revisionKey]; 18009 } 18010 const item = queriedState.items[context]?.[revisionKey]; 18011 if (!item) { 18012 return item; 18013 } 18014 return getFilteredItem(item, query._fields); 18015 }; 18016 18017 // packages/core-data/build-module/actions.mjs 18018 var actions_exports = {}; 18019 __export(actions_exports, { 18020 __experimentalBatch: () => __experimentalBatch, 18021 __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId, 18022 __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles, 18023 __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations, 18024 __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits, 18025 __unstableCreateUndoLevel: () => __unstableCreateUndoLevel, 18026 addEntities: () => addEntities, 18027 clearEntityRecordEdits: () => clearEntityRecordEdits, 18028 deleteEntityRecord: () => deleteEntityRecord, 18029 editEntityRecord: () => editEntityRecord, 18030 receiveAutosaves: () => receiveAutosaves, 18031 receiveCurrentTheme: () => receiveCurrentTheme, 18032 receiveCurrentUser: () => receiveCurrentUser, 18033 receiveDefaultTemplateId: () => receiveDefaultTemplateId, 18034 receiveEmbedPreview: () => receiveEmbedPreview, 18035 receiveEntityRecords: () => receiveEntityRecords, 18036 receiveNavigationFallbackId: () => receiveNavigationFallbackId, 18037 receiveRevisions: () => receiveRevisions, 18038 receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions, 18039 receiveThemeSupports: () => receiveThemeSupports, 18040 receiveUploadPermissions: () => receiveUploadPermissions, 18041 receiveUserPermission: () => receiveUserPermission, 18042 receiveUserPermissions: () => receiveUserPermissions, 18043 receiveUserQuery: () => receiveUserQuery, 18044 redo: () => redo, 18045 saveEditedEntityRecord: () => saveEditedEntityRecord, 18046 saveEntityRecord: () => saveEntityRecord, 18047 undo: () => undo 18048 }); 18049 var import_api_fetch5 = __toESM(require_api_fetch(), 1); 18050 var import_url3 = __toESM(require_url(), 1); 18051 var import_deprecated3 = __toESM(require_deprecated(), 1); 18052 18053 // packages/core-data/build-module/batch/default-processor.mjs 18054 var import_api_fetch4 = __toESM(require_api_fetch(), 1); 18055 var maxItems = null; 18056 function chunk(arr, chunkSize) { 18057 const tmp = [...arr]; 18058 const cache3 = []; 18059 while (tmp.length) { 18060 cache3.push(tmp.splice(0, chunkSize)); 18061 } 18062 return cache3; 18063 } 18064 async function defaultProcessor(requests) { 18065 if (maxItems === null) { 18066 const preflightResponse = await (0, import_api_fetch4.default)({ 18067 path: "/batch/v1", 18068 method: "OPTIONS" 18069 }); 18070 maxItems = preflightResponse.endpoints[0].args.requests.maxItems; 18071 } 18072 const results = []; 18073 for (const batchRequests of chunk(requests, maxItems)) { 18074 const batchResponse = await (0, import_api_fetch4.default)({ 18075 path: "/batch/v1", 18076 method: "POST", 18077 data: { 18078 validation: "require-all-validate", 18079 requests: batchRequests.map((request) => ({ 18080 path: request.path, 18081 body: request.data, 18082 // Rename 'data' to 'body'. 18083 method: request.method, 18084 headers: request.headers 18085 })) 18086 } 18087 }); 18088 let batchResults; 18089 if (batchResponse.failed) { 18090 batchResults = batchResponse.responses.map((response) => ({ 18091 error: response?.body 18092 })); 18093 } else { 18094 batchResults = batchResponse.responses.map((response) => { 18095 const result = {}; 18096 if (response.status >= 200 && response.status < 300) { 18097 result.output = response.body; 18098 } else { 18099 result.error = response.body; 18100 } 18101 return result; 18102 }); 18103 } 18104 results.push(...batchResults); 18105 } 18106 return results; 18107 } 18108 18109 // packages/core-data/build-module/batch/create-batch.mjs 18110 function createBatch(processor = defaultProcessor) { 18111 let lastId = 0; 18112 let queue = []; 18113 const pending = new ObservableSet(); 18114 return { 18115 /** 18116 * Adds an input to the batch and returns a promise that is resolved or 18117 * rejected when the input is processed by `batch.run()`. 18118 * 18119 * You may also pass a thunk which allows inputs to be added 18120 * asynchronously. 18121 * 18122 * ``` 18123 * // Both are allowed: 18124 * batch.add( { path: '/v1/books', ... } ); 18125 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) ); 18126 * ``` 18127 * 18128 * If a thunk is passed, `batch.run()` will pause until either: 18129 * 18130 * - The thunk calls its `add` argument, or; 18131 * - The thunk returns a promise and that promise resolves, or; 18132 * - The thunk returns a non-promise. 18133 * 18134 * @param {any|Function} inputOrThunk Input to add or thunk to execute. 18135 * 18136 * @return {Promise|any} If given an input, returns a promise that 18137 * is resolved or rejected when the batch is 18138 * processed. If given a thunk, returns the return 18139 * value of that thunk. 18140 */ 18141 add(inputOrThunk) { 18142 const id2 = ++lastId; 18143 pending.add(id2); 18144 const add = (input) => new Promise((resolve, reject) => { 18145 queue.push({ 18146 input, 18147 resolve, 18148 reject 18149 }); 18150 pending.delete(id2); 18151 }); 18152 if (typeof inputOrThunk === "function") { 18153 return Promise.resolve(inputOrThunk(add)).finally(() => { 18154 pending.delete(id2); 18155 }); 18156 } 18157 return add(inputOrThunk); 18158 }, 18159 /** 18160 * Runs the batch. This calls `batchProcessor` and resolves or rejects 18161 * all promises returned by `add()`. 18162 * 18163 * @return {Promise<boolean>} A promise that resolves to a boolean that is true 18164 * if the processor returned no errors. 18165 */ 18166 async run() { 18167 if (pending.size) { 18168 await new Promise((resolve) => { 18169 const unsubscribe = pending.subscribe(() => { 18170 if (!pending.size) { 18171 unsubscribe(); 18172 resolve(void 0); 18173 } 18174 }); 18175 }); 18176 } 18177 let results; 18178 try { 18179 results = await processor( 18180 queue.map(({ input }) => input) 18181 ); 18182 if (results.length !== queue.length) { 18183 throw new Error( 18184 "run: Array returned by processor must be same size as input array." 18185 ); 18186 } 18187 } catch (error) { 18188 for (const { reject } of queue) { 18189 reject(error); 18190 } 18191 throw error; 18192 } 18193 let isSuccess = true; 18194 results.forEach((result, key) => { 18195 const queueItem = queue[key]; 18196 if (result?.error) { 18197 queueItem?.reject(result.error); 18198 isSuccess = false; 18199 } else { 18200 queueItem?.resolve(result?.output ?? result); 18201 } 18202 }); 18203 queue = []; 18204 return isSuccess; 18205 } 18206 }; 18207 } 18208 var ObservableSet = class { 18209 constructor(...args2) { 18210 this.set = new Set(...args2); 18211 this.subscribers = /* @__PURE__ */ new Set(); 18212 } 18213 get size() { 18214 return this.set.size; 18215 } 18216 add(value) { 18217 this.set.add(value); 18218 this.subscribers.forEach((subscriber) => subscriber()); 18219 return this; 18220 } 18221 delete(value) { 18222 const isSuccess = this.set.delete(value); 18223 this.subscribers.forEach((subscriber) => subscriber()); 18224 return isSuccess; 18225 } 18226 subscribe(subscriber) { 18227 this.subscribers.add(subscriber); 18228 return () => { 18229 this.subscribers.delete(subscriber); 18230 }; 18231 } 18232 }; 18233 18234 // packages/core-data/build-module/utils/sync-undo-levels.mjs 18235 var syncUndoLevelCount = 0; 18236 function createSyncUndoLevelRecord(kind, name, recordId) { 18237 syncUndoLevelCount += 1; 18238 return [ 18239 { 18240 id: { kind, name, recordId, isSyncUndoLevel: true }, 18241 changes: { 18242 level: { 18243 from: syncUndoLevelCount - 1, 18244 to: syncUndoLevelCount 18245 } 18246 } 18247 } 18248 ]; 18249 } 18250 function isSyncUndoLevel(changes) { 18251 return "string" !== typeof changes.id && true === changes.id.isSyncUndoLevel; 18252 } 18253 function getRecordReference(id2) { 18254 if ("string" === typeof id2) { 18255 return void 0; 18256 } 18257 const { kind, name, recordId } = id2; 18258 if ("string" !== typeof kind || "string" !== typeof name) { 18259 return void 0; 18260 } 18261 if ("string" !== typeof recordId && "number" !== typeof recordId) { 18262 return void 0; 18263 } 18264 return { kind, name, recordId }; 18265 } 18266 function isLoadedRecord(syncManager2, record) { 18267 if (!record) { 18268 return false; 18269 } 18270 return Boolean( 18271 syncManager2?.isLoaded?.(record.kind, record.name, record.recordId) 18272 ); 18273 } 18274 function recordEntityEdit(undoManager2, syncManager2, record, isStaged = false) { 18275 const undoHistory = syncManager2?.undoHistory; 18276 undoHistory?.stopCapturing(); 18277 undoHistory?.clearRedo(); 18278 if (!record) { 18279 undoManager2.addRecord(); 18280 return; 18281 } 18282 if (isStaged && undoManager2.hasRedo()) { 18283 undoManager2.addRecord(); 18284 } 18285 undoManager2.addRecord(record, isStaged); 18286 } 18287 function popUndoLevel(undoManager2, syncManager2, type) { 18288 const undoHistory = syncManager2?.undoHistory; 18289 let record; 18290 if ("undo" === type) { 18291 record = undoManager2.undo(); 18292 } else { 18293 record = undoManager2.redo(); 18294 } 18295 if (!record) { 18296 return void 0; 18297 } 18298 const changes = record.filter( 18299 (entry) => !isSyncUndoLevel(entry) && !isLoadedRecord(syncManager2, getRecordReference(entry.id)) 18300 ); 18301 const syncLevel = record.find(isSyncUndoLevel); 18302 let syncLevelRecord; 18303 if (syncLevel) { 18304 syncLevelRecord = getRecordReference(syncLevel.id); 18305 } 18306 let didApplySyncLevel = false; 18307 if (undoHistory && syncLevelRecord && isLoadedRecord(syncManager2, syncLevelRecord)) { 18308 const { kind, name, recordId } = syncLevelRecord; 18309 didApplySyncLevel = undoHistory[type](kind, name, recordId); 18310 } 18311 return { 18312 changes, 18313 didApply: changes.length > 0 || didApplySyncLevel 18314 }; 18315 } 18316 function applyUndoLevel(undoManager2, syncManager2, type) { 18317 syncManager2?.undoHistory?.stopCapturing(); 18318 let level = popUndoLevel(undoManager2, syncManager2, type); 18319 while (level && !level.didApply) { 18320 level = popUndoLevel(undoManager2, syncManager2, type); 18321 } 18322 if (!level) { 18323 return void 0; 18324 } 18325 syncManager2?.undoHistory?.stopCapturing(); 18326 return level.changes; 18327 } 18328 18329 // packages/core-data/build-module/actions.mjs 18330 function addTitleToAutoDraft(record) { 18331 return record.status === "auto-draft" ? { ...record, title: "" } : record; 18332 } 18333 function receiveUserQuery(queryID, users2) { 18334 return { 18335 type: "RECEIVE_USER_QUERY", 18336 users: Array.isArray(users2) ? users2 : [users2], 18337 queryID 18338 }; 18339 } 18340 function receiveCurrentUser(currentUser2) { 18341 return { 18342 type: "RECEIVE_CURRENT_USER", 18343 currentUser: currentUser2 18344 }; 18345 } 18346 function addEntities(entities2) { 18347 return { 18348 type: "ADD_ENTITIES", 18349 entities: entities2 18350 }; 18351 } 18352 function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) { 18353 if (kind === "postType") { 18354 records = Array.isArray(records) ? records.map(addTitleToAutoDraft) : addTitleToAutoDraft(records); 18355 } 18356 let action; 18357 if (query) { 18358 action = receiveQueriedItems(records, query, edits, meta); 18359 } else { 18360 action = receiveItems(records, edits, meta); 18361 } 18362 return { 18363 ...action, 18364 kind, 18365 name, 18366 invalidateCache 18367 }; 18368 } 18369 function receiveCurrentTheme(currentTheme2) { 18370 return { 18371 type: "RECEIVE_CURRENT_THEME", 18372 currentTheme: currentTheme2 18373 }; 18374 } 18375 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) { 18376 return { 18377 type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID", 18378 id: currentGlobalStylesId2 18379 }; 18380 } 18381 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) { 18382 return { 18383 type: "RECEIVE_THEME_GLOBAL_STYLES", 18384 stylesheet, 18385 globalStyles 18386 }; 18387 } 18388 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) { 18389 return { 18390 type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS", 18391 stylesheet, 18392 variations 18393 }; 18394 } 18395 function receiveThemeSupports() { 18396 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", { 18397 since: "5.9" 18398 }); 18399 return { 18400 type: "DO_NOTHING" 18401 }; 18402 } 18403 function receiveThemeGlobalStyleRevisions(currentId, revisions) { 18404 (0, import_deprecated3.default)( 18405 "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()", 18406 { 18407 since: "6.5.0", 18408 alternative: "wp.data.dispatch( 'core' ).receiveRevisions" 18409 } 18410 ); 18411 return { 18412 type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS", 18413 currentId, 18414 revisions 18415 }; 18416 } 18417 function receiveEmbedPreview(url, preview) { 18418 return { 18419 type: "RECEIVE_EMBED_PREVIEW", 18420 url, 18421 preview 18422 }; 18423 } 18424 var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 18425 logEntityDeprecation(kind, name, "deleteEntityRecord"); 18426 const configs = await resolveSelect3.getEntitiesConfig(kind); 18427 const entityConfig = configs.find( 18428 (config) => config.kind === kind && config.name === name 18429 ); 18430 let error; 18431 let deletedRecord = false; 18432 if (!entityConfig) { 18433 return; 18434 } 18435 const lock2 = await dispatch4.__unstableAcquireStoreLock( 18436 STORE_NAME, 18437 ["entities", "records", kind, name, recordId], 18438 { exclusive: true } 18439 ); 18440 try { 18441 dispatch4({ 18442 type: "DELETE_ENTITY_RECORD_START", 18443 kind, 18444 name, 18445 recordId 18446 }); 18447 let hasError = false; 18448 const { baseURL } = entityConfig; 18449 try { 18450 if (!isSafeEntityKey(recordId)) { 18451 throw new Error("Invalid entity record key."); 18452 } 18453 let path = `$baseURL}/$recordId}`; 18454 if (query) { 18455 path = (0, import_url3.addQueryArgs)(path, query); 18456 } 18457 deletedRecord = await __unstableFetch({ 18458 path, 18459 method: "DELETE" 18460 }); 18461 await dispatch4(removeItems(kind, name, recordId, true)); 18462 getEntitySyncManager()?.unload(kind, name, recordId); 18463 } catch (_error) { 18464 hasError = true; 18465 error = _error; 18466 } 18467 dispatch4({ 18468 type: "DELETE_ENTITY_RECORD_FINISH", 18469 kind, 18470 name, 18471 recordId, 18472 error 18473 }); 18474 if (hasError && throwOnError) { 18475 throw error; 18476 } 18477 return deletedRecord; 18478 } finally { 18479 dispatch4.__unstableReleaseStoreLock(lock2); 18480 } 18481 }; 18482 var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select: select6, dispatch: dispatch4 }) => { 18483 logEntityDeprecation(kind, name, "editEntityRecord"); 18484 const entityConfig = select6.getEntityConfig(kind, name); 18485 if (!entityConfig) { 18486 throw new Error( 18487 `The entity being edited ($kind}, $name}) does not have a loaded config.` 18488 ); 18489 } 18490 const { mergedEdits = {} } = entityConfig; 18491 const record = select6.getRawEntityRecord(kind, name, recordId); 18492 const editedRecord = select6.getEditedEntityRecord( 18493 kind, 18494 name, 18495 recordId 18496 ); 18497 const editsWithMerges = Object.keys(edits).reduce((acc, key) => { 18498 acc[key] = mergedEdits[key] ? { ...editedRecord[key], ...edits[key] } : edits[key]; 18499 return acc; 18500 }, {}); 18501 const edit = { 18502 kind, 18503 name, 18504 recordId, 18505 // Clear edits when they are equal to their persisted counterparts 18506 // so that the property is not considered dirty. 18507 edits: clearUnchangedEdits(editsWithMerges, record) 18508 }; 18509 const syncManager2 = getEntitySyncManager(); 18510 syncManager2?.update(kind, name, recordId, editsWithMerges, { 18511 isCached: Boolean(options.isCached), 18512 undoIgnore: Boolean(options.undoIgnore) 18513 }); 18514 if (!options.undoIgnore && !syncManager2?.isLoaded?.(kind, name, recordId)) { 18515 recordEntityEdit( 18516 select6.getUndoManager(), 18517 syncManager2, 18518 [ 18519 { 18520 id: { kind, name, recordId }, 18521 changes: Object.keys(edits).reduce((acc, key) => { 18522 acc[key] = { 18523 from: editedRecord[key], 18524 to: edits[key] 18525 }; 18526 return acc; 18527 }, {}) 18528 } 18529 ], 18530 options.isCached 18531 ); 18532 } 18533 dispatch4({ 18534 type: "EDIT_ENTITY_RECORD", 18535 ...edit 18536 }); 18537 }; 18538 var clearEntityRecordEdits = (kind, name, recordId) => ({ select: select6, dispatch: dispatch4 }) => { 18539 const entityConfig = select6.getEntityConfig(kind, name); 18540 logEntityDeprecation(kind, name, "clearEntityRecordEdits"); 18541 if (!entityConfig) { 18542 throw new Error( 18543 `The entity being edited ($kind}, $name}) does not have a loaded config.` 18544 ); 18545 } 18546 const currentEdits = select6.getEntityRecordEdits( 18547 kind, 18548 name, 18549 recordId 18550 ); 18551 if (!currentEdits) { 18552 return; 18553 } 18554 const clearedEdits = Object.keys(currentEdits).reduce( 18555 (acc, key) => { 18556 acc[key] = void 0; 18557 return acc; 18558 }, 18559 {} 18560 ); 18561 dispatch4({ 18562 type: "EDIT_ENTITY_RECORD", 18563 kind, 18564 name, 18565 recordId, 18566 edits: clearedEdits 18567 }); 18568 }; 18569 var undo = () => ({ select: select6, dispatch: dispatch4 }) => { 18570 const undoRecord = applyUndoLevel( 18571 select6.getUndoManager(), 18572 getEntitySyncManager(), 18573 "undo" 18574 ); 18575 if (!undoRecord) { 18576 return; 18577 } 18578 dispatch4({ 18579 type: "UNDO", 18580 record: undoRecord 18581 }); 18582 }; 18583 var redo = () => ({ select: select6, dispatch: dispatch4 }) => { 18584 const redoRecord = applyUndoLevel( 18585 select6.getUndoManager(), 18586 getEntitySyncManager(), 18587 "redo" 18588 ); 18589 if (!redoRecord) { 18590 return; 18591 } 18592 dispatch4({ 18593 type: "REDO", 18594 record: redoRecord 18595 }); 18596 }; 18597 var __unstableCreateUndoLevel = () => ({ select: select6 }) => { 18598 recordEntityEdit(select6.getUndoManager(), getEntitySyncManager()); 18599 }; 18600 var saveEntityRecord = (kind, name, record, options = {}) => async ({ select: select6, resolveSelect: resolveSelect3, dispatch: dispatch4 }) => { 18601 const { 18602 isAutosave = false, 18603 __unstableFetch = import_api_fetch5.default, 18604 throwOnError = false 18605 } = options; 18606 logEntityDeprecation(kind, name, "saveEntityRecord"); 18607 const configs = await resolveSelect3.getEntitiesConfig(kind); 18608 const entityConfig = configs.find( 18609 (config) => config.kind === kind && config.name === name 18610 ); 18611 if (!entityConfig) { 18612 return; 18613 } 18614 const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY; 18615 const recordId = record[entityIdKey]; 18616 const isNewRecord = !!entityIdKey && !recordId; 18617 const lock2 = await dispatch4.__unstableAcquireStoreLock( 18618 STORE_NAME, 18619 ["entities", "records", kind, name, recordId || v4_default()], 18620 { exclusive: true } 18621 ); 18622 try { 18623 for (const [key, value] of Object.entries(record)) { 18624 if (typeof value === "function") { 18625 const evaluatedValue = value( 18626 select6.getEditedEntityRecord(kind, name, recordId) 18627 ); 18628 dispatch4.editEntityRecord( 18629 kind, 18630 name, 18631 recordId, 18632 { 18633 [key]: evaluatedValue 18634 }, 18635 { undoIgnore: true } 18636 ); 18637 record[key] = evaluatedValue; 18638 } 18639 } 18640 dispatch4({ 18641 type: "SAVE_ENTITY_RECORD_START", 18642 kind, 18643 name, 18644 recordId, 18645 isAutosave 18646 }); 18647 let updatedRecord; 18648 let error; 18649 let hasError = false; 18650 const { baseURL } = entityConfig; 18651 try { 18652 if (!isSafeEntityKey(recordId)) { 18653 throw new Error("Invalid entity record key."); 18654 } 18655 const path = `$baseURL}$recordId ? "/" + recordId : ""}`; 18656 const persistedRecord = !isNewRecord ? select6.getRawEntityRecord(kind, name, recordId) : {}; 18657 const syncManager2 = getEntitySyncManager(); 18658 const syncEdits = isNewRecord ? void 0 : await syncManager2?.beforeSave?.( 18659 kind, 18660 name, 18661 recordId, 18662 record, 18663 { persistedRecord, isAutosave } 18664 ); 18665 if (isAutosave) { 18666 const merged = { ...persistedRecord, ...record }; 18667 const data = [ 18668 "title", 18669 "excerpt", 18670 "content", 18671 "meta" 18672 ].reduce( 18673 (acc, key) => { 18674 if (key in merged) { 18675 acc[key] = merged[key]; 18676 } 18677 return acc; 18678 }, 18679 { 18680 // Do not update the `status` if we have edited it when auto saving. 18681 // It's very important to let the user explicitly save this change, 18682 // because it can lead to unexpected results. An example would be to 18683 // have a draft post and change the status to publish. 18684 status: merged.status === "auto-draft" ? "draft" : void 0 18685 } 18686 ); 18687 updatedRecord = await __unstableFetch({ 18688 path: `$path}/autosaves`, 18689 method: "POST", 18690 data: { ...data, ...syncEdits } 18691 }); 18692 if (persistedRecord.id === updatedRecord.id) { 18693 let newRecord = { 18694 ...persistedRecord, 18695 ...data, 18696 ...updatedRecord 18697 }; 18698 newRecord = Object.keys(newRecord).reduce( 18699 (acc, key) => { 18700 if ([ 18701 "title", 18702 "excerpt", 18703 "content", 18704 "meta" 18705 ].includes(key)) { 18706 acc[key] = newRecord[key]; 18707 } else if (key === "status") { 18708 acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status; 18709 } else { 18710 acc[key] = persistedRecord[key]; 18711 } 18712 return acc; 18713 }, 18714 {} 18715 ); 18716 dispatch4.receiveEntityRecords( 18717 kind, 18718 name, 18719 newRecord, 18720 void 0, 18721 true 18722 ); 18723 } else { 18724 dispatch4.receiveAutosaves( 18725 persistedRecord.id, 18726 updatedRecord 18727 ); 18728 } 18729 } else { 18730 let edits = { ...record, ...syncEdits }; 18731 if (entityConfig.__unstablePrePersist) { 18732 edits = { 18733 ...edits, 18734 ...await entityConfig.__unstablePrePersist( 18735 persistedRecord, 18736 edits 18737 ) 18738 }; 18739 } 18740 updatedRecord = await __unstableFetch({ 18741 path, 18742 method: recordId ? "PUT" : "POST", 18743 data: edits 18744 }); 18745 dispatch4.receiveEntityRecords( 18746 kind, 18747 name, 18748 updatedRecord, 18749 void 0, 18750 true, 18751 record 18752 ); 18753 syncManager2?.afterSave?.(kind, name, recordId, { 18754 savedRecord: updatedRecord, 18755 persistedRecord: isNewRecord ? void 0 : persistedRecord, 18756 edits: record 18757 }); 18758 } 18759 } catch (_error) { 18760 hasError = true; 18761 error = _error; 18762 } 18763 dispatch4({ 18764 type: "SAVE_ENTITY_RECORD_FINISH", 18765 kind, 18766 name, 18767 recordId, 18768 error, 18769 isAutosave 18770 }); 18771 if (hasError && throwOnError) { 18772 throw error; 18773 } 18774 return updatedRecord; 18775 } finally { 18776 dispatch4.__unstableReleaseStoreLock(lock2); 18777 } 18778 }; 18779 var __experimentalBatch = (requests) => async ({ dispatch: dispatch4 }) => { 18780 const batch = createBatch(); 18781 const api = { 18782 saveEntityRecord(kind, name, record, options) { 18783 return batch.add( 18784 (add) => dispatch4.saveEntityRecord(kind, name, record, { 18785 ...options, 18786 __unstableFetch: add 18787 }) 18788 ); 18789 }, 18790 saveEditedEntityRecord(kind, name, recordId, options) { 18791 return batch.add( 18792 (add) => dispatch4.saveEditedEntityRecord(kind, name, recordId, { 18793 ...options, 18794 __unstableFetch: add 18795 }) 18796 ); 18797 }, 18798 deleteEntityRecord(kind, name, recordId, query, options) { 18799 return batch.add( 18800 (add) => dispatch4.deleteEntityRecord(kind, name, recordId, query, { 18801 ...options, 18802 __unstableFetch: add 18803 }) 18804 ); 18805 } 18806 }; 18807 const resultPromises = requests.map((request) => request(api)); 18808 const [, ...results] = await Promise.all([ 18809 batch.run(), 18810 ...resultPromises 18811 ]); 18812 return results; 18813 }; 18814 var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select: select6, dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 18815 logEntityDeprecation(kind, name, "saveEditedEntityRecord"); 18816 if (!select6.hasEditsForEntityRecord(kind, name, recordId)) { 18817 return; 18818 } 18819 const configs = await resolveSelect3.getEntitiesConfig(kind); 18820 const entityConfig = configs.find( 18821 (config) => config.kind === kind && config.name === name 18822 ); 18823 if (!entityConfig) { 18824 return; 18825 } 18826 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; 18827 const edits = select6.getEntityRecordNonTransientEdits( 18828 kind, 18829 name, 18830 recordId 18831 ); 18832 const record = { [entityIdKey]: recordId, ...edits }; 18833 return await dispatch4.saveEntityRecord(kind, name, record, options); 18834 }; 18835 var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select: select6, dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 18836 logEntityDeprecation( 18837 kind, 18838 name, 18839 "__experimentalSaveSpecifiedEntityEdits" 18840 ); 18841 if (!select6.hasEditsForEntityRecord(kind, name, recordId)) { 18842 return; 18843 } 18844 const edits = select6.getEntityRecordNonTransientEdits( 18845 kind, 18846 name, 18847 recordId 18848 ); 18849 const editsToSave = {}; 18850 for (const item of itemsToSave) { 18851 setNestedValue(editsToSave, item, getNestedValue(edits, item)); 18852 } 18853 const configs = await resolveSelect3.getEntitiesConfig(kind); 18854 const entityConfig = configs.find( 18855 (config) => config.kind === kind && config.name === name 18856 ); 18857 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY; 18858 if (recordId) { 18859 editsToSave[entityIdKey] = recordId; 18860 } 18861 return await dispatch4.saveEntityRecord( 18862 kind, 18863 name, 18864 editsToSave, 18865 options 18866 ); 18867 }; 18868 function receiveUploadPermissions(hasUploadPermissions) { 18869 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", { 18870 since: "5.9", 18871 alternative: "receiveUserPermission" 18872 }); 18873 return receiveUserPermission("create/media", hasUploadPermissions); 18874 } 18875 function receiveUserPermission(key, isAllowed) { 18876 return { 18877 type: "RECEIVE_USER_PERMISSION", 18878 key, 18879 isAllowed 18880 }; 18881 } 18882 function receiveUserPermissions(permissions) { 18883 return { 18884 type: "RECEIVE_USER_PERMISSIONS", 18885 permissions 18886 }; 18887 } 18888 function receiveAutosaves(postId, autosaves2) { 18889 return { 18890 type: "RECEIVE_AUTOSAVES", 18891 postId, 18892 autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2] 18893 }; 18894 } 18895 function receiveNavigationFallbackId(fallbackId) { 18896 return { 18897 type: "RECEIVE_NAVIGATION_FALLBACK_ID", 18898 fallbackId 18899 }; 18900 } 18901 function receiveDefaultTemplateId(query, templateId) { 18902 return { 18903 type: "RECEIVE_DEFAULT_TEMPLATE", 18904 query, 18905 templateId 18906 }; 18907 } 18908 var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 18909 logEntityDeprecation(kind, name, "receiveRevisions"); 18910 const configs = await resolveSelect3.getEntitiesConfig(kind); 18911 const entityConfig = configs.find( 18912 (config) => config.kind === kind && config.name === name 18913 ); 18914 const key = entityConfig?.revisionKey ?? DEFAULT_ENTITY_KEY; 18915 dispatch4({ 18916 type: "RECEIVE_ITEM_REVISIONS", 18917 key, 18918 items: records, 18919 recordKey, 18920 meta, 18921 query, 18922 kind, 18923 name, 18924 invalidateCache 18925 }); 18926 }; 18927 18928 // packages/core-data/build-module/private-actions.mjs 18929 var private_actions_exports = {}; 18930 __export(private_actions_exports, { 18931 editMediaEntity: () => editMediaEntity, 18932 receiveEditorAssets: () => receiveEditorAssets, 18933 receiveEditorSettings: () => receiveEditorSettings, 18934 receiveEntityActionsConfig: () => receiveEntityActionsConfig, 18935 receiveFieldsConfig: () => receiveFieldsConfig, 18936 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta, 18937 receiveViewConfig: () => receiveViewConfig, 18938 recordSyncUndoLevel: () => recordSyncUndoLevel, 18939 saveDirtyEntities: () => saveDirtyEntities, 18940 setCollaborationSupported: () => setCollaborationSupported, 18941 setSyncConnectionStatus: () => setSyncConnectionStatus 18942 }); 18943 var import_api_fetch6 = __toESM(require_api_fetch(), 1); 18944 var import_notices = __toESM(require_notices(), 1); 18945 var import_block_editor5 = __toESM(require_block_editor(), 1); 18946 var import_html_entities = __toESM(require_html_entities(), 1); 18947 var import_i18n2 = __toESM(require_i18n(), 1); 18948 function receiveRegisteredPostMeta(postType, registeredPostMeta2) { 18949 return { 18950 type: "RECEIVE_REGISTERED_POST_META", 18951 postType, 18952 registeredPostMeta: registeredPostMeta2 18953 }; 18954 } 18955 var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch6.default, throwOnError = false } = {}) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 18956 if (!recordId) { 18957 return; 18958 } 18959 const kind = "postType"; 18960 const name = "attachment"; 18961 const configs = await resolveSelect3.getEntitiesConfig(kind); 18962 const entityConfig = configs.find( 18963 (config) => config.kind === kind && config.name === name 18964 ); 18965 if (!entityConfig) { 18966 return; 18967 } 18968 const lock2 = await dispatch4.__unstableAcquireStoreLock( 18969 STORE_NAME, 18970 ["entities", "records", kind, name, recordId], 18971 { exclusive: true } 18972 ); 18973 let updatedRecord; 18974 let error; 18975 let hasError = false; 18976 try { 18977 dispatch4({ 18978 type: "SAVE_ENTITY_RECORD_START", 18979 kind, 18980 name, 18981 recordId 18982 }); 18983 try { 18984 if (!isSafeEntityKey(recordId)) { 18985 throw new Error("Invalid entity record key."); 18986 } 18987 const path = `$entityConfig.baseURL}/$recordId}/edit`; 18988 const newRecord = await __unstableFetch({ 18989 path, 18990 method: "POST", 18991 data: { 18992 ...edits 18993 } 18994 }); 18995 if (newRecord) { 18996 dispatch4.receiveEntityRecords( 18997 kind, 18998 name, 18999 newRecord, 19000 void 0, 19001 true, 19002 void 0, 19003 void 0 19004 ); 19005 updatedRecord = newRecord; 19006 } 19007 } catch (e) { 19008 error = e; 19009 hasError = true; 19010 } 19011 dispatch4({ 19012 type: "SAVE_ENTITY_RECORD_FINISH", 19013 kind, 19014 name, 19015 recordId, 19016 error 19017 }); 19018 if (hasError && throwOnError) { 19019 throw error; 19020 } 19021 return updatedRecord; 19022 } finally { 19023 dispatch4.__unstableReleaseStoreLock(lock2); 19024 } 19025 }; 19026 function receiveEditorSettings(settings) { 19027 return { 19028 type: "RECEIVE_EDITOR_SETTINGS", 19029 settings 19030 }; 19031 } 19032 function receiveEditorAssets(assets) { 19033 return { 19034 type: "RECEIVE_EDITOR_ASSETS", 19035 assets 19036 }; 19037 } 19038 var setCollaborationSupported = (supported) => ({ dispatch: dispatch4 }) => { 19039 dispatch4({ type: "SET_COLLABORATION_SUPPORTED", supported }); 19040 if (!supported) { 19041 getEntitySyncManager()?.unloadAll(); 19042 } 19043 }; 19044 function receiveViewConfig(kind, name, config) { 19045 return { 19046 type: "RECEIVE_VIEW_CONFIG", 19047 kind, 19048 name, 19049 config 19050 }; 19051 } 19052 function receiveFieldsConfig(kind, name, config) { 19053 return { 19054 type: "RECEIVE_FIELDS_CONFIG", 19055 kind, 19056 name, 19057 config 19058 }; 19059 } 19060 function receiveEntityActionsConfig(kind, name, config) { 19061 return { 19062 type: "RECEIVE_ENTITY_ACTIONS_CONFIG", 19063 kind, 19064 name, 19065 config 19066 }; 19067 } 19068 var recordSyncUndoLevel = (kind, name, recordId) => ({ select: select6, dispatch: dispatch4 }) => { 19069 select6.getUndoManager().addRecord(createSyncUndoLevelRecord(kind, name, recordId)); 19070 dispatch4({ type: "RECORD_SYNC_UNDO_LEVEL" }); 19071 }; 19072 function setSyncConnectionStatus(kind, name, key, status) { 19073 if (!status) { 19074 return { 19075 type: "CLEAR_SYNC_CONNECTION_STATUS", 19076 kind, 19077 name, 19078 key 19079 }; 19080 } 19081 return { 19082 type: "SET_SYNC_CONNECTION_STATUS", 19083 kind, 19084 name, 19085 key, 19086 status 19087 }; 19088 } 19089 var saveDirtyEntities = ({ 19090 onSave, 19091 dirtyEntityRecords = [], 19092 entitiesToSkip = [], 19093 close, 19094 successNoticeContent 19095 } = {}) => ({ registry }) => { 19096 const PUBLISH_ON_SAVE_ENTITIES = [ 19097 { kind: "postType", name: "wp_navigation" } 19098 ]; 19099 const saveNoticeId = "site-editor-save-success"; 19100 const homeUrl = registry.select(STORE_NAME).getEntityRecord("root", "__unstableBase")?.home; 19101 registry.dispatch(import_notices.store).removeNotice(saveNoticeId); 19102 const entitiesToSave = dirtyEntityRecords.filter( 19103 ({ kind, name, key, property }) => { 19104 return !entitiesToSkip.some( 19105 (elt) => elt.kind === kind && elt.name === name && elt.key === key && elt.property === property 19106 ); 19107 } 19108 ); 19109 close?.(entitiesToSave); 19110 const siteItemsToSave = []; 19111 const pendingSavedRecords = []; 19112 entitiesToSave.forEach(({ kind, name, key, property }) => { 19113 if ("root" === kind && "site" === name) { 19114 siteItemsToSave.push(property); 19115 } else { 19116 if (PUBLISH_ON_SAVE_ENTITIES.some( 19117 (typeToPublish) => typeToPublish.kind === kind && typeToPublish.name === name 19118 )) { 19119 registry.dispatch(STORE_NAME).editEntityRecord(kind, name, key, { 19120 status: "publish" 19121 }); 19122 } 19123 pendingSavedRecords.push( 19124 registry.dispatch(STORE_NAME).saveEditedEntityRecord(kind, name, key, { 19125 throwOnError: true 19126 }).catch(ensureError) 19127 ); 19128 } 19129 }); 19130 if (siteItemsToSave.length) { 19131 pendingSavedRecords.push( 19132 registry.dispatch(STORE_NAME).__experimentalSaveSpecifiedEntityEdits( 19133 "root", 19134 "site", 19135 void 0, 19136 siteItemsToSave, 19137 { 19138 throwOnError: true 19139 } 19140 ).catch(ensureError) 19141 ); 19142 } 19143 registry.dispatch(import_block_editor5.store).__unstableMarkLastChangeAsPersistent(); 19144 return Promise.all(pendingSavedRecords).then(async (values) => { 19145 if (onSave) { 19146 await onSave(); 19147 } 19148 return values; 19149 }).then((values) => { 19150 const errors = values.filter((v) => v instanceof Error); 19151 if (errors.length) { 19152 const firstMessage = errors.find( 19153 (e) => e.message 19154 )?.message; 19155 registry.dispatch(import_notices.store).createErrorNotice( 19156 (0, import_html_entities.decodeEntities)( 19157 firstMessage || (0, import_i18n2.__)("Saving failed.") 19158 ), 19159 { 19160 type: "snackbar", 19161 id: saveNoticeId 19162 } 19163 ); 19164 } else { 19165 registry.dispatch(import_notices.store).createSuccessNotice( 19166 successNoticeContent || (0, import_i18n2.__)("Site updated."), 19167 { 19168 type: "snackbar", 19169 id: saveNoticeId, 19170 actions: [ 19171 { 19172 label: (0, import_i18n2.__)("View site"), 19173 url: homeUrl, 19174 openInNewTab: true 19175 } 19176 ] 19177 } 19178 ); 19179 } 19180 }).catch( 19181 (error) => registry.dispatch(import_notices.store).createErrorNotice( 19182 (0, import_html_entities.decodeEntities)( 19183 error?.message || (0, import_i18n2.__)("Saving failed.") 19184 ), 19185 { 19186 type: "snackbar", 19187 id: saveNoticeId 19188 } 19189 ) 19190 ); 19191 function ensureError(error) { 19192 if (error instanceof Error) { 19193 return error; 19194 } 19195 let message; 19196 if (!error) { 19197 } else if (typeof error.message === "string") { 19198 message = error.message; 19199 } else if (typeof error === "string") { 19200 message = error; 19201 } else if ( 19202 // Only consider own method, lest we erroneously end up calling 19203 // `Object#toString` at the end of the prototype chain, thereby 19204 // returning `"[object Object]"`. 19205 Object.hasOwn(error, "toString") && typeof error.toString === "function" 19206 ) { 19207 const result = error.toString(); 19208 if (typeof result === "string") { 19209 message = result; 19210 } 19211 } 19212 return new Error(message, { cause: error }); 19213 } 19214 }; 19215 19216 // packages/core-data/build-module/resolvers.mjs 19217 var resolvers_exports = {}; 19218 __export(resolvers_exports, { 19219 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2, 19220 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2, 19221 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2, 19222 canUser: () => canUser2, 19223 canUserEditEntityRecord: () => canUserEditEntityRecord2, 19224 getAuthors: () => getAuthors2, 19225 getAutosave: () => getAutosave2, 19226 getAutosaves: () => getAutosaves2, 19227 getBlockPatternCategories: () => getBlockPatternCategories2, 19228 getBlockPatterns: () => getBlockPatterns2, 19229 getCurrentTheme: () => getCurrentTheme2, 19230 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2, 19231 getCurrentUser: () => getCurrentUser2, 19232 getDefaultTemplateId: () => getDefaultTemplateId2, 19233 getEditedEntityRecord: () => getEditedEntityRecord2, 19234 getEditorAssets: () => getEditorAssets2, 19235 getEditorSettings: () => getEditorSettings2, 19236 getEmbedPreview: () => getEmbedPreview2, 19237 getEntitiesConfig: () => getEntitiesConfig2, 19238 getEntityActionsConfig: () => getEntityActionsConfig2, 19239 getEntityRecord: () => getEntityRecord2, 19240 getEntityRecords: () => getEntityRecords2, 19241 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2, 19242 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2, 19243 getFieldsConfig: () => getFieldsConfig2, 19244 getNavigationFallbackId: () => getNavigationFallbackId2, 19245 getRawEntityRecord: () => getRawEntityRecord2, 19246 getRegisteredPostMeta: () => getRegisteredPostMeta2, 19247 getRevision: () => getRevision2, 19248 getRevisions: () => getRevisions2, 19249 getThemeSupports: () => getThemeSupports2, 19250 getUserPatternCategories: () => getUserPatternCategories2, 19251 getViewConfig: () => getViewConfig2 19252 }); 19253 var import_url6 = __toESM(require_url(), 1); 19254 var import_html_entities3 = __toESM(require_html_entities(), 1); 19255 var import_api_fetch10 = __toESM(require_api_fetch(), 1); 19256 19257 // packages/core-data/build-module/fetch/index.mjs 19258 var import_api_fetch9 = __toESM(require_api_fetch(), 1); 19259 19260 // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs 19261 var import_api_fetch7 = __toESM(require_api_fetch(), 1); 19262 var import_url4 = __toESM(require_url(), 1); 19263 var import_html_entities2 = __toESM(require_html_entities(), 1); 19264 var import_i18n3 = __toESM(require_i18n(), 1); 19265 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) { 19266 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? { 19267 ...searchOptions, 19268 ...searchOptions.initialSuggestionsSearchOptions 19269 } : searchOptions; 19270 const { 19271 type, 19272 subtype, 19273 preferTypes, 19274 page, 19275 perPage = searchOptions.isInitialSuggestions ? 3 : 20 19276 } = searchOptionsToUse; 19277 const { disablePostFormats = false } = editorSettings2; 19278 const queries2 = []; 19279 if (!type || type === "post") { 19280 queries2.push( 19281 (0, import_api_fetch7.default)({ 19282 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 19283 search, 19284 page, 19285 per_page: perPage, 19286 type: "post", 19287 subtype 19288 }) 19289 }).then((results2) => { 19290 return results2.map((result) => { 19291 return { 19292 id: result.id, 19293 url: result.url, 19294 title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"), 19295 type: result.subtype || result.type, 19296 kind: "post-type" 19297 }; 19298 }); 19299 }).catch(() => []) 19300 // Fail by returning no results. 19301 ); 19302 } 19303 if (!type || type === "term") { 19304 queries2.push( 19305 (0, import_api_fetch7.default)({ 19306 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 19307 search, 19308 page, 19309 per_page: perPage, 19310 type: "term", 19311 subtype 19312 }) 19313 }).then((results2) => { 19314 return results2.map((result) => { 19315 return { 19316 id: result.id, 19317 url: result.url, 19318 title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"), 19319 type: result.subtype || result.type, 19320 kind: "taxonomy" 19321 }; 19322 }); 19323 }).catch(() => []) 19324 // Fail by returning no results. 19325 ); 19326 } 19327 if (!disablePostFormats && (!type || type === "post-format")) { 19328 queries2.push( 19329 (0, import_api_fetch7.default)({ 19330 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 19331 search, 19332 page, 19333 per_page: perPage, 19334 type: "post-format", 19335 subtype 19336 }) 19337 }).then((results2) => { 19338 return results2.map((result) => { 19339 return { 19340 id: result.id, 19341 url: result.url, 19342 title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"), 19343 type: result.subtype || result.type, 19344 kind: "taxonomy" 19345 }; 19346 }); 19347 }).catch(() => []) 19348 // Fail by returning no results. 19349 ); 19350 } 19351 if (!type || type === "attachment") { 19352 queries2.push( 19353 (0, import_api_fetch7.default)({ 19354 path: (0, import_url4.addQueryArgs)("/wp/v2/media", { 19355 search, 19356 page, 19357 per_page: perPage 19358 }) 19359 }).then((results2) => { 19360 return results2.map((result) => { 19361 return { 19362 id: result.id, 19363 url: result.source_url, 19364 title: (0, import_html_entities2.decodeEntities)(result.title.rendered || "") || (0, import_i18n3.__)("(no title)"), 19365 type: result.type, 19366 kind: "media" 19367 }; 19368 }); 19369 }).catch(() => []) 19370 // Fail by returning no results. 19371 ); 19372 } 19373 const responses = await Promise.all(queries2); 19374 let results = responses.flat(); 19375 results = results.filter((result) => !!result.id); 19376 return sortResults({ results, search, preferTypes }); 19377 } 19378 function getTitleMatch(title, search) { 19379 const plain = (text2) => (text2 ?? "").toLowerCase().trim().replace(/[\u2018\u2019]/g, "'").replace(/[\u201c\u201d]/g, '"'); 19380 const haystack = plain(title); 19381 const needle = plain(search); 19382 if (!haystack || !needle) { 19383 return { contains: false, begins: false }; 19384 } 19385 return { 19386 contains: haystack.includes(needle), 19387 begins: haystack.startsWith(needle) 19388 }; 19389 } 19390 var TYPE_ORDER = [ 19391 "post", 19392 "term", 19393 "post-format", 19394 "attachment" 19395 ]; 19396 function getSearchType(result) { 19397 if (result.kind === "media") { 19398 return "attachment"; 19399 } 19400 if (result.type === "post-format") { 19401 return "post-format"; 19402 } 19403 return result.kind === "taxonomy" ? "term" : "post"; 19404 } 19405 function getTypeRank(result, preferTypes = []) { 19406 const searchType = getSearchType(result); 19407 const preferred = preferTypes.findIndex( 19408 (entry) => typeof entry === "string" ? entry === searchType : entry.type === searchType && entry.subtype === result.type 19409 ); 19410 if (preferred !== -1) { 19411 return TYPE_ORDER.length + (preferTypes.length - preferred); 19412 } 19413 return TYPE_ORDER.length - TYPE_ORDER.indexOf(searchType); 19414 } 19415 function countWordsFound(title, searchTokens) { 19416 const titleTokens = tokenize2(title || ""); 19417 return searchTokens.filter( 19418 (searchToken) => titleTokens.some((titleToken) => titleToken.includes(searchToken)) 19419 ).length; 19420 } 19421 function getCoverage(title, searchTokens) { 19422 if (!title || !searchTokens.length) { 19423 return 0; 19424 } 19425 const titleTokens = tokenize2(title); 19426 const covered = searchTokens.reduce((total, searchToken) => { 19427 const best = titleTokens.reduce( 19428 (most, titleToken) => titleToken.includes(searchToken) ? Math.max(most, searchToken.length / titleToken.length) : most, 19429 0 19430 ); 19431 return total + best; 19432 }, 0); 19433 return covered / searchTokens.length * 10; 19434 } 19435 function isExactTitle(title, searchTokens) { 19436 const titleTokens = tokenize2(title || ""); 19437 return titleTokens.length > 0 && titleTokens.join(" ") === searchTokens.join(" "); 19438 } 19439 function sortResults({ 19440 results, 19441 search, 19442 preferTypes 19443 }) { 19444 const searchTokens = tokenize2(search); 19445 const scored = results.map((result) => ({ 19446 result, 19447 found: countWordsFound(result.title, searchTokens), 19448 ...getTitleMatch(result.title, search), 19449 type: getTypeRank(result, preferTypes), 19450 score: getCoverage(result.title, searchTokens), 19451 exact: isExactTitle(result.title, searchTokens) 19452 })); 19453 scored.sort( 19454 (a, b) => ( 19455 // Does the title contain all words searched or just one? 19456 // If the search is "black cat" then "Black is my favorite color" should rank lower than "Cats that are black" 19457 b.found - a.found || // Then whether it holds them together, as one string: i.e. "Black cats are great" vs "Cats that are black" 19458 Number(b.contains) - Number(a.contains) || // Matches are equal so far, so enforce banding by type 19459 b.type - a.type || // Within a band, a title that is exactly the search comes first, whatever its punctuation: 19460 // the search "coffee beans" ranks "“Coffee Beans”" above "Coffee Beans, Lightly Roasted" 19461 Number(b.exact) - Number(a.exact) || // Then, rank matches that start with the search string higher than mid-string matches: 19462 // i.e the search "cat" ranks the title "caterpillar" higher than "concatenate" 19463 Number(b.begins) - Number(a.begins) || // Rank by how much of the matched word the search contains: the search 19464 // "cat" ranks the title "Cats" above the title "Caterpillar" since cat is 75% of "Cats" 19465 // and only 27% of "Caterpillar" 19466 b.score - a.score 19467 ) 19468 ); 19469 return scored.map(({ result }) => result); 19470 } 19471 function tokenize2(text2) { 19472 return text2.toLowerCase().match(/[\p{L}\p{N}]+/gu) || []; 19473 } 19474 19475 // packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs 19476 var import_api_fetch8 = __toESM(require_api_fetch(), 1); 19477 var import_url5 = __toESM(require_url(), 1); 19478 var CACHE = /* @__PURE__ */ new Map(); 19479 var fetchUrlData = async (url, options = {}) => { 19480 const endpoint = "/wp-block-editor/v1/url-details"; 19481 const args2 = { 19482 url: (0, import_url5.prependHTTP)(url) 19483 }; 19484 if (!(0, import_url5.isURL)(url)) { 19485 return Promise.reject(`$url} is not a valid URL.`); 19486 } 19487 const protocol = (0, import_url5.getProtocol)(url); 19488 if (!protocol || !(0, import_url5.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) { 19489 return Promise.reject( 19490 `$url} does not have a valid protocol. URLs must be "http" based` 19491 ); 19492 } 19493 if (CACHE.has(url)) { 19494 return CACHE.get(url); 19495 } 19496 return (0, import_api_fetch8.default)({ 19497 path: (0, import_url5.addQueryArgs)(endpoint, args2), 19498 ...options 19499 }).then((res) => { 19500 CACHE.set(url, res); 19501 return res; 19502 }); 19503 }; 19504 var experimental_fetch_url_data_default = fetchUrlData; 19505 19506 // packages/core-data/build-module/fetch/index.mjs 19507 async function fetchBlockPatterns() { 19508 const restPatterns = await (0, import_api_fetch9.default)({ 19509 path: "/wp/v2/block-patterns/patterns" 19510 }); 19511 if (!restPatterns) { 19512 return []; 19513 } 19514 return restPatterns.map( 19515 (pattern) => Object.fromEntries( 19516 Object.entries(pattern).map(([key, value]) => [ 19517 camelCase(key), 19518 value 19519 ]) 19520 ) 19521 ); 19522 } 19523 19524 // packages/core-data/build-module/parsed-blocks-cache.mjs 19525 var import_data11 = __toESM(require_data(), 1); 19526 var import_blocks5 = __toESM(require_blocks(), 1); 19527 var caches = /* @__PURE__ */ new WeakMap(); 19528 function getCacheKey(kind, name, id2) { 19529 return `$kind}:$name}:$id2}`; 19530 } 19531 function getBlockTypes2() { 19532 return (0, import_data11.select)(import_blocks5.store).getBlockTypes(); 19533 } 19534 function getCachedBlocks(kind, name, id2, content) { 19535 const cached = caches.get(getBlockTypes2())?.get(getCacheKey(kind, name, id2)); 19536 if (cached && cached.content === content) { 19537 return cached.blocks; 19538 } 19539 } 19540 function setCachedBlocks(kind, name, id2, content, blocks) { 19541 const blockTypes = getBlockTypes2(); 19542 let cache3 = caches.get(blockTypes); 19543 if (!cache3) { 19544 cache3 = /* @__PURE__ */ new Map(); 19545 caches.set(blockTypes, cache3); 19546 } 19547 cache3.set(getCacheKey(kind, name, id2), { content, blocks }); 19548 } 19549 19550 // packages/core-data/build-module/resolvers.mjs 19551 var getAuthors2 = (query) => async ({ dispatch: dispatch4 }) => { 19552 const path = (0, import_url6.addQueryArgs)( 19553 "/wp/v2/users/?who=authors&per_page=100", 19554 query 19555 ); 19556 const users2 = await (0, import_api_fetch10.default)({ path }); 19557 dispatch4.receiveUserQuery(path, users2); 19558 }; 19559 var getCurrentUser2 = () => async ({ dispatch: dispatch4 }) => { 19560 const currentUser2 = await (0, import_api_fetch10.default)({ path: "/wp/v2/users/me" }); 19561 dispatch4.receiveCurrentUser(currentUser2); 19562 }; 19563 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select6, dispatch: dispatch4, registry, resolveSelect: resolveSelect3 }) => { 19564 const configs = await resolveSelect3.getEntitiesConfig(kind); 19565 const entityConfig = configs.find( 19566 (config) => config.name === name && config.kind === kind 19567 ); 19568 if (!entityConfig) { 19569 return; 19570 } 19571 if (!isSafeEntityKey(key)) { 19572 return; 19573 } 19574 const lock2 = await dispatch4.__unstableAcquireStoreLock( 19575 STORE_NAME, 19576 ["entities", "records", kind, name, key], 19577 { exclusive: false } 19578 ); 19579 try { 19580 if (query !== void 0 && query._fields) { 19581 query = { 19582 ...query, 19583 _fields: [ 19584 .../* @__PURE__ */ new Set([ 19585 ...get_normalized_comma_separable_default(query._fields) || [], 19586 entityConfig.key || DEFAULT_ENTITY_KEY 19587 ]) 19588 ].join() 19589 }; 19590 } 19591 if (query !== void 0 && query._fields) { 19592 const hasRecord = select6.hasEntityRecord( 19593 kind, 19594 name, 19595 key, 19596 query 19597 ); 19598 if (hasRecord) { 19599 return; 19600 } 19601 } 19602 const { baseURL } = entityConfig; 19603 const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), { 19604 ...entityConfig.baseURLParams, 19605 ...query 19606 }); 19607 const response = await (0, import_api_fetch10.default)({ path, parse: false }); 19608 const record = await response.json(); 19609 const permissions = getUserPermissionsFromAllowHeader( 19610 response.headers?.get("allow") 19611 ); 19612 const receiveUserPermissionArgs = {}; 19613 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19614 receiveUserPermissionArgs[getUserPermissionCacheKey(action, { 19615 kind, 19616 name, 19617 id: key 19618 })] = permissions[action]; 19619 } 19620 const canUserResolutionsArgs = [[{ kind, name, id: key }]]; 19621 const syncManager2 = select6?.isCollaborationSupported?.() === false ? void 0 : getEntitySyncManager(); 19622 if (syncManager2 && isNumericID(key) && !query && false !== syncManager2.shouldSync?.(kind, name, key)) { 19623 const recordWithTransients = { ...record }; 19624 Object.entries(entityConfig.transientEdits ?? {}).filter( 19625 ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read 19626 ).forEach(([propName, transientConfig]) => { 19627 recordWithTransients[propName] = transientConfig.read(recordWithTransients); 19628 }); 19629 if (recordWithTransients.blocks && typeof recordWithTransients.content?.raw === "string") { 19630 setCachedBlocks( 19631 kind, 19632 name, 19633 key, 19634 recordWithTransients.content.raw, 19635 recordWithTransients.blocks 19636 ); 19637 } 19638 void syncManager2.load(kind, name, key, recordWithTransients, { 19639 // Handle edits sourced from the sync manager. 19640 editRecord: (edits, options = {}) => { 19641 if (!Object.keys(edits).length) { 19642 return; 19643 } 19644 dispatch4({ 19645 type: "EDIT_ENTITY_RECORD", 19646 kind, 19647 name, 19648 recordId: key, 19649 edits, 19650 meta: { 19651 undo: void 0 19652 }, 19653 options 19654 }); 19655 }, 19656 // Get the current entity record (with edits) 19657 getEditedRecord: async () => await resolveSelect3.getEditedEntityRecord( 19658 kind, 19659 name, 19660 key 19661 ), 19662 // Refetch the current entity record from the database. 19663 refetchRecord: async () => { 19664 dispatch4.receiveEntityRecords( 19665 kind, 19666 name, 19667 await (0, import_api_fetch10.default)({ path, parse: true }), 19668 query 19669 ); 19670 }, 19671 onUndoLevelOpened: () => { 19672 dispatch4.recordSyncUndoLevel(kind, name, key); 19673 } 19674 }); 19675 } 19676 registry.batch(() => { 19677 dispatch4.receiveEntityRecords(kind, name, record, query); 19678 dispatch4.receiveUserPermissions(receiveUserPermissionArgs); 19679 dispatch4.finishResolutions("canUser", canUserResolutionsArgs); 19680 }); 19681 } finally { 19682 dispatch4.__unstableReleaseStoreLock(lock2); 19683 } 19684 }; 19685 getEntityRecord2.shouldInvalidate = (action, kind, name) => { 19686 return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of 19687 // knowing whether it's an update or fetch. Only an update would 19688 // have persistedEdits. 19689 action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template"; 19690 }; 19691 var getRawEntityRecord2 = forward_resolver_default("getEntityRecord"); 19692 var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord"); 19693 var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch: dispatch4, registry, resolveSelect: resolveSelect3 }) => { 19694 const configs = await resolveSelect3.getEntitiesConfig(kind); 19695 const entityConfig = configs.find( 19696 (config) => config.name === name && config.kind === kind 19697 ); 19698 if (!entityConfig) { 19699 return; 19700 } 19701 const lock2 = await dispatch4.__unstableAcquireStoreLock( 19702 STORE_NAME, 19703 ["entities", "records", kind, name], 19704 { exclusive: false } 19705 ); 19706 const rawQuery = { ...query }; 19707 const key = entityConfig.key || DEFAULT_ENTITY_KEY; 19708 function getResolutionsArgs(records, recordsQuery) { 19709 const normalizedQuery = normalizeQueryForResolution(recordsQuery); 19710 return records.filter((record) => record?.[key]).map((record) => [ 19711 kind, 19712 name, 19713 record[key], 19714 normalizedQuery 19715 ]); 19716 } 19717 try { 19718 if (query._fields) { 19719 query = { 19720 ...query, 19721 _fields: [ 19722 .../* @__PURE__ */ new Set([ 19723 ...get_normalized_comma_separable_default(query._fields) || [], 19724 key 19725 ]) 19726 ].join() 19727 }; 19728 } 19729 const { baseURL } = entityConfig; 19730 const path = (0, import_url6.addQueryArgs)(baseURL, { 19731 ...entityConfig.baseURLParams, 19732 ...query 19733 }); 19734 let records = [], meta; 19735 if (entityConfig.supportsPagination && query.per_page !== -1) { 19736 const response = await (0, import_api_fetch10.default)({ path, parse: false }); 19737 records = Object.values(await response.json()); 19738 meta = getPaginationMeta(response.headers); 19739 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) { 19740 let page = 1; 19741 let totalPages; 19742 do { 19743 const response = await (0, import_api_fetch10.default)({ 19744 path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }), 19745 parse: false 19746 }); 19747 const pageRecords = Object.values(await response.json()); 19748 const pageMeta = getPaginationMeta(response.headers); 19749 totalPages = pageMeta.totalPages ?? 1; 19750 if (!meta) { 19751 meta = { 19752 totalItems: pageMeta.totalItems, 19753 totalPages: 1 19754 }; 19755 } 19756 records.push(...pageRecords); 19757 registry.batch(() => { 19758 dispatch4.receiveEntityRecords( 19759 kind, 19760 name, 19761 records, 19762 query, 19763 false, 19764 void 0, 19765 meta 19766 ); 19767 dispatch4.finishResolutions( 19768 "getEntityRecord", 19769 getResolutionsArgs(pageRecords, rawQuery) 19770 ); 19771 }); 19772 page++; 19773 } while (page <= totalPages); 19774 } else { 19775 records = Object.values(await (0, import_api_fetch10.default)({ path })); 19776 meta = { 19777 totalItems: records.length, 19778 totalPages: 1 19779 }; 19780 } 19781 if (-1 === query.per_page) { 19782 void getEntitySyncManager()?.loadCollection?.(kind, name, { 19783 refetchRecords: async () => { 19784 dispatch4.receiveEntityRecords( 19785 kind, 19786 name, 19787 await (0, import_api_fetch10.default)({ path, parse: true }), 19788 query 19789 ); 19790 } 19791 }); 19792 } 19793 if (query._fields) { 19794 records = records.map((record) => { 19795 query._fields.split(",").forEach((field) => { 19796 if (!record.hasOwnProperty(field)) { 19797 record[field] = void 0; 19798 } 19799 }); 19800 return record; 19801 }); 19802 } 19803 registry.batch(() => { 19804 dispatch4.receiveEntityRecords( 19805 kind, 19806 name, 19807 records, 19808 query, 19809 false, 19810 void 0, 19811 meta 19812 ); 19813 const targetHints = records.filter( 19814 (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow 19815 ).map((record) => ({ 19816 id: record[key], 19817 permissions: getUserPermissionsFromAllowHeader( 19818 record._links.self[0].targetHints.allow 19819 ) 19820 })); 19821 const canUserResolutionsArgs = []; 19822 const receiveUserPermissionArgs = {}; 19823 for (const targetHint of targetHints) { 19824 canUserResolutionsArgs.push([ 19825 { kind, name, id: targetHint.id } 19826 ]); 19827 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19828 receiveUserPermissionArgs[getUserPermissionCacheKey(action, { 19829 kind, 19830 name, 19831 id: targetHint.id 19832 })] = targetHint.permissions[action]; 19833 } 19834 } 19835 if (targetHints.length > 0) { 19836 dispatch4.receiveUserPermissions( 19837 receiveUserPermissionArgs 19838 ); 19839 dispatch4.finishResolutions( 19840 "canUser", 19841 canUserResolutionsArgs 19842 ); 19843 } 19844 dispatch4.finishResolutions( 19845 "getEntityRecord", 19846 getResolutionsArgs(records, rawQuery) 19847 ); 19848 dispatch4.__unstableReleaseStoreLock(lock2); 19849 }); 19850 } catch { 19851 dispatch4.__unstableReleaseStoreLock(lock2); 19852 } 19853 }; 19854 getEntityRecords2.shouldInvalidate = (action, kind, name) => { 19855 return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name; 19856 }; 19857 var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords"); 19858 var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords"); 19859 var getCurrentTheme2 = () => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 19860 const activeThemes = await resolveSelect3.getEntityRecords( 19861 "root", 19862 "theme", 19863 { status: "active" } 19864 ); 19865 dispatch4.receiveCurrentTheme(activeThemes[0]); 19866 }; 19867 var getThemeSupports2 = forward_resolver_default("getCurrentTheme"); 19868 var getEmbedPreview2 = (url) => async ({ dispatch: dispatch4 }) => { 19869 try { 19870 const embedProxyResponse = await (0, import_api_fetch10.default)({ 19871 path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url }) 19872 }); 19873 dispatch4.receiveEmbedPreview(url, embedProxyResponse); 19874 } catch { 19875 dispatch4.receiveEmbedPreview(url, false); 19876 } 19877 }; 19878 var canUser2 = (resource, id2) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 19879 let resourcePath = null; 19880 if (typeof resource === "object") { 19881 if (!resource.kind || !resource.name) { 19882 throw new Error("The entity resource object is not valid."); 19883 } 19884 if (!isSafeEntityKey(resource.id)) { 19885 return; 19886 } 19887 const configs = await resolveSelect3.getEntitiesConfig( 19888 resource.kind 19889 ); 19890 const entityConfig = configs.find( 19891 (config) => config.name === resource.name && config.kind === resource.kind 19892 ); 19893 if (!entityConfig) { 19894 return; 19895 } 19896 resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : ""); 19897 } else { 19898 if (!isSafeEntityKey(resource) || !isSafeEntityKey(id2)) { 19899 return; 19900 } 19901 resourcePath = `/wp/v2/$resource}` + (id2 ? "/" + id2 : ""); 19902 } 19903 let response; 19904 try { 19905 response = await (0, import_api_fetch10.default)({ 19906 path: resourcePath, 19907 method: "OPTIONS", 19908 parse: false 19909 }); 19910 } catch { 19911 return; 19912 } 19913 const permissions = getUserPermissionsFromAllowHeader( 19914 response.headers?.get("allow") 19915 ); 19916 const receiveUserPermissionArgs = {}; 19917 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19918 receiveUserPermissionArgs[getUserPermissionCacheKey(action, resource, id2)] = permissions[action]; 19919 } 19920 dispatch4.receiveUserPermissions(receiveUserPermissionArgs); 19921 }; 19922 canUser2.getResolutionArgs = (action, resource, id2) => [resource, id2]; 19923 var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ resolveSelect: resolveSelect3 }) => { 19924 await resolveSelect3.canUser("update", { kind, name, id: recordId }); 19925 }; 19926 var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 19927 if (!isSafeEntityKey(postId)) { 19928 return; 19929 } 19930 const { 19931 rest_base: restBase, 19932 rest_namespace: restNamespace = "wp/v2", 19933 supports 19934 } = await resolveSelect3.getPostType(postType); 19935 if (!supports?.autosave) { 19936 return; 19937 } 19938 const autosaves2 = await (0, import_api_fetch10.default)({ 19939 path: `/$restNamespace}/$restBase}/$postId}/autosaves?context=edit` 19940 }); 19941 if (autosaves2 && autosaves2.length) { 19942 dispatch4.receiveAutosaves(postId, autosaves2); 19943 } 19944 }; 19945 var getAutosave2 = (postType, postId) => async ({ resolveSelect: resolveSelect3 }) => { 19946 await resolveSelect3.getAutosaves(postType, postId); 19947 }; 19948 var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 19949 const activeThemes = await resolveSelect3.getEntityRecords( 19950 "root", 19951 "theme", 19952 { status: "active" } 19953 ); 19954 const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href; 19955 if (!globalStylesURL) { 19956 return; 19957 } 19958 const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/); 19959 const id2 = matches ? Number(matches[1]) : null; 19960 if (id2) { 19961 dispatch4.__experimentalReceiveCurrentGlobalStylesId(id2); 19962 } 19963 }; 19964 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect3, dispatch: dispatch4 }) => { 19965 const currentTheme2 = await resolveSelect3.getCurrentTheme(); 19966 const themeGlobalStyles = await (0, import_api_fetch10.default)({ 19967 path: `/wp/v2/global-styles/themes/$currentTheme2.stylesheet}?context=view` 19968 }); 19969 dispatch4.__experimentalReceiveThemeBaseGlobalStyles( 19970 currentTheme2.stylesheet, 19971 themeGlobalStyles 19972 ); 19973 }; 19974 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect3, dispatch: dispatch4 }) => { 19975 const currentTheme2 = await resolveSelect3.getCurrentTheme(); 19976 const variations = await (0, import_api_fetch10.default)({ 19977 path: `/wp/v2/global-styles/themes/$currentTheme2.stylesheet}/variations?context=view` 19978 }); 19979 dispatch4.__experimentalReceiveThemeGlobalStyleVariations( 19980 currentTheme2.stylesheet, 19981 variations 19982 ); 19983 }; 19984 var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect: resolveSelect3, dispatch: dispatch4 }) => { 19985 const globalStylesId = await resolveSelect3.__experimentalGetCurrentGlobalStylesId(); 19986 const record = globalStylesId ? await resolveSelect3.getEntityRecord( 19987 "root", 19988 "globalStyles", 19989 globalStylesId 19990 ) : void 0; 19991 const revisionsURL = record?._links?.["version-history"]?.[0]?.href; 19992 if (revisionsURL) { 19993 const resetRevisions = await (0, import_api_fetch10.default)({ 19994 url: revisionsURL 19995 }); 19996 const revisions = resetRevisions?.map( 19997 (revision) => Object.fromEntries( 19998 Object.entries(revision).map(([key, value]) => [ 19999 camelCase(key), 20000 value 20001 ]) 20002 ) 20003 ); 20004 dispatch4.receiveThemeGlobalStyleRevisions( 20005 globalStylesId, 20006 revisions 20007 ); 20008 } 20009 }; 20010 getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => { 20011 return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles"; 20012 }; 20013 var getBlockPatterns2 = () => async ({ dispatch: dispatch4 }) => { 20014 const patterns = await fetchBlockPatterns(); 20015 dispatch4({ type: "RECEIVE_BLOCK_PATTERNS", patterns }); 20016 }; 20017 var getBlockPatternCategories2 = () => async ({ dispatch: dispatch4 }) => { 20018 const categories = await (0, import_api_fetch10.default)({ 20019 path: "/wp/v2/block-patterns/categories" 20020 }); 20021 dispatch4({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories }); 20022 }; 20023 var getUserPatternCategories2 = () => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 20024 const patternCategories = await resolveSelect3.getEntityRecords( 20025 "taxonomy", 20026 "wp_pattern_category", 20027 { 20028 per_page: -1, 20029 _fields: "id,name,description,slug", 20030 context: "view" 20031 } 20032 ); 20033 const mappedPatternCategories = patternCategories?.map((userCategory) => ({ 20034 ...userCategory, 20035 label: (0, import_html_entities3.decodeEntities)(userCategory.name), 20036 name: userCategory.slug 20037 })) || []; 20038 dispatch4({ 20039 type: "RECEIVE_USER_PATTERN_CATEGORIES", 20040 patternCategories: mappedPatternCategories 20041 }); 20042 }; 20043 var getNavigationFallbackId2 = () => async ({ dispatch: dispatch4, select: select6, registry }) => { 20044 const fallback = await (0, import_api_fetch10.default)({ 20045 path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", { 20046 _embed: true 20047 }) 20048 }); 20049 const record = fallback?._embedded?.self; 20050 registry.batch(() => { 20051 dispatch4.receiveNavigationFallbackId(fallback?.id); 20052 if (!record) { 20053 return; 20054 } 20055 const existingFallbackEntityRecord = select6.getEntityRecord( 20056 "postType", 20057 "wp_navigation", 20058 fallback.id 20059 ); 20060 const invalidateNavigationQueries = !existingFallbackEntityRecord; 20061 dispatch4.receiveEntityRecords( 20062 "postType", 20063 "wp_navigation", 20064 record, 20065 void 0, 20066 invalidateNavigationQueries 20067 ); 20068 dispatch4.finishResolution("getEntityRecord", [ 20069 "postType", 20070 "wp_navigation", 20071 fallback.id 20072 ]); 20073 }); 20074 }; 20075 var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch4, registry, resolveSelect: resolveSelect3 }) => { 20076 const template = await (0, import_api_fetch10.default)({ 20077 path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query) 20078 }); 20079 await resolveSelect3.getEntitiesConfig("postType"); 20080 const id2 = template?.id; 20081 registry.batch(() => { 20082 dispatch4.receiveDefaultTemplateId(query, id2 || ""); 20083 if (id2) { 20084 template.id = id2; 20085 dispatch4.receiveEntityRecords( 20086 "postType", 20087 template.type, 20088 template 20089 ); 20090 dispatch4.finishResolution("getEntityRecord", [ 20091 "postType", 20092 template.type, 20093 id2 20094 ]); 20095 } 20096 }); 20097 }; 20098 var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 20099 const configs = await resolveSelect3.getEntitiesConfig(kind); 20100 const entityConfig = configs.find( 20101 (config) => config.name === name && config.kind === kind 20102 ); 20103 if (!entityConfig || !isSafeEntityKey(recordKey)) { 20104 return; 20105 } 20106 const rawQuery = { ...query }; 20107 const lock2 = await dispatch4.__unstableAcquireStoreLock( 20108 STORE_NAME, 20109 ["entities", "records", kind, name, recordKey, "revisions"], 20110 { exclusive: false } 20111 ); 20112 try { 20113 if (query._fields) { 20114 query = { 20115 ...query, 20116 _fields: [ 20117 .../* @__PURE__ */ new Set([ 20118 ...get_normalized_comma_separable_default(query._fields) || [], 20119 entityConfig.revisionKey || DEFAULT_ENTITY_KEY 20120 ]) 20121 ].join() 20122 }; 20123 } 20124 const path = (0, import_url6.addQueryArgs)( 20125 entityConfig.getRevisionsUrl(recordKey), 20126 query 20127 ); 20128 let records, response; 20129 const meta = {}; 20130 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1; 20131 try { 20132 response = await (0, import_api_fetch10.default)({ path, parse: !isPaginated }); 20133 } catch { 20134 return; 20135 } 20136 if (response) { 20137 if (isPaginated) { 20138 records = Object.values(await response.json()); 20139 meta.totalItems = getPaginationMeta( 20140 response.headers 20141 ).totalItems; 20142 } else { 20143 records = Object.values(response); 20144 } 20145 if (query._fields) { 20146 records = records.map((record) => { 20147 query._fields.split(",").forEach((field) => { 20148 if (!record.hasOwnProperty(field)) { 20149 record[field] = void 0; 20150 } 20151 }); 20152 return record; 20153 }); 20154 } 20155 await dispatch4.receiveRevisions( 20156 kind, 20157 name, 20158 recordKey, 20159 records, 20160 query, 20161 false, 20162 meta 20163 ); 20164 const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY; 20165 const normalizedQuery = normalizeQueryForResolution(rawQuery); 20166 const resolutionsArgs = records.filter((record) => record[key]).map((record) => [ 20167 kind, 20168 name, 20169 recordKey, 20170 record[key], 20171 normalizedQuery 20172 ]); 20173 dispatch4.finishResolutions("getRevision", resolutionsArgs); 20174 } 20175 } finally { 20176 dispatch4.__unstableReleaseStoreLock(lock2); 20177 } 20178 }; 20179 getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId; 20180 var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ select: select6, dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 20181 const configs = await resolveSelect3.getEntitiesConfig(kind); 20182 const entityConfig = configs.find( 20183 (config) => config.name === name && config.kind === kind 20184 ); 20185 if (!entityConfig || !isSafeEntityKey(recordKey) || !isSafeEntityKey(revisionKey)) { 20186 return; 20187 } 20188 if (query !== void 0 && query._fields) { 20189 query = { 20190 ...query, 20191 _fields: [ 20192 .../* @__PURE__ */ new Set([ 20193 ...get_normalized_comma_separable_default(query._fields) || [], 20194 entityConfig.revisionKey || DEFAULT_ENTITY_KEY 20195 ]) 20196 ].join() 20197 }; 20198 } 20199 const lock2 = await dispatch4.__unstableAcquireStoreLock( 20200 STORE_NAME, 20201 [ 20202 "entities", 20203 "records", 20204 kind, 20205 name, 20206 recordKey, 20207 "revisions", 20208 revisionKey 20209 ], 20210 { exclusive: false } 20211 ); 20212 try { 20213 if (select6.hasRevision(kind, name, recordKey, revisionKey, query)) { 20214 return; 20215 } 20216 const path = (0, import_url6.addQueryArgs)( 20217 entityConfig.getRevisionsUrl(recordKey, revisionKey), 20218 query 20219 ); 20220 let record; 20221 try { 20222 record = await (0, import_api_fetch10.default)({ path }); 20223 } catch { 20224 return; 20225 } 20226 if (record) { 20227 await dispatch4.receiveRevisions( 20228 kind, 20229 name, 20230 recordKey, 20231 record, 20232 query 20233 ); 20234 } 20235 } finally { 20236 dispatch4.__unstableReleaseStoreLock(lock2); 20237 } 20238 }; 20239 var getRegisteredPostMeta2 = (postType) => async ({ dispatch: dispatch4, resolveSelect: resolveSelect3 }) => { 20240 let options; 20241 try { 20242 const { 20243 rest_namespace: restNamespace = "wp/v2", 20244 rest_base: restBase 20245 } = await resolveSelect3.getPostType(postType) || {}; 20246 options = await (0, import_api_fetch10.default)({ 20247 path: `$restNamespace}/$restBase}/?context=edit`, 20248 method: "OPTIONS" 20249 }); 20250 } catch { 20251 return; 20252 } 20253 if (options) { 20254 dispatch4.receiveRegisteredPostMeta( 20255 postType, 20256 options?.schema?.properties?.meta?.properties 20257 ); 20258 } 20259 }; 20260 var getEntitiesConfig2 = (kind) => async ({ dispatch: dispatch4 }) => { 20261 const loader = additionalEntityConfigLoaders.find( 20262 (l) => l.kind === kind 20263 ); 20264 if (!loader) { 20265 return; 20266 } 20267 try { 20268 const configs = await loader.loadEntities(); 20269 if (!configs.length) { 20270 return; 20271 } 20272 dispatch4.addEntities(configs); 20273 } catch { 20274 } 20275 }; 20276 var getEditorSettings2 = () => async ({ dispatch: dispatch4 }) => { 20277 const settings = await (0, import_api_fetch10.default)({ 20278 path: "/wp-block-editor/v1/settings" 20279 }); 20280 dispatch4.receiveEditorSettings(settings); 20281 }; 20282 var getEditorAssets2 = () => async ({ dispatch: dispatch4 }) => { 20283 const assets = await (0, import_api_fetch10.default)({ 20284 path: "/wp-block-editor/v1/assets" 20285 }); 20286 dispatch4.receiveEditorAssets(assets); 20287 }; 20288 var getViewConfig2 = (kind, name, options = {}) => async ({ dispatch: dispatch4 }) => { 20289 const query = { kind, name }; 20290 const fields = get_normalized_comma_separable_default(options.fields); 20291 if (fields?.length) { 20292 query._fields = fields.join(","); 20293 } 20294 const config = await (0, import_api_fetch10.default)({ 20295 path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", query) 20296 }); 20297 dispatch4.receiveViewConfig(kind, name, config); 20298 }; 20299 var getFieldsConfig2 = (kind, name) => async ({ dispatch: dispatch4 }) => { 20300 const config = await (0, import_api_fetch10.default)({ 20301 path: (0, import_url6.addQueryArgs)("/wp/v2/entity-fields", { kind, name }) 20302 }); 20303 dispatch4.receiveFieldsConfig(kind, name, config); 20304 }; 20305 var getEntityActionsConfig2 = (kind, name) => async ({ dispatch: dispatch4 }) => { 20306 const config = await (0, import_api_fetch10.default)({ 20307 path: (0, import_url6.addQueryArgs)("/wp/v2/entity-actions", { kind, name }) 20308 }); 20309 dispatch4.receiveEntityActionsConfig(kind, name, config); 20310 }; 20311 20312 // packages/core-data/build-module/locks/utils.mjs 20313 function deepCopyLocksTreePath(tree, path) { 20314 const newTree = { ...tree }; 20315 let currentNode = newTree; 20316 for (const branchName of path) { 20317 currentNode.children = { 20318 ...currentNode.children, 20319 [branchName]: { 20320 locks: [], 20321 children: {}, 20322 ...currentNode.children[branchName] 20323 } 20324 }; 20325 currentNode = currentNode.children[branchName]; 20326 } 20327 return newTree; 20328 } 20329 function getNode(tree, path) { 20330 let currentNode = tree; 20331 for (const branchName of path) { 20332 const nextNode = currentNode.children[branchName]; 20333 if (!nextNode) { 20334 return null; 20335 } 20336 currentNode = nextNode; 20337 } 20338 return currentNode; 20339 } 20340 function* iteratePath(tree, path) { 20341 let currentNode = tree; 20342 yield currentNode; 20343 for (const branchName of path) { 20344 const nextNode = currentNode.children[branchName]; 20345 if (!nextNode) { 20346 break; 20347 } 20348 yield nextNode; 20349 currentNode = nextNode; 20350 } 20351 } 20352 function* iterateDescendants(node) { 20353 const stack = Object.values(node.children); 20354 while (stack.length) { 20355 const childNode = stack.pop(); 20356 yield childNode; 20357 stack.push(...Object.values(childNode.children)); 20358 } 20359 } 20360 function hasConflictingLock({ exclusive }, locks2) { 20361 if (exclusive && locks2.length) { 20362 return true; 20363 } 20364 if (!exclusive && locks2.filter((lock2) => lock2.exclusive).length) { 20365 return true; 20366 } 20367 return false; 20368 } 20369 20370 // packages/core-data/build-module/locks/reducer.mjs 20371 var DEFAULT_STATE = { 20372 requests: [], 20373 tree: { 20374 locks: [], 20375 children: {} 20376 } 20377 }; 20378 function locks(state = DEFAULT_STATE, action) { 20379 switch (action.type) { 20380 case "ENQUEUE_LOCK_REQUEST": { 20381 const { request } = action; 20382 return { 20383 ...state, 20384 requests: [request, ...state.requests] 20385 }; 20386 } 20387 case "GRANT_LOCK_REQUEST": { 20388 const { lock: lock2, request } = action; 20389 const { store: store2, path } = request; 20390 const storePath = [store2, ...path]; 20391 const newTree = deepCopyLocksTreePath(state.tree, storePath); 20392 const node = getNode(newTree, storePath); 20393 node.locks = [...node.locks, lock2]; 20394 return { 20395 ...state, 20396 requests: state.requests.filter((r2) => r2 !== request), 20397 tree: newTree 20398 }; 20399 } 20400 case "RELEASE_LOCK": { 20401 const { lock: lock2 } = action; 20402 const storePath = [lock2.store, ...lock2.path]; 20403 const newTree = deepCopyLocksTreePath(state.tree, storePath); 20404 const node = getNode(newTree, storePath); 20405 node.locks = node.locks.filter((l) => l !== lock2); 20406 return { 20407 ...state, 20408 tree: newTree 20409 }; 20410 } 20411 } 20412 return state; 20413 } 20414 20415 // packages/core-data/build-module/locks/selectors.mjs 20416 function getPendingLockRequests(state) { 20417 return state.requests; 20418 } 20419 function isLockAvailable(state, store2, path, { exclusive }) { 20420 const storePath = [store2, ...path]; 20421 const locks2 = state.tree; 20422 for (const node2 of iteratePath(locks2, storePath)) { 20423 if (hasConflictingLock({ exclusive }, node2.locks)) { 20424 return false; 20425 } 20426 } 20427 const node = getNode(locks2, storePath); 20428 if (!node) { 20429 return true; 20430 } 20431 for (const descendant of iterateDescendants(node)) { 20432 if (hasConflictingLock({ exclusive }, descendant.locks)) { 20433 return false; 20434 } 20435 } 20436 return true; 20437 } 20438 20439 // packages/core-data/build-module/locks/engine.mjs 20440 function createLocks() { 20441 let state = locks(void 0, { type: "@@INIT" }); 20442 function processPendingLockRequests() { 20443 for (const request of getPendingLockRequests(state)) { 20444 const { store: store2, path, exclusive, notifyAcquired } = request; 20445 if (isLockAvailable(state, store2, path, { exclusive })) { 20446 const lock2 = { store: store2, path, exclusive }; 20447 state = locks(state, { 20448 type: "GRANT_LOCK_REQUEST", 20449 lock: lock2, 20450 request 20451 }); 20452 notifyAcquired(lock2); 20453 } 20454 } 20455 } 20456 function acquire(store2, path, exclusive) { 20457 return new Promise((resolve) => { 20458 state = locks(state, { 20459 type: "ENQUEUE_LOCK_REQUEST", 20460 request: { store: store2, path, exclusive, notifyAcquired: resolve } 20461 }); 20462 processPendingLockRequests(); 20463 }); 20464 } 20465 function release(lock2) { 20466 state = locks(state, { 20467 type: "RELEASE_LOCK", 20468 lock: lock2 20469 }); 20470 processPendingLockRequests(); 20471 } 20472 return { acquire, release }; 20473 } 20474 20475 // packages/core-data/build-module/locks/actions.mjs 20476 function createLocksActions() { 20477 const locks2 = createLocks(); 20478 function __unstableAcquireStoreLock(store2, path, { exclusive }) { 20479 return () => locks2.acquire(store2, path, exclusive); 20480 } 20481 function __unstableReleaseStoreLock(lock2) { 20482 return () => locks2.release(lock2); 20483 } 20484 return { __unstableAcquireStoreLock, __unstableReleaseStoreLock }; 20485 } 20486 20487 // packages/core-data/build-module/dynamic-entities.mjs 20488 var dynamicActions; 20489 var dynamicSelectors; 20490 20491 // packages/core-data/build-module/entity-provider.mjs 20492 var import_element2 = __toESM(require_element(), 1); 20493 20494 // packages/core-data/build-module/entity-context.mjs 20495 var import_element = __toESM(require_element(), 1); 20496 var EntityContext = (0, import_element.createContext)({}); 20497 EntityContext.displayName = "EntityContext"; 20498 20499 // packages/core-data/build-module/entity-provider.mjs 20500 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); 20501 function EntityProvider({ 20502 kind, 20503 type, 20504 id: id2, 20505 revisionId, 20506 children 20507 }) { 20508 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)( 20509 PrivateEntityProvider, 20510 { 20511 kind, 20512 type, 20513 id: id2, 20514 revisionId, 20515 children 20516 } 20517 ); 20518 } 20519 function PrivateEntityProvider({ 20520 kind, 20521 type: name, 20522 id: id2, 20523 revisionId, 20524 revision, 20525 children 20526 }) { 20527 const parent = (0, import_element2.useContext)(EntityContext); 20528 const providedRevision = revision ?? revisionId; 20529 const childContext = (0, import_element2.useMemo)( 20530 () => ({ 20531 ...parent, 20532 ...kind && { 20533 [kind]: { 20534 ...parent?.[kind], 20535 [name]: id2 20536 } 20537 }, 20538 ...providedRevision !== void 0 && kind && { 20539 revision: { 20540 ...parent?.revision, 20541 [kind]: { 20542 ...parent?.revision?.[kind], 20543 [name]: providedRevision 20544 } 20545 } 20546 } 20547 }), 20548 [parent, kind, name, id2, providedRevision] 20549 ); 20550 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children }); 20551 } 20552 20553 // packages/core-data/build-module/hooks/use-entity-record.mjs 20554 var import_data12 = __toESM(require_data(), 1); 20555 var import_deprecated4 = __toESM(require_deprecated(), 1); 20556 var import_element3 = __toESM(require_element(), 1); 20557 20558 // packages/core-data/build-module/hooks/constants.mjs 20559 var Status = /* @__PURE__ */ ((Status2) => { 20560 Status2["Idle"] = "IDLE"; 20561 Status2["Resolving"] = "RESOLVING"; 20562 Status2["Error"] = "ERROR"; 20563 Status2["Success"] = "SUCCESS"; 20564 return Status2; 20565 })(Status || {}); 20566 20567 // packages/core-data/build-module/hooks/utils.mjs 20568 function getResolutionStatus(resolutionStatus) { 20569 let status; 20570 switch (resolutionStatus) { 20571 case "resolving": 20572 status = Status.Resolving; 20573 break; 20574 case "finished": 20575 status = Status.Success; 20576 break; 20577 case "error": 20578 status = Status.Error; 20579 break; 20580 default: 20581 status = Status.Idle; 20582 } 20583 return { 20584 status, 20585 isResolving: status === Status.Resolving, 20586 hasStarted: status !== Status.Idle, 20587 hasResolved: status === Status.Success || status === Status.Error 20588 }; 20589 } 20590 20591 // packages/core-data/build-module/hooks/use-entity-record.mjs 20592 var EMPTY_OBJECT3 = {}; 20593 function useEntityRecord(kind, name, recordId, options = { enabled: true }) { 20594 const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data12.useDispatch)(store); 20595 const mutations = (0, import_element3.useMemo)( 20596 () => ({ 20597 edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions), 20598 save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, { 20599 throwOnError: true, 20600 ...saveOptions 20601 }) 20602 }), 20603 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2] 20604 ); 20605 const { record, editedRecord, hasEdits, edits, ...resolution } = (0, import_data12.useSelect)( 20606 (select6) => { 20607 if (!options.enabled) { 20608 return { 20609 record: null, 20610 editedRecord: EMPTY_OBJECT3, 20611 hasEdits: false, 20612 edits: EMPTY_OBJECT3, 20613 ...getResolutionStatus() 20614 }; 20615 } 20616 const storeSelectors = select6(store); 20617 const resolutionStatus = storeSelectors.getResolutionState( 20618 "getEntityRecord", 20619 [kind, name, recordId] 20620 )?.status; 20621 return { 20622 record: storeSelectors.getEntityRecord( 20623 kind, 20624 name, 20625 recordId 20626 ) ?? null, 20627 editedRecord: storeSelectors.getEditedEntityRecord( 20628 kind, 20629 name, 20630 recordId 20631 ), 20632 hasEdits: storeSelectors.hasEditsForEntityRecord( 20633 kind, 20634 name, 20635 recordId 20636 ), 20637 edits: storeSelectors.getEntityRecordNonTransientEdits( 20638 kind, 20639 name, 20640 recordId 20641 ), 20642 ...getResolutionStatus(resolutionStatus) 20643 }; 20644 }, 20645 [kind, name, recordId, options.enabled] 20646 ); 20647 return { 20648 record, 20649 editedRecord, 20650 hasEdits, 20651 edits, 20652 ...resolution, 20653 ...mutations 20654 }; 20655 } 20656 function useDeprecatedEntityRecord(kind, name, recordId, options) { 20657 (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, { 20658 alternative: "wp.data.useEntityRecord", 20659 since: "6.1" 20660 }); 20661 return useEntityRecord(kind, name, recordId, options); 20662 } 20663 20664 // packages/core-data/build-module/hooks/use-entity-records.mjs 20665 var import_url7 = __toESM(require_url(), 1); 20666 var import_deprecated5 = __toESM(require_deprecated(), 1); 20667 var import_data13 = __toESM(require_data(), 1); 20668 var import_element4 = __toESM(require_element(), 1); 20669 var EMPTY_ARRAY = []; 20670 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) { 20671 const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs); 20672 const { records, totalItems, totalPages, ...rest } = (0, import_data13.useSelect)( 20673 (select6) => { 20674 if (!options.enabled) { 20675 return { 20676 // Avoiding returning a new reference on every execution. 20677 records: EMPTY_ARRAY, 20678 totalItems: null, 20679 totalPages: null, 20680 ...getResolutionStatus() 20681 }; 20682 } 20683 const storeSelectors = select6(store); 20684 const resolutionStatus = storeSelectors.getResolutionState( 20685 "getEntityRecords", 20686 [kind, name, queryArgs] 20687 )?.status; 20688 return { 20689 records: storeSelectors.getEntityRecords( 20690 kind, 20691 name, 20692 queryArgs 20693 ), 20694 totalItems: storeSelectors.getEntityRecordsTotalItems( 20695 kind, 20696 name, 20697 queryArgs 20698 ), 20699 totalPages: storeSelectors.getEntityRecordsTotalPages( 20700 kind, 20701 name, 20702 queryArgs 20703 ), 20704 ...getResolutionStatus(resolutionStatus) 20705 }; 20706 }, 20707 [kind, name, queryAsString, options.enabled] 20708 ); 20709 return { 20710 records, 20711 totalItems, 20712 totalPages, 20713 ...rest 20714 }; 20715 } 20716 function useDeprecatedEntityRecords(kind, name, queryArgs, options) { 20717 (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, { 20718 alternative: "wp.data.useEntityRecords", 20719 since: "6.1" 20720 }); 20721 return useEntityRecords(kind, name, queryArgs, options); 20722 } 20723 function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) { 20724 const entityConfig = (0, import_data13.useSelect)( 20725 (select6) => select6(store).getEntityConfig(kind, name), 20726 [kind, name] 20727 ); 20728 const { records: data, ...ret } = useEntityRecords( 20729 kind, 20730 name, 20731 { 20732 ...queryArgs, 20733 // If _fields is provided, we need to include _links in the request for permission caching to work. 20734 ...queryArgs._fields ? { 20735 _fields: [ 20736 .../* @__PURE__ */ new Set([ 20737 ...get_normalized_comma_separable_default( 20738 queryArgs._fields 20739 ) || [], 20740 "_links" 20741 ]) 20742 ].join() 20743 } : {} 20744 }, 20745 options 20746 ); 20747 const ids = (0, import_element4.useMemo)( 20748 () => data?.map( 20749 // @ts-expect-error `data` is `unknown[]`, so the callback signature does not line up. 20750 (record) => record[entityConfig?.key ?? "id"] 20751 ) ?? [], 20752 [data, entityConfig?.key] 20753 ); 20754 const permissions = (0, import_data13.useSelect)( 20755 (select6) => { 20756 const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock( 20757 select6(store) 20758 ); 20759 return getEntityRecordsPermissions2(kind, name, ids); 20760 }, 20761 [ids, kind, name] 20762 ); 20763 const dataWithPermissions = (0, import_element4.useMemo)( 20764 () => data?.map((record, index) => ({ 20765 // @ts-expect-error `record` is `unknown`, which cannot be spread. 20766 ...record, 20767 permissions: permissions[index] 20768 })) ?? [], 20769 [data, permissions] 20770 ); 20771 return { records: dataWithPermissions, ...ret }; 20772 } 20773 20774 // packages/core-data/build-module/hooks/use-resource-permissions.mjs 20775 var import_deprecated6 = __toESM(require_deprecated(), 1); 20776 var import_warning2 = __toESM(require_warning(), 1); 20777 20778 // packages/core-data/build-module/hooks/use-query-select.mjs 20779 var import_data14 = __toESM(require_data(), 1); 20780 20781 // node_modules/.store/memize@2.1.1-roXbtpG2bis3Lggp7SQpAA/node_modules/memize/dist/index.js 20782 function memize(fn, options) { 20783 var size2 = 0; 20784 var head; 20785 var tail; 20786 options = options || {}; 20787 function memoized() { 20788 var node = head, len = arguments.length, args2, i; 20789 searchCache: while (node) { 20790 if (node.args.length !== arguments.length) { 20791 node = node.next; 20792 continue; 20793 } 20794 for (i = 0; i < len; i++) { 20795 if (node.args[i] !== arguments[i]) { 20796 node = node.next; 20797 continue searchCache; 20798 } 20799 } 20800 if (node !== head) { 20801 if (node === tail) { 20802 tail = node.prev; 20803 } 20804 node.prev.next = node.next; 20805 if (node.next) { 20806 node.next.prev = node.prev; 20807 } 20808 node.next = head; 20809 node.prev = null; 20810 head.prev = node; 20811 head = node; 20812 } 20813 return node.val; 20814 } 20815 args2 = new Array(len); 20816 for (i = 0; i < len; i++) { 20817 args2[i] = arguments[i]; 20818 } 20819 node = { 20820 args: args2, 20821 // Generate the result from original function 20822 val: fn.apply(null, args2) 20823 }; 20824 if (head) { 20825 head.prev = node; 20826 node.next = head; 20827 } else { 20828 tail = node; 20829 } 20830 if (size2 === /** @type {MemizeOptions} */ 20831 options.maxSize) { 20832 tail = /** @type {MemizeCacheNode} */ 20833 tail.prev; 20834 tail.next = null; 20835 } else { 20836 size2++; 20837 } 20838 head = node; 20839 return node.val; 20840 } 20841 memoized.clear = function() { 20842 head = null; 20843 tail = null; 20844 size2 = 0; 20845 }; 20846 return memoized; 20847 } 20848 20849 // packages/core-data/build-module/hooks/use-query-select.mjs 20850 var META_SELECTORS = [ 20851 "getIsResolving", 20852 "hasStartedResolution", 20853 "hasFinishedResolution", 20854 "isResolving", 20855 "getCachedResolvers" 20856 ]; 20857 function useQuerySelect(mapQuerySelect, deps) { 20858 return (0, import_data14.useSelect)((select6, registry) => { 20859 const resolve = (store2) => enrichSelectors(select6(store2)); 20860 return mapQuerySelect(resolve, registry); 20861 }, deps); 20862 } 20863 var enrichSelectors = memize(((selectors) => { 20864 const resolvers = {}; 20865 for (const selectorName in selectors) { 20866 if (META_SELECTORS.includes(selectorName)) { 20867 continue; 20868 } 20869 Object.defineProperty(resolvers, selectorName, { 20870 get: () => (...args2) => { 20871 const data = selectors[selectorName](...args2); 20872 const resolutionStatus = selectors.getResolutionState( 20873 selectorName, 20874 args2 20875 )?.status; 20876 return { 20877 data, 20878 ...getResolutionStatus(resolutionStatus) 20879 }; 20880 } 20881 }); 20882 } 20883 return resolvers; 20884 })); 20885 20886 // packages/core-data/build-module/hooks/use-resource-permissions.mjs 20887 function useResourcePermissions(resource, id2) { 20888 const isEntity = typeof resource === "object"; 20889 const resourceAsString = isEntity ? JSON.stringify(resource) : resource; 20890 if (isEntity && typeof id2 !== "undefined") { 20891 (0, import_warning2.default)( 20892 `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.` 20893 ); 20894 } 20895 return useQuerySelect( 20896 (resolve) => { 20897 const hasId = isEntity ? !!resource.id : !!id2; 20898 const { canUser: canUser3 } = resolve(store); 20899 const collectionResource = isEntity ? { kind: resource.kind, name: resource.name } : resource; 20900 const create9 = canUser3("create", collectionResource); 20901 if (!hasId) { 20902 const read2 = canUser3("read", collectionResource); 20903 const isResolving2 = create9.isResolving || read2.isResolving; 20904 const hasResolved2 = create9.hasResolved && read2.hasResolved; 20905 let status2 = Status.Idle; 20906 if (isResolving2) { 20907 status2 = Status.Resolving; 20908 } else if (hasResolved2) { 20909 status2 = Status.Success; 20910 } 20911 return { 20912 status: status2, 20913 isResolving: isResolving2, 20914 hasResolved: hasResolved2, 20915 canCreate: create9.hasResolved && create9.data, 20916 canRead: read2.hasResolved && read2.data 20917 }; 20918 } 20919 const read = canUser3("read", resource, id2); 20920 const update = canUser3("update", resource, id2); 20921 const _delete = canUser3("delete", resource, id2); 20922 const isResolving = read.isResolving || create9.isResolving || update.isResolving || _delete.isResolving; 20923 const hasResolved = read.hasResolved && create9.hasResolved && update.hasResolved && _delete.hasResolved; 20924 let status = Status.Idle; 20925 if (isResolving) { 20926 status = Status.Resolving; 20927 } else if (hasResolved) { 20928 status = Status.Success; 20929 } 20930 return { 20931 status, 20932 isResolving, 20933 hasResolved, 20934 canRead: hasResolved && read.data, 20935 canCreate: hasResolved && create9.data, 20936 canUpdate: hasResolved && update.data, 20937 canDelete: hasResolved && _delete.data 20938 }; 20939 }, 20940 [resourceAsString, id2] 20941 ); 20942 } 20943 var use_resource_permissions_default = useResourcePermissions; 20944 function useDeprecatedResourcePermissions(resource, id2) { 20945 (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, { 20946 alternative: "wp.data.useResourcePermissions", 20947 since: "6.1" 20948 }); 20949 return useResourcePermissions(resource, id2); 20950 } 20951 20952 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs 20953 var import_element6 = __toESM(require_element(), 1); 20954 var import_data15 = __toESM(require_data(), 1); 20955 var import_blocks6 = __toESM(require_blocks(), 1); 20956 20957 // packages/core-data/build-module/hooks/use-entity-id.mjs 20958 var import_element5 = __toESM(require_element(), 1); 20959 function useEntityId(kind, name) { 20960 const context = (0, import_element5.useContext)(EntityContext); 20961 return context?.[kind]?.[name]; 20962 } 20963 20964 // packages/core-data/build-module/footnotes/index.mjs 20965 var import_rich_text4 = __toESM(require_rich_text(), 1); 20966 var import_warning3 = __toESM(require_warning(), 1); 20967 20968 // packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs 20969 var import_block_editor6 = __toESM(require_block_editor(), 1); 20970 var unlockedApis; 20971 var cache = /* @__PURE__ */ new WeakMap(); 20972 function getRichTextValuesCached(block) { 20973 if (!unlockedApis) { 20974 unlockedApis = unlock(import_block_editor6.privateApis); 20975 } 20976 if (!cache.has(block)) { 20977 const values = unlockedApis.getRichTextValues([block]); 20978 cache.set(block, values); 20979 } 20980 return cache.get(block); 20981 } 20982 20983 // packages/core-data/build-module/footnotes/get-footnotes-order.mjs 20984 var cache2 = /* @__PURE__ */ new WeakMap(); 20985 function getBlockFootnotesOrder(block) { 20986 if (!cache2.has(block)) { 20987 const order = []; 20988 for (const value of getRichTextValuesCached(block)) { 20989 if (!value) { 20990 continue; 20991 } 20992 value.replacements.forEach(({ type, attributes }) => { 20993 if (type === "core/footnote") { 20994 order.push(attributes["data-fn"]); 20995 } 20996 }); 20997 } 20998 cache2.set(block, order); 20999 } 21000 return cache2.get(block); 21001 } 21002 function getFootnotesOrder(blocks) { 21003 return blocks.flatMap(getBlockFootnotesOrder); 21004 } 21005 21006 // packages/core-data/build-module/footnotes/index.mjs 21007 var oldFootnotes = {}; 21008 function updateFootnotesFromMeta(blocks, meta) { 21009 const output = { blocks }; 21010 if (!meta) { 21011 return output; 21012 } 21013 if (meta.footnotes === void 0) { 21014 return output; 21015 } 21016 const newOrder = getFootnotesOrder(blocks); 21017 let parsed; 21018 try { 21019 parsed = JSON.parse(meta.footnotes || "[]"); 21020 } catch { 21021 } 21022 let footnotes = []; 21023 if (Array.isArray(parsed)) { 21024 footnotes = parsed; 21025 } else { 21026 (0, import_warning3.default)("Footnotes post meta is not a JSON array; ignoring it."); 21027 } 21028 const currentOrder = footnotes.map((fn) => fn.id); 21029 if (currentOrder.join("") === newOrder.join("")) { 21030 return output; 21031 } 21032 const newFootnotes = newOrder.map( 21033 (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || { 21034 id: fnId, 21035 content: "" 21036 } 21037 ); 21038 function updateAttributes(attributes) { 21039 if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") { 21040 return attributes; 21041 } 21042 attributes = { ...attributes }; 21043 for (const key in attributes) { 21044 const value = attributes[key]; 21045 if (Array.isArray(value)) { 21046 attributes[key] = value.map(updateAttributes); 21047 continue; 21048 } 21049 if (typeof value !== "string" && !(value instanceof import_rich_text4.RichTextData)) { 21050 continue; 21051 } 21052 const richTextValue = typeof value === "string" ? import_rich_text4.RichTextData.fromHTMLString(value) : new import_rich_text4.RichTextData(value); 21053 let hasFootnotes = false; 21054 richTextValue.replacements.forEach((replacement) => { 21055 if (replacement.type === "core/footnote") { 21056 const id2 = replacement.attributes["data-fn"]; 21057 const index = newOrder.indexOf(id2); 21058 const countValue = (0, import_rich_text4.create)({ 21059 html: replacement.innerHTML 21060 }); 21061 countValue.text = String(index + 1); 21062 countValue.formats = Array.from( 21063 { length: countValue.text.length }, 21064 () => countValue.formats[0] 21065 ); 21066 countValue.replacements = Array.from( 21067 { length: countValue.text.length }, 21068 () => countValue.replacements[0] 21069 ); 21070 replacement.innerHTML = (0, import_rich_text4.toHTMLString)({ 21071 value: countValue 21072 }); 21073 hasFootnotes = true; 21074 } 21075 }); 21076 if (hasFootnotes) { 21077 attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue; 21078 } 21079 } 21080 return attributes; 21081 } 21082 function updateBlocksAttributes(__blocks) { 21083 return __blocks.map((block) => { 21084 return { 21085 ...block, 21086 attributes: updateAttributes(block.attributes), 21087 innerBlocks: updateBlocksAttributes(block.innerBlocks) 21088 }; 21089 }); 21090 } 21091 const newBlocks = updateBlocksAttributes(blocks); 21092 oldFootnotes = { 21093 ...oldFootnotes, 21094 ...footnotes.reduce((acc, fn) => { 21095 if (!newOrder.includes(fn.id)) { 21096 acc[fn.id] = fn; 21097 } 21098 return acc; 21099 }, {}) 21100 }; 21101 return { 21102 meta: { 21103 ...meta, 21104 footnotes: JSON.stringify(newFootnotes) 21105 }, 21106 blocks: newBlocks 21107 }; 21108 } 21109 21110 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs 21111 var EMPTY_ARRAY2 = []; 21112 function useEntityBlockEditor(kind, name, { id: _id } = {}) { 21113 const providerId = useEntityId(kind, name); 21114 const id2 = _id ?? providerId; 21115 const { content, editedBlocks, meta } = (0, import_data15.useSelect)( 21116 (select6) => { 21117 if (!id2) { 21118 return {}; 21119 } 21120 const { getEditedEntityRecord: getEditedEntityRecord3 } = select6(STORE_NAME); 21121 const editedRecord = getEditedEntityRecord3(kind, name, id2); 21122 return { 21123 editedBlocks: editedRecord.blocks, 21124 content: editedRecord.content, 21125 meta: editedRecord.meta 21126 }; 21127 }, 21128 [kind, name, id2] 21129 ); 21130 const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data15.useDispatch)(STORE_NAME); 21131 const blocks = (0, import_element6.useMemo)(() => { 21132 if (!id2) { 21133 return void 0; 21134 } 21135 if (editedBlocks) { 21136 return editedBlocks; 21137 } 21138 if (!content || typeof content !== "string") { 21139 return EMPTY_ARRAY2; 21140 } 21141 let _blocks = getCachedBlocks(kind, name, id2, content); 21142 if (!_blocks) { 21143 _blocks = (0, import_blocks6.parse)(content); 21144 setCachedBlocks(kind, name, id2, content, _blocks); 21145 } 21146 return _blocks; 21147 }, [kind, name, id2, editedBlocks, content]); 21148 const onChange = (0, import_element6.useCallback)( 21149 (newBlocks, options) => { 21150 const noChange = blocks === newBlocks; 21151 if (noChange) { 21152 return __unstableCreateUndoLevel2(kind, name, id2); 21153 } 21154 const { selection, ...rest } = options; 21155 const edits = { 21156 selection, 21157 content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks6.__unstableSerializeAndClean)(blocksForSerialization), 21158 ...updateFootnotesFromMeta(newBlocks, meta) 21159 }; 21160 editEntityRecord2(kind, name, id2, edits, { 21161 isCached: false, 21162 ...rest 21163 }); 21164 }, 21165 [ 21166 kind, 21167 name, 21168 id2, 21169 blocks, 21170 meta, 21171 __unstableCreateUndoLevel2, 21172 editEntityRecord2 21173 ] 21174 ); 21175 const onInput = (0, import_element6.useCallback)( 21176 (newBlocks, options) => { 21177 const { selection, ...rest } = options; 21178 const edits = { 21179 selection, 21180 ...updateFootnotesFromMeta(newBlocks, meta) 21181 }; 21182 editEntityRecord2(kind, name, id2, edits, { 21183 isCached: true, 21184 ...rest 21185 }); 21186 }, 21187 [kind, name, id2, meta, editEntityRecord2] 21188 ); 21189 return [blocks, onInput, onChange]; 21190 } 21191 21192 // packages/core-data/build-module/hooks/use-entity-prop.mjs 21193 var import_element7 = __toESM(require_element(), 1); 21194 var import_data16 = __toESM(require_data(), 1); 21195 var REVISION_QUERY = { 21196 context: "edit", 21197 _fields: "id,date,author,meta,title,excerpt,content.raw" 21198 }; 21199 function useEntityProp(kind, name, prop, _id) { 21200 const providerId = useEntityId(kind, name); 21201 const id2 = _id ?? providerId; 21202 const context = (0, import_element7.useContext)(EntityContext); 21203 const providedRevision = String(id2) === String(providerId) ? context?.revision?.[kind]?.[name] : void 0; 21204 const revisionRecord = typeof providedRevision === "object" ? providedRevision : void 0; 21205 const revisionId = revisionRecord ? void 0 : providedRevision; 21206 const isRevision = !!(revisionRecord || revisionId); 21207 const { value, fullValue } = (0, import_data16.useSelect)( 21208 (select6) => { 21209 if (revisionRecord ? prop in revisionRecord : revisionId) { 21210 const revision = revisionRecord ?? select6(STORE_NAME).getRevision( 21211 kind, 21212 name, 21213 id2, 21214 revisionId, 21215 REVISION_QUERY 21216 ); 21217 const propValue = revision?.[prop]; 21218 if (propValue === void 0) { 21219 return {}; 21220 } 21221 const isRawAttribute = propValue !== null && typeof propValue === "object" && "raw" in propValue; 21222 return { 21223 value: isRawAttribute ? propValue.raw : propValue, 21224 fullValue: propValue 21225 }; 21226 } 21227 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select6(STORE_NAME); 21228 const record = getEntityRecord3(kind, name, id2); 21229 const editedRecord = getEditedEntityRecord3(kind, name, id2); 21230 return record && editedRecord ? { 21231 value: editedRecord[prop], 21232 fullValue: record[prop] 21233 } : {}; 21234 }, 21235 [kind, name, id2, prop, revisionId, revisionRecord] 21236 ); 21237 const { editEntityRecord: editEntityRecord2 } = (0, import_data16.useDispatch)(STORE_NAME); 21238 const setValue = (0, import_element7.useCallback)( 21239 (newValue) => { 21240 if (isRevision) { 21241 return; 21242 } 21243 editEntityRecord2(kind, name, id2, { 21244 [prop]: newValue 21245 }); 21246 }, 21247 [editEntityRecord2, kind, name, id2, prop, isRevision] 21248 ); 21249 return [value, setValue, fullValue]; 21250 } 21251 21252 // packages/core-data/build-module/hooks/use-post-editor-awareness-state.mjs 21253 var import_compose3 = __toESM(require_compose(), 1); 21254 var import_element8 = __toESM(require_element(), 1); 21255 var defaultResolvedSelection = { 21256 richTextOffset: null, 21257 localClientId: null, 21258 attributeKey: null 21259 }; 21260 var defaultState = { 21261 activeCollaborators: [], 21262 resolveSelection: () => defaultResolvedSelection, 21263 getDebugData: () => ({ 21264 doc: {}, 21265 clients: {}, 21266 collaboratorMap: {} 21267 }), 21268 isCurrentCollaboratorDisconnected: false 21269 }; 21270 function getAwarenessState(awareness, newState) { 21271 const activeCollaborators = (newState ?? awareness.getCurrentState()).filter( 21272 (collaborator) => isCollaboratorInfo(collaborator.collaboratorInfo) 21273 ); 21274 return { 21275 activeCollaborators, 21276 resolveSelection: (selection, blocks) => awareness.convertSelectionStateToAbsolute(selection, blocks), 21277 getDebugData: () => awareness.getDebugData(), 21278 isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false 21279 }; 21280 } 21281 function usePostEditorAwarenessState(postId, postType) { 21282 const [state, setState] = (0, import_element8.useState)(defaultState); 21283 (0, import_element8.useEffect)(() => { 21284 if (null === postId || null === postType) { 21285 setState(defaultState); 21286 return; 21287 } 21288 const objectType = `postType/$postType}`; 21289 const objectId = postId.toString(); 21290 const awareness = getSyncManager()?.getAwareness( 21291 objectType, 21292 objectId 21293 ); 21294 if (!awareness) { 21295 setState(defaultState); 21296 return; 21297 } 21298 awareness.setUp(); 21299 setState(getAwarenessState(awareness)); 21300 const unsubscribe = awareness?.onStateChange( 21301 (newState) => { 21302 setState(getAwarenessState(awareness, newState)); 21303 } 21304 ); 21305 return unsubscribe; 21306 }, [postId, postType]); 21307 return state; 21308 } 21309 function useActiveCollaborators(postId, postType) { 21310 return usePostEditorAwarenessState(postId, postType).activeCollaborators; 21311 } 21312 function useResolvedSelection(postId, postType) { 21313 const blocks = usePostContentBlocks(); 21314 const awarenessState = usePostEditorAwarenessState(postId, postType); 21315 return (0, import_element8.useCallback)( 21316 (selection) => awarenessState.resolveSelection(selection, blocks), 21317 [blocks, awarenessState] 21318 ); 21319 } 21320 function useLastPostSave(postId, postType) { 21321 const [lastSave, setLastSave] = (0, import_element8.useState)(null); 21322 (0, import_element8.useEffect)(() => { 21323 if (null === postId || null === postType) { 21324 setLastSave(null); 21325 return; 21326 } 21327 const awareness = getSyncManager()?.getAwareness( 21328 `postType/$postType}`, 21329 postId.toString() 21330 ); 21331 if (!awareness) { 21332 setLastSave(null); 21333 return; 21334 } 21335 awareness.setUp(); 21336 const stateMap = awareness.doc.getMap("state"); 21337 const recordMap = awareness.doc.getMap("document"); 21338 const setupTime = Date.now(); 21339 const observer = (event) => { 21340 if (event.keysChanged.has("savedAt")) { 21341 const savedAt = stateMap.get("savedAt"); 21342 const savedByClientId = stateMap.get("savedBy"); 21343 if (typeof savedAt === "number" && typeof savedByClientId === "number" && savedAt > setupTime) { 21344 const postStatus = recordMap.get("status"); 21345 setLastSave({ savedAt, savedByClientId, postStatus }); 21346 } 21347 } 21348 }; 21349 stateMap.observe(observer); 21350 return () => { 21351 stateMap.unobserve(observer); 21352 }; 21353 }, [postId, postType]); 21354 return lastSave; 21355 } 21356 function useOnCollaboratorJoin(postId, postType, callback) { 21357 const { activeCollaborators } = usePostEditorAwarenessState( 21358 postId, 21359 postType 21360 ); 21361 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators); 21362 (0, import_element8.useEffect)(() => { 21363 if (!prevCollaborators || prevCollaborators.length === 0) { 21364 return; 21365 } 21366 const prevMap = new Map( 21367 prevCollaborators.map((collaborator) => [ 21368 collaborator.clientId, 21369 collaborator 21370 ]) 21371 ); 21372 const me = activeCollaborators.find( 21373 (collaborator) => collaborator.isMe 21374 ); 21375 for (const collaborator of activeCollaborators) { 21376 if (!prevMap.has(collaborator.clientId) && !collaborator.isMe) { 21377 callback(collaborator, me); 21378 } 21379 } 21380 }, [activeCollaborators, prevCollaborators, callback]); 21381 } 21382 function useOnCollaboratorLeave(postId, postType, callback) { 21383 const { activeCollaborators } = usePostEditorAwarenessState( 21384 postId, 21385 postType 21386 ); 21387 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators); 21388 (0, import_element8.useEffect)(() => { 21389 if (!prevCollaborators || prevCollaborators.length === 0) { 21390 return; 21391 } 21392 const newMap = new Map( 21393 activeCollaborators.map((collaborator) => [ 21394 collaborator.clientId, 21395 collaborator 21396 ]) 21397 ); 21398 for (const prevCollab of prevCollaborators) { 21399 if (prevCollab.isMe || !prevCollab.isConnected) { 21400 continue; 21401 } 21402 const newCollab = newMap.get(prevCollab.clientId); 21403 if (!newCollab?.isConnected) { 21404 callback(prevCollab); 21405 } 21406 } 21407 }, [activeCollaborators, prevCollaborators, callback]); 21408 } 21409 function useOnPostSave(postId, postType, callback) { 21410 const { activeCollaborators } = usePostEditorAwarenessState( 21411 postId, 21412 postType 21413 ); 21414 const lastPostSave = useLastPostSave(postId, postType); 21415 const prevPostSave = (0, import_compose3.usePrevious)(lastPostSave); 21416 (0, import_element8.useEffect)(() => { 21417 if (!lastPostSave) { 21418 return; 21419 } 21420 if (prevPostSave && lastPostSave.savedAt === prevPostSave.savedAt) { 21421 return; 21422 } 21423 const saver = activeCollaborators.find( 21424 (collaborator) => collaborator.clientId === lastPostSave.savedByClientId && !collaborator.isMe 21425 ); 21426 if (!saver) { 21427 return; 21428 } 21429 callback(lastPostSave, saver, prevPostSave ?? null); 21430 }, [lastPostSave, prevPostSave, activeCollaborators, callback]); 21431 } 21432 21433 // packages/icons/build-module/library/footer.mjs 21434 var import_primitives = __toESM(require_primitives(), 1); 21435 var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); 21436 var footer_default = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [ 21437 /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M9.75 4.75H18C18.6904 4.75 19.25 5.30964 19.25 6V14.25M9.75 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V14.25M9.75 4.75V14.25M19.25 14.25V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V14.25M19.25 14.25H9.75M9.75 14.25H4.75" }), 21438 /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M19.25 15.5V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V15.5C4.75 14.8096 5.30964 14.25 6 14.25H18C18.6904 14.25 19.25 14.8096 19.25 15.5Z", fill: "currentColor" }) 21439 ] }); 21440 21441 // packages/icons/build-module/library/header.mjs 21442 var import_primitives2 = __toESM(require_primitives(), 1); 21443 var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); 21444 var header_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [ 21445 /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75" }), 21446 /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M19.25 8.5V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V8.5C4.75 9.19036 5.30964 9.75 6 9.75H18C18.6904 9.75 19.25 9.19036 19.25 8.5Z", fill: "currentColor" }) 21447 ] }); 21448 21449 // packages/icons/build-module/library/layout.mjs 21450 var import_primitives3 = __toESM(require_primitives(), 1); 21451 var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1); 21452 var layout_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75" }) }); 21453 21454 // packages/icons/build-module/library/navigation-overlay.mjs 21455 var import_primitives4 = __toESM(require_primitives(), 1); 21456 var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1); 21457 var navigation_overlay_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [ 21458 /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M4.75 9.25V16C4.75 16.6904 5.30964 17.25 6 17.25H8M4.75 9.25V6C4.75 5.30964 5.30964 4.75 6 4.75H16C16.6904 4.75 17.25 5.30964 17.25 6V8M4.75 9.25H8" }), 21459 /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M10.75 11.25C10.75 10.9739 10.9739 10.75 11.25 10.75H18.75C19.0261 10.75 19.25 10.9739 19.25 11.25V18.75C19.25 19.0261 19.0261 19.25 18.75 19.25H11.25C10.9739 19.25 10.75 19.0261 10.75 18.75V11.25Z", fill: "currentColor" }) 21460 ] }); 21461 21462 // packages/icons/build-module/library/sidebar.mjs 21463 var import_primitives5 = __toESM(require_primitives(), 1); 21464 var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1); 21465 var sidebar_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [ 21466 /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75" }), 21467 /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M6 19.25H9.75V9.75H4.75V18C4.75 18.6904 5.30964 19.25 6 19.25Z", fill: "currentColor" }) 21468 ] }); 21469 21470 // packages/icons/build-module/library/symbol-filled.mjs 21471 var import_primitives6 = __toESM(require_primitives(), 1); 21472 var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1); 21473 var symbol_filled_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [ 21474 /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M15.2071 6.20711L20.2929 11.2929C20.6834 11.6834 20.6834 12.3166 20.2929 12.7071L15.2071 17.7929C14.8166 18.1834 14.1834 18.1834 13.7929 17.7929L8.70711 12.7071C8.31658 12.3166 8.31658 11.6834 8.70711 11.2929L13.7929 6.20711C14.1834 5.81658 14.8166 5.81658 15.2071 6.20711Z", fill: "currentColor" }), 21475 /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M9.5 5.5L3.70711 11.2929C3.31658 11.6834 3.31658 12.3166 3.70711 12.7071L9.5 18.5" }) 21476 ] }); 21477 21478 // packages/core-data/build-module/utils/get-template-part-icon.mjs 21479 function getTemplatePartIcon(areaOrIconName) { 21480 if ("header" === areaOrIconName) { 21481 return header_default; 21482 } else if ("footer" === areaOrIconName) { 21483 return footer_default; 21484 } else if ("sidebar" === areaOrIconName) { 21485 return sidebar_default; 21486 } else if ("navigation-overlay" === areaOrIconName) { 21487 return navigation_overlay_default; 21488 } 21489 return symbol_filled_default; 21490 } 21491 21492 // packages/core-data/build-module/utils/get-template-info.mjs 21493 var EMPTY_OBJECT4 = {}; 21494 var getTemplateInfo = (params2) => { 21495 if (!params2) { 21496 return EMPTY_OBJECT4; 21497 } 21498 const { templateTypes, templateAreas, template } = params2; 21499 const { description, slug, title, area } = template; 21500 const { title: defaultTitle, description: defaultDescription } = Object.values(templateTypes).find((type) => type.slug === slug) ?? EMPTY_OBJECT4; 21501 const templateTitle = typeof title === "string" ? title : title?.rendered; 21502 const templateDescription = typeof description === "string" ? description : description?.raw; 21503 const templateAreasWithIcon = templateAreas?.map((item) => ({ 21504 ...item, 21505 icon: getTemplatePartIcon(item.icon) 21506 })); 21507 const templateIcon = templateAreasWithIcon?.find((item) => area === item.area)?.icon || layout_default; 21508 return { 21509 title: templateTitle && templateTitle !== slug ? templateTitle : defaultTitle || slug, 21510 description: templateDescription || defaultDescription, 21511 icon: templateIcon 21512 }; 21513 }; 21514 21515 // node_modules/.store/clsx@2.1.1-XOLP1vUL9vEGfpiXm37fAw/node_modules/clsx/dist/clsx.mjs 21516 function r(e) { 21517 var t, f, n = ""; 21518 if ("string" == typeof e || "number" == typeof e) n += e; 21519 else if ("object" == typeof e) if (Array.isArray(e)) { 21520 var o = e.length; 21521 for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f); 21522 } else for (f in e) e[f] && (n && (n += " "), n += f); 21523 return n; 21524 } 21525 function clsx() { 21526 for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t); 21527 return n; 21528 } 21529 var clsx_default = clsx; 21530 21531 // packages/core-data/build-module/components/entities-saved-states/index.mjs 21532 var import_components3 = __toESM(require_components(), 1); 21533 var import_i18n7 = __toESM(require_i18n(), 1); 21534 var import_element10 = __toESM(require_element(), 1); 21535 var import_compose4 = __toESM(require_compose(), 1); 21536 var import_data20 = __toESM(require_data(), 1); 21537 21538 // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs 21539 var import_i18n6 = __toESM(require_i18n(), 1); 21540 var import_data18 = __toESM(require_data(), 1); 21541 var import_components2 = __toESM(require_components(), 1); 21542 21543 // packages/global-styles-engine/build-module/utils/get-global-styles-changes.mjs 21544 var import_i18n4 = __toESM(require_i18n(), 1); 21545 var import_blocks7 = __toESM(require_blocks(), 1); 21546 var globalStylesChangesCache = /* @__PURE__ */ new Map(); 21547 var EMPTY_ARRAY3 = []; 21548 var translationMap = { 21549 caption: (0, import_i18n4.__)("Caption"), 21550 link: (0, import_i18n4.__)("Link"), 21551 button: (0, import_i18n4.__)("Button"), 21552 heading: (0, import_i18n4.__)("Heading"), 21553 h1: (0, import_i18n4.__)("H1"), 21554 h2: (0, import_i18n4.__)("H2"), 21555 h3: (0, import_i18n4.__)("H3"), 21556 h4: (0, import_i18n4.__)("H4"), 21557 h5: (0, import_i18n4.__)("H5"), 21558 h6: (0, import_i18n4.__)("H6"), 21559 "settings.color": (0, import_i18n4.__)("Color"), 21560 "settings.typography": (0, import_i18n4.__)("Typography"), 21561 "settings.shadow": (0, import_i18n4.__)("Shadow"), 21562 "settings.layout": (0, import_i18n4.__)("Layout"), 21563 "styles.color": (0, import_i18n4.__)("Colors"), 21564 "styles.spacing": (0, import_i18n4.__)("Spacing"), 21565 "styles.background": (0, import_i18n4.__)("Background"), 21566 "styles.typography": (0, import_i18n4.__)("Typography"), 21567 "styles.border": (0, import_i18n4.__)("Border"), 21568 "styles.shadow": (0, import_i18n4.__)("Shadow"), 21569 "styles.outline": (0, import_i18n4.__)("Outline"), 21570 "styles.filter": (0, import_i18n4.__)("Filter"), 21571 "styles.dimensions": (0, import_i18n4.__)("Dimensions") 21572 }; 21573 var getBlockNames = memize( 21574 () => (0, import_blocks7.getBlockTypes)().reduce( 21575 (accumulator, { 21576 name, 21577 title 21578 }) => { 21579 accumulator[name] = title; 21580 return accumulator; 21581 }, 21582 {} 21583 ) 21584 ); 21585 var isObject2 = (obj) => obj !== null && typeof obj === "object"; 21586 function getTranslation(key) { 21587 if (translationMap[key]) { 21588 return translationMap[key]; 21589 } 21590 const keyArray = key.split("."); 21591 if (keyArray?.[0] === "blocks") { 21592 const blockName = getBlockNames()?.[keyArray[1]]; 21593 return blockName || keyArray[1]; 21594 } 21595 if (keyArray?.[0] === "elements") { 21596 return translationMap[keyArray[1]] || keyArray[1]; 21597 } 21598 return void 0; 21599 } 21600 function deepCompare(changedObject, originalObject, parentPath = "") { 21601 if (!isObject2(changedObject) && !isObject2(originalObject)) { 21602 return changedObject !== originalObject ? parentPath.split(".").slice(0, 2).join(".") : void 0; 21603 } 21604 changedObject = isObject2(changedObject) ? changedObject : {}; 21605 originalObject = isObject2(originalObject) ? originalObject : {}; 21606 const allKeys = /* @__PURE__ */ new Set([ 21607 ...Object.keys(changedObject), 21608 ...Object.keys(originalObject) 21609 ]); 21610 let diffs = []; 21611 for (const key of allKeys) { 21612 const path = parentPath ? parentPath + "." + key : key; 21613 const changedPath = deepCompare( 21614 changedObject[key], 21615 originalObject[key], 21616 path 21617 ); 21618 if (changedPath) { 21619 diffs = diffs.concat(changedPath); 21620 } 21621 } 21622 return diffs; 21623 } 21624 var COMPARED_STYLE_KEYS = [ 21625 "background", 21626 "color", 21627 "typography", 21628 "spacing", 21629 "border", 21630 "shadow", 21631 "outline", 21632 "filter", 21633 "dimensions" 21634 ]; 21635 function pickComparedStyles(config) { 21636 return Object.fromEntries( 21637 COMPARED_STYLE_KEYS.map((key) => [key, config?.styles?.[key]]) 21638 ); 21639 } 21640 function getGlobalStylesChangelist(next, previous) { 21641 const cacheKey = JSON.stringify({ next, previous }); 21642 if (globalStylesChangesCache.has(cacheKey)) { 21643 return globalStylesChangesCache.get(cacheKey); 21644 } 21645 const changedValueTree = deepCompare( 21646 { 21647 styles: pickComparedStyles(next), 21648 blocks: next?.styles?.blocks, 21649 elements: next?.styles?.elements, 21650 settings: next?.settings 21651 }, 21652 { 21653 styles: pickComparedStyles(previous), 21654 blocks: previous?.styles?.blocks, 21655 elements: previous?.styles?.elements, 21656 settings: previous?.settings 21657 } 21658 ); 21659 if (!changedValueTree || Array.isArray(changedValueTree) && !changedValueTree.length) { 21660 globalStylesChangesCache.set(cacheKey, []); 21661 return []; 21662 } 21663 const changedValueArray = Array.isArray(changedValueTree) ? changedValueTree : [changedValueTree]; 21664 const result = [...new Set(changedValueArray)].reduce((acc, curr) => { 21665 const translation = getTranslation(curr); 21666 if (translation) { 21667 acc.push([curr.split(".")[0], translation]); 21668 } 21669 return acc; 21670 }, []); 21671 globalStylesChangesCache.set(cacheKey, result); 21672 return result; 21673 } 21674 function getGlobalStylesChanges(next, previous, options = {}) { 21675 let changeList = getGlobalStylesChangelist(next, previous); 21676 const changesLength = changeList.length; 21677 const { maxResults } = options; 21678 if (changesLength) { 21679 if (!!maxResults && changesLength > maxResults) { 21680 changeList = changeList.slice(0, maxResults); 21681 } 21682 return Object.entries( 21683 changeList.reduce((acc, curr) => { 21684 const group = acc[curr[0]] || []; 21685 if (!group.includes(curr[1])) { 21686 acc[curr[0]] = [...group, curr[1]]; 21687 } 21688 return acc; 21689 }, {}) 21690 ).map(([key, changeValues]) => { 21691 const changeValuesLength = changeValues.length; 21692 const joinedChangesValue = changeValues.join( 21693 /* translators: Used between list items, there is a space after the comma. */ 21694 (0, import_i18n4.__)(", ") 21695 // eslint-disable-line @wordpress/i18n-no-flanking-whitespace 21696 ); 21697 switch (key) { 21698 case "blocks": { 21699 return (0, import_i18n4.sprintf)( 21700 // translators: %s: a list of block names separated by a comma. 21701 (0, import_i18n4._n)("%s block.", "%s blocks.", changeValuesLength), 21702 joinedChangesValue 21703 ); 21704 } 21705 case "elements": { 21706 return (0, import_i18n4.sprintf)( 21707 // translators: %s: a list of element names separated by a comma. 21708 (0, import_i18n4._n)("%s element.", "%s elements.", changeValuesLength), 21709 joinedChangesValue 21710 ); 21711 } 21712 case "settings": { 21713 return (0, import_i18n4.sprintf)( 21714 // translators: %s: a list of theme.json setting labels separated by a comma. 21715 (0, import_i18n4.__)("%s settings."), 21716 joinedChangesValue 21717 ); 21718 } 21719 case "styles": { 21720 return (0, import_i18n4.sprintf)( 21721 // translators: %s: a list of theme.json top-level styles labels separated by a comma. 21722 (0, import_i18n4.__)("%s styles."), 21723 joinedChangesValue 21724 ); 21725 } 21726 default: { 21727 return (0, import_i18n4.sprintf)( 21728 // translators: %s: a list of global styles changes separated by a comma. 21729 (0, import_i18n4.__)("%s."), 21730 joinedChangesValue 21731 ); 21732 } 21733 } 21734 }); 21735 } 21736 return EMPTY_ARRAY3; 21737 } 21738 21739 // packages/core-data/build-module/components/entities-saved-states/entity-record-item.mjs 21740 var import_components = __toESM(require_components(), 1); 21741 var import_i18n5 = __toESM(require_i18n(), 1); 21742 var import_data17 = __toESM(require_data(), 1); 21743 var import_html_entities4 = __toESM(require_html_entities(), 1); 21744 var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1); 21745 function EntityRecordItem({ record, checked, onChange }) { 21746 const { name, kind, title, key } = record; 21747 const { entityRecordTitle } = (0, import_data17.useSelect)( 21748 (select6) => { 21749 if ("postType" !== kind || "wp_template" !== name) { 21750 return { 21751 entityRecordTitle: title 21752 }; 21753 } 21754 const template = select6(STORE_NAME).getEditedEntityRecord( 21755 kind, 21756 name, 21757 key 21758 ); 21759 const { default_template_types: templateTypes = [] } = select6(STORE_NAME).getCurrentTheme() ?? {}; 21760 return { 21761 entityRecordTitle: getTemplateInfo({ 21762 template, 21763 templateTypes 21764 }).title 21765 }; 21766 }, 21767 [name, kind, title, key] 21768 ); 21769 return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_components.PanelRow, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)( 21770 import_components.CheckboxControl, 21771 { 21772 label: (0, import_html_entities4.decodeEntities)(entityRecordTitle) || (0, import_i18n5.__)("Untitled"), 21773 checked, 21774 onChange, 21775 className: "entities-saved-states__change-control" 21776 } 21777 ) }) }); 21778 } 21779 21780 // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs 21781 var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1); 21782 function getEntityDescription(entity2, count) { 21783 switch (entity2) { 21784 case "site": 21785 return 1 === count ? (0, import_i18n6.__)("This change will affect your whole site.") : (0, import_i18n6.__)("These changes will affect your whole site."); 21786 case "wp_template": 21787 return (0, import_i18n6.__)( 21788 "This change will affect other parts of your site that use this template." 21789 ); 21790 case "page": 21791 case "post": 21792 return (0, import_i18n6.__)("The following has been modified."); 21793 } 21794 } 21795 function GlobalStylesDescription({ record }) { 21796 const { editedRecord, savedRecord } = (0, import_data18.useSelect)( 21797 (select6) => { 21798 const { getEditedEntityRecord: getEditedEntityRecord3, getEntityRecord: getEntityRecord3 } = select6(STORE_NAME); 21799 return { 21800 editedRecord: getEditedEntityRecord3( 21801 record.kind, 21802 record.name, 21803 record.key 21804 ), 21805 savedRecord: getEntityRecord3( 21806 record.kind, 21807 record.name, 21808 record.key 21809 ) 21810 }; 21811 }, 21812 [record.kind, record.name, record.key] 21813 ); 21814 const globalStylesChanges = getGlobalStylesChanges( 21815 editedRecord, 21816 savedRecord, 21817 { 21818 maxResults: 10 21819 } 21820 ); 21821 return globalStylesChanges.length ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("ul", { className: "entities-saved-states__changes", children: globalStylesChanges.map((change) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("li", { children: change }, change)) }) : null; 21822 } 21823 function EntityDescription({ record, count }) { 21824 if ("globalStyles" === record?.name) { 21825 return null; 21826 } 21827 const description = getEntityDescription(record?.name, count); 21828 return description ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_components2.PanelRow, { children: description }) : null; 21829 } 21830 function EntityTypeList({ 21831 list, 21832 unselectedEntities, 21833 setUnselectedEntities 21834 }) { 21835 const count = list.length; 21836 const firstRecord = list[0]; 21837 const entityConfig = (0, import_data18.useSelect)( 21838 (select6) => select6(STORE_NAME).getEntityConfig( 21839 firstRecord.kind, 21840 firstRecord.name 21841 ), 21842 [firstRecord.kind, firstRecord.name] 21843 ); 21844 let entityLabel = entityConfig.label; 21845 if (firstRecord?.name === "wp_template_part") { 21846 entityLabel = 1 === count ? (0, import_i18n6.__)("Template Part") : (0, import_i18n6.__)("Template Parts"); 21847 } 21848 return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)( 21849 import_components2.PanelBody, 21850 { 21851 title: entityLabel, 21852 initialOpen: true, 21853 className: "entities-saved-states__panel-body", 21854 children: [ 21855 /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(EntityDescription, { record: firstRecord, count }), 21856 list.map((record) => { 21857 return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)( 21858 EntityRecordItem, 21859 { 21860 record, 21861 checked: !unselectedEntities.some( 21862 (elt) => elt.kind === record.kind && elt.name === record.name && elt.key === record.key && elt.property === record.property 21863 ), 21864 onChange: (value) => setUnselectedEntities(record, value) 21865 }, 21866 record.key || record.property 21867 ); 21868 }), 21869 "globalStyles" === firstRecord?.name && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(GlobalStylesDescription, { record: firstRecord }) 21870 ] 21871 } 21872 ); 21873 } 21874 21875 // packages/core-data/build-module/components/entities-saved-states/hooks/use-is-dirty.mjs 21876 var import_data19 = __toESM(require_data(), 1); 21877 var import_element9 = __toESM(require_element(), 1); 21878 var useIsDirty = () => { 21879 const { editedEntities, siteEdits, siteEntityConfig } = (0, import_data19.useSelect)( 21880 (select6) => { 21881 const { 21882 __experimentalGetDirtyEntityRecords: __experimentalGetDirtyEntityRecords2, 21883 getEntityRecordEdits: getEntityRecordEdits2, 21884 getEntityConfig: getEntityConfig2 21885 } = select6(STORE_NAME); 21886 return { 21887 editedEntities: __experimentalGetDirtyEntityRecords2(), 21888 siteEdits: getEntityRecordEdits2("root", "site"), 21889 siteEntityConfig: getEntityConfig2("root", "site") 21890 }; 21891 }, 21892 [] 21893 ); 21894 const dirtyEntityRecords = (0, import_element9.useMemo)(() => { 21895 const editedEntitiesWithoutSite = editedEntities.filter( 21896 (record) => !(record.kind === "root" && record.name === "site") 21897 ); 21898 const siteEntityLabels = siteEntityConfig?.meta?.labels ?? {}; 21899 const { 21900 title: siteTitleEdit, 21901 description: siteDescriptionEdit, 21902 site_logo: siteLogoEdit, 21903 site_icon: siteIconEdit, 21904 ...otherSiteEdits 21905 } = siteEdits ?? {}; 21906 const orderedSiteProperties = [ 21907 siteTitleEdit !== void 0 && "title", 21908 siteDescriptionEdit !== void 0 && "description", 21909 siteLogoEdit !== void 0 && "site_logo", 21910 siteIconEdit !== void 0 && "site_icon", 21911 ...Object.keys(otherSiteEdits) 21912 ].filter(Boolean); 21913 const editedSiteEntities = orderedSiteProperties.map( 21914 (property) => ({ 21915 kind: "root", 21916 name: "site", 21917 title: siteEntityLabels[property] || property, 21918 property 21919 }) 21920 ); 21921 return [...editedEntitiesWithoutSite, ...editedSiteEntities]; 21922 }, [editedEntities, siteEdits, siteEntityConfig]); 21923 const [unselectedEntities, _setUnselectedEntities] = (0, import_element9.useState)([]); 21924 const setUnselectedEntities = ({ kind, name, key, property }, checked) => { 21925 if (checked) { 21926 _setUnselectedEntities( 21927 unselectedEntities.filter( 21928 (elt) => elt.kind !== kind || elt.name !== name || elt.key !== key || elt.property !== property 21929 ) 21930 ); 21931 } else { 21932 _setUnselectedEntities([ 21933 ...unselectedEntities, 21934 { kind, name, key, property } 21935 ]); 21936 } 21937 }; 21938 const isDirty = dirtyEntityRecords.length - unselectedEntities.length > 0; 21939 return { 21940 dirtyEntityRecords, 21941 isDirty, 21942 setUnselectedEntities, 21943 unselectedEntities 21944 }; 21945 }; 21946 21947 // packages/core-data/build-module/components/entities-saved-states/index.mjs 21948 var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1); 21949 function EntitiesSavedStates({ 21950 close, 21951 renderDialog, 21952 variant 21953 }) { 21954 const isDirtyProps = useIsDirty(); 21955 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 21956 EntitiesSavedStatesExtensible, 21957 { 21958 close, 21959 renderDialog, 21960 variant, 21961 ...isDirtyProps 21962 } 21963 ); 21964 } 21965 function EntitiesSavedStatesExtensible({ 21966 additionalPrompt = void 0, 21967 close, 21968 onSave = void 0, 21969 saveEnabled: saveEnabledProp = void 0, 21970 saveLabel = (0, import_i18n7.__)("Save"), 21971 renderDialog, 21972 dirtyEntityRecords, 21973 isDirty, 21974 setUnselectedEntities, 21975 unselectedEntities, 21976 variant = "default", 21977 successNoticeContent 21978 }) { 21979 const saveButtonRef = (0, import_element10.useRef)(); 21980 const { saveDirtyEntities: saveDirtyEntities2 } = unlock((0, import_data20.useDispatch)(STORE_NAME)); 21981 const partitionedSavables = dirtyEntityRecords.reduce((acc, record) => { 21982 const { name } = record; 21983 if (!acc[name]) { 21984 acc[name] = []; 21985 } 21986 acc[name].push(record); 21987 return acc; 21988 }, {}); 21989 const { 21990 site: siteSavables, 21991 wp_template: templateSavables, 21992 wp_template_part: templatePartSavables, 21993 ...contentSavables 21994 } = partitionedSavables; 21995 const sortedPartitionedSavables = [ 21996 siteSavables, 21997 templateSavables, 21998 templatePartSavables, 21999 ...Object.values(contentSavables) 22000 ].filter(Array.isArray); 22001 const saveEnabled = saveEnabledProp ?? isDirty; 22002 const dismissPanel = (0, import_element10.useCallback)(() => close(), [close]); 22003 const [saveDialogRef, saveDialogProps] = (0, import_compose4.__experimentalUseDialog)({ 22004 onClose: () => dismissPanel() 22005 }); 22006 const dialogLabelId = (0, import_compose4.useInstanceId)( 22007 EntitiesSavedStatesExtensible, 22008 "entities-saved-states__panel-label" 22009 ); 22010 const dialogDescriptionId = (0, import_compose4.useInstanceId)( 22011 EntitiesSavedStatesExtensible, 22012 "entities-saved-states__panel-description" 22013 ); 22014 const selectItemsToSaveDescription = !!dirtyEntityRecords.length ? (0, import_i18n7.__)("Select the items you want to save.") : void 0; 22015 const isInline = variant === "inline"; 22016 const actionButtons = /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [ 22017 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 22018 import_components3.FlexItem, 22019 { 22020 isBlock: isInline ? false : true, 22021 as: import_components3.Button, 22022 variant: isInline ? "tertiary" : "secondary", 22023 size: isInline ? void 0 : "compact", 22024 onClick: dismissPanel, 22025 children: (0, import_i18n7.__)("Cancel") 22026 } 22027 ), 22028 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 22029 import_components3.FlexItem, 22030 { 22031 isBlock: isInline ? false : true, 22032 as: import_components3.Button, 22033 ref: saveButtonRef, 22034 variant: "primary", 22035 size: isInline ? void 0 : "compact", 22036 disabled: !saveEnabled, 22037 accessibleWhenDisabled: true, 22038 onClick: () => saveDirtyEntities2({ 22039 onSave, 22040 dirtyEntityRecords, 22041 entitiesToSkip: unselectedEntities, 22042 close, 22043 successNoticeContent 22044 }), 22045 className: "entities-saved-states__save-button", 22046 children: saveLabel 22047 } 22048 ) 22049 ] }); 22050 return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)( 22051 "div", 22052 { 22053 ref: renderDialog ? saveDialogRef : void 0, 22054 ...renderDialog && saveDialogProps, 22055 className: clsx_default("entities-saved-states__panel", { 22056 "is-inline": isInline 22057 }), 22058 role: renderDialog ? "dialog" : void 0, 22059 "aria-labelledby": renderDialog ? dialogLabelId : void 0, 22060 "aria-describedby": renderDialog ? dialogDescriptionId : void 0, 22061 children: [ 22062 !isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_components3.Flex, { className: "entities-saved-states__panel-header", gap: 2, children: actionButtons }), 22063 /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "entities-saved-states__text-prompt", children: [ 22064 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "entities-saved-states__text-prompt--header-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 22065 "strong", 22066 { 22067 id: renderDialog ? dialogLabelId : void 0, 22068 className: "entities-saved-states__text-prompt--header", 22069 children: (0, import_i18n7.__)("Are you ready to save?") 22070 } 22071 ) }), 22072 /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { id: renderDialog ? dialogDescriptionId : void 0, children: [ 22073 additionalPrompt, 22074 /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("p", { className: "entities-saved-states__text-prompt--changes-count", children: isDirty ? (0, import_element10.createInterpolateElement)( 22075 (0, import_i18n7.sprintf)( 22076 /* translators: %d: number of site changes waiting to be saved. */ 22077 (0, import_i18n7._n)( 22078 "There is <strong>%d site change</strong> waiting to be saved.", 22079 "There are <strong>%d site changes</strong> waiting to be saved.", 22080 dirtyEntityRecords.length 22081 ), 22082 dirtyEntityRecords.length 22083 ), 22084 { strong: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("strong", {}) } 22085 ) : selectItemsToSaveDescription }) 22086 ] }) 22087 ] }), 22088 sortedPartitionedSavables.map((list) => { 22089 return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 22090 EntityTypeList, 22091 { 22092 list, 22093 unselectedEntities, 22094 setUnselectedEntities 22095 }, 22096 list[0].name 22097 ); 22098 }), 22099 isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)( 22100 import_components3.Flex, 22101 { 22102 direction: "row", 22103 justify: "flex-end", 22104 className: "entities-saved-states__panel-footer", 22105 children: actionButtons 22106 } 22107 ) 22108 ] 22109 } 22110 ); 22111 } 22112 22113 // packages/core-data/build-module/private-apis.mjs 22114 var lockedApis = { 22115 PrivateEntityProvider, 22116 EntitiesSavedStates, 22117 EntitiesSavedStatesExtensible, 22118 getTemplateInfo, 22119 getTemplatePartIcon, 22120 useEntitiesSavedStatesIsDirty: useIsDirty, 22121 useEntityRecordsWithPermissions, 22122 RECEIVE_INTERMEDIATE_RESULTS, 22123 CRDT_AUTOSAVE_SNAPSHOT_KEY, 22124 entityContainsSnapshot, 22125 getEntitySnapshot, 22126 retrySyncConnection, 22127 useActiveCollaborators, 22128 useResolvedSelection, 22129 useOnCollaboratorJoin, 22130 useOnCollaboratorLeave, 22131 useOnPostSave, 22132 SelectionType, 22133 SelectionDirection 22134 }; 22135 var privateApis = {}; 22136 lock(privateApis, lockedApis); 22137 22138 // packages/core-data/build-module/index.mjs 22139 var entitiesConfig2 = [ 22140 ...rootEntitiesConfig, 22141 ...additionalEntityConfigLoaders.filter((config) => !!config.name) 22142 ]; 22143 var entitySelectors = entitiesConfig2.reduce((result, entity2) => { 22144 const { kind, name, plural } = entity2; 22145 const getEntityRecordMethodName = getMethodName(kind, name); 22146 result[getEntityRecordMethodName] = (state, key, query) => { 22147 logEntityDeprecation(kind, name, getEntityRecordMethodName, { 22148 isShorthandSelector: true, 22149 alternativeFunctionName: "getEntityRecord" 22150 }); 22151 return getEntityRecord(state, kind, name, key, query); 22152 }; 22153 if (plural) { 22154 const getEntityRecordsMethodName = getMethodName(kind, plural, "get"); 22155 result[getEntityRecordsMethodName] = (state, query) => { 22156 logEntityDeprecation(kind, name, getEntityRecordsMethodName, { 22157 isShorthandSelector: true, 22158 alternativeFunctionName: "getEntityRecords" 22159 }); 22160 return getEntityRecords(state, kind, name, query); 22161 }; 22162 } 22163 return result; 22164 }, {}); 22165 var entityResolvers = entitiesConfig2.reduce((result, entity2) => { 22166 const { kind, name, plural } = entity2; 22167 const getEntityRecordMethodName = getMethodName(kind, name); 22168 result[getEntityRecordMethodName] = (key, query) => { 22169 logEntityDeprecation(kind, name, getEntityRecordMethodName, { 22170 isShorthandSelector: true, 22171 alternativeFunctionName: "getEntityRecord" 22172 }); 22173 return getEntityRecord2(kind, name, key, query); 22174 }; 22175 if (plural) { 22176 const getEntityRecordsMethodName = getMethodName(kind, plural, "get"); 22177 result[getEntityRecordsMethodName] = (...args2) => { 22178 logEntityDeprecation(kind, plural, getEntityRecordsMethodName, { 22179 isShorthandSelector: true, 22180 alternativeFunctionName: "getEntityRecords" 22181 }); 22182 return getEntityRecords2(kind, name, ...args2); 22183 }; 22184 result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name); 22185 } 22186 return result; 22187 }, {}); 22188 var entityActions = entitiesConfig2.reduce((result, entity2) => { 22189 const { kind, name } = entity2; 22190 const saveEntityRecordMethodName = getMethodName(kind, name, "save"); 22191 result[saveEntityRecordMethodName] = (record, options) => { 22192 logEntityDeprecation(kind, name, saveEntityRecordMethodName, { 22193 isShorthandSelector: true, 22194 alternativeFunctionName: "saveEntityRecord" 22195 }); 22196 return saveEntityRecord(kind, name, record, options); 22197 }; 22198 const deleteEntityRecordMethodName = getMethodName(kind, name, "delete"); 22199 result[deleteEntityRecordMethodName] = (key, query, options) => { 22200 logEntityDeprecation(kind, name, deleteEntityRecordMethodName, { 22201 isShorthandSelector: true, 22202 alternativeFunctionName: "deleteEntityRecord" 22203 }); 22204 return deleteEntityRecord(kind, name, key, query, options); 22205 }; 22206 return result; 22207 }, {}); 22208 var storeConfig = () => ({ 22209 reducer: reducer_default2, 22210 actions: { 22211 ...dynamicActions, 22212 ...actions_exports, 22213 ...entityActions, 22214 ...createLocksActions() 22215 }, 22216 selectors: { 22217 ...dynamicSelectors, 22218 ...selectors_exports, 22219 ...entitySelectors 22220 }, 22221 resolvers: { ...resolvers_exports, ...entityResolvers } 22222 }); 22223 var store = (0, import_data21.createReduxStore)(STORE_NAME, storeConfig()); 22224 unlock(store).registerPrivateSelectors(private_selectors_exports); 22225 unlock(store).registerPrivateActions(private_actions_exports); 22226 (0, import_data21.register)(store); 22227 return __toCommonJS(index_exports); 22228 })(); 22229 (window.wp ||= {}).coreData = wp.coreData; 22230 })();
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Mon Nov 30 08:20:01 2026 | Cross-referenced by PHPXref |