@docx-editor.dev/pro 2.19.1 → 2.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -30
- package/dist/chunk-3QCDJ2BW.js +4 -0
- package/dist/chunk-AKAEBDLM.cjs +4 -0
- package/dist/chunk-AWGCPPLT.cjs +4 -0
- package/dist/{chunk-EMO6YTKO.cjs → chunk-OMUXC73J.cjs} +1 -1
- package/dist/{chunk-NQW54J56.js → chunk-PQNLQ2P2.js} +1 -1
- package/dist/chunk-T2MOOMO2.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-EMWNZSN3.cjs +1 -0
- package/dist/document-session-FPKBLKDC.js +1 -0
- package/dist/document-session-LBJO672O.js +1 -0
- package/dist/document-session-YZRHVYCK.cjs +1 -0
- package/dist/{hocuspocus-FGTZRYYI.cjs → hocuspocus-CCT7ZGAL.cjs} +1 -1
- package/dist/{hocuspocus-GJOYS5IH.js → hocuspocus-CFO4XIYM.js} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/react/index.cjs +2 -2
- package/dist/react/index.js +2 -2
- package/dist/vue/hocuspocus.cjs +1 -1
- package/dist/vue/hocuspocus.js +1 -1
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.d.cts +6 -6
- package/dist/vue/index.d.ts +6 -6
- package/dist/vue/index.js +1 -1
- package/dist/vue/webrtc.cjs +1 -1
- package/dist/vue/webrtc.js +1 -1
- package/dist/{webrtc-HCNKEL2L.js → webrtc-IGHNHLXV.js} +1 -1
- package/dist/{webrtc-KSMRT7P7.cjs → webrtc-TMW7JV4Q.cjs} +1 -1
- package/package.json +4 -4
- package/dist/chunk-5Q7TAD56.cjs +0 -4
- package/dist/chunk-DK2U6X6K.cjs +0 -4
- package/dist/chunk-SHLNDIAG.js +0 -4
- package/dist/chunk-VQDG6RPV.js +0 -4
- package/dist/document-session-7GYS3IV6.js +0 -1
- package/dist/document-session-RA4IXYFO.js +0 -1
- package/dist/document-session-SDHJEHPD.cjs +0 -1
- package/dist/document-session-WQSA3YUO.cjs +0 -1
package/README.md
CHANGED
|
@@ -13,8 +13,7 @@
|
|
|
13
13
|
|
|
14
14
|
# @docx-editor.dev/pro
|
|
15
15
|
|
|
16
|
-
Four capabilities for the [docx-editor.dev](https://docx-editor.dev) React and
|
|
17
|
-
Vue editors:
|
|
16
|
+
Four capabilities for the [docx-editor.dev](https://docx-editor.dev) React and Vue editors:
|
|
18
17
|
|
|
19
18
|
- **Tracked changes**: Suggesting mode, markup rendering, accept, and reject.
|
|
20
19
|
- **Comments**: Threads anchored to a range, with replies.
|
|
@@ -25,13 +24,11 @@ Vue editors:
|
|
|
25
24
|
npm install @docx-editor.dev/react @docx-editor.dev/pro
|
|
26
25
|
```
|
|
27
26
|
|
|
28
|
-
The framework-neutral entry is `@docx-editor.dev/pro`. Framework chrome lives at
|
|
29
|
-
`@docx-editor.dev/pro/react` and `@docx-editor.dev/pro/vue`.
|
|
27
|
+
The framework-neutral entry is `@docx-editor.dev/pro`. Framework chrome lives at `@docx-editor.dev/pro/react` and `@docx-editor.dev/pro/vue`.
|
|
30
28
|
|
|
31
29
|
## Register a module
|
|
32
30
|
|
|
33
|
-
Capabilities are modules passed to the editor root. Registration happens at construction, so
|
|
34
|
-
the array identity must be stable. Build it outside render, or the editor rebuilds every time.
|
|
31
|
+
Capabilities are modules passed to the editor root. Registration happens at construction, so the array identity must be stable. Build it outside render, or the editor rebuilds every time.
|
|
35
32
|
|
|
36
33
|
```tsx
|
|
37
34
|
import { DocxEditor } from '@docx-editor.dev/react';
|
|
@@ -53,17 +50,13 @@ export function Reviewer({ bytes }: { bytes: Uint8Array }) {
|
|
|
53
50
|
}
|
|
54
51
|
```
|
|
55
52
|
|
|
56
|
-
`author` is what lands in `w:author`. OOXML requires it, so the engine refuses a comment or
|
|
57
|
-
reply with no author rather than writing an empty attribute.
|
|
53
|
+
`author` is what lands in `w:author`. OOXML requires it, so the engine refuses a comment or reply with no author rather than writing an empty attribute.
|
|
58
54
|
|
|
59
|
-
Without a review module the editor still opens a document containing revisions and comments and
|
|
60
|
-
still saves them back untouched. It renders revisions in their final state and offers no review
|
|
61
|
-
UI; the module is what makes them visible and actionable.
|
|
55
|
+
Without a review module the editor still opens a document containing revisions and comments and still saves them back untouched. It renders revisions in their final state and offers no review UI; the module is what makes them visible and actionable.
|
|
62
56
|
|
|
63
57
|
## Collaboration
|
|
64
58
|
|
|
65
|
-
Use `collaborationModule` with a Yjs 13 provider. The package includes WebRTC and
|
|
66
|
-
Hocuspocus helpers for React and Vue.
|
|
59
|
+
Use `collaborationModule` with a Yjs 13 provider. The package includes WebRTC and Hocuspocus helpers for React and Vue.
|
|
67
60
|
|
|
68
61
|
Install the peer package for your transport:
|
|
69
62
|
|
|
@@ -72,16 +65,11 @@ npm install @docx-editor.dev/pro yjs y-webrtc
|
|
|
72
65
|
npm install @docx-editor.dev/pro yjs @hocuspocus/provider
|
|
73
66
|
```
|
|
74
67
|
|
|
75
|
-
Start with the
|
|
76
|
-
[real-time collaboration quickstart](https://www.docx-editor.dev/docs/2.x/collaboration).
|
|
77
|
-
Use the
|
|
78
|
-
[collaboration reference](https://www.docx-editor.dev/docs/2.x/pro/collaboration)
|
|
79
|
-
for room lifecycles, presence, recovery, and limits.
|
|
68
|
+
Start with the [real-time collaboration quickstart](https://www.docx-editor.dev/docs/2.x/collaboration). Use the [collaboration reference](https://www.docx-editor.dev/docs/2.x/pro/collaboration) for room lifecycles, presence, recovery, and limits.
|
|
80
69
|
|
|
81
70
|
## Chrome or hooks
|
|
82
71
|
|
|
83
|
-
Everything the packaged sidebar renders is reachable from `useReview()`. Use the sidebar for
|
|
84
|
-
Word-like cards out of the box, or the hook to render your own markup.
|
|
72
|
+
Everything the packaged sidebar renders is reachable from `useReview()`. Use the sidebar for Word-like cards out of the box, or the hook to render your own markup.
|
|
85
73
|
|
|
86
74
|
```tsx
|
|
87
75
|
import { useReview } from '@docx-editor.dev/pro/react';
|
|
@@ -114,15 +102,11 @@ function ChangeList() {
|
|
|
114
102
|
}
|
|
115
103
|
```
|
|
116
104
|
|
|
117
|
-
Items come from the document tree rather than from what is currently painted, and each anchor
|
|
118
|
-
comes from layout records rather than measured DOM, so a sidebar built on this does not lag a
|
|
119
|
-
repaint behind the page or break during pagination.
|
|
105
|
+
Items come from the document tree rather than from what is currently painted, and each anchor comes from layout records rather than measured DOM, so a sidebar built on this does not lag a repaint behind the page or break during pagination.
|
|
120
106
|
|
|
121
107
|
## Custom nodes
|
|
122
108
|
|
|
123
|
-
An inline node type you define (a citation, a mention, a merge field) stored as a Word content
|
|
124
|
-
control whose `w:tag` carries your identity and attributes. Word opens the document, shows the
|
|
125
|
-
node's text, and gives it back unchanged.
|
|
109
|
+
An inline node type you define (a citation, a mention, a merge field) stored as a Word content control whose `w:tag` carries your identity and attributes. Word opens the document, shows the node's text, and gives it back unchanged.
|
|
126
110
|
|
|
127
111
|
```ts
|
|
128
112
|
import { defineCustomNode, customNodesModule } from '@docx-editor.dev/pro';
|
|
@@ -140,15 +124,13 @@ const MODULES = [customNodesModule({ nodes: [Citation] })];
|
|
|
140
124
|
|
|
141
125
|
Every value reaching `fromDocx` came out of a `.docx`, so treat `attrs` and `text` as untrusted.
|
|
142
126
|
|
|
143
|
-
`insertCustomNode`, `updateCustomNode`, and `removeCustomNode` author them from code, and
|
|
144
|
-
`customNodeXml` builds the same content control on a server with no editor and no DOM.
|
|
127
|
+
`insertCustomNode`, `updateCustomNode`, and `removeCustomNode` author them from code, and `customNodeXml` builds the same content control on a server with no editor and no DOM.
|
|
145
128
|
|
|
146
129
|
## Licensing
|
|
147
130
|
|
|
148
131
|
This package is licensed under the [EigenPal Pro License](https://github.com/eigenpal/docx-editor/blob/main/packages/pro/LICENSE.md), and you can compare and buy license and support levels on the [pricing page](https://www.docx-editor.dev/pricing).
|
|
149
132
|
|
|
150
|
-
Both module factories accept an optional `licenseKey`. Construction never validates it and never
|
|
151
|
-
touches the network.
|
|
133
|
+
Both module factories accept an optional `licenseKey`. Construction never validates it and never touches the network.
|
|
152
134
|
|
|
153
135
|
## Documentation
|
|
154
136
|
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import*as x from'yjs';import {readOoxmlPackage,normalizeParagraphIdentity,TreePackageStore,writeOoxmlPackage,partNameKey,relsPartNameFor,CUSTOM_XML_PROPS_TYPE,WML_NAMESPACE_URI,isStoryPart,withPart,ORIGIN_IDS,isDangerousKey,normalizePartName,DATASTORE_NAMESPACE_URI,CUSTOM_XML_REL,CUSTOM_XML_PROPS_REL,buildRelationshipSet,resolveRelationship,XML_NAMESPACE_URI}from'@docx-editor.dev/core/store';import {createCollaborationDocumentPort,historyGroupOfJournal,reportHistoryGroup}from'@docx-editor.dev/core/collaboration/replication';import {createCollaborationStatusTracker,safeParticipantColor}from'@docx-editor.dev/core/collaboration';import {sha256FontBytes}from'@docx-editor.dev/core/layout';var $e=new WeakMap;function ie(n){return $e.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}),Lr=/^sha256:[0-9a-f]{64}$/;function Nt(n){return n?Object.freeze({...U,...n}):U}function f(n){return isDangerousKey(n)?"prototype-key":null}function A(n,e){return typeof n!="string"||n.length>e?"invalid-string":isDangerousKey(n)?"prototype-key":null}function O(n){let e=f(n);if(e)return e;if(typeof n!="string"||n.length===0)return "unsafe-part-name";let t=normalizePartName(n);return !t.ok||t.partName!==n?"unsafe-part-name":null}function Mt(n){for(let e of Object.keys(n)){let t=f(e);if(t)return t}return !Lr.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 Bt=1,_t=1,Ge=20*1024*1024,Ar="docx-collaboration-v1",Tr="docx-body-paragraphs-v1",Nr=Object.freeze({kind:"docx-collaboration-bootstrap"}),Mr="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 ${Mr}`:i);this.code=t;this.detail=r;this.name="CollaborationSchemaError";}code;detail};function qe(n){return {root:n.getMap(Ar),paragraphs:n.getMap(Tr)}}function Dr(n,e){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new g("invalid-baseline");if(n.byteLength>Ge)throw new g("baseline-too-large");let t=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:Ge,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=normalizeParagraphIdentity(r),i=new TreePackageStore(t.package,o),a=createCollaborationDocumentPort(i,{documentId:e});return {bytes:writeOoxmlPackage(i.currentPackage()),paragraphs:a.paragraphs()}}async function Yt(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 Dt(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 Xe(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 Gi(n,e,t,r){let{root:o,paragraphs:i}=qe(n);if(ae(o))throw new g("already-initialized");let a=await Yt(r.bytes);n.transact(()=>{if(ae(o))throw new g("already-initialized");o.set("protocolVersion",Bt),o.set("schemaVersion",_t),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.Text;i.set(s.paragraphId,l),l.insert(0,s.text);}o.set("initialized",true);},Nr);}async function Hi(n,e){let{root:t,paragraphs:r}=qe(n);if(!ae(t))throw new g("not-initialized");if(Xe(t,"protocolVersion")!==Bt)throw new g("protocol-version-mismatch");if(Xe(t,"schemaVersion")!==_t)throw new g("schema-version-mismatch");if(Dt(t,"documentId")!==e)throw new g("document-id-mismatch");let o=Xe(t,"baselineByteLength");if(o===0||o>Ge)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 Yt(i)!==Dt(t,"baselineSha256"))throw new g("baseline-digest-mismatch");let a=Dr(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.Text))throw new g("paragraph-set-mismatch");return a}function qi(n,e,t){let{root:r}=qe(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 Ze(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 ea(n){let e=Ze(n);if(e)throw new g(e.code,e.detail)}var Br=V.protocolVersion,_r=V.sharedSchemaVersion,Yr=V.repairVersion,Ur=V.canonicalModelVersion,zr="docx-package-meta-v1",Qe="docx-package-nodes-v1",jr="docx-package-parts-v1",Fr="docx-package-rels-v1",Kr="docx-package-overrides-v1",Vr="docx-package-defaults-v1",Jr="docx-package-binaries-v1",Wr="docx-package-namespaces-v1",$r="docx-package-attributes-v1",Xr="docx-package-bindings-v1",ve="s",Se="b",M="t",Ee="children",z="deleted",X="replacedBy",et="splitFrom",se="splitLineage";var P="",Ut="-",zt=Object.freeze({kind:"docx-package-bootstrap"}),jt=Object.freeze({kind:"docx-package-journal"});function G(n){return n.kind==="textValue"}function L(n){return !G(n)}var Gr=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)Gr.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 Ft(n){return {meta:n.getMap(zr),nodes:n.getMap(Qe),parts:n.getMap(jr),relationships:n.getMap(Fr),overrides:n.getMap(Kr),defaults:n.getMap(Vr),binaries:n.getMap(Jr),namespaces:n.getMap(Wr),attributes:n.getMap($r),bindings:n.getMap(Xr)}}var Kt=[["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"]],qr=new Map(Kt),Zr=new Map(Kt.map(([n,e])=>[e,n]));function Qr(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?Ut:qr.get(n)??`n${Qr(n)}`}function H(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===Ut||f(e))return "";let t=n.get(e);return typeof t=="string"?t:Zr.get(e)??""}function tt(n,e,t,r){return `${n}${P}${e}${P}${t}${P}${r}`}function eo(n){let e=n.split(P);return {kind:e[0]||"generic",namespaceId:e[1]??"",localName:e[2]??"",prefix:e[3]??""}}function nt(n){let e=n.has(ve)?n.get(ve):n.get(Se);return eo(typeof e=="string"?e:"")}function rt(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 ot(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 Vt(n,e){return `${n}${P}${e}`}function Jt(n){let e=n.indexOf(P);return e<0?{prefix:"",value:n}:{prefix:n.slice(0,e),value:n.slice(e+1)}}function Wt(n){let e=new x.Map,t=tt(n.kind,n.namespaceId,n.localName,n.prefix??"");e.set(Se,t);let r=new x.Array;return n.childIds&&n.childIds.length>0&&r.push([...n.childIds]),e.set(Ee,r),e}function Le(n){let e=new x.Map;return e.set(M,new x.Text(n)),e}function $t(n,e,t){let r=new x.Map;return r.set("id",n),r.set("rootId",e),r.set("contentType",t),r}function Xt(n){let e=new x.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 Gt(n){let e=new x.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 Ze({protocolVersion:n.get("protocolVersion"),sharedSchemaVersion:n.get("sharedSchemaVersion"),repairVersion:n.get("repairVersion"),canonicalModelVersion:n.get("canonicalModelVersion")})}function Ht(n){n.set("protocolVersion",Br),n.set("sharedSchemaVersion",_r),n.set("repairVersion",Yr),n.set("canonicalModelVersion",Ur),n.set("initialized",true);}function S(n){return n instanceof x.Map}function D(n){if(!S(n))return null;let e=n.get(Ee);return e instanceof x.Array?e:null}function ce(n){return S(n)&&n.get(M)instanceof x.Text}function J(n){return S(n)&&n.get(z)===true}function it(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(et);return typeof e=="string"&&e.length>0?e:null}function at(n){if(!S(n))return null;let e=n.get(se);return typeof e=="string"&&e.length>0?e:ue(n)}function qt(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(G(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=qt(n,e),o=[];if(!r||r.length===0)return;for(let l of t){let d=qt(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 to(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 to(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=Mt(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 no(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 ro(n,e){let t=n.kindOf(e);return t!==null&&!t.endsWith("Properties")}function oo(n,e,t,r){let o=new Set((t.get(e)??[]).filter(i=>ro(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 io(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 ao(n){let e=0;for(let t of n)t.kind==="putNode"&&(e+=1);return e}function st(n,e){if(n.nodeCount()+ao(e.effects)>n.limits.maxNodes)return {ok:false,code:"too-many-nodes"};let t=io(n,e.effects);return "ok"in t?t:(n.doc.transact(()=>{n.noteWrite();let r=uo(n,t.removed);for(let o of e.effects)no(n,o,t.mintedText),o.kind==="spliceChildren"&&lo(n,t,t.replacementsByEffect.get(o)??[],o.childLogicalIds);so(n,e.effects,t,r);},jt),{ok:true})}function so(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=oo(n,i,r,e);a&&n.unlistChildren(i,r.get(i)??[]),n.tombstone(i,a);}}function lo(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=co(n,o,e.reinserted),a=r.filter(s=>n.kindOf(s)==="run");we(n,o,a),n.recordRunSplit(i,o,a);}}function co(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 uo(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",po=Object.freeze({kind:"docx-package-restored-split-anchors"});function T(n,e){throw new g(n,e)}function lt(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Zt(n){return lt(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 Qt(n){return !lt(n)||!Object.keys(n).every(e=>["type","item","assoc"].includes(e))||!Zt(n.type)||n.item!==void 0&&!Zt(n.item)||n.assoc!==0&&n.assoc!==-1?T("invalid-string",B):x.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.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.createRelativePositionFromTypeIndex(s.text,u,u===0&&h==="start"?-1:0)},d=JSON.stringify({sourceId:s.sourceId,start:x.relativePositionToJSON(l(r,"start")),end:x.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.getItem(this.doc.store,l);for(;d instanceof x.Item&&d.redone!==null;)l=x.createID(d.redone.client,d.redone.clock+l.clock-d.id.clock),d=x.getItem(this.doc.store,l);let p=d instanceof x.Item&&!d.deleted&&!x.compareIDs(i,l)?x.createRelativePositionFromJSON({...x.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.compareRelativePositions(a,i.start)&&x.compareRelativePositions(s,i.end))continue;let l=JSON.stringify({sourceId:i.sourceId,start:x.relativePositionToJSON(a),end:x.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);},po);}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.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 !lt(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.Text?{sourceId:o.sourceId,start:Qt(o.start),end:Qt(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.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.createAbsolutePositionFromRelativePosition(e.start,this.doc,false),a=x.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.getItem(this.doc.store,e.start.item).deleted,endAnchorDeleted:e.end.item!==null&&x.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.createRelativePositionFromJSON(l.start),p=x.createRelativePositionFromJSON(l.end);if(s=s&&(a||p.item!==null&&x.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.createRelativePositionFromJSON(R);return a&&s&&x.compareRelativePositions(d,p)&&x.compareRelativePositions(v,d)?E==="start"?"after":"before":a&&x.compareRelativePositions(v,d)?"before":s&&x.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.relativePositionToJSON(x.createRelativePositionFromTypeIndex(r.text,u,u===0&&r.startAssoc===-1?-1:0)),c=x.relativePositionToJSON(x.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 en(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 dt=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=en(t.start,t.startAssoc,o),t.end=en(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.Doc({gc:false}),t=e.getMap(Qe);this.shadow={doc:e,nodes:t,sources:new ee(t,e,this.registry.limits)},x.applyUpdate(e,x.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?.();}},ct=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 tn(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 dt(n,i),s=new ct(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&&$e.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 Pe=class{constructor(e){this.undoManager=e;let t=r=>{this.capturing&&r.type==="undo"&&(this.gestureItem=r.stackItem,this.captured=true);};e.on("stack-item-added",t),e.on("stack-item-updated",t);}undoManager;previous;gestureItem;capturing=false;captured=false;capture(e,t){let r=this.previous;this.previous=e;let o=this.undoManager.undoStack,i=this.undoManager.captureTimeout;e===r&&e!==void 0&&o[o.length-1]===this.gestureItem?(this.undoManager.lastChange=Date.now(),this.undoManager.captureTimeout=Number.POSITIVE_INFINITY):((e!==r||e!==void 0)&&this.undoManager.stopCapturing(),this.gestureItem=void 0);let a=this.gestureItem;this.captured=false,this.capturing=e!==void 0;try{let s=t();return this.captured&&reportHistoryGroup(e,this.gestureItem===a?"extended":"started"),s}catch(s){throw this.reset(),s}finally{this.capturing=false,this.undoManager.captureTimeout=i;}}reset(){this.previous=void 0,this.gestureItem=void 0;}};var mo=new Set(["paraId","textId","id","numId","bookmarkId"]);function nn(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function rn(n){let e=new Uint8Array(16);return globalThis.crypto.getRandomValues(e),nn(e)}function Oe(n){return /^[0-9a-f]{32}$/.test(n)}function on(n,e){if(!Oe(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 ut(n,e){return `yjs:${n}:${e}`}function pt(n){if(!n.startsWith("lid:"))return null;let e=n.slice(4,n.indexOf(":",4));return Oe(e)?e:null}function ht(n){let e=[];for(let t of n)mo.has(t.localName)&&e.push(t.value);return e}var he=class{replicaId;next=0;constructor(e){if(this.replicaId=e??rn(),!Oe(this.replicaId))throw new Error("invalid replica identity")}take(){let e=on(this.replicaId,this.next);return this.next+=1,e}get counter(){return this.next}};function an(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.Array&&(s=true),l.target instanceof x.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 Te=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(et,e),i.set(se,e),this.indexExisting(o));}}indexExisting(e){let t=at(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=>at(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=>pt(l)??"").sort()[0];for(let l of a)(pt(l)??"")!==s&&o(l);}return this.cachedLosers=t,t}};function sn(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 Ne(n){return typeof n=="string"?n:""}function ln(n,e){return n<e?-1:n>e?1:0}function mt(n,e){return `${n}${P}${e}`}function fo(n){let e=n.indexOf(P);return e<0?n:n.slice(0,e)}function dn(n){let e=[];return n.forEach((t,r)=>{!S(t)||f(r)||t.forEach(o=>{if(!S(o))return;let i=Ne(o.get("id")),a=Ne(o.get("type"));if(i.length===0||a.length===0)return;let s=Ne(o.get("ownerPart"))||fo(r);if(f(s))return;let l=o.get("order");e.push({ownerPart:s,id:i,type:a,rawTarget:Ne(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||ln(t.ownerPart,r.ownerPart)||ln(t.id,r.id)),e}function cn(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 yo(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 un(n,e){let t=n.childrenSnapshot.get(e);return t||(D(n.nodes.get(e))?.toArray()??[])}function bo(n,e){let t=n.nodes.get(e);return !S(t)||J(t)}function xo(n,e,t,r){let o=[],i=new Set,a=r,s;for(;;){if(i.has(a)||(i.add(a),bo(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=un(n,d).indexOf(h);if(u<0)return null;l.push(u),d=h;}return l}function pn(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=xo(n,r,t,d);if(p==="fallback")return false;if(p==="deferred"){l=true;continue}if(p===null)continue;let h=un(n,d).indexOf(a);if(h<0)continue;let u=[...p,h];(!s||yo(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 hn(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 mn(n,e){return `${n}${P}${e}`}function gt(n,e,t,r,o){if(f(t)||f(r.localName))return;let i=H(n.namespaces,r.namespaceUri,e),a=rt(t,i,r.localName);f(a)||n.attributes.set(a,Vt(r.prefix??"",o));}function gn(n,e,t,r){n.attributes.delete(rt(e,le(t),r));}function ft(n,e,t,r,o){if(f(t)||f(r))return;let i=H(n.namespaces,o,e),a=ot(t,r);f(a)||n.bindings.set(a,i);}function fn(n,e,t){n.bindings.delete(ot(e,t));}function yt(n,e,t,r,o,i){let{prefix:a,value:s}=Jt(i),l=e.get(t);l||(l=new Map,e.set(t,l)),l.set(mn(r,o),{namespaceUri:de(n.namespaces,r),localName:o,prefix:a.length>0?a:void 0,value:s});}function Io(n,e,t,r){let o=n.get(e);o&&(o.delete(mn(t,r)),o.size===0&&n.delete(e));}function bt(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 vo(n,e,t){let r=n.get(e);r&&(r.delete(t),r.size===0&&n.delete(e));}function yn(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"){Io(e,i.logicalId,i.namespaceId,i.localName);continue}let a=n.attributes.get(String(r));typeof a=="string"&&yt(n,e,i.logicalId,i.namespaceId,i.localName,a);}}function bn(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"){vo(e,i.logicalId,i.prefix);continue}let a=n.bindings.get(String(r));typeof a=="string"&&bt(n,e,i.logicalId,i.prefix,a);}}function In(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.Text?r.length:0,children:[]}}return {isText:false,textLength:0,children:D(t)?.toArray()??[]}}function vn(n,e){let t=n.get(e);return S(t)?ce(t)?"textValue":nt(t).kind:null}function Sn(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 En(n,e,t,r,o){let i=nt(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 Rn(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 Ln(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!f(r)&&e.set(partNameKey(r),t);}),e}function wn(n){let e=new Map;return n.forEach((t,r)=>{typeof t=="string"&&!f(r)&&e.set(r,t);}),e}function Cn(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 Eo(n){return n?._item??null}function Ro(n){return n.content instanceof x.ContentType}function Pn(n){return e=>{let t=e.parent;if(t===null)return true;if(t===n)return false;let r=Eo(t);return r===null||r.parent!==n?true:e.parentSub===se||e.parentSub===Se?false:!Ro(e)}}function Lo(n){let e=n._item;return e?ut(e.id.client,e.id.clock):null}function wo(n){return typeof n=="string"?n:""}var _=class{constructor(e,t){this.doc=e;this.schema=Ft(e),this.limits=Nt(t),this.splitDedup=new Te(this.schema.nodes),this.splitTextSources=new ee(this.schema.nodes,this.doc,this.limits),this.stopObserving=cn(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 Pn(this.schema.nodes)}encodeSnapshot(){return x.encodeStateAsUpdate(this.doc)}encodeUpdate(e){return x.encodeStateAsUpdate(this.doc,e)}partEntries(){return Rn(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 wo(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.Text?r.toString():"";return {logicalId:e,kind:"textValue",value:o}}return En(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:Lo(t),wordFacingIds:ht(o)}}isTombstoned(e){return J(this.schema.nodes.get(e))}replacedByOf(e){return it(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:In(this.schema.nodes,e)}kindOf(e){return f(e)?null:vn(this.schema.nodes,e)}noteNodeWrite(e){this.schema.nodes.has(e)||(this.pendingNodeAdds+=1);}putElement(e){this.noteNodeWrite(e.logicalId);let t=H(this.schema.namespaces,e.namespaceUri,this.limits.maxStringLength);this.schema.nodes.set(e.logicalId,Wt({logicalId:e.logicalId,kind:e.kind,namespaceUri:e.namespaceUri,namespaceId:t,localName:e.localName,prefix:e.prefix}));for(let r of e.attributes)gt(this.schema,this.limits.maxStringLength,e.logicalId,r,r.value);for(let r of e.bindings)ft(this.schema,this.limits.maxStringLength,e.logicalId,r.prefix,r.namespaceUri);}updateElementShell(e,t){let r=this.require(e),o=H(this.schema.namespaces,t.namespaceUri,this.limits.maxStringLength);r.set(ve,tt(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){gn(this.schema,e,t.namespaceUri,t.localName);return}gt(this.schema,this.limits.maxStringLength,e,t,r);}setNamespaceBinding(e,t,r){if(r===null){fn(this.schema,e,t);return}ft(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=>sn(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,$t(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.Map;t.set(e.id,Xt(e)),this.schema.relationships.set(mt(e.ownerPart,e.id),t);}deleteRelationship(e,t){this.relationshipCountCache=-1,this.schema.relationships.delete(mt(e,t)),this.schema.relationships.get(e)?.delete(t);}putContentTypeOverride(e,t){this.schema.overrides.set(partNameKey(e),t);}deleteContentTypeOverride(e){this.schema.overrides.delete(partNameKey(e));}putContentTypeDefault(e,t){this.schema.defaults.set(e,t);}putBinary(e){this.schema.binaries.set(e.storageKey,Gt(e));}deleteBinary(e){this.schema.binaries.delete(e);}relationships(){return dn(this.schema.relationships)}contentTypeOverrides(){return Ln(this.schema.overrides)}contentTypeDefaults(){return wn(this.schema.defaults)}binaries(){return Cn(this.schema.binaries)}hasNode(e){return this.schema.nodes.has(e)}observeDirty(e){return an(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)||yt(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)||bt(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.Text)&&(r.path.length===0||r.target instanceof x.Array||r.target instanceof x.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.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.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.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.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,yn(this.schema,this.attributesByNode,e);}applyBindingMapEvent(e){this.unobservedWrites=0,bn(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(Sn(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;pn({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){hn({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=it(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.Text))throw new Error(`no text at ${e}`);return t}childArray(e){let t=this.require(e).get(Ee);if(!(t instanceof x.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 Me=class{blobs=new Map;get(e){let t=this.blobs.get(e);return t?t.slice():null}put(e,t){this.blobs.set(e,t.slice());}};async function An(n){let e=await globalThis.crypto.subtle.digest("SHA-256",n.slice().buffer);return `sha256:${[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}`}function Tn(n){let e=n.binaryPart;return typeof e=="function"?e:null}function Nn(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 Mn(n,e){for(let t of e)n.put(t.digest,t.bytes);}function ko(n){return n.attributes.map(e=>({namespaceUri:e.namespaceUri,localName:e.localName,prefix:e.prefix,value:e.value}))}function Po(n){return n.namespaceBindings.map(e=>({prefix:e.prefix,namespaceUri:e.namespaceUri}))}function Dn(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:ko(e),bindings:Po(e)});for(let i of e.children){let a=Dn(n,i,e.id,r+1,o);if(a)return a}}return t&&n.childArray(t).push([e.id]),null}async function Oo(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 An(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 Me){if(e.parts.size>n.limits.maxParts)return {ok:false,code:"too-many-parts"};let r=await Oo(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=Dn(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);},zt);}finally{n.endBulkLoad();}return o?{ok:false,code:o}:{ok:true}}var Be="http://schemas.openxmlformats.org/package/2006/relationships",Ao="application/vnd.openxmlformats-package.relationships+xml",Bn=/^(.*)\/_rels\/([^/]*)\.rels$/;function _n(n){return Bn.test(n)}function Yn(n){let e=Bn.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 De(n,e){return Object.freeze({kind:"genericExtension",namespaceUri:"",localName:n,value:e})}function To(n,e){let t=[De("Id",e.id),De("Type",e.type),De("Target",e.rawTarget)];return e.targetMode==="External"&&t.push(De("TargetMode","External")),Object.freeze({id:n,kind:"generic",namespaceUri:Be,localName:"Relationship",namespaceBindings:Object.freeze([]),attributes:Object.freeze(t),children:Object.freeze([])})}function Un(n,e){if(n.kind==="textValue"||n.namespaceUri!==Be||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 zn(n,e){return n.children.length!==e.length?false:n.children.every((t,r)=>Un(t,e[r]))}function jn(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 Fn(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&&Un(i,o)){r.push(i);continue}let a=i&&i.kind!=="textValue"?i.id:`${t}#rel-${o.id}`;f(a)||r.push(To(a,o));}return r}function No(n){return Object.freeze({id:`${n}#root`,kind:"generic",namespaceUri:Be,localName:"Relationships",namespaceBindings:Object.freeze([Object.freeze({prefix:"",namespaceUri:Be})]),attributes:Object.freeze([]),children:Object.freeze([])})}function Kn(n){return Object.freeze({id:n,name:n,contentType:Ao,root:No(n)})}function Vn(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 Xn=/^\/customXml\/item(\d+)\.xml$/i,_o=/^\/customXml\/itemProps(\d+)\.xml$/i;function ye(n){return Xn.test(n)}function It(n){return _o.test(n)}function Yo(n){let e=Xn.exec(n);if(!e)return null;let t=Number(e[1]);return Number.isSafeInteger(t)&&t>0?t:null}function Jn(n){return {item:`/customXml/item${String(n)}.xml`,props:`/customXml/itemProps${String(n)}.xml`}}function Uo(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 Wn(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 zo(n,e){let t=n.record(e);if(!t||!L(t))return null;for(let r of t.childIds){let o=n.record(r);if(!(!o||!L(o)||o.localName!=="schemaRefs")&&o.namespaceUri===DATASTORE_NAMESPACE_URI)for(let i of o.childIds){let a=n.record(i);if(!a||!L(a)||a.localName!=="schemaRef")continue;let s=Uo(a,"uri",DATASTORE_NAMESPACE_URI);if(s)return s}}return null}function jo(n,e){return e.childIds.some(t=>{let r=n.record(t);return !!r&&L(r)&&r.localName==="node"&&r.namespaceUri===e.namespaceUri})}function Fo(n,e){return e.localName==="node"||e.namespaceUri===WML_NAMESPACE_URI||e.namespaceUri===DATASTORE_NAMESPACE_URI||e.namespaceUri.length===0||n.parentOf(e.logicalId)!==null?false:jo(n,e)}function Ko(n,e){return e.localName!=="datastoreItem"||e.namespaceUri!==DATASTORE_NAMESPACE_URI?false:n.parentOf(e.logicalId)===null}function Gn(n,e){if(!n.hasNamespace(DATASTORE_NAMESPACE_URI))return [];let t=new Map,r=new Map;for(let[u,m]of e){let c=n.record(m.root.id);!c||!L(c)||(ye(u)&&t.set(c.logicalId,c),It(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)||(Fo(n,m)?t.set(u,m):Ko(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=zo(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)=>Wn(n,E).localeCompare(Wn(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=Yo(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=Jn(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=Jn(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 Vo(n){return n.type===CUSTOM_XML_REL||n.type===CUSTOM_XML_PROPS_REL?true:ye(n.ownerPart)}function Jo(n){let e=/^rId(\d+)$/.exec(n);if(!e)return 0;let t=Number(e[1]);return Number.isSafeInteger(t)?t:0}function Wo(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===CUSTOM_XML_REL).sort((s,l)=>s.id.localeCompare(l.id)),i=0;for(let s of r)i=Math.max(i,Jo(s.id));let a=[];for(let s=0;s<e.length;s+=1){let l=e[s],d=o[s],p=d?.id??`rId${String(i+=1)}`;a.push({ownerPart:t,id:p,type:CUSTOM_XML_REL,rawTarget:Wo(t,l.itemName),targetMode:"Internal",order:d?.order??s}),a.push({ownerPart:l.itemName,id:"rId1",type:CUSTOM_XML_PROPS_REL,rawTarget:l.propsName.slice(l.propsName.lastIndexOf("/")+1),targetMode:"Internal",order:0});}return a}function qn(n,e){return e.length===0?[...n]:[...n.filter(t=>!Vo(t)),...e]}function Zn(n){let e=new Map;for(let t of n)e.set(partNameKey(t.propsName),CUSTOM_XML_PROPS_TYPE);return e}function vt(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 Qn(n,e){if(vt(n,e))return true;for(let t of e){let r=n.get(t.itemName);if(!r)return true;let o=new Set(r.root.children.map(s=>s.id));if(t.nodeIds.some(s=>!o.has(s)))return true;let i=[];for(let s of r.root.children)s.kind!=="textValue"&&i.push(s.attributes.find(l=>l.localName==="id")?.value??s.id);let a=[...i].sort((s,l)=>s.localeCompare(l));if(i.some((s,l)=>s!==a[l]))return true}return false}var $o="http://schemas.microsoft.com/office/word/2012/wordml";function _e(n,e){return n.attributes.find(t=>t.localName===e)?.value}function Ye(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 er(n){return e=>e.localName===n&&e.namespaceUri===WML_NAMESPACE_URI}function Xo(n){return n.localName==="abstractNum"?`0${Ye(_e(n,"abstractNumId"))}`:`1${Ye(_e(n,"numId"))}`}function Go(n){return n.namespaceUri!==WML_NAMESPACE_URI?false:n.localName==="abstractNum"||n.localName==="num"}function tr(n){return n.localName==="comments"?{isMember:e=>e.kind==="comment",sortKey:e=>e.id}:n.localName==="commentsEx"?{isMember:e=>e.localName==="commentEx"&&e.namespaceUri===$o,sortKey:e=>e.id}:n.localName==="footnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:er("footnote"),sortKey:e=>Ye(_e(e,"id"))}:n.localName==="endnotes"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:er("endnote"),sortKey:e=>Ye(_e(e,"id"))}:n.localName==="numbering"&&n.namespaceUri===WML_NAMESPACE_URI?{isMember:Go,sortKey:Xo}:null}function Ho(n,e){return n.attributes.find(t=>t.localName===e)?.value}function St(n){return n.kind==="textValue"?n.id:Ho(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 or(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 qo(n){if(n.namespaceUri===XML_NAMESPACE_URI&&n.localName==="space"){let e=n.value==="preserve"?"preserve":"default";return Object.freeze({kind:"xmlSpace",namespaceUri:XML_NAMESPACE_URI,localName:"space",prefix:"xml",value:e})}return n.namespaceUri===WML_NAMESPACE_URI&&n.localName==="val"?Object.freeze({kind:"wmlVal",namespaceUri:WML_NAMESPACE_URI,localName:"val",prefix:n.prefix,value:n.value}):Object.freeze({kind:"genericExtension",namespaceUri:n.namespaceUri,localName:n.localName,prefix:n.prefix,value:n.value})}function sr(n){}function dr(n,e){return Object.freeze({id:n,kind:"textValue",value:e})}function ri(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 oi(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 Ue(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&&ri(r,n)?r.namespaceBindings:Object.freeze(n.bindings.map(o=>Object.freeze({...o}))),attributes:r&&oi(r,n)?r.attributes:Object.freeze(n.attributes.map(qo)),children:e})}function cr(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 Et(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)Et(o,e)||(r=false);return r}function ur(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 ze=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:qn(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:Vn(t)}),this.grouped.map}relationshipAssembly(e){let t=this.projected(e);return (!this.assembly||this.assembly.records!==t)&&(this.assembly={records:t,value:si(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;sr(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 si(n){let e=buildRelationshipSet(n);if(!e.ok)return null;let t=[];for(let r of n){let o=resolveRelationship(r);o.mode==="External"&&t.push({ownerPart:r.ownerPart,id:r.id,type:r.type,rawTarget:r.rawTarget,sinkSafe:o.sinkSafe.ok});}return {byOwner:e.byOwner,externalTargets:Object.freeze(t)}}var je=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 ci(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 ze(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 je;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=ur(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:ci(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&&(G(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?Et(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(G(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=dr(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])&&cr(d,i))return d;let p=d&&d.kind!=="textValue"?d.children:[];this.recordDroppedChildren(p,l);let h=Ue(i,re(p,l),d);return this.remember(e,h),h}recordDroppedChildren(e,t){if(e.length===0)return;let r=new Set(t.map(o=>o.id));for(let o of e)r.has(o.id)||this.droppedChildren.add(o.id);}remember(e,t){this.cache.set(e,t),this.heights.delete(e);}evictDeadSubtrees(e){for(let t of this.droppedChildren)e.has(t)||(this.registry.isTombstoned(t)||!this.registry.hasNode(t))&&this.evictSubtree(t,e);}evictSubtree(e,t){let r=this.cache.get(e);if(this.cache.delete(e),this.heights.delete(e),!(!r||r.kind==="textValue"))for(let o of r.children)t.has(o.id)||this.evictSubtree(o.id,t);}retainedNodeIds(){return [...this.cache.keys()]}heightOf(e){let t=this.heights.get(e.id);if(t!==void 0)return t;let r=1;if(e.kind!=="textValue")for(let o of e.children)r=Math.max(r,this.heightOf(o)+1);return this.heights.set(e.id,r),r}projectRelsParts(e){let t=this.packageCache.groupedByOwner(this.customXmlRels),r=new Set;for(let[o,i]of t){let a=relsPartNameFor(o);if(a!=="/_rels/.rels"&&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)||!_n(o))continue;let a=Yn(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||jn(o.root,t.root))&&o?o:t??Kn(e);if(zn(a.root,r))return this.relsProjection.set(e,a),a;let s=a.root.children,l=or(a,Fn(s,r,e));return this.relsProjection.set(e,l),l}adoptOrphanPartMembers(e,t,r,o,i){for(let[a,s]of e){let l=tr(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=Ue(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)=>St(m).localeCompare(St(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=Ue(p,h,a);return this.remember(e,u),u}applyCustomXmlStores(e,t,r){let o=Gn(this.registry,e);if(o.length===0||!Qn(e,o))return;let i=vt(e,o),a=new Set;for(let s of o){a.add(s.itemName),a.add(s.propsName);let l=this.adoptNodesIntoRoot(s.dataRootId,s.nodeIds,t,r),d=this.materializeOnce(s.propsRootId,t,r);if(!l||!d||d.kind==="textValue")continue;let p=Object.freeze({id:s.itemName,name:s.itemName,contentType:"application/xml",root:l}),h=Object.freeze({id:s.propsName,name:s.propsName,contentType:CUSTOM_XML_PROPS_TYPE,root:d});e.set(s.itemName,p),e.set(s.propsName,h),this.partCache.set(s.itemName,p),this.partCache.set(s.propsName,h);}if(i){for(let s of [...e.keys()])!ye(s)&&!It(s)||a.has(s)||(e.delete(s),this.partCache.delete(s));this.customXmlRels=Hn(this.registry,o),this.customXmlOverrides=Zn(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 Ke=64*1024*1024,oe="docx-package-blobs-v1";function pi(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 hi(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:0}function Fe(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=pi(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+=hi(t);}),e}put(e,t){if(!this.shared.has(e)){if(this.totalByteLength()+t.byteLength>Ke)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: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 Fe("too-many-nodes",`${r}`);let o=n.schema.parts.size;if(o>t.maxParts)return Fe("too-many-parts",`${o}`);let i=0;if(n.schema.relationships.forEach(s=>{i+=s instanceof x.Map?s.size:0;}),i>t.maxRelationships)return Fe("too-many-relationships",`${i}`);let a=e.totalByteLength();return a>Ke?Fe("blob-store-full",`${a}`):null}var mr=20*1024*1024,Lt=3e4,xi=4e3,Ii=1500,vi="docx-collaboration-seeds-v1",Rt="docxEditorSeedCandidate",Si=/^[0-9a-f]{16}$/,Ei=256;function wt(n){if(!(n instanceof Uint8Array)||n.byteLength===0)throw new g("invalid-baseline");if(n.byteLength>mr)throw new g("baseline-too-large");let e=readOoxmlPackage(n,{zip:{maxEntries:1e4,maxTotalBytes:mr,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!==WML_NAMESPACE_URI||!["document","hdr","ftr"].includes(i.root.localName)||!isStoryPart(i))continue;let a=normalizeParagraphIdentity(i);a!==i&&(r=withPart(r,a));}return new TreePackageStore(r,normalizeParagraphIdentity(r.parts.get(t.name))).currentPackage()}function Ri(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&&Ri(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 Ct(n){return n.getArray(vi)}function Ve(n){return Ct(n).length}function fr(n,e){let t=Ct(n),r=()=>{t.length>1&&e();};return r(),t.observe(r),()=>t.unobserve(r)}function Li(){let n=new Uint8Array(8);return globalThis.crypto.getRandomValues(n),[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function wi(n,e){let t=[...n.getStates().entries()].slice(0,Ei);for(let[r,o]of t){if(r===n.clientID)continue;let i=o[Rt];if(!(typeof i!="string"||!Si.test(i))&&i<e)return true}return false}async function gr(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 Ci(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 yr(n){let{ydoc:e,awareness:t,registry:r,blobs:o}=n,i=n.probeTimeoutMs??xi,a=n.electionWindowMs??Ii,s=n.timeoutMs??Lt,l=async()=>(await Ci(r,s,n.signal),"joined");if(await gr(r,o,i,n.signal))return l();let d=Li();t.setLocalStateField(Rt,d);try{let p=await gr(r,o,a,n.signal);if(!p&&wi(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,wt(n.document),o);if(!h.ok)throw new g(h.code);return e.transact(()=>{r.schema.meta.set("documentId",n.documentId),Ct(e).push([d]);}),"seeded"}finally{t.setLocalStateField(Rt,null);}}var Je=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 ki(n){let e=0;return n.schema.nodes.forEach(t=>{S(t)&&t.get(z)===true&&(e+=1);}),e}function Pi(n){let e=0;return n.schema.relationships.forEach(t=>{e+=t instanceof x.Map?t.size:0;}),e}function kt(n,e){return Object.freeze({nodes:n.nodeCount(),tombstonedNodes:ki(n),maxNodes:n.limits.maxNodes,relationships:Pi(n),maxRelationships:n.limits.maxRelationships,parts:n.schema.parts.size,maxParts:n.limits.maxParts,blobBytes:e.totalByteLength(),maxBlobBytes:Ke})}function ml(n){let e=new _(n);try{let t=new F(n.getMap(oe));return kt(e,t)}finally{e.destroy();}}var We="docxEditor",K=256,Pt=256;function Ir(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 vr(n){let e=n.trim();if(e.length===0||e.length>K)throw new g("invalid-document-id");return e}function Sr(n){let e=n?.trim()||globalThis.crypto.randomUUID();if(e.length>K)throw new g("invalid-session-id");return e}function xr(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 Ai(n){if(n===void 0||typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=xr(e.anchor),r=xr(e.head);if(t&&r)return e.kind==="cells"?{anchor:t,head:r,kind:"cells"}:{anchor:t,head:r};if(typeof e.paragraphId=="string"&&e.paragraphId.length===8&&Number.isSafeInteger(e.start)&&Number.isSafeInteger(e.end)&&e.start>=0&&e.end>=0){let o=e.paragraphId.toUpperCase();return {anchor:{paragraphId:o,offset:e.start},head:{paragraphId:o,offset:e.end}}}}function Ot(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;if(typeof e.actorId!="string"||e.actorId.length===0||e.actorId.length>K||typeof e.name!="string"||e.name.length===0||e.name.length>K)return null;let t=safeParticipantColor(typeof e.color=="string"?e.color:void 0),r=e.role==="agent"?"agent":"human",o={actorId:e.actorId,name:e.name,...t?{color:t}:{},role:r},i=Ai(e.selection);return i?{...o,selection:i}:o}function Ni(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(),Ve(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 writeOoxmlPackage(a.package)}finally{t?.destroy(),e.destroy();}}var Ui=3,zi=5e3,ji=2e3,Fi=Symbol("createDocumentCollaboration.attachWatchdogMs"),At=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.UndoManager([...a.trackedTypes()],{trackedOrigins:new Set([this.localOrigin]),captureTimeout:zi,deleteFilter:a.undoDeleteFilter()}),this.historyGroups=new Pe(this.undoManager),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=fr(e,()=>{this.setStatus("error","concurrent-seed");}),this.attachWatchdog=setTimeout(()=>{this.attachWatchdog=null,!(this.destroyed||this.port)&&console.warn(`[docx-editor] The collaboration session for "${this.documentId}" was created ${p}ms ago and no editor attached its document port. The session reports "ready" but no edits replicate. Remount the editor when the session appears \u2014 for example pass key={session.sessionId} \u2014 so collaborationModule({ session }) attaches it.`);},p),this.attachWatchdog.unref?.();}ydoc;awareness;registry;materializer;identityMap;blobs;offlineEditing;documentId;sessionId;currentIdentity;currentSelection;attachWatchdog=null;statusState=createCollaborationStatusTracker();statusListeners=new Set;selectionListeners=new Set;participantListeners=new Set;localOrigin=Object.freeze({kind:"docx-document-local"});undoManager;port=null;detachPort=null;applyingRemote=false;realignedInBatch=false;journalsHeldDuringRemote=[];drainingHeldJournals=false;remoteCounter=0;destroyed=false;refusedInARow=0;historyGroups;stopBlobWatch;stopSeedWatch;get identity(){return this.currentIdentity}clearAttachWatchdog(){this.attachWatchdog!==null&&(clearTimeout(this.attachWatchdog),this.attachWatchdog=null);}status(){return this.statusState.status()}statusSnapshot(){return this.statusState.snapshot()}resourceUsage(){return kt(this.registry,this.blobs)}subscribeStatus(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}setTransportStatus(e,t,r){if(!this.destroyed&&!(this.statusState.status()==="error"&&e!=="error")){if(t!==void 0){this.setStatus(e,t,r);return}this.setStatus(e);}}get attached(){return this.port!==null}attach(e){let t=this.refuseAttach(e);if(t)return t;this.clearAttachWatchdog(),this.port=e,this.publishSharedToPort();let r=e.observePrimitiveJournal(o=>{if(!this.destroyed){if(this.applyingRemote){this.journalsHeldDuringRemote.push(o);return}this.realignedInBatch||this.applyJournal(o);}});return this.detachPort=()=>{this.flushPendingJournals(),r(),this.port===e&&(this.port=null),this.detachPort=null;},()=>this.detachPort?.()}refuseAttach(e){return this.destroyed?()=>{}:this.port?(this.port!==e&&this.setStatus("error","port-already-attached"),()=>{}):e.documentId!==this.documentId?(this.setStatus("error","document-id-mismatch"),()=>{}):null}hasCompatibleSharedSchema(){let e=Q(this.registry.schema.meta);return e?(this.setStatus("error",e.code,e.detail),false):true}canWriteSharedState(){if(this.destroyed||!this.hasCompatibleSharedSchema())return false;let e=this.statusState.status();return e==="ready"||this.offlineEditing&&e==="disconnected"}gateOperations(e,t){return this.destroyed?"collaboration-session-destroyed":this.canWriteSharedState()?this.port?null:"collaboration-session-not-attached":"collaboration-session-not-ready"}canUndo(){return this.canWriteSharedState()&&((this.port?.hasPendingJournals()??false)||this.undoManager.undoStack.length>0)}canRedo(){return this.canWriteSharedState()&&this.undoManager.redoStack.length>0}undo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.undoStack.length===0?false:(this.historyGroups.reset(),this.undoManager.undo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}redo(){return !this.canWriteSharedState()||(this.flushPendingJournals(),!this.canWriteSharedState())||this.undoManager.redoStack.length===0?false:(this.historyGroups.reset(),this.undoManager.redo(),this.registry.normalizeRestoredSplitTextAnchors(),true)}flushPendingJournals(){this.port?.flushPendingJournals();}setLocalSelection(e){if(!this.destroyed){if(!e){this.publishAwareness();return}this.publishAwareness({anchor:{paragraphId:e.anchor.paragraphId.toUpperCase(),offset:Math.max(0,e.anchor.offset)},head:{paragraphId:e.head.paragraphId.toUpperCase(),offset:Math.max(0,e.head.offset)},...e.kind==="cells"?{kind:"cells"}:{}});}}participants(){let e=[],t=[...this.awareness.getStates().entries()].slice(0,Pt);for(let[r,o]of t){let i=Ot(o[We]);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,Pt),o=[];for(let[i,a]of r){if(i===this.awareness.clientID)continue;let s=Ot(a[We]);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=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=tn(this.registry,this.identityMap.translate(e));if(!t.ok){this.refuseLocalJournal({code:t.code,...t.detail?{detail:t.detail}:{}});return}let r=t.journal,o=this.collectJournalBlobs(e);if(o!==null&&o.ok===false){this.refuseLocalJournal(o.failure);return}if(!this.canWriteSharedState())return;let i=this.historyGroups.capture(historyGroupOfJournal(e),()=>this.ydoc.transact(()=>{if(o!==null){let s=this.putJournalBlobs(o.payloads);if(s!==null)return s}let a=st(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=Nn(e.effects,Tn(t));return r===null?null:r.ok?r:{ok:false,failure:Object.freeze(r.failure)}}putJournalBlobs(e){try{Mn(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.historyGroups.reset(),this.undoManager.stopCapturing();let t=this.statusState.snapshot();this.refusedInARow+=1,this.setStatus("error",e.code,e.detail),this.publishSharedToPort(),this.realignedInBatch=true,queueMicrotask(()=>{this.realignedInBatch=false;});let r=this.statusState.snapshot().reason;this.refusedInARow<Ui&&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: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(We,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 zl(n){let e=n[Fi]??ji,t=vr(n.documentId),r=Sr(n.sessionId),o=Ir(n.identity),i=new _(n.ydoc);try{return await Ki(n,{attachWatchdogMs:e,documentId:t,sessionId:r,identity:o,registry:i})}catch(a){throw i.destroy(),a}}async function Ki(n,e){let{attachWatchdogMs:t,documentId:r,sessionId:o,identity:i,registry:a}=e,s=new Je(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,wt(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 yr({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??Lt,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(Ve(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=writeOoxmlPackage(h.package),c=new At(n.ydoc,n.awareness,r,o,i,a,p,s,l,t,n.offlineEditing===!0);return Object.freeze({document:m,session:c,destroy:()=>c.destroy()})}catch(h){throw p.destroy(),h}}export{Bt as a,_t as b,Ge as c,g as d,qe as e,Dr as f,Gi as g,Hi as h,qi as i,V as j,ea as k,zr as l,ml as m,Ni as n,Fi as o,zl as p};
|