1(function() { 2"use strict"; 3var 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
vendor: 3,239 bytes, lines 43-134
43// node_modules/fast-deep-equal/es6/index.js 44 var require_es6 = __commonJS({ 45 "node_modules/fast-deep-equal/es6/index.js"(exports, module) { 46 "use strict"; 47 module.exports = function equal(a, b) { 48 if (a === b) return true; 49 if (a && b && typeof a == "object" && typeof b == "object") { 50 if (a.constructor !== b.constructor) return false; 51 var 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/private-apis 121 var require_private_apis = __commonJS({ 122 "package-external:@wordpress/private-apis"(exports, module) { 123 module.exports = window.wp.privateApis; 124 } 125 }); 126 127 // package-external:@wordpress/hooks 128 var require_hooks = __commonJS({ 129 "package-external:@wordpress/hooks"(exports, module) { 130 module.exports = window.wp.hooks; 131 } 132 }); 133 134
vendor: 9,722 bytes, lines 134-417
134// node_modules/equivalent-key-map/equivalent-key-map.js 135 var require_equivalent_key_map = __commonJS({ 136 "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) { 137 "use strict"; 138 function _typeof(obj) { 139 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { 140 _typeof = function(obj2) { 141 return typeof obj2; 142 }; 143 } else { 144 _typeof = function(obj2) { 145 return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; 146 }; 147 } 148 return _typeof(obj); 149 } 150 function _classCallCheck(instance, Constructor) { 151 if (!(instance instanceof Constructor)) { 152 throw new TypeError("Cannot call a class as a function"); 153 } 154 } 155 function _defineProperties(target, props) { 156 for (var i = 0; i < props.length; i++) { 157 var descriptor = props[i]; 158 descriptor.enumerable = descriptor.enumerable || false; 159 descriptor.configurable = true; 160 if ("value" in descriptor) descriptor.writable = true; 161 Object.defineProperty(target, descriptor.key, descriptor); 162 } 163 } 164 function _createClass(Constructor, protoProps, staticProps) { 165 if (protoProps) _defineProperties(Constructor.prototype, protoProps); 166 if (staticProps) _defineProperties(Constructor, staticProps); 167 return Constructor; 168 } 169 function getValuePair(instance, key) { 170 var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap; 171 if (_map.has(key)) { 172 return _map.get(key); 173 } 174 var properties = Object.keys(key).sort(); 175 var map2 = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap; 176 for (var i = 0; i < properties.length; i++) { 177 var property = properties[i]; 178 map2 = map2.get(property); 179 if (map2 === void 0) { 180 return; 181 } 182 var propertyValue = key[property]; 183 map2 = map2.get(propertyValue); 184 if (map2 === void 0) { 185 return; 186 } 187 } 188 var valuePair = map2.get("_ekm_value"); 189 if (!valuePair) { 190 return; 191 } 192 _map.delete(valuePair[0]); 193 valuePair[0] = key; 194 map2.set("_ekm_value", valuePair); 195 _map.set(key, valuePair); 196 return valuePair; 197 } 198 var EquivalentKeyMap2 = /* @__PURE__ */ (function() { 199 function EquivalentKeyMap3(iterable) { 200 _classCallCheck(this, EquivalentKeyMap3); 201 this.clear(); 202 if (iterable instanceof EquivalentKeyMap3) { 203 var iterablePairs = []; 204 iterable.forEach(function(value, key) { 205 iterablePairs.push([key, value]); 206 }); 207 iterable = iterablePairs; 208 } 209 if (iterable != null) { 210 for (var i = 0; i < iterable.length; i++) { 211 this.set(iterable[i][0], iterable[i][1]); 212 } 213 } 214 } 215 _createClass(EquivalentKeyMap3, [{ 216 key: "set", 217 /** 218 * Add or update an element with a specified key and value. 219 * 220 * @param {*} key The key of the element to add. 221 * @param {*} value The value of the element to add. 222 * 223 * @return {EquivalentKeyMap} Map instance. 224 */ 225 value: function set(key, value) { 226 if (key === null || _typeof(key) !== "object") { 227 this._map.set(key, value); 228 return this; 229 } 230 var properties = Object.keys(key).sort(); 231 var valuePair = [key, value]; 232 var map2 = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap; 233 for (var i = 0; i < properties.length; i++) { 234 var property = properties[i]; 235 if (!map2.has(property)) { 236 map2.set(property, new EquivalentKeyMap3()); 237 } 238 map2 = map2.get(property); 239 var propertyValue = key[property]; 240 if (!map2.has(propertyValue)) { 241 map2.set(propertyValue, new EquivalentKeyMap3()); 242 } 243 map2 = map2.get(propertyValue); 244 } 245 var previousValuePair = map2.get("_ekm_value"); 246 if (previousValuePair) { 247 this._map.delete(previousValuePair[0]); 248 } 249 map2.set("_ekm_value", valuePair); 250 this._map.set(key, valuePair); 251 return this; 252 } 253 /** 254 * Returns a specified element. 255 * 256 * @param {*} key The key of the element to return. 257 * 258 * @return {?*} The element associated with the specified key or undefined 259 * if the key can't be found. 260 */ 261 }, { 262 key: "get", 263 value: function get(key) { 264 if (key === null || _typeof(key) !== "object") { 265 return this._map.get(key); 266 } 267 var valuePair = getValuePair(this, key); 268 if (valuePair) { 269 return valuePair[1]; 270 } 271 } 272 /** 273 * Returns a boolean indicating whether an element with the specified key 274 * exists or not. 275 * 276 * @param {*} key The key of the element to test for presence. 277 * 278 * @return {boolean} Whether an element with the specified key exists. 279 */ 280 }, { 281 key: "has", 282 value: function has(key) { 283 if (key === null || _typeof(key) !== "object") { 284 return this._map.has(key); 285 } 286 return getValuePair(this, key) !== void 0; 287 } 288 /** 289 * Removes the specified element. 290 * 291 * @param {*} key The key of the element to remove. 292 * 293 * @return {boolean} Returns true if an element existed and has been 294 * removed, or false if the element does not exist. 295 */ 296 }, { 297 key: "delete", 298 value: function _delete(key) { 299 if (!this.has(key)) { 300 return false; 301 } 302 this.set(key, void 0); 303 return true; 304 } 305 /** 306 * Executes a provided function once per each key/value pair, in insertion 307 * order. 308 * 309 * @param {Function} callback Function to execute for each element. 310 * @param {*} thisArg Value to use as `this` when executing 311 * `callback`. 312 */ 313 }, { 314 key: "forEach", 315 value: function forEach2(callback) { 316 var _this = this; 317 var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this; 318 this._map.forEach(function(value, key) { 319 if (key !== null && _typeof(key) === "object") { 320 value = value[1]; 321 } 322 callback.call(thisArg, value, key, _this); 323 }); 324 } 325 /** 326 * Removes all elements. 327 */ 328 }, { 329 key: "clear", 330 value: function clear() { 331 this._map = /* @__PURE__ */ new Map(); 332 this._arrayTreeMap = /* @__PURE__ */ new Map(); 333 this._objectTreeMap = /* @__PURE__ */ new Map(); 334 } 335 }, { 336 key: "size", 337 get: function get() { 338 return this._map.size; 339 } 340 }]); 341 return EquivalentKeyMap3; 342 })(); 343 module.exports = EquivalentKeyMap2; 344 } 345 }); 346 347 // package-external:@wordpress/url 348 var require_url = __commonJS({ 349 "package-external:@wordpress/url"(exports, module) { 350 module.exports = window.wp.url; 351 } 352 }); 353 354 // package-external:@wordpress/blocks 355 var require_blocks = __commonJS({ 356 "package-external:@wordpress/blocks"(exports, module) { 357 module.exports = window.wp.blocks; 358 } 359 }); 360 361 // package-external:@wordpress/i18n 362 var require_i18n = __commonJS({ 363 "package-external:@wordpress/i18n"(exports, module) { 364 module.exports = window.wp.i18n; 365 } 366 }); 367 368 // package-external:@wordpress/block-editor 369 var require_block_editor = __commonJS({ 370 "package-external:@wordpress/block-editor"(exports, module) { 371 module.exports = window.wp.blockEditor; 372 } 373 }); 374 375 // package-external:@wordpress/rich-text 376 var require_rich_text = __commonJS({ 377 "package-external:@wordpress/rich-text"(exports, module) { 378 module.exports = window.wp.richText; 379 } 380 }); 381 382 // package-external:@wordpress/deprecated 383 var require_deprecated = __commonJS({ 384 "package-external:@wordpress/deprecated"(exports, module) { 385 module.exports = window.wp.deprecated; 386 } 387 }); 388 389 // package-external:@wordpress/html-entities 390 var require_html_entities = __commonJS({ 391 "package-external:@wordpress/html-entities"(exports, module) { 392 module.exports = window.wp.htmlEntities; 393 } 394 }); 395 396 // package-external:@wordpress/element 397 var require_element = __commonJS({ 398 "package-external:@wordpress/element"(exports, module) { 399 module.exports = window.wp.element; 400 } 401 }); 402 403 // vendor-external:react/jsx-runtime 404 var require_jsx_runtime = __commonJS({ 405 "vendor-external:react/jsx-runtime"(exports, module) { 406 module.exports = window.ReactJSXRuntime; 407 } 408 }); 409 410 // package-external:@wordpress/warning 411 var require_warning = __commonJS({ 412 "package-external:@wordpress/warning"(exports, module) { 413 module.exports = window.wp.warning; 414 } 415 }); 416 417
417// packages/core-data/build-module/index.mjs 418 var index_exports = {}; 419 __export(index_exports, { 420 EntityProvider: () => EntityProvider, 421 __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions, 422 __experimentalFetchUrlData: () => experimental_fetch_url_data_default, 423 __experimentalUseEntityRecord: () => useDeprecatedEntityRecord, 424 __experimentalUseEntityRecords: () => useDeprecatedEntityRecords, 425 __experimentalUseResourcePermissions: () => useDeprecatedResourcePermissions, 426 fetchBlockPatterns: () => fetchBlockPatterns, 427 privateApis: () => privateApis2, 428 store: () => store, 429 useEntityBlockEditor: () => useEntityBlockEditor, 430 useEntityId: () => useEntityId, 431 useEntityProp: () => useEntityProp, 432 useEntityRecord: () => useEntityRecord, 433 useEntityRecords: () => useEntityRecords, 434 useResourcePermissions: () => use_resource_permissions_default 435 }); 436 var import_data15 = __toESM(require_data(), 1); 437 438
438// packages/core-data/build-module/reducer.mjs 439 var import_es67 = __toESM(require_es6(), 1); 440 var import_compose2 = __toESM(require_compose(), 1); 441 var import_data7 = __toESM(require_data(), 1); 442 var import_undo_manager2 = __toESM(require_undo_manager(), 1); 443 444
444// packages/core-data/build-module/utils/clear-unchanged-edits.mjs 445 var import_es6 = __toESM(require_es6(), 1); 446 function clearUnchangedEdits(edits, persistedRecord) { 447 if (!persistedRecord) { 448 return edits; 449 } 450 return Object.fromEntries( 451 Object.entries(edits).map(([key, value]) => { 452 const persisted = persistedRecord[key]?.raw ?? persistedRecord[key]; 453 return [ 454 key, 455 (0, import_es6.default)(value, persisted) ? void 0 : value 456 ]; 457 }) 458 ); 459 } 460 461
461// packages/core-data/build-module/utils/conservative-map-item.mjs 462 var import_es62 = __toESM(require_es6(), 1); 463 function conservativeMapItem(item, nextItem) { 464 if (!item) { 465 return nextItem; 466 } 467 let hasChanges = false; 468 const result = {}; 469 for (const key in nextItem) { 470 if ((0, import_es62.default)(item[key], nextItem[key])) { 471 result[key] = item[key]; 472 } else { 473 hasChanges = true; 474 result[key] = nextItem[key]; 475 } 476 } 477 if (!hasChanges) { 478 return item; 479 } 480 for (const key in item) { 481 if (!result.hasOwnProperty(key)) { 482 result[key] = item[key]; 483 } 484 } 485 return result; 486 } 487 488
488// packages/core-data/build-module/utils/get-normalized-comma-separable.mjs 489 function getNormalizedCommaSeparable(value) { 490 if (typeof value === "string") { 491 return value.split(","); 492 } else if (Array.isArray(value)) { 493 return value; 494 } 495 return null; 496 } 497 var get_normalized_comma_separable_default = getNormalizedCommaSeparable; 498 499
499// packages/core-data/build-module/utils/if-matching-action.mjs 500 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => { 501 if (state === void 0 || isMatch(action)) { 502 return reducer(state, action); 503 } 504 return state; 505 }; 506 var if_matching_action_default = ifMatchingAction; 507 508
508// packages/core-data/build-module/utils/forward-resolver.mjs 509 var forwardResolver = (resolverName) => (...args2) => async ({ resolveSelect: resolveSelect2 }) => { 510 await resolveSelect2[resolverName](...args2); 511 }; 512 var forward_resolver_default = forwardResolver; 513 514
514// packages/core-data/build-module/utils/replace-action.mjs 515 var replaceAction = (replacer) => (reducer) => (state, action) => { 516 return reducer(state, replacer(action)); 517 }; 518 var replace_action_default = replaceAction; 519 520
520// packages/core-data/build-module/utils/with-weak-map-cache.mjs 521 function withWeakMapCache(fn) { 522 const cache3 = /* @__PURE__ */ new WeakMap(); 523 return (key) => { 524 let value; 525 if (cache3.has(key)) { 526 value = cache3.get(key); 527 } else { 528 value = fn(key); 529 if (key !== null && typeof key === "object") { 530 cache3.set(key, value); 531 } 532 } 533 return value; 534 }; 535 } 536 var with_weak_map_cache_default = withWeakMapCache; 537 538
538// packages/core-data/build-module/utils/set-nested-value.mjs 539 function setNestedValue(object, path, value) { 540 if (!object || typeof object !== "object") { 541 return object; 542 } 543 const normalizedPath = Array.isArray(path) ? path : path.split("."); 544 normalizedPath.reduce((acc, key, idx) => { 545 if (acc[key] === void 0) { 546 if (Number.isInteger(normalizedPath[idx + 1])) { 547 acc[key] = []; 548 } else { 549 acc[key] = {}; 550 } 551 } 552 if (idx === normalizedPath.length - 1) { 553 acc[key] = value; 554 } 555 return acc[key]; 556 }, object); 557 return object; 558 } 559 560
560// packages/core-data/build-module/utils/get-nested-value.mjs 561 function getNestedValue(object, path, defaultValue) { 562 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) { 563 return object; 564 } 565 const normalizedPath = Array.isArray(path) ? path : path.split("."); 566 let value = object; 567 normalizedPath.forEach((fieldName) => { 568 value = value?.[fieldName]; 569 }); 570 return value !== void 0 ? value : defaultValue; 571 } 572 573
573// packages/core-data/build-module/utils/is-numeric-id.mjs 574 function isNumericID(id2) { 575 return /^\s*\d+\s*$/.test(id2); 576 } 577 578
578// packages/core-data/build-module/utils/user-permissions.mjs 579 var ALLOWED_RESOURCE_ACTIONS = [ 580 "create", 581 "read", 582 "update", 583 "delete" 584 ]; 585 function getUserPermissionsFromAllowHeader(allowedMethods) { 586 const permissions = {}; 587 const methods = { 588 create: "POST", 589 read: "GET", 590 update: "PUT", 591 delete: "DELETE" 592 }; 593 for (const [actionName, methodName] of Object.entries(methods)) { 594 permissions[actionName] = allowedMethods ? allowedMethods.includes(methodName) : false; 595 } 596 return permissions; 597 } 598 function getUserPermissionCacheKey(action, resource, id2) { 599 const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id2]).filter(Boolean).join("/"); 600 return key; 601 } 602 603
603// packages/core-data/build-module/utils/receive-intermediate-results.mjs 604 var RECEIVE_INTERMEDIATE_RESULTS = /* @__PURE__ */ Symbol( 605 "RECEIVE_INTERMEDIATE_RESULTS" 606 ); 607 608
608// packages/core-data/build-module/utils/normalize-query-for-resolution.mjs 609 function normalizeQueryForResolution(query) { 610 if (!query) { 611 return void 0; 612 } 613 const entries = Object.entries(query).filter( 614 ([k, v]) => (k === "context" || k === "_fields") && v !== void 0 && v !== null 615 ); 616 return entries.length > 0 ? Object.fromEntries(entries) : void 0; 617 } 618 619
619// packages/core-data/build-module/utils/save-crdt-doc.mjs 620 var import_api_fetch2 = __toESM(require_api_fetch(), 1); 621 622
vendor: 4,448 bytes, lines 622-730
622// node_modules/yjs/dist/yjs.mjs 623 var yjs_exports = {}; 624 __export(yjs_exports, { 625 AbsolutePosition: () => AbsolutePosition, 626 AbstractConnector: () => AbstractConnector, 627 AbstractStruct: () => AbstractStruct, 628 AbstractType: () => AbstractType, 629 Array: () => YArray, 630 ContentAny: () => ContentAny, 631 ContentBinary: () => ContentBinary, 632 ContentDeleted: () => ContentDeleted, 633 ContentDoc: () => ContentDoc, 634 ContentEmbed: () => ContentEmbed, 635 ContentFormat: () => ContentFormat, 636 ContentJSON: () => ContentJSON, 637 ContentString: () => ContentString, 638 ContentType: () => ContentType, 639 Doc: () => Doc, 640 GC: () => GC, 641 ID: () => ID, 642 Item: () => Item, 643 Map: () => YMap, 644 PermanentUserData: () => PermanentUserData, 645 RelativePosition: () => RelativePosition, 646 Skip: () => Skip, 647 Snapshot: () => Snapshot, 648 Text: () => YText, 649 Transaction: () => Transaction, 650 UndoManager: () => UndoManager, 651 UpdateDecoderV1: () => UpdateDecoderV1, 652 UpdateDecoderV2: () => UpdateDecoderV2, 653 UpdateEncoderV1: () => UpdateEncoderV1, 654 UpdateEncoderV2: () => UpdateEncoderV2, 655 XmlElement: () => YXmlElement, 656 XmlFragment: () => YXmlFragment, 657 XmlHook: () => YXmlHook, 658 XmlText: () => YXmlText, 659 YArrayEvent: () => YArrayEvent, 660 YEvent: () => YEvent, 661 YMapEvent: () => YMapEvent, 662 YTextEvent: () => YTextEvent, 663 YXmlEvent: () => YXmlEvent, 664 applyUpdate: () => applyUpdate, 665 applyUpdateV2: () => applyUpdateV2, 666 cleanupYTextFormatting: () => cleanupYTextFormatting, 667 compareIDs: () => compareIDs, 668 compareRelativePositions: () => compareRelativePositions, 669 convertUpdateFormatV1ToV2: () => convertUpdateFormatV1ToV2, 670 convertUpdateFormatV2ToV1: () => convertUpdateFormatV2ToV1, 671 createAbsolutePositionFromRelativePosition: () => createAbsolutePositionFromRelativePosition, 672 createDeleteSet: () => createDeleteSet, 673 createDeleteSetFromStructStore: () => createDeleteSetFromStructStore, 674 createDocFromSnapshot: () => createDocFromSnapshot, 675 createID: () => createID, 676 createRelativePositionFromJSON: () => createRelativePositionFromJSON, 677 createRelativePositionFromTypeIndex: () => createRelativePositionFromTypeIndex, 678 createSnapshot: () => createSnapshot, 679 decodeRelativePosition: () => decodeRelativePosition, 680 decodeSnapshot: () => decodeSnapshot, 681 decodeSnapshotV2: () => decodeSnapshotV2, 682 decodeStateVector: () => decodeStateVector, 683 decodeUpdate: () => decodeUpdate, 684 decodeUpdateV2: () => decodeUpdateV2, 685 diffUpdate: () => diffUpdate, 686 diffUpdateV2: () => diffUpdateV2, 687 emptySnapshot: () => emptySnapshot, 688 encodeRelativePosition: () => encodeRelativePosition, 689 encodeSnapshot: () => encodeSnapshot, 690 encodeSnapshotV2: () => encodeSnapshotV2, 691 encodeStateAsUpdate: () => encodeStateAsUpdate, 692 encodeStateAsUpdateV2: () => encodeStateAsUpdateV2, 693 encodeStateVector: () => encodeStateVector, 694 encodeStateVectorFromUpdate: () => encodeStateVectorFromUpdate, 695 encodeStateVectorFromUpdateV2: () => encodeStateVectorFromUpdateV2, 696 equalDeleteSets: () => equalDeleteSets, 697 equalSnapshots: () => equalSnapshots, 698 findIndexSS: () => findIndexSS, 699 findRootTypeKey: () => findRootTypeKey, 700 getItem: () => getItem, 701 getItemCleanEnd: () => getItemCleanEnd, 702 getItemCleanStart: () => getItemCleanStart, 703 getState: () => getState, 704 getTypeChildren: () => getTypeChildren, 705 isDeleted: () => isDeleted, 706 isParentOf: () => isParentOf, 707 iterateDeletedStructs: () => iterateDeletedStructs, 708 logType: () => logType, 709 logUpdate: () => logUpdate, 710 logUpdateV2: () => logUpdateV2, 711 mergeDeleteSets: () => mergeDeleteSets, 712 mergeUpdates: () => mergeUpdates, 713 mergeUpdatesV2: () => mergeUpdatesV2, 714 obfuscateUpdate: () => obfuscateUpdate, 715 obfuscateUpdateV2: () => obfuscateUpdateV2, 716 parseUpdateMeta: () => parseUpdateMeta, 717 parseUpdateMetaV2: () => parseUpdateMetaV2, 718 readUpdate: () => readUpdate, 719 readUpdateV2: () => readUpdateV2, 720 relativePositionToJSON: () => relativePositionToJSON, 721 snapshot: () => snapshot, 722 snapshotContainsUpdate: () => snapshotContainsUpdate, 723 transact: () => transact, 724 tryGc: () => tryGc, 725 typeListToArraySnapshot: () => typeListToArraySnapshot, 726 typeMapGetAllSnapshot: () => typeMapGetAllSnapshot, 727 typeMapGetSnapshot: () => typeMapGetSnapshot 728 }); 729 730
vendor: 649 bytes, lines 730-762
730// node_modules/lib0/map.js 731 var create = () => /* @__PURE__ */ new Map(); 732 var copy = (m) => { 733 const r = create(); 734 m.forEach((v, k) => { 735 r.set(k, v); 736 }); 737 return r; 738 }; 739 var setIfUndefined = (map2, key, createT) => { 740 let set = map2.get(key); 741 if (set === void 0) { 742 map2.set(key, set = createT()); 743 } 744 return set; 745 }; 746 var map = (m, f) => { 747 const res = []; 748 for (const [key, value] of m) { 749 res.push(f(value, key)); 750 } 751 return res; 752 }; 753 var any = (m, f) => { 754 for (const [key, value] of m) { 755 if (f(value, key)) { 756 return true; 757 } 758 } 759 return false; 760 }; 761 762
vendor: 80 bytes, lines 762-765
762// node_modules/lib0/set.js 763 var create2 = () => /* @__PURE__ */ new Set(); 764 765
vendor: 723 bytes, lines 765-798
765// node_modules/lib0/array.js 766 var last = (arr) => arr[arr.length - 1]; 767 var appendTo = (dest, src) => { 768 for (let i = 0; i < src.length; i++) { 769 dest.push(src[i]); 770 } 771 }; 772 var from = Array.from; 773 var every = (arr, f) => { 774 for (let i = 0; i < arr.length; i++) { 775 if (!f(arr[i], i, arr)) { 776 return false; 777 } 778 } 779 return true; 780 }; 781 var some = (arr, f) => { 782 for (let i = 0; i < arr.length; i++) { 783 if (f(arr[i], i, arr)) { 784 return true; 785 } 786 } 787 return false; 788 }; 789 var unfold = (len, f) => { 790 const array = new Array(len); 791 for (let i = 0; i < len; i++) { 792 array[i] = f(i, array); 793 } 794 return array; 795 }; 796 var isArray = Array.isArray; 797 798
vendor: 2,956 bytes, lines 798-920
798// node_modules/lib0/observable.js 799 var ObservableV2 = class { 800 constructor() { 801 this._observers = create(); 802 } 803 /** 804 * @template {keyof EVENTS & string} NAME 805 * @param {NAME} name 806 * @param {EVENTS[NAME]} f 807 */ 808 on(name, f) { 809 setIfUndefined( 810 this._observers, 811 /** @type {string} */ 812 name, 813 create2 814 ).add(f); 815 return f; 816 } 817 /** 818 * @template {keyof EVENTS & string} NAME 819 * @param {NAME} name 820 * @param {EVENTS[NAME]} f 821 */ 822 once(name, f) { 823 const _f = (...args2) => { 824 this.off( 825 name, 826 /** @type {any} */ 827 _f 828 ); 829 f(...args2); 830 }; 831 this.on( 832 name, 833 /** @type {any} */ 834 _f 835 ); 836 } 837 /** 838 * @template {keyof EVENTS & string} NAME 839 * @param {NAME} name 840 * @param {EVENTS[NAME]} f 841 */ 842 off(name, f) { 843 const observers = this._observers.get(name); 844 if (observers !== void 0) { 845 observers.delete(f); 846 if (observers.size === 0) { 847 this._observers.delete(name); 848 } 849 } 850 } 851 /** 852 * Emit a named event. All registered event listeners that listen to the 853 * specified name will receive the event. 854 * 855 * @todo This should catch exceptions 856 * 857 * @template {keyof EVENTS & string} NAME 858 * @param {NAME} name The event name. 859 * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener. 860 */ 861 emit(name, args2) { 862 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2)); 863 } 864 destroy() { 865 this._observers = create(); 866 } 867 }; 868 var Observable = class { 869 constructor() { 870 this._observers = create(); 871 } 872 /** 873 * @param {N} name 874 * @param {function} f 875 */ 876 on(name, f) { 877 setIfUndefined(this._observers, name, create2).add(f); 878 } 879 /** 880 * @param {N} name 881 * @param {function} f 882 */ 883 once(name, f) { 884 const _f = (...args2) => { 885 this.off(name, _f); 886 f(...args2); 887 }; 888 this.on(name, _f); 889 } 890 /** 891 * @param {N} name 892 * @param {function} f 893 */ 894 off(name, f) { 895 const observers = this._observers.get(name); 896 if (observers !== void 0) { 897 observers.delete(f); 898 if (observers.size === 0) { 899 this._observers.delete(name); 900 } 901 } 902 } 903 /** 904 * Emit a named event. All registered event listeners that listen to the 905 * specified name will receive the event. 906 * 907 * @todo This should catch exceptions 908 * 909 * @param {N} name The event name. 910 * @param {Array<any>} args The arguments that are applied to the event listener. 911 */ 912 emit(name, args2) { 913 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2)); 914 } 915 destroy() { 916 this._observers = create(); 917 } 918 }; 919 920
vendor: 242 bytes, lines 920-928
920// node_modules/lib0/math.js 921 var floor = Math.floor; 922 var abs = Math.abs; 923 var min = (a, b) => a < b ? a : b; 924 var max = (a, b) => a > b ? a : b; 925 var isNaN2 = Number.isNaN; 926 var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0; 927 928
vendor: 941 bytes, lines 928-970
928// node_modules/lib0/binary.js 929 var BIT1 = 1; 930 var BIT2 = 2; 931 var BIT3 = 4; 932 var BIT4 = 8; 933 var BIT6 = 32; 934 var BIT7 = 64; 935 var BIT8 = 128; 936 var BIT18 = 1 << 17; 937 var BIT19 = 1 << 18; 938 var BIT20 = 1 << 19; 939 var BIT21 = 1 << 20; 940 var BIT22 = 1 << 21; 941 var BIT23 = 1 << 22; 942 var BIT24 = 1 << 23; 943 var BIT25 = 1 << 24; 944 var BIT26 = 1 << 25; 945 var BIT27 = 1 << 26; 946 var BIT28 = 1 << 27; 947 var BIT29 = 1 << 28; 948 var BIT30 = 1 << 29; 949 var BIT31 = 1 << 30; 950 var BIT32 = 1 << 31; 951 var BITS5 = 31; 952 var BITS6 = 63; 953 var BITS7 = 127; 954 var BITS17 = BIT18 - 1; 955 var BITS18 = BIT19 - 1; 956 var BITS19 = BIT20 - 1; 957 var BITS20 = BIT21 - 1; 958 var BITS21 = BIT22 - 1; 959 var BITS22 = BIT23 - 1; 960 var BITS23 = BIT24 - 1; 961 var BITS24 = BIT25 - 1; 962 var BITS25 = BIT26 - 1; 963 var BITS26 = BIT27 - 1; 964 var BITS27 = BIT28 - 1; 965 var BITS28 = BIT29 - 1; 966 var BITS29 = BIT30 - 1; 967 var BITS30 = BIT31 - 1; 968 var BITS31 = 2147483647; 969 970
vendor: 341 bytes, lines 970-978
970// node_modules/lib0/number.js 971 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; 972 var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; 973 var LOWEST_INT32 = 1 << 31; 974 var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num); 975 var isNaN3 = Number.isNaN; 976 var parseInt2 = Number.parseInt; 977 978
vendor: 1,355 bytes, lines 978-1009
978// node_modules/lib0/string.js 979 var fromCharCode = String.fromCharCode; 980 var fromCodePoint = String.fromCodePoint; 981 var MAX_UTF16_CHARACTER = fromCharCode(65535); 982 var toLowerCase = (s) => s.toLowerCase(); 983 var trimLeftRegex = /^\s*/g; 984 var trimLeft = (s) => s.replace(trimLeftRegex, ""); 985 var fromCamelCaseRegex = /([A-Z])/g; 986 var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match2) => `${separator}${toLowerCase(match2)}`)); 987 var _encodeUtf8Polyfill = (str) => { 988 const encodedString = unescape(encodeURIComponent(str)); 989 const len = encodedString.length; 990 const buf = new Uint8Array(len); 991 for (let i = 0; i < len; i++) { 992 buf[i] = /** @type {number} */ 993 encodedString.codePointAt(i); 994 } 995 return buf; 996 }; 997 var utf8TextEncoder = ( 998 /** @type {TextEncoder} */ 999 typeof TextEncoder !== "undefined" ? new TextEncoder() : null 1000 ); 1001 var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str); 1002 var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; 1003 var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); 1004 if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { 1005 utf8TextDecoder = null; 1006 } 1007 var repeat = (source, n) => unfold(n, () => source).join(""); 1008 1009
vendor: 8,910 bytes, lines 1009-1317
1009// node_modules/lib0/encoding.js 1010 var Encoder = class { 1011 constructor() { 1012 this.cpos = 0; 1013 this.cbuf = new Uint8Array(100); 1014 this.bufs = []; 1015 } 1016 }; 1017 var createEncoder = () => new Encoder(); 1018 var length = (encoder) => { 1019 let len = encoder.cpos; 1020 for (let i = 0; i < encoder.bufs.length; i++) { 1021 len += encoder.bufs[i].length; 1022 } 1023 return len; 1024 }; 1025 var toUint8Array = (encoder) => { 1026 const uint8arr = new Uint8Array(length(encoder)); 1027 let curPos = 0; 1028 for (let i = 0; i < encoder.bufs.length; i++) { 1029 const d = encoder.bufs[i]; 1030 uint8arr.set(d, curPos); 1031 curPos += d.length; 1032 } 1033 uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos); 1034 return uint8arr; 1035 }; 1036 var verifyLen = (encoder, len) => { 1037 const bufferLen = encoder.cbuf.length; 1038 if (bufferLen - encoder.cpos < len) { 1039 encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos)); 1040 encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); 1041 encoder.cpos = 0; 1042 } 1043 }; 1044 var write = (encoder, num) => { 1045 const bufferLen = encoder.cbuf.length; 1046 if (encoder.cpos === bufferLen) { 1047 encoder.bufs.push(encoder.cbuf); 1048 encoder.cbuf = new Uint8Array(bufferLen * 2); 1049 encoder.cpos = 0; 1050 } 1051 encoder.cbuf[encoder.cpos++] = num; 1052 }; 1053 var writeUint8 = write; 1054 var writeVarUint = (encoder, num) => { 1055 while (num > BITS7) { 1056 write(encoder, BIT8 | BITS7 & num); 1057 num = floor(num / 128); 1058 } 1059 write(encoder, BITS7 & num); 1060 }; 1061 var writeVarInt = (encoder, num) => { 1062 const isNegative = isNegativeZero(num); 1063 if (isNegative) { 1064 num = -num; 1065 } 1066 write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num); 1067 num = floor(num / 64); 1068 while (num > 0) { 1069 write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num); 1070 num = floor(num / 128); 1071 } 1072 }; 1073 var _strBuffer = new Uint8Array(3e4); 1074 var _maxStrBSize = _strBuffer.length / 3; 1075 var _writeVarStringNative = (encoder, str) => { 1076 if (str.length < _maxStrBSize) { 1077 const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; 1078 writeVarUint(encoder, written); 1079 for (let i = 0; i < written; i++) { 1080 write(encoder, _strBuffer[i]); 1081 } 1082 } else { 1083 writeVarUint8Array(encoder, encodeUtf8(str)); 1084 } 1085 }; 1086 var _writeVarStringPolyfill = (encoder, str) => { 1087 const encodedString = unescape(encodeURIComponent(str)); 1088 const len = encodedString.length; 1089 writeVarUint(encoder, len); 1090 for (let i = 0; i < len; i++) { 1091 write( 1092 encoder, 1093 /** @type {number} */ 1094 encodedString.codePointAt(i) 1095 ); 1096 } 1097 }; 1098 var writeVarString = utf8TextEncoder && /** @type {any} */ 1099 utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill; 1100 var writeBinaryEncoder = (encoder, append2) => writeUint8Array(encoder, toUint8Array(append2)); 1101 var writeUint8Array = (encoder, uint8Array) => { 1102 const bufferLen = encoder.cbuf.length; 1103 const cpos = encoder.cpos; 1104 const leftCopyLen = min(bufferLen - cpos, uint8Array.length); 1105 const rightCopyLen = uint8Array.length - leftCopyLen; 1106 encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); 1107 encoder.cpos += leftCopyLen; 1108 if (rightCopyLen > 0) { 1109 encoder.bufs.push(encoder.cbuf); 1110 encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); 1111 encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); 1112 encoder.cpos = rightCopyLen; 1113 } 1114 }; 1115 var writeVarUint8Array = (encoder, uint8Array) => { 1116 writeVarUint(encoder, uint8Array.byteLength); 1117 writeUint8Array(encoder, uint8Array); 1118 }; 1119 var writeOnDataView = (encoder, len) => { 1120 verifyLen(encoder, len); 1121 const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); 1122 encoder.cpos += len; 1123 return dview; 1124 }; 1125 var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); 1126 var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); 1127 var writeBigInt64 = (encoder, num) => ( 1128 /** @type {any} */ 1129 writeOnDataView(encoder, 8).setBigInt64(0, num, false) 1130 ); 1131 var floatTestBed = new DataView(new ArrayBuffer(4)); 1132 var isFloat32 = (num) => { 1133 floatTestBed.setFloat32(0, num); 1134 return floatTestBed.getFloat32(0) === num; 1135 }; 1136 var writeAny = (encoder, data) => { 1137 switch (typeof data) { 1138 case "string": 1139 write(encoder, 119); 1140 writeVarString(encoder, data); 1141 break; 1142 case "number": 1143 if (isInteger(data) && abs(data) <= BITS31) { 1144 write(encoder, 125); 1145 writeVarInt(encoder, data); 1146 } else if (isFloat32(data)) { 1147 write(encoder, 124); 1148 writeFloat32(encoder, data); 1149 } else { 1150 write(encoder, 123); 1151 writeFloat64(encoder, data); 1152 } 1153 break; 1154 case "bigint": 1155 write(encoder, 122); 1156 writeBigInt64(encoder, data); 1157 break; 1158 case "object": 1159 if (data === null) { 1160 write(encoder, 126); 1161 } else if (isArray(data)) { 1162 write(encoder, 117); 1163 writeVarUint(encoder, data.length); 1164 for (let i = 0; i < data.length; i++) { 1165 writeAny(encoder, data[i]); 1166 } 1167 } else if (data instanceof Uint8Array) { 1168 write(encoder, 116); 1169 writeVarUint8Array(encoder, data); 1170 } else { 1171 write(encoder, 118); 1172 const keys2 = Object.keys(data); 1173 writeVarUint(encoder, keys2.length); 1174 for (let i = 0; i < keys2.length; i++) { 1175 const key = keys2[i]; 1176 writeVarString(encoder, key); 1177 writeAny(encoder, data[key]); 1178 } 1179 } 1180 break; 1181 case "boolean": 1182 write(encoder, data ? 120 : 121); 1183 break; 1184 default: 1185 write(encoder, 127); 1186 } 1187 }; 1188 var RleEncoder = class extends Encoder { 1189 /** 1190 * @param {function(Encoder, T):void} writer 1191 */ 1192 constructor(writer) { 1193 super(); 1194 this.w = writer; 1195 this.s = null; 1196 this.count = 0; 1197 } 1198 /** 1199 * @param {T} v 1200 */ 1201 write(v) { 1202 if (this.s === v) { 1203 this.count++; 1204 } else { 1205 if (this.count > 0) { 1206 writeVarUint(this, this.count - 1); 1207 } 1208 this.count = 1; 1209 this.w(this, v); 1210 this.s = v; 1211 } 1212 } 1213 }; 1214 var flushUintOptRleEncoder = (encoder) => { 1215 if (encoder.count > 0) { 1216 writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); 1217 if (encoder.count > 1) { 1218 writeVarUint(encoder.encoder, encoder.count - 2); 1219 } 1220 } 1221 }; 1222 var UintOptRleEncoder = class { 1223 constructor() { 1224 this.encoder = new Encoder(); 1225 this.s = 0; 1226 this.count = 0; 1227 } 1228 /** 1229 * @param {number} v 1230 */ 1231 write(v) { 1232 if (this.s === v) { 1233 this.count++; 1234 } else { 1235 flushUintOptRleEncoder(this); 1236 this.count = 1; 1237 this.s = v; 1238 } 1239 } 1240 /** 1241 * Flush the encoded state and transform this to a Uint8Array. 1242 * 1243 * Note that this should only be called once. 1244 */ 1245 toUint8Array() { 1246 flushUintOptRleEncoder(this); 1247 return toUint8Array(this.encoder); 1248 } 1249 }; 1250 var flushIntDiffOptRleEncoder = (encoder) => { 1251 if (encoder.count > 0) { 1252 const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); 1253 writeVarInt(encoder.encoder, encodedDiff); 1254 if (encoder.count > 1) { 1255 writeVarUint(encoder.encoder, encoder.count - 2); 1256 } 1257 } 1258 }; 1259 var IntDiffOptRleEncoder = class { 1260 constructor() { 1261 this.encoder = new Encoder(); 1262 this.s = 0; 1263 this.count = 0; 1264 this.diff = 0; 1265 } 1266 /** 1267 * @param {number} v 1268 */ 1269 write(v) { 1270 if (this.diff === v - this.s) { 1271 this.s = v; 1272 this.count++; 1273 } else { 1274 flushIntDiffOptRleEncoder(this); 1275 this.count = 1; 1276 this.diff = v - this.s; 1277 this.s = v; 1278 } 1279 } 1280 /** 1281 * Flush the encoded state and transform this to a Uint8Array. 1282 * 1283 * Note that this should only be called once. 1284 */ 1285 toUint8Array() { 1286 flushIntDiffOptRleEncoder(this); 1287 return toUint8Array(this.encoder); 1288 } 1289 }; 1290 var StringEncoder = class { 1291 constructor() { 1292 this.sarr = []; 1293 this.s = ""; 1294 this.lensE = new UintOptRleEncoder(); 1295 } 1296 /** 1297 * @param {string} string 1298 */ 1299 write(string) { 1300 this.s += string; 1301 if (this.s.length > 19) { 1302 this.sarr.push(this.s); 1303 this.s = ""; 1304 } 1305 this.lensE.write(string.length); 1306 } 1307 toUint8Array() { 1308 const encoder = new Encoder(); 1309 this.sarr.push(this.s); 1310 this.s = ""; 1311 writeVarString(encoder, this.sarr.join("")); 1312 writeUint8Array(encoder, this.lensE.toUint8Array()); 1313 return toUint8Array(encoder); 1314 } 1315 }; 1316 1317
vendor: 228 bytes, lines 1317-1326
1317// node_modules/lib0/error.js 1318 var create3 = (s) => new Error(s); 1319 var methodUnimplemented = () => { 1320 throw create3("Method unimplemented"); 1321 }; 1322 var unexpectedCase = () => { 1323 throw create3("Unexpected case"); 1324 }; 1325 1326
vendor: 6,588 bytes, lines 1326-1569
1326// node_modules/lib0/decoding.js 1327 var errorUnexpectedEndOfArray = create3("Unexpected end of array"); 1328 var errorIntegerOutOfRange = create3("Integer out of Range"); 1329 var Decoder = class { 1330 /** 1331 * @param {Uint8Array<Buf>} uint8Array Binary data to decode 1332 */ 1333 constructor(uint8Array) { 1334 this.arr = uint8Array; 1335 this.pos = 0; 1336 } 1337 }; 1338 var createDecoder = (uint8Array) => new Decoder(uint8Array); 1339 var hasContent = (decoder) => decoder.pos !== decoder.arr.length; 1340 var readUint8Array = (decoder, len) => { 1341 const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); 1342 decoder.pos += len; 1343 return view; 1344 }; 1345 var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder)); 1346 var readUint8 = (decoder) => decoder.arr[decoder.pos++]; 1347 var readVarUint = (decoder) => { 1348 let num = 0; 1349 let mult = 1; 1350 const len = decoder.arr.length; 1351 while (decoder.pos < len) { 1352 const r = decoder.arr[decoder.pos++]; 1353 num = num + (r & BITS7) * mult; 1354 mult *= 128; 1355 if (r < BIT8) { 1356 return num; 1357 } 1358 if (num > MAX_SAFE_INTEGER) { 1359 throw errorIntegerOutOfRange; 1360 } 1361 } 1362 throw errorUnexpectedEndOfArray; 1363 }; 1364 var readVarInt = (decoder) => { 1365 let r = decoder.arr[decoder.pos++]; 1366 let num = r & BITS6; 1367 let mult = 64; 1368 const sign = (r & BIT7) > 0 ? -1 : 1; 1369 if ((r & BIT8) === 0) { 1370 return sign * num; 1371 } 1372 const len = decoder.arr.length; 1373 while (decoder.pos < len) { 1374 r = decoder.arr[decoder.pos++]; 1375 num = num + (r & BITS7) * mult; 1376 mult *= 128; 1377 if (r < BIT8) { 1378 return sign * num; 1379 } 1380 if (num > MAX_SAFE_INTEGER) { 1381 throw errorIntegerOutOfRange; 1382 } 1383 } 1384 throw errorUnexpectedEndOfArray; 1385 }; 1386 var _readVarStringPolyfill = (decoder) => { 1387 let remainingLen = readVarUint(decoder); 1388 if (remainingLen === 0) { 1389 return ""; 1390 } else { 1391 let encodedString = String.fromCodePoint(readUint8(decoder)); 1392 if (--remainingLen < 100) { 1393 while (remainingLen--) { 1394 encodedString += String.fromCodePoint(readUint8(decoder)); 1395 } 1396 } else { 1397 while (remainingLen > 0) { 1398 const nextLen = remainingLen < 1e4 ? remainingLen : 1e4; 1399 const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); 1400 decoder.pos += nextLen; 1401 encodedString += String.fromCodePoint.apply( 1402 null, 1403 /** @type {any} */ 1404 bytes 1405 ); 1406 remainingLen -= nextLen; 1407 } 1408 } 1409 return decodeURIComponent(escape(encodedString)); 1410 } 1411 }; 1412 var _readVarStringNative = (decoder) => ( 1413 /** @type any */ 1414 utf8TextDecoder.decode(readVarUint8Array(decoder)) 1415 ); 1416 var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; 1417 var readFromDataView = (decoder, len) => { 1418 const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); 1419 decoder.pos += len; 1420 return dv; 1421 }; 1422 var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false); 1423 var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false); 1424 var readBigInt64 = (decoder) => ( 1425 /** @type {any} */ 1426 readFromDataView(decoder, 8).getBigInt64(0, false) 1427 ); 1428 var readAnyLookupTable = [ 1429 (decoder) => void 0, 1430 // CASE 127: undefined 1431 (decoder) => null, 1432 // CASE 126: null 1433 readVarInt, 1434 // CASE 125: integer 1435 readFloat32, 1436 // CASE 124: float32 1437 readFloat64, 1438 // CASE 123: float64 1439 readBigInt64, 1440 // CASE 122: bigint 1441 (decoder) => false, 1442 // CASE 121: boolean (false) 1443 (decoder) => true, 1444 // CASE 120: boolean (true) 1445 readVarString, 1446 // CASE 119: string 1447 (decoder) => { 1448 const len = readVarUint(decoder); 1449 const obj = {}; 1450 for (let i = 0; i < len; i++) { 1451 const key = readVarString(decoder); 1452 obj[key] = readAny(decoder); 1453 } 1454 return obj; 1455 }, 1456 (decoder) => { 1457 const len = readVarUint(decoder); 1458 const arr = []; 1459 for (let i = 0; i < len; i++) { 1460 arr.push(readAny(decoder)); 1461 } 1462 return arr; 1463 }, 1464 readVarUint8Array 1465 // CASE 116: Uint8Array 1466 ]; 1467 var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder); 1468 var RleDecoder = class extends Decoder { 1469 /** 1470 * @param {Uint8Array} uint8Array 1471 * @param {function(Decoder):T} reader 1472 */ 1473 constructor(uint8Array, reader) { 1474 super(uint8Array); 1475 this.reader = reader; 1476 this.s = null; 1477 this.count = 0; 1478 } 1479 read() { 1480 if (this.count === 0) { 1481 this.s = this.reader(this); 1482 if (hasContent(this)) { 1483 this.count = readVarUint(this) + 1; 1484 } else { 1485 this.count = -1; 1486 } 1487 } 1488 this.count--; 1489 return ( 1490 /** @type {T} */ 1491 this.s 1492 ); 1493 } 1494 }; 1495 var UintOptRleDecoder = class extends Decoder { 1496 /** 1497 * @param {Uint8Array} uint8Array 1498 */ 1499 constructor(uint8Array) { 1500 super(uint8Array); 1501 this.s = 0; 1502 this.count = 0; 1503 } 1504 read() { 1505 if (this.count === 0) { 1506 this.s = readVarInt(this); 1507 const isNegative = isNegativeZero(this.s); 1508 this.count = 1; 1509 if (isNegative) { 1510 this.s = -this.s; 1511 this.count = readVarUint(this) + 2; 1512 } 1513 } 1514 this.count--; 1515 return ( 1516 /** @type {number} */ 1517 this.s 1518 ); 1519 } 1520 }; 1521 var IntDiffOptRleDecoder = class extends Decoder { 1522 /** 1523 * @param {Uint8Array} uint8Array 1524 */ 1525 constructor(uint8Array) { 1526 super(uint8Array); 1527 this.s = 0; 1528 this.count = 0; 1529 this.diff = 0; 1530 } 1531 /** 1532 * @return {number} 1533 */ 1534 read() { 1535 if (this.count === 0) { 1536 const diff = readVarInt(this); 1537 const hasCount = diff & 1; 1538 this.diff = floor(diff / 2); 1539 this.count = 1; 1540 if (hasCount) { 1541 this.count = readVarUint(this) + 2; 1542 } 1543 } 1544 this.s += this.diff; 1545 this.count--; 1546 return this.s; 1547 } 1548 }; 1549 var StringDecoder = class { 1550 /** 1551 * @param {Uint8Array} uint8Array 1552 */ 1553 constructor(uint8Array) { 1554 this.decoder = new UintOptRleDecoder(uint8Array); 1555 this.str = readVarString(this.decoder); 1556 this.spos = 0; 1557 } 1558 /** 1559 * @return {string} 1560 */ 1561 read() { 1562 const end = this.spos + this.decoder.read(); 1563 const res = this.str.slice(this.spos, end); 1564 this.spos = end; 1565 return res; 1566 } 1567 }; 1568 1569
vendor: 128 bytes, lines 1569-1573
1569// node_modules/lib0/webcrypto.js 1570 var subtle = crypto.subtle; 1571 var getRandomValues = crypto.getRandomValues.bind(crypto); 1572 1573
vendor: 299 bytes, lines 1573-1582
1573// node_modules/lib0/random.js 1574 var uint32 = () => getRandomValues(new Uint32Array(1))[0]; 1575 var uuidv4Template = "10000000-1000-4000-8000" + -1e11; 1576 var uuidv4 = () => uuidv4Template.replace( 1577 /[018]/g, 1578 /** @param {number} c */ 1579 (c) => (c ^ uint32() & 15 >> c / 4).toString(16) 1580 ); 1581 1582
vendor: 62 bytes, lines 1582-1585
1582// node_modules/lib0/time.js 1583 var getUnixTime = Date.now; 1584 1585
vendor: 153 bytes, lines 1585-1592
1585// node_modules/lib0/promise.js 1586 var create4 = (f) => ( 1587 /** @type {Promise<T>} */ 1588 new Promise(f) 1589 ); 1590 var all = Promise.all.bind(Promise); 1591 1592
vendor: 94 bytes, lines 1592-1595
1592// node_modules/lib0/conditions.js 1593 var undefinedToNull = (v) => v === void 0 ? null : v; 1594 1595
vendor: 655 bytes, lines 1595-1625
1595// node_modules/lib0/storage.js 1596 var VarStoragePolyfill = class { 1597 constructor() { 1598 this.map = /* @__PURE__ */ new Map(); 1599 } 1600 /** 1601 * @param {string} key 1602 * @param {any} newValue 1603 */ 1604 setItem(key, newValue) { 1605 this.map.set(key, newValue); 1606 } 1607 /** 1608 * @param {string} key 1609 */ 1610 getItem(key) { 1611 return this.map.get(key); 1612 } 1613 }; 1614 var _localStorage = new VarStoragePolyfill(); 1615 var usePolyfill = true; 1616 try { 1617 if (typeof localStorage !== "undefined" && localStorage) { 1618 _localStorage = localStorage; 1619 usePolyfill = false; 1620 } 1621 } catch (e) { 1622 } 1623 var varStorage = _localStorage; 1624 1625
vendor: 184 bytes, lines 1625-1629
1625// node_modules/lib0/trait/equality.js 1626 var EqualityTraitSymbol = /* @__PURE__ */ Symbol("Equality"); 1627 var equals = (a, b) => a === b || !!a?.[EqualityTraitSymbol]?.(b) || false; 1628 1629
vendor: 994 bytes, lines 1629-1666
1629// node_modules/lib0/object.js 1630 var isObject = (o) => typeof o === "object"; 1631 var assign = Object.assign; 1632 var keys = Object.keys; 1633 var forEach = (obj, f) => { 1634 for (const key in obj) { 1635 f(obj[key], key); 1636 } 1637 }; 1638 var size = (obj) => keys(obj).length; 1639 var isEmpty = (obj) => { 1640 for (const _k in obj) { 1641 return false; 1642 } 1643 return true; 1644 }; 1645 var every2 = (obj, f) => { 1646 for (const key in obj) { 1647 if (!f(obj[key], key)) { 1648 return false; 1649 } 1650 } 1651 return true; 1652 }; 1653 var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); 1654 var equalFlat = (a, b) => a === b || size(a) === size(b) && every2(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && equals(b[key], val)); 1655 var freeze = Object.freeze; 1656 var deepFreeze = (o) => { 1657 for (const key in o) { 1658 const c = o[key]; 1659 if (typeof c === "object" || typeof c === "function") { 1660 deepFreeze(o[key]); 1661 } 1662 } 1663 return freeze(o); 1664 }; 1665 1666
vendor: 2,128 bytes, lines 1666-1755
1666// node_modules/lib0/function.js 1667 var callAll = (fs, args2, i = 0) => { 1668 try { 1669 for (; i < fs.length; i++) { 1670 fs[i](...args2); 1671 } 1672 } finally { 1673 if (i < fs.length) { 1674 callAll(fs, args2, i + 1); 1675 } 1676 } 1677 }; 1678 var id = (a) => a; 1679 var equalityDeep = (a, b) => { 1680 if (a === b) { 1681 return true; 1682 } 1683 if (a == null || b == null || a.constructor !== b.constructor && (a.constructor || Object) !== (b.constructor || Object)) { 1684 return false; 1685 } 1686 if (a[EqualityTraitSymbol] != null) { 1687 return a[EqualityTraitSymbol](b); 1688 } 1689 switch (a.constructor) { 1690 case ArrayBuffer: 1691 a = new Uint8Array(a); 1692 b = new Uint8Array(b); 1693 // eslint-disable-next-line no-fallthrough 1694 case Uint8Array: { 1695 if (a.byteLength !== b.byteLength) { 1696 return false; 1697 } 1698 for (let i = 0; i < a.length; i++) { 1699 if (a[i] !== b[i]) { 1700 return false; 1701 } 1702 } 1703 break; 1704 } 1705 case Set: { 1706 if (a.size !== b.size) { 1707 return false; 1708 } 1709 for (const value of a) { 1710 if (!b.has(value)) { 1711 return false; 1712 } 1713 } 1714 break; 1715 } 1716 case Map: { 1717 if (a.size !== b.size) { 1718 return false; 1719 } 1720 for (const key of a.keys()) { 1721 if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) { 1722 return false; 1723 } 1724 } 1725 break; 1726 } 1727 case void 0: 1728 case Object: 1729 if (size(a) !== size(b)) { 1730 return false; 1731 } 1732 for (const key in a) { 1733 if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) { 1734 return false; 1735 } 1736 } 1737 break; 1738 case Array: 1739 if (a.length !== b.length) { 1740 return false; 1741 } 1742 for (let i = 0; i < a.length; i++) { 1743 if (!equalityDeep(a[i], b[i])) { 1744 return false; 1745 } 1746 } 1747 break; 1748 default: 1749 return false; 1750 } 1751 return true; 1752 }; 1753 var isOneOf = (value, options) => options.includes(value); 1754 1755
vendor: 2,361 bytes, lines 1755-1809
1755// node_modules/lib0/environment.js 1756 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]"; 1757 var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode; 1758 var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; 1759 var params; 1760 var args = []; 1761 var computeParams = () => { 1762 if (params === void 0) { 1763 if (isNode) { 1764 params = create(); 1765 const pargs = process.argv; 1766 let currParamName = null; 1767 for (let i = 0; i < pargs.length; i++) { 1768 const parg = pargs[i]; 1769 if (parg[0] === "-") { 1770 if (currParamName !== null) { 1771 params.set(currParamName, ""); 1772 } 1773 currParamName = parg; 1774 } else { 1775 if (currParamName !== null) { 1776 params.set(currParamName, parg); 1777 currParamName = null; 1778 } else { 1779 args.push(parg); 1780 } 1781 } 1782 } 1783 if (currParamName !== null) { 1784 params.set(currParamName, ""); 1785 } 1786 } else if (typeof location === "object") { 1787 params = create(); 1788 (location.search || "?").slice(1).split("&").forEach((kv) => { 1789 if (kv.length !== 0) { 1790 const [key, value] = kv.split("="); 1791 params.set(`--${fromCamelCase(key, "-")}`, value); 1792 params.set(`-${fromCamelCase(key, "-")}`, value); 1793 } 1794 }); 1795 } else { 1796 params = create(); 1797 } 1798 } 1799 return params; 1800 }; 1801 var hasParam = (name) => computeParams().has(name); 1802 var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name)); 1803 var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null; 1804 var production = hasConf("production"); 1805 var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]); 1806 var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors 1807 !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color")); 1808 1809
vendor: 1,174 bytes, lines 1809-1840
1809// node_modules/lib0/buffer.js 1810 var createUint8ArrayFromLen = (len) => new Uint8Array(len); 1811 var createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length2) => new Uint8Array(buffer, byteOffset, length2); 1812 var toBase64Browser = (bytes) => { 1813 let s = ""; 1814 for (let i = 0; i < bytes.byteLength; i++) { 1815 s += fromCharCode(bytes[i]); 1816 } 1817 return btoa(s); 1818 }; 1819 var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64"); 1820 var fromBase64Browser = (s) => { 1821 const a = atob(s); 1822 const bytes = createUint8ArrayFromLen(a.length); 1823 for (let i = 0; i < a.length; i++) { 1824 bytes[i] = a.charCodeAt(i); 1825 } 1826 return bytes; 1827 }; 1828 var fromBase64Node = (s) => { 1829 const buf = Buffer.from(s, "base64"); 1830 return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength); 1831 }; 1832 var toBase64 = isBrowser ? toBase64Browser : toBase64Node; 1833 var fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node; 1834 var copyUint8Array = (uint8Array) => { 1835 const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); 1836 newBuf.set(uint8Array); 1837 return newBuf; 1838 }; 1839 1840
vendor: 264 bytes, lines 1840-1853
1840// node_modules/lib0/pair.js 1841 var Pair = class { 1842 /** 1843 * @param {L} left 1844 * @param {R} right 1845 */ 1846 constructor(left, right) { 1847 this.left = left; 1848 this.right = right; 1849 } 1850 }; 1851 var create5 = (left, right) => new Pair(left, right); 1852 1853
vendor: 623 bytes, lines 1853-1869
1853// node_modules/lib0/prng.js 1854 var bool = (gen) => gen.next() >= 0.5; 1855 var int53 = (gen, min2, max2) => floor(gen.next() * (max2 + 1 - min2) + min2); 1856 var int32 = (gen, min2, max2) => floor(gen.next() * (max2 + 1 - min2) + min2); 1857 var int31 = (gen, min2, max2) => int32(gen, min2, max2); 1858 var letter = (gen) => fromCharCode(int31(gen, 97, 122)); 1859 var word = (gen, minLen = 0, maxLen = 20) => { 1860 const len = int31(gen, minLen, maxLen); 1861 let str = ""; 1862 for (let i = 0; i < len; i++) { 1863 str += letter(gen); 1864 } 1865 return str; 1866 }; 1867 var oneOf = (gen, array) => array[int31(gen, 0, array.length - 1)]; 1868 1869
vendor: 20,905 bytes, lines 1869-2605
1869// node_modules/lib0/schema.js 1870 var schemaSymbol = /* @__PURE__ */ Symbol("0schema"); 1871 var ValidationError = class { 1872 constructor() { 1873 this._rerrs = []; 1874 } 1875 /** 1876 * @param {string?} path 1877 * @param {string} expected 1878 * @param {string} has 1879 * @param {string?} message 1880 */ 1881 extend(path, expected, has, message = null) { 1882 this._rerrs.push({ path, expected, has, message }); 1883 } 1884 toString() { 1885 const s = []; 1886 for (let i = this._rerrs.length - 1; i > 0; i--) { 1887 const r = this._rerrs[i]; 1888 s.push(repeat(" ", (this._rerrs.length - i) * 2) + `${r.path != null ? `[${r.path}] ` : ""}${r.has} doesn't match ${r.expected}. ${r.message}`); 1889 } 1890 return s.join("\n"); 1891 } 1892 }; 1893 var shapeExtends = (a, b) => { 1894 if (a === b) return true; 1895 if (a == null || b == null || a.constructor !== b.constructor) return false; 1896 if (a[EqualityTraitSymbol]) return equals(a, b); 1897 if (isArray(a)) { 1898 return every( 1899 a, 1900 (aitem) => some(b, (bitem) => shapeExtends(aitem, bitem)) 1901 ); 1902 } else if (isObject(a)) { 1903 return every2( 1904 a, 1905 (aitem, akey) => shapeExtends(aitem, b[akey]) 1906 ); 1907 } 1908 return false; 1909 }; 1910 var Schema = class { 1911 // this.shape must not be defined on Schema. Otherwise typecheck on metatypes (e.g. $$object) won't work as expected anymore 1912 /** 1913 * If true, the more things are added to the shape the more objects this schema will accept (e.g. 1914 * union). By default, the more objects are added, the the fewer objects this schema will accept. 1915 * @protected 1916 */ 1917 static _dilutes = false; 1918 /** 1919 * @param {Schema<any>} other 1920 */ 1921 extends(other) { 1922 let [a, b] = [ 1923 /** @type {any} */ 1924 this.shape, 1925 /** @type {any} */ 1926 other.shape 1927 ]; 1928 if ( 1929 /** @type {typeof Schema<any>} */ 1930 this.constructor._dilutes 1931 ) [b, a] = [a, b]; 1932 return shapeExtends(a, b); 1933 } 1934 /** 1935 * Overwrite this when necessary. By default, we only check the `shape` property which every shape 1936 * should have. 1937 * @param {Schema<any>} other 1938 */ 1939 equals(other) { 1940 return this.constructor === other.constructor && equalityDeep(this.shape, other.shape); 1941 } 1942 [schemaSymbol]() { 1943 return true; 1944 } 1945 /** 1946 * @param {object} other 1947 */ 1948 [EqualityTraitSymbol](other) { 1949 return this.equals( 1950 /** @type {any} */ 1951 other 1952 ); 1953 } 1954 /** 1955 * Use `schema.validate(obj)` with a typed parameter that is already of typed to be an instance of 1956 * Schema. Validate will check the structure of the parameter and return true iff the instance 1957 * really is an instance of Schema. 1958 * 1959 * @param {T} o 1960 * @return {boolean} 1961 */ 1962 validate(o) { 1963 return this.check(o); 1964 } 1965 /* c8 ignore start */ 1966 /** 1967 * Similar to validate, but this method accepts untyped parameters. 1968 * 1969 * @param {any} _o 1970 * @param {ValidationError} [_err] 1971 * @return {_o is T} 1972 */ 1973 check(_o, _err) { 1974 methodUnimplemented(); 1975 } 1976 /* c8 ignore stop */ 1977 /** 1978 * @type {Schema<T?>} 1979 */ 1980 get nullable() { 1981 return $union(this, $null); 1982 } 1983 /** 1984 * @type {$Optional<Schema<T>>} 1985 */ 1986 get optional() { 1987 return new $Optional( 1988 /** @type {Schema<T>} */ 1989 this 1990 ); 1991 } 1992 /** 1993 * Cast a variable to a specific type. Returns the casted value, or throws an exception otherwise. 1994 * Use this if you know that the type is of a specific type and you just want to convince the type 1995 * system. 1996 * 1997 * **Do not rely on these error messages!** 1998 * Performs an assertion check only if not in a production environment. 1999 * 2000 * @template OO 2001 * @param {OO} o 2002 * @return {Extract<OO, T> extends never ? T : (OO extends Array<never> ? T : Extract<OO,T>)} 2003 */ 2004 cast(o) { 2005 assert(o, this); 2006 return ( 2007 /** @type {any} */ 2008 o 2009 ); 2010 } 2011 /** 2012 * EXPECTO PATRONUM!! 🪄 2013 * This function protects against type errors. Though it may not work in the real world. 2014 * 2015 * "After all this time?" 2016 * "Always." - Snape, talking about type safety 2017 * 2018 * Ensures that a variable is a a specific type. Returns the value, or throws an exception if the assertion check failed. 2019 * Use this if you know that the type is of a specific type and you just want to convince the type 2020 * system. 2021 * 2022 * Can be useful when defining lambdas: `s.lambda(s.$number, s.$void).expect((n) => n + 1)` 2023 * 2024 * **Do not rely on these error messages!** 2025 * Performs an assertion check if not in a production environment. 2026 * 2027 * @param {T} o 2028 * @return {o extends T ? T : never} 2029 */ 2030 expect(o) { 2031 assert(o, this); 2032 return o; 2033 } 2034 }; 2035 var $ConstructedBy = class extends Schema { 2036 /** 2037 * @param {C} c 2038 * @param {((o:Instance<C>)=>boolean)|null} check 2039 */ 2040 constructor(c, check) { 2041 super(); 2042 this.shape = c; 2043 this._c = check; 2044 } 2045 /** 2046 * @param {any} o 2047 * @param {ValidationError} [err] 2048 * @return {o is C extends ((...args:any[]) => infer T) ? T : (C extends (new (...args:any[]) => any) ? InstanceType<C> : never)} o 2049 */ 2050 check(o, err = void 0) { 2051 const c = o?.constructor === this.shape && (this._c == null || this._c(o)); 2052 !c && err?.extend(null, this.shape.name, o?.constructor.name, o?.constructor !== this.shape ? "Constructor match failed" : "Check failed"); 2053 return c; 2054 } 2055 }; 2056 var $constructedBy = (c, check = null) => new $ConstructedBy(c, check); 2057 var $$constructedBy = $constructedBy($ConstructedBy); 2058 var $Custom = class extends Schema { 2059 /** 2060 * @param {(o:any) => boolean} check 2061 */ 2062 constructor(check) { 2063 super(); 2064 this.shape = check; 2065 } 2066 /** 2067 * @param {any} o 2068 * @param {ValidationError} err 2069 * @return {o is any} 2070 */ 2071 check(o, err) { 2072 const c = this.shape(o); 2073 !c && err?.extend(null, "custom prop", o?.constructor.name, "failed to check custom prop"); 2074 return c; 2075 } 2076 }; 2077 var $custom = (check) => new $Custom(check); 2078 var $$custom = $constructedBy($Custom); 2079 var $Literal = class extends Schema { 2080 /** 2081 * @param {Array<T>} literals 2082 */ 2083 constructor(literals) { 2084 super(); 2085 this.shape = literals; 2086 } 2087 /** 2088 * 2089 * @param {any} o 2090 * @param {ValidationError} [err] 2091 * @return {o is T} 2092 */ 2093 check(o, err) { 2094 const c = this.shape.some((a) => a === o); 2095 !c && err?.extend(null, this.shape.join(" | "), o.toString()); 2096 return c; 2097 } 2098 }; 2099 var $literal = (...literals) => new $Literal(literals); 2100 var $$literal = $constructedBy($Literal); 2101 var _regexEscape = ( 2102 /** @type {any} */ 2103 RegExp.escape || /** @type {(str:string) => string} */ 2104 ((str) => str.replace(/[().|&,$^[\]]/g, (s) => "\\" + s)) 2105 ); 2106 var _schemaStringTemplateToRegex = (s) => { 2107 if ($string.check(s)) { 2108 return [_regexEscape(s)]; 2109 } 2110 if ($$literal.check(s)) { 2111 return ( 2112 /** @type {Array<string|number>} */ 2113 s.shape.map((v) => v + "") 2114 ); 2115 } 2116 if ($$number.check(s)) { 2117 return ["[+-]?\\d+.?\\d*"]; 2118 } 2119 if ($$string.check(s)) { 2120 return [".*"]; 2121 } 2122 if ($$union.check(s)) { 2123 return s.shape.map(_schemaStringTemplateToRegex).flat(1); 2124 } 2125 unexpectedCase(); 2126 }; 2127 var $StringTemplate = class extends Schema { 2128 /** 2129 * @param {T} shape 2130 */ 2131 constructor(shape) { 2132 super(); 2133 this.shape = shape; 2134 this._r = new RegExp("^" + shape.map(_schemaStringTemplateToRegex).map((opts) => `(${opts.join("|")})`).join("") + "$"); 2135 } 2136 /** 2137 * @param {any} o 2138 * @param {ValidationError} [err] 2139 * @return {o is CastStringTemplateArgsToTemplate<T>} 2140 */ 2141 check(o, err) { 2142 const c = this._r.exec(o) != null; 2143 !c && err?.extend(null, this._r.toString(), o.toString(), "String doesn't match string template."); 2144 return c; 2145 } 2146 }; 2147 var $$stringTemplate = $constructedBy($StringTemplate); 2148 var isOptionalSymbol = /* @__PURE__ */ Symbol("optional"); 2149 var $Optional = class extends Schema { 2150 /** 2151 * @param {S} shape 2152 */ 2153 constructor(shape) { 2154 super(); 2155 this.shape = shape; 2156 } 2157 /** 2158 * @param {any} o 2159 * @param {ValidationError} [err] 2160 * @return {o is (Unwrap<S>|undefined)} 2161 */ 2162 check(o, err) { 2163 const c = o === void 0 || this.shape.check(o); 2164 !c && err?.extend(null, "undefined (optional)", "()"); 2165 return c; 2166 } 2167 get [isOptionalSymbol]() { 2168 return true; 2169 } 2170 }; 2171 var $$optional = $constructedBy($Optional); 2172 var $Never = class extends Schema { 2173 /** 2174 * @param {any} _o 2175 * @param {ValidationError} [err] 2176 * @return {_o is never} 2177 */ 2178 check(_o, err) { 2179 err?.extend(null, "never", typeof _o); 2180 return false; 2181 } 2182 }; 2183 var $never = new $Never(); 2184 var $$never = $constructedBy($Never); 2185 var $Object = class _$Object extends Schema { 2186 /** 2187 * @param {S} shape 2188 * @param {boolean} partial 2189 */ 2190 constructor(shape, partial = false) { 2191 super(); 2192 this.shape = shape; 2193 this._isPartial = partial; 2194 } 2195 static _dilutes = true; 2196 /** 2197 * @type {Schema<Partial<$ObjectToType<S>>>} 2198 */ 2199 get partial() { 2200 return new _$Object(this.shape, true); 2201 } 2202 /** 2203 * @param {any} o 2204 * @param {ValidationError} err 2205 * @return {o is $ObjectToType<S>} 2206 */ 2207 check(o, err) { 2208 if (o == null) { 2209 err?.extend(null, "object", "null"); 2210 return false; 2211 } 2212 return every2(this.shape, (vv, vk) => { 2213 const c = this._isPartial && !hasProperty(o, vk) || vv.check(o[vk], err); 2214 !c && err?.extend(vk.toString(), vv.toString(), typeof o[vk], "Object property does not match"); 2215 return c; 2216 }); 2217 } 2218 }; 2219 var $object = (def) => ( 2220 /** @type {any} */ 2221 new $Object(def) 2222 ); 2223 var $$object = $constructedBy($Object); 2224 var $objectAny = $custom((o) => o != null && (o.constructor === Object || o.constructor == null)); 2225 var $Record = class extends Schema { 2226 /** 2227 * @param {Keys} keys 2228 * @param {Values} values 2229 */ 2230 constructor(keys2, values) { 2231 super(); 2232 this.shape = { 2233 keys: keys2, 2234 values 2235 }; 2236 } 2237 /** 2238 * @param {any} o 2239 * @param {ValidationError} err 2240 * @return {o is { [key in Unwrap<Keys>]: Unwrap<Values> }} 2241 */ 2242 check(o, err) { 2243 return o != null && every2(o, (vv, vk) => { 2244 const ck = this.shape.keys.check(vk, err); 2245 !ck && err?.extend(vk + "", "Record", typeof o, ck ? "Key doesn't match schema" : "Value doesn't match value"); 2246 return ck && this.shape.values.check(vv, err); 2247 }); 2248 } 2249 }; 2250 var $record = (keys2, values) => new $Record(keys2, values); 2251 var $$record = $constructedBy($Record); 2252 var $Tuple = class extends Schema { 2253 /** 2254 * @param {S} shape 2255 */ 2256 constructor(shape) { 2257 super(); 2258 this.shape = shape; 2259 } 2260 /** 2261 * @param {any} o 2262 * @param {ValidationError} err 2263 * @return {o is { [K in keyof S]: S[K] extends Schema<infer Type> ? Type : never }} 2264 */ 2265 check(o, err) { 2266 return o != null && every2(this.shape, (vv, vk) => { 2267 const c = ( 2268 /** @type {Schema<any>} */ 2269 vv.check(o[vk], err) 2270 ); 2271 !c && err?.extend(vk.toString(), "Tuple", typeof vv); 2272 return c; 2273 }); 2274 } 2275 }; 2276 var $tuple = (...def) => new $Tuple(def); 2277 var $$tuple = $constructedBy($Tuple); 2278 var $Array = class extends Schema { 2279 /** 2280 * @param {Array<S>} v 2281 */ 2282 constructor(v) { 2283 super(); 2284 this.shape = v.length === 1 ? v[0] : new $Union(v); 2285 } 2286 /** 2287 * @param {any} o 2288 * @param {ValidationError} [err] 2289 * @return {o is Array<S extends Schema<infer T> ? T : never>} o 2290 */ 2291 check(o, err) { 2292 const c = isArray(o) && every(o, (oi) => this.shape.check(oi)); 2293 !c && err?.extend(null, "Array", ""); 2294 return c; 2295 } 2296 }; 2297 var $array = (...def) => new $Array(def); 2298 var $$array = $constructedBy($Array); 2299 var $arrayAny = $custom((o) => isArray(o)); 2300 var $InstanceOf = class extends Schema { 2301 /** 2302 * @param {new (...args:any) => T} constructor 2303 * @param {((o:T) => boolean)|null} check 2304 */ 2305 constructor(constructor, check) { 2306 super(); 2307 this.shape = constructor; 2308 this._c = check; 2309 } 2310 /** 2311 * @param {any} o 2312 * @param {ValidationError} err 2313 * @return {o is T} 2314 */ 2315 check(o, err) { 2316 const c = o instanceof this.shape && (this._c == null || this._c(o)); 2317 !c && err?.extend(null, this.shape.name, o?.constructor.name); 2318 return c; 2319 } 2320 }; 2321 var $instanceOf = (c, check = null) => new $InstanceOf(c, check); 2322 var $$instanceOf = $constructedBy($InstanceOf); 2323 var $$schema = $instanceOf(Schema); 2324 var $Lambda = class extends Schema { 2325 /** 2326 * @param {Args} args 2327 */ 2328 constructor(args2) { 2329 super(); 2330 this.len = args2.length - 1; 2331 this.args = $tuple(...args2.slice(-1)); 2332 this.res = args2[this.len]; 2333 } 2334 /** 2335 * @param {any} f 2336 * @param {ValidationError} err 2337 * @return {f is _LArgsToLambdaDef<Args>} 2338 */ 2339 check(f, err) { 2340 const c = f.constructor === Function && f.length <= this.len; 2341 !c && err?.extend(null, "function", typeof f); 2342 return c; 2343 } 2344 }; 2345 var $$lambda = $constructedBy($Lambda); 2346 var $function = $custom((o) => typeof o === "function"); 2347 var $Intersection = class extends Schema { 2348 /** 2349 * @param {T} v 2350 */ 2351 constructor(v) { 2352 super(); 2353 this.shape = v; 2354 } 2355 /** 2356 * @param {any} o 2357 * @param {ValidationError} [err] 2358 * @return {o is Intersect<UnwrapArray<T>>} 2359 */ 2360 check(o, err) { 2361 const c = every(this.shape, (check) => check.check(o, err)); 2362 !c && err?.extend(null, "Intersectinon", typeof o); 2363 return c; 2364 } 2365 }; 2366 var $$intersect = $constructedBy($Intersection, (o) => o.shape.length > 0); 2367 var $Union = class extends Schema { 2368 static _dilutes = true; 2369 /** 2370 * @param {Array<Schema<S>>} v 2371 */ 2372 constructor(v) { 2373 super(); 2374 this.shape = v; 2375 } 2376 /** 2377 * @param {any} o 2378 * @param {ValidationError} [err] 2379 * @return {o is S} 2380 */ 2381 check(o, err) { 2382 const c = some(this.shape, (vv) => vv.check(o, err)); 2383 err?.extend(null, "Union", typeof o); 2384 return c; 2385 } 2386 }; 2387 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); 2388 var $$union = ( 2389 /** @type {Schema<$Union<any>>} */ 2390 $constructedBy($Union) 2391 ); 2392 var _t = () => true; 2393 var $any = $custom(_t); 2394 var $$any = ( 2395 /** @type {Schema<Schema<any>>} */ 2396 $constructedBy($Custom, (o) => o.shape === _t) 2397 ); 2398 var $bigint = $custom((o) => typeof o === "bigint"); 2399 var $$bigint = ( 2400 /** @type {Schema<Schema<BigInt>>} */ 2401 $custom((o) => o === $bigint) 2402 ); 2403 var $symbol = $custom((o) => typeof o === "symbol"); 2404 var $$symbol = ( 2405 /** @type {Schema<Schema<Symbol>>} */ 2406 $custom((o) => o === $symbol) 2407 ); 2408 var $number = $custom((o) => typeof o === "number"); 2409 var $$number = ( 2410 /** @type {Schema<Schema<number>>} */ 2411 $custom((o) => o === $number) 2412 ); 2413 var $string = $custom((o) => typeof o === "string"); 2414 var $$string = ( 2415 /** @type {Schema<Schema<string>>} */ 2416 $custom((o) => o === $string) 2417 ); 2418 var $boolean = $custom((o) => typeof o === "boolean"); 2419 var $$boolean = ( 2420 /** @type {Schema<Schema<Boolean>>} */ 2421 $custom((o) => o === $boolean) 2422 ); 2423 var $undefined = $literal(void 0); 2424 var $$undefined = ( 2425 /** @type {Schema<Schema<undefined>>} */ 2426 $constructedBy($Literal, (o) => o.shape.length === 1 && o.shape[0] === void 0) 2427 ); 2428 var $void = $literal(void 0); 2429 var $null = $literal(null); 2430 var $$null = ( 2431 /** @type {Schema<Schema<null>>} */ 2432 $constructedBy($Literal, (o) => o.shape.length === 1 && o.shape[0] === null) 2433 ); 2434 var $uint8Array = $constructedBy(Uint8Array); 2435 var $$uint8Array = ( 2436 /** @type {Schema<Schema<Uint8Array>>} */ 2437 $constructedBy($ConstructedBy, (o) => o.shape === Uint8Array) 2438 ); 2439 var $primitive = $union($number, $string, $null, $undefined, $bigint, $boolean, $symbol); 2440 var $json = (() => { 2441 const $jsonArr = ( 2442 /** @type {$Array<$any>} */ 2443 $array($any) 2444 ); 2445 const $jsonRecord = ( 2446 /** @type {$Record<$string,$any>} */ 2447 $record($string, $any) 2448 ); 2449 const $json2 = $union($number, $string, $null, $boolean, $jsonArr, $jsonRecord); 2450 $jsonArr.shape = $json2; 2451 $jsonRecord.shape.values = $json2; 2452 return $json2; 2453 })(); 2454 var $ = (o) => { 2455 if ($$schema.check(o)) { 2456 return ( 2457 /** @type {any} */ 2458 o 2459 ); 2460 } else if ($objectAny.check(o)) { 2461 const o2 = {}; 2462 for (const k in o) { 2463 o2[k] = $(o[k]); 2464 } 2465 return ( 2466 /** @type {any} */ 2467 $object(o2) 2468 ); 2469 } else if ($arrayAny.check(o)) { 2470 return ( 2471 /** @type {any} */ 2472 $union(...o.map($)) 2473 ); 2474 } else if ($primitive.check(o)) { 2475 return ( 2476 /** @type {any} */ 2477 $literal(o) 2478 ); 2479 } else if ($function.check(o)) { 2480 return ( 2481 /** @type {any} */ 2482 $constructedBy( 2483 /** @type {any} */ 2484 o 2485 ) 2486 ); 2487 } 2488 unexpectedCase(); 2489 }; 2490 var assert = production ? () => { 2491 } : (o, schema) => { 2492 const err = new ValidationError(); 2493 if (!schema.check(o, err)) { 2494 throw create3(`Expected value to be of type ${schema.constructor.name}. 2495${err.toString()}`); 2496 } 2497 }; 2498 var PatternMatcher = class { 2499 /** 2500 * @param {Schema<State>} [$state] 2501 */ 2502 constructor($state) { 2503 this.patterns = []; 2504 this.$state = $state; 2505 } 2506 /** 2507 * @template P 2508 * @template R 2509 * @param {P} pattern 2510 * @param {(o:NoInfer<Unwrap<ReadSchema<P>>>,s:State)=>R} handler 2511 * @return {PatternMatcher<State,Patterns|Pattern<Unwrap<ReadSchema<P>>,R>>} 2512 */ 2513 if(pattern, handler) { 2514 this.patterns.push({ if: $(pattern), h: handler }); 2515 return this; 2516 } 2517 /** 2518 * @template R 2519 * @param {(o:any,s:State)=>R} h 2520 */ 2521 else(h) { 2522 return this.if($any, h); 2523 } 2524 /** 2525 * @return {State extends undefined 2526 * ? <In extends Unwrap<Patterns['if']>>(o:In,state?:undefined)=>PatternMatchResult<Patterns,In> 2527 * : <In extends Unwrap<Patterns['if']>>(o:In,state:State)=>PatternMatchResult<Patterns,In>} 2528 */ 2529 done() { 2530 return ( 2531 /** @type {any} */ 2532 (o, s) => { 2533 for (let i = 0; i < this.patterns.length; i++) { 2534 const p = this.patterns[i]; 2535 if (p.if.check(o)) { 2536 return p.h(o, s); 2537 } 2538 } 2539 throw create3("Unhandled pattern"); 2540 } 2541 ); 2542 } 2543 }; 2544 var match = (state) => new PatternMatcher( 2545 /** @type {any} */ 2546 state 2547 ); 2548 var _random = ( 2549 /** @type {any} */ 2550 match( 2551 /** @type {Schema<prng.PRNG>} */ 2552 $any 2553 ).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) => { 2554 const res = {}; 2555 for (const k in o.shape) { 2556 let prop = o.shape[k]; 2557 if ($$optional.check(prop)) { 2558 if (bool(gen)) { 2559 continue; 2560 } 2561 prop = prop.shape; 2562 } 2563 res[k] = _random(prop, gen); 2564 } 2565 return res; 2566 }).if($$array, (o, gen) => { 2567 const arr = []; 2568 const n = int32(gen, 0, 42); 2569 for (let i = 0; i < n; i++) { 2570 arr.push(random(gen, o.shape)); 2571 } 2572 return arr; 2573 }).if($$literal, (o, gen) => { 2574 return oneOf(gen, o.shape); 2575 }).if($$null, (o, gen) => { 2576 return null; 2577 }).if($$lambda, (o, gen) => { 2578 const res = random(gen, o.res); 2579 return () => res; 2580 }).if($$any, (o, gen) => random(gen, oneOf(gen, [ 2581 $number, 2582 $string, 2583 $null, 2584 $undefined, 2585 $bigint, 2586 $boolean, 2587 $array($number), 2588 $record($union("a", "b", "c"), $number) 2589 ]))).if($$record, (o, gen) => { 2590 const res = {}; 2591 const keysN = int53(gen, 0, 3); 2592 for (let i = 0; i < keysN; i++) { 2593 const key = random(gen, o.shape.keys); 2594 const val = random(gen, o.shape.values); 2595 res[key] = val; 2596 } 2597 return res; 2598 }).done() 2599 ); 2600 var random = (gen, schema) => ( 2601 /** @type {any} */ 2602 _random($(schema), gen) 2603 ); 2604 2605
vendor: 903 bytes, lines 2605-2627
2605// node_modules/lib0/dom.js 2606 var doc = ( 2607 /** @type {Document} */ 2608 typeof document !== "undefined" ? document : {} 2609 ); 2610 var $fragment = $custom((el) => el.nodeType === DOCUMENT_FRAGMENT_NODE); 2611 var domParser = ( 2612 /** @type {DOMParser} */ 2613 typeof DOMParser !== "undefined" ? new DOMParser() : null 2614 ); 2615 var $element = $custom((el) => el.nodeType === ELEMENT_NODE); 2616 var $text = $custom((el) => el.nodeType === TEXT_NODE); 2617 var mapToStyleString = (m) => map(m, (value, key) => `${key}:${value};`).join(""); 2618 var ELEMENT_NODE = doc.ELEMENT_NODE; 2619 var TEXT_NODE = doc.TEXT_NODE; 2620 var CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE; 2621 var COMMENT_NODE = doc.COMMENT_NODE; 2622 var DOCUMENT_NODE = doc.DOCUMENT_NODE; 2623 var DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE; 2624 var DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE; 2625 var $node = $custom((el) => el.nodeType === DOCUMENT_NODE); 2626 2627
vendor: 58 bytes, lines 2627-2630
2627// node_modules/lib0/symbol.js 2628 var create6 = Symbol; 2629 2630
vendor: 1,129 bytes, lines 2630-2672
2630// node_modules/lib0/logging.common.js 2631 var BOLD = create6(); 2632 var UNBOLD = create6(); 2633 var BLUE = create6(); 2634 var GREY = create6(); 2635 var GREEN = create6(); 2636 var RED = create6(); 2637 var PURPLE = create6(); 2638 var ORANGE = create6(); 2639 var UNCOLOR = create6(); 2640 var computeNoColorLoggingArgs = (args2) => { 2641 if (args2.length === 1 && args2[0]?.constructor === Function) { 2642 args2 = /** @type {Array<string|Symbol|Object|number>} */ 2643 /** @type {[function]} */ 2644 args2[0](); 2645 } 2646 const strBuilder = []; 2647 const logArgs = []; 2648 let i = 0; 2649 for (; i < args2.length; i++) { 2650 const arg = args2[i]; 2651 if (arg === void 0) { 2652 break; 2653 } else if (arg.constructor === String || arg.constructor === Number) { 2654 strBuilder.push(arg); 2655 } else if (arg.constructor === Object) { 2656 break; 2657 } 2658 } 2659 if (i > 0) { 2660 logArgs.push(strBuilder.join("")); 2661 } 2662 for (; i < args2.length; i++) { 2663 const arg = args2[i]; 2664 if (!(arg instanceof Symbol)) { 2665 logArgs.push(arg); 2666 } 2667 } 2668 return logArgs; 2669 }; 2670 var lastLoggingTime = getUnixTime(); 2671 2672
vendor: 2,185 bytes, lines 2672-2742
2672// node_modules/lib0/logging.js 2673 var _browserStyleMap = { 2674 [BOLD]: create5("font-weight", "bold"), 2675 [UNBOLD]: create5("font-weight", "normal"), 2676 [BLUE]: create5("color", "blue"), 2677 [GREEN]: create5("color", "green"), 2678 [GREY]: create5("color", "grey"), 2679 [RED]: create5("color", "red"), 2680 [PURPLE]: create5("color", "purple"), 2681 [ORANGE]: create5("color", "orange"), 2682 // not well supported in chrome when debugging node with inspector - TODO: deprecate 2683 [UNCOLOR]: create5("color", "black") 2684 }; 2685 var computeBrowserLoggingArgs = (args2) => { 2686 if (args2.length === 1 && args2[0]?.constructor === Function) { 2687 args2 = /** @type {Array<string|Symbol|Object|number>} */ 2688 /** @type {[function]} */ 2689 args2[0](); 2690 } 2691 const strBuilder = []; 2692 const styles = []; 2693 const currentStyle = create(); 2694 let logArgs = []; 2695 let i = 0; 2696 for (; i < args2.length; i++) { 2697 const arg = args2[i]; 2698 const style = _browserStyleMap[arg]; 2699 if (style !== void 0) { 2700 currentStyle.set(style.left, style.right); 2701 } else { 2702 if (arg === void 0) { 2703 break; 2704 } 2705 if (arg.constructor === String || arg.constructor === Number) { 2706 const style2 = mapToStyleString(currentStyle); 2707 if (i > 0 || style2.length > 0) { 2708 strBuilder.push("%c" + arg); 2709 styles.push(style2); 2710 } else { 2711 strBuilder.push(arg); 2712 } 2713 } else { 2714 break; 2715 } 2716 } 2717 } 2718 if (i > 0) { 2719 logArgs = styles; 2720 logArgs.unshift(strBuilder.join("")); 2721 } 2722 for (; i < args2.length; i++) { 2723 const arg = args2[i]; 2724 if (!(arg instanceof Symbol)) { 2725 logArgs.push(arg); 2726 } 2727 } 2728 return logArgs; 2729 }; 2730 var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs; 2731 var print = (...args2) => { 2732 console.log(...computeLoggingArgs(args2)); 2733 vconsoles.forEach((vc) => vc.print(args2)); 2734 }; 2735 var warn = (...args2) => { 2736 console.warn(...computeLoggingArgs(args2)); 2737 args2.unshift(ORANGE); 2738 vconsoles.forEach((vc) => vc.print(args2)); 2739 }; 2740 var vconsoles = create2(); 2741 2742
vendor: 569 bytes, lines 2742-2765
2742// node_modules/lib0/iterator.js 2743 var createIterator = (next) => ({ 2744 /** 2745 * @return {IterableIterator<T>} 2746 */ 2747 [Symbol.iterator]() { 2748 return this; 2749 }, 2750 // @ts-ignore 2751 next 2752 }); 2753 var iteratorFilter = (iterator, filter) => createIterator(() => { 2754 let res; 2755 do { 2756 res = iterator.next(); 2757 } while (!res.done && !filter(res.value)); 2758 return res; 2759 }); 2760 var iteratorMap = (iterator, fmap) => createIterator(() => { 2761 const { done, value } = iterator.next(); 2762 return { done, value: done ? void 0 : fmap(value) }; 2763 }); 2764 2765
vendor: 234,549 bytes, lines 2765-10300
2765// node_modules/yjs/dist/yjs.mjs 2766 var AbstractConnector = class extends ObservableV2 { 2767 /** 2768 * @param {Doc} ydoc 2769 * @param {any} awareness 2770 */ 2771 constructor(ydoc, awareness) { 2772 super(); 2773 this.doc = ydoc; 2774 this.awareness = awareness; 2775 } 2776 }; 2777 var DeleteItem = class { 2778 /** 2779 * @param {number} clock 2780 * @param {number} len 2781 */ 2782 constructor(clock, len) { 2783 this.clock = clock; 2784 this.len = len; 2785 } 2786 }; 2787 var DeleteSet = class { 2788 constructor() { 2789 this.clients = /* @__PURE__ */ new Map(); 2790 } 2791 }; 2792 var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => { 2793 const structs = ( 2794 /** @type {Array<GC|Item>} */ 2795 transaction.doc.store.clients.get(clientid) 2796 ); 2797 if (structs != null) { 2798 const lastStruct = structs[structs.length - 1]; 2799 const clockState = lastStruct.id.clock + lastStruct.length; 2800 for (let i = 0, del = deletes[i]; i < deletes.length && del.clock < clockState; del = deletes[++i]) { 2801 iterateStructs(transaction, structs, del.clock, del.len, f); 2802 } 2803 } 2804 }); 2805 var findIndexDS = (dis, clock) => { 2806 let left = 0; 2807 let right = dis.length - 1; 2808 while (left <= right) { 2809 const midindex = floor((left + right) / 2); 2810 const mid = dis[midindex]; 2811 const midclock = mid.clock; 2812 if (midclock <= clock) { 2813 if (clock < midclock + mid.len) { 2814 return midindex; 2815 } 2816 left = midindex + 1; 2817 } else { 2818 right = midindex - 1; 2819 } 2820 } 2821 return null; 2822 }; 2823 var isDeleted = (ds, id2) => { 2824 const dis = ds.clients.get(id2.client); 2825 return dis !== void 0 && findIndexDS(dis, id2.clock) !== null; 2826 }; 2827 var sortAndMergeDeleteSet = (ds) => { 2828 ds.clients.forEach((dels) => { 2829 dels.sort((a, b) => a.clock - b.clock); 2830 let i, j; 2831 for (i = 1, j = 1; i < dels.length; i++) { 2832 const left = dels[j - 1]; 2833 const right = dels[i]; 2834 if (left.clock + left.len >= right.clock) { 2835 left.len = max(left.len, right.clock + right.len - left.clock); 2836 } else { 2837 if (j < i) { 2838 dels[j] = right; 2839 } 2840 j++; 2841 } 2842 } 2843 dels.length = j; 2844 }); 2845 }; 2846 var mergeDeleteSets = (dss) => { 2847 const merged = new DeleteSet(); 2848 for (let dssI = 0; dssI < dss.length; dssI++) { 2849 dss[dssI].clients.forEach((delsLeft, client) => { 2850 if (!merged.clients.has(client)) { 2851 const dels = delsLeft.slice(); 2852 for (let i = dssI + 1; i < dss.length; i++) { 2853 appendTo(dels, dss[i].clients.get(client) || []); 2854 } 2855 merged.clients.set(client, dels); 2856 } 2857 }); 2858 } 2859 sortAndMergeDeleteSet(merged); 2860 return merged; 2861 }; 2862 var addToDeleteSet = (ds, client, clock, length2) => { 2863 setIfUndefined(ds.clients, client, () => ( 2864 /** @type {Array<DeleteItem>} */ 2865 [] 2866 )).push(new DeleteItem(clock, length2)); 2867 }; 2868 var createDeleteSet = () => new DeleteSet(); 2869 var createDeleteSetFromStructStore = (ss) => { 2870 const ds = createDeleteSet(); 2871 ss.clients.forEach((structs, client) => { 2872 const dsitems = []; 2873 for (let i = 0; i < structs.length; i++) { 2874 const struct = structs[i]; 2875 if (struct.deleted) { 2876 const clock = struct.id.clock; 2877 let len = struct.length; 2878 if (i + 1 < structs.length) { 2879 for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) { 2880 len += next.length; 2881 } 2882 } 2883 dsitems.push(new DeleteItem(clock, len)); 2884 } 2885 } 2886 if (dsitems.length > 0) { 2887 ds.clients.set(client, dsitems); 2888 } 2889 }); 2890 return ds; 2891 }; 2892 var writeDeleteSet = (encoder, ds) => { 2893 writeVarUint(encoder.restEncoder, ds.clients.size); 2894 from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => { 2895 encoder.resetDsCurVal(); 2896 writeVarUint(encoder.restEncoder, client); 2897 const len = dsitems.length; 2898 writeVarUint(encoder.restEncoder, len); 2899 for (let i = 0; i < len; i++) { 2900 const item = dsitems[i]; 2901 encoder.writeDsClock(item.clock); 2902 encoder.writeDsLen(item.len); 2903 } 2904 }); 2905 }; 2906 var readDeleteSet = (decoder) => { 2907 const ds = new DeleteSet(); 2908 const numClients = readVarUint(decoder.restDecoder); 2909 for (let i = 0; i < numClients; i++) { 2910 decoder.resetDsCurVal(); 2911 const client = readVarUint(decoder.restDecoder); 2912 const numberOfDeletes = readVarUint(decoder.restDecoder); 2913 if (numberOfDeletes > 0) { 2914 const dsField = setIfUndefined(ds.clients, client, () => ( 2915 /** @type {Array<DeleteItem>} */ 2916 [] 2917 )); 2918 for (let i2 = 0; i2 < numberOfDeletes; i2++) { 2919 dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); 2920 } 2921 } 2922 } 2923 return ds; 2924 }; 2925 var readAndApplyDeleteSet = (decoder, transaction, store2) => { 2926 const unappliedDS = new DeleteSet(); 2927 const numClients = readVarUint(decoder.restDecoder); 2928 for (let i = 0; i < numClients; i++) { 2929 decoder.resetDsCurVal(); 2930 const client = readVarUint(decoder.restDecoder); 2931 const numberOfDeletes = readVarUint(decoder.restDecoder); 2932 const structs = store2.clients.get(client) || []; 2933 const state = getState(store2, client); 2934 for (let i2 = 0; i2 < numberOfDeletes; i2++) { 2935 const clock = decoder.readDsClock(); 2936 const clockEnd = clock + decoder.readDsLen(); 2937 if (clock < state) { 2938 if (state < clockEnd) { 2939 addToDeleteSet(unappliedDS, client, state, clockEnd - state); 2940 } 2941 let index = findIndexSS(structs, clock); 2942 let struct = structs[index]; 2943 if (!struct.deleted && struct.id.clock < clock) { 2944 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); 2945 index++; 2946 } 2947 while (index < structs.length) { 2948 struct = structs[index++]; 2949 if (struct.id.clock < clockEnd) { 2950 if (!struct.deleted) { 2951 if (clockEnd < struct.id.clock + struct.length) { 2952 structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); 2953 } 2954 struct.delete(transaction); 2955 } 2956 } else { 2957 break; 2958 } 2959 } 2960 } else { 2961 addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); 2962 } 2963 } 2964 } 2965 if (unappliedDS.clients.size > 0) { 2966 const ds = new UpdateEncoderV2(); 2967 writeVarUint(ds.restEncoder, 0); 2968 writeDeleteSet(ds, unappliedDS); 2969 return ds.toUint8Array(); 2970 } 2971 return null; 2972 }; 2973 var equalDeleteSets = (ds1, ds2) => { 2974 if (ds1.clients.size !== ds2.clients.size) return false; 2975 for (const [client, deleteItems1] of ds1.clients.entries()) { 2976 const deleteItems2 = ( 2977 /** @type {Array<import('../internals.js').DeleteItem>} */ 2978 ds2.clients.get(client) 2979 ); 2980 if (deleteItems2 === void 0 || deleteItems1.length !== deleteItems2.length) return false; 2981 for (let i = 0; i < deleteItems1.length; i++) { 2982 const di1 = deleteItems1[i]; 2983 const di2 = deleteItems2[i]; 2984 if (di1.clock !== di2.clock || di1.len !== di2.len) { 2985 return false; 2986 } 2987 } 2988 } 2989 return true; 2990 }; 2991 var generateNewClientId = uint32; 2992 var Doc = class _Doc extends ObservableV2 { 2993 /** 2994 * @param {DocOpts} opts configuration 2995 */ 2996 constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) { 2997 super(); 2998 this.gc = gc; 2999 this.gcFilter = gcFilter; 3000 this.clientID = generateNewClientId(); 3001 this.guid = guid; 3002 this.collectionid = collectionid; 3003 this.share = /* @__PURE__ */ new Map(); 3004 this.store = new StructStore(); 3005 this._transaction = null; 3006 this._transactionCleanups = []; 3007 this.subdocs = /* @__PURE__ */ new Set(); 3008 this._item = null; 3009 this.shouldLoad = shouldLoad; 3010 this.autoLoad = autoLoad; 3011 this.meta = meta; 3012 this.isLoaded = false; 3013 this.isSynced = false; 3014 this.isDestroyed = false; 3015 this.whenLoaded = create4((resolve) => { 3016 this.on("load", () => { 3017 this.isLoaded = true; 3018 resolve(this); 3019 }); 3020 }); 3021 const provideSyncedPromise = () => create4((resolve) => { 3022 const eventHandler = (isSynced) => { 3023 if (isSynced === void 0 || isSynced === true) { 3024 this.off("sync", eventHandler); 3025 resolve(); 3026 } 3027 }; 3028 this.on("sync", eventHandler); 3029 }); 3030 this.on("sync", (isSynced) => { 3031 if (isSynced === false && this.isSynced) { 3032 this.whenSynced = provideSyncedPromise(); 3033 } 3034 this.isSynced = isSynced === void 0 || isSynced === true; 3035 if (this.isSynced && !this.isLoaded) { 3036 this.emit("load", [this]); 3037 } 3038 }); 3039 this.whenSynced = provideSyncedPromise(); 3040 } 3041 /** 3042 * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). 3043 * 3044 * `load()` might be used in the future to request any provider to load the most current data. 3045 * 3046 * It is safe to call `load()` multiple times. 3047 */ 3048 load() { 3049 const item = this._item; 3050 if (item !== null && !this.shouldLoad) { 3051 transact( 3052 /** @type {any} */ 3053 item.parent.doc, 3054 (transaction) => { 3055 transaction.subdocsLoaded.add(this); 3056 }, 3057 null, 3058 true 3059 ); 3060 } 3061 this.shouldLoad = true; 3062 } 3063 getSubdocs() { 3064 return this.subdocs; 3065 } 3066 getSubdocGuids() { 3067 return new Set(from(this.subdocs).map((doc2) => doc2.guid)); 3068 } 3069 /** 3070 * Changes that happen inside of a transaction are bundled. This means that 3071 * the observer fires _after_ the transaction is finished and that all changes 3072 * that happened inside of the transaction are sent as one message to the 3073 * other peers. 3074 * 3075 * @template T 3076 * @param {function(Transaction):T} f The function that should be executed as a transaction 3077 * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin 3078 * @return T 3079 * 3080 * @public 3081 */ 3082 transact(f, origin2 = null) { 3083 return transact(this, f, origin2); 3084 } 3085 /** 3086 * Define a shared data type. 3087 * 3088 * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result 3089 * and do not overwrite each other. I.e. 3090 * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)` 3091 * 3092 * After this method is called, the type is also available on `ydoc.share.get(name)`. 3093 * 3094 * *Best Practices:* 3095 * Define all types right after the Y.Doc instance is created and store them in a separate object. 3096 * Also use the typed methods `getText(name)`, `getArray(name)`, .. 3097 * 3098 * @template {typeof AbstractType<any>} Type 3099 * @example 3100 * const ydoc = new Y.Doc(..) 3101 * const appState = { 3102 * document: ydoc.getText('document') 3103 * comments: ydoc.getArray('comments') 3104 * } 3105 * 3106 * @param {string} name 3107 * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... 3108 * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor 3109 * 3110 * @public 3111 */ 3112 get(name, TypeConstructor = ( 3113 /** @type {any} */ 3114 AbstractType 3115 )) { 3116 const type = setIfUndefined(this.share, name, () => { 3117 const t = new TypeConstructor(); 3118 t._integrate(this, null); 3119 return t; 3120 }); 3121 const Constr = type.constructor; 3122 if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { 3123 if (Constr === AbstractType) { 3124 const t = new TypeConstructor(); 3125 t._map = type._map; 3126 type._map.forEach( 3127 /** @param {Item?} n */ 3128 (n) => { 3129 for (; n !== null; n = n.left) { 3130 n.parent = t; 3131 } 3132 } 3133 ); 3134 t._start = type._start; 3135 for (let n = t._start; n !== null; n = n.right) { 3136 n.parent = t; 3137 } 3138 t._length = type._length; 3139 this.share.set(name, t); 3140 t._integrate(this, null); 3141 return ( 3142 /** @type {InstanceType<Type>} */ 3143 t 3144 ); 3145 } else { 3146 throw new Error(`Type with the name ${name} has already been defined with a different constructor`); 3147 } 3148 } 3149 return ( 3150 /** @type {InstanceType<Type>} */ 3151 type 3152 ); 3153 } 3154 /** 3155 * @template T 3156 * @param {string} [name] 3157 * @return {YArray<T>} 3158 * 3159 * @public 3160 */ 3161 getArray(name = "") { 3162 return ( 3163 /** @type {YArray<T>} */ 3164 this.get(name, YArray) 3165 ); 3166 } 3167 /** 3168 * @param {string} [name] 3169 * @return {YText} 3170 * 3171 * @public 3172 */ 3173 getText(name = "") { 3174 return this.get(name, YText); 3175 } 3176 /** 3177 * @template T 3178 * @param {string} [name] 3179 * @return {YMap<T>} 3180 * 3181 * @public 3182 */ 3183 getMap(name = "") { 3184 return ( 3185 /** @type {YMap<T>} */ 3186 this.get(name, YMap) 3187 ); 3188 } 3189 /** 3190 * @param {string} [name] 3191 * @return {YXmlElement} 3192 * 3193 * @public 3194 */ 3195 getXmlElement(name = "") { 3196 return ( 3197 /** @type {YXmlElement<{[key:string]:string}>} */ 3198 this.get(name, YXmlElement) 3199 ); 3200 } 3201 /** 3202 * @param {string} [name] 3203 * @return {YXmlFragment} 3204 * 3205 * @public 3206 */ 3207 getXmlFragment(name = "") { 3208 return this.get(name, YXmlFragment); 3209 } 3210 /** 3211 * Converts the entire document into a js object, recursively traversing each yjs type 3212 * Doesn't log types that have not been defined (using ydoc.getType(..)). 3213 * 3214 * @deprecated Do not use this method and rather call toJSON directly on the shared types. 3215 * 3216 * @return {Object<string, any>} 3217 */ 3218 toJSON() { 3219 const doc2 = {}; 3220 this.share.forEach((value, key) => { 3221 doc2[key] = value.toJSON(); 3222 }); 3223 return doc2; 3224 } 3225 /** 3226 * Emit `destroy` event and unregister all event handlers. 3227 */ 3228 destroy() { 3229 this.isDestroyed = true; 3230 from(this.subdocs).forEach((subdoc) => subdoc.destroy()); 3231 const item = this._item; 3232 if (item !== null) { 3233 this._item = null; 3234 const content = ( 3235 /** @type {ContentDoc} */ 3236 item.content 3237 ); 3238 content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false }); 3239 content.doc._item = item; 3240 transact( 3241 /** @type {any} */ 3242 item.parent.doc, 3243 (transaction) => { 3244 const doc2 = content.doc; 3245 if (!item.deleted) { 3246 transaction.subdocsAdded.add(doc2); 3247 } 3248 transaction.subdocsRemoved.add(this); 3249 }, 3250 null, 3251 true 3252 ); 3253 } 3254 this.emit("destroyed", [true]); 3255 this.emit("destroy", [this]); 3256 super.destroy(); 3257 } 3258 }; 3259 var DSDecoderV1 = class { 3260 /** 3261 * @param {decoding.Decoder} decoder 3262 */ 3263 constructor(decoder) { 3264 this.restDecoder = decoder; 3265 } 3266 resetDsCurVal() { 3267 } 3268 /** 3269 * @return {number} 3270 */ 3271 readDsClock() { 3272 return readVarUint(this.restDecoder); 3273 } 3274 /** 3275 * @return {number} 3276 */ 3277 readDsLen() { 3278 return readVarUint(this.restDecoder); 3279 } 3280 }; 3281 var UpdateDecoderV1 = class extends DSDecoderV1 { 3282 /** 3283 * @return {ID} 3284 */ 3285 readLeftID() { 3286 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); 3287 } 3288 /** 3289 * @return {ID} 3290 */ 3291 readRightID() { 3292 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); 3293 } 3294 /** 3295 * Read the next client id. 3296 * Use this in favor of readID whenever possible to reduce the number of objects created. 3297 */ 3298 readClient() { 3299 return readVarUint(this.restDecoder); 3300 } 3301 /** 3302 * @return {number} info An unsigned 8-bit integer 3303 */ 3304 readInfo() { 3305 return readUint8(this.restDecoder); 3306 } 3307 /** 3308 * @return {string} 3309 */ 3310 readString() { 3311 return readVarString(this.restDecoder); 3312 } 3313 /** 3314 * @return {boolean} isKey 3315 */ 3316 readParentInfo() { 3317 return readVarUint(this.restDecoder) === 1; 3318 } 3319 /** 3320 * @return {number} info An unsigned 8-bit integer 3321 */ 3322 readTypeRef() { 3323 return readVarUint(this.restDecoder); 3324 } 3325 /** 3326 * Write len of a struct - well suited for Opt RLE encoder. 3327 * 3328 * @return {number} len 3329 */ 3330 readLen() { 3331 return readVarUint(this.restDecoder); 3332 } 3333 /** 3334 * @return {any} 3335 */ 3336 readAny() { 3337 return readAny(this.restDecoder); 3338 } 3339 /** 3340 * @return {Uint8Array} 3341 */ 3342 readBuf() { 3343 return copyUint8Array(readVarUint8Array(this.restDecoder)); 3344 } 3345 /** 3346 * Legacy implementation uses JSON parse. We use any-decoding in v2. 3347 * 3348 * @return {any} 3349 */ 3350 readJSON() { 3351 return JSON.parse(readVarString(this.restDecoder)); 3352 } 3353 /** 3354 * @return {string} 3355 */ 3356 readKey() { 3357 return readVarString(this.restDecoder); 3358 } 3359 }; 3360 var DSDecoderV2 = class { 3361 /** 3362 * @param {decoding.Decoder} decoder 3363 */ 3364 constructor(decoder) { 3365 this.dsCurrVal = 0; 3366 this.restDecoder = decoder; 3367 } 3368 resetDsCurVal() { 3369 this.dsCurrVal = 0; 3370 } 3371 /** 3372 * @return {number} 3373 */ 3374 readDsClock() { 3375 this.dsCurrVal += readVarUint(this.restDecoder); 3376 return this.dsCurrVal; 3377 } 3378 /** 3379 * @return {number} 3380 */ 3381 readDsLen() { 3382 const diff = readVarUint(this.restDecoder) + 1; 3383 this.dsCurrVal += diff; 3384 return diff; 3385 } 3386 }; 3387 var UpdateDecoderV2 = class extends DSDecoderV2 { 3388 /** 3389 * @param {decoding.Decoder} decoder 3390 */ 3391 constructor(decoder) { 3392 super(decoder); 3393 this.keys = []; 3394 readVarUint(decoder); 3395 this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3396 this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3397 this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3398 this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); 3399 this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); 3400 this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); 3401 this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); 3402 this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3403 this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); 3404 } 3405 /** 3406 * @return {ID} 3407 */ 3408 readLeftID() { 3409 return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()); 3410 } 3411 /** 3412 * @return {ID} 3413 */ 3414 readRightID() { 3415 return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()); 3416 } 3417 /** 3418 * Read the next client id. 3419 * Use this in favor of readID whenever possible to reduce the number of objects created. 3420 */ 3421 readClient() { 3422 return this.clientDecoder.read(); 3423 } 3424 /** 3425 * @return {number} info An unsigned 8-bit integer 3426 */ 3427 readInfo() { 3428 return ( 3429 /** @type {number} */ 3430 this.infoDecoder.read() 3431 ); 3432 } 3433 /** 3434 * @return {string} 3435 */ 3436 readString() { 3437 return this.stringDecoder.read(); 3438 } 3439 /** 3440 * @return {boolean} 3441 */ 3442 readParentInfo() { 3443 return this.parentInfoDecoder.read() === 1; 3444 } 3445 /** 3446 * @return {number} An unsigned 8-bit integer 3447 */ 3448 readTypeRef() { 3449 return this.typeRefDecoder.read(); 3450 } 3451 /** 3452 * Write len of a struct - well suited for Opt RLE encoder. 3453 * 3454 * @return {number} 3455 */ 3456 readLen() { 3457 return this.lenDecoder.read(); 3458 } 3459 /** 3460 * @return {any} 3461 */ 3462 readAny() { 3463 return readAny(this.restDecoder); 3464 } 3465 /** 3466 * @return {Uint8Array} 3467 */ 3468 readBuf() { 3469 return readVarUint8Array(this.restDecoder); 3470 } 3471 /** 3472 * This is mainly here for legacy purposes. 3473 * 3474 * 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. 3475 * 3476 * @return {any} 3477 */ 3478 readJSON() { 3479 return readAny(this.restDecoder); 3480 } 3481 /** 3482 * @return {string} 3483 */ 3484 readKey() { 3485 const keyClock = this.keyClockDecoder.read(); 3486 if (keyClock < this.keys.length) { 3487 return this.keys[keyClock]; 3488 } else { 3489 const key = this.stringDecoder.read(); 3490 this.keys.push(key); 3491 return key; 3492 } 3493 } 3494 }; 3495 var DSEncoderV1 = class { 3496 constructor() { 3497 this.restEncoder = createEncoder(); 3498 } 3499 toUint8Array() { 3500 return toUint8Array(this.restEncoder); 3501 } 3502 resetDsCurVal() { 3503 } 3504 /** 3505 * @param {number} clock 3506 */ 3507 writeDsClock(clock) { 3508 writeVarUint(this.restEncoder, clock); 3509 } 3510 /** 3511 * @param {number} len 3512 */ 3513 writeDsLen(len) { 3514 writeVarUint(this.restEncoder, len); 3515 } 3516 }; 3517 var UpdateEncoderV1 = class extends DSEncoderV1 { 3518 /** 3519 * @param {ID} id 3520 */ 3521 writeLeftID(id2) { 3522 writeVarUint(this.restEncoder, id2.client); 3523 writeVarUint(this.restEncoder, id2.clock); 3524 } 3525 /** 3526 * @param {ID} id 3527 */ 3528 writeRightID(id2) { 3529 writeVarUint(this.restEncoder, id2.client); 3530 writeVarUint(this.restEncoder, id2.clock); 3531 } 3532 /** 3533 * Use writeClient and writeClock instead of writeID if possible. 3534 * @param {number} client 3535 */ 3536 writeClient(client) { 3537 writeVarUint(this.restEncoder, client); 3538 } 3539 /** 3540 * @param {number} info An unsigned 8-bit integer 3541 */ 3542 writeInfo(info) { 3543 writeUint8(this.restEncoder, info); 3544 } 3545 /** 3546 * @param {string} s 3547 */ 3548 writeString(s) { 3549 writeVarString(this.restEncoder, s); 3550 } 3551 /** 3552 * @param {boolean} isYKey 3553 */ 3554 writeParentInfo(isYKey) { 3555 writeVarUint(this.restEncoder, isYKey ? 1 : 0); 3556 } 3557 /** 3558 * @param {number} info An unsigned 8-bit integer 3559 */ 3560 writeTypeRef(info) { 3561 writeVarUint(this.restEncoder, info); 3562 } 3563 /** 3564 * Write len of a struct - well suited for Opt RLE encoder. 3565 * 3566 * @param {number} len 3567 */ 3568 writeLen(len) { 3569 writeVarUint(this.restEncoder, len); 3570 } 3571 /** 3572 * @param {any} any 3573 */ 3574 writeAny(any2) { 3575 writeAny(this.restEncoder, any2); 3576 } 3577 /** 3578 * @param {Uint8Array} buf 3579 */ 3580 writeBuf(buf) { 3581 writeVarUint8Array(this.restEncoder, buf); 3582 } 3583 /** 3584 * @param {any} embed 3585 */ 3586 writeJSON(embed) { 3587 writeVarString(this.restEncoder, JSON.stringify(embed)); 3588 } 3589 /** 3590 * @param {string} key 3591 */ 3592 writeKey(key) { 3593 writeVarString(this.restEncoder, key); 3594 } 3595 }; 3596 var DSEncoderV2 = class { 3597 constructor() { 3598 this.restEncoder = createEncoder(); 3599 this.dsCurrVal = 0; 3600 } 3601 toUint8Array() { 3602 return toUint8Array(this.restEncoder); 3603 } 3604 resetDsCurVal() { 3605 this.dsCurrVal = 0; 3606 } 3607 /** 3608 * @param {number} clock 3609 */ 3610 writeDsClock(clock) { 3611 const diff = clock - this.dsCurrVal; 3612 this.dsCurrVal = clock; 3613 writeVarUint(this.restEncoder, diff); 3614 } 3615 /** 3616 * @param {number} len 3617 */ 3618 writeDsLen(len) { 3619 if (len === 0) { 3620 unexpectedCase(); 3621 } 3622 writeVarUint(this.restEncoder, len - 1); 3623 this.dsCurrVal += len; 3624 } 3625 }; 3626 var UpdateEncoderV2 = class extends DSEncoderV2 { 3627 constructor() { 3628 super(); 3629 this.keyMap = /* @__PURE__ */ new Map(); 3630 this.keyClock = 0; 3631 this.keyClockEncoder = new IntDiffOptRleEncoder(); 3632 this.clientEncoder = new UintOptRleEncoder(); 3633 this.leftClockEncoder = new IntDiffOptRleEncoder(); 3634 this.rightClockEncoder = new IntDiffOptRleEncoder(); 3635 this.infoEncoder = new RleEncoder(writeUint8); 3636 this.stringEncoder = new StringEncoder(); 3637 this.parentInfoEncoder = new RleEncoder(writeUint8); 3638 this.typeRefEncoder = new UintOptRleEncoder(); 3639 this.lenEncoder = new UintOptRleEncoder(); 3640 } 3641 toUint8Array() { 3642 const encoder = createEncoder(); 3643 writeVarUint(encoder, 0); 3644 writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); 3645 writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); 3646 writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); 3647 writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); 3648 writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); 3649 writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); 3650 writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); 3651 writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); 3652 writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); 3653 writeUint8Array(encoder, toUint8Array(this.restEncoder)); 3654 return toUint8Array(encoder); 3655 } 3656 /** 3657 * @param {ID} id 3658 */ 3659 writeLeftID(id2) { 3660 this.clientEncoder.write(id2.client); 3661 this.leftClockEncoder.write(id2.clock); 3662 } 3663 /** 3664 * @param {ID} id 3665 */ 3666 writeRightID(id2) { 3667 this.clientEncoder.write(id2.client); 3668 this.rightClockEncoder.write(id2.clock); 3669 } 3670 /** 3671 * @param {number} client 3672 */ 3673 writeClient(client) { 3674 this.clientEncoder.write(client); 3675 } 3676 /** 3677 * @param {number} info An unsigned 8-bit integer 3678 */ 3679 writeInfo(info) { 3680 this.infoEncoder.write(info); 3681 } 3682 /** 3683 * @param {string} s 3684 */ 3685 writeString(s) { 3686 this.stringEncoder.write(s); 3687 } 3688 /** 3689 * @param {boolean} isYKey 3690 */ 3691 writeParentInfo(isYKey) { 3692 this.parentInfoEncoder.write(isYKey ? 1 : 0); 3693 } 3694 /** 3695 * @param {number} info An unsigned 8-bit integer 3696 */ 3697 writeTypeRef(info) { 3698 this.typeRefEncoder.write(info); 3699 } 3700 /** 3701 * Write len of a struct - well suited for Opt RLE encoder. 3702 * 3703 * @param {number} len 3704 */ 3705 writeLen(len) { 3706 this.lenEncoder.write(len); 3707 } 3708 /** 3709 * @param {any} any 3710 */ 3711 writeAny(any2) { 3712 writeAny(this.restEncoder, any2); 3713 } 3714 /** 3715 * @param {Uint8Array} buf 3716 */ 3717 writeBuf(buf) { 3718 writeVarUint8Array(this.restEncoder, buf); 3719 } 3720 /** 3721 * This is mainly here for legacy purposes. 3722 * 3723 * 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. 3724 * 3725 * @param {any} embed 3726 */ 3727 writeJSON(embed) { 3728 writeAny(this.restEncoder, embed); 3729 } 3730 /** 3731 * Property keys are often reused. For example, in y-prosemirror the key `bold` might 3732 * occur very often. For a 3d application, the key `position` might occur very often. 3733 * 3734 * We cache these keys in a Map and refer to them via a unique number. 3735 * 3736 * @param {string} key 3737 */ 3738 writeKey(key) { 3739 const clock = this.keyMap.get(key); 3740 if (clock === void 0) { 3741 this.keyClockEncoder.write(this.keyClock++); 3742 this.stringEncoder.write(key); 3743 } else { 3744 this.keyClockEncoder.write(clock); 3745 } 3746 } 3747 }; 3748 var writeStructs = (encoder, structs, client, clock) => { 3749 clock = max(clock, structs[0].id.clock); 3750 const startNewStructs = findIndexSS(structs, clock); 3751 writeVarUint(encoder.restEncoder, structs.length - startNewStructs); 3752 encoder.writeClient(client); 3753 writeVarUint(encoder.restEncoder, clock); 3754 const firstStruct = structs[startNewStructs]; 3755 firstStruct.write(encoder, clock - firstStruct.id.clock); 3756 for (let i = startNewStructs + 1; i < structs.length; i++) { 3757 structs[i].write(encoder, 0); 3758 } 3759 }; 3760 var writeClientsStructs = (encoder, store2, _sm) => { 3761 const sm = /* @__PURE__ */ new Map(); 3762 _sm.forEach((clock, client) => { 3763 if (getState(store2, client) > clock) { 3764 sm.set(client, clock); 3765 } 3766 }); 3767 getStateVector(store2).forEach((_clock, client) => { 3768 if (!_sm.has(client)) { 3769 sm.set(client, 0); 3770 } 3771 }); 3772 writeVarUint(encoder.restEncoder, sm.size); 3773 from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { 3774 writeStructs( 3775 encoder, 3776 /** @type {Array<GC|Item>} */ 3777 store2.clients.get(client), 3778 client, 3779 clock 3780 ); 3781 }); 3782 }; 3783 var readClientsStructRefs = (decoder, doc2) => { 3784 const clientRefs = create(); 3785 const numOfStateUpdates = readVarUint(decoder.restDecoder); 3786 for (let i = 0; i < numOfStateUpdates; i++) { 3787 const numberOfStructs = readVarUint(decoder.restDecoder); 3788 const refs = new Array(numberOfStructs); 3789 const client = decoder.readClient(); 3790 let clock = readVarUint(decoder.restDecoder); 3791 clientRefs.set(client, { i: 0, refs }); 3792 for (let i2 = 0; i2 < numberOfStructs; i2++) { 3793 const info = decoder.readInfo(); 3794 switch (BITS5 & info) { 3795 case 0: { 3796 const len = decoder.readLen(); 3797 refs[i2] = new GC(createID(client, clock), len); 3798 clock += len; 3799 break; 3800 } 3801 case 10: { 3802 const len = readVarUint(decoder.restDecoder); 3803 refs[i2] = new Skip(createID(client, clock), len); 3804 clock += len; 3805 break; 3806 } 3807 default: { 3808 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; 3809 const struct = new Item( 3810 createID(client, clock), 3811 null, 3812 // left 3813 (info & BIT8) === BIT8 ? decoder.readLeftID() : null, 3814 // origin 3815 null, 3816 // right 3817 (info & BIT7) === BIT7 ? decoder.readRightID() : null, 3818 // right origin 3819 cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null, 3820 // parent 3821 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, 3822 // parentSub 3823 readItemContent(decoder, info) 3824 // item content 3825 ); 3826 refs[i2] = struct; 3827 clock += struct.length; 3828 } 3829 } 3830 } 3831 } 3832 return clientRefs; 3833 }; 3834 var integrateStructs = (transaction, store2, clientsStructRefs) => { 3835 const stack = []; 3836 let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b); 3837 if (clientsStructRefsIds.length === 0) { 3838 return null; 3839 } 3840 const getNextStructTarget = () => { 3841 if (clientsStructRefsIds.length === 0) { 3842 return null; 3843 } 3844 let nextStructsTarget = ( 3845 /** @type {{i:number,refs:Array<GC|Item>}} */ 3846 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]) 3847 ); 3848 while (nextStructsTarget.refs.length === nextStructsTarget.i) { 3849 clientsStructRefsIds.pop(); 3850 if (clientsStructRefsIds.length > 0) { 3851 nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */ 3852 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]); 3853 } else { 3854 return null; 3855 } 3856 } 3857 return nextStructsTarget; 3858 }; 3859 let curStructsTarget = getNextStructTarget(); 3860 if (curStructsTarget === null) { 3861 return null; 3862 } 3863 const restStructs = new StructStore(); 3864 const missingSV = /* @__PURE__ */ new Map(); 3865 const updateMissingSv = (client, clock) => { 3866 const mclock = missingSV.get(client); 3867 if (mclock == null || mclock > clock) { 3868 missingSV.set(client, clock); 3869 } 3870 }; 3871 let stackHead = ( 3872 /** @type {any} */ 3873 curStructsTarget.refs[ 3874 /** @type {any} */ 3875 curStructsTarget.i++ 3876 ] 3877 ); 3878 const state = /* @__PURE__ */ new Map(); 3879 const addStackToRestSS = () => { 3880 for (const item of stack) { 3881 const client = item.id.client; 3882 const inapplicableItems = clientsStructRefs.get(client); 3883 if (inapplicableItems) { 3884 inapplicableItems.i--; 3885 restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i)); 3886 clientsStructRefs.delete(client); 3887 inapplicableItems.i = 0; 3888 inapplicableItems.refs = []; 3889 } else { 3890 restStructs.clients.set(client, [item]); 3891 } 3892 clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client); 3893 } 3894 stack.length = 0; 3895 }; 3896 while (true) { 3897 if (stackHead.constructor !== Skip) { 3898 const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store2, stackHead.id.client)); 3899 const offset = localClock - stackHead.id.clock; 3900 if (offset < 0) { 3901 stack.push(stackHead); 3902 updateMissingSv(stackHead.id.client, stackHead.id.clock - 1); 3903 addStackToRestSS(); 3904 } else { 3905 const missing = stackHead.getMissing(transaction, store2); 3906 if (missing !== null) { 3907 stack.push(stackHead); 3908 const structRefs = clientsStructRefs.get( 3909 /** @type {number} */ 3910 missing 3911 ) || { refs: [], i: 0 }; 3912 if (structRefs.refs.length === structRefs.i) { 3913 updateMissingSv( 3914 /** @type {number} */ 3915 missing, 3916 getState(store2, missing) 3917 ); 3918 addStackToRestSS(); 3919 } else { 3920 stackHead = structRefs.refs[structRefs.i++]; 3921 continue; 3922 } 3923 } else if (offset === 0 || offset < stackHead.length) { 3924 stackHead.integrate(transaction, offset); 3925 state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); 3926 } 3927 } 3928 } 3929 if (stack.length > 0) { 3930 stackHead = /** @type {GC|Item} */ 3931 stack.pop(); 3932 } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { 3933 stackHead = /** @type {GC|Item} */ 3934 curStructsTarget.refs[curStructsTarget.i++]; 3935 } else { 3936 curStructsTarget = getNextStructTarget(); 3937 if (curStructsTarget === null) { 3938 break; 3939 } else { 3940 stackHead = /** @type {GC|Item} */ 3941 curStructsTarget.refs[curStructsTarget.i++]; 3942 } 3943 } 3944 } 3945 if (restStructs.clients.size > 0) { 3946 const encoder = new UpdateEncoderV2(); 3947 writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map()); 3948 writeVarUint(encoder.restEncoder, 0); 3949 return { missing: missingSV, update: encoder.toUint8Array() }; 3950 } 3951 return null; 3952 }; 3953 var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); 3954 var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => { 3955 transaction.local = false; 3956 let retry = false; 3957 const doc2 = transaction.doc; 3958 const store2 = doc2.store; 3959 const ss = readClientsStructRefs(structDecoder, doc2); 3960 const restStructs = integrateStructs(transaction, store2, ss); 3961 const pending = store2.pendingStructs; 3962 if (pending) { 3963 for (const [client, clock] of pending.missing) { 3964 if (clock < getState(store2, client)) { 3965 retry = true; 3966 break; 3967 } 3968 } 3969 if (restStructs) { 3970 for (const [client, clock] of restStructs.missing) { 3971 const mclock = pending.missing.get(client); 3972 if (mclock == null || mclock > clock) { 3973 pending.missing.set(client, clock); 3974 } 3975 } 3976 pending.update = mergeUpdatesV2([pending.update, restStructs.update]); 3977 } 3978 } else { 3979 store2.pendingStructs = restStructs; 3980 } 3981 const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store2); 3982 if (store2.pendingDs) { 3983 const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store2.pendingDs)); 3984 readVarUint(pendingDSUpdate.restDecoder); 3985 const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store2); 3986 if (dsRest && dsRest2) { 3987 store2.pendingDs = mergeUpdatesV2([dsRest, dsRest2]); 3988 } else { 3989 store2.pendingDs = dsRest || dsRest2; 3990 } 3991 } else { 3992 store2.pendingDs = dsRest; 3993 } 3994 if (retry) { 3995 const update = ( 3996 /** @type {{update: Uint8Array}} */ 3997 store2.pendingStructs.update 3998 ); 3999 store2.pendingStructs = null; 4000 applyUpdateV2(transaction.doc, update); 4001 } 4002 }, transactionOrigin, false); 4003 var readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder)); 4004 var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { 4005 const decoder = createDecoder(update); 4006 readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); 4007 }; 4008 var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1); 4009 var writeStateAsUpdate = (encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => { 4010 writeClientsStructs(encoder, doc2.store, targetStateVector); 4011 writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store)); 4012 }; 4013 var encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => { 4014 const targetStateVector = decodeStateVector(encodedTargetStateVector); 4015 writeStateAsUpdate(encoder, doc2, targetStateVector); 4016 const updates = [encoder.toUint8Array()]; 4017 if (doc2.store.pendingDs) { 4018 updates.push(doc2.store.pendingDs); 4019 } 4020 if (doc2.store.pendingStructs) { 4021 updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector)); 4022 } 4023 if (updates.length > 1) { 4024 if (encoder.constructor === UpdateEncoderV1) { 4025 return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update))); 4026 } else if (encoder.constructor === UpdateEncoderV2) { 4027 return mergeUpdatesV2(updates); 4028 } 4029 } 4030 return updates[0]; 4031 }; 4032 var encodeStateAsUpdate = (doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1()); 4033 var readStateVector = (decoder) => { 4034 const ss = /* @__PURE__ */ new Map(); 4035 const ssLength = readVarUint(decoder.restDecoder); 4036 for (let i = 0; i < ssLength; i++) { 4037 const client = readVarUint(decoder.restDecoder); 4038 const clock = readVarUint(decoder.restDecoder); 4039 ss.set(client, clock); 4040 } 4041 return ss; 4042 }; 4043 var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))); 4044 var writeStateVector = (encoder, sv) => { 4045 writeVarUint(encoder.restEncoder, sv.size); 4046 from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { 4047 writeVarUint(encoder.restEncoder, client); 4048 writeVarUint(encoder.restEncoder, clock); 4049 }); 4050 return encoder; 4051 }; 4052 var writeDocumentStateVector = (encoder, doc2) => writeStateVector(encoder, getStateVector(doc2.store)); 4053 var encodeStateVectorV2 = (doc2, encoder = new DSEncoderV2()) => { 4054 if (doc2 instanceof Map) { 4055 writeStateVector(encoder, doc2); 4056 } else { 4057 writeDocumentStateVector(encoder, doc2); 4058 } 4059 return encoder.toUint8Array(); 4060 }; 4061 var encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1()); 4062 var EventHandler = class { 4063 constructor() { 4064 this.l = []; 4065 } 4066 }; 4067 var createEventHandler = () => new EventHandler(); 4068 var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f); 4069 var removeEventHandlerListener = (eventHandler, f) => { 4070 const l = eventHandler.l; 4071 const len = l.length; 4072 eventHandler.l = l.filter((g) => f !== g); 4073 if (len === eventHandler.l.length) { 4074 console.error("[yjs] Tried to remove event handler that doesn't exist."); 4075 } 4076 }; 4077 var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]); 4078 var ID = class { 4079 /** 4080 * @param {number} client client id 4081 * @param {number} clock unique per client id, continuous number 4082 */ 4083 constructor(client, clock) { 4084 this.client = client; 4085 this.clock = clock; 4086 } 4087 }; 4088 var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock; 4089 var createID = (client, clock) => new ID(client, clock); 4090 var writeID = (encoder, id2) => { 4091 writeVarUint(encoder, id2.client); 4092 writeVarUint(encoder, id2.clock); 4093 }; 4094 var readID = (decoder) => createID(readVarUint(decoder), readVarUint(decoder)); 4095 var findRootTypeKey = (type) => { 4096 for (const [key, value] of type.doc.share.entries()) { 4097 if (value === type) { 4098 return key; 4099 } 4100 } 4101 throw unexpectedCase(); 4102 }; 4103 var isParentOf = (parent, child) => { 4104 while (child !== null) { 4105 if (child.parent === parent) { 4106 return true; 4107 } 4108 child = /** @type {AbstractType<any>} */ 4109 child.parent._item; 4110 } 4111 return false; 4112 }; 4113 var logType = (type) => { 4114 const res = []; 4115 let n = type._start; 4116 while (n) { 4117 res.push(n); 4118 n = n.right; 4119 } 4120 console.log("Children: ", res); 4121 console.log("Children content: ", res.filter((m) => !m.deleted).map((m) => m.content)); 4122 }; 4123 var PermanentUserData = class { 4124 /** 4125 * @param {Doc} doc 4126 * @param {YMap<any>} [storeType] 4127 */ 4128 constructor(doc2, storeType = doc2.getMap("users")) { 4129 const dss = /* @__PURE__ */ new Map(); 4130 this.yusers = storeType; 4131 this.doc = doc2; 4132 this.clients = /* @__PURE__ */ new Map(); 4133 this.dss = dss; 4134 const initUser = (user, userDescription) => { 4135 const ds = user.get("ds"); 4136 const ids = user.get("ids"); 4137 const addClientId = ( 4138 /** @param {number} clientid */ 4139 (clientid) => this.clients.set(clientid, userDescription) 4140 ); 4141 ds.observe( 4142 /** @param {YArrayEvent<any>} event */ 4143 (event) => { 4144 event.changes.added.forEach((item) => { 4145 item.content.getContent().forEach((encodedDs) => { 4146 if (encodedDs instanceof Uint8Array) { 4147 this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))])); 4148 } 4149 }); 4150 }); 4151 } 4152 ); 4153 this.dss.set(userDescription, mergeDeleteSets(ds.map((encodedDs) => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))))); 4154 ids.observe( 4155 /** @param {YArrayEvent<any>} event */ 4156 (event) => event.changes.added.forEach((item) => item.content.getContent().forEach(addClientId)) 4157 ); 4158 ids.forEach(addClientId); 4159 }; 4160 storeType.observe((event) => { 4161 event.keysChanged.forEach( 4162 (userDescription) => initUser(storeType.get(userDescription), userDescription) 4163 ); 4164 }); 4165 storeType.forEach(initUser); 4166 } 4167 /** 4168 * @param {Doc} doc 4169 * @param {number} clientid 4170 * @param {string} userDescription 4171 * @param {Object} conf 4172 * @param {function(Transaction, DeleteSet):boolean} [conf.filter] 4173 */ 4174 setUserMapping(doc2, clientid, userDescription, { filter = () => true } = {}) { 4175 const users2 = this.yusers; 4176 let user = users2.get(userDescription); 4177 if (!user) { 4178 user = new YMap(); 4179 user.set("ids", new YArray()); 4180 user.set("ds", new YArray()); 4181 users2.set(userDescription, user); 4182 } 4183 user.get("ids").push([clientid]); 4184 users2.observe((_event) => { 4185 setTimeout(() => { 4186 const userOverwrite = users2.get(userDescription); 4187 if (userOverwrite !== user) { 4188 user = userOverwrite; 4189 this.clients.forEach((_userDescription, clientid2) => { 4190 if (userDescription === _userDescription) { 4191 user.get("ids").push([clientid2]); 4192 } 4193 }); 4194 const encoder = new DSEncoderV1(); 4195 const ds = this.dss.get(userDescription); 4196 if (ds) { 4197 writeDeleteSet(encoder, ds); 4198 user.get("ds").push([encoder.toUint8Array()]); 4199 } 4200 } 4201 }, 0); 4202 }); 4203 doc2.on( 4204 "afterTransaction", 4205 /** @param {Transaction} transaction */ 4206 (transaction) => { 4207 setTimeout(() => { 4208 const yds = user.get("ds"); 4209 const ds = transaction.deleteSet; 4210 if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) { 4211 const encoder = new DSEncoderV1(); 4212 writeDeleteSet(encoder, ds); 4213 yds.push([encoder.toUint8Array()]); 4214 } 4215 }); 4216 } 4217 ); 4218 } 4219 /** 4220 * @param {number} clientid 4221 * @return {any} 4222 */ 4223 getUserByClientId(clientid) { 4224 return this.clients.get(clientid) || null; 4225 } 4226 /** 4227 * @param {ID} id 4228 * @return {string | null} 4229 */ 4230 getUserByDeletedId(id2) { 4231 for (const [userDescription, ds] of this.dss.entries()) { 4232 if (isDeleted(ds, id2)) { 4233 return userDescription; 4234 } 4235 } 4236 return null; 4237 } 4238 }; 4239 var RelativePosition = class { 4240 /** 4241 * @param {ID|null} type 4242 * @param {string|null} tname 4243 * @param {ID|null} item 4244 * @param {number} assoc 4245 */ 4246 constructor(type, tname, item, assoc = 0) { 4247 this.type = type; 4248 this.tname = tname; 4249 this.item = item; 4250 this.assoc = assoc; 4251 } 4252 }; 4253 var relativePositionToJSON = (rpos) => { 4254 const json = {}; 4255 if (rpos.type) { 4256 json.type = rpos.type; 4257 } 4258 if (rpos.tname) { 4259 json.tname = rpos.tname; 4260 } 4261 if (rpos.item) { 4262 json.item = rpos.item; 4263 } 4264 if (rpos.assoc != null) { 4265 json.assoc = rpos.assoc; 4266 } 4267 return json; 4268 }; 4269 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); 4270 var AbsolutePosition = class { 4271 /** 4272 * @param {AbstractType<any>} type 4273 * @param {number} index 4274 * @param {number} [assoc] 4275 */ 4276 constructor(type, index, assoc = 0) { 4277 this.type = type; 4278 this.index = index; 4279 this.assoc = assoc; 4280 } 4281 }; 4282 var createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc); 4283 var createRelativePosition = (type, item, assoc) => { 4284 let typeid = null; 4285 let tname = null; 4286 if (type._item === null) { 4287 tname = findRootTypeKey(type); 4288 } else { 4289 typeid = createID(type._item.id.client, type._item.id.clock); 4290 } 4291 return new RelativePosition(typeid, tname, item, assoc); 4292 }; 4293 var createRelativePositionFromTypeIndex = (type, index, assoc = 0) => { 4294 let t = type._start; 4295 if (assoc < 0) { 4296 if (index === 0) { 4297 return createRelativePosition(type, null, assoc); 4298 } 4299 index--; 4300 } 4301 while (t !== null) { 4302 if (!t.deleted && t.countable) { 4303 if (t.length > index) { 4304 return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc); 4305 } 4306 index -= t.length; 4307 } 4308 if (t.right === null && assoc < 0) { 4309 return createRelativePosition(type, t.lastId, assoc); 4310 } 4311 t = t.right; 4312 } 4313 return createRelativePosition(type, null, assoc); 4314 }; 4315 var writeRelativePosition = (encoder, rpos) => { 4316 const { type, tname, item, assoc } = rpos; 4317 if (item !== null) { 4318 writeVarUint(encoder, 0); 4319 writeID(encoder, item); 4320 } else if (tname !== null) { 4321 writeUint8(encoder, 1); 4322 writeVarString(encoder, tname); 4323 } else if (type !== null) { 4324 writeUint8(encoder, 2); 4325 writeID(encoder, type); 4326 } else { 4327 throw unexpectedCase(); 4328 } 4329 writeVarInt(encoder, assoc); 4330 return encoder; 4331 }; 4332 var encodeRelativePosition = (rpos) => { 4333 const encoder = createEncoder(); 4334 writeRelativePosition(encoder, rpos); 4335 return toUint8Array(encoder); 4336 }; 4337 var readRelativePosition = (decoder) => { 4338 let type = null; 4339 let tname = null; 4340 let itemID = null; 4341 switch (readVarUint(decoder)) { 4342 case 0: 4343 itemID = readID(decoder); 4344 break; 4345 case 1: 4346 tname = readVarString(decoder); 4347 break; 4348 case 2: { 4349 type = readID(decoder); 4350 } 4351 } 4352 const assoc = hasContent(decoder) ? readVarInt(decoder) : 0; 4353 return new RelativePosition(type, tname, itemID, assoc); 4354 }; 4355 var decodeRelativePosition = (uint8Array) => readRelativePosition(createDecoder(uint8Array)); 4356 var getItemWithOffset = (store2, id2) => { 4357 const item = getItem(store2, id2); 4358 const diff = id2.clock - item.id.clock; 4359 return { 4360 item, 4361 diff 4362 }; 4363 }; 4364 var createAbsolutePositionFromRelativePosition = (rpos, doc2, followUndoneDeletions = true) => { 4365 const store2 = doc2.store; 4366 const rightID = rpos.item; 4367 const typeID = rpos.type; 4368 const tname = rpos.tname; 4369 const assoc = rpos.assoc; 4370 let type = null; 4371 let index = 0; 4372 if (rightID !== null) { 4373 if (getState(store2, rightID.client) <= rightID.clock) { 4374 return null; 4375 } 4376 const res = followUndoneDeletions ? followRedone(store2, rightID) : getItemWithOffset(store2, rightID); 4377 const right = res.item; 4378 if (!(right instanceof Item)) { 4379 return null; 4380 } 4381 type = /** @type {AbstractType<any>} */ 4382 right.parent; 4383 if (type._item === null || !type._item.deleted) { 4384 index = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1); 4385 let n = right.left; 4386 while (n !== null) { 4387 if (!n.deleted && n.countable) { 4388 index += n.length; 4389 } 4390 n = n.left; 4391 } 4392 } 4393 } else { 4394 if (tname !== null) { 4395 type = doc2.get(tname); 4396 } else if (typeID !== null) { 4397 if (getState(store2, typeID.client) <= typeID.clock) { 4398 return null; 4399 } 4400 const { item } = followUndoneDeletions ? followRedone(store2, typeID) : { item: getItem(store2, typeID) }; 4401 if (item instanceof Item && item.content instanceof ContentType) { 4402 type = item.content.type; 4403 } else { 4404 return null; 4405 } 4406 } else { 4407 throw unexpectedCase(); 4408 } 4409 if (assoc >= 0) { 4410 index = type._length; 4411 } else { 4412 index = 0; 4413 } 4414 } 4415 return createAbsolutePosition(type, index, rpos.assoc); 4416 }; 4417 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; 4418 var Snapshot = class { 4419 /** 4420 * @param {DeleteSet} ds 4421 * @param {Map<number,number>} sv state map 4422 */ 4423 constructor(ds, sv) { 4424 this.ds = ds; 4425 this.sv = sv; 4426 } 4427 }; 4428 var equalSnapshots = (snap1, snap2) => { 4429 const ds1 = snap1.ds.clients; 4430 const ds2 = snap2.ds.clients; 4431 const sv1 = snap1.sv; 4432 const sv2 = snap2.sv; 4433 if (sv1.size !== sv2.size || ds1.size !== ds2.size) { 4434 return false; 4435 } 4436 for (const [key, value] of sv1.entries()) { 4437 if (sv2.get(key) !== value) { 4438 return false; 4439 } 4440 } 4441 for (const [client, dsitems1] of ds1.entries()) { 4442 const dsitems2 = ds2.get(client) || []; 4443 if (dsitems1.length !== dsitems2.length) { 4444 return false; 4445 } 4446 for (let i = 0; i < dsitems1.length; i++) { 4447 const dsitem1 = dsitems1[i]; 4448 const dsitem2 = dsitems2[i]; 4449 if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) { 4450 return false; 4451 } 4452 } 4453 } 4454 return true; 4455 }; 4456 var encodeSnapshotV2 = (snapshot2, encoder = new DSEncoderV2()) => { 4457 writeDeleteSet(encoder, snapshot2.ds); 4458 writeStateVector(encoder, snapshot2.sv); 4459 return encoder.toUint8Array(); 4460 }; 4461 var encodeSnapshot = (snapshot2) => encodeSnapshotV2(snapshot2, new DSEncoderV1()); 4462 var decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => { 4463 return new Snapshot(readDeleteSet(decoder), readStateVector(decoder)); 4464 }; 4465 var decodeSnapshot = (buf) => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf))); 4466 var createSnapshot = (ds, sm) => new Snapshot(ds, sm); 4467 var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map()); 4468 var snapshot = (doc2) => createSnapshot(createDeleteSetFromStructStore(doc2.store), getStateVector(doc2.store)); 4469 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); 4470 var splitSnapshotAffectedStructs = (transaction, snapshot2) => { 4471 const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2); 4472 const store2 = transaction.doc.store; 4473 if (!meta.has(snapshot2)) { 4474 snapshot2.sv.forEach((clock, client) => { 4475 if (clock < getState(store2, client)) { 4476 getItemCleanStart(transaction, createID(client, clock)); 4477 } 4478 }); 4479 iterateDeletedStructs(transaction, snapshot2.ds, (_item) => { 4480 }); 4481 meta.add(snapshot2); 4482 } 4483 }; 4484 var createDocFromSnapshot = (originDoc, snapshot2, newDoc = new Doc()) => { 4485 if (originDoc.gc) { 4486 throw new Error("Garbage-collection must be disabled in `originDoc`!"); 4487 } 4488 const { sv, ds } = snapshot2; 4489 const encoder = new UpdateEncoderV2(); 4490 originDoc.transact((transaction) => { 4491 let size2 = 0; 4492 sv.forEach((clock) => { 4493 if (clock > 0) { 4494 size2++; 4495 } 4496 }); 4497 writeVarUint(encoder.restEncoder, size2); 4498 for (const [client, clock] of sv) { 4499 if (clock === 0) { 4500 continue; 4501 } 4502 if (clock < getState(originDoc.store, client)) { 4503 getItemCleanStart(transaction, createID(client, clock)); 4504 } 4505 const structs = originDoc.store.clients.get(client) || []; 4506 const lastStructIndex = findIndexSS(structs, clock - 1); 4507 writeVarUint(encoder.restEncoder, lastStructIndex + 1); 4508 encoder.writeClient(client); 4509 writeVarUint(encoder.restEncoder, 0); 4510 for (let i = 0; i <= lastStructIndex; i++) { 4511 structs[i].write(encoder, 0); 4512 } 4513 } 4514 writeDeleteSet(encoder, ds); 4515 }); 4516 applyUpdateV2(newDoc, encoder.toUint8Array(), "snapshot"); 4517 return newDoc; 4518 }; 4519 var snapshotContainsUpdateV2 = (snapshot2, update, YDecoder = UpdateDecoderV2) => { 4520 const updateDecoder = new YDecoder(createDecoder(update)); 4521 const lazyDecoder = new LazyStructReader(updateDecoder, false); 4522 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 4523 if ((snapshot2.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) { 4524 return false; 4525 } 4526 } 4527 const mergedDS = mergeDeleteSets([snapshot2.ds, readDeleteSet(updateDecoder)]); 4528 return equalDeleteSets(snapshot2.ds, mergedDS); 4529 }; 4530 var snapshotContainsUpdate = (snapshot2, update) => snapshotContainsUpdateV2(snapshot2, update, UpdateDecoderV1); 4531 var StructStore = class { 4532 constructor() { 4533 this.clients = /* @__PURE__ */ new Map(); 4534 this.pendingStructs = null; 4535 this.pendingDs = null; 4536 } 4537 }; 4538 var getStateVector = (store2) => { 4539 const sm = /* @__PURE__ */ new Map(); 4540 store2.clients.forEach((structs, client) => { 4541 const struct = structs[structs.length - 1]; 4542 sm.set(client, struct.id.clock + struct.length); 4543 }); 4544 return sm; 4545 }; 4546 var getState = (store2, client) => { 4547 const structs = store2.clients.get(client); 4548 if (structs === void 0) { 4549 return 0; 4550 } 4551 const lastStruct = structs[structs.length - 1]; 4552 return lastStruct.id.clock + lastStruct.length; 4553 }; 4554 var addStruct = (store2, struct) => { 4555 let structs = store2.clients.get(struct.id.client); 4556 if (structs === void 0) { 4557 structs = []; 4558 store2.clients.set(struct.id.client, structs); 4559 } else { 4560 const lastStruct = structs[structs.length - 1]; 4561 if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) { 4562 throw unexpectedCase(); 4563 } 4564 } 4565 structs.push(struct); 4566 }; 4567 var findIndexSS = (structs, clock) => { 4568 let left = 0; 4569 let right = structs.length - 1; 4570 let mid = structs[right]; 4571 let midclock = mid.id.clock; 4572 if (midclock === clock) { 4573 return right; 4574 } 4575 let midindex = floor(clock / (midclock + mid.length - 1) * right); 4576 while (left <= right) { 4577 mid = structs[midindex]; 4578 midclock = mid.id.clock; 4579 if (midclock <= clock) { 4580 if (clock < midclock + mid.length) { 4581 return midindex; 4582 } 4583 left = midindex + 1; 4584 } else { 4585 right = midindex - 1; 4586 } 4587 midindex = floor((left + right) / 2); 4588 } 4589 throw unexpectedCase(); 4590 }; 4591 var find = (store2, id2) => { 4592 const structs = store2.clients.get(id2.client); 4593 return structs[findIndexSS(structs, id2.clock)]; 4594 }; 4595 var getItem = ( 4596 /** @type {function(StructStore,ID):Item} */ 4597 find 4598 ); 4599 var findIndexCleanStart = (transaction, structs, clock) => { 4600 const index = findIndexSS(structs, clock); 4601 const struct = structs[index]; 4602 if (struct.id.clock < clock && struct instanceof Item) { 4603 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); 4604 return index + 1; 4605 } 4606 return index; 4607 }; 4608 var getItemCleanStart = (transaction, id2) => { 4609 const structs = ( 4610 /** @type {Array<Item>} */ 4611 transaction.doc.store.clients.get(id2.client) 4612 ); 4613 return structs[findIndexCleanStart(transaction, structs, id2.clock)]; 4614 }; 4615 var getItemCleanEnd = (transaction, store2, id2) => { 4616 const structs = store2.clients.get(id2.client); 4617 const index = findIndexSS(structs, id2.clock); 4618 const struct = structs[index]; 4619 if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) { 4620 structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1)); 4621 } 4622 return struct; 4623 }; 4624 var replaceStruct = (store2, struct, newStruct) => { 4625 const structs = ( 4626 /** @type {Array<GC|Item>} */ 4627 store2.clients.get(struct.id.client) 4628 ); 4629 structs[findIndexSS(structs, struct.id.clock)] = newStruct; 4630 }; 4631 var iterateStructs = (transaction, structs, clockStart, len, f) => { 4632 if (len === 0) { 4633 return; 4634 } 4635 const clockEnd = clockStart + len; 4636 let index = findIndexCleanStart(transaction, structs, clockStart); 4637 let struct; 4638 do { 4639 struct = structs[index++]; 4640 if (clockEnd < struct.id.clock + struct.length) { 4641 findIndexCleanStart(transaction, structs, clockEnd); 4642 } 4643 f(struct); 4644 } while (index < structs.length && structs[index].id.clock < clockEnd); 4645 }; 4646 var Transaction = class { 4647 /** 4648 * @param {Doc} doc 4649 * @param {any} origin 4650 * @param {boolean} local 4651 */ 4652 constructor(doc2, origin2, local) { 4653 this.doc = doc2; 4654 this.deleteSet = new DeleteSet(); 4655 this.beforeState = getStateVector(doc2.store); 4656 this.afterState = /* @__PURE__ */ new Map(); 4657 this.changed = /* @__PURE__ */ new Map(); 4658 this.changedParentTypes = /* @__PURE__ */ new Map(); 4659 this._mergeStructs = []; 4660 this.origin = origin2; 4661 this.meta = /* @__PURE__ */ new Map(); 4662 this.local = local; 4663 this.subdocsAdded = /* @__PURE__ */ new Set(); 4664 this.subdocsRemoved = /* @__PURE__ */ new Set(); 4665 this.subdocsLoaded = /* @__PURE__ */ new Set(); 4666 this._needFormattingCleanup = false; 4667 } 4668 }; 4669 var writeUpdateMessageFromTransaction = (encoder, transaction) => { 4670 if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) { 4671 return false; 4672 } 4673 sortAndMergeDeleteSet(transaction.deleteSet); 4674 writeStructsFromTransaction(encoder, transaction); 4675 writeDeleteSet(encoder, transaction.deleteSet); 4676 return true; 4677 }; 4678 var addChangedTypeToTransaction = (transaction, type, parentSub) => { 4679 const item = type._item; 4680 if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) { 4681 setIfUndefined(transaction.changed, type, create2).add(parentSub); 4682 } 4683 }; 4684 var tryToMergeWithLefts = (structs, pos) => { 4685 let right = structs[pos]; 4686 let left = structs[pos - 1]; 4687 let i = pos; 4688 for (; i > 0; right = left, left = structs[--i - 1]) { 4689 if (left.deleted === right.deleted && left.constructor === right.constructor) { 4690 if (left.mergeWith(right)) { 4691 if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */ 4692 right.parent._map.get(right.parentSub) === right) { 4693 right.parent._map.set( 4694 right.parentSub, 4695 /** @type {Item} */ 4696 left 4697 ); 4698 } 4699 continue; 4700 } 4701 } 4702 break; 4703 } 4704 const merged = pos - i; 4705 if (merged) { 4706 structs.splice(pos + 1 - merged, merged); 4707 } 4708 return merged; 4709 }; 4710 var tryGcDeleteSet = (ds, store2, gcFilter) => { 4711 for (const [client, deleteItems] of ds.clients.entries()) { 4712 const structs = ( 4713 /** @type {Array<GC|Item>} */ 4714 store2.clients.get(client) 4715 ); 4716 for (let di = deleteItems.length - 1; di >= 0; di--) { 4717 const deleteItem = deleteItems[di]; 4718 const endDeleteItemClock = deleteItem.clock + deleteItem.len; 4719 for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) { 4720 const struct2 = structs[si]; 4721 if (deleteItem.clock + deleteItem.len <= struct2.id.clock) { 4722 break; 4723 } 4724 if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) { 4725 struct2.gc(store2, false); 4726 } 4727 } 4728 } 4729 } 4730 }; 4731 var tryMergeDeleteSet = (ds, store2) => { 4732 ds.clients.forEach((deleteItems, client) => { 4733 const structs = ( 4734 /** @type {Array<GC|Item>} */ 4735 store2.clients.get(client) 4736 ); 4737 for (let di = deleteItems.length - 1; di >= 0; di--) { 4738 const deleteItem = deleteItems[di]; 4739 const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1)); 4740 for (let si = mostRightIndexToCheck, struct = structs[si]; si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) { 4741 si -= 1 + tryToMergeWithLefts(structs, si); 4742 } 4743 } 4744 }); 4745 }; 4746 var tryGc = (ds, store2, gcFilter) => { 4747 tryGcDeleteSet(ds, store2, gcFilter); 4748 tryMergeDeleteSet(ds, store2); 4749 }; 4750 var cleanupTransactions = (transactionCleanups, i) => { 4751 if (i < transactionCleanups.length) { 4752 const transaction = transactionCleanups[i]; 4753 const doc2 = transaction.doc; 4754 const store2 = doc2.store; 4755 const ds = transaction.deleteSet; 4756 const mergeStructs = transaction._mergeStructs; 4757 try { 4758 sortAndMergeDeleteSet(ds); 4759 transaction.afterState = getStateVector(transaction.doc.store); 4760 doc2.emit("beforeObserverCalls", [transaction, doc2]); 4761 const fs = []; 4762 transaction.changed.forEach( 4763 (subs, itemtype) => fs.push(() => { 4764 if (itemtype._item === null || !itemtype._item.deleted) { 4765 itemtype._callObserver(transaction, subs); 4766 } 4767 }) 4768 ); 4769 fs.push(() => { 4770 transaction.changedParentTypes.forEach((events, type) => { 4771 if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) { 4772 events = events.filter( 4773 (event) => event.target._item === null || !event.target._item.deleted 4774 ); 4775 events.forEach((event) => { 4776 event.currentTarget = type; 4777 event._path = null; 4778 }); 4779 events.sort((event1, event2) => event1.path.length - event2.path.length); 4780 fs.push(() => { 4781 callEventHandlerListeners(type._dEH, events, transaction); 4782 }); 4783 } 4784 }); 4785 fs.push(() => doc2.emit("afterTransaction", [transaction, doc2])); 4786 fs.push(() => { 4787 if (transaction._needFormattingCleanup) { 4788 cleanupYTextAfterTransaction(transaction); 4789 } 4790 }); 4791 }); 4792 callAll(fs, []); 4793 } finally { 4794 if (doc2.gc) { 4795 tryGcDeleteSet(ds, store2, doc2.gcFilter); 4796 } 4797 tryMergeDeleteSet(ds, store2); 4798 transaction.afterState.forEach((clock, client) => { 4799 const beforeClock = transaction.beforeState.get(client) || 0; 4800 if (beforeClock !== clock) { 4801 const structs = ( 4802 /** @type {Array<GC|Item>} */ 4803 store2.clients.get(client) 4804 ); 4805 const firstChangePos = max(findIndexSS(structs, beforeClock), 1); 4806 for (let i2 = structs.length - 1; i2 >= firstChangePos; ) { 4807 i2 -= 1 + tryToMergeWithLefts(structs, i2); 4808 } 4809 } 4810 }); 4811 for (let i2 = mergeStructs.length - 1; i2 >= 0; i2--) { 4812 const { client, clock } = mergeStructs[i2].id; 4813 const structs = ( 4814 /** @type {Array<GC|Item>} */ 4815 store2.clients.get(client) 4816 ); 4817 const replacedStructPos = findIndexSS(structs, clock); 4818 if (replacedStructPos + 1 < structs.length) { 4819 if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) { 4820 continue; 4821 } 4822 } 4823 if (replacedStructPos > 0) { 4824 tryToMergeWithLefts(structs, replacedStructPos); 4825 } 4826 } 4827 if (!transaction.local && transaction.afterState.get(doc2.clientID) !== transaction.beforeState.get(doc2.clientID)) { 4828 print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it."); 4829 doc2.clientID = generateNewClientId(); 4830 } 4831 doc2.emit("afterTransactionCleanup", [transaction, doc2]); 4832 if (doc2._observers.has("update")) { 4833 const encoder = new UpdateEncoderV1(); 4834 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); 4835 if (hasContent2) { 4836 doc2.emit("update", [encoder.toUint8Array(), transaction.origin, doc2, transaction]); 4837 } 4838 } 4839 if (doc2._observers.has("updateV2")) { 4840 const encoder = new UpdateEncoderV2(); 4841 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction); 4842 if (hasContent2) { 4843 doc2.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc2, transaction]); 4844 } 4845 } 4846 const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction; 4847 if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) { 4848 subdocsAdded.forEach((subdoc) => { 4849 subdoc.clientID = doc2.clientID; 4850 if (subdoc.collectionid == null) { 4851 subdoc.collectionid = doc2.collectionid; 4852 } 4853 doc2.subdocs.add(subdoc); 4854 }); 4855 subdocsRemoved.forEach((subdoc) => doc2.subdocs.delete(subdoc)); 4856 doc2.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc2, transaction]); 4857 subdocsRemoved.forEach((subdoc) => subdoc.destroy()); 4858 } 4859 if (transactionCleanups.length <= i + 1) { 4860 doc2._transactionCleanups = []; 4861 doc2.emit("afterAllTransactions", [doc2, transactionCleanups]); 4862 } else { 4863 cleanupTransactions(transactionCleanups, i + 1); 4864 } 4865 } 4866 } 4867 }; 4868 var transact = (doc2, f, origin2 = null, local = true) => { 4869 const transactionCleanups = doc2._transactionCleanups; 4870 let initialCall = false; 4871 let result = null; 4872 if (doc2._transaction === null) { 4873 initialCall = true; 4874 doc2._transaction = new Transaction(doc2, origin2, local); 4875 transactionCleanups.push(doc2._transaction); 4876 if (transactionCleanups.length === 1) { 4877 doc2.emit("beforeAllTransactions", [doc2]); 4878 } 4879 doc2.emit("beforeTransaction", [doc2._transaction, doc2]); 4880 } 4881 try { 4882 result = f(doc2._transaction); 4883 } finally { 4884 if (initialCall) { 4885 const finishCleanup = doc2._transaction === transactionCleanups[0]; 4886 doc2._transaction = null; 4887 if (finishCleanup) { 4888 cleanupTransactions(transactionCleanups, 0); 4889 } 4890 } 4891 } 4892 return result; 4893 }; 4894 var StackItem = class { 4895 /** 4896 * @param {DeleteSet} deletions 4897 * @param {DeleteSet} insertions 4898 */ 4899 constructor(deletions, insertions) { 4900 this.insertions = insertions; 4901 this.deletions = deletions; 4902 this.meta = /* @__PURE__ */ new Map(); 4903 } 4904 }; 4905 var clearUndoManagerStackItem = (tr, um, stackItem) => { 4906 iterateDeletedStructs(tr, stackItem.deletions, (item) => { 4907 if (item instanceof Item && um.scope.some((type) => type === tr.doc || isParentOf( 4908 /** @type {AbstractType<any>} */ 4909 type, 4910 item 4911 ))) { 4912 keepItem(item, false); 4913 } 4914 }); 4915 }; 4916 var popStackItem = (undoManager2, stack, eventType) => { 4917 let _tr = null; 4918 const doc2 = undoManager2.doc; 4919 const scope = undoManager2.scope; 4920 transact(doc2, (transaction) => { 4921 while (stack.length > 0 && undoManager2.currStackItem === null) { 4922 const store2 = doc2.store; 4923 const stackItem = ( 4924 /** @type {StackItem} */ 4925 stack.pop() 4926 ); 4927 const itemsToRedo = /* @__PURE__ */ new Set(); 4928 const itemsToDelete = []; 4929 let performedChange = false; 4930 iterateDeletedStructs(transaction, stackItem.insertions, (struct) => { 4931 if (struct instanceof Item) { 4932 if (struct.redone !== null) { 4933 let { item, diff } = followRedone(store2, struct.id); 4934 if (diff > 0) { 4935 item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff)); 4936 } 4937 struct = item; 4938 } 4939 if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf( 4940 /** @type {AbstractType<any>} */ 4941 type, 4942 /** @type {Item} */ 4943 struct 4944 ))) { 4945 itemsToDelete.push(struct); 4946 } 4947 } 4948 }); 4949 iterateDeletedStructs(transaction, stackItem.deletions, (struct) => { 4950 if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf( 4951 /** @type {AbstractType<any>} */ 4952 type, 4953 struct 4954 )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval. 4955 !isDeleted(stackItem.insertions, struct.id)) { 4956 itemsToRedo.add(struct); 4957 } 4958 }); 4959 itemsToRedo.forEach((struct) => { 4960 performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager2.ignoreRemoteMapChanges, undoManager2) !== null || performedChange; 4961 }); 4962 for (let i = itemsToDelete.length - 1; i >= 0; i--) { 4963 const item = itemsToDelete[i]; 4964 if (undoManager2.deleteFilter(item)) { 4965 item.delete(transaction); 4966 performedChange = true; 4967 } 4968 } 4969 undoManager2.currStackItem = performedChange ? stackItem : null; 4970 } 4971 transaction.changed.forEach((subProps, type) => { 4972 if (subProps.has(null) && type._searchMarker) { 4973 type._searchMarker.length = 0; 4974 } 4975 }); 4976 _tr = transaction; 4977 }, undoManager2); 4978 const res = undoManager2.currStackItem; 4979 if (res != null) { 4980 const changedParentTypes = _tr.changedParentTypes; 4981 undoManager2.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager2 }, undoManager2]); 4982 undoManager2.currStackItem = null; 4983 } 4984 return res; 4985 }; 4986 var UndoManager = class extends ObservableV2 { 4987 /** 4988 * @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. 4989 * @param {UndoManagerOptions} options 4990 */ 4991 constructor(typeScope, { 4992 captureTimeout = 500, 4993 captureTransaction = (_tr) => true, 4994 deleteFilter = () => true, 4995 trackedOrigins = /* @__PURE__ */ new Set([null]), 4996 ignoreRemoteMapChanges = false, 4997 doc: doc2 = ( 4998 /** @type {Doc} */ 4999 isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc 5000 ) 5001 } = {}) { 5002 super(); 5003 this.scope = []; 5004 this.doc = doc2; 5005 this.addToScope(typeScope); 5006 this.deleteFilter = deleteFilter; 5007 trackedOrigins.add(this); 5008 this.trackedOrigins = trackedOrigins; 5009 this.captureTransaction = captureTransaction; 5010 this.undoStack = []; 5011 this.redoStack = []; 5012 this.undoing = false; 5013 this.redoing = false; 5014 this.currStackItem = null; 5015 this.lastChange = 0; 5016 this.ignoreRemoteMapChanges = ignoreRemoteMapChanges; 5017 this.captureTimeout = captureTimeout; 5018 this.afterTransactionHandler = (transaction) => { 5019 if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has( 5020 /** @type {AbstractType<any>} */ 5021 type 5022 ) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) { 5023 return; 5024 } 5025 const undoing = this.undoing; 5026 const redoing = this.redoing; 5027 const stack = undoing ? this.redoStack : this.undoStack; 5028 if (undoing) { 5029 this.stopCapturing(); 5030 } else if (!redoing) { 5031 this.clear(false, true); 5032 } 5033 const insertions = new DeleteSet(); 5034 transaction.afterState.forEach((endClock, client) => { 5035 const startClock = transaction.beforeState.get(client) || 0; 5036 const len = endClock - startClock; 5037 if (len > 0) { 5038 addToDeleteSet(insertions, client, startClock, len); 5039 } 5040 }); 5041 const now = getUnixTime(); 5042 let didAdd = false; 5043 if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) { 5044 const lastOp = stack[stack.length - 1]; 5045 lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]); 5046 lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]); 5047 } else { 5048 stack.push(new StackItem(transaction.deleteSet, insertions)); 5049 didAdd = true; 5050 } 5051 if (!undoing && !redoing) { 5052 this.lastChange = now; 5053 } 5054 iterateDeletedStructs( 5055 transaction, 5056 transaction.deleteSet, 5057 /** @param {Item|GC} item */ 5058 (item) => { 5059 if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf( 5060 /** @type {AbstractType<any>} */ 5061 type, 5062 item 5063 ))) { 5064 keepItem(item, true); 5065 } 5066 } 5067 ); 5068 const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this]; 5069 if (didAdd) { 5070 this.emit("stack-item-added", changeEvent); 5071 } else { 5072 this.emit("stack-item-updated", changeEvent); 5073 } 5074 }; 5075 this.doc.on("afterTransaction", this.afterTransactionHandler); 5076 this.doc.on("destroy", () => { 5077 this.destroy(); 5078 }); 5079 } 5080 /** 5081 * Extend the scope. 5082 * 5083 * @param {Array<AbstractType<any> | Doc> | AbstractType<any> | Doc} ytypes 5084 */ 5085 addToScope(ytypes) { 5086 const tmpSet = new Set(this.scope); 5087 ytypes = isArray(ytypes) ? ytypes : [ytypes]; 5088 ytypes.forEach((ytype) => { 5089 if (!tmpSet.has(ytype)) { 5090 tmpSet.add(ytype); 5091 if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) warn("[yjs#509] Not same Y.Doc"); 5092 this.scope.push(ytype); 5093 } 5094 }); 5095 } 5096 /** 5097 * @param {any} origin 5098 */ 5099 addTrackedOrigin(origin2) { 5100 this.trackedOrigins.add(origin2); 5101 } 5102 /** 5103 * @param {any} origin 5104 */ 5105 removeTrackedOrigin(origin2) { 5106 this.trackedOrigins.delete(origin2); 5107 } 5108 clear(clearUndoStack = true, clearRedoStack = true) { 5109 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) { 5110 this.doc.transact((tr) => { 5111 if (clearUndoStack) { 5112 this.undoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item)); 5113 this.undoStack = []; 5114 } 5115 if (clearRedoStack) { 5116 this.redoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item)); 5117 this.redoStack = []; 5118 } 5119 this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]); 5120 }); 5121 } 5122 } 5123 /** 5124 * UndoManager merges Undo-StackItem if they are created within time-gap 5125 * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next 5126 * StackItem won't be merged. 5127 * 5128 * 5129 * @example 5130 * // without stopCapturing 5131 * ytext.insert(0, 'a') 5132 * ytext.insert(1, 'b') 5133 * um.undo() 5134 * ytext.toString() // => '' (note that 'ab' was removed) 5135 * // with stopCapturing 5136 * ytext.insert(0, 'a') 5137 * um.stopCapturing() 5138 * ytext.insert(0, 'b') 5139 * um.undo() 5140 * ytext.toString() // => 'a' (note that only 'b' was removed) 5141 * 5142 */ 5143 stopCapturing() { 5144 this.lastChange = 0; 5145 } 5146 /** 5147 * Undo last changes on type. 5148 * 5149 * @return {StackItem?} Returns StackItem if a change was applied 5150 */ 5151 undo() { 5152 this.undoing = true; 5153 let res; 5154 try { 5155 res = popStackItem(this, this.undoStack, "undo"); 5156 } finally { 5157 this.undoing = false; 5158 } 5159 return res; 5160 } 5161 /** 5162 * Redo last undo operation. 5163 * 5164 * @return {StackItem?} Returns StackItem if a change was applied 5165 */ 5166 redo() { 5167 this.redoing = true; 5168 let res; 5169 try { 5170 res = popStackItem(this, this.redoStack, "redo"); 5171 } finally { 5172 this.redoing = false; 5173 } 5174 return res; 5175 } 5176 /** 5177 * Are undo steps available? 5178 * 5179 * @return {boolean} `true` if undo is possible 5180 */ 5181 canUndo() { 5182 return this.undoStack.length > 0; 5183 } 5184 /** 5185 * Are redo steps available? 5186 * 5187 * @return {boolean} `true` if redo is possible 5188 */ 5189 canRedo() { 5190 return this.redoStack.length > 0; 5191 } 5192 destroy() { 5193 this.trackedOrigins.delete(this); 5194 this.doc.off("afterTransaction", this.afterTransactionHandler); 5195 super.destroy(); 5196 } 5197 }; 5198 function* lazyStructReaderGenerator(decoder) { 5199 const numOfStateUpdates = readVarUint(decoder.restDecoder); 5200 for (let i = 0; i < numOfStateUpdates; i++) { 5201 const numberOfStructs = readVarUint(decoder.restDecoder); 5202 const client = decoder.readClient(); 5203 let clock = readVarUint(decoder.restDecoder); 5204 for (let i2 = 0; i2 < numberOfStructs; i2++) { 5205 const info = decoder.readInfo(); 5206 if (info === 10) { 5207 const len = readVarUint(decoder.restDecoder); 5208 yield new Skip(createID(client, clock), len); 5209 clock += len; 5210 } else if ((BITS5 & info) !== 0) { 5211 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; 5212 const struct = new Item( 5213 createID(client, clock), 5214 null, 5215 // left 5216 (info & BIT8) === BIT8 ? decoder.readLeftID() : null, 5217 // origin 5218 null, 5219 // right 5220 (info & BIT7) === BIT7 ? decoder.readRightID() : null, 5221 // right origin 5222 // @ts-ignore Force writing a string here. 5223 cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null, 5224 // parent 5225 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, 5226 // parentSub 5227 readItemContent(decoder, info) 5228 // item content 5229 ); 5230 yield struct; 5231 clock += struct.length; 5232 } else { 5233 const len = decoder.readLen(); 5234 yield new GC(createID(client, clock), len); 5235 clock += len; 5236 } 5237 } 5238 } 5239 } 5240 var LazyStructReader = class { 5241 /** 5242 * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder 5243 * @param {boolean} filterSkips 5244 */ 5245 constructor(decoder, filterSkips) { 5246 this.gen = lazyStructReaderGenerator(decoder); 5247 this.curr = null; 5248 this.done = false; 5249 this.filterSkips = filterSkips; 5250 this.next(); 5251 } 5252 /** 5253 * @return {Item | GC | Skip |null} 5254 */ 5255 next() { 5256 do { 5257 this.curr = this.gen.next().value || null; 5258 } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip); 5259 return this.curr; 5260 } 5261 }; 5262 var logUpdate = (update) => logUpdateV2(update, UpdateDecoderV1); 5263 var logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => { 5264 const structs = []; 5265 const updateDecoder = new YDecoder(createDecoder(update)); 5266 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5267 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5268 structs.push(curr); 5269 } 5270 print("Structs: ", structs); 5271 const ds = readDeleteSet(updateDecoder); 5272 print("DeleteSet: ", ds); 5273 }; 5274 var decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1); 5275 var decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => { 5276 const structs = []; 5277 const updateDecoder = new YDecoder(createDecoder(update)); 5278 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5279 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5280 structs.push(curr); 5281 } 5282 return { 5283 structs, 5284 ds: readDeleteSet(updateDecoder) 5285 }; 5286 }; 5287 var LazyStructWriter = class { 5288 /** 5289 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 5290 */ 5291 constructor(encoder) { 5292 this.currClient = 0; 5293 this.startClock = 0; 5294 this.written = 0; 5295 this.encoder = encoder; 5296 this.clientStructs = []; 5297 } 5298 }; 5299 var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1); 5300 var encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => { 5301 const encoder = new YEncoder(); 5302 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false); 5303 let curr = updateDecoder.curr; 5304 if (curr !== null) { 5305 let size2 = 0; 5306 let currClient = curr.id.client; 5307 let stopCounting = curr.id.clock !== 0; 5308 let currClock = stopCounting ? 0 : curr.id.clock + curr.length; 5309 for (; curr !== null; curr = updateDecoder.next()) { 5310 if (currClient !== curr.id.client) { 5311 if (currClock !== 0) { 5312 size2++; 5313 writeVarUint(encoder.restEncoder, currClient); 5314 writeVarUint(encoder.restEncoder, currClock); 5315 } 5316 currClient = curr.id.client; 5317 currClock = 0; 5318 stopCounting = curr.id.clock !== 0; 5319 } 5320 if (curr.constructor === Skip) { 5321 stopCounting = true; 5322 } 5323 if (!stopCounting) { 5324 currClock = curr.id.clock + curr.length; 5325 } 5326 } 5327 if (currClock !== 0) { 5328 size2++; 5329 writeVarUint(encoder.restEncoder, currClient); 5330 writeVarUint(encoder.restEncoder, currClock); 5331 } 5332 const enc = createEncoder(); 5333 writeVarUint(enc, size2); 5334 writeBinaryEncoder(enc, encoder.restEncoder); 5335 encoder.restEncoder = enc; 5336 return encoder.toUint8Array(); 5337 } else { 5338 writeVarUint(encoder.restEncoder, 0); 5339 return encoder.toUint8Array(); 5340 } 5341 }; 5342 var encodeStateVectorFromUpdate = (update) => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1); 5343 var parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => { 5344 const from2 = /* @__PURE__ */ new Map(); 5345 const to = /* @__PURE__ */ new Map(); 5346 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false); 5347 let curr = updateDecoder.curr; 5348 if (curr !== null) { 5349 let currClient = curr.id.client; 5350 let currClock = curr.id.clock; 5351 from2.set(currClient, currClock); 5352 for (; curr !== null; curr = updateDecoder.next()) { 5353 if (currClient !== curr.id.client) { 5354 to.set(currClient, currClock); 5355 from2.set(curr.id.client, curr.id.clock); 5356 currClient = curr.id.client; 5357 } 5358 currClock = curr.id.clock + curr.length; 5359 } 5360 to.set(currClient, currClock); 5361 } 5362 return { from: from2, to }; 5363 }; 5364 var parseUpdateMeta = (update) => parseUpdateMetaV2(update, UpdateDecoderV1); 5365 var sliceStruct = (left, diff) => { 5366 if (left.constructor === GC) { 5367 const { client, clock } = left.id; 5368 return new GC(createID(client, clock + diff), left.length - diff); 5369 } else if (left.constructor === Skip) { 5370 const { client, clock } = left.id; 5371 return new Skip(createID(client, clock + diff), left.length - diff); 5372 } else { 5373 const leftItem = ( 5374 /** @type {Item} */ 5375 left 5376 ); 5377 const { client, clock } = leftItem.id; 5378 return new Item( 5379 createID(client, clock + diff), 5380 null, 5381 createID(client, clock + diff - 1), 5382 null, 5383 leftItem.rightOrigin, 5384 leftItem.parent, 5385 leftItem.parentSub, 5386 leftItem.content.splice(diff) 5387 ); 5388 } 5389 }; 5390 var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { 5391 if (updates.length === 1) { 5392 return updates[0]; 5393 } 5394 const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update))); 5395 let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true)); 5396 let currWrite = null; 5397 const updateEncoder = new YEncoder(); 5398 const lazyStructEncoder = new LazyStructWriter(updateEncoder); 5399 while (true) { 5400 lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null); 5401 lazyStructDecoders.sort( 5402 /** @type {function(any,any):number} */ 5403 (dec1, dec2) => { 5404 if (dec1.curr.id.client === dec2.curr.id.client) { 5405 const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock; 5406 if (clockDiff === 0) { 5407 return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1; 5408 } else { 5409 return clockDiff; 5410 } 5411 } else { 5412 return dec2.curr.id.client - dec1.curr.id.client; 5413 } 5414 } 5415 ); 5416 if (lazyStructDecoders.length === 0) { 5417 break; 5418 } 5419 const currDecoder = lazyStructDecoders[0]; 5420 const firstClient = ( 5421 /** @type {Item | GC} */ 5422 currDecoder.curr.id.client 5423 ); 5424 if (currWrite !== null) { 5425 let curr = ( 5426 /** @type {Item | GC | null} */ 5427 currDecoder.curr 5428 ); 5429 let iterated = false; 5430 while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) { 5431 curr = currDecoder.next(); 5432 iterated = true; 5433 } 5434 if (curr === null || // current decoder is empty 5435 curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient` 5436 iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) { 5437 continue; 5438 } 5439 if (firstClient !== currWrite.struct.id.client) { 5440 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5441 currWrite = { struct: curr, offset: 0 }; 5442 currDecoder.next(); 5443 } else { 5444 if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) { 5445 if (currWrite.struct.constructor === Skip) { 5446 currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock; 5447 } else { 5448 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5449 const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length; 5450 const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff); 5451 currWrite = { struct, offset: 0 }; 5452 } 5453 } else { 5454 const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock; 5455 if (diff > 0) { 5456 if (currWrite.struct.constructor === Skip) { 5457 currWrite.struct.length -= diff; 5458 } else { 5459 curr = sliceStruct(curr, diff); 5460 } 5461 } 5462 if (!currWrite.struct.mergeWith( 5463 /** @type {any} */ 5464 curr 5465 )) { 5466 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5467 currWrite = { struct: curr, offset: 0 }; 5468 currDecoder.next(); 5469 } 5470 } 5471 } 5472 } else { 5473 currWrite = { struct: ( 5474 /** @type {Item | GC} */ 5475 currDecoder.curr 5476 ), offset: 0 }; 5477 currDecoder.next(); 5478 } 5479 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()) { 5480 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5481 currWrite = { struct: next, offset: 0 }; 5482 } 5483 } 5484 if (currWrite !== null) { 5485 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset); 5486 currWrite = null; 5487 } 5488 finishLazyStructWriting(lazyStructEncoder); 5489 const dss = updateDecoders.map((decoder) => readDeleteSet(decoder)); 5490 const ds = mergeDeleteSets(dss); 5491 writeDeleteSet(updateEncoder, ds); 5492 return updateEncoder.toUint8Array(); 5493 }; 5494 var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => { 5495 const state = decodeStateVector(sv); 5496 const encoder = new YEncoder(); 5497 const lazyStructWriter = new LazyStructWriter(encoder); 5498 const decoder = new YDecoder(createDecoder(update)); 5499 const reader = new LazyStructReader(decoder, false); 5500 while (reader.curr) { 5501 const curr = reader.curr; 5502 const currClient = curr.id.client; 5503 const svClock = state.get(currClient) || 0; 5504 if (reader.curr.constructor === Skip) { 5505 reader.next(); 5506 continue; 5507 } 5508 if (curr.id.clock + curr.length > svClock) { 5509 writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0)); 5510 reader.next(); 5511 while (reader.curr && reader.curr.id.client === currClient) { 5512 writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0); 5513 reader.next(); 5514 } 5515 } else { 5516 while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) { 5517 reader.next(); 5518 } 5519 } 5520 } 5521 finishLazyStructWriting(lazyStructWriter); 5522 const ds = readDeleteSet(decoder); 5523 writeDeleteSet(encoder, ds); 5524 return encoder.toUint8Array(); 5525 }; 5526 var diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1); 5527 var flushLazyStructWriter = (lazyWriter) => { 5528 if (lazyWriter.written > 0) { 5529 lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) }); 5530 lazyWriter.encoder.restEncoder = createEncoder(); 5531 lazyWriter.written = 0; 5532 } 5533 }; 5534 var writeStructToLazyStructWriter = (lazyWriter, struct, offset) => { 5535 if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) { 5536 flushLazyStructWriter(lazyWriter); 5537 } 5538 if (lazyWriter.written === 0) { 5539 lazyWriter.currClient = struct.id.client; 5540 lazyWriter.encoder.writeClient(struct.id.client); 5541 writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset); 5542 } 5543 struct.write(lazyWriter.encoder, offset); 5544 lazyWriter.written++; 5545 }; 5546 var finishLazyStructWriting = (lazyWriter) => { 5547 flushLazyStructWriter(lazyWriter); 5548 const restEncoder = lazyWriter.encoder.restEncoder; 5549 writeVarUint(restEncoder, lazyWriter.clientStructs.length); 5550 for (let i = 0; i < lazyWriter.clientStructs.length; i++) { 5551 const partStructs = lazyWriter.clientStructs[i]; 5552 writeVarUint(restEncoder, partStructs.written); 5553 writeUint8Array(restEncoder, partStructs.restEncoder); 5554 } 5555 }; 5556 var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => { 5557 const updateDecoder = new YDecoder(createDecoder(update)); 5558 const lazyDecoder = new LazyStructReader(updateDecoder, false); 5559 const updateEncoder = new YEncoder(); 5560 const lazyWriter = new LazyStructWriter(updateEncoder); 5561 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) { 5562 writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0); 5563 } 5564 finishLazyStructWriting(lazyWriter); 5565 const ds = readDeleteSet(updateDecoder); 5566 writeDeleteSet(updateEncoder, ds); 5567 return updateEncoder.toUint8Array(); 5568 }; 5569 var createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => { 5570 let i = 0; 5571 const mapKeyCache = create(); 5572 const nodeNameCache = create(); 5573 const formattingKeyCache = create(); 5574 const formattingValueCache = create(); 5575 formattingValueCache.set(null, null); 5576 return (block) => { 5577 switch (block.constructor) { 5578 case GC: 5579 case Skip: 5580 return block; 5581 case Item: { 5582 const item = ( 5583 /** @type {Item} */ 5584 block 5585 ); 5586 const content = item.content; 5587 switch (content.constructor) { 5588 case ContentDeleted: 5589 break; 5590 case ContentType: { 5591 if (yxml) { 5592 const type = ( 5593 /** @type {ContentType} */ 5594 content.type 5595 ); 5596 if (type instanceof YXmlElement) { 5597 type.nodeName = setIfUndefined(nodeNameCache, type.nodeName, () => "node-" + i); 5598 } 5599 if (type instanceof YXmlHook) { 5600 type.hookName = setIfUndefined(nodeNameCache, type.hookName, () => "hook-" + i); 5601 } 5602 } 5603 break; 5604 } 5605 case ContentAny: { 5606 const c = ( 5607 /** @type {ContentAny} */ 5608 content 5609 ); 5610 c.arr = c.arr.map(() => i); 5611 break; 5612 } 5613 case ContentBinary: { 5614 const c = ( 5615 /** @type {ContentBinary} */ 5616 content 5617 ); 5618 c.content = new Uint8Array([i]); 5619 break; 5620 } 5621 case ContentDoc: { 5622 const c = ( 5623 /** @type {ContentDoc} */ 5624 content 5625 ); 5626 if (subdocs) { 5627 c.opts = {}; 5628 c.doc.guid = i + ""; 5629 } 5630 break; 5631 } 5632 case ContentEmbed: { 5633 const c = ( 5634 /** @type {ContentEmbed} */ 5635 content 5636 ); 5637 c.embed = {}; 5638 break; 5639 } 5640 case ContentFormat: { 5641 const c = ( 5642 /** @type {ContentFormat} */ 5643 content 5644 ); 5645 if (formatting) { 5646 c.key = setIfUndefined(formattingKeyCache, c.key, () => i + ""); 5647 c.value = setIfUndefined(formattingValueCache, c.value, () => ({ i })); 5648 } 5649 break; 5650 } 5651 case ContentJSON: { 5652 const c = ( 5653 /** @type {ContentJSON} */ 5654 content 5655 ); 5656 c.arr = c.arr.map(() => i); 5657 break; 5658 } 5659 case ContentString: { 5660 const c = ( 5661 /** @type {ContentString} */ 5662 content 5663 ); 5664 c.str = repeat(i % 10 + "", c.str.length); 5665 break; 5666 } 5667 default: 5668 unexpectedCase(); 5669 } 5670 if (item.parentSub) { 5671 item.parentSub = setIfUndefined(mapKeyCache, item.parentSub, () => i + ""); 5672 } 5673 i++; 5674 return block; 5675 } 5676 default: 5677 unexpectedCase(); 5678 } 5679 }; 5680 }; 5681 var obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1); 5682 var obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2); 5683 var convertUpdateFormatV1ToV2 = (update) => convertUpdateFormat(update, id, UpdateDecoderV1, UpdateEncoderV2); 5684 var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1); 5685 var errorComputeChanges = "You must not compute changes after the event-handler fired."; 5686 var YEvent = class { 5687 /** 5688 * @param {T} target The changed type. 5689 * @param {Transaction} transaction 5690 */ 5691 constructor(target, transaction) { 5692 this.target = target; 5693 this.currentTarget = target; 5694 this.transaction = transaction; 5695 this._changes = null; 5696 this._keys = null; 5697 this._delta = null; 5698 this._path = null; 5699 } 5700 /** 5701 * Computes the path from `y` to the changed type. 5702 * 5703 * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with. 5704 * 5705 * The following property holds: 5706 * @example 5707 * let type = y 5708 * event.path.forEach(dir => { 5709 * type = type.get(dir) 5710 * }) 5711 * type === event.target // => true 5712 */ 5713 get path() { 5714 return this._path || (this._path = getPathTo(this.currentTarget, this.target)); 5715 } 5716 /** 5717 * Check if a struct is deleted by this event. 5718 * 5719 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. 5720 * 5721 * @param {AbstractStruct} struct 5722 * @return {boolean} 5723 */ 5724 deletes(struct) { 5725 return isDeleted(this.transaction.deleteSet, struct.id); 5726 } 5727 /** 5728 * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>} 5729 */ 5730 get keys() { 5731 if (this._keys === null) { 5732 if (this.transaction.doc._transactionCleanups.length === 0) { 5733 throw create3(errorComputeChanges); 5734 } 5735 const keys2 = /* @__PURE__ */ new Map(); 5736 const target = this.target; 5737 const changed = ( 5738 /** @type Set<string|null> */ 5739 this.transaction.changed.get(target) 5740 ); 5741 changed.forEach((key) => { 5742 if (key !== null) { 5743 const item = ( 5744 /** @type {Item} */ 5745 target._map.get(key) 5746 ); 5747 let action; 5748 let oldValue; 5749 if (this.adds(item)) { 5750 let prev = item.left; 5751 while (prev !== null && this.adds(prev)) { 5752 prev = prev.left; 5753 } 5754 if (this.deletes(item)) { 5755 if (prev !== null && this.deletes(prev)) { 5756 action = "delete"; 5757 oldValue = last(prev.content.getContent()); 5758 } else { 5759 return; 5760 } 5761 } else { 5762 if (prev !== null && this.deletes(prev)) { 5763 action = "update"; 5764 oldValue = last(prev.content.getContent()); 5765 } else { 5766 action = "add"; 5767 oldValue = void 0; 5768 } 5769 } 5770 } else { 5771 if (this.deletes(item)) { 5772 action = "delete"; 5773 oldValue = last( 5774 /** @type {Item} */ 5775 item.content.getContent() 5776 ); 5777 } else { 5778 return; 5779 } 5780 } 5781 keys2.set(key, { action, oldValue }); 5782 } 5783 }); 5784 this._keys = keys2; 5785 } 5786 return this._keys; 5787 } 5788 /** 5789 * This is a computed property. Note that this can only be safely computed during the 5790 * event call. Computing this property after other changes happened might result in 5791 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes 5792 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. 5793 * 5794 * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>} 5795 */ 5796 get delta() { 5797 return this.changes.delta; 5798 } 5799 /** 5800 * Check if a struct is added by this event. 5801 * 5802 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted. 5803 * 5804 * @param {AbstractStruct} struct 5805 * @return {boolean} 5806 */ 5807 adds(struct) { 5808 return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0); 5809 } 5810 /** 5811 * This is a computed property. Note that this can only be safely computed during the 5812 * event call. Computing this property after other changes happened might result in 5813 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes 5814 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object. 5815 * 5816 * @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}>}} 5817 */ 5818 get changes() { 5819 let changes = this._changes; 5820 if (changes === null) { 5821 if (this.transaction.doc._transactionCleanups.length === 0) { 5822 throw create3(errorComputeChanges); 5823 } 5824 const target = this.target; 5825 const added = create2(); 5826 const deleted = create2(); 5827 const delta = []; 5828 changes = { 5829 added, 5830 deleted, 5831 delta, 5832 keys: this.keys 5833 }; 5834 const changed = ( 5835 /** @type Set<string|null> */ 5836 this.transaction.changed.get(target) 5837 ); 5838 if (changed.has(null)) { 5839 let lastOp = null; 5840 const packOp = () => { 5841 if (lastOp) { 5842 delta.push(lastOp); 5843 } 5844 }; 5845 for (let item = target._start; item !== null; item = item.right) { 5846 if (item.deleted) { 5847 if (this.deletes(item) && !this.adds(item)) { 5848 if (lastOp === null || lastOp.delete === void 0) { 5849 packOp(); 5850 lastOp = { delete: 0 }; 5851 } 5852 lastOp.delete += item.length; 5853 deleted.add(item); 5854 } 5855 } else { 5856 if (this.adds(item)) { 5857 if (lastOp === null || lastOp.insert === void 0) { 5858 packOp(); 5859 lastOp = { insert: [] }; 5860 } 5861 lastOp.insert = lastOp.insert.concat(item.content.getContent()); 5862 added.add(item); 5863 } else { 5864 if (lastOp === null || lastOp.retain === void 0) { 5865 packOp(); 5866 lastOp = { retain: 0 }; 5867 } 5868 lastOp.retain += item.length; 5869 } 5870 } 5871 } 5872 if (lastOp !== null && lastOp.retain === void 0) { 5873 packOp(); 5874 } 5875 } 5876 this._changes = changes; 5877 } 5878 return ( 5879 /** @type {any} */ 5880 changes 5881 ); 5882 } 5883 }; 5884 var getPathTo = (parent, child) => { 5885 const path = []; 5886 while (child._item !== null && child !== parent) { 5887 if (child._item.parentSub !== null) { 5888 path.unshift(child._item.parentSub); 5889 } else { 5890 let i = 0; 5891 let c = ( 5892 /** @type {AbstractType<any>} */ 5893 child._item.parent._start 5894 ); 5895 while (c !== child._item && c !== null) { 5896 if (!c.deleted && c.countable) { 5897 i += c.length; 5898 } 5899 c = c.right; 5900 } 5901 path.unshift(i); 5902 } 5903 child = /** @type {AbstractType<any>} */ 5904 child._item.parent; 5905 } 5906 return path; 5907 }; 5908 var warnPrematureAccess = () => { 5909 warn("Invalid access: Add Yjs type to a document before reading data."); 5910 }; 5911 var maxSearchMarker = 80; 5912 var globalSearchMarkerTimestamp = 0; 5913 var ArraySearchMarker = class { 5914 /** 5915 * @param {Item} p 5916 * @param {number} index 5917 */ 5918 constructor(p, index) { 5919 p.marker = true; 5920 this.p = p; 5921 this.index = index; 5922 this.timestamp = globalSearchMarkerTimestamp++; 5923 } 5924 }; 5925 var refreshMarkerTimestamp = (marker) => { 5926 marker.timestamp = globalSearchMarkerTimestamp++; 5927 }; 5928 var overwriteMarker = (marker, p, index) => { 5929 marker.p.marker = false; 5930 marker.p = p; 5931 p.marker = true; 5932 marker.index = index; 5933 marker.timestamp = globalSearchMarkerTimestamp++; 5934 }; 5935 var markPosition = (searchMarker, p, index) => { 5936 if (searchMarker.length >= maxSearchMarker) { 5937 const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b); 5938 overwriteMarker(marker, p, index); 5939 return marker; 5940 } else { 5941 const pm = new ArraySearchMarker(p, index); 5942 searchMarker.push(pm); 5943 return pm; 5944 } 5945 }; 5946 var findMarker = (yarray, index) => { 5947 if (yarray._start === null || index === 0 || yarray._searchMarker === null) { 5948 return null; 5949 } 5950 const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b); 5951 let p = yarray._start; 5952 let pindex = 0; 5953 if (marker !== null) { 5954 p = marker.p; 5955 pindex = marker.index; 5956 refreshMarkerTimestamp(marker); 5957 } 5958 while (p.right !== null && pindex < index) { 5959 if (!p.deleted && p.countable) { 5960 if (index < pindex + p.length) { 5961 break; 5962 } 5963 pindex += p.length; 5964 } 5965 p = p.right; 5966 } 5967 while (p.left !== null && pindex > index) { 5968 p = p.left; 5969 if (!p.deleted && p.countable) { 5970 pindex -= p.length; 5971 } 5972 } 5973 while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) { 5974 p = p.left; 5975 if (!p.deleted && p.countable) { 5976 pindex -= p.length; 5977 } 5978 } 5979 if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */ 5980 p.parent.length / maxSearchMarker) { 5981 overwriteMarker(marker, p, pindex); 5982 return marker; 5983 } else { 5984 return markPosition(yarray._searchMarker, p, pindex); 5985 } 5986 }; 5987 var updateMarkerChanges = (searchMarker, index, len) => { 5988 for (let i = searchMarker.length - 1; i >= 0; i--) { 5989 const m = searchMarker[i]; 5990 if (len > 0) { 5991 let p = m.p; 5992 p.marker = false; 5993 while (p && (p.deleted || !p.countable)) { 5994 p = p.left; 5995 if (p && !p.deleted && p.countable) { 5996 m.index -= p.length; 5997 } 5998 } 5999 if (p === null || p.marker === true) { 6000 searchMarker.splice(i, 1); 6001 continue; 6002 } 6003 m.p = p; 6004 p.marker = true; 6005 } 6006 if (index < m.index || len > 0 && index === m.index) { 6007 m.index = max(index, m.index + len); 6008 } 6009 } 6010 }; 6011 var getTypeChildren = (t) => { 6012 t.doc ?? warnPrematureAccess(); 6013 let s = t._start; 6014 const arr = []; 6015 while (s) { 6016 arr.push(s); 6017 s = s.right; 6018 } 6019 return arr; 6020 }; 6021 var callTypeObservers = (type, transaction, event) => { 6022 const changedType = type; 6023 const changedParentTypes = transaction.changedParentTypes; 6024 while (true) { 6025 setIfUndefined(changedParentTypes, type, () => []).push(event); 6026 if (type._item === null) { 6027 break; 6028 } 6029 type = /** @type {AbstractType<any>} */ 6030 type._item.parent; 6031 } 6032 callEventHandlerListeners(changedType._eH, event, transaction); 6033 }; 6034 var AbstractType = class { 6035 constructor() { 6036 this._item = null; 6037 this._map = /* @__PURE__ */ new Map(); 6038 this._start = null; 6039 this.doc = null; 6040 this._length = 0; 6041 this._eH = createEventHandler(); 6042 this._dEH = createEventHandler(); 6043 this._searchMarker = null; 6044 } 6045 /** 6046 * @return {AbstractType<any>|null} 6047 */ 6048 get parent() { 6049 return this._item ? ( 6050 /** @type {AbstractType<any>} */ 6051 this._item.parent 6052 ) : null; 6053 } 6054 /** 6055 * Integrate this type into the Yjs instance. 6056 * 6057 * * Save this struct in the os 6058 * * This type is sent to other client 6059 * * Observer functions are fired 6060 * 6061 * @param {Doc} y The Yjs instance 6062 * @param {Item|null} item 6063 */ 6064 _integrate(y, item) { 6065 this.doc = y; 6066 this._item = item; 6067 } 6068 /** 6069 * @return {AbstractType<EventType>} 6070 */ 6071 _copy() { 6072 throw methodUnimplemented(); 6073 } 6074 /** 6075 * Makes a copy of this data type that can be included somewhere else. 6076 * 6077 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6078 * 6079 * @return {AbstractType<EventType>} 6080 */ 6081 clone() { 6082 throw methodUnimplemented(); 6083 } 6084 /** 6085 * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder 6086 */ 6087 _write(_encoder) { 6088 } 6089 /** 6090 * The first non-deleted item 6091 */ 6092 get _first() { 6093 let n = this._start; 6094 while (n !== null && n.deleted) { 6095 n = n.right; 6096 } 6097 return n; 6098 } 6099 /** 6100 * Creates YEvent and calls all type observers. 6101 * Must be implemented by each type. 6102 * 6103 * @param {Transaction} transaction 6104 * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified. 6105 */ 6106 _callObserver(transaction, _parentSubs) { 6107 if (!transaction.local && this._searchMarker) { 6108 this._searchMarker.length = 0; 6109 } 6110 } 6111 /** 6112 * Observe all events that are created on this type. 6113 * 6114 * @param {function(EventType, Transaction):void} f Observer function 6115 */ 6116 observe(f) { 6117 addEventHandlerListener(this._eH, f); 6118 } 6119 /** 6120 * Observe all events that are created by this type and its children. 6121 * 6122 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function 6123 */ 6124 observeDeep(f) { 6125 addEventHandlerListener(this._dEH, f); 6126 } 6127 /** 6128 * Unregister an observer function. 6129 * 6130 * @param {function(EventType,Transaction):void} f Observer function 6131 */ 6132 unobserve(f) { 6133 removeEventHandlerListener(this._eH, f); 6134 } 6135 /** 6136 * Unregister an observer function. 6137 * 6138 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function 6139 */ 6140 unobserveDeep(f) { 6141 removeEventHandlerListener(this._dEH, f); 6142 } 6143 /** 6144 * @abstract 6145 * @return {any} 6146 */ 6147 toJSON() { 6148 } 6149 }; 6150 var typeListSlice = (type, start, end) => { 6151 type.doc ?? warnPrematureAccess(); 6152 if (start < 0) { 6153 start = type._length + start; 6154 } 6155 if (end < 0) { 6156 end = type._length + end; 6157 } 6158 let len = end - start; 6159 const cs = []; 6160 let n = type._start; 6161 while (n !== null && len > 0) { 6162 if (n.countable && !n.deleted) { 6163 const c = n.content.getContent(); 6164 if (c.length <= start) { 6165 start -= c.length; 6166 } else { 6167 for (let i = start; i < c.length && len > 0; i++) { 6168 cs.push(c[i]); 6169 len--; 6170 } 6171 start = 0; 6172 } 6173 } 6174 n = n.right; 6175 } 6176 return cs; 6177 }; 6178 var typeListToArray = (type) => { 6179 type.doc ?? warnPrematureAccess(); 6180 const cs = []; 6181 let n = type._start; 6182 while (n !== null) { 6183 if (n.countable && !n.deleted) { 6184 const c = n.content.getContent(); 6185 for (let i = 0; i < c.length; i++) { 6186 cs.push(c[i]); 6187 } 6188 } 6189 n = n.right; 6190 } 6191 return cs; 6192 }; 6193 var typeListToArraySnapshot = (type, snapshot2) => { 6194 const cs = []; 6195 let n = type._start; 6196 while (n !== null) { 6197 if (n.countable && isVisible(n, snapshot2)) { 6198 const c = n.content.getContent(); 6199 for (let i = 0; i < c.length; i++) { 6200 cs.push(c[i]); 6201 } 6202 } 6203 n = n.right; 6204 } 6205 return cs; 6206 }; 6207 var typeListForEach = (type, f) => { 6208 let index = 0; 6209 let n = type._start; 6210 type.doc ?? warnPrematureAccess(); 6211 while (n !== null) { 6212 if (n.countable && !n.deleted) { 6213 const c = n.content.getContent(); 6214 for (let i = 0; i < c.length; i++) { 6215 f(c[i], index++, type); 6216 } 6217 } 6218 n = n.right; 6219 } 6220 }; 6221 var typeListMap = (type, f) => { 6222 const result = []; 6223 typeListForEach(type, (c, i) => { 6224 result.push(f(c, i, type)); 6225 }); 6226 return result; 6227 }; 6228 var typeListCreateIterator = (type) => { 6229 let n = type._start; 6230 let currentContent = null; 6231 let currentContentIndex = 0; 6232 return { 6233 [Symbol.iterator]() { 6234 return this; 6235 }, 6236 next: () => { 6237 if (currentContent === null) { 6238 while (n !== null && n.deleted) { 6239 n = n.right; 6240 } 6241 if (n === null) { 6242 return { 6243 done: true, 6244 value: void 0 6245 }; 6246 } 6247 currentContent = n.content.getContent(); 6248 currentContentIndex = 0; 6249 n = n.right; 6250 } 6251 const value = currentContent[currentContentIndex++]; 6252 if (currentContent.length <= currentContentIndex) { 6253 currentContent = null; 6254 } 6255 return { 6256 done: false, 6257 value 6258 }; 6259 } 6260 }; 6261 }; 6262 var typeListGet = (type, index) => { 6263 type.doc ?? warnPrematureAccess(); 6264 const marker = findMarker(type, index); 6265 let n = type._start; 6266 if (marker !== null) { 6267 n = marker.p; 6268 index -= marker.index; 6269 } 6270 for (; n !== null; n = n.right) { 6271 if (!n.deleted && n.countable) { 6272 if (index < n.length) { 6273 return n.content.getContent()[index]; 6274 } 6275 index -= n.length; 6276 } 6277 } 6278 }; 6279 var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => { 6280 let left = referenceItem; 6281 const doc2 = transaction.doc; 6282 const ownClientId = doc2.clientID; 6283 const store2 = doc2.store; 6284 const right = referenceItem === null ? parent._start : referenceItem.right; 6285 let jsonContent = []; 6286 const packJsonContent = () => { 6287 if (jsonContent.length > 0) { 6288 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent)); 6289 left.integrate(transaction, 0); 6290 jsonContent = []; 6291 } 6292 }; 6293 content.forEach((c) => { 6294 if (c === null) { 6295 jsonContent.push(c); 6296 } else { 6297 switch (c.constructor) { 6298 case Number: 6299 case Object: 6300 case Boolean: 6301 case Array: 6302 case String: 6303 jsonContent.push(c); 6304 break; 6305 default: 6306 packJsonContent(); 6307 switch (c.constructor) { 6308 case Uint8Array: 6309 case ArrayBuffer: 6310 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array( 6311 /** @type {Uint8Array} */ 6312 c 6313 ))); 6314 left.integrate(transaction, 0); 6315 break; 6316 case Doc: 6317 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc( 6318 /** @type {Doc} */ 6319 c 6320 )); 6321 left.integrate(transaction, 0); 6322 break; 6323 default: 6324 if (c instanceof AbstractType) { 6325 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c)); 6326 left.integrate(transaction, 0); 6327 } else { 6328 throw new Error("Unexpected content type in insert operation"); 6329 } 6330 } 6331 } 6332 } 6333 }); 6334 packJsonContent(); 6335 }; 6336 var lengthExceeded = () => create3("Length exceeded!"); 6337 var typeListInsertGenerics = (transaction, parent, index, content) => { 6338 if (index > parent._length) { 6339 throw lengthExceeded(); 6340 } 6341 if (index === 0) { 6342 if (parent._searchMarker) { 6343 updateMarkerChanges(parent._searchMarker, index, content.length); 6344 } 6345 return typeListInsertGenericsAfter(transaction, parent, null, content); 6346 } 6347 const startIndex = index; 6348 const marker = findMarker(parent, index); 6349 let n = parent._start; 6350 if (marker !== null) { 6351 n = marker.p; 6352 index -= marker.index; 6353 if (index === 0) { 6354 n = n.prev; 6355 index += n && n.countable && !n.deleted ? n.length : 0; 6356 } 6357 } 6358 for (; n !== null; n = n.right) { 6359 if (!n.deleted && n.countable) { 6360 if (index <= n.length) { 6361 if (index < n.length) { 6362 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); 6363 } 6364 break; 6365 } 6366 index -= n.length; 6367 } 6368 } 6369 if (parent._searchMarker) { 6370 updateMarkerChanges(parent._searchMarker, startIndex, content.length); 6371 } 6372 return typeListInsertGenericsAfter(transaction, parent, n, content); 6373 }; 6374 var typeListPushGenerics = (transaction, parent, content) => { 6375 const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start }); 6376 let n = marker.p; 6377 if (n) { 6378 while (n.right) { 6379 n = n.right; 6380 } 6381 } 6382 return typeListInsertGenericsAfter(transaction, parent, n, content); 6383 }; 6384 var typeListDelete = (transaction, parent, index, length2) => { 6385 if (length2 === 0) { 6386 return; 6387 } 6388 const startIndex = index; 6389 const startLength = length2; 6390 const marker = findMarker(parent, index); 6391 let n = parent._start; 6392 if (marker !== null) { 6393 n = marker.p; 6394 index -= marker.index; 6395 } 6396 for (; n !== null && index > 0; n = n.right) { 6397 if (!n.deleted && n.countable) { 6398 if (index < n.length) { 6399 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index)); 6400 } 6401 index -= n.length; 6402 } 6403 } 6404 while (length2 > 0 && n !== null) { 6405 if (!n.deleted) { 6406 if (length2 < n.length) { 6407 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length2)); 6408 } 6409 n.delete(transaction); 6410 length2 -= n.length; 6411 } 6412 n = n.right; 6413 } 6414 if (length2 > 0) { 6415 throw lengthExceeded(); 6416 } 6417 if (parent._searchMarker) { 6418 updateMarkerChanges( 6419 parent._searchMarker, 6420 startIndex, 6421 -startLength + length2 6422 /* in case we remove the above exception */ 6423 ); 6424 } 6425 }; 6426 var typeMapDelete = (transaction, parent, key) => { 6427 const c = parent._map.get(key); 6428 if (c !== void 0) { 6429 c.delete(transaction); 6430 } 6431 }; 6432 var typeMapSet = (transaction, parent, key, value) => { 6433 const left = parent._map.get(key) || null; 6434 const doc2 = transaction.doc; 6435 const ownClientId = doc2.clientID; 6436 let content; 6437 if (value == null) { 6438 content = new ContentAny([value]); 6439 } else { 6440 switch (value.constructor) { 6441 case Number: 6442 case Object: 6443 case Boolean: 6444 case Array: 6445 case String: 6446 case Date: 6447 case BigInt: 6448 content = new ContentAny([value]); 6449 break; 6450 case Uint8Array: 6451 content = new ContentBinary( 6452 /** @type {Uint8Array} */ 6453 value 6454 ); 6455 break; 6456 case Doc: 6457 content = new ContentDoc( 6458 /** @type {Doc} */ 6459 value 6460 ); 6461 break; 6462 default: 6463 if (value instanceof AbstractType) { 6464 content = new ContentType(value); 6465 } else { 6466 throw new Error("Unexpected content type"); 6467 } 6468 } 6469 } 6470 new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0); 6471 }; 6472 var typeMapGet = (parent, key) => { 6473 parent.doc ?? warnPrematureAccess(); 6474 const val = parent._map.get(key); 6475 return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0; 6476 }; 6477 var typeMapGetAll = (parent) => { 6478 const res = {}; 6479 parent.doc ?? warnPrematureAccess(); 6480 parent._map.forEach((value, key) => { 6481 if (!value.deleted) { 6482 res[key] = value.content.getContent()[value.length - 1]; 6483 } 6484 }); 6485 return res; 6486 }; 6487 var typeMapHas = (parent, key) => { 6488 parent.doc ?? warnPrematureAccess(); 6489 const val = parent._map.get(key); 6490 return val !== void 0 && !val.deleted; 6491 }; 6492 var typeMapGetSnapshot = (parent, key, snapshot2) => { 6493 let v = parent._map.get(key) || null; 6494 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) { 6495 v = v.left; 6496 } 6497 return v !== null && isVisible(v, snapshot2) ? v.content.getContent()[v.length - 1] : void 0; 6498 }; 6499 var typeMapGetAllSnapshot = (parent, snapshot2) => { 6500 const res = {}; 6501 parent._map.forEach((value, key) => { 6502 let v = value; 6503 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) { 6504 v = v.left; 6505 } 6506 if (v !== null && isVisible(v, snapshot2)) { 6507 res[key] = v.content.getContent()[v.length - 1]; 6508 } 6509 }); 6510 return res; 6511 }; 6512 var createMapIterator = (type) => { 6513 type.doc ?? warnPrematureAccess(); 6514 return iteratorFilter( 6515 type._map.entries(), 6516 /** @param {any} entry */ 6517 (entry) => !entry[1].deleted 6518 ); 6519 }; 6520 var YArrayEvent = class extends YEvent { 6521 }; 6522 var YArray = class _YArray extends AbstractType { 6523 constructor() { 6524 super(); 6525 this._prelimContent = []; 6526 this._searchMarker = []; 6527 } 6528 /** 6529 * Construct a new YArray containing the specified items. 6530 * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T 6531 * @param {Array<T>} items 6532 * @return {YArray<T>} 6533 */ 6534 static from(items2) { 6535 const a = new _YArray(); 6536 a.push(items2); 6537 return a; 6538 } 6539 /** 6540 * Integrate this type into the Yjs instance. 6541 * 6542 * * Save this struct in the os 6543 * * This type is sent to other client 6544 * * Observer functions are fired 6545 * 6546 * @param {Doc} y The Yjs instance 6547 * @param {Item} item 6548 */ 6549 _integrate(y, item) { 6550 super._integrate(y, item); 6551 this.insert( 6552 0, 6553 /** @type {Array<any>} */ 6554 this._prelimContent 6555 ); 6556 this._prelimContent = null; 6557 } 6558 /** 6559 * @return {YArray<T>} 6560 */ 6561 _copy() { 6562 return new _YArray(); 6563 } 6564 /** 6565 * Makes a copy of this data type that can be included somewhere else. 6566 * 6567 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6568 * 6569 * @return {YArray<T>} 6570 */ 6571 clone() { 6572 const arr = new _YArray(); 6573 arr.insert(0, this.toArray().map( 6574 (el) => el instanceof AbstractType ? ( 6575 /** @type {typeof el} */ 6576 el.clone() 6577 ) : el 6578 )); 6579 return arr; 6580 } 6581 get length() { 6582 this.doc ?? warnPrematureAccess(); 6583 return this._length; 6584 } 6585 /** 6586 * Creates YArrayEvent and calls observers. 6587 * 6588 * @param {Transaction} transaction 6589 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 6590 */ 6591 _callObserver(transaction, parentSubs) { 6592 super._callObserver(transaction, parentSubs); 6593 callTypeObservers(this, transaction, new YArrayEvent(this, transaction)); 6594 } 6595 /** 6596 * Inserts new content at an index. 6597 * 6598 * Important: This function expects an array of content. Not just a content 6599 * object. The reason for this "weirdness" is that inserting several elements 6600 * is very efficient when it is done as a single operation. 6601 * 6602 * @example 6603 * // Insert character 'a' at position 0 6604 * yarray.insert(0, ['a']) 6605 * // Insert numbers 1, 2 at position 1 6606 * yarray.insert(1, [1, 2]) 6607 * 6608 * @param {number} index The index to insert content at. 6609 * @param {Array<T>} content The array of content 6610 */ 6611 insert(index, content) { 6612 if (this.doc !== null) { 6613 transact(this.doc, (transaction) => { 6614 typeListInsertGenerics( 6615 transaction, 6616 this, 6617 index, 6618 /** @type {any} */ 6619 content 6620 ); 6621 }); 6622 } else { 6623 this._prelimContent.splice(index, 0, ...content); 6624 } 6625 } 6626 /** 6627 * Appends content to this YArray. 6628 * 6629 * @param {Array<T>} content Array of content to append. 6630 * 6631 * @todo Use the following implementation in all types. 6632 */ 6633 push(content) { 6634 if (this.doc !== null) { 6635 transact(this.doc, (transaction) => { 6636 typeListPushGenerics( 6637 transaction, 6638 this, 6639 /** @type {any} */ 6640 content 6641 ); 6642 }); 6643 } else { 6644 this._prelimContent.push(...content); 6645 } 6646 } 6647 /** 6648 * Prepends content to this YArray. 6649 * 6650 * @param {Array<T>} content Array of content to prepend. 6651 */ 6652 unshift(content) { 6653 this.insert(0, content); 6654 } 6655 /** 6656 * Deletes elements starting from an index. 6657 * 6658 * @param {number} index Index at which to start deleting elements 6659 * @param {number} length The number of elements to remove. Defaults to 1. 6660 */ 6661 delete(index, length2 = 1) { 6662 if (this.doc !== null) { 6663 transact(this.doc, (transaction) => { 6664 typeListDelete(transaction, this, index, length2); 6665 }); 6666 } else { 6667 this._prelimContent.splice(index, length2); 6668 } 6669 } 6670 /** 6671 * Returns the i-th element from a YArray. 6672 * 6673 * @param {number} index The index of the element to return from the YArray 6674 * @return {T} 6675 */ 6676 get(index) { 6677 return typeListGet(this, index); 6678 } 6679 /** 6680 * Transforms this YArray to a JavaScript Array. 6681 * 6682 * @return {Array<T>} 6683 */ 6684 toArray() { 6685 return typeListToArray(this); 6686 } 6687 /** 6688 * Returns a portion of this YArray into a JavaScript Array selected 6689 * from start to end (end not included). 6690 * 6691 * @param {number} [start] 6692 * @param {number} [end] 6693 * @return {Array<T>} 6694 */ 6695 slice(start = 0, end = this.length) { 6696 return typeListSlice(this, start, end); 6697 } 6698 /** 6699 * Transforms this Shared Type to a JSON object. 6700 * 6701 * @return {Array<any>} 6702 */ 6703 toJSON() { 6704 return this.map((c) => c instanceof AbstractType ? c.toJSON() : c); 6705 } 6706 /** 6707 * Returns an Array with the result of calling a provided function on every 6708 * element of this YArray. 6709 * 6710 * @template M 6711 * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array 6712 * @return {Array<M>} A new array with each element being the result of the 6713 * callback function 6714 */ 6715 map(f) { 6716 return typeListMap( 6717 this, 6718 /** @type {any} */ 6719 f 6720 ); 6721 } 6722 /** 6723 * Executes a provided function once on every element of this YArray. 6724 * 6725 * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray. 6726 */ 6727 forEach(f) { 6728 typeListForEach(this, f); 6729 } 6730 /** 6731 * @return {IterableIterator<T>} 6732 */ 6733 [Symbol.iterator]() { 6734 return typeListCreateIterator(this); 6735 } 6736 /** 6737 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 6738 */ 6739 _write(encoder) { 6740 encoder.writeTypeRef(YArrayRefID); 6741 } 6742 }; 6743 var readYArray = (_decoder) => new YArray(); 6744 var YMapEvent = class extends YEvent { 6745 /** 6746 * @param {YMap<T>} ymap The YArray that changed. 6747 * @param {Transaction} transaction 6748 * @param {Set<any>} subs The keys that changed. 6749 */ 6750 constructor(ymap, transaction, subs) { 6751 super(ymap, transaction); 6752 this.keysChanged = subs; 6753 } 6754 }; 6755 var YMap = class _YMap extends AbstractType { 6756 /** 6757 * 6758 * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap 6759 */ 6760 constructor(entries) { 6761 super(); 6762 this._prelimContent = null; 6763 if (entries === void 0) { 6764 this._prelimContent = /* @__PURE__ */ new Map(); 6765 } else { 6766 this._prelimContent = new Map(entries); 6767 } 6768 } 6769 /** 6770 * Integrate this type into the Yjs instance. 6771 * 6772 * * Save this struct in the os 6773 * * This type is sent to other client 6774 * * Observer functions are fired 6775 * 6776 * @param {Doc} y The Yjs instance 6777 * @param {Item} item 6778 */ 6779 _integrate(y, item) { 6780 super._integrate(y, item); 6781 this._prelimContent.forEach((value, key) => { 6782 this.set(key, value); 6783 }); 6784 this._prelimContent = null; 6785 } 6786 /** 6787 * @return {YMap<MapType>} 6788 */ 6789 _copy() { 6790 return new _YMap(); 6791 } 6792 /** 6793 * Makes a copy of this data type that can be included somewhere else. 6794 * 6795 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 6796 * 6797 * @return {YMap<MapType>} 6798 */ 6799 clone() { 6800 const map2 = new _YMap(); 6801 this.forEach((value, key) => { 6802 map2.set(key, value instanceof AbstractType ? ( 6803 /** @type {typeof value} */ 6804 value.clone() 6805 ) : value); 6806 }); 6807 return map2; 6808 } 6809 /** 6810 * Creates YMapEvent and calls observers. 6811 * 6812 * @param {Transaction} transaction 6813 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 6814 */ 6815 _callObserver(transaction, parentSubs) { 6816 callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs)); 6817 } 6818 /** 6819 * Transforms this Shared Type to a JSON object. 6820 * 6821 * @return {Object<string,any>} 6822 */ 6823 toJSON() { 6824 this.doc ?? warnPrematureAccess(); 6825 const map2 = {}; 6826 this._map.forEach((item, key) => { 6827 if (!item.deleted) { 6828 const v = item.content.getContent()[item.length - 1]; 6829 map2[key] = v instanceof AbstractType ? v.toJSON() : v; 6830 } 6831 }); 6832 return map2; 6833 } 6834 /** 6835 * Returns the size of the YMap (count of key/value pairs) 6836 * 6837 * @return {number} 6838 */ 6839 get size() { 6840 return [...createMapIterator(this)].length; 6841 } 6842 /** 6843 * Returns the keys for each element in the YMap Type. 6844 * 6845 * @return {IterableIterator<string>} 6846 */ 6847 keys() { 6848 return iteratorMap( 6849 createMapIterator(this), 6850 /** @param {any} v */ 6851 (v) => v[0] 6852 ); 6853 } 6854 /** 6855 * Returns the values for each element in the YMap Type. 6856 * 6857 * @return {IterableIterator<MapType>} 6858 */ 6859 values() { 6860 return iteratorMap( 6861 createMapIterator(this), 6862 /** @param {any} v */ 6863 (v) => v[1].content.getContent()[v[1].length - 1] 6864 ); 6865 } 6866 /** 6867 * Returns an Iterator of [key, value] pairs 6868 * 6869 * @return {IterableIterator<[string, MapType]>} 6870 */ 6871 entries() { 6872 return iteratorMap( 6873 createMapIterator(this), 6874 /** @param {any} v */ 6875 (v) => ( 6876 /** @type {any} */ 6877 [v[0], v[1].content.getContent()[v[1].length - 1]] 6878 ) 6879 ); 6880 } 6881 /** 6882 * Executes a provided function on once on every key-value pair. 6883 * 6884 * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray. 6885 */ 6886 forEach(f) { 6887 this.doc ?? warnPrematureAccess(); 6888 this._map.forEach((item, key) => { 6889 if (!item.deleted) { 6890 f(item.content.getContent()[item.length - 1], key, this); 6891 } 6892 }); 6893 } 6894 /** 6895 * Returns an Iterator of [key, value] pairs 6896 * 6897 * @return {IterableIterator<[string, MapType]>} 6898 */ 6899 [Symbol.iterator]() { 6900 return this.entries(); 6901 } 6902 /** 6903 * Remove a specified element from this YMap. 6904 * 6905 * @param {string} key The key of the element to remove. 6906 */ 6907 delete(key) { 6908 if (this.doc !== null) { 6909 transact(this.doc, (transaction) => { 6910 typeMapDelete(transaction, this, key); 6911 }); 6912 } else { 6913 this._prelimContent.delete(key); 6914 } 6915 } 6916 /** 6917 * Adds or updates an element with a specified key and value. 6918 * @template {MapType} VAL 6919 * 6920 * @param {string} key The key of the element to add to this YMap 6921 * @param {VAL} value The value of the element to add 6922 * @return {VAL} 6923 */ 6924 set(key, value) { 6925 if (this.doc !== null) { 6926 transact(this.doc, (transaction) => { 6927 typeMapSet( 6928 transaction, 6929 this, 6930 key, 6931 /** @type {any} */ 6932 value 6933 ); 6934 }); 6935 } else { 6936 this._prelimContent.set(key, value); 6937 } 6938 return value; 6939 } 6940 /** 6941 * Returns a specified element from this YMap. 6942 * 6943 * @param {string} key 6944 * @return {MapType|undefined} 6945 */ 6946 get(key) { 6947 return ( 6948 /** @type {any} */ 6949 typeMapGet(this, key) 6950 ); 6951 } 6952 /** 6953 * Returns a boolean indicating whether the specified key exists or not. 6954 * 6955 * @param {string} key The key to test. 6956 * @return {boolean} 6957 */ 6958 has(key) { 6959 return typeMapHas(this, key); 6960 } 6961 /** 6962 * Removes all elements from this YMap. 6963 */ 6964 clear() { 6965 if (this.doc !== null) { 6966 transact(this.doc, (transaction) => { 6967 this.forEach(function(_value, key, map2) { 6968 typeMapDelete(transaction, map2, key); 6969 }); 6970 }); 6971 } else { 6972 this._prelimContent.clear(); 6973 } 6974 } 6975 /** 6976 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 6977 */ 6978 _write(encoder) { 6979 encoder.writeTypeRef(YMapRefID); 6980 } 6981 }; 6982 var readYMap = (_decoder) => new YMap(); 6983 var equalAttrs = (a, b) => a === b || typeof a === "object" && typeof b === "object" && a && b && equalFlat(a, b); 6984 var ItemTextListPosition = class { 6985 /** 6986 * @param {Item|null} left 6987 * @param {Item|null} right 6988 * @param {number} index 6989 * @param {Map<string,any>} currentAttributes 6990 */ 6991 constructor(left, right, index, currentAttributes) { 6992 this.left = left; 6993 this.right = right; 6994 this.index = index; 6995 this.currentAttributes = currentAttributes; 6996 } 6997 /** 6998 * Only call this if you know that this.right is defined 6999 */ 7000 forward() { 7001 if (this.right === null) { 7002 unexpectedCase(); 7003 } 7004 switch (this.right.content.constructor) { 7005 case ContentFormat: 7006 if (!this.right.deleted) { 7007 updateCurrentAttributes( 7008 this.currentAttributes, 7009 /** @type {ContentFormat} */ 7010 this.right.content 7011 ); 7012 } 7013 break; 7014 default: 7015 if (!this.right.deleted) { 7016 this.index += this.right.length; 7017 } 7018 break; 7019 } 7020 this.left = this.right; 7021 this.right = this.right.right; 7022 } 7023 }; 7024 var findNextPosition = (transaction, pos, count) => { 7025 while (pos.right !== null && count > 0) { 7026 switch (pos.right.content.constructor) { 7027 case ContentFormat: 7028 if (!pos.right.deleted) { 7029 updateCurrentAttributes( 7030 pos.currentAttributes, 7031 /** @type {ContentFormat} */ 7032 pos.right.content 7033 ); 7034 } 7035 break; 7036 default: 7037 if (!pos.right.deleted) { 7038 if (count < pos.right.length) { 7039 getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count)); 7040 } 7041 pos.index += pos.right.length; 7042 count -= pos.right.length; 7043 } 7044 break; 7045 } 7046 pos.left = pos.right; 7047 pos.right = pos.right.right; 7048 } 7049 return pos; 7050 }; 7051 var findPosition = (transaction, parent, index, useSearchMarker) => { 7052 const currentAttributes = /* @__PURE__ */ new Map(); 7053 const marker = useSearchMarker ? findMarker(parent, index) : null; 7054 if (marker) { 7055 const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes); 7056 return findNextPosition(transaction, pos, index - marker.index); 7057 } else { 7058 const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes); 7059 return findNextPosition(transaction, pos, index); 7060 } 7061 }; 7062 var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => { 7063 while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs( 7064 negatedAttributes.get( 7065 /** @type {ContentFormat} */ 7066 currPos.right.content.key 7067 ), 7068 /** @type {ContentFormat} */ 7069 currPos.right.content.value 7070 ))) { 7071 if (!currPos.right.deleted) { 7072 negatedAttributes.delete( 7073 /** @type {ContentFormat} */ 7074 currPos.right.content.key 7075 ); 7076 } 7077 currPos.forward(); 7078 } 7079 const doc2 = transaction.doc; 7080 const ownClientId = doc2.clientID; 7081 negatedAttributes.forEach((val, key) => { 7082 const left = currPos.left; 7083 const right = currPos.right; 7084 const nextFormat = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); 7085 nextFormat.integrate(transaction, 0); 7086 currPos.right = nextFormat; 7087 currPos.forward(); 7088 }); 7089 }; 7090 var updateCurrentAttributes = (currentAttributes, format) => { 7091 const { key, value } = format; 7092 if (value === null) { 7093 currentAttributes.delete(key); 7094 } else { 7095 currentAttributes.set(key, value); 7096 } 7097 }; 7098 var minimizeAttributeChanges = (currPos, attributes) => { 7099 while (true) { 7100 if (currPos.right === null) { 7101 break; 7102 } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs( 7103 attributes[ 7104 /** @type {ContentFormat} */ 7105 currPos.right.content.key 7106 ] ?? null, 7107 /** @type {ContentFormat} */ 7108 currPos.right.content.value 7109 )) ; 7110 else { 7111 break; 7112 } 7113 currPos.forward(); 7114 } 7115 }; 7116 var insertAttributes = (transaction, parent, currPos, attributes) => { 7117 const doc2 = transaction.doc; 7118 const ownClientId = doc2.clientID; 7119 const negatedAttributes = /* @__PURE__ */ new Map(); 7120 for (const key in attributes) { 7121 const val = attributes[key]; 7122 const currentVal = currPos.currentAttributes.get(key) ?? null; 7123 if (!equalAttrs(currentVal, val)) { 7124 negatedAttributes.set(key, currentVal); 7125 const { left, right } = currPos; 7126 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val)); 7127 currPos.right.integrate(transaction, 0); 7128 currPos.forward(); 7129 } 7130 } 7131 return negatedAttributes; 7132 }; 7133 var insertText = (transaction, parent, currPos, text2, attributes) => { 7134 currPos.currentAttributes.forEach((_val, key) => { 7135 if (attributes[key] === void 0) { 7136 attributes[key] = null; 7137 } 7138 }); 7139 const doc2 = transaction.doc; 7140 const ownClientId = doc2.clientID; 7141 minimizeAttributeChanges(currPos, attributes); 7142 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); 7143 const content = text2.constructor === String ? new ContentString( 7144 /** @type {string} */ 7145 text2 7146 ) : text2 instanceof AbstractType ? new ContentType(text2) : new ContentEmbed(text2); 7147 let { left, right, index } = currPos; 7148 if (parent._searchMarker) { 7149 updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength()); 7150 } 7151 right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content); 7152 right.integrate(transaction, 0); 7153 currPos.right = right; 7154 currPos.index = index; 7155 currPos.forward(); 7156 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); 7157 }; 7158 var formatText = (transaction, parent, currPos, length2, attributes) => { 7159 const doc2 = transaction.doc; 7160 const ownClientId = doc2.clientID; 7161 minimizeAttributeChanges(currPos, attributes); 7162 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes); 7163 iterationLoop: while (currPos.right !== null && (length2 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) { 7164 if (!currPos.right.deleted) { 7165 switch (currPos.right.content.constructor) { 7166 case ContentFormat: { 7167 const { key, value } = ( 7168 /** @type {ContentFormat} */ 7169 currPos.right.content 7170 ); 7171 const attr = attributes[key]; 7172 if (attr !== void 0) { 7173 if (equalAttrs(attr, value)) { 7174 negatedAttributes.delete(key); 7175 } else { 7176 if (length2 === 0) { 7177 break iterationLoop; 7178 } 7179 negatedAttributes.set(key, value); 7180 } 7181 currPos.right.delete(transaction); 7182 } else { 7183 currPos.currentAttributes.set(key, value); 7184 } 7185 break; 7186 } 7187 default: 7188 if (length2 < currPos.right.length) { 7189 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); 7190 } 7191 length2 -= currPos.right.length; 7192 break; 7193 } 7194 } 7195 currPos.forward(); 7196 } 7197 if (length2 > 0) { 7198 let newlines = ""; 7199 for (; length2 > 0; length2--) { 7200 newlines += "\n"; 7201 } 7202 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)); 7203 currPos.right.integrate(transaction, 0); 7204 currPos.forward(); 7205 } 7206 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes); 7207 }; 7208 var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => { 7209 let end = start; 7210 const endFormats = create(); 7211 while (end && (!end.countable || end.deleted)) { 7212 if (!end.deleted && end.content.constructor === ContentFormat) { 7213 const cf = ( 7214 /** @type {ContentFormat} */ 7215 end.content 7216 ); 7217 endFormats.set(cf.key, cf); 7218 } 7219 end = end.right; 7220 } 7221 let cleanups = 0; 7222 let reachedCurr = false; 7223 while (start !== end) { 7224 if (curr === start) { 7225 reachedCurr = true; 7226 } 7227 if (!start.deleted) { 7228 const content = start.content; 7229 switch (content.constructor) { 7230 case ContentFormat: { 7231 const { key, value } = ( 7232 /** @type {ContentFormat} */ 7233 content 7234 ); 7235 const startAttrValue = startAttributes.get(key) ?? null; 7236 if (endFormats.get(key) !== content || startAttrValue === value) { 7237 start.delete(transaction); 7238 cleanups++; 7239 if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) { 7240 if (startAttrValue === null) { 7241 currAttributes.delete(key); 7242 } else { 7243 currAttributes.set(key, startAttrValue); 7244 } 7245 } 7246 } 7247 if (!reachedCurr && !start.deleted) { 7248 updateCurrentAttributes( 7249 currAttributes, 7250 /** @type {ContentFormat} */ 7251 content 7252 ); 7253 } 7254 break; 7255 } 7256 } 7257 } 7258 start = /** @type {Item} */ 7259 start.right; 7260 } 7261 return cleanups; 7262 }; 7263 var cleanupContextlessFormattingGap = (transaction, item) => { 7264 while (item && item.right && (item.right.deleted || !item.right.countable)) { 7265 item = item.right; 7266 } 7267 const attrs = /* @__PURE__ */ new Set(); 7268 while (item && (item.deleted || !item.countable)) { 7269 if (!item.deleted && item.content.constructor === ContentFormat) { 7270 const key = ( 7271 /** @type {ContentFormat} */ 7272 item.content.key 7273 ); 7274 if (attrs.has(key)) { 7275 item.delete(transaction); 7276 } else { 7277 attrs.add(key); 7278 } 7279 } 7280 item = item.left; 7281 } 7282 }; 7283 var cleanupYTextFormatting = (type) => { 7284 let res = 0; 7285 transact( 7286 /** @type {Doc} */ 7287 type.doc, 7288 (transaction) => { 7289 let start = ( 7290 /** @type {Item} */ 7291 type._start 7292 ); 7293 let end = type._start; 7294 let startAttributes = create(); 7295 const currentAttributes = copy(startAttributes); 7296 while (end) { 7297 if (end.deleted === false) { 7298 switch (end.content.constructor) { 7299 case ContentFormat: 7300 updateCurrentAttributes( 7301 currentAttributes, 7302 /** @type {ContentFormat} */ 7303 end.content 7304 ); 7305 break; 7306 default: 7307 res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes); 7308 startAttributes = copy(currentAttributes); 7309 start = end; 7310 break; 7311 } 7312 } 7313 end = end.right; 7314 } 7315 } 7316 ); 7317 return res; 7318 }; 7319 var cleanupYTextAfterTransaction = (transaction) => { 7320 const needFullCleanup = /* @__PURE__ */ new Set(); 7321 const doc2 = transaction.doc; 7322 for (const [client, afterClock] of transaction.afterState.entries()) { 7323 const clock = transaction.beforeState.get(client) || 0; 7324 if (afterClock === clock) { 7325 continue; 7326 } 7327 iterateStructs( 7328 transaction, 7329 /** @type {Array<Item|GC>} */ 7330 doc2.store.clients.get(client), 7331 clock, 7332 afterClock, 7333 (item) => { 7334 if (!item.deleted && /** @type {Item} */ 7335 item.content.constructor === ContentFormat && item.constructor !== GC) { 7336 needFullCleanup.add( 7337 /** @type {any} */ 7338 item.parent 7339 ); 7340 } 7341 } 7342 ); 7343 } 7344 transact(doc2, (t) => { 7345 iterateDeletedStructs(transaction, transaction.deleteSet, (item) => { 7346 if (item instanceof GC || !/** @type {YText} */ 7347 item.parent._hasFormatting || needFullCleanup.has( 7348 /** @type {YText} */ 7349 item.parent 7350 )) { 7351 return; 7352 } 7353 const parent = ( 7354 /** @type {YText} */ 7355 item.parent 7356 ); 7357 if (item.content.constructor === ContentFormat) { 7358 needFullCleanup.add(parent); 7359 } else { 7360 cleanupContextlessFormattingGap(t, item); 7361 } 7362 }); 7363 for (const yText of needFullCleanup) { 7364 cleanupYTextFormatting(yText); 7365 } 7366 }); 7367 }; 7368 var deleteText = (transaction, currPos, length2) => { 7369 const startLength = length2; 7370 const startAttrs = copy(currPos.currentAttributes); 7371 const start = currPos.right; 7372 while (length2 > 0 && currPos.right !== null) { 7373 if (currPos.right.deleted === false) { 7374 switch (currPos.right.content.constructor) { 7375 case ContentType: 7376 case ContentEmbed: 7377 case ContentString: 7378 if (length2 < currPos.right.length) { 7379 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length2)); 7380 } 7381 length2 -= currPos.right.length; 7382 currPos.right.delete(transaction); 7383 break; 7384 } 7385 } 7386 currPos.forward(); 7387 } 7388 if (start) { 7389 cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes); 7390 } 7391 const parent = ( 7392 /** @type {AbstractType<any>} */ 7393 /** @type {Item} */ 7394 (currPos.left || currPos.right).parent 7395 ); 7396 if (parent._searchMarker) { 7397 updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length2); 7398 } 7399 return currPos; 7400 }; 7401 var YTextEvent = class extends YEvent { 7402 /** 7403 * @param {YText} ytext 7404 * @param {Transaction} transaction 7405 * @param {Set<any>} subs The keys that changed 7406 */ 7407 constructor(ytext, transaction, subs) { 7408 super(ytext, transaction); 7409 this.childListChanged = false; 7410 this.keysChanged = /* @__PURE__ */ new Set(); 7411 subs.forEach((sub) => { 7412 if (sub === null) { 7413 this.childListChanged = true; 7414 } else { 7415 this.keysChanged.add(sub); 7416 } 7417 }); 7418 } 7419 /** 7420 * @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}>}} 7421 */ 7422 get changes() { 7423 if (this._changes === null) { 7424 const changes = { 7425 keys: this.keys, 7426 delta: this.delta, 7427 added: /* @__PURE__ */ new Set(), 7428 deleted: /* @__PURE__ */ new Set() 7429 }; 7430 this._changes = changes; 7431 } 7432 return ( 7433 /** @type {any} */ 7434 this._changes 7435 ); 7436 } 7437 /** 7438 * Compute the changes in the delta format. 7439 * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document. 7440 * 7441 * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>} 7442 * 7443 * @public 7444 */ 7445 get delta() { 7446 if (this._delta === null) { 7447 const y = ( 7448 /** @type {Doc} */ 7449 this.target.doc 7450 ); 7451 const delta = []; 7452 transact(y, (transaction) => { 7453 const currentAttributes = /* @__PURE__ */ new Map(); 7454 const oldAttributes = /* @__PURE__ */ new Map(); 7455 let item = this.target._start; 7456 let action = null; 7457 const attributes = {}; 7458 let insert2 = ""; 7459 let retain = 0; 7460 let deleteLen = 0; 7461 const addOp = () => { 7462 if (action !== null) { 7463 let op = null; 7464 switch (action) { 7465 case "delete": 7466 if (deleteLen > 0) { 7467 op = { delete: deleteLen }; 7468 } 7469 deleteLen = 0; 7470 break; 7471 case "insert": 7472 if (typeof insert2 === "object" || insert2.length > 0) { 7473 op = { insert: insert2 }; 7474 if (currentAttributes.size > 0) { 7475 op.attributes = {}; 7476 currentAttributes.forEach((value, key) => { 7477 if (value !== null) { 7478 op.attributes[key] = value; 7479 } 7480 }); 7481 } 7482 } 7483 insert2 = ""; 7484 break; 7485 case "retain": 7486 if (retain > 0) { 7487 op = { retain }; 7488 if (!isEmpty(attributes)) { 7489 op.attributes = assign({}, attributes); 7490 } 7491 } 7492 retain = 0; 7493 break; 7494 } 7495 if (op) delta.push(op); 7496 action = null; 7497 } 7498 }; 7499 while (item !== null) { 7500 switch (item.content.constructor) { 7501 case ContentType: 7502 case ContentEmbed: 7503 if (this.adds(item)) { 7504 if (!this.deletes(item)) { 7505 addOp(); 7506 action = "insert"; 7507 insert2 = item.content.getContent()[0]; 7508 addOp(); 7509 } 7510 } else if (this.deletes(item)) { 7511 if (action !== "delete") { 7512 addOp(); 7513 action = "delete"; 7514 } 7515 deleteLen += 1; 7516 } else if (!item.deleted) { 7517 if (action !== "retain") { 7518 addOp(); 7519 action = "retain"; 7520 } 7521 retain += 1; 7522 } 7523 break; 7524 case ContentString: 7525 if (this.adds(item)) { 7526 if (!this.deletes(item)) { 7527 if (action !== "insert") { 7528 addOp(); 7529 action = "insert"; 7530 } 7531 insert2 += /** @type {ContentString} */ 7532 item.content.str; 7533 } 7534 } else if (this.deletes(item)) { 7535 if (action !== "delete") { 7536 addOp(); 7537 action = "delete"; 7538 } 7539 deleteLen += item.length; 7540 } else if (!item.deleted) { 7541 if (action !== "retain") { 7542 addOp(); 7543 action = "retain"; 7544 } 7545 retain += item.length; 7546 } 7547 break; 7548 case ContentFormat: { 7549 const { key, value } = ( 7550 /** @type {ContentFormat} */ 7551 item.content 7552 ); 7553 if (this.adds(item)) { 7554 if (!this.deletes(item)) { 7555 const curVal = currentAttributes.get(key) ?? null; 7556 if (!equalAttrs(curVal, value)) { 7557 if (action === "retain") { 7558 addOp(); 7559 } 7560 if (equalAttrs(value, oldAttributes.get(key) ?? null)) { 7561 delete attributes[key]; 7562 } else { 7563 attributes[key] = value; 7564 } 7565 } else if (value !== null) { 7566 item.delete(transaction); 7567 } 7568 } 7569 } else if (this.deletes(item)) { 7570 oldAttributes.set(key, value); 7571 const curVal = currentAttributes.get(key) ?? null; 7572 if (!equalAttrs(curVal, value)) { 7573 if (action === "retain") { 7574 addOp(); 7575 } 7576 attributes[key] = curVal; 7577 } 7578 } else if (!item.deleted) { 7579 oldAttributes.set(key, value); 7580 const attr = attributes[key]; 7581 if (attr !== void 0) { 7582 if (!equalAttrs(attr, value)) { 7583 if (action === "retain") { 7584 addOp(); 7585 } 7586 if (value === null) { 7587 delete attributes[key]; 7588 } else { 7589 attributes[key] = value; 7590 } 7591 } else if (attr !== null) { 7592 item.delete(transaction); 7593 } 7594 } 7595 } 7596 if (!item.deleted) { 7597 if (action === "insert") { 7598 addOp(); 7599 } 7600 updateCurrentAttributes( 7601 currentAttributes, 7602 /** @type {ContentFormat} */ 7603 item.content 7604 ); 7605 } 7606 break; 7607 } 7608 } 7609 item = item.right; 7610 } 7611 addOp(); 7612 while (delta.length > 0) { 7613 const lastOp = delta[delta.length - 1]; 7614 if (lastOp.retain !== void 0 && lastOp.attributes === void 0) { 7615 delta.pop(); 7616 } else { 7617 break; 7618 } 7619 } 7620 }); 7621 this._delta = delta; 7622 } 7623 return ( 7624 /** @type {any} */ 7625 this._delta 7626 ); 7627 } 7628 }; 7629 var YText = class _YText extends AbstractType { 7630 /** 7631 * @param {String} [string] The initial value of the YText. 7632 */ 7633 constructor(string) { 7634 super(); 7635 this._pending = string !== void 0 ? [() => this.insert(0, string)] : []; 7636 this._searchMarker = []; 7637 this._hasFormatting = false; 7638 } 7639 /** 7640 * Number of characters of this text type. 7641 * 7642 * @type {number} 7643 */ 7644 get length() { 7645 this.doc ?? warnPrematureAccess(); 7646 return this._length; 7647 } 7648 /** 7649 * @param {Doc} y 7650 * @param {Item} item 7651 */ 7652 _integrate(y, item) { 7653 super._integrate(y, item); 7654 try { 7655 this._pending.forEach((f) => f()); 7656 } catch (e) { 7657 console.error(e); 7658 } 7659 this._pending = null; 7660 } 7661 _copy() { 7662 return new _YText(); 7663 } 7664 /** 7665 * Makes a copy of this data type that can be included somewhere else. 7666 * 7667 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 7668 * 7669 * @return {YText} 7670 */ 7671 clone() { 7672 const text2 = new _YText(); 7673 text2.applyDelta(this.toDelta()); 7674 return text2; 7675 } 7676 /** 7677 * Creates YTextEvent and calls observers. 7678 * 7679 * @param {Transaction} transaction 7680 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 7681 */ 7682 _callObserver(transaction, parentSubs) { 7683 super._callObserver(transaction, parentSubs); 7684 const event = new YTextEvent(this, transaction, parentSubs); 7685 callTypeObservers(this, transaction, event); 7686 if (!transaction.local && this._hasFormatting) { 7687 transaction._needFormattingCleanup = true; 7688 } 7689 } 7690 /** 7691 * Returns the unformatted string representation of this YText type. 7692 * 7693 * @public 7694 */ 7695 toString() { 7696 this.doc ?? warnPrematureAccess(); 7697 let str = ""; 7698 let n = this._start; 7699 while (n !== null) { 7700 if (!n.deleted && n.countable && n.content.constructor === ContentString) { 7701 str += /** @type {ContentString} */ 7702 n.content.str; 7703 } 7704 n = n.right; 7705 } 7706 return str; 7707 } 7708 /** 7709 * Returns the unformatted string representation of this YText type. 7710 * 7711 * @return {string} 7712 * @public 7713 */ 7714 toJSON() { 7715 return this.toString(); 7716 } 7717 /** 7718 * Apply a {@link Delta} on this shared YText type. 7719 * 7720 * @param {Array<any>} delta The changes to apply on this element. 7721 * @param {object} opts 7722 * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true. 7723 * 7724 * 7725 * @public 7726 */ 7727 applyDelta(delta, { sanitize = true } = {}) { 7728 if (this.doc !== null) { 7729 transact(this.doc, (transaction) => { 7730 const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map()); 7731 for (let i = 0; i < delta.length; i++) { 7732 const op = delta[i]; 7733 if (op.insert !== void 0) { 7734 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; 7735 if (typeof ins !== "string" || ins.length > 0) { 7736 insertText(transaction, this, currPos, ins, op.attributes || {}); 7737 } 7738 } else if (op.retain !== void 0) { 7739 formatText(transaction, this, currPos, op.retain, op.attributes || {}); 7740 } else if (op.delete !== void 0) { 7741 deleteText(transaction, currPos, op.delete); 7742 } 7743 } 7744 }); 7745 } else { 7746 this._pending.push(() => this.applyDelta(delta)); 7747 } 7748 } 7749 /** 7750 * Returns the Delta representation of this YText type. 7751 * 7752 * @param {Snapshot} [snapshot] 7753 * @param {Snapshot} [prevSnapshot] 7754 * @param {function('removed' | 'added', ID):any} [computeYChange] 7755 * @return {any} The Delta representation of this type. 7756 * 7757 * @public 7758 */ 7759 toDelta(snapshot2, prevSnapshot, computeYChange) { 7760 this.doc ?? warnPrematureAccess(); 7761 const ops = []; 7762 const currentAttributes = /* @__PURE__ */ new Map(); 7763 const doc2 = ( 7764 /** @type {Doc} */ 7765 this.doc 7766 ); 7767 let str = ""; 7768 let n = this._start; 7769 function packStr() { 7770 if (str.length > 0) { 7771 const attributes = {}; 7772 let addAttributes = false; 7773 currentAttributes.forEach((value, key) => { 7774 addAttributes = true; 7775 attributes[key] = value; 7776 }); 7777 const op = { insert: str }; 7778 if (addAttributes) { 7779 op.attributes = attributes; 7780 } 7781 ops.push(op); 7782 str = ""; 7783 } 7784 } 7785 const computeDelta = () => { 7786 while (n !== null) { 7787 if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) { 7788 switch (n.content.constructor) { 7789 case ContentString: { 7790 const cur = currentAttributes.get("ychange"); 7791 if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) { 7792 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") { 7793 packStr(); 7794 currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" }); 7795 } 7796 } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) { 7797 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") { 7798 packStr(); 7799 currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" }); 7800 } 7801 } else if (cur !== void 0) { 7802 packStr(); 7803 currentAttributes.delete("ychange"); 7804 } 7805 str += /** @type {ContentString} */ 7806 n.content.str; 7807 break; 7808 } 7809 case ContentType: 7810 case ContentEmbed: { 7811 packStr(); 7812 const op = { 7813 insert: n.content.getContent()[0] 7814 }; 7815 if (currentAttributes.size > 0) { 7816 const attrs = ( 7817 /** @type {Object<string,any>} */ 7818 {} 7819 ); 7820 op.attributes = attrs; 7821 currentAttributes.forEach((value, key) => { 7822 attrs[key] = value; 7823 }); 7824 } 7825 ops.push(op); 7826 break; 7827 } 7828 case ContentFormat: 7829 if (isVisible(n, snapshot2)) { 7830 packStr(); 7831 updateCurrentAttributes( 7832 currentAttributes, 7833 /** @type {ContentFormat} */ 7834 n.content 7835 ); 7836 } 7837 break; 7838 } 7839 } 7840 n = n.right; 7841 } 7842 packStr(); 7843 }; 7844 if (snapshot2 || prevSnapshot) { 7845 transact(doc2, (transaction) => { 7846 if (snapshot2) { 7847 splitSnapshotAffectedStructs(transaction, snapshot2); 7848 } 7849 if (prevSnapshot) { 7850 splitSnapshotAffectedStructs(transaction, prevSnapshot); 7851 } 7852 computeDelta(); 7853 }, "cleanup"); 7854 } else { 7855 computeDelta(); 7856 } 7857 return ops; 7858 } 7859 /** 7860 * Insert text at a given index. 7861 * 7862 * @param {number} index The index at which to start inserting. 7863 * @param {String} text The text to insert at the specified position. 7864 * @param {TextAttributes} [attributes] Optionally define some formatting 7865 * information to apply on the inserted 7866 * Text. 7867 * @public 7868 */ 7869 insert(index, text2, attributes) { 7870 if (text2.length <= 0) { 7871 return; 7872 } 7873 const y = this.doc; 7874 if (y !== null) { 7875 transact(y, (transaction) => { 7876 const pos = findPosition(transaction, this, index, !attributes); 7877 if (!attributes) { 7878 attributes = {}; 7879 pos.currentAttributes.forEach((v, k) => { 7880 attributes[k] = v; 7881 }); 7882 } 7883 insertText(transaction, this, pos, text2, attributes); 7884 }); 7885 } else { 7886 this._pending.push(() => this.insert(index, text2, attributes)); 7887 } 7888 } 7889 /** 7890 * Inserts an embed at a index. 7891 * 7892 * @param {number} index The index to insert the embed at. 7893 * @param {Object | AbstractType<any>} embed The Object that represents the embed. 7894 * @param {TextAttributes} [attributes] Attribute information to apply on the 7895 * embed 7896 * 7897 * @public 7898 */ 7899 insertEmbed(index, embed, attributes) { 7900 const y = this.doc; 7901 if (y !== null) { 7902 transact(y, (transaction) => { 7903 const pos = findPosition(transaction, this, index, !attributes); 7904 insertText(transaction, this, pos, embed, attributes || {}); 7905 }); 7906 } else { 7907 this._pending.push(() => this.insertEmbed(index, embed, attributes || {})); 7908 } 7909 } 7910 /** 7911 * Deletes text starting from an index. 7912 * 7913 * @param {number} index Index at which to start deleting. 7914 * @param {number} length The number of characters to remove. Defaults to 1. 7915 * 7916 * @public 7917 */ 7918 delete(index, length2) { 7919 if (length2 === 0) { 7920 return; 7921 } 7922 const y = this.doc; 7923 if (y !== null) { 7924 transact(y, (transaction) => { 7925 deleteText(transaction, findPosition(transaction, this, index, true), length2); 7926 }); 7927 } else { 7928 this._pending.push(() => this.delete(index, length2)); 7929 } 7930 } 7931 /** 7932 * Assigns properties to a range of text. 7933 * 7934 * @param {number} index The position where to start formatting. 7935 * @param {number} length The amount of characters to assign properties to. 7936 * @param {TextAttributes} attributes Attribute information to apply on the 7937 * text. 7938 * 7939 * @public 7940 */ 7941 format(index, length2, attributes) { 7942 if (length2 === 0) { 7943 return; 7944 } 7945 const y = this.doc; 7946 if (y !== null) { 7947 transact(y, (transaction) => { 7948 const pos = findPosition(transaction, this, index, false); 7949 if (pos.right === null) { 7950 return; 7951 } 7952 formatText(transaction, this, pos, length2, attributes); 7953 }); 7954 } else { 7955 this._pending.push(() => this.format(index, length2, attributes)); 7956 } 7957 } 7958 /** 7959 * Removes an attribute. 7960 * 7961 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 7962 * 7963 * @param {String} attributeName The attribute name that is to be removed. 7964 * 7965 * @public 7966 */ 7967 removeAttribute(attributeName) { 7968 if (this.doc !== null) { 7969 transact(this.doc, (transaction) => { 7970 typeMapDelete(transaction, this, attributeName); 7971 }); 7972 } else { 7973 this._pending.push(() => this.removeAttribute(attributeName)); 7974 } 7975 } 7976 /** 7977 * Sets or updates an attribute. 7978 * 7979 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 7980 * 7981 * @param {String} attributeName The attribute name that is to be set. 7982 * @param {any} attributeValue The attribute value that is to be set. 7983 * 7984 * @public 7985 */ 7986 setAttribute(attributeName, attributeValue) { 7987 if (this.doc !== null) { 7988 transact(this.doc, (transaction) => { 7989 typeMapSet(transaction, this, attributeName, attributeValue); 7990 }); 7991 } else { 7992 this._pending.push(() => this.setAttribute(attributeName, attributeValue)); 7993 } 7994 } 7995 /** 7996 * Returns an attribute value that belongs to the attribute name. 7997 * 7998 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 7999 * 8000 * @param {String} attributeName The attribute name that identifies the 8001 * queried value. 8002 * @return {any} The queried attribute value. 8003 * 8004 * @public 8005 */ 8006 getAttribute(attributeName) { 8007 return ( 8008 /** @type {any} */ 8009 typeMapGet(this, attributeName) 8010 ); 8011 } 8012 /** 8013 * Returns all attribute name/value pairs in a JSON Object. 8014 * 8015 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks. 8016 * 8017 * @return {Object<string, any>} A JSON Object that describes the attributes. 8018 * 8019 * @public 8020 */ 8021 getAttributes() { 8022 return typeMapGetAll(this); 8023 } 8024 /** 8025 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8026 */ 8027 _write(encoder) { 8028 encoder.writeTypeRef(YTextRefID); 8029 } 8030 }; 8031 var readYText = (_decoder) => new YText(); 8032 var YXmlTreeWalker = class { 8033 /** 8034 * @param {YXmlFragment | YXmlElement} root 8035 * @param {function(AbstractType<any>):boolean} [f] 8036 */ 8037 constructor(root, f = () => true) { 8038 this._filter = f; 8039 this._root = root; 8040 this._currentNode = /** @type {Item} */ 8041 root._start; 8042 this._firstCall = true; 8043 root.doc ?? warnPrematureAccess(); 8044 } 8045 [Symbol.iterator]() { 8046 return this; 8047 } 8048 /** 8049 * Get the next node. 8050 * 8051 * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node. 8052 * 8053 * @public 8054 */ 8055 next() { 8056 let n = this._currentNode; 8057 let type = n && n.content && /** @type {any} */ 8058 n.content.type; 8059 if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) { 8060 do { 8061 type = /** @type {any} */ 8062 n.content.type; 8063 if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) { 8064 n = type._start; 8065 } else { 8066 while (n !== null) { 8067 const nxt = n.next; 8068 if (nxt !== null) { 8069 n = nxt; 8070 break; 8071 } else if (n.parent === this._root) { 8072 n = null; 8073 } else { 8074 n = /** @type {AbstractType<any>} */ 8075 n.parent._item; 8076 } 8077 } 8078 } 8079 } while (n !== null && (n.deleted || !this._filter( 8080 /** @type {ContentType} */ 8081 n.content.type 8082 ))); 8083 } 8084 this._firstCall = false; 8085 if (n === null) { 8086 return { value: void 0, done: true }; 8087 } 8088 this._currentNode = n; 8089 return { value: ( 8090 /** @type {any} */ 8091 n.content.type 8092 ), done: false }; 8093 } 8094 }; 8095 var YXmlFragment = class _YXmlFragment extends AbstractType { 8096 constructor() { 8097 super(); 8098 this._prelimContent = []; 8099 } 8100 /** 8101 * @type {YXmlElement|YXmlText|null} 8102 */ 8103 get firstChild() { 8104 const first = this._first; 8105 return first ? first.content.getContent()[0] : null; 8106 } 8107 /** 8108 * Integrate this type into the Yjs instance. 8109 * 8110 * * Save this struct in the os 8111 * * This type is sent to other client 8112 * * Observer functions are fired 8113 * 8114 * @param {Doc} y The Yjs instance 8115 * @param {Item} item 8116 */ 8117 _integrate(y, item) { 8118 super._integrate(y, item); 8119 this.insert( 8120 0, 8121 /** @type {Array<any>} */ 8122 this._prelimContent 8123 ); 8124 this._prelimContent = null; 8125 } 8126 _copy() { 8127 return new _YXmlFragment(); 8128 } 8129 /** 8130 * Makes a copy of this data type that can be included somewhere else. 8131 * 8132 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8133 * 8134 * @return {YXmlFragment} 8135 */ 8136 clone() { 8137 const el = new _YXmlFragment(); 8138 el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item)); 8139 return el; 8140 } 8141 get length() { 8142 this.doc ?? warnPrematureAccess(); 8143 return this._prelimContent === null ? this._length : this._prelimContent.length; 8144 } 8145 /** 8146 * Create a subtree of childNodes. 8147 * 8148 * @example 8149 * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div') 8150 * for (let node in walker) { 8151 * // `node` is a div node 8152 * nop(node) 8153 * } 8154 * 8155 * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and 8156 * returns a Boolean indicating whether the child 8157 * is to be included in the subtree. 8158 * @return {YXmlTreeWalker} A subtree and a position within it. 8159 * 8160 * @public 8161 */ 8162 createTreeWalker(filter) { 8163 return new YXmlTreeWalker(this, filter); 8164 } 8165 /** 8166 * Returns the first YXmlElement that matches the query. 8167 * Similar to DOM's {@link querySelector}. 8168 * 8169 * Query support: 8170 * - tagname 8171 * TODO: 8172 * - id 8173 * - attribute 8174 * 8175 * @param {CSS_Selector} query The query on the children. 8176 * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. 8177 * 8178 * @public 8179 */ 8180 querySelector(query) { 8181 query = query.toUpperCase(); 8182 const iterator = new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query); 8183 const next = iterator.next(); 8184 if (next.done) { 8185 return null; 8186 } else { 8187 return next.value; 8188 } 8189 } 8190 /** 8191 * Returns all YXmlElements that match the query. 8192 * Similar to Dom's {@link querySelectorAll}. 8193 * 8194 * @todo Does not yet support all queries. Currently only query by tagName. 8195 * 8196 * @param {CSS_Selector} query The query on the children 8197 * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query. 8198 * 8199 * @public 8200 */ 8201 querySelectorAll(query) { 8202 query = query.toUpperCase(); 8203 return from(new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query)); 8204 } 8205 /** 8206 * Creates YXmlEvent and calls observers. 8207 * 8208 * @param {Transaction} transaction 8209 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified. 8210 */ 8211 _callObserver(transaction, parentSubs) { 8212 callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction)); 8213 } 8214 /** 8215 * Get the string representation of all the children of this YXmlFragment. 8216 * 8217 * @return {string} The string representation of all children. 8218 */ 8219 toString() { 8220 return typeListMap(this, (xml) => xml.toString()).join(""); 8221 } 8222 /** 8223 * @return {string} 8224 */ 8225 toJSON() { 8226 return this.toString(); 8227 } 8228 /** 8229 * Creates a Dom Element that mirrors this YXmlElement. 8230 * 8231 * @param {Document} [_document=document] The document object (you must define 8232 * this when calling this method in 8233 * nodejs) 8234 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks 8235 * are presented in the DOM 8236 * @param {any} [binding] You should not set this property. This is 8237 * used if DomBinding wants to create a 8238 * association to the created DOM type. 8239 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8240 * 8241 * @public 8242 */ 8243 toDOM(_document = document, hooks = {}, binding) { 8244 const fragment = _document.createDocumentFragment(); 8245 if (binding !== void 0) { 8246 binding._createAssociation(fragment, this); 8247 } 8248 typeListForEach(this, (xmlType) => { 8249 fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null); 8250 }); 8251 return fragment; 8252 } 8253 /** 8254 * Inserts new content at an index. 8255 * 8256 * @example 8257 * // Insert character 'a' at position 0 8258 * xml.insert(0, [new Y.XmlText('text')]) 8259 * 8260 * @param {number} index The index to insert content at 8261 * @param {Array<YXmlElement|YXmlText>} content The array of content 8262 */ 8263 insert(index, content) { 8264 if (this.doc !== null) { 8265 transact(this.doc, (transaction) => { 8266 typeListInsertGenerics(transaction, this, index, content); 8267 }); 8268 } else { 8269 this._prelimContent.splice(index, 0, ...content); 8270 } 8271 } 8272 /** 8273 * Inserts new content at an index. 8274 * 8275 * @example 8276 * // Insert character 'a' at position 0 8277 * xml.insert(0, [new Y.XmlText('text')]) 8278 * 8279 * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at 8280 * @param {Array<YXmlElement|YXmlText>} content The array of content 8281 */ 8282 insertAfter(ref, content) { 8283 if (this.doc !== null) { 8284 transact(this.doc, (transaction) => { 8285 const refItem = ref && ref instanceof AbstractType ? ref._item : ref; 8286 typeListInsertGenericsAfter(transaction, this, refItem, content); 8287 }); 8288 } else { 8289 const pc = ( 8290 /** @type {Array<any>} */ 8291 this._prelimContent 8292 ); 8293 const index = ref === null ? 0 : pc.findIndex((el) => el === ref) + 1; 8294 if (index === 0 && ref !== null) { 8295 throw create3("Reference item not found"); 8296 } 8297 pc.splice(index, 0, ...content); 8298 } 8299 } 8300 /** 8301 * Deletes elements starting from an index. 8302 * 8303 * @param {number} index Index at which to start deleting elements 8304 * @param {number} [length=1] The number of elements to remove. Defaults to 1. 8305 */ 8306 delete(index, length2 = 1) { 8307 if (this.doc !== null) { 8308 transact(this.doc, (transaction) => { 8309 typeListDelete(transaction, this, index, length2); 8310 }); 8311 } else { 8312 this._prelimContent.splice(index, length2); 8313 } 8314 } 8315 /** 8316 * Transforms this YArray to a JavaScript Array. 8317 * 8318 * @return {Array<YXmlElement|YXmlText|YXmlHook>} 8319 */ 8320 toArray() { 8321 return typeListToArray(this); 8322 } 8323 /** 8324 * Appends content to this YArray. 8325 * 8326 * @param {Array<YXmlElement|YXmlText>} content Array of content to append. 8327 */ 8328 push(content) { 8329 this.insert(this.length, content); 8330 } 8331 /** 8332 * Prepends content to this YArray. 8333 * 8334 * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend. 8335 */ 8336 unshift(content) { 8337 this.insert(0, content); 8338 } 8339 /** 8340 * Returns the i-th element from a YArray. 8341 * 8342 * @param {number} index The index of the element to return from the YArray 8343 * @return {YXmlElement|YXmlText} 8344 */ 8345 get(index) { 8346 return typeListGet(this, index); 8347 } 8348 /** 8349 * Returns a portion of this YXmlFragment into a JavaScript Array selected 8350 * from start to end (end not included). 8351 * 8352 * @param {number} [start] 8353 * @param {number} [end] 8354 * @return {Array<YXmlElement|YXmlText>} 8355 */ 8356 slice(start = 0, end = this.length) { 8357 return typeListSlice(this, start, end); 8358 } 8359 /** 8360 * Executes a provided function on once on every child element. 8361 * 8362 * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray. 8363 */ 8364 forEach(f) { 8365 typeListForEach(this, f); 8366 } 8367 /** 8368 * Transform the properties of this type to binary and write it to an 8369 * BinaryEncoder. 8370 * 8371 * This is called when this Item is sent to a remote peer. 8372 * 8373 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8374 */ 8375 _write(encoder) { 8376 encoder.writeTypeRef(YXmlFragmentRefID); 8377 } 8378 }; 8379 var readYXmlFragment = (_decoder) => new YXmlFragment(); 8380 var YXmlElement = class _YXmlElement extends YXmlFragment { 8381 constructor(nodeName = "UNDEFINED") { 8382 super(); 8383 this.nodeName = nodeName; 8384 this._prelimAttrs = /* @__PURE__ */ new Map(); 8385 } 8386 /** 8387 * @type {YXmlElement|YXmlText|null} 8388 */ 8389 get nextSibling() { 8390 const n = this._item ? this._item.next : null; 8391 return n ? ( 8392 /** @type {YXmlElement|YXmlText} */ 8393 /** @type {ContentType} */ 8394 n.content.type 8395 ) : null; 8396 } 8397 /** 8398 * @type {YXmlElement|YXmlText|null} 8399 */ 8400 get prevSibling() { 8401 const n = this._item ? this._item.prev : null; 8402 return n ? ( 8403 /** @type {YXmlElement|YXmlText} */ 8404 /** @type {ContentType} */ 8405 n.content.type 8406 ) : null; 8407 } 8408 /** 8409 * Integrate this type into the Yjs instance. 8410 * 8411 * * Save this struct in the os 8412 * * This type is sent to other client 8413 * * Observer functions are fired 8414 * 8415 * @param {Doc} y The Yjs instance 8416 * @param {Item} item 8417 */ 8418 _integrate(y, item) { 8419 super._integrate(y, item); 8420 /** @type {Map<string, any>} */ 8421 this._prelimAttrs.forEach((value, key) => { 8422 this.setAttribute(key, value); 8423 }); 8424 this._prelimAttrs = null; 8425 } 8426 /** 8427 * Creates an Item with the same effect as this Item (without position effect) 8428 * 8429 * @return {YXmlElement} 8430 */ 8431 _copy() { 8432 return new _YXmlElement(this.nodeName); 8433 } 8434 /** 8435 * Makes a copy of this data type that can be included somewhere else. 8436 * 8437 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8438 * 8439 * @return {YXmlElement<KV>} 8440 */ 8441 clone() { 8442 const el = new _YXmlElement(this.nodeName); 8443 const attrs = this.getAttributes(); 8444 forEach(attrs, (value, key) => { 8445 el.setAttribute( 8446 key, 8447 /** @type {any} */ 8448 value 8449 ); 8450 }); 8451 el.insert(0, this.toArray().map((v) => v instanceof AbstractType ? v.clone() : v)); 8452 return el; 8453 } 8454 /** 8455 * Returns the XML serialization of this YXmlElement. 8456 * The attributes are ordered by attribute-name, so you can easily use this 8457 * method to compare YXmlElements 8458 * 8459 * @return {string} The string representation of this type. 8460 * 8461 * @public 8462 */ 8463 toString() { 8464 const attrs = this.getAttributes(); 8465 const stringBuilder = []; 8466 const keys2 = []; 8467 for (const key in attrs) { 8468 keys2.push(key); 8469 } 8470 keys2.sort(); 8471 const keysLen = keys2.length; 8472 for (let i = 0; i < keysLen; i++) { 8473 const key = keys2[i]; 8474 stringBuilder.push(key + '="' + attrs[key] + '"'); 8475 } 8476 const nodeName = this.nodeName.toLocaleLowerCase(); 8477 const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : ""; 8478 return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`; 8479 } 8480 /** 8481 * Removes an attribute from this YXmlElement. 8482 * 8483 * @param {string} attributeName The attribute name that is to be removed. 8484 * 8485 * @public 8486 */ 8487 removeAttribute(attributeName) { 8488 if (this.doc !== null) { 8489 transact(this.doc, (transaction) => { 8490 typeMapDelete(transaction, this, attributeName); 8491 }); 8492 } else { 8493 this._prelimAttrs.delete(attributeName); 8494 } 8495 } 8496 /** 8497 * Sets or updates an attribute. 8498 * 8499 * @template {keyof KV & string} KEY 8500 * 8501 * @param {KEY} attributeName The attribute name that is to be set. 8502 * @param {KV[KEY]} attributeValue The attribute value that is to be set. 8503 * 8504 * @public 8505 */ 8506 setAttribute(attributeName, attributeValue) { 8507 if (this.doc !== null) { 8508 transact(this.doc, (transaction) => { 8509 typeMapSet(transaction, this, attributeName, attributeValue); 8510 }); 8511 } else { 8512 this._prelimAttrs.set(attributeName, attributeValue); 8513 } 8514 } 8515 /** 8516 * Returns an attribute value that belongs to the attribute name. 8517 * 8518 * @template {keyof KV & string} KEY 8519 * 8520 * @param {KEY} attributeName The attribute name that identifies the 8521 * queried value. 8522 * @return {KV[KEY]|undefined} The queried attribute value. 8523 * 8524 * @public 8525 */ 8526 getAttribute(attributeName) { 8527 return ( 8528 /** @type {any} */ 8529 typeMapGet(this, attributeName) 8530 ); 8531 } 8532 /** 8533 * Returns whether an attribute exists 8534 * 8535 * @param {string} attributeName The attribute name to check for existence. 8536 * @return {boolean} whether the attribute exists. 8537 * 8538 * @public 8539 */ 8540 hasAttribute(attributeName) { 8541 return ( 8542 /** @type {any} */ 8543 typeMapHas(this, attributeName) 8544 ); 8545 } 8546 /** 8547 * Returns all attribute name/value pairs in a JSON Object. 8548 * 8549 * @param {Snapshot} [snapshot] 8550 * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes. 8551 * 8552 * @public 8553 */ 8554 getAttributes(snapshot2) { 8555 return ( 8556 /** @type {any} */ 8557 snapshot2 ? typeMapGetAllSnapshot(this, snapshot2) : typeMapGetAll(this) 8558 ); 8559 } 8560 /** 8561 * Creates a Dom Element that mirrors this YXmlElement. 8562 * 8563 * @param {Document} [_document=document] The document object (you must define 8564 * this when calling this method in 8565 * nodejs) 8566 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks 8567 * are presented in the DOM 8568 * @param {any} [binding] You should not set this property. This is 8569 * used if DomBinding wants to create a 8570 * association to the created DOM type. 8571 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8572 * 8573 * @public 8574 */ 8575 toDOM(_document = document, hooks = {}, binding) { 8576 const dom = _document.createElement(this.nodeName); 8577 const attrs = this.getAttributes(); 8578 for (const key in attrs) { 8579 const value = attrs[key]; 8580 if (typeof value === "string") { 8581 dom.setAttribute(key, value); 8582 } 8583 } 8584 typeListForEach(this, (yxml) => { 8585 dom.appendChild(yxml.toDOM(_document, hooks, binding)); 8586 }); 8587 if (binding !== void 0) { 8588 binding._createAssociation(dom, this); 8589 } 8590 return dom; 8591 } 8592 /** 8593 * Transform the properties of this type to binary and write it to an 8594 * BinaryEncoder. 8595 * 8596 * This is called when this Item is sent to a remote peer. 8597 * 8598 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8599 */ 8600 _write(encoder) { 8601 encoder.writeTypeRef(YXmlElementRefID); 8602 encoder.writeKey(this.nodeName); 8603 } 8604 }; 8605 var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey()); 8606 var YXmlEvent = class extends YEvent { 8607 /** 8608 * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created. 8609 * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the 8610 * child list changed. 8611 * @param {Transaction} transaction The transaction instance with which the 8612 * change was created. 8613 */ 8614 constructor(target, subs, transaction) { 8615 super(target, transaction); 8616 this.childListChanged = false; 8617 this.attributesChanged = /* @__PURE__ */ new Set(); 8618 subs.forEach((sub) => { 8619 if (sub === null) { 8620 this.childListChanged = true; 8621 } else { 8622 this.attributesChanged.add(sub); 8623 } 8624 }); 8625 } 8626 }; 8627 var YXmlHook = class _YXmlHook extends YMap { 8628 /** 8629 * @param {string} hookName nodeName of the Dom Node. 8630 */ 8631 constructor(hookName) { 8632 super(); 8633 this.hookName = hookName; 8634 } 8635 /** 8636 * Creates an Item with the same effect as this Item (without position effect) 8637 */ 8638 _copy() { 8639 return new _YXmlHook(this.hookName); 8640 } 8641 /** 8642 * Makes a copy of this data type that can be included somewhere else. 8643 * 8644 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8645 * 8646 * @return {YXmlHook} 8647 */ 8648 clone() { 8649 const el = new _YXmlHook(this.hookName); 8650 this.forEach((value, key) => { 8651 el.set(key, value); 8652 }); 8653 return el; 8654 } 8655 /** 8656 * Creates a Dom Element that mirrors this YXmlElement. 8657 * 8658 * @param {Document} [_document=document] The document object (you must define 8659 * this when calling this method in 8660 * nodejs) 8661 * @param {Object.<string, any>} [hooks] Optional property to customize how hooks 8662 * are presented in the DOM 8663 * @param {any} [binding] You should not set this property. This is 8664 * used if DomBinding wants to create a 8665 * association to the created DOM type 8666 * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8667 * 8668 * @public 8669 */ 8670 toDOM(_document = document, hooks = {}, binding) { 8671 const hook = hooks[this.hookName]; 8672 let dom; 8673 if (hook !== void 0) { 8674 dom = hook.createDom(this); 8675 } else { 8676 dom = document.createElement(this.hookName); 8677 } 8678 dom.setAttribute("data-yjs-hook", this.hookName); 8679 if (binding !== void 0) { 8680 binding._createAssociation(dom, this); 8681 } 8682 return dom; 8683 } 8684 /** 8685 * Transform the properties of this type to binary and write it to an 8686 * BinaryEncoder. 8687 * 8688 * This is called when this Item is sent to a remote peer. 8689 * 8690 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8691 */ 8692 _write(encoder) { 8693 encoder.writeTypeRef(YXmlHookRefID); 8694 encoder.writeKey(this.hookName); 8695 } 8696 }; 8697 var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey()); 8698 var YXmlText = class _YXmlText extends YText { 8699 /** 8700 * @type {YXmlElement|YXmlText|null} 8701 */ 8702 get nextSibling() { 8703 const n = this._item ? this._item.next : null; 8704 return n ? ( 8705 /** @type {YXmlElement|YXmlText} */ 8706 /** @type {ContentType} */ 8707 n.content.type 8708 ) : null; 8709 } 8710 /** 8711 * @type {YXmlElement|YXmlText|null} 8712 */ 8713 get prevSibling() { 8714 const n = this._item ? this._item.prev : null; 8715 return n ? ( 8716 /** @type {YXmlElement|YXmlText} */ 8717 /** @type {ContentType} */ 8718 n.content.type 8719 ) : null; 8720 } 8721 _copy() { 8722 return new _YXmlText(); 8723 } 8724 /** 8725 * Makes a copy of this data type that can be included somewhere else. 8726 * 8727 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc. 8728 * 8729 * @return {YXmlText} 8730 */ 8731 clone() { 8732 const text2 = new _YXmlText(); 8733 text2.applyDelta(this.toDelta()); 8734 return text2; 8735 } 8736 /** 8737 * Creates a Dom Element that mirrors this YXmlText. 8738 * 8739 * @param {Document} [_document=document] The document object (you must define 8740 * this when calling this method in 8741 * nodejs) 8742 * @param {Object<string, any>} [hooks] Optional property to customize how hooks 8743 * are presented in the DOM 8744 * @param {any} [binding] You should not set this property. This is 8745 * used if DomBinding wants to create a 8746 * association to the created DOM type. 8747 * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element} 8748 * 8749 * @public 8750 */ 8751 toDOM(_document = document, hooks, binding) { 8752 const dom = _document.createTextNode(this.toString()); 8753 if (binding !== void 0) { 8754 binding._createAssociation(dom, this); 8755 } 8756 return dom; 8757 } 8758 toString() { 8759 return this.toDelta().map((delta) => { 8760 const nestedNodes = []; 8761 for (const nodeName in delta.attributes) { 8762 const attrs = []; 8763 for (const key in delta.attributes[nodeName]) { 8764 attrs.push({ key, value: delta.attributes[nodeName][key] }); 8765 } 8766 attrs.sort((a, b) => a.key < b.key ? -1 : 1); 8767 nestedNodes.push({ nodeName, attrs }); 8768 } 8769 nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1); 8770 let str = ""; 8771 for (let i = 0; i < nestedNodes.length; i++) { 8772 const node = nestedNodes[i]; 8773 str += `<${node.nodeName}`; 8774 for (let j = 0; j < node.attrs.length; j++) { 8775 const attr = node.attrs[j]; 8776 str += ` ${attr.key}="${attr.value}"`; 8777 } 8778 str += ">"; 8779 } 8780 str += delta.insert; 8781 for (let i = nestedNodes.length - 1; i >= 0; i--) { 8782 str += `</${nestedNodes[i].nodeName}>`; 8783 } 8784 return str; 8785 }).join(""); 8786 } 8787 /** 8788 * @return {string} 8789 */ 8790 toJSON() { 8791 return this.toString(); 8792 } 8793 /** 8794 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8795 */ 8796 _write(encoder) { 8797 encoder.writeTypeRef(YXmlTextRefID); 8798 } 8799 }; 8800 var readYXmlText = (decoder) => new YXmlText(); 8801 var AbstractStruct = class { 8802 /** 8803 * @param {ID} id 8804 * @param {number} length 8805 */ 8806 constructor(id2, length2) { 8807 this.id = id2; 8808 this.length = length2; 8809 } 8810 /** 8811 * @type {boolean} 8812 */ 8813 get deleted() { 8814 throw methodUnimplemented(); 8815 } 8816 /** 8817 * Merge this struct with the item to the right. 8818 * This method is already assuming that `this.id.clock + this.length === this.id.clock`. 8819 * Also this method does *not* remove right from StructStore! 8820 * @param {AbstractStruct} right 8821 * @return {boolean} whether this merged with right 8822 */ 8823 mergeWith(right) { 8824 return false; 8825 } 8826 /** 8827 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 8828 * @param {number} offset 8829 * @param {number} encodingRef 8830 */ 8831 write(encoder, offset, encodingRef) { 8832 throw methodUnimplemented(); 8833 } 8834 /** 8835 * @param {Transaction} transaction 8836 * @param {number} offset 8837 */ 8838 integrate(transaction, offset) { 8839 throw methodUnimplemented(); 8840 } 8841 }; 8842 var structGCRefNumber = 0; 8843 var GC = class extends AbstractStruct { 8844 get deleted() { 8845 return true; 8846 } 8847 delete() { 8848 } 8849 /** 8850 * @param {GC} right 8851 * @return {boolean} 8852 */ 8853 mergeWith(right) { 8854 if (this.constructor !== right.constructor) { 8855 return false; 8856 } 8857 this.length += right.length; 8858 return true; 8859 } 8860 /** 8861 * @param {Transaction} transaction 8862 * @param {number} offset 8863 */ 8864 integrate(transaction, offset) { 8865 if (offset > 0) { 8866 this.id.clock += offset; 8867 this.length -= offset; 8868 } 8869 addStruct(transaction.doc.store, this); 8870 } 8871 /** 8872 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8873 * @param {number} offset 8874 */ 8875 write(encoder, offset) { 8876 encoder.writeInfo(structGCRefNumber); 8877 encoder.writeLen(this.length - offset); 8878 } 8879 /** 8880 * @param {Transaction} transaction 8881 * @param {StructStore} store 8882 * @return {null | number} 8883 */ 8884 getMissing(transaction, store2) { 8885 return null; 8886 } 8887 }; 8888 var ContentBinary = class _ContentBinary { 8889 /** 8890 * @param {Uint8Array} content 8891 */ 8892 constructor(content) { 8893 this.content = content; 8894 } 8895 /** 8896 * @return {number} 8897 */ 8898 getLength() { 8899 return 1; 8900 } 8901 /** 8902 * @return {Array<any>} 8903 */ 8904 getContent() { 8905 return [this.content]; 8906 } 8907 /** 8908 * @return {boolean} 8909 */ 8910 isCountable() { 8911 return true; 8912 } 8913 /** 8914 * @return {ContentBinary} 8915 */ 8916 copy() { 8917 return new _ContentBinary(this.content); 8918 } 8919 /** 8920 * @param {number} offset 8921 * @return {ContentBinary} 8922 */ 8923 splice(offset) { 8924 throw methodUnimplemented(); 8925 } 8926 /** 8927 * @param {ContentBinary} right 8928 * @return {boolean} 8929 */ 8930 mergeWith(right) { 8931 return false; 8932 } 8933 /** 8934 * @param {Transaction} transaction 8935 * @param {Item} item 8936 */ 8937 integrate(transaction, item) { 8938 } 8939 /** 8940 * @param {Transaction} transaction 8941 */ 8942 delete(transaction) { 8943 } 8944 /** 8945 * @param {StructStore} store 8946 */ 8947 gc(store2) { 8948 } 8949 /** 8950 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 8951 * @param {number} offset 8952 */ 8953 write(encoder, offset) { 8954 encoder.writeBuf(this.content); 8955 } 8956 /** 8957 * @return {number} 8958 */ 8959 getRef() { 8960 return 3; 8961 } 8962 }; 8963 var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf()); 8964 var ContentDeleted = class _ContentDeleted { 8965 /** 8966 * @param {number} len 8967 */ 8968 constructor(len) { 8969 this.len = len; 8970 } 8971 /** 8972 * @return {number} 8973 */ 8974 getLength() { 8975 return this.len; 8976 } 8977 /** 8978 * @return {Array<any>} 8979 */ 8980 getContent() { 8981 return []; 8982 } 8983 /** 8984 * @return {boolean} 8985 */ 8986 isCountable() { 8987 return false; 8988 } 8989 /** 8990 * @return {ContentDeleted} 8991 */ 8992 copy() { 8993 return new _ContentDeleted(this.len); 8994 } 8995 /** 8996 * @param {number} offset 8997 * @return {ContentDeleted} 8998 */ 8999 splice(offset) { 9000 const right = new _ContentDeleted(this.len - offset); 9001 this.len = offset; 9002 return right; 9003 } 9004 /** 9005 * @param {ContentDeleted} right 9006 * @return {boolean} 9007 */ 9008 mergeWith(right) { 9009 this.len += right.len; 9010 return true; 9011 } 9012 /** 9013 * @param {Transaction} transaction 9014 * @param {Item} item 9015 */ 9016 integrate(transaction, item) { 9017 addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len); 9018 item.markDeleted(); 9019 } 9020 /** 9021 * @param {Transaction} transaction 9022 */ 9023 delete(transaction) { 9024 } 9025 /** 9026 * @param {StructStore} store 9027 */ 9028 gc(store2) { 9029 } 9030 /** 9031 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9032 * @param {number} offset 9033 */ 9034 write(encoder, offset) { 9035 encoder.writeLen(this.len - offset); 9036 } 9037 /** 9038 * @return {number} 9039 */ 9040 getRef() { 9041 return 1; 9042 } 9043 }; 9044 var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen()); 9045 var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false }); 9046 var ContentDoc = class _ContentDoc { 9047 /** 9048 * @param {Doc} doc 9049 */ 9050 constructor(doc2) { 9051 if (doc2._item) { 9052 console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."); 9053 } 9054 this.doc = doc2; 9055 const opts = {}; 9056 this.opts = opts; 9057 if (!doc2.gc) { 9058 opts.gc = false; 9059 } 9060 if (doc2.autoLoad) { 9061 opts.autoLoad = true; 9062 } 9063 if (doc2.meta !== null) { 9064 opts.meta = doc2.meta; 9065 } 9066 } 9067 /** 9068 * @return {number} 9069 */ 9070 getLength() { 9071 return 1; 9072 } 9073 /** 9074 * @return {Array<any>} 9075 */ 9076 getContent() { 9077 return [this.doc]; 9078 } 9079 /** 9080 * @return {boolean} 9081 */ 9082 isCountable() { 9083 return true; 9084 } 9085 /** 9086 * @return {ContentDoc} 9087 */ 9088 copy() { 9089 return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts)); 9090 } 9091 /** 9092 * @param {number} offset 9093 * @return {ContentDoc} 9094 */ 9095 splice(offset) { 9096 throw methodUnimplemented(); 9097 } 9098 /** 9099 * @param {ContentDoc} right 9100 * @return {boolean} 9101 */ 9102 mergeWith(right) { 9103 return false; 9104 } 9105 /** 9106 * @param {Transaction} transaction 9107 * @param {Item} item 9108 */ 9109 integrate(transaction, item) { 9110 this.doc._item = item; 9111 transaction.subdocsAdded.add(this.doc); 9112 if (this.doc.shouldLoad) { 9113 transaction.subdocsLoaded.add(this.doc); 9114 } 9115 } 9116 /** 9117 * @param {Transaction} transaction 9118 */ 9119 delete(transaction) { 9120 if (transaction.subdocsAdded.has(this.doc)) { 9121 transaction.subdocsAdded.delete(this.doc); 9122 } else { 9123 transaction.subdocsRemoved.add(this.doc); 9124 } 9125 } 9126 /** 9127 * @param {StructStore} store 9128 */ 9129 gc(store2) { 9130 } 9131 /** 9132 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9133 * @param {number} offset 9134 */ 9135 write(encoder, offset) { 9136 encoder.writeString(this.doc.guid); 9137 encoder.writeAny(this.opts); 9138 } 9139 /** 9140 * @return {number} 9141 */ 9142 getRef() { 9143 return 9; 9144 } 9145 }; 9146 var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny())); 9147 var ContentEmbed = class _ContentEmbed { 9148 /** 9149 * @param {Object} embed 9150 */ 9151 constructor(embed) { 9152 this.embed = embed; 9153 } 9154 /** 9155 * @return {number} 9156 */ 9157 getLength() { 9158 return 1; 9159 } 9160 /** 9161 * @return {Array<any>} 9162 */ 9163 getContent() { 9164 return [this.embed]; 9165 } 9166 /** 9167 * @return {boolean} 9168 */ 9169 isCountable() { 9170 return true; 9171 } 9172 /** 9173 * @return {ContentEmbed} 9174 */ 9175 copy() { 9176 return new _ContentEmbed(this.embed); 9177 } 9178 /** 9179 * @param {number} offset 9180 * @return {ContentEmbed} 9181 */ 9182 splice(offset) { 9183 throw methodUnimplemented(); 9184 } 9185 /** 9186 * @param {ContentEmbed} right 9187 * @return {boolean} 9188 */ 9189 mergeWith(right) { 9190 return false; 9191 } 9192 /** 9193 * @param {Transaction} transaction 9194 * @param {Item} item 9195 */ 9196 integrate(transaction, item) { 9197 } 9198 /** 9199 * @param {Transaction} transaction 9200 */ 9201 delete(transaction) { 9202 } 9203 /** 9204 * @param {StructStore} store 9205 */ 9206 gc(store2) { 9207 } 9208 /** 9209 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9210 * @param {number} offset 9211 */ 9212 write(encoder, offset) { 9213 encoder.writeJSON(this.embed); 9214 } 9215 /** 9216 * @return {number} 9217 */ 9218 getRef() { 9219 return 5; 9220 } 9221 }; 9222 var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON()); 9223 var ContentFormat = class _ContentFormat { 9224 /** 9225 * @param {string} key 9226 * @param {Object} value 9227 */ 9228 constructor(key, value) { 9229 this.key = key; 9230 this.value = value; 9231 } 9232 /** 9233 * @return {number} 9234 */ 9235 getLength() { 9236 return 1; 9237 } 9238 /** 9239 * @return {Array<any>} 9240 */ 9241 getContent() { 9242 return []; 9243 } 9244 /** 9245 * @return {boolean} 9246 */ 9247 isCountable() { 9248 return false; 9249 } 9250 /** 9251 * @return {ContentFormat} 9252 */ 9253 copy() { 9254 return new _ContentFormat(this.key, this.value); 9255 } 9256 /** 9257 * @param {number} _offset 9258 * @return {ContentFormat} 9259 */ 9260 splice(_offset) { 9261 throw methodUnimplemented(); 9262 } 9263 /** 9264 * @param {ContentFormat} _right 9265 * @return {boolean} 9266 */ 9267 mergeWith(_right) { 9268 return false; 9269 } 9270 /** 9271 * @param {Transaction} _transaction 9272 * @param {Item} item 9273 */ 9274 integrate(_transaction, item) { 9275 const p = ( 9276 /** @type {YText} */ 9277 item.parent 9278 ); 9279 p._searchMarker = null; 9280 p._hasFormatting = true; 9281 } 9282 /** 9283 * @param {Transaction} transaction 9284 */ 9285 delete(transaction) { 9286 } 9287 /** 9288 * @param {StructStore} store 9289 */ 9290 gc(store2) { 9291 } 9292 /** 9293 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9294 * @param {number} offset 9295 */ 9296 write(encoder, offset) { 9297 encoder.writeKey(this.key); 9298 encoder.writeJSON(this.value); 9299 } 9300 /** 9301 * @return {number} 9302 */ 9303 getRef() { 9304 return 6; 9305 } 9306 }; 9307 var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON()); 9308 var ContentJSON = class _ContentJSON { 9309 /** 9310 * @param {Array<any>} arr 9311 */ 9312 constructor(arr) { 9313 this.arr = arr; 9314 } 9315 /** 9316 * @return {number} 9317 */ 9318 getLength() { 9319 return this.arr.length; 9320 } 9321 /** 9322 * @return {Array<any>} 9323 */ 9324 getContent() { 9325 return this.arr; 9326 } 9327 /** 9328 * @return {boolean} 9329 */ 9330 isCountable() { 9331 return true; 9332 } 9333 /** 9334 * @return {ContentJSON} 9335 */ 9336 copy() { 9337 return new _ContentJSON(this.arr); 9338 } 9339 /** 9340 * @param {number} offset 9341 * @return {ContentJSON} 9342 */ 9343 splice(offset) { 9344 const right = new _ContentJSON(this.arr.slice(offset)); 9345 this.arr = this.arr.slice(0, offset); 9346 return right; 9347 } 9348 /** 9349 * @param {ContentJSON} right 9350 * @return {boolean} 9351 */ 9352 mergeWith(right) { 9353 this.arr = this.arr.concat(right.arr); 9354 return true; 9355 } 9356 /** 9357 * @param {Transaction} transaction 9358 * @param {Item} item 9359 */ 9360 integrate(transaction, item) { 9361 } 9362 /** 9363 * @param {Transaction} transaction 9364 */ 9365 delete(transaction) { 9366 } 9367 /** 9368 * @param {StructStore} store 9369 */ 9370 gc(store2) { 9371 } 9372 /** 9373 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9374 * @param {number} offset 9375 */ 9376 write(encoder, offset) { 9377 const len = this.arr.length; 9378 encoder.writeLen(len - offset); 9379 for (let i = offset; i < len; i++) { 9380 const c = this.arr[i]; 9381 encoder.writeString(c === void 0 ? "undefined" : JSON.stringify(c)); 9382 } 9383 } 9384 /** 9385 * @return {number} 9386 */ 9387 getRef() { 9388 return 2; 9389 } 9390 }; 9391 var readContentJSON = (decoder) => { 9392 const len = decoder.readLen(); 9393 const cs = []; 9394 for (let i = 0; i < len; i++) { 9395 const c = decoder.readString(); 9396 if (c === "undefined") { 9397 cs.push(void 0); 9398 } else { 9399 cs.push(JSON.parse(c)); 9400 } 9401 } 9402 return new ContentJSON(cs); 9403 }; 9404 var isDevMode = getVariable("node_env") === "development"; 9405 var ContentAny = class _ContentAny { 9406 /** 9407 * @param {Array<any>} arr 9408 */ 9409 constructor(arr) { 9410 this.arr = arr; 9411 isDevMode && deepFreeze(arr); 9412 } 9413 /** 9414 * @return {number} 9415 */ 9416 getLength() { 9417 return this.arr.length; 9418 } 9419 /** 9420 * @return {Array<any>} 9421 */ 9422 getContent() { 9423 return this.arr; 9424 } 9425 /** 9426 * @return {boolean} 9427 */ 9428 isCountable() { 9429 return true; 9430 } 9431 /** 9432 * @return {ContentAny} 9433 */ 9434 copy() { 9435 return new _ContentAny(this.arr); 9436 } 9437 /** 9438 * @param {number} offset 9439 * @return {ContentAny} 9440 */ 9441 splice(offset) { 9442 const right = new _ContentAny(this.arr.slice(offset)); 9443 this.arr = this.arr.slice(0, offset); 9444 return right; 9445 } 9446 /** 9447 * @param {ContentAny} right 9448 * @return {boolean} 9449 */ 9450 mergeWith(right) { 9451 this.arr = this.arr.concat(right.arr); 9452 return true; 9453 } 9454 /** 9455 * @param {Transaction} transaction 9456 * @param {Item} item 9457 */ 9458 integrate(transaction, item) { 9459 } 9460 /** 9461 * @param {Transaction} transaction 9462 */ 9463 delete(transaction) { 9464 } 9465 /** 9466 * @param {StructStore} store 9467 */ 9468 gc(store2) { 9469 } 9470 /** 9471 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9472 * @param {number} offset 9473 */ 9474 write(encoder, offset) { 9475 const len = this.arr.length; 9476 encoder.writeLen(len - offset); 9477 for (let i = offset; i < len; i++) { 9478 const c = this.arr[i]; 9479 encoder.writeAny(c); 9480 } 9481 } 9482 /** 9483 * @return {number} 9484 */ 9485 getRef() { 9486 return 8; 9487 } 9488 }; 9489 var readContentAny = (decoder) => { 9490 const len = decoder.readLen(); 9491 const cs = []; 9492 for (let i = 0; i < len; i++) { 9493 cs.push(decoder.readAny()); 9494 } 9495 return new ContentAny(cs); 9496 }; 9497 var ContentString = class _ContentString { 9498 /** 9499 * @param {string} str 9500 */ 9501 constructor(str) { 9502 this.str = str; 9503 } 9504 /** 9505 * @return {number} 9506 */ 9507 getLength() { 9508 return this.str.length; 9509 } 9510 /** 9511 * @return {Array<any>} 9512 */ 9513 getContent() { 9514 return this.str.split(""); 9515 } 9516 /** 9517 * @return {boolean} 9518 */ 9519 isCountable() { 9520 return true; 9521 } 9522 /** 9523 * @return {ContentString} 9524 */ 9525 copy() { 9526 return new _ContentString(this.str); 9527 } 9528 /** 9529 * @param {number} offset 9530 * @return {ContentString} 9531 */ 9532 splice(offset) { 9533 const right = new _ContentString(this.str.slice(offset)); 9534 this.str = this.str.slice(0, offset); 9535 const firstCharCode = this.str.charCodeAt(offset - 1); 9536 if (firstCharCode >= 55296 && firstCharCode <= 56319) { 9537 this.str = this.str.slice(0, offset - 1) + "\uFFFD"; 9538 right.str = "\uFFFD" + right.str.slice(1); 9539 } 9540 return right; 9541 } 9542 /** 9543 * @param {ContentString} right 9544 * @return {boolean} 9545 */ 9546 mergeWith(right) { 9547 this.str += right.str; 9548 return true; 9549 } 9550 /** 9551 * @param {Transaction} transaction 9552 * @param {Item} item 9553 */ 9554 integrate(transaction, item) { 9555 } 9556 /** 9557 * @param {Transaction} transaction 9558 */ 9559 delete(transaction) { 9560 } 9561 /** 9562 * @param {StructStore} store 9563 */ 9564 gc(store2) { 9565 } 9566 /** 9567 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9568 * @param {number} offset 9569 */ 9570 write(encoder, offset) { 9571 encoder.writeString(offset === 0 ? this.str : this.str.slice(offset)); 9572 } 9573 /** 9574 * @return {number} 9575 */ 9576 getRef() { 9577 return 4; 9578 } 9579 }; 9580 var readContentString = (decoder) => new ContentString(decoder.readString()); 9581 var typeRefs = [ 9582 readYArray, 9583 readYMap, 9584 readYText, 9585 readYXmlElement, 9586 readYXmlFragment, 9587 readYXmlHook, 9588 readYXmlText 9589 ]; 9590 var YArrayRefID = 0; 9591 var YMapRefID = 1; 9592 var YTextRefID = 2; 9593 var YXmlElementRefID = 3; 9594 var YXmlFragmentRefID = 4; 9595 var YXmlHookRefID = 5; 9596 var YXmlTextRefID = 6; 9597 var ContentType = class _ContentType { 9598 /** 9599 * @param {AbstractType<any>} type 9600 */ 9601 constructor(type) { 9602 this.type = type; 9603 } 9604 /** 9605 * @return {number} 9606 */ 9607 getLength() { 9608 return 1; 9609 } 9610 /** 9611 * @return {Array<any>} 9612 */ 9613 getContent() { 9614 return [this.type]; 9615 } 9616 /** 9617 * @return {boolean} 9618 */ 9619 isCountable() { 9620 return true; 9621 } 9622 /** 9623 * @return {ContentType} 9624 */ 9625 copy() { 9626 return new _ContentType(this.type._copy()); 9627 } 9628 /** 9629 * @param {number} offset 9630 * @return {ContentType} 9631 */ 9632 splice(offset) { 9633 throw methodUnimplemented(); 9634 } 9635 /** 9636 * @param {ContentType} right 9637 * @return {boolean} 9638 */ 9639 mergeWith(right) { 9640 return false; 9641 } 9642 /** 9643 * @param {Transaction} transaction 9644 * @param {Item} item 9645 */ 9646 integrate(transaction, item) { 9647 this.type._integrate(transaction.doc, item); 9648 } 9649 /** 9650 * @param {Transaction} transaction 9651 */ 9652 delete(transaction) { 9653 let item = this.type._start; 9654 while (item !== null) { 9655 if (!item.deleted) { 9656 item.delete(transaction); 9657 } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) { 9658 transaction._mergeStructs.push(item); 9659 } 9660 item = item.right; 9661 } 9662 this.type._map.forEach((item2) => { 9663 if (!item2.deleted) { 9664 item2.delete(transaction); 9665 } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) { 9666 transaction._mergeStructs.push(item2); 9667 } 9668 }); 9669 transaction.changed.delete(this.type); 9670 } 9671 /** 9672 * @param {StructStore} store 9673 */ 9674 gc(store2) { 9675 let item = this.type._start; 9676 while (item !== null) { 9677 item.gc(store2, true); 9678 item = item.right; 9679 } 9680 this.type._start = null; 9681 this.type._map.forEach( 9682 /** @param {Item | null} item */ 9683 (item2) => { 9684 while (item2 !== null) { 9685 item2.gc(store2, true); 9686 item2 = item2.left; 9687 } 9688 } 9689 ); 9690 this.type._map = /* @__PURE__ */ new Map(); 9691 } 9692 /** 9693 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 9694 * @param {number} offset 9695 */ 9696 write(encoder, offset) { 9697 this.type._write(encoder); 9698 } 9699 /** 9700 * @return {number} 9701 */ 9702 getRef() { 9703 return 7; 9704 } 9705 }; 9706 var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder)); 9707 var followRedone = (store2, id2) => { 9708 let nextID = id2; 9709 let diff = 0; 9710 let item; 9711 do { 9712 if (diff > 0) { 9713 nextID = createID(nextID.client, nextID.clock + diff); 9714 } 9715 item = getItem(store2, nextID); 9716 diff = nextID.clock - item.id.clock; 9717 nextID = item.redone; 9718 } while (nextID !== null && item instanceof Item); 9719 return { 9720 item, 9721 diff 9722 }; 9723 }; 9724 var keepItem = (item, keep) => { 9725 while (item !== null && item.keep !== keep) { 9726 item.keep = keep; 9727 item = /** @type {AbstractType<any>} */ 9728 item.parent._item; 9729 } 9730 }; 9731 var splitItem = (transaction, leftItem, diff) => { 9732 const { client, clock } = leftItem.id; 9733 const rightItem = new Item( 9734 createID(client, clock + diff), 9735 leftItem, 9736 createID(client, clock + diff - 1), 9737 leftItem.right, 9738 leftItem.rightOrigin, 9739 leftItem.parent, 9740 leftItem.parentSub, 9741 leftItem.content.splice(diff) 9742 ); 9743 if (leftItem.deleted) { 9744 rightItem.markDeleted(); 9745 } 9746 if (leftItem.keep) { 9747 rightItem.keep = true; 9748 } 9749 if (leftItem.redone !== null) { 9750 rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff); 9751 } 9752 leftItem.right = rightItem; 9753 if (rightItem.right !== null) { 9754 rightItem.right.left = rightItem; 9755 } 9756 transaction._mergeStructs.push(rightItem); 9757 if (rightItem.parentSub !== null && rightItem.right === null) { 9758 rightItem.parent._map.set(rightItem.parentSub, rightItem); 9759 } 9760 leftItem.length = diff; 9761 return rightItem; 9762 }; 9763 var isDeletedByUndoStack = (stack, id2) => some( 9764 stack, 9765 /** @param {StackItem} s */ 9766 (s) => isDeleted(s.deletions, id2) 9767 ); 9768 var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => { 9769 const doc2 = transaction.doc; 9770 const store2 = doc2.store; 9771 const ownClientID = doc2.clientID; 9772 const redone = item.redone; 9773 if (redone !== null) { 9774 return getItemCleanStart(transaction, redone); 9775 } 9776 let parentItem = ( 9777 /** @type {AbstractType<any>} */ 9778 item.parent._item 9779 ); 9780 let left = null; 9781 let right; 9782 if (parentItem !== null && parentItem.deleted === true) { 9783 if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) { 9784 return null; 9785 } 9786 while (parentItem.redone !== null) { 9787 parentItem = getItemCleanStart(transaction, parentItem.redone); 9788 } 9789 } 9790 const parentType = parentItem === null ? ( 9791 /** @type {AbstractType<any>} */ 9792 item.parent 9793 ) : ( 9794 /** @type {ContentType} */ 9795 parentItem.content.type 9796 ); 9797 if (item.parentSub === null) { 9798 left = item.left; 9799 right = item; 9800 while (left !== null) { 9801 let leftTrace = left; 9802 while (leftTrace !== null && /** @type {AbstractType<any>} */ 9803 leftTrace.parent._item !== parentItem) { 9804 leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone); 9805 } 9806 if (leftTrace !== null && /** @type {AbstractType<any>} */ 9807 leftTrace.parent._item === parentItem) { 9808 left = leftTrace; 9809 break; 9810 } 9811 left = left.left; 9812 } 9813 while (right !== null) { 9814 let rightTrace = right; 9815 while (rightTrace !== null && /** @type {AbstractType<any>} */ 9816 rightTrace.parent._item !== parentItem) { 9817 rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone); 9818 } 9819 if (rightTrace !== null && /** @type {AbstractType<any>} */ 9820 rightTrace.parent._item === parentItem) { 9821 right = rightTrace; 9822 break; 9823 } 9824 right = right.right; 9825 } 9826 } else { 9827 right = null; 9828 if (item.right && !ignoreRemoteMapChanges) { 9829 left = item; 9830 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))) { 9831 left = left.right; 9832 while (left.redone) left = getItemCleanStart(transaction, left.redone); 9833 } 9834 if (left && left.right !== null) { 9835 return null; 9836 } 9837 } else { 9838 left = parentType._map.get(item.parentSub) || null; 9839 } 9840 } 9841 const nextClock = getState(store2, ownClientID); 9842 const nextId = createID(ownClientID, nextClock); 9843 const redoneItem = new Item( 9844 nextId, 9845 left, 9846 left && left.lastId, 9847 right, 9848 right && right.id, 9849 parentType, 9850 item.parentSub, 9851 item.content.copy() 9852 ); 9853 item.redone = nextId; 9854 keepItem(redoneItem, true); 9855 redoneItem.integrate(transaction, 0); 9856 return redoneItem; 9857 }; 9858 var Item = class _Item extends AbstractStruct { 9859 /** 9860 * @param {ID} id 9861 * @param {Item | null} left 9862 * @param {ID | null} origin 9863 * @param {Item | null} right 9864 * @param {ID | null} rightOrigin 9865 * @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. 9866 * @param {string | null} parentSub 9867 * @param {AbstractContent} content 9868 */ 9869 constructor(id2, left, origin2, right, rightOrigin, parent, parentSub, content) { 9870 super(id2, content.getLength()); 9871 this.origin = origin2; 9872 this.left = left; 9873 this.right = right; 9874 this.rightOrigin = rightOrigin; 9875 this.parent = parent; 9876 this.parentSub = parentSub; 9877 this.redone = null; 9878 this.content = content; 9879 this.info = this.content.isCountable() ? BIT2 : 0; 9880 } 9881 /** 9882 * This is used to mark the item as an indexed fast-search marker 9883 * 9884 * @type {boolean} 9885 */ 9886 set marker(isMarked) { 9887 if ((this.info & BIT4) > 0 !== isMarked) { 9888 this.info ^= BIT4; 9889 } 9890 } 9891 get marker() { 9892 return (this.info & BIT4) > 0; 9893 } 9894 /** 9895 * If true, do not garbage collect this Item. 9896 */ 9897 get keep() { 9898 return (this.info & BIT1) > 0; 9899 } 9900 set keep(doKeep) { 9901 if (this.keep !== doKeep) { 9902 this.info ^= BIT1; 9903 } 9904 } 9905 get countable() { 9906 return (this.info & BIT2) > 0; 9907 } 9908 /** 9909 * Whether this item was deleted or not. 9910 * @type {Boolean} 9911 */ 9912 get deleted() { 9913 return (this.info & BIT3) > 0; 9914 } 9915 set deleted(doDelete) { 9916 if (this.deleted !== doDelete) { 9917 this.info ^= BIT3; 9918 } 9919 } 9920 markDeleted() { 9921 this.info |= BIT3; 9922 } 9923 /** 9924 * Return the creator clientID of the missing op or define missing items and return null. 9925 * 9926 * @param {Transaction} transaction 9927 * @param {StructStore} store 9928 * @return {null | number} 9929 */ 9930 getMissing(transaction, store2) { 9931 if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store2, this.origin.client)) { 9932 return this.origin.client; 9933 } 9934 if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store2, this.rightOrigin.client)) { 9935 return this.rightOrigin.client; 9936 } 9937 if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store2, this.parent.client)) { 9938 return this.parent.client; 9939 } 9940 if (this.origin) { 9941 this.left = getItemCleanEnd(transaction, store2, this.origin); 9942 this.origin = this.left.lastId; 9943 } 9944 if (this.rightOrigin) { 9945 this.right = getItemCleanStart(transaction, this.rightOrigin); 9946 this.rightOrigin = this.right.id; 9947 } 9948 if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) { 9949 this.parent = null; 9950 } else if (!this.parent) { 9951 if (this.left && this.left.constructor === _Item) { 9952 this.parent = this.left.parent; 9953 this.parentSub = this.left.parentSub; 9954 } else if (this.right && this.right.constructor === _Item) { 9955 this.parent = this.right.parent; 9956 this.parentSub = this.right.parentSub; 9957 } 9958 } else if (this.parent.constructor === ID) { 9959 const parentItem = getItem(store2, this.parent); 9960 if (parentItem.constructor === GC) { 9961 this.parent = null; 9962 } else { 9963 this.parent = /** @type {ContentType} */ 9964 parentItem.content.type; 9965 } 9966 } 9967 return null; 9968 } 9969 /** 9970 * @param {Transaction} transaction 9971 * @param {number} offset 9972 */ 9973 integrate(transaction, offset) { 9974 if (offset > 0) { 9975 this.id.clock += offset; 9976 this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1)); 9977 this.origin = this.left.lastId; 9978 this.content = this.content.splice(offset); 9979 this.length -= offset; 9980 } 9981 if (this.parent) { 9982 if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) { 9983 let left = this.left; 9984 let o; 9985 if (left !== null) { 9986 o = left.right; 9987 } else if (this.parentSub !== null) { 9988 o = /** @type {AbstractType<any>} */ 9989 this.parent._map.get(this.parentSub) || null; 9990 while (o !== null && o.left !== null) { 9991 o = o.left; 9992 } 9993 } else { 9994 o = /** @type {AbstractType<any>} */ 9995 this.parent._start; 9996 } 9997 const conflictingItems = /* @__PURE__ */ new Set(); 9998 const itemsBeforeOrigin = /* @__PURE__ */ new Set(); 9999 while (o !== null && o !== this.right) { 10000 itemsBeforeOrigin.add(o); 10001 conflictingItems.add(o); 10002 if (compareIDs(this.origin, o.origin)) { 10003 if (o.id.client < this.id.client) { 10004 left = o; 10005 conflictingItems.clear(); 10006 } else if (compareIDs(this.rightOrigin, o.rightOrigin)) { 10007 break; 10008 } 10009 } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) { 10010 if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) { 10011 left = o; 10012 conflictingItems.clear(); 10013 } 10014 } else { 10015 break; 10016 } 10017 o = o.right; 10018 } 10019 this.left = left; 10020 } 10021 if (this.left !== null) { 10022 const right = this.left.right; 10023 this.right = right; 10024 this.left.right = this; 10025 } else { 10026 let r; 10027 if (this.parentSub !== null) { 10028 r = /** @type {AbstractType<any>} */ 10029 this.parent._map.get(this.parentSub) || null; 10030 while (r !== null && r.left !== null) { 10031 r = r.left; 10032 } 10033 } else { 10034 r = /** @type {AbstractType<any>} */ 10035 this.parent._start; 10036 this.parent._start = this; 10037 } 10038 this.right = r; 10039 } 10040 if (this.right !== null) { 10041 this.right.left = this; 10042 } else if (this.parentSub !== null) { 10043 this.parent._map.set(this.parentSub, this); 10044 if (this.left !== null) { 10045 this.left.delete(transaction); 10046 } 10047 } 10048 if (this.parentSub === null && this.countable && !this.deleted) { 10049 this.parent._length += this.length; 10050 } 10051 addStruct(transaction.doc.store, this); 10052 this.content.integrate(transaction, this); 10053 addChangedTypeToTransaction( 10054 transaction, 10055 /** @type {AbstractType<any>} */ 10056 this.parent, 10057 this.parentSub 10058 ); 10059 if ( 10060 /** @type {AbstractType<any>} */ 10061 this.parent._item !== null && /** @type {AbstractType<any>} */ 10062 this.parent._item.deleted || this.parentSub !== null && this.right !== null 10063 ) { 10064 this.delete(transaction); 10065 } 10066 } else { 10067 new GC(this.id, this.length).integrate(transaction, 0); 10068 } 10069 } 10070 /** 10071 * Returns the next non-deleted item 10072 */ 10073 get next() { 10074 let n = this.right; 10075 while (n !== null && n.deleted) { 10076 n = n.right; 10077 } 10078 return n; 10079 } 10080 /** 10081 * Returns the previous non-deleted item 10082 */ 10083 get prev() { 10084 let n = this.left; 10085 while (n !== null && n.deleted) { 10086 n = n.left; 10087 } 10088 return n; 10089 } 10090 /** 10091 * Computes the last content address of this Item. 10092 */ 10093 get lastId() { 10094 return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1); 10095 } 10096 /** 10097 * Try to merge two items 10098 * 10099 * @param {Item} right 10100 * @return {boolean} 10101 */ 10102 mergeWith(right) { 10103 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)) { 10104 const searchMarker = ( 10105 /** @type {AbstractType<any>} */ 10106 this.parent._searchMarker 10107 ); 10108 if (searchMarker) { 10109 searchMarker.forEach((marker) => { 10110 if (marker.p === right) { 10111 marker.p = this; 10112 if (!this.deleted && this.countable) { 10113 marker.index -= this.length; 10114 } 10115 } 10116 }); 10117 } 10118 if (right.keep) { 10119 this.keep = true; 10120 } 10121 this.right = right.right; 10122 if (this.right !== null) { 10123 this.right.left = this; 10124 } 10125 this.length += right.length; 10126 return true; 10127 } 10128 return false; 10129 } 10130 /** 10131 * Mark this Item as deleted. 10132 * 10133 * @param {Transaction} transaction 10134 */ 10135 delete(transaction) { 10136 if (!this.deleted) { 10137 const parent = ( 10138 /** @type {AbstractType<any>} */ 10139 this.parent 10140 ); 10141 if (this.countable && this.parentSub === null) { 10142 parent._length -= this.length; 10143 } 10144 this.markDeleted(); 10145 addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length); 10146 addChangedTypeToTransaction(transaction, parent, this.parentSub); 10147 this.content.delete(transaction); 10148 } 10149 } 10150 /** 10151 * @param {StructStore} store 10152 * @param {boolean} parentGCd 10153 */ 10154 gc(store2, parentGCd) { 10155 if (!this.deleted) { 10156 throw unexpectedCase(); 10157 } 10158 this.content.gc(store2); 10159 if (parentGCd) { 10160 replaceStruct(store2, this, new GC(this.id, this.length)); 10161 } else { 10162 this.content = new ContentDeleted(this.length); 10163 } 10164 } 10165 /** 10166 * Transform the properties of this type to binary and write it to an 10167 * BinaryEncoder. 10168 * 10169 * This is called when this Item is sent to a remote peer. 10170 * 10171 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to. 10172 * @param {number} offset 10173 */ 10174 write(encoder, offset) { 10175 const origin2 = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin; 10176 const rightOrigin = this.rightOrigin; 10177 const parentSub = this.parentSub; 10178 const info = this.content.getRef() & BITS5 | (origin2 === null ? 0 : BIT8) | // origin is defined 10179 (rightOrigin === null ? 0 : BIT7) | // right origin is defined 10180 (parentSub === null ? 0 : BIT6); 10181 encoder.writeInfo(info); 10182 if (origin2 !== null) { 10183 encoder.writeLeftID(origin2); 10184 } 10185 if (rightOrigin !== null) { 10186 encoder.writeRightID(rightOrigin); 10187 } 10188 if (origin2 === null && rightOrigin === null) { 10189 const parent = ( 10190 /** @type {AbstractType<any>} */ 10191 this.parent 10192 ); 10193 if (parent._item !== void 0) { 10194 const parentItem = parent._item; 10195 if (parentItem === null) { 10196 const ykey = findRootTypeKey(parent); 10197 encoder.writeParentInfo(true); 10198 encoder.writeString(ykey); 10199 } else { 10200 encoder.writeParentInfo(false); 10201 encoder.writeLeftID(parentItem.id); 10202 } 10203 } else if (parent.constructor === String) { 10204 encoder.writeParentInfo(true); 10205 encoder.writeString(parent); 10206 } else if (parent.constructor === ID) { 10207 encoder.writeParentInfo(false); 10208 encoder.writeLeftID(parent); 10209 } else { 10210 unexpectedCase(); 10211 } 10212 if (parentSub !== null) { 10213 encoder.writeString(parentSub); 10214 } 10215 } 10216 this.content.write(encoder, offset); 10217 } 10218 }; 10219 var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder); 10220 var contentRefs = [ 10221 () => { 10222 unexpectedCase(); 10223 }, 10224 // GC is not ItemContent 10225 readContentDeleted, 10226 // 1 10227 readContentJSON, 10228 // 2 10229 readContentBinary, 10230 // 3 10231 readContentString, 10232 // 4 10233 readContentEmbed, 10234 // 5 10235 readContentFormat, 10236 // 6 10237 readContentType, 10238 // 7 10239 readContentAny, 10240 // 8 10241 readContentDoc, 10242 // 9 10243 () => { 10244 unexpectedCase(); 10245 } 10246 // 10 - Skip is not ItemContent 10247 ]; 10248 var structSkipRefNumber = 10; 10249 var Skip = class extends AbstractStruct { 10250 get deleted() { 10251 return true; 10252 } 10253 delete() { 10254 } 10255 /** 10256 * @param {Skip} right 10257 * @return {boolean} 10258 */ 10259 mergeWith(right) { 10260 if (this.constructor !== right.constructor) { 10261 return false; 10262 } 10263 this.length += right.length; 10264 return true; 10265 } 10266 /** 10267 * @param {Transaction} transaction 10268 * @param {number} offset 10269 */ 10270 integrate(transaction, offset) { 10271 unexpectedCase(); 10272 } 10273 /** 10274 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder 10275 * @param {number} offset 10276 */ 10277 write(encoder, offset) { 10278 encoder.writeInfo(structSkipRefNumber); 10279 writeVarUint(encoder.restEncoder, this.length - offset); 10280 } 10281 /** 10282 * @param {Transaction} transaction 10283 * @param {StructStore} store 10284 * @return {null | number} 10285 */ 10286 getMissing(transaction, store2) { 10287 return null; 10288 } 10289 }; 10290 var glo = ( 10291 /** @type {any} */ 10292 typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {} 10293 ); 10294 var importIdentifier = "__ $YJS$ __"; 10295 if (glo[importIdentifier] === true) { 10296 console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"); 10297 } 10298 glo[importIdentifier] = true; 10299 10300
vendor: 3,901 bytes, lines 10300-10429
10300// node_modules/y-protocols/awareness.js 10301 var outdatedTimeout = 3e4; 10302 var Awareness = class extends Observable { 10303 /** 10304 * @param {Y.Doc} doc 10305 */ 10306 constructor(doc2) { 10307 super(); 10308 this.doc = doc2; 10309 this.clientID = doc2.clientID; 10310 this.states = /* @__PURE__ */ new Map(); 10311 this.meta = /* @__PURE__ */ new Map(); 10312 this._checkInterval = /** @type {any} */ 10313 setInterval(() => { 10314 const now = getUnixTime(); 10315 if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */ 10316 this.meta.get(this.clientID).lastUpdated) { 10317 this.setLocalState(this.getLocalState()); 10318 } 10319 const remove = []; 10320 this.meta.forEach((meta, clientid) => { 10321 if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) { 10322 remove.push(clientid); 10323 } 10324 }); 10325 if (remove.length > 0) { 10326 removeAwarenessStates(this, remove, "timeout"); 10327 } 10328 }, floor(outdatedTimeout / 10)); 10329 doc2.on("destroy", () => { 10330 this.destroy(); 10331 }); 10332 this.setLocalState({}); 10333 } 10334 destroy() { 10335 this.emit("destroy", [this]); 10336 this.setLocalState(null); 10337 super.destroy(); 10338 clearInterval(this._checkInterval); 10339 } 10340 /** 10341 * @return {Object<string,any>|null} 10342 */ 10343 getLocalState() { 10344 return this.states.get(this.clientID) || null; 10345 } 10346 /** 10347 * @param {Object<string,any>|null} state 10348 */ 10349 setLocalState(state) { 10350 const clientID = this.clientID; 10351 const currLocalMeta = this.meta.get(clientID); 10352 const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1; 10353 const prevState = this.states.get(clientID); 10354 if (state === null) { 10355 this.states.delete(clientID); 10356 } else { 10357 this.states.set(clientID, state); 10358 } 10359 this.meta.set(clientID, { 10360 clock, 10361 lastUpdated: getUnixTime() 10362 }); 10363 const added = []; 10364 const updated = []; 10365 const filteredUpdated = []; 10366 const removed = []; 10367 if (state === null) { 10368 removed.push(clientID); 10369 } else if (prevState == null) { 10370 if (state != null) { 10371 added.push(clientID); 10372 } 10373 } else { 10374 updated.push(clientID); 10375 if (!equalityDeep(prevState, state)) { 10376 filteredUpdated.push(clientID); 10377 } 10378 } 10379 if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) { 10380 this.emit("change", [{ added, updated: filteredUpdated, removed }, "local"]); 10381 } 10382 this.emit("update", [{ added, updated, removed }, "local"]); 10383 } 10384 /** 10385 * @param {string} field 10386 * @param {any} value 10387 */ 10388 setLocalStateField(field, value) { 10389 const state = this.getLocalState(); 10390 if (state !== null) { 10391 this.setLocalState({ 10392 ...state, 10393 [field]: value 10394 }); 10395 } 10396 } 10397 /** 10398 * @return {Map<number,Object<string,any>>} 10399 */ 10400 getStates() { 10401 return this.states; 10402 } 10403 }; 10404 var removeAwarenessStates = (awareness, clients, origin2) => { 10405 const removed = []; 10406 for (let i = 0; i < clients.length; i++) { 10407 const clientID = clients[i]; 10408 if (awareness.states.has(clientID)) { 10409 awareness.states.delete(clientID); 10410 if (clientID === awareness.clientID) { 10411 const curMeta = ( 10412 /** @type {MetaClientState} */ 10413 awareness.meta.get(clientID) 10414 ); 10415 awareness.meta.set(clientID, { 10416 clock: curMeta.clock + 1, 10417 lastUpdated: getUnixTime() 10418 }); 10419 } 10420 removed.push(clientID); 10421 } 10422 } 10423 if (removed.length > 0) { 10424 awareness.emit("change", [{ added: [], updated: [], removed }, origin2]); 10425 awareness.emit("update", [{ added: [], updated: [], removed }, origin2]); 10426 } 10427 }; 10428 10429
10429// packages/sync/build-module/config.mjs 10430 var CRDT_DOC_VERSION = 1; 10431 var CRDT_DOC_META_PERSISTENCE_KEY = "fromPersistence"; 10432 var CRDT_RECORD_MAP_KEY = "document"; 10433 var CRDT_STATE_MAP_KEY = "state"; 10434 var CRDT_STATE_MAP_SAVED_AT_KEY = "savedAt"; 10435 var CRDT_STATE_MAP_SAVED_BY_KEY = "savedBy"; 10436 var CRDT_STATE_MAP_VERSION_KEY = "version"; 10437 var LOCAL_EDITOR_ORIGIN = "gutenberg"; 10438 var LOCAL_SYNC_MANAGER_ORIGIN = "syncManager"; 10439 var LOCAL_UNDO_IGNORED_ORIGIN = "gutenberg-undo-ignored"; 10440 10441
10441// packages/sync/build-module/errors.mjs 10442 var ConnectionErrorCode = /* @__PURE__ */ ((ConnectionErrorCode22) => { 10443 ConnectionErrorCode22["AUTHENTICATION_FAILED"] = "authentication-failed"; 10444 ConnectionErrorCode22["CONNECTION_EXPIRED"] = "connection-expired"; 10445 ConnectionErrorCode22["CONNECTION_LIMIT_EXCEEDED"] = "connection-limit-exceeded"; 10446 ConnectionErrorCode22["DOCUMENT_SIZE_LIMIT_EXCEEDED"] = "document-size-limit-exceeded"; 10447 ConnectionErrorCode22["PROTOCOL_MISMATCH"] = "protocol-mismatch"; 10448 ConnectionErrorCode22["UNKNOWN_ERROR"] = "unknown-error"; 10449 return ConnectionErrorCode22; 10450 })(ConnectionErrorCode || {}); 10451 var ConnectionError = class extends Error { 10452 constructor(code = "unknown-error", message) { 10453 super(message); 10454 this.code = code; 10455 this.name = "ConnectionError"; 10456 } 10457 }; 10458 10459
10459// packages/sync/build-module/lock-unlock.mjs 10460 var import_private_apis = __toESM(require_private_apis(), 1); 10461 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)( 10462 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.", 10463 "@wordpress/sync" 10464 ); 10465 10466
10466// packages/sync/build-module/performance.mjs 10467 function logPerformanceTiming(fn) { 10468 return function(...args2) { 10469 const start = performance.now(); 10470 const result = fn.apply(this, args2); 10471 const end = performance.now(); 10472 console.log( 10473 `[SyncManager][performance]: ${fn.name} took ${(end - start).toFixed(2)} ms` 10474 ); 10475 return result; 10476 }; 10477 } 10478 function passThru(fn) { 10479 return ((...args2) => fn(...args2)); 10480 } 10481 function yieldToEventLoop(fn) { 10482 return function(...args2) { 10483 setTimeout(() => { 10484 fn.apply(this, args2); 10485 }, 0); 10486 }; 10487 } 10488 10489
10489// packages/sync/build-module/providers/index.mjs 10490 var import_hooks3 = __toESM(require_hooks(), 1); 10491 10492
10492// packages/sync/build-module/providers/http-polling/polling-manager.mjs 10493 var import_hooks2 = __toESM(require_hooks(), 1); 10494 10495
vendor: 1,589 bytes, lines 10495-10539
10495// node_modules/y-protocols/sync.js 10496 var messageYjsSyncStep1 = 0; 10497 var messageYjsSyncStep2 = 1; 10498 var messageYjsUpdate = 2; 10499 var writeSyncStep1 = (encoder, doc2) => { 10500 writeVarUint(encoder, messageYjsSyncStep1); 10501 const sv = encodeStateVector(doc2); 10502 writeVarUint8Array(encoder, sv); 10503 }; 10504 var writeSyncStep2 = (encoder, doc2, encodedStateVector) => { 10505 writeVarUint(encoder, messageYjsSyncStep2); 10506 writeVarUint8Array(encoder, encodeStateAsUpdate(doc2, encodedStateVector)); 10507 }; 10508 var readSyncStep1 = (decoder, encoder, doc2) => writeSyncStep2(encoder, doc2, readVarUint8Array(decoder)); 10509 var readSyncStep2 = (decoder, doc2, transactionOrigin, errorHandler) => { 10510 try { 10511 applyUpdate(doc2, readVarUint8Array(decoder), transactionOrigin); 10512 } catch (error) { 10513 if (errorHandler != null) errorHandler( 10514 /** @type {Error} */ 10515 error 10516 ); 10517 console.error("Caught error while handling a Yjs update", error); 10518 } 10519 }; 10520 var readUpdate2 = readSyncStep2; 10521 var readSyncMessage = (decoder, encoder, doc2, transactionOrigin, errorHandler) => { 10522 const messageType = readVarUint(decoder); 10523 switch (messageType) { 10524 case messageYjsSyncStep1: 10525 readSyncStep1(decoder, encoder, doc2); 10526 break; 10527 case messageYjsSyncStep2: 10528 readSyncStep2(decoder, doc2, transactionOrigin, errorHandler); 10529 break; 10530 case messageYjsUpdate: 10531 readUpdate2(decoder, doc2, transactionOrigin, errorHandler); 10532 break; 10533 default: 10534 throw new Error("Unknown message type"); 10535 } 10536 return messageType; 10537 }; 10538 10539
10539// packages/sync/build-module/providers/http-polling/config.mjs 10540 var import_hooks = __toESM(require_hooks(), 1); 10541 var DEFAULT_CLIENT_LIMIT_PER_ROOM = 3; 10542 var ERROR_RETRY_DELAYS_SOLO_MS = [ 10543 2e3, 10544 4e3, 10545 8e3, 10546 12e3 10547 // Solo: 26s total retry time solo before dialog 10548 ]; 10549 var ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS = [ 10550 1e3, 10551 2e3, 10552 4e3, 10553 8e3 10554 // With collaborators: 15s total retry time before dialog 10555 ]; 10556 var DISCONNECT_DIALOG_RETRY_MS = 3e4; 10557 var MANUAL_RETRY_INTERVAL_MS = 15e3; 10558 var MAX_ENCODED_UPDATE_SIZE_IN_BYTES = 1 * 1024 * 1024; 10559 var MAX_UPDATE_SIZE_IN_BYTES = Math.floor(MAX_ENCODED_UPDATE_SIZE_IN_BYTES / 4) * 3; 10560 var MAX_ROOMS_PER_REQUEST = 50; 10561 var MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES = 15 * 1024 * 1024; 10562 var MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES = 2 * 1024 * 1024; 10563 var DEFAULT_POLLING_INTERVAL_IN_MS = 4e3; 10564 var DEFAULT_POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS = 1e3; 10565 function getFilteredPollingInterval(hookName, defaultInterval) { 10566 const filteredInterval = (0, import_hooks.applyFilters)(hookName, defaultInterval); 10567 if (typeof filteredInterval !== "number" || !Number.isFinite(filteredInterval) || filteredInterval <= 0) { 10568 return defaultInterval; 10569 } 10570 return Math.min(filteredInterval, defaultInterval); 10571 } 10572 var POLLING_INTERVAL_IN_MS = getFilteredPollingInterval( 10573 "sync.pollingManager.pollingInterval", 10574 DEFAULT_POLLING_INTERVAL_IN_MS 10575 ); 10576 var POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS = getFilteredPollingInterval( 10577 "sync.pollingManager.pollingIntervalWithCollaborators", 10578 DEFAULT_POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS 10579 ); 10580 var POLLING_INTERVAL_BACKGROUND_TAB_IN_MS = 25 * 1e3; 10581 10582
10582// packages/sync/build-module/providers/http-polling/types.mjs 10583 var SyncUpdateType = /* @__PURE__ */ ((SyncUpdateType2) => { 10584 SyncUpdateType2["COMPACTION"] = "compaction"; 10585 SyncUpdateType2["SYNC_STEP_1"] = "sync_step1"; 10586 SyncUpdateType2["SYNC_STEP_2"] = "sync_step2"; 10587 SyncUpdateType2["UPDATE"] = "update"; 10588 return SyncUpdateType2; 10589 })(SyncUpdateType || {}); 10590 10591
10591// packages/sync/build-module/providers/http-polling/utils.mjs 10592 var import_api_fetch = __toESM(require_api_fetch(), 1); 10593 var SYNC_API_PATH = "/wp-sync/v1/updates"; 10594 function uint8ArrayToBase64(data) { 10595 let binary = ""; 10596 const len = data.byteLength; 10597 for (let i = 0; i < len; i++) { 10598 binary += String.fromCharCode(data[i]); 10599 } 10600 return globalThis.btoa(binary); 10601 } 10602 function base64ToUint8Array(base64) { 10603 const binaryString = globalThis.atob(base64); 10604 const len = binaryString.length; 10605 const bytes = new Uint8Array(len); 10606 for (let i = 0; i < len; i++) { 10607 bytes[i] = binaryString.charCodeAt(i); 10608 } 10609 return bytes; 10610 } 10611 function createSyncUpdate(data, type) { 10612 return { 10613 data: uint8ArrayToBase64(data), 10614 type 10615 }; 10616 } 10617 function createUpdateQueue(initial = [], paused = true) { 10618 let isPaused = paused; 10619 const updates = [...initial]; 10620 return { 10621 add(update) { 10622 updates.push(update); 10623 }, 10624 addBulk(bulkUpdates) { 10625 if (0 === bulkUpdates.length) { 10626 return; 10627 } 10628 updates.push(...bulkUpdates); 10629 }, 10630 clear() { 10631 updates.splice(0, updates.length); 10632 }, 10633 get() { 10634 if (isPaused) { 10635 return []; 10636 } 10637 return updates.splice(0, updates.length); 10638 }, 10639 pause() { 10640 isPaused = true; 10641 }, 10642 peek() { 10643 if (isPaused) { 10644 return []; 10645 } 10646 return [...updates]; 10647 }, 10648 restore(restoredUpdates) { 10649 const filtered = restoredUpdates.filter( 10650 (u) => u.type !== SyncUpdateType.COMPACTION 10651 ); 10652 if (0 === filtered.length) { 10653 return; 10654 } 10655 updates.unshift(...filtered); 10656 }, 10657 restoreExact(restoredUpdates) { 10658 if (0 === restoredUpdates.length) { 10659 return; 10660 } 10661 updates.unshift(...restoredUpdates); 10662 }, 10663 resume() { 10664 isPaused = false; 10665 }, 10666 size() { 10667 return updates.length; 10668 }, 10669 take(count) { 10670 if (isPaused || count <= 0) { 10671 return []; 10672 } 10673 return updates.splice(0, count); 10674 } 10675 }; 10676 } 10677 function postSyncUpdate(payload) { 10678 return (0, import_api_fetch.default)({ 10679 method: "POST", 10680 path: SYNC_API_PATH, 10681 data: payload 10682 }); 10683 } 10684 function postSyncUpdateNonBlocking(payload) { 10685 if (payload.rooms.length === 0) { 10686 return; 10687 } 10688 (0, import_api_fetch.default)({ 10689 method: "POST", 10690 path: SYNC_API_PATH, 10691 data: payload, 10692 keepalive: true 10693 }).catch(() => { 10694 }); 10695 } 10696 function intValueOrDefault(value, defaultValue) { 10697 const intValue = parseInt(String(value), 10); 10698 return isNaN(intValue) ? defaultValue : intValue; 10699 } 10700 function rotateWindow(items2, offset, size2) { 10701 if (items2.length === 0) { 10702 return { window: [], nextOffset: 0 }; 10703 } 10704 const start = (offset % items2.length + items2.length) % items2.length; 10705 const wrapped = [...items2.slice(start), ...items2.slice(0, start)]; 10706 return { 10707 window: wrapped.slice(0, Math.max(0, size2)), 10708 nextOffset: (start + Math.max(0, size2)) % items2.length 10709 }; 10710 } 10711 10712
10712// packages/sync/build-module/providers/http-polling/polling-manager.mjs 10713 var POLLING_MANAGER_ORIGIN = "polling-manager"; 10714 function isForbiddenError(error) { 10715 return error?.data?.status === 403; 10716 } 10717 function isRequestBodyTooLargeError(error) { 10718 return error?.data?.status === 413 && error?.code === "rest_sync_body_too_large"; 10719 } 10720 function isProtocolMismatchError(error) { 10721 return error?.code === "rest_sync_protocol_mismatch"; 10722 } 10723 function handleForbiddenError(error, requestedRooms) { 10724 const requestedRoomNames = new Set( 10725 requestedRooms.map((room) => room.room) 10726 ); 10727 const forbiddenRooms = Array.isArray(error.data.rooms) ? error.data.rooms.filter((room) => requestedRoomNames.has(room)) : []; 10728 if (forbiddenRooms.length > 0) { 10729 for (const room of forbiddenRooms) { 10730 const state = roomStates.get(room); 10731 if (state) { 10732 state.log( 10733 "Permission denied, unregistering room", 10734 { error }, 10735 "error", 10736 true 10737 // force 10738 ); 10739 unregisterRoom(room, { sendDisconnectSignal: false }); 10740 } 10741 } 10742 for (const room of requestedRooms) { 10743 if (forbiddenRooms.includes(room.room)) { 10744 continue; 10745 } 10746 if (!roomStates.has(room.room)) { 10747 continue; 10748 } 10749 const remainingState = roomStates.get(room.room); 10750 if (room.updates.length > 0) { 10751 remainingState.updateQueue.restore(room.updates); 10752 } 10753 } 10754 } else { 10755 const rooms = [...roomStates.keys()]; 10756 for (const room of rooms) { 10757 const state = roomStates.get(room); 10758 if (state) { 10759 state.log( 10760 "Permission denied, unregistering room", 10761 { error }, 10762 "error", 10763 true 10764 // force 10765 ); 10766 unregisterRoom(room, { sendDisconnectSignal: false }); 10767 } 10768 } 10769 } 10770 } 10771 var roomStates = /* @__PURE__ */ new Map(); 10772 function createDeprecatedCompactionUpdate(updates) { 10773 const mergeable = updates.filter( 10774 (u) => [SyncUpdateType.COMPACTION, SyncUpdateType.UPDATE].includes( 10775 u.type 10776 ) 10777 ).map((u) => base64ToUint8Array(u.data)); 10778 return createSyncUpdate( 10779 mergeUpdatesV2(mergeable), 10780 SyncUpdateType.COMPACTION 10781 ); 10782 } 10783 function createSyncStep1Update(doc2) { 10784 const encoder = createEncoder(); 10785 writeSyncStep1(encoder, doc2); 10786 return createSyncUpdate( 10787 toUint8Array(encoder), 10788 SyncUpdateType.SYNC_STEP_1 10789 ); 10790 } 10791 function createSyncStep2Update(doc2, step1) { 10792 const decoder = createDecoder(step1); 10793 const encoder = createEncoder(); 10794 readSyncMessage( 10795 decoder, 10796 encoder, 10797 doc2, 10798 POLLING_MANAGER_ORIGIN 10799 ); 10800 return createSyncUpdate( 10801 toUint8Array(encoder), 10802 SyncUpdateType.SYNC_STEP_2 10803 ); 10804 } 10805 function processAwarenessUpdate(state, awareness) { 10806 const currentStates = awareness.getStates(); 10807 const added = /* @__PURE__ */ new Set(); 10808 const updated = /* @__PURE__ */ new Set(); 10809 const removed = new Set( 10810 Array.from(currentStates.keys()).filter( 10811 (clientId) => !state[clientId] 10812 ) 10813 ); 10814 Object.entries(state).forEach(([clientIdString, awarenessState]) => { 10815 const clientId = Number(clientIdString); 10816 if (clientId === awareness.clientID) { 10817 return; 10818 } 10819 if (null === awarenessState) { 10820 currentStates.delete(clientId); 10821 removed.add(clientId); 10822 return; 10823 } 10824 if (!currentStates.has(clientId)) { 10825 currentStates.set(clientId, awarenessState); 10826 added.add(clientId); 10827 return; 10828 } 10829 const currentState = currentStates.get(clientId); 10830 if (JSON.stringify(currentState) !== JSON.stringify(awarenessState)) { 10831 currentStates.set(clientId, awarenessState); 10832 updated.add(clientId); 10833 } 10834 }); 10835 if (added.size + updated.size > 0) { 10836 awareness.emit("change", [ 10837 { 10838 added: Array.from(added), 10839 updated: Array.from(updated), 10840 // Left blank on purpose, as the removal of clients is handled in the if condition below. 10841 removed: [] 10842 } 10843 ]); 10844 } 10845 if (removed.size > 0) { 10846 removeAwarenessStates( 10847 awareness, 10848 Array.from(removed), 10849 POLLING_MANAGER_ORIGIN 10850 ); 10851 } 10852 } 10853 function processDocUpdate(update, doc2, onSync) { 10854 const data = base64ToUint8Array(update.data); 10855 switch (update.type) { 10856 case SyncUpdateType.SYNC_STEP_1: { 10857 return createSyncStep2Update(doc2, data); 10858 } 10859 case SyncUpdateType.SYNC_STEP_2: { 10860 const decoder = createDecoder(data); 10861 const encoder = createEncoder(); 10862 readSyncMessage( 10863 decoder, 10864 encoder, 10865 doc2, 10866 POLLING_MANAGER_ORIGIN 10867 ); 10868 onSync(); 10869 return; 10870 } 10871 case SyncUpdateType.COMPACTION: 10872 case SyncUpdateType.UPDATE: {
10873 applyUpdateV2(doc2, data, POLLING_MANAGER_ORIGIN); 10874 } 10875 } 10876 } 10877 function checkConnectionLimit(awareness, roomState) { 10878 if (!roomState.isPrimaryRoom || hasCheckedConnectionLimit) { 10879 return false; 10880 } 10881 hasCheckedConnectionLimit = true; 10882 const maxClientsPerRoom = (0, import_hooks2.applyFilters)( 10883 "sync.pollingProvider.maxClientsPerRoom", 10884 DEFAULT_CLIENT_LIMIT_PER_ROOM, 10885 roomState.room 10886 ); 10887 const clientCount = Object.keys(awareness).length; 10888 const validatedLimit = intValueOrDefault( 10889 maxClientsPerRoom, 10890 DEFAULT_CLIENT_LIMIT_PER_ROOM 10891 ); 10892 if (clientCount > validatedLimit) { 10893 roomState.log("Connection limit exceeded", { 10894 clientCount, 10895 maxClientsPerRoom: validatedLimit, 10896 room: roomState.room 10897 }); 10898 return true; 10899 } 10900 return false; 10901 } 10902 var areListenersRegistered = false; 10903 var consecutiveFailures = 0; 10904 var hasCheckedConnectionLimit = false; 10905 var isManualRetry = false; 10906 var hasCollaborators = false; 10907 var isActiveBrowser = "visible" === document.visibilityState; 10908 var isPolling = false; 10909 var isUnloadPending = false; 10910 var pollInterval = POLLING_INTERVAL_IN_MS; 10911 var pollingTimeoutId = null; 10912 var syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 10913 var roomOverflowOffset = 0; 10914 function handleBeforeUnload() { 10915 isUnloadPending = true; 10916 } 10917 function handlePageHide() { 10918 const rooms = Array.from(roomStates.entries()).map( 10919 ([room, state]) => ({ 10920 after: 0, 10921 awareness: null, 10922 client_id: state.clientId, 10923 room, 10924 updates: [] 10925 }) 10926 ); 10927 for (let i = 0; i < rooms.length; i += MAX_ROOMS_PER_REQUEST) { 10928 postSyncUpdateNonBlocking({ 10929 rooms: rooms.slice(i, i + MAX_ROOMS_PER_REQUEST) 10930 }); 10931 } 10932 } 10933 function handleVisibilityChange() { 10934 const wasActive = isActiveBrowser; 10935 isActiveBrowser = document.visibilityState === "visible"; 10936 if (isActiveBrowser && !wasActive) { 10937 if (pollingTimeoutId) { 10938 clearTimeout(pollingTimeoutId); 10939 pollingTimeoutId = null; 10940 poll(); 10941 } 10942 } 10943 } 10944 function selectRoomsForRequest() { 10945 const allRooms = Array.from(roomStates.values()); 10946 if (allRooms.length <= MAX_ROOMS_PER_REQUEST) { 10947 return allRooms; 10948 } 10949 const primaryRoom = allRooms.find((state) => state.isPrimaryRoom); 10950 const overflowRooms = allRooms.filter((state) => state !== primaryRoom); 10951 const overflowSlotsPerRequest = MAX_ROOMS_PER_REQUEST - (primaryRoom ? 1 : 0); 10952 const { window: overflowSlice, nextOffset } = rotateWindow( 10953 overflowRooms, 10954 roomOverflowOffset, 10955 overflowSlotsPerRequest 10956 ); 10957 roomOverflowOffset = nextOffset; 10958 if (primaryRoom) { 10959 return [primaryRoom, ...overflowSlice]; 10960 } 10961 return overflowSlice; 10962 } 10963 var textEncoder = new TextEncoder(); 10964 function getJsonByteLength(value) { 10965 return textEncoder.encode(JSON.stringify(value)).byteLength; 10966 } 10967 function createPayloadRoom(state, updates = []) { 10968 return { 10969 after: state.endCursor ?? 0, 10970 awareness: state.localAwarenessState, 10971 client_id: state.clientId, 10972 room: state.room, 10973 updates 10974 }; 10975 } 10976 function getUpdatePayloadSizeDelta(existingUpdateCount, update) { 10977 const commaSize = existingUpdateCount === 0 ? 0 : 1; 10978 return commaSize + getJsonByteLength(update); 10979 } 10980 function buildPayloadForRequest(selectedRoomStates) { 10981 const payload = { rooms: [] }; 10982 const roomsInRequest = []; 10983 for (const state of selectedRoomStates) { 10984 const room = createPayloadRoom(state); 10985 const candidate = { rooms: [...payload.rooms, room] }; 10986 if (payload.rooms.length > 0 && getJsonByteLength(candidate) > syncRequestBodySizeLimit) { 10987 break; 10988 } 10989 payload.rooms.push(room); 10990 roomsInRequest.push(state); 10991 } 10992 const pendingUpdates = roomsInRequest.map( 10993 (state) => state.updateQueue.peek() 10994 ); 10995 const sentUpdateCounts = roomsInRequest.map(() => 0); 10996 let payloadSize = getJsonByteLength(payload); 10997 let addedUpdate = true; 10998 while (addedUpdate) { 10999 addedUpdate = false;
11000 for (let i = 0; i < roomsInRequest.length; i++) { 11001 const update = pendingUpdates[i][sentUpdateCounts[i]]; 11002 if (!update) { 11003 continue; 11004 } 11005 const sizeDelta = getUpdatePayloadSizeDelta( 11006 sentUpdateCounts[i], 11007 update 11008 ); 11009 if (payloadSize + sizeDelta > syncRequestBodySizeLimit) { 11010 continue; 11011 } 11012 sentUpdateCounts[i]++; 11013 payloadSize += sizeDelta; 11014 addedUpdate = true; 11015 } 11016 } 11017 for (let i = 0; i < roomsInRequest.length; i++) { 11018 payload.rooms[i].updates = roomsInRequest[i].updateQueue.take( 11019 sentUpdateCounts[i] 11020 ); 11021 } 11022 return { payload, roomsInRequest }; 11023 } 11024 function restoreExactUpdates(payload) { 11025 for (const room of payload.rooms) { 11026 if (!roomStates.has(room.room) || room.updates.length === 0) { 11027 continue; 11028 } 11029 roomStates.get(room.room).updateQueue.restoreExact(room.updates); 11030 } 11031 } 11032 function poll() { 11033 isPolling = true; 11034 pollingTimeoutId = null; 11035 async function start() { 11036 if (0 === roomStates.size) { 11037 isPolling = false; 11038 return; 11039 } 11040 isUnloadPending = false; 11041 const { payload, roomsInRequest } = buildPayloadForRequest( 11042 selectRoomsForRequest() 11043 ); 11044 roomsInRequest.forEach((state) => { 11045 state.onStatusChange({ status: "connecting" }); 11046 }); 11047 try { 11048 const { rooms } = await postSyncUpdate(payload); 11049 consecutiveFailures = 0; 11050 isManualRetry = false; 11051 syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 11052 roomsInRequest.forEach((state) => { 11053 if (roomStates.get(state.room) !== state) { 11054 return; 11055 } 11056 state.onStatusChange({ status: "connected" }); 11057 }); 11058 hasCollaborators = false; 11059 rooms.forEach((room) => { 11060 if (!roomStates.has(room.room)) { 11061 return; 11062 } 11063 const roomState = roomStates.get(room.room); 11064 roomState.endCursor = room.end_cursor; 11065 if (checkConnectionLimit(room.awareness, roomState)) { 11066 roomState.onStatusChange({ 11067 status: "disconnected", 11068 error: new ConnectionError( 11069 ConnectionErrorCode.CONNECTION_LIMIT_EXCEEDED, 11070 "Connection limit exceeded" 11071 ) 11072 }); 11073 unregisterRoom(room.room); 11074 return; 11075 } 11076 roomState.processAwarenessUpdate(room.awareness); 11077 if (roomState.isPrimaryRoom && Object.keys(room.awareness).length > 1) { 11078 hasCollaborators = true; 11079 roomStates.forEach((state) => { 11080 state.updateQueue.resume(); 11081 }); 11082 } 11083 const responseUpdates = []; 11084 for (const update of room.updates) { 11085 try { 11086 const response = roomState.processDocUpdate(update); 11087 if (response) { 11088 responseUpdates.push(response); 11089 } 11090 } catch (error) { 11091 roomState.log( 11092 "Failed to apply sync update", 11093 { error, update }, 11094 "error", 11095 true 11096 // force 11097 ); 11098 } 11099 } 11100 roomState.updateQueue.addBulk(responseUpdates); 11101 if (room.should_compact) { 11102 roomState.log("Server requested compaction update"); 11103 roomState.updateQueue.clear(); 11104 roomState.updateQueue.add( 11105 roomState.createCompactionUpdate() 11106 ); 11107 } else if (room.compaction_request) { 11108 roomState.log("Server requested (old) compaction update"); 11109 roomState.updateQueue.add( 11110 createDeprecatedCompactionUpdate( 11111 room.compaction_request 11112 ) 11113 ); 11114 } 11115 }); 11116 if (isActiveBrowser && hasCollaborators) { 11117 pollInterval = POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS; 11118 } else if (isActiveBrowser) { 11119 pollInterval = POLLING_INTERVAL_IN_MS; 11120 } else { 11121 pollInterval = POLLING_INTERVAL_BACKGROUND_TAB_IN_MS; 11122 } 11123 } catch (error) { 11124 if (isForbiddenError(error)) { 11125 handleForbiddenError(error, payload.rooms); 11126 if (roomStates.size === 0) { 11127 isPolling = false;
11128 return; 11129 } 11130 } else if (isRequestBodyTooLargeError(error)) { 11131 syncRequestBodySizeLimit = Math.max( 11132 MIN_SYNC_REQUEST_BODY_SIZE_LIMIT_IN_BYTES, 11133 Math.floor(syncRequestBodySizeLimit / 2) 11134 ); 11135 pollInterval = hasCollaborators ? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS[0] : ERROR_RETRY_DELAYS_SOLO_MS[0]; 11136 restoreExactUpdates(payload); 11137 for (const room of payload.rooms) { 11138 if (!roomStates.has(room.room)) { 11139 continue; 11140 } 11141 roomStates.get(room.room).log( 11142 "Sync request body too large, retrying with smaller batches", 11143 { 11144 error, 11145 nextPoll: pollInterval, 11146 syncRequestBodySizeLimit 11147 }, 11148 "error", 11149 true 11150 // force 11151 ); 11152 } 11153 } else if (isProtocolMismatchError(error)) { 11154 const affectedRooms = [...roomStates.entries()]; 11155 for (const [, state] of affectedRooms) { 11156 state.onStatusChange({ 11157 status: "disconnected", 11158 error: new ConnectionError( 11159 ConnectionErrorCode.PROTOCOL_MISMATCH, 11160 "Protocol mismatch between client and server" 11161 ) 11162 }); 11163 } 11164 for (const [room] of affectedRooms) { 11165 unregisterRoom(room, { sendDisconnectSignal: false }); 11166 } 11167 isPolling = false; 11168 return; 11169 } else { 11170 consecutiveFailures++; 11171 const retrySchedule = hasCollaborators ? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS : ERROR_RETRY_DELAYS_SOLO_MS; 11172 if (consecutiveFailures <= retrySchedule.length) { 11173 pollInterval = retrySchedule[consecutiveFailures - 1]; 11174 } else { 11175 pollInterval = DISCONNECT_DIALOG_RETRY_MS; 11176 } 11177 if (isManualRetry) { 11178 pollInterval = MANUAL_RETRY_INTERVAL_MS; 11179 isManualRetry = false; 11180 } 11181 for (const room of payload.rooms) { 11182 if (!roomStates.has(room.room)) { 11183 continue; 11184 } 11185 const state = roomStates.get(room.room); 11186 if (room.updates.length > 0 && state.endCursor > 0) { 11187 state.updateQueue.clear(); 11188 state.updateQueue.add(state.createCompactionUpdate()); 11189 } else if (room.updates.length > 0) { 11190 state.updateQueue.restore(room.updates); 11191 } 11192 state.log( 11193 "Error posting sync update, will retry with backoff", 11194 { error, nextPoll: pollInterval }, 11195 "error", 11196 true 11197 // force 11198 ); 11199 } 11200 if (!isUnloadPending) { 11201 const backgroundRetriesFailed = consecutiveFailures > retrySchedule.length; 11202 roomsInRequest.forEach((state) => { 11203 if (roomStates.get(state.room) !== state) { 11204 return; 11205 } 11206 state.onStatusChange({ 11207 status: "disconnected", 11208 canManuallyRetry: true, 11209 consecutiveFailures, 11210 backgroundRetriesFailed, 11211 willAutoRetryInMs: pollInterval 11212 }); 11213 }); 11214 } 11215 } 11216 } 11217 pollingTimeoutId = setTimeout(poll, pollInterval); 11218 } 11219 void start(); 11220 } 11221 function registerRoom({ 11222 room, 11223 doc: doc2, 11224 awareness, 11225 log, 11226 onSync, 11227 onStatusChange 11228 }) { 11229 if (roomStates.has(room)) { 11230 return; 11231 } 11232 const updateQueue = createUpdateQueue([createSyncStep1Update(doc2)]); 11233 const isPrimaryRoom = 0 === roomStates.size; 11234 function onAwarenessUpdate() {
11235 roomState.localAwarenessState = awareness.getLocalState() ?? {}; 11236 } 11237 function onDocUpdate(update, origin2) { 11238 if (POLLING_MANAGER_ORIGIN === origin2) { 11239 return; 11240 } 11241 if (update.byteLength > MAX_UPDATE_SIZE_IN_BYTES) { 11242 const state = roomStates.get(room); 11243 if (!state) { 11244 return; 11245 } 11246 state.log("Document size limit exceeded", { 11247 maxUpdateSizeInBytes: MAX_UPDATE_SIZE_IN_BYTES, 11248 updateSizeInBytes: update.byteLength 11249 }); 11250 state.onStatusChange({ 11251 status: "disconnected", 11252 error: new ConnectionError( 11253 ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED, 11254 "Document size limit exceeded" 11255 ) 11256 }); 11257 unregisterRoom(room); 11258 return; 11259 } 11260 updateQueue.add(createSyncUpdate(update, SyncUpdateType.UPDATE)); 11261 } 11262 function unregister() { 11263 doc2.off("updateV2", onDocUpdate); 11264 awareness.off("change", onAwarenessUpdate); 11265 updateQueue.clear(); 11266 } 11267 const roomState = { 11268 clientId: doc2.clientID, 11269 createCompactionUpdate: () => createSyncUpdate( 11270 encodeStateAsUpdateV2(doc2), 11271 SyncUpdateType.COMPACTION 11272 ), 11273 endCursor: 0, 11274 isPrimaryRoom,
11275 localAwarenessState: awareness.getLocalState() ?? {}, 11276 log, 11277 onStatusChange, 11278 processAwarenessUpdate: (state) => processAwarenessUpdate(state, awareness), 11279 processDocUpdate: (update) => processDocUpdate(update, doc2, onSync), 11280 room, 11281 unregister, 11282 updateQueue 11283 }; 11284 doc2.on("updateV2", onDocUpdate); 11285 awareness.on("change", onAwarenessUpdate); 11286 roomStates.set(room, roomState); 11287 if (!areListenersRegistered) { 11288 window.addEventListener("beforeunload", handleBeforeUnload); 11289 window.addEventListener("pagehide", handlePageHide); 11290 document.addEventListener("visibilitychange", handleVisibilityChange); 11291 areListenersRegistered = true; 11292 } 11293 if (!isPolling) { 11294 poll(); 11295 } 11296 } 11297 function unregisterRoom(room, { sendDisconnectSignal = true } = {}) { 11298 const state = roomStates.get(room); 11299 if (state) { 11300 if (sendDisconnectSignal) { 11301 const rooms = [ 11302 { 11303 after: 0, 11304 awareness: null, 11305 client_id: state.clientId, 11306 room, 11307 updates: [] 11308 } 11309 ]; 11310 postSyncUpdateNonBlocking({ rooms }); 11311 } 11312 state.unregister(); 11313 roomStates.delete(room); 11314 } 11315 if (0 === roomStates.size && areListenersRegistered) { 11316 window.removeEventListener("beforeunload", handleBeforeUnload); 11317 window.removeEventListener("pagehide", handlePageHide); 11318 document.removeEventListener( 11319 "visibilitychange", 11320 handleVisibilityChange 11321 ); 11322 areListenersRegistered = false; 11323 hasCheckedConnectionLimit = false; 11324 consecutiveFailures = 0; 11325 roomOverflowOffset = 0; 11326 syncRequestBodySizeLimit = MAX_SYNC_REQUEST_BODY_SIZE_IN_BYTES; 11327 } 11328 } 11329 function retryNow() { 11330 isManualRetry = true; 11331 if (pollingTimeoutId) { 11332 clearTimeout(pollingTimeoutId); 11333 pollingTimeoutId = null; 11334 poll(); 11335 } 11336 } 11337 var pollingManager = { 11338 registerRoom, 11339 retryNow, 11340 unregisterRoom 11341 }; 11342 11343
11343// packages/sync/build-module/providers/http-polling/http-polling-provider.mjs 11344 var HttpPollingProvider = class extends ObservableV2 { 11345 constructor(options) { 11346 super(); 11347 this.options = options; 11348 this.log("Initializing", { room: options.room }); 11349 this.awareness = options.awareness ?? new Awareness(options.ydoc); 11350 this.connect(); 11351 } 11352 awareness; 11353 status = "disconnected"; 11354 synced = false; 11355 /** 11356 * Connect to the endpoint and initialize sync. 11357 */ 11358 connect() { 11359 this.log("Connecting"); 11360 pollingManager.registerRoom({ 11361 room: this.options.room, 11362 doc: this.options.ydoc, 11363 awareness: this.awareness, 11364 log: this.log, 11365 onStatusChange: this.emitStatus, 11366 onSync: this.onSync 11367 }); 11368 } 11369 /** 11370 * Destroy the provider and cleanup resources. 11371 */ 11372 destroy() { 11373 this.disconnect(); 11374 super.destroy(); 11375 } 11376 /** 11377 * Disconnect the provider and allow reconnection later. 11378 */ 11379 disconnect() { 11380 this.log("Disconnecting"); 11381 pollingManager.unregisterRoom(this.options.room); 11382 this.emitStatus({ status: "disconnected" }); 11383 } 11384 /** 11385 * Emit connection status, passing the full object through so that 11386 * additional fields (e.g. `willAutoRetryInMs`) are preserved for consumers. 11387 * 11388 * @param connectionStatus The connection status object 11389 */ 11390 emitStatus = (connectionStatus) => { 11391 const { status } = connectionStatus; 11392 const error = status === "disconnected" ? connectionStatus.error : void 0; 11393 if (this.status === status && !error) { 11394 return; 11395 } 11396 if (status === "connecting" && this.status !== "disconnected") { 11397 return; 11398 } 11399 this.log("Status change", { status, error }); 11400 this.status = status; 11401 this.emit("status", [connectionStatus]); 11402 }; 11403 /** 11404 * Log debug messages if debugging is enabled. 11405 * 11406 * @param message The debug message 11407 * @param debug Additional debug information 11408 * @param errorLevel The console method to use for logging 11409 * @param force Whether to force logging regardless of debug setting 11410 */ 11411 log = (message, debug = {}, errorLevel = "log", force = false) => { 11412 if (!this.options.debug && !force) { 11413 return; 11414 } 11415 const logFn = console[errorLevel] || console.log; 11416 logFn(`[${this.constructor.name}]: ${message}`, { 11417 room: this.options.room, 11418 ...debug 11419 }); 11420 }; 11421 /** 11422 * Handle synchronization events from the polling manager. 11423 */ 11424 onSync = () => { 11425 if (!this.synced) { 11426 this.synced = true; 11427 this.log("Synced"); 11428 } 11429 }; 11430 }; 11431 function createHttpPollingProvider() { 11432 return async ({ 11433 awareness, 11434 objectType, 11435 objectId, 11436 ydoc 11437 }) => { 11438 const room = objectId ? `${objectType}:${objectId}` : objectType; 11439 const provider = new HttpPollingProvider({ 11440 awareness, 11441 // debug: true, 11442 room, 11443 ydoc 11444 }); 11445 return { 11446 destroy: () => provider.destroy(), 11447 // Adapter: ObservableV2.on is compatible with ProviderOn 11448 // The callback receives data as the first parameter 11449 on: (event, callback) => { 11450 provider.on(event, callback); 11451 } 11452 }; 11453 }; 11454 } 11455 11456
11456// packages/sync/build-module/providers/index.mjs 11457 var providerCreators = null; 11458 function getDefaultProviderCreators() { 11459 return [createHttpPollingProvider()]; 11460 } 11461 function isProviderCreator(creator) { 11462 return "function" === typeof creator; 11463 } 11464 function getProviderCreators() { 11465 if (providerCreators) { 11466 return providerCreators; 11467 } 11468 if (!window._wpCollaborationEnabled) { 11469 return []; 11470 } 11471 const filteredProviderCreators = (0, import_hooks3.applyFilters)( 11472 "sync.providers", 11473 getDefaultProviderCreators() 11474 ); 11475 if (!Array.isArray(filteredProviderCreators)) { 11476 providerCreators = []; 11477 return providerCreators; 11478 } 11479 providerCreators = filteredProviderCreators.filter(isProviderCreator); 11480 return providerCreators; 11481 } 11482 11483
11483// packages/sync/build-module/y-utilities/y-multidoc-undomanager.mjs 11484 var popStackItem2 = (mum, type) => { 11485 const stack = type === "undo" ? mum.undoStack : mum.redoStack; 11486 while (stack.length > 0) { 11487 const um = ( 11488 /** @type {Y.UndoManager} */ 11489 stack.pop() 11490 ); 11491 const prevUmStack = type === "undo" ? um.undoStack : um.redoStack; 11492 const stackItem = ( 11493 /** @type {any} */ 11494 prevUmStack.pop() 11495 ); 11496 let actionPerformed = false; 11497 if (type === "undo") { 11498 um.undoStack = [stackItem]; 11499 actionPerformed = um.undo() !== null; 11500 um.undoStack = prevUmStack; 11501 } else { 11502 um.redoStack = [stackItem]; 11503 actionPerformed = um.redo() !== null; 11504 um.redoStack = prevUmStack; 11505 } 11506 if (actionPerformed) { 11507 return stackItem; 11508 } 11509 } 11510 return null; 11511 }; 11512 var YMultiDocUndoManager = class extends Observable { 11513 /** 11514 * @param {Y.AbstractType<any>|Array<Y.AbstractType<any>>} typeScope Accepts either a single type, or an array of types 11515 * @param {ConstructorParameters<typeof Y.UndoManager>[1]} opts 11516 */ 11517 constructor(typeScope = [], opts = {}) { 11518 super(); 11519 this.docs = /* @__PURE__ */ new Map();
11520 this.trackedOrigins = opts.trackedOrigins || /* @__PURE__ */ new Set([null]); 11521 opts.trackedOrigins = this.trackedOrigins; 11522 this._defaultOpts = opts; 11523 this.undoStack = []; 11524 this.redoStack = []; 11525 this.addToScope(typeScope); 11526 } 11527 /** 11528 * @param {Array<Y.AbstractType<any>> | Y.AbstractType<any>} ytypes 11529 */ 11530 addToScope(ytypes) { 11531 ytypes = isArray(ytypes) ? ytypes : [ytypes]; 11532 ytypes.forEach((ytype) => { 11533 const ydoc = ( 11534 /** @type {Y.Doc} */ 11535 ytype.doc 11536 ); 11537 const um = setIfUndefined(this.docs, ydoc, () => { 11538 const um2 = new UndoManager([ytype], this._defaultOpts); 11539 um2.on( 11540 "stack-cleared", 11541 /** @param {any} opts */ 11542 ({ 11543 undoStackCleared, 11544 redoStackCleared 11545 }) => { 11546 this.clear(undoStackCleared, redoStackCleared); 11547 } 11548 ); 11549 ydoc.on("destroy", () => { 11550 this.docs.delete(ydoc); 11551 this.undoStack = this.undoStack.filter( 11552 (um3) => um3.doc !== ydoc 11553 ); 11554 this.redoStack = this.redoStack.filter( 11555 (um3) => um3.doc !== ydoc 11556 ); 11557 }); 11558 um2.on( 11559 "stack-item-added", 11560 /** @param {any} change */ 11561 (change) => { 11562 const stack = change.type === "undo" ? this.undoStack : this.redoStack; 11563 stack.push(um2); 11564 this.emit("stack-item-added", [ 11565 { ...change, ydoc }, 11566 this 11567 ]); 11568 } 11569 ); 11570 um2.on( 11571 "stack-item-updated", 11572 /** @param {any} change */ 11573 (change) => { 11574 this.emit("stack-item-updated", [ 11575 { ...change, ydoc }, 11576 this 11577 ]); 11578 } 11579 ); 11580 um2.on( 11581 "stack-item-popped", 11582 /** @param {any} change */ 11583 (change) => { 11584 this.emit("stack-item-popped", [ 11585 { ...change, ydoc }, 11586 this 11587 ]); 11588 } 11589 ); 11590 return um2; 11591 }); 11592 if (um.scope.every((yt) => yt !== ytype)) { 11593 um.scope.push(ytype); 11594 } 11595 }); 11596 } 11597 /** 11598 * @param {any} origin 11599 */ 11600 /* c8 ignore next 3 */ 11601 addTrackedOrigin(origin2) { 11602 this.trackedOrigins.add(origin2); 11603 } 11604 /** 11605 * @param {any} origin 11606 */ 11607 /* c8 ignore next 3 */ 11608 removeTrackedOrigin(origin2) { 11609 this.trackedOrigins.delete(origin2); 11610 } 11611 /** 11612 * Undo last changes on type. 11613 * 11614 * @return {any?} Returns StackItem if a change was applied 11615 */ 11616 undo() { 11617 return popStackItem2(this, "undo"); 11618 } 11619 /** 11620 * Redo last undo operation. 11621 * 11622 * @return {any?} Returns StackItem if a change was applied 11623 */ 11624 redo() { 11625 return popStackItem2(this, "redo"); 11626 } 11627 clear(clearUndoStack = true, clearRedoStack = true) { 11628 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) { 11629 this.docs.forEach((um) => { 11630 clearUndoStack && (this.undoStack = []); 11631 clearRedoStack && (this.redoStack = []); 11632 um.clear(clearUndoStack, clearRedoStack); 11633 }); 11634 this.emit("stack-cleared", [ 11635 { 11636 undoStackCleared: clearUndoStack, 11637 redoStackCleared: clearRedoStack 11638 } 11639 ]); 11640 } 11641 } 11642 /* c8 ignore next 5 */ 11643 stopCapturing() { 11644 this.docs.forEach((um) => { 11645 um.stopCapturing(); 11646 }); 11647 } 11648 /** 11649 * Are undo steps available? 11650 * 11651 * @return {boolean} `true` if undo is possible 11652 */ 11653 canUndo() { 11654 return this.undoStack.length > 0; 11655 } 11656 /** 11657 * Are redo steps available? 11658 * 11659 * @return {boolean} `true` if redo is possible 11660 */ 11661 canRedo() { 11662 return this.redoStack.length > 0; 11663 } 11664 destroy() { 11665 this.docs.forEach((um) => um.destroy()); 11666 super.destroy(); 11667 } 11668 }; 11669 11670
11670// packages/sync/build-module/undo-manager.mjs 11671 function createUndoManager() { 11672 const undoMetaHandlers = /* @__PURE__ */ new Map(); 11673 const yUndoManager = new YMultiDocUndoManager([], { 11674 // Throttle undo/redo captures after 500ms of inactivity. 11675 // 500 was selected from subjective local UX testing, shorter timeouts 11676 // may cause mid-word undo stack items. 11677 captureTimeout: 500, 11678 // Ensure that we only scope the undo/redo to the current editor. 11679 // The yjs document's clientID is added once it's available. 11680 trackedOrigins: /* @__PURE__ */ new Set([LOCAL_EDITOR_ORIGIN]) 11681 }); 11682 const getUndoStackState = () => ({ 11683 hasRedo: yUndoManager.canRedo(), 11684 hasUndo: yUndoManager.canUndo() 11685 }); 11686 const notifyUndoStackChange = (ydoc) => { 11687 undoMetaHandlers.get(ydoc)?.onUndoStackChange?.(getUndoStackState()); 11688 }; 11689 yUndoManager.on("stack-item-added", (event) => { 11690 const handlers = undoMetaHandlers.get(event.ydoc); 11691 if (!handlers) { 11692 return; 11693 } 11694 handlers.addUndoMeta(event.ydoc, event.stackItem.meta); 11695 notifyUndoStackChange(event.ydoc); 11696 }); 11697 yUndoManager.on("stack-item-updated", (event) => { 11698 notifyUndoStackChange(event.ydoc); 11699 }); 11700 yUndoManager.on("stack-item-popped", (event) => { 11701 const handlers = undoMetaHandlers.get(event.ydoc); 11702 if (!handlers) { 11703 return; 11704 } 11705 handlers.restoreUndoMeta(event.ydoc, event.stackItem.meta); 11706 notifyUndoStackChange(event.ydoc); 11707 }); 11708 yUndoManager.on("stack-cleared", () => { 11709 undoMetaHandlers.forEach((handlers) => { 11710 handlers.onUndoStackChange?.(getUndoStackState()); 11711 }); 11712 }); 11713 return { 11714 /** 11715 * Record changes into the history. 11716 * Since Yjs automatically tracks changes, this method translates the WordPress 11717 * HistoryRecord format into Yjs operations. 11718 * 11719 * @param _record A record of changes to record. 11720 * @param _isStaged Whether to immediately create an undo point or not. 11721 */ 11722 addRecord(_record, _isStaged = false) { 11723 }, 11724 /** 11725 * Add a Yjs map to the scope of the undo manager. 11726 * 11727 * @param {Y.Map< any >} ymap The Yjs map to add to the scope. 11728 * @param handlers Handlers for the scoped document. 11729 * @param handlers.addUndoMeta Handler to add metadata to undo items. 11730 * @param handlers.onUndoStackChange Handler for undo stack changes. 11731 * @param handlers.restoreUndoMeta Handler to restore metadata from undo items. 11732 */ 11733 addToScope(ymap, handlers) { 11734 if (ymap.doc === null) { 11735 return; 11736 } 11737 const ydoc = ymap.doc; 11738 yUndoManager.addToScope(ymap); 11739 if (!undoMetaHandlers.has(ydoc)) { 11740 ydoc.on("destroy", () => undoMetaHandlers.delete(ydoc)); 11741 } 11742 undoMetaHandlers.set(ydoc, handlers); 11743 }, 11744 /** 11745 * Undo the last recorded changes. 11746 * 11747 */ 11748 undo() { 11749 if (!yUndoManager.canUndo()) { 11750 return; 11751 } 11752 yUndoManager.undo(); 11753 return []; 11754 }, 11755 /** 11756 * Redo the last undone changes. 11757 */ 11758 redo() { 11759 if (!yUndoManager.canRedo()) { 11760 return; 11761 } 11762 yUndoManager.redo(); 11763 return []; 11764 }, 11765 /** 11766 * Check if there are changes that can be undone. 11767 * 11768 * @return {boolean} Whether there are changes to undo. 11769 */ 11770 hasUndo() { 11771 return yUndoManager.canUndo(); 11772 }, 11773 /** 11774 * Check if there are changes that can be redone. 11775 * 11776 * @return {boolean} Whether there are changes to redo. 11777 */ 11778 hasRedo() { 11779 return yUndoManager.canRedo(); 11780 }, 11781 /** 11782 * Stop capturing changes into the current undo item. 11783 * The next change will create a new undo item. 11784 */ 11785 stopCapturing() { 11786 yUndoManager.stopCapturing(); 11787 } 11788 }; 11789 } 11790 11791
11791// packages/sync/build-module/utils.mjs 11792 function createYjsDoc(documentMeta = {}) { 11793 const metaMap = new Map( 11794 Object.entries(documentMeta) 11795 ); 11796 return new Doc({ meta: metaMap }); 11797 } 11798 function initializeYjsDoc(ydoc) { 11799 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11800 stateMap.set(CRDT_STATE_MAP_VERSION_KEY, CRDT_DOC_VERSION); 11801 } 11802 function markEntityAsSaved(ydoc) { 11803 const recordMeta = ydoc.getMap(CRDT_STATE_MAP_KEY); 11804 recordMeta.set(CRDT_STATE_MAP_SAVED_AT_KEY, Date.now()); 11805 recordMeta.set(CRDT_STATE_MAP_SAVED_BY_KEY, ydoc.clientID); 11806 } 11807 function pseudoRandomID() { 11808 return Math.floor(Math.random() * 1e9); 11809 } 11810 function serializeCrdtDoc(crdtDoc) { 11811 return JSON.stringify({ 11812 document: toBase64(encodeStateAsUpdateV2(crdtDoc)), 11813 updateId: pseudoRandomID() 11814 // helps with debugging 11815 }); 11816 } 11817 function deserializeCrdtDoc(serializedCrdtDoc) { 11818 try { 11819 const { document: document2 } = JSON.parse(serializedCrdtDoc); 11820 const docMeta = { 11821 [CRDT_DOC_META_PERSISTENCE_KEY]: true 11822 }; 11823 const ydoc = createYjsDoc(docMeta); 11824 const yupdate = fromBase64(document2); 11825 applyUpdateV2(ydoc, yupdate); 11826 ydoc.clientID = pseudoRandomID(); 11827 return ydoc; 11828 } catch { 11829 return null; 11830 } 11831 } 11832 11833
11833// packages/sync/build-module/manager.mjs 11834 function getEntityId(objectType, objectId) { 11835 return `${objectType}_${objectId}`; 11836 } 11837 function createSyncManager(debug = false) { 11838 const debugWrap = debug ? logPerformanceTiming : passThru; 11839 const collectionStates = /* @__PURE__ */ new Map(); 11840 const entityStates = /* @__PURE__ */ new Map(); 11841 let undoManager2; 11842 function log(component, message, entityId, context = {}) { 11843 if (!debug) { 11844 return; 11845 } 11846 console.log(`[SyncManager][${component}]: ${message}`, { 11847 ...context, 11848 entityId 11849 }); 11850 } 11851 async function loadEntity(syncConfig, objectType, objectId, record, handlers) { 11852 const providerCreators2 = getProviderCreators(); 11853 const entityId = getEntityId(objectType, objectId); 11854 if (0 === providerCreators2.length) { 11855 log("loadEntity", "no providers, skipping", entityId); 11856 return; 11857 } 11858 if (entityStates.has(entityId)) { 11859 log("loadEntity", "already loaded", entityId); 11860 return; 11861 } 11862 if (false === syncConfig.shouldSync?.(objectType, objectId)) { 11863 log("loadEntity", "shouldSync false, skipping", entityId); 11864 return; 11865 } 11866 log("loadEntity", "loading", entityId); 11867 handlers = { 11868 addUndoMeta: debugWrap(handlers.addUndoMeta), 11869 editRecord: debugWrap(handlers.editRecord), 11870 getEditedRecord: debugWrap(handlers.getEditedRecord), 11871 onStatusChange: debugWrap(handlers.onStatusChange), 11872 persistCRDTDoc: debugWrap(handlers.persistCRDTDoc), 11873 refetchRecord: debugWrap(handlers.refetchRecord), 11874 restoreUndoMeta: debugWrap(handlers.restoreUndoMeta), 11875 onUndoStackChange: handlers.onUndoStackChange ? debugWrap(handlers.onUndoStackChange) : void 0 11876 }; 11877 const ydoc = createYjsDoc({ objectType }); 11878 const recordMap = ydoc.getMap(CRDT_RECORD_MAP_KEY); 11879 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11880 const now = Date.now(); 11881 let hasObserversAttached = false; 11882 let isEntityUnloaded = false; 11883 const unload = () => { 11884 log("loadEntity", "unloading", entityId); 11885 isEntityUnloaded = true; 11886 providerResults?.forEach((result) => result.destroy()); 11887 handlers.onStatusChange(null); 11888 if (hasObserversAttached) { 11889 recordMap.unobserveDeep(onRecordUpdate); 11890 stateMap.unobserve(onStateMapUpdate); 11891 } 11892 ydoc.destroy(); 11893 entityStates.delete(entityId); 11894 }; 11895 const awareness = syncConfig.createAwareness?.(ydoc, objectId); 11896 const onRecordUpdate = (_events, transaction) => { 11897 if (transaction.local && !(transaction.origin instanceof UndoManager)) { 11898 return; 11899 } 11900 void internal.updateEntityRecord(objectType, objectId); 11901 }; 11902 const onStateMapUpdate = (event, transaction) => { 11903 if (transaction.local) { 11904 return; 11905 } 11906 event.keysChanged.forEach((key) => { 11907 switch (key) { 11908 case CRDT_STATE_MAP_SAVED_AT_KEY: 11909 const savedAt = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY); 11910 if ("number" === typeof savedAt && savedAt > now) { 11911 log("loadEntity", "refetching record", entityId); 11912 void handlers.refetchRecord().catch(() => { 11913 }); 11914 } 11915 break; 11916 } 11917 }); 11918 }; 11919 if (!undoManager2) { 11920 undoManager2 = createUndoManager(); 11921 } 11922 const { addUndoMeta, onUndoStackChange, restoreUndoMeta } = handlers; 11923 undoManager2.addToScope(recordMap, { 11924 addUndoMeta, 11925 restoreUndoMeta, 11926 onUndoStackChange 11927 }); 11928 let providerResults; 11929 const entityState = { 11930 awareness, 11931 handlers, 11932 objectId, 11933 objectType, 11934 syncConfig, 11935 unload, 11936 ydoc 11937 }; 11938 entityStates.set(entityId, entityState); 11939 log("loadEntity", "connecting", entityId); 11940 providerResults = await Promise.all( 11941 providerCreators2.map(async (create9) => { 11942 const provider = await create9({ 11943 objectType, 11944 objectId, 11945 ydoc, 11946 awareness, 11947 Y: yjs_exports 11948 }); 11949 provider.on("status", handlers.onStatusChange); 11950 return provider; 11951 }) 11952 ); 11953 if (isEntityUnloaded) { 11954 log("loadEntity", "unloaded during connect, aborting", entity
11954Id); 11955 providerResults.forEach((result) => result.destroy()); 11956 return; 11957 } 11958 initializeYjsDoc(ydoc); 11959 internal.applyPersistedCrdtDoc(objectType, objectId, record); 11960 recordMap.observeDeep(onRecordUpdate); 11961 stateMap.observe(onStateMapUpdate); 11962 hasObserversAttached = true; 11963 } 11964 async function loadCollection(syncConfig, objectType, handlers) { 11965 const providerCreators2 = getProviderCreators(); 11966 const entityId = getEntityId(objectType, null); 11967 if (0 === providerCreators2.length) { 11968 log("loadCollection", "no providers, skipping", entityId); 11969 return; 11970 } 11971 if (collectionStates.has(objectType)) { 11972 log("loadCollection", "already loaded", entityId); 11973 return; 11974 } 11975 if (false === syncConfig.shouldSync?.(objectType, null)) { 11976 log("loadCollection", "shouldSync false, skipping", entityId); 11977 return; 11978 } 11979 log("loadCollection", "loading", entityId); 11980 const ydoc = createYjsDoc({ collection: true, objectType }); 11981 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY); 11982 const now = Date.now(); 11983 let hasObserversAttached = false; 11984 let isCollectionUnloaded = false; 11985 const unload = () => { 11986 log("loadCollection", "unloading", entityId); 11987 isCollectionUnloaded = true; 11988 providerResults?.forEach((result) => result.destroy()); 11989 handlers.onStatusChange(null); 11990 if (hasObserversAttached) { 11991 stateMap.unobserve(onStateMapUpdate); 11992 } 11993 ydoc.destroy(); 11994 collectionStates.delete(objectType); 11995 }; 11996 const onStateMapUpdate = (event, transaction) => { 11997 if (transaction.local) { 11998 return; 11999 } 12000 event.keysChanged.forEach((key) => { 12001 switch (key) { 12002 case CRDT_STATE_MAP_SAVED_AT_KEY: 12003 const newValue = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY); 12004 if ("number" === typeof newValue && newValue > now) { 12005 void handlers.refetchRecords().catch(() => { 12006 }); 12007 } 12008 break; 12009 } 12010 }); 12011 }; 12012 const awareness = syncConfig.createAwareness?.(ydoc); 12013 let providerResults; 12014 const collectionState = { 12015 awareness, 12016 handlers, 12017 syncConfig, 12018 unload, 12019 ydoc 12020 }; 12021 collectionStates.set(objectType, collectionState); 12022 log("loadCollection", "connecting", entityId); 12023 providerResults = await Promise.all( 12024 providerCreators2.map(async (create9) => { 12025 const provider = await create9({ 12026 awareness, 12027 objectType, 12028 objectId: null, 12029 ydoc, 12030 Y: yjs_exports 12031 }); 12032 provider.on("status", handlers.onStatusChange); 12033 return provider; 12034 }) 12035 ); 12036 if (isCollectionUnloaded) { 12037 log( 12038 "loadCollection", 12039 "unloaded during connect, aborting", 12040 entityId 12041 ); 12042 providerResults.forEach((result) => result.destroy()); 12043 return; 12044 } 12045 stateMap.observe(onStateMapUpdate); 12046 hasObserversAttached = true; 12047 initializeYjsDoc(ydoc); 12048 } 12049 function unloadEntity(objectType, objectId) { 12050 const entityId = getEntityId(objectType, objectId); 12051 log("unloadEntity", "unloading", entityId); 12052 entityStates.get(entityId)?.unload(); 12053 updateCRDTDoc(objectType, null, {}, origin, { 12054 isSave: true 12055 }); 12056 } 12057 function unloadAll() { 12058 log("unloadAll", "unloading all entities", "all"); 12059 for (const [, entityState] of [...entityStates]) { 12060 entityState.unload(); 12061 } 12062 entityStates.clear(); 12063 undoManager2 = void 0; 12064 for (const [, collectionState] of [...collectionStates]) { 12065 collectionState.unload(); 12066 } 12067 collectionStates.clear(); 12068 } 12069 function getAwareness(objectType, objectId) { 12070 const entityId = getEntityId(objectType, objectId); 12071 const entityState = entityStates.get(entityId); 12072 if (!entityState || !entityState.awareness) { 12073 return void 0; 12074 } 12075 return entityState.awareness; 12076 } 12077 function _applyPersistedCrdtDoc(objectType, objectId, record) { 12078 const entityId = getEntityId(objectType, objectId); 12079 const entityState = entityStates.get(entityId); 12080 if (!entityState) {
12081 log("applyPersistedCrdtDoc", "no entity state", entityId); 12082 return; 12083 } 12084 const { 12085 handlers, 12086 syncConfig: { 12087 applyChangesToCRDTDoc, 12088 getChangesFromCRDTDoc, 12089 getPersistedCRDTDoc 12090 }, 12091 ydoc: targetDoc 12092 } = entityState; 12093 const serialized = getPersistedCRDTDoc?.(record); 12094 const tempDoc = serialized ? deserializeCrdtDoc(serialized) : null; 12095 if (!tempDoc) { 12096 log("applyPersistedCrdtDoc", "no persisted doc", entityId); 12097 targetDoc.transact(() => { 12098 applyChangesToCRDTDoc(targetDoc, record); 12099 handlers.persistCRDTDoc(); 12100 }, LOCAL_SYNC_MANAGER_ORIGIN); 12101 return; 12102 } 12103 const update = encodeStateAsUpdateV2(tempDoc); 12104 applyUpdateV2(targetDoc, update); 12105 const invalidations = getChangesFromCRDTDoc(tempDoc, record); 12106 const invalidatedKeys = Object.keys(invalidations); 12107 tempDoc.destroy(); 12108 if (0 === invalidatedKeys.length) { 12109 log("applyPersistedCrdtDoc", "valid persisted doc", entityId); 12110 return; 12111 } 12112 log("applyPersistedCrdtDoc", "invalidated keys", entityId, { 12113 invalidatedKeys 12114 }); 12115 const changes = invalidatedKeys.reduce( 12116 (acc, key) => Object.assign(acc, { 12117 [key]: record[key] 12118 }), 12119 {} 12120 ); 12121 targetDoc.transact(() => { 12122 applyChangesToCRDTDoc(targetDoc, changes); 12123 handlers.persistCRDTDoc(); 12124 }, LOCAL_SYNC_MANAGER_ORIGIN); 12125 } 12126 function updateCRDTDoc(objectType, objectId, changes, origin2, options = {}) { 12127 const { isSave = false, isNewUndoLevel = false } = options; 12128 const entityId = getEntityId(objectType, objectId); 12129 const entityState = entityStates.get(entityId); 12130 const collectionState = collectionStates.get(objectType); 12131 if (entityState) { 12132 const { syncConfig, ydoc } = entityState; 12133 if (isNewUndoLevel && undoManager2) { 12134 undoManager2.stopCapturing?.(); 12135 } 12136 ydoc.transact(() => {
12137 log("updateCRDTDoc", "applying changes", entityId, { 12138 changedKeys: Object.keys(changes) 12139 }); 12140 syncConfig.applyChangesToCRDTDoc(ydoc, changes); 12141 if (isSave) { 12142 markEntityAsSaved(ydoc); 12143 } 12144 }, origin2); 12145 } 12146 if (collectionState && isSave) { 12147 collectionState.ydoc.transact(() => { 12148 markEntityAsSaved(collectionState.ydoc); 12149 }, origin2); 12150 } 12151 } 12152 const deferUpdateCRDTDoc = yieldToEventLoop(updateCRDTDoc); 12153 function updateOrDefer(objectType, objectId, changes, origin2, options = {}) { 12154 const hasRemotePeers = (getAwareness(objectType, objectId)?.getStates().size ?? 0) > 1; 12155 const update = hasRemotePeers ? updateCRDTDoc : deferUpdateCRDTDoc; 12156 update(objectType, objectId, changes, origin2, options); 12157 } 12158 async function _updateEntityRecord(objectType, objectId) { 12159 const entityId = getEntityId(objectType, objectId); 12160 const entityState = entityStates.get(entityId); 12161 if (!entityState) { 12162 log("updateEntityRecord", "no entity state", entityId); 12163 return; 12164 } 12165 const { handlers, syncConfig, ydoc } = entityState; 12166 const changes = syncConfig.getChangesFromCRDTDoc( 12167 ydoc, 12168 await handlers.getEditedRecord() 12169 ); 12170 const changedKeys = Object.keys(changes); 12171 if (0 === changedKeys.length) { 12172 return; 12173 }
12174 log("updateEntityRecord", "changes", entityId, { 12175 changedKeys 12176 }); 12177 handlers.editRecord(changes); 12178 } 12179 async function createPersistedCRDTDoc(objectType, objectId) { 12180 const entityId = getEntityId(objectType, objectId); 12181 const entityState = entityStates.get(entityId); 12182 if (!entityState?.ydoc) { 12183 return null; 12184 } 12185 await new Promise((resolve) => setTimeout(resolve, 0)); 12186 return serializeCrdtDoc(entityState.ydoc); 12187 } 12188 const internal = { 12189 applyPersistedCrdtDoc: debugWrap(_applyPersistedCrdtDoc), 12190 updateEntityRecord: debugWrap(_updateEntityRecord) 12191 }; 12192 return { 12193 createPersistedCRDTDoc: debugWrap(createPersistedCRDTDoc), 12194 getAwareness, 12195 load: debugWrap(loadEntity), 12196 loadCollection: debugWrap(loadCollection), 12197 // Use getter to ensure we always return the current value of `undoManager`. 12198 get undoManager() { 12199 return undoManager2; 12200 }, 12201 unload: debugWrap(unloadEntity), 12202 unloadAll: debugWrap(unloadAll), 12203 update: debugWrap(updateOrDefer) 12204 }; 12205 } 12206 12207
vendor: 7,816 bytes, lines 12207-12409
12207// node_modules/diff/libesm/diff/base.js 12208 var Diff = class { 12209 diff(oldStr, newStr, options = {}) { 12210 let callback; 12211 if (typeof options === "function") { 12212 callback = options; 12213 options = {}; 12214 } else if ("callback" in options) { 12215 callback = options.callback; 12216 } 12217 const oldString = this.castInput(oldStr, options); 12218 const newString = this.castInput(newStr, options); 12219 const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); 12220 const newTokens = this.removeEmpty(this.tokenize(newString, options)); 12221 return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); 12222 } 12223 diffWithOptionsObj(oldTokens, newTokens, options, callback) { 12224 var _a; 12225 const done = (value) => { 12226 value = this.postProcess(value, options); 12227 if (callback) { 12228 setTimeout(function() { 12229 callback(value); 12230 }, 0); 12231 return void 0; 12232 } else { 12233 return value; 12234 } 12235 }; 12236 const newLen = newTokens.length, oldLen = oldTokens.length; 12237 let editLength = 1; 12238 let maxEditLength = newLen + oldLen; 12239 if (options.maxEditLength != null) { 12240 maxEditLength = Math.min(maxEditLength, options.maxEditLength); 12241 } 12242 const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity; 12243 const abortAfterTimestamp = Date.now() + maxExecutionTime; 12244 const bestPath = [{ oldPos: -1, lastComponent: void 0 }]; 12245 let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); 12246 if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { 12247 return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); 12248 } 12249 let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; 12250 const execEditLength = () => { 12251 for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { 12252 let basePath; 12253 const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; 12254 if (removePath) { 12255 bestPath[diagonalPath - 1] = void 0; 12256 } 12257 let canAdd = false; 12258 if (addPath) { 12259 const addPathNewPos = addPath.oldPos - diagonalPath; 12260 canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; 12261 } 12262 const canRemove = removePath && removePath.oldPos + 1 < oldLen; 12263 if (!canAdd && !canRemove) { 12264 bestPath[diagonalPath] = void 0; 12265 continue; 12266 } 12267 if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) { 12268 basePath = this.addToPath(addPath, true, false, 0, options); 12269 } else { 12270 basePath = this.addToPath(removePath, false, true, 1, options); 12271 } 12272 newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); 12273 if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { 12274 return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; 12275 } else { 12276 bestPath[diagonalPath] = basePath; 12277 if (basePath.oldPos + 1 >= oldLen) { 12278 maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); 12279 } 12280 if (newPos + 1 >= newLen) { 12281 minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); 12282 } 12283 } 12284 } 12285 editLength++; 12286 }; 12287 if (callback) { 12288 (function exec() { 12289 setTimeout(function() { 12290 if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { 12291 return callback(void 0); 12292 } 12293 if (!execEditLength()) { 12294 exec(); 12295 } 12296 }, 0); 12297 })(); 12298 } else { 12299 while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { 12300 const ret = execEditLength(); 12301 if (ret) { 12302 return ret; 12303 } 12304 } 12305 } 12306 } 12307 addToPath(path, added, removed, oldPosInc, options) { 12308 const last2 = path.lastComponent; 12309 if (last2 && !options.oneChangePerToken && last2.added === added && last2.removed === removed) { 12310 return { 12311 oldPos: path.oldPos + oldPosInc, 12312 lastComponent: { count: last2.count + 1, added, removed, previousComponent: last2.previousComponent } 12313 }; 12314 } else { 12315 return { 12316 oldPos: path.oldPos + oldPosInc, 12317 lastComponent: { count: 1, added, removed, previousComponent: last2 } 12318 }; 12319 } 12320 } 12321 extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { 12322 const newLen = newTokens.length, oldLen = oldTokens.length; 12323 let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; 12324 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { 12325 newPos++; 12326 oldPos++; 12327 commonCount++; 12328 if (options.oneChangePerToken) { 12329 basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; 12330 } 12331 } 12332 if (commonCount && !options.oneChangePerToken) { 12333 basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; 12334 } 12335 basePath.oldPos = oldPos; 12336 return newPos; 12337 } 12338 equals(left, right, options) { 12339 if (options.comparator) { 12340 return options.comparator(left, right); 12341 } else { 12342 return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase(); 12343 } 12344 } 12345 removeEmpty(array) { 12346 const ret = []; 12347 for (let i = 0; i < array.length; i++) { 12348 if (array[i]) { 12349 ret.push(array[i]); 12350 } 12351 } 12352 return ret; 12353 } 12354 // eslint-disable-next-line @typescript-eslint/no-unused-vars 12355 castInput(value, options) { 12356 return value; 12357 } 12358 // eslint-disable-next-line @typescript-eslint/no-unused-vars 12359 tokenize(value, options) { 12360 return Array.from(value); 12361 } 12362 join(chars) { 12363 return chars.join(""); 12364 } 12365 postProcess(changeObjects, options) { 12366 return changeObjects; 12367 } 12368 get useLongestToken() { 12369 return false; 12370 } 12371 buildValues(lastComponent, newTokens, oldTokens) { 12372 const components = []; 12373 let nextComponent; 12374 while (lastComponent) { 12375 components.push(lastComponent); 12376 nextComponent = lastComponent.previousComponent; 12377 delete lastComponent.previousComponent; 12378 lastComponent = nextComponent; 12379 } 12380 components.reverse(); 12381 const componentLen = components.length; 12382 let componentPos = 0, newPos = 0, oldPos = 0; 12383 for (; componentPos < componentLen; componentPos++) { 12384 const component = components[componentPos]; 12385 if (!component.removed) { 12386 if (!component.added && this.useLongestToken) { 12387 let value = newTokens.slice(newPos, newPos + component.count); 12388 value = value.map(function(value2, i) { 12389 const oldValue = oldTokens[oldPos + i]; 12390 return oldValue.length > value2.length ? oldValue : value2; 12391 }); 12392 component.value = this.join(value); 12393 } else { 12394 component.value = this.join(newTokens.slice(newPos, newPos + component.count)); 12395 } 12396 newPos += component.count; 12397 if (!component.added) { 12398 oldPos += component.count; 12399 } 12400 } else { 12401 component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); 12402 oldPos += component.count; 12403 } 12404 } 12405 return components; 12406 } 12407 }; 12408 12409
vendor: 248 bytes, lines 12409-12417
12409// node_modules/diff/libesm/diff/character.js 12410 var CharacterDiff = class extends Diff { 12411 }; 12412 var characterDiff = new CharacterDiff(); 12413 function diffChars(oldStr, newStr, options) { 12414 return characterDiff.diff(oldStr, newStr, options); 12415 } 12416 12417
vendor: 1,451 bytes, lines 12417-12465
12417// node_modules/diff/libesm/diff/line.js 12418 var LineDiff = class extends Diff { 12419 constructor() { 12420 super(...arguments); 12421 this.tokenize = tokenize; 12422 } 12423 equals(left, right, options) { 12424 if (options.ignoreWhitespace) { 12425 if (!options.newlineIsToken || !left.includes("\n")) { 12426 left = left.trim(); 12427 } 12428 if (!options.newlineIsToken || !right.includes("\n")) { 12429 right = right.trim(); 12430 } 12431 } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { 12432 if (left.endsWith("\n")) { 12433 left = left.slice(0, -1); 12434 } 12435 if (right.endsWith("\n")) { 12436 right = right.slice(0, -1); 12437 } 12438 } 12439 return super.equals(left, right, options); 12440 } 12441 }; 12442 var lineDiff = new LineDiff(); 12443 function diffLines(oldStr, newStr, options) { 12444 return lineDiff.diff(oldStr, newStr, options); 12445 } 12446 function tokenize(value, options) { 12447 if (options.stripTrailingCr) { 12448 value = value.replace(/\r\n/g, "\n"); 12449 } 12450 const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); 12451 if (!linesAndNewlines[linesAndNewlines.length - 1]) { 12452 linesAndNewlines.pop(); 12453 } 12454 for (let i = 0; i < linesAndNewlines.length; i++) { 12455 const line = linesAndNewlines[i]; 12456 if (i % 2 && !options.newlineIsToken) { 12457 retLines[retLines.length - 1] += line; 12458 } else { 12459 retLines.push(line); 12460 } 12461 } 12462 return retLines; 12463 } 12464 12465
12465// packages/sync/build-module/quill-delta/Delta.mjs 12466 var import_es64 = __toESM(require_es6(), 1); 12467 12468
vendor: 2,709 bytes, lines 12468-12562
12468// packages/sync/build-module/quill-delta/AttributeMap.mjs 12469 var import_es63 = __toESM(require_es6(), 1); 12470 function cloneDeep(value) { 12471 return JSON.parse(JSON.stringify(value)); 12472 } 12473 var AttributeMap; 12474 ((AttributeMap2) => { 12475 function compose3(a = {}, b = {}, keepNull = false) { 12476 if (typeof a !== "object") { 12477 a = {}; 12478 } 12479 if (typeof b !== "object") { 12480 b = {}; 12481 } 12482 let attributes = cloneDeep(b); 12483 if (!keepNull) { 12484 attributes = Object.keys(attributes).reduce( 12485 (copy2, key) => { 12486 if (attributes[key] !== null || attributes[key] !== void 0) { 12487 copy2[key] = attributes[key]; 12488 } 12489 return copy2; 12490 }, 12491 {} 12492 ); 12493 } 12494 for (const key in a) { 12495 if (a[key] !== void 0 && b[key] === void 0) { 12496 attributes[key] = a[key]; 12497 } 12498 } 12499 return Object.keys(attributes).length > 0 ? attributes : void 0; 12500 } 12501 AttributeMap2.compose = compose3; 12502 function diff(a = {}, b = {}) { 12503 if (typeof a !== "object") { 12504 a = {}; 12505 } 12506 if (typeof b !== "object") { 12507 b = {}; 12508 } 12509 const attributes = Object.keys(a).concat(Object.keys(b)).reduce((attrs, key) => { 12510 if (!(0, import_es63.default)(a[key], b[key])) { 12511 attrs[key] = b[key] === void 0 ? null : b[key]; 12512 } 12513 return attrs; 12514 }, {}); 12515 return Object.keys(attributes).length > 0 ? attributes : void 0; 12516 } 12517 AttributeMap2.diff = diff; 12518 function invert(attr = {}, base = {}) { 12519 attr = attr || {}; 12520 const baseInverted = Object.keys(base).reduce( 12521 (memo, key) => { 12522 if (base[key] !== attr[key] && attr[key] !== void 0) { 12523 memo[key] = base[key]; 12524 } 12525 return memo; 12526 }, 12527 {} 12528 ); 12529 return Object.keys(attr).reduce((memo, key) => { 12530 if (attr[key] !== base[key] && base[key] === void 0) { 12531 memo[key] = null; 12532 } 12533 return memo; 12534 }, baseInverted); 12535 } 12536 AttributeMap2.invert = invert; 12537 function transform(a, b, priority = false) { 12538 if (typeof a !== "object") { 12539 return b; 12540 } 12541 if (typeof b !== "object") { 12542 return void 0; 12543 } 12544 if (!priority) { 12545 return b; 12546 } 12547 const attributes = Object.keys(b).reduce( 12548 (attrs, key) => { 12549 if (a[key] === void 0) { 12550 attrs[key] = b[key]; 12551 } 12552 return attrs; 12553 }, 12554 {} 12555 ); 12556 return Object.keys(attributes).length > 0 ? attributes : void 0; 12557 } 12558 AttributeMap2.transform = transform; 12559 })(AttributeMap || (AttributeMap = {})); 12560 var AttributeMap_default = AttributeMap; 12561 12562
12562// packages/sync/build-module/quill-delta/Op.mjs 12563 var Op; 12564 ((Op2) => { 12565 function length2(op) { 12566 if (typeof op.delete === "number") { 12567 return op.delete; 12568 } else if (typeof op.retain === "number") { 12569 return op.retain; 12570 } else if (typeof op.retain === "object" && op.retain !== null) { 12571 return 1; 12572 } 12573 return typeof op.insert === "string" ? op.insert.length : 1; 12574 } 12575 Op2.length = length2; 12576 })(Op || (Op = {})); 12577 var Op_default = Op; 12578 12579
12579// packages/sync/build-module/quill-delta/OpIterator.mjs 12580 var Iterator2 = class { 12581 ops; 12582 index; 12583 offset; 12584 constructor(ops) { 12585 this.ops = ops; 12586 this.index = 0; 12587 this.offset = 0; 12588 } 12589 hasNext() { 12590 return this.peekLength() < Infinity; 12591 } 12592 next(length2) { 12593 if (!length2) { 12594 length2 = Infinity; 12595 } 12596 const nextOp = this.ops[this.index]; 12597 if (nextOp) { 12598 const offset = this.offset; 12599 const opLength = Op_default.length(nextOp); 12600 if (length2 >= opLength - offset) { 12601 length2 = opLength - offset; 12602 this.index += 1; 12603 this.offset = 0; 12604 } else { 12605 this.offset += length2; 12606 } 12607 if (typeof nextOp.delete === "number") { 12608 return { delete: length2 }; 12609 } 12610 const retOp = {}; 12611 if (nextOp.attributes) { 12612 retOp.attributes = nextOp.attributes; 12613 } 12614 if (typeof nextOp.retain === "number") { 12615 retOp.retain = length2; 12616 } else if (typeof nextOp.retain === "object" && nextOp.retain !== null) { 12617 retOp.retain = nextOp.retain; 12618 } else if (typeof nextOp.insert === "string") { 12619 retOp.insert = nextOp.insert.substr(offset, length2); 12620 } else { 12621 retOp.insert = nextOp.insert; 12622 } 12623 return retOp; 12624 } 12625 return { retain: Infinity }; 12626 } 12627 peek() { 12628 return this.ops[this.index]; 12629 } 12630 peekLength() { 12631 if (this.ops[this.index]) { 12632 return Op_default.length(this.ops[this.index]) - this.offset; 12633 } 12634 return Infinity; 12635 } 12636 peekType() { 12637 const op = this.ops[this.index]; 12638 if (op) { 12639 if (typeof op.delete === "number") { 12640 return "delete"; 12641 } else if (typeof op.retain === "number" || typeof op.retain === "object" && op.retain !== null) { 12642 return "retain"; 12643 } 12644 return "insert"; 12645 } 12646 return "retain"; 12647 } 12648 rest() { 12649 if (!this.hasNext()) { 12650 return []; 12651 } else if (this.offset === 0) { 12652 return this.ops.slice(this.index); 12653 } 12654 const offset = this.offset; 12655 const index = this.index; 12656 const next = this.next(); 12657 const rest = this.ops.slice(this.index); 12658 this.offset = offset; 12659 this.index = index; 12660 return [next].concat(rest); 12661 } 12662 }; 12663 12664
vendor: 4,483 bytes, lines 12664-12801
12664// packages/sync/build-module/quill-delta/Delta.mjs 12665 function cloneDeep2(value) { 12666 return JSON.parse(JSON.stringify(value)); 12667 } 12668 var NULL_CHARACTER = String.fromCharCode(0); 12669 var STRING_TOO_LARGE_THRESHOLD = 1e4; 12670 function normalizeChangeCounts(changes) { 12671 return changes.map((change) => ({ 12672 ...change, 12673 count: change.value.length 12674 })); 12675 } 12676 var getEmbedTypeAndData = (a, b) => { 12677 if (typeof a !== "object" || a === null) { 12678 throw new Error(`cannot retain a ${typeof a}`); 12679 } 12680 if (typeof b !== "object" || b === null) { 12681 throw new Error(`cannot retain a ${typeof b}`); 12682 } 12683 const embedType = Object.keys(a)[0]; 12684 if (!embedType || embedType !== Object.keys(b)[0]) { 12685 throw new Error( 12686 `embed types not matched: ${embedType} != ${Object.keys(b)[0]}` 12687 ); 12688 } 12689 return [embedType, a[embedType], b[embedType]]; 12690 }; 12691 var Delta = class _Delta { 12692 static Op = Op_default; 12693 static OpIterator = Iterator2; 12694 static AttributeMap = AttributeMap_default; 12695 static handlers = {}; 12696 static registerEmbed(embedType, handler) { 12697 this.handlers[embedType] = handler; 12698 } 12699 static unregisterEmbed(embedType) { 12700 delete this.handlers[embedType]; 12701 } 12702 static getHandler(embedType) { 12703 const handler = this.handlers[embedType]; 12704 if (!handler) { 12705 throw new Error(`no handlers for embed type "${embedType}"`); 12706 } 12707 return handler; 12708 } 12709 ops; 12710 constructor(ops) { 12711 if (Array.isArray(ops)) { 12712 this.ops = ops; 12713 } else if (ops !== null && ops !== void 0 && Array.isArray(ops.ops)) { 12714 this.ops = ops.ops; 12715 } else { 12716 this.ops = []; 12717 } 12718 } 12719 insert(arg, attributes) { 12720 const newOp = {}; 12721 if (typeof arg === "string" && arg.length === 0) { 12722 return this; 12723 } 12724 newOp.insert = arg; 12725 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) { 12726 newOp.attributes = attributes; 12727 } 12728 return this.push(newOp); 12729 } 12730 delete(length2) { 12731 if (length2 <= 0) { 12732 return this; 12733 } 12734 return this.push({ delete: length2 }); 12735 } 12736 retain(length2, attributes) { 12737 if (typeof length2 === "number" && length2 <= 0) { 12738 return this; 12739 } 12740 const newOp = { retain: length2 }; 12741 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) { 12742 newOp.attributes = attributes; 12743 } 12744 return this.push(newOp); 12745 } 12746 push(newOp) { 12747 let index = this.ops.length; 12748 let lastOp = this.ops[index - 1]; 12749 newOp = cloneDeep2(newOp); 12750 if (typeof lastOp === "object") { 12751 if (typeof newOp.delete === "number" && typeof lastOp.delete === "number") { 12752 this.ops[index - 1] = { 12753 delete: lastOp.delete + newOp.delete 12754 }; 12755 return this; 12756 } 12757 if (typeof lastOp.delete === "number" && newOp.insert !== null && newOp.insert !== void 0) { 12758 index -= 1; 12759 lastOp = this.ops[index - 1]; 12760 if (typeof lastOp !== "object") { 12761 this.ops.unshift(newOp); 12762 return this; 12763 } 12764 } 12765 if ((0, import_es64.default)(newOp.attributes, lastOp.attributes)) { 12766 if (typeof newOp.insert === "string" && typeof lastOp.insert === "string") { 12767 this.ops[index - 1] = { 12768 insert: lastOp.insert + newOp.insert 12769 }; 12770 if (typeof newOp.attributes === "object") { 12771 this.ops[index - 1].attributes = newOp.attributes; 12772 } 12773 return this; 12774 } else if (typeof newOp.retain === "number" && typeof lastOp.retain === "number") { 12775 this.ops[index - 1] = { 12776 retain: lastOp.retain + newOp.retain 12777 }; 12778 if (typeof newOp.attributes === "object") { 12779 this.ops[index - 1].attributes = newOp.attributes; 12780 } 12781 return this; 12782 } 12783 } 12784 } 12785 if (index === this.ops.length) { 12786 this.ops.push(newOp); 12787 } else { 12788 this.ops.splice(index, 0, newOp); 12789 } 12790 return this; 12791 } 12792 chop() { 12793 const lastOp = this.ops[this.ops.length - 1]; 12794 if (lastOp && typeof lastOp.retain === "number" && !lastOp.attributes) { 12795 this.ops.pop(); 12796 } 12797 return this; 12798 } 12799 filter(predicate) { 12800 return this.ops.filter(predicate); 12801 }
12802 forEach(predicate) { 12803 this.ops.forEach(predicate); 12804 } 12805 map(predicate) { 12806 return this.ops.map(predicate); 12807 } 12808 partition(predicate) { 12809 const passed = []; 12810 const failed = []; 12811 this.forEach((op) => { 12812 const target = predicate(op) ? passed : failed; 12813 target.push(op); 12814 }); 12815 return [passed, failed]; 12816 } 12817 reduce(predicate, initialValue) { 12818 return this.ops.reduce(predicate, initialValue); 12819 } 12820 changeLength() { 12821 return this.reduce((length2, elem) => { 12822 if (elem.insert) { 12823 return length2 + Op_default.length(elem); 12824 } else if (elem.delete) { 12825 return length2 - elem.delete; 12826 } 12827 return length2; 12828 }, 0); 12829 } 12830 length() { 12831 return this.reduce((length2, elem) => { 12832 return length2 + Op_default.length(elem); 12833 }, 0); 12834 } 12835 slice(start = 0, end = Infinity) { 12836 const ops = []; 12837 const iter = new Iterator2(this.ops); 12838 let index = 0; 12839 while (index < end && iter.hasNext()) { 12840 let nextOp; 12841 if (index < start) { 12842 nextOp = iter.next(start - index); 12843 } else { 12844 nextOp = iter.next(end - index); 12845 ops.push(nextOp); 12846 } 12847 index += Op_default.length(nextOp); 12848 } 12849 return new _Delta(ops); 12850 } 12851 compose(other) { 12852 const thisIter = new Iterator2(this.ops); 12853 const otherIter = new Iterator2(other.ops); 12854 const ops = []; 12855 const firstOther = otherIter.peek(); 12856 if (firstOther !== null && firstOther !== void 0 && typeof firstOther.retain === "number" && (firstOther.attributes === null || firstOther.attributes === void 0)) { 12857 let firstLeft = firstOther.retain; 12858 while (thisIter.peekType() === "insert" && thisIter.peekLength() <= firstLeft) { 12859 firstLeft -= thisIter.peekLength(); 12860 ops.push(thisIter.next()); 12861 } 12862 if (firstOther.retain - firstLeft > 0) { 12863 otherIter.next(firstOther.retain - firstLeft); 12864 } 12865 } 12866 const delta = new _Delta(ops); 12867 while (thisIter.hasNext() || otherIter.hasNext()) { 12868 if (otherIter.peekType() === "insert") { 12869 delta.push(otherIter.next()); 12870 } else if (thisIter.peekType() === "delete") { 12871 delta.push(thisIter.next()); 12872 } else { 12873 const length2 = Math.min( 12874 thisIter.peekLength(), 12875 otherIter.peekLength() 12876 ); 12877 const thisOp = thisIter.next(length2); 12878 const otherOp = otherIter.next(length2); 12879 if (otherOp.retain) { 12880 const newOp = {}; 12881 if (typeof thisOp.retain === "number") { 12882 newOp.retain = typeof otherOp.retain === "number" ? length2 : otherOp.retain; 12883 } else if (typeof otherOp.retain === "number") { 12884 if (thisOp.retain === null || thisOp.retain === void 0) { 12885 newOp.insert = thisOp.insert; 12886 } else { 12887 newOp.retain = thisOp.retain; 12888 } 12889 } else { 12890 const action = thisOp.retain === null || thisOp.retain === void 0 ? "insert" : "retain"; 12891 const [embedType, thisData, otherData] = getEmbedTypeAndData( 12892 thisOp[action], 12893 otherOp.retain 12894 ); 12895 const handler = _Delta.getHandler(embedType); 12896 newOp[action] = { 12897 [embedType]: handler.compose( 12898 thisData, 12899 otherData, 12900 action === "retain" 12901 ) 12902 }; 12903 } 12904 const attributes = AttributeMap_default.compose( 12905 thisOp.attributes, 12906 otherOp.attributes, 12907 typeof thisOp.retain === "number" 12908 ); 12909 if (attributes) { 12910 newOp.attributes = attributes; 12911 } 12912 delta.push(newOp); 12913 if (!otherIter.hasNext() && (0, import_es64.default)(delta.ops[delta.ops.length - 1], newOp)) { 12914 const rest = new _Delta(thisIter.rest()); 12915 return delta.concat(rest).chop(); 12916 } 12917 } else if (typeof otherOp.delete === "number" && (typeof thisOp.retain === "number" || typeof thisOp.retain === "object" && thisOp.retain !== null)) { 12918 delta.push(otherOp); 12919 } 12920 } 12921 } 12922 return delta.chop(); 12923 } 12924 concat(other) { 12925 const delta = new _Delta(this.ops.slice()); 12926 if (other.ops.length > 0) { 12927 delta.push(other.ops[0]); 12928 delta.ops = delta.ops.concat(other.ops.slice(1)); 12929 } 12930 return delta; 12931 } 12932 diff(other) { 12933 if (this.ops === other.ops) { 12934 return new _Delta(); 12935 } 12936 const strings = this.deltasToStrings(other); 12937 const diffResult = normalizeChangeCounts(
vendor: 5,652 bytes, lines 12938-13095
12938 diffChars(strings[0], strings[1]) 12939 ); 12940 const thisIter = new Iterator2(this.ops); 12941 const otherIter = new Iterator2(other.ops); 12942 const retDelta = this.convertChangesToDelta( 12943 diffResult, 12944 thisIter, 12945 otherIter 12946 ); 12947 return retDelta.chop(); 12948 } 12949 eachLine(predicate, newline = "\n") { 12950 const iter = new Iterator2(this.ops); 12951 let line = new _Delta(); 12952 let i = 0; 12953 while (iter.hasNext()) { 12954 if (iter.peekType() !== "insert") { 12955 return; 12956 } 12957 const thisOp = iter.peek(); 12958 const start = Op_default.length(thisOp) - iter.peekLength(); 12959 const index = typeof thisOp.insert === "string" ? thisOp.insert.indexOf(newline, start) - start : -1; 12960 if (index < 0) { 12961 line.push(iter.next()); 12962 } else if (index > 0) { 12963 line.push(iter.next(index)); 12964 } else { 12965 if (predicate(line, iter.next(1).attributes || {}, i) === false) { 12966 return; 12967 } 12968 i += 1; 12969 line = new _Delta(); 12970 } 12971 } 12972 if (line.length() > 0) { 12973 predicate(line, {}, i); 12974 } 12975 } 12976 invert(base) { 12977 const inverted = new _Delta(); 12978 this.reduce((baseIndex, op) => { 12979 if (op.insert) { 12980 inverted.delete(Op_default.length(op)); 12981 } else if (typeof op.retain === "number" && (op.attributes === null || op.attributes === void 0)) { 12982 inverted.retain(op.retain); 12983 return baseIndex + op.retain; 12984 } else if (op.delete || typeof op.retain === "number") { 12985 const length2 = op.delete || op.retain; 12986 const slice = base.slice(baseIndex, baseIndex + length2); 12987 slice.forEach((baseOp) => { 12988 if (op.delete) { 12989 inverted.push(baseOp); 12990 } else if (op.retain && op.attributes) { 12991 inverted.retain( 12992 Op_default.length(baseOp), 12993 AttributeMap_default.invert( 12994 op.attributes, 12995 baseOp.attributes 12996 ) 12997 ); 12998 } 12999 }); 13000 return baseIndex + length2; 13001 } else if (typeof op.retain === "object" && op.retain !== null) { 13002 const slice = base.slice(baseIndex, baseIndex + 1); 13003 const baseOp = new Iterator2(slice.ops).next(); 13004 const [embedType, opData, baseOpData] = getEmbedTypeAndData( 13005 op.retain, 13006 baseOp.insert 13007 ); 13008 const handler = _Delta.getHandler(embedType); 13009 inverted.retain( 13010 { [embedType]: handler.invert(opData, baseOpData) }, 13011 AttributeMap_default.invert(op.attributes, baseOp.attributes) 13012 ); 13013 return baseIndex + 1; 13014 } 13015 return baseIndex; 13016 }, 0); 13017 return inverted.chop(); 13018 } 13019 transform(arg, priority = false) { 13020 priority = !!priority; 13021 if (typeof arg === "number") { 13022 return this.transformPosition(arg, priority); 13023 } 13024 const other = arg; 13025 const thisIter = new Iterator2(this.ops); 13026 const otherIter = new Iterator2(other.ops); 13027 const delta = new _Delta(); 13028 while (thisIter.hasNext() || otherIter.hasNext()) { 13029 if (thisIter.peekType() === "insert" && (priority || otherIter.peekType() !== "insert")) { 13030 delta.retain(Op_default.length(thisIter.next())); 13031 } else if (otherIter.peekType() === "insert") { 13032 delta.push(otherIter.next()); 13033 } else { 13034 const length2 = Math.min( 13035 thisIter.peekLength(), 13036 otherIter.peekLength() 13037 ); 13038 const thisOp = thisIter.next(length2); 13039 const otherOp = otherIter.next(length2); 13040 if (thisOp.delete) { 13041 continue; 13042 } else if (otherOp.delete) { 13043 delta.push(otherOp); 13044 } else { 13045 const thisData = thisOp.retain; 13046 const otherData = otherOp.retain; 13047 let transformedData = typeof otherData === "object" && otherData !== null ? otherData : length2; 13048 if (typeof thisData === "object" && thisData !== null && typeof otherData === "object" && otherData !== null) { 13049 const embedType = Object.keys(thisData)[0]; 13050 if (embedType === Object.keys(otherData)[0]) { 13051 const handler = _Delta.getHandler(embedType); 13052 if (handler) { 13053 transformedData = { 13054 [embedType]: handler.transform( 13055 thisData[embedType], 13056 otherData[embedType], 13057 priority 13058 ) 13059 }; 13060 } 13061 } 13062 } 13063 delta.retain( 13064 transformedData, 13065 AttributeMap_default.transform( 13066 thisOp.attributes, 13067 otherOp.attributes, 13068 priority 13069 ) 13070 ); 13071 } 13072 } 13073 } 13074 return delta.chop(); 13075 } 13076 transformPosition(index, priority = false) { 13077 priority = !!priority; 13078 const thisIter = new Iterator2(this.ops); 13079 let offset = 0; 13080 while (thisIter.hasNext() && offset <= index) { 13081 const length2 = thisIter.peekLength(); 13082 const nextType = thisIter.peekType(); 13083 thisIter.next(); 13084 if (nextType === "delete") { 13085 index -= Math.min(length2, index - offset); 13086 continue; 13087 } else if (nextType === "insert" && (offset < index || !priority)) { 13088 index += length2; 13089 } 13090 offset += length2; 13091 } 13092 return index; 13093 } 13094 /** 13095 * Given a Delta and a cursor position, do a diff and attempt to adjust
13096 * the diff to place insertions or deletions at the cursor position. 13097 * 13098 * @todo There are at least a few known cases where this produces a corrupted 13099 * diff. When this is fixed, it should not be necessary to verify that the 13100 * transformed diff applies cleanly. 13101 * 13102 * @see import("@wordpress/core-data/src/utils/crdt-blocks").mergeRichTextUpdate() 13103 * 13104 * @param other - The other Delta to diff against. 13105 * @param cursorAfterChange - The cursor position index after the change. 13106 * @return A Delta that attempts to place insertions or deletions at the cursor position. 13107 */ 13108 diffWithCursor(other, cursorAfterChange) { 13109 if (this.ops === other.ops) { 13110 return new _Delta(); 13111 } 13112 const strings = this.deltasToStrings(other); 13113 const maxStringLength = Math.max( 13114 ...strings.map((str) => str.length) 13115 ); 13116 if (maxStringLength > STRING_TOO_LARGE_THRESHOLD) { 13117 const diffResult = normalizeChangeCounts( 13118 diffLines(strings[0], strings[1]) 13119 ); 13120 const thisIterLarge = new Iterator2(this.ops); 13121 const otherIterLarge = new Iterator2(other.ops); 13122 return this.convertChangesToDelta( 13123 diffResult, 13124 thisIterLarge, 13125 otherIterLarge 13126 ).chop(); 13127 } else if (cursorAfterChange === null) { 13128 return this.diff(other); 13129 } 13130 let diffs = normalizeChangeCounts( 13131 diffChars(strings[0], strings[1]) 13132 ); 13133 let lastDiffPosition = 0; 13134 const adjustedDiffs = []; 13135 for (let i = 0; i < diffs.length; i++) { 13136 const diff = diffs[i]; 13137 const segmentStart = lastDiffPosition; 13138 const segmentEnd = lastDiffPosition + (diff.count ?? 0); 13139 const isCursorInSegment = cursorAfterChange > segmentStart && cursorAfterChange <= segmentEnd; 13140 const isUnchangedSegment = !diff.added && !diff.removed; 13141 const isRemovalSegment = diff.removed && !diff.added; 13142 const nextDiff = diffs[i + 1]; 13143 const isNextDiffAnInsert = nextDiff && nextDiff.added && !nextDiff.removed; 13144 if (isUnchangedSegment && isCursorInSegment && isNextDiffAnInsert) { 13145 const movedSegments = this.tryMoveInsertionToCursor( 13146 diff, 13147 nextDiff, 13148 cursorAfterChange, 13149 segmentStart 13150 ); 13151 if (movedSegments) { 13152 adjustedDiffs.push(...movedSegments); 13153 i++; 13154 lastDiffPosition = segmentEnd; 13155 continue; 13156 } 13157 } 13158 if (isRemovalSegment) { 13159 const movedSegments = this.tryMoveDeletionToCursor( 13160 diff, 13161 adjustedDiffs, 13162 cursorAfterChange, 13163 lastDiffPosition 13164 ); 13165 if (movedSegments) { 13166 adjustedDiffs.pop(); 13167 adjustedDiffs.push(...movedSegments); 13168 lastDiffPosition += diff.count ?? 0; 13169 continue; 13170 } 13171 } 13172 adjustedDiffs.push(diff); 13173 if (!diff.added) { 13174 lastDiffPosition += diff.count ?? 0; 13175 } 13176 } 13177 diffs = adjustedDiffs; 13178 const thisIter = new Iterator2(this.ops); 13179 const otherIter = new Iterator2(other.ops); 13180 const retDelta = this.convertChangesToDelta( 13181 diffs, 13182 thisIter, 13183 otherIter 13184 ); 13185 return retDelta.chop(); 13186 } 13187 /** 13188 * Try to move an insertion operation from after an unchanged segment to the cursor position within it. 13189 * This is a "look-ahead" strategy. 13190 * 13191 * @param diff - The current unchanged diff segment. 13192 * @param nextDiff - The next diff segment (expected to be an insertion). 13193 * @param cursorAfterChange - The cursor position after the change. 13194 * @param segmentStart - The start position of the current segment. 13195 * @return An array of adjusted diff segments if the insertion was successfully moved, null otherwise. 13196 */ 13197 tryMoveInsertionToCursor(diff, nextDiff, cursorAfterChange, segmentStart) { 13198 const nextDiffInsert = nextDiff.value; 13199 const insertLength = nextDiffInsert.length; 13200 const insertOffset = cursorAfterChange - segmentStart - insertLength; 13201 const textAtCursor = diff.value.substring( 13202 insertOffset, 13203 insertOffset + nextDiffInsert.length 13204 ); 13205 const isInsertMoveable = textAtCursor === nextDiffInsert; 13206 if (!isInsertMoveable) { 13207 return null; 13208 } 13209 const beforeCursor = diff.value.substring(0, insertOffset);
13210 const afterCursor = diff.value.substring(insertOffset); 13211 const result = []; 13212 if (beforeCursor.length > 0) { 13213 result.push({ 13214 value: beforeCursor, 13215 count: beforeCursor.length, 13216 added: false, 13217 removed: false 13218 }); 13219 } 13220 result.push(nextDiff); 13221 if (afterCursor.length > 0) { 13222 result.push({ 13223 value: afterCursor, 13224 count: afterCursor.length, 13225 added: false, 13226 removed: false 13227 }); 13228 } 13229 return result; 13230 } 13231 /** 13232 * Try to move a deletion operation to the cursor position by looking back at the previous unchanged segment. 13233 * This is a "look-back" strategy. 13234 * 13235 * @param diff - The current deletion diff segment. 13236 * @param adjustedDiffs - The array of previously processed diff segments. 13237 * @param cursorAfterChange - The cursor position after the change. 13238 * @param lastDiffPosition - The position in the document up to (but not including) the current diff. 13239 * @return An array of adjusted diff segments if the deletion was successfully moved, null otherwise. 13240 */ 13241 tryMoveDeletionToCursor(diff, adjustedDiffs, cursorAfterChange, lastDiffPosition) { 13242 const prevDiff = adjustedDiffs[adjustedDiffs.length - 1]; 13243 if (!prevDiff || prevDiff.added || prevDiff.removed) { 13244 return null; 13245 } 13246 const prevSegmentStart = lastDiffPosition - (prevDiff.count ?? 0); 13247 const prevSegmentEnd = lastDiffPosition; 13248 if (cursorAfterChange < prevSegmentStart || cursorAfterChange >= prevSegmentEnd) { 13249 return null; 13250 } 13251 const deletedChars = diff.value; 13252 const deleteOffset = cursorAfterChange - prevSegmentStart; 13253 const textAtCursor = prevDiff.value.substring( 13254 deleteOffset, 13255 deleteOffset + deletedChars.length 13256 ); 13257 const canBePlacedHere = textAtCursor === deletedChars; 13258 if (!canBePlacedHere) { 13259 return null; 13260 } 13261 const beforeCursor = prevDiff.value.substring(0, deleteOffset); 13262 const atAndAfterCursor = prevDiff.value.substring(deleteOffset); 13263 const deletionLength = diff.count ?? 0; 13264 const afterDeletion = atAndAfterCursor.substring(deletionLength); 13265 const result = []; 13266 if (beforeCursor.length > 0) { 13267 result.push({ 13268 value: beforeCursor, 13269 count: beforeCursor.length, 13270 added: false, 13271 removed: false 13272 }); 13273 } 13274 result.push(diff); 13275 if (afterDeletion.length > 0) { 13276 result.push({ 13277 value: afterDeletion, 13278 count: afterDeletion.length, 13279 added: false, 13280 removed: false 13281 }); 13282 } 13283 return result; 13284 } 13285 /** 13286 * Convert two Deltas to string representations for diffing. 13287 * 13288 * @param other - The other Delta to convert. 13289 * @return A tuple of [thisString, otherString]. 13290 */ 13291 deltasToStrings(other) { 13292 return [this, other].map((delta) => { 13293 return delta.map((op) => { 13294 if (op.insert !== null || op.insert !== void 0) { 13295 return typeof op.insert === "string" ? op.insert : NULL_CHARACTER; 13296 } 13297 const prep = delta === other ? "on" : "with"; 13298 throw new Error( 13299 "diff() called " + prep + " non-document" 13300 ); 13301 }).join(""); 13302 }); 13303 } 13304 /** 13305 * Process diff changes and convert them to Delta operations. 13306 * 13307 * @param changes - The array of changes from the diff algorithm. 13308 * @param thisIter - Iterator for this Delta's operations. 13309 * @param otherIter - Iterator for the other Delta's operations. 13310 * @return A Delta containing the processed diff operations. 13311 */ 13312 convertChangesToDelta(changes, thisIter, otherIter) { 13313 const retDelta = new _Delta();
13314 changes.forEach((component) => { 13315 let length2 = component.count ?? 0; 13316 while (length2 > 0) { 13317 let opLength = 0; 13318 if (component.added) { 13319 opLength = Math.min(otherIter.peekLength(), length2); 13320 retDelta.push(otherIter.next(opLength)); 13321 } else if (component.removed) { 13322 opLength = Math.min(length2, thisIter.peekLength()); 13323 thisIter.next(opLength); 13324 retDelta.delete(opLength); 13325 } else { 13326 opLength = Math.min( 13327 thisIter.peekLength(), 13328 otherIter.peekLength(), 13329 length2 13330 ); 13331 const thisOp = thisIter.next(opLength); 13332 const otherOp = otherIter.next(opLength); 13333 if ((0, import_es64.default)(thisOp.insert, otherOp.insert)) { 13334 retDelta.retain( 13335 opLength, 13336 AttributeMap_default.diff( 13337 thisOp.attributes, 13338 otherOp.attributes 13339 ) 13340 ); 13341 } else { 13342 retDelta.push(otherOp).delete(opLength); 13343 } 13344 } 13345 length2 -= opLength; 13346 } 13347 }); 13348 return retDelta; 13349 } 13350 }; 13351 var Delta_default = Delta; 13352 13353
13353// packages/sync/build-module/private-apis.mjs 13354 var privateApis = {}; 13355 lock(privateApis, { 13356 ConnectionErrorCode, 13357 createSyncManager, 13358 Delta: Delta_default, 13359 CRDT_DOC_META_PERSISTENCE_KEY, 13360 CRDT_RECORD_MAP_KEY, 13361 LOCAL_EDITOR_ORIGIN, 13362 LOCAL_UNDO_IGNORED_ORIGIN, 13363 retrySyncConnection: () => pollingManager.retryNow() 13364 }); 13365 13366
13366// packages/core-data/build-module/lock-unlock.mjs 13367 var import_private_apis3 = __toESM(require_private_apis(), 1); 13368 var { lock: lock2, unlock: unlock2 } = (0, import_private_apis3.__dangerousOptInToUnstableAPIsOnlyForCoreModules)( 13369 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.", 13370 "@wordpress/core-data" 13371 ); 13372 13373
13373// packages/core-data/build-module/sync.mjs 13374 var { 13375 ConnectionErrorCode: ConnectionErrorCode2, 13376 createSyncManager: createSyncManager2, 13377 Delta: Delta2, 13378 CRDT_DOC_META_PERSISTENCE_KEY: CRDT_DOC_META_PERSISTENCE_KEY2, 13379 CRDT_RECORD_MAP_KEY: CRDT_RECORD_MAP_KEY2, 13380 LOCAL_EDITOR_ORIGIN: LOCAL_EDITOR_ORIGIN2, 13381 LOCAL_UNDO_IGNORED_ORIGIN: LOCAL_UNDO_IGNORED_ORIGIN2, 13382 retrySyncConnection 13383 } = unlock2(privateApis); 13384 var syncManager; 13385 function getSyncManager() { 13386 if (syncManager) { 13387 return syncManager; 13388 } 13389 syncManager = createSyncManager2(); 13390 return syncManager; 13391 } 13392 function hasSyncManager() { 13393 return Boolean(syncManager); 13394 } 13395 13396
13396// packages/core-data/build-module/utils/save-crdt-doc.mjs 13397 var SYNC_SAVE_API_PATH = "/wp-sync/v1/save"; 13398 var saveCRDTDocQueues = /* @__PURE__ */ new Map(); 13399 async function serializeAndSaveCRDTDoc(objectType, objectId, room) { 13400 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc( 13401 objectType, 13402 objectId 13403 ); 13404 if (!serializedDoc) { 13405 return; 13406 } 13407 await (0, import_api_fetch2.default)({ 13408 path: SYNC_SAVE_API_PATH, 13409 method: "POST", 13410 data: { 13411 room, 13412 doc: serializedDoc 13413 } 13414 }); 13415 } 13416 async function saveCRDTDoc(objectType, objectId) { 13417 const room = `${objectType}:${objectId}`; 13418 const previousSave = saveCRDTDocQueues.get(room) || Promise.resolve(); 13419 const currentSave = previousSave.catch(() => { 13420 }).then(() => serializeAndSaveCRDTDoc(objectType, objectId, room)); 13421 saveCRDTDocQueues.set(room, currentSave); 13422 try { 13423 await currentSave; 13424 } finally { 13425 if (saveCRDTDocQueues.get(room) === currentSave) { 13426 saveCRDTDocQueues.delete(room); 13427 } 13428 } 13429 } 13430 13431
13431// packages/core-data/build-module/queried-data/actions.mjs 13432 function receiveItems(items2, edits, meta) { 13433 return { 13434 type: "RECEIVE_ITEMS", 13435 items: items2, 13436 persistedEdits: edits, 13437 meta 13438 }; 13439 } 13440 function removeItems(kind, name, records, invalidateCache = false) { 13441 return { 13442 type: "REMOVE_ITEMS", 13443 itemIds: Array.isArray(records) ? records : [records], 13444 kind, 13445 name, 13446 invalidateCache 13447 }; 13448 } 13449 function receiveQueriedItems(items2, query = {}, edits, meta) { 13450 return { 13451 ...receiveItems(items2, edits, meta), 13452 query 13453 }; 13454 } 13455 13456
13456// packages/core-data/build-module/queried-data/selectors.mjs 13457 var import_equivalent_key_map = __toESM(require_equivalent_key_map(), 1); 13458 13459
13459// packages/core-data/build-module/queried-data/get-query-parts.mjs 13460 var import_url = __toESM(require_url(), 1); 13461 function getQueryParts(query) { 13462 const parts = { 13463 stableKey: "", 13464 page: 1, 13465 perPage: 10, 13466 offset: null, 13467 fields: null, 13468 include: null, 13469 context: "default" 13470 }; 13471 const keys2 = Object.keys(query).sort(); 13472 for (let i = 0; i < keys2.length; i++) { 13473 const key = keys2[i]; 13474 let value = query[key]; 13475 switch (key) { 13476 case "page": 13477 parts[key] = Number(value); 13478 break; 13479 case "per_page": 13480 parts.perPage = Number(value); 13481 break; 13482 case "offset": { 13483 const numericOffset = Number(value); 13484 if (Number.isFinite(numericOffset)) { 13485 parts.offset = numericOffset; 13486 } 13487 break; 13488 } 13489 case "context": 13490 parts.context = value; 13491 break; 13492 default: 13493 if (key === "_fields") { 13494 parts.fields = get_normalized_comma_separable_default(value) ?? []; 13495 value = parts.fields.join(); 13496 } 13497 if (key === "include") { 13498 if (typeof value === "number") { 13499 value = value.toString(); 13500 } 13501 parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number); 13502 value = parts.include.join(); 13503 } 13504 parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1); 13505 } 13506 } 13507 return parts; 13508 } 13509 var get_query_parts_default = with_weak_map_cache_default(getQueryParts); 13510 13511
13511// packages/core-data/build-module/queried-data/selectors.mjs 13512 var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap(); 13513 function getQueriedItemsUncached(state, query, options = {}) { 13514 const { supportsPagination = true } = options; 13515 const { 13516 stableKey, 13517 page, 13518 perPage, 13519 offset: queryOffset, 13520 include, 13521 fields, 13522 context 13523 } = get_query_parts_default(query); 13524 const itemIds = state.queries?.[context]?.[stableKey]?.itemIds; 13525 if (!itemIds) { 13526 return null; 13527 } 13528 const isPaginated = supportsPagination && perPage !== -1; 13529 const startOffset = isPaginated ? queryOffset ?? (page - 1) * perPage : 0; 13530 const endOffset = isPaginated ? Math.min(startOffset + perPage, itemIds.length) : itemIds.length; 13531 if (isPaginated && itemIds.length < startOffset + perPage) { 13532 const totalItems = state.queries[context][stableKey].meta?.totalItems; 13533 if (Number.isFinite(totalItems) && itemIds.length < totalItems) { 13534 return null; 13535 } 13536 } 13537 const items2 = []; 13538 for (let i = startOffset; i < endOffset; i++) { 13539 const itemId = itemIds[i]; 13540 if (Array.isArray(include) && !include.includes(itemId)) { 13541 continue; 13542 } 13543 if (itemId === void 0) { 13544 continue; 13545 } 13546 if (!state.items[context]?.hasOwnProperty(itemId)) { 13547 return null; 13548 } 13549 const item = state.items[context][itemId]; 13550 let filteredItem; 13551 if (Array.isArray(fields)) { 13552 filteredItem = {}; 13553 for (let f = 0; f < fields.length; f++) { 13554 const field = fields[f].split("."); 13555 let value = item; 13556 field.forEach((fieldName) => { 13557 value = value?.[fieldName]; 13558 }); 13559 setNestedValue(filteredItem, field, value); 13560 } 13561 } else { 13562 if (!state.itemIsComplete[context]?.[itemId]) { 13563 return null; 13564 } 13565 filteredItem = item; 13566 } 13567 items2.push(filteredItem); 13568 } 13569 return items2; 13570 } 13571 function getQueriedItems(state, query = {}, options = {}) { 13572 let queriedItemsCache = queriedItemsCacheByState.get(state); 13573 if (queriedItemsCache) { 13574 const queriedItems = queriedItemsCache.get(query); 13575 if (queriedItems !== void 0) { 13576 return queriedItems; 13577 } 13578 } else { 13579 queriedItemsCache = new import_equivalent_key_map.default(); 13580 queriedItemsCacheByState.set(state, queriedItemsCache); 13581 } 13582 const items2 = getQueriedItemsUncached(state, query, options); 13583 queriedItemsCache.set(query, items2); 13584 return items2; 13585 } 13586 function getQueriedTotalItems(state, query = {}) { 13587 const { stableKey, context } = get_query_parts_default(query); 13588 return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null; 13589 } 13590 function getQueriedTotalPages(state, query = {}) { 13591 const { stableKey, context } = get_query_parts_default(query); 13592 return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null; 13593 } 13594 13595
13595// packages/core-data/build-module/queried-data/reducer.mjs 13596 var import_data6 = __toESM(require_data(), 1); 13597 var import_compose = __toESM(require_compose(), 1); 13598 13599
vendor: 378 bytes, lines 13599-13611
13599// node_modules/tslib/tslib.es6.mjs 13600 var __assign = function() { 13601 __assign = Object.assign || function __assign2(t) { 13602 for (var s, i = 1, n = arguments.length; i < n; i++) { 13603 s = arguments[i]; 13604 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; 13605 } 13606 return t; 13607 }; 13608 return __assign.apply(this, arguments); 13609 }; 13610 13611
vendor: 113 bytes, lines 13611-13616
13611// node_modules/lower-case/dist.es2015/index.js 13612 function lowerCase(str) { 13613 return str.toLowerCase(); 13614 } 13615 13616
vendor: 1,109 bytes, lines 13616-13641
13616// node_modules/no-case/dist.es2015/index.js 13617 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g]; 13618 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi; 13619 function noCase(input, options) { 13620 if (options === void 0) { 13621 options = {}; 13622 } 13623 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; 13624 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0"); 13625 var start = 0; 13626 var end = result.length; 13627 while (result.charAt(start) === "\0") 13628 start++; 13629 while (result.charAt(end - 1) === "\0") 13630 end--; 13631 return result.slice(start, end).split("\0").map(transform).join(delimiter); 13632 } 13633 function replace(input, re, value) { 13634 if (re instanceof RegExp) 13635 return input.replace(re, value); 13636 return re.reduce(function(input2, re2) { 13637 return input2.replace(re2, value); 13638 }, input); 13639 } 13640 13641
vendor: 552 bytes, lines 13641-13657
13641// node_modules/pascal-case/dist.es2015/index.js 13642 function pascalCaseTransform(input, index) { 13643 var firstChar = input.charAt(0); 13644 var lowerChars = input.substr(1).toLowerCase(); 13645 if (index > 0 && firstChar >= "0" && firstChar <= "9") { 13646 return "_" + firstChar + lowerChars; 13647 } 13648 return "" + firstChar.toUpperCase() + lowerChars; 13649 } 13650 function pascalCase(input, options) { 13651 if (options === void 0) { 13652 options = {}; 13653 } 13654 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options)); 13655 } 13656 13657
vendor: 385 bytes, lines 13657-13670
13657// node_modules/camel-case/dist.es2015/index.js 13658 function camelCaseTransform(input, index) { 13659 if (index === 0) 13660 return input.toLowerCase(); 13661 return pascalCaseTransform(input, index); 13662 } 13663 function camelCase(input, options) { 13664 if (options === void 0) { 13665 options = {}; 13666 } 13667 return pascalCase(input, __assign({ transform: camelCaseTransform }, options)); 13668 } 13669 13670
vendor: 156 bytes, lines 13670-13675
13670// node_modules/upper-case-first/dist.es2015/index.js 13671 function upperCaseFirst(input) { 13672 return input.charAt(0).toUpperCase() + input.substr(1); 13673 } 13674 13675
vendor: 345 bytes, lines 13675-13686
13675// node_modules/capital-case/dist.es2015/index.js 13676 function capitalCaseTransform(input) { 13677 return upperCaseFirst(input.toLowerCase()); 13678 } 13679 function capitalCase(input, options) { 13680 if (options === void 0) { 13681 options = {}; 13682 } 13683 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options)); 13684 } 13685 13686
13686// packages/core-data/build-module/entities.mjs 13687 var import_api_fetch3 = __toESM(require_api_fetch(), 1); 13688 var import_blocks4 = __toESM(require_blocks(), 1); 13689 var import_i18n = __toESM(require_i18n(), 1); 13690 13691
13691// packages/core-data/build-module/awareness/post-editor-awareness.mjs 13692 var import_data4 = __toESM(require_data(), 1); 13693 var import_block_editor3 = __toESM(require_block_editor(), 1); 13694 13695
13695// packages/core-data/build-module/awareness/base-awareness.mjs 13696 var import_data = __toESM(require_data(), 1); 13697 13698
13698// packages/core-data/build-module/awareness/config.mjs 13699 var AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS = 100; 13700 var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5; 13701 var REMOVAL_DELAY_IN_MS = 5e3; 13702 13703
13703// packages/core-data/build-module/awareness/utils.mjs 13704 function getBrowserName() { 13705 const userAgent = window.navigator.userAgent; 13706 let browserName = "Unknown"; 13707 if (userAgent.includes("Firefox")) { 13708 browserName = "Firefox"; 13709 } else if (userAgent.includes("Edg")) { 13710 browserName = "Microsoft Edge"; 13711 } else if (userAgent.includes("Chrome") && !userAgent.includes("Edg")) { 13712 browserName = "Chrome"; 13713 } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) { 13714 browserName = "Safari"; 13715 } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) { 13716 browserName = "Internet Explorer"; 13717 } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) { 13718 browserName = "Opera"; 13719 } 13720 return browserName; 13721 } 13722 function areMapsEqual(map1, map2, comparatorFn) { 13723 if (map1.size !== map2.size) { 13724 return false; 13725 } 13726 for (const [key, value1] of map1.entries()) { 13727 if (!map2.has(key)) { 13728 return false; 13729 } 13730 if (!comparatorFn(value1, map2.get(key))) { 13731 return false; 13732 } 13733 } 13734 return true; 13735 } 13736 function areCollaboratorInfosEqual(collaboratorInfo1, collaboratorInfo2) { 13737 if (!collaboratorInfo1 || !collaboratorInfo2) { 13738 return collaboratorInfo1 === collaboratorInfo2; 13739 } 13740 if (Object.keys(collaboratorInfo1).length !== Object.keys(collaboratorInfo2).length) { 13741 return false; 13742 } 13743 return Object.entries(collaboratorInfo1).every(([key, value]) => { 13744 return value === collaboratorInfo2[key]; 13745 }); 13746 } 13747 function generateCollaboratorInfo(currentCollaborator) { 13748 const { avatar_urls, id: id2, name, slug } = currentCollaborator; 13749 return { 13750 avatar_urls, 13751 // eslint-disable-line camelcase 13752 browserType: getBrowserName(), 13753 enteredAt: Date.now(), 13754 id: id2, 13755 name, 13756 slug 13757 }; 13758 } 13759 function getRecordValue(obj, key) { 13760 if ("object" === typeof obj && null !== obj && key in obj) { 13761 return obj[key]; 13762 } 13763 return null; 13764 } 13765 function getTypedKeys(obj) { 13766 return Object.keys(obj); 13767 } 13768 13769
13769// packages/core-data/build-module/awareness/typed-awareness.mjs 13770 var TypedAwareness = class extends Awareness { 13771 /** 13772 * Get the states from an awareness document. 13773 */ 13774 getStates() { 13775 return super.getStates(); 13776 } 13777 /** 13778 * Get a local state field from an awareness document. 13779 * @param field 13780 */ 13781 getLocalStateField(field) { 13782 const state = this.getLocalState(); 13783 return getRecordValue(state, field); 13784 } 13785 /** 13786 * Set a local state field on an awareness document. 13787 * @param field 13788 * @param value 13789 */ 13790 setLocalStateField(field, value) { 13791 super.setLocalStateField(field, value); 13792 } 13793 }; 13794 13795
13795// packages/core-data/build-module/awareness/awareness-state.mjs 13796 var AwarenessWithEqualityChecks = class extends TypedAwareness { 13797 /** OVERRIDDEN METHODS */ 13798 /** 13799 * Set a local state field on an awareness document. Calling this method may 13800 * trigger rerenders of any subscribed components. 13801 * 13802 * Equality checks are provided by the abstract `equalityFieldChecks` property. 13803 * @param field - The field to set. 13804 * @param value - The value to set. 13805 */ 13806 setLocalStateField(field, value) { 13807 if (this.isFieldEqual( 13808 field, 13809 value, 13810 this.getLocalStateField(field) ?? void 0 13811 )) { 13812 return; 13813 } 13814 super.setLocalStateField(field, value); 13815 } 13816 /** CUSTOM METHODS */ 13817 /** 13818 * Determine if a field value has changed using the provided equality checks. 13819 * @param field - The field to check. 13820 * @param value1 - The first value to compare. 13821 * @param value2 - The second value to compare. 13822 */ 13823 isFieldEqual(field, value1, value2) { 13824 if (["clientId", "isConnected", "isMe"].includes(field)) { 13825 return value1 === value2; 13826 } 13827 if (field in this.equalityFieldChecks) { 13828 const fn = this.equalityFieldChecks[field]; 13829 return fn(value1, value2); 13830 } 13831 throw new Error( 13832 `No equality check implemented for awareness state field "${field.toString()}".` 13833 ); 13834 } 13835 /** 13836 * Determine if two states are equal by comparing each field using the 13837 * provided equality checks. 13838 * @param state1 - The first state to compare. 13839 * @param state2 - The second state to compare. 13840 */ 13841 isStateEqual(state1, state2) { 13842 return [ 13843 .../* @__PURE__ */ new Set([ 13844 ...getTypedKeys(state1), 13845 ...getTypedKeys(state2) 13846 ]) 13847 ].every((field) => { 13848 const value1 = state1[field]; 13849 const value2 = state2[field]; 13850 return this.isFieldEqual(field, value1, value2); 13851 }); 13852 } 13853 }; 13854 var AwarenessState = class extends AwarenessWithEqualityChecks { 13855 /** CUSTOM PROPERTIES */ 13856 /** 13857 * Whether the setUp method has been called, to avoid running it multiple 13858 * times. 13859 */ 13860 hasSetupRun = false; 13861 /** 13862 * We keep track of all seen states during the current session for two reasons: 13863 * 13864 * 1. So that we can represent recently disconnected collaborators in our UI, even 13865 * after they have been removed from the awareness document. 13866 * 2. So that we can provide debug information about all collaborators seen during 13867 * the session. 13868 */ 13869 disconnectedCollaborators = /* @__PURE__ */ new Set(); 13870 seenStates = /* @__PURE__ */ new Map(); 13871 /** 13872 * Hold a snapshot of the previous awareness state allows us to compare the 13873 * state values and avoid unnecessary updates to subscribers. 13874 */ 13875 previousSnapshot = /* @__PURE__ */ new Map(); 13876 stateSubscriptions = []; 13877 /** 13878 * In some cases, we may want to throttle setting local state fields to avoid 13879 * overwhelming the awareness document with rapid updates. At the same time, we 13880 * want to ensure that when we read our own state locally, we get the latest 13881 * value -- even if it hasn't yet been set on the awareness instance. 13882 */ 13883 myThrottledState = {}; 13884 throttleTimeouts = /* @__PURE__ */ new Map(); 13885 /** CUSTOM METHODS */ 13886 /** 13887 * Set up the awareness state. This method is idempotent and will only run 13888 * once. Subclasses should override `onSetUp()` instead of this method to 13889 * add their own setup logic. 13890 * 13891 * This is defined as a readonly arrow function property to prevent 13892 * subclasses from overriding it. 13893 */ 13894 setUp = () => { 13895 if (this.hasSetupRun) { 13896 return; 13897 } 13898 this.hasSetupRun = true; 13899 this.onSetUp(); 13900 this.on( 13901 "change", 13902 ({ added, removed, updated }) => { 13903 [...added, ...updated].forEach((id2) => { 13904 this.disconnectedCollaborators.delete(id2); 13905 }); 13906 removed.forEach((id2) => { 13907 this.disconnectedCollaborators.add(id2); 13908 setTimeout(() => { 13909 this.disconnectedCollaborators.delete(id2); 13910 this.updateSubscribers( 13911 true 13912 /* force update */ 13913 ); 13914 }, REMOVAL_DELAY_IN_MS); 13915 }); 13916 this.updateSubscribers(); 13917 } 13918 ); 13919 }; 13920 /** 13921 * Get the most recent state from the last processed change event. 13922 * 13923 * @return An array of EnhancedState< State >. 13924 */ 13925 getCurrentState() {
13926 return Array.from(this.previousSnapshot.values()); 13927 } 13928 /** 13929 * Get all seen states in this session to enable debug reporting. 13930 */ 13931 getSeenStates() { 13932 return this.seenStates; 13933 } 13934 /** 13935 * Allow external code to subscribe to awareness state changes. 13936 * @param callback - The callback to subscribe to. 13937 */ 13938 onStateChange(callback) { 13939 this.stateSubscriptions.push(callback); 13940 return () => { 13941 this.stateSubscriptions = this.stateSubscriptions.filter( 13942 (cb) => cb !== callback 13943 ); 13944 }; 13945 } 13946 /** 13947 * Set a local state field on an awareness document with throttle. See caveats 13948 * of this.setLocalStateField. 13949 * @param field - The field to set. 13950 * @param value - The value to set. 13951 * @param wait - The wait time in milliseconds. 13952 */ 13953 setThrottledLocalStateField(field, value, wait) { 13954 this.setLocalStateField(field, value); 13955 this.throttleTimeouts.set( 13956 field, 13957 setTimeout(() => { 13958 this.throttleTimeouts.delete(field); 13959 if (this.myThrottledState[field]) { 13960 this.setLocalStateField( 13961 field, 13962 this.myThrottledState[field] 13963 ); 13964 delete this.myThrottledState[field]; 13965 } 13966 }, wait) 13967 ); 13968 } 13969 /** 13970 * Set the current collaborator's connection status as awareness state. 13971 * @param isConnected - The connection status. 13972 */ 13973 setConnectionStatus(isConnected) { 13974 if (isConnected) { 13975 this.disconnectedCollaborators.delete(this.clientID); 13976 } else { 13977 this.disconnectedCollaborators.add(this.clientID); 13978 } 13979 this.updateSubscribers( 13980 true 13981 /* force update */ 13982 ); 13983 } 13984 /** 13985 * Update all subscribed listeners with the latest awareness state. 13986 * @param forceUpdate - Whether to force an update. 13987 */ 13988 updateSubscribers(forceUpdate = false) { 13989 if (!this.stateSubscriptions.length) { 13990 return; 13991 } 13992 const states = this.getStates(); 13993 this.seenStates = new Map([ 13994 ...this.seenStates.entries(), 13995 ...states.entries() 13996 ]); 13997 const updatedStates = new Map( 13998 [...this.disconnectedCollaborators, ...states.keys()].filter((clientId) => { 13999 return Object.keys(this.seenStates.get(clientId) ?? {}).length > 0; 14000 }).map((clientId) => { 14001 const rawState = this.seenStates.get(clientId); 14002 const isConnected = !this.disconnectedCollaborators.has(clientId); 14003 const isMe = clientId === this.clientID; 14004 const myState = isMe ? this.myThrottledState : {}; 14005 const state = { 14006 ...rawState, 14007 ...myState, 14008 clientId, 14009 isConnected, 14010 isMe 14011 }; 14012 return [clientId, state]; 14013 }) 14014 ); 14015 if (!forceUpdate) { 14016 if (areMapsEqual( 14017 this.previousSnapshot, 14018 updatedStates, 14019 this.isStateEqual.bind(this) 14020 )) { 14021 return; 14022 } 14023 } 14024 this.previousSnapshot = updatedStates; 14025 this.stateSubscriptions.forEach((callback) => { 14026 callback(Array.from(updatedStates.values())); 14027 }); 14028 } 14029 }; 14030 14031
14031// packages/core-data/build-module/name.mjs 14032 var STORE_NAME = "core"; 14033 14034
14034// packages/core-data/build-module/awareness/base-awareness.mjs 14035 var BaseAwarenessState = class extends AwarenessState { 14036 onSetUp() { 14037 void this.setCurrentCollaboratorInfo(); 14038 } 14039 /** 14040 * Set the current collaborator info in the local state. 14041 */ 14042 async setCurrentCollaboratorInfo() { 14043 const currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser(); 14044 const collaboratorInfo = generateCollaboratorInfo(currentUser2); 14045 this.setLocalStateField("collaboratorInfo", collaboratorInfo); 14046 } 14047 }; 14048 var baseEqualityFieldChecks = { 14049 collaboratorInfo: areCollaboratorInfosEqual 14050 }; 14051 var BaseAwareness = class extends BaseAwarenessState { 14052 equalityFieldChecks = baseEqualityFieldChecks; 14053 }; 14054 14055
14055// packages/core-data/build-module/awareness/block-lookup.mjs 14056 var import_data2 = __toESM(require_data(), 1); 14057 var import_block_editor = __toESM(require_block_editor(), 1); 14058 function getContainingBlockYMap(yType) { 14059 let current = yType; 14060 while (current) { 14061 const parent = current.parent; 14062 if (parent instanceof yjs_exports.Map && parent.parent instanceof yjs_exports.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof yjs_exports.Array) { 14063 return parent; 14064 } 14065 current = parent instanceof yjs_exports.AbstractType ? parent : null; 14066 } 14067 return null; 14068 } 14069 function getBlockPathInYdoc(yType) { 14070 const path = []; 14071 let current = yType; 14072 while (current) { 14073 const parentArray = current.parent; 14074 if (!parentArray || !(parentArray instanceof yjs_exports.Array)) { 14075 return null; 14076 } 14077 let index = -1; 14078 for (let i = 0; i < parentArray.length; i++) { 14079 if (parentArray.get(i) === current) { 14080 index = i; 14081 break; 14082 } 14083 } 14084 if (index === -1) { 14085 return null; 14086 } 14087 path.unshift(index); 14088 const grandparent = parentArray.parent; 14089 if (grandparent instanceof yjs_exports.Map && grandparent.get("clientId") !== void 0) { 14090 current = grandparent; 14091 } else { 14092 break; 14093 } 14094 } 14095 return path; 14096 } 14097 function resolveBlockClientIdByPath(path, blocks) { 14098 if (path.length === 0) { 14099 return null; 14100 } 14101 for (let i = 0; i < path.length; i++) { 14102 const block = blocks[path[i]]; 14103 if (!block) { 14104 return null; 14105 } 14106 if (i === path.length - 1) { 14107 return block.clientId; 14108 } 14109 blocks = block.innerBlocks; 14110 } 14111 return null; 14112 } 14113 function usePostContentBlocks() { 14114 return (0, import_data2.useSelect)((select4) => { 14115 const { getBlocksByName, getClientIdsTree } = unlock2( 14116 select4(import_block_editor.store) 14117 ); 14118 const [postContentClientId] = getBlocksByName("core/post-content"); 14119 return getClientIdsTree(postContentClientId ?? ""); 14120 }, []); 14121 } 14122 14123
14123// packages/core-data/build-module/utils/crdt-utils.mjs 14124 var import_rich_text = __toESM(require_rich_text(), 1); 14125 function getRootMap(doc2, key) { 14126 return doc2.getMap(key); 14127 } 14128 function createYMap(partial = {}) { 14129 return new yjs_exports.Map(Object.entries(partial)); 14130 } 14131 function isYMap(value) { 14132 return value instanceof yjs_exports.Map; 14133 } 14134 function asRichTextOffset(offset) { 14135 return offset; 14136 } 14137 function asHtmlStringIndex(index) { 14138 return index; 14139 } 14140 function getYTextByAttributeKey(attributes, attributeKey) { 14141 const directValue = attributes.get(attributeKey); 14142 if (directValue instanceof yjs_exports.Text) { 14143 return directValue; 14144 } 14145 let value = attributes; 14146 for (const pathPart of attributeKey.split(".")) { 14147 if (value instanceof yjs_exports.Map) { 14148 value = value.get(pathPart); 14149 } else if (value instanceof yjs_exports.Array) { 14150 const index = Number.parseInt(pathPart, 10); 14151 if (!Number.isSafeInteger(index) || index < 0 || index.toString() !== pathPart) { 14152 return null; 14153 } 14154 value = value.get(index); 14155 } else { 14156 return null; 14157 } 14158 } 14159 return value instanceof yjs_exports.Text ? value : null; 14160 } 14161 function findBlockByClientIdInDoc(blockId, ydoc) { 14162 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2); 14163 const blocks = ymap.get("blocks"); 14164 if (!(blocks instanceof yjs_exports.Array)) { 14165 return null; 14166 } 14167 return findBlockByClientIdInBlocks(blockId, blocks); 14168 } 14169 var MARKER_START = 57344; 14170 function pickMarker(text2) { 14171 const tryCount = 16; 14172 for (let code = MARKER_START; code < MARKER_START + tryCount; code++) {
14173 const candidate = String.fromCharCode(code); 14174 if (!text2.includes(candidate)) { 14175 return candidate; 14176 } 14177 } 14178 return null; 14179 } 14180 function htmlIndexToRichTextOffset(html, htmlIndex) { 14181 if (!html.includes("<") && !html.includes("&")) { 14182 return asRichTextOffset(htmlIndex); 14183 } 14184 const marker = pickMarker(html); 14185 if (!marker) { 14186 return asRichTextOffset(htmlIndex); 14187 } 14188 const withMarker = html.slice(0, htmlIndex) + marker + html.slice(htmlIndex); 14189 const value = (0, import_rich_text.create)({ html: withMarker }); 14190 const markerPos = value.text.indexOf(marker); 14191 return asRichTextOffset(markerPos === -1 ? htmlIndex : markerPos); 14192 } 14193 function richTextOffsetToHtmlIndex(html, richTextOffset) { 14194 if (!html.includes("<") && !html.includes("&")) { 14195 return asHtmlStringIndex(richTextOffset); 14196 } 14197 const marker = pickMarker(html); 14198 if (!marker) { 14199 return asHtmlStringIndex(richTextOffset); 14200 } 14201 const value = (0, import_rich_text.create)({ html }); 14202 const markerValue = (0, import_rich_text.create)({ text: marker }); 14203 if (value.formats[richTextOffset]) { 14204 markerValue.formats[0] = value.formats[richTextOffset]; 14205 } 14206 const withMarker = (0, import_rich_text.insert)( 14207 value, 14208 markerValue, 14209 richTextOffset, 14210 richTextOffset 14211 ); 14212 const htmlWithMarker = (0, import_rich_text.toHTMLString)({ value: withMarker }); 14213 const markerIndex = htmlWithMarker.indexOf(marker); 14214 return asHtmlStringIndex( 14215 markerIndex === -1 ? richTextOffset : markerIndex 14216 ); 14217 } 14218 function findBlockByClientIdInBlocks(blockId, blocks) { 14219 for (const block of blocks) { 14220 if (block.get("clientId") === blockId) { 14221 return block; 14222 } 14223 const innerBlocks = block.get("innerBlocks"); 14224 if (innerBlocks && innerBlocks.length > 0) { 14225 const innerBlock = findBlockByClientIdInBlocks( 14226 blockId, 14227 innerBlocks 14228 ); 14229 if (innerBlock) { 14230 return innerBlock; 14231 } 14232 } 14233 } 14234 return null; 14235 } 14236 14237
14237// packages/core-data/build-module/utils/crdt-user-selections.mjs 14238 var import_data3 = __toESM(require_data(), 1); 14239 var import_block_editor2 = __toESM(require_block_editor(), 1); 14240 var SelectionType = /* @__PURE__ */ ((SelectionType2) => { 14241 SelectionType2["None"] = "none"; 14242 SelectionType2["Cursor"] = "cursor"; 14243 SelectionType2["SelectionInOneBlock"] = "selection-in-one-block"; 14244 SelectionType2["SelectionInMultipleBlocks"] = "selection-in-multiple-blocks"; 14245 SelectionType2["WholeBlock"] = "whole-block"; 14246 return SelectionType2; 14247 })(SelectionType || {}); 14248 var SelectionDirection = /* @__PURE__ */ ((SelectionDirection2) => { 14249 SelectionDirection2["Forward"] = "f"; 14250 SelectionDirection2["Backward"] = "b"; 14251 return SelectionDirection2; 14252 })(SelectionDirection || {}); 14253 function getSelectionState(selectionStart, selectionEnd, yDoc, options) { 14254 const { selectionDirection } = options ?? {}; 14255 const ymap = getRootMap(yDoc, CRDT_RECORD_MAP_KEY2); 14256 const yBlocks = ymap.get("blocks"); 14257 const isSelectionEmpty = Object.keys(selectionStart).length === 0; 14258 const noSelection = { 14259 type: "none" 14260 /* None */ 14261 }; 14262 if (isSelectionEmpty || !yBlocks) { 14263 return noSelection; 14264 } 14265 const isSelectionInOneBlock = selectionStart.clientId === selectionEnd.clientId; 14266 const isCursorOnly = isSelectionInOneBlock && selectionStart.offset === selectionEnd.offset; 14267 const isSelectionAWholeBlock = isSelectionInOneBlock && selectionStart.offset === void 0 && selectionEnd.offset === void 0; 14268 if (isSelectionAWholeBlock) { 14269 const path = getBlockPathForLocalClientId(selectionStart.clientId); 14270 const blockPosition = path ? createRelativePositionForBlockPath(path, yBlocks) : null; 14271 if (!blockPosition) { 14272 return noSelection; 14273 } 14274 return { 14275 type: "whole-block", 14276 blockPosition 14277 }; 14278 } else if (isCursorOnly) { 14279 const cursorPosition = getCursorPosition(selectionStart, yBlocks); 14280 if (!cursorPosition) { 14281 return noSelection; 14282 } 14283 return { 14284 type: "cursor", 14285 cursorPosition 14286 }; 14287 } else if (isSelectionInOneBlock) { 14288 const cursorStartPosition2 = getCursorPosition( 14289 selectionStart, 14290 yBlocks 14291 ); 14292 const cursorEndPosition2 = getCursorPosition(selectionEnd, yBlocks); 14293 if (!cursorStartPosition2 || !cursorEndPosition2) { 14294 return noSelection; 14295 } 14296 return { 14297 type: "selection-in-one-block", 14298 cursorStartPosition: cursorStartPosition2, 14299 cursorEndPosition: cursorEndPosition2, 14300 selectionDirection 14301 }; 14302 } 14303 const cursorStartPosition = getCursorPosition(selectionStart, yBlocks); 14304 const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks); 14305 if (!cursorStartPosition || !cursorEndPosition) { 14306 return noSelection; 14307 } 14308 return { 14309 type: "selection-in-multiple-blocks", 14310 cursorStartPosition, 14311 cursorEndPosition, 14312 selectionDirection 14313 }; 14314 } 14315 function getCursorPosition(selection, blocks) { 14316 const path = getBlockPathForLocalClientId(selection.clientId); 14317 const block = path ? findBlockByPath(path, blocks) : null; 14318 if (!block || !selection.attributeKey || void 0 === selection.offset) { 14319 return null; 14320 } 14321 const attributes = block.get("attributes"); 14322 const currentYText = attributes ? getYTextByAttributeKey(attributes, selection.attributeKey) : null; 14323 if (!(currentYText instanceof yjs_exports.Text)) { 14324 return null; 14325 } 14326 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex( 14327 currentYText, 14328 richTextOffsetToHtmlIndex( 14329 currentYText.toString(), 14330 asRichTextOffset(selection.offset) 14331 ) 14332 ); 14333 return { 14334 relativePosition, 14335 absoluteOffset: selection.offset, 14336 attributeKey: selection.attributeKey 14337 }; 14338 } 14339 function getBlockPathForLocalClientId(clientId) { 14340 const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data3.select)(import_block_editor2.store); 14341 const path = []; 14342 let current = clientId; 14343 while (current) { 14344 const index = getBlockIndex(current); 14345 if (index === -1) { 14346 return null; 14347 } 14348 path.unshift(index);
14349 const parent = getBlockRootClientId(current); 14350 if (!parent) { 14351 break; 14352 } 14353 const parentName = getBlockName(parent); 14354 if (parentName === "core/post-content") { 14355 break; 14356 } 14357 current = parent; 14358 } 14359 return path.length > 0 ? path : null; 14360 } 14361 function findBlockByPath(path, blocks) { 14362 let currentBlocks = blocks; 14363 for (let i = 0; i < path.length; i++) { 14364 if (path[i] >= currentBlocks.length) { 14365 return null; 14366 } 14367 const block = currentBlocks.get(path[i]); 14368 if (!block) { 14369 return null; 14370 } 14371 if (i === path.length - 1) { 14372 return block; 14373 } 14374 currentBlocks = block.get("innerBlocks") ?? new yjs_exports.Array(); 14375 } 14376 return null; 14377 } 14378 function createRelativePositionForBlockPath(path, blocks) { 14379 let currentBlocks = blocks; 14380 for (let i = 0; i < path.length; i++) { 14381 if (path[i] >= currentBlocks.length) { 14382 return null; 14383 } 14384 if (i === path.length - 1) { 14385 return yjs_exports.createRelativePositionFromTypeIndex( 14386 currentBlocks, 14387 path[i] 14388 ); 14389 } 14390 const block = currentBlocks.get(path[i]); 14391 currentBlocks = block?.get("innerBlocks") ?? new yjs_exports.Array(); 14392 } 14393 return null; 14394 } 14395 function areSelectionsStatesEqual(selection1, selection2) { 14396 if (selection1.type !== selection2.type) { 14397 return false; 14398 } 14399 switch (selection1.type) { 14400 case "none": 14401 return true; 14402 case "cursor": 14403 return areCursorPositionsEqual( 14404 selection1.cursorPosition, 14405 selection2.cursorPosition 14406 ); 14407 case "selection-in-one-block": 14408 return areCursorPositionsEqual( 14409 selection1.cursorStartPosition, 14410 selection2.cursorStartPosition 14411 ) && areCursorPositionsEqual( 14412 selection1.cursorEndPosition, 14413 selection2.cursorEndPosition 14414 ) && selection1.selectionDirection === selection2.selectionDirection; 14415 case "selection-in-multiple-blocks": 14416 return areCursorPositionsEqual( 14417 selection1.cursorStartPosition, 14418 selection2.cursorStartPosition 14419 ) && areCursorPositionsEqual( 14420 selection1.cursorEndPosition, 14421 selection2.cursorEndPosition 14422 ) && selection1.selectionDirection === selection2.selectionDirection; 14423 case "whole-block": 14424 return yjs_exports.compareRelativePositions( 14425 selection1.blockPosition, 14426 selection2.blockPosition 14427 ); 14428 default: 14429 return false; 14430 } 14431 } 14432 function areCursorPositionsEqual(cursorPosition1, cursorPosition2) { 14433 const isRelativePositionEqual = yjs_exports.compareRelativePositions( 14434 cursorPosition1.relativePosition, 14435 cursorPosition2.relativePosition 14436 ); 14437 const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset; 14438 return isRelativePositionEqual && isAbsoluteOffsetEqual; 14439 } 14440 14441
14441// packages/core-data/build-module/awareness/post-editor-awareness.mjs 14442 var PostEditorAwareness = class extends BaseAwarenessState { 14443 constructor(doc2, kind, name, postId) { 14444 super(doc2); 14445 this.kind = kind; 14446 this.name = name; 14447 this.postId = postId; 14448 } 14449 equalityFieldChecks = { 14450 ...baseEqualityFieldChecks, 14451 editorState: this.areEditorStatesEqual 14452 }; 14453 onSetUp() { 14454 super.onSetUp(); 14455 this.subscribeToCollaboratorSelectionChanges(); 14456 } 14457 /** 14458 * Subscribe to collaborator selection changes and update the selection state. 14459 */ 14460 subscribeToCollaboratorSelectionChanges() { 14461 const { 14462 getSelectionStart, 14463 getSelectionEnd, 14464 getSelectedBlocksInitialCaretPosition 14465 } = (0, import_data4.select)(import_block_editor3.store); 14466 let selectionStart = getSelectionStart(); 14467 let selectionEnd = getSelectionEnd(); 14468 let localCursorTimeout = null; 14469 let selectionBeforeDebounce = null; 14470 (0, import_data4.subscribe)(() => { 14471 const newSelectionStart = getSelectionStart(); 14472 const newSelectionEnd = getSelectionEnd(); 14473 if (newSelectionStart === selectionStart && newSelectionEnd === selectionEnd) { 14474 return; 14475 } 14476 if (!selectionBeforeDebounce) { 14477 selectionBeforeDebounce = { 14478 start: selectionStart, 14479 end: selectionEnd 14480 }; 14481 } 14482 selectionStart = newSelectionStart; 14483 selectionEnd = newSelectionEnd; 14484 const initialPosition = getSelectedBlocksInitialCaretPosition(); 14485 void this.updateSelectionInEntityRecord( 14486 selectionStart, 14487 selectionEnd, 14488 initialPosition 14489 ); 14490 if (localCursorTimeout) { 14491 clearTimeout(localCursorTimeout); 14492 } 14493 localCursorTimeout = setTimeout(() => { 14494 const selectionStateOptions = {}; 14495 if (selectionBeforeDebounce) { 14496 selectionStateOptions.selectionDirection = detectSelectionDirection( 14497 selectionBeforeDebounce.start, 14498 selectionBeforeDebounce.end, 14499 selectionStart, 14500 selectionEnd 14501 ); 14502 selectionBeforeDebounce = null; 14503 } 14504 const selectionState = getSelectionState( 14505 selectionStart, 14506 selectionEnd, 14507 this.doc, 14508 selectionStateOptions 14509 ); 14510 this.setThrottledLocalStateField( 14511 "editorState", 14512 { selection: selectionState }, 14513 AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS 14514 ); 14515 }, LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS); 14516 }); 14517 } 14518 /** 14519 * Update the entity record with the current collaborator's selection. 14520 * 14521 * @param selectionStart - The start position of the selection. 14522 * @param selectionEnd - The end position of the selection. 14523 * @param initialPosition - The initial position of the selection. 14524 */ 14525 async updateSelectionInEntityRecord(selectionStart, selectionEnd, initialPosition) { 14526 const edits = { 14527 selection: { selectionStart, selectionEnd, initialPosition } 14528 }; 14529 const options = { 14530 undoIgnore: true 14531 }; 14532 (0, import_data4.dispatch)(STORE_NAME).editEntityRecord( 14533 this.kind, 14534 this.name, 14535 this.postId, 14536 edits, 14537 options 14538 ); 14539 } 14540 /** 14541 * Check if two editor states are equal. 14542 * 14543 * @param state1 - The first editor state. 14544 * @param state2 - The second editor state. 14545 * @return True if the editor states are equal, false otherwise. 14546 */ 14547 areEditorStatesEqual(state1, state2) { 14548 if (!state1 || !state2) { 14549 return state1 === state2; 14550 } 14551 if (!state1.selection || !state2.selection) { 14552 return state1.selection === state2.selection; 14553 } 14554 return areSelectionsStatesEqual(state1.selection, state2.selection); 14555 } 14556 /** 14557 * Resolve a selection state to a text index and block client ID. 14558 * 14559 * For text-based selections, navigates up from the resolved Y.Text via 14560 * AbstractType.parent to find the containing block, then resolves the 14561 * local clientId via the block's tree path. 14562 * For WholeBlock selections, resolves the block's relative position and 14563 * then finds the local clientId via tree path. 14564 * 14565 * Tree-path resolution is used instead of reading the clientId directly 14566 * from the Yjs block because the local block-editor store may use different 14567 * clientIds (e.g. in "Show Template" mode where blocks are cloned). 14568 * 14569 * @param selection - The selection state. 14570 * @param blocks - The tree of block-editor store post content blocks. 14571 * @return The rich-text offset and block client ID, or nulls if not resolvable. 14572 */ 14573 convertSelectionStateToAbsolute(selection, blocks) { 14574 if (selection.type === SelectionType.None) { 14575 return { 14576 richTextOffset: null, 14577 localClientId: null, 14578 attributeKey: null 14579 }; 14580 } 14581 if (selection.type === SelectionType.WholeBlock) { 14582 const absolutePos = yjs_exports.createAbsolutePositionFromRelativePosition( 14583 selection.blockPosition, 14584 this.doc 14585 ); 14586 let localClientId2 = null; 14587 if (absolutePos && absolutePos.type instanceof yjs_exports.Array) { 14588 const parentArray = absolutePos.type; 14589 const block = parentArray.get(absolutePos.index); 14590 if (block instanceof yjs_exports.Map) { 14591 const path2 = getBlockPathInYdoc(block); 14592 localClientId2 = path2 ? resolveBlockClientIdByPath(path2, blocks) : null; 14593 } 14594 } 14595 return { 14596 richTextOffset: null, 14597 localClientId: localClientId2, 14598 attributeKey: null 14599 }; 14600 }
14601 const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition; 14602 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition( 14603 cursorPos.relativePosition, 14604 this.doc 14605 ); 14606 if (!absolutePosition) { 14607 return { 14608 richTextOffset: null, 14609 localClientId: null, 14610 attributeKey: null 14611 }; 14612 } 14613 const yType = getContainingBlockYMap(absolutePosition.type); 14614 const path = yType ? getBlockPathInYdoc(yType) : null; 14615 const localClientId = path ? resolveBlockClientIdByPath(path, blocks) : null; 14616 return { 14617 richTextOffset: htmlIndexToRichTextOffset( 14618 absolutePosition.type.toString(), 14619 asHtmlStringIndex(absolutePosition.index) 14620 ), 14621 localClientId, 14622 attributeKey: cursorPos.attributeKey ?? null 14623 }; 14624 } 14625 /** 14626 * Type guard to check if a struct is a Y.Item (not Y.GC) 14627 * @param struct - The struct to check. 14628 * @return True if the struct is a Y.Item, false otherwise. 14629 */ 14630 isYItem(struct) { 14631 return "content" in struct; 14632 } 14633 /** 14634 * Get data for debugging, using the awareness state. 14635 * 14636 * @return {YDocDebugData} The debug data. 14637 */ 14638 getDebugData() { 14639 const ydoc = this.doc; 14640 const docData = Object.fromEntries( 14641 Array.from(ydoc.share, ([key, value]) => [ 14642 key, 14643 value.toJSON() 14644 ]) 14645 ); 14646 const collaboratorMapData = new Map( 14647 Array.from(this.getSeenStates().entries()).map( 14648 ([clientId, collaboratorState]) => [ 14649 String(clientId), 14650 { 14651 name: collaboratorState.collaboratorInfo.name, 14652 wpUserId: collaboratorState.collaboratorInfo.id 14653 } 14654 ] 14655 ) 14656 ); 14657 const serializableClientItems = {}; 14658 ydoc.store.clients.forEach((structs, clientId) => { 14659 const items2 = structs.filter(this.isYItem); 14660 serializableClientItems[clientId] = items2.map((item) => { 14661 const { left, right, ...rest } = item; 14662 return { 14663 ...rest, 14664 left: left ? { 14665 id: left.id, 14666 length: left.length, 14667 origin: left.origin, 14668 content: left.content 14669 } : null, 14670 right: right ? { 14671 id: right.id, 14672 length: right.length, 14673 origin: right.origin, 14674 content: right.content 14675 } : null 14676 }; 14677 }); 14678 }); 14679 return { 14680 doc: docData, 14681 clients: serializableClientItems, 14682 collaboratorMap: Object.fromEntries(collaboratorMapData) 14683 }; 14684 } 14685 }; 14686 function detectSelectionDirection(prevStart, prevEnd, newStart, newEnd) { 14687 const startMoved = !areBlockSelectionsEqual(prevStart, newStart); 14688 const endMoved = !areBlockSelectionsEqual(prevEnd, newEnd); 14689 if (startMoved && !endMoved) { 14690 return SelectionDirection.Backward; 14691 } 14692 return SelectionDirection.Forward; 14693 } 14694 function areBlockSelectionsEqual(a, b) { 14695 return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset; 14696 } 14697 14698
14698// packages/core-data/build-module/utils/crdt.mjs 14699 var import_es66 = __toESM(require_es6(), 1); 14700 var import_blocks3 = __toESM(require_blocks(), 1); 14701 14702
vendor: 725 bytes, lines 14702-14711
14702// node_modules/uuid/dist/stringify.js 14703 var byteToHex = []; 14704 for (let i = 0; i < 256; ++i) { 14705 byteToHex.push((i + 256).toString(16).slice(1)); 14706 } 14707 function unsafeStringify(arr, offset = 0) { 14708 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(); 14709 } 14710 14711
vendor: 135 bytes, lines 14711-14717
14711// node_modules/uuid/dist/rng.js 14712 var rnds8 = new Uint8Array(16); 14713 function rng() { 14714 return crypto.getRandomValues(rnds8); 14715 } 14716 14717
vendor: 860 bytes, lines 14717-14746
14717// node_modules/uuid/dist/v4.js 14718 function v4(options, buf, offset) { 14719 if (!buf && !options && crypto.randomUUID) { 14720 return crypto.randomUUID(); 14721 } 14722 return _v4(options, buf, offset); 14723 } 14724 function _v4(options, buf, offset) { 14725 options = options || {}; 14726 const rnds = options.random ?? options.rng?.() ?? rng(); 14727 if (rnds.length < 16) { 14728 throw new Error("Random bytes length must be >= 16"); 14729 } 14730 rnds[6] = rnds[6] & 15 | 64; 14731 rnds[8] = rnds[8] & 63 | 128; 14732 if (buf) { 14733 offset = offset || 0; 14734 if (offset < 0 || offset + 16 > buf.length) { 14735 throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); 14736 } 14737 for (let i = 0; i < 16; ++i) { 14738 buf[offset + i] = rnds[i]; 14739 } 14740 return buf; 14741 } 14742 return unsafeStringify(rnds); 14743 } 14744 var v4_default = v4; 14745 14746
14746// packages/core-data/build-module/utils/crdt-blocks.mjs 14747 var import_es65 = __toESM(require_es6(), 1); 14748 var import_blocks = __toESM(require_blocks(), 1); 14749 var import_rich_text3 = __toESM(require_rich_text(), 1); 14750 14751
14751// packages/core-data/build-module/utils/crdt-text.mjs 14752 var import_rich_text2 = __toESM(require_rich_text(), 1); 14753 var RICH_TEXT_CACHE_MAX_SIZE = 500; 14754 function createRichTextDataCache(maxSize) { 14755 const cache3 = /* @__PURE__ */ new Map(); 14756 return function(value) { 14757 const cached = cache3.get(value); 14758 if (cached) { 14759 return cached; 14760 } 14761 const result = import_rich_text2.RichTextData.fromHTMLString(value); 14762 if (cache3.size >= maxSize) { 14763 cache3.delete(cache3.keys().next().value); 14764 } 14765 cache3.set(value, result); 14766 return result; 14767 }; 14768 } 14769 var getCachedRichTextData = createRichTextDataCache( 14770 RICH_TEXT_CACHE_MAX_SIZE 14771 ); 14772 14773
14773// packages/core-data/build-module/utils/crdt-blocks.mjs 14774 var serializableBlocksCache = /* @__PURE__ */ new WeakMap(); 14775 function serializeAttributeValue(value) { 14776 if (value instanceof import_rich_text3.RichTextData) { 14777 return value.valueOf(); 14778 } 14779 if (Array.isArray(value)) { 14780 return value.map(serializeAttributeValue); 14781 } 14782 if (value && typeof value === "object") { 14783 const result = {}; 14784 for (const [k, v] of Object.entries(value)) { 14785 result[k] = serializeAttributeValue(v); 14786 } 14787 return result; 14788 } 14789 return value; 14790 } 14791 function makeBlockAttributesSerializable(blockName, attributes) { 14792 const newAttributes = { ...attributes }; 14793 for (const [key, value] of Object.entries(attributes)) { 14794 if (isLocalAttribute(blockName, key)) { 14795 delete newAttributes[key]; 14796 continue; 14797 } 14798 newAttributes[key] = serializeAttributeValue(value); 14799 } 14800 return newAttributes; 14801 } 14802 function makeBlocksSerializable(blocks) { 14803 return blocks.map((block) => { 14804 const { 14805 name, 14806 innerBlocks, 14807 attributes, 14808 /* 14809 * Any validation issues discovered when loading a block are appended 14810 * to the block node with a logging function, which cannot be serialized. 14811 * 14812 * @see import("@wordpress/blocks/src/api/parser").parseRawBlock() 14813 */ 14814 validationIssues, 14815 ...rest 14816 } = block; 14817 return { 14818 ...rest, 14819 name, 14820 attributes: makeBlockAttributesSerializable(name, attributes), 14821 innerBlocks: makeBlocksSerializable(innerBlocks) 14822 }; 14823 }); 14824 } 14825 function deserializeAttributeValue(schema, value) { 14826 if (schema?.type === "rich-text" && typeof value === "string") { 14827 return getCachedRichTextData(value); 14828 } 14829 if (Array.isArray(value)) { 14830 return value.map( 14831 (item) => deserializeAttributeValue(schema, item) 14832 ); 14833 } 14834 if (value && typeof value === "object") { 14835 const result = {}; 14836 for (const [key, innerValue] of Object.entries( 14837 value 14838 )) { 14839 result[key] = deserializeAttributeValue( 14840 schema?.query?.[key], 14841 innerValue 14842 ); 14843 } 14844 return result; 14845 } 14846 return value; 14847 } 14848 function deserializeBlockAttributes(blocks) { 14849 return blocks.map((block) => { 14850 const { name, innerBlocks, attributes, ...rest } = block; 14851 const newAttributes = { ...attributes }; 14852 for (const [key, value] of Object.entries(attributes)) { 14853 const schema = getBlockAttributeSchema(name, key); 14854 if (schema) { 14855 newAttributes[key] = deserializeAttributeValue( 14856 schema, 14857 value 14858 ); 14859 } 14860 } 14861 return { 14862 ...rest, 14863 name, 14864 attributes: newAttributes, 14865 innerBlocks: deserializeBlockAttributes(innerBlocks ?? []) 14866 }; 14867 }); 14868 } 14869 function areBlocksEqual(gblock, yblock) { 14870 const yblockAsJson = yblock.toJSON(); 14871 const overwrites = { 14872 innerBlocks: null, 14873 clientId: null 14874 }; 14875 const res = (0, import_es65.default)( 14876 Object.assign({}, gblock, overwrites), 14877 Object.assign({}, yblockAsJson, overwrites) 14878 ); 14879 const inners = gblock.innerBlocks || []; 14880 const yinners = yblock.get("innerBlocks"); 14881 return res && inners.length === yinners?.length && inners.every( 14882 (block, i) => areBlocksEqual(block, yinners.get(i)) 14883 ); 14884 } 14885 function createNewYAttributeMap(blockName, attributes) { 14886 return new yjs_exports.Map( 14887 Object.entries(attributes).map( 14888 ([attributeName, attributeValue]) => { 14889 return [ 14890 attributeName, 14891 createNewYAttributeValue( 14892 blockName, 14893 attributeName, 14894 attributeValue 14895 ) 14896 ]; 14897 } 14898 ) 14899 ); 14900 } 14901 function createNewYAttributeValue(blockName, attributeName, attributeValue) { 14902 const schema = getBlockAttributeSchema(blockName, attributeName); 14903 return createYValueFromSchema(schema, attributeValue); 14904 } 14905 function createYValueFromSchema(schema, value) { 14906 if (!schema) { 14907 return value; 14908 } 14909 if (schema.type === "rich-text") { 14910 return new yjs_exports.Text(value?.toString() ?? ""); 14911 } 14912 if (schema.type === "array" && schema.query && Array.isArray(value)) { 14913 const query = schema.query; 14914 const yArray = new yjs_exports.Array(); 14915 yArray.insert( 14916 0, 14917 value.map((item) => createYMapFromQuery(query, item)) 14918 ); 14919 return yArray; 14920 } 14921 if (schema.type === "object" && schema.query && isRecord(value)) { 14922 return createYMapFromQuery(schema.query, value); 14923 } 14924 return value; 14925 } 14926 function isRecord(value) { 14927 return !!value && typeof value === "object" && !Array.isArray(value); 14928 } 14929 function createYMapFromQuery(query, obj) { 14930 if (!isRecord(obj)) { 14931 return new yjs_exports.Map(); 14932 } 14933 const entries = Object.entries(obj).map( 14934 ([key, val]) => { 14935 const subSchema = query[key]; 14936 return [key, createYValueFromSchema(subSchema, val)]; 14937 } 14938 ); 14939 return new yjs_exports.Map(entries); 14940 } 14941 function createNewYBlock(block) { 14942 return createYMap( 14943 Object.fromEntries( 14944 Object.entries(block).map(([key, value]) => { 14945 switch (key) { 14946 case "attributes": { 14947 return [ 14948 key, 14949 createNewYAttributeMap(block.name, value) 14950 ]; 14951 } 14952 case "innerBlocks": { 14953 const innerBlocks = new yjs_exports.Array(); 14954 if (!Array.isArray(value)) { 14955 return [key, innerBlocks]; 14956 } 14957 innerBlocks.insert( 14958 0, 14959 value.map( 14960 (innerBlock) => createNewYBlock(innerBlock) 14961 ) 14962 ); 14963 return [key, innerBlocks]; 14964 } 14965 default: 14966 return [key, value]; 14967 } 14968 }) 14969 ) 14970 ); 14971 } 14972 function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor, options = {}) { 14973 if (!serializableBlocksCache.has(incomingBlocks)) { 14974 serializableBlocksCache.set( 14975 incomingBlocks, 14976 makeBlocksSerializable(incomingBlocks) 14977 ); 14978 } 14979 const incomingBlocksToSync = serializableBlocksCache.get(incomingBlocks) ?? []; 14980 const numOfCommonEntries = Math.min( 14981 incomingBlocksToSync.length ?? 0, 14982 yblocks.length 14983 ); 14984 let left = 0; 14985 let right = 0; 14986 for (; left < numOfCommonEntries && areBlocksEqual(incomingBlocksToSync[left], yblocks.get(left)); left++) { 14987 } 14988 for (; right < numOfCommonEntries - left && areBlocksEqual( 14989 incomingBlocksToSync[incomingBlocksToSync.length - right - 1], 14990 yblocks.get(yblocks.length - right - 1) 14991 ); right++) { 14992 } 14993 const numOfUpdatesNeeded = numOfCommonEntries - left - right; 14994 const numOfInsertionsNeeded = Math.max( 14995 0, 14996 incomingBlocksToSync.length - yblocks.length 14997 ); 14998 const numOfDeletionsNeeded = Math.max( 14999 0, 15000 yblocks.length - incomingBlocksToSync.length 15001 ); 15002 for (let i = 0; i < numOfUpdatesNeeded; i++, left++) { 15003 const incomingYBlock = incomingBlocksToSync[left]; 15004 const localYBlock = yblocks.get(left);
15005 Object.entries(incomingYBlock).forEach( 15006 ([incomingBlockProperty, incomingBlockPropertyValue]) => { 15007 switch (incomingBlockProperty) { 15008 case "attributes": { 15009 const localAttributes = localYBlock.get( 15010 incomingBlockProperty 15011 ); 15012 const incomingAttributes = incomingBlockPropertyValue; 15013 if (!localAttributes) { 15014 localYBlock.set( 15015 incomingBlockProperty, 15016 createNewYAttributeMap( 15017 incomingYBlock.name, 15018 incomingAttributes 15019 ) 15020 ); 15021 break; 15022 } 15023 Object.entries(incomingAttributes).forEach( 15024 ([ 15025 incomingAttributeName, 15026 incomingAttributeValue 15027 ]) => { 15028 const currentAttribute = localAttributes?.get( 15029 incomingAttributeName 15030 ); 15031 const isExpectedType = isExpectedAttributeType( 15032 incomingYBlock.name, 15033 incomingAttributeName, 15034 currentAttribute 15035 ); 15036 const isYType = currentAttribute instanceof yjs_exports.AbstractType; 15037 const isAttributeChanged = !isExpectedType || isYType || !(0, import_es65.default)( 15038 currentAttribute, 15039 incomingAttributeValue 15040 ); 15041 if (isAttributeChanged) { 15042 updateYBlockAttribute( 15043 incomingYBlock.name, 15044 incomingYBlock.clientId, 15045 incomingAttributeName, 15046 incomingAttributeValue, 15047 localAttributes, 15048 attributeCursor 15049 ); 15050 } 15051 } 15052 ); 15053 localAttributes.forEach( 15054 (_attrValue, attrName) => { 15055 if (!incomingBlockPropertyValue.hasOwnProperty( 15056 attrName 15057 )) { 15058 localAttributes.delete(attrName); 15059 } 15060 } 15061 ); 15062 break; 15063 } 15064 case "innerBlocks": { 15065 let yInnerBlocks = localYBlock.get( 15066 incomingBlockProperty 15067 ); 15068 if (!(yInnerBlocks instanceof yjs_exports.Array)) { 15069 yInnerBlocks = new yjs_exports.Array(); 15070 localYBlock.set( 15071 incomingBlockProperty, 15072 yInnerBlocks 15073 ); 15074 } 15075 mergeCrdtBlocks( 15076 yInnerBlocks, 15077 incomingBlockPropertyValue ?? [], 15078 attributeCursor, 15079 options 15080 ); 15081 break; 15082 } 15083 case "clientId": { 15084 if (options.preserveClientIds) { 15085 break; 15086 } 15087 if (incomingBlockPropertyValue !== localYBlock.get(incomingBlockProperty)) { 15088 localYBlock.set( 15089 incomingBlockProperty, 15090 incomingBlockPropertyValue 15091 ); 15092 } 15093 break; 15094 } 15095 default: 15096 if (!(0, import_es65.default)( 15097 incomingYBlock[incomingBlockProperty], 15098 localYBlock.get(incomingBlockProperty) 15099 )) { 15100 localYBlock.set( 15101 incomingBlockProperty, 15102 incomingBlockPropertyValue 15103 ); 15104 } 15105 } 15106 } 15107 ); 15108 localYBlock.forEach((_v, k) => { 15109 if (!incomingYBlock.hasOwnProperty(k)) { 15110 localYBlock.delete(k); 15111 } 15112 }); 15113 } 15114 yblocks.delete(left, numOfDeletionsNeeded); 15115 for (let i = 0; i < numOfInsertionsNeeded; i++, left++) { 15116 const newBlock = [createNewYBlock(incomingBlocksToSync[left])]; 15117 yblocks.insert(left, newBlock); 15118 } 15119 const knownClientIds = /* @__PURE__ */ new Set(); 15120 for (let j = 0; j < yblocks.length; j++) { 15121 const yblock = yblocks.get(j); 15122 let clientId = yblock.get("clientId"); 15123 if (!clientId) { 15124 continue; 15125 } 15126 if (knownClientIds.has(clientId)) { 15127 clientId = v4_default(); 15128 yblock.set("clientId", clientId); 15129 } 15130 knownClientIds.add(clientId); 15131 } 15132 } 15133 function areArrayElementsEqual(newElement, yElement) { 15134 if (yElement instanceof yjs_exports.Map && isRecord(newElement)) { 15135 return (0, import_es65.default)(newElement, yElement.toJSON()); 15136 } 15137 return (0, import_es65.default)(newElement, yElement); 15138 } 15139 function mergeYArray(yArray, newValue, schema, cursorPosition, cursorScope) { 15140 if (!schema.query) { 15141 return; 15142 } 15143 const query = schema.query; 15144 const numOfCommonEntries = Math.min(newValue.length, yArray.length); 15145 let left = 0; 15146 let right = 0; 15147 for (; left < numOfCommonEntries && areArrayElementsEqual(newValue[left], yArray.get(left)); left++) { 15148 } 15149 for (; right < numOfCommonEntries - left && areArrayElementsEqual( 15150 newValue[newValue.length - right - 1], 15151 yArray.get(yArray.length - right - 1) 15152 ); right++) { 15153 } 15154 const numOfUpdatesNeeded = numOfCommonEntries - left - right; 15155 for (let i = 0; i < numOfUpdatesNeeded; i++) {
15156 const currentElement = yArray.get(left + i); 15157 const newElement = newValue[left + i]; 15158 if (currentElement instanceof yjs_exports.Map && isRecord(newElement)) { 15159 mergeYMapValues( 15160 currentElement, 15161 newElement, 15162 query, 15163 cursorPosition, 15164 cursorScope 15165 ); 15166 } else { 15167 yArray.delete(0, yArray.length); 15168 yArray.insert( 15169 0, 15170 newValue.map((item) => createYMapFromQuery(query, item)) 15171 ); 15172 return; 15173 } 15174 } 15175 const numOfDeletionsNeeded = Math.max(0, yArray.length - newValue.length); 15176 if (numOfDeletionsNeeded > 0) { 15177 yArray.delete(left + numOfUpdatesNeeded, numOfDeletionsNeeded); 15178 } 15179 const numOfInsertionsNeeded = Math.max( 15180 0, 15181 newValue.length - yArray.length 15182 ); 15183 if (numOfInsertionsNeeded > 0) { 15184 const insertAt = left + numOfUpdatesNeeded; 15185 const itemsToInsert = new Array( 15186 numOfInsertionsNeeded 15187 ); 15188 for (let i = 0; i < numOfInsertionsNeeded; i++) { 15189 itemsToInsert[i] = createYMapFromQuery( 15190 query, 15191 newValue[insertAt + i] 15192 ); 15193 } 15194 yArray.insert(insertAt, itemsToInsert); 15195 } 15196 } 15197 function mergeYValue(schema, newVal, yMap, key, cursorPosition, cursorScope) { 15198 const currentVal = yMap.get(key); 15199 if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof yjs_exports.Text) { 15200 mergeRichTextUpdate( 15201 currentVal, 15202 newVal, 15203 resolveRichTextCursorPosition(cursorPosition, cursorScope, newVal) 15204 ); 15205 } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof yjs_exports.Array) { 15206 mergeYArray(currentVal, newVal, schema, cursorPosition, cursorScope); 15207 } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof yjs_exports.Map) { 15208 mergeYMapValues( 15209 currentVal, 15210 newVal, 15211 schema.query, 15212 cursorPosition, 15213 cursorScope 15214 ); 15215 } else { 15216 const newYValue = createYValueFromSchema(schema, newVal); 15217 if (newYValue !== newVal || !(0, import_es65.default)(currentVal, newVal)) { 15218 yMap.set(key, newYValue); 15219 } 15220 } 15221 } 15222 function mergeYMapValues(yMap, newObj, query, cursorPosition, cursorScope) { 15223 for (const [key, newVal] of Object.entries(newObj)) { 15224 mergeYValue( 15225 query[key], 15226 newVal, 15227 yMap, 15228 key, 15229 cursorPosition, 15230 cursorScope 15231 ); 15232 } 15233 for (const key of yMap.keys()) { 15234 if (!Object.hasOwn(newObj, key)) { 15235 yMap.delete(key); 15236 } 15237 } 15238 } 15239 function updateYBlockAttribute(blockName, clientId, attributeName, attributeValue, currentAttributes, newCursorPosition) { 15240 const schema = getBlockAttributeSchema(blockName, attributeName); 15241 mergeYValue( 15242 schema, 15243 attributeValue, 15244 currentAttributes, 15245 attributeName, 15246 newCursorPosition, 15247 { attributeKey: attributeName, clientId } 15248 ); 15249 } 15250 function resolveRichTextCursorPosition(cursorPosition, cursorScope, updatedValue) { 15251 return cursorPosition && cursorPosition.clientId === cursorScope.clientId && cursorPosition.attributeKey === cursorScope.attributeKey && "number" === typeof cursorPosition.offset && Number.isInteger(cursorPosition.offset) ? richTextOffsetToHtmlIndex( 15252 updatedValue, 15253 asRichTextOffset(cursorPosition.offset) 15254 ) : null; 15255 } 15256 var cachedBlockAttributeSchemas; 15257 function getBlockAttributeSchema(blockName, attributeName) { 15258 if (!cachedBlockAttributeSchemas) { 15259 cachedBlockAttributeSchemas = /* @__PURE__ */ new Map(); 15260 for (const blockType of (0, import_blocks.getBlockTypes)()) { 15261 cachedBlockAttributeSchemas.set( 15262 blockType.name, 15263 new Map( 15264 Object.entries(blockType.attributes ?? {}).map( 15265 ([name, definition]) => { 15266 const { role, type, query } = definition; 15267 return [name, { role, type, query }]; 15268 } 15269 ) 15270 ) 15271 ); 15272 } 15273 } 15274 return cachedBlockAttributeSchemas.get(blockName)?.get(attributeName); 15275 } 15276 function isExpectedAttributeType(blockName, attributeName, attributeValue) { 15277 const schema = getBlockAttributeSchema(blockName, attributeName); 15278 if (schema?.type === "rich-text") { 15279 return attributeValue instanceof yjs_exports.Text; 15280 } 15281 if (schema?.type === "string") { 15282 return typeof attributeValue === "string"; 15283 } 15284 if (schema?.type === "array" && schema.query) { 15285 return attributeValue instanceof yjs_exports.Array; 15286 } 15287 if (schema?.type === "object" && schema.query) { 15288 return attributeValue instanceof yjs_exports.Map; 15289 } 15290 return true; 15291 } 15292 function isLocalAttribute(blockName, attributeName) { 15293 return "local" === getBlockAttributeSchema(blockName, attributeName)?.role; 15294 } 15295 var localDoc; 15296 function mergeRichTextUpdate(blockYText, updatedValue, htmlCursorIndex = null) { 15297 const currentValueAsDelta = new Delta2(blockYText.toDelta()); 15298 const updatedValueAsDelta = new Delta2([{ insert: updatedValue }]); 15299 const deltaDiff = currentValueAsDelta.diffWithCursor( 15300 updatedValueAsDelta, 15301 htmlCursorIndex 15302 ); 15303 const safeDiff = htmlCursorIndex === null || isDeltaVerificationMatch(blockYText, deltaDiff, updatedValue) ? deltaDiff : currentValueAsDelta.diff(updatedValueAsDelta); 15304 blockYText.applyDelta(safeDiff.ops); 15305 } 15306 function isDeltaVerificationMatch(blockYText, delta, expectedValue) { 15307 if (!localDoc) { 15308 localDoc = new yjs_exports.Doc(); 15309 } 15310 const verificationYText = localDoc.getText("verification-text"); 15311 verificationYText.delete(0, verificationYText.length); 15312 verificationYText.insert(0, blockYText.toString()); 15313 verificationYText.applyDelta(delta.ops); 15314 return verificationYText.toString() === expectedValue; 15315 } 15316 15317
15317// packages/core-data/build-module/utils/crdt-selection.mjs 15318 var import_data5 = __toESM(require_data(), 1); 15319 var import_block_editor4 = __toESM(require_block_editor(), 1); 15320 var import_blocks2 = __toESM(require_blocks(), 1); 15321 15322
15322// packages/core-data/build-module/utils/block-selection-history.mjs 15323 var SELECTION_HISTORY_DEFAULT_SIZE = 5; 15324 var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => { 15325 YSelectionType2["RelativeSelection"] = "RelativeSelection"; 15326 YSelectionType2["BlockSelection"] = "BlockSelection"; 15327 return YSelectionType2; 15328 })(YSelectionType || {}); 15329 function createBlockSelectionHistory(ydoc, historySize = SELECTION_HISTORY_DEFAULT_SIZE) { 15330 let history = []; 15331 const getSelectionHistory2 = () => { 15332 return history.slice(0); 15333 }; 15334 const updateSelection = (newSelection) => { 15335 if (!newSelection?.selectionStart?.clientId || !newSelection?.selectionEnd?.clientId) { 15336 return; 15337 } 15338 const { selectionStart, selectionEnd } = newSelection; 15339 const start = convertWPBlockSelectionToSelection( 15340 selectionStart, 15341 ydoc 15342 ); 15343 const end = convertWPBlockSelectionToSelection(selectionEnd, ydoc); 15344 addToHistory({ start, end }); 15345 }; 15346 const addToHistory = (yFullSelection) => { 15347 const startClientId = yFullSelection.start.clientId; 15348 const endClientId = yFullSelection.end.clientId; 15349 history = history.filter((entry) => { 15350 const isSameBlockCombination = entry.start.clientId === startClientId && entry.end.clientId === endClientId; 15351 return !isSameBlockCombination; 15352 }); 15353 history.unshift(yFullSelection); 15354 if (history.length > historySize + 1) { 15355 history = history.slice(0, historySize + 1); 15356 } 15357 }; 15358 return { 15359 getSelectionHistory: getSelectionHistory2, 15360 updateSelection 15361 }; 15362 } 15363 function convertWPBlockSelectionToSelection(selection, ydoc) { 15364 const clientId = selection.clientId; 15365 const block = findBlockByClientIdInDoc(clientId, ydoc); 15366 const attributes = block?.get("attributes"); 15367 const attributeKey = selection.attributeKey; 15368 let changedYText = null; 15369 if (attributeKey && attributes) { 15370 changedYText = getYTextByAttributeKey(attributes, attributeKey); 15371 } 15372 if (!(changedYText instanceof yjs_exports.Text) || !attributeKey || !clientId) { 15373 return { 15374 type: "BlockSelection", 15375 clientId 15376 }; 15377 } 15378 const offset = selection.offset ?? 0; 15379 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex( 15380 changedYText, 15381 richTextOffsetToHtmlIndex( 15382 changedYText.toString(), 15383 asRichTextOffset(offset) 15384 ) 15385 ); 15386 return { 15387 type: "RelativeSelection", 15388 attributeKey, 15389 relativePosition, 15390 clientId, 15391 offset 15392 }; 15393 } 15394 15395
15395// packages/core-data/build-module/utils/crdt-selection.mjs 15396 var selectionHistoryMap = /* @__PURE__ */ new WeakMap(); 15397 function getBlockSelectionHistory(ydoc) { 15398 let history = selectionHistoryMap.get(ydoc); 15399 if (!history) { 15400 history = createBlockSelectionHistory(ydoc); 15401 selectionHistoryMap.set(ydoc, history); 15402 } 15403 return history; 15404 } 15405 function getSelectionHistory(ydoc) { 15406 return getBlockSelectionHistory(ydoc).getSelectionHistory(); 15407 } 15408 function updateSelectionHistory(ydoc, wpSelection) { 15409 return getBlockSelectionHistory(ydoc).updateSelection(wpSelection); 15410 } 15411 function convertYSelectionToBlockSelection(ySelection, ydoc) { 15412 if (ySelection.type === YSelectionType.RelativeSelection) { 15413 const { relativePosition, attributeKey, clientId } = ySelection; 15414 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition( 15415 relativePosition, 15416 ydoc 15417 ); 15418 if (absolutePosition) { 15419 return { 15420 clientId, 15421 attributeKey, 15422 offset: htmlIndexToRichTextOffset( 15423 absolutePosition.type.toString(), 15424 asHtmlStringIndex(absolutePosition.index) 15425 ) 15426 }; 15427 } 15428 } else if (ySelection.type === YSelectionType.BlockSelection) { 15429 return { 15430 clientId: ySelection.clientId, 15431 attributeKey: void 0, 15432 offset: void 0 15433 }; 15434 } 15435 return null; 15436 } 15437 function convertYFullSelectionToWPSelection(yFullSelection, ydoc) { 15438 const { start, end } = yFullSelection; 15439 const startBlock = findBlockByClientIdInDoc(start.clientId, ydoc); 15440 const endBlock = findBlockByClientIdInDoc(end.clientId, ydoc); 15441 if (!startBlock || !endBlock) { 15442 return null; 15443 } 15444 const startBlockSelection = convertYSelectionToBlockSelection( 15445 start, 15446 ydoc 15447 ); 15448 const endBlockSelection = convertYSelectionToBlockSelection(end, ydoc); 15449 if (startBlockSelection === null || endBlockSelection === null) { 15450 return null; 15451 } 15452 return { 15453 selectionStart: startBlockSelection, 15454 selectionEnd: endBlockSelection 15455 }; 15456 } 15457 function findSelectionFromHistory(ydoc, selectionHistory) { 15458 for (const positionToTry of selectionHistory) { 15459 const result = convertYFullSelectionToWPSelection( 15460 positionToTry, 15461 ydoc 15462 ); 15463 if (result !== null) { 15464 return result; 15465 } 15466 } 15467 return null; 15468 } 15469 function restoreSelection(selectionHistory, ydoc) { 15470 const selectionToRestore = findSelectionFromHistory( 15471 ydoc, 15472 selectionHistory 15473 ); 15474 if (selectionToRestore === null) { 15475 return; 15476 } 15477 const { getBlock } = (0, import_data5.select)(import_block_editor4.store); 15478 const { resetSelection } = (0, import_data5.dispatch)(import_block_editor4.store); 15479 const { selectionStart, selectionEnd } = selectionToRestore; 15480 const isSelectionInSameBlock = selectionStart.clientId === selectionEnd.clientId; 15481 if (isSelectionInSameBlock) { 15482 const block = getBlock(selectionStart.clientId); 15483 const isBlockEmpty = block && (0, import_blocks2.isUnmodifiedBlock)(block); 15484 const isBeginningOfEmptyBlock = 0 === selectionStart.offset && 0 === selectionEnd.offset && isBlockEmpty && !selectionStart.attributeKey && !selectionEnd.attributeKey; 15485 if (isBeginningOfEmptyBlock) { 15486 const selectionStartWithoutOffset = { 15487 clientId: selectionStart.clientId 15488 }; 15489 const selectionEndWithoutOffset = { 15490 clientId: selectionEnd.clientId 15491 }; 15492 resetSelection( 15493 selectionStartWithoutOffset, 15494 selectionEndWithoutOffset, 15495 0 15496 ); 15497 } else { 15498 resetSelection(selectionStart, selectionEnd, 0); 15499 } 15500 } else { 15501 resetSelection(selectionEnd, selectionEnd, 0); 15502 } 15503 } 15504 function getShiftedSelection(ydoc, selectionHistory) { 15505 if (selectionHistory.length === 0) { 15506 return null; 15507 } 15508 const { start, end } = selectionHistory[0]; 15509 if (start.type === YSelectionType.BlockSelection || end.type === YSelectionType.BlockSelection) { 15510 return null; 15511 } 15512 const selectionStart = convertYSelectionToBlockSelection(start, ydoc); 15513 const selectionEnd = convertYSelectionToBlockSelection(end, ydoc); 15514 if (!selectionStart || !selectionEnd) { 15515 return null; 15516 } 15517 const startShifted = selectionStart.offset !== start.offset; 15518 const endShifted = selectionEnd.offset !== end.offset; 15519 if (!startShifted && !endShifted) { 15520 return null; 15521 } 15522 return { selectionStart, selectionEnd }; 15523 } 15524 15525
15525// packages/core-data/build-module/utils/crdt.mjs 15526 var POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document"; 15527 var disallowedPostMetaKeys = /* @__PURE__ */ new Set([ 15528 POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE 15529 ]); 15530 function defaultApplyChangesToCRDTDoc(ydoc, changes) { 15531 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2); 15532 Object.entries(changes).forEach(([key, newValue]) => { 15533 if ("function" === typeof newValue) { 15534 return; 15535 } 15536 switch (key) { 15537 // Add support for additional data types here. 15538 default: { 15539 const currentValue = ymap.get(key); 15540 updateMapValue(ymap, key, currentValue, newValue); 15541 } 15542 } 15543 }); 15544 } 15545 function applyPostChangesToCRDTDoc(ydoc, changes, syncedProperties) { 15546 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2); 15547 Object.keys(changes).forEach((key) => { 15548 if (!syncedProperties.has(key)) { 15549 return; 15550 } 15551 const newValue = changes[key]; 15552 if ("function" === typeof newValue) { 15553 return; 15554 } 15555 switch (key) { 15556 case "blocks": { 15557 const newCursorPosition = parseCursorSelection( 15558 changes.selection 15559 ); 15560 const rawContent = getRawValue(changes.content); 15561 if (!newValue && typeof rawContent === "string") { 15562 mergeContentWithoutBlocks( 15563 ymap, 15564 rawContent, 15565 newCursorPosition 15566 ); 15567 break; 15568 } else if (!newValue) { 15569 ymap.set(key, void 0); 15570 break; 15571 } 15572 let currentBlocks = ymap.get(key); 15573 if (!(currentBlocks instanceof yjs_exports.Array)) { 15574 currentBlocks = new yjs_exports.Array(); 15575 ymap.set(key, currentBlocks); 15576 } 15577 mergeCrdtBlocks(currentBlocks, newValue, newCursorPosition); 15578 break; 15579 } 15580 case "content": 15581 case "excerpt": 15582 case "title": { 15583 const currentValue = ymap.get(key); 15584 let rawValue = getRawValue(newValue); 15585 if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) { 15586 rawValue = ""; 15587 } 15588 if (currentValue instanceof yjs_exports.Text) { 15589 mergeRichTextUpdate(currentValue, rawValue ?? ""); 15590 } else { 15591 const newYText = new yjs_exports.Text(rawValue ?? ""); 15592 ymap.set(key, newYText); 15593 } 15594 break; 15595 } 15596 // "Meta" is overloaded term; here, it refers to post meta. 15597 case "meta": { 15598 let metaMap = ymap.get("meta"); 15599 if (!isYMap(metaMap)) { 15600 metaMap = createYMap(); 15601 ymap.set("meta", metaMap); 15602 } 15603 Object.entries(newValue ?? {}).forEach( 15604 ([metaKey, metaValue]) => { 15605 if (disallowedPostMetaKeys.has(metaKey)) { 15606 return; 15607 } 15608 updateMapValue( 15609 metaMap, 15610 metaKey, 15611 metaMap.get(metaKey), 15612 // current value in CRDT 15613 metaValue 15614 // new value from changes 15615 ); 15616 } 15617 ); 15618 break; 15619 } 15620 case "slug": { 15621 if (!newValue) { 15622 break; 15623 } 15624 const currentValue = ymap.get(key); 15625 updateMapValue(ymap, key, currentValue, newValue); 15626 break; 15627 } 15628 // Add support for additional properties here. 15629 default: { 15630 const currentValue = ymap.get(key); 15631 updateMapValue(ymap, key, currentValue, newValue); 15632 } 15633 } 15634 }); 15635 if (changes.selection) { 15636 const selection = changes.selection; 15637 setTimeout(() => { 15638 updateSelectionHistory(ydoc, selection); 15639 }, 0); 15640 } 15641 } 15642 function mergeContentWithoutBlocks(ymap, rawContent, cursorPosition) {
15643 let currentBlocks = ymap.get("blocks"); 15644 if (!(currentBlocks instanceof yjs_exports.Array)) { 15645 currentBlocks = new yjs_exports.Array(); 15646 ymap.set("blocks", currentBlocks); 15647 } 15648 mergeCrdtBlocks( 15649 currentBlocks, 15650 (0, import_blocks3.parse)(rawContent), 15651 cursorPosition, 15652 { preserveClientIds: true } 15653 ); 15654 } 15655 function parseCursorSelection(selection) { 15656 const selectionStart = selection?.selectionStart; 15657 return selectionStart?.clientId && selectionStart.attributeKey && "number" === typeof selectionStart.offset && Number.isInteger(selectionStart.offset) ? { 15658 attributeKey: selectionStart.attributeKey, 15659 clientId: selectionStart.clientId, 15660 offset: asRichTextOffset(selectionStart.offset) 15661 } : null; 15662 } 15663 function defaultGetChangesFromCRDTDoc(crdtDoc, editedRecord) { 15664 const docRecord = getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY2).toJSON(); 15665 return Object.fromEntries( 15666 Object.entries(docRecord).filter( 15667 ([key, newValue]) => haveValuesChanged(editedRecord?.[key], newValue) 15668 ) 15669 ); 15670 } 15671 function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) { 15672 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2); 15673 let allowedMetaChanges = {}; 15674 const changes = Object.fromEntries( 15675 Object.entries(ymap.toJSON()).filter(([key, newValue]) => { 15676 if (!syncedProperties.has(key)) { 15677 return false; 15678 } 15679 const currentValue = editedRecord[key]; 15680 switch (key) { 15681 case "blocks": { 15682 if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY2) && editedRecord.content) { 15683 const blocksJson = ymap.get("blocks")?.toJSON() ?? []; 15684 return (0, import_blocks3.__unstableSerializeAndClean)(blocksJson).trim() !== getRawValue(editedRecord.content); 15685 } 15686 return true; 15687 } 15688 case "date": { 15689 const currentDateIsFloating = null === currentValue || editedRecord.modified === currentValue; 15690 if (currentDateIsFloating) { 15691 return false; 15692 } 15693 return haveValuesChanged(currentValue, newValue); 15694 } 15695 case "meta": { 15696 const currentMeta = currentValue ?? {}; 15697 allowedMetaChanges = Object.fromEntries( 15698 Object.entries(newValue ?? {}).filter( 15699 ([metaKey]) => { 15700 if (disallowedPostMetaKeys.has(metaKey)) { 15701 return false; 15702 } 15703 return metaKey in currentMeta; 15704 } 15705 ) 15706 ); 15707 const mergedValue = { 15708 ...currentMeta, 15709 ...allowedMetaChanges 15710 }; 15711 return haveValuesChanged(currentValue, mergedValue); 15712 } 15713 case "status": { 15714 if ("auto-draft" === newValue) { 15715 return false; 15716 } 15717 return haveValuesChanged(currentValue, newValue); 15718 } 15719 case "content": 15720 case "excerpt": 15721 case "title": { 15722 return haveValuesChanged( 15723 getRawValue(currentValue), 15724 newValue 15725 ); 15726 } 15727 // Add support for additional data types here. 15728 default: { 15729 return haveValuesChanged(currentValue, newValue); 15730 } 15731 } 15732 }) 15733 ); 15734 if (changes.blocks) { 15735 changes.blocks = deserializeBlockAttributes( 15736 changes.blocks 15737 ); 15738 } 15739 if (changes.blocks && !changes.content) { 15740 const capturedBlocks = changes.blocks; 15741 changes.content = () => (0, import_blocks3.__unstableSerializeAndClean)(capturedBlocks); 15742 } 15743 if ("object" === typeof changes.meta) { 15744 changes.meta = { 15745 ...editedRecord.meta, 15746 ...allowedMetaChanges 15747 }; 15748 } 15749 const selectionHistory = getSelectionHistory(ydoc); 15750 const shiftedSelection = getShiftedSelection(ydoc, selectionHistory); 15751 if (shiftedSelection) { 15752 changes.selection = { 15753 ...shiftedSelection, 15754 initialPosition: 0 15755 }; 15756 } 15757 return changes; 15758 } 15759 var defaultSyncConfig = { 15760 applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc, 15761 createAwareness: (ydoc) => new BaseAwareness(ydoc), 15762 getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc 15763 }; 15764 var defaultCollectionSyncConfig = { 15765 applyChangesToCRDTDoc: () => { 15766 }, 15767 getChangesFromCRDTDoc: () => ({}), 15768 shouldSync: (_, objectId) => null === objectId 15769 }; 15770 function getRawValue(value) { 15771 if ("string" === typeof value) { 15772 return value; 15773 } 15774 if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) { 15775 return value.raw; 15776 } 15777 return void 0; 15778 } 15779 function haveValuesChanged(currentValue, newValue) { 15780 return !(0, import_es66.default)(currentValue, newValue); 15781 } 15782 function updateMapValue(map2, key, currentValue, newValue) { 15783 if (void 0 === newValue) { 15784 map2.delete(key); 15785 return; 15786 } 15787 if (haveValuesChanged(currentValue, newValue)) { 15788 map2.set(key, newValue); 15789 } 15790 } 15791 15792
15792// packages/core-data/build-module/entities.mjs 15793 var DEFAULT_ENTITY_KEY = "id"; 15794 var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"]; 15795 var blocksTransientEdits = { 15796 blocks: { 15797 read: (record) => (0, import_blocks4.parse)(record.content?.raw ?? ""), 15798 write: (record) => ({ 15799 content: (0, import_blocks4.__unstableSerializeAndClean)(record.blocks) 15800 }) 15801 } 15802 }; 15803 var rootEntitiesConfig = [ 15804 { 15805 label: (0, import_i18n.__)("Base"), 15806 kind: "root", 15807 key: false, 15808 name: "__unstableBase", 15809 baseURL: "/", 15810 baseURLParams: { 15811 // Please also change the preload path when changing this. 15812 // @see lib/compat/wordpress-7.1/preload.php 15813 _fields: [ 15814 "description", 15815 "gmt_offset", 15816 "home", 15817 "image_max_bit_depth", 15818 "image_sizes", 15819 "image_size_threshold", 15820 "image_strip_meta", 15821 "name", 15822 "site_icon", 15823 "site_icon_url", 15824 "site_logo", 15825 "timezone_string", 15826 "url", 15827 "page_for_posts", 15828 "page_on_front", 15829 "show_on_front" 15830 ].join(",") 15831 }, 15832 // The entity doesn't support selecting multiple records. 15833 // The property is maintained for backward compatibility. 15834 plural: "__unstableBases", 15835 supportsPagination: false 15836 }, 15837 { 15838 label: (0, import_i18n.__)("Post Type"), 15839 name: "postType", 15840 kind: "root", 15841 key: "slug", 15842 baseURL: "/wp/v2/types", 15843 baseURLParams: { context: "edit" }, 15844 plural: "postTypes", 15845 supportsPagination: false 15846 }, 15847 { 15848 name: "media", 15849 kind: "root", 15850 baseURL: "/wp/v2/media", 15851 baseURLParams: { context: "edit" }, 15852 plural: "mediaItems", 15853 label: (0, import_i18n.__)("Media"), 15854 rawAttributes: ["caption", "title", "description"], 15855 supportsPagination: true 15856 }, 15857 { 15858 name: "taxonomy", 15859 kind: "root", 15860 key: "slug", 15861 baseURL: "/wp/v2/taxonomies", 15862 baseURLParams: { context: "edit" }, 15863 plural: "taxonomies", 15864 label: (0, import_i18n.__)("Taxonomy"), 15865 supportsPagination: false 15866 }, 15867 { 15868 name: "sidebar", 15869 kind: "root", 15870 baseURL: "/wp/v2/sidebars", 15871 baseURLParams: { context: "edit" }, 15872 plural: "sidebars", 15873 transientEdits: { blocks: true }, 15874 label: (0, import_i18n.__)("Widget areas"), 15875 supportsPagination: false 15876 }, 15877 { 15878 name: "widget", 15879 kind: "root", 15880 baseURL: "/wp/v2/widgets", 15881 baseURLParams: { context: "edit" }, 15882 plural: "widgets", 15883 transientEdits: { blocks: true }, 15884 label: (0, import_i18n.__)("Widgets"), 15885 supportsPagination: false 15886 }, 15887 { 15888 name: "widgetType", 15889 kind: "root", 15890 baseURL: "/wp/v2/widget-types", 15891 baseURLParams: { context: "edit" }, 15892 plural: "widgetTypes", 15893 label: (0, import_i18n.__)("Widget types"), 15894 supportsPagination: false 15895 }, 15896 { 15897 label: (0, import_i18n.__)("User"), 15898 name: "user", 15899 kind: "root", 15900 baseURL: "/wp/v2/users", 15901 getTitle: (record) => record?.name || record?.slug, 15902 baseURLParams: { context: "edit" }, 15903 plural: "users", 15904 supportsPagination: true 15905 }, 15906 { 15907 name: "comment", 15908 kind: "root", 15909 baseURL: "/wp/v2/comments", 15910 baseURLParams: { context: "edit" }, 15911 plural: "comments", 15912 label: (0, import_i18n.__)("Comment"), 15913 supportsPagination: true, 15914 syncConfig: defaultCollectionSyncConfig 15915 }, 15916 { 15917 name: "menu", 15918 kind: "root", 15919 baseURL: "/wp/v2/menus", 15920 baseURLParams: { context: "edit" }, 15921 plural: "menus", 15922 label: (0, import_i18n.__)("Menu"), 15923 supportsPagination: true 15924 }, 15925 { 15926 name: "menuItem", 15927 kind: "root", 15928 baseURL: "/wp/v2/menu-items", 15929 baseURLParams: { context: "edit" }, 15930 plural: "menuItems", 15931 label: (0, import_i18n.__)("Menu Item"), 15932 rawAttributes: ["title"], 15933 supportsPagination: true 15934 }, 15935 { 15936 name: "menuLocation", 15937 kind: "root", 15938 baseURL: "/wp/v2/menu-locations", 15939 baseURLParams: { context: "edit" }, 15940 plural: "menuLocations", 15941 label: (0, import_i18n.__)("Menu Location"), 15942 key: "name", 15943 supportsPagination: false 15944 }, 15945 { 15946 label: (0, import_i18n.__)("Global Styles"), 15947 name: "globalStyles", 15948 kind: "root", 15949 baseURL: "/wp/v2/global-styles", 15950 baseURLParams: { context: "edit" }, 15951 plural: "globalStylesVariations", 15952 // Should be different from name. 15953 getTitle: () => (0, import_i18n.__)("Custom Styles"), 15954 getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`, 15955 supportsPagination: true 15956 }, 15957 { 15958 label: (0, import_i18n.__)("Themes"), 15959 name: "theme", 15960 kind: "root", 15961 baseURL: "/wp/v2/themes", 15962 baseURLParams: { context: "edit" }, 15963 plural: "themes", 15964 key: "stylesheet", 15965 supportsPagination: false 15966 }, 15967 { 15968 label: (0, import_i18n.__)("Plugins"), 15969 name: "plugin", 15970 kind: "root",
15971 baseURL: "/wp/v2/plugins", 15972 baseURLParams: { context: "edit" }, 15973 plural: "plugins", 15974 key: "plugin", 15975 supportsPagination: false 15976 }, 15977 { 15978 label: (0, import_i18n.__)("Status"), 15979 name: "status", 15980 kind: "root", 15981 baseURL: "/wp/v2/statuses", 15982 baseURLParams: { context: "edit" }, 15983 plural: "statuses", 15984 key: "slug", 15985 supportsPagination: false 15986 }, 15987 { 15988 label: (0, import_i18n.__)("Registered Templates"), 15989 name: "registeredTemplate", 15990 kind: "root", 15991 baseURL: "/wp/v2/registered-templates", 15992 key: "id", 15993 supportsPagination: false 15994 }, 15995 { 15996 label: (0, import_i18n.__)("Font Collections"), 15997 name: "fontCollection", 15998 kind: "root", 15999 baseURL: "/wp/v2/font-collections", 16000 baseURLParams: { context: "view" }, 16001 plural: "fontCollections", 16002 key: "slug", 16003 supportsPagination: true 16004 }, 16005 { 16006 label: (0, import_i18n.__)("Icons"), 16007 name: "icon", 16008 kind: "root", 16009 baseURL: "/wp/v2/icons", 16010 baseURLParams: { context: "view" }, 16011 plural: "icons", 16012 key: "name", 16013 supportsPagination: false 16014 }, 16015 { 16016 label: (0, import_i18n.__)("Icon Collections"), 16017 name: "iconCollection", 16018 kind: "root", 16019 baseURL: "/wp/v2/icon-collections", 16020 baseURLParams: { context: "view" }, 16021 plural: "iconCollections", 16022 key: "slug", 16023 supportsPagination: false 16024 } 16025 ]; 16026 var deprecatedEntities = { 16027 root: { 16028 media: { 16029 since: "6.9", 16030 alternative: { 16031 kind: "postType", 16032 name: "attachment" 16033 } 16034 } 16035 } 16036 }; 16037 var additionalEntityConfigLoaders = [ 16038 { kind: "postType", loadEntities: loadPostTypeEntities }, 16039 { kind: "taxonomy", loadEntities: loadTaxonomyEntities }, 16040 { 16041 kind: "root", 16042 name: "site", 16043 plural: "sites", 16044 loadEntities: loadSiteEntity 16045 } 16046 ]; 16047 var prePersistPostType = async (persistedRecord, edits, name, isTemplate) => { 16048 const newEdits = {}; 16049 if (!isTemplate && persistedRecord?.status === "auto-draft") { 16050 if (!edits.status && !newEdits.status) { 16051 newEdits.status = "draft"; 16052 } 16053 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) { 16054 newEdits.title = ""; 16055 } 16056 } 16057 if (persistedRecord) { 16058 const objectType = `postType/${name}`; 16059 const objectId = persistedRecord.id; 16060 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc( 16061 objectType, 16062 objectId 16063 ); 16064 if (serializedDoc) { 16065 newEdits.meta = { 16066 ...edits.meta, 16067 [POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializedDoc 16068 }; 16069 } 16070 } 16071 return newEdits; 16072 }; 16073 async function loadPostTypeEntities() { 16074 const postTypesPromise = (0, import_api_fetch3.default)({ path: "/wp/v2/types?context=view" }); 16075 const taxonomiesPromise = window._wpCollaborationEnabled ? (0, import_api_fetch3.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({}); 16076 const [postTypes, taxonomies] = await Promise.all([ 16077 postTypesPromise, 16078 taxonomiesPromise 16079 ]); 16080 return Object.entries(postTypes ?? {}).map(([name, postType]) => { 16081 const isTemplate = ["wp_template", "wp_template_part"].includes( 16082 name 16083 ); 16084 const namespace = postType?.rest_namespace ?? "wp/v2"; 16085 const syncedProperties = /* @__PURE__ */ new Set([ 16086 "author", 16087 "blocks", 16088 "content", 16089 "comment_status", 16090 "date", 16091 "excerpt", 16092 "featured_media", 16093 "format", 16094 "meta", 16095 "ping_status", 16096 "slug", 16097 "status", 16098 "sticky", 16099 "template", 16100 "title", 16101 ...postType.taxonomies?.map((taxonomy) => taxonomies?.[taxonomy]?.rest_base)?.filter(Boolean) ?? [] 16102 ]); 16103 const entity2 = { 16104 kind: "postType", 16105 baseURL: `/${namespace}/${postType.rest_base}`, 16106 baseURLParams: { context: "edit" }, 16107 name, 16108 label: postType.name, 16109 transientEdits: { 16110 ...blocksTransientEdits, 16111 selection: true 16112 }, 16113 mergedEdits: { meta: true }, 16114 rawAttributes: POST_RAW_ATTRIBUTES, 16115 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)), 16116 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate), 16117 __unstable_rest_base: postType.rest_base, 16118 supportsPagination: true, 16119 getRevisionsUrl: (parentId, revisionId) => `/${namespace}/${postType.rest_base}/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`, 16120 revisionKey: isTemplate && !window?.__experimentalTemplateActivate ? "wp_id" : DEFAULT_ENTITY_KEY 16121 };
16122 entity2.syncConfig = { 16123 // Save a CRDT document with this entity 16124 supportsPersistence: true, 16125 /** 16126 * Apply changes from the local editor to the local CRDT document so 16127 * that those changes can be synced to other peers (via the provider). 16128 * 16129 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc 16130 * @param {Partial< import('@wordpress/sync').ObjectData >} changes 16131 * @return {void} 16132 */ 16133 applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, syncedProperties), 16134 /** 16135 * Create the awareness instance for the entity's CRDT document. 16136 * 16137 * @param {import('@wordpress/sync').CRDTDoc} ydoc 16138 * @param {import('@wordpress/sync').ObjectID} objectId 16139 * @return {import('@wordpress/sync').Awareness} Awareness instance 16140 */ 16141 createAwareness: (ydoc, objectId) => { 16142 const kind = "postType"; 16143 const id2 = parseInt(objectId, 10); 16144 return new PostEditorAwareness(ydoc, kind, name, id2); 16145 }, 16146 /** 16147 * Extract changes from a CRDT document that can be used to update the 16148 * local editor state. 16149 * 16150 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc 16151 * @param {import('@wordpress/sync').ObjectData} editedRecord 16152 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record 16153 */ 16154 getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc( 16155 crdtDoc, 16156 editedRecord, 16157 syncedProperties 16158 ), 16159 /** 16160 * Extract changes from a CRDT document that can be used to update the 16161 * local editor state. 16162 * 16163 * @param {import('@wordpress/sync').ObjectData} record 16164 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record 16165 */ 16166 getPersistedCRDTDoc: (record) => { 16167 return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null; 16168 }, 16169 shouldSync: () => !(Array.isArray(window._wpCollaborationDisabledPostTypes) && window._wpCollaborationDisabledPostTypes.includes(name)) 16170 }; 16171 return entity2; 16172 }); 16173 } 16174 async function loadTaxonomyEntities() { 16175 const taxonomies = await (0, import_api_fetch3.default)({ 16176 path: "/wp/v2/taxonomies?context=view" 16177 }); 16178 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => { 16179 const namespace = taxonomy?.rest_namespace ?? "wp/v2"; 16180 const entity2 = { 16181 kind: "taxonomy", 16182 baseURL: `/${namespace}/${taxonomy.rest_base}`, 16183 baseURLParams: { context: "edit" }, 16184 name, 16185 label: taxonomy.name, 16186 getTitle: (record) => record?.name, 16187 supportsPagination: true 16188 }; 16189 entity2.syncConfig = defaultSyncConfig; 16190 return entity2; 16191 }); 16192 } 16193 async function loadSiteEntity() { 16194 const entity2 = { 16195 label: (0, import_i18n.__)("Site"), 16196 name: "site", 16197 kind: "root", 16198 key: false, 16199 baseURL: "/wp/v2/settings", 16200 supportsPagination: false, 16201 meta: {} 16202 }; 16203 const site = await (0, import_api_fetch3.default)({ 16204 path: entity2.baseURL, 16205 method: "OPTIONS" 16206 }); 16207 const labels = {}; 16208 Object.entries(site?.schema?.properties ?? {}).forEach( 16209 ([key, value]) => { 16210 if (typeof value === "object" && value.title) { 16211 labels[key] = value.title; 16212 } 16213 } 16214 ); 16215 return [{ ...entity2, meta: { labels } }]; 16216 } 16217 var getMethodName = (kind, name, prefix = "get") => { 16218 const kindPrefix = kind === "root" ? "" : pascalCase(kind); 16219 const suffix = pascalCase(name); 16220 return `${prefix}${kindPrefix}${suffix}`; 16221 }; 16222 16223
16223// packages/core-data/build-module/queried-data/reducer.mjs 16224 function getContextFromAction(action) { 16225 const { query } = action; 16226 if (!query) { 16227 return "default"; 16228 } 16229 const queryParts = get_query_parts_default(query); 16230 return queryParts.context; 16231 } 16232 function getMergedItemIds(itemIds = [], nextItemIds, { page = 1, offset, perPage = 10 } = {}) { 16233 if (perPage === -1) { 16234 return nextItemIds; 16235 } 16236 const nextItemIdsStartIndex = offset ?? (page - 1) * perPage; 16237 const nextItemIdsRange = Math.max(perPage, nextItemIds.length); 16238 const size2 = Math.max( 16239 itemIds.length, 16240 nextItemIdsStartIndex + nextItemIds.length 16241 ); 16242 const mergedItemIds = new Array(size2); 16243 for (let i = 0; i < size2; i++) { 16244 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIdsRange; 16245 if (isInNextItemsRange) { 16246 mergedItemIds[i] = nextItemIds[i - nextItemIdsStartIndex]; 16247 } else { 16248 mergedItemIds[i] = itemIds[i]; 16249 } 16250 } 16251 return mergedItemIds; 16252 } 16253 function removeEntitiesById(entities2, ids) { 16254 return Object.fromEntries( 16255 Object.entries(entities2).filter( 16256 ([id2]) => !ids.some((itemId) => { 16257 if (Number.isInteger(itemId)) { 16258 return itemId === +id2; 16259 } 16260 return itemId === id2; 16261 }) 16262 ) 16263 ); 16264 } 16265 function items(state = {}, action) { 16266 switch (action.type) { 16267 case "RECEIVE_ITEMS": { 16268 const context = getContextFromAction(action); 16269 const key = action.key || DEFAULT_ENTITY_KEY; 16270 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16271 return { 16272 ...state, 16273 [context]: { 16274 ...state[context], 16275 ...Object.fromEntries( 16276 itemsList.map((item) => [ 16277 item?.[key], 16278 conservativeMapItem( 16279 state?.[context]?.[item?.[key]], 16280 item 16281 ) 16282 ]) 16283 ) 16284 } 16285 }; 16286 } 16287 case "REMOVE_ITEMS": 16288 return Object.fromEntries( 16289 Object.entries(state).map(([itemId, contextState]) => [ 16290 itemId, 16291 removeEntitiesById(contextState, action.itemIds) 16292 ]) 16293 ); 16294 } 16295 return state; 16296 } 16297 function itemIsComplete(state = {}, action) { 16298 switch (action.type) { 16299 case "RECEIVE_ITEMS": { 16300 const context = getContextFromAction(action); 16301 const { query, key = DEFAULT_ENTITY_KEY } = action; 16302 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16303 const queryParts = query ? get_query_parts_default(query) : {}; 16304 const isCompleteQuery = !query || !Array.isArray(queryParts.fields); 16305 return { 16306 ...state, 16307 [context]: { 16308 ...state[context], 16309 ...itemsList.reduce((result, item) => { 16310 const itemId = item?.[key]; 16311 result[itemId] = state?.[context]?.[itemId] || isCompleteQuery; 16312 return result; 16313 }, {}) 16314 } 16315 }; 16316 } 16317 case "REMOVE_ITEMS": 16318 return Object.fromEntries( 16319 Object.entries(state).map(([itemId, contextState]) => [ 16320 itemId, 16321 removeEntitiesById(contextState, action.itemIds) 16322 ]) 16323 ); 16324 } 16325 return state; 16326 } 16327 var receiveQueries = (0, import_compose.compose)([ 16328 // Limit to matching action type so we don't attempt to replace action on 16329 // an unhandled action. 16330 if_matching_action_default((action) => "query" in action), 16331 // Inject query parts into action for use both in `keyedReducer` and reducer. 16332 replace_action_default((action) => { 16333 if (action.query) { 16334 return { 16335 ...action, 16336 ...get_query_parts_default(action.query) 16337 }; 16338 } 16339 return action; 16340 }), 16341 (0, import_data6.keyedReducer)("context"), 16342 // Queries shape is shared, but keyed by query `stableKey` part. Original 16343 // reducer tracks only a single query object. 16344 (0, import_data6.keyedReducer)("stableKey") 16345 ])((state = {}, action) => { 16346 if (action.type !== "RECEIVE_ITEMS") { 16347 return state; 16348 } 16349 if (!Array.isArray(action.items)) { 16350 return state; 16351 }
16352 const key = action.key ?? DEFAULT_ENTITY_KEY; 16353 return { 16354 itemIds: getMergedItemIds( 16355 state.itemIds, 16356 action.items.map((item) => item?.[key]).filter(Boolean), 16357 { 16358 page: action.page, 16359 offset: action.offset, 16360 perPage: action.perPage 16361 } 16362 ), 16363 meta: action.meta 16364 }; 16365 }); 16366 var queries = (state = {}, action) => { 16367 switch (action.type) { 16368 case "RECEIVE_ITEMS": 16369 return receiveQueries(state, action); 16370 case "REMOVE_ITEMS": 16371 const removedItems = action.itemIds.reduce((result, itemId) => { 16372 result[itemId] = true; 16373 return result; 16374 }, {}); 16375 return Object.fromEntries( 16376 Object.entries(state).map( 16377 ([queryGroup, contextQueries]) => [ 16378 queryGroup, 16379 Object.fromEntries( 16380 Object.entries(contextQueries).map( 16381 ([query, queryItems]) => [ 16382 query, 16383 { 16384 ...queryItems, 16385 itemIds: queryItems.itemIds.filter( 16386 (queryId) => !removedItems[queryId] 16387 ) 16388 } 16389 ] 16390 ) 16391 ) 16392 ] 16393 ) 16394 ); 16395 default: 16396 return state; 16397 } 16398 }; 16399 var reducer_default = (0, import_data6.combineReducers)({ 16400 items, 16401 itemIsComplete, 16402 queries 16403 }); 16404 16405
16405// packages/core-data/build-module/reducer.mjs 16406 function users(state = { byId: {}, queries: {} }, action) { 16407 switch (action.type) { 16408 case "RECEIVE_USER_QUERY": 16409 return { 16410 byId: { 16411 ...state.byId, 16412 // Key users by their ID. 16413 ...action.users.reduce( 16414 (newUsers, user) => ({ 16415 ...newUsers, 16416 [user.id]: user 16417 }), 16418 {} 16419 ) 16420 }, 16421 queries: { 16422 ...state.queries, 16423 [action.queryID]: action.users.map((user) => user.id) 16424 } 16425 }; 16426 } 16427 return state; 16428 } 16429 function currentUser(state = {}, action) { 16430 switch (action.type) { 16431 case "RECEIVE_CURRENT_USER": 16432 return action.currentUser; 16433 } 16434 return state; 16435 } 16436 function currentTheme(state = void 0, action) { 16437 switch (action.type) { 16438 case "RECEIVE_CURRENT_THEME": 16439 return action.currentTheme.stylesheet; 16440 } 16441 return state; 16442 } 16443 function currentGlobalStylesId(state = void 0, action) { 16444 switch (action.type) { 16445 case "RECEIVE_CURRENT_GLOBAL_STYLES_ID": 16446 return action.id; 16447 } 16448 return state; 16449 } 16450 function themeBaseGlobalStyles(state = {}, action) { 16451 switch (action.type) { 16452 case "RECEIVE_THEME_GLOBAL_STYLES": 16453 return { 16454 ...state, 16455 [action.stylesheet]: action.globalStyles 16456 }; 16457 } 16458 return state; 16459 } 16460 function themeGlobalStyleVariations(state = {}, action) { 16461 switch (action.type) { 16462 case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS": 16463 return { 16464 ...state, 16465 [action.stylesheet]: action.variations 16466 }; 16467 } 16468 return state; 16469 } 16470 var withMultiEntityRecordEdits = (reducer) => (state, action) => { 16471 if (action.type === "UNDO" || action.type === "REDO") { 16472 const { record } = action; 16473 let newState = state; 16474 record.forEach(({ id: { kind, name, recordId }, changes }) => { 16475 const persistedRecord = state?.queriedData?.items?.default?.[recordId]; 16476 const edits = Object.fromEntries( 16477 Object.entries(changes).map(([key, value]) => [ 16478 key, 16479 action.type === "UNDO" ? value.from : value.to 16480 ]) 16481 ); 16482 newState = reducer(newState, { 16483 type: "EDIT_ENTITY_RECORD", 16484 kind, 16485 name, 16486 recordId, 16487 // Clear edits matching the persisted record so the entity is 16488 // no longer dirty after undoing back to its saved state. 16489 edits: clearUnchangedEdits(edits, persistedRecord) 16490 }); 16491 }); 16492 return newState; 16493 } 16494 return reducer(state, action); 16495 }; 16496 function entity(entityConfig) { 16497 return (0, import_compose2.compose)([ 16498 withMultiEntityRecordEdits, 16499 // Limit to matching action type so we don't attempt to replace action on 16500 // an unhandled action. 16501 if_matching_action_default( 16502 (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind 16503 ), 16504 // Inject the entity config into the action. 16505 replace_action_default((action) => { 16506 return { 16507 key: entityConfig.key || DEFAULT_ENTITY_KEY, 16508 ...action 16509 }; 16510 }) 16511 ])( 16512 (0, import_data7.combineReducers)({ 16513 queriedData: reducer_default, 16514 edits: (state = {}, action) => { 16515 switch (action.type) { 16516 case "RECEIVE_ITEMS": 16517 const context = action?.query?.context ?? "default"; 16518 if (context !== "default") { 16519 return state; 16520 } 16521 const nextState = { ...state }; 16522 const itemsList = Array.isArray(action.items) ? action.items : [action.items]; 16523 for (const record of itemsList) { 16524 const recordId = record?.[action.key]; 16525 const edits = nextState[recordId]; 16526 if (!edits) { 16527 continue; 16528 } 16529 const nextEdits2 = Object.keys(edits).reduce( 16530 (acc, key) => { 16531 if ( 16532 // Edits are the "raw" attribute values, but records may have 16533 // objects with more properties, so we use `get` here for the 16534 // comparison. 16535 !(0, import_es67.default)( 16536 edits[key],
16537 record[key]?.raw ?? record[key] 16538 ) && // Sometimes the server alters the sent value which means 16539 // we need to also remove the edits before the api request. 16540 (!action.persistedEdits || !(0, import_es67.default)( 16541 edits[key], 16542 action.persistedEdits[key] 16543 )) 16544 ) { 16545 acc[key] = edits[key]; 16546 } 16547 return acc; 16548 }, 16549 {} 16550 ); 16551 if (Object.keys(nextEdits2).length) { 16552 nextState[recordId] = nextEdits2; 16553 } else { 16554 delete nextState[recordId]; 16555 } 16556 } 16557 return nextState; 16558 case "EDIT_ENTITY_RECORD": 16559 const nextEdits = { 16560 ...state[action.recordId], 16561 ...action.edits 16562 }; 16563 Object.keys(nextEdits).forEach((key) => { 16564 if (nextEdits[key] === void 0) { 16565 delete nextEdits[key]; 16566 } 16567 }); 16568 return { 16569 ...state, 16570 [action.recordId]: nextEdits 16571 }; 16572 } 16573 return state; 16574 }, 16575 saving: (state = {}, action) => { 16576 switch (action.type) { 16577 case "SAVE_ENTITY_RECORD_START": 16578 case "SAVE_ENTITY_RECORD_FINISH": 16579 return { 16580 ...state, 16581 [action.recordId]: { 16582 pending: action.type === "SAVE_ENTITY_RECORD_START", 16583 error: action.error, 16584 isAutosave: action.isAutosave 16585 } 16586 }; 16587 } 16588 return state; 16589 }, 16590 deleting: (state = {}, action) => { 16591 switch (action.type) { 16592 case "DELETE_ENTITY_RECORD_START": 16593 case "DELETE_ENTITY_RECORD_FINISH": 16594 return { 16595 ...state, 16596 [action.recordId]: { 16597 pending: action.type === "DELETE_ENTITY_RECORD_START", 16598 error: action.error 16599 } 16600 }; 16601 } 16602 return state; 16603 }, 16604 revisions: (state = {}, action) => { 16605 if (action.type === "RECEIVE_ITEM_REVISIONS") { 16606 const recordKey = action.recordKey; 16607 delete action.recordKey; 16608 const newState = reducer_default(state[recordKey], { 16609 ...action, 16610 type: "RECEIVE_ITEMS" 16611 }); 16612 return { 16613 ...state, 16614 [recordKey]: newState 16615 }; 16616 } 16617 if (action.type === "REMOVE_ITEMS") { 16618 return Object.fromEntries( 16619 Object.entries(state).filter( 16620 ([id2]) => !action.itemIds.some((itemId) => { 16621 if (Number.isInteger(itemId)) { 16622 return itemId === +id2; 16623 } 16624 return itemId === id2; 16625 }) 16626 ) 16627 ); 16628 } 16629 return state; 16630 } 16631 }) 16632 ); 16633 } 16634 function entitiesConfig(state = rootEntitiesConfig, action) { 16635 switch (action.type) { 16636 case "ADD_ENTITIES": 16637 return [...state, ...action.entities]; 16638 } 16639 return state; 16640 } 16641 var entities = (state = {}, action) => { 16642 const newConfig = entitiesConfig(state.config, action); 16643 let entitiesDataReducer = state.reducer; 16644 if (!entitiesDataReducer || newConfig !== state.config) { 16645 const entitiesByKind = newConfig.reduce((acc, record) => { 16646 const { kind } = record; 16647 if (!acc[kind]) { 16648 acc[kind] = []; 16649 } 16650 acc[kind].push(record); 16651 return acc; 16652 }, {}); 16653 entitiesDataReducer = (0, import_data7.combineReducers)( 16654 Object.fromEntries( 16655 Object.entries(entitiesByKind).map( 16656 ([kind, subEntities]) => { 16657 const kindReducer = (0, import_data7.combineReducers)( 16658 Object.fromEntries( 16659 subEntities.map((entityConfig) => [ 16660 entityConfig.name, 16661 entity(entityConfig) 16662 ]) 16663 ) 16664 ); 16665 return [kind, kindReducer]; 16666 } 16667 ) 16668 ) 16669 ); 16670 } 16671 const newData = entitiesDataReducer(state.records, action); 16672 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) { 16673 return state; 16674 } 16675 return { 16676 reducer: entitiesDataReducer, 16677 records: newData, 16678 config: newConfig 16679 }; 16680 }; 16681 function undoManager(state = (0, import_undo_manager2.createUndoManager)()) { 16682 return state; 16683 } 16684 function syncUndoManagerState(state = { hasRedo: false, hasUndo: false }, action) { 16685 switch (action.type) { 16686 case "SYNC_UNDO_MANAGER_CHANGE": 16687 return { 16688 hasRedo: action.hasRedo, 16689 hasUndo: action.hasUndo 16690 }; 16691 } 16692 return state; 16693 } 16694 function editsReference(state = {}, action) { 16695 switch (action.type) { 16696 case "EDIT_ENTITY_RECORD": 16697 case "UNDO": 16698 case "REDO": 16699 return {}; 16700 } 16701 return state; 16702 } 16703 function embedPreviews(state = {}, action) { 16704 switch (action.type) { 16705 case "RECEIVE_EMBED_PREVIEW": 16706 const { url, preview } = action; 16707 return { 16708 ...state, 16709 [url]: preview 16710 }; 16711 } 16712 return state; 16713 } 16714 function userPermissions(state = {}, action) { 16715 switch (action.type) { 16716 case "RECEIVE_USER_PERMISSION": 16717 return { 16718 ...state, 16719 [action.key]: action.isAllowed 16720 }; 16721 case "RECEIVE_USER_PERMISSIONS": 16722 return { 16723 ...state, 16724 ...action.permissions 16725 }; 16726 } 16727 return state; 16728 } 16729 function autosaves(state = {}, action) { 16730 switch (action.type) { 16731 case "RECEIVE_AUTOSAVES": 16732 const { postId, autosaves: autosavesData } = action; 16733 return { 16734 ...state, 16735 [postId]: autosavesData 16736 }; 16737 } 16738 return state; 16739 } 16740 function blockPatterns(state = [], action) { 16741 switch (action.type) { 16742 case "RECEIVE_BLOCK_PATTERNS": 16743 return action.patterns; 16744 } 16745 return state; 16746 } 16747 function blockPatternCategories(state = [], action) { 16748 switch (action.type) { 16749 case "RECEIVE_BLOCK_PATTERN_CATEGORIES": 16750 return action.categories; 16751 } 16752 return state; 16753 } 16754 function userPatternCategories(state = [], action) { 16755 switch (action.type) { 16756 case "RECEIVE_USER_PATTERN_CATEGORIES": 16757 return action.patternCategories; 16758 } 16759 return state; 16760 } 16761 function navigationFallbackId(state = null, action) { 16762 switch (action.type) { 16763 case "RECEIVE_NAVIGATION_FALLBACK_ID": 16764 return action.fallbackId; 16765 } 16766 return state; 16767 } 16768 function themeGlobalStyleRevisions(state = {}, action) { 16769 switch (action.type) { 16770 case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS": 16771 return { 16772 ...state, 16773 [action.currentId]: action.revisions 16774 }; 16775 } 16776 return state; 16777 } 16778 function defaultTemplates(state = {}, action) { 16779 switch (action.type) { 16780 case "RECEIVE_DEFAULT_TEMPLATE": 16781 return { 16782 ...state, 16783 [JSON.stringify(action.query)]: action.templateId 16784 }; 16785 } 16786 return state; 16787 } 16788 function registeredPostMeta(state = {}, action) { 16789 switch (action.type) {
16790 case "RECEIVE_REGISTERED_POST_META": 16791 return { 16792 ...state, 16793 [action.postType]: action.registeredPostMeta 16794 }; 16795 } 16796 return state; 16797 } 16798 function editorSettings(state = null, action) { 16799 switch (action.type) { 16800 case "RECEIVE_EDITOR_SETTINGS": 16801 return action.settings; 16802 } 16803 return state; 16804 } 16805 function editorAssets(state = null, action) { 16806 switch (action.type) { 16807 case "RECEIVE_EDITOR_ASSETS": 16808 return action.assets; 16809 } 16810 return state; 16811 } 16812 function syncConnectionStatuses(state = {}, action) { 16813 switch (action.type) { 16814 case "SET_SYNC_CONNECTION_STATUS": { 16815 const key = `${action.kind}/${action.name}:${action.key}`; 16816 return { 16817 ...state, 16818 [key]: action.status 16819 }; 16820 } 16821 case "CLEAR_SYNC_CONNECTION_STATUS": { 16822 const key = `${action.kind}/${action.name}:${action.key}`; 16823 const { [key]: _, ...rest } = state; 16824 return rest; 16825 } 16826 } 16827 return state; 16828 } 16829 function collaborationSupported(state = true, action) { 16830 switch (action.type) { 16831 case "SET_COLLABORATION_SUPPORTED": 16832 return action.supported; 16833 case "SET_SYNC_CONNECTION_STATUS": 16834 if (ConnectionErrorCode2.DOCUMENT_SIZE_LIMIT_EXCEEDED === action.status?.error?.code) { 16835 return false; 16836 } 16837 return state; 16838 } 16839 return state; 16840 } 16841 function viewConfigs(state = {}, action) { 16842 switch (action.type) { 16843 case "RECEIVE_VIEW_CONFIG": { 16844 const key = `${action.kind}/${action.name}`; 16845 return { 16846 ...state, 16847 [key]: { 16848 ...state[key], 16849 ...action.config 16850 } 16851 }; 16852 } 16853 } 16854 return state; 16855 } 16856 var reducer_default2 = (0, import_data7.combineReducers)({ 16857 users, 16858 currentTheme, 16859 currentGlobalStylesId, 16860 currentUser, 16861 themeGlobalStyleVariations, 16862 themeBaseGlobalStyles, 16863 themeGlobalStyleRevisions, 16864 entities, 16865 editsReference, 16866 syncUndoManagerState, 16867 undoManager, 16868 embedPreviews, 16869 userPermissions, 16870 autosaves, 16871 blockPatterns, 16872 blockPatternCategories, 16873 userPatternCategories, 16874 navigationFallbackId, 16875 defaultTemplates, 16876 registeredPostMeta, 16877 editorSettings, 16878 editorAssets, 16879 syncConnectionStatuses, 16880 collaborationSupported, 16881 viewConfigs 16882 }); 16883 16884
16884// packages/core-data/build-module/selectors.mjs 16885 var selectors_exports = {}; 16886 __export(selectors_exports, { 16887 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId, 16888 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles, 16889 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations, 16890 __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords, 16891 __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved, 16892 __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver, 16893 canUser: () => canUser, 16894 canUserEditEntityRecord: () => canUserEditEntityRecord, 16895 getAuthors: () => getAuthors, 16896 getAutosave: () => getAutosave, 16897 getAutosaves: () => getAutosaves, 16898 getBlockPatternCategories: () => getBlockPatternCategories, 16899 getBlockPatterns: () => getBlockPatterns, 16900 getCurrentTheme: () => getCurrentTheme, 16901 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions, 16902 getCurrentUser: () => getCurrentUser, 16903 getDefaultTemplateId: () => getDefaultTemplateId, 16904 getEditedEntityRecord: () => getEditedEntityRecord, 16905 getEmbedPreview: () => getEmbedPreview, 16906 getEntitiesByKind: () => getEntitiesByKind, 16907 getEntitiesConfig: () => getEntitiesConfig, 16908 getEntity: () => getEntity, 16909 getEntityConfig: () => getEntityConfig, 16910 getEntityRecord: () => getEntityRecord, 16911 getEntityRecordEdits: () => getEntityRecordEdits, 16912 getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits, 16913 getEntityRecords: () => getEntityRecords, 16914 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems, 16915 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages, 16916 getLastEntityDeleteError: () => getLastEntityDeleteError, 16917 getLastEntitySaveError: () => getLastEntitySaveError, 16918 getRawEntityRecord: () => getRawEntityRecord, 16919 getRedoEdit: () => getRedoEdit, 16920 getReferenceByDistinctEdits: () => getReferenceByDistinctEdits, 16921 getRevision: () => getRevision, 16922 getRevisions: () => getRevisions, 16923 getThemeSupports: () => getThemeSupports, 16924 getUndoEdit: () => getUndoEdit, 16925 getUserPatternCategories: () => getUserPatternCategories, 16926 getUserQueryResults: () => getUserQueryResults, 16927 hasEditsForEntityRecord: () => hasEditsForEntityRecord, 16928 hasEntityRecord: () => hasEntityRecord, 16929 hasEntityRecords: () => hasEntityRecords, 16930 hasFetchedAutosaves: () => hasFetchedAutosaves, 16931 hasRedo: () => hasRedo, 16932 hasRevision: () => hasRevision, 16933 hasUndo: () => hasUndo, 16934 isAutosavingEntityRecord: () => isAutosavingEntityRecord, 16935 isDeletingEntityRecord: () => isDeletingEntityRecord, 16936 isPreviewEmbedFallback: () => isPreviewEmbedFallback, 16937 isRequestingEmbedPreview: () => isRequestingEmbedPreview, 16938 isSavingEntityRecord: () => isSavingEntityRecord 16939 }); 16940 var import_data9 = __toESM(require_data(), 1); 16941 var import_url2 = __toESM(require_url(), 1); 16942 var import_deprecated2 = __toESM(require_deprecated(), 1); 16943 16944
16944// packages/core-data/build-module/private-selectors.mjs 16945 var private_selectors_exports = {}; 16946 __export(private_selectors_exports, { 16947 getBlockPatternsForPostType: () => getBlockPatternsForPostType, 16948 getEditorAssets: () => getEditorAssets, 16949 getEditorSettings: () => getEditorSettings, 16950 getEntityRecordPermissions: () => getEntityRecordPermissions, 16951 getEntityRecordsPermissions: () => getEntityRecordsPermissions, 16952 getHomePage: () => getHomePage, 16953 getNavigationFallbackId: () => getNavigationFallbackId, 16954 getPostsPageId: () => getPostsPageId, 16955 getRegisteredPostMeta: () => getRegisteredPostMeta, 16956 getSyncConnectionStatus: () => getSyncConnectionStatus, 16957 getTemplateId: () => getTemplateId, 16958 getUndoManager: () => getUndoManager, 16959 getViewConfig: () => getViewConfig, 16960 isCollaborationSupported: () => isCollaborationSupported 16961 }); 16962 var import_data8 = __toESM(require_data(), 1); 16963 16964
16964// packages/core-data/build-module/utils/log-entity-deprecation.mjs 16965 var import_deprecated = __toESM(require_deprecated(), 1); 16966 var loggedAlready = false; 16967 function logEntityDeprecation(kind, name, functionName, { 16968 alternativeFunctionName, 16969 isShorthandSelector = false 16970 } = {}) { 16971 const deprecation = deprecatedEntities[kind]?.[name]; 16972 if (!deprecation) { 16973 return; 16974 } 16975 if (!loggedAlready) { 16976 const { alternative } = deprecation; 16977 const message = isShorthandSelector ? `'${functionName}'` : `The '${kind}', '${name}' entity (used via '${functionName}')`; 16978 let alternativeMessage = `the '${alternative.kind}', '${alternative.name}' entity`; 16979 if (alternativeFunctionName) { 16980 alternativeMessage += ` via the '${alternativeFunctionName}' function`; 16981 } 16982 (0, import_deprecated.default)(message, { 16983 ...deprecation, 16984 alternative: alternativeMessage 16985 }); 16986 } 16987 loggedAlready = true; 16988 setTimeout(() => { 16989 loggedAlready = false; 16990 }, 0); 16991 } 16992 16993
16993// packages/core-data/build-module/private-selectors.mjs 16994 var EMPTY_OBJECT = {}; 16995 function getUndoManager(state) { 16996 return getSyncManager()?.undoManager ?? state.undoManager; 16997 } 16998 function getNavigationFallbackId(state) { 16999 return state.navigationFallbackId; 17000 } 17001 var getBlockPatternsForPostType = (0, import_data8.createRegistrySelector)( 17002 (select4) => (0, import_data8.createSelector)( 17003 (state, postType) => select4(STORE_NAME).getBlockPatterns().filter( 17004 ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType) 17005 ), 17006 () => [select4(STORE_NAME).getBlockPatterns()] 17007 ) 17008 ); 17009 var getEntityRecordsPermissions = (0, import_data8.createRegistrySelector)( 17010 (select4) => (0, import_data8.createSelector)( 17011 (state, kind, name, ids) => { 17012 const normalizedIds = Array.isArray(ids) ? ids : [ids]; 17013 return normalizedIds.map((id2) => ({ 17014 delete: select4(STORE_NAME).canUser("delete", { 17015 kind, 17016 name, 17017 id: id2 17018 }), 17019 update: select4(STORE_NAME).canUser("update", { 17020 kind, 17021 name, 17022 id: id2 17023 }) 17024 })); 17025 }, 17026 (state) => [state.userPermissions] 17027 ) 17028 ); 17029 function getEntityRecordPermissions(state, kind, name, id2) { 17030 logEntityDeprecation(kind, name, "getEntityRecordPermissions"); 17031 return getEntityRecordsPermissions(state, kind, name, id2)[0]; 17032 } 17033 function getRegisteredPostMeta(state, postType) { 17034 return state.registeredPostMeta?.[postType] ?? {}; 17035 } 17036 function normalizePageId(value) { 17037 if (!value || !["number", "string"].includes(typeof value)) { 17038 return null; 17039 } 17040 if (Number(value) === 0) { 17041 return null; 17042 } 17043 return value.toString(); 17044 } 17045 var getHomePage = (0, import_data8.createRegistrySelector)( 17046 (select4) => (0, import_data8.createSelector)( 17047 () => { 17048 const siteData = select4(STORE_NAME).getEntityRecord( 17049 "root", 17050 "__unstableBase" 17051 ); 17052 if (!siteData) { 17053 return null; 17054 } 17055 const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null; 17056 if (homepageId) { 17057 return { postType: "page", postId: homepageId }; 17058 } 17059 const frontPageTemplateId = select4( 17060 STORE_NAME 17061 ).getDefaultTemplateId({ 17062 slug: "front-page" 17063 }); 17064 if (frontPageTemplateId) { 17065 return { 17066 postType: "wp_template", 17067 postId: frontPageTemplateId 17068 }; 17069 } 17070 if (frontPageTemplateId === "") { 17071 return EMPTY_OBJECT; 17072 } 17073 return null; 17074 }, 17075 (state) => [ 17076 // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes, 17077 // it doesn't seem to invalidate this cache, I'm not sure why. 17078 getEntityRecord(state, "root", "site"), 17079 getEntityRecord(state, "root", "__unstableBase"), 17080 getDefaultTemplateId(state, { 17081 slug: "front-page" 17082 }) 17083 ] 17084 ) 17085 ); 17086 var getPostsPageId = (0, import_data8.createRegistrySelector)((select4) => () => { 17087 const siteData = select4(STORE_NAME).getEntityRecord( 17088 "root", 17089 "__unstableBase" 17090 ); 17091 return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null; 17092 }); 17093 var getTemplateId = (0, import_data8.createRegistrySelector)( 17094 (select4) => (state, postType, postId) => { 17095 const homepage = unlock2(select4(STORE_NAME)).getHomePage(); 17096 if (!homepage) { 17097 return; 17098 } 17099 if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) { 17100 const templates = select4(STORE_NAME).getEntityRecords( 17101 "postType", 17102 "wp_template", 17103 { 17104 per_page: -1 17105 } 17106 ); 17107 if (!templates) { 17108 return; 17109 } 17110 const id2 = templates.find(({ slug }) => slug === "front-page")?.id; 17111 if (id2) { 17112 return id2; 17113 } 17114 } 17115 const editedEntity = select4(STORE_NAME).getEditedEntityRecord( 17116 "postType", 17117 postType, 17118 postId 17119 ); 17120 if (!editedEntity) { 17121 return; 17122 } 17123 const postsPageId = unlock2(select4(STORE_NAME)).getPostsPageId(); 17124 if (postType === "page" && postsPageId === postId.toString()) { 17125 return select4(STORE_NAME).getDefaultTemplateId({ 17126 slug: "home" 17127 }); 17128 } 17129 const currentTemplateSlug = editedEntity.template; 17130 if (currentTemplateSlug) { 17131 const currentTemplate = select4(STORE_NAME).getEntityRecords("postType", "wp_template", { 17132 per_page: -1 17133 })?.find(({ slug }) => slug === currentTemplateSlug); 17134 if (currentTemplate) { 17135 return currentTemplate.id; 17136 } 17137 } 17138 let slugToCheck; 17139 if (editedEntity.slug) { 17140 slugToCheck = postType === "page" ? `${postType}-${editedEntity.slug}` : `single-${postType}-${editedEntity.slug}`; 17141 } else { 17142 slugToCheck = postType === "page" ? "page" : `single-${postType}`; 17143 } 17144 return select4(STORE_NAME).getDefaultTemplateId({ 17145 slug: slugToCheck 17146 }); 17147 } 17148 ); 17149 function getEditorSettings(state) { 17150 return state.editorSettings; 17151 } 17152 function getEditorAssets(state) { 17153 return state.editorAssets; 17154 } 17155 function isCollaborationSupported(state) { 17156 return state.collaborationSupported; 17157 } 17158 function getViewConfig(state, kind, name) { 17159 return state.viewConfigs?.[`${kind}/${name}`] ?? { 17160 default_view: void 0, 17161 default_layouts: void 0, 17162 view_list: void 0, 17163 form: void 0 17164 }; 17165 } 17166 function getSyncConnectionStatus(state) { 17167 if (!state.syncConnectionStatuses) { 17168 return void 0; 17169 } 17170 const PRIORITIZED_STATUSES = ["disconnected", "connecting", "connected"];
17171 let coalesced; 17172 for (const status of Object.values(state.syncConnectionStatuses)) { 17173 if (!coalesced || PRIORITIZED_STATUSES.indexOf(status.status) < PRIORITIZED_STATUSES.indexOf(coalesced.status)) { 17174 coalesced = status; 17175 } 17176 } 17177 return coalesced; 17178 } 17179 17180
17180// packages/core-data/build-module/selectors.mjs 17181 var EMPTY_OBJECT2 = {}; 17182 var isRequestingEmbedPreview = (0, import_data9.createRegistrySelector)( 17183 (select4) => (state, url) => { 17184 return select4(STORE_NAME).isResolving("getEmbedPreview", [ 17185 url 17186 ]); 17187 } 17188 ); 17189 function getAuthors(state, query) { 17190 (0, import_deprecated2.default)("select( 'core' ).getAuthors()", { 17191 since: "5.9", 17192 alternative: "select( 'core' ).getUsers({ who: 'authors' })" 17193 }); 17194 const path = (0, import_url2.addQueryArgs)( 17195 "/wp/v2/users/?who=authors&per_page=100", 17196 query 17197 ); 17198 return getUserQueryResults(state, path); 17199 } 17200 function getCurrentUser(state) { 17201 return state.currentUser; 17202 } 17203 var getUserQueryResults = (0, import_data9.createSelector)( 17204 (state, queryID) => { 17205 const queryResults = state.users.queries[queryID] ?? []; 17206 return queryResults.map((id2) => state.users.byId[id2]); 17207 }, 17208 (state, queryID) => [ 17209 state.users.queries[queryID], 17210 state.users.byId 17211 ] 17212 ); 17213 function getEntitiesByKind(state, kind) { 17214 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", { 17215 since: "6.0", 17216 alternative: "wp.data.select( 'core' ).getEntitiesConfig()" 17217 }); 17218 return getEntitiesConfig(state, kind); 17219 } 17220 var getEntitiesConfig = (0, import_data9.createSelector)( 17221 (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind), 17222 /* eslint-disable @typescript-eslint/no-unused-vars */ 17223 (state, kind) => state.entities.config 17224 /* eslint-enable @typescript-eslint/no-unused-vars */ 17225 ); 17226 function getEntity(state, kind, name) { 17227 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", { 17228 since: "6.0", 17229 alternative: "wp.data.select( 'core' ).getEntityConfig()" 17230 }); 17231 return getEntityConfig(state, kind, name); 17232 } 17233 function getEntityConfig(state, kind, name) { 17234 logEntityDeprecation(kind, name, "getEntityConfig"); 17235 return state.entities.config?.find( 17236 (config) => config.kind === kind && config.name === name 17237 ); 17238 } 17239 var getEntityRecord = (0, import_data9.createSelector)( 17240 ((state, kind, name, key, query) => { 17241 logEntityDeprecation(kind, name, "getEntityRecord"); 17242 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17243 if (!queriedState) { 17244 return void 0; 17245 } 17246 const context = query?.context ?? "default"; 17247 if (!query || !query._fields) { 17248 if (!queriedState.itemIsComplete[context]?.[key]) { 17249 return void 0; 17250 } 17251 return queriedState.items[context][key]; 17252 } 17253 const item = queriedState.items[context]?.[key]; 17254 if (!item) { 17255 return item; 17256 } 17257 const filteredItem = {}; 17258 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17259 for (let f = 0; f < fields.length; f++) { 17260 const field = fields[f].split("."); 17261 let value = item; 17262 field.forEach((fieldName) => { 17263 value = value?.[fieldName]; 17264 }); 17265 setNestedValue(filteredItem, field, value); 17266 } 17267 return filteredItem; 17268 }), 17269 (state, kind, name, recordId, query) => { 17270 const context = query?.context ?? "default"; 17271 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17272 return [ 17273 queriedState?.items[context]?.[recordId], 17274 queriedState?.itemIsComplete[context]?.[recordId] 17275 ]; 17276 } 17277 ); 17278 getEntityRecord.__unstableNormalizeArgs = (args2) => { 17279 const newArgs = [...args2]; 17280 const recordKey = newArgs?.[2]; 17281 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey; 17282 return newArgs; 17283 }; 17284 function hasEntityRecord(state, kind, name, key, query) { 17285 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17286 if (!queriedState) { 17287 return false; 17288 } 17289 const context = query?.context ?? "default"; 17290 if (!query || !query._fields) { 17291 return !!queriedState.itemIsComplete[context]?.[key]; 17292 } 17293 const item = queriedState.items[context]?.[key]; 17294 if (!item) { 17295 return false;
17296 } 17297 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17298 for (let i = 0; i < fields.length; i++) { 17299 const path = fields[i].split("."); 17300 let value = item; 17301 for (let p = 0; p < path.length; p++) { 17302 const part = path[p]; 17303 if (!value || !Object.hasOwn(value, part)) { 17304 return false; 17305 } 17306 value = value[part]; 17307 } 17308 } 17309 return true; 17310 } 17311 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) { 17312 return getEntityRecord(state, kind, name, key); 17313 } 17314 var getRawEntityRecord = (0, import_data9.createSelector)( 17315 (state, kind, name, key) => { 17316 logEntityDeprecation(kind, name, "getRawEntityRecord"); 17317 const record = getEntityRecord( 17318 state, 17319 kind, 17320 name, 17321 key 17322 ); 17323 const config = getEntityConfig(state, kind, name); 17324 if (!record || !config?.rawAttributes?.length) { 17325 return record; 17326 } 17327 return Object.fromEntries( 17328 Object.keys(record).map((_key) => { 17329 if (config.rawAttributes.includes(_key)) { 17330 const rawValue = record[_key]?.raw; 17331 return [ 17332 _key, 17333 rawValue !== void 0 ? rawValue : record[_key] 17334 ]; 17335 } 17336 return [_key, record[_key]]; 17337 }) 17338 ); 17339 }, 17340 (state, kind, name, recordId, query) => { 17341 const context = query?.context ?? "default"; 17342 return [ 17343 state.entities.config, 17344 state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId], 17345 state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId] 17346 ]; 17347 } 17348 ); 17349 function hasEntityRecords(state, kind, name, query) { 17350 logEntityDeprecation(kind, name, "hasEntityRecords"); 17351 return Array.isArray(getEntityRecords(state, kind, name, query)); 17352 } 17353 var getEntityRecords = ((state, kind, name, query) => { 17354 logEntityDeprecation(kind, name, "getEntityRecords"); 17355 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17356 if (!queriedState) { 17357 return null; 17358 } 17359 return getQueriedItems(queriedState, query, { 17360 supportsPagination: !!getEntityConfig(state, kind, name)?.supportsPagination 17361 }); 17362 }); 17363 var getEntityRecordsTotalItems = (state, kind, name, query) => { 17364 logEntityDeprecation(kind, name, "getEntityRecordsTotalItems"); 17365 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17366 if (!queriedState) { 17367 return null; 17368 } 17369 return getQueriedTotalItems(queriedState, query); 17370 }; 17371 var getEntityRecordsTotalPages = (state, kind, name, query) => { 17372 logEntityDeprecation(kind, name, "getEntityRecordsTotalPages"); 17373 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData; 17374 if (!queriedState) { 17375 return null; 17376 } 17377 if (!getEntityConfig(state, kind, name)?.supportsPagination || query?.per_page === -1) { 17378 return 1; 17379 } 17380 const totalItems = getQueriedTotalItems(queriedState, query); 17381 if (!totalItems) { 17382 return totalItems; 17383 } 17384 if (!query?.per_page) { 17385 return getQueriedTotalPages(queriedState, query); 17386 } 17387 return Math.ceil(totalItems / query.per_page); 17388 }; 17389 var __experimentalGetDirtyEntityRecords = (0, import_data9.createSelector)( 17390 (state) => { 17391 const { 17392 entities: { records } 17393 } = state; 17394 const dirtyRecords = [];
17395 Object.keys(records).forEach((kind) => { 17396 Object.keys(records[kind]).forEach((name) => { 17397 const primaryKeys = Object.keys(records[kind][name].edits).filter( 17398 (primaryKey) => ( 17399 // The entity record must exist (not be deleted), 17400 // and it must have edits. 17401 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey) 17402 ) 17403 ); 17404 if (primaryKeys.length) { 17405 const entityConfig = getEntityConfig(state, kind, name); 17406 primaryKeys.forEach((primaryKey) => { 17407 const entityRecord = getEditedEntityRecord( 17408 state, 17409 kind, 17410 name, 17411 primaryKey 17412 ); 17413 dirtyRecords.push({ 17414 // We avoid using primaryKey because it's transformed into a string 17415 // when it's used as an object key. 17416 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0, 17417 title: entityConfig?.getTitle?.(entityRecord) || "", 17418 name, 17419 kind 17420 }); 17421 }); 17422 } 17423 }); 17424 }); 17425 return dirtyRecords; 17426 }, 17427 (state) => [state.entities.records] 17428 ); 17429 var __experimentalGetEntitiesBeingSaved = (0, import_data9.createSelector)( 17430 (state) => { 17431 const { 17432 entities: { records } 17433 } = state; 17434 const recordsBeingSaved = [];
17435 Object.keys(records).forEach((kind) => { 17436 Object.keys(records[kind]).forEach((name) => { 17437 const primaryKeys = Object.keys(records[kind][name].saving).filter( 17438 (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey) 17439 ); 17440 if (primaryKeys.length) { 17441 const entityConfig = getEntityConfig(state, kind, name); 17442 primaryKeys.forEach((primaryKey) => { 17443 const entityRecord = getEditedEntityRecord( 17444 state, 17445 kind, 17446 name, 17447 primaryKey 17448 ); 17449 recordsBeingSaved.push({ 17450 // We avoid using primaryKey because it's transformed into a string 17451 // when it's used as an object key. 17452 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0, 17453 title: entityConfig?.getTitle?.(entityRecord) || "", 17454 name, 17455 kind 17456 }); 17457 }); 17458 } 17459 }); 17460 }); 17461 return recordsBeingSaved; 17462 }, 17463 (state) => [state.entities.records] 17464 ); 17465 function getEntityRecordEdits(state, kind, name, recordId) { 17466 logEntityDeprecation(kind, name, "getEntityRecordEdits"); 17467 return state.entities.records?.[kind]?.[name]?.edits?.[recordId]; 17468 } 17469 var getEntityRecordNonTransientEdits = (0, import_data9.createSelector)( 17470 (state, kind, name, recordId) => { 17471 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits"); 17472 const { transientEdits } = getEntityConfig(state, kind, name) || {}; 17473 const edits = getEntityRecordEdits(state, kind, name, recordId) || {}; 17474 if (!transientEdits) { 17475 return edits; 17476 } 17477 return Object.keys(edits).reduce((acc, key) => { 17478 if (!transientEdits[key]) { 17479 acc[key] = edits[key]; 17480 } 17481 return acc; 17482 }, {}); 17483 }, 17484 (state, kind, name, recordId) => [ 17485 state.entities.config, 17486 state.entities.records?.[kind]?.[name]?.edits?.[recordId] 17487 ] 17488 ); 17489 function hasEditsForEntityRecord(state, kind, name, recordId) { 17490 logEntityDeprecation(kind, name, "hasEditsForEntityRecord"); 17491 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys( 17492 getEntityRecordNonTransientEdits(state, kind, name, recordId) 17493 ).length > 0; 17494 } 17495 var getEditedEntityRecord = (0, import_data9.createSelector)( 17496 (state, kind, name, recordId) => { 17497 logEntityDeprecation(kind, name, "getEditedEntityRecord"); 17498 const raw = getRawEntityRecord(state, kind, name, recordId); 17499 const edited = getEntityRecordEdits(state, kind, name, recordId); 17500 if (!raw && !edited) { 17501 return false; 17502 } 17503 return { 17504 ...raw, 17505 ...edited 17506 }; 17507 }, 17508 (state, kind, name, recordId, query) => { 17509 const context = query?.context ?? "default"; 17510 return [ 17511 state.entities.config, 17512 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId], 17513 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId], 17514 state.entities.records?.[kind]?.[name]?.edits?.[recordId] 17515 ]; 17516 } 17517 ); 17518 function isAutosavingEntityRecord(state, kind, name, recordId) { 17519 logEntityDeprecation(kind, name, "isAutosavingEntityRecord"); 17520 const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {}; 17521 return Boolean(pending && isAutosave); 17522 } 17523 function isSavingEntityRecord(state, kind, name, recordId) { 17524 logEntityDeprecation(kind, name, "isSavingEntityRecord"); 17525 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.pending ?? false; 17526 } 17527 function isDeletingEntityRecord(state, kind, name, recordId) { 17528 logEntityDeprecation(kind, name, "isDeletingEntityRecord"); 17529 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.pending ?? false; 17530 } 17531 function getLastEntitySaveError(state, kind, name, recordId) { 17532 logEntityDeprecation(kind, name, "getLastEntitySaveError"); 17533 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.error; 17534 } 17535 function getLastEntityDeleteError(state, kind, name, recordId) { 17536 logEntityDeprecation(kind, name, "getLastEntityDeleteError"); 17537 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error; 17538 } 17539 function getUndoEdit(state) { 17540 (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", { 17541 since: "6.3" 17542 }); 17543 return void 0; 17544 } 17545 function getRedoEdit(state) { 17546 (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", { 17547 since: "6.3" 17548 }); 17549 return void 0; 17550 } 17551 function hasUndo(state) { 17552 if (getSyncManager()?.undoManager) { 17553 return state.syncUndoManagerState.hasUndo; 17554 } 17555 return getUndoManager(state).hasUndo(); 17556 } 17557 function hasRedo(state) { 17558 if (getSyncManager()?.undoManager) { 17559 return state.syncUndoManagerState.hasRedo; 17560 } 17561 return getUndoManager(state).hasRedo(); 17562 } 17563 function getCurrentTheme(state) { 17564 if (!state.currentTheme) { 17565 return null; 17566 } 17567 return getEntityRecord(state, "root", "theme", state.currentTheme); 17568 } 17569 function __experimentalGetCurrentGlobalStylesId(state) { 17570 return state.currentGlobalStylesId; 17571 } 17572 function getThemeSupports(state) { 17573 return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT2; 17574 } 17575 function getEmbedPreview(state, url) { 17576 return state.embedPreviews[url]; 17577 } 17578 function isPreviewEmbedFallback(state, url) { 17579 const preview = state.embedPreviews[url]; 17580 const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>"; 17581 if (!preview) { 17582 return false;
17583 } 17584 return preview.html === oEmbedLinkCheck; 17585 } 17586 function canUser(state, action, resource, id2) { 17587 const isEntity = typeof resource === "object"; 17588 if (isEntity && (!resource.kind || !resource.name)) { 17589 return false; 17590 } 17591 if (isEntity) { 17592 logEntityDeprecation(resource.kind, resource.name, "canUser"); 17593 } 17594 const key = getUserPermissionCacheKey(action, resource, id2); 17595 return state.userPermissions[key]; 17596 } 17597 function canUserEditEntityRecord(state, kind, name, recordId) { 17598 (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, { 17599 since: "6.7", 17600 alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )` 17601 }); 17602 return canUser(state, "update", { kind, name, id: recordId }); 17603 } 17604 function getAutosaves(state, postType, postId) { 17605 return state.autosaves[postId]; 17606 } 17607 function getAutosave(state, postType, postId, authorId) { 17608 if (authorId === void 0) { 17609 return; 17610 } 17611 const autosaves2 = state.autosaves[postId]; 17612 return autosaves2?.find( 17613 (autosave) => autosave.author === authorId 17614 ); 17615 } 17616 var hasFetchedAutosaves = (0, import_data9.createRegistrySelector)( 17617 (select4) => (state, postType, postId) => { 17618 return select4(STORE_NAME).hasFinishedResolution("getAutosaves", [ 17619 postType, 17620 postId 17621 ]); 17622 } 17623 ); 17624 function getReferenceByDistinctEdits(state) { 17625 return state.editsReference; 17626 } 17627 function __experimentalGetCurrentThemeBaseGlobalStyles(state) { 17628 const currentTheme2 = getCurrentTheme(state); 17629 if (!currentTheme2) { 17630 return null; 17631 } 17632 return state.themeBaseGlobalStyles[currentTheme2.stylesheet]; 17633 } 17634 function __experimentalGetCurrentThemeGlobalStylesVariations(state) { 17635 const currentTheme2 = getCurrentTheme(state); 17636 if (!currentTheme2) { 17637 return null; 17638 } 17639 return state.themeGlobalStyleVariations[currentTheme2.stylesheet]; 17640 } 17641 function getBlockPatterns(state) { 17642 return state.blockPatterns; 17643 } 17644 function getBlockPatternCategories(state) { 17645 return state.blockPatternCategories; 17646 } 17647 function getUserPatternCategories(state) { 17648 return state.userPatternCategories; 17649 } 17650 function getCurrentThemeGlobalStylesRevisions(state) { 17651 (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", { 17652 since: "6.5.0", 17653 alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )" 17654 }); 17655 const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state); 17656 if (!currentGlobalStylesId2) { 17657 return null; 17658 } 17659 return state.themeGlobalStyleRevisions[currentGlobalStylesId2]; 17660 } 17661 function getDefaultTemplateId(state, query) { 17662 return state.defaultTemplates[JSON.stringify(query)]; 17663 } 17664 var getRevisions = (state, kind, name, recordKey, query) => { 17665 logEntityDeprecation(kind, name, "getRevisions"); 17666 const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17667 if (!queriedStateRevisions) { 17668 return null; 17669 } 17670 return getQueriedItems(queriedStateRevisions, query); 17671 }; 17672 function hasRevision(state, kind, name, recordKey, revisionKey, query) { 17673 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17674 if (!queriedState) { 17675 return false; 17676 } 17677 const context = query?.context ?? "default"; 17678 if (!query || !query._fields) { 17679 return !!queriedState.itemIsComplete[context]?.[revisionKey]; 17680 } 17681 const item = queriedState.items[context]?.[revisionKey]; 17682 if (!item) { 17683 return false; 17684 } 17685 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17686 for (let i = 0; i < fields.length; i++) { 17687 const path = fields[i].split("."); 17688 let value = item; 17689 for (let p = 0; p < path.length; p++) { 17690 const part = path[p]; 17691 if (!value || !Object.hasOwn(value, part)) { 17692 return false; 17693 } 17694 value = value[part]; 17695 } 17696 } 17697 return true; 17698 } 17699 var getRevision = (0, import_data9.createSelector)(
17700 (state, kind, name, recordKey, revisionKey, query) => { 17701 logEntityDeprecation(kind, name, "getRevision"); 17702 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17703 if (!queriedState) { 17704 return void 0; 17705 } 17706 const context = query?.context ?? "default"; 17707 if (!query || !query._fields) { 17708 if (!queriedState.itemIsComplete[context]?.[revisionKey]) { 17709 return void 0; 17710 } 17711 return queriedState.items[context][revisionKey]; 17712 } 17713 const item = queriedState.items[context]?.[revisionKey]; 17714 if (!item) { 17715 return item; 17716 } 17717 const filteredItem = {}; 17718 const fields = get_normalized_comma_separable_default(query._fields) ?? []; 17719 for (let f = 0; f < fields.length; f++) { 17720 const field = fields[f].split("."); 17721 let value = item; 17722 field.forEach((fieldName) => { 17723 value = value?.[fieldName]; 17724 }); 17725 setNestedValue(filteredItem, field, value); 17726 } 17727 return filteredItem; 17728 }, 17729 (state, kind, name, recordKey, revisionKey, query) => { 17730 const context = query?.context ?? "default"; 17731 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey]; 17732 return [ 17733 queriedState?.items?.[context]?.[revisionKey], 17734 queriedState?.itemIsComplete?.[context]?.[revisionKey] 17735 ]; 17736 } 17737 ); 17738 17739
17739// packages/core-data/build-module/actions.mjs 17740 var actions_exports = {}; 17741 __export(actions_exports, { 17742 __experimentalBatch: () => __experimentalBatch, 17743 __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId, 17744 __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles, 17745 __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations, 17746 __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits, 17747 __unstableCreateUndoLevel: () => __unstableCreateUndoLevel, 17748 addEntities: () => addEntities, 17749 clearEntityRecordEdits: () => clearEntityRecordEdits, 17750 deleteEntityRecord: () => deleteEntityRecord, 17751 editEntityRecord: () => editEntityRecord, 17752 receiveAutosaves: () => receiveAutosaves, 17753 receiveCurrentTheme: () => receiveCurrentTheme, 17754 receiveCurrentUser: () => receiveCurrentUser, 17755 receiveDefaultTemplateId: () => receiveDefaultTemplateId, 17756 receiveEmbedPreview: () => receiveEmbedPreview, 17757 receiveEntityRecords: () => receiveEntityRecords, 17758 receiveNavigationFallbackId: () => receiveNavigationFallbackId, 17759 receiveRevisions: () => receiveRevisions, 17760 receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions, 17761 receiveThemeSupports: () => receiveThemeSupports, 17762 receiveUploadPermissions: () => receiveUploadPermissions, 17763 receiveUserPermission: () => receiveUserPermission, 17764 receiveUserPermissions: () => receiveUserPermissions, 17765 receiveUserQuery: () => receiveUserQuery, 17766 redo: () => redo, 17767 saveEditedEntityRecord: () => saveEditedEntityRecord, 17768 saveEntityRecord: () => saveEntityRecord, 17769 undo: () => undo 17770 }); 17771 var import_api_fetch5 = __toESM(require_api_fetch(), 1); 17772 var import_url3 = __toESM(require_url(), 1); 17773 var import_deprecated3 = __toESM(require_deprecated(), 1); 17774 17775
17775// packages/core-data/build-module/batch/default-processor.mjs 17776 var import_api_fetch4 = __toESM(require_api_fetch(), 1); 17777 var maxItems = null; 17778 function chunk(arr, chunkSize) { 17779 const tmp = [...arr]; 17780 const cache3 = []; 17781 while (tmp.length) { 17782 cache3.push(tmp.splice(0, chunkSize)); 17783 } 17784 return cache3; 17785 } 17786 async function defaultProcessor(requests) { 17787 if (maxItems === null) { 17788 const preflightResponse = await (0, import_api_fetch4.default)({ 17789 path: "/batch/v1", 17790 method: "OPTIONS" 17791 }); 17792 maxItems = preflightResponse.endpoints[0].args.requests.maxItems; 17793 } 17794 const results = []; 17795 for (const batchRequests of chunk(requests, maxItems)) { 17796 const batchResponse = await (0, import_api_fetch4.default)({ 17797 path: "/batch/v1", 17798 method: "POST", 17799 data: { 17800 validation: "require-all-validate", 17801 requests: batchRequests.map((request) => ({ 17802 path: request.path, 17803 body: request.data, 17804 // Rename 'data' to 'body'. 17805 method: request.method, 17806 headers: request.headers 17807 })) 17808 } 17809 }); 17810 let batchResults; 17811 if (batchResponse.failed) { 17812 batchResults = batchResponse.responses.map((response) => ({ 17813 error: response?.body 17814 })); 17815 } else { 17816 batchResults = batchResponse.responses.map((response) => { 17817 const result = {}; 17818 if (response.status >= 200 && response.status < 300) { 17819 result.output = response.body; 17820 } else { 17821 result.error = response.body; 17822 } 17823 return result; 17824 }); 17825 } 17826 results.push(...batchResults); 17827 } 17828 return results; 17829 } 17830 17831
17831// packages/core-data/build-module/batch/create-batch.mjs 17832 function createBatch(processor = defaultProcessor) { 17833 let lastId = 0; 17834 let queue = []; 17835 const pending = new ObservableSet(); 17836 return { 17837 /** 17838 * Adds an input to the batch and returns a promise that is resolved or 17839 * rejected when the input is processed by `batch.run()`. 17840 * 17841 * You may also pass a thunk which allows inputs to be added 17842 * asynchronously. 17843 * 17844 * ``` 17845 * // Both are allowed: 17846 * batch.add( { path: '/v1/books', ... } ); 17847 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) ); 17848 * ``` 17849 * 17850 * If a thunk is passed, `batch.run()` will pause until either: 17851 * 17852 * - The thunk calls its `add` argument, or; 17853 * - The thunk returns a promise and that promise resolves, or; 17854 * - The thunk returns a non-promise. 17855 * 17856 * @param {any|Function} inputOrThunk Input to add or thunk to execute. 17857 * 17858 * @return {Promise|any} If given an input, returns a promise that 17859 * is resolved or rejected when the batch is 17860 * processed. If given a thunk, returns the return 17861 * value of that thunk. 17862 */ 17863 add(inputOrThunk) { 17864 const id2 = ++lastId; 17865 pending.add(id2); 17866 const add = (input) => new Promise((resolve, reject) => { 17867 queue.push({ 17868 input, 17869 resolve, 17870 reject 17871 }); 17872 pending.delete(id2); 17873 }); 17874 if (typeof inputOrThunk === "function") { 17875 return Promise.resolve(inputOrThunk(add)).finally(() => { 17876 pending.delete(id2); 17877 }); 17878 } 17879 return add(inputOrThunk); 17880 }, 17881 /** 17882 * Runs the batch. This calls `batchProcessor` and resolves or rejects 17883 * all promises returned by `add()`. 17884 * 17885 * @return {Promise<boolean>} A promise that resolves to a boolean that is true 17886 * if the processor returned no errors. 17887 */ 17888 async run() { 17889 if (pending.size) { 17890 await new Promise((resolve) => { 17891 const unsubscribe = pending.subscribe(() => { 17892 if (!pending.size) { 17893 unsubscribe(); 17894 resolve(void 0); 17895 } 17896 }); 17897 }); 17898 } 17899 let results; 17900 try { 17901 results = await processor( 17902 queue.map(({ input }) => input) 17903 ); 17904 if (results.length !== queue.length) { 17905 throw new Error( 17906 "run: Array returned by processor must be same size as input array." 17907 ); 17908 } 17909 } catch (error) { 17910 for (const { reject } of queue) { 17911 reject(error); 17912 } 17913 throw error; 17914 } 17915 let isSuccess = true; 17916 results.forEach((result, key) => { 17917 const queueItem = queue[key]; 17918 if (result?.error) { 17919 queueItem?.reject(result.error); 17920 isSuccess = false; 17921 } else { 17922 queueItem?.resolve(result?.output ?? result); 17923 } 17924 }); 17925 queue = []; 17926 return isSuccess; 17927 } 17928 }; 17929 } 17930 var ObservableSet = class { 17931 constructor(...args2) { 17932 this.set = new Set(...args2); 17933 this.subscribers = /* @__PURE__ */ new Set(); 17934 } 17935 get size() { 17936 return this.set.size; 17937 } 17938 add(value) { 17939 this.set.add(value); 17940 this.subscribers.forEach((subscriber) => subscriber()); 17941 return this; 17942 } 17943 delete(value) { 17944 const isSuccess = this.set.delete(value); 17945 this.subscribers.forEach((subscriber) => subscriber()); 17946 return isSuccess; 17947 } 17948 subscribe(subscriber) { 17949 this.subscribers.add(subscriber); 17950 return () => { 17951 this.subscribers.delete(subscriber); 17952 }; 17953 } 17954 }; 17955 17956
17956// packages/core-data/build-module/actions.mjs 17957 function addTitleToAutoDraft(record) { 17958 return record.status === "auto-draft" ? { ...record, title: "" } : record; 17959 } 17960 function receiveUserQuery(queryID, users2) { 17961 return { 17962 type: "RECEIVE_USER_QUERY", 17963 users: Array.isArray(users2) ? users2 : [users2], 17964 queryID 17965 }; 17966 } 17967 function receiveCurrentUser(currentUser2) { 17968 return { 17969 type: "RECEIVE_CURRENT_USER", 17970 currentUser: currentUser2 17971 }; 17972 } 17973 function addEntities(entities2) { 17974 return { 17975 type: "ADD_ENTITIES", 17976 entities: entities2 17977 }; 17978 } 17979 function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) { 17980 if (kind === "postType") { 17981 records = Array.isArray(records) ? records.map(addTitleToAutoDraft) : addTitleToAutoDraft(records); 17982 } 17983 let action; 17984 if (query) { 17985 action = receiveQueriedItems(records, query, edits, meta); 17986 } else { 17987 action = receiveItems(records, edits, meta); 17988 } 17989 return { 17990 ...action, 17991 kind, 17992 name, 17993 invalidateCache 17994 }; 17995 } 17996 function receiveCurrentTheme(currentTheme2) { 17997 return { 17998 type: "RECEIVE_CURRENT_THEME", 17999 currentTheme: currentTheme2 18000 }; 18001 } 18002 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) { 18003 return { 18004 type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID", 18005 id: currentGlobalStylesId2 18006 }; 18007 } 18008 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) { 18009 return { 18010 type: "RECEIVE_THEME_GLOBAL_STYLES", 18011 stylesheet, 18012 globalStyles 18013 }; 18014 } 18015 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) { 18016 return { 18017 type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS", 18018 stylesheet, 18019 variations 18020 }; 18021 } 18022 function receiveThemeSupports() { 18023 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", { 18024 since: "5.9" 18025 }); 18026 return { 18027 type: "DO_NOTHING" 18028 }; 18029 } 18030 function receiveThemeGlobalStyleRevisions(currentId, revisions) { 18031 (0, import_deprecated3.default)( 18032 "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()", 18033 { 18034 since: "6.5.0", 18035 alternative: "wp.data.dispatch( 'core' ).receiveRevisions" 18036 } 18037 ); 18038 return { 18039 type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS", 18040 currentId, 18041 revisions 18042 }; 18043 } 18044 function receiveEmbedPreview(url, preview) { 18045 return { 18046 type: "RECEIVE_EMBED_PREVIEW", 18047 url, 18048 preview 18049 }; 18050 } 18051 var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 18052 logEntityDeprecation(kind, name, "deleteEntityRecord"); 18053 const configs = await resolveSelect2.getEntitiesConfig(kind); 18054 const entityConfig = configs.find( 18055 (config) => config.kind === kind && config.name === name 18056 ); 18057 let error; 18058 let deletedRecord = false; 18059 if (!entityConfig) { 18060 return; 18061 } 18062 const lock3 = await dispatch3.__unstableAcquireStoreLock( 18063 STORE_NAME, 18064 ["entities", "records", kind, name, recordId], 18065 { exclusive: true } 18066 ); 18067 try { 18068 dispatch3({ 18069 type: "DELETE_ENTITY_RECORD_START", 18070 kind, 18071 name, 18072 recordId 18073 }); 18074 let hasError = false; 18075 let { baseURL } = entityConfig; 18076 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) { 18077 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates"; 18078 } 18079 try { 18080 let path = `${baseURL}/${recordId}`; 18081 if (query) { 18082 path = (0, import_url3.addQueryArgs)(path, query); 18083 } 18084 deletedRecord = await __unstableFetch({ 18085 path, 18086 method: "DELETE" 18087 }); 18088 await dispatch3(removeItems(kind, name, recordId, true)); 18089 if (entityConfig.syncConfig) { 18090 const objectType = `${kind}/${name}`; 18091 const objectId = recordId; 18092 getSyncManager()?.unload(objectType, objectId); 18093 } 18094 } catch (_error) { 18095 hasError = true; 18096 error = _error; 18097 } 18098 dispatch3({ 18099 type: "DELETE_ENTITY_RECORD_FINISH", 18100 kind, 18101 name, 18102 recordId, 18103 error 18104 }); 18105 if (hasError && throwOnError) { 18106 throw error; 18107 } 18108 return deletedRecord; 18109 } finally { 18110 dispatch3.__unstableReleaseStoreLock(lock3); 18111 } 18112 }; 18113 var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select: select4, dispatch: dispatch3 }) => { 18114 logEntityDeprecation(kind, name, "editEntityRecord"); 18115 const entityConfig = select4.getEntityConfig(kind, name); 18116 if (!entityConfig) { 18117 throw new Error( 18118 `The entity being edited (${kind}, ${name}) does not have a loaded config.` 18119 ); 18120 } 18121 const { mergedEdits = {} } = entityConfig; 18122 const record = select4.getRawEntityRecord(kind, name, recordId); 18123 const editedRecord = select4.getEditedEntityRecord( 18124 kind, 18125 name, 18126 recordId 18127 ); 18128 const editsWithMerges = Object.keys(edits).reduce((acc, key) => { 18129 acc[key] = mergedEdits[key] ? { ...editedRecord[key], ...edits[key] } : edits[key]; 18130 return acc; 18131 }, {}); 18132 const edit = { 18133 kind, 18134 name, 18135 recordId, 18136 // Clear edits when they are equal to their persisted counterparts 18137 // so that the property is not considered dirty. 18138 edits: clearUnchangedEdits(editsWithMerges, record) 18139 }; 18140 if (entityConfig.syncConfig) { 18141 const objectType = `${kind}/${name}`; 18142 const objectId = recordId; 18143 const isNewUndoLevel = options.undoIgnore ? false : !options.isCached; 18144 const origin2 = options.undoIgnore ? LOCAL_UNDO_IGNORED_ORIGIN2 : LOCAL_EDITOR_ORIGIN2; 18145 getSyncManager()?.update( 18146 objectType, 18147 objectId, 18148 editsWithMerges, 18149 origin2, 18150 { isNewUndoLevel } 18151 ); 18152 } 18153 if (!options.undoIgnore) { 18154 select4.getUndoManager().addRecord( 18155 [ 18156 { 18157 id: { kind, name, recordId }, 18158 changes: Object.keys(edits).reduce((acc, key) => { 18159 acc[key] = { 18160 from: editedRecord[key], 18161 to: edits[key] 18162 }; 18163 return acc; 18164 }, {}) 18165 } 18166 ], 18167 options.isCached 18168 ); 18169 } 18170 dispatch3({ 18171 type: "EDIT_ENTITY_RECORD", 18172 ...edit 18173 }); 18174 }; 18175 var clearEntityRecordEdits = (kind, name, recordId) => ({ select: select4, dispatch: dispatch3 }) => { 18176 const entityConfig = select4.getEntityConfig(kind, name); 18177 logEntityDeprecation(kind, name, "clearEntityRecordEdits"); 18178 if (!entityConfig) { 18179 throw new Error( 18180 `The entity being edited (${kind}, ${name}) does not have a loaded config.` 18181 ); 18182 } 18183 const currentEdits = select4.getEntityRecordEdits( 18184 kind, 18185 name, 18186 recordId 18187 ); 18188 if (!currentEdits) { 18189 return; 18190 } 18191 const clearedEdits = Object.keys(currentEdits).reduce( 18192 (acc, key) => { 18193 acc[key] = void 0; 18194 return acc; 18195 }, 18196 {} 18197 ); 18198 dispatch3({ 18199 type: "EDIT_ENTITY_RECORD", 18200 kind, 18201 name, 18202 recordId, 18203 edits: clearedEdits 18204 }); 18205 };
18206 var undo = () => ({ select: select4, dispatch: dispatch3 }) => { 18207 const undoRecord = select4.getUndoManager().undo(); 18208 if (!undoRecord) { 18209 return; 18210 } 18211 dispatch3({ 18212 type: "UNDO", 18213 record: undoRecord 18214 }); 18215 }; 18216 var redo = () => ({ select: select4, dispatch: dispatch3 }) => { 18217 const redoRecord = select4.getUndoManager().redo(); 18218 if (!redoRecord) { 18219 return; 18220 } 18221 dispatch3({ 18222 type: "REDO", 18223 record: redoRecord 18224 }); 18225 }; 18226 var __unstableCreateUndoLevel = () => ({ select: select4 }) => { 18227 select4.getUndoManager().addRecord(); 18228 }; 18229 var saveEntityRecord = (kind, name, record, options = {}) => async ({ select: select4, resolveSelect: resolveSelect2, dispatch: dispatch3 }) => { 18230 const { 18231 isAutosave = false, 18232 __unstableFetch = import_api_fetch5.default, 18233 __unstableSkipSyncUpdate = false, 18234 throwOnError = false 18235 } = options; 18236 logEntityDeprecation(kind, name, "saveEntityRecord"); 18237 const configs = await resolveSelect2.getEntitiesConfig(kind); 18238 const entityConfig = configs.find( 18239 (config) => config.kind === kind && config.name === name 18240 ); 18241 if (!entityConfig) { 18242 return; 18243 } 18244 const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY; 18245 const recordId = record[entityIdKey]; 18246 const isNewRecord = !!entityIdKey && !recordId; 18247 const lock3 = await dispatch3.__unstableAcquireStoreLock( 18248 STORE_NAME, 18249 ["entities", "records", kind, name, recordId || v4_default()], 18250 { exclusive: true } 18251 ); 18252 try { 18253 for (const [key, value] of Object.entries(record)) { 18254 if (typeof value === "function") { 18255 const evaluatedValue = value( 18256 select4.getEditedEntityRecord(kind, name, recordId) 18257 ); 18258 dispatch3.editEntityRecord( 18259 kind, 18260 name, 18261 recordId, 18262 { 18263 [key]: evaluatedValue 18264 }, 18265 { undoIgnore: true } 18266 ); 18267 record[key] = evaluatedValue; 18268 } 18269 } 18270 dispatch3({ 18271 type: "SAVE_ENTITY_RECORD_START", 18272 kind, 18273 name, 18274 recordId, 18275 isAutosave 18276 }); 18277 let updatedRecord; 18278 let error; 18279 let hasError = false; 18280 let { baseURL } = entityConfig; 18281 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) { 18282 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates"; 18283 } 18284 try { 18285 const path = `${baseURL}${recordId ? "/" + recordId : ""}`; 18286 const persistedRecord = !isNewRecord ? select4.getRawEntityRecord(kind, name, recordId) : {}; 18287 if (isAutosave) { 18288 const merged = { ...persistedRecord, ...record }; 18289 const data = [ 18290 "title", 18291 "excerpt", 18292 "content", 18293 "meta" 18294 ].reduce( 18295 (acc, key) => { 18296 if (key in merged) { 18297 acc[key] = merged[key]; 18298 } 18299 return acc; 18300 }, 18301 { 18302 // Do not update the `status` if we have edited it when auto saving. 18303 // It's very important to let the user explicitly save this change, 18304 // because it can lead to unexpected results. An example would be to 18305 // have a draft post and change the status to publish. 18306 status: merged.status === "auto-draft" ? "draft" : void 0 18307 } 18308 ); 18309 updatedRecord = await __unstableFetch({ 18310 path: `${path}/autosaves`, 18311 method: "POST", 18312 data 18313 }); 18314 if (persistedRecord.id === updatedRecord.id) { 18315 let newRecord = { 18316 ...persistedRecord, 18317 ...data, 18318 ...updatedRecord 18319 }; 18320 newRecord = Object.keys(newRecord).reduce( 18321 (acc, key) => { 18322 if ([ 18323 "title", 18324 "excerpt", 18325 "content", 18326 "meta" 18327 ].includes(key)) { 18328 acc[key] = newRecord[key]; 18329 } else if (key === "status") { 18330 acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status; 18331 } else { 18332 acc[key] = persistedRecord[key]; 18333 } 18334 return acc; 18335 }, 18336 {} 18337 ); 18338 dispatch3.receiveEntityRecords( 18339 kind, 18340 name, 18341 newRecord, 18342 void 0, 18343 true 18344 ); 18345 } else { 18346 dispatch3.receiveAutosaves( 18347 persistedRecord.id, 18348 updatedRecord 18349 ); 18350 } 18351 } else { 18352 let edits = record; 18353 if (entityConfig.__unstablePrePersist) { 18354 edits = { 18355 ...edits, 18356 ...await entityConfig.__unstablePrePersist( 18357 persistedRecord, 18358 edits 18359 ) 18360 }; 18361 } 18362 updatedRecord = await __unstableFetch({ 18363 path, 18364 method: recordId ? "PUT" : "POST", 18365 data: edits 18366 }); 18367 dispatch3.receiveEntityRecords( 18368 kind, 18369 name, 18370 updatedRecord, 18371 void 0, 18372 true, 18373 edits 18374 ); 18375 if (entityConfig.syncConfig) { 18376 getSyncManager()?.update( 18377 `${kind}/${name}`, 18378 recordId, 18379 __unstableSkipSyncUpdate ? {} : updatedRecord, 18380 LOCAL_UNDO_IGNORED_ORIGIN2, 18381 { isSave: true } 18382 ); 18383 } 18384 } 18385 } catch (_error) { 18386 hasError = true; 18387 error = _error; 18388 } 18389 dispatch3({ 18390 type: "SAVE_ENTITY_RECORD_FINISH", 18391 kind, 18392 name, 18393 recordId, 18394 error, 18395 isAutosave 18396 }); 18397 if (hasError && throwOnError) { 18398 throw error; 18399 } 18400 return updatedRecord; 18401 } finally { 18402 dispatch3.__unstableReleaseStoreLock(lock3); 18403 } 18404 }; 18405 var __experimentalBatch = (requests) => async ({ dispatch: dispatch3 }) => { 18406 const batch = createBatch(); 18407 const api = { 18408 saveEntityRecord(kind, name, record, options) { 18409 return batch.add( 18410 (add) => dispatch3.saveEntityRecord(kind, name, record, { 18411 ...options, 18412 __unstableFetch: add 18413 }) 18414 ); 18415 }, 18416 saveEditedEntityRecord(kind, name, recordId, options) { 18417 return batch.add( 18418 (add) => dispatch3.saveEditedEntityRecord(kind, name, recordId, { 18419 ...options, 18420 __unstableFetch: add 18421 }) 18422 ); 18423 }, 18424 deleteEntityRecord(kind, name, recordId, query, options) { 18425 return batch.add( 18426 (add) => dispatch3.deleteEntityRecord(kind, name, recordId, query, { 18427 ...options, 18428 __unstableFetch: add 18429 }) 18430 ); 18431 } 18432 }; 18433 const resultPromises = requests.map((request) => request(api)); 18434 const [, ...results] = await Promise.all([ 18435 batch.run(), 18436 ...resultPromises 18437 ]); 18438 return results; 18439 }; 18440 var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 18441 logEntityDeprecation(kind, name, "saveEditedEntityRecord"); 18442 if (!select4.hasEditsForEntityRecord(kind, name, recordId)) { 18443 return; 18444 } 18445 const configs = await resolveSelect2.getEntitiesConfig(kind); 18446 const entityConfig = configs.find( 18447 (config) => config.kind === kind && config.name === name 18448 ); 18449 if (!entityConfig) { 18450 return; 18451 } 18452 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; 18453 const edits = select4.getEntityRecordNonTransientEdits( 18454 kind, 18455 name, 18456 recordId 18457 ); 18458 const record = { [entityIdKey]: recordId, ...edits }; 18459 return await dispatch3.saveEntityRecord(kind, name, record, options); 18460 }; 18461 var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 18462 logEntityDeprecation( 18463 kind, 18464 name, 18465 "__experimentalSaveSpecifiedEntityEdits" 18466 ); 18467 if (!select4.hasEditsForEntityRecord(kind, name, recordId)) { 18468 return; 18469 } 18470 const edits = select4.getEntityRecordNonTransientEdits( 18471 kind, 18472 name, 18473 recordId 18474 ); 18475 const editsToSave = {}; 18476 for (const item of itemsToSave) { 18477 setNestedValue(editsToSave, item, getNestedValue(edits, item)); 18478 } 18479 const configs = await resolveSelect2.getEntitiesConfig(kind); 18480 const entityConfig = configs.find( 18481 (config) => config.kind === kind && config.name === name 18482 ); 18483 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY; 18484 if (recordId) { 18485 editsToSave[entityIdKey] = recordId; 18486 } 18487 return await dispatch3.saveEntityRecord( 18488 kind, 18489 name, 18490 editsToSave, 18491 options 18492 ); 18493 };
18494 function receiveUploadPermissions(hasUploadPermissions) { 18495 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", { 18496 since: "5.9", 18497 alternative: "receiveUserPermission" 18498 }); 18499 return receiveUserPermission("create/media", hasUploadPermissions); 18500 } 18501 function receiveUserPermission(key, isAllowed) { 18502 return { 18503 type: "RECEIVE_USER_PERMISSION", 18504 key, 18505 isAllowed 18506 }; 18507 } 18508 function receiveUserPermissions(permissions) { 18509 return { 18510 type: "RECEIVE_USER_PERMISSIONS", 18511 permissions 18512 }; 18513 } 18514 function receiveAutosaves(postId, autosaves2) { 18515 return { 18516 type: "RECEIVE_AUTOSAVES", 18517 postId, 18518 autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2] 18519 }; 18520 } 18521 function receiveNavigationFallbackId(fallbackId) { 18522 return { 18523 type: "RECEIVE_NAVIGATION_FALLBACK_ID", 18524 fallbackId 18525 }; 18526 } 18527 function receiveDefaultTemplateId(query, templateId) { 18528 return { 18529 type: "RECEIVE_DEFAULT_TEMPLATE", 18530 query, 18531 templateId 18532 }; 18533 } 18534 var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 18535 logEntityDeprecation(kind, name, "receiveRevisions"); 18536 const configs = await resolveSelect2.getEntitiesConfig(kind); 18537 const entityConfig = configs.find( 18538 (config) => config.kind === kind && config.name === name 18539 ); 18540 const key = entityConfig?.revisionKey ?? DEFAULT_ENTITY_KEY; 18541 dispatch3({ 18542 type: "RECEIVE_ITEM_REVISIONS", 18543 key, 18544 items: records, 18545 recordKey, 18546 meta, 18547 query, 18548 kind, 18549 name, 18550 invalidateCache 18551 }); 18552 }; 18553 18554
18554// packages/core-data/build-module/private-actions.mjs 18555 var private_actions_exports = {}; 18556 __export(private_actions_exports, { 18557 __unstableNotifySyncUndoManagerChange: () => __unstableNotifySyncUndoManagerChange, 18558 editMediaEntity: () => editMediaEntity, 18559 receiveEditorAssets: () => receiveEditorAssets, 18560 receiveEditorSettings: () => receiveEditorSettings, 18561 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta, 18562 receiveViewConfig: () => receiveViewConfig, 18563 setCollaborationSupported: () => setCollaborationSupported, 18564 setSyncConnectionStatus: () => setSyncConnectionStatus 18565 }); 18566 var import_api_fetch6 = __toESM(require_api_fetch(), 1); 18567 function receiveRegisteredPostMeta(postType, registeredPostMeta2) { 18568 return { 18569 type: "RECEIVE_REGISTERED_POST_META", 18570 postType, 18571 registeredPostMeta: registeredPostMeta2 18572 }; 18573 } 18574 var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch6.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 18575 if (!recordId) { 18576 return; 18577 } 18578 const kind = "postType"; 18579 const name = "attachment"; 18580 const configs = await resolveSelect2.getEntitiesConfig(kind); 18581 const entityConfig = configs.find( 18582 (config) => config.kind === kind && config.name === name 18583 ); 18584 if (!entityConfig) { 18585 return; 18586 } 18587 const lock3 = await dispatch3.__unstableAcquireStoreLock( 18588 STORE_NAME, 18589 ["entities", "records", kind, name, recordId], 18590 { exclusive: true } 18591 ); 18592 let updatedRecord; 18593 let error; 18594 let hasError = false; 18595 try { 18596 dispatch3({ 18597 type: "SAVE_ENTITY_RECORD_START", 18598 kind, 18599 name, 18600 recordId 18601 }); 18602 try { 18603 const path = `${entityConfig.baseURL}/${recordId}/edit`; 18604 const newRecord = await __unstableFetch({ 18605 path, 18606 method: "POST", 18607 data: { 18608 ...edits 18609 } 18610 }); 18611 if (newRecord) { 18612 dispatch3.receiveEntityRecords( 18613 kind, 18614 name, 18615 newRecord, 18616 void 0, 18617 true, 18618 void 0, 18619 void 0 18620 ); 18621 updatedRecord = newRecord; 18622 } 18623 } catch (e) { 18624 error = e; 18625 hasError = true; 18626 } 18627 dispatch3({ 18628 type: "SAVE_ENTITY_RECORD_FINISH", 18629 kind, 18630 name, 18631 recordId, 18632 error 18633 }); 18634 if (hasError && throwOnError) { 18635 throw error; 18636 } 18637 return updatedRecord; 18638 } finally { 18639 dispatch3.__unstableReleaseStoreLock(lock3); 18640 } 18641 }; 18642 function receiveEditorSettings(settings) { 18643 return { 18644 type: "RECEIVE_EDITOR_SETTINGS", 18645 settings 18646 }; 18647 } 18648 function receiveEditorAssets(assets) { 18649 return { 18650 type: "RECEIVE_EDITOR_ASSETS", 18651 assets 18652 }; 18653 } 18654 var setCollaborationSupported = (supported) => ({ dispatch: dispatch3 }) => { 18655 dispatch3({ type: "SET_COLLABORATION_SUPPORTED", supported }); 18656 if (!supported && hasSyncManager()) { 18657 getSyncManager().unloadAll(); 18658 dispatch3.__unstableNotifySyncUndoManagerChange({ 18659 hasUndo: false, 18660 hasRedo: false 18661 }); 18662 } 18663 }; 18664 function receiveViewConfig(kind, name, config) { 18665 return { 18666 type: "RECEIVE_VIEW_CONFIG", 18667 kind, 18668 name, 18669 config 18670 }; 18671 } 18672 function __unstableNotifySyncUndoManagerChange(state) { 18673 return { 18674 type: "SYNC_UNDO_MANAGER_CHANGE", 18675 ...state 18676 }; 18677 } 18678 function setSyncConnectionStatus(kind, name, key, status) { 18679 if (!status) { 18680 return { 18681 type: "CLEAR_SYNC_CONNECTION_STATUS", 18682 kind, 18683 name, 18684 key 18685 }; 18686 } 18687 return { 18688 type: "SET_SYNC_CONNECTION_STATUS", 18689 kind, 18690 name, 18691 key, 18692 status 18693 }; 18694 } 18695 18696
18696// packages/core-data/build-module/resolvers.mjs 18697 var resolvers_exports = {}; 18698 __export(resolvers_exports, { 18699 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2, 18700 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2, 18701 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2, 18702 canUser: () => canUser2, 18703 canUserEditEntityRecord: () => canUserEditEntityRecord2, 18704 getAuthors: () => getAuthors2, 18705 getAutosave: () => getAutosave2, 18706 getAutosaves: () => getAutosaves2, 18707 getBlockPatternCategories: () => getBlockPatternCategories2, 18708 getBlockPatterns: () => getBlockPatterns2, 18709 getCurrentTheme: () => getCurrentTheme2, 18710 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2, 18711 getCurrentUser: () => getCurrentUser2, 18712 getDefaultTemplateId: () => getDefaultTemplateId2, 18713 getEditedEntityRecord: () => getEditedEntityRecord2, 18714 getEditorAssets: () => getEditorAssets2, 18715 getEditorSettings: () => getEditorSettings2, 18716 getEmbedPreview: () => getEmbedPreview2, 18717 getEntitiesConfig: () => getEntitiesConfig2, 18718 getEntityRecord: () => getEntityRecord2, 18719 getEntityRecords: () => getEntityRecords2, 18720 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2, 18721 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2, 18722 getNavigationFallbackId: () => getNavigationFallbackId2, 18723 getRawEntityRecord: () => getRawEntityRecord2, 18724 getRegisteredPostMeta: () => getRegisteredPostMeta2, 18725 getRevision: () => getRevision2, 18726 getRevisions: () => getRevisions2, 18727 getThemeSupports: () => getThemeSupports2, 18728 getUserPatternCategories: () => getUserPatternCategories2, 18729 getViewConfig: () => getViewConfig2 18730 }); 18731 var import_url6 = __toESM(require_url(), 1); 18732 var import_html_entities2 = __toESM(require_html_entities(), 1); 18733 var import_api_fetch10 = __toESM(require_api_fetch(), 1); 18734 18735
18735// packages/core-data/build-module/fetch/index.mjs 18736 var import_api_fetch9 = __toESM(require_api_fetch(), 1); 18737 18738
18738// packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs 18739 var import_api_fetch7 = __toESM(require_api_fetch(), 1); 18740 var import_url4 = __toESM(require_url(), 1); 18741 var import_html_entities = __toESM(require_html_entities(), 1); 18742 var import_i18n2 = __toESM(require_i18n(), 1); 18743 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) { 18744 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? { 18745 ...searchOptions, 18746 ...searchOptions.initialSuggestionsSearchOptions 18747 } : searchOptions; 18748 const { 18749 type, 18750 subtype, 18751 page, 18752 perPage = searchOptions.isInitialSuggestions ? 3 : 20 18753 } = searchOptionsToUse; 18754 const { disablePostFormats = false } = editorSettings2; 18755 const queries2 = []; 18756 if (!type || type === "post") { 18757 queries2.push( 18758 (0, import_api_fetch7.default)({ 18759 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 18760 search, 18761 page, 18762 per_page: perPage, 18763 type: "post", 18764 subtype 18765 }) 18766 }).then((results2) => { 18767 return results2.map((result) => { 18768 return { 18769 id: result.id, 18770 url: result.url, 18771 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"), 18772 type: result.subtype || result.type, 18773 kind: "post-type" 18774 }; 18775 }); 18776 }).catch(() => []) 18777 // Fail by returning no results. 18778 ); 18779 } 18780 if (!type || type === "term") { 18781 queries2.push( 18782 (0, import_api_fetch7.default)({ 18783 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 18784 search, 18785 page, 18786 per_page: perPage, 18787 type: "term", 18788 subtype 18789 }) 18790 }).then((results2) => { 18791 return results2.map((result) => { 18792 return { 18793 id: result.id, 18794 url: result.url, 18795 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"), 18796 type: result.subtype || result.type, 18797 kind: "taxonomy" 18798 }; 18799 }); 18800 }).catch(() => []) 18801 // Fail by returning no results. 18802 ); 18803 } 18804 if (!disablePostFormats && (!type || type === "post-format")) { 18805 queries2.push( 18806 (0, import_api_fetch7.default)({ 18807 path: (0, import_url4.addQueryArgs)("/wp/v2/search", { 18808 search, 18809 page, 18810 per_page: perPage, 18811 type: "post-format", 18812 subtype 18813 }) 18814 }).then((results2) => { 18815 return results2.map((result) => { 18816 return { 18817 id: result.id, 18818 url: result.url, 18819 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"), 18820 type: result.subtype || result.type, 18821 kind: "taxonomy" 18822 }; 18823 }); 18824 }).catch(() => []) 18825 // Fail by returning no results. 18826 ); 18827 } 18828 if (!type || type === "attachment") { 18829 queries2.push( 18830 (0, import_api_fetch7.default)({ 18831 path: (0, import_url4.addQueryArgs)("/wp/v2/media", { 18832 search, 18833 page, 18834 per_page: perPage 18835 }) 18836 }).then((results2) => { 18837 return results2.map((result) => { 18838 return { 18839 id: result.id, 18840 url: result.source_url, 18841 title: (0, import_html_entities.decodeEntities)(result.title.rendered || "") || (0, import_i18n2.__)("(no title)"), 18842 type: result.type, 18843 kind: "media" 18844 }; 18845 }); 18846 }).catch(() => []) 18847 // Fail by returning no results. 18848 ); 18849 } 18850 const responses = await Promise.all(queries2); 18851 let results = responses.flat(); 18852 results = results.filter((result) => !!result.id); 18853 results = sortResults(results, search); 18854 results = results.slice(0, perPage); 18855 return results; 18856 } 18857 function sortResults(results, search) { 18858 const searchTokens = tokenize2(search); 18859 const scores = {}; 18860 for (const result of results) { 18861 if (result.title) { 18862 const titleTokens = tokenize2(result.title); 18863 const exactMatchingTokens = titleTokens.filter( 18864 (titleToken) => searchTokens.some( 18865 (searchToken) => titleToken === searchToken 18866 ) 18867 ); 18868 const subMatchingTokens = titleTokens.filter( 18869 (titleToken) => searchTokens.some( 18870 (searchToken) => titleToken !== searchToken && titleToken.includes(searchToken) 18871 ) 18872 ); 18873 const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10; 18874 const subMatchScore = subMatchingTokens.length / titleTokens.length; 18875 scores[result.id] = exactMatchScore + subMatchScore; 18876 } else { 18877 scores[result.id] = 0; 18878 } 18879 } 18880 return results.sort((a, b) => scores[b.id] - scores[a.id]); 18881 } 18882 function tokenize2(text2) { 18883 return text2.toLowerCase().match(/[\p{L}\p{N}]+/gu) || []; 18884 } 18885 18886
18886// packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs 18887 var import_api_fetch8 = __toESM(require_api_fetch(), 1); 18888 var import_url5 = __toESM(require_url(), 1); 18889 var CACHE = /* @__PURE__ */ new Map(); 18890 var fetchUrlData = async (url, options = {}) => { 18891 const endpoint = "/wp-block-editor/v1/url-details"; 18892 const args2 = { 18893 url: (0, import_url5.prependHTTP)(url) 18894 }; 18895 if (!(0, import_url5.isURL)(url)) { 18896 return Promise.reject(`${url} is not a valid URL.`); 18897 } 18898 const protocol = (0, import_url5.getProtocol)(url); 18899 if (!protocol || !(0, import_url5.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) { 18900 return Promise.reject( 18901 `${url} does not have a valid protocol. URLs must be "http" based` 18902 ); 18903 } 18904 if (CACHE.has(url)) { 18905 return CACHE.get(url); 18906 } 18907 return (0, import_api_fetch8.default)({ 18908 path: (0, import_url5.addQueryArgs)(endpoint, args2), 18909 ...options 18910 }).then((res) => { 18911 CACHE.set(url, res); 18912 return res; 18913 }); 18914 }; 18915 var experimental_fetch_url_data_default = fetchUrlData; 18916 18917
18917// packages/core-data/build-module/fetch/index.mjs 18918 async function fetchBlockPatterns() { 18919 const restPatterns = await (0, import_api_fetch9.default)({ 18920 path: "/wp/v2/block-patterns/patterns" 18921 }); 18922 if (!restPatterns) { 18923 return []; 18924 } 18925 return restPatterns.map( 18926 (pattern) => Object.fromEntries( 18927 Object.entries(pattern).map(([key, value]) => [ 18928 camelCase(key), 18929 value 18930 ]) 18931 ) 18932 ); 18933 } 18934 18935
18935// packages/core-data/build-module/parsed-blocks-cache.mjs 18936 var parsedBlocksCache = /* @__PURE__ */ new Map(); 18937 function getCacheKey(kind, name, id2) { 18938 return `${kind}:${name}:${id2}`; 18939 } 18940 18941
18941// packages/core-data/build-module/resolvers.mjs 18942 var getAuthors2 = (query) => async ({ dispatch: dispatch3 }) => { 18943 const path = (0, import_url6.addQueryArgs)( 18944 "/wp/v2/users/?who=authors&per_page=100", 18945 query 18946 ); 18947 const users2 = await (0, import_api_fetch10.default)({ path }); 18948 dispatch3.receiveUserQuery(path, users2); 18949 }; 18950 var getCurrentUser2 = () => async ({ dispatch: dispatch3 }) => { 18951 const currentUser2 = await (0, import_api_fetch10.default)({ path: "/wp/v2/users/me" }); 18952 dispatch3.receiveCurrentUser(currentUser2); 18953 }; 18954 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select4, dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => { 18955 const configs = await resolveSelect2.getEntitiesConfig(kind); 18956 const entityConfig = configs.find( 18957 (config) => config.name === name && config.kind === kind 18958 ); 18959 if (!entityConfig) { 18960 return; 18961 } 18962 const lock3 = await dispatch3.__unstableAcquireStoreLock( 18963 STORE_NAME, 18964 ["entities", "records", kind, name, key], 18965 { exclusive: false } 18966 ); 18967 try { 18968 if (query !== void 0 && query._fields) { 18969 query = { 18970 ...query, 18971 _fields: [ 18972 .../* @__PURE__ */ new Set([ 18973 ...get_normalized_comma_separable_default(query._fields) || [], 18974 entityConfig.key || DEFAULT_ENTITY_KEY 18975 ]) 18976 ].join() 18977 }; 18978 } 18979 if (query !== void 0 && query._fields) { 18980 const hasRecord = select4.hasEntityRecord( 18981 kind, 18982 name, 18983 key, 18984 query 18985 ); 18986 if (hasRecord) { 18987 return; 18988 } 18989 } 18990 let { baseURL } = entityConfig; 18991 if (kind === "postType" && name === "wp_template" && (key && typeof key === "string" && !/^\d+$/.test(key) || !window?.__experimentalTemplateActivate)) { 18992 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates"; 18993 } 18994 const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), { 18995 ...entityConfig.baseURLParams, 18996 ...query 18997 }); 18998 const response = await (0, import_api_fetch10.default)({ path, parse: false }); 18999 const record = await response.json(); 19000 const permissions = getUserPermissionsFromAllowHeader( 19001 response.headers?.get("allow") 19002 ); 19003 const canUserResolutionsArgs = []; 19004 const receiveUserPermissionArgs = {}; 19005 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19006 receiveUserPermissionArgs[getUserPermissionCacheKey(action, { 19007 kind, 19008 name, 19009 id: key 19010 })] = permissions[action]; 19011 canUserResolutionsArgs.push([ 19012 action, 19013 { kind, name, id: key } 19014 ]); 19015 } 19016 if (entityConfig.syncConfig && isNumericID(key) && !query) { 19017 const objectType = `${kind}/${name}`; 19018 const objectId = key; 19019 const recordWithTransients = { ...record }; 19020 Object.entries(entityConfig.transientEdits ?? {}).filter( 19021 ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read 19022 ).forEach(([propName, transientConfig]) => { 19023 recordWithTransients[propName] = transientConfig.read(recordWithTransients); 19024 }); 19025 if (recordWithTransients.blocks && typeof recordWithTransients.content?.raw === "string") { 19026 parsedBlocksCache.set(getCacheKey(kind, name, key), { 19027 content: recordWithTransients.content.raw, 19028 blocks: recordWithTransients.blocks 19029 }); 19030 } 19031 const syncManager2 = select4?.isCollaborationSupported?.() === false ? void 0 : getSyncManager(); 19032 void syncManager2?.load( 19033 entityConfig.syncConfig, 19034 objectType, 19035 objectId, 19036 recordWithTransients, 19037 { 19038 // Handle edits sourced from the sync manager. 19039 editRecord: (edits, options = {}) => { 19040 if (!Object.keys(edits).length) { 19041 return; 19042 } 19043 dispatch3({ 19044 type: "EDIT_ENTITY_RECORD", 19045 kind, 19046 name, 19047 recordId: key, 19048 edits, 19049 meta: { 19050 undo: void 0 19051 }, 19052 options 19053 }); 19054 }, 19055 // Get the current entity record (with edits) 19056 getEditedRecord: async () => await resolveSelect2.getEditedEntityRecord( 19057 kind, 19058 name, 19059 key 19060 ), 19061 // Handle sync connection status changes. 19062 onStatusChange: (status) => { 19063 dispatch3.setSyncConnectionStatus( 19064 kind, 19065 name, 19066 key, 19067 status 19068 ); 19069 }, 19070 // Refetch the current entity record from the database. 19071 refetchRecord: async () => { 19072 dispatch3.receiveEntityRecords( 19073 kind, 19074 name, 19075 await (0, import_api_fetch10.default)({ path, parse: true }), 19076 query 19077 ); 19078 }, 19079 // Persist the CRDT document. 19080 // 19081 // TODO: Currently, persisted CRDT documents are stored in post meta. 19082 // This effectively means that only post entities support CRDT 19083 // persistence. As we add support for syncing additional entity, 19084 // we'll need to revisit where persisted CRDT documents are stored.
19085 persistCRDTDoc: () => { 19086 if (!entityConfig.syncConfig?.supportsPersistence) { 19087 return; 19088 } 19089 return resolveSelect2.getEditedEntityRecord(kind, name, key).then(async (editedRecord) => { 19090 const { meta, status } = editedRecord; 19091 if ("auto-draft" === status || !meta) { 19092 return; 19093 } 19094 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY; 19095 const entityId = editedRecord[entityIdKey]; 19096 await saveCRDTDoc( 19097 `${kind}/${name}`, 19098 entityId 19099 ); 19100 }); 19101 }, 19102 addUndoMeta: (ydoc, meta) => { 19103 const selectionHistory = getSelectionHistory(ydoc); 19104 if (selectionHistory) { 19105 meta.set( 19106 "selectionHistory", 19107 selectionHistory 19108 ); 19109 } 19110 }, 19111 onUndoStackChange: (undoState) => { 19112 dispatch3.__unstableNotifySyncUndoManagerChange( 19113 undoState 19114 ); 19115 }, 19116 restoreUndoMeta: (ydoc, meta) => { 19117 const selectionHistory = meta.get("selectionHistory"); 19118 if (selectionHistory) { 19119 setTimeout(() => { 19120 restoreSelection(selectionHistory, ydoc); 19121 }, 0); 19122 } 19123 } 19124 } 19125 ); 19126 } 19127 registry.batch(() => { 19128 dispatch3.receiveEntityRecords(kind, name, record, query); 19129 dispatch3.receiveUserPermissions(receiveUserPermissionArgs); 19130 dispatch3.finishResolutions("canUser", canUserResolutionsArgs); 19131 }); 19132 } finally { 19133 dispatch3.__unstableReleaseStoreLock(lock3); 19134 } 19135 }; 19136 getEntityRecord2.shouldInvalidate = (action, kind, name) => { 19137 return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of 19138 // knowing whether it's an update or fetch. Only an update would 19139 // have persistedEdits. 19140 action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template"; 19141 }; 19142 var getRawEntityRecord2 = forward_resolver_default("getEntityRecord"); 19143 var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord"); 19144 var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => { 19145 const configs = await resolveSelect2.getEntitiesConfig(kind); 19146 const entityConfig = configs.find( 19147 (config) => config.name === name && config.kind === kind 19148 ); 19149 if (!entityConfig) { 19150 return; 19151 } 19152 const lock3 = await dispatch3.__unstableAcquireStoreLock( 19153 STORE_NAME, 19154 ["entities", "records", kind, name], 19155 { exclusive: false } 19156 ); 19157 const rawQuery = { ...query }; 19158 const key = entityConfig.key || DEFAULT_ENTITY_KEY; 19159 function getResolutionsArgs(records, recordsQuery) { 19160 const normalizedQuery = normalizeQueryForResolution(recordsQuery); 19161 return records.filter((record) => record?.[key]).map((record) => [ 19162 kind, 19163 name, 19164 record[key], 19165 normalizedQuery 19166 ]); 19167 } 19168 try { 19169 if (query._fields) { 19170 query = { 19171 ...query, 19172 _fields: [ 19173 .../* @__PURE__ */ new Set([ 19174 ...get_normalized_comma_separable_default(query._fields) || [], 19175 key 19176 ]) 19177 ].join() 19178 }; 19179 } 19180 let { baseURL } = entityConfig; 19181 const { combinedTemplates = true } = query; 19182 if (kind === "postType" && name === "wp_template" && combinedTemplates) { 19183 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates"; 19184 } 19185 const path = (0, import_url6.addQueryArgs)(baseURL, { 19186 ...entityConfig.baseURLParams, 19187 ...query 19188 }); 19189 let records = [], meta; 19190 if (entityConfig.supportsPagination && query.per_page !== -1) { 19191 const response = await (0, import_api_fetch10.default)({ path, parse: false }); 19192 records = Object.values(await response.json()); 19193 meta = { 19194 totalItems: parseInt( 19195 response.headers.get("X-WP-Total") 19196 ), 19197 totalPages: parseInt( 19198 response.headers.get("X-WP-TotalPages") 19199 ) 19200 }; 19201 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) { 19202 let page = 1; 19203 let totalPages; 19204 do { 19205 const response = await (0, import_api_fetch10.default)({ 19206 path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }), 19207 parse: false 19208 }); 19209 const pageRecords = Object.values(await response.json()); 19210 totalPages = parseInt( 19211 response.headers.get("X-WP-TotalPages") 19212 ); 19213 if (!meta) { 19214 meta = { 19215 totalItems: parseInt( 19216 response.headers.get("X-WP-Total") 19217 ), 19218 totalPages: 1 19219 }; 19220 } 19221 records.push(...pageRecords); 19222 registry.batch(() => { 19223 dispatch3.receiveEntityRecords( 19224 kind, 19225 name, 19226 records, 19227 query, 19228 false, 19229 void 0, 19230 meta 19231 ); 19232 dispatch3.finishResolutions( 19233 "getEntityRecord", 19234 getResolutionsArgs(pageRecords, rawQuery) 19235 ); 19236 }); 19237 page++; 19238 } while (page <= totalPages); 19239 } else { 19240 records = Object.values(await (0, import_api_fetch10.default)({ path })); 19241 meta = { 19242 totalItems: records.length, 19243 totalPages: 1 19244 }; 19245 } 19246 if (entityConfig.syncConfig && -1 === query.per_page) { 19247 const objectType = `${kind}/${name}`; 19248 getSyncManager()?.loadCollection( 19249 entityConfig.syncConfig, 19250 objectType, 19251 { 19252 onStatusChange: (status) => { 19253 dispatch3.setSyncConnectionStatus( 19254 kind, 19255 name, 19256 null, 19257 status 19258 ); 19259 }, 19260 refetchRecords: async () => { 19261 dispatch3.receiveEntityRecords( 19262 kind, 19263 name, 19264 await (0, import_api_fetch10.default)({ path, parse: true }), 19265 query 19266 ); 19267 } 19268 } 19269 ); 19270 } 19271 if (query._fields) { 19272 records = records.map((record) => { 19273 query._fields.split(",").forEach((field) => { 19274 if (!record.hasOwnProperty(field)) { 19275 record[field] = void 0; 19276 } 19277 }); 19278 return record; 19279 }); 19280 } 19281 registry.batch(() => { 19282 dispatch3.receiveEntityRecords( 19283 kind, 19284 name, 19285 records, 19286 query, 19287 false, 19288 void 0, 19289 meta 19290 ); 19291 const targetHints = records.filter( 19292 (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow 19293 ).map((record) => ({ 19294 id: record[key], 19295 permissions: getUserPermissionsFromAllowHeader( 19296 record._links.self[0].targetHints.allow 19297 ) 19298 })); 19299 const canUserResolutionsArgs = []; 19300 const receiveUserPermissionArgs = {}; 19301 for (const targetHint of targetHints) { 19302 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19303 canUserResolutionsArgs.push([ 19304 action, 19305 { kind, name, id: targetHint.id } 19306 ]); 19307 receiveUserPermissionArgs[getUserPermissionCacheKey(action, { 19308 kind, 19309 name, 19310 id: targetHint.id 19311 })] = targetHint.permissions[action]; 19312 } 19313 } 19314 if (targetHints.length > 0) { 19315 dispatch3.receiveUserPermissions( 19316 receiveUserPermissionArgs 19317 ); 19318 dispatch3.finishResolutions( 19319 "canUser", 19320 canUserResolutionsArgs 19321 ); 19322 } 19323 dispatch3.finishResolutions( 19324 "getEntityRecord", 19325 getResolutionsArgs(records, rawQuery) 19326 ); 19327 dispatch3.__unstableReleaseStoreLock(lock3); 19328 }); 19329 } catch { 19330 dispatch3.__unstableReleaseStoreLock(lock3); 19331 } 19332 }; 19333 getEntityRecords2.shouldInvalidate = (action, kind, name) => { 19334 return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name; 19335 }; 19336 var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords"); 19337 var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords"); 19338 var getCurrentTheme2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19339 const activeThemes = await resolveSelect2.getEntityRecords( 19340 "root", 19341 "theme", 19342 { status: "active" } 19343 ); 19344 dispatch3.receiveCurrentTheme(activeThemes[0]); 19345 }; 19346 var getThemeSupports2 = forward_resolver_default("getCurrentTheme"); 19347 var getEmbedPreview2 = (url) => async ({ dispatch: dispatch3 }) => { 19348 try { 19349 const embedProxyResponse = await (0, import_api_fetch10.default)({ 19350 path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url }) 19351 }); 19352 dispatch3.receiveEmbedPreview(url, embedProxyResponse); 19353 } catch { 19354 dispatch3.receiveEmbedPreview(url, false); 19355 } 19356 }; 19357 var canUser2 = (requestedAction, resource, id2) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => { 19358 if (!ALLOWED_RESOURCE_ACTIONS.includes(requestedAction)) { 19359 throw new Error(`'${requestedAction}' is not a valid action.`); 19360 } 19361 const { hasStartedResolution } = registry.select(STORE_NAME); 19362 for (const relatedAction of ALLOWED_RESOURCE_ACTIONS) { 19363 if (relatedAction === requestedAction) { 19364 continue; 19365 } 19366 const isAlreadyResolving = hasStartedResolution("canUser", [ 19367 relatedAction, 19368 resource, 19369 id2 19370 ]); 19371 if (isAlreadyResolving) { 19372 return; 19373 } 19374 } 19375 let resourcePath = null; 19376 if (typeof resource === "object") { 19377 if (!resource.kind || !resource.name) {
19378 throw new Error("The entity resource object is not valid."); 19379 } 19380 const configs = await resolveSelect2.getEntitiesConfig( 19381 resource.kind 19382 ); 19383 const entityConfig = configs.find( 19384 (config) => config.name === resource.name && config.kind === resource.kind 19385 ); 19386 if (!entityConfig) { 19387 return; 19388 } 19389 resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : ""); 19390 } else { 19391 resourcePath = `/wp/v2/${resource}` + (id2 ? "/" + id2 : ""); 19392 } 19393 let response; 19394 try { 19395 response = await (0, import_api_fetch10.default)({ 19396 path: resourcePath, 19397 method: "OPTIONS", 19398 parse: false 19399 }); 19400 } catch { 19401 return; 19402 } 19403 const permissions = getUserPermissionsFromAllowHeader( 19404 response.headers?.get("allow") 19405 ); 19406 const receiveUserPermissionArgs = {}; 19407 const canUserResolutionsArgs = []; 19408 for (const action of ALLOWED_RESOURCE_ACTIONS) { 19409 receiveUserPermissionArgs[getUserPermissionCacheKey(action, resource, id2)] = permissions[action]; 19410 if (action !== requestedAction) { 19411 canUserResolutionsArgs.push([action, resource, id2]); 19412 } 19413 } 19414 registry.batch(() => { 19415 dispatch3.receiveUserPermissions(receiveUserPermissionArgs); 19416 dispatch3.finishResolutions("canUser", canUserResolutionsArgs); 19417 }); 19418 }; 19419 var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ dispatch: dispatch3 }) => { 19420 await dispatch3(canUser2("update", { kind, name, id: recordId })); 19421 }; 19422 var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19423 const { 19424 rest_base: restBase, 19425 rest_namespace: restNamespace = "wp/v2", 19426 supports 19427 } = await resolveSelect2.getPostType(postType); 19428 if (!supports?.autosave) { 19429 return; 19430 } 19431 const autosaves2 = await (0, import_api_fetch10.default)({ 19432 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit` 19433 }); 19434 if (autosaves2 && autosaves2.length) { 19435 dispatch3.receiveAutosaves(postId, autosaves2); 19436 } 19437 }; 19438 var getAutosave2 = (postType, postId) => async ({ resolveSelect: resolveSelect2 }) => { 19439 await resolveSelect2.getAutosaves(postType, postId); 19440 }; 19441 var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19442 const activeThemes = await resolveSelect2.getEntityRecords( 19443 "root", 19444 "theme", 19445 { status: "active" } 19446 ); 19447 const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href; 19448 if (!globalStylesURL) { 19449 return; 19450 } 19451 const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/); 19452 const id2 = matches ? Number(matches[1]) : null; 19453 if (id2) { 19454 dispatch3.__experimentalReceiveCurrentGlobalStylesId(id2); 19455 } 19456 }; 19457 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => { 19458 const currentTheme2 = await resolveSelect2.getCurrentTheme(); 19459 const themeGlobalStyles = await (0, import_api_fetch10.default)({ 19460 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}?context=view` 19461 }); 19462 dispatch3.__experimentalReceiveThemeBaseGlobalStyles( 19463 currentTheme2.stylesheet, 19464 themeGlobalStyles 19465 ); 19466 }; 19467 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => { 19468 const currentTheme2 = await resolveSelect2.getCurrentTheme(); 19469 const variations = await (0, import_api_fetch10.default)({ 19470 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}/variations?context=view` 19471 }); 19472 dispatch3.__experimentalReceiveThemeGlobalStyleVariations( 19473 currentTheme2.stylesheet, 19474 variations 19475 ); 19476 }; 19477 var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => { 19478 const globalStylesId = await resolveSelect2.__experimentalGetCurrentGlobalStylesId(); 19479 const record = globalStylesId ? await resolveSelect2.getEntityRecord( 19480 "root", 19481 "globalStyles", 19482 globalStylesId 19483 ) : void 0; 19484 const revisionsURL = record?._links?.["version-history"]?.[0]?.href; 19485 if (revisionsURL) { 19486 const resetRevisions = await (0, import_api_fetch10.default)({ 19487 url: revisionsURL 19488 }); 19489 const revisions = resetRevisions?.map( 19490 (revision) => Object.fromEntries( 19491 Object.entries(revision).map(([key, value]) => [ 19492 camelCase(key), 19493 value 19494 ]) 19495 ) 19496 ); 19497 dispatch3.receiveThemeGlobalStyleRevisions( 19498 globalStylesId, 19499 revisions 19500 ); 19501 } 19502 }; 19503 getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => { 19504 return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles"; 19505 }; 19506 var getBlockPatterns2 = () => async ({ dispatch: dispatch3 }) => { 19507 const patterns = await fetchBlockPatterns(); 19508 dispatch3({ type: "RECEIVE_BLOCK_PATTERNS", patterns }); 19509 }; 19510 var getBlockPatternCategories2 = () => async ({ dispatch: dispatch3 }) => { 19511 const categories = await (0, import_api_fetch10.default)({ 19512 path: "/wp/v2/block-patterns/categories" 19513 }); 19514 dispatch3({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories }); 19515 }; 19516 var getUserPatternCategories2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19517 const patternCategories = await resolveSelect2.getEntityRecords( 19518 "taxonomy", 19519 "wp_pattern_category", 19520 { 19521 per_page: -1, 19522 _fields: "id,name,description,slug", 19523 context: "view" 19524 } 19525 ); 19526 const mappedPatternCategories = patternCategories?.map((userCategory) => ({ 19527 ...userCategory, 19528 label: (0, import_html_entities2.decodeEntities)(userCategory.name), 19529 name: userCategory.slug 19530 })) || []; 19531 dispatch3({ 19532 type: "RECEIVE_USER_PATTERN_CATEGORIES", 19533 patternCategories: mappedPatternCategories 19534 }); 19535 }; 19536 var getNavigationFallbackId2 = () => async ({ dispatch: dispatch3, select: select4, registry }) => { 19537 const fallback = await (0, import_api_fetch10.default)({ 19538 path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", { 19539 _embed: true 19540 }) 19541 }); 19542 const record = fallback?._embedded?.self; 19543 registry.batch(() => { 19544 dispatch3.receiveNavigationFallbackId(fallback?.id); 19545 if (!record) { 19546 return; 19547 } 19548 const existingFallbackEntityRecord = select4.getEntityRecord( 19549 "postType", 19550 "wp_navigation", 19551 fallback.id 19552 ); 19553 const invalidateNavigationQueries = !existingFallbackEntityRecord; 19554 dispatch3.receiveEntityRecords( 19555 "postType", 19556 "wp_navigation", 19557 record, 19558 void 0, 19559 invalidateNavigationQueries 19560 ); 19561 dispatch3.finishResolution("getEntityRecord", [ 19562 "postType", 19563 "wp_navigation", 19564 fallback.id 19565 ]); 19566 }); 19567 }; 19568 var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => { 19569 const template = await (0, import_api_fetch10.default)({ 19570 path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query) 19571 }); 19572 await resolveSelect2.getEntitiesConfig("postType"); 19573 const id2 = window?.__experimentalTemplateActivate ? template?.wp_id || template?.id : template?.id; 19574 registry.batch(() => { 19575 dispatch3.receiveDefaultTemplateId(query, id2 || ""); 19576 if (id2) { 19577 template.id = id2; 19578 dispatch3.receiveEntityRecords( 19579 "postType", 19580 template.type, 19581 template 19582 ); 19583 dispatch3.finishResolution("getEntityRecord", [ 19584 "postType", 19585 template.type, 19586 id2 19587 ]); 19588 } 19589 }); 19590 }; 19591 getDefaultTemplateId2.shouldInvalidate = (action) => { 19592 return action.type === "RECEIVE_ITEMS" && action.kind === "root" && action.name === "site" && !!action.persistedEdits; 19593 }; 19594 var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19595 const configs = await resolveSelect2.getEntitiesConfig(kind); 19596 const entityConfig = configs.find( 19597 (config) => config.name === name && config.kind === kind 19598 ); 19599 if (!entityConfig) { 19600 return; 19601 } 19602 const rawQuery = { ...query }; 19603 const lock3 = await dispatch3.__unstableAcquireStoreLock( 19604 STORE_NAME, 19605 ["entities", "records", kind, name, recordKey, "revisions"], 19606 { exclusive: false } 19607 ); 19608 try { 19609 if (query._fields) { 19610 query = { 19611 ...query, 19612 _fields: [ 19613 .../* @__PURE__ */ new Set([ 19614 ...get_normalized_comma_separable_default(query._fields) || [], 19615 entityConfig.revisionKey || DEFAULT_ENTITY_KEY 19616 ]) 19617 ].join() 19618 }; 19619 } 19620 const path = (0, import_url6.addQueryArgs)( 19621 entityConfig.getRevisionsUrl(recordKey), 19622 query 19623 ); 19624 let records, response; 19625 const meta = {};
19626 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1; 19627 try { 19628 response = await (0, import_api_fetch10.default)({ path, parse: !isPaginated }); 19629 } catch { 19630 return; 19631 } 19632 if (response) { 19633 if (isPaginated) { 19634 records = Object.values(await response.json()); 19635 meta.totalItems = parseInt( 19636 response.headers.get("X-WP-Total") 19637 ); 19638 } else { 19639 records = Object.values(response); 19640 } 19641 if (query._fields) { 19642 records = records.map((record) => { 19643 query._fields.split(",").forEach((field) => { 19644 if (!record.hasOwnProperty(field)) { 19645 record[field] = void 0; 19646 } 19647 }); 19648 return record; 19649 }); 19650 } 19651 await dispatch3.receiveRevisions( 19652 kind, 19653 name, 19654 recordKey, 19655 records, 19656 query, 19657 false, 19658 meta 19659 ); 19660 const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY; 19661 const normalizedQuery = normalizeQueryForResolution(rawQuery); 19662 const resolutionsArgs = records.filter((record) => record[key]).map((record) => [ 19663 kind, 19664 name, 19665 recordKey, 19666 record[key], 19667 normalizedQuery 19668 ]); 19669 dispatch3.finishResolutions("getRevision", resolutionsArgs); 19670 } 19671 } finally { 19672 dispatch3.__unstableReleaseStoreLock(lock3); 19673 } 19674 }; 19675 getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId; 19676 var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19677 const configs = await resolveSelect2.getEntitiesConfig(kind); 19678 const entityConfig = configs.find( 19679 (config) => config.name === name && config.kind === kind 19680 ); 19681 if (!entityConfig) { 19682 return; 19683 } 19684 if (query !== void 0 && query._fields) { 19685 query = { 19686 ...query, 19687 _fields: [ 19688 .../* @__PURE__ */ new Set([ 19689 ...get_normalized_comma_separable_default(query._fields) || [], 19690 entityConfig.revisionKey || DEFAULT_ENTITY_KEY 19691 ]) 19692 ].join() 19693 }; 19694 } 19695 const lock3 = await dispatch3.__unstableAcquireStoreLock( 19696 STORE_NAME, 19697 [ 19698 "entities", 19699 "records", 19700 kind, 19701 name, 19702 recordKey, 19703 "revisions", 19704 revisionKey 19705 ], 19706 { exclusive: false } 19707 ); 19708 try { 19709 if (select4.hasRevision(kind, name, recordKey, revisionKey, query)) { 19710 return; 19711 } 19712 const path = (0, import_url6.addQueryArgs)( 19713 entityConfig.getRevisionsUrl(recordKey, revisionKey), 19714 query 19715 ); 19716 let record;
19717 try { 19718 record = await (0, import_api_fetch10.default)({ path }); 19719 } catch { 19720 return; 19721 } 19722 if (record) { 19723 await dispatch3.receiveRevisions( 19724 kind, 19725 name, 19726 recordKey, 19727 record, 19728 query 19729 ); 19730 } 19731 } finally { 19732 dispatch3.__unstableReleaseStoreLock(lock3); 19733 } 19734 }; 19735 var getRegisteredPostMeta2 = (postType) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => { 19736 let options; 19737 try { 19738 const { 19739 rest_namespace: restNamespace = "wp/v2", 19740 rest_base: restBase 19741 } = await resolveSelect2.getPostType(postType) || {}; 19742 options = await (0, import_api_fetch10.default)({ 19743 path: `${restNamespace}/${restBase}/?context=edit`, 19744 method: "OPTIONS" 19745 }); 19746 } catch { 19747 return; 19748 } 19749 if (options) { 19750 dispatch3.receiveRegisteredPostMeta( 19751 postType, 19752 options?.schema?.properties?.meta?.properties 19753 ); 19754 } 19755 }; 19756 var getEntitiesConfig2 = (kind) => async ({ dispatch: dispatch3 }) => { 19757 const loader = additionalEntityConfigLoaders.find( 19758 (l) => l.kind === kind 19759 ); 19760 if (!loader) { 19761 return; 19762 } 19763 try { 19764 const configs = await loader.loadEntities(); 19765 if (!configs.length) { 19766 return; 19767 } 19768 dispatch3.addEntities(configs); 19769 } catch { 19770 } 19771 }; 19772 var getEditorSettings2 = () => async ({ dispatch: dispatch3 }) => { 19773 const settings = await (0, import_api_fetch10.default)({ 19774 path: "/wp-block-editor/v1/settings" 19775 }); 19776 dispatch3.receiveEditorSettings(settings); 19777 }; 19778 var getEditorAssets2 = () => async ({ dispatch: dispatch3 }) => { 19779 const assets = await (0, import_api_fetch10.default)({ 19780 path: "/wp-block-editor/v1/assets" 19781 }); 19782 dispatch3.receiveEditorAssets(assets); 19783 }; 19784 var getViewConfig2 = (kind, name, options = {}) => async ({ dispatch: dispatch3 }) => { 19785 const query = { kind, name }; 19786 const fields = get_normalized_comma_separable_default(options.fields); 19787 if (fields?.length) { 19788 query._fields = fields.join(","); 19789 } 19790 const config = await (0, import_api_fetch10.default)({ 19791 path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", query) 19792 }); 19793 dispatch3.receiveViewConfig(kind, name, config); 19794 }; 19795 19796
19796// packages/core-data/build-module/locks/utils.mjs 19797 function deepCopyLocksTreePath(tree, path) { 19798 const newTree = { ...tree }; 19799 let currentNode = newTree; 19800 for (const branchName of path) { 19801 currentNode.children = { 19802 ...currentNode.children, 19803 [branchName]: { 19804 locks: [], 19805 children: {}, 19806 ...currentNode.children[branchName] 19807 } 19808 }; 19809 currentNode = currentNode.children[branchName]; 19810 } 19811 return newTree; 19812 } 19813 function getNode(tree, path) { 19814 let currentNode = tree; 19815 for (const branchName of path) { 19816 const nextNode = currentNode.children[branchName]; 19817 if (!nextNode) { 19818 return null; 19819 } 19820 currentNode = nextNode; 19821 } 19822 return currentNode; 19823 } 19824 function* iteratePath(tree, path) { 19825 let currentNode = tree; 19826 yield currentNode; 19827 for (const branchName of path) { 19828 const nextNode = currentNode.children[branchName]; 19829 if (!nextNode) { 19830 break; 19831 } 19832 yield nextNode; 19833 currentNode = nextNode; 19834 } 19835 } 19836 function* iterateDescendants(node) { 19837 const stack = Object.values(node.children); 19838 while (stack.length) { 19839 const childNode = stack.pop(); 19840 yield childNode; 19841 stack.push(...Object.values(childNode.children)); 19842 } 19843 } 19844 function hasConflictingLock({ exclusive }, locks2) { 19845 if (exclusive && locks2.length) { 19846 return true; 19847 } 19848 if (!exclusive && locks2.filter((lock3) => lock3.exclusive).length) { 19849 return true; 19850 } 19851 return false; 19852 } 19853 19854
19854// packages/core-data/build-module/locks/reducer.mjs 19855 var DEFAULT_STATE = { 19856 requests: [], 19857 tree: { 19858 locks: [], 19859 children: {} 19860 } 19861 }; 19862 function locks(state = DEFAULT_STATE, action) { 19863 switch (action.type) { 19864 case "ENQUEUE_LOCK_REQUEST": { 19865 const { request } = action; 19866 return { 19867 ...state, 19868 requests: [request, ...state.requests] 19869 }; 19870 } 19871 case "GRANT_LOCK_REQUEST": { 19872 const { lock: lock3, request } = action; 19873 const { store: store2, path } = request; 19874 const storePath = [store2, ...path]; 19875 const newTree = deepCopyLocksTreePath(state.tree, storePath); 19876 const node = getNode(newTree, storePath); 19877 node.locks = [...node.locks, lock3]; 19878 return { 19879 ...state, 19880 requests: state.requests.filter((r) => r !== request), 19881 tree: newTree 19882 }; 19883 } 19884 case "RELEASE_LOCK": { 19885 const { lock: lock3 } = action; 19886 const storePath = [lock3.store, ...lock3.path]; 19887 const newTree = deepCopyLocksTreePath(state.tree, storePath); 19888 const node = getNode(newTree, storePath); 19889 node.locks = node.locks.filter((l) => l !== lock3); 19890 return { 19891 ...state, 19892 tree: newTree 19893 }; 19894 } 19895 } 19896 return state; 19897 } 19898 19899
19899// packages/core-data/build-module/locks/selectors.mjs 19900 function getPendingLockRequests(state) { 19901 return state.requests; 19902 } 19903 function isLockAvailable(state, store2, path, { exclusive }) { 19904 const storePath = [store2, ...path]; 19905 const locks2 = state.tree; 19906 for (const node2 of iteratePath(locks2, storePath)) { 19907 if (hasConflictingLock({ exclusive }, node2.locks)) { 19908 return false; 19909 } 19910 } 19911 const node = getNode(locks2, storePath); 19912 if (!node) { 19913 return true; 19914 } 19915 for (const descendant of iterateDescendants(node)) { 19916 if (hasConflictingLock({ exclusive }, descendant.locks)) { 19917 return false; 19918 } 19919 } 19920 return true; 19921 } 19922 19923
19923// packages/core-data/build-module/locks/engine.mjs 19924 function createLocks() { 19925 let state = locks(void 0, { type: "@@INIT" }); 19926 function processPendingLockRequests() { 19927 for (const request of getPendingLockRequests(state)) { 19928 const { store: store2, path, exclusive, notifyAcquired } = request; 19929 if (isLockAvailable(state, store2, path, { exclusive })) { 19930 const lock3 = { store: store2, path, exclusive }; 19931 state = locks(state, { 19932 type: "GRANT_LOCK_REQUEST", 19933 lock: lock3, 19934 request 19935 }); 19936 notifyAcquired(lock3); 19937 } 19938 } 19939 } 19940 function acquire(store2, path, exclusive) { 19941 return new Promise((resolve) => { 19942 state = locks(state, { 19943 type: "ENQUEUE_LOCK_REQUEST", 19944 request: { store: store2, path, exclusive, notifyAcquired: resolve } 19945 }); 19946 processPendingLockRequests(); 19947 }); 19948 } 19949 function release(lock3) { 19950 state = locks(state, { 19951 type: "RELEASE_LOCK", 19952 lock: lock3 19953 }); 19954 processPendingLockRequests(); 19955 } 19956 return { acquire, release }; 19957 } 19958 19959
19959// packages/core-data/build-module/locks/actions.mjs 19960 function createLocksActions() { 19961 const locks2 = createLocks(); 19962 function __unstableAcquireStoreLock(store2, path, { exclusive }) { 19963 return () => locks2.acquire(store2, path, exclusive); 19964 } 19965 function __unstableReleaseStoreLock(lock3) { 19966 return () => locks2.release(lock3); 19967 } 19968 return { __unstableAcquireStoreLock, __unstableReleaseStoreLock }; 19969 } 19970 19971
19971// packages/core-data/build-module/dynamic-entities.mjs 19972 var dynamicActions; 19973 var dynamicSelectors; 19974 19975
19975// packages/core-data/build-module/entity-provider.mjs 19976 var import_element2 = __toESM(require_element(), 1); 19977 19978
19978// packages/core-data/build-module/entity-context.mjs 19979 var import_element = __toESM(require_element(), 1); 19980 var EntityContext = (0, import_element.createContext)({}); 19981 EntityContext.displayName = "EntityContext"; 19982 19983
19983// packages/core-data/build-module/entity-provider.mjs 19984 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); 19985 function EntityProvider({ 19986 kind, 19987 type: name, 19988 id: id2, 19989 revisionId, 19990 children 19991 }) { 19992 const parent = (0, import_element2.useContext)(EntityContext); 19993 const childContext = (0, import_element2.useMemo)( 19994 () => ({ 19995 ...parent, 19996 ...kind && { 19997 [kind]: { 19998 ...parent?.[kind], 19999 [name]: id2 20000 } 20001 }, 20002 ...revisionId !== void 0 && { revisionId } 20003 }), 20004 [parent, kind, name, id2, revisionId] 20005 ); 20006 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children }); 20007 } 20008 20009
20009// packages/core-data/build-module/hooks/use-entity-record.mjs 20010 var import_data10 = __toESM(require_data(), 1); 20011 var import_deprecated4 = __toESM(require_deprecated(), 1); 20012 var import_element3 = __toESM(require_element(), 1); 20013 20014
20014// packages/core-data/build-module/hooks/constants.mjs 20015 var Status = /* @__PURE__ */ ((Status2) => { 20016 Status2["Idle"] = "IDLE"; 20017 Status2["Resolving"] = "RESOLVING"; 20018 Status2["Error"] = "ERROR"; 20019 Status2["Success"] = "SUCCESS"; 20020 return Status2; 20021 })(Status || {}); 20022 20023
20023// packages/core-data/build-module/hooks/utils.mjs 20024 function getResolutionStatus(resolutionStatus) { 20025 let status; 20026 switch (resolutionStatus) { 20027 case "resolving": 20028 status = Status.Resolving; 20029 break; 20030 case "finished": 20031 status = Status.Success; 20032 break; 20033 case "error": 20034 status = Status.Error; 20035 break; 20036 default: 20037 status = Status.Idle; 20038 } 20039 return { 20040 status, 20041 isResolving: status === Status.Resolving, 20042 hasStarted: status !== Status.Idle, 20043 hasResolved: status === Status.Success || status === Status.Error 20044 }; 20045 } 20046 20047
20047// packages/core-data/build-module/hooks/use-entity-record.mjs 20048 var EMPTY_OBJECT3 = {}; 20049 function useEntityRecord(kind, name, recordId, options = { enabled: true }) { 20050 const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data10.useDispatch)(store); 20051 const mutations = (0, import_element3.useMemo)( 20052 () => ({ 20053 edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions), 20054 save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, { 20055 throwOnError: true, 20056 ...saveOptions 20057 }) 20058 }), 20059 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2] 20060 ); 20061 const { record, editedRecord, hasEdits, edits, ...resolution } = (0, import_data10.useSelect)( 20062 (select4) => { 20063 if (!options.enabled) { 20064 return { 20065 record: null, 20066 editedRecord: EMPTY_OBJECT3, 20067 hasEdits: false, 20068 edits: EMPTY_OBJECT3, 20069 ...getResolutionStatus() 20070 }; 20071 } 20072 const storeSelectors = select4(store); 20073 const resolutionStatus = storeSelectors.getResolutionState( 20074 "getEntityRecord", 20075 [kind, name, recordId] 20076 )?.status; 20077 return { 20078 record: storeSelectors.getEntityRecord( 20079 kind, 20080 name, 20081 recordId 20082 ) ?? null, 20083 editedRecord: storeSelectors.getEditedEntityRecord( 20084 kind, 20085 name, 20086 recordId 20087 ), 20088 hasEdits: storeSelectors.hasEditsForEntityRecord( 20089 kind, 20090 name, 20091 recordId 20092 ), 20093 edits: storeSelectors.getEntityRecordNonTransientEdits( 20094 kind, 20095 name, 20096 recordId 20097 ), 20098 ...getResolutionStatus(resolutionStatus) 20099 }; 20100 }, 20101 [kind, name, recordId, options.enabled] 20102 ); 20103 return { 20104 record, 20105 editedRecord, 20106 hasEdits, 20107 edits, 20108 ...resolution, 20109 ...mutations 20110 }; 20111 } 20112 function useDeprecatedEntityRecord(kind, name, recordId, options) { 20113 (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, { 20114 alternative: "wp.data.useEntityRecord", 20115 since: "6.1" 20116 }); 20117 return useEntityRecord(kind, name, recordId, options); 20118 } 20119 20120
20120// packages/core-data/build-module/hooks/use-entity-records.mjs 20121 var import_url7 = __toESM(require_url(), 1); 20122 var import_deprecated5 = __toESM(require_deprecated(), 1); 20123 var import_data11 = __toESM(require_data(), 1); 20124 var import_element4 = __toESM(require_element(), 1); 20125 var EMPTY_ARRAY = []; 20126 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) { 20127 const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs); 20128 const { records, totalItems, totalPages, ...rest } = (0, import_data11.useSelect)( 20129 (select4) => { 20130 if (!options.enabled) { 20131 return { 20132 // Avoiding returning a new reference on every execution. 20133 records: EMPTY_ARRAY, 20134 totalItems: null, 20135 totalPages: null, 20136 ...getResolutionStatus() 20137 }; 20138 } 20139 const storeSelectors = select4(store); 20140 const resolutionStatus = storeSelectors.getResolutionState( 20141 "getEntityRecords", 20142 [kind, name, queryArgs] 20143 )?.status; 20144 return { 20145 records: storeSelectors.getEntityRecords( 20146 kind, 20147 name, 20148 queryArgs 20149 ), 20150 totalItems: storeSelectors.getEntityRecordsTotalItems( 20151 kind, 20152 name, 20153 queryArgs 20154 ), 20155 totalPages: storeSelectors.getEntityRecordsTotalPages( 20156 kind, 20157 name, 20158 queryArgs 20159 ), 20160 ...getResolutionStatus(resolutionStatus) 20161 }; 20162 }, 20163 [kind, name, queryAsString, options.enabled] 20164 ); 20165 return { 20166 records, 20167 totalItems, 20168 totalPages, 20169 ...rest 20170 }; 20171 } 20172 function useDeprecatedEntityRecords(kind, name, queryArgs, options) { 20173 (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, { 20174 alternative: "wp.data.useEntityRecords", 20175 since: "6.1" 20176 }); 20177 return useEntityRecords(kind, name, queryArgs, options); 20178 } 20179 function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) { 20180 const entityConfig = (0, import_data11.useSelect)( 20181 (select4) => select4(store).getEntityConfig(kind, name), 20182 [kind, name] 20183 ); 20184 const { records: data, ...ret } = useEntityRecords( 20185 kind, 20186 name, 20187 { 20188 ...queryArgs, 20189 // If _fields is provided, we need to include _links in the request for permission caching to work. 20190 ...queryArgs._fields ? { 20191 _fields: [ 20192 .../* @__PURE__ */ new Set([ 20193 ...get_normalized_comma_separable_default( 20194 queryArgs._fields 20195 ) || [], 20196 "_links" 20197 ]) 20198 ].join() 20199 } : {} 20200 }, 20201 options 20202 ); 20203 const ids = (0, import_element4.useMemo)( 20204 () => data?.map( 20205 // @ts-ignore 20206 (record) => record[entityConfig?.key ?? "id"] 20207 ) ?? [], 20208 [data, entityConfig?.key] 20209 ); 20210 const permissions = (0, import_data11.useSelect)( 20211 (select4) => { 20212 const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock2( 20213 select4(store) 20214 ); 20215 return getEntityRecordsPermissions2(kind, name, ids); 20216 }, 20217 [ids, kind, name] 20218 ); 20219 const dataWithPermissions = (0, import_element4.useMemo)( 20220 () => data?.map((record, index) => ({ 20221 // @ts-ignore 20222 ...record, 20223 permissions: permissions[index] 20224 })) ?? [], 20225 [data, permissions] 20226 ); 20227 return { records: dataWithPermissions, ...ret }; 20228 } 20229 20230
20230// packages/core-data/build-module/hooks/use-resource-permissions.mjs 20231 var import_deprecated6 = __toESM(require_deprecated(), 1); 20232 var import_warning = __toESM(require_warning(), 1); 20233 20234
20234// packages/core-data/build-module/hooks/use-query-select.mjs 20235 var import_data12 = __toESM(require_data(), 1); 20236 20237
vendor: 1,642 bytes, lines 20237-20305
20237// node_modules/memize/dist/index.js 20238 function memize(fn, options) { 20239 var size2 = 0; 20240 var head; 20241 var tail; 20242 options = options || {}; 20243 function memoized() { 20244 var node = head, len = arguments.length, args2, i; 20245 searchCache: while (node) { 20246 if (node.args.length !== arguments.length) { 20247 node = node.next; 20248 continue; 20249 } 20250 for (i = 0; i < len; i++) { 20251 if (node.args[i] !== arguments[i]) { 20252 node = node.next; 20253 continue searchCache; 20254 } 20255 } 20256 if (node !== head) { 20257 if (node === tail) { 20258 tail = node.prev; 20259 } 20260 node.prev.next = node.next; 20261 if (node.next) { 20262 node.next.prev = node.prev; 20263 } 20264 node.next = head; 20265 node.prev = null; 20266 head.prev = node; 20267 head = node; 20268 } 20269 return node.val; 20270 } 20271 args2 = new Array(len); 20272 for (i = 0; i < len; i++) { 20273 args2[i] = arguments[i]; 20274 } 20275 node = { 20276 args: args2, 20277 // Generate the result from original function 20278 val: fn.apply(null, args2) 20279 }; 20280 if (head) { 20281 head.prev = node; 20282 node.next = head; 20283 } else { 20284 tail = node; 20285 } 20286 if (size2 === /** @type {MemizeOptions} */ 20287 options.maxSize) { 20288 tail = /** @type {MemizeCacheNode} */ 20289 tail.prev; 20290 tail.next = null; 20291 } else { 20292 size2++; 20293 } 20294 head = node; 20295 return node.val; 20296 } 20297 memoized.clear = function() { 20298 head = null; 20299 tail = null; 20300 size2 = 0; 20301 }; 20302 return memoized; 20303 } 20304 20305
20305// packages/core-data/build-module/hooks/use-query-select.mjs 20306 var META_SELECTORS = [ 20307 "getIsResolving", 20308 "hasStartedResolution", 20309 "hasFinishedResolution", 20310 "isResolving", 20311 "getCachedResolvers" 20312 ]; 20313 function useQuerySelect(mapQuerySelect, deps) { 20314 return (0, import_data12.useSelect)((select4, registry) => { 20315 const resolve = (store2) => enrichSelectors(select4(store2)); 20316 return mapQuerySelect(resolve, registry); 20317 }, deps); 20318 } 20319 var enrichSelectors = memize(((selectors) => { 20320 const resolvers = {}; 20321 for (const selectorName in selectors) { 20322 if (META_SELECTORS.includes(selectorName)) { 20323 continue; 20324 } 20325 Object.defineProperty(resolvers, selectorName, { 20326 get: () => (...args2) => { 20327 const data = selectors[selectorName](...args2); 20328 const resolutionStatus = selectors.getResolutionState( 20329 selectorName, 20330 args2 20331 )?.status; 20332 return { 20333 data, 20334 ...getResolutionStatus(resolutionStatus) 20335 }; 20336 } 20337 }); 20338 } 20339 return resolvers; 20340 })); 20341 20342
20342// packages/core-data/build-module/hooks/use-resource-permissions.mjs 20343 function useResourcePermissions(resource, id2) { 20344 const isEntity = typeof resource === "object"; 20345 const resourceAsString = isEntity ? JSON.stringify(resource) : resource; 20346 if (isEntity && typeof id2 !== "undefined") { 20347 (0, import_warning.default)( 20348 `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.` 20349 ); 20350 } 20351 return useQuerySelect( 20352 (resolve) => { 20353 const hasId = isEntity ? !!resource.id : !!id2; 20354 const { canUser: canUser3 } = resolve(store); 20355 const collectionResource = isEntity ? { kind: resource.kind, name: resource.name } : resource; 20356 const create9 = canUser3("create", collectionResource); 20357 if (!hasId) { 20358 const read2 = canUser3("read", collectionResource); 20359 const isResolving2 = create9.isResolving || read2.isResolving; 20360 const hasResolved2 = create9.hasResolved && read2.hasResolved; 20361 let status2 = Status.Idle; 20362 if (isResolving2) { 20363 status2 = Status.Resolving; 20364 } else if (hasResolved2) { 20365 status2 = Status.Success; 20366 } 20367 return { 20368 status: status2, 20369 isResolving: isResolving2, 20370 hasResolved: hasResolved2, 20371 canCreate: create9.hasResolved && create9.data, 20372 canRead: read2.hasResolved && read2.data 20373 }; 20374 } 20375 const read = canUser3("read", resource, id2); 20376 const update = canUser3("update", resource, id2); 20377 const _delete = canUser3("delete", resource, id2); 20378 const isResolving = read.isResolving || create9.isResolving || update.isResolving || _delete.isResolving; 20379 const hasResolved = read.hasResolved && create9.hasResolved && update.hasResolved && _delete.hasResolved; 20380 let status = Status.Idle; 20381 if (isResolving) { 20382 status = Status.Resolving; 20383 } else if (hasResolved) { 20384 status = Status.Success; 20385 } 20386 return { 20387 status, 20388 isResolving, 20389 hasResolved, 20390 canRead: hasResolved && read.data, 20391 canCreate: hasResolved && create9.data, 20392 canUpdate: hasResolved && update.data, 20393 canDelete: hasResolved && _delete.data 20394 }; 20395 }, 20396 [resourceAsString, id2] 20397 ); 20398 } 20399 var use_resource_permissions_default = useResourcePermissions; 20400 function useDeprecatedResourcePermissions(resource, id2) { 20401 (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, { 20402 alternative: "wp.data.useResourcePermissions", 20403 since: "6.1" 20404 }); 20405 return useResourcePermissions(resource, id2); 20406 } 20407 20408
20408// packages/core-data/build-module/hooks/use-entity-block-editor.mjs 20409 var import_element6 = __toESM(require_element(), 1); 20410 var import_data13 = __toESM(require_data(), 1); 20411 var import_blocks5 = __toESM(require_blocks(), 1); 20412 20413
20413// packages/core-data/build-module/hooks/use-entity-id.mjs 20414 var import_element5 = __toESM(require_element(), 1); 20415 function useEntityId(kind, name) { 20416 const context = (0, import_element5.useContext)(EntityContext); 20417 return context?.[kind]?.[name]; 20418 } 20419 20420
20420// packages/core-data/build-module/footnotes/index.mjs 20421 var import_rich_text4 = __toESM(require_rich_text(), 1); 20422 20423
20423// packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs 20424 var import_block_editor5 = __toESM(require_block_editor(), 1); 20425 var unlockedApis; 20426 var cache = /* @__PURE__ */ new WeakMap(); 20427 function getRichTextValuesCached(block) { 20428 if (!unlockedApis) { 20429 unlockedApis = unlock2(import_block_editor5.privateApis); 20430 } 20431 if (!cache.has(block)) { 20432 const values = unlockedApis.getRichTextValues([block]); 20433 cache.set(block, values); 20434 } 20435 return cache.get(block); 20436 } 20437 20438
20438// packages/core-data/build-module/footnotes/get-footnotes-order.mjs 20439 var cache2 = /* @__PURE__ */ new WeakMap(); 20440 function getBlockFootnotesOrder(block) { 20441 if (!cache2.has(block)) { 20442 const order = []; 20443 for (const value of getRichTextValuesCached(block)) { 20444 if (!value) { 20445 continue; 20446 } 20447 value.replacements.forEach(({ type, attributes }) => { 20448 if (type === "core/footnote") { 20449 order.push(attributes["data-fn"]); 20450 } 20451 }); 20452 } 20453 cache2.set(block, order); 20454 } 20455 return cache2.get(block); 20456 } 20457 function getFootnotesOrder(blocks) { 20458 return blocks.flatMap(getBlockFootnotesOrder); 20459 } 20460 20461
20461// packages/core-data/build-module/footnotes/index.mjs 20462 var oldFootnotes = {}; 20463 function updateFootnotesFromMeta(blocks, meta) { 20464 const output = { blocks }; 20465 if (!meta) { 20466 return output; 20467 } 20468 if (meta.footnotes === void 0) { 20469 return output; 20470 } 20471 const newOrder = getFootnotesOrder(blocks); 20472 const footnotes = meta.footnotes ? JSON.parse(meta.footnotes) : []; 20473 const currentOrder = footnotes.map((fn) => fn.id); 20474 if (currentOrder.join("") === newOrder.join("")) { 20475 return output; 20476 } 20477 const newFootnotes = newOrder.map( 20478 (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || { 20479 id: fnId, 20480 content: "" 20481 } 20482 ); 20483 function updateAttributes(attributes) { 20484 if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") { 20485 return attributes; 20486 } 20487 attributes = { ...attributes }; 20488 for (const key in attributes) { 20489 const value = attributes[key]; 20490 if (Array.isArray(value)) { 20491 attributes[key] = value.map(updateAttributes); 20492 continue; 20493 } 20494 if (typeof value !== "string" && !(value instanceof import_rich_text4.RichTextData)) { 20495 continue; 20496 } 20497 const richTextValue = typeof value === "string" ? import_rich_text4.RichTextData.fromHTMLString(value) : new import_rich_text4.RichTextData(value); 20498 let hasFootnotes = false; 20499 richTextValue.replacements.forEach((replacement) => { 20500 if (replacement.type === "core/footnote") { 20501 const id2 = replacement.attributes["data-fn"]; 20502 const index = newOrder.indexOf(id2); 20503 const countValue = (0, import_rich_text4.create)({ 20504 html: replacement.innerHTML 20505 }); 20506 countValue.text = String(index + 1); 20507 countValue.formats = Array.from( 20508 { length: countValue.text.length }, 20509 () => countValue.formats[0] 20510 ); 20511 countValue.replacements = Array.from( 20512 { length: countValue.text.length }, 20513 () => countValue.replacements[0] 20514 ); 20515 replacement.innerHTML = (0, import_rich_text4.toHTMLString)({ 20516 value: countValue 20517 }); 20518 hasFootnotes = true; 20519 } 20520 }); 20521 if (hasFootnotes) { 20522 attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue; 20523 } 20524 } 20525 return attributes; 20526 } 20527 function updateBlocksAttributes(__blocks) { 20528 return __blocks.map((block) => { 20529 return { 20530 ...block, 20531 attributes: updateAttributes(block.attributes), 20532 innerBlocks: updateBlocksAttributes(block.innerBlocks) 20533 }; 20534 }); 20535 } 20536 const newBlocks = updateBlocksAttributes(blocks); 20537 oldFootnotes = { 20538 ...oldFootnotes, 20539 ...footnotes.reduce((acc, fn) => { 20540 if (!newOrder.includes(fn.id)) { 20541 acc[fn.id] = fn; 20542 } 20543 return acc; 20544 }, {}) 20545 }; 20546 return { 20547 meta: { 20548 ...meta, 20549 footnotes: JSON.stringify(newFootnotes) 20550 }, 20551 blocks: newBlocks 20552 }; 20553 } 20554 20555
20555// packages/core-data/build-module/hooks/use-entity-block-editor.mjs 20556 var EMPTY_ARRAY2 = []; 20557 function useEntityBlockEditor(kind, name, { id: _id } = {}) { 20558 const providerId = useEntityId(kind, name); 20559 const id2 = _id ?? providerId; 20560 const { content, editedBlocks, meta } = (0, import_data13.useSelect)( 20561 (select4) => { 20562 if (!id2) { 20563 return {}; 20564 } 20565 const { getEditedEntityRecord: getEditedEntityRecord3 } = select4(STORE_NAME); 20566 const editedRecord = getEditedEntityRecord3(kind, name, id2); 20567 return { 20568 editedBlocks: editedRecord.blocks, 20569 content: editedRecord.content, 20570 meta: editedRecord.meta 20571 }; 20572 }, 20573 [kind, name, id2] 20574 ); 20575 const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data13.useDispatch)(STORE_NAME); 20576 const blocks = (0, import_element6.useMemo)(() => { 20577 if (!id2) { 20578 return void 0; 20579 } 20580 if (editedBlocks) { 20581 return editedBlocks; 20582 } 20583 if (!content || typeof content !== "string") { 20584 return EMPTY_ARRAY2; 20585 } 20586 const cacheKey = getCacheKey(kind, name, id2); 20587 const cached = parsedBlocksCache.get(cacheKey); 20588 let _blocks; 20589 if (cached && cached.content === content) { 20590 _blocks = cached.blocks; 20591 } else { 20592 _blocks = (0, import_blocks5.parse)(content); 20593 parsedBlocksCache.set(cacheKey, { content, blocks: _blocks }); 20594 } 20595 return _blocks; 20596 }, [kind, name, id2, editedBlocks, content]); 20597 const onChange = (0, import_element6.useCallback)( 20598 (newBlocks, options) => { 20599 const noChange = blocks === newBlocks; 20600 if (noChange) { 20601 return __unstableCreateUndoLevel2(kind, name, id2); 20602 } 20603 const { selection, ...rest } = options; 20604 const edits = { 20605 selection, 20606 content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks5.__unstableSerializeAndClean)(blocksForSerialization), 20607 ...updateFootnotesFromMeta(newBlocks, meta) 20608 }; 20609 editEntityRecord2(kind, name, id2, edits, { 20610 isCached: false, 20611 ...rest 20612 }); 20613 }, 20614 [ 20615 kind, 20616 name, 20617 id2, 20618 blocks, 20619 meta, 20620 __unstableCreateUndoLevel2, 20621 editEntityRecord2 20622 ] 20623 ); 20624 const onInput = (0, import_element6.useCallback)( 20625 (newBlocks, options) => { 20626 const { selection, ...rest } = options; 20627 const edits = { 20628 selection, 20629 ...updateFootnotesFromMeta(newBlocks, meta) 20630 }; 20631 editEntityRecord2(kind, name, id2, edits, { 20632 isCached: true, 20633 ...rest 20634 }); 20635 }, 20636 [kind, name, id2, meta, editEntityRecord2] 20637 ); 20638 return [blocks, onInput, onChange]; 20639 } 20640 20641
20641// packages/core-data/build-module/hooks/use-entity-prop.mjs 20642 var import_element7 = __toESM(require_element(), 1); 20643 var import_data14 = __toESM(require_data(), 1); 20644 function useEntityProp(kind, name, prop, _id) { 20645 const providerId = useEntityId(kind, name); 20646 const id2 = _id ?? providerId; 20647 const context = (0, import_element7.useContext)(EntityContext); 20648 const revisionId = context?.revisionId; 20649 const { value, fullValue } = (0, import_data14.useSelect)( 20650 (select4) => { 20651 if (revisionId) { 20652 const revisions = select4(STORE_NAME).getRevisions( 20653 kind, 20654 name, 20655 id2, 20656 { 20657 per_page: -1, 20658 context: "edit", 20659 _fields: "id,date,author,meta,title.raw,excerpt.raw,content.raw" 20660 } 20661 ); 20662 const entityConfig = select4(STORE_NAME).getEntityConfig( 20663 kind, 20664 name 20665 ); 20666 const revKey = entityConfig?.revisionKey || DEFAULT_ENTITY_KEY; 20667 const revision = revisions?.find( 20668 (r) => r[revKey] === revisionId 20669 ); 20670 return revision ? { 20671 value: revision[prop]?.raw ?? revision[prop], 20672 fullValue: revision[prop] 20673 } : {}; 20674 } 20675 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select4(STORE_NAME); 20676 const record = getEntityRecord3(kind, name, id2); 20677 const editedRecord = getEditedEntityRecord3(kind, name, id2); 20678 return record && editedRecord ? { 20679 value: editedRecord[prop], 20680 fullValue: record[prop] 20681 } : {}; 20682 }, 20683 [kind, name, id2, prop, revisionId] 20684 ); 20685 const { editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME); 20686 const setValue = (0, import_element7.useCallback)( 20687 (newValue) => { 20688 if (revisionId) { 20689 return; 20690 } 20691 editEntityRecord2(kind, name, id2, { 20692 [prop]: newValue 20693 }); 20694 }, 20695 [editEntityRecord2, kind, name, id2, prop, revisionId] 20696 ); 20697 return [value, setValue, fullValue]; 20698 } 20699 20700
20700// packages/core-data/build-module/hooks/use-post-editor-awareness-state.mjs 20701 var import_compose3 = __toESM(require_compose(), 1); 20702 var import_element8 = __toESM(require_element(), 1); 20703 var defaultResolvedSelection = { 20704 richTextOffset: null, 20705 localClientId: null, 20706 attributeKey: null 20707 }; 20708 var defaultState = { 20709 activeCollaborators: [], 20710 resolveSelection: () => defaultResolvedSelection, 20711 getDebugData: () => ({ 20712 doc: {}, 20713 clients: {}, 20714 collaboratorMap: {} 20715 }), 20716 isCurrentCollaboratorDisconnected: false 20717 }; 20718 function getAwarenessState(awareness, newState) { 20719 const activeCollaborators = newState ?? awareness.getCurrentState(); 20720 return { 20721 activeCollaborators, 20722 resolveSelection: (selection, blocks) => awareness.convertSelectionStateToAbsolute(selection, blocks), 20723 getDebugData: () => awareness.getDebugData(), 20724 isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false 20725 }; 20726 } 20727 function usePostEditorAwarenessState(postId, postType) { 20728 const [state, setState] = (0, import_element8.useState)(defaultState); 20729 (0, import_element8.useEffect)(() => { 20730 if (null === postId || null === postType) { 20731 setState(defaultState); 20732 return; 20733 } 20734 const objectType = `postType/${postType}`; 20735 const objectId = postId.toString(); 20736 const awareness = getSyncManager()?.getAwareness( 20737 objectType, 20738 objectId 20739 ); 20740 if (!awareness) { 20741 setState(defaultState); 20742 return; 20743 } 20744 awareness.setUp(); 20745 setState(getAwarenessState(awareness)); 20746 const unsubscribe = awareness?.onStateChange( 20747 (newState) => { 20748 setState(getAwarenessState(awareness, newState)); 20749 } 20750 ); 20751 return unsubscribe; 20752 }, [postId, postType]); 20753 return state; 20754 } 20755 function useActiveCollaborators(postId, postType) { 20756 return usePostEditorAwarenessState(postId, postType).activeCollaborators; 20757 } 20758 function useResolvedSelection(postId, postType) { 20759 const blocks = usePostContentBlocks(); 20760 const awarenessState = usePostEditorAwarenessState(postId, postType); 20761 return (0, import_element8.useCallback)( 20762 (selection) => awarenessState.resolveSelection(selection, blocks), 20763 [blocks, awarenessState] 20764 ); 20765 } 20766 function useLastPostSave(postId, postType) { 20767 const [lastSave, setLastSave] = (0, import_element8.useState)(null); 20768 (0, import_element8.useEffect)(() => { 20769 if (null === postId || null === postType) { 20770 setLastSave(null); 20771 return; 20772 } 20773 const awareness = getSyncManager()?.getAwareness( 20774 `postType/${postType}`, 20775 postId.toString() 20776 ); 20777 if (!awareness) { 20778 setLastSave(null); 20779 return; 20780 } 20781 awareness.setUp(); 20782 const stateMap = awareness.doc.getMap("state"); 20783 const recordMap = awareness.doc.getMap("document"); 20784 const setupTime = Date.now(); 20785 const observer = (event) => { 20786 if (event.keysChanged.has("savedAt")) { 20787 const savedAt = stateMap.get("savedAt"); 20788 const savedByClientId = stateMap.get("savedBy"); 20789 if (typeof savedAt === "number" && typeof savedByClientId === "number" && savedAt > setupTime) { 20790 const postStatus = recordMap.get("status"); 20791 setLastSave({ savedAt, savedByClientId, postStatus }); 20792 } 20793 } 20794 }; 20795 stateMap.observe(observer); 20796 return () => { 20797 stateMap.unobserve(observer); 20798 }; 20799 }, [postId, postType]); 20800 return lastSave; 20801 } 20802 function useOnCollaboratorJoin(postId, postType, callback) { 20803 const { activeCollaborators } = usePostEditorAwarenessState( 20804 postId, 20805 postType 20806 ); 20807 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators); 20808 (0, import_element8.useEffect)(() => { 20809 if (!prevCollaborators || prevCollaborators.length === 0) { 20810 return; 20811 } 20812 const prevMap = new Map( 20813 prevCollaborators.map((collaborator) => [ 20814 collaborator.clientId, 20815 collaborator 20816 ]) 20817 ); 20818 const me = activeCollaborators.find( 20819 (collaborator) => collaborator.isMe 20820 ); 20821 for (const collaborator of activeCollaborators) { 20822 if (!prevMap.has(collaborator.clientId) && !collaborator.isMe) { 20823 callback(collaborator, me); 20824 } 20825 } 20826 }, [activeCollaborators, prevCollaborators, callback]); 20827 } 20828 function useOnCollaboratorLeave(postId, postType, callback) { 20829 const { activeCollaborators } = usePostEditorAwarenessState( 20830 postId, 20831 postType 20832 ); 20833 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators); 20834 (0, import_element8.useEffect)(() => { 20835 if (!prevCollaborators || prevCollaborators.length === 0) { 20836 return; 20837 } 20838 const newMap = new Map( 20839 activeCollaborators.map((collaborator) => [ 20840 collaborator.clientId, 20841 collaborator 20842 ]) 20843 ); 20844 for (const prevCollab of prevCollaborators) { 20845 if (prevCollab.isMe || !prevCollab.isConnected) { 20846 continue; 20847 } 20848 const newCollab = newMap.get(prevCollab.clientId); 20849 if (!newCollab?.isConnected) { 20850 callback(prevCollab); 20851 } 20852 } 20853 }, [activeCollaborators, prevCollaborators, callback]); 20854 } 20855 function useOnPostSave(postId, postType, callback) { 20856 const { activeCollaborators } = usePostEditorAwarenessState( 20857 postId, 20858 postType 20859 ); 20860 const lastPostSave = useLastPostSave(postId, postType); 20861 const prevPostSave = (0, import_compose3.usePrevious)(lastPostSave); 20862 (0, import_element8.useEffect)(() => { 20863 if (!lastPostSave) { 20864 return; 20865 } 20866 if (prevPostSave && lastPostSave.savedAt === prevPostSave.savedAt) { 20867 return; 20868 } 20869 const saver = activeCollaborators.find( 20870 (collaborator) => collaborator.clientId === lastPostSave.savedByClientId && !collaborator.isMe 20871 ); 20872 if (!saver) { 20873 return; 20874 } 20875 callback(lastPostSave, saver, prevPostSave ?? null); 20876 }, [lastPostSave, prevPostSave, activeCollaborators, callback]); 20877 } 20878 20879
20879// packages/core-data/build-module/private-apis.mjs 20880 var lockedApis = { 20881 useEntityRecordsWithPermissions, 20882 RECEIVE_INTERMEDIATE_RESULTS, 20883 retrySyncConnection, 20884 useActiveCollaborators, 20885 useResolvedSelection, 20886 useOnCollaboratorJoin, 20887 useOnCollaboratorLeave, 20888 useOnPostSave, 20889 SelectionType, 20890 SelectionDirection 20891 }; 20892 var privateApis2 = {}; 20893 lock2(privateApis2, lockedApis); 20894 20895
20895// packages/core-data/build-module/index.mjs 20896 var entitiesConfig2 = [ 20897 ...rootEntitiesConfig, 20898 ...additionalEntityConfigLoaders.filter((config) => !!config.name) 20899 ]; 20900 var entitySelectors = entitiesConfig2.reduce((result, entity2) => { 20901 const { kind, name, plural } = entity2; 20902 const getEntityRecordMethodName = getMethodName(kind, name); 20903 result[getEntityRecordMethodName] = (state, key, query) => { 20904 logEntityDeprecation(kind, name, getEntityRecordMethodName, { 20905 isShorthandSelector: true, 20906 alternativeFunctionName: "getEntityRecord" 20907 }); 20908 return getEntityRecord(state, kind, name, key, query); 20909 }; 20910 if (plural) { 20911 const getEntityRecordsMethodName = getMethodName(kind, plural, "get"); 20912 result[getEntityRecordsMethodName] = (state, query) => { 20913 logEntityDeprecation(kind, name, getEntityRecordsMethodName, { 20914 isShorthandSelector: true, 20915 alternativeFunctionName: "getEntityRecords" 20916 }); 20917 return getEntityRecords(state, kind, name, query); 20918 }; 20919 } 20920 return result; 20921 }, {}); 20922 var entityResolvers = entitiesConfig2.reduce((result, entity2) => { 20923 const { kind, name, plural } = entity2; 20924 const getEntityRecordMethodName = getMethodName(kind, name); 20925 result[getEntityRecordMethodName] = (key, query) => { 20926 logEntityDeprecation(kind, name, getEntityRecordMethodName, { 20927 isShorthandSelector: true, 20928 alternativeFunctionName: "getEntityRecord" 20929 }); 20930 return getEntityRecord2(kind, name, key, query); 20931 }; 20932 if (plural) { 20933 const getEntityRecordsMethodName = getMethodName(kind, plural, "get"); 20934 result[getEntityRecordsMethodName] = (...args2) => { 20935 logEntityDeprecation(kind, plural, getEntityRecordsMethodName, { 20936 isShorthandSelector: true, 20937 alternativeFunctionName: "getEntityRecords" 20938 }); 20939 return getEntityRecords2(kind, name, ...args2); 20940 }; 20941 result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name); 20942 } 20943 return result; 20944 }, {}); 20945 var entityActions = entitiesConfig2.reduce((result, entity2) => { 20946 const { kind, name } = entity2; 20947 const saveEntityRecordMethodName = getMethodName(kind, name, "save"); 20948 result[saveEntityRecordMethodName] = (record, options) => { 20949 logEntityDeprecation(kind, name, saveEntityRecordMethodName, { 20950 isShorthandSelector: true, 20951 alternativeFunctionName: "saveEntityRecord" 20952 }); 20953 return saveEntityRecord(kind, name, record, options); 20954 }; 20955 const deleteEntityRecordMethodName = getMethodName(kind, name, "delete"); 20956 result[deleteEntityRecordMethodName] = (key, query, options) => { 20957 logEntityDeprecation(kind, name, deleteEntityRecordMethodName, { 20958 isShorthandSelector: true, 20959 alternativeFunctionName: "deleteEntityRecord" 20960 }); 20961 return deleteEntityRecord(kind, name, key, query, options); 20962 }; 20963 return result; 20964 }, {}); 20965 var storeConfig = () => ({ 20966 reducer: reducer_default2, 20967 actions: { 20968 ...dynamicActions, 20969 ...actions_exports, 20970 ...entityActions, 20971 ...createLocksActions() 20972 }, 20973 selectors: { 20974 ...dynamicSelectors, 20975 ...selectors_exports, 20976 ...entitySelectors 20977 }, 20978 resolvers: { ...resolvers_exports, ...entityResolvers } 20979 }); 20980 var store = (0, import_data15.createReduxStore)(STORE_NAME, storeConfig()); 20981 unlock2(store).registerPrivateSelectors(private_selectors_exports); 20982 unlock2(store).registerPrivateActions(private_actions_exports); 20983 (0, import_data15.register)(store); 20984 return __toCommonJS(index_exports); 20985})(); 20986(window.wp ||= {}).coreData = wp.coreData; 20987})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.