@docx-editor.dev/pro 2.16.2 → 2.18.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/dist/chunk-4NIIGM6D.cjs +4 -0
- package/dist/chunk-EFCL3VQI.cjs +4 -0
- package/dist/chunk-HMTYXNMO.js +4 -0
- package/dist/chunk-OZT67MLG.js +4 -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.d.cts +87 -6
- package/dist/collaboration/index.d.ts +87 -6
- package/dist/collaboration/index.js +2 -2
- package/dist/collaboration/webrtc.cjs +1 -1
- package/dist/collaboration/webrtc.js +1 -1
- package/dist/document-session-HHDGRM4Z.js +1 -0
- package/dist/document-session-I2C7MA6E.cjs +1 -0
- package/dist/document-session-OXC3PO7A.js +1 -0
- package/dist/document-session-U4VGKQYC.cjs +1 -0
- package/dist/hocuspocus-KOLAIT7T.cjs +1 -0
- package/dist/hocuspocus-ZBQCCO4G.js +1 -0
- 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.d.cts +3 -3
- package/dist/vue/index.d.ts +3 -3
- package/dist/vue/index.js +1 -1
- package/dist/vue/webrtc.cjs +1 -1
- package/dist/vue/webrtc.js +1 -1
- package/dist/{webrtc-F6OLZU65.cjs → webrtc-6HVF33UP.cjs} +1 -1
- package/dist/{webrtc-O3Y4W4P6.js → webrtc-CUEMY3DZ.js} +1 -1
- package/package.json +4 -4
- package/dist/chunk-3625DZUE.js +0 -3
- package/dist/chunk-54OI2PSM.js +0 -3
- package/dist/chunk-AB6CJLJ4.cjs +0 -3
- package/dist/chunk-DOVUXFIP.cjs +0 -3
- package/dist/document-session-6NLJAJY2.cjs +0 -1
- package/dist/document-session-CULOPWY6.js +0 -1
- package/dist/document-session-JVA7VYPB.cjs +0 -1
- package/dist/document-session-R4ETEHGF.js +0 -1
- package/dist/hocuspocus-AJOJV5NQ.js +0 -1
- package/dist/hocuspocus-TST45TQ6.cjs +0 -1
package/dist/chunk-3625DZUE.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import*as O 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 rr=new Set(["paraId","textId","id","numId","bookmarkId"]);function pt(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function ht(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),pt(e)}function ce(n){return /^[0-9a-f]{32}$/.test(n)}function mt(n,e){if(!ce(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 Te(n,e){return `yjs:${n}:${e}`}function K(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return ce(e)?e:null}function Ae(n){let e=[];for(let t of n)rr.has(t.localName)&&e.push(t.value);return e}var H=class{replicaId;next=0;constructor(e){if(this.replicaId=e??ht(),!ce(this.replicaId))throw new Error("invalid replica identity")}take(){let e=mt(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}),ir=/^sha256:[0-9a-f]{64}$/;function ft(n){return n?Object.freeze({...N,...n}):N}function g(n){return isDangerousKey(n)?"prototype-key":null}function k(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function w(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 yt(n){for(let e of Object.keys(n)){let t=g(e);if(t)return t}return !ir.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>N.maxBlobBytes?"blob-too-large":k(n.mediaType,N.maxMediaTypeLength)||n.mediaType.length===0||k(n.storageKey,N.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var bt=1,xt=2,It=1,vt=1,ar="docx-package-meta-v1",sr="docx-package-nodes-v1",lr="docx-package-parts-v1",dr="docx-package-rels-v1",cr="docx-package-overrides-v1",ur="docx-package-defaults-v1",pr="docx-package-binaries-v1",hr="docx-package-namespaces-v1",mr="docx-package-attributes-v1",gr="docx-package-bindings-v1",D="s",T="t",ue="children",Y="deleted",G="replacedBy",Me="splitFrom",Ne="splitBaseText",De="splitStart",E="",St="-",Lt=Object.freeze({kind:"docx-package-bootstrap"}),Et=Object.freeze({kind:"docx-package-journal"});function pe(n){return n.kind==="textValue"}function I(n){return !pe(n)}var fr=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),yr=200;function Rt(n){let e=new Map;for(let t of n)fr.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,yr)}function wt(n){return {meta:n.getMap(ar),nodes:n.getMap(sr),parts:n.getMap(lr),relationships:n.getMap(dr),overrides:n.getMap(cr),defaults:n.getMap(ur),binaries:n.getMap(pr),namespaces:n.getMap(hr),attributes:n.getMap(mr),bindings:n.getMap(gr)}}var Ct=[["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"]],br=new Map(Ct),xr=new Map(Ct.map(([n,e])=>[e,n]));function Ir(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 q(n){return n.length===0?St:br.get(n)??`n${Ir(n)}`}function F(n,e,t){let r=q(e);return e.length===0||g(r)||k(e,t)||n.get(r)!==e&&n.set(r,e),r}function Z(n,e){if(e===St||g(e))return "";let t=n.get(e);return typeof t=="string"?t:xr.get(e)??""}function Be(n,e,t,r){return `${n}${E}${e}${E}${t}${E}${r}`}function W(n){let e=n.split(E);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function _e(n,e,t){return `${n}${E}${e}${E}${t}`}function Q(n){let e=n.split(E);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 Ue(n,e){return `${n}${E}${e}`}function ee(n){let e=n.split(E);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function Ot(n,e){return `${n}${E}${e}`}function kt(n){let e=n.indexOf(E);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Pt(n){let e=new O.Map;e.set(D,Be(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new O.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ue,t),e}function Tt(n){let e=new O.Map;return e.set(T,new O.Text(n)),e}function At(n,e,t){let r=new O.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function Mt(n){let e=new O.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 Nt(n){let e=new O.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Dt(n){n.set("protocolVersion",bt),n.set("sharedSchemaVersion",xt),n.set("repairVersion",It),n.set("canonicalModelVersion",vt),n.set("initialized",true);}function b(n){return n instanceof O.Map}function C(n){if(!b(n))return null;let e=n.get(ue);return e instanceof O.Array?e:null}function z(n){return b(n)&&n.get(T)instanceof O.Text}function A(n){return b(n)&&n.get(Y)===true}function Ye(n){if(!b(n))return null;let e=n.get(G);return typeof e=="string"&&e.length>0?e:null}function V(n){if(!b(n))return null;let e=n.get(Me);return typeof e=="string"&&e.length>0?e:null}function he(n,e){if(!b(n))return null;let t=n.get(Ne);return typeof t=="string"&&t.length<=e?t:null}function ze(n){if(!b(n))return null;let e=n.get(De);return Number.isSafeInteger(e)&&e>=0?e:null}function _t(n,e){let t=n.get(e);if(!b(t))return null;if(z(t)){let r=t.get(T);return {isText:true,textLength:r instanceof O.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:C(t)?.toArray()??[]}}function me(n,e){let t=n.get(e);if(!b(t))return null;if(z(t))return "textValue";let r=t.get(D);return W(typeof r=="string"?r:"").kind}function Ut(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}var vr=256,ge=class{constructor(e,t){this.nodes=e;this.limits=t;}nodes;limits;runsBySplitOrigin=new Map;replicasByOrigin=new Map;contestedOrigins=new Set;originsByTextWitness=new Map;pendingTextRepairOrigins=new Set;textOverlays=new Map;overlayIdsByOrigin=new Map;liveRootedOrigins=new Set;declinedTangleCount=0;reset(){this.runsBySplitOrigin=new Map,this.replicasByOrigin=new Map,this.contestedOrigins=new Set,this.liveRootedOrigins=new Set,this.originsByTextWitness=new Map,this.pendingTextRepairOrigins=new Set,this.textOverlays=new Map,this.overlayIdsByOrigin=new Map;}record(e,t,r){let o=this.nodes.get(e),i=this.nodes.get(t);if(!b(o)||!b(i))return;let s=he(o,this.limits.maxTextLength)??this.runText(e)?.value,a=ze(i)??0,l=r.map(h=>({id:h,text:this.runText(h)})),d=s!==void 0&&s.length<=this.limits.maxTextLength&&l.every(h=>h.text!==null);d&&(o.set(Ne,s),this.indexTextWitnesses(e,this.runText(e)));let c=a;for(let h of l){let u=this.nodes.get(h.id);if(!b(u))return;e!==h.id&&(u.set(Me,e),d&&u.set(De,c),this.index(e,h.id),d&&this.indexTextWitnesses(e,h.text),c+=h.text?.value.length??0);}this.reSplitOfContestedOrigin(e)&&(this.declinedTangleCount+=l.length);}concurrentTextOverlays(e){let t=new Set,r=this.pendingTextRepairOrigins;this.pendingTextRepairOrigins=new Set;for(let o of r){for(let p of this.overlayIdsByOrigin.get(o)??[])this.textOverlays.delete(p)&&t.add(p);this.overlayIdsByOrigin.delete(o);let i=this.runsBySplitOrigin.get(o);if(!i||this.isReSplit(o)||e(o))continue;let s=he(this.nodes.get(o),this.limits.maxTextLength),a=this.runText(o);if(s===null||!a||a.value===s)continue;let l=new Set;for(let p of i)e(p)&&l.add(K(p)??"");let d=[...l].sort()[0];if(d===void 0)continue;let c=[...i].filter(p=>e(p)&&K(p)===d).map(p=>({id:p,start:ze(this.nodes.get(p)),text:this.runText(p)})).sort((p,f)=>(p.start??0)-(f.start??0)||p.id.localeCompare(f.id));if(!this.productsCoverBaseline(c,s))continue;let h=Sr(s,a.value,c),u=new Set;for(let p=0;p<c.length;p+=1){let f=c[p],y=Lr(f.text,h[p]);for(let L=0;L<f.text.parts.length;L+=1){let S=f.text.parts[L].id,x=y[L];this.textOverlays.get(S)!==x&&t.add(S),this.textOverlays.set(S,x),u.add(S);}}this.overlayIdsByOrigin.set(o,u);}return {values:this.textOverlays,changedIds:t}}noteChanged(e){for(let t of this.originsByTextWitness.get(e)??[])this.pendingTextRepairOrigins.add(t);}productsCoverBaseline(e,t){if(e.length===0||e[0]?.start!==0)return false;for(let r=0;r<e.length;r+=1){let o=e[r];if(o.start===null||!o.text)return false;let i=e[r+1]?.start??t.length;if(i<o.start||i>t.length)return false}return true}runText(e){if(me(this.nodes,e)!=="run")return null;let t=[],r=[],o="",i=new Set,s=(a,l)=>{if(l>this.limits.maxTreeDepth||i.has(a))return false;i.add(a),r.push(a);let d=this.nodes.get(a);if(!b(d))return false;if(z(d)){let u=d.get(T);if(!(u instanceof O.Text))return false;let p=u.toString();return o+=p,o.length>this.limits.maxTextLength?false:(t.push({id:a,value:p}),true)}let c=d.get(D),h=W(typeof c=="string"?c:"");if(l>0&&h.kind==="runProperties")return true;if(l>0&&h.localName!=="t")return false;for(let u of C(d)?.toArray()??[])if(!s(u,l+1))return false;return true};return s(e,0)&&t.length>0?{parts:t,witnessIds:r,value:o}:null}reSplitOfContestedOrigin(e){if(V(this.nodes.get(e))===null)return false;let t=e;for(let r=0;r<vr;r+=1){if(this.contestedOrigins.has(t)||this.liveRootedOrigins.has(t))return true;let o=V(this.nodes.get(t));if(o===null||o===t)return false;t=o;}return false}indexExisting(e){let t=V(this.nodes.get(e));if(t!==null&&t!==e){this.index(t,e),this.indexTextWitnesses(t,this.runText(t)),this.indexTextWitnesses(t,this.runText(e));let r=he(this.nodes.get(t),this.limits.maxTextLength),o=this.runText(t);r!==null&&o&&o.value!==r&&this.pendingTextRepairOrigins.add(t);}}indexTextWitnesses(e,t){if(t)for(let r of t.witnessIds){let o=this.originsByTextWitness.get(r)??new Set;o.add(e),this.originsByTextWitness.set(r,o);}}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(K(t)??""),this.replicasByOrigin.set(e,o),o.size>1&&this.contestedOrigins.add(e);let i=this.nodes.get(e);b(i)&&!A(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(K(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&&(K(d)??"")===l||e.isPresent(d)&&t.add(d);}return t}};function je(n,e,t){let r=0,o=Math.min(n.length,e.length);for(;r<o&&n.charCodeAt(r)===e.charCodeAt(r);)r+=1;let i=0;for(;i<n.length-r&&i<e.length-r&&n.charCodeAt(n.length-i-1)===e.charCodeAt(e.length-i-1);)i+=1;let s=n.length-i,a=e.length-i;return t<=r?t:t>=s?a+t-s:r}function Sr(n,e,t){let r=Er(n,e),o=t.findIndex((i,s)=>{let a=t[s+1]?.start??n.length;return i.start!==null&&r.start>=i.start&&r.start<=a});return t.map((i,s)=>{let a=i.start,l=t[s+1]?.start??n.length,d=n.slice(a,l),c=i.text.value,h=Math.max(r.start,a),u=Math.min(r.end,l),p=s===o&&r.insert.length>0;if(h>=u&&!p)return c;let f=Math.max(0,(p?r.start:h)-a),y=Math.max(f,u-a),L=je(d,c,f),S=je(d,c,y);return L===S&&p&&c.slice(L,L+r.insert.length)===r.insert?c:c.slice(0,L)+(p?r.insert:"")+c.slice(S)})}function Lr(n,e){let t=[0];for(let o of n.parts)t.push(t.at(-1)+o.value.length);let r=t.map(o=>je(n.value,e,o));return n.parts.map((o,i)=>e.slice(r[i],r[i+1]))}function Er(n,e){let t=0,r=Math.min(n.length,e.length);for(;t<r&&n.charCodeAt(t)===e.charCodeAt(t);)t+=1;let o=0;for(;o<n.length-t&&o<e.length-t&&n.charCodeAt(n.length-o-1)===e.charCodeAt(e.length-o-1);)o+=1;return {start:t,end:n.length-o,insert:e.slice(t,e.length-o)}}function Ke(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 fe(n){return typeof n=="string"?n:""}function zt(n,e){return n<e?-1:n>e?1:0}function Fe(n,e){return `${n}${E}${e}`}function wr(n){let e=n.indexOf(E);return e<0?n:n.slice(0,e)}function jt(n){let e=[];return n.forEach((t,r)=>{!b(t)||g(r)||t.forEach(o=>{if(!b(o))return;let i=fe(o.get("id")),s=fe(o.get("type"));if(i.length===0||s.length===0)return;let a=fe(o.get("ownerPart"))||wr(r);if(g(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,rawTarget:fe(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||zt(t.ownerPart,r.ownerPart)||zt(t.id,r.id)),e}function Kt(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 Cr(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 Ft(n,e){let t=n.childrenSnapshot.get(e);return t||(C(n.nodes.get(e))?.toArray()??[])}function Or(n,e){let t=n.nodes.get(e);return !b(t)||A(t)}function kr(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),Or(n,s)))return null;a=e.get(s);let c=n.parentIndex.get(s);if(a!==void 0){if(c!==void 0)return "fallback";break}if(c===void 0)return t.has(s)?"deferred":null;o.push(s),s=c;}let l=[a],d=s;for(let c=o.length-1;c>=0;c-=1){let h=o[c],u=Ft(n,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function Wt(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 c=kr(n,r,t,d);if(c==="fallback")return false;if(c==="deferred"){l=true;continue}if(c===null)continue;let h=Ft(n,d).indexOf(s);if(h<0)continue;let u=[...c,h];(!a||Cr(u,a.rank)<0)&&(a={rank:u,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 Vt(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 c=d.id;if(d.parent!==null&&(e===null||e.has(c))&&(r.has(c)||r.set(c,d.parent)),a.has(c))continue;let h=t.get(c);if(!b(h)||A(h))continue;let u=o.get(c)??C(h)?.toArray()??[];a.add(c),l.push({id:c,parent:null,exit:true});let p=new Set,f=[];for(let y of u)p.has(y)||y===c||(p.add(y),f.push(y));for(let y=f.length-1;y>=0;y-=1)l.push({id:f[y],parent:c,exit:false});}}}function Xt(n,e){return `${n}${E}${e}`}function We(n,e,t,r,o){if(g(t)||g(r.localName))return;let i=F(n.namespaces,r.namespaceUri,e),s=_e(t,i,r.localName);g(s)||n.attributes.set(s,Ot(r.prefix??"",o));}function $t(n,e,t,r){n.attributes.delete(_e(e,q(t),r));}function Ve(n,e,t,r,o){if(g(t)||g(r))return;let i=F(n.namespaces,o,e),s=Ue(t,r);g(s)||n.bindings.set(s,i);}function Jt(n,e,t){n.bindings.delete(Ue(e,t));}function Xe(n,e,t,r,o,i){let{prefix:s,value:a}=kt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(Xt(r,o),{namespaceUri:Z(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function Pr(n,e,t,r){let o=n.get(e);o&&(o.delete(Xt(t,r)),o.size===0&&n.delete(e));}function $e(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:Z(n.namespaces,o)});}function Tr(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function Ht(n,e,t){for(let[r,o]of t.changes.keys){let i=Q(String(r));if(!i||g(i.logicalId)||g(i.localName))continue;if(o.action==="delete"){Pr(e,i.logicalId,i.namespaceId,i.localName);continue}let s=n.attributes.get(String(r));typeof s=="string"&&Xe(n,e,i.logicalId,i.namespaceId,i.localName,s);}}function Gt(n,e,t){for(let[r,o]of t.changes.keys){let i=ee(String(r));if(!i||g(i.logicalId)||g(i.prefix))continue;if(o.action==="delete"){Tr(e,i.logicalId,i.prefix);continue}let s=n.bindings.get(String(r));typeof s=="string"&&$e(n,e,i.logicalId,i.prefix,s);}}function X(n){return typeof n=="string"?n:""}function qt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=X(t.get("rootId"));o.length!==0&&e.push({name:r,id:X(t.get("id")),rootLogicalId:o,contentType:X(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Zt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(partNameKey(r),t);}),e}function Qt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(r,t);}),e}function en(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||g(r))return;let o=X(t.get("digest")),i=t.get("size"),s=X(t.get("mediaType")),a=X(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:s,storageKey:a});}),e}function Mr(n){return n?._item??null}function Nr(n){return n.content instanceof O.ContentType}function nn(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=Mr(t);return r===null||r.parent!==n?true:!Nr(e)}}function Dr(n){let e=n._item;return e?Te(e.id.client,e.id.clock):null}function on(n){return typeof n=="string"?n:""}var M=class{constructor(e,t){this.doc=e;this.schema=wt(e),this.limits=ft(t),this.splitDedup=new ge(this.schema.nodes,this.limits),this.stopObserving=Kt(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 nn(this.schema.nodes)}encodeSnapshot(){return O.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return O.encodeStateAsUpdate(this.doc,e)}partEntries(){return qt(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 on(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(T),o=r instanceof O.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:Dr(t),wordFacingIds:Ae(o)}}isTombstoned(e){return A(this.schema.nodes.get(e))}replacedByOf(e){return Ye(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(q(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:_t(this.schema.nodes,e)}kindOf(e){return g(e)?null:me(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=F(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Pt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)We(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)Ve(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=F(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(D,Be(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Tt(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){$t(this.schema,e,t.namespaceUri,t.localName);return}We(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){Jt(this.schema,e,t);return}Ve(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(Y,true),t&&r.set(G,t);}recordRunSplit(e,t,r){this.splitDedup.record(e,t,r);}splitOriginOf(e){return V(this.schema.nodes.get(e))}replacementLoserRuns(){return this.splitDedup.loserRuns({isPresent:e=>Ke(this,e)})}concurrentSplitTextOverlays(){return this.splitDedup.concurrentTextOverlays(e=>Ke(this,e))}declinedSplitTangleEvents(){return this.splitDedup.declinedTangleEvents()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?C(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,At(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 O.Map;t.set(e.id,Mt(e)),this.schema.relationships.set(Fe(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(Fe(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,Nt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return jt(this.schema.relationships)}contentTypeOverrides(){return Zt(this.schema.overrides)}contentTypeDefaults(){return Qt(this.schema.defaults)}binaries(){return en(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 c of l.changes.keys.keys())s.add(String(c));a=true;continue}s.add(String(d[0])),l.target instanceof O.Array&&(a=true),l.target instanceof O.Map&&(l.changes.keys.has(Y)||l.changes.keys.has(G))&&(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=Q(String(a))??ee(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=C(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)=>{A(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=Q(t);!r||g(r.logicalId)||g(r.localName)||Xe(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=ee(t);!r||g(r.logicalId)||g(r.prefix)||$e(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&&this.splitDedup.noteChanged(String(r.path[0])),r.path.length===0&&r.target instanceof O.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 O.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 O.Map&&r.path.length===1&&(r.changes.keys.has(Y)||r.changes.keys.has(G))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,Ht(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,Gt(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?C(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(Ut(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;Wt({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){Vt({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=Ye(r);if(o!==null){if(A(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 C(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=C(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?C(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=W(on(t.get(D))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:Z(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:C(t)?.toArray()??[]}}textOf(e){let t=this.require(e).get(T);if(!(t instanceof O.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ue);if(!(t instanceof O.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 ye=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 an(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 sn(n){let e=n.binaryPart;return typeof e=="function"?e:null}function ln(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 dn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function _r(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function Ur(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function cn(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(k(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(k(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(k(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:_r(e),bindings:Ur(e)});for(let i of e.children){let s=cn(n,i,e.id,r+1,o);if(s)return s}}return t&&n.childArray(t).push([e.id]),null}async function Yr(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=w(r);if(a)return {ok:false,code:a};if(o.byteLength>N.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await an(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 te(n,e,t=new ye){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await Yr(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=w(a);if(d){o=d;return}if(k(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let c=cn(n,l.root,null,0,i);if(c){o=c;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=w(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=w(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);Dt(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},Lt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var be=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 un(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 B(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 zr(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}:k(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function jr(n,e,t){switch(e.kind){case "putNode":return zr(n,e.descriptor,t);case "spliceText":{let r=B(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=B(t,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:k(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=B(t,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&k(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=B(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=B(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=B(t,e.logicalId);if(r)return r;let o=B(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=w(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=B(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=w(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=w(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=w(e.partName);return r?{ok:false,code:r}:k(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=yt(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return g(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function Kr(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;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 Fr(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function Wr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Fr(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 Vr(n,e){let t=new be(n),r=[],o=new Set,i=new Set,s=new Map;for(let a of e){let l=jr(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 c=a.start+a.deleteCount;for(let h=a.start;h<c;h+=1){let u=d.children[h];u!==void 0&&(r.push(u),a.childLogicalIds.length>0&&s.set(u,a.childLogicalIds));}}for(let c of a.childLogicalIds)o.add(c);}else a.kind==="moveNode"?o.add(a.logicalId):a.kind==="putNode"&&a.descriptor.kind==="textValue"&&i.add(a.descriptor.logicalId);un(t,a);}return {removed:r,reinserted:o,mintedText:i,replacementsByRemoved:s}}function Xr(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function Je(n,e){if(n.nodeCount()+Xr(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=Vr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=Gr(n,t.removed);for(let o of e.effects)Kr(n,o,t.mintedText);$r(n,e.effects,t,r),Jr(n,t);},Et),{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=Wr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function Jr(n,e){for(let[t,r]of e.replacementsByRemoved){if(n.kindOf(t)!=="run")continue;let o=Hr(n,t,e.reinserted),i=r.filter(s=>n.kindOf(s)==="run");n.recordRunSplit(o,t,i);}}function Hr(n,e,t){let r=e;for(let o=0;o<n.limits.maxTreeDepth&&t.has(r);o+=1){let i=n.splitOriginOf(r);if(i===null||i===r)break;r=i;}return r}function Gr(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 Ie="http://schemas.openxmlformats.org/package/2006/relationships",qr="application/vnd.openxmlformats-package.relationships+xml",pn=/^(.*)\/_rels\/([^/]*)\.rels$/;function hn(n){return pn.test(n)}function mn(n){let e=pn.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function ne(n,e){return n.attributes.find(t=>t.localName===e)?.value}function xe(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Zr(n,e){let t=[xe("Id",e.id),xe("Type",e.type),xe("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(xe("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:Ie,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function gn(n,e){if(n.kind==="textValue"||n.namespaceUri!==Ie||n.localName!=="Relationship"||ne(n,"Id")!==e.id||ne(n,"Type")!==e.type||ne(n,"Target")!==e.rawTarget)return false;let t=ne(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function fn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>gn(t,e[r]))}function yn(n,e){if(n.id!==e.id||n.kind!==e.kind||n.namespaceUri!==e.namespaceUri||n.localName!==e.localName||n.prefix!==e.prefix||n.attributes.length!==e.attributes.length)return false;for(let t=0;t<n.attributes.length;t+=1){let r=n.attributes[t],o=e.attributes[t];if(r.namespaceUri!==o.namespaceUri||r.localName!==o.localName||r.value!==o.value||r.prefix!==o.prefix)return false}return n.namespaceBindings.length!==e.namespaceBindings.length?false:n.namespaceBindings.every((t,r)=>{let o=e.namespaceBindings[r];return t.prefix===o.prefix&&t.namespaceUri===o.namespaceUri})}function bn(n,e,t){let r=[];for(let o of e){if(g(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&ne(a,"Id")===o.id);if(i&&gn(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;g(s)||r.push(Zr(s,o));}return r}function Qr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:Ie,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:Ie})]),attributes:Object.freeze([]),children:Object.freeze([])})}function xn(n){return Object.freeze({id:n,name:n,contentType:qr,root:Qr(n)})}function In(n){let e=new Map;for(let t of n){if(g(t.id)||t.ownerPart!=="/"&&w(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var En=/^\/customXml\/item(\d+)\.xml$/i,ro=/^\/customXml\/itemProps(\d+)\.xml$/i;function oe(n){return En.test(n)}function Ge(n){return ro.test(n)}function oo(n){let e=En.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function vn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function io(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 Sn(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 ao(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=io(s,"uri",DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function so(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&I(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function lo(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:so(n,e)}function co(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function Rn(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,p]of e){let f=n.record(p.root.id);!f||!I(f)||(oe(u)&&t.set(f.logicalId,f),Ge(u)&&r.set(f.logicalId,f));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let p=n.record(u);!p||!I(p)||(lo(n,p)?t.set(u,p):co(n,p)&&r.set(u,p));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let p=o.get(u.namespaceUri)??[];p.push(u),o.set(u.namespaceUri,p);}let i=new Map;for(let u of r.values()){let p=ao(n,u.logicalId);if(!p)continue;let f=i.get(p)??[];f.push(u),i.set(p,f);}let s=[];for(let[u,p]of o){let f=i.get(u);if(!f||f.length===0)continue;p.sort((v,R)=>v.logicalId.localeCompare(R.logicalId)),f.sort((v,R)=>v.logicalId.localeCompare(R.logicalId));let y=p[0],L=f[0],S=[],x=new Set;for(let v of p)for(let R of v.childIds){if(x.has(R))continue;let de=n.record(R);!de||!I(de)||de.localName!=="node"||de.namespaceUri!==u||(x.add(R),S.push(R));}for(let v of n.allLogicalIds()){if(x.has(v)||n.isTombstoned(v))continue;let R=n.record(v);!R||!I(R)||R.localName!=="node"||R.namespaceUri!==u||(x.add(v),S.push(v));}S.sort((v,R)=>Sn(n,v).localeCompare(Sn(n,R))),s.push({data:y,props:L,nodeIds:S});}s.sort((u,p)=>u.data.logicalId.localeCompare(p.data.logicalId));let a=new Set,l=[],d=new Set,c=new Set;for(let[u,p]of e){let f=oo(u);if(f===null)continue;let y=s.find(x=>x.data.logicalId===p.root.id&&!d.has(x.data.logicalId));if(!y)continue;let L=vn(f).props,S=e.get(L);S&&S.root.id!==y.props.logicalId||(a.add(f),d.add(y.data.logicalId),c.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:u,propsName:L,nodeIds:y.nodeIds}));}let h=1;for(let u of s){if(d.has(u.data.logicalId))continue;for(;a.has(h);)h+=1;a.add(h);let p=vn(h);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:p.item,propsName:p.props,nodeIds:u.nodeIds}),h+=1;}return l.sort((u,p)=>u.itemName.localeCompare(p.itemName)),l}function uo(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:oe(n.ownerPart)}function po(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function ho(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 wn(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,po(a.id));let s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=o[a],c=d?.id??`rId${String(i+=1)}`;s.push({ownerPart:t,id:c,type:CUSTOM_XML_REL,rawTarget:ho(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 Cn(n,e){return e.length===0?[...n]:[...n.filter(t=>!uo(t)),...e]}function On(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function qe(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(oe).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 kn(n,e){if(qe(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 mo="http://schemas.microsoft.com/office/word/2012/wordml";function ve(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Se(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 Pn(n){return e=>e.localName===n&&e.namespaceUri===WML_NAMESPACE_URI}function go(n){return n.localName==="abstractNum"?`0${Se(ve(n,"abstractNumId"))}`:`1${Se(ve(n,"numId"))}`}function fo(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Tn(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===mo,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Pn("footnote"),sortKey:e=>Se(ve(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Pn("endnote"),sortKey:e=>Se(ve(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:fo,sortKey:go}:null}function yo(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ze(n){return n.kind==="textValue"?n.id:yo(n,"id")??n.id}function $(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 Nn(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:$(t.children,e)});return Object.freeze({...n,root:r})}function bo(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 _n(n){}function Yn(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function Eo(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 Ro(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 Le(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&&Eo(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Ro(r,n)?r.attributes:Object.freeze(n.attributes.map(bo)),children:e})}function zn(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 Qe(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)Qe(o,e)||(r=false);return r}function jn(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 Ee=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:Cn(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:In(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:Oo(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;_n(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 Oo(n){let e=buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var Re=class{lastLosers=new Set;textOverlays=new Map;losers=new Set;update(e){let t=[],r=e.replacementLoserRuns(),o=s=>{let a=e.parentOf(s);a!==null&&t.push(a);};for(let s of r)this.lastLosers.has(s)||o(s);for(let s of this.lastLosers)r.has(s)||o(s);this.lastLosers=r,this.losers=r;let i=e.concurrentSplitTextOverlays();return this.textOverlays=i.values,t.push(...i.changedIds),t}textValue(e,t){return this.textOverlays.get(e)??t}};function To(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 j=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Ee(e),this.stop=e.observeDirty(r=>{for(let o of r.logicalIds)this.pendingDirty.add(o);r.membershipChanged&&(this.pendingMembership=true),r.packageChanged&&(this.pendingPackage=true);});}registry;blobs;cache=new Map;heights=new Map;partCache=new Map;packageCache;relsProjection=new Map;pendingDirty=new Set;pendingMembership=false;pendingPackage=false;lastDirty=new Set;lastAdoption=new Map;placementContested=false;splitProjection=new Re;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let c of this.adoptionChanges())e.add(c);for(let c of this.splitProjection.update(this.registry))e.add(c);let o=jn(this.registry,e),i=new Set(this.registry.partEntries().map(c=>c.rootLogicalId)),s=[...e].some(c=>i.has(c)||this.registry.parentOf(c)===null&&!this.registry.isTombstoned(c)),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:To(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 c=new Set,h=this.materialize(d.rootLogicalId,o,c,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===h&&u.contentType===d.contentType){i.set(d.name,u);continue}let p=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,p),this.partCache.set(d.name,p);}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,c])=>this.pkg?.parts.get(d)===c)?{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 c of d.childIds)s.push({id:c,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&&(pe(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let u=this.cache.get(e);if(u&&r.size+this.heightOf(u)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?Qe(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(pe(i)){let u=this.splitProjection.textValue(e,i.value),p=this.cache.get(e);if(p?.kind==="textValue"&&p.value===u)return p;let f=Yn(e,u);return this.remember(e,f),f}r.add(e);let s=new Set,a=[...i.childIds];for(let u of this.registry.adoptedChildren(e))a.includes(u)||a.push(u);let l=[];for(let u of a){if(u===e){this.push("self-child",u);continue}if(s.has(u)){this.push("duplicate-child",u);continue}if(s.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(this.splitProjection.losers.has(u)){t.add(u);continue}if(g(u)||!this.registry.hasNode(u)){this.push("child-id-not-in-registry",u);continue}if(!this.claimsWholeSubtrees){let f=this.registry.listingParents(u);f.length>1&&(this.placementContested=true,this.contestEncountered.add(u),f.some(y=>this.registry.isTombstoned(y)&&this.registry.replacedByOf(y)!==null)?this.contestMatchesResolution=false:!t.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let p=this.materialize(u,t,r,o);p&&l.push(p);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,p)=>u===l[p])&&zn(d,i))return d;let c=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(c,l);let h=Le(i,$(c,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let s=relsPartNameFor(o);if(s!=="/_rels/.rels"&&w(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)||!hn(o))continue;let s=mn(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||yn(o.root,t.root))&&o?o:t??xn(e);if(fn(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=Nn(s,bn(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=Tn(a.root);if(!l)continue;let d=x=>x.logicalId!==a.root.id&&l.isMember(x),c=[],h=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)||(c.push(x),h.add(x.id));}if(this.adoptLooseMembers(c,h,d,t,r,o,i)===0)continue;c.sort((x,v)=>l.sortKey(x).localeCompare(l.sortKey(v)));let p=[];for(let x of a.root.children)h.has(x.id)||p.push(x);let f=$(a.root.children,[...p,...c]);if(f===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!I(y))continue;let L=Le(y,f,a.root);this.remember(a.root.id,L);let S=Object.freeze({...a,root:L});e.set(s,S),this.partCache.set(s,S);}}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 c=this.registry.record(d);if(!c||!I(c)||!r(c))continue;let h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),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(p=>p.id)),d=0;for(let p of t){if(l.has(p))continue;let f=this.materializeOnce(p,r,o);!f||f.kind==="textValue"||(a.push(f),l.add(p),d+=1);}if(a.sort((p,f)=>Ze(p).localeCompare(Ze(f))),d===0&&a.every((p,f)=>p===s.children[f]))return s;let c=this.registry.record(e);if(!c||!I(c))return s;let h=$(s.children,a),u=Le(c,h,s);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=Rn(this.registry,e);if(o.length===0||!kn(e,o))return;let i=qe(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 c=Object.freeze({id:a.itemName,name:a.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:a.propsName,name:a.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,c),e.set(a.propsName,h),this.partCache.set(a.itemName,c),this.partCache.set(a.propsName,h);}if(i){for(let a of [...e.keys()])!oe(a)&&!Ge(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=wn(this.registry,o),this.customXmlOverrides=On(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 Fn=1,Wn=1,tt=20*1024*1024,_o="docx-collaboration-v1",Uo="docx-body-paragraphs-v1",Yo=Object.freeze({kind:"docx-collaboration-bootstrap"}),m=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function rt(n){return {root:n.getMap(_o),paragraphs:n.getMap(Uo)}}function zo(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new m("invalid-baseline");if(n.byteLength>tt)throw new m("baseline-too-large");let t=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:tt,maxRatio:200}});if(!t.ok)throw new m("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new m("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 Vn(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 Kn(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new m("invalid-shared-metadata",e);return t}function et(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new m("invalid-shared-metadata",e);return t}function ae(n){return n.get("initialized")===true}async function Ha(n,e,t,r){let{root:o,paragraphs:i}=rt(n);if(ae(o))throw new m("already-initialized");let s=await Vn(r.bytes);n.transact(()=>{if(ae(o))throw new m("already-initialized");o.set("protocolVersion",Fn),o.set("schemaVersion",Wn),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 m("duplicate-paragraph-id");let l=new O.Text;i.set(a.paragraphId,l),l.insert(0,a.text);}o.set("initialized",true);},Yo);}async function Ga(n,e){let{root:t,paragraphs:r}=rt(n);if(!ae(t))throw new m("not-initialized");if(et(t,"protocolVersion")!==Fn)throw new m("protocol-version-mismatch");if(et(t,"schemaVersion")!==Wn)throw new m("schema-version-mismatch");if(Kn(t,"documentId")!==e)throw new m("document-id-mismatch");let o=et(t,"baselineByteLength");if(o===0||o>tt)throw new m("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new m("invalid-baseline");if(await Vn(i)!==Kn(t,"baselineSha256"))throw new m("baseline-digest-mismatch");let s=zo(new Uint8Array(i),e),a=new Set(s.paragraphs.map(l=>l.paragraphId));if(r.size!==a.size)throw new m("paragraph-set-mismatch");for(let[l,d]of r)if(!a.has(l)||!(d instanceof O.Text))throw new m("paragraph-set-mismatch");return s}function qa(n,e,t){let{root:r}=rt(n);return ae(r)?Promise.resolve():t?.aborted?Promise.reject(new m("initialization-aborted")):new Promise((o,i)=>{let s=c=>{clearTimeout(d),r.unobserve(a),t?.removeEventListener("abort",l),c?i(c):o();},a=()=>{ae(r)&&s();},l=()=>s(new m("initialization-aborted")),d=setTimeout(()=>s(new m("initialization-timeout")),e);r.observe(a),t?.addEventListener("abort",l,{once:true});})}var Ce=64*1024*1024,J="docx-package-blobs-v1";function Ko(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 Fo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function we(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var _=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=Ko(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+=Fo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Ce)throw new m("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 se(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return we("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return we("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof O.Map?a.size:0;}),i>t.maxRelationships)return we("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>Ce?we("blob-store-full",`${s}`):null}var $n=20*1024*1024,it=3e4,$o=4e3,Jo=1500,Ho="docx-collaboration-seeds-v1",ot="docxEditorSeedCandidate",Go=/^[0-9a-f]{16}$/,qo=256;function at(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new m("invalid-baseline");if(n.byteLength>$n)throw new m("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:$n,maxRatio:200}});if(!e.ok)throw new m("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new m("no-main-document-part");return new TreePackageStore(e.package,normalizeParagraphIdentity(t)).currentPackage()}function Zo(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function le(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Zo(n,e),s=()=>{let l=e.poisonedDigest();return l?new m("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new m("initialization-aborted")):new Promise((l,d)=>{let c=f=>{clearTimeout(p),o.unobserve(h),n.doc.off("afterTransaction",h),r?.removeEventListener("abort",u),f?d(f):l();},h=()=>{let f=s();if(f){c(f);return}i()&&c();},u=()=>c(new m("initialization-aborted")),p=setTimeout(()=>c(new m("initialization-timeout")),t);o.observe(h),n.doc.on("afterTransaction",h),r?.addEventListener("abort",u,{once:true});})}function st(n){return n.getArray(Ho)}function Oe(n){return st(n).length}function Hn(n,e){let t=st(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Qo(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function ei(n,e){let t=[...n.getStates().entries()].slice(0,qo);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[ot];if(!(typeof i!="string"||!Go.test(i))&&i<e)return true}return false}async function Jn(n,e,t,r){try{return await le(n,e,t,r),!0}catch(o){if(o instanceof m&&o.code==="initialization-timeout")return false;throw o}}function ti(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new m("initialization-aborted")):new Promise((i,s)=>{let a=h=>{clearTimeout(c),r.unobserve(l),t?.removeEventListener("abort",d),h?s(h):i();},l=()=>{o()&&a();},d=()=>a(new m("initialization-aborted")),c=setTimeout(()=>a(new m("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function Gn(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??$o,s=n.electionWindowMs??Jo,a=n.timeoutMs??it,l=async()=>(await ti(r,a,n.signal),"joined");if(await Jn(r,o,i,n.signal))return l();let d=Qo();t.setLocalStateField(ot,d);try{let c=await Jn(r,o,s,n.signal);if(!c&&ei(t,d)&&(await le(r,o,a,n.signal),c=!0),c)return await l();if(r.schema.meta.get("initialized")===!0)return await le(r,o,a,n.signal),await l();let h=await te(r,at(n.document),o);if(!h.ok)throw new m(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),st(e).push([d]);}),"seeded"}finally{t.setLocalStateField(ot,null);}}var ke=class{constructor(e,t){this.knows=e;this.allocator=new H(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 ni(n){let e=0;return n.schema.nodes.forEach(t=>{b(t)&&t.get(Y)===true&&(e+=1);}),e}function ri(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof O.Map?t.size:0;}),e}function lt(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:ni(n),maxNodes:n.limits.maxNodes,relationships:ri(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Ce})}function us(n){let e=new M(n);try{let t=new _(n.getMap(J));return lt(e,t)}finally{e.destroy();}}var Pe="docxEditor",U=256,dt=256;function Qn(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>U||t.length===0||t.length>U)throw new m("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new m("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function er(n){let e=n.trim();if(e.length===0||e.length>U)throw new m("invalid-document-id");return e}function tr(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>U)throw new m("invalid-session-id");return e}function Zn(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 ii(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Zn(e.anchor),r=Zn(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 ct(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>U||typeof e.name!="string"||e.name.length===0||e.name.length>U)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=ii(e.selection);return i?{...o,selection:i}:o}function si(n){let e=new M(n),t=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new m("not-initialized");if(Oe(n)>1)throw new m("concurrent-seed");let r=new _(n.getMap(J)),o=se(e,r);if(o)throw new m(o.code,o.detail);t=new j(e,r);let i=t.current(),s=r.poisonedDigest();if(s)throw new m("blob-digest-mismatch",s);if(!i.ok)throw new m(i.code);return writeOoxmlPackage(i.package)}finally{t?.destroy(),e.destroy();}}var pi=3,hi=5e3,mi=2e3,gi=Symbol("createDocumentCollaboration.attachWatchdogMs"),ut=class{constructor(e,t,r,o,i,s,a,l,d,c,h){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new O.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:hi,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let p=d.verifyNow(u);p&&this.setStatus("error","blob-digest-mismatch",p);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=Hn(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 ${c}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.`);},c),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 lt(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,dt);for(let[r,o]of t){let i=ct(o[Pe]);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,dt),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=ct(s[Pe]);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>U)throw new m("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new m("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=Je(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=ln(e.effects,sn(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{dn(this.blobs,e);}catch(t){return t instanceof m?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<pi&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(t.status==="ready"||t.status==="disconnected")&&this.setStatus(t.status,t.reason?.code,t.reason?.detail);}onYjsTransaction=e=>{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=se(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=Rt(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 m?t.code:"remote-apply-failed",t instanceof m?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(Pe,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 Ms(n){let e=n[gi]??mi,t=er(n.documentId),r=tr(n.sessionId),o=Qn(n.identity),i=new M(n.ydoc);try{return await fi(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(s){throw i.destroy(),s}}async function fi(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:s}=e,a=new ke(h=>s.hasNode(h)),l=new _(n.ydoc.getMap(J));if(n.bootstrap.kind==="create"){if(s.schema.meta.get("initialized")===true)throw new m("already-initialized");let h=await te(s,at(n.bootstrap.document),l);if(!h.ok)throw new m(h.code);n.ydoc.transact(()=>{s.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await Gn({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 m("document-id-mismatch");s.rebuildDerivedIndexes();}}else {if(await le(s,l,n.bootstrap.timeoutMs??it,n.bootstrap.signal),s.schema.meta.get("documentId")!==r)throw new m("document-id-mismatch");s.rebuildDerivedIndexes();}if(Oe(n.ydoc)>1)throw new m("concurrent-seed");let d=se(s,l);if(d)throw new m(d.code,d.detail);let c=new j(s,l);try{let h=c.current(),u=l.poisonedDigest();if(u)throw new m("blob-digest-mismatch",u);if(!h.ok)throw new m(h.code);let p=writeOoxmlPackage(h.package),f=new ut(n.ydoc,n.awareness,r,o,i,s,c,a,l,t,n.offlineEditing===!0);return Object.freeze({document:p,session:f,destroy:()=>f.destroy()})}catch(h){throw c.destroy(),h}}export{Fn as a,Wn as b,tt as c,m as d,rt as e,zo as f,Ha as g,Ga as h,qa as i,us as j,si as k,gi as l,Ms as m};
|
package/dist/chunk-54OI2PSM.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import*as O from'yjs';import {writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,readOoxmlPackage,TreePackageStore,normalizeParagraphIdentity,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'@docx-editor.dev/core/collaboration/replication';var Jn=new Set(["paraId","textId","id","numId","bookmarkId"]);function at(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function st(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),at(e)}function de(n){return /^[0-9a-f]{32}$/.test(n)}function lt(n,e){if(!de(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 Pe(n,e){return `yjs:${n}:${e}`}function K(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return de(e)?e:null}function Te(n){let e=[];for(let t of n)Jn.has(t.localName)&&e.push(t.value);return e}var J=class{replicaId;next=0;constructor(e){if(this.replicaId=e??st(),!de(this.replicaId))throw new Error("invalid replica identity")}take(){let e=lt(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};var M=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}),Gn=/^sha256:[0-9a-f]{64}$/;function ct(n){return n?Object.freeze({...M,...n}):M}function m(n){return isDangerousKey(n)?"prototype-key":null}function k(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function w(n){let e=m(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 ut(n){for(let e of Object.keys(n)){let t=m(e);if(t)return t}return !Gn.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>M.maxBlobBytes?"blob-too-large":k(n.mediaType,M.maxMediaTypeLength)||n.mediaType.length===0||k(n.storageKey,M.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var pt=1,ht=2,mt=1,gt=1,qn="docx-package-meta-v1",Zn="docx-package-nodes-v1",Qn="docx-package-parts-v1",er="docx-package-rels-v1",tr="docx-package-overrides-v1",nr="docx-package-defaults-v1",rr="docx-package-binaries-v1",or="docx-package-namespaces-v1",ir="docx-package-attributes-v1",ar="docx-package-bindings-v1",N="s",T="t",ce="children",_="deleted",H="replacedBy",Ae="splitFrom",Me="splitBaseText",Ne="splitStart",E="",ft="-",yt=Object.freeze({kind:"docx-package-bootstrap"}),bt=Object.freeze({kind:"docx-package-journal"});function ue(n){return n.kind==="textValue"}function I(n){return !ue(n)}var sr=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),lr=200;function xt(n){let e=new Map;for(let t of n)sr.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,lr)}function It(n){return {meta:n.getMap(qn),nodes:n.getMap(Zn),parts:n.getMap(Qn),relationships:n.getMap(er),overrides:n.getMap(tr),defaults:n.getMap(nr),binaries:n.getMap(rr),namespaces:n.getMap(or),attributes:n.getMap(ir),bindings:n.getMap(ar)}}var vt=[["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"]],dr=new Map(vt),cr=new Map(vt.map(([n,e])=>[e,n]));function ur(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 G(n){return n.length===0?ft:dr.get(n)??`n${ur(n)}`}function F(n,e,t){let r=G(e);return e.length===0||m(r)||k(e,t)||n.get(r)!==e&&n.set(r,e),r}function q(n,e){if(e===ft||m(e))return "";let t=n.get(e);return typeof t=="string"?t:cr.get(e)??""}function De(n,e,t,r){return `${n}${E}${e}${E}${t}${E}${r}`}function W(n){let e=n.split(E);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function Be(n,e,t){return `${n}${E}${e}${E}${t}`}function Z(n){let e=n.split(E);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 _e(n,e){return `${n}${E}${e}`}function Q(n){let e=n.split(E);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function St(n,e){return `${n}${E}${e}`}function Lt(n){let e=n.indexOf(E);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Et(n){let e=new O.Map;e.set(N,De(n.kind,n.namespaceId,n.localName,n.prefix??""));let t=new O.Array;return n.childIds&&n.childIds.length>0&&t.push([...n.childIds]),e.set(ce,t),e}function Rt(n){let e=new O.Map;return e.set(T,new O.Text(n)),e}function wt(n,e,t){let r=new O.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function Ct(n){let e=new O.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 Ot(n){let e=new O.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function kt(n){n.set("protocolVersion",pt),n.set("sharedSchemaVersion",ht),n.set("repairVersion",mt),n.set("canonicalModelVersion",gt),n.set("initialized",true);}function b(n){return n instanceof O.Map}function C(n){if(!b(n))return null;let e=n.get(ce);return e instanceof O.Array?e:null}function U(n){return b(n)&&n.get(T)instanceof O.Text}function A(n){return b(n)&&n.get(_)===true}function Ue(n){if(!b(n))return null;let e=n.get(H);return typeof e=="string"&&e.length>0?e:null}function V(n){if(!b(n))return null;let e=n.get(Ae);return typeof e=="string"&&e.length>0?e:null}function pe(n,e){if(!b(n))return null;let t=n.get(Me);return typeof t=="string"&&t.length<=e?t:null}function Ye(n){if(!b(n))return null;let e=n.get(Ne);return Number.isSafeInteger(e)&&e>=0?e:null}function Tt(n,e){let t=n.get(e);if(!b(t))return null;if(U(t)){let r=t.get(T);return {isText:true,textLength:r instanceof O.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:C(t)?.toArray()??[]}}function he(n,e){let t=n.get(e);if(!b(t))return null;if(U(t))return "textValue";let r=t.get(N);return W(typeof r=="string"?r:"").kind}function At(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}var pr=256,me=class{constructor(e,t){this.nodes=e;this.limits=t;}nodes;limits;runsBySplitOrigin=new Map;replicasByOrigin=new Map;contestedOrigins=new Set;originsByTextWitness=new Map;pendingTextRepairOrigins=new Set;textOverlays=new Map;overlayIdsByOrigin=new Map;liveRootedOrigins=new Set;declinedTangleCount=0;reset(){this.runsBySplitOrigin=new Map,this.replicasByOrigin=new Map,this.contestedOrigins=new Set,this.liveRootedOrigins=new Set,this.originsByTextWitness=new Map,this.pendingTextRepairOrigins=new Set,this.textOverlays=new Map,this.overlayIdsByOrigin=new Map;}record(e,t,r){let o=this.nodes.get(e),i=this.nodes.get(t);if(!b(o)||!b(i))return;let s=pe(o,this.limits.maxTextLength)??this.runText(e)?.value,a=Ye(i)??0,l=r.map(h=>({id:h,text:this.runText(h)})),d=s!==void 0&&s.length<=this.limits.maxTextLength&&l.every(h=>h.text!==null);d&&(o.set(Me,s),this.indexTextWitnesses(e,this.runText(e)));let u=a;for(let h of l){let c=this.nodes.get(h.id);if(!b(c))return;e!==h.id&&(c.set(Ae,e),d&&c.set(Ne,u),this.index(e,h.id),d&&this.indexTextWitnesses(e,h.text),u+=h.text?.value.length??0);}this.reSplitOfContestedOrigin(e)&&(this.declinedTangleCount+=l.length);}concurrentTextOverlays(e){let t=new Set,r=this.pendingTextRepairOrigins;this.pendingTextRepairOrigins=new Set;for(let o of r){for(let p of this.overlayIdsByOrigin.get(o)??[])this.textOverlays.delete(p)&&t.add(p);this.overlayIdsByOrigin.delete(o);let i=this.runsBySplitOrigin.get(o);if(!i||this.isReSplit(o)||e(o))continue;let s=pe(this.nodes.get(o),this.limits.maxTextLength),a=this.runText(o);if(s===null||!a||a.value===s)continue;let l=new Set;for(let p of i)e(p)&&l.add(K(p)??"");let d=[...l].sort()[0];if(d===void 0)continue;let u=[...i].filter(p=>e(p)&&K(p)===d).map(p=>({id:p,start:Ye(this.nodes.get(p)),text:this.runText(p)})).sort((p,g)=>(p.start??0)-(g.start??0)||p.id.localeCompare(g.id));if(!this.productsCoverBaseline(u,s))continue;let h=hr(s,a.value,u),c=new Set;for(let p=0;p<u.length;p+=1){let g=u[p],y=mr(g.text,h[p]);for(let L=0;L<g.text.parts.length;L+=1){let S=g.text.parts[L].id,x=y[L];this.textOverlays.get(S)!==x&&t.add(S),this.textOverlays.set(S,x),c.add(S);}}this.overlayIdsByOrigin.set(o,c);}return {values:this.textOverlays,changedIds:t}}noteChanged(e){for(let t of this.originsByTextWitness.get(e)??[])this.pendingTextRepairOrigins.add(t);}productsCoverBaseline(e,t){if(e.length===0||e[0]?.start!==0)return false;for(let r=0;r<e.length;r+=1){let o=e[r];if(o.start===null||!o.text)return false;let i=e[r+1]?.start??t.length;if(i<o.start||i>t.length)return false}return true}runText(e){if(he(this.nodes,e)!=="run")return null;let t=[],r=[],o="",i=new Set,s=(a,l)=>{if(l>this.limits.maxTreeDepth||i.has(a))return false;i.add(a),r.push(a);let d=this.nodes.get(a);if(!b(d))return false;if(U(d)){let c=d.get(T);if(!(c instanceof O.Text))return false;let p=c.toString();return o+=p,o.length>this.limits.maxTextLength?false:(t.push({id:a,value:p}),true)}let u=d.get(N),h=W(typeof u=="string"?u:"");if(l>0&&h.kind==="runProperties")return true;if(l>0&&h.localName!=="t")return false;for(let c of C(d)?.toArray()??[])if(!s(c,l+1))return false;return true};return s(e,0)&&t.length>0?{parts:t,witnessIds:r,value:o}:null}reSplitOfContestedOrigin(e){if(V(this.nodes.get(e))===null)return false;let t=e;for(let r=0;r<pr;r+=1){if(this.contestedOrigins.has(t)||this.liveRootedOrigins.has(t))return true;let o=V(this.nodes.get(t));if(o===null||o===t)return false;t=o;}return false}indexExisting(e){let t=V(this.nodes.get(e));if(t!==null&&t!==e){this.index(t,e),this.indexTextWitnesses(t,this.runText(t)),this.indexTextWitnesses(t,this.runText(e));let r=pe(this.nodes.get(t),this.limits.maxTextLength),o=this.runText(t);r!==null&&o&&o.value!==r&&this.pendingTextRepairOrigins.add(t);}}indexTextWitnesses(e,t){if(t)for(let r of t.witnessIds){let o=this.originsByTextWitness.get(r)??new Set;o.add(e),this.originsByTextWitness.set(r,o);}}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(K(t)??""),this.replicasByOrigin.set(e,o),o.size>1&&this.contestedOrigins.add(e);let i=this.nodes.get(e);b(i)&&!A(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(K(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&&(K(d)??"")===l||e.isPresent(d)&&t.add(d);}return t}};function ze(n,e,t){let r=0,o=Math.min(n.length,e.length);for(;r<o&&n.charCodeAt(r)===e.charCodeAt(r);)r+=1;let i=0;for(;i<n.length-r&&i<e.length-r&&n.charCodeAt(n.length-i-1)===e.charCodeAt(e.length-i-1);)i+=1;let s=n.length-i,a=e.length-i;return t<=r?t:t>=s?a+t-s:r}function hr(n,e,t){let r=gr(n,e),o=t.findIndex((i,s)=>{let a=t[s+1]?.start??n.length;return i.start!==null&&r.start>=i.start&&r.start<=a});return t.map((i,s)=>{let a=i.start,l=t[s+1]?.start??n.length,d=n.slice(a,l),u=i.text.value,h=Math.max(r.start,a),c=Math.min(r.end,l),p=s===o&&r.insert.length>0;if(h>=c&&!p)return u;let g=Math.max(0,(p?r.start:h)-a),y=Math.max(g,c-a),L=ze(d,u,g),S=ze(d,u,y);return L===S&&p&&u.slice(L,L+r.insert.length)===r.insert?u:u.slice(0,L)+(p?r.insert:"")+u.slice(S)})}function mr(n,e){let t=[0];for(let o of n.parts)t.push(t.at(-1)+o.value.length);let r=t.map(o=>ze(n.value,e,o));return n.parts.map((o,i)=>e.slice(r[i],r[i+1]))}function gr(n,e){let t=0,r=Math.min(n.length,e.length);for(;t<r&&n.charCodeAt(t)===e.charCodeAt(t);)t+=1;let o=0;for(;o<n.length-t&&o<e.length-t&&n.charCodeAt(n.length-o-1)===e.charCodeAt(e.length-o-1);)o+=1;return {start:t,end:n.length-o,insert:e.slice(t,e.length-o)}}function je(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 ge(n){return typeof n=="string"?n:""}function Nt(n,e){return n<e?-1:n>e?1:0}function Ke(n,e){return `${n}${E}${e}`}function yr(n){let e=n.indexOf(E);return e<0?n:n.slice(0,e)}function Dt(n){let e=[];return n.forEach((t,r)=>{!b(t)||m(r)||t.forEach(o=>{if(!b(o))return;let i=ge(o.get("id")),s=ge(o.get("type"));if(i.length===0||s.length===0)return;let a=ge(o.get("ownerPart"))||yr(r);if(m(a))return;let l=o.get("order");e.push({ownerPart:a,id:i,type:s,rawTarget:ge(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||Nt(t.ownerPart,r.ownerPart)||Nt(t.id,r.id)),e}function Bt(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 br(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 _t(n,e){let t=n.childrenSnapshot.get(e);return t||(C(n.nodes.get(e))?.toArray()??[])}function xr(n,e){let t=n.nodes.get(e);return !b(t)||A(t)}function Ir(n,e,t,r){let o=[],i=new Set,s=r,a;for(;;){if(i.has(s)||(i.add(s),xr(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 h=o[u],c=_t(n,d).indexOf(h);if(c<0)return null;l.push(c),d=h;}return l}function Ut(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 h=_t(n,d).indexOf(s);if(h<0)continue;let c=[...u,h];(!a||br(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 Yt(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 h=t.get(u);if(!b(h)||A(h))continue;let c=o.get(u)??C(h)?.toArray()??[];a.add(u),l.push({id:u,parent:null,exit:true});let p=new Set,g=[];for(let y of c)p.has(y)||y===u||(p.add(y),g.push(y));for(let y=g.length-1;y>=0;y-=1)l.push({id:g[y],parent:u,exit:false});}}}function zt(n,e){return `${n}${E}${e}`}function Fe(n,e,t,r,o){if(m(t)||m(r.localName))return;let i=F(n.namespaces,r.namespaceUri,e),s=Be(t,i,r.localName);m(s)||n.attributes.set(s,St(r.prefix??"",o));}function jt(n,e,t,r){n.attributes.delete(Be(e,G(t),r));}function We(n,e,t,r,o){if(m(t)||m(r))return;let i=F(n.namespaces,o,e),s=_e(t,r);m(s)||n.bindings.set(s,i);}function Kt(n,e,t){n.bindings.delete(_e(e,t));}function Ve(n,e,t,r,o,i){let{prefix:s,value:a}=Lt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(zt(r,o),{namespaceUri:q(n.namespaces,r),localName:o,prefix:s.length>0?s:void 0,value:a});}function vr(n,e,t,r){let o=n.get(e);o&&(o.delete(zt(t,r)),o.size===0&&n.delete(e));}function Xe(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:q(n.namespaces,o)});}function Sr(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function Ft(n,e,t){for(let[r,o]of t.changes.keys){let i=Z(String(r));if(!i||m(i.logicalId)||m(i.localName))continue;if(o.action==="delete"){vr(e,i.logicalId,i.namespaceId,i.localName);continue}let s=n.attributes.get(String(r));typeof s=="string"&&Ve(n,e,i.logicalId,i.namespaceId,i.localName,s);}}function Wt(n,e,t){for(let[r,o]of t.changes.keys){let i=Q(String(r));if(!i||m(i.logicalId)||m(i.prefix))continue;if(o.action==="delete"){Sr(e,i.logicalId,i.prefix);continue}let s=n.bindings.get(String(r));typeof s=="string"&&Xe(n,e,i.logicalId,i.prefix,s);}}function X(n){return typeof n=="string"?n:""}function Vt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||m(r))return;let o=X(t.get("rootId"));o.length!==0&&e.push({name:r,id:X(t.get("id")),rootLogicalId:o,contentType:X(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Xt(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(partNameKey(r),t);}),e}function $t(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!m(r)&&e.set(r,t);}),e}function Jt(n){let e=[];return n.forEach((t,r)=>{if(!b(t)||m(r))return;let o=X(t.get("digest")),i=t.get("size"),s=X(t.get("mediaType")),a=X(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 Rr(n){return n.content instanceof O.ContentType}function Gt(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:!Rr(e)}}function wr(n){let e=n._item;return e?Pe(e.id.client,e.id.clock):null}function Zt(n){return typeof n=="string"?n:""}var Y=class{constructor(e,t){this.doc=e;this.schema=It(e),this.limits=ct(t),this.splitDedup=new me(this.schema.nodes,this.limits),this.stopObserving=Bt(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 Gt(this.schema.nodes)}encodeSnapshot(){return O.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return O.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 Zt(this.schema.meta.get("mainDocumentPart"))}record(e){if(m(e))return null;let t=this.schema.nodes.get(e);if(!b(t))return null;if(U(t)){let r=t.get(T),o=r instanceof O.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:wr(t),wordFacingIds:Te(o)}}isTombstoned(e){return A(this.schema.nodes.get(e))}replacedByOf(e){return Ue(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(G(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=>!m(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return m(e)?null:Tt(this.schema.nodes,e)}kindOf(e){return m(e)?null:he(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=F(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Et({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)Fe(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)We(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=F(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(N,De(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Rt(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){jt(this.schema,e,t.namespaceUri,t.localName);return}Fe(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){Kt(this.schema,e,t);return}We(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(_,true),t&&r.set(H,t);}recordRunSplit(e,t,r){this.splitDedup.record(e,t,r);}splitOriginOf(e){return V(this.schema.nodes.get(e))}replacementLoserRuns(){return this.splitDedup.loserRuns({isPresent:e=>je(this,e)})}concurrentSplitTextOverlays(){return this.splitDedup.concurrentTextOverlays(e=>je(this,e))}declinedSplitTangleEvents(){return this.splitDedup.declinedTangleEvents()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?C(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,wt(e.id,e.rootLogicalId,e.contentType));}deleteXmlPart(e){this.partCountCache=-1,this.schema.parts.delete(e);}putRelationship(e){if(m(e.ownerPart)||m(e.id))return;this.relationshipCountCache=-1;let t=new O.Map;t.set(e.id,Ct(e)),this.schema.relationships.set(Ke(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(Ke(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,Ot(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return Dt(this.schema.relationships)}contentTypeOverrides(){return Xt(this.schema.overrides)}contentTypeDefaults(){return $t(this.schema.defaults)}binaries(){return Jt(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 O.Array&&(a=true),l.target instanceof O.Map&&(l.changes.keys.has(_)||l.changes.keys.has(H))&&(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=Z(String(a))??Q(String(a));!l||m(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(m(t))return;let r=C(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)=>{A(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=Z(t);!r||m(r.logicalId)||m(r.localName)||Ve(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||m(t))return;let r=Q(t);!r||m(r.logicalId)||m(r.prefix)||Xe(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&&this.splitDedup.noteChanged(String(r.path[0])),r.path.length===0&&r.target instanceof O.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"||m(String(o)))){this.splitDedup.indexExisting(String(o));for(let s of this.syncChildListings(String(o)))t.add(s);}continue}if(r.target instanceof O.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 O.Map&&r.path.length===1&&(r.changes.keys.has(_)||r.changes.keys.has(H))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,Ft(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,Wt(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?C(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(At(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;Ut({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){Yt({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=Ue(r);if(o!==null){if(A(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 C(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=C(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?C(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=W(Zt(t.get(N))),o=[...this.attributesByNode.get(e)?.values()??[]],i=[...this.bindingsByNode.get(e)?.values()??[]];return {logicalId:e,kind:r.kind,namespaceUri:q(this.schema.namespaces,r.namespaceId),localName:r.localName,prefix:r.prefix.length>0?r.prefix:void 0,attributes:o,bindings:i,childIds:C(t)?.toArray()??[]}}textOf(e){let t=this.require(e).get(T);if(!(t instanceof O.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(ce);if(!(t instanceof O.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 fe=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 Qt(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 en(n){let e=n.binaryPart;return typeof e=="function"?e:null}function tn(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 nn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function Or(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 rn(n,e,t,r,o){if(r>n.limits.maxTreeDepth)return "tree-too-deep";if(m(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(k(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(m(i.localName))return "prototype-key";if(k(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(m(i.prefix))return "prototype-key";if(k(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:Or(e),bindings:kr(e)});for(let i of e.children){let s=rn(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=w(r);if(a)return {ok:false,code:a};if(o.byteLength>M.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await Qt(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 ee(n,e,t=new fe){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=w(a);if(d){o=d;return}if(k(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let u=rn(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=w(l.ownerPart);if(d){o=d;return}}if(m(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(m(a)){o="prototype-key";return}n.putContentTypeDefault(a,l);}for(let[a,l]of e.contentTypes.overrides){let d=w(a);if(d){o=d;return}n.putContentTypeOverride(a,l);}for(let a of r.descriptors)n.putBinary(a);kt(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},yt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var ye=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 on(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 D(n,e){return m(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:n.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function Tr(n,e,t){if(m(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:m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:k(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function Ar(n,e,t){switch(e.kind){case "putNode":return Tr(n,e.descriptor,t);case "spliceText":{let r=D(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=D(t,e.logicalId);return r||(m(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:k(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=D(t,e.logicalId);return r||(m(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&k(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=D(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=D(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=D(t,e.logicalId);if(r)return r;let o=D(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=w(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=D(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=w(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=w(e.owner);if(r)return {ok:false,code:r}}return m(e.record.id)?{ok:false,code:"prototype-key"}:n.relationshipCount()>=n.limits.maxRelationships?{ok:false,code:"too-many-relationships"}:null}case "deleteRelationship":return m(e.relationshipId)?{ok:false,code:"prototype-key"}:null;case "putContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:k(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=w(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=ut(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return m(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function Mr(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 Nr(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function Dr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Nr(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 Br(n,e){let t=new ye(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 h=a.start;h<u;h+=1){let c=d.children[h];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);on(t,a);}return {removed:r,reinserted:o,mintedText:i,replacementsByRemoved:s}}function _r(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function $e(n,e){if(n.nodeCount()+_r(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=Br(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=jr(n,t.removed);for(let o of e.effects)Mr(n,o,t.mintedText);Ur(n,e.effects,t,r),Yr(n,t);},bt),{ok:true})}function Ur(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=Dr(n,i,r,e);s&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,s);}}function Yr(n,e){for(let[t,r]of e.replacementsByRemoved){if(n.kindOf(t)!=="run")continue;let o=zr(n,t,e.reinserted),i=r.filter(s=>n.kindOf(s)==="run");n.recordRunSplit(o,t,i);}}function zr(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 jr(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 xe="http://schemas.openxmlformats.org/package/2006/relationships",Kr="application/vnd.openxmlformats-package.relationships+xml",an=/^(.*)\/_rels\/([^/]*)\.rels$/;function sn(n){return an.test(n)}function ln(n){let e=an.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function te(n,e){return n.attributes.find(t=>t.localName===e)?.value}function be(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Fr(n,e){let t=[be("Id",e.id),be("Type",e.type),be("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(be("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:xe,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function dn(n,e){if(n.kind==="textValue"||n.namespaceUri!==xe||n.localName!=="Relationship"||te(n,"Id")!==e.id||te(n,"Type")!==e.type||te(n,"Target")!==e.rawTarget)return false;let t=te(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function cn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>dn(t,e[r]))}function un(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 pn(n,e,t){let r=[];for(let o of e){if(m(o.id))continue;let i=n.find(a=>a.kind!=="textValue"&&te(a,"Id")===o.id);if(i&&dn(i,o)){r.push(i);continue}let s=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;m(s)||r.push(Fr(s,o));}return r}function Wr(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:xe,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:xe})]),attributes:Object.freeze([]),children:Object.freeze([])})}function hn(n){return Object.freeze({id:n,name:n,contentType:Kr,root:Wr(n)})}function mn(n){let e=new Map;for(let t of n){if(m(t.id)||t.ownerPart!=="/"&&w(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var bn=/^\/customXml\/item(\d+)\.xml$/i,Jr=/^\/customXml\/itemProps(\d+)\.xml$/i;function re(n){return bn.test(n)}function He(n){return Jr.test(n)}function Hr(n){let e=bn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function gn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Gr(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 fn(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 qr(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=Gr(s,"uri",DATASTORE_NAMESPACE_URI);if(a)return a}}return null}function Zr(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&I(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Qr(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:Zr(n,e)}function eo(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function xn(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[c,p]of e){let g=n.record(p.root.id);!g||!I(g)||(re(c)&&t.set(g.logicalId,g),He(c)&&r.set(g.logicalId,g));}for(let c of n.allLogicalIds()){if(n.isTombstoned(c)||t.has(c)||r.has(c))continue;let p=n.record(c);!p||!I(p)||(Qr(n,p)?t.set(c,p):eo(n,p)&&r.set(c,p));}if(t.size===0)return [];let o=new Map;for(let c of t.values()){let p=o.get(c.namespaceUri)??[];p.push(c),o.set(c.namespaceUri,p);}let i=new Map;for(let c of r.values()){let p=qr(n,c.logicalId);if(!p)continue;let g=i.get(p)??[];g.push(c),i.set(p,g);}let s=[];for(let[c,p]of o){let g=i.get(c);if(!g||g.length===0)continue;p.sort((v,R)=>v.logicalId.localeCompare(R.logicalId)),g.sort((v,R)=>v.logicalId.localeCompare(R.logicalId));let y=p[0],L=g[0],S=[],x=new Set;for(let v of p)for(let R of v.childIds){if(x.has(R))continue;let le=n.record(R);!le||!I(le)||le.localName!=="node"||le.namespaceUri!==c||(x.add(R),S.push(R));}for(let v of n.allLogicalIds()){if(x.has(v)||n.isTombstoned(v))continue;let R=n.record(v);!R||!I(R)||R.localName!=="node"||R.namespaceUri!==c||(x.add(v),S.push(v));}S.sort((v,R)=>fn(n,v).localeCompare(fn(n,R))),s.push({data:y,props:L,nodeIds:S});}s.sort((c,p)=>c.data.logicalId.localeCompare(p.data.logicalId));let a=new Set,l=[],d=new Set,u=new Set;for(let[c,p]of e){let g=Hr(c);if(g===null)continue;let y=s.find(x=>x.data.logicalId===p.root.id&&!d.has(x.data.logicalId));if(!y)continue;let L=gn(g).props,S=e.get(L);S&&S.root.id!==y.props.logicalId||(a.add(g),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:L,nodeIds:y.nodeIds}));}let h=1;for(let c of s){if(d.has(c.data.logicalId))continue;for(;a.has(h);)h+=1;a.add(h);let p=gn(h);l.push({dataRootId:c.data.logicalId,propsRootId:c.props.logicalId,namespaceUri:c.data.namespaceUri,itemName:p.item,propsName:p.props,nodeIds:c.nodeIds}),h+=1;}return l.sort((c,p)=>c.itemName.localeCompare(p.itemName)),l}function to(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:re(n.ownerPart)}function no(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function ro(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,no(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:ro(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 vn(n,e){return e.length===0?[...n]:[...n.filter(t=>!to(t)),...e]}function Sn(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function Ge(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(re).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 Ln(n,e){if(Ge(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 oo="http://schemas.microsoft.com/office/word/2012/wordml";function Ie(n,e){return n.attributes.find(t=>t.localName===e)?.value}function ve(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 io(n){return n.localName==="abstractNum"?`0${ve(Ie(n,"abstractNumId"))}`:`1${ve(Ie(n,"numId"))}`}function ao(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Rn(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===oo,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:En("footnote"),sortKey:e=>ve(Ie(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:En("endnote"),sortKey:e=>ve(Ie(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:ao,sortKey:io}:null}function so(n,e){return n.attributes.find(t=>t.localName===e)?.value}function qe(n){return n.kind==="textValue"?n.id:so(n,"id")??n.id}function $(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 On(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:$(t.children,e)});return Object.freeze({...n,root:r})}function lo(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 Tn(n){}function Mn(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function go(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 fo(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 Se(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&&go(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&fo(r,n)?r.attributes:Object.freeze(n.attributes.map(lo)),children:e})}function Nn(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 Ze(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)Ze(o,e)||(r=false);return r}function Dn(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 Le=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:vn(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:mn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:xo(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;Tn(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 xo(n){let e=buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var Ee=class{lastLosers=new Set;textOverlays=new Map;losers=new Set;update(e){let t=[],r=e.replacementLoserRuns(),o=s=>{let a=e.parentOf(s);a!==null&&t.push(a);};for(let s of r)this.lastLosers.has(s)||o(s);for(let s of this.lastLosers)r.has(s)||o(s);this.lastLosers=r,this.losers=r;let i=e.concurrentSplitTextOverlays();return this.textOverlays=i.values,t.push(...i.changedIds),t}textValue(e,t){return this.textOverlays.get(e)??t}};function So(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 z=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Le(e),this.stop=e.observeDirty(r=>{for(let o of r.logicalIds)this.pendingDirty.add(o);r.membershipChanged&&(this.pendingMembership=true),r.packageChanged&&(this.pendingPackage=true);});}registry;blobs;cache=new Map;heights=new Map;partCache=new Map;packageCache;relsProjection=new Map;pendingDirty=new Set;pendingMembership=false;pendingPackage=false;lastDirty=new Set;lastAdoption=new Map;placementContested=false;splitProjection=new Ee;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let u of this.adoptionChanges())e.add(u);for(let u of this.splitProjection.update(this.registry))e.add(u);let o=Dn(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:So(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,h=this.materialize(d.rootLogicalId,o,u,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let c=this.partCache.get(d.name);if(c&&c.root===h&&c.contentType===d.contentType){i.set(d.name,c);continue}let p=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,p),this.partCache.set(d.name,p);}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?Ze(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.splitProjection.textValue(e,i.value),p=this.cache.get(e);if(p?.kind==="textValue"&&p.value===c)return p;let g=Mn(e,c);return this.remember(e,g),g}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.splitProjection.losers.has(c)){t.add(c);continue}if(m(c)||!this.registry.hasNode(c)){this.push("child-id-not-in-registry",c);continue}if(!this.claimsWholeSubtrees){let g=this.registry.listingParents(c);g.length>1&&(this.placementContested=true,this.contestEncountered.add(c),g.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 p=this.materialize(c,t,r,o);p&&l.push(p);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((c,p)=>c===l[p])&&Nn(d,i))return d;let u=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(u,l);let h=Se(i,$(u,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let s=relsPartNameFor(o);if(s!=="/_rels/.rels"&&w(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)||!sn(o))continue;let s=ln(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||un(o.root,t.root))&&o?o:t??hn(e);if(cn(s.root,r))return this.relsProjection.set(e,s),s;let a=s.root.children,l=On(s,pn(a,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[s,a]of e){let l=Rn(a.root);if(!l)continue;let d=x=>x.logicalId!==a.root.id&&l.isMember(x),u=[],h=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),h.add(x.id));}if(this.adoptLooseMembers(u,h,d,t,r,o,i)===0)continue;u.sort((x,v)=>l.sortKey(x).localeCompare(l.sortKey(v)));let p=[];for(let x of a.root.children)h.has(x.id)||p.push(x);let g=$(a.root.children,[...p,...u]);if(g===a.root.children)continue;let y=this.registry.record(a.root.id);if(!y||!I(y))continue;let L=Se(y,g,a.root);this.remember(a.root.id,L);let S=Object.freeze({...a,root:L});e.set(s,S),this.partCache.set(s,S);}}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 h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),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(p=>p.id)),d=0;for(let p of t){if(l.has(p))continue;let g=this.materializeOnce(p,r,o);!g||g.kind==="textValue"||(a.push(g),l.add(p),d+=1);}if(a.sort((p,g)=>qe(p).localeCompare(qe(g))),d===0&&a.every((p,g)=>p===s.children[g]))return s;let u=this.registry.record(e);if(!u||!I(u))return s;let h=$(s.children,a),c=Se(u,h,s);return this.remember(e,c),c}applyCustomXmlStores(e,t,r){let o=xn(this.registry,e);if(o.length===0||!Ln(e,o))return;let i=Ge(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}),h=Object.freeze({id:a.propsName,name:a.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(a.itemName,u),e.set(a.propsName,h),this.partCache.set(a.itemName,u),this.partCache.set(a.propsName,h);}if(i){for(let a of [...e.keys()])!re(a)&&!He(a)||s.has(a)||(e.delete(a),this.partCache.delete(a));this.customXmlRels=In(this.registry,o),this.customXmlOverrides=Sn(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 f=class extends Error{constructor(t,r){super(r?`${t}: ${r}`:t);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};var we=64*1024*1024,ie="docx-package-blobs-v1";function Ro(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 wo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function Re(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var j=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=Ro(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+=wo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>we)throw new f("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 ae(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return Re("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return Re("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(a=>{i+=a instanceof O.Map?a.size:0;}),i>t.maxRelationships)return Re("too-many-relationships",`${i}`);let s=e.totalByteLength();return s>we?Re("blob-store-full",`${s}`):null}var _n=20*1024*1024,et=3e4,Po=4e3,To=1500,Ao="docx-collaboration-seeds-v1",Qe="docxEditorSeedCandidate",Mo=/^[0-9a-f]{16}$/,No=256;function tt(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new f("invalid-baseline");if(n.byteLength>_n)throw new f("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:_n,maxRatio:200}});if(!e.ok)throw new f("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new f("no-main-document-part");return new TreePackageStore(e.package,normalizeParagraphIdentity(t)).currentPackage()}function Do(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function se(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Do(n,e),s=()=>{let l=e.poisonedDigest();return l?new f("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let a=s();return a?Promise.reject(a):r?.aborted?Promise.reject(new f("initialization-aborted")):new Promise((l,d)=>{let u=g=>{clearTimeout(p),o.unobserve(h),n.doc.off("afterTransaction",h),r?.removeEventListener("abort",c),g?d(g):l();},h=()=>{let g=s();if(g){u(g);return}i()&&u();},c=()=>u(new f("initialization-aborted")),p=setTimeout(()=>u(new f("initialization-timeout")),t);o.observe(h),n.doc.on("afterTransaction",h),r?.addEventListener("abort",c,{once:true});})}function nt(n){return n.getArray(Ao)}function Ce(n){return nt(n).length}function Yn(n,e){let t=nt(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Bo(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function _o(n,e){let t=[...n.getStates().entries()].slice(0,No);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Qe];if(!(typeof i!="string"||!Mo.test(i))&&i<e)return true}return false}async function Un(n,e,t,r){try{return await se(n,e,t,r),!0}catch(o){if(o instanceof f&&o.code==="initialization-timeout")return false;throw o}}function Uo(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new f("initialization-aborted")):new Promise((i,s)=>{let a=h=>{clearTimeout(u),r.unobserve(l),t?.removeEventListener("abort",d),h?s(h):i();},l=()=>{o()&&a();},d=()=>a(new f("initialization-aborted")),u=setTimeout(()=>a(new f("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function zn(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??Po,s=n.electionWindowMs??To,a=n.timeoutMs??et,l=async()=>(await Uo(r,a,n.signal),"joined");if(await Un(r,o,i,n.signal))return l();let d=Bo();t.setLocalStateField(Qe,d);try{let u=await Un(r,o,s,n.signal);if(!u&&_o(t,d)&&(await se(r,o,a,n.signal),u=!0),u)return await l();if(r.schema.meta.get("initialized")===!0)return await se(r,o,a,n.signal),await l();let h=await ee(r,tt(n.document),o);if(!h.ok)throw new f(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),nt(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Qe,null);}}var Oe=class{constructor(e,t){this.knows=e;this.allocator=new J(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 Yo(n){let e=0;return n.schema.nodes.forEach(t=>{b(t)&&t.get(_)===true&&(e+=1);}),e}function zo(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof O.Map?t.size:0;}),e}function Kn(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:Yo(n),maxNodes:n.limits.maxNodes,relationships:zo(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:we})}var ke="docxEditor",B=256,rt=256;function Wn(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>B||t.length===0||t.length>B)throw new f("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new f("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function Vn(n){let e=n.trim();if(e.length===0||e.length>B)throw new f("invalid-document-id");return e}function Xn(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>B)throw new f("invalid-session-id");return e}function Fn(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 Ko(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=Fn(e.anchor),r=Fn(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 ot(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>B||typeof e.name!="string"||e.name.length===0||e.name.length>B)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=Ko(e.selection);return i?{...o,selection:i}:o}function Wo(n){let e=new Y(n),t=null;try{if(e.rebuildDerivedIndexes(),typeof e.schema.meta.get("documentId")!="string")throw new f("not-initialized");if(Ce(n)>1)throw new f("concurrent-seed");let r=new j(n.getMap(ie)),o=ae(e,r);if(o)throw new f(o.code,o.detail);t=new z(e,r);let i=t.current(),s=r.poisonedDigest();if(s)throw new f("blob-digest-mismatch",s);if(!i.ok)throw new f(i.code);return writeOoxmlPackage(i.package)}finally{t?.destroy(),e.destroy();}}var Ho=3,Go=5e3,qo=2e3,Zo=Symbol("createDocumentCollaboration.attachWatchdogMs"),it=class{constructor(e,t,r,o,i,s,a,l,d,u,h){this.ydoc=e;this.awareness=t;this.registry=s;this.materializer=a;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new O.UndoManager([...s.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Go,deleteFilter:s.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(c=>{let p=d.verifyNow(c);p&&this.setStatus("error","blob-digest-mismatch",p);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=Yn(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 Kn(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,rt);for(let[r,o]of t){let i=ot(o[ke]);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,rt),o=[];for(let[i,s]of r){if(i===this.awareness.clientID)continue;let a=ot(s[ke]);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>B)throw new f("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new f("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=$e(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=tn(e.effects,en(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{nn(this.blobs,e);}catch(t){return t instanceof f?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<Ho&&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=ae(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=xt(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 f?t.code:"remote-apply-failed",t instanceof f?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(ke,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 bs(n){let e=n[Zo]??qo,t=Vn(n.documentId),r=Xn(n.sessionId),o=Wn(n.identity),i=new Y(n.ydoc);try{return await Qo(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(s){throw i.destroy(),s}}async function Qo(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:s}=e,a=new Oe(h=>s.hasNode(h)),l=new j(n.ydoc.getMap(ie));if(n.bootstrap.kind==="create"){if(s.schema.meta.get("initialized")===true)throw new f("already-initialized");let h=await ee(s,tt(n.bootstrap.document),l);if(!h.ok)throw new f(h.code);n.ydoc.transact(()=>{s.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await zn({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 f("document-id-mismatch");s.rebuildDerivedIndexes();}}else {if(await se(s,l,n.bootstrap.timeoutMs??et,n.bootstrap.signal),s.schema.meta.get("documentId")!==r)throw new f("document-id-mismatch");s.rebuildDerivedIndexes();}if(Ce(n.ydoc)>1)throw new f("concurrent-seed");let d=ae(s,l);if(d)throw new f(d.code,d.detail);let u=new z(s,l);try{let h=u.current(),c=l.poisonedDigest();if(c)throw new f("blob-digest-mismatch",c);if(!h.ok)throw new f(h.code);let p=writeOoxmlPackage(h.package),g=new it(n.ydoc,n.awareness,r,o,i,s,u,a,l,t,n.offlineEditing===!0);return Object.freeze({document:p,session:g,destroy:()=>g.destroy()})}catch(h){throw u.destroy(),h}}export{f as a,Wo as b,Zo as c,bs as d};
|