@docx-editor.dev/pro 2.18.0 → 2.19.1
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-5Q7TAD56.cjs +4 -0
- package/dist/chunk-DK2U6X6K.cjs +4 -0
- package/dist/chunk-SHLNDIAG.js +4 -0
- package/dist/chunk-VQDG6RPV.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.js +1 -1
- package/dist/collaboration/webrtc.cjs +1 -1
- package/dist/collaboration/webrtc.js +1 -1
- package/dist/document-session-7GYS3IV6.js +1 -0
- package/dist/document-session-RA4IXYFO.js +1 -0
- package/dist/document-session-SDHJEHPD.cjs +1 -0
- package/dist/document-session-WQSA3YUO.cjs +1 -0
- package/dist/{hocuspocus-KOLAIT7T.cjs → hocuspocus-FGTZRYYI.cjs} +1 -1
- package/dist/{hocuspocus-ZBQCCO4G.js → hocuspocus-GJOYS5IH.js} +1 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.js +1 -1
- package/dist/vue/hocuspocus.cjs +1 -1
- package/dist/vue/hocuspocus.js +1 -1
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.js +1 -1
- package/dist/vue/webrtc.cjs +1 -1
- package/dist/vue/webrtc.js +1 -1
- package/dist/{webrtc-CUEMY3DZ.js → webrtc-HCNKEL2L.js} +1 -1
- package/dist/{webrtc-6HVF33UP.cjs → webrtc-KSMRT7P7.cjs} +1 -1
- package/package.json +4 -4
- package/dist/chunk-4NIIGM6D.cjs +0 -4
- package/dist/chunk-EFCL3VQI.cjs +0 -4
- package/dist/chunk-HMTYXNMO.js +0 -4
- package/dist/chunk-OZT67MLG.js +0 -4
- package/dist/document-session-HHDGRM4Z.js +0 -1
- package/dist/document-session-I2C7MA6E.cjs +0 -1
- package/dist/document-session-OXC3PO7A.js +0 -1
- package/dist/document-session-U4VGKQYC.cjs +0 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var x=require('yjs'),store=require('@docx-editor.dev/core/store');require('@docx-editor.dev/core/collaboration/replication');var collaboration=require('@docx-editor.dev/core/collaboration'),layout=require('@docx-editor.dev/core/layout');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var x__namespace=/*#__PURE__*/_interopNamespace(x);var Je=new WeakMap;function oe(n){return Je.get(n)}var Y=Object.freeze({maxNodes:2e5,maxTreeDepth:256,maxTextLength:1048576,maxAttributes:4096,maxChildren:1e5,maxParts:512,maxRelationships:1e4,maxBlobBytes:32*1024*1024,maxDigestLength:80,maxMediaTypeLength:256,maxStorageKeyLength:512,maxStringLength:4096}),gr=/^sha256:[0-9a-f]{64}$/;function Lt(n){return n?Object.freeze({...Y,...n}):Y}function g(n){return store.isDangerousKey(n)?"prototype-key":null}function A(n,e){return typeof n!="string"||n.length>e?"invalid-string":store.isDangerousKey(n)?"prototype-key":null}function O(n){let e=g(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=store.normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function wt(n){for(let e of Object.keys(n)){let t=g(e);if(t)return t}return !gr.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>Y.maxBlobBytes?"blob-too-large":A(n.mediaType,Y.maxMediaTypeLength)||n.mediaType.length===0||A(n.storageKey,Y.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var yr="https://www.docx-editor.dev/docs/latest/pro/collaboration-versions",y=class extends Error{constructor(t,r){let o=t==="collaboration-format-mismatch"||t==="protocol-version-mismatch"||t==="schema-version-mismatch",i=r?`${t}: ${r}`:t;super(o?`${i}
|
|
2
|
+
Collaboration upgrade required. Save local changes and use a compatible app version, or upgrade the saved room. See ${yr}`:i);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};var F=Object.freeze({protocolVersion:1,sharedSchemaVersion:3,repairVersion:1,canonicalModelVersion:1});function Ct(n){let e=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{};for(let t of Object.keys(F)){let r=F[t],o=Object.hasOwn(e,t)?e[t]:void 0;if(o===r)continue;let i=o===void 0?"missing":typeof o=="number"&&Number.isSafeInteger(o)?String(o):"invalid";return {code:t==="protocolVersion"?"protocol-version-mismatch":"schema-version-mismatch",detail:`${t}: expected ${r}, received ${i}`}}return null}var br=F.protocolVersion,xr=F.sharedSchemaVersion,Ir=F.repairVersion,vr=F.canonicalModelVersion,Sr="docx-package-meta-v1",We="docx-package-nodes-v1",Er="docx-package-parts-v1",Rr="docx-package-rels-v1",Lr="docx-package-overrides-v1",wr="docx-package-defaults-v1",Cr="docx-package-binaries-v1",kr="docx-package-namespaces-v1",Pr="docx-package-attributes-v1",Or="docx-package-bindings-v1",Ie="s",ve="b",M="t",Se="children",U="deleted",X="replacedBy",$e="splitFrom",ie="splitLineage";var P="",kt="-",Pt=Object.freeze({kind:"docx-package-bootstrap"}),Ot=Object.freeze({kind:"docx-package-journal"});function H(n){return n.kind==="textValue"}function L(n){return !H(n)}var Ar=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),Tr=200;function Ee(n){let e=new Map;for(let t of n)Ar.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,Tr)}function At(n){return {meta:n.getMap(Sr),nodes:n.getMap(We),parts:n.getMap(Er),relationships:n.getMap(Rr),overrides:n.getMap(Lr),defaults:n.getMap(wr),binaries:n.getMap(Cr),namespaces:n.getMap(kr),attributes:n.getMap(Pr),bindings:n.getMap(Or)}}var Tt=[["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"]],Nr=new Map(Tt),Mr=new Map(Tt.map(([n,e])=>[e,n]));function Dr(n){let e=0xcbf29ce484222325n,t=0x100000001b3n;for(let r=0;r<n.length;r+=1)e^=BigInt(n.charCodeAt(r)),e=e*t&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function ae(n){return n.length===0?kt:Nr.get(n)??`n${Dr(n)}`}function G(n,e,t){let r=ae(e);return e.length===0||g(r)||A(e,t)||n.get(r)!==e&&n.set(r,e),r}function se(n,e){if(e===kt||g(e))return "";let t=n.get(e);return typeof t=="string"?t:Mr.get(e)??""}function Xe(n,e,t,r){return `${n}${P}${e}${P}${t}${P}${r}`}function Br(n){let e=n.split(P);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function He(n){let e=n.has(Ie)?n.get(Ie):n.get(ve);return Br(typeof e=="string"?e:"")}function Ge(n,e,t){return `${n}${P}${e}${P}${t}`}function q(n){let e=n.split(P);if(e.length!==3)return null;let t=e[0],r=e[1],o=e[2];return t.length===0||o.length===0?null:{logicalId:t,namespaceId:r,localName:o}}function qe(n,e){return `${n}${P}${e}`}function Z(n){let e=n.split(P);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function Nt(n,e){return `${n}${P}${e}`}function Mt(n){let e=n.indexOf(P);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Dt(n){let e=new x__namespace.Map,t=Xe(n.kind,n.namespaceId,n.localName,n.prefix??"");e.set(ve,t);let r=new x__namespace.Array;return n.childIds&&n.childIds.length>0&&r.push([...n.childIds]),e.set(Se,r),e}function Re(n){let e=new x__namespace.Map;return e.set(M,new x__namespace.Text(n)),e}function Bt(n,e,t){let r=new x__namespace.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function _t(n){let e=new x__namespace.Map;return e.set("ownerPart",n.ownerPart),e.set("id",n.id),e.set("type",n.type),e.set("rawTarget",n.rawTarget),e.set("targetMode",n.targetMode),e.set("order",n.order),e}function Yt(n){let e=new x__namespace.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Q(n){return Ct({protocolVersion:n.get("protocolVersion"),sharedSchemaVersion:n.get("sharedSchemaVersion"),repairVersion:n.get("repairVersion"),canonicalModelVersion:n.get("canonicalModelVersion")})}function Ut(n){n.set("protocolVersion",br),n.set("sharedSchemaVersion",xr),n.set("repairVersion",Ir),n.set("canonicalModelVersion",vr),n.set("initialized",true);}function S(n){return n instanceof x__namespace.Map}function D(n){if(!S(n))return null;let e=n.get(Se);return e instanceof x__namespace.Array?e:null}function le(n){return S(n)&&n.get(M)instanceof x__namespace.Text}function K(n){return S(n)&&n.get(U)===true}function Ze(n){if(!S(n))return null;let e=n.get(X);return typeof e=="string"&&e.length>0?e:null}function de(n){if(!S(n))return null;let e=n.get($e);return typeof e=="string"&&e.length>0?e:null}function Qe(n){if(!S(n))return null;let e=n.get(ie);return typeof e=="string"&&e.length>0?e:de(n)}function zt(n,e){let t=[],r=[{id:e,depth:0}],o=new Set,i=0;for(;r.length>0;){let{id:a,depth:s}=r.pop();if(o.has(a)||s>n.limits.maxTreeDepth)return null;o.add(a);let l=n.record(a);if(!l)return null;if(H(l)){let d=n.projectedTextValue(a)??l.value;if(i+=d.length,i>n.limits.maxTextLength)return null;t.push({id:a,value:d});}else if(L(l)&&!l.kind.endsWith("Properties"))for(let d=l.childIds.length-1;d>=0;d-=1)r.push({id:l.childIds[d],depth:s+1});}return t}function Le(n,e,t){let r=zt(n,e),o=[];if(!r||r.length===0)return;for(let l of t){let d=zt(n,l);if(!d)return;for(let p of d)o.push(p);}if(r.map(l=>l.value).join("")!==o.map(l=>l.value).join(""))return;let i=[],a=0,s=0;for(let l of o){for(;a<r.length-1&&s===r[a].value.length;)a+=1,s=0;let d=r[a];if(!d||s+l.value.length>d.value.length)return;l.id!==d.id&&i.push({product:l.id,source:d.id,start:s,end:s+l.value.length}),s+=l.value.length;}for(let l of i)n.registerSplitText(l.product,l.source,l.start,l.end);}var V=class{constructor(e){this.registry=e;}registry;touched=new Map;created=new Set;has(e){return this.created.has(e)||this.touched.has(e)||this.registry.hasNode(e)}node(e){let t=this.touched.get(e);if(t)return t;let r=this.registry.nodeShape(e);return r?(this.touched.set(e,r),r):null}putNode(e){this.node(e.logicalId)||(this.created.add(e.logicalId),this.touched.set(e.logicalId,{isText:e.kind==="textValue",textLength:0,children:[]}));}spliceText(e,t,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-t)+r);}spliceChildren(e,t,r,o){let i=this.node(e);i&&i.children.splice(t,r,...o);}moveNode(e,t,r){let o=this.parentOf(e);if(o!==null){let s=this.node(o),l=s?.children.indexOf(e)??-1;s&&l>=0&&s.children.splice(l,1);}let i=this.node(t);if(!i)return;let a=Math.min(r,i.children.length);i.children.splice(a,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function ce(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 z(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 _r(n,e,t){if(g(e.logicalId)||e.logicalId.length===0)return {ok:false,code:"invalid-logical-id",detail:e.logicalId};let r=t.node(e.logicalId);return r&&r.isText!==(e.kind==="textValue")?{ok:false,code:"invalid-bound",detail:`node class ${e.logicalId}`}:e.kind==="textValue"?null:g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function we(n,e,t){switch(e.kind){case "putNode":return _r(n,e.descriptor,t);case "spliceText":{let r=z(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=z(t,e.logicalId);return r||(g(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>n.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=z(t,e.logicalId);return r||(g(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&A(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=z(t,e.parentLogicalId);if(r)return r;if(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.deleteCount)||e.start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let a=z(t,i);if(a)return a}let o=t.node(e.parentLogicalId);if(o&&!o.isText){if(e.start+e.deleteCount>o.children.length)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};if(o.children.length-e.deleteCount+e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};return null}case "moveNode":{let r=z(t,e.logicalId);if(r)return r;let o=z(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=O(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=z(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=O(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=O(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=O(e.partName);return r?{ok:false,code:r}:A(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=O(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=wt(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 Yr(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;let r=oe(e);n.spliceText(r?.logicalId??e.logicalId,r?.utf16Start??e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":n.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":n.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":n.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":n.deleteXmlPart(e.name);return;case "putRelationship":n.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":n.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":n.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":n.deleteContentTypeOverride(e.partName);return;case "putBinary":n.putBinary(e.descriptor);return;case "deleteBinary":n.deleteBinary(e.storageKey);return}}function Ur(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function zr(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>Ur(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(a=>o.has(a)))return i.parentLogicalId}}function jr(n,e){let t=new V(n),r=[],o=new Set,i=new Set,a=new Set,s=new Map;for(let l of e){let d=we(n,l,t);if(d)return d;if(l.kind==="spliceChildren"){let p=l.deleteCount>0?t.node(l.parentLogicalId):null;if(p&&!p.isText){let h=l.start+l.deleteCount;for(let u=l.start;u<h;u+=1){let m=p.children[u];if(m!==void 0&&(r.push(m),l.childLogicalIds.length>0)){let c=s.get(l)??[];c.push(m),s.set(l,c);}}}for(let h of l.childLogicalIds)o.add(h);}else l.kind==="moveNode"?o.add(l.logicalId):l.kind==="putNode"&&(a.add(l.descriptor.logicalId),l.descriptor.kind==="textValue"&&i.add(l.descriptor.logicalId));ce(t,l);}return {removed:r,reinserted:o,mintedText:i,mintedNodes:a,replacementsByEffect:s}}function Fr(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function et(n,e){if(n.nodeCount()+Fr(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=jr(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=Wr(n,t.removed);for(let o of e.effects)Yr(n,o,t.mintedText),o.kind==="spliceChildren"&&Vr(n,t,t.replacementsByEffect.get(o)??[],o.childLogicalIds);Kr(n,e.effects,t,r);},Ot),{ok:true})}function Kr(n,e,t,r){if(t.removed.length===0)return;let o=new Set;for(let i of n.partEntries())o.add(i.rootLogicalId);for(let i of t.removed){if(t.reinserted.has(i)||!n.hasNode(i)||n.isTombstoned(i)||o.has(i))continue;let a=zr(n,i,r,e);a&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,a);}}function Vr(n,e,t,r){for(let o of t){if(n.kindOf(o)!=="run"||e.reinserted.has(o)&&!e.mintedNodes.has(o))continue;let i=Jr(n,o,e.reinserted),a=r.filter(s=>n.kindOf(s)==="run");Le(n,o,a),n.recordRunSplit(i,o,a);}}function Jr(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 Wr(n,e){let t=new Map;for(let r of e){let o=n.nodeShape(r);o&&!o.isText&&t.set(r,o.children);}return t}var B="splitTextSource",$r=Object.freeze({kind:"docx-package-restored-split-anchors"});function T(n,e){throw new y(n,e)}function tt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function jt(n){return tt(n)&&Object.keys(n).every(e=>e==="client"||e==="clock")&&Number.isSafeInteger(n.client)&&n.client>=0&&Number.isSafeInteger(n.clock)&&n.clock>=0}function Ft(n){return !tt(n)||!Object.keys(n).every(e=>["type","item","assoc"].includes(e))||!jt(n.type)||n.item!==void 0&&!jt(n.item)||n.assoc!==0&&n.assoc!==-1?T("invalid-string",B):x__namespace.createRelativePositionFromJSON(n)}var ee=class{constructor(e,t,r){this.nodes=e;this.doc=t;this.limits=r;}nodes;doc;limits;sourceByAlias=new Map;aliasesBySource=new Map;pending=new Set;values=new Map;register(e,t,r,o){let i=this.nodes.get(e);(!S(i)||!(i.get(M)instanceof x__namespace.Text))&&T("invalid-bound",e);let a=this.read(t),s=a===null?{sourceId:t,text:this.sourceText(t),start:0,end:this.sourceText(t).length}:this.resolve(a);(s.sourceId.length===0||s.sourceId.length>this.limits.maxStringLength||g(s.sourceId))&&T("invalid-string",t),(!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||r<0||o<r||o>s.end-s.start||e===s.sourceId)&&T("invalid-bound",e);let l=(p,h)=>{if(a&&h==="end"&&p===s.end-s.start)return a.end;if(a&&p===0)return a.start;if(a&&p===s.end-s.start)return a.end;let u=s.start+p;return x__namespace.createRelativePositionFromTypeIndex(s.text,u,u===0&&h==="start"?-1:0)},d=JSON.stringify({sourceId:s.sourceId,start:x__namespace.relativePositionToJSON(l(r,"start")),end:x__namespace.relativePositionToJSON(l(o,"end"))});d.length>this.limits.maxStringLength&&T("invalid-string",e),i.set(B,d),this.indexExisting(e);}normalizeRestoredAnchors(){let e=new Map,t=o=>{let i=o.item;if(i===null)return o;let a=`${i.client}:${i.clock}:${o.assoc}`,s=e.get(a);if(s)return s;let l=i,d=x__namespace.getItem(this.doc.store,l);for(;d instanceof x__namespace.Item&&d.redone!==null;)l=x__namespace.createID(d.redone.client,d.redone.clock+l.clock-d.id.clock),d=x__namespace.getItem(this.doc.store,l);let p=d instanceof x__namespace.Item&&!d.deleted&&!x__namespace.compareIDs(i,l)?x__namespace.createRelativePositionFromJSON({...x__namespace.relativePositionToJSON(o),item:{client:l.client,clock:l.clock}}):o;return e.set(a,p),p},r=[];for(let o of this.sourceByAlias.keys()){let i=this.read(o);if(!i)continue;let a=t(i.start),s=t(i.end);if(x__namespace.compareRelativePositions(a,i.start)&&x__namespace.compareRelativePositions(s,i.end))continue;let l=JSON.stringify({sourceId:i.sourceId,start:x__namespace.relativePositionToJSON(a),end:x__namespace.relativePositionToJSON(s)});l.length>this.limits.maxStringLength&&T("invalid-string",o),r.push({id:o,encoded:l});}r.length!==0&&this.doc.transact(()=>{for(let{id:o,encoded:i}of r)this.nodes.get(o).set(B,i),this.indexExisting(o);},$r);}sourceAliases(e){return [...this.aliasesBySource.get(e)??[]]}range(e){let t=this.read(e);return t===null?null:this.resolve(t)}value(e){let t=this.range(e);return t===null?null:t.text.toString().slice(t.start,t.end)}indexExisting(e){let t=this.read(e);t&&this.resolve(t);let r=this.sourceByAlias.get(e);if(r!==void 0&&r!==t?.sourceId){let o=this.aliasesBySource.get(r);o?.delete(e),o?.size===0&&this.aliasesBySource.delete(r),this.sourceByAlias.delete(e);}if(t){this.sourceByAlias.set(e,t.sourceId);let o=this.aliasesBySource.get(t.sourceId)??new Set;o.add(e),this.aliasesBySource.set(t.sourceId,o);}(t||r!==void 0||this.values.has(e))&&this.pending.add(e);}noteChanged(e){this.indexExisting(e);for(let t of this.aliasesBySource.get(e)??[])this.pending.add(t);}reset(){this.sourceByAlias.clear(),this.aliasesBySource.clear();for(let e of this.values.keys())this.pending.add(e);this.nodes.forEach((e,t)=>this.indexExisting(t));}overlays(){let e=new Set,t=new Map;for(let r of this.pending){let o=this.range(r),i=null;if(o){let a=t.get(o.sourceId);a===void 0&&(a=o.text.toString(),t.set(o.sourceId,a)),i=a.slice(o.start,o.end);}i===null?this.values.delete(r)&&e.add(r):i!==this.values.get(r)&&(this.values.set(r,i),e.add(r));}return this.pending.clear(),{values:this.values,changedIds:e}}sourceText(e){let t=this.nodes.get(e),r=S(t)?t.get(M):null;return !(r instanceof x__namespace.Text)||r.doc!==this.doc||r.length>this.limits.maxTextLength?T("invalid-bound",e):r}read(e){let t=this.nodes.get(e);if(!S(t)||!t.has(B))return null;let r=t.get(B);if(typeof r!="string"||r.length>this.limits.maxStringLength)return T("invalid-string",e);let o;try{o=JSON.parse(r);}catch{return T("invalid-string",e)}return !tt(o)||!Object.keys(o).every(i=>["sourceId","start","end"].includes(i))||typeof o.sourceId!="string"||o.sourceId.length===0||o.sourceId.length>this.limits.maxStringLength||g(o.sourceId)||o.sourceId===e?T("invalid-string",e):t.get(M)instanceof x__namespace.Text?{sourceId:o.sourceId,start:Ft(o.start),end:Ft(o.end)}:T("invalid-bound",e)}resolve(e){let t=this.nodes.get(e.sourceId);if(S(t)&&t.has(B))return T("invalid-bound",e.sourceId);let r=this.sourceText(e.sourceId),o=x__namespace.createRelativePositionFromTypeIndex(r,0).type;if(!o||[e.start,e.end].some(s=>s.type?.client!==o.client||s.type?.clock!==o.clock))return T("invalid-bound",e.sourceId);let i=x__namespace.createAbsolutePositionFromRelativePosition(e.start,this.doc,false),a=x__namespace.createAbsolutePositionFromRelativePosition(e.end,this.doc,false);return i===null||a===null||i.type!==r||a.type!==r||i.index<0||a.index<i.index||a.index>r.length?T("invalid-bound",e.sourceId):{sourceId:e.sourceId,text:r,start:i.index,end:a.index,startAssoc:e.start.assoc,endAssoc:e.end.assoc,startAnchorDeleted:e.start.item!==null&&x__namespace.getItem(this.doc.store,e.start.item).deleted,endAnchorDeleted:e.end.item!==null&&x__namespace.getItem(this.doc.store,e.end.item).deleted}}};function Ce(n,e,t,r,o,i){if(!r||i.length===0)return null;let a=o===0&&r.startAssoc!==-1,s=o===r.end-r.start;if(!a&&!s)return null;let l=JSON.parse(n.get(t).get(B)),d=x__namespace.createRelativePositionFromJSON(l.start),p=x__namespace.createRelativePositionFromJSON(l.end);if(s=s&&(a||p.item!==null&&x__namespace.getItem(r.text.doc.store,p.item).deleted),!a&&!s)return null;let h=[];for(let u of e.sourceAliases(r.sourceId)){if(!e.range(u))continue;let m=n.get(u),c=JSON.parse(m.get(B)),f=(R,E)=>{let v=x__namespace.createRelativePositionFromJSON(R);return a&&s&&x__namespace.compareRelativePositions(d,p)&&x__namespace.compareRelativePositions(v,d)?E==="start"?"after":"before":a&&x__namespace.compareRelativePositions(v,d)?"before":s&&x__namespace.compareRelativePositions(v,p)?"after":null},b=u===t&&a?"before":f(c.start,"start"),I=u===t&&s?"after":f(c.end,"end");(b||I)&&h.push({record:m,start:b,end:I});}return ()=>{let u=r.start+o,m=x__namespace.relativePositionToJSON(x__namespace.createRelativePositionFromTypeIndex(r.text,u,u===0&&r.startAssoc===-1?-1:0)),c=x__namespace.relativePositionToJSON(x__namespace.createRelativePositionFromTypeIndex(r.text,u+i.length,0));for(let f of h){let b=JSON.parse(f.record.get(B));f.start&&(b.start=f.start==="before"?m:c),f.end&&(b.end=f.end==="before"?m:c);let I=JSON.stringify(b);I!==f.record.get(B)&&f.record.set(B,I);}}}function Kt(n,e,t){if(t.keepBoundary&&n===t.start)return n;let r=n<=t.start?n:Math.max(t.start,n-t.deleted);return r<t.start||r===t.start&&e<0?r:r+t.inserted.length}var nt=class{constructor(e,t){this.registry=e;this.raw=t;}registry;raw;ranges=new Map;histories=new Map;strings=new Map;actions=[];shadow=null;range(e){if(this.shadow){let r=this.shadow.sources.range(e);return r?{...r,revision:0}:null}if(!this.ranges.has(e)){let r=this.registry.splitTextRange(e);this.ranges.set(e,r?{...r,revision:0}:null);}let t=this.ranges.get(e);if(t){let r=this.histories.get(t.sourceId)??[];for(;t.revision<r.length;){let o=r[t.revision],i=(a,s)=>{let l=s<0?a-1:a;return l>=o.start&&l<o.start+o.deleted};if(t.startAnchorDeleted||t.endAnchorDeleted||o.ambiguousBoundary||i(t.start,t.startAssoc)||i(t.end,t.endAssoc)){this.ensureShadow();let a=this.shadow.sources.range(e);return a?{...a,revision:0}:null}t.start=Kt(t.start,t.startAssoc,o),t.end=Kt(t.end,t.endAssoc,o),t.revision+=1;}}return t}value(e){let t=this.range(e);if(t)return this.value(t.sourceId).slice(t.start,t.end);let r=this.strings.get(e);if(r===void 0){r=this.registry.hasNode(e)?this.registry.textOf(e).toString():"";for(let o of this.histories.get(e)??[])r=r.slice(0,o.start)+o.inserted+r.slice(o.start+o.deleted);this.strings.set(e,r);}return r}apply(e){let t=oe(e),r=t?this.range(t.logicalId):null,o={keepBoundary:t?.utf16Start===0&&r?.startAssoc!==-1&&e.insert.length>0,ambiguousBoundary:r!==null&&r.start===r.end&&e.insert.length>0,start:e.utf16Start,deleted:e.deleteCount,inserted:e.insert},i=this.histories.get(e.logicalId)??[];i.push(o),this.histories.set(e.logicalId,i);let a=this.strings.get(e.logicalId);a!==void 0&&this.strings.set(e.logicalId,a.slice(0,o.start)+o.inserted+a.slice(o.start+o.deleted));let s={kind:"splice",effect:e};this.actions.push(s),this.shadow&&this.replay(s);}register(e,t,r,o){let i=this.range(t),a=i?.sourceId??t,s=i?.start??0,l=i?i.end-i.start:this.raw.node(t)?.textLength??0,d=(m,c)=>i&&c==="end"&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:i&&m===0?{assoc:i.startAssoc,deleted:i.startAnchorDeleted}:i&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:{assoc:s+m===0&&c==="start"?-1:0,deleted:false},p=d(r,"start"),h=d(o,"end");this.ranges.set(e,{sourceId:a,start:s+r,end:s+o,startAssoc:p.assoc,endAssoc:h.assoc,startAnchorDeleted:p.deleted,endAnchorDeleted:h.deleted,revision:this.histories.get(a)?.length??0});let u={kind:"register",product:e,source:t,start:r,end:o};this.actions.push(u),this.shadow&&this.replay(u);}destroy(){this.shadow?.doc.destroy();}ensureShadow(){if(this.shadow)return;let e=new x__namespace.Doc({gc:false}),t=e.getMap(We);this.shadow={doc:e,nodes:t,sources:new ee(t,e,this.registry.limits)},x__namespace.applyUpdate(e,x__namespace.encodeStateAsUpdate(this.registry.doc)),e.clientID=this.registry.doc.clientID,this.shadow.sources.reset();for(let r of this.actions)this.replay(r);}replay(e){let t=this.shadow,r=h=>(t.nodes.has(h)||t.nodes.set(h,Re("")),t.nodes.get(h).get(M));if(e.kind==="register"){r(e.product),t.sources.register(e.product,e.source,e.start,e.end);return}let{effect:o}=e,i=oe(o),a=i?t.sources.range(i.logicalId):null,s=a?.text??r(o.logicalId),l=i?.utf16Start??o.utf16Start,d=(a?.start??0)+l,p=Ce(t.nodes,t.sources,i?.logicalId??o.logicalId,a,l,o.insert);o.deleteCount>0&&s.delete(d,o.deleteCount),o.insert.length>0&&s.insert(d,o.insert),p?.();}},rt=class extends V{constructor(t,r,o,i){super(t);this.hidden=r;this.raw=o;this.text=i;}hidden;raw;text;filtered=new Set;node(t){let r=super.node(t);if(r&&!this.filtered.has(t)&&(this.filtered.add(t),r.children=r.children.filter(o=>!this.hidden.has(o))),r?.isText){let o=this.text.range(t);r.textLength=o?o.end-o.start:this.raw.node(t)?.textLength??r.textLength;}return r}};function Vt(n,e){let t=n.replacementLoserRuns(),r=e.effects.filter(c=>c.kind==="putNode").length;if(n.nodeCount()+r>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let o=new Set;for(let c of e.effects){if(c.kind==="spliceChildren"){if(c.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let f of c.childLogicalIds)o.add(f);}else c.kind==="moveNode"&&o.add(c.logicalId);if(o.size>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"}}let i=new V(n),a=new nt(n,i),s=new rt(n,t,i,a),l=new Map,d=c=>l.get(c)?.kind??n.kindOf(c),p={limits:n.limits,projectedTextValue:c=>i.node(c)?.isText?a.value(c):null,registerSplitText:(c,f,b,I)=>a.register(c,f,b,I),record:c=>{let f=i.node(c);if(!f)return null;if(f.isText)return {logicalId:c,kind:"textValue",value:a.value(c)};let b=l.get(c),I=b?null:n.record(c);return I&&I.kind!=="textValue"?{...I,childIds:f.children}:!b||b.kind==="textValue"?null:{logicalId:c,kind:b.kind,namespaceUri:b.qname.namespaceUri,localName:b.qname.localName,prefix:b.qname.prefix??"",attributes:[],bindings:[],childIds:f.children}}},h=[],u=null,m=c=>{if(u)return;let f=we(n,c,i);if(f&&!f.ok){u=f;return}h.push(c),ce(i,c),c.kind==="spliceText"&&a.apply(c);};try{for(let c of e.effects){let f=we(n,c,s);if(f&&!f.ok)return f;if(ce(s,c),c.kind==="putNode"&&l.set(c.descriptor.logicalId,c.descriptor),c.kind==="spliceText"){let b=a.range(c.logicalId),I=b?{...c,logicalId:b.sourceId,utf16Start:b.start+c.utf16Start}:c;b&&Je.set(I,{logicalId:c.logicalId,utf16Start:c.utf16Start}),m(I);}else if(c.kind==="spliceChildren"){let b=i.node(c.parentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let I=b.children.flatMap((v,w)=>t.has(v)?[]:[w]),R=I.slice(c.start,c.start+c.deleteCount).map(v=>b.children[v]),E=I[c.start]??b.children.length;if(c.deleteCount===0)m({...c,start:E});else {let v=I.slice(c.start,c.start+c.deleteCount),w=v.length;for(;w>0;){let _=w-1;for(;_>0&&v[_-1]===v[_]-1;)_-=1;m({...c,start:v[_],deleteCount:w-_,childLogicalIds:_===0?c.childLogicalIds:[]}),w=_;}}if(!u&&c.childLogicalIds.length>0){let v=c.childLogicalIds.filter(w=>d(w)==="run");for(let w of R)d(w)==="run"&&(!o.has(w)||l.has(w))&&Le(p,w,v);}}else if(c.kind==="moveNode"){let b=i.node(c.destinationParentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let I=b.children.filter(E=>E!==c.logicalId),R=I.flatMap((E,v)=>t.has(E)?[]:[v]);m({...c,destinationIndex:R[c.destinationIndex]??I.length});}else m(c);if(u)return u}return {ok:!0,journal:{effects:h}}}finally{a.destroy();}}var Xr=new Set(["paraId","textId","id","numId","bookmarkId"]);function Jt(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function Wt(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),Jt(e)}function ke(n){return /^[0-9a-f]{32}$/.test(n)}function $t(n,e){if(!ke(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 ot(n,e){return `yjs:${n}:${e}`}function it(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return ke(e)?e:null}function at(n){let e=[];for(let t of n)Xr.has(t.localName)&&e.push(t.value);return e}var ue=class{replicaId;next=0;constructor(e){if(this.replicaId=e??Wt(),!ke(this.replicaId))throw new Error("invalid replica identity")}take(){let e=$t(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};function Xt(n,e){let t=i=>{let a=new Set,s=false;for(let l of i){let d=l.path;if(d.length===0){for(let p of l.changes.keys.keys())a.add(String(p));s=true;continue}a.add(String(d[0])),l.target instanceof x__namespace.Array&&(s=true),l.target instanceof x__namespace.Map&&(l.changes.keys.has(U)||l.changes.keys.has(X))&&(s=true);}(a.size>0||s)&&e({logicalIds:a,membershipChanged:s,packageChanged:false});},r=i=>{let a=new Set;for(let s of i.changes.keys.keys()){let l=q(String(s))??Z(String(s));!l||g(l.logicalId)||a.add(l.logicalId);}a.size>0&&e({logicalIds:a,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return n.nodes.observeDeep(t),n.attributes.observe(r),n.bindings.observe(r),n.parts.observeDeep(o),n.relationships.observeDeep(o),n.overrides.observe(o),n.defaults.observe(o),n.binaries.observeDeep(o),()=>{n.nodes.unobserveDeep(t),n.attributes.unobserve(r),n.bindings.unobserve(r),n.parts.unobserveDeep(o),n.relationships.unobserveDeep(o),n.overrides.unobserve(o),n.defaults.unobserve(o),n.binaries.unobserveDeep(o);}}var Oe=class{constructor(e){this.nodes=e;}nodes;cachedLosers=null;invalidate(){this.cachedLosers=null;}runsBySplitOrigin=new Map;liveRootedOrigins=new Set;reset(){this.invalidate(),this.runsBySplitOrigin.clear(),this.liveRootedOrigins.clear();}record(e,t,r){this.invalidate();for(let o of r){if(o===e)continue;let i=this.nodes.get(o);S(i)&&(i.set($e,e),i.set(ie,e),this.indexExisting(o));}}indexExisting(e){let t=Qe(this.nodes.get(e));if(t===null||t===e)return;this.invalidate();let r=this.runsBySplitOrigin.get(t)??new Set;r.add(e),this.runsBySplitOrigin.set(t,r),this.liveRootedOrigins.add(t);}productsOf(e){return [...this.runsBySplitOrigin.get(e)??[]].filter(t=>Qe(this.nodes.get(t))===e)}loserRuns(e){if(this.cachedLosers)return this.cachedLosers;let t=new Set,r=new Set,o=i=>{let a=[i];for(;a.length>0;){let s=a.pop();if(!r.has(s)){r.add(s),e.isPresent(s)&&t.add(s);for(let l of this.productsOf(s))a.push(l);}}};for(let i of this.liveRootedOrigins){let a=this.productsOf(i),s=e.isPresent(i)?null:a.filter(l=>de(this.nodes.get(l))===i).map(l=>it(l)??"").sort()[0];for(let l of a)(it(l)??"")!==s&&o(l);}return this.cachedLosers=t,t}};function Ht(n,e){if(!n.hasNode(e)||n.isTombstoned(e))return false;let t=n.parentOf(e);if(t===null)return false;let r=n.record(t);return r!==null&&L(r)&&r.childIds.includes(e)}function Ae(n){return typeof n=="string"?n:""}function Gt(n,e){return n<e?-1:n>e?1:0}function st(n,e){return `${n}${P}${e}`}function Gr(n){let e=n.indexOf(P);return e<0?n:n.slice(0,e)}function qt(n){let e=[];return n.forEach((t,r)=>{!S(t)||g(r)||t.forEach(o=>{if(!S(o))return;let i=Ae(o.get("id")),a=Ae(o.get("type"));if(i.length===0||a.length===0)return;let s=Ae(o.get("ownerPart"))||Gr(r);if(g(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:Ae(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||Gt(t.ownerPart,r.ownerPart)||Gt(t.id,r.id)),e}function Zt(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 qr(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 Qt(n,e){let t=n.childrenSnapshot.get(e);return t||(D(n.nodes.get(e))?.toArray()??[])}function Zr(n,e){let t=n.nodes.get(e);return !S(t)||K(t)}function Qr(n,e,t,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),Zr(n,a)))return null;s=e.get(a);let p=n.parentIndex.get(a);if(s!==void 0){if(p!==void 0)return "fallback";break}if(p===void 0)return t.has(a)?"deferred":null;o.push(a),a=p;}let l=[s],d=a;for(let p=o.length-1;p>=0;p-=1){let h=o[p],u=Qt(n,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function en(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,a)=>{r.has(i)||r.set(i,a);});let o=[...t];for(;o.length>0;){let i=[];for(let a of o){let s=null,l=false;for(let d of n.listings.get(a)??[]){if(d===a)continue;let p=Qr(n,r,t,d);if(p==="fallback")return false;if(p==="deferred"){l=true;continue}if(p===null)continue;let h=Qt(n,d).indexOf(a);if(h<0)continue;let u=[...p,h];(!s||qr(u,s.rank)<0)&&(s={rank:u,parent:d});}if(l){i.push(a);continue}s&&n.parentIndex.set(a,s.parent),t.delete(a);}if(i.length===o.length)return false;o=i;}return true}function tn(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let a of e)r.delete(a);for(let a of i){let s=new Set,l=[{id:a,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){s.delete(d.id);continue}let p=d.id;if(d.parent!==null&&(e===null||e.has(p))&&(r.has(p)||r.set(p,d.parent)),s.has(p))continue;let h=t.get(p);if(!S(h)||K(h))continue;let u=o.get(p)??D(h)?.toArray()??[];s.add(p),l.push({id:p,parent:null,exit:true});let m=new Set,c=[];for(let f of u)m.has(f)||f===p||(m.add(f),c.push(f));for(let f=c.length-1;f>=0;f-=1)l.push({id:c[f],parent:p,exit:false});}}}function nn(n,e){return `${n}${P}${e}`}function lt(n,e,t,r,o){if(g(t)||g(r.localName))return;let i=G(n.namespaces,r.namespaceUri,e),a=Ge(t,i,r.localName);g(a)||n.attributes.set(a,Nt(r.prefix??"",o));}function rn(n,e,t,r){n.attributes.delete(Ge(e,ae(t),r));}function dt(n,e,t,r,o){if(g(t)||g(r))return;let i=G(n.namespaces,o,e),a=qe(t,r);g(a)||n.bindings.set(a,i);}function on(n,e,t){n.bindings.delete(qe(e,t));}function ct(n,e,t,r,o,i){let{prefix:a,value:s}=Mt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(nn(r,o),{namespaceUri:se(n.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function eo(n,e,t,r){let o=n.get(e);o&&(o.delete(nn(t,r)),o.size===0&&n.delete(e));}function ut(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:se(n.namespaces,o)});}function to(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function an(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"){eo(e,i.logicalId,i.namespaceId,i.localName);continue}let a=n.attributes.get(String(r));typeof a=="string"&&ct(n,e,i.logicalId,i.namespaceId,i.localName,a);}}function sn(n,e,t){for(let[r,o]of t.changes.keys){let i=Z(String(r));if(!i||g(i.logicalId)||g(i.prefix))continue;if(o.action==="delete"){to(e,i.logicalId,i.prefix);continue}let a=n.bindings.get(String(r));typeof a=="string"&&ut(n,e,i.logicalId,i.prefix,a);}}function dn(n,e){let t=n.get(e);if(!S(t))return null;if(le(t)){let r=t.get(M);return {isText:true,textLength:r instanceof x__namespace.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:D(t)?.toArray()??[]}}function cn(n,e){let t=n.get(e);return S(t)?le(t)?"textValue":He(t).kind:null}function un(n,e){if(n.length!==e.length)return false;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return false;return true}function pn(n,e,t,r,o){let i=He(e);return {logicalId:n,kind:i.kind,namespaceUri:se(t.namespaces,i.namespaceId),localName:i.localName,prefix:i.prefix.length>0?i.prefix:void 0,attributes:r,bindings:o,childIds:D(e)?.toArray()??[]}}function ne(n){return typeof n=="string"?n:""}function hn(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||g(r))return;let o=ne(t.get("rootId"));o.length!==0&&e.push({name:r,id:ne(t.get("id")),rootLogicalId:o,contentType:ne(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function mn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(store.partNameKey(r),t);}),e}function gn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!g(r)&&e.set(r,t);}),e}function fn(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||g(r))return;let o=ne(t.get("digest")),i=t.get("size"),a=ne(t.get("mediaType")),s=ne(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:a,storageKey:s});}),e}function ro(n){return n?._item??null}function oo(n){return n.content instanceof x__namespace.ContentType}function bn(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=ro(t);return r===null||r.parent!==n?true:e.parentSub===ie||e.parentSub===ve?false:!oo(e)}}function io(n){let e=n._item;return e?ot(e.id.client,e.id.clock):null}function ao(n){return typeof n=="string"?n:""}var J=class{constructor(e,t){this.doc=e;this.schema=At(e),this.limits=Lt(t),this.splitDedup=new Oe(this.schema.nodes),this.splitTextSources=new ee(this.schema.nodes,this.doc,this.limits),this.stopObserving=Zt(this.schema,{onNodeEvents:r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);},onAttributeEvent:r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);},onBindingEvent:r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);},onRelationshipChange:()=>{this.relationshipCountCache=-1;},onPartChange:()=>{this.partCountCache=-1;}});}doc;schema;limits;parentIndex=new Map;listings=new Map;childrenSnapshot=new Map;adoptees=new Map;tombstoneSources=new Map;tombstoneSurvivor=new Map;attributesByNode=new Map;bindingsByNode=new Map;splitDedup;splitTextSources;bulkLoad=0;unobservedWrites=0;nodeCountCache=-1;pendingNodeAdds=0;relationshipCountCache=-1;partCountCache=-1;stopObserving;destroy(){this.stopObserving();}beginBulkLoad(){this.bulkLoad+=1;}endBulkLoad(){this.bulkLoad=Math.max(0,this.bulkLoad-1),this.bulkLoad===0&&this.rebuildDerivedIndexes();}trackedTypes(){return [this.schema.meta,this.schema.nodes,this.schema.parts,this.schema.relationships,this.schema.overrides,this.schema.defaults,this.schema.binaries,this.schema.attributes,this.schema.bindings]}undoDeleteFilter(){return bn(this.schema.nodes)}encodeSnapshot(){return x__namespace.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return x__namespace.encodeStateAsUpdate(this.doc,e)}partEntries(){return hn(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 ao(this.schema.meta.get("mainDocumentPart"))}record(e){if(g(e))return null;let t=this.schema.nodes.get(e);if(!S(t))return null;if(le(t)){let r=t.get(M),o=r instanceof x__namespace.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return pn(e,t,this.schema,[...this.attributesByNode.get(e)?.values()??[]],[...this.bindingsByNode.get(e)?.values()??[]])}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let t=this.schema.nodes.get(e);if(!t)return null;let r=this.record(e),o=r&&L(r)?r.attributes:[];return {logicalId:e,yjsItemKey:io(t),wordFacingIds:at(o)}}isTombstoned(e){return K(this.schema.nodes.get(e))}replacedByOf(e){return Ze(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(ae(e))===e}noteWrite(){this.unobservedWrites+=1;}hasUnobservedWrites(){return this.unobservedWrites>0}listingParents(e){return [...this.listings.get(e)??[]]}allLogicalIds(){return [...this.schema.nodes.keys()].filter(e=>!g(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return g(e)?null:dn(this.schema.nodes,e)}kindOf(e){return g(e)?null:cn(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=G(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Dt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)lt(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)dt(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=G(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(Ie,Xe(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Re(t));}spliceText(e,t,r,o){let i=this.splitTextSources.range(e),a=Ce(this.schema.nodes,this.splitTextSources,e,i,t,o),s=i?.text??this.textOf(e),l=(i?.start??0)+t;r>0&&s.delete(l,r),o.length>0&&s.insert(l,o),a?.();}setAttribute(e,t,r){if(r===null){rn(this.schema,e,t.namespaceUri,t.localName);return}lt(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){on(this.schema,e,t);return}dt(this.schema,this.limits.maxStringLength,e,t,r);}spliceChildren(e,t,r,o){let i=this.childArray(e);r>0&&i.delete(t,r),o.length>0&&i.insert(t,[...o]);}moveNode(e,t,r){this.unlinkFromAllParents(e);let o=this.childArray(t);o.insert(Math.max(0,Math.min(r,o.length)),[e]);}tombstone(e,t){this.unlinkFromAllParents(e);let r=this.require(e);r.set(U,true),t&&r.set(X,t);}recordRunSplit(e,t,r){this.splitDedup.record(e,t,r);}splitOriginOf(e){return de(this.schema.nodes.get(e))}replacementLoserRuns(){return this.hasUnobservedWrites()&&this.splitDedup.invalidate(),this.splitDedup.loserRuns({isPresent:e=>Ht(this,e)})}splitTextRange(e){return this.splitTextSources.range(e)}projectedTextValue(e){return this.splitTextSources.value(e)}registerSplitText(e,t,r,o){this.splitTextSources.register(e,t,r,o);}normalizeRestoredSplitTextAnchors(){this.splitTextSources.normalizeRestoredAnchors();}concurrentSplitTextOverlays(){return this.splitTextSources.overlays()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?D(r):null;if(!o)return;let i=new Map;for(let a of t)i.set(a,(i.get(a)??0)+1);for(let a=o.length-1;a>=0;a-=1){let s=o.get(a),l=i.get(s)??0;l!==0&&(i.set(s,l-1),o.delete(a,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,Bt(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 x__namespace.Map;t.set(e.id,_t(e)),this.schema.relationships.set(st(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(st(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(store.partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(store.partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,Yt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return qt(this.schema.relationships)}contentTypeOverrides(){return mn(this.schema.overrides)}contentTypeDefaults(){return gn(this.schema.defaults)}binaries(){return fn(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){return Xt(this.schema,e)}rebuildDerivedIndexes(){this.unobservedWrites=0,this.nodeCountCache=-1,this.pendingNodeAdds=0,this.relationshipCountCache=-1,this.partCountCache=-1,this.parentIndex=new Map,this.listings=new Map,this.childrenSnapshot=new Map,this.adoptees=new Map,this.tombstoneSources=new Map,this.tombstoneSurvivor=new Map,this.attributesByNode=new Map,this.bindingsByNode=new Map,this.splitDedup.reset(),this.splitTextSources.reset(),this.schema.nodes.forEach((e,t)=>{if(g(t))return;let r=D(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(t,o);for(let i of o)this.addListing(i,t);}),this.schema.nodes.forEach((e,t)=>{K(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)||ct(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||g(t))return;let r=Z(t);!r||g(r.logicalId)||g(r.prefix)||ut(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(S(e)&&(e.has("parent")||e.has("parentId")))throw new Error("registry record must not replicate a parent field")});}applyChildArrayEvents(e){this.unobservedWrites=0,this.pendingNodeAdds=0;let t=new Set;for(let r of e){if(!(r.target instanceof x__namespace.Text)&&(r.path.length===0||r.target instanceof x__namespace.Array||r.target instanceof x__namespace.Map&&[...r.changes.keys.keys()].some(o=>["deleted","replacedBy","splitFrom","splitLineage","children"].includes(String(o))))&&this.splitDedup.invalidate(),r.path.length>0&&this.splitTextSources.noteChanged(String(r.path[0])),r.path.length===0&&r.target instanceof x__namespace.Map){for(let[o,i]of r.changes.keys)if(this.nodeCountCache>=0&&i.action!=="update"&&(this.nodeCountCache+=i.action==="add"?1:-1),!(i.action==="delete"||g(String(o)))){this.splitDedup.indexExisting(String(o)),this.splitTextSources.indexExisting(String(o));for(let a of this.syncChildListings(String(o)))t.add(a);}continue}if(r.target instanceof x__namespace.Map&&r.path.length===1&&(r.changes.keys.has("splitFrom")||r.changes.keys.has("splitLineage"))&&this.splitDedup.indexExisting(String(r.path[0])),r.target instanceof x__namespace.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))t.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof x__namespace.Map&&r.path.length===1&&(r.changes.keys.has(U)||r.changes.keys.has(X))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,an(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,sn(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?D(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(un(o,r))return [];let i=new Set(r),a=new Set(o),s=[];for(let l of o)i.has(l)||(this.removeListing(l,e),s.push(l));for(let l of r)a.has(l)||(this.addListing(l,e),s.push(l));return this.childrenSnapshot.set(e,r),s}addListing(e,t){let r=this.listings.get(e)??new Set;r.add(t),this.listings.set(e,r);}removeListing(e,t){let r=this.listings.get(e);r&&(r.delete(t),r.size===0&&this.listings.delete(e));}resolveParents(e){let t=[];for(let o of e){let i=this.listings.get(o);if(!i||i.size===0){this.parentIndex.delete(o);continue}if(i.size===1){this.parentIndex.set(o,[...i][0]);continue}t.push(o);}if(t.length===0)return;en({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){tn({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=Ze(r);if(o!==null){if(K(r)){let i=this.tombstoneSources.get(o)??new Set;i.add(e),this.tombstoneSources.set(o,i),this.tombstoneSurvivor.set(e,o);}this.recomputeAdoptees(o);}}isContentWitness(e){let t=this.kindOf(e);return t!==null&&!t.endsWith("Properties")}recomputeAdoptees(e){let t=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of D(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&t.push(i);}t.length>0?this.adoptees.set(e,t):this.adoptees.delete(e);}unlinkFromAllParents(e){let t=[...this.listings.get(e)??[]];if(t.length===0){this.schema.nodes.forEach(r=>{let o=D(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?D(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,t){for(let r=e.length-1;r>=0;r-=1)e.get(r)===t&&e.delete(r,1);}textOf(e){let t=this.require(e).get(M);if(!(t instanceof x__namespace.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(Se);if(!(t instanceof x__namespace.Array))throw new Error(`no children at ${e}`);return t}require(e){let t=this.schema.nodes.get(e);if(!t)throw new Error(`registry node ${e} missing`);return t}};var Te=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 In(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 vn(n){let e=n.binaryPart;return typeof e=="function"?e:null}function Sn(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 En(n,e){for(let t of e)n.put(t.digest,t.bytes);}function lo(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function co(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(g(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>n.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>n.limits.maxTextLength)return "text-too-long";n.putText(e.id,e.value);}else {if(e.attributes.length>n.limits.maxAttributes)return "too-many-attributes";if(e.children.length>n.limits.maxChildren)return "too-many-children";if(A(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(g(i.localName))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(g(i.prefix))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}n.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:lo(e),bindings:co(e)});for(let i of e.children){let a=Rn(n,i,e.id,r+1,o);if(a)return a}}return t&&n.childArray(t).push([e.id]),null}async function uo(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let a=n.contentTypes.overrides.get(r)??"application/octet-stream",s=O(r);if(s)return {ok:false,code:s};if(o.byteLength>Y.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await In(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:a,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function pe(n,e,t=new Te){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await uo(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let s of r.payloads)t.put(s.digest,s.bytes);let i={nodes:0};for(let[s,l]of e.parts){let d=O(s);if(d){o=d;return}if(A(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let p=Rn(n,l.root,null,0,i);if(p){o=p;return}n.putXmlPart({name:s,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let a=0;for(let s of e.relationships.values())for(let l of s){if(a+=1,a>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=O(l.ownerPart);if(d){o=d;return}}if(g(l.id)){o="prototype-key";return}n.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[s,l]of e.contentTypes.defaults){if(g(s)){o="prototype-key";return}n.putContentTypeDefault(s,l);}for(let[s,l]of e.contentTypes.overrides){let d=O(s);if(d){o=d;return}n.putContentTypeOverride(s,l);}for(let s of r.descriptors)n.putBinary(s);Ut(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},Pt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var Me="http://schemas.openxmlformats.org/package/2006/relationships",po="application/vnd.openxmlformats-package.relationships+xml",Ln=/^(.*)\/_rels\/([^/]*)\.rels$/;function wn(n){return Ln.test(n)}function Cn(n){let e=Ln.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function he(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ne(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function ho(n,e){let t=[Ne("Id",e.id),Ne("Type",e.type),Ne("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(Ne("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:Me,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function kn(n,e){if(n.kind==="textValue"||n.namespaceUri!==Me||n.localName!=="Relationship"||he(n,"Id")!==e.id||he(n,"Type")!==e.type||he(n,"Target")!==e.rawTarget)return false;let t=he(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function Pn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>kn(t,e[r]))}function On(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 An(n,e,t){let r=[];for(let o of e){if(g(o.id))continue;let i=n.find(s=>s.kind!=="textValue"&&he(s,"Id")===o.id);if(i&&kn(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;g(a)||r.push(ho(a,o));}return r}function mo(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:Me,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:Me})]),attributes:Object.freeze([]),children:Object.freeze([])})}function Tn(n){return Object.freeze({id:n,name:n,contentType:po,root:mo(n)})}function Nn(n){let e=new Map;for(let t of n){if(g(t.id)||t.ownerPart!=="/"&&O(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var _n=/^\/customXml\/item(\d+)\.xml$/i,bo=/^\/customXml\/itemProps(\d+)\.xml$/i;function ge(n){return _n.test(n)}function ht(n){return bo.test(n)}function xo(n){let e=_n.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function Mn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function 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 Dn(n,e){let t=n.record(e);return !t||!L(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function vo(n,e){let t=n.record(e);if(!t||!L(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!L(o)||o.localName!=="schemaRefs")&&o.namespaceUri===store.DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=n.record(i);if(!a||!L(a)||a.localName!=="schemaRef")continue;let s=Io(a,"uri",store.DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function So(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&L(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Eo(n,e){return e.localName==="node"||e.namespaceUri===store.WML_NAMESPACE_URI||e.namespaceUri===store.DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:So(n,e)}function Ro(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==store.DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function Yn(n,e){if(!n.hasNamespace(store.DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,m]of e){let c=n.record(m.root.id);!c||!L(c)||(ge(u)&&t.set(c.logicalId,c),ht(u)&&r.set(c.logicalId,c));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let m=n.record(u);!m||!L(m)||(Eo(n,m)?t.set(u,m):Ro(n,m)&&r.set(u,m));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let m=o.get(u.namespaceUri)??[];m.push(u),o.set(u.namespaceUri,m);}let i=new Map;for(let u of r.values()){let m=vo(n,u.logicalId);if(!m)continue;let c=i.get(m)??[];c.push(u),i.set(m,c);}let a=[];for(let[u,m]of o){let c=i.get(u);if(!c||c.length===0)continue;m.sort((E,v)=>E.logicalId.localeCompare(v.logicalId)),c.sort((E,v)=>E.logicalId.localeCompare(v.logicalId));let f=m[0],b=c[0],I=[],R=new Set;for(let E of m)for(let v of E.childIds){if(R.has(v))continue;let w=n.record(v);!w||!L(w)||w.localName!=="node"||w.namespaceUri!==u||(R.add(v),I.push(v));}for(let E of n.allLogicalIds()){if(R.has(E)||n.isTombstoned(E))continue;let v=n.record(E);!v||!L(v)||v.localName!=="node"||v.namespaceUri!==u||(R.add(E),I.push(E));}I.sort((E,v)=>Dn(n,E).localeCompare(Dn(n,v))),a.push({data:f,props:b,nodeIds:I});}a.sort((u,m)=>u.data.logicalId.localeCompare(m.data.logicalId));let s=new Set,l=[],d=new Set,p=new Set;for(let[u,m]of e){let c=xo(u);if(c===null)continue;let f=a.find(R=>R.data.logicalId===m.root.id&&!d.has(R.data.logicalId));if(!f)continue;let b=Mn(c).props,I=e.get(b);I&&I.root.id!==f.props.logicalId||(s.add(c),d.add(f.data.logicalId),p.add(f.props.logicalId),l.push({dataRootId:f.data.logicalId,propsRootId:f.props.logicalId,namespaceUri:f.data.namespaceUri,itemName:u,propsName:b,nodeIds:f.nodeIds}));}let h=1;for(let u of a){if(d.has(u.data.logicalId))continue;for(;s.has(h);)h+=1;s.add(h);let m=Mn(h);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:u.nodeIds}),h+=1;}return l.sort((u,m)=>u.itemName.localeCompare(m.itemName)),l}function Lo(n){return n.type===store.CUSTOM_XML_REL||n.type===store.CUSTOM_XML_PROPS_REL?true:ge(n.ownerPart)}function wo(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Co(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 Un(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(s=>s.ownerPart===t&&s.type===store.CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,wo(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],p=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:t,id:p,type:store.CUSTOM_XML_REL,rawTarget:Co(t,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:store.CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function zn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Lo(t)),...e]}function jn(n){let e=new Map;for(let t of n)e.set(store.partNameKey(t.propsName),store.CUSTOM_XML_PROPS_TYPE);return e}function mt(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(ge).sort(),r=e.map(o=>o.itemName).sort();if(t.length!==r.length||t.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=n.get(o.itemName),a=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!a||a.root.id!==o.propsRootId)return true}return false}function Fn(n,e){if(mt(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(t.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var ko="http://schemas.microsoft.com/office/word/2012/wordml";function De(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Be(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 Kn(n){return e=>e.localName===n&&e.namespaceUri===store.WML_NAMESPACE_URI}function Po(n){return n.localName==="abstractNum"?`0${Be(De(n,"abstractNumId"))}`:`1${Be(De(n,"numId"))}`}function Oo(n){return n.namespaceUri!==store.WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function Vn(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===ko,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Kn("footnote"),sortKey:e=>Be(De(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Kn("endnote"),sortKey:e=>Be(De(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Oo,sortKey:Po}:null}function Ao(n,e){return n.attributes.find(t=>t.localName===e)?.value}function gt(n){return n.kind==="textValue"?n.id:Ao(n,"id")??n.id}function re(n,e){if(n.length===e.length&&n.every((a,s)=>a===e[s]))return n;let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t+=1;let o=n.length,i=e.length;for(;o>t&&i>t&&n[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...n.slice(0,t),...e.slice(t,i),...n.slice(o)])}function $n(n,e){let t=n.root;if(t.children.length===e.length&&t.children.every((o,i)=>o===e[i]))return n;let r=Object.freeze({...t,children:re(t.children,e)});return Object.freeze({...n,root:r})}function To(n){if(n.namespaceUri===store.XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:store.XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===store.WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:store.WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function Gn(n){}function Zn(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function Yo(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 Uo(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 _e(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&&Yo(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&Uo(r,n)?r.attributes:Object.freeze(n.attributes.map(To)),children:e})}function Qn(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
3
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
4
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function ft(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)ft(o,e)||(r=false);return r}function er(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 Ye=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:zn(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:Nn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:Fo(t)}),this.assembly.value}contentTypeDefaults(){return this.defaults??=this.registry.contentTypeDefaults()}contentTypeOverrides(){return this.overrides??=this.registry.contentTypeOverrides()}resolvePartBytes(e){if(this.partBytes)return this.partBytes;let t=new Map,r=new Set;for(let o of this.registry.binaries()){r.add(o.storageKey);let i=this.blobBytes.get(o.storageKey);if(i&&i.digest===o.digest){t.set(o.storageKey,i.bytes);continue}let a=e.get(o.digest);if(!a)return null;Gn(a.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:a}),t.set(o.storageKey,a);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function Fo(n){let e=store.buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=store.resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var Ue=class{lastLosers=new Set;textOverlays=new Map;losers=new Set;update(e){let t=[],r=e.replacementLoserRuns(),o=a=>{let s=e.parentOf(a);s!==null&&t.push(s);};for(let a of r)this.lastLosers.has(a)||o(a);for(let a of this.lastLosers)r.has(a)||o(a);this.lastLosers=r,this.losers=r;let i=e.concurrentSplitTextOverlays();return this.textOverlays=i.values,t.push(...i.changedIds),t}textValue(e,t){return this.textOverlays.get(e)??t}};function Jo(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 W=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Ye(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 Ue;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let p of this.adoptionChanges())e.add(p);for(let p of this.splitProjection.update(this.registry))e.add(p);let o=er(this.registry,e),i=new Set(this.registry.partEntries().map(p=>p.rootLogicalId)),a=[...e].some(p=>i.has(p)||this.registry.parentOf(p)===null&&!this.registry.isTombstoned(p)),s=this.pkg!==null&&!r&&!a&&(o.size>0||t),l=this.materializePass(o,t,s);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:Jo(l.issues)};let d=this.materializePass(o,t,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let t=this.lastContestResolution.get(e);if(t===void 0||t!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let t of this.contestEncountered)e.set(t,this.registry.parentOf(t));for(let t of this.lastDuplicateParents)e.set(t,this.registry.parentOf(t));this.lastContestResolution=e;}materializePass(e,t,r){if(this.issues.length=0,this.lastDirty=e,this.placementContested=false,this.contestEncountered.clear(),this.contestMatchesResolution=true,this.claimsWholeSubtrees=!r,this.droppedChildren.clear(),r)for(let d of this.lastDuplicateParents)this.push("duplicate-parent",d);this.customXmlRels=[],this.customXmlOverrides.clear();let o=new Set,i=new Map;for(let d of this.registry.partEntries()){let p=new Set,h=this.materialize(d.rootLogicalId,o,p,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===h&&u.contentType===d.contentType){i.set(d.name,u);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,m),this.partCache.set(d.name,m);}let a=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),s=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,a,s),this.applyCustomXmlStores(i,o,r);for(let d of [...this.partCache.keys()])i.has(d)||this.partCache.delete(d);for(let d of [...this.relsProjection.keys()])i.has(d)||this.relsProjection.delete(d);this.evictDeadSubtrees(o),this.reportOrphans(a,o,r,s),this.looseCandidates=s,r||(this.lastDuplicateParents=this.issues.filter(d=>d.code==="duplicate-parent"&&d.logicalId!==void 0).map(d=>d.logicalId));let l=this.assemblePackage(i);return l.ok?this.pkg&&!t&&this.pkg.parts.size===i.size&&[...i].every(([d,p])=>this.pkg?.parts.get(d)===p)?{ok:true,package:this.pkg,issues:[...this.issues]}:(this.pkg=l.package,{ok:true,package:this.pkg,issues:[...this.issues]}):l}push(e,t){this.issues.push(t?{code:e,logicalId:t}:{code:e});}stillListed(e){for(let t of this.registry.listingParents(e)){let r=this.registry.record(t);if(r&&L(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let s of e)this.registry.isTombstoned(s)||t.has(s)||(this.pushOrphan(s),o.add(s));return}let i=new Set(this.registry.partEntries().map(s=>s.rootLogicalId)),a=new Set;for(let s of e)a.has(s)||(a.add(s),this.reportOrphansUnder(s,t,i)&&o.add(s));}reportOrphansUnder(e,t,r){let o=false,i=new Set,a=[{id:e,underTombstone:false}];for(;a.length>0;){let{id:s,underTombstone:l}=a.pop();if(!(i.has(s)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(s),this.registry.isTombstoned(s)){let d=this.registry.record(s);if(d&&L(d))for(let p of d.childIds)a.push({id:p,underTombstone:true});continue}r.has(s)||(l?t.has(s):this.stillListed(s))||(this.pushOrphan(s),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(H(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let u=this.cache.get(e);if(u&&r.size+this.heightOf(u)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?ft(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(H(i)){let u=this.splitProjection.textValue(e,i.value),m=this.cache.get(e);if(m?.kind==="textValue"&&m.value===u)return m;let c=Zn(e,u);return this.remember(e,c),c}r.add(e);let a=new Set,s=[...i.childIds];for(let u of this.registry.adoptedChildren(e))s.includes(u)||s.push(u);let l=[];for(let u of s){if(u===e){this.push("self-child",u);continue}if(a.has(u)){this.push("duplicate-child",u);continue}if(a.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(this.splitProjection.losers.has(u)){t.add(u);continue}if(g(u)||!this.registry.hasNode(u)){this.push("child-id-not-in-registry",u);continue}if(!this.claimsWholeSubtrees){let c=this.registry.listingParents(u);c.length>1&&(this.placementContested=true,this.contestEncountered.add(u),c.some(f=>this.registry.isTombstoned(f)&&this.registry.replacedByOf(f)!==null)?this.contestMatchesResolution=false:!t.has(u)&&this.registry.parentOf(u)!==e&&(this.contestMatchesResolution=false));}let m=this.materialize(u,t,r,o);m&&l.push(m);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,m)=>u===l[m])&&Qn(d,i))return d;let p=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(p,l);let h=_e(i,re(p,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let a=store.relsPartNameFor(o);if(a!=="/_rels/.rels"&&O(a))continue;r.add(a);let s=this.projectOneRelsPart(a,e.get(a),i);s&&(e.set(a,s),this.partCache.set(a,s));}for(let[o,i]of e){if(r.has(o)||!wn(o))continue;let a=Cn(o);if(a===null)continue;let s=this.projectOneRelsPart(o,i,t.get(a)??[]);!s||s===i||(e.set(o,s),this.partCache.set(o,s));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),a=!!o&&(!t||On(o.root,t.root))&&o?o:t??Tn(e);if(Pn(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=$n(a,An(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[a,s]of e){let l=Vn(s.root);if(!l)continue;let d=R=>R.logicalId!==s.root.id&&l.isMember(R),p=[],h=new Set;for(let R of s.root.children){if(R.kind==="textValue")continue;let E=this.registry.record(R.id);!E||!L(E)||!d(E)||(p.push(R),h.add(R.id));}if(this.adoptLooseMembers(p,h,d,t,r,o,i)===0)continue;p.sort((R,E)=>l.sortKey(R).localeCompare(l.sortKey(E)));let m=[];for(let R of s.root.children)h.has(R.id)||m.push(R);let c=re(s.root.children,[...m,...p]);if(c===s.root.children)continue;let f=this.registry.record(s.root.id);if(!f||!L(f))continue;let b=_e(f,c,s.root);this.remember(s.root.id,b);let I=Object.freeze({...s,root:b});e.set(a,I),this.partCache.set(a,I);}}adoptLooseMembers(e,t,r,o,i,a,s){let l=0;for(let d of a){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let p=this.registry.record(d);if(!p||!L(p)||!r(p))continue;let h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),t.add(d),s.add(d),l+=1);}return l}materializeOnce(e,t,r){return t.has(e)?this.cache.get(e)??null:this.materialize(e,t,new Set,r)}adoptNodesIntoRoot(e,t,r,o){let i=this.cache.get(e),a=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!a||a.kind==="textValue")return null;let s=[...a.children],l=new Set(s.map(m=>m.id)),d=0;for(let m of t){if(l.has(m))continue;let c=this.materializeOnce(m,r,o);!c||c.kind==="textValue"||(s.push(c),l.add(m),d+=1);}if(s.sort((m,c)=>gt(m).localeCompare(gt(c))),d===0&&s.every((m,c)=>m===a.children[c]))return a;let p=this.registry.record(e);if(!p||!L(p))return a;let h=re(a.children,s),u=_e(p,h,a);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=Yn(this.registry,e);if(o.length===0||!Fn(e,o))return;let i=mt(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,t,r),d=this.materializeOnce(s.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let p=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:s.propsName,name:s.propsName,contentType:store.CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,p),e.set(s.propsName,h),this.partCache.set(s.itemName,p),this.partCache.set(s.propsName,h);}if(i){for(let s of [...e.keys()])!ge(s)&&!ht(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=Un(this.registry,o),this.customXmlOverrides=jn(o),this.projectRelsParts(e);}}assemblePackage(e){let t=this.packageCache.relationshipAssembly(this.customXmlRels);if(!t)return {ok:false,code:"invalid-relationships",issues:[...this.issues]};let r=this.packageCache.resolvePartBytes(this.blobs);if(!r)return {ok:false,code:"missing-blob",issues:[...this.issues]};let o=new Map(this.packageCache.contentTypeOverrides());for(let[s,l]of this.customXmlOverrides)o.set(s,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},a=this.registry.mainDocumentPart()||[...e.keys()].find(s=>s.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:a}),issues:[...this.issues]}}};var je=64*1024*1024,ye="docx-package-blobs-v1";function $o(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 Xo(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function ze(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=$o(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+=Xo(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>je)throw new y("blob-store-full");this.shared.set(e,new Uint8Array(t));}}verify(e,t,r){return this.verified.has(t)?true:this.poisoned.has(e)?false:layout.sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(t),true)}};function be(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return ze("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return ze("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(s=>{i+=s instanceof x__namespace.Map?s.size:0;}),i>t.maxRelationships)return ze("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>je?ze("blob-store-full",`${a}`):null}var rr=20*1024*1024,bt=3e4,ei=4e3,ti=1500,ni="docx-collaboration-seeds-v1",yt="docxEditorSeedCandidate",ri=/^[0-9a-f]{16}$/,oi=256;function xt(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new y("invalid-baseline");if(n.byteLength>rr)throw new y("baseline-too-large");let e=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:rr,maxRatio:200}});if(!e.ok)throw new y("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new y("no-main-document-part");let r=e.package;for(let i of r.parts.values()){if(i.root.namespaceUri!==store.WML_NAMESPACE_URI||!["document","hdr","ftr"].includes(i.root.localName)||!store.isStoryPart(i))continue;let a=store.normalizeParagraphIdentity(i);a!==i&&(r=store.withPart(r,a));}return new store.TreePackageStore(r,store.normalizeParagraphIdentity(r.parts.get(t.name))).currentPackage()}function ii(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function xe(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&ii(n,e),a=()=>{let l=e.poisonedDigest();return l?new y("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let s=a();return s?Promise.reject(s):r?.aborted?Promise.reject(new y("initialization-aborted")):new Promise((l,d)=>{let p=c=>{clearTimeout(m),o.unobserve(h),n.doc.off("afterTransaction",h),r?.removeEventListener("abort",u),c?d(c):l();},h=()=>{let c=a();if(c){p(c);return}i()&&p();},u=()=>p(new y("initialization-aborted")),m=setTimeout(()=>p(new y("initialization-timeout")),t);o.observe(h),n.doc.on("afterTransaction",h),r?.addEventListener("abort",u,{once:true});})}function It(n){return n.getArray(ni)}function Fe(n){return It(n).length}function ir(n,e){let t=It(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function ai(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function si(n,e){let t=[...n.getStates().entries()].slice(0,oi);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[yt];if(!(typeof i!="string"||!ri.test(i))&&i<e)return true}return false}async function or(n,e,t,r){try{return await xe(n,e,t,r),!0}catch(o){if(o instanceof y&&o.code==="initialization-timeout")return false;throw o}}function li(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new y("initialization-aborted")):new Promise((i,a)=>{let s=h=>{clearTimeout(p),r.unobserve(l),t?.removeEventListener("abort",d),h?a(h):i();},l=()=>{o()&&s();},d=()=>s(new y("initialization-aborted")),p=setTimeout(()=>s(new y("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function ar(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??ei,a=n.electionWindowMs??ti,s=n.timeoutMs??bt,l=async()=>(await li(r,s,n.signal),"joined");if(await or(r,o,i,n.signal))return l();let d=ai();t.setLocalStateField(yt,d);try{let p=await or(r,o,a,n.signal);if(!p&&si(t,d)&&(await xe(r,o,s,n.signal),p=!0),p)return await l();if(r.schema.meta.get("initialized")===!0)return await xe(r,o,s,n.signal),await l();let h=await pe(r,xt(n.document),o);if(!h.ok)throw new y(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),It(e).push([d]);}),"seeded"}finally{t.setLocalStateField(yt,null);}}var Ke=class{constructor(e,t){this.knows=e;this.allocator=new ue(t);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let t=this.allocator.take();return this.toLogical.set(e,t),t}resolve(e){return this.toLogical.get(e)??e}translate(e){let t=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),t.push(i);}return r?Object.freeze({effects:Object.freeze(t)}):e}translateEffect(e){switch(e.kind){case "putNode":{let t=this.translateDescriptor(e.descriptor);return t.logicalId===e.descriptor.logicalId?e:{...e,descriptor:t}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let t=this.resolve(e.logicalId);return t===e.logicalId?e:{...e,logicalId:t}}case "spliceChildren":{let t=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return t===e.parentLogicalId&&r.every((i,a)=>i===e.childLogicalIds[a])?e:{...e,parentLogicalId:t,childLogicalIds:r}}case "moveNode":{let t=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return t===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:t,destinationParentLogicalId:r}}case "putXmlPart":{let t=this.resolve(e.rootLogicalId);return t===e.rootLogicalId?e:{...e,rootLogicalId:t}}default:return e}}translateDescriptor(e){let t=this.resolve(e.logicalId);return this.knows(t)?{...e,logicalId:t}:{...e,logicalId:this.mint(e.logicalId)}}};function di(n){let e=0;return n.schema.nodes.forEach(t=>{S(t)&&t.get(U)===true&&(e+=1);}),e}function ci(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof x__namespace.Map?t.size:0;}),e}function lr(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:di(n),maxNodes:n.limits.maxNodes,relationships:ci(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:je})}var Ve="docxEditor",j=256,vt=256;function cr(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>j||t.length===0||t.length>j)throw new y("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new y("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function ur(n){let e=n.trim();if(e.length===0||e.length>j)throw new y("invalid-document-id");return e}function pr(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>j)throw new y("invalid-session-id");return e}function dr(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 pi(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=dr(e.anchor),r=dr(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 St(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>j||typeof e.name!="string"||e.name.length===0||e.name.length>j)return null;let t=collaboration.safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=pi(e.selection);return i?{...o,selection:i}:o}function mi(n){let e=new J(n),t=null;try{if(e.schema.meta.get("initialized")!==!0||typeof e.schema.meta.get("documentId")!="string")throw new y("not-initialized");let r=Q(e.schema.meta);if(r)throw new y(r.code,r.detail);if(e.rebuildDerivedIndexes(),Fe(n)>1)throw new y("concurrent-seed");let o=new $(n.getMap(ye)),i=be(e,o);if(i)throw new y(i.code,i.detail);t=new W(e,o);let a=t.current(),s=o.poisonedDigest();if(s)throw new y("blob-digest-mismatch",s);if(!a.ok)throw new y(a.code);let l=Ee(a.issues);if(l)throw new y("materialize-dropped-content",l);if(!a.package.parts.has(a.package.mainDocumentPart))throw new y("no-main-document-part");return store.writeOoxmlPackage(a.package)}finally{t?.destroy(),e.destroy();}}var xi=3,Ii=5e3,vi=2e3,Si=Symbol("createDocumentCollaboration.attachWatchdogMs"),Et=class{constructor(e,t,r,o,i,a,s,l,d,p,h){this.ydoc=e;this.awareness=t;this.registry=a;this.materializer=s;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new x__namespace.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:Ii,deleteFilter:a.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let m=d.verifyNow(u);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=ir(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${p}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},p),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;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 lr(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}hasCompatibleSharedSchema(){let e=Q(this.registry.schema.meta);return e?(this.setStatus("error",e.code,e.detail),false):true}canWriteSharedState(){if(this.destroyed||!this.hasCompatibleSharedSchema())return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,t){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.undoManager.undo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],t=[...this.awareness.getStates().entries()].slice(0,vt);for(let[r,o]of t){let i=St(o[Ve]);i&&e.push({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},role:i.role,isLocal:r===this.awareness.clientID});}return Object.freeze(e)}subscribeParticipants(e){return this.participantListeners.add(e),()=>this.participantListeners.delete(e)}remoteSelections(){let e=this.port;if(!e)return [];let t=i=>{let a=e.paragraphByStableId(i.paragraphId);return a?Object.freeze({paragraphId:a.paragraphId,nodeId:a.nodeId,offset:Math.min(i.offset,a.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,vt),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=St(a[Ve]);if(!s?.selection)continue;let l=t(s.selection.anchor),d=t(s.selection.head);!l||!d||o.push(Object.freeze({actorId:s.actorId,name:s.name,...s.color?{color:s.color}:{},...s.selection.kind==="cells"?{kind:"cells"}:{},anchor:l,head:d}));}return Object.freeze(o)}subscribeRemoteSelections(e){return this.selectionListeners.add(e),()=>this.selectionListeners.delete(e)}setIdentity(e){if(this.destroyed)return;let t=e.name===void 0?this.currentIdentity.name:e.name.trim();if(t.length===0||t.length>j)throw new y("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new y("invalid-identity-color");r=collaboration.safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:t,...r?{color:r}:{},role:this.currentIdentity.role??"human"}),this.publishAwareness(this.currentSelection);}destroy(){this.destroyed||(this.clearAttachWatchdog(),this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.stopBlobWatch(),this.stopSeedWatch(),this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.materializer.destroy(),this.registry.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){if(!this.canWriteSharedState())return;let t=Vt(this.registry,this.identityMap.translate(e));if(!t.ok){this.refuseLocalJournal({code:t.code,...t.detail?{detail:t.detail}:{}});return}let r=t.journal,o=this.collectJournalBlobs(e);if(o!==null&&o.ok===false){this.refuseLocalJournal(o.failure);return}if(!this.canWriteSharedState())return;let i=this.ydoc.transact(()=>{if(o!==null){let s=this.putJournalBlobs(o.payloads);if(s!==null)return s}let a=et(this.registry,r);return a.ok?null:{code:a.code,...a.detail?{detail:a.detail}:{}}},this.localOrigin);if(i===null){this.refusedInARow=0;return}this.refuseLocalJournal(i);}collectJournalBlobs(e){let t=this.port;if(!t)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=Sn(e.effects,vn(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{En(this.blobs,e);}catch(t){return t instanceof y?Object.freeze({code:t.code,...t.detail?{detail:t.detail}:{}}):Object.freeze({code:"blob-store-full"})}return null}refuseLocalJournal(e){this.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<xi&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(t.status==="ready"||t.status==="disconnected")&&this.setStatus(t.status,t.reason?.code,t.reason?.detail);}onYjsTransaction=e=>{this.destroyed||!this.hasCompatibleSharedSchema()||!this.port||e.origin!==this.localOrigin&&this.publishSharedToPort();};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{if(!this.hasCompatibleSharedSchema())return;let t=be(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=Ee(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let a=e.applyRemotePackage(r.package,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!a.ok){this.setStatus("error","remote-apply-failed",a.reason);return}a.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof y?t.code:"remote-apply-failed",t instanceof y?t.detail:void 0);}finally{this.applyingRemote=false,this.drainJournalsHeldDuringRemote();}}}drainJournalsHeldDuringRemote(){if(!this.drainingHeldJournals){this.drainingHeldJournals=true;try{for(;this.journalsHeldDuringRemote.length>0;){if(this.destroyed||this.realignedInBatch){this.journalsHeldDuringRemote.length=0;return}let e=this.journalsHeldDuringRemote.shift();e&&this.applyJournal(e);}}finally{this.drainingHeldJournals=false;}}}onAwarenessChange=()=>{if(this.destroyed)return;let e=this.remoteSelections();for(let r of [...this.selectionListeners])r(e);let t=this.participants();for(let r of [...this.participantListeners])r(t);};publishAwareness(e){this.currentSelection=e;let t={actorId:this.identity.actorId,name:this.identity.name,...this.identity.color?{color:this.identity.color}:{},role:this.identity.role??"human",...e?{selection:e}:{}};this.awareness.setLocalStateField(Ve,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 fl(n){let e=n[Si]??vi,t=ur(n.documentId),r=pr(n.sessionId),o=cr(n.identity),i=new J(n.ydoc);try{return await Ei(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function Ei(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new Ke(h=>a.hasNode(h)),l=new $(n.ydoc.getMap(ye));if(n.bootstrap.kind==="create"){if(a.schema.meta.get("initialized")===true)throw new y("already-initialized");let h=await pe(a,xt(n.bootstrap.document),l);if(!h.ok)throw new y(h.code);n.ydoc.transact(()=>{a.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await ar({ydoc:n.ydoc,awareness:n.awareness,registry:a,blobs:l,documentId:r,document:n.bootstrap.document,probeTimeoutMs:n.bootstrap.probeTimeoutMs,electionWindowMs:n.bootstrap.electionWindowMs,timeoutMs:n.bootstrap.timeoutMs,signal:n.bootstrap.signal})==="joined"){if(a.schema.meta.get("documentId")!==r)throw new y("document-id-mismatch");let u=Q(a.schema.meta);if(u)throw new y(u.code,u.detail);a.rebuildDerivedIndexes();}}else {if(await xe(a,l,n.bootstrap.timeoutMs??bt,n.bootstrap.signal),a.schema.meta.get("documentId")!==r)throw new y("document-id-mismatch");let h=Q(a.schema.meta);if(h)throw new y(h.code,h.detail);a.rebuildDerivedIndexes();}if(Fe(n.ydoc)>1)throw new y("concurrent-seed");let d=be(a,l);if(d)throw new y(d.code,d.detail);let p=new W(a,l);try{let h=p.current(),u=l.poisonedDigest();if(u)throw new y("blob-digest-mismatch",u);if(!h.ok)throw new y(h.code);let m=store.writeOoxmlPackage(h.package),c=new Et(n.ydoc,n.awareness,r,o,i,a,p,s,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:c,destroy:()=>c.destroy()})}catch(h){throw p.destroy(),h}}exports.a=y;exports.b=mi;exports.c=Si;exports.d=fl;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';var x=require('yjs'),store=require('@docx-editor.dev/core/store'),replication=require('@docx-editor.dev/core/collaboration/replication'),collaboration=require('@docx-editor.dev/core/collaboration'),layout=require('@docx-editor.dev/core/layout');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var x__namespace=/*#__PURE__*/_interopNamespace(x);var We=new WeakMap;function ie(n){return We.get(n)}var U=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}),Rr=/^sha256:[0-9a-f]{64}$/;function Tt(n){return n?Object.freeze({...U,...n}):U}function f(n){return store.isDangerousKey(n)?"prototype-key":null}function A(n,e){return typeof n!="string"||n.length>e?"invalid-string":store.isDangerousKey(n)?"prototype-key":null}function O(n){let e=f(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=store.normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function Nt(n){for(let e of Object.keys(n)){let t=f(e);if(t)return t}return !Rr.test(n.digest)||n.digest.length>80||!Number.isSafeInteger(n.size)||n.size<0?"invalid-blob-descriptor":n.size>U.maxBlobBytes?"blob-too-large":A(n.mediaType,U.maxMediaTypeLength)||n.mediaType.length===0||A(n.storageKey,U.maxStorageKeyLength)||n.storageKey.length===0?"invalid-blob-descriptor":null}var Dt=1,Bt=1,Xe=20*1024*1024,Or="docx-collaboration-v1",Ar="docx-body-paragraphs-v1",Tr=Object.freeze({kind:"docx-collaboration-bootstrap"}),Nr="https://www.docx-editor.dev/docs/latest/pro/collaboration-versions",g=class extends Error{constructor(t,r){let o=t==="collaboration-format-mismatch"||t==="protocol-version-mismatch"||t==="schema-version-mismatch",i=r?`${t}: ${r}`:t;super(o?`${i}
|
|
2
|
+
Collaboration upgrade required. Save local changes and use a compatible app version, or upgrade the saved room. See ${Nr}`:i);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function Ge(n){return {root:n.getMap(Or),paragraphs:n.getMap(Ar)}}function Mr(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new g("invalid-baseline");if(n.byteLength>Xe)throw new g("baseline-too-large");let t=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:Xe,maxRatio:200}});if(!t.ok)throw new g("invalid-baseline");let r=t.package.parts.get(t.package.mainDocumentPart);if(!r)throw new g("no-main-document-part");let o=store.normalizeParagraphIdentity(r),i=new store.TreePackageStore(t.package,o),a=replication.createCollaborationDocumentPort(i,{documentId:e});return {bytes:store.writeOoxmlPackage(i.currentPackage()),paragraphs:a.paragraphs()}}async function _t(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 Mt(n,e){let t=n.get(e);if(typeof t!="string"||t.length===0||t.length>256)throw new g("invalid-shared-metadata",e);return t}function $e(n,e){let t=n.get(e);if(!Number.isSafeInteger(t)||t<0)throw new g("invalid-shared-metadata",e);return t}function ae(n){return n.get("initialized")===true}async function Wi(n,e,t,r){let{root:o,paragraphs:i}=Ge(n);if(ae(o))throw new g("already-initialized");let a=await _t(r.bytes);n.transact(()=>{if(ae(o))throw new g("already-initialized");o.set("protocolVersion",Dt),o.set("schemaVersion",Bt),o.set("documentId",e),o.set("baselineSha256",a),o.set("baselineByteLength",r.bytes.byteLength),o.set("initializedBy",t),o.set("baseline",new Uint8Array(r.bytes));for(let s of r.paragraphs){if(i.has(s.paragraphId))throw new g("duplicate-paragraph-id");let l=new x__namespace.Text;i.set(s.paragraphId,l),l.insert(0,s.text);}o.set("initialized",true);},Tr);}async function $i(n,e){let{root:t,paragraphs:r}=Ge(n);if(!ae(t))throw new g("not-initialized");if($e(t,"protocolVersion")!==Dt)throw new g("protocol-version-mismatch");if($e(t,"schemaVersion")!==Bt)throw new g("schema-version-mismatch");if(Mt(t,"documentId")!==e)throw new g("document-id-mismatch");let o=$e(t,"baselineByteLength");if(o===0||o>Xe)throw new g("baseline-too-large");let i=t.get("baseline");if(!(i instanceof Uint8Array)||i.byteLength!==o)throw new g("invalid-baseline");if(await _t(i)!==Mt(t,"baselineSha256"))throw new g("baseline-digest-mismatch");let a=Mr(new Uint8Array(i),e),s=new Set(a.paragraphs.map(l=>l.paragraphId));if(r.size!==s.size)throw new g("paragraph-set-mismatch");for(let[l,d]of r)if(!s.has(l)||!(d instanceof x__namespace.Text))throw new g("paragraph-set-mismatch");return a}function Xi(n,e,t){let{root:r}=Ge(n);return ae(r)?Promise.resolve():t?.aborted?Promise.reject(new g("initialization-aborted")):new Promise((o,i)=>{let a=p=>{clearTimeout(d),r.unobserve(s),t?.removeEventListener("abort",l),p?i(p):o();},s=()=>{ae(r)&&a();},l=()=>a(new g("initialization-aborted")),d=setTimeout(()=>a(new g("initialization-timeout")),e);r.observe(s),t?.addEventListener("abort",l,{once:true});})}var V=Object.freeze({protocolVersion:1,sharedSchemaVersion:3,repairVersion:1,canonicalModelVersion:1});function qe(n){let e=n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{};for(let t of Object.keys(V)){let r=V[t],o=Object.hasOwn(e,t)?e[t]:void 0;if(o===r)continue;let i=o===void 0?"missing":typeof o=="number"&&Number.isSafeInteger(o)?String(o):"invalid";return {code:t==="protocolVersion"?"protocol-version-mismatch":"schema-version-mismatch",detail:`${t}: expected ${r}, received ${i}`}}return null}function qi(n){let e=qe(n);if(e)throw new g(e.code,e.detail)}var Dr=V.protocolVersion,Br=V.sharedSchemaVersion,_r=V.repairVersion,Yr=V.canonicalModelVersion,Ur="docx-package-meta-v1",Ze="docx-package-nodes-v1",zr="docx-package-parts-v1",jr="docx-package-rels-v1",Fr="docx-package-overrides-v1",Kr="docx-package-defaults-v1",Vr="docx-package-binaries-v1",Jr="docx-package-namespaces-v1",Wr="docx-package-attributes-v1",$r="docx-package-bindings-v1",ve="s",Se="b",M="t",Ee="children",z="deleted",X="replacedBy",Qe="splitFrom",se="splitLineage";var P="",Yt="-",Ut=Object.freeze({kind:"docx-package-bootstrap"}),zt=Object.freeze({kind:"docx-package-journal"});function H(n){return n.kind==="textValue"}function L(n){return !H(n)}var Xr=Object.freeze(new Set(["missing-node","child-id-not-in-registry","cycle"])),Hr=200;function Re(n){let e=new Map;for(let t of n)Xr.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,Hr)}function jt(n){return {meta:n.getMap(Ur),nodes:n.getMap(Ze),parts:n.getMap(zr),relationships:n.getMap(jr),overrides:n.getMap(Fr),defaults:n.getMap(Kr),binaries:n.getMap(Vr),namespaces:n.getMap(Jr),attributes:n.getMap(Wr),bindings:n.getMap($r)}}var Ft=[["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"]],Gr=new Map(Ft),qr=new Map(Ft.map(([n,e])=>[e,n]));function Zr(n){let e=0xcbf29ce484222325n,t=0x100000001b3n;for(let r=0;r<n.length;r+=1)e^=BigInt(n.charCodeAt(r)),e=e*t&0xffffffffffffffffn;return e.toString(16).padStart(16,"0")}function le(n){return n.length===0?Yt:Gr.get(n)??`n${Zr(n)}`}function G(n,e,t){let r=le(e);return e.length===0||f(r)||A(e,t)||n.get(r)!==e&&n.set(r,e),r}function de(n,e){if(e===Yt||f(e))return "";let t=n.get(e);return typeof t=="string"?t:qr.get(e)??""}function et(n,e,t,r){return `${n}${P}${e}${P}${t}${P}${r}`}function Qr(n){let e=n.split(P);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function tt(n){let e=n.has(ve)?n.get(ve):n.get(Se);return Qr(typeof e=="string"?e:"")}function nt(n,e,t){return `${n}${P}${e}${P}${t}`}function q(n){let e=n.split(P);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 rt(n,e){return `${n}${P}${e}`}function Z(n){let e=n.split(P);if(e.length!==2)return null;let t=e[0],r=e[1];return t.length===0?null:{logicalId:t,prefix:r}}function Kt(n,e){return `${n}${P}${e}`}function Vt(n){let e=n.indexOf(P);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Jt(n){let e=new x__namespace.Map,t=et(n.kind,n.namespaceId,n.localName,n.prefix??"");e.set(Se,t);let r=new x__namespace.Array;return n.childIds&&n.childIds.length>0&&r.push([...n.childIds]),e.set(Ee,r),e}function Le(n){let e=new x__namespace.Map;return e.set(M,new x__namespace.Text(n)),e}function Wt(n,e,t){let r=new x__namespace.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function $t(n){let e=new x__namespace.Map;return e.set("ownerPart",n.ownerPart),e.set("id",n.id),e.set("type",n.type),e.set("rawTarget",n.rawTarget),e.set("targetMode",n.targetMode),e.set("order",n.order),e}function Xt(n){let e=new x__namespace.Map;return e.set("digest",n.digest),e.set("size",n.size),e.set("mediaType",n.mediaType),e.set("storageKey",n.storageKey),e}function Q(n){return qe({protocolVersion:n.get("protocolVersion"),sharedSchemaVersion:n.get("sharedSchemaVersion"),repairVersion:n.get("repairVersion"),canonicalModelVersion:n.get("canonicalModelVersion")})}function Ht(n){n.set("protocolVersion",Dr),n.set("sharedSchemaVersion",Br),n.set("repairVersion",_r),n.set("canonicalModelVersion",Yr),n.set("initialized",true);}function S(n){return n instanceof x__namespace.Map}function D(n){if(!S(n))return null;let e=n.get(Ee);return e instanceof x__namespace.Array?e:null}function ce(n){return S(n)&&n.get(M)instanceof x__namespace.Text}function J(n){return S(n)&&n.get(z)===true}function ot(n){if(!S(n))return null;let e=n.get(X);return typeof e=="string"&&e.length>0?e:null}function ue(n){if(!S(n))return null;let e=n.get(Qe);return typeof e=="string"&&e.length>0?e:null}function it(n){if(!S(n))return null;let e=n.get(se);return typeof e=="string"&&e.length>0?e:ue(n)}function Gt(n,e){let t=[],r=[{id:e,depth:0}],o=new Set,i=0;for(;r.length>0;){let{id:a,depth:s}=r.pop();if(o.has(a)||s>n.limits.maxTreeDepth)return null;o.add(a);let l=n.record(a);if(!l)return null;if(H(l)){let d=n.projectedTextValue(a)??l.value;if(i+=d.length,i>n.limits.maxTextLength)return null;t.push({id:a,value:d});}else if(L(l)&&!l.kind.endsWith("Properties"))for(let d=l.childIds.length-1;d>=0;d-=1)r.push({id:l.childIds[d],depth:s+1});}return t}function we(n,e,t){let r=Gt(n,e),o=[];if(!r||r.length===0)return;for(let l of t){let d=Gt(n,l);if(!d)return;for(let p of d)o.push(p);}if(r.map(l=>l.value).join("")!==o.map(l=>l.value).join(""))return;let i=[],a=0,s=0;for(let l of o){for(;a<r.length-1&&s===r[a].value.length;)a+=1,s=0;let d=r[a];if(!d||s+l.value.length>d.value.length)return;l.id!==d.id&&i.push({product:l.id,source:d.id,start:s,end:s+l.value.length}),s+=l.value.length;}for(let l of i)n.registerSplitText(l.product,l.source,l.start,l.end);}var W=class{constructor(e){this.registry=e;}registry;touched=new Map;created=new Set;has(e){return this.created.has(e)||this.touched.has(e)||this.registry.hasNode(e)}node(e){let t=this.touched.get(e);if(t)return t;let r=this.registry.nodeShape(e);return r?(this.touched.set(e,r),r):null}putNode(e){this.node(e.logicalId)||(this.created.add(e.logicalId),this.touched.set(e.logicalId,{isText:e.kind==="textValue",textLength:0,children:[]}));}spliceText(e,t,r){let o=this.node(e);o&&(o.textLength=Math.max(0,o.textLength-t)+r);}spliceChildren(e,t,r,o){let i=this.node(e);i&&i.children.splice(t,r,...o);}moveNode(e,t,r){let o=this.parentOf(e);if(o!==null){let s=this.node(o),l=s?.children.indexOf(e)??-1;s&&l>=0&&s.children.splice(l,1);}let i=this.node(t);if(!i)return;let a=Math.min(r,i.children.length);i.children.splice(a,0,e);}parentOf(e){for(let[t,r]of this.touched)if(r.children.includes(e))return t;return this.registry.parentOf(e)}};function pe(n,e){switch(e.kind){case "putNode":n.putNode(e.descriptor);return;case "spliceText":n.spliceText(e.logicalId,e.deleteCount,e.insert.length);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;default:return}}function j(n,e){return f(e)||e.length===0?{ok:false,code:"prototype-key",detail:e}:n.has(e)?null:{ok:false,code:"unknown-logical-id",detail:e}}function eo(n,e,t){if(f(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:f(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null}function Ce(n,e,t){switch(e.kind){case "putNode":return eo(n,e.descriptor,t);case "spliceText":{let r=j(t,e.logicalId);if(r)return r;if(!Number.isSafeInteger(e.utf16Start)||!Number.isSafeInteger(e.deleteCount)||e.utf16Start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.insert.length>n.limits.maxTextLength)return {ok:false,code:"text-too-long"};let o=t.node(e.logicalId);if(o&&o.isText){if(e.utf16Start+e.deleteCount>o.textLength)return {ok:false,code:"invalid-bound",detail:e.logicalId};if(o.textLength-e.deleteCount+e.insert.length>n.limits.maxTextLength)return {ok:false,code:"text-too-long"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.logicalId};return null}case "setAttribute":{let r=j(t,e.logicalId);return r||(f(e.qname.localName)?{ok:false,code:"prototype-key",detail:e.qname.localName}:A(e.qname.namespaceUri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:e.value!==null&&e.value.length>n.limits.maxStringLength?{ok:false,code:"invalid-string"}:null)}case "setNamespaceBinding":{let r=j(t,e.logicalId);return r||(f(e.prefix)?{ok:false,code:"prototype-key"}:e.uri!==null&&A(e.uri,n.limits.maxStringLength)?{ok:false,code:"invalid-string"}:null)}case "spliceChildren":{let r=j(t,e.parentLogicalId);if(r)return r;if(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.deleteCount)||e.start<0||e.deleteCount<0)return {ok:false,code:"invalid-bound"};if(e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let i of e.childLogicalIds){let a=j(t,i);if(a)return a}let o=t.node(e.parentLogicalId);if(o&&!o.isText){if(e.start+e.deleteCount>o.children.length)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};if(o.children.length-e.deleteCount+e.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"}}else if(o)return {ok:false,code:"invalid-bound",detail:e.parentLogicalId};return null}case "moveNode":{let r=j(t,e.logicalId);if(r)return r;let o=j(t,e.destinationParentLogicalId);return o||(!Number.isSafeInteger(e.destinationIndex)||e.destinationIndex<0?{ok:false,code:"invalid-bound"}:null)}case "putXmlPart":{let r=O(e.name);if(r)return {ok:false,code:r,detail:e.name};let o=j(t,e.rootLogicalId);return o||(n.partCount()>=n.limits.maxParts?{ok:false,code:"too-many-parts"}:null)}case "deleteXmlPart":{let r=O(e.name);return r?{ok:false,code:r,detail:e.name}:null}case "putRelationship":{if(e.record.ownerPart!=="/"){let r=O(e.owner);if(r)return {ok:false,code:r}}return f(e.record.id)?{ok:false,code:"prototype-key"}:n.relationshipCount()>=n.limits.maxRelationships?{ok:false,code:"too-many-relationships"}:null}case "deleteRelationship":return f(e.relationshipId)?{ok:false,code:"prototype-key"}:null;case "putContentTypeOverride":{let r=O(e.partName);return r?{ok:false,code:r}:A(e.mediaType,n.limits.maxMediaTypeLength)?{ok:false,code:"invalid-string"}:null}case "deleteContentTypeOverride":{let r=O(e.partName);return r?{ok:false,code:r}:null}case "putBinary":{let r=Nt(e.descriptor);return r?{ok:false,code:r}:null}case "deleteBinary":return f(e.storageKey)?{ok:false,code:"prototype-key"}:null;default:return {ok:false,code:"invalid-bound"}}}function to(n,e,t){switch(e.kind){case "putNode":e.descriptor.kind==="textValue"?n.hasNode(e.descriptor.logicalId)||n.putText(e.descriptor.logicalId,""):n.hasNode(e.descriptor.logicalId)?n.updateElementShell(e.descriptor.logicalId,{kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix}):n.putElement({logicalId:e.descriptor.logicalId,kind:e.descriptor.kind,namespaceUri:e.descriptor.qname.namespaceUri,localName:e.descriptor.qname.localName,prefix:e.descriptor.qname.prefix,attributes:[],bindings:[]});return;case "spliceText":if(t.has(e.logicalId)&&e.utf16Start===0&&e.deleteCount===0&&n.textOf(e.logicalId).toString()===e.insert)return;let r=ie(e);n.spliceText(r?.logicalId??e.logicalId,r?.utf16Start??e.utf16Start,e.deleteCount,e.insert);return;case "setAttribute":n.setAttribute(e.logicalId,e.qname,e.value);return;case "setNamespaceBinding":n.setNamespaceBinding(e.logicalId,e.prefix,e.uri);return;case "spliceChildren":n.spliceChildren(e.parentLogicalId,e.start,e.deleteCount,e.childLogicalIds);return;case "moveNode":n.moveNode(e.logicalId,e.destinationParentLogicalId,e.destinationIndex);return;case "putXmlPart":n.putXmlPart({name:e.name,id:e.name,rootLogicalId:e.rootLogicalId,contentType:"application/xml"});return;case "deleteXmlPart":n.deleteXmlPart(e.name);return;case "putRelationship":n.putRelationship({...e.record,ownerPart:e.owner});return;case "deleteRelationship":n.deleteRelationship(e.owner,e.relationshipId);return;case "putContentTypeOverride":n.putContentTypeOverride(e.partName,e.mediaType);return;case "deleteContentTypeOverride":n.deleteContentTypeOverride(e.partName);return;case "putBinary":n.putBinary(e.descriptor);return;case "deleteBinary":n.deleteBinary(e.storageKey);return}}function no(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function ro(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>no(n,i)));if(o.size!==0){for(let i of r)if(!(i.kind!=="spliceChildren"||i.parentLogicalId===e)&&i.childLogicalIds.some(a=>o.has(a)))return i.parentLogicalId}}function oo(n,e){let t=new W(n),r=[],o=new Set,i=new Set,a=new Set,s=new Map;for(let l of e){let d=Ce(n,l,t);if(d)return d;if(l.kind==="spliceChildren"){let p=l.deleteCount>0?t.node(l.parentLogicalId):null;if(p&&!p.isText){let h=l.start+l.deleteCount;for(let u=l.start;u<h;u+=1){let m=p.children[u];if(m!==void 0&&(r.push(m),l.childLogicalIds.length>0)){let c=s.get(l)??[];c.push(m),s.set(l,c);}}}for(let h of l.childLogicalIds)o.add(h);}else l.kind==="moveNode"?o.add(l.logicalId):l.kind==="putNode"&&(a.add(l.descriptor.logicalId),l.descriptor.kind==="textValue"&&i.add(l.descriptor.logicalId));pe(t,l);}return {removed:r,reinserted:o,mintedText:i,mintedNodes:a,replacementsByEffect:s}}function io(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function at(n,e){if(n.nodeCount()+io(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=oo(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=co(n,t.removed);for(let o of e.effects)to(n,o,t.mintedText),o.kind==="spliceChildren"&&so(n,t,t.replacementsByEffect.get(o)??[],o.childLogicalIds);ao(n,e.effects,t,r);},zt),{ok:true})}function ao(n,e,t,r){if(t.removed.length===0)return;let o=new Set;for(let i of n.partEntries())o.add(i.rootLogicalId);for(let i of t.removed){if(t.reinserted.has(i)||!n.hasNode(i)||n.isTombstoned(i)||o.has(i))continue;let a=ro(n,i,r,e);a&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,a);}}function so(n,e,t,r){for(let o of t){if(n.kindOf(o)!=="run"||e.reinserted.has(o)&&!e.mintedNodes.has(o))continue;let i=lo(n,o,e.reinserted),a=r.filter(s=>n.kindOf(s)==="run");we(n,o,a),n.recordRunSplit(i,o,a);}}function lo(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 co(n,e){let t=new Map;for(let r of e){let o=n.nodeShape(r);o&&!o.isText&&t.set(r,o.children);}return t}var B="splitTextSource",uo=Object.freeze({kind:"docx-package-restored-split-anchors"});function T(n,e){throw new g(n,e)}function st(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function qt(n){return st(n)&&Object.keys(n).every(e=>e==="client"||e==="clock")&&Number.isSafeInteger(n.client)&&n.client>=0&&Number.isSafeInteger(n.clock)&&n.clock>=0}function Zt(n){return !st(n)||!Object.keys(n).every(e=>["type","item","assoc"].includes(e))||!qt(n.type)||n.item!==void 0&&!qt(n.item)||n.assoc!==0&&n.assoc!==-1?T("invalid-string",B):x__namespace.createRelativePositionFromJSON(n)}var ee=class{constructor(e,t,r){this.nodes=e;this.doc=t;this.limits=r;}nodes;doc;limits;sourceByAlias=new Map;aliasesBySource=new Map;pending=new Set;values=new Map;register(e,t,r,o){let i=this.nodes.get(e);(!S(i)||!(i.get(M)instanceof x__namespace.Text))&&T("invalid-bound",e);let a=this.read(t),s=a===null?{sourceId:t,text:this.sourceText(t),start:0,end:this.sourceText(t).length}:this.resolve(a);(s.sourceId.length===0||s.sourceId.length>this.limits.maxStringLength||f(s.sourceId))&&T("invalid-string",t),(!Number.isSafeInteger(r)||!Number.isSafeInteger(o)||r<0||o<r||o>s.end-s.start||e===s.sourceId)&&T("invalid-bound",e);let l=(p,h)=>{if(a&&h==="end"&&p===s.end-s.start)return a.end;if(a&&p===0)return a.start;if(a&&p===s.end-s.start)return a.end;let u=s.start+p;return x__namespace.createRelativePositionFromTypeIndex(s.text,u,u===0&&h==="start"?-1:0)},d=JSON.stringify({sourceId:s.sourceId,start:x__namespace.relativePositionToJSON(l(r,"start")),end:x__namespace.relativePositionToJSON(l(o,"end"))});d.length>this.limits.maxStringLength&&T("invalid-string",e),i.set(B,d),this.indexExisting(e);}normalizeRestoredAnchors(){let e=new Map,t=o=>{let i=o.item;if(i===null)return o;let a=`${i.client}:${i.clock}:${o.assoc}`,s=e.get(a);if(s)return s;let l=i,d=x__namespace.getItem(this.doc.store,l);for(;d instanceof x__namespace.Item&&d.redone!==null;)l=x__namespace.createID(d.redone.client,d.redone.clock+l.clock-d.id.clock),d=x__namespace.getItem(this.doc.store,l);let p=d instanceof x__namespace.Item&&!d.deleted&&!x__namespace.compareIDs(i,l)?x__namespace.createRelativePositionFromJSON({...x__namespace.relativePositionToJSON(o),item:{client:l.client,clock:l.clock}}):o;return e.set(a,p),p},r=[];for(let o of this.sourceByAlias.keys()){let i=this.read(o);if(!i)continue;let a=t(i.start),s=t(i.end);if(x__namespace.compareRelativePositions(a,i.start)&&x__namespace.compareRelativePositions(s,i.end))continue;let l=JSON.stringify({sourceId:i.sourceId,start:x__namespace.relativePositionToJSON(a),end:x__namespace.relativePositionToJSON(s)});l.length>this.limits.maxStringLength&&T("invalid-string",o),r.push({id:o,encoded:l});}r.length!==0&&this.doc.transact(()=>{for(let{id:o,encoded:i}of r)this.nodes.get(o).set(B,i),this.indexExisting(o);},uo);}sourceAliases(e){return [...this.aliasesBySource.get(e)??[]]}range(e){let t=this.read(e);return t===null?null:this.resolve(t)}value(e){let t=this.range(e);return t===null?null:t.text.toString().slice(t.start,t.end)}indexExisting(e){let t=this.read(e);t&&this.resolve(t);let r=this.sourceByAlias.get(e);if(r!==void 0&&r!==t?.sourceId){let o=this.aliasesBySource.get(r);o?.delete(e),o?.size===0&&this.aliasesBySource.delete(r),this.sourceByAlias.delete(e);}if(t){this.sourceByAlias.set(e,t.sourceId);let o=this.aliasesBySource.get(t.sourceId)??new Set;o.add(e),this.aliasesBySource.set(t.sourceId,o);}(t||r!==void 0||this.values.has(e))&&this.pending.add(e);}noteChanged(e){this.indexExisting(e);for(let t of this.aliasesBySource.get(e)??[])this.pending.add(t);}reset(){this.sourceByAlias.clear(),this.aliasesBySource.clear();for(let e of this.values.keys())this.pending.add(e);this.nodes.forEach((e,t)=>this.indexExisting(t));}overlays(){let e=new Set,t=new Map;for(let r of this.pending){let o=this.range(r),i=null;if(o){let a=t.get(o.sourceId);a===void 0&&(a=o.text.toString(),t.set(o.sourceId,a)),i=a.slice(o.start,o.end);}i===null?this.values.delete(r)&&e.add(r):i!==this.values.get(r)&&(this.values.set(r,i),e.add(r));}return this.pending.clear(),{values:this.values,changedIds:e}}sourceText(e){let t=this.nodes.get(e),r=S(t)?t.get(M):null;return !(r instanceof x__namespace.Text)||r.doc!==this.doc||r.length>this.limits.maxTextLength?T("invalid-bound",e):r}read(e){let t=this.nodes.get(e);if(!S(t)||!t.has(B))return null;let r=t.get(B);if(typeof r!="string"||r.length>this.limits.maxStringLength)return T("invalid-string",e);let o;try{o=JSON.parse(r);}catch{return T("invalid-string",e)}return !st(o)||!Object.keys(o).every(i=>["sourceId","start","end"].includes(i))||typeof o.sourceId!="string"||o.sourceId.length===0||o.sourceId.length>this.limits.maxStringLength||f(o.sourceId)||o.sourceId===e?T("invalid-string",e):t.get(M)instanceof x__namespace.Text?{sourceId:o.sourceId,start:Zt(o.start),end:Zt(o.end)}:T("invalid-bound",e)}resolve(e){let t=this.nodes.get(e.sourceId);if(S(t)&&t.has(B))return T("invalid-bound",e.sourceId);let r=this.sourceText(e.sourceId),o=x__namespace.createRelativePositionFromTypeIndex(r,0).type;if(!o||[e.start,e.end].some(s=>s.type?.client!==o.client||s.type?.clock!==o.clock))return T("invalid-bound",e.sourceId);let i=x__namespace.createAbsolutePositionFromRelativePosition(e.start,this.doc,false),a=x__namespace.createAbsolutePositionFromRelativePosition(e.end,this.doc,false);return i===null||a===null||i.type!==r||a.type!==r||i.index<0||a.index<i.index||a.index>r.length?T("invalid-bound",e.sourceId):{sourceId:e.sourceId,text:r,start:i.index,end:a.index,startAssoc:e.start.assoc,endAssoc:e.end.assoc,startAnchorDeleted:e.start.item!==null&&x__namespace.getItem(this.doc.store,e.start.item).deleted,endAnchorDeleted:e.end.item!==null&&x__namespace.getItem(this.doc.store,e.end.item).deleted}}};function ke(n,e,t,r,o,i){if(!r||i.length===0)return null;let a=o===0&&r.startAssoc!==-1,s=o===r.end-r.start;if(!a&&!s)return null;let l=JSON.parse(n.get(t).get(B)),d=x__namespace.createRelativePositionFromJSON(l.start),p=x__namespace.createRelativePositionFromJSON(l.end);if(s=s&&(a||p.item!==null&&x__namespace.getItem(r.text.doc.store,p.item).deleted),!a&&!s)return null;let h=[];for(let u of e.sourceAliases(r.sourceId)){if(!e.range(u))continue;let m=n.get(u),c=JSON.parse(m.get(B)),y=(R,E)=>{let v=x__namespace.createRelativePositionFromJSON(R);return a&&s&&x__namespace.compareRelativePositions(d,p)&&x__namespace.compareRelativePositions(v,d)?E==="start"?"after":"before":a&&x__namespace.compareRelativePositions(v,d)?"before":s&&x__namespace.compareRelativePositions(v,p)?"after":null},b=u===t&&a?"before":y(c.start,"start"),I=u===t&&s?"after":y(c.end,"end");(b||I)&&h.push({record:m,start:b,end:I});}return ()=>{let u=r.start+o,m=x__namespace.relativePositionToJSON(x__namespace.createRelativePositionFromTypeIndex(r.text,u,u===0&&r.startAssoc===-1?-1:0)),c=x__namespace.relativePositionToJSON(x__namespace.createRelativePositionFromTypeIndex(r.text,u+i.length,0));for(let y of h){let b=JSON.parse(y.record.get(B));y.start&&(b.start=y.start==="before"?m:c),y.end&&(b.end=y.end==="before"?m:c);let I=JSON.stringify(b);I!==y.record.get(B)&&y.record.set(B,I);}}}function Qt(n,e,t){if(t.keepBoundary&&n===t.start)return n;let r=n<=t.start?n:Math.max(t.start,n-t.deleted);return r<t.start||r===t.start&&e<0?r:r+t.inserted.length}var lt=class{constructor(e,t){this.registry=e;this.raw=t;}registry;raw;ranges=new Map;histories=new Map;strings=new Map;actions=[];shadow=null;range(e){if(this.shadow){let r=this.shadow.sources.range(e);return r?{...r,revision:0}:null}if(!this.ranges.has(e)){let r=this.registry.splitTextRange(e);this.ranges.set(e,r?{...r,revision:0}:null);}let t=this.ranges.get(e);if(t){let r=this.histories.get(t.sourceId)??[];for(;t.revision<r.length;){let o=r[t.revision],i=(a,s)=>{let l=s<0?a-1:a;return l>=o.start&&l<o.start+o.deleted};if(t.startAnchorDeleted||t.endAnchorDeleted||o.ambiguousBoundary||i(t.start,t.startAssoc)||i(t.end,t.endAssoc)){this.ensureShadow();let a=this.shadow.sources.range(e);return a?{...a,revision:0}:null}t.start=Qt(t.start,t.startAssoc,o),t.end=Qt(t.end,t.endAssoc,o),t.revision+=1;}}return t}value(e){let t=this.range(e);if(t)return this.value(t.sourceId).slice(t.start,t.end);let r=this.strings.get(e);if(r===void 0){r=this.registry.hasNode(e)?this.registry.textOf(e).toString():"";for(let o of this.histories.get(e)??[])r=r.slice(0,o.start)+o.inserted+r.slice(o.start+o.deleted);this.strings.set(e,r);}return r}apply(e){let t=ie(e),r=t?this.range(t.logicalId):null,o={keepBoundary:t?.utf16Start===0&&r?.startAssoc!==-1&&e.insert.length>0,ambiguousBoundary:r!==null&&r.start===r.end&&e.insert.length>0,start:e.utf16Start,deleted:e.deleteCount,inserted:e.insert},i=this.histories.get(e.logicalId)??[];i.push(o),this.histories.set(e.logicalId,i);let a=this.strings.get(e.logicalId);a!==void 0&&this.strings.set(e.logicalId,a.slice(0,o.start)+o.inserted+a.slice(o.start+o.deleted));let s={kind:"splice",effect:e};this.actions.push(s),this.shadow&&this.replay(s);}register(e,t,r,o){let i=this.range(t),a=i?.sourceId??t,s=i?.start??0,l=i?i.end-i.start:this.raw.node(t)?.textLength??0,d=(m,c)=>i&&c==="end"&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:i&&m===0?{assoc:i.startAssoc,deleted:i.startAnchorDeleted}:i&&m===l?{assoc:i.endAssoc,deleted:i.endAnchorDeleted}:{assoc:s+m===0&&c==="start"?-1:0,deleted:false},p=d(r,"start"),h=d(o,"end");this.ranges.set(e,{sourceId:a,start:s+r,end:s+o,startAssoc:p.assoc,endAssoc:h.assoc,startAnchorDeleted:p.deleted,endAnchorDeleted:h.deleted,revision:this.histories.get(a)?.length??0});let u={kind:"register",product:e,source:t,start:r,end:o};this.actions.push(u),this.shadow&&this.replay(u);}destroy(){this.shadow?.doc.destroy();}ensureShadow(){if(this.shadow)return;let e=new x__namespace.Doc({gc:false}),t=e.getMap(Ze);this.shadow={doc:e,nodes:t,sources:new ee(t,e,this.registry.limits)},x__namespace.applyUpdate(e,x__namespace.encodeStateAsUpdate(this.registry.doc)),e.clientID=this.registry.doc.clientID,this.shadow.sources.reset();for(let r of this.actions)this.replay(r);}replay(e){let t=this.shadow,r=h=>(t.nodes.has(h)||t.nodes.set(h,Le("")),t.nodes.get(h).get(M));if(e.kind==="register"){r(e.product),t.sources.register(e.product,e.source,e.start,e.end);return}let{effect:o}=e,i=ie(o),a=i?t.sources.range(i.logicalId):null,s=a?.text??r(o.logicalId),l=i?.utf16Start??o.utf16Start,d=(a?.start??0)+l,p=ke(t.nodes,t.sources,i?.logicalId??o.logicalId,a,l,o.insert);o.deleteCount>0&&s.delete(d,o.deleteCount),o.insert.length>0&&s.insert(d,o.insert),p?.();}},dt=class extends W{constructor(t,r,o,i){super(t);this.hidden=r;this.raw=o;this.text=i;}hidden;raw;text;filtered=new Set;node(t){let r=super.node(t);if(r&&!this.filtered.has(t)&&(this.filtered.add(t),r.children=r.children.filter(o=>!this.hidden.has(o))),r?.isText){let o=this.text.range(t);r.textLength=o?o.end-o.start:this.raw.node(t)?.textLength??r.textLength;}return r}};function en(n,e){let t=n.replacementLoserRuns(),r=e.effects.filter(c=>c.kind==="putNode").length;if(n.nodeCount()+r>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let o=new Set;for(let c of e.effects){if(c.kind==="spliceChildren"){if(c.childLogicalIds.length>n.limits.maxChildren)return {ok:false,code:"too-many-children"};for(let y of c.childLogicalIds)o.add(y);}else c.kind==="moveNode"&&o.add(c.logicalId);if(o.size>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"}}let i=new W(n),a=new lt(n,i),s=new dt(n,t,i,a),l=new Map,d=c=>l.get(c)?.kind??n.kindOf(c),p={limits:n.limits,projectedTextValue:c=>i.node(c)?.isText?a.value(c):null,registerSplitText:(c,y,b,I)=>a.register(c,y,b,I),record:c=>{let y=i.node(c);if(!y)return null;if(y.isText)return {logicalId:c,kind:"textValue",value:a.value(c)};let b=l.get(c),I=b?null:n.record(c);return I&&I.kind!=="textValue"?{...I,childIds:y.children}:!b||b.kind==="textValue"?null:{logicalId:c,kind:b.kind,namespaceUri:b.qname.namespaceUri,localName:b.qname.localName,prefix:b.qname.prefix??"",attributes:[],bindings:[],childIds:y.children}}},h=[],u=null,m=c=>{if(u)return;let y=Ce(n,c,i);if(y&&!y.ok){u=y;return}h.push(c),pe(i,c),c.kind==="spliceText"&&a.apply(c);};try{for(let c of e.effects){let y=Ce(n,c,s);if(y&&!y.ok)return y;if(pe(s,c),c.kind==="putNode"&&l.set(c.descriptor.logicalId,c.descriptor),c.kind==="spliceText"){let b=a.range(c.logicalId),I=b?{...c,logicalId:b.sourceId,utf16Start:b.start+c.utf16Start}:c;b&&We.set(I,{logicalId:c.logicalId,utf16Start:c.utf16Start}),m(I);}else if(c.kind==="spliceChildren"){let b=i.node(c.parentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let I=b.children.flatMap((v,w)=>t.has(v)?[]:[w]),R=I.slice(c.start,c.start+c.deleteCount).map(v=>b.children[v]),E=I[c.start]??b.children.length;if(c.deleteCount===0)m({...c,start:E});else {let v=I.slice(c.start,c.start+c.deleteCount),w=v.length;for(;w>0;){let Y=w-1;for(;Y>0&&v[Y-1]===v[Y]-1;)Y-=1;m({...c,start:v[Y],deleteCount:w-Y,childLogicalIds:Y===0?c.childLogicalIds:[]}),w=Y;}}if(!u&&c.childLogicalIds.length>0){let v=c.childLogicalIds.filter(w=>d(w)==="run");for(let w of R)d(w)==="run"&&(!o.has(w)||l.has(w))&&we(p,w,v);}}else if(c.kind==="moveNode"){let b=i.node(c.destinationParentLogicalId);if(!b||b.isText)return {ok:!1,code:"invalid-bound"};let I=b.children.filter(E=>E!==c.logicalId),R=I.flatMap((E,v)=>t.has(E)?[]:[v]);m({...c,destinationIndex:R[c.destinationIndex]??I.length});}else m(c);if(u)return u}return {ok:!0,journal:{effects:h}}}finally{a.destroy();}}var po=new Set(["paraId","textId","id","numId","bookmarkId"]);function tn(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function nn(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),tn(e)}function Pe(n){return /^[0-9a-f]{32}$/.test(n)}function rn(n,e){if(!Pe(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 ct(n,e){return `yjs:${n}:${e}`}function ut(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return Pe(e)?e:null}function pt(n){let e=[];for(let t of n)po.has(t.localName)&&e.push(t.value);return e}var he=class{replicaId;next=0;constructor(e){if(this.replicaId=e??nn(),!Pe(this.replicaId))throw new Error("invalid replica identity")}take(){let e=rn(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};function on(n,e){let t=i=>{let a=new Set,s=false;for(let l of i){let d=l.path;if(d.length===0){for(let p of l.changes.keys.keys())a.add(String(p));s=true;continue}a.add(String(d[0])),l.target instanceof x__namespace.Array&&(s=true),l.target instanceof x__namespace.Map&&(l.changes.keys.has(z)||l.changes.keys.has(X))&&(s=true);}(a.size>0||s)&&e({logicalIds:a,membershipChanged:s,packageChanged:false});},r=i=>{let a=new Set;for(let s of i.changes.keys.keys()){let l=q(String(s))??Z(String(s));!l||f(l.logicalId)||a.add(l.logicalId);}a.size>0&&e({logicalIds:a,membershipChanged:false,packageChanged:false});},o=()=>{e({logicalIds:new Set,membershipChanged:false,packageChanged:true});};return n.nodes.observeDeep(t),n.attributes.observe(r),n.bindings.observe(r),n.parts.observeDeep(o),n.relationships.observeDeep(o),n.overrides.observe(o),n.defaults.observe(o),n.binaries.observeDeep(o),()=>{n.nodes.unobserveDeep(t),n.attributes.unobserve(r),n.bindings.unobserve(r),n.parts.unobserveDeep(o),n.relationships.unobserveDeep(o),n.overrides.unobserve(o),n.defaults.unobserve(o),n.binaries.unobserveDeep(o);}}var Ae=class{constructor(e){this.nodes=e;}nodes;cachedLosers=null;invalidate(){this.cachedLosers=null;}runsBySplitOrigin=new Map;liveRootedOrigins=new Set;reset(){this.invalidate(),this.runsBySplitOrigin.clear(),this.liveRootedOrigins.clear();}record(e,t,r){this.invalidate();for(let o of r){if(o===e)continue;let i=this.nodes.get(o);S(i)&&(i.set(Qe,e),i.set(se,e),this.indexExisting(o));}}indexExisting(e){let t=it(this.nodes.get(e));if(t===null||t===e)return;this.invalidate();let r=this.runsBySplitOrigin.get(t)??new Set;r.add(e),this.runsBySplitOrigin.set(t,r),this.liveRootedOrigins.add(t);}productsOf(e){return [...this.runsBySplitOrigin.get(e)??[]].filter(t=>it(this.nodes.get(t))===e)}loserRuns(e){if(this.cachedLosers)return this.cachedLosers;let t=new Set,r=new Set,o=i=>{let a=[i];for(;a.length>0;){let s=a.pop();if(!r.has(s)){r.add(s),e.isPresent(s)&&t.add(s);for(let l of this.productsOf(s))a.push(l);}}};for(let i of this.liveRootedOrigins){let a=this.productsOf(i),s=e.isPresent(i)?null:a.filter(l=>ue(this.nodes.get(l))===i).map(l=>ut(l)??"").sort()[0];for(let l of a)(ut(l)??"")!==s&&o(l);}return this.cachedLosers=t,t}};function an(n,e){if(!n.hasNode(e)||n.isTombstoned(e))return false;let t=n.parentOf(e);if(t===null)return false;let r=n.record(t);return r!==null&&L(r)&&r.childIds.includes(e)}function Te(n){return typeof n=="string"?n:""}function sn(n,e){return n<e?-1:n>e?1:0}function ht(n,e){return `${n}${P}${e}`}function mo(n){let e=n.indexOf(P);return e<0?n:n.slice(0,e)}function ln(n){let e=[];return n.forEach((t,r)=>{!S(t)||f(r)||t.forEach(o=>{if(!S(o))return;let i=Te(o.get("id")),a=Te(o.get("type"));if(i.length===0||a.length===0)return;let s=Te(o.get("ownerPart"))||mo(r);if(f(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:Te(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||sn(t.ownerPart,r.ownerPart)||sn(t.id,r.id)),e}function dn(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 go(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 cn(n,e){let t=n.childrenSnapshot.get(e);return t||(D(n.nodes.get(e))?.toArray()??[])}function fo(n,e){let t=n.nodes.get(e);return !S(t)||J(t)}function yo(n,e,t,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),fo(n,a)))return null;s=e.get(a);let p=n.parentIndex.get(a);if(s!==void 0){if(p!==void 0)return "fallback";break}if(p===void 0)return t.has(a)?"deferred":null;o.push(a),a=p;}let l=[s],d=a;for(let p=o.length-1;p>=0;p-=1){let h=o[p],u=cn(n,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function un(n,e){let t=new Set(e);for(let i of t)n.parentIndex.delete(i);let r=new Map;n.partRoots.forEach((i,a)=>{r.has(i)||r.set(i,a);});let o=[...t];for(;o.length>0;){let i=[];for(let a of o){let s=null,l=false;for(let d of n.listings.get(a)??[]){if(d===a)continue;let p=yo(n,r,t,d);if(p==="fallback")return false;if(p==="deferred"){l=true;continue}if(p===null)continue;let h=cn(n,d).indexOf(a);if(h<0)continue;let u=[...p,h];(!s||go(u,s.rank)<0)&&(s={rank:u,parent:d});}if(l){i.push(a);continue}s&&n.parentIndex.set(a,s.parent),t.delete(a);}if(i.length===o.length)return false;o=i;}return true}function pn(n,e){let{nodes:t,parentIndex:r,childrenSnapshot:o,partRoots:i}=n;if(e)for(let a of e)r.delete(a);for(let a of i){let s=new Set,l=[{id:a,parent:null,exit:false}];for(;l.length>0;){let d=l.pop();if(d.exit){s.delete(d.id);continue}let p=d.id;if(d.parent!==null&&(e===null||e.has(p))&&(r.has(p)||r.set(p,d.parent)),s.has(p))continue;let h=t.get(p);if(!S(h)||J(h))continue;let u=o.get(p)??D(h)?.toArray()??[];s.add(p),l.push({id:p,parent:null,exit:true});let m=new Set,c=[];for(let y of u)m.has(y)||y===p||(m.add(y),c.push(y));for(let y=c.length-1;y>=0;y-=1)l.push({id:c[y],parent:p,exit:false});}}}function hn(n,e){return `${n}${P}${e}`}function mt(n,e,t,r,o){if(f(t)||f(r.localName))return;let i=G(n.namespaces,r.namespaceUri,e),a=nt(t,i,r.localName);f(a)||n.attributes.set(a,Kt(r.prefix??"",o));}function mn(n,e,t,r){n.attributes.delete(nt(e,le(t),r));}function gt(n,e,t,r,o){if(f(t)||f(r))return;let i=G(n.namespaces,o,e),a=rt(t,r);f(a)||n.bindings.set(a,i);}function gn(n,e,t){n.bindings.delete(rt(e,t));}function ft(n,e,t,r,o,i){let{prefix:a,value:s}=Vt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(hn(r,o),{namespaceUri:de(n.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function bo(n,e,t,r){let o=n.get(e);o&&(o.delete(hn(t,r)),o.size===0&&n.delete(e));}function yt(n,e,t,r,o){let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(r,{prefix:r,namespaceUri:de(n.namespaces,o)});}function xo(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function fn(n,e,t){for(let[r,o]of t.changes.keys){let i=q(String(r));if(!i||f(i.logicalId)||f(i.localName))continue;if(o.action==="delete"){bo(e,i.logicalId,i.namespaceId,i.localName);continue}let a=n.attributes.get(String(r));typeof a=="string"&&ft(n,e,i.logicalId,i.namespaceId,i.localName,a);}}function yn(n,e,t){for(let[r,o]of t.changes.keys){let i=Z(String(r));if(!i||f(i.logicalId)||f(i.prefix))continue;if(o.action==="delete"){xo(e,i.logicalId,i.prefix);continue}let a=n.bindings.get(String(r));typeof a=="string"&&yt(n,e,i.logicalId,i.prefix,a);}}function xn(n,e){let t=n.get(e);if(!S(t))return null;if(ce(t)){let r=t.get(M);return {isText:true,textLength:r instanceof x__namespace.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:D(t)?.toArray()??[]}}function In(n,e){let t=n.get(e);return S(t)?ce(t)?"textValue":tt(t).kind:null}function vn(n,e){if(n.length!==e.length)return false;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return false;return true}function Sn(n,e,t,r,o){let i=tt(e);return {logicalId:n,kind:i.kind,namespaceUri:de(t.namespaces,i.namespaceId),localName:i.localName,prefix:i.prefix.length>0?i.prefix:void 0,attributes:r,bindings:o,childIds:D(e)?.toArray()??[]}}function ne(n){return typeof n=="string"?n:""}function En(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||f(r))return;let o=ne(t.get("rootId"));o.length!==0&&e.push({name:r,id:ne(t.get("id")),rootLogicalId:o,contentType:ne(t.get("contentType"))});}),e.sort((t,r)=>t.name<r.name?-1:t.name>r.name?1:0),e}function Rn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!f(r)&&e.set(store.partNameKey(r),t);}),e}function Ln(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!f(r)&&e.set(r,t);}),e}function wn(n){let e=[];return n.forEach((t,r)=>{if(!S(t)||f(r))return;let o=ne(t.get("digest")),i=t.get("size"),a=ne(t.get("mediaType")),s=ne(t.get("storageKey"))||r;o.length===0||typeof i!="number"||e.push({digest:o,size:i,mediaType:a,storageKey:s});}),e}function vo(n){return n?._item??null}function So(n){return n.content instanceof x__namespace.ContentType}function kn(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=vo(t);return r===null||r.parent!==n?true:e.parentSub===se||e.parentSub===Se?false:!So(e)}}function Eo(n){let e=n._item;return e?ct(e.id.client,e.id.clock):null}function Ro(n){return typeof n=="string"?n:""}var _=class{constructor(e,t){this.doc=e;this.schema=jt(e),this.limits=Tt(t),this.splitDedup=new Ae(this.schema.nodes),this.splitTextSources=new ee(this.schema.nodes,this.doc,this.limits),this.stopObserving=dn(this.schema,{onNodeEvents:r=>{this.bulkLoad>0||this.applyChildArrayEvents(r);},onAttributeEvent:r=>{this.bulkLoad>0||this.applyAttributeMapEvent(r);},onBindingEvent:r=>{this.bulkLoad>0||this.applyBindingMapEvent(r);},onRelationshipChange:()=>{this.relationshipCountCache=-1;},onPartChange:()=>{this.partCountCache=-1;}});}doc;schema;limits;parentIndex=new Map;listings=new Map;childrenSnapshot=new Map;adoptees=new Map;tombstoneSources=new Map;tombstoneSurvivor=new Map;attributesByNode=new Map;bindingsByNode=new Map;splitDedup;splitTextSources;bulkLoad=0;unobservedWrites=0;nodeCountCache=-1;pendingNodeAdds=0;relationshipCountCache=-1;partCountCache=-1;stopObserving;destroy(){this.stopObserving();}beginBulkLoad(){this.bulkLoad+=1;}endBulkLoad(){this.bulkLoad=Math.max(0,this.bulkLoad-1),this.bulkLoad===0&&this.rebuildDerivedIndexes();}trackedTypes(){return [this.schema.meta,this.schema.nodes,this.schema.parts,this.schema.relationships,this.schema.overrides,this.schema.defaults,this.schema.binaries,this.schema.attributes,this.schema.bindings]}undoDeleteFilter(){return kn(this.schema.nodes)}encodeSnapshot(){return x__namespace.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return x__namespace.encodeStateAsUpdate(this.doc,e)}partEntries(){return En(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 Ro(this.schema.meta.get("mainDocumentPart"))}record(e){if(f(e))return null;let t=this.schema.nodes.get(e);if(!S(t))return null;if(ce(t)){let r=t.get(M),o=r instanceof x__namespace.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return Sn(e,t,this.schema,[...this.attributesByNode.get(e)?.values()??[]],[...this.bindingsByNode.get(e)?.values()??[]])}parentOf(e){return this.parentIndex.get(e)??null}identityMeta(e){let t=this.schema.nodes.get(e);if(!t)return null;let r=this.record(e),o=r&&L(r)?r.attributes:[];return {logicalId:e,yjsItemKey:Eo(t),wordFacingIds:pt(o)}}isTombstoned(e){return J(this.schema.nodes.get(e))}replacedByOf(e){return ot(this.schema.nodes.get(e))}adoptedChildren(e){return this.adoptees.get(e)??[]}adoptionIndex(){return this.adoptees}hasNamespace(e){return this.schema.namespaces.get(le(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=>!f(e))}nodeCount(){return this.nodeCountCache<0&&(this.nodeCountCache=this.schema.nodes.size),this.nodeCountCache+this.pendingNodeAdds}nodeShape(e){return f(e)?null:xn(this.schema.nodes,e)}kindOf(e){return f(e)?null:In(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=G(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Jt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)mt(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)gt(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=G(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(ve,et(t.kind,o,t.localName,t.prefix??""));}putText(e,t){this.noteNodeWrite(e),this.schema.nodes.set(e,Le(t));}spliceText(e,t,r,o){let i=this.splitTextSources.range(e),a=ke(this.schema.nodes,this.splitTextSources,e,i,t,o),s=i?.text??this.textOf(e),l=(i?.start??0)+t;r>0&&s.delete(l,r),o.length>0&&s.insert(l,o),a?.();}setAttribute(e,t,r){if(r===null){mn(this.schema,e,t.namespaceUri,t.localName);return}mt(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){gn(this.schema,e,t);return}gt(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(z,true),t&&r.set(X,t);}recordRunSplit(e,t,r){this.splitDedup.record(e,t,r);}splitOriginOf(e){return ue(this.schema.nodes.get(e))}replacementLoserRuns(){return this.hasUnobservedWrites()&&this.splitDedup.invalidate(),this.splitDedup.loserRuns({isPresent:e=>an(this,e)})}splitTextRange(e){return this.splitTextSources.range(e)}projectedTextValue(e){return this.splitTextSources.value(e)}registerSplitText(e,t,r,o){this.splitTextSources.register(e,t,r,o);}normalizeRestoredSplitTextAnchors(){this.splitTextSources.normalizeRestoredAnchors();}concurrentSplitTextOverlays(){return this.splitTextSources.overlays()}unlistChildren(e,t){if(t.length===0)return;let r=this.schema.nodes.get(e),o=r?D(r):null;if(!o)return;let i=new Map;for(let a of t)i.set(a,(i.get(a)??0)+1);for(let a=o.length-1;a>=0;a-=1){let s=o.get(a),l=i.get(s)??0;l!==0&&(i.set(s,l-1),o.delete(a,1));}}putXmlPart(e){this.partCountCache=-1,this.schema.parts.set(e.name,Wt(e.id,e.rootLogicalId,e.contentType));}deleteXmlPart(e){this.partCountCache=-1,this.schema.parts.delete(e);}putRelationship(e){if(f(e.ownerPart)||f(e.id))return;this.relationshipCountCache=-1;let t=new x__namespace.Map;t.set(e.id,$t(e)),this.schema.relationships.set(ht(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(ht(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(store.partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(store.partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,Xt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return ln(this.schema.relationships)}contentTypeOverrides(){return Rn(this.schema.overrides)}contentTypeDefaults(){return Ln(this.schema.defaults)}binaries(){return wn(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){return on(this.schema,e)}rebuildDerivedIndexes(){this.unobservedWrites=0,this.nodeCountCache=-1,this.pendingNodeAdds=0,this.relationshipCountCache=-1,this.partCountCache=-1,this.parentIndex=new Map,this.listings=new Map,this.childrenSnapshot=new Map,this.adoptees=new Map,this.tombstoneSources=new Map,this.tombstoneSurvivor=new Map,this.attributesByNode=new Map,this.bindingsByNode=new Map,this.splitDedup.reset(),this.splitTextSources.reset(),this.schema.nodes.forEach((e,t)=>{if(f(t))return;let r=D(e);if(!r)return;let o=r.toArray();this.childrenSnapshot.set(t,o);for(let i of o)this.addListing(i,t);}),this.schema.nodes.forEach((e,t)=>{J(e)&&this.syncAdoptee(t),this.splitDedup.indexExisting(t);}),this.schema.attributes.forEach((e,t)=>{if(typeof e!="string"||f(t))return;let r=q(t);!r||f(r.logicalId)||f(r.localName)||ft(this.schema,this.attributesByNode,r.logicalId,r.namespaceId,r.localName,e);}),this.schema.bindings.forEach((e,t)=>{if(typeof e!="string"||f(t))return;let r=Z(t);!r||f(r.logicalId)||f(r.prefix)||yt(this.schema,this.bindingsByNode,r.logicalId,r.prefix,e);}),this.assignFirstReachable(null);}assertNoParentFields(){this.schema.nodes.forEach(e=>{if(S(e)&&(e.has("parent")||e.has("parentId")))throw new Error("registry record must not replicate a parent field")});}applyChildArrayEvents(e){this.unobservedWrites=0,this.pendingNodeAdds=0;let t=new Set;for(let r of e){if(!(r.target instanceof x__namespace.Text)&&(r.path.length===0||r.target instanceof x__namespace.Array||r.target instanceof x__namespace.Map&&[...r.changes.keys.keys()].some(o=>["deleted","replacedBy","splitFrom","splitLineage","children"].includes(String(o))))&&this.splitDedup.invalidate(),r.path.length>0&&this.splitTextSources.noteChanged(String(r.path[0])),r.path.length===0&&r.target instanceof x__namespace.Map){for(let[o,i]of r.changes.keys)if(this.nodeCountCache>=0&&i.action!=="update"&&(this.nodeCountCache+=i.action==="add"?1:-1),!(i.action==="delete"||f(String(o)))){this.splitDedup.indexExisting(String(o)),this.splitTextSources.indexExisting(String(o));for(let a of this.syncChildListings(String(o)))t.add(a);}continue}if(r.target instanceof x__namespace.Map&&r.path.length===1&&(r.changes.keys.has("splitFrom")||r.changes.keys.has("splitLineage"))&&this.splitDedup.indexExisting(String(r.path[0])),r.target instanceof x__namespace.Array&&r.path.length>0){let o=String(r.path[0]);for(let i of this.syncChildListings(o))t.add(i);this.isTombstoned(o)&&this.syncAdoptee(o);continue}r.target instanceof x__namespace.Map&&r.path.length===1&&(r.changes.keys.has(z)||r.changes.keys.has(X))&&this.syncAdoptee(String(r.path[0]));}t.size>0&&this.resolveParents(t);}applyAttributeMapEvent(e){this.unobservedWrites=0,fn(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,yn(this.schema,this.bindingsByNode,e);}syncChildListings(e){let t=this.schema.nodes.get(e),r=t?D(t)?.toArray()??[]:[],o=this.childrenSnapshot.get(e)??[];if(vn(o,r))return [];let i=new Set(r),a=new Set(o),s=[];for(let l of o)i.has(l)||(this.removeListing(l,e),s.push(l));for(let l of r)a.has(l)||(this.addListing(l,e),s.push(l));return this.childrenSnapshot.set(e,r),s}addListing(e,t){let r=this.listings.get(e)??new Set;r.add(t),this.listings.set(e,r);}removeListing(e,t){let r=this.listings.get(e);r&&(r.delete(t),r.size===0&&this.listings.delete(e));}resolveParents(e){let t=[];for(let o of e){let i=this.listings.get(o);if(!i||i.size===0){this.parentIndex.delete(o);continue}if(i.size===1){this.parentIndex.set(o,[...i][0]);continue}t.push(o);}if(t.length===0)return;un({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){pn({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=ot(r);if(o!==null){if(J(r)){let i=this.tombstoneSources.get(o)??new Set;i.add(e),this.tombstoneSources.set(o,i),this.tombstoneSurvivor.set(e,o);}this.recomputeAdoptees(o);}}isContentWitness(e){let t=this.kindOf(e);return t!==null&&!t.endsWith("Properties")}recomputeAdoptees(e){let t=[];for(let r of this.tombstoneSources.get(e)??[]){let o=this.schema.nodes.get(r);if(o)for(let i of D(o)?.toArray()??[])this.isTombstoned(i)||!this.schema.nodes.has(i)||this.isContentWitness(i)&&t.push(i);}t.length>0?this.adoptees.set(e,t):this.adoptees.delete(e);}unlinkFromAllParents(e){let t=[...this.listings.get(e)??[]];if(t.length===0){this.schema.nodes.forEach(r=>{let o=D(r);o&&this.removeFromArray(o,e);});return}for(let r of t){let o=this.schema.nodes.get(r),i=o?D(o):null;i&&this.removeFromArray(i,e);}}removeFromArray(e,t){for(let r=e.length-1;r>=0;r-=1)e.get(r)===t&&e.delete(r,1);}textOf(e){let t=this.require(e).get(M);if(!(t instanceof x__namespace.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(Ee);if(!(t instanceof x__namespace.Array))throw new Error(`no children at ${e}`);return t}require(e){let t=this.schema.nodes.get(e);if(!t)throw new Error(`registry node ${e} missing`);return t}};var Ne=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 On(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 An(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 wo(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function Co(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Mn(n,e,t,r,o){if(r>n.limits.maxTreeDepth)return "tree-too-deep";if(f(e.id))return "prototype-key";if(o.nodes+=1,o.nodes>n.limits.maxNodes)return "too-many-nodes";if(e.kind==="textValue"){if(e.value.length>n.limits.maxTextLength)return "text-too-long";n.putText(e.id,e.value);}else {if(e.attributes.length>n.limits.maxAttributes)return "too-many-attributes";if(e.children.length>n.limits.maxChildren)return "too-many-children";if(A(e.namespaceUri,n.limits.maxStringLength))return "invalid-string";for(let i of e.attributes){if(f(i.localName))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}for(let i of e.namespaceBindings){if(f(i.prefix))return "prototype-key";if(A(i.namespaceUri,n.limits.maxStringLength))return "invalid-string"}n.putElement({logicalId:e.id,kind:e.kind,namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,attributes:wo(e),bindings:Co(e)});for(let i of e.children){let a=Mn(n,i,e.id,r+1,o);if(a)return a}}return t&&n.childArray(t).push([e.id]),null}async function ko(n){let e=[],t=[];for(let[r,o]of n.partBytes){if(n.parts.has(r))continue;let a=n.contentTypes.overrides.get(r)??"application/octet-stream",s=O(r);if(s)return {ok:false,code:s};if(o.byteLength>U.maxBlobBytes)return {ok:false,code:"blob-too-large"};let l=await On(o);t.push({digest:l,bytes:o}),e.push({digest:l,size:o.byteLength,mediaType:a,storageKey:r});}return {ok:true,descriptors:e,payloads:t}}async function me(n,e,t=new Ne){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await ko(e);if(!r.ok)return r;let o=null;n.beginBulkLoad();try{n.doc.transact(()=>{for(let s of r.payloads)t.put(s.digest,s.bytes);let i={nodes:0};for(let[s,l]of e.parts){let d=O(s);if(d){o=d;return}if(A(l.contentType,n.limits.maxMediaTypeLength)){o="invalid-string";return}let p=Mn(n,l.root,null,0,i);if(p){o=p;return}n.putXmlPart({name:s,id:l.id,rootLogicalId:l.root.id,contentType:l.contentType});}let a=0;for(let s of e.relationships.values())for(let l of s){if(a+=1,a>n.limits.maxRelationships){o="too-many-relationships";return}if(l.ownerPart!=="/"){let d=O(l.ownerPart);if(d){o=d;return}}if(f(l.id)){o="prototype-key";return}n.putRelationship({ownerPart:l.ownerPart,id:l.id,type:l.type,rawTarget:l.rawTarget,targetMode:l.targetMode,order:l.order});}for(let[s,l]of e.contentTypes.defaults){if(f(s)){o="prototype-key";return}n.putContentTypeDefault(s,l);}for(let[s,l]of e.contentTypes.overrides){let d=O(s);if(d){o=d;return}n.putContentTypeOverride(s,l);}for(let s of r.descriptors)n.putBinary(s);Ht(n.schema.meta),n.schema.meta.set("mainDocumentPart",e.mainDocumentPart);},Ut);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var De="http://schemas.openxmlformats.org/package/2006/relationships",Po="application/vnd.openxmlformats-package.relationships+xml",Dn=/^(.*)\/_rels\/([^/]*)\.rels$/;function Bn(n){return Dn.test(n)}function _n(n){let e=Dn.exec(n);return e?e[2]===""?"/":`${e[1]}/${e[2]}`:null}function ge(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Me(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function Oo(n,e){let t=[Me("Id",e.id),Me("Type",e.type),Me("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(Me("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:De,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function Yn(n,e){if(n.kind==="textValue"||n.namespaceUri!==De||n.localName!=="Relationship"||ge(n,"Id")!==e.id||ge(n,"Type")!==e.type||ge(n,"Target")!==e.rawTarget)return false;let t=ge(n,"TargetMode");return e.targetMode==="External"?t==="External":t===void 0}function Un(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>Yn(t,e[r]))}function zn(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 jn(n,e,t){let r=[];for(let o of e){if(f(o.id))continue;let i=n.find(s=>s.kind!=="textValue"&&ge(s,"Id")===o.id);if(i&&Yn(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;f(a)||r.push(Oo(a,o));}return r}function Ao(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:De,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:De})]),attributes:Object.freeze([]),children:Object.freeze([])})}function Fn(n){return Object.freeze({id:n,name:n,contentType:Po,root:Ao(n)})}function Kn(n){let e=new Map;for(let t of n){if(f(t.id)||t.ownerPart!=="/"&&O(t.ownerPart))continue;let r=e.get(t.ownerPart)??[];r.push(t),e.set(t.ownerPart,r);}return e}var $n=/^\/customXml\/item(\d+)\.xml$/i,Do=/^\/customXml\/itemProps(\d+)\.xml$/i;function ye(n){return $n.test(n)}function xt(n){return Do.test(n)}function Bo(n){let e=$n.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 _o(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 Jn(n,e){let t=n.record(e);return !t||!L(t)?e:t.attributes.find(o=>o.localName==="id"&&o.value.length>0)?.value??e}function Yo(n,e){let t=n.record(e);if(!t||!L(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!L(o)||o.localName!=="schemaRefs")&&o.namespaceUri===store.DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=n.record(i);if(!a||!L(a)||a.localName!=="schemaRef")continue;let s=_o(a,"uri",store.DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function Uo(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&L(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function zo(n,e){return e.localName==="node"||e.namespaceUri===store.WML_NAMESPACE_URI||e.namespaceUri===store.DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:Uo(n,e)}function jo(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==store.DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function Xn(n,e){if(!n.hasNamespace(store.DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,m]of e){let c=n.record(m.root.id);!c||!L(c)||(ye(u)&&t.set(c.logicalId,c),xt(u)&&r.set(c.logicalId,c));}for(let u of n.allLogicalIds()){if(n.isTombstoned(u)||t.has(u)||r.has(u))continue;let m=n.record(u);!m||!L(m)||(zo(n,m)?t.set(u,m):jo(n,m)&&r.set(u,m));}if(t.size===0)return [];let o=new Map;for(let u of t.values()){let m=o.get(u.namespaceUri)??[];m.push(u),o.set(u.namespaceUri,m);}let i=new Map;for(let u of r.values()){let m=Yo(n,u.logicalId);if(!m)continue;let c=i.get(m)??[];c.push(u),i.set(m,c);}let a=[];for(let[u,m]of o){let c=i.get(u);if(!c||c.length===0)continue;m.sort((E,v)=>E.logicalId.localeCompare(v.logicalId)),c.sort((E,v)=>E.logicalId.localeCompare(v.logicalId));let y=m[0],b=c[0],I=[],R=new Set;for(let E of m)for(let v of E.childIds){if(R.has(v))continue;let w=n.record(v);!w||!L(w)||w.localName!=="node"||w.namespaceUri!==u||(R.add(v),I.push(v));}for(let E of n.allLogicalIds()){if(R.has(E)||n.isTombstoned(E))continue;let v=n.record(E);!v||!L(v)||v.localName!=="node"||v.namespaceUri!==u||(R.add(E),I.push(E));}I.sort((E,v)=>Jn(n,E).localeCompare(Jn(n,v))),a.push({data:y,props:b,nodeIds:I});}a.sort((u,m)=>u.data.logicalId.localeCompare(m.data.logicalId));let s=new Set,l=[],d=new Set,p=new Set;for(let[u,m]of e){let c=Bo(u);if(c===null)continue;let y=a.find(R=>R.data.logicalId===m.root.id&&!d.has(R.data.logicalId));if(!y)continue;let b=Vn(c).props,I=e.get(b);I&&I.root.id!==y.props.logicalId||(s.add(c),d.add(y.data.logicalId),p.add(y.props.logicalId),l.push({dataRootId:y.data.logicalId,propsRootId:y.props.logicalId,namespaceUri:y.data.namespaceUri,itemName:u,propsName:b,nodeIds:y.nodeIds}));}let h=1;for(let u of a){if(d.has(u.data.logicalId))continue;for(;s.has(h);)h+=1;s.add(h);let m=Vn(h);l.push({dataRootId:u.data.logicalId,propsRootId:u.props.logicalId,namespaceUri:u.data.namespaceUri,itemName:m.item,propsName:m.props,nodeIds:u.nodeIds}),h+=1;}return l.sort((u,m)=>u.itemName.localeCompare(m.itemName)),l}function Fo(n){return n.type===store.CUSTOM_XML_REL||n.type===store.CUSTOM_XML_PROPS_REL?true:ye(n.ownerPart)}function Ko(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Vo(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 Hn(n,e){if(e.length===0)return [];let t=n.mainDocumentPart();if(!t)return [];let r=n.relationships(),o=r.filter(s=>s.ownerPart===t&&s.type===store.CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,Ko(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],p=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:t,id:p,type:store.CUSTOM_XML_REL,rawTarget:Vo(t,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:store.CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function Gn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Fo(t)),...e]}function qn(n){let e=new Map;for(let t of n)e.set(store.partNameKey(t.propsName),store.CUSTOM_XML_PROPS_TYPE);return e}function It(n,e){if(e.length===0)return false;let t=[...n.keys()].filter(ye).sort(),r=e.map(o=>o.itemName).sort();if(t.length!==r.length||t.some((o,i)=>o!==r[i]))return true;for(let o of e){let i=n.get(o.itemName),a=n.get(o.propsName);if(!i||i.root.id!==o.dataRootId||!a||a.root.id!==o.propsRootId)return true}return false}function Zn(n,e){if(It(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(t.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var Jo="http://schemas.microsoft.com/office/word/2012/wordml";function Be(n,e){return n.attributes.find(t=>t.localName===e)?.value}function _e(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 Qn(n){return e=>e.localName===n&&e.namespaceUri===store.WML_NAMESPACE_URI}function Wo(n){return n.localName==="abstractNum"?`0${_e(Be(n,"abstractNumId"))}`:`1${_e(Be(n,"numId"))}`}function $o(n){return n.namespaceUri!==store.WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function er(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===Jo,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Qn("footnote"),sortKey:e=>_e(Be(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:Qn("endnote"),sortKey:e=>_e(Be(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===store.WML_NAMESPACE_URI?{isMember:$o,sortKey:Wo}:null}function Xo(n,e){return n.attributes.find(t=>t.localName===e)?.value}function vt(n){return n.kind==="textValue"?n.id:Xo(n,"id")??n.id}function re(n,e){if(n.length===e.length&&n.every((a,s)=>a===e[s]))return n;let t=0,r=Math.min(n.length,e.length);for(;t<r&&n[t]===e[t];)t+=1;let o=n.length,i=e.length;for(;o>t&&i>t&&n[o-1]===e[i-1];)o-=1,i-=1;return Object.freeze([...n.slice(0,t),...e.slice(t,i),...n.slice(o)])}function rr(n,e){let t=n.root;if(t.children.length===e.length&&t.children.every((o,i)=>o===e[i]))return n;let r=Object.freeze({...t,children:re(t.children,e)});return Object.freeze({...n,root:r})}function Ho(n){if(n.namespaceUri===store.XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:store.XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===store.WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:store.WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function ar(n){}function lr(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function ti(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 ni(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 Ye(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&&ti(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&ni(r,n)?r.attributes:Object.freeze(n.attributes.map(Ho)),children:e})}function dr(n,e){if(n.attributes.length!==e.attributes.length)return false;let t=new Map(e.attributes.map(r=>[`${r.namespaceUri}
|
|
3
|
+
${r.localName}`,r.value]));for(let r of n.attributes)if(t.get(`${r.namespaceUri}
|
|
4
|
+
${r.localName}`)!==r.value)return false;return n.localName===e.localName&&n.kind===e.kind}function St(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)St(o,e)||(r=false);return r}function cr(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 Ue=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:Gn(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:Kn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:ii(t)}),this.assembly.value}contentTypeDefaults(){return this.defaults??=this.registry.contentTypeDefaults()}contentTypeOverrides(){return this.overrides??=this.registry.contentTypeOverrides()}resolvePartBytes(e){if(this.partBytes)return this.partBytes;let t=new Map,r=new Set;for(let o of this.registry.binaries()){r.add(o.storageKey);let i=this.blobBytes.get(o.storageKey);if(i&&i.digest===o.digest){t.set(o.storageKey,i.bytes);continue}let a=e.get(o.digest);if(!a)return null;ar(a.length),this.blobBytes.set(o.storageKey,{digest:o.digest,bytes:a}),t.set(o.storageKey,a);}for(let o of [...this.blobBytes.keys()])r.has(o)||this.blobBytes.delete(o);return this.partBytes=t,t}};function ii(n){let e=store.buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=store.resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var ze=class{lastLosers=new Set;textOverlays=new Map;losers=new Set;update(e){let t=[],r=e.replacementLoserRuns(),o=a=>{let s=e.parentOf(a);s!==null&&t.push(s);};for(let a of r)this.lastLosers.has(a)||o(a);for(let a of this.lastLosers)r.has(a)||o(a);this.lastLosers=r,this.losers=r;let i=e.concurrentSplitTextOverlays();return this.textOverlays=i.values,t.push(...i.changedIds),t}textValue(e,t){return this.textOverlays.get(e)??t}};function li(n){let e=new Set,t=[];for(let r of n){let o=`${r.code}${r.logicalId??""}`;e.has(o)||(e.add(o),t.push(r));}return t}var $=class{constructor(e,t){this.registry=e;this.blobs=t;this.packageCache=new Ue(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 ze;lastContestResolution=new Map;contestEncountered=new Set;contestMatchesResolution=true;claimsWholeSubtrees=true;lastDuplicateParents=[];droppedChildren=new Set;looseCandidates=new Set;pkg=null;customXmlRels=[];customXmlOverrides=new Map;stop;issues=[];destroy(){this.stop();}dirtyLogicalIds(){return this.lastDirty}current(){return this.pkg&&this.pendingDirty.size===0&&!this.pendingPackage&&!this.pendingMembership?{ok:true,package:this.pkg,issues:[...this.issues]}:this.rebuild()}adoptionChanges(){let e=[],t=new Map;for(let[r,o]of this.registry.adoptionIndex()){let i=o.join("");t.set(r,i),this.lastAdoption.get(r)!==i&&e.push(r);}for(let r of this.lastAdoption.keys())t.has(r)||e.push(r);return this.lastAdoption=t,e}rebuild(){let e=new Set(this.pendingDirty),t=this.pendingPackage;this.pendingDirty.clear(),this.pendingMembership=false,this.pendingPackage=false;let r=this.registry.hasUnobservedWrites();r&&this.registry.rebuildDerivedIndexes(),(t||r)&&this.packageCache.invalidate();for(let p of this.adoptionChanges())e.add(p);for(let p of this.splitProjection.update(this.registry))e.add(p);let o=cr(this.registry,e),i=new Set(this.registry.partEntries().map(p=>p.rootLogicalId)),a=[...e].some(p=>i.has(p)||this.registry.parentOf(p)===null&&!this.registry.isTombstoned(p)),s=this.pkg!==null&&!r&&!a&&(o.size>0||t),l=this.materializePass(o,t,s);if(!this.placementContested)return l;if(l.ok&&this.contestMatchesResolution&&this.contestUnchanged())return {ok:true,package:l.package,issues:li(l.issues)};let d=this.materializePass(o,t,false);return this.recordContestResolution(),d}contestUnchanged(){for(let e of this.contestEncountered){let t=this.lastContestResolution.get(e);if(t===void 0||t!==this.registry.parentOf(e))return false}return true}recordContestResolution(){let e=new Map;for(let t of this.contestEncountered)e.set(t,this.registry.parentOf(t));for(let t of this.lastDuplicateParents)e.set(t,this.registry.parentOf(t));this.lastContestResolution=e;}materializePass(e,t,r){if(this.issues.length=0,this.lastDirty=e,this.placementContested=false,this.contestEncountered.clear(),this.contestMatchesResolution=true,this.claimsWholeSubtrees=!r,this.droppedChildren.clear(),r)for(let d of this.lastDuplicateParents)this.push("duplicate-parent",d);this.customXmlRels=[],this.customXmlOverrides.clear();let o=new Set,i=new Map;for(let d of this.registry.partEntries()){let p=new Set,h=this.materialize(d.rootLogicalId,o,p,r);if(!h||h.kind==="textValue")return {ok:false,code:"missing-root",issues:[...this.issues]};let u=this.partCache.get(d.name);if(u&&u.root===h&&u.contentType===d.contentType){i.set(d.name,u);continue}let m=Object.freeze({id:d.id||d.name,name:d.name,contentType:d.contentType,root:h});i.set(d.name,m),this.partCache.set(d.name,m);}let a=r?new Set([...this.droppedChildren,...this.looseCandidates]):this.registry.allLogicalIds(),s=new Set;this.projectRelsParts(i),this.adoptOrphanPartMembers(i,o,r,a,s),this.applyCustomXmlStores(i,o,r);for(let d of [...this.partCache.keys()])i.has(d)||this.partCache.delete(d);for(let d of [...this.relsProjection.keys()])i.has(d)||this.relsProjection.delete(d);this.evictDeadSubtrees(o),this.reportOrphans(a,o,r,s),this.looseCandidates=s,r||(this.lastDuplicateParents=this.issues.filter(d=>d.code==="duplicate-parent"&&d.logicalId!==void 0).map(d=>d.logicalId));let l=this.assemblePackage(i);return l.ok?this.pkg&&!t&&this.pkg.parts.size===i.size&&[...i].every(([d,p])=>this.pkg?.parts.get(d)===p)?{ok:true,package:this.pkg,issues:[...this.issues]}:(this.pkg=l.package,{ok:true,package:this.pkg,issues:[...this.issues]}):l}push(e,t){this.issues.push(t?{code:e,logicalId:t}:{code:e});}stillListed(e){for(let t of this.registry.listingParents(e)){let r=this.registry.record(t);if(r&&L(r)&&r.childIds.includes(e))return true}return false}reportOrphans(e,t,r,o){if(!r){for(let s of e)this.registry.isTombstoned(s)||t.has(s)||(this.pushOrphan(s),o.add(s));return}let i=new Set(this.registry.partEntries().map(s=>s.rootLogicalId)),a=new Set;for(let s of e)a.has(s)||(a.add(s),this.reportOrphansUnder(s,t,i)&&o.add(s));}reportOrphansUnder(e,t,r){let o=false,i=new Set,a=[{id:e,underTombstone:false}];for(;a.length>0;){let{id:s,underTombstone:l}=a.pop();if(!(i.has(s)||i.size>=this.registry.limits.maxTreeDepth)){if(i.add(s),this.registry.isTombstoned(s)){let d=this.registry.record(s);if(d&&L(d))for(let p of d.childIds)a.push({id:p,underTombstone:true});continue}r.has(s)||(l?t.has(s):this.stillListed(s))||(this.pushOrphan(s),o=true);}}return o}pushOrphan(e){let t=this.registry.record(e),r=!!t&&(H(t)?t.value.length>0:t.childIds.length>0||t.attributes.length>0);this.push(r?"orphan-with-content":"orphan",e);}materialize(e,t,r,o){if(r.has(e)||r.size>=this.registry.limits.maxTreeDepth)return this.push("cycle",e),null;if(t.has(e))return this.push("duplicate-parent",e),null;if(o&&!this.lastDirty.has(e)){let u=this.cache.get(e);if(u&&r.size+this.heightOf(u)<=this.registry.limits.maxTreeDepth)return this.claimsWholeSubtrees?St(u,t)||(this.placementContested=true):t.add(u.id),u}if(this.registry.isTombstoned(e))return null;t.add(e);let i=this.registry.record(e);if(!i)return this.push("missing-node",e),null;if(H(i)){let u=this.splitProjection.textValue(e,i.value),m=this.cache.get(e);if(m?.kind==="textValue"&&m.value===u)return m;let c=lr(e,u);return this.remember(e,c),c}r.add(e);let a=new Set,s=[...i.childIds];for(let u of this.registry.adoptedChildren(e))s.includes(u)||s.push(u);let l=[];for(let u of s){if(u===e){this.push("self-child",u);continue}if(a.has(u)){this.push("duplicate-child",u);continue}if(a.add(u),this.registry.isTombstoned(u)){this.push("deleted-referenced",u);continue}if(this.splitProjection.losers.has(u)){t.add(u);continue}if(f(u)||!this.registry.hasNode(u)){this.push("child-id-not-in-registry",u);continue}if(!this.claimsWholeSubtrees){let c=this.registry.listingParents(u);c.length>1&&(this.placementContested=true,this.contestEncountered.add(u),c.some(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 m=this.materialize(u,t,r,o);m&&l.push(m);}r.delete(e);let d=this.cache.get(e);if(d&&d.kind!=="textValue"&&d.children.length===l.length&&d.children.every((u,m)=>u===l[m])&&dr(d,i))return d;let p=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(p,l);let h=Ye(i,re(p,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let a=store.relsPartNameFor(o);if(a!=="/_rels/.rels"&&O(a))continue;r.add(a);let s=this.projectOneRelsPart(a,e.get(a),i);s&&(e.set(a,s),this.partCache.set(a,s));}for(let[o,i]of e){if(r.has(o)||!Bn(o))continue;let a=_n(o);if(a===null)continue;let s=this.projectOneRelsPart(o,i,t.get(a)??[]);!s||s===i||(e.set(o,s),this.partCache.set(o,s));}}projectOneRelsPart(e,t,r){if(!t&&r.length===0)return this.relsProjection.delete(e),null;let o=this.relsProjection.get(e),a=!!o&&(!t||zn(o.root,t.root))&&o?o:t??Fn(e);if(Un(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=rr(a,jn(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[a,s]of e){let l=er(s.root);if(!l)continue;let d=R=>R.logicalId!==s.root.id&&l.isMember(R),p=[],h=new Set;for(let R of s.root.children){if(R.kind==="textValue")continue;let E=this.registry.record(R.id);!E||!L(E)||!d(E)||(p.push(R),h.add(R.id));}if(this.adoptLooseMembers(p,h,d,t,r,o,i)===0)continue;p.sort((R,E)=>l.sortKey(R).localeCompare(l.sortKey(E)));let m=[];for(let R of s.root.children)h.has(R.id)||m.push(R);let c=re(s.root.children,[...m,...p]);if(c===s.root.children)continue;let y=this.registry.record(s.root.id);if(!y||!L(y))continue;let b=Ye(y,c,s.root);this.remember(s.root.id,b);let I=Object.freeze({...s,root:b});e.set(a,I),this.partCache.set(a,I);}}adoptLooseMembers(e,t,r,o,i,a,s){let l=0;for(let d of a){if(o.has(d)||t.has(d)||this.registry.isTombstoned(d)||i&&this.stillListed(d))continue;let p=this.registry.record(d);if(!p||!L(p)||!r(p))continue;let h=this.materialize(d,o,new Set,i);!h||h.kind==="textValue"||(e.push(h),t.add(d),s.add(d),l+=1);}return l}materializeOnce(e,t,r){return t.has(e)?this.cache.get(e)??null:this.materialize(e,t,new Set,r)}adoptNodesIntoRoot(e,t,r,o){let i=this.cache.get(e),a=i&&i.kind!=="textValue"?i:this.materializeOnce(e,r,o);if(!a||a.kind==="textValue")return null;let s=[...a.children],l=new Set(s.map(m=>m.id)),d=0;for(let m of t){if(l.has(m))continue;let c=this.materializeOnce(m,r,o);!c||c.kind==="textValue"||(s.push(c),l.add(m),d+=1);}if(s.sort((m,c)=>vt(m).localeCompare(vt(c))),d===0&&s.every((m,c)=>m===a.children[c]))return a;let p=this.registry.record(e);if(!p||!L(p))return a;let h=re(a.children,s),u=Ye(p,h,a);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=Xn(this.registry,e);if(o.length===0||!Zn(e,o))return;let i=It(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,t,r),d=this.materializeOnce(s.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let p=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:s.propsName,name:s.propsName,contentType:store.CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,p),e.set(s.propsName,h),this.partCache.set(s.itemName,p),this.partCache.set(s.propsName,h);}if(i){for(let s of [...e.keys()])!ye(s)&&!xt(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=Hn(this.registry,o),this.customXmlOverrides=qn(o),this.projectRelsParts(e);}}assemblePackage(e){let t=this.packageCache.relationshipAssembly(this.customXmlRels);if(!t)return {ok:false,code:"invalid-relationships",issues:[...this.issues]};let r=this.packageCache.resolvePartBytes(this.blobs);if(!r)return {ok:false,code:"missing-blob",issues:[...this.issues]};let o=new Map(this.packageCache.contentTypeOverrides());for(let[s,l]of this.customXmlOverrides)o.set(s,l);let i={defaults:this.packageCache.contentTypeDefaults(),overrides:o},a=this.registry.mainDocumentPart()||[...e.keys()].find(s=>s.endsWith("document.xml"))||"";return {ok:true,package:Object.freeze({parts:e,partBytes:r,relationships:t.byOwner,externalTargets:t.externalTargets,contentTypes:i,mainDocumentPart:a}),issues:[...this.issues]}}};var Fe=64*1024*1024,oe="docx-package-blobs-v1";function ci(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 ui(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function je(n,e){return Object.freeze(e===void 0?{code:n}:{code:n,detail:e})}var F=class{constructor(e){this.shared=e;}shared;verified=new WeakSet;poisoned=new Set;get(e){let t=this.shared.get(e),r=ci(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+=ui(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Fe)throw new g("blob-store-full");this.shared.set(e,new Uint8Array(t));}}verify(e,t,r){return this.verified.has(t)?true:this.poisoned.has(e)?false:layout.sha256FontBytes(r)!==e?(this.poisoned.add(e),false):(this.verified.add(t),true)}};function xe(n,e){let{limits:t}=n,r=n.nodeCount();if(r>t.maxNodes)return je("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return je("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(s=>{i+=s instanceof x__namespace.Map?s.size:0;}),i>t.maxRelationships)return je("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>Fe?je("blob-store-full",`${a}`):null}var hr=20*1024*1024,Rt=3e4,yi=4e3,bi=1500,xi="docx-collaboration-seeds-v1",Et="docxEditorSeedCandidate",Ii=/^[0-9a-f]{16}$/,vi=256;function Lt(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new g("invalid-baseline");if(n.byteLength>hr)throw new g("baseline-too-large");let e=store.readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:hr,maxRatio:200}});if(!e.ok)throw new g("invalid-baseline");let t=e.package.parts.get(e.package.mainDocumentPart);if(!t)throw new g("no-main-document-part");let r=e.package;for(let i of r.parts.values()){if(i.root.namespaceUri!==store.WML_NAMESPACE_URI||!["document","hdr","ftr"].includes(i.root.localName)||!store.isStoryPart(i))continue;let a=store.normalizeParagraphIdentity(i);a!==i&&(r=store.withPart(r,a));}return new store.TreePackageStore(r,store.normalizeParagraphIdentity(r.parts.get(t.name))).currentPackage()}function Si(n,e){for(let t of n.binaries())if(!e.has(t.digest))return false;return true}function Ie(n,e,t,r){let o=n.schema.meta,i=()=>o.get("initialized")===true&&Si(n,e),a=()=>{let l=e.poisonedDigest();return l?new g("blob-digest-mismatch",l):null};if(i())return Promise.resolve();let s=a();return s?Promise.reject(s):r?.aborted?Promise.reject(new g("initialization-aborted")):new Promise((l,d)=>{let p=c=>{clearTimeout(m),o.unobserve(h),n.doc.off("afterTransaction",h),r?.removeEventListener("abort",u),c?d(c):l();},h=()=>{let c=a();if(c){p(c);return}i()&&p();},u=()=>p(new g("initialization-aborted")),m=setTimeout(()=>p(new g("initialization-timeout")),t);o.observe(h),n.doc.on("afterTransaction",h),r?.addEventListener("abort",u,{once:true});})}function wt(n){return n.getArray(xi)}function Ke(n){return wt(n).length}function gr(n,e){let t=wt(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Ei(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function Ri(n,e){let t=[...n.getStates().entries()].slice(0,vi);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Et];if(!(typeof i!="string"||!Ii.test(i))&&i<e)return true}return false}async function mr(n,e,t,r){try{return await Ie(n,e,t,r),!0}catch(o){if(o instanceof g&&o.code==="initialization-timeout")return false;throw o}}function Li(n,e,t){let r=n.schema.meta,o=()=>r.get("documentId")!==void 0;return o()?Promise.resolve():t?.aborted?Promise.reject(new g("initialization-aborted")):new Promise((i,a)=>{let s=h=>{clearTimeout(p),r.unobserve(l),t?.removeEventListener("abort",d),h?a(h):i();},l=()=>{o()&&s();},d=()=>s(new g("initialization-aborted")),p=setTimeout(()=>s(new g("initialization-timeout")),e);r.observe(l),t?.addEventListener("abort",d,{once:true});})}async function fr(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??yi,a=n.electionWindowMs??bi,s=n.timeoutMs??Rt,l=async()=>(await Li(r,s,n.signal),"joined");if(await mr(r,o,i,n.signal))return l();let d=Ei();t.setLocalStateField(Et,d);try{let p=await mr(r,o,a,n.signal);if(!p&&Ri(t,d)&&(await Ie(r,o,s,n.signal),p=!0),p)return await l();if(r.schema.meta.get("initialized")===!0)return await Ie(r,o,s,n.signal),await l();let h=await me(r,Lt(n.document),o);if(!h.ok)throw new g(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),wt(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Et,null);}}var Ve=class{constructor(e,t){this.knows=e;this.allocator=new he(t);}knows;allocator;toLogical=new Map;get replicaId(){return this.allocator.replicaId}reset(){this.toLogical.clear();}mint(e){let t=this.allocator.take();return this.toLogical.set(e,t),t}resolve(e){return this.toLogical.get(e)??e}translate(e){let t=[],r=false;for(let o of e.effects){let i=this.translateEffect(o);i!==o&&(r=true),t.push(i);}return r?Object.freeze({effects:Object.freeze(t)}):e}translateEffect(e){switch(e.kind){case "putNode":{let t=this.translateDescriptor(e.descriptor);return t.logicalId===e.descriptor.logicalId?e:{...e,descriptor:t}}case "spliceText":case "setAttribute":case "setNamespaceBinding":{let t=this.resolve(e.logicalId);return t===e.logicalId?e:{...e,logicalId:t}}case "spliceChildren":{let t=this.resolve(e.parentLogicalId),r=e.childLogicalIds.map(i=>this.resolve(i));return t===e.parentLogicalId&&r.every((i,a)=>i===e.childLogicalIds[a])?e:{...e,parentLogicalId:t,childLogicalIds:r}}case "moveNode":{let t=this.resolve(e.logicalId),r=this.resolve(e.destinationParentLogicalId);return t===e.logicalId&&r===e.destinationParentLogicalId?e:{...e,logicalId:t,destinationParentLogicalId:r}}case "putXmlPart":{let t=this.resolve(e.rootLogicalId);return t===e.rootLogicalId?e:{...e,rootLogicalId:t}}default:return e}}translateDescriptor(e){let t=this.resolve(e.logicalId);return this.knows(t)?{...e,logicalId:t}:{...e,logicalId:this.mint(e.logicalId)}}};function wi(n){let e=0;return n.schema.nodes.forEach(t=>{S(t)&&t.get(z)===true&&(e+=1);}),e}function Ci(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof x__namespace.Map?t.size:0;}),e}function Ct(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:wi(n),maxNodes:n.limits.maxNodes,relationships:Ci(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Fe})}function dl(n){let e=new _(n);try{let t=new F(n.getMap(oe));return Ct(e,t)}finally{e.destroy();}}var Je="docxEditor",K=256,kt=256;function xr(n){let e=n.actorId.trim(),t=n.name.trim();if(e.length===0||e.length>K||t.length===0||t.length>K)throw new g("invalid-identity");if(n.color!==void 0&&n.color.length>64)throw new g("invalid-identity-color");return Object.freeze({actorId:e,name:t,...n.color?{color:n.color}:{},role:n.role??"human"})}function Ir(n){let e=n.trim();if(e.length===0||e.length>K)throw new g("invalid-document-id");return e}function vr(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>K)throw new g("invalid-session-id");return e}function br(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 Pi(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=br(e.anchor),r=br(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 Pt(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>K||typeof e.name!="string"||e.name.length===0||e.name.length>K)return null;let t=collaboration.safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=Pi(e.selection);return i?{...o,selection:i}:o}function Ai(n){let e=new _(n),t=null;try{if(e.schema.meta.get("initialized")!==!0||typeof e.schema.meta.get("documentId")!="string")throw new g("not-initialized");let r=Q(e.schema.meta);if(r)throw new g(r.code,r.detail);if(e.rebuildDerivedIndexes(),Ke(n)>1)throw new g("concurrent-seed");let o=new F(n.getMap(oe)),i=xe(e,o);if(i)throw new g(i.code,i.detail);t=new $(e,o);let a=t.current(),s=o.poisonedDigest();if(s)throw new g("blob-digest-mismatch",s);if(!a.ok)throw new g(a.code);let l=Re(a.issues);if(l)throw new g("materialize-dropped-content",l);if(!a.package.parts.has(a.package.mainDocumentPart))throw new g("no-main-document-part");return store.writeOoxmlPackage(a.package)}finally{t?.destroy(),e.destroy();}}var Bi=3,_i=5e3,Yi=2e3,Ui=Symbol("createDocumentCollaboration.attachWatchdogMs"),Ot=class{constructor(e,t,r,o,i,a,s,l,d,p,h){this.ydoc=e;this.awareness=t;this.registry=a;this.materializer=s;this.identityMap=l;this.blobs=d;this.offlineEditing=h;this.documentId=r,this.sessionId=o,this.currentIdentity=i,this.undoManager=new x__namespace.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:_i,deleteFilter:a.undoDeleteFilter()}),e.on("afterTransaction",this.onYjsTransaction),t.on("change",this.onAwarenessChange),this.stopBlobWatch=d.observeChanges(u=>{let m=d.verifyNow(u);m&&this.setStatus("error","blob-digest-mismatch",m);}),this.publishAwareness(),this.setStatus("ready"),this.stopSeedWatch=gr(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${p}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},p),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=collaboration.createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;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 Ct(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}hasCompatibleSharedSchema(){let e=Q(this.registry.schema.meta);return e?(this.setStatus("error",e.code,e.detail),false):true}canWriteSharedState(){if(this.destroyed||!this.hasCompatibleSharedSchema())return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,t){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.undoManager.undo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.undoManager.redo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],t=[...this.awareness.getStates().entries()].slice(0,kt);for(let[r,o]of t){let i=Pt(o[Je]);i&&e.push({actorId:i.actorId,name:i.name,...i.color?{color:i.color}:{},role:i.role,isLocal:r===this.awareness.clientID});}return Object.freeze(e)}subscribeParticipants(e){return this.participantListeners.add(e),()=>this.participantListeners.delete(e)}remoteSelections(){let e=this.port;if(!e)return [];let t=i=>{let a=e.paragraphByStableId(i.paragraphId);return a?Object.freeze({paragraphId:a.paragraphId,nodeId:a.nodeId,offset:Math.min(i.offset,a.text.length)}):null},r=[...this.awareness.getStates().entries()].slice(0,kt),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=Pt(a[Je]);if(!s?.selection)continue;let l=t(s.selection.anchor),d=t(s.selection.head);!l||!d||o.push(Object.freeze({actorId:s.actorId,name:s.name,...s.color?{color:s.color}:{},...s.selection.kind==="cells"?{kind:"cells"}:{},anchor:l,head:d}));}return Object.freeze(o)}subscribeRemoteSelections(e){return this.selectionListeners.add(e),()=>this.selectionListeners.delete(e)}setIdentity(e){if(this.destroyed)return;let t=e.name===void 0?this.currentIdentity.name:e.name.trim();if(t.length===0||t.length>K)throw new g("invalid-identity");let r=this.currentIdentity.color;if(e.color!==void 0){if(e.color.length>64)throw new g("invalid-identity-color");r=collaboration.safeParticipantColor(e.color);}this.currentIdentity=Object.freeze({actorId:this.currentIdentity.actorId,name:t,...r?{color:r}:{},role:this.currentIdentity.role??"human"}),this.publishAwareness(this.currentSelection);}destroy(){this.destroyed||(this.clearAttachWatchdog(),this.flushPendingJournals(),this.detachPort?.(),this.destroyed=true,this.stopBlobWatch(),this.stopSeedWatch(),this.ydoc.off("afterTransaction",this.onYjsTransaction),this.awareness.off("change",this.onAwarenessChange),this.awareness.setLocalState(null),this.undoManager.destroy(),this.materializer.destroy(),this.registry.destroy(),this.setStatus("destroyed"),this.statusListeners.clear(),this.selectionListeners.clear(),this.participantListeners.clear());}applyJournal(e){if(!this.canWriteSharedState())return;let t=en(this.registry,this.identityMap.translate(e));if(!t.ok){this.refuseLocalJournal({code:t.code,...t.detail?{detail:t.detail}:{}});return}let r=t.journal,o=this.collectJournalBlobs(e);if(o!==null&&o.ok===false){this.refuseLocalJournal(o.failure);return}if(!this.canWriteSharedState())return;let i=this.ydoc.transact(()=>{if(o!==null){let s=this.putJournalBlobs(o.payloads);if(s!==null)return s}let a=at(this.registry,r);return a.ok?null:{code:a.code,...a.detail?{detail:a.detail}:{}}},this.localOrigin);if(i===null){this.refusedInARow=0;return}this.refuseLocalJournal(i);}collectJournalBlobs(e){let t=this.port;if(!t)return e.effects.some(i=>i.kind==="putBinary")?{ok:false,failure:Object.freeze({code:"collaboration-session-not-attached"})}:null;let r=Tn(e.effects,An(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 g?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<Bi&&this.statusState.status()==="error"&&r!==void 0&&r.code===e.code&&r.detail===e.detail&&(t.status==="ready"||t.status==="disconnected")&&this.setStatus(t.status,t.reason?.code,t.reason?.detail);}onYjsTransaction=e=>{this.destroyed||!this.hasCompatibleSharedSchema()||!this.port||e.origin!==this.localOrigin&&this.publishSharedToPort();};publishSharedToPort(){let e=this.port;if(!(!e||this.applyingRemote)){this.applyingRemote=true;try{if(!this.hasCompatibleSharedSchema())return;let t=xe(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=Re(r.issues);if(i){this.setStatus("error","materialize-dropped-content",i);return}this.remoteCounter+=1;let a=e.applyRemotePackage(r.package,{origin:store.ORIGIN_IDS.mutationRemote,actorId:"remote",operationId:`${this.sessionId}:remote:${this.remoteCounter}`});if(!a.ok){this.setStatus("error","remote-apply-failed",a.reason);return}a.changed&&this.identityMap.reset();}catch(t){this.setStatus("error",t instanceof g?t.code:"remote-apply-failed",t instanceof g?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(Je,t);}setStatus(e,t,r){if(!this.statusState.set(e,t,r))return;let o=this.statusState.snapshot();for(let i of [...this.statusListeners])i(o.status,o.reason?.code,o.reason?.detail);}};async function Nl(n){let e=n[Ui]??Yi,t=Ir(n.documentId),r=vr(n.sessionId),o=xr(n.identity),i=new _(n.ydoc);try{return await zi(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function zi(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new Ve(h=>a.hasNode(h)),l=new F(n.ydoc.getMap(oe));if(n.bootstrap.kind==="create"){if(a.schema.meta.get("initialized")===true)throw new g("already-initialized");let h=await me(a,Lt(n.bootstrap.document),l);if(!h.ok)throw new g(h.code);n.ydoc.transact(()=>{a.schema.meta.set("documentId",r);});}else if(n.bootstrap.kind==="create-or-join"){if(await fr({ydoc:n.ydoc,awareness:n.awareness,registry:a,blobs:l,documentId:r,document:n.bootstrap.document,probeTimeoutMs:n.bootstrap.probeTimeoutMs,electionWindowMs:n.bootstrap.electionWindowMs,timeoutMs:n.bootstrap.timeoutMs,signal:n.bootstrap.signal})==="joined"){if(a.schema.meta.get("documentId")!==r)throw new g("document-id-mismatch");let u=Q(a.schema.meta);if(u)throw new g(u.code,u.detail);a.rebuildDerivedIndexes();}}else {if(await Ie(a,l,n.bootstrap.timeoutMs??Rt,n.bootstrap.signal),a.schema.meta.get("documentId")!==r)throw new g("document-id-mismatch");let h=Q(a.schema.meta);if(h)throw new g(h.code,h.detail);a.rebuildDerivedIndexes();}if(Ke(n.ydoc)>1)throw new g("concurrent-seed");let d=xe(a,l);if(d)throw new g(d.code,d.detail);let p=new $(a,l);try{let h=p.current(),u=l.poisonedDigest();if(u)throw new g("blob-digest-mismatch",u);if(!h.ok)throw new g(h.code);let m=store.writeOoxmlPackage(h.package),c=new Ot(n.ydoc,n.awareness,r,o,i,a,p,s,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:c,destroy:()=>c.destroy()})}catch(h){throw p.destroy(),h}}exports.a=Dt;exports.b=Bt;exports.c=Xe;exports.d=g;exports.e=Ge;exports.f=Mr;exports.g=Wi;exports.h=$i;exports.i=Xi;exports.j=V;exports.k=qi;exports.l=Ur;exports.m=dl;exports.n=Ai;exports.o=Ui;exports.p=Nl;
|