@docx-editor.dev/pro 2.26.0 → 2.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/chunk-6CDC4KCE.js +4 -0
  2. package/dist/chunk-6SR5OK66.cjs +4 -0
  3. package/dist/chunk-HZEWGK5A.cjs +4 -0
  4. package/dist/chunk-PVRTSPHN.cjs +1 -0
  5. package/dist/chunk-Q7P2DQ33.js +1 -0
  6. package/dist/chunk-RGR2BLZD.js +4 -0
  7. package/dist/collaboration/hocuspocus.cjs +1 -1
  8. package/dist/collaboration/hocuspocus.js +1 -1
  9. package/dist/collaboration/index.cjs +2 -2
  10. package/dist/collaboration/index.js +1 -1
  11. package/dist/collaboration/webrtc.cjs +1 -1
  12. package/dist/collaboration/webrtc.js +1 -1
  13. package/dist/{define-custom-node-CkjSwcxy.d.cts → define-custom-node-DG5gpRa5.d.cts} +2 -0
  14. package/dist/{define-custom-node-DA6UEXID.d.ts → define-custom-node-DUJ4ZZdo.d.ts} +2 -0
  15. package/dist/document-session-32FPPQHT.js +1 -0
  16. package/dist/document-session-32ULDU2C.js +1 -0
  17. package/dist/document-session-HCU2O55L.cjs +1 -0
  18. package/dist/document-session-ZOM2KHHX.cjs +1 -0
  19. package/dist/{hocuspocus-QIIKEK6J.js → hocuspocus-BMF7MTMJ.js} +1 -1
  20. package/dist/{hocuspocus-BCQPTL3M.cjs → hocuspocus-JPJOC6ZV.cjs} +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +1 -1
  25. package/dist/react/index.cjs +2 -2
  26. package/dist/react/index.d.cts +2 -2
  27. package/dist/react/index.d.ts +2 -2
  28. package/dist/react/index.js +2 -2
  29. package/dist/vue/hocuspocus.cjs +1 -1
  30. package/dist/vue/hocuspocus.js +1 -1
  31. package/dist/vue/index.cjs +2 -2
  32. package/dist/vue/index.d.cts +2 -0
  33. package/dist/vue/index.d.ts +2 -0
  34. package/dist/vue/index.js +2 -2
  35. package/dist/vue/webrtc.cjs +1 -1
  36. package/dist/vue/webrtc.js +1 -1
  37. package/dist/{webrtc-TIHZFB4K.cjs → webrtc-MM3LDVLU.cjs} +1 -1
  38. package/dist/{webrtc-54VKWBFN.js → webrtc-RYONN7E7.js} +1 -1
  39. package/package.json +4 -4
  40. package/dist/chunk-3JW4VNG5.js +0 -4
  41. package/dist/chunk-JDLJS5RD.cjs +0 -4
  42. package/dist/chunk-MRW46GJW.js +0 -4
  43. package/dist/chunk-OMUXC73J.cjs +0 -1
  44. package/dist/chunk-PQNLQ2P2.js +0 -1
  45. package/dist/chunk-VCMQFPO2.cjs +0 -4
  46. package/dist/document-session-6X24KXAM.js +0 -1
  47. package/dist/document-session-BDVKTCYX.js +0 -1
  48. package/dist/document-session-NECF3VT6.cjs +0 -1
  49. package/dist/document-session-RKQQLHEL.cjs +0 -1
@@ -0,0 +1,4 @@
1
+ import*as I from'yjs';import {writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,readOoxmlPackage,WML_NAMESPACE_URI,isStoryPart,normalizeParagraphIdentity,withPart,TreePackageStore,ORIGIN_IDS,isDangerousKey,normalizePartName,DATASTORE_NAMESPACE_URI,CUSTOM_XML_REL,CUSTOM_XML_PROPS_REL,buildRelationshipSet,resolveRelationship,XML_NAMESPACE_URI}from'@docx-editor.dev/core/store';import {historyGroupOfJournal,reportHistoryGroup,registerUndoHistoryPosition}from'@docx-editor.dev/core/collaboration/replication';import {createCollaborationStatusTracker,safeParticipantColor}from'@docx-editor.dev/core/collaboration';import {sha256FontBytes}from'@docx-editor.dev/core/layout';var Xe=new WeakMap;function oe(n){return Xe.get(n)}var Y=Object.freeze({maxNodes:2e5,maxTreeDepth:256,maxTextLength:1048576,maxAttributes:4096,maxChildren:1e5,maxParts:512,maxRelationships:1e4,maxBlobBytes:32*1024*1024,maxDigestLength:80,maxMediaTypeLength:256,maxStorageKeyLength:512,maxStringLength:4096}),Ir=/^sha256:[0-9a-f]{64}$/;function Pt(n){return n?Object.freeze({...Y,...n}):Y}function g(n){return isDangerousKey(n)?"prototype-key":null}function A(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function P(n){let e=g(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function Ot(n){for(let e of Object.keys(n)){let t=g(e);if(t)return t}return !Ir.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>Y.maxBlobBytes?"blob-too-large":A(n.mediaType,Y.maxMediaTypeLength)||n.mediaType.length===0||A(n.storageKey,Y.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var Sr="https://www.docx-editor.dev/docs/latest/pro/collaboration-versions",y=class extends Error{constructor(t,r){let o=t==="collaboration-format-mismatch"||t==="protocol-version-mismatch"||t==="schema-version-mismatch",i=r?`${t}: ${r}`:t;super(o?`${i}
2
+ Collaboration upgrade required. Save local changes and use a compatible app version, or upgrade the saved room. See ${Sr}`:i);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};var K=Object.freeze({protocolVersion:1,sharedSchemaVersion:3,repairVersion:1,canonicalModelVersion:1});function At(n){let e=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{};for(let t of Object.keys(K)){let r=K[t],o=Object.hasOwn(e,t)?e[t]:void 0;if(o===r)continue;let i=o===void 0?"missing":typeof o=="number"&&Number.isSafeInteger(o)?String(o):"invalid";return {code:t==="protocolVersion"?"protocol-version-mismatch":"schema-version-mismatch",detail:`${t}: expected ${r}, received ${i}`}}return null}var Er=K.protocolVersion,Rr=K.sharedSchemaVersion,Lr=K.repairVersion,wr=K.canonicalModelVersion,Cr="docx-package-meta-v1",Ge="docx-package-nodes-v1",kr="docx-package-parts-v1",Pr="docx-package-rels-v1",Or="docx-package-overrides-v1",Ar="docx-package-defaults-v1",Tr="docx-package-binaries-v1",Nr="docx-package-namespaces-v1",Mr="docx-package-attributes-v1",Dr="docx-package-bindings-v1",Se="s",Ee="b",M="t",Re="children",U="deleted",G="replacedBy",He="splitFrom",ie="splitLineage";var k="",Tt="-",Nt=Object.freeze({kind:"docx-package-bootstrap"}),Mt=Object.freeze({kind:"docx-package-journal"});function H(n){return n.kind==="textValue"}function L(n){return !H(n)}var Br=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),_r=200;function Le(n){let e=new Map;for(let t of n)Br.has(t.code)&&e.set(t.code,(e.get(t.code)??0)+1);return e.size===0?null:[...e].sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${t}=${r}`).join(",").slice(0,_r)}function Dt(n){return {meta:n.getMap(Cr),nodes:n.getMap(Ge),parts:n.getMap(kr),relationships:n.getMap(Pr),overrides:n.getMap(Or),defaults:n.getMap(Ar),binaries:n.getMap(Tr),namespaces:n.getMap(Nr),attributes:n.getMap(Mr),bindings:n.getMap(Dr)}}var Bt=[["http://schemas.openxmlformats.org/wordprocessingml/2006/main","w"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships","r"],["http://schemas.openxmlformats.org/package/2006/relationships","pr"],["http://schemas.openxmlformats.org/package/2006/content-types","ct"],["http://www.w3.org/XML/1998/namespace","xml"],["http://www.w3.org/2000/xmlns/","xmlns"],["http://schemas.openxmlformats.org/drawingml/2006/main","a"],["http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing","wp"],["http://schemas.openxmlformats.org/drawingml/2006/picture","pic"],["http://schemas.openxmlformats.org/officeDocument/2006/math","m"],["http://schemas.openxmlformats.org/markup-compatibility/2006","mc"],["http://schemas.microsoft.com/office/word/2010/wordml","w14"],["http://schemas.microsoft.com/office/word/2012/wordml","w15"],["http://schemas.microsoft.com/office/word/2015/wordml/symex","w16se"],["http://schemas.microsoft.com/office/word/2016/wordml/cid","w16cid"],["http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument","od"],["http://schemas.openxmlformats.org/officeDocument/2006/extended-properties","ep"],["http://schemas.openxmlformats.org/package/2006/metadata/core-properties","cp"],["http://purl.org/dc/elements/1.1/","dc"],["http://purl.org/dc/terms/","dcterms"],["http://www.w3.org/2001/XMLSchema-instance","xsi"],["http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes","vt"],["http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas","wpc"],["http://schemas.microsoft.com/office/word/2010/wordprocessingGroup","wpg"],["http://schemas.microsoft.com/office/word/2010/wordprocessingInk","wpi"],["http://schemas.microsoft.com/office/word/2010/wordprocessingShape","wps"],["http://schemas.openxmlformats.org/drawingml/2006/chart","c"],["http://schemas.openxmlformats.org/schemaLibrary/2006/main","sl"]],Yr=new Map(Bt),Ur=new Map(Bt.map(([n,e])=>[e,n]));function zr(n){let e=0xcbf29ce484222325n,t=0x100000001b3n;for(let r=0;r<n.length;r+=1)e^=BigInt(n.charCodeAt(r)),e=e*t&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function ae(n){return n.length===0?Tt:Yr.get(n)??`n${zr(n)}`}function q(n,e,t){let r=ae(e);return e.length===0||g(r)||A(e,t)||n.get(r)!==e&&n.set(r,e),r}function se(n,e){if(e===Tt||g(e))return "";let t=n.get(e);return typeof t=="string"?t:Ur.get(e)??""}function qe(n,e,t,r){return `${n}${k}${e}${k}${t}${k}${r}`}function jr(n){let e=n.split(k);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function le(n){let e=n.has(Se)?n.get(Se):n.get(Ee);return jr(typeof e=="string"?e:"")}function Ze(n,e,t){return `${n}${k}${e}${k}${t}`}function Z(n){let e=n.split(k);if(e.length!==3)return null;let t=e[0],r=e[1],o=e[2];return t.length===0||o.length===0?null:{logicalId:t,namespaceId:r,localName:o}}function Qe(n,e){return `${n}${k}${e}`}function z(n){let e=n.split(k);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function _t(n,e){return `${n}${k}${e}`}function Yt(n){let e=n.indexOf(k);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Ut(n){let e=new I.Map,t=qe(n.kind,n.namespaceId,n.localName,n.prefix??"");e.set(Ee,t);let r=new I.Array;return n.childIds&&n.childIds.length>0&&r.push([...n.childIds]),e.set(Re,r),e}function we(n){let e=new I.Map;return e.set(M,new I.Text(n)),e}function zt(n,e,t){let r=new I.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function jt(n){let e=new I.Map;return e.set("ownerPart",n.ownerPart),e.set("id",n.id),e.set("type",n.type),e.set("rawTarget",n.rawTarget),e.set("targetMode",n.targetMode),e.set("order",n.order),e}function Ft(n){let e=new I.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Q(n){return At({protocolVersion:n.get("protocolVersion"),sharedSchemaVersion:n.get("sharedSchemaVersion"),repairVersion:n.get("repairVersion"),canonicalModelVersion:n.get("canonicalModelVersion")})}function Kt(n){n.set("protocolVersion",Er),n.set("sharedSchemaVersion",Rr),n.set("repairVersion",Lr),n.set("canonicalModelVersion",wr),n.set("initialized",true);}function S(n){return n instanceof I.Map}function D(n){if(!S(n))return null;let e=n.get(Re);return e instanceof I.Array?e:null}function de(n){return S(n)&&n.get(M)instanceof I.Text}function V(n){return S(n)&&n.get(U)===true}function et(n){if(!S(n))return null;let e=n.get(G);return typeof e=="string"&&e.length>0?e:null}function ce(n){if(!S(n))return null;let e=n.get(He);return typeof e=="string"&&e.length>0?e:null}function tt(n){if(!S(n))return null;let e=n.get(ie);return typeof e=="string"&&e.length>0?e:ce(n)}function Vt(n,e){let t=[],r=[{id:e,depth:0}],o=new Set,i=0;for(;r.length>0;){let{id:a,depth:s}=r.pop();if(o.has(a)||s>n.limits.maxTreeDepth)return null;o.add(a);let l=n.record(a);if(!l)return null;if(H(l)){let d=n.projectedTextValue(a)??l.value;if(i+=d.length,i>n.limits.maxTextLength)return null;t.push({id:a,value:d});}else if(L(l)&&!l.kind.endsWith("Properties"))for(let d=l.childIds.length-1;d>=0;d-=1)r.push({id:l.childIds[d],depth:s+1});}return t}function ue(n,e,t){let r=Vt(n,e),o=[];if(!r||r.length===0)return false;for(let l of t){let d=Vt(n,l);if(!d)return false;for(let p of d)o.push(p);}if(r.map(l=>l.value).join("")!==o.map(l=>l.value).join(""))return false;let i=[],a=0,s=0;for(let l of o){for(;a<r.length-1&&s===r[a].value.length;)a+=1,s=0;let d=r[a];if(!d||s+l.value.length>d.value.length)return false;l.id!==d.id&&i.push({product:l.id,source:d.id,start:s,end:s+l.value.length}),s+=l.value.length;}for(let l of i)n.registerSplitText(l.product,l.source,l.start,l.end);return true}function Ce(n,e,t){return n!=="run"&&n!=="text"?null:e.filter(r=>t(r)===n)}var J=class{constructor(e){this.registry=e;}registry;touched=new Map;created=new Set;has(e){return this.created.has(e)||this.touched.has(e)||this.registry.hasNode(e)}node(e){let t=this.touched.get(e);if(t)return t;let r=this.registry.nodeShape(e);return r?(this.touched.set(e,r),r):null}putNode(e){this.node(e.logicalId)||(this.created.add(e.logicalId),this.touched.set(e.logicalId,{isText:e.kind==="textValue",textLength:0,children:[]}));}spliceText(e,t,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-t)+r);}spliceChildren(e,t,r,o){let i=this.node(e);i&&i.children.splice(t,r,...o);}moveNode(e,t,r){let o=this.parentOf(e);if(o!==null){let s=this.node(o),l=s?.children.indexOf(e)??-1;s&&l>=0&&s.children.splice(l,1);}let i=this.node(t);if(!i)return;let a=Math.min(r,i.children.length);i.children.splice(a,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function pe(n,e){switch(e.kind){case "putNode":n.putNode(e.descriptor);return;case "spliceText":n.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function j(n,e){return g(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:n.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function Fr(n,e,t){if(g(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=t.node(e.logicalId);return r&&r.isText!==(e.kind==="textValue")?{ok:false,code:"invalid-bound",detail:`node class ${e.logicalId}`}:e.kind==="textValue"?null:g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function ke(n,e,t){switch(e.kind){case "putNode":return Fr(n,e.descriptor,t);case "spliceText":{let r=j(t,e.logicalId);if(r)return r;if(!Number.isSafeInteger(e.utf16Start)||!Number.isSafeInteger(e.deleteCount)||e.utf16Start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.insert.length>n.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=t.node(e.logicalId);if(o&&o.isText){if(e.utf16Start+e.deleteCount>o.textLength)return {ok:false,code:"invalid-bound",detail:e.logicalId};if(o.textLength-e.deleteCount+e.insert.length>n.limits.maxTextLength)return {ok:false,code:"text-too-long"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.logicalId};return null}case "setAttribute":{let r=j(t,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>n.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=j(t,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&A(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=j(t,e.parentLogicalId);if(r)return r;if(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.deleteCount)||e.start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let a=j(t,i);if(a)return a}let o=t.node(e.parentLogicalId);if(o&&!o.isText){if(e.start+e.deleteCount>o.children.length)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};if(o.children.length-e.deleteCount+e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};return null}case "moveNode":{let r=j(t,e.logicalId);if(r)return r;let o=j(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=P(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=j(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=P(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=P(e.owner);if(r)return {ok:false,code:r}}return g(e.record.id)?{ok:false,code:"prototype-key"}:n.relationshipCount()>=n.limits.maxRelationships?{ok:false,code:"too-many-relationships"}:null}case "deleteRelationship":return g(e.relationshipId)?{ok:false,code:"prototype-key"}:null;case "putContentTypeOverride":{let r=P(e.partName);return r?{ok:false,code:r}:A(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=P(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=Ot(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return g(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function Kr(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;let r=oe(e);n.spliceText(r?.logicalId??e.logicalId,r?.utf16Start??e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":n.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":n.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":n.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":n.deleteXmlPart(e.name);return;case "putRelationship":n.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":n.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":n.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":n.deleteContentTypeOverride(e.partName);return;case "putBinary":n.putBinary(e.descriptor);return;case "deleteBinary":n.deleteBinary(e.storageKey);return}}function Vr(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function Jr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Vr(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(a=>o.has(a)))return i.parentLogicalId}}function Wr(n,e){let t=new J(n),r=[],o=new Set,i=new Set,a=new Set,s=new Map;for(let l of e){let d=ke(n,l,t);if(d)return d;if(l.kind==="spliceChildren"){let p=l.deleteCount>0?t.node(l.parentLogicalId):null;if(p&&!p.isText){let h=l.start+l.deleteCount;for(let u=l.start;u<h;u+=1){let m=p.children[u];if(m!==void 0&&(r.push(m),l.childLogicalIds.length>0)){let c=s.get(l)??[];c.push(m),s.set(l,c);}}}for(let h of l.childLogicalIds)o.add(h);}else l.kind==="moveNode"?o.add(l.logicalId):l.kind==="putNode"&&(a.add(l.descriptor.logicalId),l.descriptor.kind==="textValue"&&i.add(l.descriptor.logicalId));pe(t,l);}return {removed:r,reinserted:o,mintedText:i,mintedNodes:a,replacementsByEffect:s}}function $r(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function nt(n,e){if(n.nodeCount()+$r(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=Wr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=qr(n,t.removed);for(let o of e.effects)Kr(n,o,t.mintedText),o.kind==="spliceChildren"&&Gr(n,t,t.replacementsByEffect.get(o)??[],o.childLogicalIds);Xr(n,e.effects,t,r);},Mt),{ok:true})}function Xr(n,e,t,r){if(t.removed.length===0)return;let o=new Set;for(let i of n.partEntries())o.add(i.rootLogicalId);for(let i of t.removed){if(t.reinserted.has(i)||!n.hasNode(i)||n.isTombstoned(i)||o.has(i))continue;let a=Jr(n,i,r,e);a&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,a);}}function Gr(n,e,t,r){for(let o of t){let i=n.kindOf(o);if(i!=="run"&&i!=="text"||e.reinserted.has(o)&&!e.mintedNodes.has(o))continue;let a=Hr(n,o,e.reinserted);if(i==="text"){let l=Ce(i,r,d=>n.kindOf(d));if(l&&ue(n,o,l)){let d=r.filter(p=>e.mintedNodes.has(p));n.recordRunSplit(a,o,d);}continue}let s=r.filter(l=>n.kindOf(l)==="run");ue(n,o,s),n.recordRunSplit(a,o,s);}}function Hr(n,e,t){let r=e;for(let o=0;o<n.limits.maxTreeDepth&&t.has(r);o+=1){let i=n.splitOriginOf(r);if(i===null||i===r)break;r=i;}return r}function qr(n,e){let t=new Map;for(let r of e){let o=n.nodeShape(r);o&&!o.isText&&t.set(r,o.children);}return t}var B="splitTextSource",Zr=Object.freeze({kind:"docx-package-restored-split-anchors"});function T(n,e){throw new y(n,e)}function rt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Jt(n){return rt(n)&&Object.keys(n).every(e=>e==="client"||e==="clock")&&Number.isSafeInteger(n.client)&&n.client>=0&&Number.isSafeInteger(n.clock)&&n.clock>=0}function Wt(n){return !rt(n)||!Object.keys(n).every(e=>["type","item","assoc"].includes(e))||!Jt(n.type)||n.item!==void 0&&!Jt(n.item)||n.assoc!==0&&n.assoc!==-1?T("invalid-string",B):I.createRelativePositionFromJSON(n)}var ee=class{constructor(e,t,r){this.nodes=e;this.doc=t;this.limits=r;}nodes;doc;limits;sourceByAlias=new Map;aliasesBySource=new Map;pending=new Set;values=new Map;register(e,t,r,o){let i=this.nodes.get(e);(!S(i)||!(i.get(M)instanceof I.Text))&&T("invalid-bound",e);let a=this.read(t),s=a===null?{sourceId:t,text:this.sourceText(t),start:0,end:this.sourceText(t).length}:this.resolve(a);(s.sourceId.length===0||s.sourceId.length>this.limits.maxStringLength||g(s.sourceId))&&T("invalid-string",t),(!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||r<0||o<r||o>s.end-s.start||e===s.sourceId)&&T("invalid-bound",e);let l=(p,h)=>{if(a&&h==="end"&&p===s.end-s.start)return a.end;if(a&&p===0)return a.start;if(a&&p===s.end-s.start)return a.end;let u=s.start+p;return I.createRelativePositionFromTypeIndex(s.text,u,u===0&&h==="start"?-1:0)},d=JSON.stringify({sourceId:s.sourceId,start:I.relativePositionToJSON(l(r,"start")),end:I.relativePositionToJSON(l(o,"end"))});d.length>this.limits.maxStringLength&&T("invalid-string",e),i.set(B,d),this.indexExisting(e);}normalizeRestoredAnchors(){let e=new Map,t=o=>{let i=o.item;if(i===null)return o;let a=`${i.client}:${i.clock}:${o.assoc}`,s=e.get(a);if(s)return s;let l=i,d=I.getItem(this.doc.store,l);for(;d instanceof I.Item&&d.redone!==null;)l=I.createID(d.redone.client,d.redone.clock+l.clock-d.id.clock),d=I.getItem(this.doc.store,l);let p=d instanceof I.Item&&!d.deleted&&!I.compareIDs(i,l)?I.createRelativePositionFromJSON({...I.relativePositionToJSON(o),item:{client:l.client,clock:l.clock}}):o;return e.set(a,p),p},r=[];for(let o of this.sourceByAlias.keys()){let i=this.read(o);if(!i)continue;let a=t(i.start),s=t(i.end);if(I.compareRelativePositions(a,i.start)&&I.compareRelativePositions(s,i.end))continue;let l=JSON.stringify({sourceId:i.sourceId,start:I.relativePositionToJSON(a),end:I.relativePositionToJSON(s)});l.length>this.limits.maxStringLength&&T("invalid-string",o),r.push({id:o,encoded:l});}r.length!==0&&this.doc.transact(()=>{for(let{id:o,encoded:i}of r)this.nodes.get(o).set(B,i),this.indexExisting(o);},Zr);}sourceAliases(e){return [...this.aliasesBySource.get(e)??[]]}range(e){let t=this.read(e);return t===null?null:this.resolve(t)}value(e){let t=this.range(e);return t===null?null:t.text.toString().slice(t.start,t.end)}indexExisting(e){let t=this.read(e);t&&this.resolve(t);let r=this.sourceByAlias.get(e);if(r!==void 0&&r!==t?.sourceId){let o=this.aliasesBySource.get(r);o?.delete(e),o?.size===0&&this.aliasesBySource.delete(r),this.sourceByAlias.delete(e);}if(t){this.sourceByAlias.set(e,t.sourceId);let o=this.aliasesBySource.get(t.sourceId)??new Set;o.add(e),this.aliasesBySource.set(t.sourceId,o);}(t||r!==void 0||this.values.has(e))&&this.pending.add(e);}noteChanged(e){this.indexExisting(e);for(let t of this.aliasesBySource.get(e)??[])this.pending.add(t);}reset(){this.sourceByAlias.clear(),this.aliasesBySource.clear();for(let e of this.values.keys())this.pending.add(e);this.nodes.forEach((e,t)=>this.indexExisting(t));}overlays(){let e=new Set,t=new Map;for(let r of this.pending){let o=this.range(r),i=null;if(o){let a=t.get(o.sourceId);a===void 0&&(a=o.text.toString(),t.set(o.sourceId,a)),i=a.slice(o.start,o.end);}i===null?this.values.delete(r)&&e.add(r):i!==this.values.get(r)&&(this.values.set(r,i),e.add(r));}return this.pending.clear(),{values:this.values,changedIds:e}}sourceText(e){let t=this.nodes.get(e),r=S(t)?t.get(M):null;return !(r instanceof I.Text)||r.doc!==this.doc||r.length>this.limits.maxTextLength?T("invalid-bound",e):r}read(e){let t=this.nodes.get(e);if(!S(t)||!t.has(B))return null;let r=t.get(B);if(typeof r!="string"||r.length>this.limits.maxStringLength)return T("invalid-string",e);let o;try{o=JSON.parse(r);}catch{return T("invalid-string",e)}return !rt(o)||!Object.keys(o).every(i=>["sourceId","start","end"].includes(i))||typeof o.sourceId!="string"||o.sourceId.length===0||o.sourceId.length>this.limits.maxStringLength||g(o.sourceId)||o.sourceId===e?T("invalid-string",e):t.get(M)instanceof I.Text?{sourceId:o.sourceId,start:Wt(o.start),end:Wt(o.end)}:T("invalid-bound",e)}resolve(e){let t=this.nodes.get(e.sourceId);if(S(t)&&t.has(B))return T("invalid-bound",e.sourceId);let r=this.sourceText(e.sourceId),o=I.createRelativePositionFromTypeIndex(r,0).type;if(!o||[e.start,e.end].some(s=>s.type?.client!==o.client||s.type?.clock!==o.clock))return T("invalid-bound",e.sourceId);let i=I.createAbsolutePositionFromRelativePosition(e.start,this.doc,false),a=I.createAbsolutePositionFromRelativePosition(e.end,this.doc,false);return i===null||a===null||i.type!==r||a.type!==r||i.index<0||a.index<i.index||a.index>r.length?T("invalid-bound",e.sourceId):{sourceId:e.sourceId,text:r,start:i.index,end:a.index,startAssoc:e.start.assoc,endAssoc:e.end.assoc,startAnchorDeleted:e.start.item!==null&&I.getItem(this.doc.store,e.start.item).deleted,endAnchorDeleted:e.end.item!==null&&I.getItem(this.doc.store,e.end.item).deleted}}};function Pe(n,e,t,r,o,i){if(!r||i.length===0)return null;let a=o===0&&r.startAssoc!==-1,s=o===r.end-r.start;if(!a&&!s)return null;let l=JSON.parse(n.get(t).get(B)),d=I.createRelativePositionFromJSON(l.start),p=I.createRelativePositionFromJSON(l.end);if(s=s&&(a||p.item!==null&&I.getItem(r.text.doc.store,p.item).deleted),!a&&!s)return null;let h=[];for(let u of e.sourceAliases(r.sourceId)){if(!e.range(u))continue;let m=n.get(u),c=JSON.parse(m.get(B)),f=(R,E)=>{let x=I.createRelativePositionFromJSON(R);return a&&s&&I.compareRelativePositions(d,p)&&I.compareRelativePositions(x,d)?E==="start"?"after":"before":a&&I.compareRelativePositions(x,d)?"before":s&&I.compareRelativePositions(x,p)?"after":null},b=u===t&&a?"before":f(c.start,"start"),v=u===t&&s?"after":f(c.end,"end");(b||v)&&h.push({record:m,start:b,end:v});}return ()=>{let u=r.start+o,m=I.relativePositionToJSON(I.createRelativePositionFromTypeIndex(r.text,u,u===0&&r.startAssoc===-1?-1:0)),c=I.relativePositionToJSON(I.createRelativePositionFromTypeIndex(r.text,u+i.length,0));for(let f of h){let b=JSON.parse(f.record.get(B));f.start&&(b.start=f.start==="before"?m:c),f.end&&(b.end=f.end==="before"?m:c);let v=JSON.stringify(b);v!==f.record.get(B)&&f.record.set(B,v);}}}function $t(n,e,t){if(t.keepBoundary&&n===t.start)return n;let r=n<=t.start?n:Math.max(t.start,n-t.deleted);return r<t.start||r===t.start&&e<0?r:r+t.inserted.length}var ot=class{constructor(e,t){this.registry=e;this.raw=t;}registry;raw;ranges=new Map;histories=new Map;strings=new Map;actions=[];shadow=null;range(e){if(this.shadow){let r=this.shadow.sources.range(e);return r?{...r,revision:0}:null}if(!this.ranges.has(e)){let r=this.registry.splitTextRange(e);this.ranges.set(e,r?{...r,revision:0}:null);}let t=this.ranges.get(e);if(t){let r=this.histories.get(t.sourceId)??[];for(;t.revision<r.length;){let o=r[t.revision],i=(a,s)=>{let l=s<0?a-1:a;return l>=o.start&&l<o.start+o.deleted};if(t.startAnchorDeleted||t.endAnchorDeleted||o.ambiguousBoundary||i(t.start,t.startAssoc)||i(t.end,t.endAssoc)){this.ensureShadow();let a=this.shadow.sources.range(e);return a?{...a,revision:0}:null}t.start=$t(t.start,t.startAssoc,o),t.end=$t(t.end,t.endAssoc,o),t.revision+=1;}}return t}value(e){let t=this.range(e);if(t)return this.value(t.sourceId).slice(t.start,t.end);let r=this.strings.get(e);if(r===void 0){r=this.registry.hasNode(e)?this.registry.textOf(e).toString():"";for(let o of this.histories.get(e)??[])r=r.slice(0,o.start)+o.inserted+r.slice(o.start+o.deleted);this.strings.set(e,r);}return r}apply(e){let t=oe(e),r=t?this.range(t.logicalId):null,o={keepBoundary:t?.utf16Start===0&&r?.startAssoc!==-1&&e.insert.length>0,ambiguousBoundary:r!==null&&r.start===r.end&&e.insert.length>0,start:e.utf16Start,deleted:e.deleteCount,inserted:e.insert},i=this.histories.get(e.logicalId)??[];i.push(o),this.histories.set(e.logicalId,i);let a=this.strings.get(e.logicalId);a!==void 0&&this.strings.set(e.logicalId,a.slice(0,o.start)+o.inserted+a.slice(o.start+o.deleted));let s={kind:"splice",effect:e};this.actions.push(s),this.shadow&&this.replay(s);}register(e,t,r,o){let i=this.range(t),a=i?.sourceId??t,s=i?.start??0,l=i?i.end-i.start:this.raw.node(t)?.textLength??0,d=(m,c)=>i&&c==="end"&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:i&&m===0?{assoc:i.startAssoc,deleted:i.startAnchorDeleted}:i&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:{assoc:s+m===0&&c==="start"?-1:0,deleted:false},p=d(r,"start"),h=d(o,"end");this.ranges.set(e,{sourceId:a,start:s+r,end:s+o,startAssoc:p.assoc,endAssoc:h.assoc,startAnchorDeleted:p.deleted,endAnchorDeleted:h.deleted,revision:this.histories.get(a)?.length??0});let u={kind:"register",product:e,source:t,start:r,end:o};this.actions.push(u),this.shadow&&this.replay(u);}destroy(){this.shadow?.doc.destroy();}ensureShadow(){if(this.shadow)return;let e=new I.Doc({gc:false}),t=e.getMap(Ge);this.shadow={doc:e,nodes:t,sources:new ee(t,e,this.registry.limits)},I.applyUpdate(e,I.encodeStateAsUpdate(this.registry.doc)),e.clientID=this.registry.doc.clientID,this.shadow.sources.reset();for(let r of this.actions)this.replay(r);}replay(e){let t=this.shadow,r=h=>(t.nodes.has(h)||t.nodes.set(h,we("")),t.nodes.get(h).get(M));if(e.kind==="register"){r(e.product),t.sources.register(e.product,e.source,e.start,e.end);return}let{effect:o}=e,i=oe(o),a=i?t.sources.range(i.logicalId):null,s=a?.text??r(o.logicalId),l=i?.utf16Start??o.utf16Start,d=(a?.start??0)+l,p=Pe(t.nodes,t.sources,i?.logicalId??o.logicalId,a,l,o.insert);o.deleteCount>0&&s.delete(d,o.deleteCount),o.insert.length>0&&s.insert(d,o.insert),p?.();}},it=class extends J{constructor(t,r,o,i){super(t);this.hidden=r;this.raw=o;this.text=i;}hidden;raw;text;filtered=new Set;node(t){let r=super.node(t);if(r&&!this.filtered.has(t)&&(this.filtered.add(t),r.children=r.children.filter(o=>!this.hidden.has(o))),r?.isText){let o=this.text.range(t);r.textLength=o?o.end-o.start:this.raw.node(t)?.textLength??r.textLength;}return r}};function Xt(n,e){let t=n.replacementLoserRuns(),r=e.effects.filter(c=>c.kind==="putNode").length;if(n.nodeCount()+r>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let o=new Set;for(let c of e.effects){if(c.kind==="spliceChildren"){if(c.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let f of c.childLogicalIds)o.add(f);}else c.kind==="moveNode"&&o.add(c.logicalId);if(o.size>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"}}let i=new J(n),a=new ot(n,i),s=new it(n,t,i,a),l=new Map,d=c=>l.get(c)?.kind??n.kindOf(c),p={limits:n.limits,projectedTextValue:c=>i.node(c)?.isText?a.value(c):null,registerSplitText:(c,f,b,v)=>a.register(c,f,b,v),record:c=>{let f=i.node(c);if(!f)return null;if(f.isText)return {logicalId:c,kind:"textValue",value:a.value(c)};let b=l.get(c),v=b?null:n.record(c);return v&&v.kind!=="textValue"?{...v,childIds:f.children}:!b||b.kind==="textValue"?null:{logicalId:c,kind:b.kind,namespaceUri:b.qname.namespaceUri,localName:b.qname.localName,prefix:b.qname.prefix??"",attributes:[],bindings:[],childIds:f.children}}},h=[],u=null,m=c=>{if(u)return;let f=ke(n,c,i);if(f&&!f.ok){u=f;return}h.push(c),pe(i,c),c.kind==="spliceText"&&a.apply(c);};try{for(let c of e.effects){let f=ke(n,c,s);if(f&&!f.ok)return f;if(pe(s,c),c.kind==="putNode"&&l.set(c.descriptor.logicalId,c.descriptor),c.kind==="spliceText"){let b=a.range(c.logicalId),v=b?{...c,logicalId:b.sourceId,utf16Start:b.start+c.utf16Start}:c;b&&Xe.set(v,{logicalId:c.logicalId,utf16Start:c.utf16Start}),m(v);}else if(c.kind==="spliceChildren"){let b=i.node(c.parentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let v=b.children.flatMap((x,O)=>t.has(x)?[]:[O]),R=v.slice(c.start,c.start+c.deleteCount).map(x=>b.children[x]),E=v[c.start]??b.children.length;if(c.deleteCount===0)m({...c,start:E});else {let x=v.slice(c.start,c.start+c.deleteCount),O=x.length;for(;O>0;){let _=O-1;for(;_>0&&x[_-1]===x[_]-1;)_-=1;m({...c,start:x[_],deleteCount:O-_,childLogicalIds:_===0?c.childLogicalIds:[]}),O=_;}}if(!u&&c.childLogicalIds.length>0)for(let x of R){if(o.has(x)&&!l.has(x))continue;let O=Ce(d(x),c.childLogicalIds,d);O&&ue(p,x,O);}}else if(c.kind==="moveNode"){let b=i.node(c.destinationParentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let v=b.children.filter(E=>E!==c.logicalId),R=v.flatMap((E,x)=>t.has(E)?[]:[x]);m({...c,destinationIndex:R[c.destinationIndex]??v.length});}else m(c);if(u)return u}return {ok:!0,journal:{effects:h}}}finally{a.destroy();}}var Oe=class{constructor(e,t){this.undoManager=e;let r=o=>{this.capturing&&o.type==="undo"&&(this.gestureItem=o.stackItem,this.captured=true);};e.on("stack-item-added",r),e.on("stack-item-updated",r),t&&to(t,e,()=>this.reset());}undoManager;previous;gestureItem;capturing=false;captured=false;capture(e,t){let r=this.previous;this.previous=e;let o=this.undoManager.undoStack,i=this.undoManager.captureTimeout;e===r&&e!==void 0&&o[o.length-1]===this.gestureItem?(this.undoManager.lastChange=Date.now(),this.undoManager.captureTimeout=Number.POSITIVE_INFINITY):((e!==r||e!==void 0)&&this.undoManager.stopCapturing(),this.gestureItem=void 0);let a=this.gestureItem;this.captured=false,this.capturing=e!==void 0;try{let s=t();return this.captured&&reportHistoryGroup(e,this.gestureItem===a?"extended":"started"),s}catch(s){throw this.reset(),s}finally{this.capturing=false,this.undoManager.captureTimeout=i;}}reset(){this.previous=void 0,this.gestureItem=void 0;}};function to(n,e,t){let r=new WeakMap,o=i=>{let a=r.get(i);return a||r.set(i,a={}),a};e.on("stack-item-popped",({stackItem:i,type:a})=>{let s=(a==="undo"?e.redoStack:e.undoStack).at(-1);s&&r.set(s,o(i));}),registerUndoHistoryPosition(n,{current:()=>{let i=e.undoStack.at(-1);return i?o(i):null},split:()=>{t(),e.stopCapturing(),e.clear(false,true);}});}var no=new Set(["paraId","textId","id","numId","bookmarkId"]);function Gt(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function Ht(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Gt(e)}function Ae(n){return /^[0-9a-f]{32}$/.test(n)}function qt(n,e){if(!Ae(n))throw new Error("invalid replica identity");if(!Number.isSafeInteger(e)||e<0)throw new Error("invalid logical-id counter");return `lid:${n}:${e.toString(10)}`}function at(n,e){return `yjs:${n}:${e}`}function st(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return Ae(e)?e:null}function lt(n){let e=[];for(let t of n)no.has(t.localName)&&e.push(t.value);return e}var he=class{replicaId;next=0;constructor(e){if(this.replicaId=e??Ht(),!Ae(this.replicaId))throw new Error("invalid replica identity")}take(){let e=qt(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};function Zt(n,e){let t=i=>{let a=new Set,s=false;for(let l of i){let d=l.path;if(d.length===0){for(let p of l.changes.keys.keys())a.add(String(p));s=true;continue}a.add(String(d[0])),l.target instanceof I.Array&&(s=true),l.target instanceof I.Map&&(l.changes.keys.has(U)||l.changes.keys.has(G))&&(s=true);}(a.size>0||s)&&e({logicalIds:a,membershipChanged:s,packageChanged:false});},r=i=>{let a=new Set;for(let s of i.changes.keys.keys()){let l=Z(String(s))??z(String(s));!l||g(l.logicalId)||a.add(l.logicalId);}a.size>0&&e({logicalIds:a,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return n.nodes.observeDeep(t),n.attributes.observe(r),n.bindings.observe(r),n.parts.observeDeep(o),n.relationships.observeDeep(o),n.overrides.observe(o),n.defaults.observe(o),n.binaries.observeDeep(o),()=>{n.nodes.unobserveDeep(t),n.attributes.unobserve(r),n.bindings.unobserve(r),n.parts.unobserveDeep(o),n.relationships.unobserveDeep(o),n.overrides.unobserve(o),n.defaults.unobserve(o),n.binaries.unobserveDeep(o);}}var Ne=class{constructor(e){this.nodes=e;}nodes;cachedLosers=null;invalidate(){this.cachedLosers=null;}runsBySplitOrigin=new Map;liveRootedOrigins=new Set;reset(){this.invalidate(),this.runsBySplitOrigin.clear(),this.liveRootedOrigins.clear();}record(e,t,r){this.invalidate();for(let o of r){if(o===e)continue;let i=this.nodes.get(o);S(i)&&(i.set(He,e),i.set(ie,e),this.indexExisting(o));}}indexExisting(e){let t=tt(this.nodes.get(e));if(t===null||t===e)return;this.invalidate();let r=this.runsBySplitOrigin.get(t)??new Set;r.add(e),this.runsBySplitOrigin.set(t,r),this.liveRootedOrigins.add(t);}productsOf(e){return [...this.runsBySplitOrigin.get(e)??[]].filter(t=>tt(this.nodes.get(t))===e)}loserRuns(e){if(this.cachedLosers)return this.cachedLosers;let t=new Set,r=new Set,o=i=>{let a=[i];for(;a.length>0;){let s=a.pop();if(!r.has(s)){r.add(s),e.isPresent(s)&&t.add(s);for(let l of this.productsOf(s))a.push(l);}}};for(let i of this.liveRootedOrigins){let a=this.productsOf(i),s=e.isPresent(i)?null:a.filter(l=>ce(this.nodes.get(l))===i).map(l=>st(l)??"").sort()[0];for(let l of a)(st(l)??"")!==s&&o(l);}return this.cachedLosers=t,t}};function Qt(n,e){if(!n.hasNode(e)||n.isTombstoned(e))return false;let t=n.parentOf(e);if(t===null)return false;let r=n.record(t);return r!==null&&L(r)&&r.childIds.includes(e)}function Me(n){return typeof n=="string"?n:""}function en(n,e){return n<e?-1:n>e?1:0}function dt(n,e){return `${n}${k}${e}`}function oo(n){let e=n.indexOf(k);return e<0?n:n.slice(0,e)}function tn(n){let e=[];return n.forEach((t,r)=>{!S(t)||g(r)||t.forEach(o=>{if(!S(o))return;let i=Me(o.get("id")),a=Me(o.get("type"));if(i.length===0||a.length===0)return;let s=Me(o.get("ownerPart"))||oo(r);if(g(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:Me(o.get("rawTarget")),targetMode:o.get("targetMode")==="External"?"External":"Internal",order:typeof l=="number"&&Number.isSafeInteger(l)?l:0});});}),e.sort((t,r)=>t.order-r.order||en(t.ownerPart,r.ownerPart)||en(t.id,r.id)),e}function nn(n,e){return n.nodes.observeDeep(e.onNodeEvents),n.attributes.observe(e.onAttributeEvent),n.bindings.observe(e.onBindingEvent),n.relationships.observeDeep(e.onRelationshipChange),n.parts.observeDeep(e.onPartChange),()=>{n.nodes.unobserveDeep(e.onNodeEvents),n.attributes.unobserve(e.onAttributeEvent),n.bindings.unobserve(e.onBindingEvent),n.relationships.unobserveDeep(e.onRelationshipChange),n.parts.unobserveDeep(e.onPartChange);}}function io(n,e){let t=Math.min(n.length,e.length);for(let r=0;r<t;r+=1){let o=n[r]-e[r];if(o!==0)return o}return n.length-e.length}function rn(n,e){let t=n.childrenSnapshot.get(e);return t||(D(n.nodes.get(e))?.toArray()??[])}function ao(n,e){let t=n.nodes.get(e);return !S(t)||V(t)}function so(n,e,t,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),ao(n,a)))return null;s=e.get(a);let p=n.parentIndex.get(a);if(s!==void 0){if(p!==void 0)return "fallback";break}if(p===void 0)return t.has(a)?"deferred":null;o.push(a),a=p;}let l=[s],d=a;for(let p=o.length-1;p>=0;p-=1){let h=o[p],u=rn(n,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function on(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,a)=>{r.has(i)||r.set(i,a);});let o=[...t];for(;o.length>0;){let i=[];for(let a of o){let s=null,l=false;for(let d of n.listings.get(a)??[]){if(d===a)continue;let p=so(n,r,t,d);if(p==="fallback")return false;if(p==="deferred"){l=true;continue}if(p===null)continue;let h=rn(n,d).indexOf(a);if(h<0)continue;let u=[...p,h];(!s||io(u,s.rank)<0)&&(s={rank:u,parent:d});}if(l){i.push(a);continue}s&&n.parentIndex.set(a,s.parent),t.delete(a);}if(i.length===o.length)return false;o=i;}return true}function an(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let a of e)r.delete(a);for(let a of i){let s=new Set,l=[{id:a,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){s.delete(d.id);continue}let p=d.id;if(d.parent!==null&&(e===null||e.has(p))&&(r.has(p)||r.set(p,d.parent)),s.has(p))continue;let h=t.get(p);if(!S(h)||V(h))continue;let u=o.get(p)??D(h)?.toArray()??[];s.add(p),l.push({id:p,parent:null,exit:true});let m=new Set,c=[];for(let f of u)m.has(f)||f===p||(m.add(f),c.push(f));for(let f=c.length-1;f>=0;f-=1)l.push({id:c[f],parent:p,exit:false});}}}function sn(n,e){return `${n}${k}${e}`}function ct(n,e,t,r,o){if(g(t)||g(r.localName))return;let i=q(n.namespaces,r.namespaceUri,e),a=Ze(t,i,r.localName);g(a)||n.attributes.set(a,_t(r.prefix??"",o));}function ln(n,e,t,r){n.attributes.delete(Ze(e,ae(t),r));}function ut(n,e,t,r,o){if(g(t)||g(r))return;let i=q(n.namespaces,o,e),a=Qe(t,r);g(a)||n.bindings.set(a,i);}function dn(n,e,t){n.bindings.delete(Qe(e,t));}function pt(n,e,t,r,o,i){let{prefix:a,value:s}=Yt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(sn(r,o),{namespaceUri:se(n.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function lo(n,e,t,r){let o=n.get(e);o&&(o.delete(sn(t,r)),o.size===0&&n.delete(e));}function ht(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:se(n.namespaces,o)});}function co(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function cn(n,e,t){for(let[r,o]of t.changes.keys){let i=Z(String(r));if(!i||g(i.logicalId)||g(i.localName))continue;if(o.action==="delete"){lo(e,i.logicalId,i.namespaceId,i.localName);continue}let a=n.attributes.get(String(r));typeof a=="string"&&pt(n,e,i.logicalId,i.namespaceId,i.localName,a);}}function un(n,e,t){for(let[r,o]of t.changes.keys){let i=z(String(r));if(!i||g(i.logicalId)||g(i.prefix))continue;if(o.action==="delete"){co(e,i.logicalId,i.prefix);continue}let a=n.bindings.get(String(r));typeof a=="string"&&ht(n,e,i.logicalId,i.prefix,a);}}function hn(n,e){let t=n.get(e);if(!S(t))return null;if(de(t)){let r=t.get(M);return {isText:true,textLength:r instanceof I.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:D(t)?.toArray()??[]}}function mn(n,e){let t=n.get(e);return S(t)?de(t)?"textValue":le(t).kind:null}function gn(n,e){if(n.length!==e.length)return false;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return false;return true}function fn(n,e,t,r,o){let i=le(e);return {logicalId:n,kind:i.kind,namespaceUri:se(t.namespaces,i.namespaceId),localName:i.localName,prefix:i.prefix.length>0?i.prefix:void 0,attributes:r,bindings:o,childIds:D(e)?.toArray()??[]}}function ne(n){return typeof n=="string"?n:""}function yn(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||g(r))return;let o=ne(t.get("rootId"));o.length!==0&&e.push({name:r,id:ne(t.get("id")),rootLogicalId:o,contentType:ne(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function bn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(partNameKey(r),t);}),e}function xn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(r,t);}),e}function In(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||g(r))return;let o=ne(t.get("digest")),i=t.get("size"),a=ne(t.get("mediaType")),s=ne(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:a,storageKey:s});}),e}var mt="/word/numbering.xml",po="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";function vn(n,e){let t=e.parent;if(t===n.bindings&&e.parentSub){let s=z(e.parentSub),l=s&&n.nodes.get(s.logicalId);if(l){let d=le(l);if(d.localName==="numbering"&&n.namespaces.get(d.namespaceId)==="http://schemas.openxmlformats.org/wordprocessingml/2006/main")return true}}if(t===n.overrides&&e.parentSub===mt||t===n.parts&&e.parentSub===mt)return true;let r=t?._item;if(r?.parent===n.parts&&r.parentSub===mt)return true;let o=s=>s instanceof I.Map&&s.get("type")===po,i=s=>s instanceof I.Map&&[...s.values()].some(o);return t===n.relationships?e.content.getContent().some(i):r?.parent===n.relationships?e.content.getContent().some(o):r?.parent?._item?.parent===n.relationships&&o(t)}function ho(n){return n?._item??null}function mo(n){return n.content instanceof I.ContentType}function En(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=ho(t);return r===null||r.parent!==n?true:e.parentSub===ie||e.parentSub===Ee?false:!mo(e)}}function go(n){let e=n._item;return e?at(e.id.client,e.id.clock):null}function fo(n){return typeof n=="string"?n:""}var W=class{constructor(e,t){this.doc=e;this.schema=Dt(e),this.limits=Pt(t),this.splitDedup=new Ne(this.schema.nodes),this.splitTextSources=new ee(this.schema.nodes,this.doc,this.limits),this.stopObserving=nn(this.schema,{onNodeEvents:r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);},onAttributeEvent:r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);},onBindingEvent:r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);},onRelationshipChange:()=>{this.relationshipCountCache=-1;},onPartChange:()=>{this.partCountCache=-1;}});}doc;schema;limits;parentIndex=new Map;listings=new Map;childrenSnapshot=new Map;adoptees=new Map;tombstoneSources=new Map;tombstoneSurvivor=new Map;attributesByNode=new Map;bindingsByNode=new Map;splitDedup;splitTextSources;bulkLoad=0;unobservedWrites=0;nodeCountCache=-1;pendingNodeAdds=0;relationshipCountCache=-1;partCountCache=-1;stopObserving;destroy(){this.stopObserving();}beginBulkLoad(){this.bulkLoad+=1;}endBulkLoad(){this.bulkLoad=Math.max(0,this.bulkLoad-1),this.bulkLoad===0&&this.rebuildDerivedIndexes();}trackedTypes(){return [this.schema.meta,this.schema.nodes,this.schema.parts,this.schema.relationships,this.schema.overrides,this.schema.defaults,this.schema.binaries,this.schema.attributes,this.schema.bindings]}undoDeleteFilter(){let e=En(this.schema.nodes);return t=>!vn(this.schema,t)&&e(t)}encodeSnapshot(){return I.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return I.encodeStateAsUpdate(this.doc,e)}partEntries(){return yn(this.schema.parts)}partCount(){return this.partCountCache<0&&(this.partCountCache=this.partEntries().length),this.partCountCache}relationshipCount(){return this.relationshipCountCache<0&&(this.relationshipCountCache=this.relationships().length),this.relationshipCountCache}mainDocumentPart(){return fo(this.schema.meta.get("mainDocumentPart"))}record(e){if(g(e))return null;let t=this.schema.nodes.get(e);if(!S(t))return null;if(de(t)){let r=t.get(M),o=r instanceof I.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return fn(e,t,this.schema,[...this.attributesByNode.get(e)?.values()??[]],[...this.bindingsByNode.get(e)?.values()??[]])}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let t=this.schema.nodes.get(e);if(!t)return null;let r=this.record(e),o=r&&L(r)?r.attributes:[];return {logicalId:e,yjsItemKey:go(t),wordFacingIds:lt(o)}}isTombstoned(e){return V(this.schema.nodes.get(e))}replacedByOf(e){return et(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(ae(e))===e}noteWrite(){this.unobservedWrites+=1;}hasUnobservedWrites(){return this.unobservedWrites>0}listingParents(e){return [...this.listings.get(e)??[]]}allLogicalIds(){return [...this.schema.nodes.keys()].filter(e=>!g(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return g(e)?null:hn(this.schema.nodes,e)}kindOf(e){return g(e)?null:mn(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=q(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Ut({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)ct(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)ut(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=q(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(Se,qe(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,we(t));}spliceText(e,t,r,o){let i=this.splitTextSources.range(e),a=Pe(this.schema.nodes,this.splitTextSources,e,i,t,o),s=i?.text??this.textOf(e),l=(i?.start??0)+t;r>0&&s.delete(l,r),o.length>0&&s.insert(l,o),a?.();}setAttribute(e,t,r){if(r===null){ln(this.schema,e,t.namespaceUri,t.localName);return}ct(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){dn(this.schema,e,t);return}ut(this.schema,this.limits.maxStringLength,e,t,r);}spliceChildren(e,t,r,o){let i=this.childArray(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,[...o]);}moveNode(e,t,r){this.unlinkFromAllParents(e);let o=this.childArray(t);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,t){this.unlinkFromAllParents(e);let r=this.require(e);r.set(U,true),t&&r.set(G,t);}recordRunSplit(e,t,r){this.splitDedup.record(e,t,r);}splitOriginOf(e){return ce(this.schema.nodes.get(e))}replacementLoserRuns(){return this.hasUnobservedWrites()&&this.splitDedup.invalidate(),this.splitDedup.loserRuns({isPresent:e=>Qt(this,e)})}splitTextRange(e){return this.splitTextSources.range(e)}projectedTextValue(e){return this.splitTextSources.value(e)}registerSplitText(e,t,r,o){this.splitTextSources.register(e,t,r,o);}normalizeRestoredSplitTextAnchors(){this.splitTextSources.normalizeRestoredAnchors();}concurrentSplitTextOverlays(){return this.splitTextSources.overlays()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?D(r):null;if(!o)return;let i=new Map;for(let a of t)i.set(a,(i.get(a)??0)+1);for(let a=o.length-1;a>=0;a-=1){let s=o.get(a),l=i.get(s)??0;l!==0&&(i.set(s,l-1),o.delete(a,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,zt(e.id,e.rootLogicalId,e.contentType));}deleteXmlPart(e){this.partCountCache=-1,this.schema.parts.delete(e);}putRelationship(e){if(g(e.ownerPart)||g(e.id))return;this.relationshipCountCache=-1;let t=new I.Map;t.set(e.id,jt(e)),this.schema.relationships.set(dt(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(dt(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,Ft(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return tn(this.schema.relationships)}contentTypeOverrides(){return bn(this.schema.overrides)}contentTypeDefaults(){return xn(this.schema.defaults)}binaries(){return In(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){return Zt(this.schema,e)}rebuildDerivedIndexes(){this.unobservedWrites=0,this.nodeCountCache=-1,this.pendingNodeAdds=0,this.relationshipCountCache=-1,this.partCountCache=-1,this.parentIndex=new Map,this.listings=new Map,this.childrenSnapshot=new Map,this.adoptees=new Map,this.tombstoneSources=new Map,this.tombstoneSurvivor=new Map,this.attributesByNode=new Map,this.bindingsByNode=new Map,this.splitDedup.reset(),this.splitTextSources.reset(),this.schema.nodes.forEach((e,t)=>{if(g(t))return;let r=D(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(t,o);for(let i of o)this.addListing(i,t);}),this.schema.nodes.forEach((e,t)=>{V(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=Z(t);!r||g(r.logicalId)||g(r.localName)||pt(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=z(t);!r||g(r.logicalId)||g(r.prefix)||ht(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(S(e)&&(e.has("parent")||e.has("parentId")))throw new Error("registry record must not replicate a parent field")});}applyChildArrayEvents(e){this.unobservedWrites=0,this.pendingNodeAdds=0;let t=new Set;for(let r of e){if(!(r.target instanceof I.Text)&&(r.path.length===0||r.target instanceof I.Array||r.target instanceof I.Map&&[...r.changes.keys.keys()].some(o=>["deleted","replacedBy","splitFrom","splitLineage","children"].includes(String(o))))&&this.splitDedup.invalidate(),r.path.length>0&&this.splitTextSources.noteChanged(String(r.path[0])),r.path.length===0&&r.target instanceof I.Map){for(let[o,i]of r.changes.keys)if(this.nodeCountCache>=0&&i.action!=="update"&&(this.nodeCountCache+=i.action==="add"?1:-1),!(i.action==="delete"||g(String(o)))){this.splitDedup.indexExisting(String(o)),this.splitTextSources.indexExisting(String(o));for(let a of this.syncChildListings(String(o)))t.add(a);}continue}if(r.target instanceof I.Map&&r.path.length===1&&(r.changes.keys.has("splitFrom")||r.changes.keys.has("splitLineage"))&&this.splitDedup.indexExisting(String(r.path[0])),r.target instanceof I.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))t.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof I.Map&&r.path.length===1&&(r.changes.keys.has(U)||r.changes.keys.has(G))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,cn(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,un(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?D(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(gn(o,r))return [];let i=new Set(r),a=new Set(o),s=[];for(let l of o)i.has(l)||(this.removeListing(l,e),s.push(l));for(let l of r)a.has(l)||(this.addListing(l,e),s.push(l));return this.childrenSnapshot.set(e,r),s}addListing(e,t){let r=this.listings.get(e)??new Set;r.add(t),this.listings.set(e,r);}removeListing(e,t){let r=this.listings.get(e);r&&(r.delete(t),r.size===0&&this.listings.delete(e));}resolveParents(e){let t=[];for(let o of e){let i=this.listings.get(o);if(!i||i.size===0){this.parentIndex.delete(o);continue}if(i.size===1){this.parentIndex.set(o,[...i][0]);continue}t.push(o);}if(t.length===0)return;on({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(o=>o.rootLogicalId)},t)||this.assignFirstReachable(new Set(t));}assignFirstReachable(e){an({nodes:this.schema.nodes,parentIndex:this.parentIndex,listings:this.listings,childrenSnapshot:this.childrenSnapshot,partRoots:this.partEntries().map(t=>t.rootLogicalId)},e);}syncAdoptee(e){let t=this.tombstoneSurvivor.get(e);if(t!==void 0){this.tombstoneSurvivor.delete(e);let i=this.tombstoneSources.get(t);i&&(i.delete(e),i.size===0&&this.tombstoneSources.delete(t));}let r=this.schema.nodes.get(e),o=et(r);if(o!==null){if(V(r)){let i=this.tombstoneSources.get(o)??new Set;i.add(e),this.tombstoneSources.set(o,i),this.tombstoneSurvivor.set(e,o);}this.recomputeAdoptees(o);}}isContentWitness(e){let t=this.kindOf(e);return t!==null&&!t.endsWith("Properties")}recomputeAdoptees(e){let t=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of D(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&t.push(i);}t.length>0?this.adoptees.set(e,t):this.adoptees.delete(e);}unlinkFromAllParents(e){let t=[...this.listings.get(e)??[]];if(t.length===0){this.schema.nodes.forEach(r=>{let o=D(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?D(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,t){for(let r=e.length-1;r>=0;r-=1)e.get(r)===t&&e.delete(r,1);}textOf(e){let t=this.require(e).get(M);if(!(t instanceof I.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(Re);if(!(t instanceof I.Array))throw new Error(`no children at ${e}`);return t}require(e){let t=this.schema.nodes.get(e);if(!t)throw new Error(`registry node ${e} missing`);return t}};var De=class{blobs=new Map;get(e){let t=this.blobs.get(e);return t?t.slice():null}put(e,t){this.blobs.set(e,t.slice());}};async function Ln(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}`}function wn(n){let e=n.binaryPart;return typeof e=="function"?e:null}function Cn(n,e){let t=[];for(let o of n)o.kind==="putBinary"&&t.push(o.descriptor);if(t.length===0)return null;if(!e)return {ok:false,failure:{code:"blob-read",detail:"binary-part-reader"}};let r=[];for(let o of t){let i=e(o.storageKey);if(!i)return {ok:false,failure:{code:"missing-local-blob",detail:o.storageKey}};r.push({digest:o.digest,bytes:i});}return {ok:true,payloads:r}}function kn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function bo(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function xo(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Pn(n,e,t,r,o){if(r>n.limits.maxTreeDepth)return "tree-too-deep";if(g(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>n.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>n.limits.maxTextLength)return "text-too-long";n.putText(e.id,e.value);}else {if(e.attributes.length>n.limits.maxAttributes)return "too-many-attributes";if(e.children.length>n.limits.maxChildren)return "too-many-children";if(A(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}n.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:bo(e),bindings:xo(e)});for(let i of e.children){let a=Pn(n,i,e.id,r+1,o);if(a)return a}}return t&&n.childArray(t).push([e.id]),null}async function Io(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let a=n.contentTypes.overrides.get(r)??"application/octet-stream",s=P(r);if(s)return {ok:false,code:s};if(o.byteLength>Y.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await Ln(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:a,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function me(n,e,t=new De){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await Io(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let s of r.payloads)t.put(s.digest,s.bytes);let i={nodes:0};for(let[s,l]of e.parts){let d=P(s);if(d){o=d;return}if(A(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let p=Pn(n,l.root,null,0,i);if(p){o=p;return}n.putXmlPart({name:s,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let a=0;for(let s of e.relationships.values())for(let l of s){if(a+=1,a>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=P(l.ownerPart);if(d){o=d;return}}if(g(l.id)){o="prototype-key";return}n.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[s,l]of e.contentTypes.defaults){if(g(s)){o="prototype-key";return}n.putContentTypeDefault(s,l);}for(let[s,l]of e.contentTypes.overrides){let d=P(s);if(d){o=d;return}n.putContentTypeOverride(s,l);}for(let s of r.descriptors)n.putBinary(s);Kt(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},Nt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var _e="http://schemas.openxmlformats.org/package/2006/relationships",vo="application/vnd.openxmlformats-package.relationships+xml",On=/^(.*)\/_rels\/([^/]*)\.rels$/;function An(n){return On.test(n)}function Tn(n){let e=On.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function ge(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Be(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function So(n,e){let t=[Be("Id",e.id),Be("Type",e.type),Be("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(Be("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:_e,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function Nn(n,e){if(n.kind==="textValue"||n.namespaceUri!==_e||n.localName!=="Relationship"||ge(n,"Id")!==e.id||ge(n,"Type")!==e.type||ge(n,"Target")!==e.rawTarget)return false;let t=ge(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function Mn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>Nn(t,e[r]))}function Dn(n,e){if(n.id!==e.id||n.kind!==e.kind||n.namespaceUri!==e.namespaceUri||n.localName!==e.localName||n.prefix!==e.prefix||n.attributes.length!==e.attributes.length)return false;for(let t=0;t<n.attributes.length;t+=1){let r=n.attributes[t],o=e.attributes[t];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return n.namespaceBindings.length!==e.namespaceBindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.namespaceBindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function Bn(n,e,t){let r=[];for(let o of e){if(g(o.id))continue;let i=n.find(s=>s.kind!=="textValue"&&ge(s,"Id")===o.id);if(i&&Nn(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;g(a)||r.push(So(a,o));}return r}function Eo(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:_e,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:_e})]),attributes:Object.freeze([]),children:Object.freeze([])})}function _n(n){return Object.freeze({id:n,name:n,contentType:vo,root:Eo(n)})}function Yn(n){let e=new Map;for(let t of n){if(g(t.id)||t.ownerPart!=="/"&&P(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var Fn=/^\/customXml\/item(\d+)\.xml$/i,Co=/^\/customXml\/itemProps(\d+)\.xml$/i;function ye(n){return Fn.test(n)}function yt(n){return Co.test(n)}function ko(n){let e=Fn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function Un(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Po(n,e,t){let r=n.attributes.find(o=>o.localName===e&&o.namespaceUri===t);return r&&r.value.length>0?r.value:null}function zn(n,e){let t=n.record(e);return !t||!L(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Oo(n,e){let t=n.record(e);if(!t||!L(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!L(o)||o.localName!=="schemaRefs")&&o.namespaceUri===DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=n.record(i);if(!a||!L(a)||a.localName!=="schemaRef")continue;let s=Po(a,"uri",DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function Ao(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&L(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function To(n,e){return e.localName==="node"||e.namespaceUri===WML_NAMESPACE_URI||e.namespaceUri===DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:Ao(n,e)}function No(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function Kn(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,m]of e){let c=n.record(m.root.id);!c||!L(c)||(ye(u)&&t.set(c.logicalId,c),yt(u)&&r.set(c.logicalId,c));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let m=n.record(u);!m||!L(m)||(To(n,m)?t.set(u,m):No(n,m)&&r.set(u,m));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let m=o.get(u.namespaceUri)??[];m.push(u),o.set(u.namespaceUri,m);}let i=new Map;for(let u of r.values()){let m=Oo(n,u.logicalId);if(!m)continue;let c=i.get(m)??[];c.push(u),i.set(m,c);}let a=[];for(let[u,m]of o){let c=i.get(u);if(!c||c.length===0)continue;m.sort((E,x)=>E.logicalId.localeCompare(x.logicalId)),c.sort((E,x)=>E.logicalId.localeCompare(x.logicalId));let f=m[0],b=c[0],v=[],R=new Set;for(let E of m)for(let x of E.childIds){if(R.has(x))continue;let O=n.record(x);!O||!L(O)||O.localName!=="node"||O.namespaceUri!==u||(R.add(x),v.push(x));}for(let E of n.allLogicalIds()){if(R.has(E)||n.isTombstoned(E))continue;let x=n.record(E);!x||!L(x)||x.localName!=="node"||x.namespaceUri!==u||(R.add(E),v.push(E));}v.sort((E,x)=>zn(n,E).localeCompare(zn(n,x))),a.push({data:f,props:b,nodeIds:v});}a.sort((u,m)=>u.data.logicalId.localeCompare(m.data.logicalId));let s=new Set,l=[],d=new Set,p=new Set;for(let[u,m]of e){let c=ko(u);if(c===null)continue;let f=a.find(R=>R.data.logicalId===m.root.id&&!d.has(R.data.logicalId));if(!f)continue;let b=Un(c).props,v=e.get(b);v&&v.root.id!==f.props.logicalId||(s.add(c),d.add(f.data.logicalId),p.add(f.props.logicalId),l.push({dataRootId:f.data.logicalId,propsRootId:f.props.logicalId,namespaceUri:f.data.namespaceUri,itemName:u,propsName:b,nodeIds:f.nodeIds}));}let h=1;for(let u of a){if(d.has(u.data.logicalId))continue;for(;s.has(h);)h+=1;s.add(h);let m=Un(h);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:u.nodeIds}),h+=1;}return l.sort((u,m)=>u.itemName.localeCompare(m.itemName)),l}function Mo(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:ye(n.ownerPart)}function Do(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Bo(n,e){let t=n.split("/").slice(1,-1),r=e.split("/").slice(1),o=0;for(;o<t.length&&o<r.length-1&&t[o]===r[o];)o+=1;return `${"../".repeat(t.length-o)}${r.slice(o).join("/")}`}function Vn(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(s=>s.ownerPart===t&&s.type===CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,Do(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],p=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:t,id:p,type:CUSTOM_XML_REL,rawTarget:Bo(t,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function Jn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Mo(t)),...e]}function Wn(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function bt(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(ye).sort(),r=e.map(o=>o.itemName).sort();if(t.length!==r.length||t.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=n.get(o.itemName),a=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!a||a.root.id!==o.propsRootId)return true}return false}function $n(n,e){if(bt(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(t.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var _o="http://schemas.microsoft.com/office/word/2012/wordml";function Ye(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ue(n){let e=Number(n);return n===void 0||n.length===0||!Number.isSafeInteger(e)?`2${n??""}`:`${e<0?"0":"1"}${String(Math.abs(e)).padStart(12,"0")}`}function Xn(n){return e=>e.localName===n&&e.namespaceUri===WML_NAMESPACE_URI}function Yo(n){return n.localName==="abstractNum"?`0${Ue(Ye(n,"abstractNumId"))}`:`1${Ue(Ye(n,"numId"))}`}function Uo(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Gn(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===_o,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Xn("footnote"),sortKey:e=>Ue(Ye(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Xn("endnote"),sortKey:e=>Ue(Ye(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Uo,sortKey:Yo}:null}function zo(n,e){return n.attributes.find(t=>t.localName===e)?.value}function xt(n){return n.kind==="textValue"?n.id:zo(n,"id")??n.id}function re(n,e){if(n.length===e.length&&n.every((a,s)=>a===e[s]))return n;let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t+=1;let o=n.length,i=e.length;for(;o>t&&i>t&&n[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...n.slice(0,t),...e.slice(t,i),...n.slice(o)])}function Zn(n,e){let t=n.root;if(t.children.length===e.length&&t.children.every((o,i)=>o===e[i]))return n;let r=Object.freeze({...t,children:re(t.children,e)});return Object.freeze({...n,root:r})}function jo(n){if(n.namespaceUri===XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function tr(n){}function rr(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function $o(n,e){return n.namespaceBindings.length!==e.bindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.bindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function Xo(n,e){return n.attributes.length!==e.attributes.length?false:n.attributes.every((t,r)=>{let o=e.attributes[r];return t.namespaceUri===o.namespaceUri&&t.localName===o.localName&&t.value===o.value&&t.prefix===(o.prefix?.length?o.prefix:void 0)})}function ze(n,e,t){let r=t&&t.kind!=="textValue"?t:void 0;return Object.freeze({id:n.logicalId,kind:n.kind,namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,namespaceBindings:r&&$o(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Xo(r,n)?r.attributes:Object.freeze(n.attributes.map(jo)),children:e})}function or(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
3
+ ${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
4
+ ${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function It(n,e){let t=e.size;e.add(n.id);let r=e.size!==t;if(n.kind==="textValue")return r;for(let o of n.children)It(o,e)||(r=false);return r}function ir(n,e){let t=new Set(e);for(let r of e){let o=n.parentOf(r);for(;o&&!t.has(o);)t.add(o),o=n.parentOf(o);}return t}var je=class{constructor(e){this.registry=e;}registry;decoded=null;merged=null;grouped=null;assembly=null;defaults=null;overrides=null;partBytes=null;blobBytes=new Map;invalidate(){this.decoded=null,this.merged=null,this.grouped=null,this.assembly=null,this.defaults=null,this.overrides=null,this.partBytes=null;}projected(e){return this.decoded||(this.decoded=this.registry.relationships(),this.merged=null),(!this.merged||this.merged.custom!==e)&&(this.merged={custom:e,records:e.length===0?this.decoded:Jn(this.decoded,e)}),this.merged.records}groupedByOwner(e){let t=this.projected(e);return (!this.grouped||this.grouped.records!==t)&&(this.grouped={records:t,map:Yn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:qo(t)}),this.assembly.value}contentTypeDefaults(){return this.defaults??=this.registry.contentTypeDefaults()}contentTypeOverrides(){return this.overrides??=this.registry.contentTypeOverrides()}resolvePartBytes(e){if(this.partBytes)return this.partBytes;let t=new Map,r=new Set;for(let o of this.registry.binaries()){r.add(o.storageKey);let i=this.blobBytes.get(o.storageKey);if(i&&i.digest===o.digest){t.set(o.storageKey,i.bytes);continue}let a=e.get(o.digest);if(!a)return null;tr(a.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:a}),t.set(o.storageKey,a);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function qo(n){let e=buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var Fe=class{lastLosers=new Set;textOverlays=new Map;losers=new Set;update(e){let t=[],r=e.replacementLoserRuns(),o=a=>{let s=e.parentOf(a);s!==null&&t.push(s);};for(let a of r)this.lastLosers.has(a)||o(a);for(let a of this.lastLosers)r.has(a)||o(a);this.lastLosers=r,this.losers=r;let i=e.concurrentSplitTextOverlays();return this.textOverlays=i.values,t.push(...i.changedIds),t}textValue(e,t){return this.textOverlays.get(e)??t}};function ei(n){let e=new Set,t=[];for(let r of n){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),t.push(r));}return t}var $=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new je(e),this.stop=e.observeDirty(r=>{for(let o of r.logicalIds)this.pendingDirty.add(o);r.membershipChanged&&(this.pendingMembership=true),r.packageChanged&&(this.pendingPackage=true);});}registry;blobs;cache=new Map;heights=new Map;partCache=new Map;packageCache;relsProjection=new Map;pendingDirty=new Set;pendingMembership=false;pendingPackage=false;lastDirty=new Set;lastAdoption=new Map;placementContested=false;splitProjection=new Fe;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let p of this.adoptionChanges())e.add(p);for(let p of this.splitProjection.update(this.registry))e.add(p);let o=ir(this.registry,e),i=new Set(this.registry.partEntries().map(p=>p.rootLogicalId)),a=[...e].some(p=>i.has(p)||this.registry.parentOf(p)===null&&!this.registry.isTombstoned(p)),s=this.pkg!==null&&!r&&!a&&(o.size>0||t),l=this.materializePass(o,t,s);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:ei(l.issues)};let d=this.materializePass(o,t,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let t=this.lastContestResolution.get(e);if(t===void 0||t!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let t of this.contestEncountered)e.set(t,this.registry.parentOf(t));for(let t of this.lastDuplicateParents)e.set(t,this.registry.parentOf(t));this.lastContestResolution=e;}materializePass(e,t,r){if(this.issues.length=0,this.lastDirty=e,this.placementContested=false,this.contestEncountered.clear(),this.contestMatchesResolution=true,this.claimsWholeSubtrees=!r,this.droppedChildren.clear(),r)for(let d of this.lastDuplicateParents)this.push("duplicate-parent",d);this.customXmlRels=[],this.customXmlOverrides.clear();let o=new Set,i=new Map;for(let d of this.registry.partEntries()){let p=new Set,h=this.materialize(d.rootLogicalId,o,p,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===h&&u.contentType===d.contentType){i.set(d.name,u);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,m),this.partCache.set(d.name,m);}let a=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),s=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,a,s),this.applyCustomXmlStores(i,o,r);for(let d of [...this.partCache.keys()])i.has(d)||this.partCache.delete(d);for(let d of [...this.relsProjection.keys()])i.has(d)||this.relsProjection.delete(d);this.evictDeadSubtrees(o),this.reportOrphans(a,o,r,s),this.looseCandidates=s,r||(this.lastDuplicateParents=this.issues.filter(d=>d.code==="duplicate-parent"&&d.logicalId!==void 0).map(d=>d.logicalId));let l=this.assemblePackage(i);return l.ok?this.pkg&&!t&&this.pkg.parts.size===i.size&&[...i].every(([d,p])=>this.pkg?.parts.get(d)===p)?{ok:true,package:this.pkg,issues:[...this.issues]}:(this.pkg=l.package,{ok:true,package:this.pkg,issues:[...this.issues]}):l}push(e,t){this.issues.push(t?{code:e,logicalId:t}:{code:e});}stillListed(e){for(let t of this.registry.listingParents(e)){let r=this.registry.record(t);if(r&&L(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let s of e)this.registry.isTombstoned(s)||t.has(s)||(this.pushOrphan(s),o.add(s));return}let i=new Set(this.registry.partEntries().map(s=>s.rootLogicalId)),a=new Set;for(let s of e)a.has(s)||(a.add(s),this.reportOrphansUnder(s,t,i)&&o.add(s));}reportOrphansUnder(e,t,r){let o=false,i=new Set,a=[{id:e,underTombstone:false}];for(;a.length>0;){let{id:s,underTombstone:l}=a.pop();if(!(i.has(s)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(s),this.registry.isTombstoned(s)){let d=this.registry.record(s);if(d&&L(d))for(let p of d.childIds)a.push({id:p,underTombstone:true});continue}r.has(s)||(l?t.has(s):this.stillListed(s))||(this.pushOrphan(s),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(H(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let u=this.cache.get(e);if(u&&r.size+this.heightOf(u)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?It(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(H(i)){let u=this.splitProjection.textValue(e,i.value),m=this.cache.get(e);if(m?.kind==="textValue"&&m.value===u)return m;let c=rr(e,u);return this.remember(e,c),c}r.add(e);let a=new Set,s=[...i.childIds];for(let u of this.registry.adoptedChildren(e))s.includes(u)||s.push(u);let l=[];for(let u of s){if(u===e){this.push("self-child",u);continue}if(a.has(u)){this.push("duplicate-child",u);continue}if(a.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(this.splitProjection.losers.has(u)){t.add(u);continue}if(g(u)||!this.registry.hasNode(u)){this.push("child-id-not-in-registry",u);continue}if(!this.claimsWholeSubtrees){let c=this.registry.listingParents(u);c.length>1&&(this.placementContested=true,this.contestEncountered.add(u),c.some(f=>this.registry.isTombstoned(f)&&this.registry.replacedByOf(f)!==null)?this.contestMatchesResolution=false:!t.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let m=this.materialize(u,t,r,o);m&&l.push(m);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,m)=>u===l[m])&&or(d,i))return d;let p=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(p,l);let h=ze(i,re(p,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let a=relsPartNameFor(o);if(a!=="/_rels/.rels"&&P(a))continue;r.add(a);let s=this.projectOneRelsPart(a,e.get(a),i);s&&(e.set(a,s),this.partCache.set(a,s));}for(let[o,i]of e){if(r.has(o)||!An(o))continue;let a=Tn(o);if(a===null)continue;let s=this.projectOneRelsPart(o,i,t.get(a)??[]);!s||s===i||(e.set(o,s),this.partCache.set(o,s));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),a=!!o&&(!t||Dn(o.root,t.root))&&o?o:t??_n(e);if(Mn(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=Zn(a,Bn(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[a,s]of e){let l=Gn(s.root);if(!l)continue;let d=R=>R.logicalId!==s.root.id&&l.isMember(R),p=[],h=new Set;for(let R of s.root.children){if(R.kind==="textValue")continue;let E=this.registry.record(R.id);!E||!L(E)||!d(E)||(p.push(R),h.add(R.id));}if(this.adoptLooseMembers(p,h,d,t,r,o,i)===0)continue;p.sort((R,E)=>l.sortKey(R).localeCompare(l.sortKey(E)));let m=[];for(let R of s.root.children)h.has(R.id)||m.push(R);let c=re(s.root.children,[...m,...p]);if(c===s.root.children)continue;let f=this.registry.record(s.root.id);if(!f||!L(f))continue;let b=ze(f,c,s.root);this.remember(s.root.id,b);let v=Object.freeze({...s,root:b});e.set(a,v),this.partCache.set(a,v);}}adoptLooseMembers(e,t,r,o,i,a,s){let l=0;for(let d of a){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let p=this.registry.record(d);if(!p||!L(p)||!r(p))continue;let h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),t.add(d),s.add(d),l+=1);}return l}materializeOnce(e,t,r){return t.has(e)?this.cache.get(e)??null:this.materialize(e,t,new Set,r)}adoptNodesIntoRoot(e,t,r,o){let i=this.cache.get(e),a=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!a||a.kind==="textValue")return null;let s=[...a.children],l=new Set(s.map(m=>m.id)),d=0;for(let m of t){if(l.has(m))continue;let c=this.materializeOnce(m,r,o);!c||c.kind==="textValue"||(s.push(c),l.add(m),d+=1);}if(s.sort((m,c)=>xt(m).localeCompare(xt(c))),d===0&&s.every((m,c)=>m===a.children[c]))return a;let p=this.registry.record(e);if(!p||!L(p))return a;let h=re(a.children,s),u=ze(p,h,a);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=Kn(this.registry,e);if(o.length===0||!$n(e,o))return;let i=bt(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,t,r),d=this.materializeOnce(s.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let p=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:s.propsName,name:s.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,p),e.set(s.propsName,h),this.partCache.set(s.itemName,p),this.partCache.set(s.propsName,h);}if(i){for(let s of [...e.keys()])!ye(s)&&!yt(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=Vn(this.registry,o),this.customXmlOverrides=Wn(o),this.projectRelsParts(e);}}assemblePackage(e){let t=this.packageCache.relationshipAssembly(this.customXmlRels);if(!t)return {ok:false,code:"invalid-relationships",issues:[...this.issues]};let r=this.packageCache.resolvePartBytes(this.blobs);if(!r)return {ok:false,code:"missing-blob",issues:[...this.issues]};let o=new Map(this.packageCache.contentTypeOverrides());for(let[s,l]of this.customXmlOverrides)o.set(s,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},a=this.registry.mainDocumentPart()||[...e.keys()].find(s=>s.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:a}),issues:[...this.issues]}}};var Ve=64*1024*1024,xe="docx-package-blobs-v1";function ni(n){if(n instanceof Uint8Array)return new Uint8Array(n);if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n)){let e=n;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}return null}function ri(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function Ke(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var X=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=ni(t);return !r||typeof t!="object"||t===null?null:this.verify(e,t,r)?r:null}has(e){let t=this.shared.get(e);return t===void 0?false:this.verified.has(t)?true:this.get(e)!==null}poisonedDigest(){for(let e of this.poisoned)return e;return null}observeChanges(e){let t=r=>{e([...r.keysChanged]);};return this.shared.observe(t),()=>this.shared.unobserve(t)}verifyNow(e){for(let t of e)if(this.shared.has(t)&&this.get(t)===null)return t;return null}totalByteLength(){let e=0;return this.shared.forEach(t=>{e+=ri(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Ve)throw new y("blob-store-full");this.shared.set(e,new Uint8Array(t));}}verify(e,t,r){return this.verified.has(t)?true:this.poisoned.has(e)?false:sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(t),true)}};function Ie(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return Ke("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return Ke("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(s=>{i+=s instanceof I.Map?s.size:0;}),i>t.maxRelationships)return Ke("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>Ve?Ke("blob-store-full",`${a}`):null}var lr=20*1024*1024,St=3e4,di=4e3,ci=1500,ui="docx-collaboration-seeds-v1",vt="docxEditorSeedCandidate",pi=/^[0-9a-f]{16}$/,hi=256;function Et(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new y("invalid-baseline");if(n.byteLength>lr)throw new y("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:lr,maxRatio:200}});if(!e.ok)throw new y("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new y("no-main-document-part");let r=e.package;for(let i of r.parts.values()){if(i.root.namespaceUri!==WML_NAMESPACE_URI||!["document","hdr","ftr"].includes(i.root.localName)||!isStoryPart(i))continue;let a=normalizeParagraphIdentity(i);a!==i&&(r=withPart(r,a));}return new TreePackageStore(r,normalizeParagraphIdentity(r.parts.get(t.name))).currentPackage()}function mi(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function ve(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&mi(n,e),a=()=>{let l=e.poisonedDigest();return l?new y("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let s=a();return s?Promise.reject(s):r?.aborted?Promise.reject(new y("initialization-aborted")):new Promise((l,d)=>{let p=c=>{clearTimeout(m),o.unobserve(h),n.doc.off("afterTransaction",h),r?.removeEventListener("abort",u),c?d(c):l();},h=()=>{let c=a();if(c){p(c);return}i()&&p();},u=()=>p(new y("initialization-aborted")),m=setTimeout(()=>p(new y("initialization-timeout")),t);o.observe(h),n.doc.on("afterTransaction",h),r?.addEventListener("abort",u,{once:true});})}function Rt(n){return n.getArray(ui)}function Je(n){return Rt(n).length}function cr(n,e){let t=Rt(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function gi(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function fi(n,e){let t=[...n.getStates().entries()].slice(0,hi);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[vt];if(!(typeof i!="string"||!pi.test(i))&&i<e)return true}return false}async function dr(n,e,t,r){try{return await ve(n,e,t,r),!0}catch(o){if(o instanceof y&&o.code==="initialization-timeout")return false;throw o}}function yi(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new y("initialization-aborted")):new Promise((i,a)=>{let s=h=>{clearTimeout(p),r.unobserve(l),t?.removeEventListener("abort",d),h?a(h):i();},l=()=>{o()&&s();},d=()=>s(new y("initialization-aborted")),p=setTimeout(()=>s(new y("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function ur(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??di,a=n.electionWindowMs??ci,s=n.timeoutMs??St,l=async()=>(await yi(r,s,n.signal),"joined");if(await dr(r,o,i,n.signal))return l();let d=gi();t.setLocalStateField(vt,d);try{let p=await dr(r,o,a,n.signal);if(!p&&fi(t,d)&&(await ve(r,o,s,n.signal),p=!0),p)return await l();if(r.schema.meta.get("initialized")===!0)return await ve(r,o,s,n.signal),await l();let h=await me(r,Et(n.document),o);if(!h.ok)throw new y(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Rt(e).push([d]);}),"seeded"}finally{t.setLocalStateField(vt,null);}}var We=class{constructor(e,t){this.knows=e;this.allocator=new he(t);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let t=this.allocator.take();return this.toLogical.set(e,t),t}resolve(e){return this.toLogical.get(e)??e}translate(e){let t=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),t.push(i);}return r?Object.freeze({effects:Object.freeze(t)}):e}translateEffect(e){switch(e.kind){case "putNode":{let t=this.translateDescriptor(e.descriptor);return t.logicalId===e.descriptor.logicalId?e:{...e,descriptor:t}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let t=this.resolve(e.logicalId);return t===e.logicalId?e:{...e,logicalId:t}}case "spliceChildren":{let t=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return t===e.parentLogicalId&&r.every((i,a)=>i===e.childLogicalIds[a])?e:{...e,parentLogicalId:t,childLogicalIds:r}}case "moveNode":{let t=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return t===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:t,destinationParentLogicalId:r}}case "putXmlPart":{let t=this.resolve(e.rootLogicalId);return t===e.rootLogicalId?e:{...e,rootLogicalId:t}}default:return e}}translateDescriptor(e){let t=this.resolve(e.logicalId);return this.knows(t)?{...e,logicalId:t}:{...e,logicalId:this.mint(e.logicalId)}}};function bi(n){let e=0;return n.schema.nodes.forEach(t=>{S(t)&&t.get(U)===true&&(e+=1);}),e}function xi(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof I.Map?t.size:0;}),e}function hr(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:bi(n),maxNodes:n.limits.maxNodes,relationships:xi(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Ve})}var $e="docxEditor",F=256,Lt=256;function gr(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>F||t.length===0||t.length>F)throw new y("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new y("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function fr(n){let e=n.trim();if(e.length===0||e.length>F)throw new y("invalid-document-id");return e}function yr(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>F)throw new y("invalid-session-id");return e}function mr(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.paragraphId!="string"||e.paragraphId.length!==8||!Number.isSafeInteger(e.offset)||e.offset<0?null:{paragraphId:e.paragraphId.toUpperCase(),offset:e.offset}}function vi(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=mr(e.anchor),r=mr(e.head);if(t&&r)return e.kind==="cells"?{anchor:t,head:r,kind:"cells"}:{anchor:t,head:r};if(typeof e.paragraphId=="string"&&e.paragraphId.length===8&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>=0){let o=e.paragraphId.toUpperCase();return {anchor:{paragraphId:o,offset:e.start},head:{paragraphId:o,offset:e.end}}}}function wt(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>F||typeof e.name!="string"||e.name.length===0||e.name.length>F)return null;let t=safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=vi(e.selection);return i?{...o,selection:i}:o}function Ei(n){let e=new W(n),t=null;try{if(e.schema.meta.get("initialized")!==!0||typeof e.schema.meta.get("documentId")!="string")throw new y("not-initialized");let r=Q(e.schema.meta);if(r)throw new y(r.code,r.detail);if(e.rebuildDerivedIndexes(),Je(n)>1)throw new y("concurrent-seed");let o=new X(n.getMap(xe)),i=Ie(e,o);if(i)throw new y(i.code,i.detail);t=new $(e,o);let a=t.current(),s=o.poisonedDigest();if(s)throw new y("blob-digest-mismatch",s);if(!a.ok)throw new y(a.code);let l=Le(a.issues);if(l)throw new y("materialize-dropped-content",l);if(!a.package.parts.has(a.package.mainDocumentPart))throw new y("no-main-document-part");return writeOoxmlPackage(a.package)}finally{t?.destroy(),e.destroy();}}var Pi=3,Oi=5e3,Ai=2e3,Ti=Symbol("createDocumentCollaboration.attachWatchdogMs"),Ct=class{constructor(e,t,r,o,i,a,s,l,d,p,h){this.ydoc=e;this.awareness=t;this.registry=a;this.materializer=s;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new I.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Oi,deleteFilter:a.undoDeleteFilter()}),this.historyGroups=new Oe(this.undoManager,this),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let m=d.verifyNow(u);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=cr(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${p}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},p),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;destroyed=false;refusedInARow=0;historyGroups;stopBlobWatch;stopSeedWatch;get identity(){return this.currentIdentity}clearAttachWatchdog(){this.attachWatchdog!==null&&(clearTimeout(this.attachWatchdog),this.attachWatchdog=null);}status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}resourceUsage(){return hr(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}hasCompatibleSharedSchema(){let e=Q(this.registry.schema.meta);return e?(this.setStatus("error",e.code,e.detail),false):true}canWriteSharedState(){if(this.destroyed||!this.hasCompatibleSharedSchema())return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,t){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.historyGroups.reset(),this.undoManager.undo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.historyGroups.reset(),this.undoManager.redo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],t=[...this.awareness.getStates().entries()].slice(0,Lt);for(let[r,o]of t){let i=wt(o[$e]);i&&e.push({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},role:i.role,isLocal:r===this.awareness.clientID});}return Object.freeze(e)}subscribeParticipants(e){return this.participantListeners.add(e),()=>this.participantListeners.delete(e)}remoteSelections(){let e=this.port;if(!e)return [];let t=i=>{let a=e.paragraphByStableId(i.paragraphId);return a?Object.freeze({paragraphId:a.paragraphId,nodeId:a.nodeId,offset:Math.min(i.offset,a.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,Lt),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=wt(a[$e]);if(!s?.selection)continue;let l=t(s.selection.anchor),d=t(s.selection.head);!l||!d||o.push(Object.freeze({actorId:s.actorId,name:s.name,...s.color?{color:s.color}:{},...s.selection.kind==="cells"?{kind:"cells"}:{},anchor:l,head:d}));}return Object.freeze(o)}subscribeRemoteSelections(e){return this.selectionListeners.add(e),()=>this.selectionListeners.delete(e)}setIdentity(e){if(this.destroyed)return;let t=e.name===void 0?this.currentIdentity.name:e.name.trim();if(t.length===0||t.length>F)throw new y("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new y("invalid-identity-color");r=safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:t,...r?{color:r}:{},role:this.currentIdentity.role??"human"}),this.publishAwareness(this.currentSelection);}destroy(){this.destroyed||(this.clearAttachWatchdog(),this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.stopBlobWatch(),this.stopSeedWatch(),this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.materializer.destroy(),this.registry.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){if(!this.canWriteSharedState())return;let t=Xt(this.registry,this.identityMap.translate(e));if(!t.ok){this.refuseLocalJournal({code:t.code,...t.detail?{detail:t.detail}:{}});return}let r=t.journal,o=this.collectJournalBlobs(e);if(o!==null&&o.ok===false){this.refuseLocalJournal(o.failure);return}if(!this.canWriteSharedState())return;let i=this.historyGroups.capture(historyGroupOfJournal(e),()=>this.ydoc.transact(()=>{if(o!==null){let s=this.putJournalBlobs(o.payloads);if(s!==null)return s}let a=nt(this.registry,r);return a.ok?null:{code:a.code,...a.detail?{detail:a.detail}:{}}},this.localOrigin));if(i===null){this.refusedInARow=0;return}this.refuseLocalJournal(i);}collectJournalBlobs(e){let t=this.port;if(!t)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=Cn(e.effects,wn(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{kn(this.blobs,e);}catch(t){return t instanceof y?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.historyGroups.reset(),this.undoManager.stopCapturing();let t=this.statusState.snapshot();this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let r=this.statusState.snapshot().reason;this.refusedInARow<Pi&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(t.status==="ready"||t.status==="disconnected")&&this.setStatus(t.status,t.reason?.code,t.reason?.detail);}onYjsTransaction=e=>{this.destroyed||!this.hasCompatibleSharedSchema()||!this.port||e.origin!==this.localOrigin&&this.publishSharedToPort();};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{if(!this.hasCompatibleSharedSchema())return;let t=Ie(this.registry,this.blobs);if(t){this.setStatus("error",t.code,t.detail);return}let r=this.materializer.current(),o=this.blobs.poisonedDigest();if(o){this.setStatus("error","blob-digest-mismatch",o);return}if(!r.ok){this.setStatus("error",r.code);return}let i=Le(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let a=e.applyRemotePackage(r.package,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!a.ok){this.setStatus("error","remote-apply-failed",a.reason);return}a.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof y?t.code:"remote-apply-failed",t instanceof y?t.detail:void 0);}finally{this.applyingRemote=false,this.drainJournalsHeldDuringRemote();}}}drainJournalsHeldDuringRemote(){if(!this.drainingHeldJournals){this.drainingHeldJournals=true;try{for(;this.journalsHeldDuringRemote.length>0;){if(this.destroyed||this.realignedInBatch){this.journalsHeldDuringRemote.length=0;return}let e=this.journalsHeldDuringRemote.shift();e&&this.applyJournal(e);}}finally{this.drainingHeldJournals=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let t=this.participants();for(let r of [...this.participantListeners])r(t);};publishAwareness(e){this.currentSelection=e;let t={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...e?{selection:e}:{}};this.awareness.setLocalStateField($e,t);}setStatus(e,t,r){if(!this.statusState.set(e,t,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};async function Nl(n){let e=n[Ti]??Ai,t=fr(n.documentId),r=yr(n.sessionId),o=gr(n.identity),i=new W(n.ydoc);try{return await Ni(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function Ni(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new We(h=>a.hasNode(h)),l=new X(n.ydoc.getMap(xe));if(n.bootstrap.kind==="create"){if(a.schema.meta.get("initialized")===true)throw new y("already-initialized");let h=await me(a,Et(n.bootstrap.document),l);if(!h.ok)throw new y(h.code);n.ydoc.transact(()=>{a.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await ur({ydoc:n.ydoc,awareness:n.awareness,registry:a,blobs:l,documentId:r,document:n.bootstrap.document,probeTimeoutMs:n.bootstrap.probeTimeoutMs,electionWindowMs:n.bootstrap.electionWindowMs,timeoutMs:n.bootstrap.timeoutMs,signal:n.bootstrap.signal})==="joined"){if(a.schema.meta.get("documentId")!==r)throw new y("document-id-mismatch");let u=Q(a.schema.meta);if(u)throw new y(u.code,u.detail);a.rebuildDerivedIndexes();}}else {if(await ve(a,l,n.bootstrap.timeoutMs??St,n.bootstrap.signal),a.schema.meta.get("documentId")!==r)throw new y("document-id-mismatch");let h=Q(a.schema.meta);if(h)throw new y(h.code,h.detail);a.rebuildDerivedIndexes();}if(Je(n.ydoc)>1)throw new y("concurrent-seed");let d=Ie(a,l);if(d)throw new y(d.code,d.detail);let p=new $(a,l);try{let h=p.current(),u=l.poisonedDigest();if(u)throw new y("blob-digest-mismatch",u);if(!h.ok)throw new y(h.code);let m=writeOoxmlPackage(h.package),c=new Ct(n.ydoc,n.awareness,r,o,i,a,p,s,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:c,destroy:()=>c.destroy()})}catch(h){throw p.destroy(),h}}export{y as a,Ei as b,Ti as c,Nl as d};
@@ -1 +1 @@
1
- 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunkVCMQFPO2_cjs=require('../chunk-VCMQFPO2.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var P__namespace=/*#__PURE__*/_interopNamespace(P);var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new chunkVCMQFPO2_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new chunkVCMQFPO2_cjs.d("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[O]??F,n=new P__namespace.Doc,r=new awareness.Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await chunkVCMQFPO2_cjs.p({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",collaboration.isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b||(b=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.HOCUSPOCUS_PROVIDER_FOR_TESTS=O;exports.createHocuspocusCollaboration=_;
1
+ 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunk6SR5OK66_cjs=require('../chunk-6SR5OK66.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var P__namespace=/*#__PURE__*/_interopNamespace(P);var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new chunk6SR5OK66_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new chunk6SR5OK66_cjs.d("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[O]??F,n=new P__namespace.Doc,r=new awareness.Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await chunk6SR5OK66_cjs.p({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",collaboration.isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b||(b=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.HOCUSPOCUS_PROVIDER_FOR_TESTS=O;exports.createHocuspocusCollaboration=_;
@@ -1 +1 @@
1
- import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {p,d}from'../chunk-MRW46GJW.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';import {isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d$1){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new d(isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new d("initialization-timeout"));},d$1);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=b(o.roomId),c=o[O]??F,n=new P.Doc,r=new Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await p({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p$1=a=>{l.setTransportStatus("error",isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p$1);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b$1||(b$1=true,e.off("status",f),e.off("authenticationFailed",p$1),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}export{O as HOCUSPOCUS_PROVIDER_FOR_TESTS,_ as createHocuspocusCollaboration};
1
+ import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {p,d}from'../chunk-6CDC4KCE.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';import {isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d$1){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new d(isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new d("initialization-timeout"));},d$1);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=b(o.roomId),c=o[O]??F,n=new P.Doc,r=new Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await p({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p$1=a=>{l.setTransportStatus("error",isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p$1);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b$1||(b$1=true,e.off("status",f),e.off("authenticationFailed",p$1),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}export{O as HOCUSPOCUS_PROVIDER_FOR_TESTS,_ as createHocuspocusCollaboration};
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunkVCMQFPO2_cjs=require('../chunk-VCMQFPO2.cjs'),l=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var l__namespace=/*#__PURE__*/_interopNamespace(l);var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new chunkVCMQFPO2_cjs.d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new chunkVCMQFPO2_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new chunkVCMQFPO2_cjs.d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunkVCMQFPO2_cjs.d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunkVCMQFPO2_cjs.e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l__namespace.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===store.ORIGIN_IDS.mutationRemote||o.origin===store.ORIGIN_IDS.projection||o.origin===store.ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof chunkVCMQFPO2_cjs.d?e.code:"local-mirror-failed",e instanceof chunkVCMQFPO2_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l__namespace.encodeRelativePosition(l__namespace.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e={anchor:r,head:i});}this.publishAwareness(e);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof chunkVCMQFPO2_cjs.d?a.code:"shared-schema-invalid",a instanceof chunkVCMQFPO2_cjs.d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l__namespace.Text)||a.get(e.paragraphId).length>v))throw new chunkVCMQFPO2_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new chunkVCMQFPO2_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunkVCMQFPO2_cjs.a||t.get("schemaVersion")!==chunkVCMQFPO2_cjs.b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new chunkVCMQFPO2_cjs.d("immutable-metadata-changed");let e=t.get("baseline");if(!(e instanceof Uint8Array)||e.byteLength!==this.baseline.bytes.byteLength||e.some((r,i)=>r!==this.baseline.bytes[i]))throw new chunkVCMQFPO2_cjs.d("immutable-baseline-changed");for(let[r,i]of a)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>v)throw new chunkVCMQFPO2_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new chunkVCMQFPO2_cjs.d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=chunkVCMQFPO2_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new chunkVCMQFPO2_cjs.d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new chunkVCMQFPO2_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",collaboration.isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof chunkVCMQFPO2_cjs.d?o.code:"remote-apply-failed",o instanceof chunkVCMQFPO2_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=chunkVCMQFPO2_cjs.f(n.bootstrap.document,t);return await chunkVCMQFPO2_cjs.g(n.ydoc,t,a.actorId,o),chunkVCMQFPO2_cjs.h(n.ydoc,t)}return await chunkVCMQFPO2_cjs.i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),chunkVCMQFPO2_cjs.h(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>chunkVCMQFPO2_cjs.j[n]));function et(n){if(n!==F)throw new chunkVCMQFPO2_cjs.d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(chunkVCMQFPO2_cjs.l))throw new chunkVCMQFPO2_cjs.d("not-initialized");let t;try{t=n.getMap(chunkVCMQFPO2_cjs.l);}catch{throw new chunkVCMQFPO2_cjs.d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new chunkVCMQFPO2_cjs.d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new chunkVCMQFPO2_cjs.d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
2
- Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.d}});Object.defineProperty(exports,"DOCUMENT_COLLABORATION_VERSIONS",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.j}});Object.defineProperty(exports,"MAX_BASELINE_BYTES",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.c}});Object.defineProperty(exports,"PROTOCOL_VERSION",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.a}});Object.defineProperty(exports,"SCHEMA_VERSION",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.b}});Object.defineProperty(exports,"assertDocumentCollaborationCompatibility",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.k}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.p}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.n}});Object.defineProperty(exports,"readCollaborationResourceUsage",{enumerable:true,get:function(){return chunkVCMQFPO2_cjs.m}});exports.COLLABORATION_FORMAT_VERSION=F;exports.assertCollaborationFormatCompatibility=et;exports.createTextCollaboration=tt;exports.readCollaborationFormatVersion=ot;
1
+ 'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunk6SR5OK66_cjs=require('../chunk-6SR5OK66.cjs'),l=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var l__namespace=/*#__PURE__*/_interopNamespace(l);var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new chunk6SR5OK66_cjs.d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new chunk6SR5OK66_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new chunk6SR5OK66_cjs.d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunk6SR5OK66_cjs.d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunk6SR5OK66_cjs.e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l__namespace.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===store.ORIGIN_IDS.mutationRemote||o.origin===store.ORIGIN_IDS.projection||o.origin===store.ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof chunk6SR5OK66_cjs.d?e.code:"local-mirror-failed",e instanceof chunk6SR5OK66_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l__namespace.encodeRelativePosition(l__namespace.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e={anchor:r,head:i});}this.publishAwareness(e);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof chunk6SR5OK66_cjs.d?a.code:"shared-schema-invalid",a instanceof chunk6SR5OK66_cjs.d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l__namespace.Text)||a.get(e.paragraphId).length>v))throw new chunk6SR5OK66_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new chunk6SR5OK66_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunk6SR5OK66_cjs.a||t.get("schemaVersion")!==chunk6SR5OK66_cjs.b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new chunk6SR5OK66_cjs.d("immutable-metadata-changed");let e=t.get("baseline");if(!(e instanceof Uint8Array)||e.byteLength!==this.baseline.bytes.byteLength||e.some((r,i)=>r!==this.baseline.bytes[i]))throw new chunk6SR5OK66_cjs.d("immutable-baseline-changed");for(let[r,i]of a)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>v)throw new chunk6SR5OK66_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new chunk6SR5OK66_cjs.d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=chunk6SR5OK66_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new chunk6SR5OK66_cjs.d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new chunk6SR5OK66_cjs.d(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",collaboration.isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof chunk6SR5OK66_cjs.d?o.code:"remote-apply-failed",o instanceof chunk6SR5OK66_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=chunk6SR5OK66_cjs.f(n.bootstrap.document,t);return await chunk6SR5OK66_cjs.g(n.ydoc,t,a.actorId,o),chunk6SR5OK66_cjs.h(n.ydoc,t)}return await chunk6SR5OK66_cjs.i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),chunk6SR5OK66_cjs.h(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>chunk6SR5OK66_cjs.j[n]));function et(n){if(n!==F)throw new chunk6SR5OK66_cjs.d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(chunk6SR5OK66_cjs.l))throw new chunk6SR5OK66_cjs.d("not-initialized");let t;try{t=n.getMap(chunk6SR5OK66_cjs.l);}catch{throw new chunk6SR5OK66_cjs.d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new chunk6SR5OK66_cjs.d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new chunk6SR5OK66_cjs.d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
2
+ Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.d}});Object.defineProperty(exports,"DOCUMENT_COLLABORATION_VERSIONS",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.j}});Object.defineProperty(exports,"MAX_BASELINE_BYTES",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.c}});Object.defineProperty(exports,"PROTOCOL_VERSION",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.a}});Object.defineProperty(exports,"SCHEMA_VERSION",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.b}});Object.defineProperty(exports,"assertDocumentCollaborationCompatibility",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.k}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.p}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.n}});Object.defineProperty(exports,"readCollaborationResourceUsage",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.m}});exports.COLLABORATION_FORMAT_VERSION=F;exports.assertCollaborationFormatCompatibility=et;exports.createTextCollaboration=tt;exports.readCollaborationFormatVersion=ot;
@@ -1,2 +1,2 @@
1
- export{b as collaborationModule}from'../chunk-Q2VBO66F.js';import {j,d,l as l$1,f,g,h as h$1,i,e,a,b}from'../chunk-MRW46GJW.js';export{d as CollaborationSchemaError,j as DOCUMENT_COLLABORATION_VERSIONS,c as MAX_BASELINE_BYTES,a as PROTOCOL_VERSION,b as SCHEMA_VERSION,k as assertDocumentCollaborationCompatibility,p as createDocumentCollaboration,n as readCollaborationDocument,m as readCollaborationResourceUsage}from'../chunk-MRW46GJW.js';import*as l from'yjs';import {ORIGIN_IDS}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e$1,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e$1,this.identity=r;let{root:d,paragraphs:p}=e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===ORIGIN_IDS.mutationRemote||o.origin===ORIGIN_IDS.projection||o.origin===ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof d?e.code:"local-mirror-failed",e instanceof d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l.encodeRelativePosition(l.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e$1;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e$1={anchor:r,head:i});}this.publishAwareness(e$1);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l.createAbsolutePositionFromRelativePosition(l.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof d?a.code:"shared-schema-invalid",a instanceof d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l.Text)||a.get(e.paragraphId).length>v))throw new d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a$1}=e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new d("unsupported-root-key");if(t.get("protocolVersion")!==a||t.get("schemaVersion")!==b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new d("immutable-metadata-changed");let e$1=t.get("baseline");if(!(e$1 instanceof Uint8Array)||e$1.byteLength!==this.baseline.bytes.byteLength||e$1.some((r,i)=>r!==this.baseline.bytes[i]))throw new d("immutable-baseline-changed");for(let[r,i]of a$1)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l.Text)||i.length>v)throw new d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new d(isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof d?o.code:"remote-apply-failed",o instanceof d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=f(n.bootstrap.document,t);return await g(n.ydoc,t,a.actorId,o),h$1(n.ydoc,t)}return await i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),h$1(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>j[n]));function et(n){if(n!==F)throw new d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(l$1))throw new d("not-initialized");let t;try{t=n.getMap(l$1);}catch{throw new d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
1
+ export{b as collaborationModule}from'../chunk-Q2VBO66F.js';import {j,d,l as l$1,f,g,h as h$1,i,e,a,b}from'../chunk-6CDC4KCE.js';export{d as CollaborationSchemaError,j as DOCUMENT_COLLABORATION_VERSIONS,c as MAX_BASELINE_BYTES,a as PROTOCOL_VERSION,b as SCHEMA_VERSION,k as assertDocumentCollaborationCompatibility,p as createDocumentCollaboration,n as readCollaborationDocument,m as readCollaborationResourceUsage}from'../chunk-6CDC4KCE.js';import*as l from'yjs';import {ORIGIN_IDS}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var w="docxEditor",h=256,L=256,v=1e6,$=3e4;function X(n){let t=n.actorId.trim(),a=n.name.trim();if(t.length===0||t.length>h||a.length===0||a.length>h)throw new d("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new d("invalid-identity-color");return Object.freeze({actorId:t,name:a,...n.color?{color:n.color}:{},role:n.role??"human"})}function G(n){let t=n.trim();if(t.length===0||t.length>h)throw new d("invalid-document-id");return t}function J(n){let t=n?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new d("invalid-session-id");return t}function Z(n,t){let a=n.toString();if(a===t)return;let o=0;for(;o<a.length&&o<t.length&&a.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<a.length-o&&e<t.length-o&&a.charCodeAt(a.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=a.length-o-e;r>0&&n.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&n.insert(o,i);}function M(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;return typeof t.paragraphId!="string"||t.paragraphId.length!==8||typeof t.position!="string"||t.position.length===0||t.position.length>2048||!/^[A-Za-z0-9_-]+$/.test(t.position)?null:{paragraphId:t.paragraphId,position:t.position}}function W(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let t=n,a=M(t.anchor),o=M(t.head);if(a&&o)return {anchor:a,head:o};if(typeof t.paragraphId=="string"&&t.paragraphId.length===8&&typeof t.anchor=="string"&&typeof t.head=="string"&&t.anchor.length>0&&t.head.length>0&&t.anchor.length<=2048&&t.head.length<=2048&&/^[A-Za-z0-9_-]+$/.test(t.anchor)&&/^[A-Za-z0-9_-]+$/.test(t.head))return {anchor:{paragraphId:t.paragraphId,position:t.anchor},head:{paragraphId:t.paragraphId,position:t.head}}}function _(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let t=n;if(typeof t.actorId!="string"||t.actorId.length===0||t.actorId.length>h||typeof t.name!="string"||t.name.length===0||t.name.length>h)return null;let a=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=W(t.selection);return {actorId:t.actorId,name:t.name,...a?{color:a}:{},role:o,...e?{selection:e}:{}}}function K(n){let t="";for(let a of n)t+=String.fromCharCode(a);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function q(n){let t=n.replace(/-/g,"+").replace(/_/g,"/"),a=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(a,o=>o.charCodeAt(0))}var A=class{constructor(t,a,o,e$1,r,i){this.ydoc=t;this.awareness=a;this.baseline=i;this.documentId=o,this.sessionId=e$1,this.identity=r;let{root:d,paragraphs:p}=e(t);this.baselineSha256=String(d.get("baselineSha256")),this.initializedBy=String(d.get("initializedBy")),this.undoManager=new l.UndoManager([...p.values()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:0}),t.on("afterTransaction",this.onYjsTransaction),a.on("change",this.onAwarenessChange),this.publishAwareness(),this.setStatus("ready");}ydoc;awareness;baseline;documentId;sessionId;identity;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-collaboration-local"});undoManager;baselineSha256;initializedBy;port=null;detachPort=null;applyingSharedState=false;remoteCounter=0;destroyed=false;status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}subscribeStatus(t){return this.statusListeners.add(t),()=>this.statusListeners.delete(t)}setTransportStatus(t,a,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(a!==void 0){this.setStatus(t,a,o);return}this.setStatus(t);}}get attached(){return this.port!==null}attach(t){if(this.destroyed)return ()=>{};if(this.port)return ()=>{};if(t.documentId!==this.documentId)return this.setStatus("error","document-id-mismatch"),()=>{};this.validateParagraphSet(t),this.port=t,this.reconcilePortFromYjs();let a=t.subscribe(o=>{if(!(this.destroyed||this.applyingSharedState)&&!(o.origin===ORIGIN_IDS.mutationRemote||o.origin===ORIGIN_IDS.projection||o.origin===ORIGIN_IDS.awareness))try{this.reconcileYjsFromPort();}catch(e){this.setStatus("error",e instanceof d?e.code:"local-mirror-failed",e instanceof d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),a(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,a){if(this.destroyed)return "collaboration-session-destroyed";if(this.statusState.status()!=="ready")return "collaboration-session-not-ready";if(!this.port)return "collaboration-session-not-attached";if(a.kind!=="body")return "experimental-collaboration-body-text-only";let o=new Map(this.port.paragraphs().map(e=>[e.nodeId,e.text.length]));for(let e of t){if(e.op!=="insertText"&&e.op!=="deleteText")return "experimental-collaboration-text-only";if("revision"in e&&e.revision!==void 0)return "experimental-collaboration-untracked-text-only";if(!this.port.paragraphByNodeId(e.paragraphId))return "experimental-collaboration-existing-paragraphs-only";let r=o.get(e.paragraphId);if(r===void 0)return "experimental-collaboration-existing-paragraphs-only";let i=e.op==="insertText"?r+e.text.length:r-Math.max(0,e.end-e.start);if(i>v)return "collaboration-text-limit";o.set(e.paragraphId,Math.max(0,i));}return null}canUndo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.undoStack.length>0}canRedo(){return !this.destroyed&&this.statusState.status()==="ready"&&this.undoManager.redoStack.length>0}undo(){return this.canUndo()?(this.undoManager.undo(),true):false}redo(){return this.canRedo()?(this.undoManager.redo(),true):false}setLocalSelection(t){if(this.destroyed)return;let{paragraphs:a}=e(this.ydoc),o=(r,i)=>{let d=a.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:K(l.encodeRelativePosition(l.createRelativePositionFromTypeIndex(d,Math.max(0,Math.min(i,d.length)))))}},e$1;if(t){let r=o(t.anchor.paragraphId,t.anchor.offset),i=o(t.head.paragraphId,t.head.offset);r&&i&&(e$1={anchor:r,head:i});}this.publishAwareness(e$1);}participants(){let t=[],a=[...this.awareness.getStates().entries()].slice(0,L);for(let[o,e]of a){let r=_(e[w]);r&&t.push({actorId:r.actorId,name:r.name,...r.color?{color:r.color}:{},role:r.role??"human",isLocal:o===this.awareness.clientID});}return Object.freeze(t)}subscribeParticipants(t){return this.participantListeners.add(t),()=>this.participantListeners.delete(t)}remoteSelections(){if(!this.port)return [];let t=[...this.awareness.getStates().entries()].slice(0,L),{paragraphs:a}=e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=_(r[w]);if(!i?.selection)continue;let d=y=>{let T=a.get(y.paragraphId);if(!T)return null;let u;try{u=l.createAbsolutePositionFromRelativePosition(l.decodeRelativePosition(q(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==T)return null;let f=this.port?.paragraphs().find(U=>U.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),x=d(i.selection.head);!p||!x||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(x)}));}return Object.freeze(o)}subscribeRemoteSelections(t){return this.selectionListeners.add(t),()=>this.selectionListeners.delete(t)}destroy(){this.destroyed||(this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}flushPendingJournals(){this.port?.flushPendingJournals();}onYjsTransaction=t=>{if(!this.destroyed&&t.origin!==this.localOrigin){try{this.validateImmutableSchema();}catch(a){this.setStatus("error",a instanceof d?a.code:"shared-schema-invalid",a instanceof d?a.detail:void 0);return}this.port&&this.reconcilePortFromYjs();}};onAwarenessChange=()=>{if(this.destroyed)return;let t=this.remoteSelections();for(let o of [...this.selectionListeners])o(t);let a=this.participants();for(let o of [...this.participantListeners])o(a);};publishAwareness(t){let a={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...t?{selection:t}:{}};this.awareness.setLocalStateField(w,a);}validateParagraphSet(t){let{paragraphs:a}=e(this.ydoc),o=t.paragraphs();if(o.length!==a.size||o.some(e=>!a.has(e.paragraphId)||!(a.get(e.paragraphId)instanceof l.Text)||a.get(e.paragraphId).length>v))throw new d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:a$1}=e(this.ydoc),o=new Set(["protocolVersion","schemaVersion","documentId","baselineSha256","baselineByteLength","initializedBy","baseline","initialized"]);if([...t.keys()].some(r=>!o.has(r)))throw new d("unsupported-root-key");if(t.get("protocolVersion")!==a||t.get("schemaVersion")!==b||t.get("documentId")!==this.documentId||t.get("baselineSha256")!==this.baselineSha256||t.get("baselineByteLength")!==this.baseline.bytes.byteLength||t.get("initializedBy")!==this.initializedBy||t.get("initialized")!==true)throw new d("immutable-metadata-changed");let e$1=t.get("baseline");if(!(e$1 instanceof Uint8Array)||e$1.byteLength!==this.baseline.bytes.byteLength||e$1.some((r,i)=>r!==this.baseline.bytes[i]))throw new d("immutable-baseline-changed");for(let[r,i]of a$1)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l.Text)||i.length>v)throw new d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:a}=e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=a.get(o.paragraphId);if(!e)throw new d("paragraph-set-mismatch");Z(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:a}=e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=a.get(e.paragraphId);if(!r)throw new d("paragraph-set-mismatch");let i=r.toString();i!==e.text&&o.push({paragraphId:e.paragraphId,text:i});}if(o.length>0){this.remoteCounter+=1;let e=t.applyParagraphTexts(o,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`remote:${this.remoteCounter}`});if(!e.ok)throw new d(isCollaborationFailureCode(e.reason)?e.reason:"remote-apply-failed",isCollaborationFailureCode(e.reason)?void 0:e.reason)}}catch(o){this.setStatus("error",o instanceof d?o.code:"remote-apply-failed",o instanceof d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,a,o){if(!this.statusState.set(t,a,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function Q(n,t,a){if(n.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(n.bootstrap.kind==="create"){let o=f(n.bootstrap.document,t);return await g(n.ydoc,t,a.actorId,o),h$1(n.ydoc,t)}return await i(n.ydoc,n.bootstrap.timeoutMs??$,n.bootstrap.signal),h$1(n.ydoc,t)}async function tt(n){let t=G(n.documentId),a=J(n.sessionId),o=X(n.identity),e=await Q(n,t,o),r=new A(n.ydoc,n.awareness,t,a,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}var D=["protocolVersion","sharedSchemaVersion","repairVersion","canonicalModelVersion"];function Y(n){return `docx-collaboration:${n.join(".")}`}var F=Y(D.map(n=>j[n]));function et(n){if(n!==F)throw new d("collaboration-format-mismatch","The collaboration format version is missing or incompatible with this deployment.")}function ot(n){if(!n.share.has(l$1))throw new d("not-initialized");let t;try{t=n.getMap(l$1);}catch{throw new d("collaboration-format-mismatch","The saved room has invalid collaboration version information.")}if(t.get("initialized")!==true||typeof t.get("documentId")!="string")throw new d("not-initialized");let a=D.map(o=>{let e=t.get(o);if(typeof e!="number"||!Number.isSafeInteger(e)||e<0)throw new d("collaboration-format-mismatch","The saved room has missing or invalid collaboration version information.");return e});return Y(a)}
2
2
  export{F as COLLABORATION_FORMAT_VERSION,et as assertCollaborationFormatCompatibility,tt as createTextCollaboration,ot as readCollaborationFormatVersion};
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunkVCMQFPO2_cjs=require('../chunk-VCMQFPO2.cjs'),F=require('yjs'),awareness=require('y-protocols/awareness'),yWebrtc=require('y-webrtc');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var F__namespace=/*#__PURE__*/_interopNamespace(F);var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=chunkLUUFBXJ5_cjs.b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F__namespace.Doc,d=new awareness.Awareness(o),c=null,l=()=>{},f=()=>{let u=new yWebrtc.WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await chunkVCMQFPO2_cjs.p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b,destroy(){S||(S=true,b.off("status",h),s.destroy(),b.destroy(),d.destroy(),o.destroy());}})}
1
+ 'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunk6SR5OK66_cjs=require('../chunk-6SR5OK66.cjs'),F=require('yjs'),awareness=require('y-protocols/awareness'),yWebrtc=require('y-webrtc');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var F__namespace=/*#__PURE__*/_interopNamespace(F);var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=chunkLUUFBXJ5_cjs.b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F__namespace.Doc,d=new awareness.Awareness(o),c=null,l=()=>{},f=()=>{let u=new yWebrtc.WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await chunk6SR5OK66_cjs.p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b,destroy(){S||(S=true,b.off("status",h),s.destroy(),b.destroy(),d.destroy(),o.destroy());}})}
2
2
  Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.DEMO_SIGNALING_ENDPOINTS=W;exports.createWebrtcCollaboration=ee;exports.resetDemoSignalingWarningForTests=V;exports.resolveWebrtcRoomPassword=X;exports.warnOnDemoSignalingFallback=H;
@@ -1,2 +1,2 @@
1
- import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {p}from'../chunk-MRW46GJW.js';import*as F from'yjs';import {Awareness}from'y-protocols/awareness';import {WebrtcProvider}from'y-webrtc';var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F.Doc,d=new Awareness(o),c=null,l=()=>{},f=()=>{let u=new WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b$1=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b$1.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b$1,destroy(){S||(S=true,b$1.off("status",h),s.destroy(),b$1.destroy(),d.destroy(),o.destroy());}})}
1
+ import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {p}from'../chunk-6CDC4KCE.js';import*as F from'yjs';import {Awareness}from'y-protocols/awareness';import {WebrtcProvider}from'y-webrtc';var D=new WeakSet,T=(e,n)=>(e[n]<<24|e[n+1]<<16|e[n+2]<<8|e[n+3])>>>0,w=(e,n,i)=>{e[n]=i>>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=i&255;},B=e=>e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):null,Y=e=>new Promise(n=>{setTimeout(n,e);});function L(e,n){if(D.has(e))return;D.add(e);let i=e.send.bind(e),o=e._onChannelMessage.bind(e),d=n?.partialTimeoutMs,c=typeof d=="number"&&Number.isFinite(d)&&d>0?d:3e4,l=n?.onAbandonedMessage,f=[],s=new Map,b=false,E=1,h=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),s.delete(t),e.destroyed!==true&&l?.());},S=t=>{let r=s.get(t);r&&(r.timer!==void 0&&clearTimeout(r.timer),r.timer=setTimeout(()=>{h(t);},c));},u=()=>e._channel?.bufferedAmount??0,p=async()=>{let t=0;for(;u()>1048576;){if(e.destroyed===true||t>=3e4)return false;await Y(20),t+=20;}return e.destroyed!==true},I=async t=>{let r=Math.ceil(t.byteLength/16371);if(r>8192)throw new Error(`collaboration message needs ${r} chunks, above the 8192 limit`);let g=E;E=E+1>>>0||1;for(let A=0;A<r;A+=1){if(!await p())return;let y=A*16371,a=t.subarray(y,Math.min(y+16371,t.byteLength)),m=new Uint8Array(13+a.byteLength);m[0]=251,w(m,1,g),w(m,5,A),w(m,9,r),m.set(a,13),i(m);}},k=async()=>{if(!b){b=true;try{for(;f.length>0;){let t=f.shift();if(t){if(e.destroyed===!0)return;await I(t);}}}finally{b=false;}}};e.send=t=>{if(typeof t=="string"||t.byteLength<=16371){i(t);return}f.push(t),k();},e._onChannelMessage=t=>{let r=B(t.data);if(!r||r.byteLength<13||r[0]!==251){o(t);return}let g=T(r,1),A=T(r,5),y=T(r,9);if(y===0||y>8192||A>=y)return;let a=s.get(g);if(!a){if(s.size>=4){let _=s.keys().next();_.done||h(_.value);}a={chunks:new Array(y),count:y,received:0,bytes:0,timer:void 0},s.set(g,a);}if(a.count!==y||a.chunks[A])return;let m=r.subarray(13);if(a.chunks[A]=m,a.received+=1,a.bytes+=m.byteLength,a.received!==a.count){S(g);return}a.timer!==void 0&&clearTimeout(a.timer),s.delete(g);let v=new Uint8Array(a.bytes),P=0;for(let _ of a.chunks){if(!_)return;v.set(_,P),P+=_.byteLength;}e.destroyed!==true&&e.push(v);};}var W=Object.freeze(["wss://turn.0docker.com/ws"]),R=false;function H(e){e===void 0&&(R||(R=true,console.warn("[docx-editor] createWebrtcCollaboration was called without `signaling`, so it uses the public demo endpoints. They are shared, unauthenticated, and can go away. Pass your own `signaling` URLs (and TURN `iceServers`) in production, or pass `signaling: DEMO_SIGNALING_ENDPOINTS` explicitly to accept the demo endpoints.")));}function V(){R=false;}var G=/^[A-Za-z0-9_-]{24,256}$/,U="#collab=";function X(e){let n=e.password?.trim()??"";return n.length>0?n:K(e.href)}var K=e=>{let n=e??(typeof globalThis.location=="object"&&globalThis.location!==null?String(globalThis.location.href??""):"");if(n.length===0)return;let i;try{i=new URL(n).hash;}catch{return}if(!i.startsWith(U))return;let o;try{o=decodeURIComponent(i.slice(U.length));}catch{return}if(G.test(o))return o},z=(e,n)=>{Promise.resolve(e.key).then(()=>{let i=e.room;if(!i)return;let o=i.webrtcConns,d=l=>{L(l.peer,{onAbandonedMessage:n});};for(let l of o.values())d(l);let c=o.set.bind(o);o.set=(l,f)=>(d(f),c(l,f));});};async function ee(e){let n=b(e.roomId);H(e.signaling);let i=X({password:e.password}),o=new F.Doc,d=new Awareness(o),c=null,l=()=>{},f=()=>{let u=new WebrtcProvider(n,o,{awareness:d,signaling:[...e.signaling??W],...i!==void 0?{password:i}:{},...e.iceServers?{peerOpts:{config:{iceServers:e.iceServers.map(p=>({...p}))}}}:{}});return z(u,()=>l()),u},s;try{e.bootstrap.kind!=="create"&&(c=f()),s=await p({ydoc:o,awareness:d,documentId:n,identity:e.identity,bootstrap:e.bootstrap,offlineEditing:e.offlineEditing}),c||(c=f());}catch(u){throw c?.destroy(),d.destroy(),o.destroy(),u}if(!c)throw s.destroy(),d.destroy(),o.destroy(),new Error("WebRTC provider did not initialize");let b$1=c,E=s.session;l=()=>{E.setTransportStatus("error","transport","incomplete chunk");};let h=u=>{E.setTransportStatus(u.connected?"ready":"disconnected",u.connected?void 0:"transport-disconnected",u.connected?void 0:"webrtc disconnected");};b$1.on("status",h);let S=false;return Object.freeze({document:s.document,session:E,ydoc:o,provider:b$1,destroy(){S||(S=true,b$1.off("status",h),s.destroy(),b$1.destroy(),d.destroy(),o.destroy());}})}
2
2
  export{W as DEMO_SIGNALING_ENDPOINTS,ee as createWebrtcCollaboration,V as resetDemoSignalingWarningForTests,X as resolveWebrtcRoomPassword,H as warnOnDemoSignalingFallback};
@@ -267,6 +267,8 @@ interface CustomNodeDefinition<Schema extends StandardSchemaV1 | undefined = any
267
267
  /**
268
268
  * Contribute a card to the review sidebar for every recognized node of this
269
269
  * definition, anchored at the node's range. Return null to skip one node.
270
+ * Without this hook the node has no card: it never becomes the active review
271
+ * item, so placing the cursor inside it shows no active highlight.
270
272
  *
271
273
  * `attrs` and `text` originate in the file — untrusted; the returned strings
272
274
  * are rendered as TEXT by the pane, never markup. The context-menu section
@@ -267,6 +267,8 @@ interface CustomNodeDefinition<Schema extends StandardSchemaV1 | undefined = any
267
267
  /**
268
268
  * Contribute a card to the review sidebar for every recognized node of this
269
269
  * definition, anchored at the node's range. Return null to skip one node.
270
+ * Without this hook the node has no card: it never becomes the active review
271
+ * item, so placing the cursor inside it shows no active highlight.
270
272
  *
271
273
  * `attrs` and `text` originate in the file — untrusted; the returned strings
272
274
  * are rendered as TEXT by the pane, never markup. The context-menu section
@@ -0,0 +1 @@
1
+ export{o as ATTACH_WATCHDOG_MS_FOR_TESTS,p as createDocumentCollaboration,n as readCollaborationDocument}from'./chunk-6CDC4KCE.js';
@@ -0,0 +1 @@
1
+ export{c as ATTACH_WATCHDOG_MS_FOR_TESTS,d as createDocumentCollaboration,b as readCollaborationDocument}from'./chunk-RGR2BLZD.js';
@@ -0,0 +1 @@
1
+ 'use strict';var chunkHZEWGK5A_cjs=require('./chunk-HZEWGK5A.cjs');Object.defineProperty(exports,"ATTACH_WATCHDOG_MS_FOR_TESTS",{enumerable:true,get:function(){return chunkHZEWGK5A_cjs.c}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkHZEWGK5A_cjs.d}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkHZEWGK5A_cjs.b}});
@@ -0,0 +1 @@
1
+ 'use strict';var chunk6SR5OK66_cjs=require('./chunk-6SR5OK66.cjs');Object.defineProperty(exports,"ATTACH_WATCHDOG_MS_FOR_TESTS",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.o}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.p}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunk6SR5OK66_cjs.n}});
@@ -1 +1 @@
1
- import {b}from'./chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'./chunk-6DEUT2RQ.js';import {d,a}from'./chunk-3JW4VNG5.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';import {isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new a(isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d$1=b(o.roomId),c=o[O]??F,n=new P.Doc,r=new Awareness(n),s=()=>c({url:o.url,name:d$1,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await d({ydoc:n,awareness:r,documentId:d$1,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b$1||(b$1=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}export{O as HOCUSPOCUS_PROVIDER_FOR_TESTS,_ as createHocuspocusCollaboration};
1
+ import {b}from'./chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'./chunk-6DEUT2RQ.js';import {d,a}from'./chunk-RGR2BLZD.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';import {isCollaborationFailureCode}from'@docx-editor.dev/core/collaboration';var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new a(isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d$1=b(o.roomId),c=o[O]??F,n=new P.Doc,r=new Awareness(n),s=()=>c({url:o.url,name:d$1,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await d({ydoc:n,awareness:r,documentId:d$1,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b$1||(b$1=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}export{O as HOCUSPOCUS_PROVIDER_FOR_TESTS,_ as createHocuspocusCollaboration};
@@ -1 +1 @@
1
- 'use strict';var chunkLUUFBXJ5_cjs=require('./chunk-LUUFBXJ5.cjs'),chunkJDLJS5RD_cjs=require('./chunk-JDLJS5RD.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var P__namespace=/*#__PURE__*/_interopNamespace(P);var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new chunkJDLJS5RD_cjs.a(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new chunkJDLJS5RD_cjs.a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[O]??F,n=new P__namespace.Doc,r=new awareness.Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await chunkJDLJS5RD_cjs.d({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",collaboration.isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b||(b=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.HOCUSPOCUS_PROVIDER_FOR_TESTS=O;exports.createHocuspocusCollaboration=_;
1
+ 'use strict';var chunkLUUFBXJ5_cjs=require('./chunk-LUUFBXJ5.cjs'),chunkHZEWGK5A_cjs=require('./chunk-HZEWGK5A.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider'),collaboration=require('@docx-editor.dev/core/collaboration');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var P__namespace=/*#__PURE__*/_interopNamespace(P);var S=3e4,O=Symbol("createHocuspocusCollaboration.provider"),F=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function I(o,d){return new Promise((c,n)=>{if(o.isSynced){c();return}let r=()=>{clearTimeout(i),o.off("synced",s),o.off("authenticationFailed",t);},s=()=>{r(),c();},t=e=>{r(),n(new chunkHZEWGK5A_cjs.a(collaboration.isCollaborationFailureCode(e.reason)?e.reason:"initialization-aborted",`authentication failed: ${e.reason}`));},i=setTimeout(()=>{r(),n(new chunkHZEWGK5A_cjs.a("initialization-timeout"));},d);o.on("synced",s),o.on("authenticationFailed",t);})}async function _(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[O]??F,n=new P__namespace.Doc,r=new awareness.Awareness(n),s=()=>c({url:o.url,name:d,document:n,awareness:r,...o.token!==void 0?{token:o.token}:{}}),t=null,i=null;try{o.bootstrap.kind!=="create"&&(t=s(),await I(t,o.syncedTimeoutMs??S)),i=await chunkHZEWGK5A_cjs.d({ydoc:n,awareness:r,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=s());}catch(a){throw i?.destroy(),t?.destroy(),r.destroy(),n.destroy(),a}let e=t,u=i,l=u.session,f=a=>{l.setTransportStatus(a.status==="connected"?"ready":"disconnected",a.status==="connected"?void 0:"transport-disconnected",a.status==="connected"?void 0:"websocket disconnected");};e.on("status",f);let p=a=>{l.setTransportStatus("error",collaboration.isCollaborationFailureCode(a.reason)?a.reason:"authentication-failed");};e.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:n,provider:e,destroy(){b||(b=true,e.off("status",f),e.off("authenticationFailed",p),u.destroy(),e.destroy(),r.destroy(),n.destroy());}})}Object.defineProperty(exports,"createCollaborationRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.a}});Object.defineProperty(exports,"validateRoomId",{enumerable:true,get:function(){return chunkLUUFBXJ5_cjs.b}});exports.HOCUSPOCUS_PROVIDER_FOR_TESTS=O;exports.createHocuspocusCollaboration=_;