@docx-editor.dev/pro 2.12.0 → 2.13.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.
- package/README.md +27 -6
- package/dist/chunk-ABW4JBFQ.js +3 -0
- package/dist/chunk-L6J5LQXZ.cjs +3 -0
- package/dist/chunk-MTNG3CRI.js +3 -0
- package/dist/chunk-VRIYIY2Y.cjs +3 -0
- package/dist/collaboration/hocuspocus.cjs +1 -1
- package/dist/collaboration/hocuspocus.js +1 -1
- package/dist/collaboration/index.cjs +2 -2
- package/dist/collaboration/index.js +1 -1
- package/dist/collaboration/webrtc.cjs +1 -1
- package/dist/collaboration/webrtc.js +1 -1
- package/dist/document-session-2QOWIMD7.js +1 -0
- package/dist/document-session-2YB34CXA.js +1 -0
- package/dist/document-session-BIMEOZBG.cjs +1 -0
- package/dist/document-session-DPSXU7I7.cjs +1 -0
- package/dist/{hocuspocus-FC5NXRLW.js → hocuspocus-ABVDFDOK.js} +1 -1
- package/dist/{hocuspocus-3FLNEX7M.cjs → hocuspocus-IIJMOMM5.cjs} +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.js +1 -1
- package/dist/vue/hocuspocus.cjs +1 -1
- package/dist/vue/hocuspocus.js +1 -1
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.js +1 -1
- package/dist/vue/webrtc.cjs +1 -1
- package/dist/vue/webrtc.js +1 -1
- package/dist/{webrtc-UAS5I63G.cjs → webrtc-2WNLDNHU.cjs} +1 -1
- package/dist/{webrtc-V2JQ2NO7.js → webrtc-PZCIQ4FZ.js} +1 -1
- package/package.json +4 -4
- package/dist/chunk-C4RVARMI.cjs +0 -3
- package/dist/chunk-DHIPX767.js +0 -3
- package/dist/chunk-KOGVHJ7U.js +0 -3
- package/dist/chunk-QA3F5EUJ.cjs +0 -3
- package/dist/document-session-I77CU7RQ.cjs +0 -1
- package/dist/document-session-MTK2LEYT.cjs +0 -1
- package/dist/document-session-NFUE7UBO.js +0 -1
- package/dist/document-session-WEZH77T3.js +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import*as R from'yjs';import {readOoxmlPackage,normalizeParagraphIdentity,TreePackageStore,writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,ORIGIN_IDS,isDangerousKey,normalizePartName,WML_NAMESPACE_URI,DATASTORE_NAMESPACE_URI,CUSTOM_XML_REL,CUSTOM_XML_PROPS_REL,buildRelationshipSet,resolveRelationship,XML_NAMESPACE_URI}from'@docx-editor.dev/core/store';import {createCollaborationStatusTracker,safeParticipantColor}from'@docx-editor.dev/core/collaboration';import {sha256FontBytes}from'@docx-editor.dev/core/layout';import {createCollaborationDocumentPort}from'@docx-editor.dev/core/collaboration/replication';var Gn=new Set(["paraId","textId","id","numId","bookmarkId"]);function ot(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function it(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),ot(e)}function le(n){return /^[0-9a-f]{32}$/.test(n)}function at(n,e){if(!le(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 ke(n,e){return `yjs:${n}:${e}`}function de(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return le(e)?e:null}function Pe(n){let e=[];for(let t of n)Gn.has(t.localName)&&e.push(t.value);return e}var $=class{replicaId;next=0;constructor(e){if(this.replicaId=e??it(),!le(this.replicaId))throw new Error("invalid replica identity")}take(){let e=at(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};var N=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}),Zn=/^sha256:[0-9a-f]{64}$/;function lt(n){return n?Object.freeze({...N,...n}):N}function g(n){return isDangerousKey(n)?"prototype-key":null}function w(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function L(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 dt(n){for(let e of Object.keys(n)){let t=g(e);if(t)return t}return !Zn.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>N.maxBlobBytes?"blob-too-large":w(n.mediaType,N.maxMediaTypeLength)||n.mediaType.length===0||w(n.storageKey,N.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var ct=1,ut=2,pt=1,ht=1,Qn="docx-package-meta-v1",er="docx-package-nodes-v1",tr="docx-package-parts-v1",nr="docx-package-rels-v1",rr="docx-package-overrides-v1",or="docx-package-defaults-v1",ir="docx-package-binaries-v1",ar="docx-package-namespaces-v1",sr="docx-package-attributes-v1",lr="docx-package-bindings-v1",z="s",_="t",ce="children",U="deleted",X="replacedBy",Oe="splitFrom",S="",mt="-",gt=Object.freeze({kind:"docx-package-bootstrap"}),ft=Object.freeze({kind:"docx-package-journal"});function ue(n){return n.kind==="textValue"}function I(n){return !ue(n)}var dr=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),cr=200;function yt(n){let e=new Map;for(let t of n)dr.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,cr)}function bt(n){return {meta:n.getMap(Qn),nodes:n.getMap(er),parts:n.getMap(tr),relationships:n.getMap(nr),overrides:n.getMap(rr),defaults:n.getMap(or),binaries:n.getMap(ir),namespaces:n.getMap(ar),attributes:n.getMap(sr),bindings:n.getMap(lr)}}var It=[["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"]],ur=new Map(It),pr=new Map(It.map(([n,e])=>[e,n]));function hr(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 J(n){return n.length===0?mt:ur.get(n)??`n${hr(n)}`}function j(n,e,t){let r=J(e);return e.length===0||g(r)||w(e,t)||n.get(r)!==e&&n.set(r,e),r}function H(n,e){if(e===mt||g(e))return "";let t=n.get(e);return typeof t=="string"?t:pr.get(e)??""}function Ae(n,e,t,r){return `${n}${S}${e}${S}${t}${S}${r}`}function pe(n){let e=n.split(S);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Ne(n,e,t){return `${n}${S}${e}${S}${t}`}function G(n){let e=n.split(S);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 Me(n,e){return `${n}${S}${e}`}function q(n){let e=n.split(S);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function xt(n,e){return `${n}${S}${e}`}function vt(n){let e=n.indexOf(S);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function St(n){let e=new R.Map;e.set(z,Ae(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new R.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ce,t),e}function Et(n){let e=new R.Map;return e.set(_,new R.Text(n)),e}function Lt(n,e,t){let r=new R.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function Rt(n){let e=new R.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 wt(n){let e=new R.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Ct(n){n.set("protocolVersion",ct),n.set("sharedSchemaVersion",ut),n.set("repairVersion",pt),n.set("canonicalModelVersion",ht),n.set("initialized",true);}function b(n){return n instanceof R.Map}function k(n){if(!b(n))return null;let e=n.get(ce);return e instanceof R.Array?e:null}function Z(n){return b(n)&&n.get(_)instanceof R.Text}function O(n){return b(n)&&n.get(U)===true}function Te(n){if(!b(n))return null;let e=n.get(X);return typeof e=="string"&&e.length>0?e:null}function K(n){if(!b(n))return null;let e=n.get(Oe);return typeof e=="string"&&e.length>0?e:null}var mr=256,he=class{constructor(e){this.nodes=e;}nodes;runsBySplitOrigin=new Map;replicasByOrigin=new Map;contestedOrigins=new Set;liveRootedOrigins=new Set;declinedTangleCount=0;reset(){this.runsBySplitOrigin=new Map,this.replicasByOrigin=new Map,this.contestedOrigins=new Set,this.liveRootedOrigins=new Set;}record(e,t){let r=this.nodes.get(t);b(r)&&e!==t&&(r.set(Oe,e),this.index(e,t),this.reSplitOfContestedOrigin(e)&&(this.declinedTangleCount+=1));}reSplitOfContestedOrigin(e){if(K(this.nodes.get(e))===null)return false;let t=e;for(let r=0;r<mr;r+=1){if(this.contestedOrigins.has(t)||this.liveRootedOrigins.has(t))return true;let o=K(this.nodes.get(t));if(o===null||o===t)return false;t=o;}return false}indexExisting(e){let t=K(this.nodes.get(e));t!==null&&t!==e&&this.index(t,e);}index(e,t){let r=this.runsBySplitOrigin.get(e)??new Set;r.add(t),this.runsBySplitOrigin.set(e,r);let o=this.replicasByOrigin.get(e)??new Set;o.add(de(t)??""),this.replicasByOrigin.set(e,o),o.size>1&&this.contestedOrigins.add(e);let i=this.nodes.get(e);b(i)&&!O(i)&&this.liveRootedOrigins.add(e);}declinedTangleEvents(){return this.declinedTangleCount}isReSplit(e){let t=this.runsBySplitOrigin.get(e);if(!t)return false;for(let r of t)if((this.runsBySplitOrigin.get(r)?.size??0)>0)return true;return false}loserRuns(e){let t=new Set,r=new Set([...this.contestedOrigins,...this.liveRootedOrigins]);for(let o of r){let i=this.runsBySplitOrigin.get(o);if(!i||this.isReSplit(o))continue;let s=new Set;for(let d of i)e.isPresent(d)&&s.add(de(d)??"");let a=e.isPresent(o);if(!a&&s.size<=1)continue;let l=a?null:[...s].sort()[0];for(let d of i)!a&&(de(d)??"")===l||e.isPresent(d)&&t.add(d);}return t}};function kt(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&&I(r)&&r.childIds.includes(e)}function me(n){return typeof n=="string"?n:""}function Pt(n,e){return n<e?-1:n>e?1:0}function De(n,e){return `${n}${S}${e}`}function fr(n){let e=n.indexOf(S);return e<0?n:n.slice(0,e)}function Ot(n){let e=[];return n.forEach((t,r)=>{!b(t)||g(r)||t.forEach(o=>{if(!b(o))return;let i=me(o.get("id")),s=me(o.get("type"));if(i.length===0||s.length===0)return;let a=me(o.get("ownerPart"))||fr(r);if(g(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,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||Pt(t.ownerPart,r.ownerPart)||Pt(t.id,r.id)),e}function At(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 yr(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 Nt(n,e){let t=n.childrenSnapshot.get(e);return t||(k(n.nodes.get(e))?.toArray()??[])}function br(n,e){let t=n.nodes.get(e);return !b(t)||O(t)}function Ir(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),br(n,s)))return null;a=e.get(s);let u=n.parentIndex.get(s);if(a!==void 0){if(u!==void 0)return "fallback";break}if(u===void 0)return t.has(s)?"deferred":null;o.push(s),s=u;}let l=[a],d=s;for(let u=o.length-1;u>=0;u-=1){let p=o[u],c=Nt(n,d).indexOf(p);if(c<0)return null;l.push(c),d=p;}return l}function Mt(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,s)=>{r.has(i)||r.set(i,s);});let o=[...t];for(;o.length>0;){let i=[];for(let s of o){let a=null,l=false;for(let d of n.listings.get(s)??[]){if(d===s)continue;let u=Ir(n,r,t,d);if(u==="fallback")return false;if(u==="deferred"){l=true;continue}if(u===null)continue;let p=Nt(n,d).indexOf(s);if(p<0)continue;let c=[...u,p];(!a||yr(c,a.rank)<0)&&(a={rank:c,parent:d});}if(l){i.push(s);continue}a&&n.parentIndex.set(s,a.parent),t.delete(s);}if(i.length===o.length)return false;o=i;}return true}function Tt(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let s of e)r.delete(s);for(let s of i){let a=new Set,l=[{id:s,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){a.delete(d.id);continue}let u=d.id;if(d.parent!==null&&(e===null||e.has(u))&&(r.has(u)||r.set(u,d.parent)),a.has(u))continue;let p=t.get(u);if(!b(p)||O(p))continue;let c=o.get(u)??k(p)?.toArray()??[];a.add(u),l.push({id:u,parent:null,exit:true});let m=new Set,f=[];for(let y of c)m.has(y)||y===u||(m.add(y),f.push(y));for(let y=f.length-1;y>=0;y-=1)l.push({id:f[y],parent:u,exit:false});}}}function Dt(n,e){return `${n}${S}${e}`}function Be(n,e,t,r,o){if(g(t)||g(r.localName))return;let i=j(n.namespaces,r.namespaceUri,e),s=Ne(t,i,r.localName);g(s)||n.attributes.set(s,xt(r.prefix??"",o));}function Bt(n,e,t,r){n.attributes.delete(Ne(e,J(t),r));}function _e(n,e,t,r,o){if(g(t)||g(r))return;let i=j(n.namespaces,o,e),s=Me(t,r);g(s)||n.bindings.set(s,i);}function _t(n,e,t){n.bindings.delete(Me(e,t));}function Ue(n,e,t,r,o,i){let{prefix:s,value:a}=vt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(Dt(r,o),{namespaceUri:H(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function xr(n,e,t,r){let o=n.get(e);o&&(o.delete(Dt(t,r)),o.size===0&&n.delete(e));}function Ye(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:H(n.namespaces,o)});}function vr(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function Ut(n,e,t){for(let[r,o]of t.changes.keys){let i=G(String(r));if(!i||g(i.logicalId)||g(i.localName))continue;if(o.action==="delete"){xr(e,i.logicalId,i.namespaceId,i.localName);continue}let s=n.attributes.get(String(r));typeof s=="string"&&Ue(n,e,i.logicalId,i.namespaceId,i.localName,s);}}function Yt(n,e,t){for(let[r,o]of t.changes.keys){let i=q(String(r));if(!i||g(i.logicalId)||g(i.prefix))continue;if(o.action==="delete"){vr(e,i.logicalId,i.prefix);continue}let s=n.bindings.get(String(r));typeof s=="string"&&Ye(n,e,i.logicalId,i.prefix,s);}}function jt(n,e){let t=n.get(e);if(!b(t))return null;if(Z(t)){let r=t.get(_);return {isText:true,textLength:r instanceof R.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:k(t)?.toArray()??[]}}function Kt(n,e){let t=n.get(e);if(!b(t))return null;if(Z(t))return "textValue";let r=t.get(z);return pe(typeof r=="string"?r:"").kind}function Ft(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 F(n){return typeof n=="string"?n:""}function Vt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=F(t.get("rootId"));o.length!==0&&e.push({name:r,id:F(t.get("id")),rootLogicalId:o,contentType:F(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Wt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(partNameKey(r),t);}),e}function $t(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(r,t);}),e}function Xt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=F(t.get("digest")),i=t.get("size"),s=F(t.get("mediaType")),a=F(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:s,storageKey:a});}),e}function Er(n){return n?._item??null}function Lr(n){return n.content instanceof R.ContentType}function Ht(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=Er(t);return r===null||r.parent!==n?true:!Lr(e)}}function Rr(n){let e=n._item;return e?ke(e.id.client,e.id.clock):null}function qt(n){return typeof n=="string"?n:""}var A=class{constructor(e,t){this.doc=e;this.schema=bt(e),this.limits=lt(t),this.splitDedup=new he(this.schema.nodes),this.stopObserving=At(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;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(){return Ht(this.schema.nodes)}encodeSnapshot(){return R.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return R.encodeStateAsUpdate(this.doc,e)}partEntries(){return Vt(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 qt(this.schema.meta.get("mainDocumentPart"))}record(e){if(g(e))return null;let t=this.schema.nodes.get(e);if(!b(t))return null;if(Z(t)){let r=t.get(_),o=r instanceof R.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,t)}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&&I(r)?r.attributes:[];return {logicalId:e,yjsItemKey:Rr(t),wordFacingIds:Pe(o)}}isTombstoned(e){return O(this.schema.nodes.get(e))}replacedByOf(e){return Te(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(J(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:jt(this.schema.nodes,e)}kindOf(e){return g(e)?null:Kt(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=j(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,St({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Be(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)_e(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=j(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(z,Ae(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Et(t));}spliceText(e,t,r,o){let i=this.textOf(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,o);}setAttribute(e,t,r){if(r===null){Bt(this.schema,e,t.namespaceUri,t.localName);return}Be(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){_t(this.schema,e,t);return}_e(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(X,t);}recordSplitFrom(e,t){this.splitDedup.record(e,t);}splitOriginOf(e){return K(this.schema.nodes.get(e))}replacementLoserRuns(){return this.splitDedup.loserRuns({isPresent:e=>kt(this,e)})}declinedSplitTangleEvents(){return this.splitDedup.declinedTangleEvents()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?k(r):null;if(!o)return;let i=new Map;for(let s of t)i.set(s,(i.get(s)??0)+1);for(let s=o.length-1;s>=0;s-=1){let a=o.get(s),l=i.get(a)??0;l!==0&&(i.set(a,l-1),o.delete(s,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,Lt(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 R.Map;t.set(e.id,Rt(e)),this.schema.relationships.set(De(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(De(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,wt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return Ot(this.schema.relationships)}contentTypeOverrides(){return Wt(this.schema.overrides)}contentTypeDefaults(){return $t(this.schema.defaults)}binaries(){return Xt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let t=i=>{let s=new Set,a=false;for(let l of i){let d=l.path;if(d.length===0){for(let u of l.changes.keys.keys())s.add(String(u));a=true;continue}s.add(String(d[0])),l.target instanceof R.Array&&(a=true),l.target instanceof R.Map&&(l.changes.keys.has(U)||l.changes.keys.has(X))&&(a=true);}(s.size>0||a)&&e({logicalIds:s,membershipChanged:a,packageChanged:false});},r=i=>{let s=new Set;for(let a of i.changes.keys.keys()){let l=G(String(a))??q(String(a));!l||g(l.logicalId)||s.add(l.logicalId);}s.size>0&&e({logicalIds:s,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(t),this.schema.attributes.observe(r),this.schema.bindings.observe(r),this.schema.parts.observeDeep(o),this.schema.relationships.observeDeep(o),this.schema.overrides.observe(o),this.schema.defaults.observe(o),this.schema.binaries.observeDeep(o),()=>{this.schema.nodes.unobserveDeep(t),this.schema.attributes.unobserve(r),this.schema.bindings.unobserve(r),this.schema.parts.unobserveDeep(o),this.schema.relationships.unobserveDeep(o),this.schema.overrides.unobserve(o),this.schema.defaults.unobserve(o),this.schema.binaries.unobserveDeep(o);}}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.schema.nodes.forEach((e,t)=>{if(g(t))return;let r=k(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)=>{O(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=G(t);!r||g(r.logicalId)||g(r.localName)||Ue(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=q(t);!r||g(r.logicalId)||g(r.prefix)||Ye(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(b(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.path.length===0&&r.target instanceof R.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));for(let s of this.syncChildListings(String(o)))t.add(s);}continue}if(r.target instanceof R.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 R.Map&&r.path.length===1&&(r.changes.keys.has(U)||r.changes.keys.has(X))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,Ut(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,Yt(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?k(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(Ft(o,r))return [];let i=new Set(r),s=new Set(o),a=[];for(let l of o)i.has(l)||(this.removeListing(l,e),a.push(l));for(let l of r)s.has(l)||(this.addListing(l,e),a.push(l));return this.childrenSnapshot.set(e,r),a}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;Mt({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){Tt({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=Te(r);if(o!==null){if(O(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 k(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=k(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?k(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);}elementRecord(e,t){let r=pe(qt(t.get(z))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:H(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:k(t)?.toArray()??[]}}textOf(e){let t=this.require(e).get(_);if(!(t instanceof R.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ce);if(!(t instanceof R.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 ge=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 Zt(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 Qt(n){let e=n.binaryPart;return typeof e=="function"?e:null}function en(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 tn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function Cr(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function kr(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function nn(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(w(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(w(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(w(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:Cr(e),bindings:kr(e)});for(let i of e.children){let s=nn(n,i,e.id,r+1,o);if(s)return s}}return t&&n.childArray(t).push([e.id]),null}async function Pr(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let s=n.contentTypes.overrides.get(r)??"application/octet-stream",a=L(r);if(a)return {ok:false,code:a};if(o.byteLength>N.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await Zt(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:s,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function Q(n,e,t=new ge){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await Pr(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let a of r.payloads)t.put(a.digest,a.bytes);let i={nodes:0};for(let[a,l]of e.parts){let d=L(a);if(d){o=d;return}if(w(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let u=nn(n,l.root,null,0,i);if(u){o=u;return}n.putXmlPart({name:a,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let s=0;for(let a of e.relationships.values())for(let l of a){if(s+=1,s>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=L(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[a,l]of e.contentTypes.defaults){if(g(a)){o="prototype-key";return}n.putContentTypeDefault(a,l);}for(let[a,l]of e.contentTypes.overrides){let d=L(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);Ct(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},gt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var fe=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 a=this.node(o),l=a?.children.indexOf(e)??-1;a&&l>=0&&a.children.splice(l,1);}let i=this.node(t);if(!i)return;let s=Math.min(r,i.children.length);i.children.splice(s,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function rn(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 M(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 Or(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}:w(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function Ar(n,e,t){switch(e.kind){case "putNode":return Or(n,e.descriptor,t);case "spliceText":{let r=M(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=M(t,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:w(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=M(t,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&w(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=M(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 s=M(t,i);if(s)return s}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=M(t,e.logicalId);if(r)return r;let o=M(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=L(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=M(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=L(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=L(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=L(e.partName);return r?{ok:false,code:r}:w(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=L(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=dt(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 Nr(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;n.spliceText(e.logicalId,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 Mr(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function Tr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Mr(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(s=>o.has(s)))return i.parentLogicalId}}function Dr(n,e){let t=new fe(n),r=[],o=new Set,i=new Set,s=new Map;for(let a of e){let l=Ar(n,a,t);if(l)return l;if(a.kind==="spliceChildren"){let d=a.deleteCount>0?t.node(a.parentLogicalId):null;if(d&&!d.isText){let u=a.start+a.deleteCount;for(let p=a.start;p<u;p+=1){let c=d.children[p];c!==void 0&&(r.push(c),a.childLogicalIds.length>0&&s.set(c,a.childLogicalIds));}}for(let u of a.childLogicalIds)o.add(u);}else a.kind==="moveNode"?o.add(a.logicalId):a.kind==="putNode"&&a.descriptor.kind==="textValue"&&i.add(a.descriptor.logicalId);rn(t,a);}return {removed:r,reinserted:o,mintedText:i,replacementsByRemoved:s}}function Br(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function ze(n,e){if(n.nodeCount()+Br(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=Dr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=zr(n,t.removed);for(let o of e.effects)Nr(n,o,t.mintedText);_r(n,e.effects,t,r),Ur(n,t);},ft),{ok:true})}function _r(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 s=Tr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function Ur(n,e){for(let[t,r]of e.replacementsByRemoved){if(n.kindOf(t)!=="run")continue;let o=Yr(n,t,e.reinserted);for(let i of r)n.kindOf(i)==="run"&&n.recordSplitFrom(o,i);}}function Yr(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 zr(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 be="http://schemas.openxmlformats.org/package/2006/relationships",jr="application/vnd.openxmlformats-package.relationships+xml",on=/^(.*)\/_rels\/([^/]*)\.rels$/;function an(n){return on.test(n)}function sn(n){let e=on.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function ee(n,e){return n.attributes.find(t=>t.localName===e)?.value}function ye(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Kr(n,e){let t=[ye("Id",e.id),ye("Type",e.type),ye("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(ye("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:be,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function ln(n,e){if(n.kind==="textValue"||n.namespaceUri!==be||n.localName!=="Relationship"||ee(n,"Id")!==e.id||ee(n,"Type")!==e.type||ee(n,"Target")!==e.rawTarget)return false;let t=ee(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function dn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>ln(t,e[r]))}function cn(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 un(n,e,t){let r=[];for(let o of e){if(g(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&ee(a,"Id")===o.id);if(i&&ln(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;g(s)||r.push(Kr(s,o));}return r}function Fr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:be,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:be})]),attributes:Object.freeze([]),children:Object.freeze([])})}function pn(n){return Object.freeze({id:n,name:n,contentType:jr,root:Fr(n)})}function hn(n){let e=new Map;for(let t of n){if(g(t.id)||t.ownerPart!=="/"&&L(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var yn=/^\/customXml\/item(\d+)\.xml$/i,Xr=/^\/customXml\/itemProps(\d+)\.xml$/i;function ne(n){return yn.test(n)}function Ke(n){return Xr.test(n)}function Jr(n){let e=yn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function mn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Hr(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 gn(n,e){let t=n.record(e);return !t||!I(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Gr(n,e){let t=n.record(e);if(!t||!I(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!I(o)||o.localName!=="schemaRefs")&&o.namespaceUri===DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let s=n.record(i);if(!s||!I(s)||s.localName!=="schemaRef")continue;let a=Hr(s,"uri",DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function qr(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&I(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Zr(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:qr(n,e)}function Qr(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function bn(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[c,m]of e){let f=n.record(m.root.id);!f||!I(f)||(ne(c)&&t.set(f.logicalId,f),Ke(c)&&r.set(f.logicalId,f));}for(let c of n.allLogicalIds()){if(n.isTombstoned(c)||t.has(c)||r.has(c))continue;let m=n.record(c);!m||!I(m)||(Zr(n,m)?t.set(c,m):Qr(n,m)&&r.set(c,m));}if(t.size===0)return [];let o=new Map;for(let c of t.values()){let m=o.get(c.namespaceUri)??[];m.push(c),o.set(c.namespaceUri,m);}let i=new Map;for(let c of r.values()){let m=Gr(n,c.logicalId);if(!m)continue;let f=i.get(m)??[];f.push(c),i.set(m,f);}let s=[];for(let[c,m]of o){let f=i.get(c);if(!f||f.length===0)continue;m.sort((v,E)=>v.logicalId.localeCompare(E.logicalId)),f.sort((v,E)=>v.logicalId.localeCompare(E.logicalId));let y=m[0],B=f[0],P=[],x=new Set;for(let v of m)for(let E of v.childIds){if(x.has(E))continue;let se=n.record(E);!se||!I(se)||se.localName!=="node"||se.namespaceUri!==c||(x.add(E),P.push(E));}for(let v of n.allLogicalIds()){if(x.has(v)||n.isTombstoned(v))continue;let E=n.record(v);!E||!I(E)||E.localName!=="node"||E.namespaceUri!==c||(x.add(v),P.push(v));}P.sort((v,E)=>gn(n,v).localeCompare(gn(n,E))),s.push({data:y,props:B,nodeIds:P});}s.sort((c,m)=>c.data.logicalId.localeCompare(m.data.logicalId));let a=new Set,l=[],d=new Set,u=new Set;for(let[c,m]of e){let f=Jr(c);if(f===null)continue;let y=s.find(x=>x.data.logicalId===m.root.id&&!d.has(x.data.logicalId));if(!y)continue;let B=mn(f).props,P=e.get(B);P&&P.root.id!==y.props.logicalId||(a.add(f),d.add(y.data.logicalId),u.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:c,propsName:B,nodeIds:y.nodeIds}));}let p=1;for(let c of s){if(d.has(c.data.logicalId))continue;for(;a.has(p);)p+=1;a.add(p);let m=mn(p);l.push({dataRootId:c.data.logicalId,propsRootId:c.props.logicalId,namespaceUri:c.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:c.nodeIds}),p+=1;}return l.sort((c,m)=>c.itemName.localeCompare(m.itemName)),l}function eo(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:ne(n.ownerPart)}function to(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function no(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 In(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(a=>a.ownerPart===t&&a.type===CUSTOM_XML_REL).sort((a,l)=>a.id.localeCompare(l.id)),i=0;for(let a of r)i=Math.max(i,to(a.id));let s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=o[a],u=d?.id??`rId${String(i+=1)}`;s.push({ownerPart:t,id:u,type:CUSTOM_XML_REL,rawTarget:no(t,l.itemName),targetMode:"Internal",order:d?.order??a}),s.push({ownerPart:l.itemName,id:"rId1",type:CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return s}function xn(n,e){return e.length===0?[...n]:[...n.filter(t=>!eo(t)),...e]}function vn(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function Fe(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(ne).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),s=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!s||s.root.id!==o.propsRootId)return true}return false}function Sn(n,e){if(Fe(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(a=>a.id));if(t.nodeIds.some(a=>!o.has(a)))return true;let i=[];for(let a of r.root.children)a.kind!=="textValue"&&i.push(a.attributes.find(l=>l.localName==="id")?.value??a.id);let s=[...i].sort((a,l)=>a.localeCompare(l));if(i.some((a,l)=>a!==s[l]))return true}return false}var ro="http://schemas.microsoft.com/office/word/2012/wordml";function Ie(n,e){return n.attributes.find(t=>t.localName===e)?.value}function xe(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 En(n){return e=>e.localName===n&&e.namespaceUri===WML_NAMESPACE_URI}function oo(n){return n.localName==="abstractNum"?`0${xe(Ie(n,"abstractNumId"))}`:`1${xe(Ie(n,"numId"))}`}function io(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Ln(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===ro,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:En("footnote"),sortKey:e=>xe(Ie(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:En("endnote"),sortKey:e=>xe(Ie(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:io,sortKey:oo}:null}function ao(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ve(n){return n.kind==="textValue"?n.id:ao(n,"id")??n.id}function V(n,e){if(n.length===e.length&&n.every((s,a)=>s===e[a]))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 Cn(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:V(t.children,e)});return Object.freeze({...n,root:r})}function so(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 On(n){}function Nn(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function mo(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 go(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 ve(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&&mo(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&go(r,n)?r.attributes:Object.freeze(n.attributes.map(so)),children:e})}function Mn(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
2
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
3
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function We(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)We(o,e)||(r=false);return r}function Tn(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 Se=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:xn(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:hn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:bo(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 s=e.get(o.digest);if(!s)return null;On(s.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:s}),t.set(o.storageKey,s);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function bo(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)}}function vo(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 Y=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Se(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;replacementLosers=new Set;lastLosers=new Set;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}loserChanges(e){let t=[],r=o=>{let i=this.registry.parentOf(o);i!==null&&t.push(i);};for(let o of e)this.lastLosers.has(o)||r(o);for(let o of this.lastLosers)e.has(o)||r(o);return this.lastLosers=e,t}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 u of this.adoptionChanges())e.add(u);this.replacementLosers=this.registry.replacementLoserRuns();for(let u of this.loserChanges(this.replacementLosers))e.add(u);let o=Tn(this.registry,e),i=new Set(this.registry.partEntries().map(u=>u.rootLogicalId)),s=[...e].some(u=>i.has(u)||this.registry.parentOf(u)===null&&!this.registry.isTombstoned(u)),a=this.pkg!==null&&!r&&!s&&(o.size>0||t),l=this.materializePass(o,t,a);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:vo(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 u=new Set,p=this.materialize(d.rootLogicalId,o,u,r);if(!p||p.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let c=this.partCache.get(d.name);if(c&&c.root===p&&c.contentType===d.contentType){i.set(d.name,c);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:p});i.set(d.name,m),this.partCache.set(d.name,m);}let s=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),a=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,s,a),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(s,o,r,a),this.looseCandidates=a,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,u])=>this.pkg?.parts.get(d)===u)?{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&&I(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let a of e)this.registry.isTombstoned(a)||t.has(a)||(this.pushOrphan(a),o.add(a));return}let i=new Set(this.registry.partEntries().map(a=>a.rootLogicalId)),s=new Set;for(let a of e)s.has(a)||(s.add(a),this.reportOrphansUnder(a,t,i)&&o.add(a));}reportOrphansUnder(e,t,r){let o=false,i=new Set,s=[{id:e,underTombstone:false}];for(;s.length>0;){let{id:a,underTombstone:l}=s.pop();if(!(i.has(a)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(a),this.registry.isTombstoned(a)){let d=this.registry.record(a);if(d&&I(d))for(let u of d.childIds)s.push({id:u,underTombstone:true});continue}r.has(a)||(l?t.has(a):this.stillListed(a))||(this.pushOrphan(a),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(ue(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 c=this.cache.get(e);if(c&&r.size+this.heightOf(c)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?We(c,t)||(this.placementContested=true):t.add(c.id),c}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(ue(i)){let c=this.cache.get(e);if(c?.kind==="textValue"&&c.value===i.value)return c;let m=Nn(e,i.value);return this.remember(e,m),m}r.add(e);let s=new Set,a=[...i.childIds];for(let c of this.registry.adoptedChildren(e))a.includes(c)||a.push(c);let l=[];for(let c of a){if(c===e){this.push("self-child",c);continue}if(s.has(c)){this.push("duplicate-child",c);continue}if(s.add(c),this.registry.isTombstoned(c)){this.push("deleted-referenced",c);continue}if(this.replacementLosers.has(c)){t.add(c);continue}if(g(c)||!this.registry.hasNode(c)){this.push("child-id-not-in-registry",c);continue}if(!this.claimsWholeSubtrees){let f=this.registry.listingParents(c);f.length>1&&(this.placementContested=true,this.contestEncountered.add(c),f.some(y=>this.registry.isTombstoned(y)&&this.registry.replacedByOf(y)!==null)?this.contestMatchesResolution=false:!t.has(c)&&this.registry.parentOf(c)!==e&&(this.contestMatchesResolution=false));}let m=this.materialize(c,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((c,m)=>c===l[m])&&Mn(d,i))return d;let u=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(u,l);let p=ve(i,V(u,l),d);return this.remember(e,p),p}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 s=relsPartNameFor(o);if(s!=="/_rels/.rels"&&L(s))continue;r.add(s);let a=this.projectOneRelsPart(s,e.get(s),i);a&&(e.set(s,a),this.partCache.set(s,a));}for(let[o,i]of e){if(r.has(o)||!an(o))continue;let s=sn(o);if(s===null)continue;let a=this.projectOneRelsPart(o,i,t.get(s)??[]);!a||a===i||(e.set(o,a),this.partCache.set(o,a));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),s=!!o&&(!t||cn(o.root,t.root))&&o?o:t??pn(e);if(dn(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=Cn(s,un(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=Ln(a.root);if(!l)continue;let d=x=>x.logicalId!==a.root.id&&l.isMember(x),u=[],p=new Set;for(let x of a.root.children){if(x.kind==="textValue")continue;let v=this.registry.record(x.id);!v||!I(v)||!d(v)||(u.push(x),p.add(x.id));}if(this.adoptLooseMembers(u,p,d,t,r,o,i)===0)continue;u.sort((x,v)=>l.sortKey(x).localeCompare(l.sortKey(v)));let m=[];for(let x of a.root.children)p.has(x.id)||m.push(x);let f=V(a.root.children,[...m,...u]);if(f===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!I(y))continue;let B=ve(y,f,a.root);this.remember(a.root.id,B);let P=Object.freeze({...a,root:B});e.set(s,P),this.partCache.set(s,P);}}adoptLooseMembers(e,t,r,o,i,s,a){let l=0;for(let d of s){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let u=this.registry.record(d);if(!u||!I(u)||!r(u))continue;let p=this.materialize(d,o,new Set,i);!p||p.kind==="textValue"||(e.push(p),t.add(d),a.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),s=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!s||s.kind==="textValue")return null;let a=[...s.children],l=new Set(a.map(m=>m.id)),d=0;for(let m of t){if(l.has(m))continue;let f=this.materializeOnce(m,r,o);!f||f.kind==="textValue"||(a.push(f),l.add(m),d+=1);}if(a.sort((m,f)=>Ve(m).localeCompare(Ve(f))),d===0&&a.every((m,f)=>m===s.children[f]))return s;let u=this.registry.record(e);if(!u||!I(u))return s;let p=V(s.children,a),c=ve(u,p,s);return this.remember(e,c),c}applyCustomXmlStores(e,t,r){let o=bn(this.registry,e);if(o.length===0||!Sn(e,o))return;let i=Fe(e,o),s=new Set;for(let a of o){s.add(a.itemName),s.add(a.propsName);let l=this.adoptNodesIntoRoot(a.dataRootId,a.nodeIds,t,r),d=this.materializeOnce(a.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let u=Object.freeze({id:a.itemName,name:a.itemName,contentType:"application/xml",root:l}),p=Object.freeze({id:a.propsName,name:a.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,u),e.set(a.propsName,p),this.partCache.set(a.itemName,u),this.partCache.set(a.propsName,p);}if(i){for(let a of [...e.keys()])!ne(a)&&!Ke(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=In(this.registry,o),this.customXmlOverrides=vn(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[a,l]of this.customXmlOverrides)o.set(a,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},s=this.registry.mainDocumentPart()||[...e.keys()].find(a=>a.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:s}),issues:[...this.issues]}}};var Bn=1,_n=1,Xe=20*1024*1024,Co="docx-collaboration-v1",ko="docx-body-paragraphs-v1",Po=Object.freeze({kind:"docx-collaboration-bootstrap"}),h=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function He(n){return {root:n.getMap(Co),paragraphs:n.getMap(ko)}}function Oo(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>Xe)throw new h("baseline-too-large");let t=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:Xe,maxRatio:200}});if(!t.ok)throw new h("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new h("no-main-document-part");let o=normalizeParagraphIdentity(r),i=new TreePackageStore(t.package,o),s=createCollaborationDocumentPort(i,{documentId:e});return {bytes:writeOoxmlPackage(i.currentPackage()),paragraphs:s.paragraphs()}}async function Un(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return [...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Dn(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new h("invalid-shared-metadata",e);return t}function $e(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new h("invalid-shared-metadata",e);return t}function oe(n){return n.get("initialized")===true}async function Ba(n,e,t,r){let{root:o,paragraphs:i}=He(n);if(oe(o))throw new h("already-initialized");let s=await Un(r.bytes);n.transact(()=>{if(oe(o))throw new h("already-initialized");o.set("protocolVersion",Bn),o.set("schemaVersion",_n),o.set("documentId",e),o.set("baselineSha256",s),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",t),o.set("baseline",new Uint8Array(r.bytes));for(let a of r.paragraphs){if(i.has(a.paragraphId))throw new h("duplicate-paragraph-id");let l=new R.Text;i.set(a.paragraphId,l),l.insert(0,a.text);}o.set("initialized",true);},Po);}async function _a(n,e){let{root:t,paragraphs:r}=He(n);if(!oe(t))throw new h("not-initialized");if($e(t,"protocolVersion")!==Bn)throw new h("protocol-version-mismatch");if($e(t,"schemaVersion")!==_n)throw new h("schema-version-mismatch");if(Dn(t,"documentId")!==e)throw new h("document-id-mismatch");let o=$e(t,"baselineByteLength");if(o===0||o>Xe)throw new h("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new h("invalid-baseline");if(await Un(i)!==Dn(t,"baselineSha256"))throw new h("baseline-digest-mismatch");let s=Oo(new Uint8Array(i),e),a=new Set(s.paragraphs.map(l=>l.paragraphId));if(r.size!==a.size)throw new h("paragraph-set-mismatch");for(let[l,d]of r)if(!a.has(l)||!(d instanceof R.Text))throw new h("paragraph-set-mismatch");return s}function Ua(n,e,t){let{root:r}=He(n);return oe(r)?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((o,i)=>{let s=u=>{clearTimeout(d),r.unobserve(a),t?.removeEventListener("abort",l),u?i(u):o();},a=()=>{oe(r)&&s();},l=()=>s(new h("initialization-aborted")),d=setTimeout(()=>s(new h("initialization-timeout")),e);r.observe(a),t?.addEventListener("abort",l,{once:true});})}var Le=64*1024*1024,W="docx-package-blobs-v1";function No(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 Mo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function Ee(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var T=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=No(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+=Mo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Le)throw new h("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 Ee("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return Ee("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof R.Map?a.size:0;}),i>t.maxRelationships)return Ee("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>Le?Ee("blob-store-full",`${s}`):null}var zn=20*1024*1024,qe=3e4,_o=4e3,Uo=1500,Yo="docx-collaboration-seeds-v1",Ge="docxEditorSeedCandidate",zo=/^[0-9a-f]{16}$/,jo=256;function Ze(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>zn)throw new h("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:zn,maxRatio:200}});if(!e.ok)throw new h("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new h("no-main-document-part");return new TreePackageStore(e.package,normalizeParagraphIdentity(t)).currentPackage()}function Ko(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function ae(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Ko(n,e),s=()=>{let l=e.poisonedDigest();return l?new h("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((l,d)=>{let u=f=>{clearTimeout(m),o.unobserve(p),n.doc.off("afterTransaction",p),r?.removeEventListener("abort",c),f?d(f):l();},p=()=>{let f=s();if(f){u(f);return}i()&&u();},c=()=>u(new h("initialization-aborted")),m=setTimeout(()=>u(new h("initialization-timeout")),t);o.observe(p),n.doc.on("afterTransaction",p),r?.addEventListener("abort",c,{once:true});})}function Qe(n){return n.getArray(Yo)}function Re(n){return Qe(n).length}function Kn(n,e){let t=Qe(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Fo(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function Vo(n,e){let t=[...n.getStates().entries()].slice(0,jo);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Ge];if(!(typeof i!="string"||!zo.test(i))&&i<e)return true}return false}async function jn(n,e,t,r){try{return await ae(n,e,t,r),!0}catch(o){if(o instanceof h&&o.code==="initialization-timeout")return false;throw o}}function Wo(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((i,s)=>{let a=p=>{clearTimeout(u),r.unobserve(l),t?.removeEventListener("abort",d),p?s(p):i();},l=()=>{o()&&a();},d=()=>a(new h("initialization-aborted")),u=setTimeout(()=>a(new h("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function Fn(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??_o,s=n.electionWindowMs??Uo,a=n.timeoutMs??qe,l=async()=>(await Wo(r,a,n.signal),"joined");if(await jn(r,o,i,n.signal))return l();let d=Fo();t.setLocalStateField(Ge,d);try{let u=await jn(r,o,s,n.signal);if(!u&&Vo(t,d)&&(await ae(r,o,a,n.signal),u=!0),u)return await l();if(r.schema.meta.get("initialized")===!0)return await ae(r,o,a,n.signal),await l();let p=await Q(r,Ze(n.document),o);if(!p.ok)throw new h(p.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Qe(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Ge,null);}}var we=class{constructor(e,t){this.knows=e;this.allocator=new $(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,s)=>i===e.childLogicalIds[s])?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 $o(n){let e=0;return n.schema.nodes.forEach(t=>{b(t)&&t.get(U)===true&&(e+=1);}),e}function Xo(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof R.Map?t.size:0;}),e}function et(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:$o(n),maxNodes:n.limits.maxNodes,relationships:Xo(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Le})}function Za(n){let e=new A(n);try{let t=new T(n.getMap(W));return et(e,t)}finally{e.destroy();}}var Ce="docxEditor",D=256,tt=256;function $n(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>D||t.length===0||t.length>D)throw new h("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new h("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function Xn(n){let e=n.trim();if(e.length===0||e.length>D)throw new h("invalid-document-id");return e}function Jn(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>D)throw new h("invalid-session-id");return e}function Wn(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 Ho(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Wn(e.anchor),r=Wn(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 nt(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>D||typeof e.name!="string"||e.name.length===0||e.name.length>D)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=Ho(e.selection);return i?{...o,selection:i}:o}function qo(n){let e=new A(n),t=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new h("not-initialized");if(Re(n)>1)throw new h("concurrent-seed");let r=new T(n.getMap(W)),o=ie(e,r);if(o)throw new h(o.code,o.detail);t=new Y(e,r);let i=t.current(),s=r.poisonedDigest();if(s)throw new h("blob-digest-mismatch",s);if(!i.ok)throw new h(i.code);return writeOoxmlPackage(i.package)}finally{t?.destroy(),e.destroy();}}var ni=3,ri=5e3,oi=2e3,ii=Symbol("createDocumentCollaboration.attachWatchdogMs"),rt=class{constructor(e,t,r,o,i,s,a,l,d,u,p){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=p;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new R.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:ri,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(c=>{let m=d.verifyNow(c);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=Kn(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 ${u}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.`);},u),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;seenDeclinedTangles=0;destroyed=false;refusedInARow=0;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 et(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}canWriteSharedState(){if(this.destroyed)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.undoManager.undo(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),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,tt);for(let[r,o]of t){let i=nt(o[Ce]);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 s=e.paragraphByStableId(i.paragraphId);return s?Object.freeze({paragraphId:s.paragraphId,nodeId:s.nodeId,offset:Math.min(i.offset,s.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,tt),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=nt(s[Ce]);if(!a?.selection)continue;let l=t(a.selection.anchor),d=t(a.selection.head);!l||!d||o.push(Object.freeze({actorId:a.actorId,name:a.name,...a.color?{color:a.color}:{},...a.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>D)throw new h("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new h("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){let t=this.identityMap.translate(e),r=this.collectJournalBlobs(e);if(r!==null&&r.ok===false){this.refuseLocalJournal(r.failure);return}let o=this.ydoc.transact(()=>{if(r!==null){let s=this.putJournalBlobs(r.payloads);if(s!==null)return s}let i=ze(this.registry,t);return i.ok?null:{code:i.code,...i.detail?{detail:i.detail}:{}}},this.localOrigin);if(o===null){this.refusedInARow=0;return}this.refuseLocalJournal(o);}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=en(e.effects,Qt(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{tn(this.blobs,e);}catch(t){return t instanceof h?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){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<ni&&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=>{if(!(this.destroyed||!this.port)){if(e.origin===this.localOrigin){let t=this.registry.declinedSplitTangleEvents();t!==this.seenDeclinedTangles&&(this.seenDeclinedTangles=t,this.publishSharedToPort());return}this.publishSharedToPort();}};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{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=yt(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let s=e.applyRemotePackage(r.package,{origin:ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!s.ok){this.setStatus("error","remote-apply-failed",s.reason);return}s.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof h?t.code:"remote-apply-failed",t instanceof h?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(Ce,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 xs(n){let e=n[ii]??oi,t=Xn(n.documentId),r=Jn(n.sessionId),o=$n(n.identity),i=new A(n.ydoc);try{return await ai(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(s){throw i.destroy(),s}}async function ai(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:s}=e,a=new we(p=>s.hasNode(p)),l=new T(n.ydoc.getMap(W));if(n.bootstrap.kind==="create"){if(s.schema.meta.get("initialized")===true)throw new h("already-initialized");let p=await Q(s,Ze(n.bootstrap.document),l);if(!p.ok)throw new h(p.code);n.ydoc.transact(()=>{s.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await Fn({ydoc:n.ydoc,awareness:n.awareness,registry:s,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(s.schema.meta.get("documentId")!==r)throw new h("document-id-mismatch");s.rebuildDerivedIndexes();}}else {if(await ae(s,l,n.bootstrap.timeoutMs??qe,n.bootstrap.signal),s.schema.meta.get("documentId")!==r)throw new h("document-id-mismatch");s.rebuildDerivedIndexes();}if(Re(n.ydoc)>1)throw new h("concurrent-seed");let d=ie(s,l);if(d)throw new h(d.code,d.detail);let u=new Y(s,l);try{let p=u.current(),c=l.poisonedDigest();if(c)throw new h("blob-digest-mismatch",c);if(!p.ok)throw new h(p.code);let m=writeOoxmlPackage(p.package),f=new rt(n.ydoc,n.awareness,r,o,i,s,u,a,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:f,destroy:()=>f.destroy()})}catch(p){throw u.destroy(),p}}export{Bn as a,_n as b,Xe as c,h as d,He as e,Oo as f,Ba as g,_a as h,Ua as i,Za as j,qo as k,ii as l,xs as m};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var R=require('yjs'),store=require('@docx-editor.dev/core/store'),collaboration=require('@docx-editor.dev/core/collaboration'),layout=require('@docx-editor.dev/core/layout'),replication=require('@docx-editor.dev/core/collaboration/replication');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 R__namespace=/*#__PURE__*/_interopNamespace(R);var Gn=new Set(["paraId","textId","id","numId","bookmarkId"]);function ot(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function it(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),ot(e)}function le(n){return /^[0-9a-f]{32}$/.test(n)}function at(n,e){if(!le(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 ke(n,e){return `yjs:${n}:${e}`}function de(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return le(e)?e:null}function Pe(n){let e=[];for(let t of n)Gn.has(t.localName)&&e.push(t.value);return e}var $=class{replicaId;next=0;constructor(e){if(this.replicaId=e??it(),!le(this.replicaId))throw new Error("invalid replica identity")}take(){let e=at(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};var N=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}),Zn=/^sha256:[0-9a-f]{64}$/;function lt(n){return n?Object.freeze({...N,...n}):N}function g(n){return store.isDangerousKey(n)?"prototype-key":null}function w(n,e){return typeof n!="string"||n.length>e?"invalid-string":store.isDangerousKey(n)?"prototype-key":null}function L(n){let e=g(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=store.normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function dt(n){for(let e of Object.keys(n)){let t=g(e);if(t)return t}return !Zn.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>N.maxBlobBytes?"blob-too-large":w(n.mediaType,N.maxMediaTypeLength)||n.mediaType.length===0||w(n.storageKey,N.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var ct=1,ut=2,pt=1,ht=1,Qn="docx-package-meta-v1",er="docx-package-nodes-v1",tr="docx-package-parts-v1",nr="docx-package-rels-v1",rr="docx-package-overrides-v1",or="docx-package-defaults-v1",ir="docx-package-binaries-v1",ar="docx-package-namespaces-v1",sr="docx-package-attributes-v1",lr="docx-package-bindings-v1",z="s",_="t",ce="children",U="deleted",X="replacedBy",Oe="splitFrom",S="",mt="-",gt=Object.freeze({kind:"docx-package-bootstrap"}),ft=Object.freeze({kind:"docx-package-journal"});function ue(n){return n.kind==="textValue"}function I(n){return !ue(n)}var dr=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),cr=200;function yt(n){let e=new Map;for(let t of n)dr.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,cr)}function bt(n){return {meta:n.getMap(Qn),nodes:n.getMap(er),parts:n.getMap(tr),relationships:n.getMap(nr),overrides:n.getMap(rr),defaults:n.getMap(or),binaries:n.getMap(ir),namespaces:n.getMap(ar),attributes:n.getMap(sr),bindings:n.getMap(lr)}}var It=[["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"]],ur=new Map(It),pr=new Map(It.map(([n,e])=>[e,n]));function hr(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 J(n){return n.length===0?mt:ur.get(n)??`n${hr(n)}`}function j(n,e,t){let r=J(e);return e.length===0||g(r)||w(e,t)||n.get(r)!==e&&n.set(r,e),r}function H(n,e){if(e===mt||g(e))return "";let t=n.get(e);return typeof t=="string"?t:pr.get(e)??""}function Ae(n,e,t,r){return `${n}${S}${e}${S}${t}${S}${r}`}function pe(n){let e=n.split(S);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Ne(n,e,t){return `${n}${S}${e}${S}${t}`}function G(n){let e=n.split(S);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 Me(n,e){return `${n}${S}${e}`}function q(n){let e=n.split(S);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function xt(n,e){return `${n}${S}${e}`}function vt(n){let e=n.indexOf(S);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function St(n){let e=new R__namespace.Map;e.set(z,Ae(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new R__namespace.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ce,t),e}function Et(n){let e=new R__namespace.Map;return e.set(_,new R__namespace.Text(n)),e}function Lt(n,e,t){let r=new R__namespace.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function Rt(n){let e=new R__namespace.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 wt(n){let e=new R__namespace.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Ct(n){n.set("protocolVersion",ct),n.set("sharedSchemaVersion",ut),n.set("repairVersion",pt),n.set("canonicalModelVersion",ht),n.set("initialized",true);}function b(n){return n instanceof R__namespace.Map}function k(n){if(!b(n))return null;let e=n.get(ce);return e instanceof R__namespace.Array?e:null}function Z(n){return b(n)&&n.get(_)instanceof R__namespace.Text}function O(n){return b(n)&&n.get(U)===true}function Te(n){if(!b(n))return null;let e=n.get(X);return typeof e=="string"&&e.length>0?e:null}function K(n){if(!b(n))return null;let e=n.get(Oe);return typeof e=="string"&&e.length>0?e:null}var mr=256,he=class{constructor(e){this.nodes=e;}nodes;runsBySplitOrigin=new Map;replicasByOrigin=new Map;contestedOrigins=new Set;liveRootedOrigins=new Set;declinedTangleCount=0;reset(){this.runsBySplitOrigin=new Map,this.replicasByOrigin=new Map,this.contestedOrigins=new Set,this.liveRootedOrigins=new Set;}record(e,t){let r=this.nodes.get(t);b(r)&&e!==t&&(r.set(Oe,e),this.index(e,t),this.reSplitOfContestedOrigin(e)&&(this.declinedTangleCount+=1));}reSplitOfContestedOrigin(e){if(K(this.nodes.get(e))===null)return false;let t=e;for(let r=0;r<mr;r+=1){if(this.contestedOrigins.has(t)||this.liveRootedOrigins.has(t))return true;let o=K(this.nodes.get(t));if(o===null||o===t)return false;t=o;}return false}indexExisting(e){let t=K(this.nodes.get(e));t!==null&&t!==e&&this.index(t,e);}index(e,t){let r=this.runsBySplitOrigin.get(e)??new Set;r.add(t),this.runsBySplitOrigin.set(e,r);let o=this.replicasByOrigin.get(e)??new Set;o.add(de(t)??""),this.replicasByOrigin.set(e,o),o.size>1&&this.contestedOrigins.add(e);let i=this.nodes.get(e);b(i)&&!O(i)&&this.liveRootedOrigins.add(e);}declinedTangleEvents(){return this.declinedTangleCount}isReSplit(e){let t=this.runsBySplitOrigin.get(e);if(!t)return false;for(let r of t)if((this.runsBySplitOrigin.get(r)?.size??0)>0)return true;return false}loserRuns(e){let t=new Set,r=new Set([...this.contestedOrigins,...this.liveRootedOrigins]);for(let o of r){let i=this.runsBySplitOrigin.get(o);if(!i||this.isReSplit(o))continue;let s=new Set;for(let d of i)e.isPresent(d)&&s.add(de(d)??"");let a=e.isPresent(o);if(!a&&s.size<=1)continue;let l=a?null:[...s].sort()[0];for(let d of i)!a&&(de(d)??"")===l||e.isPresent(d)&&t.add(d);}return t}};function kt(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&&I(r)&&r.childIds.includes(e)}function me(n){return typeof n=="string"?n:""}function Pt(n,e){return n<e?-1:n>e?1:0}function De(n,e){return `${n}${S}${e}`}function fr(n){let e=n.indexOf(S);return e<0?n:n.slice(0,e)}function Ot(n){let e=[];return n.forEach((t,r)=>{!b(t)||g(r)||t.forEach(o=>{if(!b(o))return;let i=me(o.get("id")),s=me(o.get("type"));if(i.length===0||s.length===0)return;let a=me(o.get("ownerPart"))||fr(r);if(g(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,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||Pt(t.ownerPart,r.ownerPart)||Pt(t.id,r.id)),e}function At(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 yr(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 Nt(n,e){let t=n.childrenSnapshot.get(e);return t||(k(n.nodes.get(e))?.toArray()??[])}function br(n,e){let t=n.nodes.get(e);return !b(t)||O(t)}function Ir(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),br(n,s)))return null;a=e.get(s);let u=n.parentIndex.get(s);if(a!==void 0){if(u!==void 0)return "fallback";break}if(u===void 0)return t.has(s)?"deferred":null;o.push(s),s=u;}let l=[a],d=s;for(let u=o.length-1;u>=0;u-=1){let p=o[u],c=Nt(n,d).indexOf(p);if(c<0)return null;l.push(c),d=p;}return l}function Mt(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,s)=>{r.has(i)||r.set(i,s);});let o=[...t];for(;o.length>0;){let i=[];for(let s of o){let a=null,l=false;for(let d of n.listings.get(s)??[]){if(d===s)continue;let u=Ir(n,r,t,d);if(u==="fallback")return false;if(u==="deferred"){l=true;continue}if(u===null)continue;let p=Nt(n,d).indexOf(s);if(p<0)continue;let c=[...u,p];(!a||yr(c,a.rank)<0)&&(a={rank:c,parent:d});}if(l){i.push(s);continue}a&&n.parentIndex.set(s,a.parent),t.delete(s);}if(i.length===o.length)return false;o=i;}return true}function Tt(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let s of e)r.delete(s);for(let s of i){let a=new Set,l=[{id:s,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){a.delete(d.id);continue}let u=d.id;if(d.parent!==null&&(e===null||e.has(u))&&(r.has(u)||r.set(u,d.parent)),a.has(u))continue;let p=t.get(u);if(!b(p)||O(p))continue;let c=o.get(u)??k(p)?.toArray()??[];a.add(u),l.push({id:u,parent:null,exit:true});let m=new Set,f=[];for(let y of c)m.has(y)||y===u||(m.add(y),f.push(y));for(let y=f.length-1;y>=0;y-=1)l.push({id:f[y],parent:u,exit:false});}}}function Dt(n,e){return `${n}${S}${e}`}function Be(n,e,t,r,o){if(g(t)||g(r.localName))return;let i=j(n.namespaces,r.namespaceUri,e),s=Ne(t,i,r.localName);g(s)||n.attributes.set(s,xt(r.prefix??"",o));}function Bt(n,e,t,r){n.attributes.delete(Ne(e,J(t),r));}function _e(n,e,t,r,o){if(g(t)||g(r))return;let i=j(n.namespaces,o,e),s=Me(t,r);g(s)||n.bindings.set(s,i);}function _t(n,e,t){n.bindings.delete(Me(e,t));}function Ue(n,e,t,r,o,i){let{prefix:s,value:a}=vt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(Dt(r,o),{namespaceUri:H(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function xr(n,e,t,r){let o=n.get(e);o&&(o.delete(Dt(t,r)),o.size===0&&n.delete(e));}function Ye(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:H(n.namespaces,o)});}function vr(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function Ut(n,e,t){for(let[r,o]of t.changes.keys){let i=G(String(r));if(!i||g(i.logicalId)||g(i.localName))continue;if(o.action==="delete"){xr(e,i.logicalId,i.namespaceId,i.localName);continue}let s=n.attributes.get(String(r));typeof s=="string"&&Ue(n,e,i.logicalId,i.namespaceId,i.localName,s);}}function Yt(n,e,t){for(let[r,o]of t.changes.keys){let i=q(String(r));if(!i||g(i.logicalId)||g(i.prefix))continue;if(o.action==="delete"){vr(e,i.logicalId,i.prefix);continue}let s=n.bindings.get(String(r));typeof s=="string"&&Ye(n,e,i.logicalId,i.prefix,s);}}function jt(n,e){let t=n.get(e);if(!b(t))return null;if(Z(t)){let r=t.get(_);return {isText:true,textLength:r instanceof R__namespace.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:k(t)?.toArray()??[]}}function Kt(n,e){let t=n.get(e);if(!b(t))return null;if(Z(t))return "textValue";let r=t.get(z);return pe(typeof r=="string"?r:"").kind}function Ft(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 F(n){return typeof n=="string"?n:""}function Vt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=F(t.get("rootId"));o.length!==0&&e.push({name:r,id:F(t.get("id")),rootLogicalId:o,contentType:F(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Wt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(store.partNameKey(r),t);}),e}function $t(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(r,t);}),e}function Xt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=F(t.get("digest")),i=t.get("size"),s=F(t.get("mediaType")),a=F(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:s,storageKey:a});}),e}function Er(n){return n?._item??null}function Lr(n){return n.content instanceof R__namespace.ContentType}function Ht(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=Er(t);return r===null||r.parent!==n?true:!Lr(e)}}function Rr(n){let e=n._item;return e?ke(e.id.client,e.id.clock):null}function qt(n){return typeof n=="string"?n:""}var A=class{constructor(e,t){this.doc=e;this.schema=bt(e),this.limits=lt(t),this.splitDedup=new he(this.schema.nodes),this.stopObserving=At(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;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(){return Ht(this.schema.nodes)}encodeSnapshot(){return R__namespace.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return R__namespace.encodeStateAsUpdate(this.doc,e)}partEntries(){return Vt(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 qt(this.schema.meta.get("mainDocumentPart"))}record(e){if(g(e))return null;let t=this.schema.nodes.get(e);if(!b(t))return null;if(Z(t)){let r=t.get(_),o=r instanceof R__namespace.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return this.elementRecord(e,t)}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&&I(r)?r.attributes:[];return {logicalId:e,yjsItemKey:Rr(t),wordFacingIds:Pe(o)}}isTombstoned(e){return O(this.schema.nodes.get(e))}replacedByOf(e){return Te(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(J(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:jt(this.schema.nodes,e)}kindOf(e){return g(e)?null:Kt(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=j(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,St({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Be(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)_e(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=j(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(z,Ae(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Et(t));}spliceText(e,t,r,o){let i=this.textOf(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,o);}setAttribute(e,t,r){if(r===null){Bt(this.schema,e,t.namespaceUri,t.localName);return}Be(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){_t(this.schema,e,t);return}_e(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(X,t);}recordSplitFrom(e,t){this.splitDedup.record(e,t);}splitOriginOf(e){return K(this.schema.nodes.get(e))}replacementLoserRuns(){return this.splitDedup.loserRuns({isPresent:e=>kt(this,e)})}declinedSplitTangleEvents(){return this.splitDedup.declinedTangleEvents()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?k(r):null;if(!o)return;let i=new Map;for(let s of t)i.set(s,(i.get(s)??0)+1);for(let s=o.length-1;s>=0;s-=1){let a=o.get(s),l=i.get(a)??0;l!==0&&(i.set(a,l-1),o.delete(s,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,Lt(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 R__namespace.Map;t.set(e.id,Rt(e)),this.schema.relationships.set(De(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(De(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(store.partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(store.partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,wt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return Ot(this.schema.relationships)}contentTypeOverrides(){return Wt(this.schema.overrides)}contentTypeDefaults(){return $t(this.schema.defaults)}binaries(){return Xt(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){let t=i=>{let s=new Set,a=false;for(let l of i){let d=l.path;if(d.length===0){for(let u of l.changes.keys.keys())s.add(String(u));a=true;continue}s.add(String(d[0])),l.target instanceof R__namespace.Array&&(a=true),l.target instanceof R__namespace.Map&&(l.changes.keys.has(U)||l.changes.keys.has(X))&&(a=true);}(s.size>0||a)&&e({logicalIds:s,membershipChanged:a,packageChanged:false});},r=i=>{let s=new Set;for(let a of i.changes.keys.keys()){let l=G(String(a))??q(String(a));!l||g(l.logicalId)||s.add(l.logicalId);}s.size>0&&e({logicalIds:s,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return this.schema.nodes.observeDeep(t),this.schema.attributes.observe(r),this.schema.bindings.observe(r),this.schema.parts.observeDeep(o),this.schema.relationships.observeDeep(o),this.schema.overrides.observe(o),this.schema.defaults.observe(o),this.schema.binaries.observeDeep(o),()=>{this.schema.nodes.unobserveDeep(t),this.schema.attributes.unobserve(r),this.schema.bindings.unobserve(r),this.schema.parts.unobserveDeep(o),this.schema.relationships.unobserveDeep(o),this.schema.overrides.unobserve(o),this.schema.defaults.unobserve(o),this.schema.binaries.unobserveDeep(o);}}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.schema.nodes.forEach((e,t)=>{if(g(t))return;let r=k(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)=>{O(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=G(t);!r||g(r.logicalId)||g(r.localName)||Ue(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=q(t);!r||g(r.logicalId)||g(r.prefix)||Ye(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(b(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.path.length===0&&r.target instanceof R__namespace.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));for(let s of this.syncChildListings(String(o)))t.add(s);}continue}if(r.target instanceof R__namespace.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 R__namespace.Map&&r.path.length===1&&(r.changes.keys.has(U)||r.changes.keys.has(X))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,Ut(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,Yt(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?k(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(Ft(o,r))return [];let i=new Set(r),s=new Set(o),a=[];for(let l of o)i.has(l)||(this.removeListing(l,e),a.push(l));for(let l of r)s.has(l)||(this.addListing(l,e),a.push(l));return this.childrenSnapshot.set(e,r),a}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;Mt({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){Tt({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=Te(r);if(o!==null){if(O(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 k(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=k(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?k(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);}elementRecord(e,t){let r=pe(qt(t.get(z))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:H(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:k(t)?.toArray()??[]}}textOf(e){let t=this.require(e).get(_);if(!(t instanceof R__namespace.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ce);if(!(t instanceof R__namespace.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 ge=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 Zt(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 Qt(n){let e=n.binaryPart;return typeof e=="function"?e:null}function en(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 tn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function Cr(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function kr(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function nn(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(w(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(w(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(w(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:Cr(e),bindings:kr(e)});for(let i of e.children){let s=nn(n,i,e.id,r+1,o);if(s)return s}}return t&&n.childArray(t).push([e.id]),null}async function Pr(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let s=n.contentTypes.overrides.get(r)??"application/octet-stream",a=L(r);if(a)return {ok:false,code:a};if(o.byteLength>N.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await Zt(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:s,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function Q(n,e,t=new ge){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await Pr(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let a of r.payloads)t.put(a.digest,a.bytes);let i={nodes:0};for(let[a,l]of e.parts){let d=L(a);if(d){o=d;return}if(w(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let u=nn(n,l.root,null,0,i);if(u){o=u;return}n.putXmlPart({name:a,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let s=0;for(let a of e.relationships.values())for(let l of a){if(s+=1,s>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=L(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[a,l]of e.contentTypes.defaults){if(g(a)){o="prototype-key";return}n.putContentTypeDefault(a,l);}for(let[a,l]of e.contentTypes.overrides){let d=L(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);Ct(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},gt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var fe=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 a=this.node(o),l=a?.children.indexOf(e)??-1;a&&l>=0&&a.children.splice(l,1);}let i=this.node(t);if(!i)return;let s=Math.min(r,i.children.length);i.children.splice(s,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function rn(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 M(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 Or(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}:w(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function Ar(n,e,t){switch(e.kind){case "putNode":return Or(n,e.descriptor,t);case "spliceText":{let r=M(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=M(t,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:w(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=M(t,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&w(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=M(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 s=M(t,i);if(s)return s}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=M(t,e.logicalId);if(r)return r;let o=M(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=L(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=M(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=L(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=L(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=L(e.partName);return r?{ok:false,code:r}:w(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=L(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=dt(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 Nr(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;n.spliceText(e.logicalId,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 Mr(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function Tr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Mr(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(s=>o.has(s)))return i.parentLogicalId}}function Dr(n,e){let t=new fe(n),r=[],o=new Set,i=new Set,s=new Map;for(let a of e){let l=Ar(n,a,t);if(l)return l;if(a.kind==="spliceChildren"){let d=a.deleteCount>0?t.node(a.parentLogicalId):null;if(d&&!d.isText){let u=a.start+a.deleteCount;for(let p=a.start;p<u;p+=1){let c=d.children[p];c!==void 0&&(r.push(c),a.childLogicalIds.length>0&&s.set(c,a.childLogicalIds));}}for(let u of a.childLogicalIds)o.add(u);}else a.kind==="moveNode"?o.add(a.logicalId):a.kind==="putNode"&&a.descriptor.kind==="textValue"&&i.add(a.descriptor.logicalId);rn(t,a);}return {removed:r,reinserted:o,mintedText:i,replacementsByRemoved:s}}function Br(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function ze(n,e){if(n.nodeCount()+Br(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=Dr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=zr(n,t.removed);for(let o of e.effects)Nr(n,o,t.mintedText);_r(n,e.effects,t,r),Ur(n,t);},ft),{ok:true})}function _r(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 s=Tr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function Ur(n,e){for(let[t,r]of e.replacementsByRemoved){if(n.kindOf(t)!=="run")continue;let o=Yr(n,t,e.reinserted);for(let i of r)n.kindOf(i)==="run"&&n.recordSplitFrom(o,i);}}function Yr(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 zr(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 be="http://schemas.openxmlformats.org/package/2006/relationships",jr="application/vnd.openxmlformats-package.relationships+xml",on=/^(.*)\/_rels\/([^/]*)\.rels$/;function an(n){return on.test(n)}function sn(n){let e=on.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function ee(n,e){return n.attributes.find(t=>t.localName===e)?.value}function ye(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Kr(n,e){let t=[ye("Id",e.id),ye("Type",e.type),ye("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(ye("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:be,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function ln(n,e){if(n.kind==="textValue"||n.namespaceUri!==be||n.localName!=="Relationship"||ee(n,"Id")!==e.id||ee(n,"Type")!==e.type||ee(n,"Target")!==e.rawTarget)return false;let t=ee(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function dn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>ln(t,e[r]))}function cn(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 un(n,e,t){let r=[];for(let o of e){if(g(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&ee(a,"Id")===o.id);if(i&&ln(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;g(s)||r.push(Kr(s,o));}return r}function Fr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:be,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:be})]),attributes:Object.freeze([]),children:Object.freeze([])})}function pn(n){return Object.freeze({id:n,name:n,contentType:jr,root:Fr(n)})}function hn(n){let e=new Map;for(let t of n){if(g(t.id)||t.ownerPart!=="/"&&L(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var yn=/^\/customXml\/item(\d+)\.xml$/i,Xr=/^\/customXml\/itemProps(\d+)\.xml$/i;function ne(n){return yn.test(n)}function Ke(n){return Xr.test(n)}function Jr(n){let e=yn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function mn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Hr(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 gn(n,e){let t=n.record(e);return !t||!I(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Gr(n,e){let t=n.record(e);if(!t||!I(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!I(o)||o.localName!=="schemaRefs")&&o.namespaceUri===store.DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let s=n.record(i);if(!s||!I(s)||s.localName!=="schemaRef")continue;let a=Hr(s,"uri",store.DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function qr(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&I(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Zr(n,e){return e.localName==="node"||e.namespaceUri===store.WML_NAMESPACE_URI||e.namespaceUri===store.DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:qr(n,e)}function Qr(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==store.DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function bn(n,e){if(!n.hasNamespace(store.DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[c,m]of e){let f=n.record(m.root.id);!f||!I(f)||(ne(c)&&t.set(f.logicalId,f),Ke(c)&&r.set(f.logicalId,f));}for(let c of n.allLogicalIds()){if(n.isTombstoned(c)||t.has(c)||r.has(c))continue;let m=n.record(c);!m||!I(m)||(Zr(n,m)?t.set(c,m):Qr(n,m)&&r.set(c,m));}if(t.size===0)return [];let o=new Map;for(let c of t.values()){let m=o.get(c.namespaceUri)??[];m.push(c),o.set(c.namespaceUri,m);}let i=new Map;for(let c of r.values()){let m=Gr(n,c.logicalId);if(!m)continue;let f=i.get(m)??[];f.push(c),i.set(m,f);}let s=[];for(let[c,m]of o){let f=i.get(c);if(!f||f.length===0)continue;m.sort((v,E)=>v.logicalId.localeCompare(E.logicalId)),f.sort((v,E)=>v.logicalId.localeCompare(E.logicalId));let y=m[0],B=f[0],P=[],x=new Set;for(let v of m)for(let E of v.childIds){if(x.has(E))continue;let se=n.record(E);!se||!I(se)||se.localName!=="node"||se.namespaceUri!==c||(x.add(E),P.push(E));}for(let v of n.allLogicalIds()){if(x.has(v)||n.isTombstoned(v))continue;let E=n.record(v);!E||!I(E)||E.localName!=="node"||E.namespaceUri!==c||(x.add(v),P.push(v));}P.sort((v,E)=>gn(n,v).localeCompare(gn(n,E))),s.push({data:y,props:B,nodeIds:P});}s.sort((c,m)=>c.data.logicalId.localeCompare(m.data.logicalId));let a=new Set,l=[],d=new Set,u=new Set;for(let[c,m]of e){let f=Jr(c);if(f===null)continue;let y=s.find(x=>x.data.logicalId===m.root.id&&!d.has(x.data.logicalId));if(!y)continue;let B=mn(f).props,P=e.get(B);P&&P.root.id!==y.props.logicalId||(a.add(f),d.add(y.data.logicalId),u.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:c,propsName:B,nodeIds:y.nodeIds}));}let p=1;for(let c of s){if(d.has(c.data.logicalId))continue;for(;a.has(p);)p+=1;a.add(p);let m=mn(p);l.push({dataRootId:c.data.logicalId,propsRootId:c.props.logicalId,namespaceUri:c.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:c.nodeIds}),p+=1;}return l.sort((c,m)=>c.itemName.localeCompare(m.itemName)),l}function eo(n){return n.type===store.CUSTOM_XML_REL||n.type===store.CUSTOM_XML_PROPS_REL?true:ne(n.ownerPart)}function to(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function no(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 In(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(a=>a.ownerPart===t&&a.type===store.CUSTOM_XML_REL).sort((a,l)=>a.id.localeCompare(l.id)),i=0;for(let a of r)i=Math.max(i,to(a.id));let s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=o[a],u=d?.id??`rId${String(i+=1)}`;s.push({ownerPart:t,id:u,type:store.CUSTOM_XML_REL,rawTarget:no(t,l.itemName),targetMode:"Internal",order:d?.order??a}),s.push({ownerPart:l.itemName,id:"rId1",type:store.CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return s}function xn(n,e){return e.length===0?[...n]:[...n.filter(t=>!eo(t)),...e]}function vn(n){let e=new Map;for(let t of n)e.set(store.partNameKey(t.propsName),store.CUSTOM_XML_PROPS_TYPE);return e}function Fe(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(ne).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),s=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!s||s.root.id!==o.propsRootId)return true}return false}function Sn(n,e){if(Fe(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(a=>a.id));if(t.nodeIds.some(a=>!o.has(a)))return true;let i=[];for(let a of r.root.children)a.kind!=="textValue"&&i.push(a.attributes.find(l=>l.localName==="id")?.value??a.id);let s=[...i].sort((a,l)=>a.localeCompare(l));if(i.some((a,l)=>a!==s[l]))return true}return false}var ro="http://schemas.microsoft.com/office/word/2012/wordml";function Ie(n,e){return n.attributes.find(t=>t.localName===e)?.value}function xe(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 En(n){return e=>e.localName===n&&e.namespaceUri===store.WML_NAMESPACE_URI}function oo(n){return n.localName==="abstractNum"?`0${xe(Ie(n,"abstractNumId"))}`:`1${xe(Ie(n,"numId"))}`}function io(n){return n.namespaceUri!==store.WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Ln(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===ro,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:En("footnote"),sortKey:e=>xe(Ie(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:En("endnote"),sortKey:e=>xe(Ie(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:io,sortKey:oo}:null}function ao(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ve(n){return n.kind==="textValue"?n.id:ao(n,"id")??n.id}function V(n,e){if(n.length===e.length&&n.every((s,a)=>s===e[a]))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 Cn(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:V(t.children,e)});return Object.freeze({...n,root:r})}function so(n){if(n.namespaceUri===store.XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:store.XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===store.WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:store.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 On(n){}function Nn(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function mo(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 go(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 ve(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&&mo(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&go(r,n)?r.attributes:Object.freeze(n.attributes.map(so)),children:e})}function Mn(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
2
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
3
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function We(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)We(o,e)||(r=false);return r}function Tn(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 Se=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:xn(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:hn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:bo(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 s=e.get(o.digest);if(!s)return null;On(s.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:s}),t.set(o.storageKey,s);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function bo(n){let e=store.buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=store.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)}}function vo(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 Y=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Se(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;replacementLosers=new Set;lastLosers=new Set;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}loserChanges(e){let t=[],r=o=>{let i=this.registry.parentOf(o);i!==null&&t.push(i);};for(let o of e)this.lastLosers.has(o)||r(o);for(let o of this.lastLosers)e.has(o)||r(o);return this.lastLosers=e,t}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 u of this.adoptionChanges())e.add(u);this.replacementLosers=this.registry.replacementLoserRuns();for(let u of this.loserChanges(this.replacementLosers))e.add(u);let o=Tn(this.registry,e),i=new Set(this.registry.partEntries().map(u=>u.rootLogicalId)),s=[...e].some(u=>i.has(u)||this.registry.parentOf(u)===null&&!this.registry.isTombstoned(u)),a=this.pkg!==null&&!r&&!s&&(o.size>0||t),l=this.materializePass(o,t,a);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:vo(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 u=new Set,p=this.materialize(d.rootLogicalId,o,u,r);if(!p||p.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let c=this.partCache.get(d.name);if(c&&c.root===p&&c.contentType===d.contentType){i.set(d.name,c);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:p});i.set(d.name,m),this.partCache.set(d.name,m);}let s=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),a=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,s,a),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(s,o,r,a),this.looseCandidates=a,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,u])=>this.pkg?.parts.get(d)===u)?{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&&I(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let a of e)this.registry.isTombstoned(a)||t.has(a)||(this.pushOrphan(a),o.add(a));return}let i=new Set(this.registry.partEntries().map(a=>a.rootLogicalId)),s=new Set;for(let a of e)s.has(a)||(s.add(a),this.reportOrphansUnder(a,t,i)&&o.add(a));}reportOrphansUnder(e,t,r){let o=false,i=new Set,s=[{id:e,underTombstone:false}];for(;s.length>0;){let{id:a,underTombstone:l}=s.pop();if(!(i.has(a)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(a),this.registry.isTombstoned(a)){let d=this.registry.record(a);if(d&&I(d))for(let u of d.childIds)s.push({id:u,underTombstone:true});continue}r.has(a)||(l?t.has(a):this.stillListed(a))||(this.pushOrphan(a),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(ue(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 c=this.cache.get(e);if(c&&r.size+this.heightOf(c)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?We(c,t)||(this.placementContested=true):t.add(c.id),c}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(ue(i)){let c=this.cache.get(e);if(c?.kind==="textValue"&&c.value===i.value)return c;let m=Nn(e,i.value);return this.remember(e,m),m}r.add(e);let s=new Set,a=[...i.childIds];for(let c of this.registry.adoptedChildren(e))a.includes(c)||a.push(c);let l=[];for(let c of a){if(c===e){this.push("self-child",c);continue}if(s.has(c)){this.push("duplicate-child",c);continue}if(s.add(c),this.registry.isTombstoned(c)){this.push("deleted-referenced",c);continue}if(this.replacementLosers.has(c)){t.add(c);continue}if(g(c)||!this.registry.hasNode(c)){this.push("child-id-not-in-registry",c);continue}if(!this.claimsWholeSubtrees){let f=this.registry.listingParents(c);f.length>1&&(this.placementContested=true,this.contestEncountered.add(c),f.some(y=>this.registry.isTombstoned(y)&&this.registry.replacedByOf(y)!==null)?this.contestMatchesResolution=false:!t.has(c)&&this.registry.parentOf(c)!==e&&(this.contestMatchesResolution=false));}let m=this.materialize(c,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((c,m)=>c===l[m])&&Mn(d,i))return d;let u=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(u,l);let p=ve(i,V(u,l),d);return this.remember(e,p),p}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 s=store.relsPartNameFor(o);if(s!=="/_rels/.rels"&&L(s))continue;r.add(s);let a=this.projectOneRelsPart(s,e.get(s),i);a&&(e.set(s,a),this.partCache.set(s,a));}for(let[o,i]of e){if(r.has(o)||!an(o))continue;let s=sn(o);if(s===null)continue;let a=this.projectOneRelsPart(o,i,t.get(s)??[]);!a||a===i||(e.set(o,a),this.partCache.set(o,a));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),s=!!o&&(!t||cn(o.root,t.root))&&o?o:t??pn(e);if(dn(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=Cn(s,un(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=Ln(a.root);if(!l)continue;let d=x=>x.logicalId!==a.root.id&&l.isMember(x),u=[],p=new Set;for(let x of a.root.children){if(x.kind==="textValue")continue;let v=this.registry.record(x.id);!v||!I(v)||!d(v)||(u.push(x),p.add(x.id));}if(this.adoptLooseMembers(u,p,d,t,r,o,i)===0)continue;u.sort((x,v)=>l.sortKey(x).localeCompare(l.sortKey(v)));let m=[];for(let x of a.root.children)p.has(x.id)||m.push(x);let f=V(a.root.children,[...m,...u]);if(f===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!I(y))continue;let B=ve(y,f,a.root);this.remember(a.root.id,B);let P=Object.freeze({...a,root:B});e.set(s,P),this.partCache.set(s,P);}}adoptLooseMembers(e,t,r,o,i,s,a){let l=0;for(let d of s){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let u=this.registry.record(d);if(!u||!I(u)||!r(u))continue;let p=this.materialize(d,o,new Set,i);!p||p.kind==="textValue"||(e.push(p),t.add(d),a.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),s=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!s||s.kind==="textValue")return null;let a=[...s.children],l=new Set(a.map(m=>m.id)),d=0;for(let m of t){if(l.has(m))continue;let f=this.materializeOnce(m,r,o);!f||f.kind==="textValue"||(a.push(f),l.add(m),d+=1);}if(a.sort((m,f)=>Ve(m).localeCompare(Ve(f))),d===0&&a.every((m,f)=>m===s.children[f]))return s;let u=this.registry.record(e);if(!u||!I(u))return s;let p=V(s.children,a),c=ve(u,p,s);return this.remember(e,c),c}applyCustomXmlStores(e,t,r){let o=bn(this.registry,e);if(o.length===0||!Sn(e,o))return;let i=Fe(e,o),s=new Set;for(let a of o){s.add(a.itemName),s.add(a.propsName);let l=this.adoptNodesIntoRoot(a.dataRootId,a.nodeIds,t,r),d=this.materializeOnce(a.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let u=Object.freeze({id:a.itemName,name:a.itemName,contentType:"application/xml",root:l}),p=Object.freeze({id:a.propsName,name:a.propsName,contentType:store.CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,u),e.set(a.propsName,p),this.partCache.set(a.itemName,u),this.partCache.set(a.propsName,p);}if(i){for(let a of [...e.keys()])!ne(a)&&!Ke(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=In(this.registry,o),this.customXmlOverrides=vn(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[a,l]of this.customXmlOverrides)o.set(a,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},s=this.registry.mainDocumentPart()||[...e.keys()].find(a=>a.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:s}),issues:[...this.issues]}}};var Bn=1,_n=1,Xe=20*1024*1024,Co="docx-collaboration-v1",ko="docx-body-paragraphs-v1",Po=Object.freeze({kind:"docx-collaboration-bootstrap"}),h=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function He(n){return {root:n.getMap(Co),paragraphs:n.getMap(ko)}}function Oo(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>Xe)throw new h("baseline-too-large");let t=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:Xe,maxRatio:200}});if(!t.ok)throw new h("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new h("no-main-document-part");let o=store.normalizeParagraphIdentity(r),i=new store.TreePackageStore(t.package,o),s=replication.createCollaborationDocumentPort(i,{documentId:e});return {bytes:store.writeOoxmlPackage(i.currentPackage()),paragraphs:s.paragraphs()}}async function Un(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return [...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Dn(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new h("invalid-shared-metadata",e);return t}function $e(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new h("invalid-shared-metadata",e);return t}function oe(n){return n.get("initialized")===true}async function Ba(n,e,t,r){let{root:o,paragraphs:i}=He(n);if(oe(o))throw new h("already-initialized");let s=await Un(r.bytes);n.transact(()=>{if(oe(o))throw new h("already-initialized");o.set("protocolVersion",Bn),o.set("schemaVersion",_n),o.set("documentId",e),o.set("baselineSha256",s),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",t),o.set("baseline",new Uint8Array(r.bytes));for(let a of r.paragraphs){if(i.has(a.paragraphId))throw new h("duplicate-paragraph-id");let l=new R__namespace.Text;i.set(a.paragraphId,l),l.insert(0,a.text);}o.set("initialized",true);},Po);}async function _a(n,e){let{root:t,paragraphs:r}=He(n);if(!oe(t))throw new h("not-initialized");if($e(t,"protocolVersion")!==Bn)throw new h("protocol-version-mismatch");if($e(t,"schemaVersion")!==_n)throw new h("schema-version-mismatch");if(Dn(t,"documentId")!==e)throw new h("document-id-mismatch");let o=$e(t,"baselineByteLength");if(o===0||o>Xe)throw new h("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new h("invalid-baseline");if(await Un(i)!==Dn(t,"baselineSha256"))throw new h("baseline-digest-mismatch");let s=Oo(new Uint8Array(i),e),a=new Set(s.paragraphs.map(l=>l.paragraphId));if(r.size!==a.size)throw new h("paragraph-set-mismatch");for(let[l,d]of r)if(!a.has(l)||!(d instanceof R__namespace.Text))throw new h("paragraph-set-mismatch");return s}function Ua(n,e,t){let{root:r}=He(n);return oe(r)?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((o,i)=>{let s=u=>{clearTimeout(d),r.unobserve(a),t?.removeEventListener("abort",l),u?i(u):o();},a=()=>{oe(r)&&s();},l=()=>s(new h("initialization-aborted")),d=setTimeout(()=>s(new h("initialization-timeout")),e);r.observe(a),t?.addEventListener("abort",l,{once:true});})}var Le=64*1024*1024,W="docx-package-blobs-v1";function No(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 Mo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function Ee(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var T=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=No(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+=Mo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Le)throw new h("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:layout.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 Ee("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return Ee("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof R__namespace.Map?a.size:0;}),i>t.maxRelationships)return Ee("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>Le?Ee("blob-store-full",`${s}`):null}var zn=20*1024*1024,qe=3e4,_o=4e3,Uo=1500,Yo="docx-collaboration-seeds-v1",Ge="docxEditorSeedCandidate",zo=/^[0-9a-f]{16}$/,jo=256;function Ze(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new h("invalid-baseline");if(n.byteLength>zn)throw new h("baseline-too-large");let e=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:zn,maxRatio:200}});if(!e.ok)throw new h("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new h("no-main-document-part");return new store.TreePackageStore(e.package,store.normalizeParagraphIdentity(t)).currentPackage()}function Ko(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function ae(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Ko(n,e),s=()=>{let l=e.poisonedDigest();return l?new h("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((l,d)=>{let u=f=>{clearTimeout(m),o.unobserve(p),n.doc.off("afterTransaction",p),r?.removeEventListener("abort",c),f?d(f):l();},p=()=>{let f=s();if(f){u(f);return}i()&&u();},c=()=>u(new h("initialization-aborted")),m=setTimeout(()=>u(new h("initialization-timeout")),t);o.observe(p),n.doc.on("afterTransaction",p),r?.addEventListener("abort",c,{once:true});})}function Qe(n){return n.getArray(Yo)}function Re(n){return Qe(n).length}function Kn(n,e){let t=Qe(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Fo(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function Vo(n,e){let t=[...n.getStates().entries()].slice(0,jo);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Ge];if(!(typeof i!="string"||!zo.test(i))&&i<e)return true}return false}async function jn(n,e,t,r){try{return await ae(n,e,t,r),!0}catch(o){if(o instanceof h&&o.code==="initialization-timeout")return false;throw o}}function Wo(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new h("initialization-aborted")):new Promise((i,s)=>{let a=p=>{clearTimeout(u),r.unobserve(l),t?.removeEventListener("abort",d),p?s(p):i();},l=()=>{o()&&a();},d=()=>a(new h("initialization-aborted")),u=setTimeout(()=>a(new h("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function Fn(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??_o,s=n.electionWindowMs??Uo,a=n.timeoutMs??qe,l=async()=>(await Wo(r,a,n.signal),"joined");if(await jn(r,o,i,n.signal))return l();let d=Fo();t.setLocalStateField(Ge,d);try{let u=await jn(r,o,s,n.signal);if(!u&&Vo(t,d)&&(await ae(r,o,a,n.signal),u=!0),u)return await l();if(r.schema.meta.get("initialized")===!0)return await ae(r,o,a,n.signal),await l();let p=await Q(r,Ze(n.document),o);if(!p.ok)throw new h(p.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Qe(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Ge,null);}}var we=class{constructor(e,t){this.knows=e;this.allocator=new $(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,s)=>i===e.childLogicalIds[s])?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 $o(n){let e=0;return n.schema.nodes.forEach(t=>{b(t)&&t.get(U)===true&&(e+=1);}),e}function Xo(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof R__namespace.Map?t.size:0;}),e}function et(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:$o(n),maxNodes:n.limits.maxNodes,relationships:Xo(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Le})}function Za(n){let e=new A(n);try{let t=new T(n.getMap(W));return et(e,t)}finally{e.destroy();}}var Ce="docxEditor",D=256,tt=256;function $n(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>D||t.length===0||t.length>D)throw new h("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new h("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function Xn(n){let e=n.trim();if(e.length===0||e.length>D)throw new h("invalid-document-id");return e}function Jn(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>D)throw new h("invalid-session-id");return e}function Wn(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 Ho(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Wn(e.anchor),r=Wn(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 nt(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>D||typeof e.name!="string"||e.name.length===0||e.name.length>D)return null;let t=collaboration.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=Ho(e.selection);return i?{...o,selection:i}:o}function qo(n){let e=new A(n),t=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new h("not-initialized");if(Re(n)>1)throw new h("concurrent-seed");let r=new T(n.getMap(W)),o=ie(e,r);if(o)throw new h(o.code,o.detail);t=new Y(e,r);let i=t.current(),s=r.poisonedDigest();if(s)throw new h("blob-digest-mismatch",s);if(!i.ok)throw new h(i.code);return store.writeOoxmlPackage(i.package)}finally{t?.destroy(),e.destroy();}}var ni=3,ri=5e3,oi=2e3,ii=Symbol("createDocumentCollaboration.attachWatchdogMs"),rt=class{constructor(e,t,r,o,i,s,a,l,d,u,p){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=p;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new R__namespace.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:ri,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(c=>{let m=d.verifyNow(c);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=Kn(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 ${u}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.`);},u),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=collaboration.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;seenDeclinedTangles=0;destroyed=false;refusedInARow=0;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 et(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}canWriteSharedState(){if(this.destroyed)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.undoManager.undo(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),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,tt);for(let[r,o]of t){let i=nt(o[Ce]);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 s=e.paragraphByStableId(i.paragraphId);return s?Object.freeze({paragraphId:s.paragraphId,nodeId:s.nodeId,offset:Math.min(i.offset,s.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,tt),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=nt(s[Ce]);if(!a?.selection)continue;let l=t(a.selection.anchor),d=t(a.selection.head);!l||!d||o.push(Object.freeze({actorId:a.actorId,name:a.name,...a.color?{color:a.color}:{},...a.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>D)throw new h("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new h("invalid-identity-color");r=collaboration.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){let t=this.identityMap.translate(e),r=this.collectJournalBlobs(e);if(r!==null&&r.ok===false){this.refuseLocalJournal(r.failure);return}let o=this.ydoc.transact(()=>{if(r!==null){let s=this.putJournalBlobs(r.payloads);if(s!==null)return s}let i=ze(this.registry,t);return i.ok?null:{code:i.code,...i.detail?{detail:i.detail}:{}}},this.localOrigin);if(o===null){this.refusedInARow=0;return}this.refuseLocalJournal(o);}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=en(e.effects,Qt(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{tn(this.blobs,e);}catch(t){return t instanceof h?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){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<ni&&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=>{if(!(this.destroyed||!this.port)){if(e.origin===this.localOrigin){let t=this.registry.declinedSplitTangleEvents();t!==this.seenDeclinedTangles&&(this.seenDeclinedTangles=t,this.publishSharedToPort());return}this.publishSharedToPort();}};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{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=yt(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let s=e.applyRemotePackage(r.package,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!s.ok){this.setStatus("error","remote-apply-failed",s.reason);return}s.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof h?t.code:"remote-apply-failed",t instanceof h?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(Ce,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 xs(n){let e=n[ii]??oi,t=Xn(n.documentId),r=Jn(n.sessionId),o=$n(n.identity),i=new A(n.ydoc);try{return await ai(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(s){throw i.destroy(),s}}async function ai(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:s}=e,a=new we(p=>s.hasNode(p)),l=new T(n.ydoc.getMap(W));if(n.bootstrap.kind==="create"){if(s.schema.meta.get("initialized")===true)throw new h("already-initialized");let p=await Q(s,Ze(n.bootstrap.document),l);if(!p.ok)throw new h(p.code);n.ydoc.transact(()=>{s.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await Fn({ydoc:n.ydoc,awareness:n.awareness,registry:s,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(s.schema.meta.get("documentId")!==r)throw new h("document-id-mismatch");s.rebuildDerivedIndexes();}}else {if(await ae(s,l,n.bootstrap.timeoutMs??qe,n.bootstrap.signal),s.schema.meta.get("documentId")!==r)throw new h("document-id-mismatch");s.rebuildDerivedIndexes();}if(Re(n.ydoc)>1)throw new h("concurrent-seed");let d=ie(s,l);if(d)throw new h(d.code,d.detail);let u=new Y(s,l);try{let p=u.current(),c=l.poisonedDigest();if(c)throw new h("blob-digest-mismatch",c);if(!p.ok)throw new h(p.code);let m=store.writeOoxmlPackage(p.package),f=new rt(n.ydoc,n.awareness,r,o,i,s,u,a,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:f,destroy:()=>f.destroy()})}catch(p){throw u.destroy(),p}}exports.a=Bn;exports.b=_n;exports.c=Xe;exports.d=h;exports.e=He;exports.f=Oo;exports.g=Ba;exports.h=_a;exports.i=Ua;exports.j=Za;exports.k=qo;exports.l=ii;exports.m=xs;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),
|
|
1
|
+
'use strict';var chunkLUUFBXJ5_cjs=require('../chunk-LUUFBXJ5.cjs'),chunkVRIYIY2Y_cjs=require('../chunk-VRIYIY2Y.cjs'),P=require('yjs'),awareness=require('y-protocols/awareness'),provider=require('@hocuspocus/provider');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 g=3e4,S=Symbol("createHocuspocusCollaboration.provider"),O=o=>new provider.HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function F(o,d){return new Promise((c,e)=>{if(o.isSynced){c();return}let n=()=>{clearTimeout(s),o.off("synced",a),o.off("authenticationFailed",t);},a=()=>{n(),c();},t=r=>{n(),e(new chunkVRIYIY2Y_cjs.d("initialization-aborted",`authentication failed: ${r.reason}`));},s=setTimeout(()=>{n(),e(new chunkVRIYIY2Y_cjs.d("initialization-timeout"));},d);o.on("synced",a),o.on("authenticationFailed",t);})}async function E(o){let d=chunkLUUFBXJ5_cjs.b(o.roomId),c=o[S]??O,e=new P__namespace.Doc,n=new awareness.Awareness(e),a=()=>c({url:o.url,name:d,document:e,awareness:n,...o.token!==void 0?{token:o.token}:{}}),t=null,s=null;try{o.bootstrap.kind!=="create"&&(t=a(),await F(t,o.syncedTimeoutMs??g)),s=await chunkVRIYIY2Y_cjs.m({ydoc:e,awareness:n,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=a());}catch(i){throw s?.destroy(),t?.destroy(),n.destroy(),e.destroy(),i}let r=t,u=s,l=u.session,f=i=>{l.setTransportStatus(i.status==="connected"?"ready":"disconnected",i.status==="connected"?void 0:"transport-disconnected",i.status==="connected"?void 0:"websocket disconnected");};r.on("status",f);let p=()=>{l.setTransportStatus("error","authentication-failed");};r.on("authenticationFailed",p);let b=false;return Object.freeze({document:u.document,session:l,ydoc:e,provider:r,destroy(){b||(b=true,r.off("status",f),r.off("authenticationFailed",p),u.destroy(),r.destroy(),n.destroy(),e.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=S;exports.createHocuspocusCollaboration=E;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {m,d}from'../chunk-
|
|
1
|
+
import {b}from'../chunk-6DEUT2RQ.js';export{a as createCollaborationRoomId,b as validateRoomId}from'../chunk-6DEUT2RQ.js';import {m,d}from'../chunk-MTNG3CRI.js';import*as P from'yjs';import {Awareness}from'y-protocols/awareness';import {HocuspocusProvider}from'@hocuspocus/provider';var g=3e4,S=Symbol("createHocuspocusCollaboration.provider"),O=o=>new HocuspocusProvider({url:o.url,name:o.name,document:o.document,awareness:o.awareness,...o.token!==void 0?{token:o.token}:{}});function F(o,d$1){return new Promise((c,e)=>{if(o.isSynced){c();return}let n=()=>{clearTimeout(s),o.off("synced",a),o.off("authenticationFailed",t);},a=()=>{n(),c();},t=r=>{n(),e(new d("initialization-aborted",`authentication failed: ${r.reason}`));},s=setTimeout(()=>{n(),e(new d("initialization-timeout"));},d$1);o.on("synced",a),o.on("authenticationFailed",t);})}async function E(o){let d=b(o.roomId),c=o[S]??O,e=new P.Doc,n=new Awareness(e),a=()=>c({url:o.url,name:d,document:e,awareness:n,...o.token!==void 0?{token:o.token}:{}}),t=null,s=null;try{o.bootstrap.kind!=="create"&&(t=a(),await F(t,o.syncedTimeoutMs??g)),s=await m({ydoc:e,awareness:n,documentId:d,identity:o.identity,bootstrap:o.bootstrap,offlineEditing:o.offlineEditing}),t||(t=a());}catch(i){throw s?.destroy(),t?.destroy(),n.destroy(),e.destroy(),i}let r=t,u=s,l=u.session,f=i=>{l.setTransportStatus(i.status==="connected"?"ready":"disconnected",i.status==="connected"?void 0:"transport-disconnected",i.status==="connected"?void 0:"websocket disconnected");};r.on("status",f);let p=()=>{l.setTransportStatus("error","authentication-failed");};r.on("authenticationFailed",p);let b$1=false;return Object.freeze({document:u.document,session:l,ydoc:e,provider:r,destroy(){b$1||(b$1=true,r.off("status",f),r.off("authenticationFailed",p),u.destroy(),r.destroy(),n.destroy(),e.destroy());}})}export{S as HOCUSPOCUS_PROVIDER_FOR_TESTS,E as createHocuspocusCollaboration};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunkC4RVARMI_cjs=require('../chunk-C4RVARMI.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 C="docxEditor",h=256,O=256,I=1e6,D=3e4;function B(a){let t=a.actorId.trim(),n=a.name.trim();if(t.length===0||t.length>h||n.length===0||n.length>h)throw new chunkC4RVARMI_cjs.d("invalid-identity");if(a.color!==void 0&&a.color.length>64)throw new chunkC4RVARMI_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:n,...a.color?{color:a.color}:{},role:a.role??"human"})}function F(a){let t=a.trim();if(t.length===0||t.length>h)throw new chunkC4RVARMI_cjs.d("invalid-document-id");return t}function N(a){let t=a?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunkC4RVARMI_cjs.d("invalid-session-id");return t}function H(a,t){let n=a.toString();if(n===t)return;let o=0;for(;o<n.length&&o<t.length&&n.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<n.length-o&&e<t.length-o&&n.charCodeAt(n.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=n.length-o-e;r>0&&a.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&a.insert(o,i);}function R(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;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 V(a){if(a===void 0||typeof a!="object"||a===null||Array.isArray(a))return;let t=a,n=R(t.anchor),o=R(t.head);if(n&&o)return {anchor:n,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 L(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;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 n=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=V(t.selection);return {actorId:t.actorId,name:t.name,...n?{color:n}:{},role:o,...e?{selection:e}:{}}}function X(a){let t="";for(let n of a)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function $(a){let t=a.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,o=>o.charCodeAt(0))}var w=class{constructor(t,n,o,e,r,i){this.ydoc=t;this.awareness=n;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunkC4RVARMI_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),n.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,n,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(n!==void 0){this.setStatus(t,n,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 n=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 chunkC4RVARMI_cjs.d?e.code:"local-mirror-failed",e instanceof chunkC4RVARMI_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),n(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,n){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(n.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>I)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:n}=chunkC4RVARMI_cjs.e(this.ydoc),o=(r,i)=>{let d=n.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:X(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=[],n=[...this.awareness.getStates().entries()].slice(0,O);for(let[o,e]of n){let r=L(e[C]);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,O),{paragraphs:n}=chunkC4RVARMI_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=L(r[C]);if(!i?.selection)continue;let d=y=>{let x=n.get(y.paragraphId);if(!x)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition($(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==x)return null;let f=this.port?.paragraphs().find(M=>M.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),v=d(i.selection.head);!p||!v||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(v)}));}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(n){this.setStatus("error",n instanceof chunkC4RVARMI_cjs.d?n.code:"shared-schema-invalid",n instanceof chunkC4RVARMI_cjs.d?n.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 n=this.participants();for(let o of [...this.participantListeners])o(n);};publishAwareness(t){let n={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(C,n);}validateParagraphSet(t){let{paragraphs:n}=chunkC4RVARMI_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==n.size||o.some(e=>!n.has(e.paragraphId)||!(n.get(e.paragraphId)instanceof l__namespace.Text)||n.get(e.paragraphId).length>I))throw new chunkC4RVARMI_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:n}=chunkC4RVARMI_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 chunkC4RVARMI_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunkC4RVARMI_cjs.a||t.get("schemaVersion")!==chunkC4RVARMI_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 chunkC4RVARMI_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 chunkC4RVARMI_cjs.d("immutable-baseline-changed");for(let[r,i]of n)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>I)throw new chunkC4RVARMI_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:n}=chunkC4RVARMI_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=n.get(o.paragraphId);if(!e)throw new chunkC4RVARMI_cjs.d("paragraph-set-mismatch");H(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:n}=chunkC4RVARMI_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=n.get(e.paragraphId);if(!r)throw new chunkC4RVARMI_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 chunkC4RVARMI_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 chunkC4RVARMI_cjs.d?o.code:"remote-apply-failed",o instanceof chunkC4RVARMI_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,n,o){if(!this.statusState.set(t,n,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function J(a,t,n){if(a.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(a.bootstrap.kind==="create"){let o=chunkC4RVARMI_cjs.f(a.bootstrap.document,t);return await chunkC4RVARMI_cjs.g(a.ydoc,t,n.actorId,o),chunkC4RVARMI_cjs.h(a.ydoc,t)}return await chunkC4RVARMI_cjs.i(a.ydoc,a.bootstrap.timeoutMs??D,a.bootstrap.signal),chunkC4RVARMI_cjs.h(a.ydoc,t)}async function Z(a){let t=F(a.documentId),n=N(a.sessionId),o=B(a.identity),e=await J(a,t,o),r=new w(a.ydoc,a.awareness,t,n,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}
|
|
2
|
-
Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return
|
|
1
|
+
'use strict';var chunkQLZH2Q2C_cjs=require('../chunk-QLZH2Q2C.cjs'),chunkVRIYIY2Y_cjs=require('../chunk-VRIYIY2Y.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 C="docxEditor",h=256,O=256,I=1e6,D=3e4;function B(a){let t=a.actorId.trim(),n=a.name.trim();if(t.length===0||t.length>h||n.length===0||n.length>h)throw new chunkVRIYIY2Y_cjs.d("invalid-identity");if(a.color!==void 0&&a.color.length>64)throw new chunkVRIYIY2Y_cjs.d("invalid-identity-color");return Object.freeze({actorId:t,name:n,...a.color?{color:a.color}:{},role:a.role??"human"})}function F(a){let t=a.trim();if(t.length===0||t.length>h)throw new chunkVRIYIY2Y_cjs.d("invalid-document-id");return t}function N(a){let t=a?.trim()||globalThis.crypto.randomUUID();if(t.length===0||t.length>h)throw new chunkVRIYIY2Y_cjs.d("invalid-session-id");return t}function H(a,t){let n=a.toString();if(n===t)return;let o=0;for(;o<n.length&&o<t.length&&n.charCodeAt(o)===t.charCodeAt(o);)o+=1;let e=0;for(;e<n.length-o&&e<t.length-o&&n.charCodeAt(n.length-e-1)===t.charCodeAt(t.length-e-1);)e+=1;let r=n.length-o-e;r>0&&a.delete(o,r);let i=t.slice(o,t.length-e);i.length>0&&a.insert(o,i);}function R(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;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 V(a){if(a===void 0||typeof a!="object"||a===null||Array.isArray(a))return;let t=a,n=R(t.anchor),o=R(t.head);if(n&&o)return {anchor:n,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 L(a){if(typeof a!="object"||a===null||Array.isArray(a))return null;let t=a;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 n=typeof t.color=="string"&&t.color.length<=64?t.color:void 0,o=t.role==="agent"?"agent":"human",e=V(t.selection);return {actorId:t.actorId,name:t.name,...n?{color:n}:{},role:o,...e?{selection:e}:{}}}function X(a){let t="";for(let n of a)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function $(a){let t=a.replace(/-/g,"+").replace(/_/g,"/"),n=atob(t+"=".repeat((4-t.length%4)%4));return Uint8Array.from(n,o=>o.charCodeAt(0))}var w=class{constructor(t,n,o,e,r,i){this.ydoc=t;this.awareness=n;this.baseline=i;this.documentId=o,this.sessionId=e,this.identity=r;let{root:d,paragraphs:p}=chunkVRIYIY2Y_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),n.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,n,o){if(!this.destroyed&&!(this.statusState.status()==="error"&&t!=="error")){if(n!==void 0){this.setStatus(t,n,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 n=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 chunkVRIYIY2Y_cjs.d?e.code:"local-mirror-failed",e instanceof chunkVRIYIY2Y_cjs.d?e.detail:void 0);}});return this.detachPort=()=>{this.flushPendingJournals(),n(),this.port===t&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}gateOperations(t,n){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(n.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>I)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:n}=chunkVRIYIY2Y_cjs.e(this.ydoc),o=(r,i)=>{let d=n.get(r.toUpperCase());if(d)return {paragraphId:r.toUpperCase(),position:X(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=[],n=[...this.awareness.getStates().entries()].slice(0,O);for(let[o,e]of n){let r=L(e[C]);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,O),{paragraphs:n}=chunkVRIYIY2Y_cjs.e(this.ydoc),o=[];for(let[e,r]of t){if(e===this.awareness.clientID)continue;let i=L(r[C]);if(!i?.selection)continue;let d=y=>{let x=n.get(y.paragraphId);if(!x)return null;let u;try{u=l__namespace.createAbsolutePositionFromRelativePosition(l__namespace.decodeRelativePosition($(y.position)),this.ydoc);}catch{return null}if(!u||u.type!==x)return null;let f=this.port?.paragraphs().find(M=>M.paragraphId===y.paragraphId);return f?{paragraphId:f.paragraphId,nodeId:f.nodeId,offset:u.index}:null},p=d(i.selection.anchor),v=d(i.selection.head);!p||!v||o.push(Object.freeze({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},anchor:Object.freeze(p),head:Object.freeze(v)}));}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(n){this.setStatus("error",n instanceof chunkVRIYIY2Y_cjs.d?n.code:"shared-schema-invalid",n instanceof chunkVRIYIY2Y_cjs.d?n.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 n=this.participants();for(let o of [...this.participantListeners])o(n);};publishAwareness(t){let n={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(C,n);}validateParagraphSet(t){let{paragraphs:n}=chunkVRIYIY2Y_cjs.e(this.ydoc),o=t.paragraphs();if(o.length!==n.size||o.some(e=>!n.has(e.paragraphId)||!(n.get(e.paragraphId)instanceof l__namespace.Text)||n.get(e.paragraphId).length>I))throw new chunkVRIYIY2Y_cjs.d("paragraph-set-mismatch")}validateImmutableSchema(){let{root:t,paragraphs:n}=chunkVRIYIY2Y_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 chunkVRIYIY2Y_cjs.d("unsupported-root-key");if(t.get("protocolVersion")!==chunkVRIYIY2Y_cjs.a||t.get("schemaVersion")!==chunkVRIYIY2Y_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 chunkVRIYIY2Y_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 chunkVRIYIY2Y_cjs.d("immutable-baseline-changed");for(let[r,i]of n)if(!this.baseline.paragraphs.some(d=>d.paragraphId===r)||!(i instanceof l__namespace.Text)||i.length>I)throw new chunkVRIYIY2Y_cjs.d("paragraph-set-mismatch")}reconcileYjsFromPort(){let t=this.port;if(!t)return;let{paragraphs:n}=chunkVRIYIY2Y_cjs.e(this.ydoc);this.ydoc.transact(()=>{for(let o of t.paragraphs()){let e=n.get(o.paragraphId);if(!e)throw new chunkVRIYIY2Y_cjs.d("paragraph-set-mismatch");H(e,o.text);}},this.localOrigin),this.undoManager.stopCapturing();}reconcilePortFromYjs(){let t=this.port;if(!t||this.applyingSharedState)return;let{paragraphs:n}=chunkVRIYIY2Y_cjs.e(this.ydoc);this.applyingSharedState=true;try{this.validateParagraphSet(t);let o=[];for(let e of t.paragraphs()){let r=n.get(e.paragraphId);if(!r)throw new chunkVRIYIY2Y_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 chunkVRIYIY2Y_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 chunkVRIYIY2Y_cjs.d?o.code:"remote-apply-failed",o instanceof chunkVRIYIY2Y_cjs.d?o.detail:void 0);}finally{this.applyingSharedState=false;}}setStatus(t,n,o){if(!this.statusState.set(t,n,o))return;let e=this.statusState.snapshot();for(let r of [...this.statusListeners])r(e.status,e.reason?.code,e.reason?.detail);}};async function J(a,t,n){if(a.bootstrap.kind==="create-or-join")throw new TypeError("createTextCollaboration does not support bootstrap kind 'create-or-join'. Use createDocumentCollaboration.");if(a.bootstrap.kind==="create"){let o=chunkVRIYIY2Y_cjs.f(a.bootstrap.document,t);return await chunkVRIYIY2Y_cjs.g(a.ydoc,t,n.actorId,o),chunkVRIYIY2Y_cjs.h(a.ydoc,t)}return await chunkVRIYIY2Y_cjs.i(a.ydoc,a.bootstrap.timeoutMs??D,a.bootstrap.signal),chunkVRIYIY2Y_cjs.h(a.ydoc,t)}async function Z(a){let t=F(a.documentId),n=N(a.sessionId),o=B(a.identity),e=await J(a,t,o),r=new w(a.ydoc,a.awareness,t,n,o,e);return Object.freeze({document:new Uint8Array(e.bytes),session:r,destroy:()=>r.destroy()})}
|
|
2
|
+
Object.defineProperty(exports,"collaborationModule",{enumerable:true,get:function(){return chunkQLZH2Q2C_cjs.b}});Object.defineProperty(exports,"CollaborationSchemaError",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.d}});Object.defineProperty(exports,"MAX_BASELINE_BYTES",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.c}});Object.defineProperty(exports,"PROTOCOL_VERSION",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.a}});Object.defineProperty(exports,"SCHEMA_VERSION",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.b}});Object.defineProperty(exports,"createDocumentCollaboration",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.m}});Object.defineProperty(exports,"readCollaborationDocument",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.k}});Object.defineProperty(exports,"readCollaborationResourceUsage",{enumerable:true,get:function(){return chunkVRIYIY2Y_cjs.j}});exports.createTextCollaboration=Z;
|