revise 3.1.7 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1677 -184
- package/FONT-LICENSE-HAN-EXT-B.txt +91 -0
- package/FONT-LICENSE-KATEX.txt +95 -0
- package/FONT-LICENSE-LIBERATION.txt +102 -0
- package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +93 -0
- package/FONT-LICENSE-NOTO-SANS-SC.txt +93 -0
- package/FONT-LICENSE-NOTO.txt +94 -0
- package/FONT-LICENSE-SOURCE-CODE-PRO.txt +94 -0
- package/FONT-LICENSE-SOURCE-SERIF-4.txt +93 -0
- package/LICENSE +41 -21
- package/README.md +29 -121
- package/THIRD-PARTY-NOTICES.md +2751 -0
- package/assets/historyMaterializeWorker-ZFUHJDWr.js +619 -0
- package/chunks/AgentPageRenderer-CHHktDQ1.js +1 -0
- package/chunks/AgentPageRenderer-CN-N65JC.js +1 -0
- package/chunks/AttachmentDocumentImporter-DnHC9t7I.js +1 -0
- package/chunks/AttachmentDocumentImporter-Dqg7IPtK.js +1 -0
- package/chunks/ColorParserFull-BKH72fK8.js +446 -0
- package/chunks/DocumentScrubber-Ch_bOtHW.js +1 -0
- package/chunks/DocumentScrubber-DRzACkWJ.js +1 -0
- package/chunks/DocxConverter-BGPkGmyg.js +13 -0
- package/chunks/DocxConverter-DeurS5EF.js +13 -0
- package/chunks/DocxGraft-D71OgoMh.js +1 -0
- package/chunks/DocxGraft-QLkGEcwQ.js +1 -0
- package/chunks/FileImporter-BIT0ZBDY.js +1 -0
- package/chunks/FileImporter-Cgwoawuk.js +1 -0
- package/chunks/OdtConverter-2pm0SH5c.js +6 -0
- package/chunks/OdtConverter-CSUQTfVp.js +6 -0
- package/chunks/OfficeImportShared-C_mYnG5V.js +1 -0
- package/chunks/OfficeImportShared-O-d47J7O.js +1 -0
- package/chunks/PdfConverter-BYg_pr5J.js +21 -0
- package/chunks/PdfConverter-Z2HlY84F.js +21 -0
- package/chunks/PdfImportService-C2gwK1Sq.js +2 -0
- package/chunks/PdfImportService-CxtUtxM6.js +2 -0
- package/chunks/RtfConverter-BrtojpDV.js +15 -0
- package/chunks/RtfConverter-DlztsAoK.js +15 -0
- package/chunks/XmlConverter-3XWISlqr.js +2 -0
- package/chunks/XmlConverter-B1Kcohr0.js +2 -0
- package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
- package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +1 -0
- package/chunks/ar-vDYSGTpE.js +13 -0
- package/chunks/browser-module-BVdVmrPb.js +3 -0
- package/chunks/browser-module-CWlRHeO2.js +3 -0
- package/chunks/bundle.min-DRpfgV69.js +782 -0
- package/chunks/de-CWX4cvtt.js +13 -0
- package/chunks/es-DoAhvF6_.js +13 -0
- package/chunks/fil-DdAeD8Br.js +13 -0
- package/chunks/fr-CazsUjNQ.js +13 -0
- package/chunks/html2canvas.esm-CntiHiYW.js +997 -0
- package/chunks/index-BWdRWxoH.js +1807 -0
- package/chunks/index-D9_PwgOX.js +402 -0
- package/chunks/index-DcIXw_KB.js +402 -0
- package/chunks/ja-alh_QHTB.js +13 -0
- package/chunks/jspdf.es.min-BuJNZ-oY.js +1882 -0
- package/chunks/katex-DWj8TvwO.js +1462 -0
- package/chunks/pdf-BLWDCiFF.js +1828 -0
- package/chunks/persistInlineDocumentImages-DQj2iaqg.js +1 -0
- package/chunks/pseudoLocale-Bld5ZUFr.js +1 -0
- package/chunks/pseudoLocale-CLm3_c4X.js +1 -0
- package/chunks/tree-sitter-D6zWWUMP.js +4 -0
- package/chunks/wasmInline.generated-CBYFkdSM.js +1 -0
- package/chunks/web-tree-sitter-BXGZGnNj.js +2 -0
- package/chunks/zh-20eXwzFZ.js +13 -0
- package/cli-shim.js +34 -0
- package/full.js +1 -0
- package/index.d.ts +995 -13
- package/index.js +1 -31
- package/legacy/server.d.ts +19 -19
- package/legacy/server.js +39 -23
- package/package.json +55 -45
- package/serverToolContract.d.ts +420 -0
- package/serverToolInputs.generated.d.ts +269 -0
- package/style.css +1 -0
- package/version.d.ts +4 -0
- package/version.js +2 -0
- package/agent.d.ts +0 -139
- package/chunks/chunk-SMTOJL2X.js +0 -2436
- package/chunks/chunk-U5X47PZ6.js +0 -135
- package/chunks/chunk-U6YKQBKL.js +0 -15
- package/chunks/package-5SHL5FOJ.js +0 -14
- package/chunks/render-QD5VWKSV.js +0 -109
- package/cli-output.schema.json +0 -2159
- package/cli.js +0 -4152
- package/document.d.ts +0 -439
- package/docx.d.ts +0 -73
- package/errors.d.ts +0 -14
- package/legacy/editor.d.ts +0 -19
- package/legacy/editor.js +0 -16
- package/legacy/style.css +0 -2
- package/package.d.ts +0 -23
- package/render.d.ts +0 -27
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{an as Ae,ao as Ni,ap as Er,aq as Ai,c as Ti,h as Mi,ar as Dr,as as Ei,at as Di,au as Bi,av as Ee,I as Ri,aw as Li,ax as Fi,ay as Oi,K as Ft,az as Ot,aA as $i,aB as _i,R as Ct,aC as Wi,aD as tr,L as Qe,aE as Br,aF as Xi,aG as Rr,aH as zi,aI as rr,aJ as Hi,aK as Lr,aL as ji,aM as Gi,aN as Ji,u as Ui,v as Ki,G as Zi,_ as Vi,aO as Fr,aP as qi,aQ as Yi,ak as Qi,aR as en,aS as tn,aT as rn,aU as ir,aV as nn,aW as on,Q as sn,aX as an,aY as Or,aZ as ln,a_ as cn,a$ as $r,J as dn,b0 as _r,b1 as pn,m as nr,b2 as Wr,b3 as hn,b4 as gn,b5 as mn,b6 as Xr,b7 as or,b8 as un,b9 as fn}from"./index-D9_PwgOX.js";const zr=()=>new XMLSerializer,Hr=new Set(["w:rStyle","w:b","w:i","w:u","w:strike","w:dstrike","w:smallCaps","w:caps","w:vanish","w:lang","w:spacing","w:vertAlign","w:color","w:highlight","w:shd","w:rFonts","w:sz","w:rPrChange","w:bCs","w:iCs","w:szCs","w:highlightCs","w:ins","w:del","w:rtl","w:specVanish","w:imprint","w:emboss","w:snapToGrid"]),jr=new Set(["w:pStyle","w:keepNext","w:keepLines","w:widowControl","w:bidi","w:jc","w:ind","w:pageBreakBefore","w:spacing","w:contextualSpacing","w:outlineLvl","w:numPr","w:pBdr","w:shd","w:tabs","w:rPr","w:sectPr","w:pPrChange"]),Gr=new Set(["w:tblStyle","w:tblW","w:jc","w:tblInd","w:tblBorders","w:tblLayout","w:tblCellMar","w:tblPrChange"]),Jr=new Set(["w:tblHeader","w:ins","w:del","w:trPrChange"]),Ur=new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]),Kr=new Set(["w:pgSz","w:pgMar","w:pgNumType","w:lnNumType","w:cols","w:type","w:docGrid","w:titlePg","w:headerReference","w:footerReference","w:sectPrChange","w:rPr"]);function at(F,e){if(!F)return;let r="";const t=zr();for(let i=0;i<F.children.length;i++){const n=F.children[i];e.has(n.tagName)||(r+=t.serializeToString(n))}return r?ar(r):void 0}function sr(F){if(!F||F.attributes.length===0)return;const e={};for(let i=0;i<F.attributes.length;i++){const n=F.attributes[i];n.name==="xmlns"||n.name.startsWith("xmlns:")||(e[n.name]=n.value)}const r=Object.keys(e).sort();if(r.length===0)return;const t={};for(const i of r)t[i]=e[i];return JSON.stringify(t)}function ar(F){if(!/[\n\r\t]/.test(F))return F;let e="",r=!1,t=null;for(let i=0;i<F.length;i++){const n=F[i];if(t){n===t?(t=null,e+=n):n===`
|
|
2
|
+
`?e+=" ":n==="\r"?e+=" ":n===" "?e+="	":e+=n;continue}r&&(n==='"'||n==="'")?t=n:n==="<"?r=!0:n===">"&&(r=!1),e+=n}return e}function lr(F){const e=ar(zr().serializeToString(F));let r;const t=F.getElementsByTagName("o:OLEObject")[0];if(t)r=t.getAttribute("ProgID")??void 0;else if(F.tagName==="w:altChunk")r=F.getAttribute("r:id")??void 0;else{const i=F.getElementsByTagName("a:graphicData")[0]?.getAttribute("uri")?.split("/").filter(Boolean).pop();i&&i!=="picture"&&(r=i)}return{xml:e,tagName:F.tagName,...r?{detail:r}:{}}}function cr(F){return F.includes("http://schemas.openxmlformats.org/officeDocument/2006/relationships")}const Zr=new Set(["w:p","w:tbl","w:sdt","w:customXml","w:sectPr","w:bookmarkStart","w:bookmarkEnd","w:commentRangeStart","w:commentRangeEnd","w:moveFromRangeStart","w:moveFromRangeEnd","w:moveToRangeStart","w:moveToRangeEnd","w:permStart","w:permEnd","w:ins","w:del","w:moveFrom","w:moveTo","w:proofErr","w:tcPr","w:trPr","w:tblPr","w:tblGrid","w:tblPrEx","w:pPr"]),wn=/^[A-Za-z_][\w.-]*(?::[\w.-]+)?$/;function Vr(F,e){let r;try{r=JSON.parse(F)}catch{return""}if(r===null||typeof r!="object"||Array.isArray(r))return"";let t="";for(const[i,n]of Object.entries(r)){if(typeof n!="string"||!wn.test(i)||e?.has(i))continue;const a=n.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""");t+=` ${i}="${a}"`}return t}const bn=Object.freeze(Object.defineProperty({__proto__:null,KNOWN_BODY_TAGS:Zr,KNOWN_PPR_TAGS:jr,KNOWN_RPR_TAGS:Hr,KNOWN_SECTPR_TAGS:Kr,KNOWN_TBLPR_TAGS:Gr,KNOWN_TCPR_TAGS:Ur,KNOWN_TRPR_TAGS:Jr,attrsJsonToXmlAttributes:Vr,captureRawElement:lr,extractElementAttrsJson:sr,extractOpaqueChildrenXml:at,stabilizeSerializedXml:ar,xmlReferencesRelationships:cr},Symbol.toStringTag,{value:"Module"})),yn="http://schemas.openxmlformats.org/officeDocument/2006/math",qr=`<m:oMath xmlns:m="${yn}">`,vn=new Set("∑∏∐∫∬∭∮∯∰∱∲∳⋀⋁⋂⋃⨀⨁⨂⨄⨆".split("")),xn=new Set(["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"]),Sn=new Set(["lim","liminf","limsup","max","min","sup","inf","Pr"]),Yr={"^":"̂","ˆ":"̂","̂":"̂","~":"̃","˜":"̃","̃":"̃","ˉ":"̄","¯":"̄","̄":"̄","˙":"̇","̇":"̇","¨":"̈","̈":"̈","ˊ":"́","´":"́","́":"́","ˋ":"̀","`":"̀","̀":"̀","ˇ":"̌","̌":"̌","˘":"̆","̆":"̆","→":"⃗","⃗":"⃗"},In=new Set(["‾","¯","_","―","−"]),kn=new Set(["⏞","⏟","⏜","⏝","⎴","⎵"]),Pn=new Set(["","","",""]),dr={normal:'<m:sty m:val="p"/>',bold:'<m:sty m:val="b"/>',italic:'<m:sty m:val="i"/>',"bold-italic":'<m:sty m:val="bi"/>',"double-struck":'<m:scr m:val="double-struck"/><m:sty m:val="p"/>',script:'<m:scr m:val="script"/>',"bold-script":'<m:scr m:val="script"/><m:sty m:val="b"/>',fraktur:'<m:scr m:val="fraktur"/>',"bold-fraktur":'<m:scr m:val="fraktur"/><m:sty m:val="b"/>',"sans-serif":'<m:scr m:val="sans-serif"/><m:sty m:val="p"/>',monospace:'<m:scr m:val="monospace"/><m:sty m:val="p"/>'};function Qr(F){return F.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function lt(F){return Qr(F)}function We(F){return Array.from(F.children)}function $e(F){return(F.textContent??"").replace(/[-]/g,"")}function xe(F){return F.localName.toLowerCase()}function pr(F){let e=F;for(;["mrow","mstyle","mpadded","semantics"].includes(xe(e))&&We(e).filter(r=>!$t(r)).length===1;)e=We(e).filter(r=>!$t(r))[0];return e}function $t(F){return xe(F)==="mo"&&Pn.has((F.textContent??"").trim())}function _t(F){if(!F)return null;const e=pr(F);if(xe(e)!=="mo")return null;const r=$e(e).trim();return vn.has(r)?r:null}function Wt(F){if(!F)return null;const e=pr(F);if(!["mi","mo"].includes(xe(e)))return null;const r=$e(e).trim();return xn.has(r)?r:null}const Cn=new Set("+-−=<>≤≥≠≈≡∼≃≅∝,;:∣∈∉⊂⊆⊃⊇→←↔⇒⇐⇔".split(""));function Nn(F){return xe(F)==="mo"&&Cn.has($e(F).trim())}function ei(F,e){let r=e;for(;r<F.length&&!Nn(F[r]);)r+=1;return r}function ti(F){return!!F&&xe(F)==="mo"&&F.getAttribute("fence")==="true"}function Je(F,e){if(!F)return"";const r=/^\s+$/.test(F)?`${F}`:F,t=/^\s|\s$/.test(r)?' xml:space="preserve"':"";return`<m:r>${e?`<m:rPr>${e}</m:rPr>`:""}<m:t${t}>${Qr(r)}</m:t></m:r>`}function An(F,e){const r=xe(F),t=$e(F);if(!t)return"";if(r==="mtext"||r==="ms")return Je(t,"<m:nor/>");const i=F.getAttribute("mathvariant")??e.mathvariant;return i&&dr[i]?Je(t,dr[i]):r==="mi"&&[...t].length>1?Je(t,'<m:sty m:val="p"/>'):Je(t,"")}function le(F,e){return`<m:${F}>${e}</m:${F}>`}function ri(F,e,r,t,i){return`<m:nary><m:naryPr>${`<m:chr m:val="${lt(F)}"/><m:limLoc m:val="${e}"/>`+(r===null?'<m:subHide m:val="1"/>':"")+(t===null?'<m:supHide m:val="1"/>':"")}</m:naryPr>`+le("sub",r??"")+le("sup",t??"")+le("e",i)+"</m:nary>"}function ii(F,e){return`<m:func>${le("fName",F)}${le("e",e)}</m:func>`}function ni(F){return parseFloat(F.getAttribute("width")??"")>0?" ":""}function Tn(F){return xe(F)==="mrow"&&F.children.length===0&&!$e(F).trim()}function Ue(F,e){const r=F.filter(i=>!$t(i)&&!Tn(i));if(r.length>=2&&ti(r[0])){const i=r[r.length-1],n=ti(i),a=r.slice(1,n?-1:void 0),o=$e(r[0]).trim(),s=n?$e(i).trim():"";return`<m:d><m:dPr><m:begChr m:val="${lt(o)}"/><m:endChr m:val="${lt(s)}"/></m:dPr>`+le("e",Ue(a,e))+"</m:d>"}let t="";for(let i=0;i<r.length;i+=1){const n=r[i],a=xe(n),o=r[i+1];if(["msub","msup","msubsup","munder","mover","munderover"].includes(a)&&_t(We(n)[0])){const[c,p,h]=We(n),g=_t(c),f=a.startsWith("mu")?"undOvr":"subSup",w=["msub","msubsup","munder","munderover"].includes(a)?pe(p,e):null,u=a==="msubsup"||a==="munderover"?pe(h,e):a==="msup"||a==="mover"?pe(p,e):null,m=ei(r,i+1);t+=ri(g,f,w,u,Ue(r.slice(i+1,m),e)),i=m-1;continue}if(a==="mo"&&_t(n)){const c=ei(r,i+1);t+=ri(_t(n),"undOvr",null,null,Ue(r.slice(i+1,c),e)),i=c-1;continue}const s=["msub","munder"].includes(a)?Wt(We(n)[0]):null;if(s&&Sn.has(s)&&o){const[c,p]=We(n),h=`<m:limLow>${le("e",Je(Wt(c),'<m:sty m:val="p"/>'))}${le("lim",pe(p,e))}</m:limLow>`;t+=ii(h,pe(o,e)),i+=1;continue}if(Wt(n)&&o){t+=ii(Je(Wt(n),'<m:sty m:val="p"/>'),pe(o,e)),i+=1;continue}if(a==="mtext"||a==="mspace"){let c="",p=i;for(;r[p]&&["mtext","mspace"].includes(xe(r[p]));)c+=xe(r[p])==="mtext"?$e(r[p]):ni(r[p]),p+=1;i=p-1;const h=c.replace(/\s{2,}/g," ");h&&(t+=Je(h,"<m:nor/>"));continue}const l=a==="mi"?n.getAttribute("mathvariant"):null;if(l){let c=$e(n);for(;r[i+1]&&xe(r[i+1])==="mi"&&r[i+1].getAttribute("mathvariant")===l;)i+=1,c+=$e(r[i]);t+=Je(c,dr[l]??"");continue}t+=pe(n,e)}return t}function pe(F,e){if(!F)return"";const r=xe(F),t=We(F);switch(r){case"math":case"semantics":case"mrow":case"mpadded":case"merror":return Ue(t,e);case"mstyle":{const i=F.getAttribute("mathvariant");return Ue(t,i?{...e,mathvariant:i}:e)}case"annotation":case"annotation-xml":case"mphantom":case"none":case"mprescripts":return"";case"mi":case"mn":case"mo":case"mtext":case"ms":return $t(F)?"":An(F,e);case"mspace":{const i=ni(F);return i?Je(i,"<m:nor/>"):""}case"mfrac":{const i=F.getAttribute("linethickness");return`<m:f>${i!==null&&parseFloat(i)===0?'<m:fPr><m:type m:val="noBar"/></m:fPr>':""}`+le("num",pe(t[0],e))+le("den",pe(t[1],e))+"</m:f>"}case"msqrt":return'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>'+le("e",Ue(t,e))+"</m:rad>";case"mroot":return"<m:rad>"+le("deg",pe(t[1],e))+le("e",pe(t[0],e))+"</m:rad>";case"msub":return`<m:sSub>${le("e",pe(t[0],e))}${le("sub",pe(t[1],e))}</m:sSub>`;case"msup":return`<m:sSup>${le("e",pe(t[0],e))}${le("sup",pe(t[1],e))}</m:sSup>`;case"msubsup":return`<m:sSubSup>${le("e",pe(t[0],e))}`+le("sub",pe(t[1],e))+le("sup",pe(t[2],e))+"</m:sSubSup>";case"mover":case"munder":return Mn(F,r==="mover"?"top":"bot",e);case"munderover":{const[i,n,a]=t,o=`<m:limLow>${le("e",pe(i,e))}${le("lim",pe(n,e))}</m:limLow>`;return`<m:limUpp>${le("e",o)}${le("lim",pe(a,e))}</m:limUpp>`}case"mtable":return"<m:m>"+t.filter(i=>["mtr","mlabeledtr"].includes(xe(i))).map(i=>"<m:mr>"+We(i).filter(n=>xe(n)==="mtd").map(n=>le("e",Ue(We(n),e))).join("")+"</m:mr>").join("")+"</m:m>";case"menclose":{const i=Ue(t,e),n=F.getAttribute("notation")??"";return/\bbox\b|roundedbox/.test(n)?`<m:borderBox>${le("e",i)}</m:borderBox>`:i}case"mfenced":{const i=F.getAttribute("open")??"(",n=F.getAttribute("close")??")";return`<m:d><m:dPr><m:begChr m:val="${lt(i)}"/><m:endChr m:val="${lt(n)}"/></m:dPr>`+t.map(a=>le("e",pe(a,e))).join("")+"</m:d>"}default:return Ue(t,e)}}function Mn(F,e,r){const[t,i]=We(F),n=pe(t,r),a=i?pr(i):void 0,o=a&&xe(a)==="mo"?$e(a).trim():"";if(o&&In.has(o))return`<m:bar><m:barPr><m:pos m:val="${e}"/></m:barPr>${le("e",n)}</m:bar>`;if(o&&kn.has(o))return`<m:groupChr><m:groupChrPr><m:chr m:val="${lt(o)}"/><m:pos m:val="${e}"/><m:vertJc m:val="${e==="top"?"bot":"top"}"/></m:groupChrPr>`+le("e",n)+"</m:groupChr>";const s=F.getAttribute(e==="top"?"accent":"accentunder")==="true";if(e==="top"&&o&&(s||Yr[o])){const c=Yr[o]??o;return`<m:acc><m:accPr><m:chr m:val="${lt(c)}"/></m:accPr>${le("e",n)}</m:acc>`}const l=e==="top"?"limUpp":"limLow";return`<m:${l}>${le("e",n)}${le("lim",pe(i,r))}</m:${l}>`}function En(F){return new DOMParser().parseFromString(F,"text/html").querySelector("math")}function Dn(F){const e=En(F);if(!e)throw new Error("mathmlToOmml: no <math> element in input");return`${qr}${pe(e,{})}</m:oMath>`}const oi="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",ue=class hr{static async parseFile(e,r){if(!e.name.toLowerCase().endsWith(".docx"))throw new Error(`DocxConverter only supports .docx files, got: ${e.name}`);return this.parseDocxFile(e,r)}static async parseDocxFile(e,r){const t=await e.arrayBuffer(),i=await Er.loadAsync(t),n=await i.file("word/document.xml")?.async("string");if(!n)return{type:"doc",children:[this.createEmptyParagraph()]};const a=this.parseDocumentXml(n);if(!a)return{type:"doc",children:[this.createEmptyParagraph()]};const o=await this.loadOOXMLPackageContext(i,n),s=await this.parseDocumentPageLayoutFromPackage(n,i,a),l=await i.file("word/fontTable.xml")?.async("string"),c=this.parseFontTableXml(l),p=await i.file("word/settings.xml")?.async("string"),h=!!(p&&/<w:autoHyphenation(?![^>]*w:val="(?:0|false)")[^>]*\/?>/.test(p)),g=r?.retainSource?new Map:void 0,f=await this.parseStructuredDocxDocument(n,s,o,a,g),w=await i.file("docProps/custom.xml")?.async("string");if(w){const T=this.parseDocumentXml(w),O=(T&&Array.from(T.getElementsByTagNameNS("*","property")).find(X=>X.getAttribute("name")==="Revise.BlockSpacingPx"))?.textContent?.trim(),W=O?Number(O):NaN;Number.isFinite(W)&&W>=0&&W<=192&&(f.pageLayout={...f.pageLayout??{},blockSpacingPx:W})}h&&(f.pageLayout={...f.pageLayout??{},hyphenationEnabled:!0}),c&&(f.fontSubstitutes=c,Ai(c));const u=await i.file("word/footnotes.xml")?.async("string"),m=await i.file("word/endnotes.xml")?.async("string"),b=new Map;u&&await this.collectNotesFromXml(f,u,"w:footnote","docxfn","footnote",b,o),m&&await this.collectNotesFromXml(f,m,"w:endnote","docxen","endnote",b,o),this.finalizeImportedFootnoteRefs(f,b);const v=await i.file("word/comments.xml")?.async("string");if(v){const T=await i.file("word/commentsExtended.xml")?.async("string");this.attachCommentsFromXml(f,v,T,o)}await this.attachHeadersFootersFromPackage(f,n,i,o,a);const y=await i.file("docProps/core.xml")?.async("string");if(y){const T=this.parseCoreProperties(y);T&&(f.coreProperties=T)}return g&&Ti(f,g,await Mi(new Uint8Array(t))),f}static parseCoreProperties(e){const r=this.parseDocumentXml(e);if(!r)return;const t=new Set(this.CORE_PROPERTY_LOCAL_NAMES),i={},n=r.documentElement;for(let a=0;a<n.children.length;a++){const o=n.children[a],s=o.tagName.split(":").pop()??o.tagName;if(!t.has(s))continue;const l=o.textContent??"";l.trim().length!==0&&(i[s]=l)}return Object.keys(i).length>0?i:void 0}static readHeaderFooterReferences(e,r){const t={};for(let i=0;i<e.children.length;i++){const n=e.children[i];if(n.tagName!==r)continue;const a=n.getAttribute("w:type")??"default",o=a==="first"||a==="even"?a:"default",s=n.getAttribute("r:id")??n.getAttribute("relationships:id");s&&(t[o]=s)}return t}static resolveSectionHeaderFooterReferences(e){const r=[];for(let t=0;t<e.length;t++){const i=r[t-1]??{header:{},footer:{}};r.push({header:{...i.header,...this.readHeaderFooterReferences(e[t],"w:headerReference")},footer:{...i.footer,...this.readHeaderFooterReferences(e[t],"w:footerReference")}})}return r}static async attachHeadersFootersFromPackage(e,r,t,i,n){const a=(n??this.parseDocumentXml(r))?.getElementsByTagName("w:body")[0];if(!a)return;const o=this.findAllSectionProperties(a);if(o.length===0)return;const s=this.resolveSectionHeaderFooterReferences(o),l=o.length-1,c=s[l],p=new Map,h=async O=>{const W=p.get(O);if(W)return W;const X={paragraphs:[],images:[]},D=i?.relationships.get(O);if(D){const M=D.target.startsWith("word/")?D.target:`word/${D.target.replace(/^\//,"")}`,L=await t.file(M)?.async("string");if(L){const I=M.split("/").pop()??M,B=await t.file(`word/_rels/${I}.rels`)?.async("string");if(X.paragraphs=await this.parseHeaderFooterPart(L,B?this.parseRelationshipsXml(B,M):void 0),!e.watermark){const E=this.parseVmlWatermark(L);E&&(e.watermark=E)}X.images=await this.parseHeaderFooterImages(L,M,t,i)}}return p.set(O,X),X},g=async O=>(await h(O)).paragraphs,f=["default","first","even"],w=[],u=async(O,W)=>{const X={};for(const D of f){const M=O[D];if(!M)continue;const L=await h(M);L.paragraphs.length>0&&(X[D]=L.paragraphs);for(const I of L.images)w.push({side:W,slot:D,...I})}return Object.keys(X).length>0?X:void 0},m=await u(c.header,"header"),b=await u(c.footer,"footer");m&&(e.headers=m),b&&(e.footers=b),w.length>0&&(e.chromeImages=w);const v=[];for(let O=0;O<l;O++)for(const W of["header","footer"])for(const X of f){const D=s[O][W][X],M=c[W][X];if(D===M)continue;const L=D?await g(D):[];v.push(Dr(W,X,L.length>0?Ei(L):void 0,void 0,O))}const y=[],T=new Set(v.map(O=>`${O.side}/${O.slot}/${O.sectionIndex}`));for(let O=0;O<o.length;O++)if(o[O].getElementsByTagName("w:titlePg").length!==0)for(const W of["header","footer"]){const X=s[O][W].first;if((X?await g(X):[]).length>0||!s[O][W].default)continue;const D=O===l?void 0:O;T.has(`${W}/first/${D}`)||y.push(Dr(W,"first",void 0,void 0,D))}(v.length>0||y.length>0)&&(e.chrome=[...Di(e.headers,e.footers),...v,...y])}static parseVmlWatermark(e){if(!e.includes("v:textpath"))return;const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("v:textpath");for(let i=0;i<t.length;i++){const n=t[i],a=(n.getAttribute("string")??"").trim();if(!a)continue;let o=n.parentNode;for(;o&&o.tagName!=="v:shape";)o=o.parentNode;const s=(o?.getAttribute("style")??"").match(/rotation:\s*(-?\d+(?:\.\d+)?)/),l=s?(parseFloat(s[1])%360+360)%360:0,c=this.vmlFillColorToHex(o?.getAttribute("fillcolor")??"");let p;const h=o?.getElementsByTagName("v:fill")[0]?.getAttribute("opacity");if(h){const w=h.endsWith("f")?parseFloat(h)/65536:parseFloat(h);Number.isFinite(w)&&w>0&&w<=1&&(p=Math.abs(w-Fr)<.05?void 0:w)}const g=(n.getAttribute("style")??"").match(/font-size:\s*(\d+(?:\.\d+)?)pt/),f=g?parseFloat(g[1]):void 0;return Bi({text:a,...c?{color:c}:{},...p!==void 0?{opacity:p}:{},diagonal:l!==0,...f&&f>2?{fontSizePx:Math.round(f*(4/3))}:{}})}}static vmlFillColorToHex(e){const r=e.trim().toLowerCase();if(r){if(r.startsWith("#")){const t=r.slice(1,7);return/^[0-9a-f]{6}$/.test(t)?`#${t.toUpperCase()}`:void 0}return{silver:"#C0C0C0",gray:"#808080",grey:"#808080",black:"#000000",red:"#FF0000",blue:"#0000FF",green:"#008000",white:"#FFFFFF"}[r]}}static async parseHeaderFooterImages(e,r,t,i){if(!i||!e.includes("w:drawing"))return[];const n=this.parseDocumentXml(e);if(!n)return[];const a=n.getElementsByTagName("w:drawing");if(a.length===0)return[];const o=r.split("/").pop()??r,s=await t.file(`word/_rels/${o}.rels`)?.async("string"),l={...i,relationships:this.parseRelationshipsXml(s,r)},c=[];for(let p=0;p<a.length;p++){const h=await this.parseImageFromDrawing(a[p],void 0,l);if(h){const g=this.headerFooterImageAlign(a[p]);c.push({src:h.src,width:h.width,height:h.height,...h.alt?{alt:h.alt}:{},...g?{align:g}:{}})}}return c}static headerFooterImageAlign(e){let r=e.parentElement;for(;r&&r.tagName!=="w:p";)r=r.parentElement;if(!r)return;const t=Array.from(r.children).find(n=>n.tagName==="w:pPr"),i=(t?Array.from(t.children).find(n=>n.tagName==="w:jc"):void 0)?.getAttribute("w:val");if(i==="center")return"center";if(i==="right"||i==="end")return"right"}static async parseHeaderFooterPart(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=[],n=Array.from(t.getElementsByTagName("w:p")).filter(a=>{let o=a.parentElement;for(;o;){if(o.tagName==="w:txbxContent")return!1;o=o.parentElement}return!0});for(let a=0;a<n.length;a++){const o=n[a],s=[];let l=null,c=!1;const p=m=>{const b={},v=this.getDirectChild(m,"w:rPr");v&&(this.applyRunPropertiesFromElement(b,v),(this.getDirectChild(v,"w:rStyle")?.getAttribute("w:val")||void 0)===this.CODE_INLINE_STYLE_ID&&(b.code=!0,/courier/i.test(b.fontFamily??"")&&delete b.fontFamily,/^(light)?gray$/i.test(b.backgroundColor??"")&&delete b.backgroundColor));let y=m.parentElement;for(;y&&y!==o;){if(y.tagName==="w:ins"||y.tagName==="w:del"){const O=y.tagName==="w:ins",W=this.parseTrackedRevisionMeta(y);Object.assign(b,{...O?{insertion:!0}:{deletion:!0},suggestionId:W.revisionId?`docxrev-${W.revisionId}`:this.generateId(),...this.revisionAuthorIdentity(W.author),suggestionLabel:O?"Insert":"Delete",...W.createdAt!==void 0?{suggestionCreatedAt:W.createdAt}:{},...W.author?{suggestionAuthorName:W.author}:{}});break}y=y.parentElement}let T=m.parentElement;for(;T&&T!==o;){if(T.tagName==="w:hyperlink"){const O=T.getAttribute("r:id"),W=T.getAttribute("w:anchor"),X=O?r?.get(O)?.target:void 0;X?b.link=X:W&&(b.link=`#${W}`);break}T=T.parentElement}return b},h=Array.from(o.getElementsByTagName("w:r")).filter(m=>{let b=m.parentElement;for(;b&&b!==o;){if(b.tagName==="w:p")return!1;b=b.parentElement}return b===o});for(let m=0;m<h.length;m++){const b=h[m],v=p(b);for(let y=0;y<b.children.length;y++){const T=b.children[y];if(T.tagName==="w:t"||T.tagName==="w:delText"){if(c)continue;const O=T.textContent??"";O&&s.push({type:"text",text:O,...Object.keys(v).length>0?{marks:v}:{}})}else if(T.tagName==="w:tab")s.push({type:"text",text:" "});else if(T.tagName==="w:br"&&!c&&(T.getAttribute("w:type")??"textWrapping")==="textWrapping")s.push({type:"text",text:`
|
|
3
|
+
`,...Object.keys(v).length>0?{marks:v}:{}});else if(T.tagName==="w:fldChar"){const O=T.getAttribute("w:fldCharType");O==="begin"&&(c=!0),O==="end"&&(l&&s.push({type:"text",text:"1",marks:{...v,field:l}}),l=null,c=!1)}else if(T.tagName==="w:instrText"&&c){const O=(T.textContent??"").trim().toUpperCase();O.startsWith("PAGE")?l="page":O.startsWith("NUMPAGES")&&(l="numPages")}}}const g=o.getElementsByTagName("w:fldSimple");for(let m=0;m<g.length;m++){const b=(g[m].getAttribute("w:instr")??"").trim().toUpperCase();b.startsWith("PAGE")?s.push({type:"text",text:"1",marks:{field:"page"}}):b.startsWith("NUMPAGES")&&s.push({type:"text",text:"1",marks:{field:"numPages"}})}const f=this.getDirectChild(this.getDirectChild(o,"w:pPr")??o,"w:jc")?.getAttribute("w:val"),w=f==="center"?"center":f==="right"||f==="end"?"right":f==="both"?"justify":void 0;s.length>0&&i.push({type:"paragraph",id:this.generateId(),children:s,...w?{align:w}:{}});const u=await this.parseTextBoxContent(o,void 0);i.push(...u.filter(m=>m.type==="paragraph"))}return i}static attachCommentsFromXml(e,r,t,i){const n=this.parseDocumentXml(r);if(!n)return;const a=new Set,o=u=>{if(!u||typeof u!="object")return;if(Array.isArray(u)){u.forEach(o);return}const m=u;m.marks?.comment&&m.marks.comment.split(",").forEach(b=>a.add(b)),o(m.children)};o(e.children);const s=(i??this.fallbackCommentState).collapsedCommentAnchorBlockById;s?.forEach((u,m)=>a.add(`docxcmt-${m}`));const l=new Map;if(t){const u=this.parseDocumentXml(t)?.getElementsByTagName("w15:commentEx")??[];for(let m=0;m<u.length;m++){const b=u[m],v=b.getAttribute("w15:paraId");v&&l.set(v,{done:b.getAttribute("w15:done")==="1",parentParaId:b.getAttribute("w15:paraIdParent")??void 0})}}const c=[],p=new Map,h=new Map,g=n.getElementsByTagName("w:comment");for(let u=0;u<g.length;u++){const m=g[u],b=m.getAttribute("w:id");if(!b)continue;const v=`docxcmt-${b}`,y=m.getElementsByTagName("w:p"),T=[];for(let D=0;D<y.length;D++){const M=y[D].getElementsByTagName("w:t");let L="";for(let B=0;B<M.length;B++)L+=M[B].textContent??"";T.push(L);const I=y[D].getAttribute("w14:paraId");I&&(p.set(v,I),h.set(I,v))}const O=m.getAttribute("w:date"),W=O?Date.parse(O):NaN,X=s?.get(b);c.push({id:v,author:m.getAttribute("w:author")??"Unknown",...m.getAttribute("w:initials")?{initials:m.getAttribute("w:initials")}:{},createdAt:Number.isFinite(W)?new Date(W).toISOString():new Date(0).toISOString(),bodyMd:T.filter(D=>D.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`),importedId:parseInt(b,10),...X?{anchorBlockId:X}:{}})}for(const u of c){const m=p.get(u.id),b=m?l.get(m):void 0;if(b?.done&&(u.resolved=!0),b?.parentParaId){const v=h.get(b.parentParaId);v&&(u.parentId=v)}}const f=u=>{let m=u;const b=new Map(c.map(v=>[v.id,v]));for(;m.parentId&&b.has(m.parentId);)m=b.get(m.parentId);return m.id},w=c.filter(u=>a.has(f(u)));w.length>0&&(e.comments=w)}static async collectNotesFromXml(e,r,t,i,n,a,o){const s=this.parseDocumentXml(r);if(!s)return;if(o){const p=t==="w:footnote"?"footnotes":"endnotes",h=await o.zip.file(`word/_rels/${p}.xml.rels`)?.async("string");if(h){const g=this.parseRelationshipsXml(h,`word/${p}.xml`);g.size>0&&(o={...o,relationships:new Map([...o.relationships,...g])})}}const l=Ee(e.pageLayout).indentStepPx,c=s.getElementsByTagName(t);for(let p=0;p<c.length;p++){const h=c[p],g=h.getAttribute("w:type");if(g==="separator"||g==="continuationSeparator")continue;const f=h.getAttribute("w:id");if(!f)continue;const w=await this.parseBodyChildren(h,l,o),u=this.applyParagraphMarkRevisions(w),m=u.length>0?u:[this.createEmptyParagraph()];Ri(m),a.set(`${i}-${f}`,{type:"footnote",id:`${i}-${f}`,...n==="endnote"?{noteKind:"endnote"}:{},children:m})}}static finalizeImportedFootnoteRefs(e,r){const t=[],i={footnote:0,endnote:0},n=new Map,a=(o,s)=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(p=>a(p));return}const l=o,c=l.marks?.footnoteRef;if(c&&(c.startsWith("docxfn-")||c.startsWith("docxen-"))){const p=r.get(c),h=l.marks?.suggestionId;if(p&&!p.structuralSuggestionId&&typeof h=="string"&&(l.marks?.insertion||l.marks?.deletion)&&(p.structuralSuggestionId=h,p.structuralSuggestionKind=l.marks?.deletion?"delete":"insert"),!r.has(c))l.text="",delete l.marks.footnoteRef,delete l.marks.superscript;else{if(!t.includes(c)){t.push(c);const g=c.startsWith("docxen-")?"endnote":"footnote";i[g]+=1,n.set(c,dn(i[g],g))}l.text=n.get(c)??""}}a(l.children)};a(e.children);for(const o of t){const s=r.get(o);s&&e.children.push(s)}}static documentHasMath(e){return e.includes("m:oMath")||e.includes("m:oMathPara")}static documentHasNativePageBreaks(e){return e.includes('w:br w:type="page"')||e.includes("<w:lastRenderedPageBreak")||e.includes("<w:pageBreakBefore")}static documentHasComplexBodyContent(e){return e.includes("<w:tbl")||e.includes("<w:drawing")||e.includes("<w:pict")||e.includes("<w:object")}static shouldUseStructuredDocxParser(e){return!!(this.documentHasMath(e)||this.documentHasNativePageBreaks(e)&&!this.documentHasComplexBodyContent(e))}static resolveIndentStepPx(e){return Ee(e?.pageLayout).indentStepPx}static stripXmlBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}static parseDocumentXml(e){const r=new DOMParser().parseFromString(this.stripXmlBom(e),"application/xml");return r.querySelector("parsererror")?null:r}static async loadOOXMLPackageContext(e,r){const[t,i,n,a]=await Promise.all([e.file("word/_rels/document.xml.rels")?.async("string"),e.file("word/styles.xml")?.async("string"),e.file("word/numbering.xml")?.async("string"),e.file("[Content_Types].xml")?.async("string")]),o=this.parseRelationshipsXml(t,"word/document.xml");return{zip:e,documentXml:r,relationships:o,styles:this.parseStylesXml(i),stylesXmlRaw:i||void 0,numbering:this.parseNumberingXml(n),contentTypes:this.parseContentTypesXml(a),themeFonts:await this.parseThemeFonts(e,o)}}static async parseThemeFonts(e,r){let t="word/theme/theme1.xml";for(const l of r.values())if(l.type.endsWith("/theme")&&l.targetMode!=="External"){t=l.target;break}const i=await e.file(t)?.async("string");if(!i)return;const n=this.parseDocumentXml(i);if(!n)return;const a=l=>n.getElementsByTagName(l)[0]?.getElementsByTagName("a:latin")[0]?.getAttribute("typeface")?.trim()||void 0,o=a("a:majorFont"),s=a("a:minorFont");if(!(!o&&!s))return{...o?{major:o}:{},...s?{minor:s}:{}}}static parseRelationshipsXml(e,r){const t=new Map;if(!e)return t;const i=this.parseDocumentXml(e);if(!i)return t;const n=i.getElementsByTagName("Relationship");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("Id"),l=o.getAttribute("Target"),c=o.getAttribute("Type");if(!s||!l||!c)continue;const p=o.getAttribute("TargetMode")||void 0;t.set(s,{id:s,type:c,target:p?.toLowerCase()==="external"?l:this.resolvePackageTargetPath(r,l),targetMode:p})}return t}static resolvePackageTargetPath(e,r){if(r.startsWith("/"))return r.replace(/^\/+/,"");const t=e.split("/");t.pop();const i=r.split("/");for(const n of i)if(!(!n||n===".")){if(n===".."){t.pop();continue}t.push(n)}return t.join("/")}static parseStylesXml(e){const r={stylesById:new Map,defaultStyleIdByType:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:docDefaults")[0];if(i){const a=i.getElementsByTagName("w:pPrDefault")[0],o=i.getElementsByTagName("w:rPrDefault")[0];r.paragraphDefault=a?this.getDirectChild(a,"w:pPr"):void 0,r.runDefault=o?this.getDirectChild(o,"w:rPr"):void 0}const n=t.getElementsByTagName("w:style");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("w:styleId");if(!s)continue;const l=this.getDirectChild(o,"w:name"),c=this.getDirectChild(o,"w:basedOn"),p=o.getAttribute("w:type")||"";r.stylesById.set(s,{id:s,type:p,basedOn:c?.getAttribute("w:val")||void 0,name:l?.getAttribute("w:val")||void 0,pPr:this.getDirectChild(o,"w:pPr"),rPr:this.getDirectChild(o,"w:rPr"),tblPr:this.getDirectChild(o,"w:tblPr")}),p&&this.isOnAttribute(o.getAttribute("w:default"))&&(r.defaultStyleIdByType.has(p)||r.defaultStyleIdByType.set(p,s))}return r}static parseFontTableXml(e){if(!e)return;const r=this.parseDocumentXml(e);if(!r)return;const t={},i=r.getElementsByTagName("w:font");for(let n=0;n<i.length;n++){const a=i[n],o=(a.getAttribute("w:name")||"").trim();if(!o)continue;const s=(this.getDirectChild(a,"w:altName")?.getAttribute("w:val")||"").trim(),l=(this.getDirectChild(a,"w:family")?.getAttribute("w:val")||"").trim().toLowerCase(),c=(this.getDirectChild(a,"w:pitch")?.getAttribute("w:val")||"").trim().toLowerCase(),p=(this.getDirectChild(a,"w:panose1")?.getAttribute("w:val")||"").trim(),h={};s&&(h.alt=s);const g=this.genericFamilyFromFontMetrics(l,c,p);g&&(h.generic=g),(h.alt||h.generic)&&(t[o.toLowerCase()]=h)}return Object.keys(t).length>0?t:void 0}static genericFamilyFromFontMetrics(e,r,t){if(r==="fixed"||e==="modern")return"monospace";if(/^[0-9a-fA-F]{20}$/.test(t)){const i=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16);if(i===2){if(n>=2&&n<=10)return"serif";if(n>=11&&n<=15)return"sans-serif"}}if(e==="roman")return"serif";if(e==="swiss")return"sans-serif"}static parseNumberingXml(e){const r={abstractNums:new Map,nums:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:abstractNum");for(let a=0;a<i.length;a++){const o=i[a],s=o.getAttribute("w:abstractNumId");if(!s)continue;const l=new Map,c=o.getElementsByTagName("w:lvl");for(let p=0;p<c.length;p++){const h=c[p],g=h.getAttribute("w:ilvl"),f=g?parseInt(g,10):NaN;if(!Number.isFinite(f))continue;const w=this.getDirectChild(h,"w:numFmt"),u=this.getDirectChild(h,"w:lvlText"),m=this.getDirectChild(h,"w:start")?.getAttribute("w:val");l.set(f,{level:f,format:w?.getAttribute("w:val")||void 0,text:u?.getAttribute("w:val")||void 0,start:m&&Number.isFinite(parseInt(m,10))?parseInt(m,10):void 0})}r.abstractNums.set(s,{abstractNumId:s,levels:l})}const n=t.getElementsByTagName("w:num");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("w:numId");if(!s)continue;const l=this.getDirectChild(o,"w:abstractNumId"),c=new Map,p=o.getElementsByTagName("w:lvlOverride");for(let h=0;h<p.length;h++){const g=p[h],f=g.getAttribute("w:ilvl"),w=f?parseInt(f,10):NaN;if(!Number.isFinite(w))continue;const u=g.getElementsByTagName("w:startOverride")[0]?.getAttribute("w:val");u&&Number.isFinite(parseInt(u,10))&&c.set(w,parseInt(u,10))}r.nums.set(s,{numId:s,abstractNumId:l?.getAttribute("w:val")||void 0,levelStartOverrides:c})}return r}static parseContentTypesXml(e){const r=new Map;if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("Default");for(let a=0;a<i.length;a++){const o=i[a],s=(o.getAttribute("Extension")||"").toLowerCase(),l=o.getAttribute("ContentType");s&&l&&r.set(s,l)}const n=t.getElementsByTagName("Override");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("PartName"),l=o.getAttribute("ContentType");s&&l&&r.set(s.replace(/^\/+/,""),l)}return r}static getDirectChild(e,r){for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName===r)return i}}static parseTwipsAttribute(e,r){if(!e)return;const t=e.getAttribute(r);if(!t)return;const i=Number.parseInt(t,10);return Number.isFinite(i)?i:void 0}static parseOnOffElement(e){if(!e)return;const r=(e.getAttribute("w:val")||e.getAttribute("val")||"").trim().toLowerCase();return r?!(r==="0"||r==="false"||r==="off"):!0}static pxToTwips(e){return Number.isFinite(e)?Math.round(e*this.TWIPS_PER_PX):0}static pxToDocxHalfPoints(e){return Number.isFinite(e)?Math.max(2,Math.round(e*this.DOCX_HALF_POINTS_PER_PX)):2}static twipsToPx(e){return Number.isFinite(e)?e/this.TWIPS_PER_PX:0}static inferPageSizePresetFromTwips(e,r){const t=e/this.TWIPS_PER_INCH,i=r/this.TWIPS_PER_INCH,n=Math.min(t,i),a=Math.max(t,i);let o="letter",s=Number.POSITIVE_INFINITY;for(const l of this.PAGE_SIZE_PRESETS){const c=Math.abs(n-l.width)+Math.abs(a-l.height);c<s&&(s=c,o=l.preset)}return o}static findAllSectionProperties(e){const r=[],t=i=>{for(const n of Array.from(i.children)){if(n.tagName==="w:sdt"){const a=this.getDirectChild(n,"w:sdtContent");a&&t(a);continue}if(n.tagName==="w:p"){const a=this.getDirectChild(n,"w:pPr"),o=a?this.getDirectChild(a,"w:sectPr"):void 0;o&&r.push(o)}n.tagName==="w:sectPr"&&r.push(n)}};return t(e),r}static findBodySectionProperties(e){const r=this.findAllSectionProperties(e);return r[r.length-1]}static parseSectionPropertiesElement(e){const r={},t=this.getDirectChild(e,"w:pgSz");if(t){const h=this.parseTwipsAttribute(t,"w:w"),g=this.parseTwipsAttribute(t,"w:h"),f=(t.getAttribute("w:orient")||"").trim().toLowerCase();h!==void 0&&h>0&&g!==void 0&&g>0?r.orientation=h>g?"landscape":"portrait":(f==="landscape"||f==="portrait")&&(r.orientation=f),h!==void 0&&h>0&&g!==void 0&&g>0&&(r.pageSize=this.inferPageSizePresetFromTwips(h,g))}const i=this.getDirectChild(e,"w:pgMar");if(i){const h=this.parseTwipsAttribute(i,"w:top"),g=this.parseTwipsAttribute(i,"w:right"),f=this.parseTwipsAttribute(i,"w:bottom"),w=this.parseTwipsAttribute(i,"w:left");h!==void 0&&(r.marginTopPx=this.twipsToPx(h)),g!==void 0&&(r.marginRightPx=this.twipsToPx(g)),f!==void 0&&(r.marginBottomPx=this.twipsToPx(f)),w!==void 0&&(r.marginLeftPx=this.twipsToPx(w))}const n=this.getDirectChild(e,"w:pgNumType"),a=(n?.getAttribute("w:start")||"").trim();if(a!==""){const h=parseInt(a,10);Number.isFinite(h)&&h>0&&(r.pageNumberStart=h)}const o=(n?.getAttribute("w:fmt")||"").trim();Li(o)&&(r.pageNumberFormat=o);const s=this.getDirectChild(e,"w:lnNumType");if(s){const h=(s.getAttribute("w:countBy")||"").trim(),g=(s.getAttribute("w:start")||"").trim(),f=(s.getAttribute("w:restart")||"").trim(),w=(s.getAttribute("w:distance")||"").trim(),u=h?parseInt(h,10):NaN,m=g?parseInt(g,10):NaN,b=w?parseInt(w,10):NaN;r.lineNumbering=Fi({countBy:Number.isFinite(u)&&u>=1?u:1,start:Number.isFinite(m)&&m>=1?m:1,restart:f==="newSection"||f==="continuous"?f:"newPage",...Number.isFinite(b)&&b>=0?{distancePx:b/15}:{}})}const l=this.getDirectChild(e,"w:cols");if(l){const h=(l.getAttribute("w:num")||"").trim(),g=h?parseInt(h,10):NaN;if(Number.isFinite(g)&&g>1){r.columnCount=g;const f=(l.getAttribute("w:space")||"").trim(),w=f?parseInt(f,10):NaN;Number.isFinite(w)&&w>=0&&(r.columnGapTwips=w)}}const c=Oi(this.getDirectChild(e,"w:pgBorders"));c&&(r.pageBorders=c);const p=at(e,Kr);return p&&(r.oxmlSectPr=p),Object.keys(r).length>0?r:void 0}static parseSectionStartType(e){const r=(this.getDirectChild(e,"w:type")?.getAttribute("w:val")||"").trim();if(r==="continuous")return"continuous";if(r==="evenPage")return"evenPage";if(r==="oddPage")return"oddPage";if(r==="nextPage")return"nextPage"}static parseDocumentPageLayout(e,r){const t=r??this.parseDocumentXml(e);if(!t)return;const i=t.getElementsByTagName("w:body")[0];if(!i)return;const n=this.findBodySectionProperties(i);if(!n)return;const a=this.parseSectionPropertiesElement(n);return a?.pageNumberStart!==void 0&&(a.pageNumberRestart=!0),a}static async parseDocumentPageLayoutFromPackage(e,r,t){const i=t??this.parseDocumentXml(e);if(!i)return;const n=this.parseDocumentPageLayout(e,i)??{},a=i.getElementsByTagName("w:body")[0];if(!a)return Object.keys(n).length>0?n:void 0;const o=this.findAllSectionProperties(a);if(o.length===0)return Object.keys(n).length>0?n:void 0;const s=this.resolveSectionHeaderFooterReferences(o)[o.length-1],l=await r.file("word/_rels/document.xml.rels")?.async("string");if(!l)return Object.keys(n).length>0?n:void 0;const c=this.parseDocumentXml(l);if(!c)return Object.keys(n).length>0?n:void 0;const p=new Map,h=c.getElementsByTagName("Relationship");for(let f=0;f<h.length;f++){const w=h[f],u=w.getAttribute("Id"),m=w.getAttribute("Target");u&&m&&p.set(u,m)}const g=async(f,w)=>{const u=s[f].default,m=u?p.get(u):void 0;if(!m)return;const b=m.startsWith("/")?m.slice(1):m.startsWith("word/")?m:`word/${m.replace(/^\.?\//,"")}`,v=await r.file(b)?.async("string");if(!v)return;const y=this.parsePageNumberInfoFromReferenceXml(v);y&&(n.showPageNumbers=!0,n.pageNumberPosition=`${w}-${y.horizontal}`)};return await g("header","top"),n.showPageNumbers||await g("footer","bottom"),Object.keys(n).length>0?n:void 0}static parsePageNumberInfoFromReferenceXml(e){const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("w:p");for(let i=0;i<t.length;i++){const n=t[i],a=n.getElementsByTagName("w:instrText");let o=!1;for(let l=0;l<a.length;l++)if((a[l].textContent||"").toUpperCase().includes("PAGE")){o=!0;break}if(!o){const l=n.getElementsByTagName("w:fldSimple");for(let c=0;c<l.length;c++)if((l[c].getAttribute("w:instr")||"").toUpperCase().includes("PAGE")){o=!0;break}}if(!o)continue;const s=this.getDirectChild(n,"w:pPr");return{horizontal:((s?this.getDirectChild(s,"w:jc"):void 0)?.getAttribute("w:val")||"").toLowerCase()==="left"?"left":"right"}}}static parseWordParagraphProperties(e,r){const t=this.getDirectChild(e,"w:pPr");if(!t)return{isList:!1};const i={isList:!!this.getDirectChild(t,"w:numPr")},n=this.parseOnOffElement(this.getDirectChild(t,"w:pageBreakBefore"));n!==void 0&&(i.pageBreakBefore=n),this.getDirectChild(t,"w:keepNext")&&(i.keepNext=this.isOn(t,"w:keepNext")),this.getDirectChild(t,"w:keepLines")&&(i.keepLines=this.isOn(t,"w:keepLines")),this.getDirectChild(t,"w:widowControl")&&(i.widowControl=this.isOn(t,"w:widowControl")),this.getDirectChild(t,"w:bidi")&&(i.direction=this.isOn(t,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(t,i),this.applyTabStopsFromPPr(i,t),this.applyJcFromPPr(i,t);const a=this.getDirectChild(t,"w:ind");if(a){const o=this.parseTwipsAttribute(a,"w:start")??this.parseTwipsAttribute(a,"w:left");if(o===0)i.leftIndent=0;else if(o!==void 0&&o>0){const c=Ft(this.twipsToPx(o),{indentStepPx:r,storedAsUnits:!1});c!==void 0&&(i.leftIndent=c)}const s=this.parseTwipsAttribute(a,"w:firstLine"),l=this.parseTwipsAttribute(a,"w:hanging");if(l!==void 0&&l>0)i.firstLineIndent=-1;else if(s===0)i.firstLineIndent=0;else if(s!==void 0&&s>0){const c=Ft(this.twipsToPx(s),{indentStepPx:r,storedAsUnits:!1,firstLine:!0});c!==void 0&&(i.firstLineIndent=c)}}return this.resolveLogicalAlignment(i),i}static applyJcFromPPr(e,r){const t=(this.getDirectChild(r,"w:jc")?.getAttribute("w:val")||"").toLowerCase();t==="center"?(e.align=t,delete e.jcLogical,delete e.jcPhysical):t==="left"||t==="right"?(e.jcPhysical=t,delete e.align,delete e.jcLogical):t==="both"||t==="justify"?(e.align="justify",delete e.jcLogical,delete e.jcPhysical):(t==="start"||t==="end")&&(e.jcLogical=t,delete e.align,delete e.jcPhysical)}static resolveLogicalAlignment(e){const r=e.direction==="rtl",t=e.jcPhysical;if(t){if(delete e.jcPhysical,delete e.jcLogical,!r){e.align=t;return}const a=t==="left"?"right":"left";a==="right"?delete e.align:e.align=a;return}const i=e.jcLogical;if(!i)return;delete e.jcLogical;const n=i==="start"?r?"right":"left":r?"left":"right";n===(r?"right":"left")?delete e.align:e.align=n}static extractTopLevelParagraphProperties(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=t.getElementsByTagName("w:body")[0];if(!i)return[];const n=[];for(let a=0;a<i.children.length;a++){const o=i.children[a];o.tagName==="w:p"&&n.push(this.parseWordParagraphProperties(o,r))}return n}static applyTopLevelParagraphProperties(e,r){const t=r.filter(n=>!n.isList);let i=0;for(const n of e.children){if(n.type!=="paragraph")continue;const a=t[i];if(!a)break;i+=1,a.align&&(n.align=a.align),a.leftIndent!==void 0&&(n.leftIndent=a.leftIndent),a.firstLineIndent!==void 0&&(n.firstLineIndent=a.firstLineIndent);const o=this.directionAttrFor(a.direction,this.paragraphNodeText(n));o&&(n.direction=o)}}static paragraphNodeText(e){let r="";for(const t of e.children)t.type==="text"&&(r+=t.text);return r}static directionAttrFor(e,r){if(e==="rtl")return"rtl";if(e==="ltr"&&Ot(r)==="rtl")return"ltr"}static async parseStructuredDocxDocument(e,r,t,i,n){t||(this.fallbackCommentState={});const a=i??this.parseDocumentXml(e);if(!a)return{type:"doc",children:[this.createEmptyParagraph()]};const o=a.getElementsByTagName("w:body")[0];if(!o)return{type:"doc",children:[this.createEmptyParagraph()]};const s=Ee(r).indentStepPx,l=[];this.importSdtWrappers=l;const c=[];this.importOxmlRanges=c,this.sdtAncestorStack=[];const p=t??this.fallbackCommentState;p.moveRangeByWrapper=e.includes("<w:moveFrom")||e.includes("<w:moveTo")?this.indexImportedMoveRanges(a):new WeakMap,p.collapsedCommentAnchorBlockById=new Map;let h;try{h=await this.parseBodyChildren(o,s,t,l,n)}finally{this.importSdtWrappers=void 0,this.importOxmlRanges=void 0,this.sdtAncestorStack=[],delete p.moveRangeByWrapper}this.finalizeImportedMovePairs(h),h=this.applyParagraphMarkMoves(h),this.applyTableMoves(h),h=this.applyParagraphMarkRevisions(h),h=this.collapseTocRegions(h);const g=this.findAllSectionProperties(o);if(g.length>1){let w=0;for(const u of h){if(u.type!=="section-break")continue;const m=g[w+1];if(m){const b=this.parseSectionStartType(m);b&&(u.breakType=b)}w++}}const f={type:"doc",children:h.length>0?h:[this.createEmptyParagraph()]};if(r){if(f.pageLayout=r,r.pageNumberFormat&&r.pageNumberFormat!=="decimal")for(const w of f.children)w.type==="section-break"&&w.layout?.pageNumberFormat===void 0&&(w.layout={...w.layout??{},pageNumberFormat:"decimal"});if((r.columnCount??1)>1)for(const w of f.children)w.type==="section-break"&&w.layout?.columnCount===void 0&&(w.layout={...w.layout??{},columnCount:1})}if(l.length>0&&(f.sdtWrappers=l),c.length>0&&(f.oxmlRanges=c),t?.stylesXmlRaw){f.stylesXml=t.stylesXmlRaw;const w=this.buildDocumentStylesheet(t,s);w&&(f.stylesheet=w)}return f}static resolveStylesheetFromStylesXml(e,r){const t=this.parseStylesXml(e);return this.buildDocumentStylesheet({styles:t,numbering:{abstractNums:new Map,nums:new Map}},Ee(r).indentStepPx)}static buildDocumentStylesheet(e,r){const t=e.styles;if(t.stylesById.size===0)return;const i=t.defaultStyleIdByType?.get("paragraph"),n=[];for(const a of t.stylesById.values()){if(a.type!=="paragraph")continue;const o={isList:!1},s=[];t.paragraphDefault&&s.push(t.paragraphDefault),s.push(...this.resolveStyleChainPPr(a.id,t,"paragraph"));const l=this.resolveRunMarks(void 0,a.id,e),c=typeof l.fontSize=="number"&&l.fontSize>0?l.fontSize:Ae.paragraph;for(const f of s)this.applyParagraphPropertiesFromElement(o,f,r,e,c);this.resolveLogicalAlignment(o);const p={};o.align&&(p.align=o.align),o.direction&&(p.direction=o.direction),o.leftIndent!==void 0&&(p.leftIndent=o.leftIndent),o.firstLineIndent!==void 0&&(p.firstLineIndent=o.firstLineIndent),o.lineSpacing!==void 0&&(p.lineSpacing=o.lineSpacing),this.applyDocxParagraphSpacing(p,o),o.keepNext!==void 0&&(p.keepNext=o.keepNext),o.keepLines!==void 0&&(p.keepLines=o.keepLines),o.widowControl!==void 0&&(p.widowControl=o.widowControl),o.bordersJson&&(p.borders=o.bordersJson),o.shading&&(p.shading=o.shading),o.tabStops&&o.tabStops.length>0&&(p.tabStops=JSON.stringify(o.tabStops));const h={styleId:a.id};a.name&&(h.name=a.name);const g=this.headingLevelForStyle(a)||o.heading;g&&(h.headingLevel=g),a.id===i&&(h.default=!0),Object.keys(p).length>0&&(h.paragraphAttrs=p),Object.keys(l).length>0&&(h.runMarks=l),n.push(h)}return n.length>0?{paragraphStyles:n}:void 0}static tocInstrOfBlock(e){if(e.type!=="paragraph")return;const r=e.children.filter(i=>i.type==="text"&&((i.text??"")!==""||i.marks?.fieldInstr));if(r.length===0)return;const t=r[0].marks?.fieldInstr;if(!(!t||!/^TOC\b/i.test(t.trim())))return r.every(i=>i.marks?.fieldInstr===t)?t:void 0}static tocTypographyOfRegion(e,r){const t=e.flatMap(l=>l.children.filter(c=>c.type==="text"&&(c.text??"").trim()!=="")),i=l=>{if(t.length===0)return;const c=l(t[0]);if(c!==void 0)return t.every(p=>l(p)===c)?c:void 0},n={},a=i(l=>l.marks?.fontFamily);a&&a!==r&&(n.fontFamily=a);const o=i(l=>l.marks?.fontSize);$i(o)&&(n.fontSize=o);const s=i(l=>$r(l.marks?.color));return s&&(n.color=s),n}static collapseTocRegions(e){const r=[];let t,i,n=[],a={},o,s=!1;const l=()=>{if(t){s||(o=this.inferDocumentFontFamily({type:"doc",children:e.filter(p=>!this.tocInstrOfBlock(p))}),s=!0);const c={type:"toc",...a,...this.tocTypographyOfRegion(n,o),id:i||this.generateId(),instr:t,levels:pn(t),..._r(t)?{source:"captions",captionLabel:_r(t)}:{}};r.push(c)}t=void 0,i=void 0,n=[],a={}};for(const c of e){const p=this.tocInstrOfBlock(c);if(p&&p===t){c.type==="paragraph"&&n.push(c);continue}if(t&&l(),p){t=p,i=c.id,c.type==="paragraph"&&(n.push(c),c.direction&&(a.direction=c.direction,a.align=c.direction==="rtl"?"right":"left"),c.align&&(a.align=c.align));continue}r.push(c)}return l(),r}static parseParagraphMarkRevision(e){const r=this.getDirectChild(e,"w:pPr"),t=r?this.getDirectChild(r,"w:rPr"):void 0;if(!t)return null;const i=this.getDirectChild(t,"w:ins");if(i)return{kind:"split",meta:this.parseTrackedRevisionMeta(i)};const n=this.getDirectChild(t,"w:del");return n?{kind:"merge",meta:this.parseTrackedRevisionMeta(n)}:null}static parseParagraphMarkMove(e,r){const t=this.getDirectChild(e,"w:pPr"),i=t?this.getDirectChild(t,"w:rPr"):void 0;if(!i)return null;const n=this.getDirectChild(i,"w:moveFrom")??this.getDirectChild(i,"w:moveTo");if(!n)return null;const a=(r??this.fallbackCommentState).moveRangeByWrapper?.get(n);return{role:n.tagName==="w:moveFrom"?"from":"to",meta:this.parseTrackedRevisionMeta(n),...a?{move:a}:{}}}static markWholeBlockMove(e,r){if(!e||typeof e!="object")return;if(Array.isArray(e)){e.forEach(i=>this.markWholeBlockMove(i,r));return}const t=e;if(t.marks?.suggestionId===r&&t.marks.docxMove)try{t.marks.docxMove=JSON.stringify({...JSON.parse(t.marks.docxMove),wholeBlocks:!0})}catch{}this.markWholeBlockMove(t.children,r)}static applyParagraphMarkMoves(e){const r=new Set,t=s=>{if(!s||typeof s!="object")return;if(Array.isArray(s)){s.forEach(t);return}const l=s;l.marks?.docxMove&&l.marks.suggestionId&&r.add(l.marks.suggestionId),t(l.children)};t(e);const i=(s,l)=>{if(!s?.move)return;const c=`docxmove-${encodeURIComponent(s.move.name)}`;return r.has(c)&&l.every(p=>p.type!=="text"||!p.text||p.marks?.suggestionId===c&&this.parseDocxMoveMark(p.marks.docxMove)?.role===s.role)?c:void 0},n=s=>{if(!(!s||typeof s!="object")){if(Array.isArray(s)){s.forEach(n);return}delete s.__pilcrowMove,n(s.children)}},a=(s,l,c)=>{s.structuralSuggestionId=c,s.structuralSuggestionKind=l.role==="from"?"delete":"insert",s.structuralSuggestionLabel="Move",this.markWholeBlockMove(s,c),delete s.structuralSuggestionRole,delete s.structuralSuggestionRecord},o=[];for(const s of e){if(s.type==="paragraph"){const l=s.__pilcrowMove;delete s.__pilcrowMove;const c=i(l,s.children);l&&c?a(s,l,c):l&&!s.structuralSuggestionKind&&(s.__pilcrowRevision={kind:l.role==="from"?"merge":"split",meta:l.meta}),n(s.children),o.push(s);continue}if(s.type==="list"&&s.children.length>0){const l=[];for(const p of s.children){const h=p.__pilcrowMove,g=i(h,p.children),f=h&&g?{marker:h,moveId:g}:void 0,w=f?`${f.moveId}\0${f.marker.role}`:"",u=l[l.length-1];u&&u.key===w?u.items.push(p):l.push({key:w,move:f,items:[p]})}const c={...s};l.forEach((p,h)=>{const g=h===0?s:{...c,id:this.generateId()};h>0&&s.numberingChainId&&delete g.startNumber,g.children=p.items,p.move&&a(g,p.move.marker,p.move.moveId);for(const f of p.items)delete f.__pilcrowMove;n(g.children),o.push(g)});continue}n(s),o.push(s)}return o}static applyTableMoves(e){for(const r of e){if(r.type!=="table"||r.children.length===0)continue;const t=r.children[0].diffState,i=r.children[0].suggestionId;if(t!=="insert"&&t!=="delete"||!i||!r.children.every(h=>h.diffState===t&&h.suggestionId===i))continue;const n=t==="delete"?"from":"to",a=new Set;let o=!0;const s=h=>{if(!o||!h||typeof h!="object")return;if(Array.isArray(h)){h.forEach(s);return}const g=h;g.type==="table-cell"&&g.diffState&&(o=!1),g.type==="text"&&g.text&&(this.parseDocxMoveMark(g.marks?.docxMove)?.role===n&&g.marks?.suggestionId&&(n==="from"?g.marks.deletion:g.marks.insertion)?a.add(g.marks.suggestionId):o=!1),s(g.children)};if(s(r.children),!o||a.size!==1)continue;let l=[];try{const h=JSON.parse(r.structuralSuggestionRecords??"[]");Array.isArray(h)&&(l=h)}catch{continue}const c=l.find(h=>h?.id===i);if(c?.type!=="table-change"||c.tableRevision.operations.length!==r.children.length||!c.tableRevision.operations.every(h=>h.kind==="row"&&h.action===t))continue;const p=l.filter(h=>h!==c);p.length>0?r.structuralSuggestionRecords=JSON.stringify(p):delete r.structuralSuggestionRecords;for(const h of r.children)delete h.diffState,delete h.suggestionId;r.diffState=t,r.suggestionId=[...a][0],this.markWholeBlockMove(r,r.suggestionId)}}static applyParagraphMarkRevisions(e){const r=(a,o)=>{if(a.type!=="paragraph")return!1;const s=o==="insertion"?"deletion":"insertion";return a.children.every(l=>{const c=l.marks;return!!c?.[o]&&!c?.[s]})},t=a=>a.__pilcrowRevision?.kind;for(let a=0;a<e.length;a++){const o=t(e[a]);if(!o||e[a].type!=="paragraph")continue;const s=o==="split"?"insertion":"deletion";if(r(e[a],s))continue;let l=a+1;for(;l<e.length&&r(e[l],s)&&t(e[l])===o;)l+=1;l<e.length&&r(e[l],s)&&!t(e[l])&&(e[l].__pilcrowRevision=e[a].__pilcrowRevision,delete e[a].__pilcrowRevision)}const i=[];let n=0;for(;n<e.length;){const a=e[n];if(a.type!=="paragraph"||!a.__pilcrowRevision){i.push(a),n+=1;continue}let o=n;for(;o<e.length&&e[o].type==="paragraph"&&e[o].__pilcrowRevision;)o+=1;const s=e.slice(n,o),l=o<e.length&&e[o].type==="paragraph"?e[o]:void 0,c=s.map(p=>p.__pilcrowRevision);s.forEach(p=>delete p.__pilcrowRevision),s.every((p,h)=>r(p,c[h].kind==="split"?"insertion":"deletion"))?(s.forEach((p,h)=>this.markWholeParagraphRevision(p,c[h])),i.push(...s),n=o):s.length===1&&!l?(i.push(s[0]),n=o):s.length===1&&l&&!s[0].structuralSuggestionId&&!l.structuralSuggestionId?(this.linkParagraphMarkRevision(s[0],l,c[0]),i.push(s[0],l),n=o+1):(i.push(...this.replaceParagraphMarkRun(l?[...s,l]:s,c)),n=l?o+1:o)}return i}static markWholeParagraphRevision(e,r){const t=r.kind==="split"?"insert":"delete";e.children=this.unwrapWholeBlockRunMarks(e.children,r);const i=r.meta.revisionId?`docxrev-${r.meta.revisionId}`:this.generateId(),n=this.revisionAuthorIdentity(r.meta.author),a={id:i,blockId:e.id,source:n.suggestionSource,authorType:n.suggestionAuthorType,label:t==="insert"?"Insert":"Delete",...r.meta.createdAt!==void 0?{createdAt:r.meta.createdAt}:{},...r.meta.author?{agentName:r.meta.author}:{}},o=t==="insert"?{...a,type:"block-insert"}:{...a,type:"block-delete",beforeBlock:{...e}};e.structuralSuggestionId=i,e.structuralSuggestionKind=t,e.structuralSuggestionRecord=JSON.stringify(o)}static unwrapWholeBlockRunMarks(e,r){const t=r.kind==="split"?"insertion":"deletion",i=n=>!!n[t]&&(r.meta.author===void 0||n.suggestionAuthorName===r.meta.author)&&(r.meta.createdAt===void 0||n.suggestionCreatedAt===r.meta.createdAt);return e.map(n=>{const a=n.marks;if(!a||!i(a))return n;const o=Object.fromEntries(Object.entries(a).filter(([s])=>s!=="insertion"&&s!=="deletion"&&s!=="formatChange"&&s!=="layeredInsertion"&&!s.startsWith("suggestion")));if(t==="deletion"&&typeof a.layeredInsertion=="string")try{const s=JSON.parse(a.layeredInsertion);Object.assign(o,{insertion:!0,...s.id?{suggestionId:s.id}:{},...s.source?{suggestionSource:s.source}:{},...s.authorType?{suggestionAuthorType:s.authorType}:{},...s.createdAt!==void 0?{suggestionCreatedAt:s.createdAt}:{},suggestionLabel:s.label??"Insert",...s.authorName?{suggestionAuthorName:s.authorName}:{}})}catch{}return{...n,marks:o}})}static markListItemPropertyChange(e,r){const t=r,i=t.__propertyChange;if(delete t.__propertyChange,!i||r.structuralSuggestionId)return;const n=i.priorProps,a=r,o=e,s={type:"list-item",id:r.id,children:[]},l={type:"list-item",id:r.id,children:[]};let c=!1;for(const g of this.LIST_ITEM_PROPERTY_FIELDS){const f=a[g]??o[g],w=n[g]??o[g];f!==void 0&&(l[g]=f),w!==void 0&&(s[g]=w),JSON.stringify(f)!==JSON.stringify(w)&&(c=!0)}if(i.priorLevel!==void 0){const g=r.indentLevel??0;l.indentLevel=g,s.indentLevel=i.priorLevel,g!==i.priorLevel&&(c=!0)}if(!c)return;const p=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),h=this.revisionAuthorIdentity(i.meta.author);r.structuralSuggestionId=p,r.structuralSuggestionKind="change",r.structuralSuggestionLabel="Format",r.structuralSuggestionRecord=JSON.stringify({id:p,type:"block-change",blockId:e.id,beforeBlock:{...e,children:[]},listItemSuggestion:{kind:"change",beforeItem:s,afterItem:l},label:"Format",source:h.suggestionSource,authorType:h.suggestionAuthorType,...i.meta.createdAt!==void 0?{createdAt:i.meta.createdAt}:{},...i.meta.author?{agentName:i.meta.author}:{}})}static markWholeListItemRevision(e,r){const t=r,i=t.__pilcrowRevision;if(delete t.__pilcrowRevision,!i)return;const n=i.kind==="split"?"insertion":"deletion",a=n==="insertion"?"deletion":"insertion";if(!r.children.every(h=>{const g=h.marks;return!!g?.[n]&&!g?.[a]}))return;r.children=this.unwrapWholeBlockRunMarks(r.children,i);const o=i.kind==="split"?"insert":"delete",s=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),l=this.revisionAuthorIdentity(i.meta.author),c=JSON.parse(JSON.stringify(r)),p=o==="insert"?"Insert":"Delete";r.structuralSuggestionId=s,r.structuralSuggestionKind=o,r.structuralSuggestionLabel=p,r.structuralSuggestionRecord=JSON.stringify({id:s,type:"block-change",blockId:e.id,beforeBlock:{...e,children:[]},listItemSuggestion:o==="insert"?{kind:o,afterItem:c}:{kind:o,beforeItem:c},label:p,source:l.suggestionSource,authorType:l.suggestionAuthorType,...i.meta.createdAt!==void 0?{createdAt:i.meta.createdAt}:{},...i.meta.author?{agentName:i.meta.author}:{}})}static linkParagraphMarkRevision(e,r,t){const i=t.meta.revisionId?`docxrev-${t.meta.revisionId}`:this.generateId(),n=t.kind==="split"?"Split":"Merge",a=this.revisionAuthorIdentity(t.meta.author),o={id:i,source:a.suggestionSource,authorType:a.suggestionAuthorType,label:n,...t.meta.createdAt!==void 0?{createdAt:t.meta.createdAt}:{},...t.meta.author?{agentName:t.meta.author}:{}},s=t.kind==="split"?{...o,type:"paragraph-split",blockId:e.id,insertedBlockId:r.id,beforeBlock:{...this.paragraphPropertiesOf(r),type:"paragraph",id:e.id,children:[...e.children,...r.children]}}:{...o,type:"paragraph-merge",firstBlockId:e.id,secondBlockId:r.id};e.structuralSuggestionId=i,e.structuralSuggestionKind=t.kind,e.structuralSuggestionRole="before",e.structuralSuggestionLabel=n,e.structuralSuggestionRecord=JSON.stringify(s),r.structuralSuggestionId=i,r.structuralSuggestionKind=t.kind,r.structuralSuggestionRole="after",r.structuralSuggestionLabel=n}static paragraphPropertiesOf(e){const{id:r,type:t,children:i,structuralSuggestionId:n,structuralSuggestionKind:a,structuralSuggestionRole:o,structuralSuggestionLabel:s,structuralSuggestionRecord:l,...c}=e;return delete c.__pilcrowRevision,c}static replaceParagraphMarkRun(e,r){const t=r[0].meta,i=c=>c==="insertion"||c==="deletion"||c==="formatChange"||c==="layeredInsertion"||c==="docxMove"||c.startsWith("suggestion"),n=c=>Object.fromEntries(Object.entries(c).filter(([p])=>!i(p))),a=(c,p)=>c.children.filter(h=>{const g=h.marks;return p==="before"?!g?.insertion:!g?.deletion}).map(h=>{const g=h.marks;if(!g)return h;if(p==="before"&&g.formatChange){let f={};try{f=JSON.parse(g.suggestionPriorAttributes??"{}")}catch{f={}}return{...h,marks:n(f)}}return{...h,marks:n(g)}}),o=c=>{const p=c==="before"?"split":"merge",h=[[]];return e.forEach((g,f)=>{h[h.length-1].push(g),(f>=r.length||r[f].kind!==p)&&h.push([])}),h.filter(g=>g.length>0)},s=this.revisionAuthorIdentity(t.author),l=(c,p)=>{const h=c[c.length-1],g=h.structuralSuggestionRecord?JSON.parse(h.structuralSuggestionRecord):void 0,f=p==="before"&&g?.type==="block-change"&&g.beforeBlock?g.beforeBlock:h,w={...this.paragraphPropertiesOf(f),type:"paragraph",id:p==="after"?c[0].id:this.generateId(),children:c.flatMap(v=>a(v,p))},u=p==="after"?"insert":"delete",m=this.generateId(),b={id:m,blockId:w.id,source:s.suggestionSource,authorType:s.suggestionAuthorType,label:u==="insert"?"Insert":"Delete",...t.createdAt!==void 0?{createdAt:t.createdAt}:{},...t.author?{agentName:t.author}:{}};return{...w,structuralSuggestionId:m,structuralSuggestionKind:u,structuralSuggestionRecord:JSON.stringify(u==="insert"?{...b,type:"block-insert"}:{...b,type:"block-delete",beforeBlock:w})}};return[...o("before").map(c=>l(c,"before")),...o("after").map(c=>l(c,"after"))]}static parseParagraphPropertyChange(e,r,t){const i=this.getDirectChild(e,"w:pPr"),n=i?this.getDirectChild(i,"w:pPrChange"):void 0;if(!n)return null;const a=this.parseTrackedRevisionMeta(n),o=this.getDirectChild(n,"w:pPr"),s={isList:!1};if(t){const p=o&&this.getDirectChild(o,"w:pStyle")?.getAttribute("w:val")||void 0;s.styleId=p;const h=[];t.styles.paragraphDefault&&h.push(t.styles.paragraphDefault),h.push(...this.resolveStyleChainPPr(p,t.styles,"paragraph")),o&&h.push(o);for(const g of h)this.applyParagraphPropertiesFromElement(s,g,r,t)}else o&&this.applyParagraphPropertiesFromElement(s,o,r);this.resolveLogicalAlignment(s);const l=o?this.getDirectChild(this.getDirectChild(o,"w:numPr")??o,"w:ilvl")?.getAttribute("w:val"):void 0,c=o&&this.getDirectChild(o,"w:numPr")&&l?parseInt(l,10):void 0;return{meta:a,priorProps:s,...c!==void 0&&Number.isFinite(c)?{priorLevel:c}:{}}}static applyParsedPropertiesToParagraphNode(e,r){delete e.align,delete e.leftIndent,delete e.firstLineIndent,delete e.heading,delete e.lineSpacing,delete e.keepNext,delete e.keepLines,delete e.widowControl,delete e.borders,delete e.shading,delete e.styleId,delete e.direction,r.align&&(e.align=r.align);const t=this.directionAttrFor(r.direction,this.paragraphNodeText(e));t&&(e.direction=t),r.leftIndent!==void 0&&(e.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(e.firstLineIndent=r.firstLineIndent),r.heading&&(e.heading=r.heading),r.lineSpacing!==void 0&&(e.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(e,r),r.keepNext&&(e.keepNext=!0),r.keepLines&&(e.keepLines=!0),r.widowControl===!1&&(e.widowControl=!1),r.bordersJson&&(e.borders=r.bordersJson),r.shading&&(e.shading=r.shading);const i=r.styleId;i&&i.toLowerCase()!=="normal"&&(e.styleId=i)}static applyDocxParagraphSpacing(e,r){r.contextualSpacing&&(e.contextualSpacing=!0),e.spaceBefore=r.spaceBefore??0,e.spaceAfter=r.spaceAfter??0}static async parseWordParagraphBlocks(e,r,t){const i=[];for(let m=0;m+1<e.children.length;m++){const b=e.children[m],v=e.children[m+1],y=b.getAttribute("w:id");b.tagName==="w:commentRangeStart"&&v.tagName==="w:commentRangeEnd"&&y&&v.getAttribute("w:id")===y&&i.push(y)}const n=this.resolveParagraphProperties(e,r,t),a=this.parseParagraphMarkRevision(e),o=a?null:this.parseParagraphMarkMove(e,t),s=[];let l=!1,c="";const p=[];n.pageBreakBefore&&p.push(this.createPageBreakBlock());for(let m=0;m<e.children.length;m++){const b=e.children[m],v=b.tagName;if(!this.trackCommentRangeMarker(b,t)&&!(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t))){if(v==="w:fldSimple"){s.push(...await this.parseFldSimpleItems(b,n,t));continue}if(v==="mc:AlternateContent"){const y=this.selectAlternateContentBranch(b);y&&s.push(...await this.parseInlineItemsFromChildren(y,n,t));continue}if(v==="w:r")s.push(...this.stampOpenComments(await this.parseWordRunItems(b,n,t),t));else if(v==="w:sdt")s.push(...await this.parseInlineSdtItems(b,n,t));else if(v==="w:ins"||v==="w:del"||v==="w:moveFrom"||v==="w:moveTo")s.push(...await this.parseTrackedChangeItems(b,n,t));else if(v==="w:hyperlink")s.push(...await this.parseHyperlinkItems(b,n,t));else if(v==="m:oMathPara"){const y=this.ommlToLatex(b);y&&(s.some(T=>T.kind==="text"&&T.node.text.trim()!=="")?s.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}}):(l=!0,c=y))}else if(v==="m:oMath"){const y=this.ommlToLatex(b);y&&s.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}})}}}const h=s.filter(m=>m.kind==="text");if(l&&h.every(m=>m.node.text.trim()===""))return p.push({type:"math",id:this.generateId(),content:c,displayMode:"block",align:n.align==="left"||n.align==="right"||n.align==="center"?n.align:"center"}),p;const g=p.concat(this.buildBlocksFromParagraphItems(s,n));if(t){const m=g.find(v=>v.type==="paragraph"),b=m?.children[0];if(m&&m.children.length===1&&b?.type==="text"&&b.text===""&&b.marks?.fontSize===void 0){const v=this.getDirectChild(e,"w:pPr"),y=this.resolveRunMarks(v?this.getDirectChild(v,"w:rPr"):void 0,n.styleId,t),T={};typeof y.fontSize=="number"&&y.fontSize>0&&(T.fontSize=y.fontSize),y.fontFamily&&!b.marks?.fontFamily&&(T.fontFamily=y.fontFamily),Object.keys(T).length>0&&(b.marks={...b.marks,...T})}}const f=this.getDirectChild(e,"w:pPr"),w=sr(e),u=at(f,jr);if(w||u){const m=g.find(b=>b.type==="paragraph");m&&(w&&(m.oxmlAttrs=w),u&&(m.oxmlPPr=u))}if(i.length>0){const m=g.find(b=>b.type==="paragraph");if(m?.id){const b=t??this.fallbackCommentState,v=b.collapsedCommentAnchorBlockById??(b.collapsedCommentAnchorBlockById=new Map);for(const y of i)v.set(y,m.id)}}if(n.list&&!a){const m=this.parseParagraphPropertyChange(e,r,t);if(m){for(let b=g.length-1;b>=0;b--)if(g[b].type==="paragraph"){g[b].__propertyChange=m;break}}}if(!n.list&&!a){const m=this.parseParagraphPropertyChange(e,r,t);if(m)for(let b=g.length-1;b>=0;b--){const v=g[b];if(v.type!=="paragraph")continue;const y=m.meta.revisionId?`docxrev-${m.meta.revisionId}`:this.generateId(),T=this.revisionAuthorIdentity(m.meta.author),O=JSON.parse(JSON.stringify(v)),W=JSON.parse(JSON.stringify(v));this.applyParsedPropertiesToParagraphNode(W,m.priorProps),v.structuralSuggestionId=y,v.structuralSuggestionKind="change",v.structuralSuggestionLabel="Paragraph format",v.structuralSuggestionRecord=JSON.stringify({id:y,type:"block-change",blockId:v.id,source:T.suggestionSource,authorType:T.suggestionAuthorType,label:"Paragraph format",...m.meta.createdAt!==void 0?{createdAt:m.meta.createdAt}:{},...m.meta.author?{agentName:m.meta.author}:{},beforeBlock:W,acceptedBlock:O});break}}if(a){for(let m=g.length-1;m>=0;m--)if(g[m].type==="paragraph"){g[m].__pilcrowRevision=a;break}}if(o){for(let m=g.length-1;m>=0;m--)if(g[m].type==="paragraph"){g[m].__pilcrowMove=o;break}}return g}static async parseBodyChildren(e,r,t,i,n){const a=[];let o;const s=new Map,l=m=>m.abstractNumId??m.numId,c=m=>{const b=l(m);let v=s.get(b);return v||(v={chainId:this.generateId(),seenNumIds:new Set,started:!1},s.set(b,v)),v},p=m=>{const b=c(m),v=m.hasLevel0StartOverride&&!b.seenNumIds.has(m.numId);if(!b.started||v)return m.startNumber},h=()=>{o&&o.list.children.length>0&&a.push(o.list),o=void 0},g=Array.from(e.children),f=[];let w;const u=(m,b)=>{if(n){for(const v of f)nr(n,m,v);f.length=0,nr(n,m,b),w=m}};for(let m=0;m<g.length;m++){const b=g[m],v=b.tagName==="w:bookmarkStart"||this.OXML_RANGE_PAIRS.has(b.tagName)?"start":b.tagName==="w:bookmarkEnd"||[...this.OXML_RANGE_PAIRS.values()].includes(b.tagName)?"end":null;if(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t)){n&&v==="end"&&w?nr(n,w,m):n&&v!==null&&f.push(m);continue}const y=i&&b.tagName==="w:sdt"?this.getDirectChild(b,"w:sdtPr"):void 0;let T=-1,O,W;y&&(h(),T=a.length,O=this.generateId(),W=this.sdtAncestorStack[this.sdtAncestorStack.length-1]?.id,this.sdtAncestorStack.push({el:b,id:O}));let X;try{X=await this.parseBodyChild(b,r,t)}finally{y&&this.sdtAncestorStack.pop()}for(const D of X){if(D.kind==="list-item"){if(!o||o.numId!==D.list.numId||o.variant!==D.list.variant){h();const M=D.list.variant==="ordered",L=M?c(D.list):null;o={numId:D.list.numId,variant:D.list.variant,list:{type:"list",id:this.generateId(),variant:D.list.variant,children:[],startNumber:M?p(D.list):void 0,lineSpacing:D.list.lineSpacing,...M&&D.list.formatSpec?{numberingFormat:D.list.formatSpec}:{}}},L&&(o.list.numberingChainId=L.chainId,L.started=!0,L.seenNumIds.add(D.list.numId))}o.list.lineSpacing===void 0&&D.list.lineSpacing!==void 0&&(o.list.lineSpacing=D.list.lineSpacing),o.list.spaceBefore===void 0&&this.applyDocxParagraphSpacing(o.list,D.list);for(const M of["lineSpacing","spaceBefore","spaceAfter"])(D.item[M]===void 0||D.item[M]===o.list[M])&&delete D.item[M];this.markWholeListItemRevision(o.list,D.item),this.markListItemPropertyChange(o.list,D.item),o.list.children.push(D.item),u(o.list,m);continue}h(),a.push(D.block),u(D.block,m)}if(y&&T>=0){h();const D=a.slice(T).map(M=>M.id).filter(M=>!!M);if(D.length>0&&i)try{const M=new XMLSerializer().serializeToString(y);i.push({id:O??this.generateId(),prXml:M,...W?{parentId:W}:{},blockIds:D})}catch{}}}return h(),a}static async parseBodyChild(e,r,t){if(e.tagName==="w:sdt"){const i=this.getDirectChild(e,"w:sdtContent");if(!i)return[];const n=this.sdtAncestorStack,a=n.length>0&&n[n.length-1].el===e;let o;if(!a&&n.length>0&&this.importSdtWrappers){const l=this.getDirectChild(e,"w:sdtPr");if(l)try{o={id:this.generateId(),prXml:new XMLSerializer().serializeToString(l),parentId:n[n.length-1].id}}catch{}}o&&n.push({el:e,id:o.id});const s=[];try{for(let l=0;l<i.children.length;l++)s.push(...await this.parseBodyChild(i.children[l],r,t))}finally{o&&n.pop()}if(o&&this.importSdtWrappers){const l=s.filter(c=>c.kind==="block").map(c=>c.block.id).filter(c=>!!c);l.length>0&&(o.blockIds=l,this.importSdtWrappers.push(o))}return s}if(e.tagName==="w:p"){const i=await this.parseWordParagraphBlocks(e,r,t),n=this.getDirectChild(e,"w:pPr"),a=n?this.getDirectChild(n,"w:sectPr"):void 0;if(a){const s={...this.parseSectionPropertiesElement(a),...this.getDirectChild(a,"w:pgBorders")?{}:{pageBorders:null}},l=i.find(g=>g.type==="paragraph"&&g.__pilcrowRevision),c=l?.__pilcrowRevision?.kind==="merge"?l.__pilcrowRevision:void 0;c&&l&&delete l.__pilcrowRevision;const p={kind:"block",block:{type:"section-break",id:this.generateId(),...s?{layout:s}:{},...c?{diffState:"delete",suggestionId:c.meta.revisionId?`docxrev-${c.meta.revisionId}`:this.generateId(),...c.meta.author?{suggestionAuthorName:c.meta.author}:{},...c.meta.createdAt!==void 0?{suggestionCreatedAt:c.meta.createdAt}:{}}:{}}};if(i.length===1&&i[0].type==="paragraph"&&!i[0].__pilcrowRevision&&i[0].children.every(g=>g.type==="text"&&g.text.length===0))return[p];const h=[];for(const g of i)h.push({kind:"block",block:g});return h.push(p),h}const o=[];for(const s of i){if(s.type!=="paragraph"){o.push({kind:"block",block:s});continue}const l=this.codeBlockFromStyledParagraph(s);if(l){o.push({kind:"block",block:l});continue}const c=this.resolveParagraphProperties(e,r,t);if(!c.list){const p=this.todoItemFromParagraph(s,c);if(p){o.push(p);continue}o.push({kind:"block",block:s});continue}o.push({kind:"list-item",list:c.list,item:this.carryPilcrowMove(s,{type:"list-item",id:this.generateId(),children:s.children,lineSpacing:c.lineSpacing,spaceBefore:c.spaceBefore,spaceAfter:c.spaceAfter,indentLevel:c.list.level,...s.heading?{heading:s.heading}:{}})})}return o}if(e.tagName==="w:tbl"){const i=await this.parseTableBlock(e,r,t);return i?[{kind:"block",block:i}]:[]}if(e.tagName==="w:customXml"){const i=[];for(let n=0;n<e.children.length;n++)i.push(...await this.parseBodyChild(e.children[n],r,t));return i}if(!Zr.has(e.tagName))try{return[{kind:"block",block:{type:"docx-raw",id:this.generateId(),origin:"body",...lr(e)}}]}catch{}return[]}static codeBlockFromStyledParagraph(e){const r=e.styleId;if(!r||!r.startsWith(this.CODE_BLOCK_STYLE_ID))return;const t=r.slice(this.CODE_BLOCK_STYLE_ID.length);if(t.length>0&&!t.startsWith("_"))return;const i=t.startsWith("_")?t.slice(1):void 0,n=e.children.filter(a=>a.type==="text").map(a=>a.text).join("");return{type:"code",id:e.id??this.generateId(),content:n,...i?{language:i}:{}}}static todoItemFromParagraph(e,r){if(e.styleId||r.heading)return;const t=e.children[0];if(!t||t.type!=="text")return;const i=this.TODO_MARKERS.find(([s])=>t.text.startsWith(s));if(!i)return;const n=t.text.slice(i[0].length),a=[...n.length>0?[{...t,text:n}]:[],...e.children.slice(1)].filter(s=>s.type==="text");a.length===0&&a.push({type:"text",text:""});const o=Math.max(0,Math.round(Number(e.leftIndent??0)>0?Number(e.leftIndent)-1:0));return{kind:"list-item",list:{numId:"revise-todo",level:o,variant:"todo",lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,contextualSpacing:r.contextualSpacing},item:this.carryPilcrowMove(e,{type:"list-item",id:this.generateId(),children:a,lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,indentLevel:o,...i[1]?{checked:!0}:{}})}}static carryPilcrowMove(e,r){const t=e.__pilcrowMove;t&&(r.__pilcrowMove=t);const i=e.__pilcrowRevision;i&&(r.__pilcrowRevision=i);const n=e.__propertyChange;return n&&(r.__propertyChange=n),r}static buildBlocksFromParagraphItems(e,r){const t=[];let i=[];const n=(a=!1)=>{if(i.length===0&&!a)return;const o={type:"paragraph",id:this.generateId(),children:i.length>0?i:[{type:"text",text:"",marks:{}}]};r.align&&(o.align=r.align),r.leftIndent!==void 0&&(o.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(o.firstLineIndent=r.firstLineIndent),r.heading&&(o.heading=r.heading),r.lineSpacing!==void 0&&(o.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(o,r),r.keepNext&&(o.keepNext=!0),r.keepLines&&(o.keepLines=!0),r.widowControl===!1&&(o.widowControl=!1),r.bordersJson&&(o.borders=r.bordersJson),r.shading&&(o.shading=r.shading);const s=r.styleId;s&&s.toLowerCase()!=="normal"&&(o.styleId=s),r.tabStops&&r.tabStops.length&&(o.tabStops=JSON.stringify(r.tabStops));const l=this.directionAttrFor(r.direction,this.paragraphNodeText(o));l&&(o.direction=l),t.push(o),i=[]};for(const a of e){if(a.kind==="text"){i.push(a.node);continue}if(a.kind==="pagebreak"){n(),t.push(this.createPageBreakBlock());continue}if(a.kind==="blocks"){n(),t.push(...a.blocks);continue}n(),t.push(a.node)}return t.length===0&&i.length===0?n(!0):n(),t}static resolveParagraphProperties(e,r,t){if(!t)return this.parseWordParagraphProperties(e,r);const i=this.getDirectChild(e,"w:pPr"),n=this.getDirectChild(i||e,"w:pStyle")?.getAttribute("w:val")||void 0,a={isList:!1,styleId:n},o=this.effectiveParagraphStyleId(n,t.styles),s=[];t.styles.paragraphDefault&&s.push(t.styles.paragraphDefault),s.push(...this.resolveStyleChainPPr(o,t.styles,"paragraph")),i&&s.push(i);const l=this.resolveParagraphFontSizePx(i,o,t);for(const c of s)this.applyParagraphPropertiesFromElement(a,c,r,t,l);return this.resolveLogicalAlignment(a),a}static lineSpacingFromDocxSpacing(e,r,t){const i=(r||"auto").trim().toLowerCase();if(i!=="exact"&&i!=="atleast")return Math.round(e/240*100)/100;const n=t&&t>0?t:Ae.paragraph,a=e/20*(4/3),o=Math.round(a/n*100)/100;return i==="atleast"?o>_i.paragraph?o:void 0:Math.max(.1,o)}static effectiveParagraphStyleId(e,r){return e??r.defaultStyleIdByType?.get("paragraph")}static resolveParagraphFontSizePx(e,r,t){const i=e?this.getDirectChild(e,"w:rPr"):void 0,n=this.resolveRunMarks(i,r,t);return typeof n.fontSize=="number"&&n.fontSize>0?n.fontSize:Ae.paragraph}static resolveStyleChainPPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.pPr).filter(Boolean):[]}static resolveStyleChainRPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.rPr).filter(Boolean):[]}static resolveStyleChain(e,r,t){const i=[],n=new Set;let a=r.stylesById.get(e);for(;a&&!n.has(a.id);)n.add(a.id),(!t||a.type===t)&&i.unshift(a),a=a.basedOn?r.stylesById.get(a.basedOn):void 0;return i}static applyParagraphPropertiesFromElement(e,r,t,i,n){if(!r)return;this.getDirectChild(r,"w:keepNext")&&(e.keepNext=this.isOn(r,"w:keepNext")),this.getDirectChild(r,"w:keepLines")&&(e.keepLines=this.isOn(r,"w:keepLines")),this.getDirectChild(r,"w:widowControl")&&(e.widowControl=this.isOn(r,"w:widowControl")),this.getDirectChild(r,"w:bidi")&&(e.direction=this.isOn(r,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(r,e),this.applyTabStopsFromPPr(e,r),this.applyJcFromPPr(e,r);const a=this.getDirectChild(r,"w:ind");if(a){const m=this.parseTwipsAttribute(a,"w:start")??this.parseTwipsAttribute(a,"w:left");if(m===0)e.leftIndent=0;else if(m!==void 0&&m>0){const y=Ft(this.twipsToPx(m),{indentStepPx:t,storedAsUnits:!1});y!==void 0&&(e.leftIndent=y)}const b=this.parseTwipsAttribute(a,"w:firstLine"),v=this.parseTwipsAttribute(a,"w:hanging");if(v!==void 0&&v>0)e.firstLineIndent=-1;else if(b===0)e.firstLineIndent=0;else if(b!==void 0&&b>0){const y=Ft(this.twipsToPx(b),{indentStepPx:t,storedAsUnits:!1,firstLine:!0});y!==void 0&&(e.firstLineIndent=y)}}const o=this.parseOnOffElement(this.getDirectChild(r,"w:pageBreakBefore"));o!==void 0&&(e.pageBreakBefore=o);const s=this.getDirectChild(r,"w:spacing"),l=s?.getAttribute("w:line");if(l){const m=parseInt(l,10);if(Number.isFinite(m)&&m>0){const b=this.lineSpacingFromDocxSpacing(m,s?.getAttribute("w:lineRule"),n);b!==void 0&&(e.lineSpacing=b)}}const c=m=>Math.max(0,Math.round(this.twipsToPx(m)*100)/100),p=this.parseTwipsAttribute(s,"w:before");p!==void 0&&(e.spaceBefore=c(p));const h=this.parseTwipsAttribute(s,"w:after");h!==void 0&&(e.spaceAfter=c(h)),this.getDirectChild(r,"w:contextualSpacing")&&(e.contextualSpacing=this.isOn(r,"w:contextualSpacing"));const g=this.getDirectChild(r,"w:outlineLvl")?.getAttribute("w:val"),f=g?parseInt(g,10):NaN;Number.isFinite(f)&&f>=0&&f<6&&(e.heading=f+1);const w=this.getDirectChild(r,"w:pStyle")?.getAttribute("w:val");if(w){e.styleId=w;const m=i?this.headingLevelForStyle(i.styles.stylesById.get(w)):this.headingLevelForStyle({id:w});m&&(e.heading=m)}const u=i?this.getDirectChild(r,"w:numPr"):void 0;if(u&&i){const m=this.getDirectChild(u,"w:ilvl"),b=this.getDirectChild(u,"w:numId")?.getAttribute("w:val"),v=m?.getAttribute("w:val"),y=v&&Number.isFinite(parseInt(v,10))?parseInt(v,10):0;if(b==="0")delete e.list,e.isList=!1;else if(b){const T=this.resolveListInfo(b,y,i.numbering);T&&(e.list={...T,lineSpacing:e.lineSpacing,spaceBefore:e.spaceBefore,spaceAfter:e.spaceAfter,contextualSpacing:e.contextualSpacing},e.isList=!0)}}}static headingLevelForStyle(e){if(!e)return;const r=[e.id,e.name].filter(Boolean).map(t=>t.toLowerCase().replace(/[\s_-]+/g,""));for(const t of r){const i=t.match(/heading([1-6])$/);if(i)return parseInt(i[1],10)}}static resolveListInfo(e,r,t){const i=t.nums.get(e),n=i?.abstractNumId?t.abstractNums.get(i.abstractNumId):void 0,a=n?.levels.get(r);if(!a)return;const o=(a.format||"").toLowerCase()==="bullet"?"unordered":"ordered",s=i?.levelStartOverrides.get(r)??a.start;let l;if(o==="ordered"&&n){const c=[];let p=!1;for(let h=0;h<=2;h++){const g=n.levels.get(h);(g?.format||g?.text)&&(p=!0),c.push({...g?.format?{numFmt:g.format}:{},...g?.text?{lvlText:g.text}:{}})}p&&(l=JSON.stringify(c))}return{numId:e,level:r,variant:o,startNumber:s,abstractNumId:i?.abstractNumId,hasLevel0StartOverride:i?.levelStartOverrides.has(0)??!1,formatSpec:l}}static async parseHyperlinkItems(e,r,t){const i=e.getAttribute("r:id"),n=e.getAttribute("w:anchor"),a=(i?t?.relationships.get(i)?.target:void 0)||(n?`#${n}`:void 0),o=[];for(let s=0;s<e.children.length;s++){const l=e.children[s];if(!(this.trackBookmarkMarker(l,t)||this.trackOxmlRangeMarker(l,t))){if(l.tagName==="w:ins"||l.tagName==="w:del"){const c=await this.parseTrackedChangeItems(l,r,t),p=h=>{const g={...h,link:h?.link??a};if(g.suggestionPriorAttributes)try{const f=JSON.parse(g.suggestionPriorAttributes);f&&typeof f=="object"&&!f.link&&(g.suggestionPriorAttributes=JSON.stringify({...f,link:a}))}catch{}return g};o.push(...c.map(h=>h.kind==="text"&&a?{...h,node:{...h.node,marks:p(h.node.marks)}}:h));continue}l.tagName==="w:r"&&o.push(...await this.parseWordRunItems(l,r,t,a))}}return o}static revisionAuthorIdentity(e){return e?.trim()===Ct?{suggestionSource:"agent",suggestionAuthorType:"ai"}:{suggestionSource:"manual",suggestionAuthorType:"human"}}static indexImportedMoveRanges(e){const r=new WeakMap,t={from:[],to:[]},i=(a,o)=>{const s=a?.getAttribute("w:name")?.trim(),l=a?.getAttribute("w:id")?.trim();if(!a||!s||!l)return;const c=a.getAttribute("w:date"),p=c?Date.parse(c):NaN;return{version:1,name:s,role:o,rangeId:l,...a.getAttribute("w:author")?.trim()?{rangeAuthor:a.getAttribute("w:author").trim()}:{},...Number.isFinite(p)?{rangeCreatedAt:p}:{}}},n=Array.from(e.getElementsByTagName("*"));for(let a=0;a<n.length;a++){const o=n[a],s=o.tagName==="w:moveFromRangeStart"?"from":o.tagName==="w:moveToRangeStart"?"to":void 0;if(s){const p=i(o,s);p&&t[s].push(p);continue}const l=o.tagName==="w:moveFrom"?"from":o.tagName==="w:moveTo"?"to":void 0;if(l){let p=t[l][t[l].length-1];const h=o.parentElement,g=h?.parentElement;!p&&h?.tagName==="w:rPr"&&g?.tagName==="w:pPr"&&g.parentElement?.tagName==="w:p"&&(p=i(g.parentElement.getElementsByTagName(l==="from"?"w:moveFromRangeStart":"w:moveToRangeStart")[0],l));const f=o.getAttribute("w:id")?.trim();p&&f&&r.set(o,{...p,wrapperId:f,fallbackSuggestionId:`docxrev-${f}`});continue}const c=o.tagName==="w:moveFromRangeEnd"?"from":o.tagName==="w:moveToRangeEnd"?"to":void 0;if(c){const p=o.getAttribute("w:id")?.trim(),h=t[c],g=p?h.map(f=>f.rangeId).lastIndexOf(p):h.length-1;g>=0&&h.splice(g,1)}}return r}static parseDocxMoveMark(e){if(!(typeof e!="string"||!e))try{const r=JSON.parse(e);return r.version!==1||typeof r.name!="string"||!r.name||r.role!=="from"&&r.role!=="to"||typeof r.rangeId!="string"||!r.rangeId||typeof r.wrapperId!="string"||!r.wrapperId||typeof r.fallbackSuggestionId!="string"||!r.fallbackSuggestionId?void 0:r}catch{return}}static finalizeImportedMovePairs(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(t);return}const n=i;if(n.type==="text"&&n.marks?.docxMove){const a=this.parseDocxMoveMark(n.marks.docxMove);if(a){const o=r.get(a.name)??{roles:new Set,nodes:[]};o.roles.add(a.role),o.nodes.push(n),r.set(a.name,o)}}t(n.children)};t(e);for(const i of r.values())if(!(i.roles.has("from")&&i.roles.has("to")))for(const n of i.nodes){const a=this.parseDocxMoveMark(n.marks?.docxMove);!a||!n.marks||(n.marks.suggestionId=a.fallbackSuggestionId,delete n.marks.docxMove)}}static hasDocxMoveMarks(e){if(!e||typeof e!="object")return!1;if(Array.isArray(e))return e.some(t=>this.hasDocxMoveMarks(t));const r=e;return!!r.marks?.docxMove||this.hasDocxMoveMarks(r.children)}static applyTabStopsFromPPr(e,r){const t=this.getDirectChild(r,"w:tabs");if(!t)return;const i=e.tabStops?[...e.tabStops]:[];for(let n=0;n<t.children.length;n++){const a=t.children[n];if(a.tagName!=="w:tab")continue;const o=parseFloat(a.getAttribute("w:pos")||"");if(!Number.isFinite(o)||o<0)continue;const s=this.twipsToPx(o),l=i.findIndex(f=>Math.abs(f.pos-s)<.5);l>=0&&i.splice(l,1);const c=(a.getAttribute("w:val")||"left").toLowerCase();if(c==="clear")continue;let p;if(c==="right"||c==="end")p="right";else if(c==="center")p="center";else if(c==="decimal")p="decimal";else if(c==="left"||c==="start"||c==="num")p="left";else continue;const h={pos:s,align:p},g=(a.getAttribute("w:leader")||"").toLowerCase();g==="dot"||g==="middledot"?h.leader="dot":g==="hyphen"?h.leader="hyphen":(g==="underscore"||g==="heavy")&&(h.leader="underscore"),i.push(h)}i.sort((n,a)=>n.pos-a.pos),i.length>0?e.tabStops=i:delete e.tabStops}static parseParagraphDecoration(e,r){const t=this.getDirectChild(e,"w:pBdr");if(t){let n={};if(r.bordersJson)try{n=JSON.parse(r.bordersJson)}catch{n={}}for(const a of["top","bottom","left","right"]){const o=this.getDirectChild(t,`w:${a}`);if(!o)continue;const s=(o.getAttribute("w:val")||"single").toLowerCase();if(s==="none"||s==="nil"){n[a]={style:"none",width:0,color:"#000000"};continue}const l=["dashed","dotted","double"].includes(s)?s:"single",c=parseInt(o.getAttribute("w:sz")||"4",10),p=Math.max(.5,Math.round((Number.isFinite(c)?c:4)/6*100)/100),h=(o.getAttribute("w:color")||"auto").trim(),g=h.toLowerCase()==="auto"?"#000000":`#${h.replace(/^#/,"")}`;n[a]={style:l,width:p,color:g}}Object.keys(n).length>0&&(r.bordersJson=JSON.stringify(n))}const i=this.getDirectChild(e,"w:shd");if(i){const n=(i.getAttribute("w:fill")||"").trim(),a=(i.getAttribute("w:val")||"clear").toLowerCase();n&&n.toLowerCase()!=="auto"?r.shading=`#${n.replace(/^#/,"")}`:(!n||n.toLowerCase()==="auto"||a==="nil"||a==="none")&&(r.shading="transparent")}}static trackBookmarkMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:bookmarkStart"){const i=e.getAttribute("w:id"),n=e.getAttribute("w:name");return i&&n&&n!=="_GoBack"&&((t.openBookmarkNames??(t.openBookmarkNames=new Set)).add(n),(t.bookmarkNameById??(t.bookmarkNameById=new Map)).set(i,n)),!0}if(e.tagName==="w:bookmarkEnd"){const i=e.getAttribute("w:id"),n=i?t.bookmarkNameById?.get(i):void 0;return n&&t.openBookmarkNames?.delete(n),!0}return!1}static trackOxmlRangeMarker(e,r){const t=r??this.fallbackCommentState;if(this.OXML_RANGE_PAIRS.has(e.tagName)){const i=e.getAttribute("w:id");if(i)try{const n={id:this.generateId(),tagName:e.tagName,startXml:new XMLSerializer().serializeToString(e),endXml:""};(t.openOxmlRanges??(t.openOxmlRanges=new Map)).set(i,n)}catch{}return!0}for(const[i,n]of this.OXML_RANGE_PAIRS){if(e.tagName!==n)continue;const a=e.getAttribute("w:id"),o=a?t.openOxmlRanges?.get(a):void 0;if(o&&a){try{o.endXml=new XMLSerializer().serializeToString(e),this.importOxmlRanges?.push(o)}catch{}t.openOxmlRanges.delete(a)}return!0}return!1}static async parseFldSimpleItems(e,r,t){const i=(e.getAttribute("w:instr")||"").trim(),n=await this.parseInlineItemsFromChildren(e,r,t);if(!i)return n;for(const a of n)a.kind==="text"&&a.node&&(a.node.marks={...a.node.marks??{},fieldInstr:i});return n}static trackCommentRangeMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:commentRangeStart"){const i=e.getAttribute("w:id");return i&&(t.openCommentIds??(t.openCommentIds=new Set)).add(i),!0}if(e.tagName==="w:commentRangeEnd"){const i=e.getAttribute("w:id");return i&&t.openCommentIds?.delete(i),!0}return!1}static stampOpenComments(e,r){const t=(r??this.fallbackCommentState).openCommentIds;if(!t||t.size===0)return e;const i=[...t].sort().map(n=>`docxcmt-${n}`).join(",");for(const n of e)n.kind==="text"&&n.node&&(n.node.marks={...n.node.marks??{},comment:i});return e}static async parseInlineSdtItems(e,r,t){const i=this.getDirectChild(e,"w:sdtContent");if(!i)return[];const n=this.importSdtWrappers;let a;if(n){const s=this.getDirectChild(e,"w:sdtPr");if(s)try{const l=this.sdtAncestorStack[this.sdtAncestorStack.length-1];a={id:this.generateId(),prXml:new XMLSerializer().serializeToString(s),scope:"inline",...l?{parentId:l.id}:{}}}catch{}}a&&this.sdtAncestorStack.push({el:e,id:a.id});let o;try{o=await this.parseInlineItemsFromChildren(i,r,t)}finally{a&&this.sdtAncestorStack.pop()}if(a&&n){let s=!1;for(const l of o)if(l.kind==="text"&&l.node){const c=l.node.marks?.sdtInline;l.node.marks={...l.node.marks??{},sdtInline:c?`${c},${a.id}`:a.id},s=!0}s&&n.push(a)}return o}static async parseInlineItemsFromChildren(e,r,t){const i=[];for(let n=0;n<e.children.length;n++){const a=e.children[n];if(!this.trackCommentRangeMarker(a,t)&&!(this.trackBookmarkMarker(a,t)||this.trackOxmlRangeMarker(a,t))){if(a.tagName==="w:fldSimple"){i.push(...await this.parseFldSimpleItems(a,r,t));continue}if(a.tagName==="mc:AlternateContent"){const o=this.selectAlternateContentBranch(a);o&&i.push(...await this.parseInlineItemsFromChildren(o,r,t));continue}a.tagName==="w:r"?i.push(...this.stampOpenComments(await this.parseWordRunItems(a,r,t),t)):a.tagName==="w:hyperlink"?i.push(...await this.parseHyperlinkItems(a,r,t)):a.tagName==="w:ins"||a.tagName==="w:del"||a.tagName==="w:moveFrom"||a.tagName==="w:moveTo"?i.push(...await this.parseTrackedChangeItems(a,r,t)):a.tagName==="w:sdt"&&i.push(...await this.parseInlineSdtItems(a,r,t))}}return i}static parseTrackedRevisionMeta(e){const r=e.getAttribute("w:id"),t=e.getAttribute("w:author")?.trim()||void 0,i=e.getAttribute("w:date"),n=i?Date.parse(i):NaN;return{revisionId:r&&r.length>0?r:null,author:t,createdAt:Number.isFinite(n)?n:void 0}}static async parseTrackedChangeItems(e,r,t,i){const n=e.tagName==="w:ins"||e.tagName==="w:moveTo",a=e.tagName==="w:moveFrom"||e.tagName==="w:moveTo",o=this.parseTrackedRevisionMeta(e),s=a?(t??this.fallbackCommentState).moveRangeByWrapper?.get(e):void 0,l=s?`docxmove-${encodeURIComponent(s.name)}`:o.revisionId?`docxrev-${o.revisionId}`:this.generateId(),c={...n?{insertion:!0}:{deletion:!0},suggestionId:l,...this.revisionAuthorIdentity(o.author),suggestionLabel:a?"Move":n?"Insert":"Delete",...o.createdAt!==void 0?{suggestionCreatedAt:o.createdAt}:{},...o.author?{suggestionAuthorName:o.author}:{},...s?{docxMove:JSON.stringify(s)}:{},...!n&&i?{layeredInsertion:JSON.stringify(i)}:{}},p=g=>g.map(f=>f.kind==="text"?{...f,node:{...f.node,marks:{...f.node.marks??{},...c}}}:f),h=[];for(let g=0;g<e.children.length;g++){const f=e.children[g];this.trackCommentRangeMarker(f,t)||this.trackBookmarkMarker(f,t)||this.trackOxmlRangeMarker(f,t)||(f.tagName==="w:r"?h.push(...p(this.stampOpenComments(await this.parseWordRunItems(f,r,t),t))):f.tagName==="w:hyperlink"?h.push(...p(this.stampOpenComments(await this.parseHyperlinkItems(f,r,t),t))):f.tagName==="w:del"&&n?h.push(...await this.parseTrackedChangeItems(f,r,t,{id:l,...(()=>{const w=this.revisionAuthorIdentity(o.author);return{source:w.suggestionSource,authorType:w.suggestionAuthorType}})(),createdAt:o.createdAt,label:"Insert",authorName:o.author})):(f.tagName==="w:ins"||f.tagName==="w:del")&&h.push(...await this.parseTrackedChangeItems(f,r,t)))}return h}static async parseWordRunItems(e,r,t,i,n){const a=this.getDirectChild(e,"w:rPr"),o=n?{...n}:this.resolveRunMarks(a,r.styleId,t,i);if(!n&&!r.heading&&o.fontSize===Ae.paragraph&&this.docDefaultRunSizePx(t)===Ae.paragraph&&delete o.fontSize,!n){const g=at(a,Hr);g&&(o.oxmlRPr=g)}const s=!n&&a?this.getDirectChild(a,"w:rPrChange"):void 0;if(s){const g=this.parseTrackedRevisionMeta(s),f=this.getDirectChild(s,"w:rPr"),w=this.resolveRunMarks(f,r.styleId,t,i);Object.assign(o,{formatChange:!0,suggestionId:g.revisionId?`docxrev-${g.revisionId}`:this.generateId(),...this.revisionAuthorIdentity(g.author),suggestionLabel:"Format",...g.createdAt!==void 0?{suggestionCreatedAt:g.createdAt}:{},...g.author?{suggestionAuthorName:g.author}:{},suggestionPriorAttributes:JSON.stringify(w??{})})}const l=[];let c="";const p=t??this.fallbackCommentState,h=()=>{if(!c)return;const g={...o},f=p.openBookmarkNames;f&&f.size>0&&(g.bookmark=[...f].sort().join(","));const w=p.openOxmlRanges;w&&w.size>0&&(g.oxmlRange=[...w.values()].map(m=>m.id).sort().join(","));const u=p.fieldInstrStack?.[0];u?.inResult&&u.instr.trim()&&(g.fieldInstr=u.instr.trim()),l.push({kind:"text",node:{type:"text",text:c,marks:Object.keys(g).length>0?g:void 0}}),c=""};for(let g=0;g<e.children.length;g++){const f=e.children[g];if(f.tagName==="w:t"){c+=f.textContent||"";continue}if(f.tagName==="w:fldChar"){const w=f.getAttribute("w:fldCharType"),u=p.fieldInstrStack??(p.fieldInstrStack=[]);h(),w==="begin"?u.push({instr:"",inResult:!1}):w==="separate"?u.length>0&&(u[u.length-1].inResult=!0):w==="end"&&u.pop();continue}if(f.tagName==="w:instrText"){const w=p.fieldInstrStack;w&&w.length>0&&(w[w.length-1].instr+=f.textContent||"");continue}if(f.tagName==="w:footnoteReference"||f.tagName==="w:endnoteReference"){const w=f.getAttribute("w:id");if(w){h();const u=f.tagName==="w:endnoteReference"?"docxen":"docxfn";l.push({kind:"text",node:{type:"text",text:"0",marks:{...o,footnoteRef:`${u}-${w}`,superscript:!0}}})}continue}if(f.tagName==="w:delText"){c+=f.textContent||"";continue}if(f.tagName==="w:tab"){c+=" ";continue}if(f.tagName==="w:br"){(f.getAttribute("w:type")||"").trim().toLowerCase()==="page"?(h(),l.push({kind:"pagebreak"})):c+=`
|
|
6
|
+
`;continue}if(f.tagName!=="w:lastRenderedPageBreak"){if(f.tagName==="mc:AlternateContent"){h();const w=this.selectAlternateContentBranch(f);w&&l.push(...await this.parseWordRunItems(w,r,t,i,o));continue}if(f.tagName==="w:drawing"){h();const w=await this.parseImageFromDrawing(f,r.align,t);w&&l.push({kind:"image",node:w});const u=await this.parseTextBoxContent(f,t);if(u.length>0&&l.push({kind:"blocks",blocks:u}),!w&&u.length===0){const m=this.rawChipFromRunChild(f);m&&l.push({kind:"blocks",blocks:[m]})}continue}if(f.tagName==="w:pict"||f.tagName==="w:object"){h();const w=f.getElementsByTagName("*");let u=!1;for(let b=0;b<w.length;b++){const v=(w[b].getAttribute("o:hr")||"").toLowerCase();if(v==="t"||v==="true"||v==="1"){u=!0;break}}if(u){const b={type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}],borders:Wi()};l.push({kind:"blocks",blocks:[b]});continue}const m=await this.parseTextBoxContent(f,t);if(m.length>0)l.push({kind:"blocks",blocks:m});else{const b=this.rawChipFromRunChild(f);b&&l.push({kind:"blocks",blocks:[b]})}continue}}}return h(),l}static rawChipFromRunChild(e){try{return{type:"docx-raw",id:this.generateId(),origin:"run",...lr(e)}}catch{return}}static async parseTextBoxContent(e,r){const t=e.getElementsByTagName("w:txbxContent");if(t.length===0)return[];const i=Ee(void 0).indentStepPx,n=[];for(let a=0;a<t.length;a++){const o=t[a];let s=o.parentElement,l=!1;for(;s&&s!==e;){if(s.tagName==="mc:Fallback"){const p=s.parentElement,h=p?Array.from(p.children).find(g=>g.tagName==="mc:Choice"):void 0;l=!!(h&&h.getElementsByTagName("w:txbxContent").length>0);break}s=s.parentElement}if(l)continue;const c=(await this.parseBodyChildren(o,i,r)).filter(p=>p.type!=="paragraph"||p.children.some(h=>h.type==="text"&&h.text.trim()!==""));n.push(...c)}return n}static selectAlternateContentBranch(e){let r;for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName==="mc:Fallback"){r=i;continue}if(i.tagName==="mc:Choice"&&(i.getElementsByTagName("w:t").length>0||i.getElementsByTagName("w:delText").length>0||i.getElementsByTagName("w:txbxContent").length>0||i.getElementsByTagName("a:blip").length>0))return i}return r}static resolveRunMarks(e,r,t,i){const n={};if(t){const a=[];t.styles.runDefault&&a.push(t.styles.runDefault),a.push(...this.resolveStyleChainRPr(this.effectiveParagraphStyleId(r,t.styles),t.styles,"paragraph"));const o=e&&this.getDirectChild(e,"w:rStyle")?.getAttribute("w:val")||void 0;a.push(...this.resolveStyleChainRPr(o,t.styles,"character")),e&&a.push(e);for(const s of a)this.applyRunPropertiesFromElement(n,s,t.themeFonts);o===this.CODE_INLINE_STYLE_ID&&(n.code=!0,/courier/i.test(n.fontFamily??"")&&delete n.fontFamily,/^(light)?gray$/i.test(n.backgroundColor??"")&&delete n.backgroundColor)}else e&&this.applyRunPropertiesFromElement(n,e);return i&&(n.link=i),n}static applyRunPropertiesFromElement(e,r,t){if(!r)return;const i=(y,T)=>{this.getDirectChild(r,y)&&(e[T]=this.isOn(r,y))},n=()=>new Set(e.docxRunPropertyResets?.split(",").map(y=>y.trim()).filter(Boolean)??[]),a=(y,T)=>{const O=n();T?O.add(y):O.delete(y),O.size>0?e.docxRunPropertyResets=[...O].sort().join(","):delete e.docxRunPropertyResets};i("w:b","bold"),i("w:i","italic");const o=this.getDirectChild(r,"w:u");if(o){const y=(o.getAttribute("w:val")||"").toLowerCase();e.underline=!["none","0","false","off"].includes(y)}i("w:strike","strikethrough"),i("w:dstrike","doubleStrikethrough"),i("w:smallCaps","smallCaps"),i("w:caps","allCaps"),i("w:vanish","hidden");const s=this.getDirectChild(r,"w:lang")?.getAttribute("w:val");s&&(e.lang=s);const l=(this.getDirectChild(r,"w:spacing")?.getAttribute("w:val")||"").trim();if(l!==""){const y=parseInt(l,10);Number.isFinite(y)&&(e.letterSpacing=Math.round(y/15*100)/100)}const c=(this.getDirectChild(r,"w:vertAlign")?.getAttribute("w:val")||"").toLowerCase();c==="superscript"?(e.superscript=!0,e.subscript=!1):c==="subscript"?(e.superscript=!1,e.subscript=!0):c==="baseline"&&(e.superscript=!1,e.subscript=!1);const p=this.getDirectChild(r,"w:color"),h=p?.getAttribute("w:val");p&&h?.toLowerCase()==="auto"?(delete e.color,a("color",!0)):h&&(e.color=`#${h.replace(/^#/,"")}`,a("color",!1));const g=this.getDirectChild(r,"w:highlight")?.getAttribute("w:val");g?.toLowerCase()==="none"?(delete e.backgroundColor,a("highlight",!0)):g&&(e.backgroundColor=this.highlightValueToColor(g),a("highlight",!1));const f=this.getDirectChild(r,"w:shd")?.getAttribute("w:fill");if(f&&["auto","none"].includes(f.toLowerCase()))delete e.backgroundColor,a("highlight",!0);else if(f){const y=tr(f);y&&(e.backgroundColor=y,a("highlight",!1))}const w=this.getDirectChild(r,"w:rFonts"),u=w?.getAttribute("w:asciiTheme")||w?.getAttribute("w:hAnsiTheme")||w?.getAttribute("w:cstheme")||w?.getAttribute("w:eastAsiaTheme"),m=u&&t?u.toLowerCase().startsWith("major")?t.major:t.minor:void 0,b=w?.getAttribute("w:ascii")||w?.getAttribute("w:hAnsi")||w?.getAttribute("w:cs")||w?.getAttribute("w:eastAsia")||m;b&&(e.fontFamily=b);const v=this.getDirectChild(r,"w:sz")?.getAttribute("w:val");if(v){const y=parseInt(v,10);Number.isFinite(y)&&y>0&&(e.fontSize=Math.max(1,Math.round(y*(2/3)*100)/100))}}static collectTextlessMoveHalves(e){const r=this.exportLinkedMoveSides,t=s=>{const l=s;let c,p,h=!1;return this.UNTRACKABLE_MOVE_KINDS.has(s.type)?(c=l.diffState,p=l.suggestionId,h=!0):s.type==="paragraph"&&s.children.every(g=>g.type==="text"&&g.text==="")&&(c=l.structuralSuggestionKind??l.diffState,p=l.structuralSuggestionId??l.suggestionId),c!=="insert"&&c!=="delete"||!p||!h&&r?.has(p)?null:{kind:c,id:p}},i=s=>{const l={};for(const[c,p]of Object.entries(s))c==="id"||c==="diffState"||c==="suggestionId"||c.startsWith("structuralSuggestion")||(l[c]=p);return JSON.stringify(l)},n=new Map;for(const s of e){const l=t(s);if(l?.kind!=="delete")continue;const c=`${l.id}\0${i(s)}`;n.set(c,[...n.get(c)??[],s])}const a=new Set,o=new Set;for(const s of e){const l=t(s);if(l?.kind!=="insert")continue;const c=n.get(`${l.id}\0${i(s)}`)?.shift();c&&(a.add(s.id),o.add(c.id))}return{destinations:a,sources:o}}static withoutMoveState(e){const r={};for(const[t,i]of Object.entries(e))t==="diffState"||t==="suggestionId"||t.startsWith("structuralSuggestion")||(r[t]=i);return r}static collectLinkedMoveSides(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(t);return}const n=i,a=n.marks;if(n.type==="text"&&a?.docxMove&&typeof a.suggestionId=="string"){const o=this.parseDocxMoveMark(a.docxMove);if(o&&(o.role==="from"&&a.deletion||o.role==="to"&&a.insertion)){const s=r.get(a.suggestionId)??{};if(!s[o.role]){const l=this.suggestionRevisionAttrs(a);s[o.role]={move:o,author:o.rangeAuthor??l.author,date:typeof o.rangeCreatedAt=="number"?new Date(o.rangeCreatedAt).toISOString():l.date}}r.set(a.suggestionId,s)}}t(n.children)};t(e);for(const[i,n]of r)(!n.from||!n.to)&&r.delete(i);return r}static linkedMoveSideFor(e,r){if(typeof e!="string")return;const t=r==="delete"?"from":r==="insert"?"to":void 0;return t?this.exportLinkedMoveSides?.get(e)?.[t]:void 0}static collectLinkedMoveBlockIds(e,r){const t=new Map;if(r.size===0)return t;const i=o=>o==="delete"?"from":o==="insert"?"to":void 0,n=new Map,a=o=>{const s=n.get(o);if(n.delete(o),!s?.marked)return;const l=t.get(o)??new Set;s.ids.forEach(c=>l.add(c)),t.set(o,l)};for(const o of e){const s=new Set,l=new Set,c=[],p=h=>{if(!h||typeof h!="object")return;if(Array.isArray(h)){h.forEach(p);return}const g=h;typeof g.id=="string"&&c.push(g.id);const f=i(g.structuralSuggestionKind);typeof g.structuralSuggestionId=="string"&&f&&s.add(`${g.structuralSuggestionId}\0${f}`);const w=i(g.diffState);typeof g.suggestionId=="string"&&w&&s.add(`${g.suggestionId}\0${w}`);const u=g.marks;if(g.type==="text"&&u?.docxMove&&typeof u.suggestionId=="string"){const m=this.parseDocxMoveMark(u.docxMove);if(m&&(m.role==="from"&&u.deletion||m.role==="to"&&u.insertion)){const b=`${u.suggestionId}\0${m.role}`;s.add(b),l.add(b)}}p(g.children)};p(o);for(const h of Array.from(n.keys()))s.has(h)||a(h);for(const h of s){const g=n.get(h)??{marked:!1,ids:[]};g.marked||(g.marked=l.has(h)),g.ids.push(...c),n.set(h,g)}}for(const o of Array.from(n.keys()))a(o);return t}static isInLinkedMoveRange(e,r){return!this.exportLinkedMoveBlockIds||typeof e.id!="string"?!0:this.exportLinkedMoveBlockIds.get(`${e.structuralSuggestionId}\0${r}`)?.has(e.id)??!1}static inferDefaultRunSizeHalfPoints(e){const r=e.stylesheet?.paragraphStyles.find(t=>t.default)?.runMarks?.fontSize;return typeof r=="number"&&r>0&&r!==Ae.paragraph?this.DEFAULT_RUN_SIZE_HALF_POINTS:void 0}static docDefaultRunSizePx(e){const r=e?.styles.runDefault;if(!r)return;const t=this.getDirectChild(r,"w:sz")?.getAttribute("w:val"),i=t?parseInt(t,10):NaN;return Number.isFinite(i)&&i>0?Math.max(1,Math.round(i*(2/3)*100)/100):void 0}static isOnAttribute(e){const r=(e||"").trim().toLowerCase();return r==="1"||r==="true"||r==="on"}static isOn(e,r){const t=this.getDirectChild(e,r);if(!t)return!1;const i=(t.getAttribute("w:val")||"").toLowerCase();return i!=="false"&&i!=="0"&&i!=="off"}static async parseImageFromDrawing(e,r,t){if(!t)return null;const i=e.getElementsByTagName("a:blip")[0],n=i?.getAttribute("r:embed")||i?.getAttribute("r:link")||"";if(!n)return null;const a=t.relationships.get(n);if(!a)return null;const o=i?this.findSvgBlipRelationshipId(i):void 0;let s,l;if(o){const T=t.relationships.get(o),O=T?t.zip.file(T.target):void 0;O&&(s=await O.async("uint8array"),l="image/svg+xml")}if(!s||!l){const T=t.zip.file(a.target);if(!T)return null;s=await T.async("uint8array"),l=this.getContentTypeForPart(a.target,t.contentTypes)||this.inferImagePartMimeType(a.target)}if(!s)return null;const c=l?this.vectorFormatForMimeType(l):void 0;if(!c&&(!l||!this.isSupportedImageMimeType(l)))return null;const p=e.getElementsByTagName("wp:extent")[0]||e.getElementsByTagName("a:ext")[0],h=p?.getAttribute("cx"),g=p?.getAttribute("cy"),f=h?Math.max(1,Math.round(parseInt(h,10)/9525)):200,w=g?Math.max(1,Math.round(parseInt(g,10)/9525)):200,u=e.getElementsByTagName("wp:docPr")[0],m=u?.getAttribute("descr")||u?.getAttribute("title")||u?.getAttribute("name")||void 0,b=this.buildImageDataUrl(s,c?c==="emf"?"image/x-emf":"image/x-wmf":l),v={type:"image",id:this.generateId(),src:b,width:f,height:w,alt:m,align:r&&r!=="justify"?r:void 0};c&&(v.originalFormat=c,v.originalDataUrl=b);const y=this.getDirectChild(e,"wp:anchor");if(y)try{v.anchorXml=this.serializeXmlPreservingPrefixes(y)}catch{}return v}static findSvgBlipRelationshipId(e){const r=e.getElementsByTagName("*");for(let t=0;t<r.length;t++){const i=r[t],n=i.tagName||"";if(n==="svgBlip"||n.endsWith(":svgBlip"))return i.getAttribute("r:embed")||i.getAttribute("r:link")||void 0}}static inferImagePartMimeType(e){const r=e.split(".").pop()?.toLowerCase();switch(r){case"svg":return"image/svg+xml";case"emf":return"image/x-emf";case"wmf":return"image/x-wmf";default:return r?this.inferMimeTypeFromPath(e):void 0}}static vectorFormatForMimeType(e){const r=e.toLowerCase();if(r==="image/x-emf"||r==="image/emf")return"emf";if(r==="image/x-wmf"||r==="image/wmf")return"wmf"}static async parseTableBlock(e,r,t){const i=[],n=[],a=[],o=(k,H)=>{for(const G of Array.from(k.children))if(G.tagName==="w:tr")H&&H.trIndexes.push(n.length),n.push(G);else if(G.tagName==="w:sdt"){const q=this.getDirectChild(G,"w:sdtContent");if(q){let Z=H;if(this.importSdtWrappers&&!H){const be=this.getDirectChild(G,"w:sdtPr");if(be)try{Z={prXml:new XMLSerializer().serializeToString(be),trIndexes:[]},a.push(Z)}catch{Z=H}}o(q,Z)}}};o(e);const s=this.getDirectChild(e,"w:tblPr"),l=s?this.getDirectChild(s,"w:tblCellMar"):void 0,c=l?this.nonUniformCellMarginJson(l):void 0,p=this.getDirectChild(e,"w:tblGrid"),h=p?this.getDirectChild(p,"w:tblGridChange"):void 0,g=h?this.getDirectChild(h,"w:tblGrid"):void 0,f=k=>{if(!k)return[];const H=[];for(const G of Array.from(k.children)){if(G.tagName!=="w:gridCol")continue;const q=Number(G.getAttribute("w:w"));Number.isFinite(q)&&q>0&&H.push(q)}return H},w=k=>{const H=f(k),G=H.reduce((q,Z)=>q+Z,0);return G>0?H.map(q=>Math.round(q/G*100)):[]},u=[],m=[],b=[],v=[],y=[],T=[],O=[],W=s?this.getDirectChild(s,"w:tblPrChange"):void 0,X=W?this.getDirectChild(W,"w:tblPr"):void 0,D=W?this.parseTrackedRevisionMeta(W):null;let M;if(X)try{M=new XMLSerializer().serializeToString(X)}catch{M=void 0}const L=new Map,I=new Map,B=[];for(let k=0;k<n.length;k++){const H=n[k],G=this.generateId(),q=this.getDirectChild(H,"w:tblPrEx"),Z=q?this.getDirectChild(q,"w:tblPrExChange"):void 0,be=Z?this.getDirectChild(Z,"w:tblPrEx"):void 0,de=this.getDirectChild(H,"w:trPr"),ve=de?this.getDirectChild(de,"w:ins"):void 0,Se=de?this.getDirectChild(de,"w:del"):void 0,fe=de?this.getDirectChild(de,"w:trPrChange"):void 0,et=fe?this.getDirectChild(fe,"w:trPr"):void 0;if(ve){const we=this.parseTrackedRevisionMeta(ve);u.push({rowId:G,kind:"insert",...we})}else if(Se){const we=this.parseTrackedRevisionMeta(Se);u.push({rowId:G,kind:"delete",...we})}de&&fe&&et&&m.push({rowId:G,rowIndex:k,...this.parseTrackedRevisionMeta(fe),currentXml:this.serializePropertiesWithoutRevisionChildren(de,new Set(["w:ins","w:del","w:trPrChange"])),priorXml:new XMLSerializer().serializeToString(et),...k===0?{currentTableAttributes:this.tableHeaderAttributesFromRowProperties(de),priorTableAttributes:this.tableHeaderAttributesFromRowProperties(et)}:{}}),q&&Z&&be&&b.push({rowId:G,rowIndex:k,...this.parseTrackedRevisionMeta(Z),currentXml:this.serializePropertiesWithoutRevisionChildren(q,new Set(["w:tblPrExChange"])),priorXml:new XMLSerializer().serializeToString(be)});const ie=[];let he=0;const Ie=[];for(let we=0;we<H.children.length;we++){const Pe=H.children[we];if(Pe.tagName==="w:tc")Ie.push({el:Pe});else if(Pe.tagName==="w:sdt"){const ce=this.getDirectChild(Pe,"w:sdtContent");if(!ce)continue;let De;if(this.importSdtWrappers){const Be=this.getDirectChild(Pe,"w:sdtPr");if(Be)try{De={prXml:new XMLSerializer().serializeToString(Be),cellIds:[]},B.push(De)}catch{De=void 0}}for(const Be of Array.from(ce.children))Be.tagName==="w:tc"&&Ie.push({el:Be,sdtGroup:De})}}for(let we=0;we<Ie.length;we++){const Pe=Ie[we].el,ce=this.getDirectChild(Pe,"w:tcPr"),De=this.getDirectChild(ce||Pe,"w:shd")?.getAttribute("w:fill"),Be=ce?this.getDirectChild(ce,"w:gridSpan")?.getAttribute("w:val"):void 0,Nt=Be?parseInt(Be,10):1,Ke=Number.isFinite(Nt)?Math.min(Math.max(1,Nt),1e3):1,tt=ce?this.getDirectChild(ce,"w:cellIns"):void 0,ft=ce?this.getDirectChild(ce,"w:cellDel"):void 0,ge=ce?this.getDirectChild(ce,"w:cellMerge"):void 0,dt=ce?this.getDirectChild(ce,"w:tcPrChange"):void 0,Ce=dt?this.getDirectChild(dt,"w:tcPr"):void 0,ye={type:"table-cell",id:this.generateId(),backgroundColor:De&&De.toLowerCase()!=="auto"&&De.toLowerCase()!=="none"?`#${De.replace(/^#/,"")}`:void 0,children:this.applyParagraphMarkRevisions(await this.parseBodyChildren(Pe,r,t))};Ke>1&&(ye.colSpan=Ke);const rt=at(ce,Ur);rt&&(ye.oxmlTcPr=rt);const wt=ce?this.getDirectChild(ce,"w:tcBorders"):void 0,Ze=wt?this.parseDocxBordersElement(wt,!1):void 0;Ze&&(ye.borders=Ze);const Fe=ce?this.getDirectChild(ce,"w:tcMar"):void 0,Ve=(Fe?this.parseDocxCellMargins(Fe):void 0)??c;Ve&&(ye.padding=Ve);const _e=ce?this.getDirectChild(ce,"w:vAlign")?.getAttribute("w:val"):void 0;(_e==="top"||_e==="center"||_e==="bottom")&&(ye.verticalAlign=_e==="center"?"middle":_e),ge&&T.push({rowId:G,gridColumn:he,...this.parseTrackedRevisionMeta(ge),...ge.getAttribute("w:vMerge")?{vMerge:ge.getAttribute("w:vMerge")}:{},...ge.getAttribute("w:vMergeOrig")?{vMergeOrig:ge.getAttribute("w:vMergeOrig")}:{}});const it=ce?this.getDirectChild(ce,"w:vMerge"):void 0,nt=it?.getAttribute("w:val");if(it&&nt!=="restart"){const Ne=L.get(he);if(Ne){if(Ne.cell.rowSpan=(Ne.cell.rowSpan??1)+1,ge){const ot=this.parseTrackedRevisionMeta(ge);O.push({row:k,pos:ie.length,colSpan:Ke,anchorRow:Ne.rowIndex,anchorPos:Ne.cellPos,rowId:G,gridColumn:he,restoredCellId:ye.id,restoredCell:JSON.parse(JSON.stringify(ye)),direction:"merge",...ot,...ge.getAttribute("w:vMerge")?{vMerge:ge.getAttribute("w:vMerge")}:{},...ge.getAttribute("w:vMergeOrig")?{vMergeOrig:ge.getAttribute("w:vMergeOrig")}:{}})}he+=Ke;continue}}it&&nt==="restart"?L.set(he,{cell:ye,rowIndex:k,cellPos:ie.length}):L.delete(he);const pt=ge?.hasAttribute("w:vMergeOrig")?ge.getAttribute("w:vMergeOrig"):it?nt??"continue":void 0,ht=pt==="restart"||pt==="rest",bt=pt==="continue"||pt==="cont";if(ht)I.set(he,{cell:ye,rowIndex:k,cellPos:ie.length});else if(bt){const Ne=I.get(he);if(Ne&&ge&&!it){const ot=this.parseTrackedRevisionMeta(ge);O.push({row:k,pos:ie.length,colSpan:Ke,anchorRow:Ne.rowIndex,anchorPos:Ne.cellPos,rowId:G,gridColumn:he,restoredCellId:ye.id,restoredCell:JSON.parse(JSON.stringify(ye)),direction:"unmerge",...ot,...ge.getAttribute("w:vMerge")?{vMerge:ge.getAttribute("w:vMerge")}:{},...ge.getAttribute("w:vMergeOrig")?{vMergeOrig:ge.getAttribute("w:vMergeOrig")}:{}})}}else I.delete(he);tt&&v.push({cellId:ye.id,kind:"insert",...this.parseTrackedRevisionMeta(tt)}),ft&&v.push({cellId:ye.id,kind:"delete",...this.parseTrackedRevisionMeta(ft)}),dt&&Ce&&y.push({rowId:G,cellId:ye.id,rowIndex:k,cellIndex:ie.length,gridColumn:he,...this.parseTrackedRevisionMeta(dt),currentXml:this.serializePropertiesWithoutRevisionChildren(ce,new Set(["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])),priorXml:new XMLSerializer().serializeToString(Ce),currentAttributes:this.tableCellAttributesFromProperties(ce),priorAttributes:this.tableCellAttributesFromProperties(Ce)}),Ie[we].sdtGroup?.cellIds.push(ye.id),ie.push(ye),he+=Ke}const Le={type:"table-row",id:G,children:ie},ke=sr(H);ke&&(Le.oxmlAttrs=ke);const ct=at(de,Jr);ct&&(Le.oxmlTrPr=ct),i.push(Le)}if(i.length===0)return null;if(this.importSdtWrappers){const k=this.sdtAncestorStack[this.sdtAncestorStack.length-1];for(const H of a){const G=H.trIndexes.map(q=>i[q]?.id).filter(q=>!!q);G.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:H.prXml,scope:"row",...k?{parentId:k.id}:{},blockIds:G})}for(const H of B)H.cellIds.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:H.prXml,scope:"cell",...k?{parentId:k.id}:{},blockIds:[...H.cellIds]})}const E=w(p),S=n[0]?this.getDirectChild(n[0],"w:trPr"):void 0,R=S?this.tableHeaderAttributesFromRowProperties(S).hasHeader===!0:!1,z=this.generateId(),$=new Map,j=(k,H,G)=>{const q=k.revisionId?`docxrev-${k.revisionId}`:this.generateId(),Z=$.get(q);if(Z)return Z;const be=this.revisionAuthorIdentity(k.author),de={id:q,type:"table-change",tableId:z,source:be.suggestionSource,authorType:be.suggestionAuthorType,label:H,...k.createdAt!==void 0?{createdAt:k.createdAt}:{},...k.author?{agentName:k.author}:{},tableRevision:{version:1,suggestionKind:G,markers:[],operations:[]}};return $.set(q,de),de};if(p&&h&&g){const k=this.parseTrackedRevisionMeta(h),H=this.serializePropertiesWithoutRevisionChildren(p,new Set(["w:tblGridChange"])),G=new XMLSerializer().serializeToString(g),q=w(p),Z=w(g),be=j(k,"Change table column widths","format");be.tableRevision.markers.push({kind:"table-grid",revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:H,priorPropertiesXml:G,currentColumnWidths:q,priorColumnWidths:Z}),be.tableRevision.operations.push({kind:"grid",currentGridXml:H,priorGridXml:G,currentColumnWidths:q,priorColumnWidths:Z})}for(const k of u){const H=i.findIndex(Z=>Z.id===k.rowId),G=i[H];if(!G)continue;const q=j(k,k.kind==="insert"?"Insert table row":"Delete table row",k.kind);q.tableRevision.markers.push({kind:k.kind==="insert"?"row-insert":"row-delete",rowId:k.rowId,rowIndex:H,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt}),q.tableRevision.operations.push({kind:"row",action:k.kind,rowId:k.rowId,rowIndex:H,row:JSON.parse(JSON.stringify(G))}),G.diffState=k.kind,G.suggestionId=q.id}for(const k of v){let H=-1,G=-1,q,Z;for(let ve=0;ve<i.length&&!Z;ve++){const Se=i[ve].children.findIndex(fe=>fe.id===k.cellId);Se>=0&&(H=ve,G=Se,q=i[ve],Z=q.children[Se])}if(!q||!Z)continue;const be=Qe({children:i,columnWidths:E}).byId.get(Z.id),de=j(k,k.kind==="insert"?"Insert table cell":"Delete table cell",k.kind);de.tableRevision.markers.push({kind:k.kind==="insert"?"cell-insert":"cell-delete",rowId:q.id,cellId:Z.id,rowIndex:H,cellIndex:G,gridColumn:be?.col,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt}),de.tableRevision.operations.push({kind:"cell",action:k.kind,rowId:q.id,cellId:Z.id,cellIndex:G,cell:JSON.parse(JSON.stringify(Z))}),Z.diffState=k.kind,Z.suggestionId=de.id}for(const k of m){const H=j(k,"Change table row properties","format");H.tableRevision.markers.push({kind:"row-properties",rowId:k.rowId,rowIndex:k.rowIndex,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),H.tableRevision.operations.push({kind:"properties",target:"row",rowId:k.rowId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml,currentTableAttributes:k.currentTableAttributes,priorTableAttributes:k.priorTableAttributes})}for(const k of b){const H=j(k,"Change row table-style exceptions","format");H.tableRevision.markers.push({kind:"row-exception-properties",rowId:k.rowId,rowIndex:k.rowIndex,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),H.tableRevision.operations.push({kind:"properties",target:"row-exception",rowId:k.rowId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml})}for(const k of y){const H=j(k,"Change table cell properties","format");H.tableRevision.markers.push({kind:"cell-properties",rowId:k.rowId,cellId:k.cellId,rowIndex:k.rowIndex,cellIndex:k.cellIndex,gridColumn:k.gridColumn,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),H.tableRevision.operations.push({kind:"properties",target:"cell",rowId:k.rowId,cellId:k.cellId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml,currentAttributes:k.currentAttributes,priorAttributes:k.priorAttributes})}const K=new Map;for(const k of O){const H=k.revisionId?`docxrev-${k.revisionId}`:this.generateId(),G=K.get(H)??[];G.push(k),K.set(H,G)}for(const[k,H]of K){const G=H[0],q={revisionId:G.revisionId,author:G.author,createdAt:G.createdAt},Z=j(q,H.every(ie=>ie.direction==="unmerge")?"Split table cells":"Merge table cells","format");Z.id!==k&&!$.has(k)&&($.delete(Z.id),Z.id=k,$.set(k,Z));const be=G.revisionId?T.filter(ie=>ie.revisionId===G.revisionId):H;for(const ie of be)Z.tableRevision.markers.push({kind:"cell-merge",rowId:ie.rowId,gridColumn:ie.gridColumn,revisionId:ie.revisionId,author:ie.author,createdAt:ie.createdAt,vMerge:ie.vMerge,vMergeOrig:ie.vMergeOrig});const de=JSON.parse(JSON.stringify(i)),ve=new Map,Se=new Set;for(const ie of H){const he=de[ie.anchorRow]?.children[ie.anchorPos],Ie=de[ie.row];if(ie.direction==="merge"){if(he?.rowSpan!==void 0){const ke=he.rowSpan-1;ke>1?he.rowSpan=ke:delete he.rowSpan}if(Ie){const ke=ve.get(ie.row)??0;Ie.children.splice(ie.pos+ke,0,JSON.parse(JSON.stringify(ie.restoredCell))),ve.set(ie.row,ke+1)}}else if(he&&(he.rowSpan=(he.rowSpan??1)+1),Ie){const ke=Ie.children.findIndex(ct=>ct.id===ie.restoredCellId);ke>=0&&Ie.children.splice(ke,1)}Ie&&Se.add(Ie.id);const Le=de[ie.anchorRow];Le&&Se.add(Le.id)}const fe=i.filter(ie=>Se.has(ie.id)).map(ie=>JSON.parse(JSON.stringify(ie))),et=de.filter(ie=>Se.has(ie.id));Z.tableRevision.operations.push({kind:"geometry",pendingRows:fe,acceptedRows:JSON.parse(JSON.stringify(fe)),rejectedRows:et})}if(D&&s&&X){const k=j(D,"Change table properties","format"),H=this.serializePropertiesWithoutRevisionChildren(s,new Set(["w:tblPrChange"])),G=M??new XMLSerializer().serializeToString(X);k.tableRevision.markers.push({kind:"table-properties",revisionId:D.revisionId,author:D.author,createdAt:D.createdAt,currentPropertiesXml:H,priorPropertiesXml:G}),k.tableRevision.operations.push({kind:"properties",target:"table",currentPropertiesXml:H,priorPropertiesXml:G,currentAttributes:{...this.tableAttributesFromProperties(s,t)},priorAttributes:{...this.tableAttributesFromProperties(X,t)}})}const J=Array.from($.values()),re=this.tableAttributesFromProperties(s,t);return{type:"table",id:z,...J.length>0?{structuralSuggestionRecords:JSON.stringify(J)}:{},children:i,columnWidths:E,...re,...R?{hasHeader:!0}:{},...(()=>{const k=at(s,Gr);return k?{oxmlTblPr:k}:{}})()}}static serializePropertiesWithoutRevisionChildren(e,r){const t=e.cloneNode(!0);for(const i of Array.from(t.children))r.has(i.tagName)&&i.remove();return new XMLSerializer().serializeToString(t)}static tableCellAttributesFromProperties(e){const r={},t=this.getDirectChild(e,"w:shd")?.getAttribute("w:fill");t&&t.toLowerCase()!=="auto"&&t.toLowerCase()!=="none"&&(r.backgroundColor=`#${t.replace(/^#/,"")}`);const i=this.getDirectChild(e,"w:tcBorders"),n=i?this.parseDocxBordersElement(i,!1):void 0;n&&(r.borders=n);const a=this.getDirectChild(e,"w:tcMar"),o=a?this.parseDocxCellMargins(a):void 0;o&&(r.padding=o);const s=this.getDirectChild(e,"w:gridSpan")?.getAttribute("w:val"),l=s?Number(s):void 0;l&&Number.isFinite(l)&&l>1&&(r.colSpan=l);const c=this.getDirectChild(e,"w:vAlign")?.getAttribute("w:val");return(c==="top"||c==="center"||c==="bottom")&&(r.verticalAlign=c==="center"?"middle":c),r}static tableHeaderAttributesFromRowProperties(e){const r=this.getDirectChild(e,"w:tblHeader");if(!r)return{};const t=r.getAttribute("w:val")?.trim().toLowerCase();return t==="0"||t==="false"||t==="off"||t==="no"?{}:{hasHeader:!0}}static tableAttributesFromProperties(e,r){const t={};if(t.borders=this.resolveTableBordersJson(e,r),!e)return t;const i=this.getDirectChild(e,"w:jc")?.getAttribute("w:val");i==="center"||i==="right"?t.align=i:i==="left"||i==="start"?t.align="left":i==="end"&&(t.align="right");const n=this.getDirectChild(e,"w:tblW"),a=n?.getAttribute("w:type"),o=Number(n?.getAttribute("w:w"));a==="dxa"&&Number.isFinite(o)&&o>0&&(t.tableWidth=Math.round(o/15));const s=this.getDirectChild(e,"w:tblCellMar"),l=s?this.parseDocxCellMargins(s):void 0;if(l)try{const c=JSON.parse(l),p=[c.top,c.right,c.bottom,c.left];p.every(h=>Number.isFinite(h))&&p.every(h=>h===p[0])&&(t.cellPadding=p[0])}catch{}return t}static mapDocxBorderStyle(e){switch((e||"").trim()){case"none":case"nil":return"none";case"dotted":return"dotted";case"dashed":case"dashSmallGap":case"dashDotStroked":case"dotDash":case"dotDotDash":return"dashed";case"double":case"triple":case"doubleWave":return"double";default:return"single"}}static parseDocxBordersElement(e,r){return Br(this.parseDocxBordersSpec(e,r))}static resolveTableBordersJson(e,r){const t={},i=s=>{s&&Object.assign(t,this.parseDocxBordersSpec(s,!0))},n=r?.styles;if(n){const s=(e&&this.getDirectChild(e,"w:tblStyle")?.getAttribute("w:val")||void 0)??n.defaultStyleIdByType?.get("table"),l=s?this.resolveStyleChain(s,n,"table"):[];for(const c of l)i(c.tblPr?this.getDirectChild(c.tblPr,"w:tblBorders"):void 0)}i(e?this.getDirectChild(e,"w:tblBorders"):void 0);const a={style:"none",width:0,color:"#000000"},o={top:t.top??a,bottom:t.bottom??a,left:t.left??a,right:t.right??a,insideH:t.insideH??a,insideV:t.insideV??a};return Br(o)}static parseDocxBordersSpec(e,r){const t=(...l)=>{let c;for(const m of l)if(c=this.getDirectChild(e,m),c)break;if(!c)return;const p=this.mapDocxBorderStyle(c.getAttribute("w:val")),h=parseInt(c.getAttribute("w:sz")||"",10),g=p!=="none"&&h===0?"none":p,f=g==="none"?0:Number.isFinite(h)&&h>0?Math.max(.25,Math.round(h/6*100)/100):1,w=(c.getAttribute("w:color")||"").trim(),u=w&&w.toLowerCase()!=="auto"?`#${w.replace(/^#/,"").toLowerCase()}`:"#000000";return{style:g,width:f,color:u}},i={},n=t("w:top"),a=t("w:bottom"),o=t("w:left","w:start"),s=t("w:right","w:end");if(n&&(i.top=n),a&&(i.bottom=a),o&&(i.left=o),s&&(i.right=s),r){const l=t("w:insideH"),c=t("w:insideV");l&&(i.insideH=l),c&&(i.insideV=c)}return i}static nonUniformCellMarginJson(e){const r=this.parseDocxCellMargins(e);if(r){try{const t=JSON.parse(r),i=[t.top,t.right,t.bottom,t.left];if(i.every(n=>Number.isFinite(n))&&i.every(n=>n===i[0]))return}catch{return}return r}}static parseDocxCellMargins(e){const r=(...o)=>{let s;for(const c of o)if(s=this.getDirectChild(e,c),s)break;if(!s)return;const l=parseInt(s.getAttribute("w:w")||"",10);if(!(!Number.isFinite(l)||l<0))return Math.round(l/15*100)/100},t=r("w:top"),i=r("w:bottom"),n=r("w:left","w:start"),a=r("w:right","w:end");if(!(t===void 0&&i===void 0&&n===void 0&&a===void 0))return Xi({top:t??0,bottom:i??0,left:n??7.2,right:a??7.2})}static getContentTypeForPart(e,r){const t=r.get(e);if(t)return t;const i=e.split(".").pop()?.toLowerCase();return i?r.get(i):void 0}static isSupportedImageMimeType(e){return e==="image/png"||e==="image/jpeg"||e==="image/jpg"||e==="image/gif"||e==="image/bmp"||e==="image/svg+xml"}static buildImageDataUrl(e,r){return`data:${r};base64,${this.uint8ArrayToBase64(e)}`}static uint8ArrayToBase64(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let r="";const t=32768;for(let i=0;i<e.length;i+=t){const n=e.subarray(i,i+t);r+=String.fromCharCode(...n)}return btoa(r)}static createEmptyParagraph(){return{type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}]}}static createPageBreakBlock(){return{type:"page-break",id:this.generateId()}}static generateId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let t=0;t<6;t++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}static ommlToLatex(e){try{return this.parseOmmlElement(e)}catch(r){return console.warn("Failed to convert OMML to LaTeX:",r),""}}static parseOmmlElement(e){const r=e.tagName;switch(r){case"m:oMathPara":case"m:oMath":return this.parseOmmlChildren(e);case"m:r":{const t=e.getElementsByTagName("m:t")[0];if(!t)return"";const i=(t.textContent||"").replace(/\u200B/g,""),n=e.getElementsByTagName("m:rPr")[0];if(n?.getElementsByTagName("m:nor")[0]){const c=i.replace(/\u00a0/g," "),p={"\\":"\\textbackslash{}","{":"\\{","}":"\\}","&":"\\&","%":"\\%",$:"\\$","#":"\\#",_:"\\_","^":"\\textasciicircum{}","~":"\\textasciitilde{}"};return`\\text{${c.replace(/[\\{}&%$#_^~]/g,h=>p[h])}}`}const a=this.cleanMathText(i),o=n?.getElementsByTagName("m:scr")[0]?.getAttribute("m:val"),s=n?.getElementsByTagName("m:sty")[0]?.getAttribute("m:val"),l={"double-struck":"\\mathbb",script:"\\mathcal",fraktur:"\\mathfrak","sans-serif":"\\mathsf",monospace:"\\mathtt"};return o&&l[o]?`${l[o]}{${a}}`:s==="b"||s==="bi"?`\\mathbf{${a}}`:s==="p"&&/^[A-Za-z]+$/.test(i)?hr.OMML_FUNCTION_NAMES.includes(i)?`\\${i} `:`\\mathrm{${i}}`:a}case"m:sSub":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return`${n}_{${a}}`}case"m:sSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sup")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return`${n}^{${a}}`}case"m:sSubSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],a=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"",s=n?this.parseOmmlChildren(n):"";return`${a}_{${o}}^{${s}}`}case"m:f":{const t=e.getElementsByTagName("m:num")[0],i=e.getElementsByTagName("m:den")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return e.getElementsByTagName("m:fPr")[0]?.getElementsByTagName("m:type")[0]?.getAttribute("m:val")==="noBar"?`{${n} \\atop ${a}}`:`\\frac{${n}}{${a}}`}case"m:rad":{const t=e.getElementsByTagName("m:deg")[0],i=e.getElementsByTagName("m:e")[0],n=t?this.parseOmmlChildren(t).trim():"",a=i?this.parseOmmlChildren(i):"";return n&&n!=="2"?`\\sqrt[${n}]{${a}}`:`\\sqrt{${a}}`}case"m:nary":{const t=e.getElementsByTagName("m:naryPr")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],a=e.getElementsByTagName("m:e")[0];let o="\\sum";if(t){const h=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");h&&(o={"∑":"\\sum","∏":"\\prod","∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","⋃":"\\bigcup","⋂":"\\bigcap"}[h]||"\\sum")}const s=i?this.parseOmmlChildren(i):"",l=n?this.parseOmmlChildren(n):"",c=a?this.parseOmmlChildren(a):"";let p=o;return s&&(p+=`_{${s}}`),l&&(p+=`^{${l}}`),p+=` ${c}`,p}case"m:d":{const t=e.getElementsByTagName("m:dPr")[0],i=e.getElementsByTagName("m:e")[0];let n="(",a=")";if(t){const l=t.getElementsByTagName("m:begChr")[0],c=t.getElementsByTagName("m:endChr")[0];l?.hasAttribute("m:val")&&(n=l.getAttribute("m:val")??""),c?.hasAttribute("m:val")&&(a=c.getAttribute("m:val")??"")}const o=l=>({"":".","{":"\\{","}":"\\}","⟨":"\\langle","⟩":"\\rangle","‖":"\\|","∥":"\\|","∣":"|","⌊":"\\lfloor","⌋":"\\rfloor","⌈":"\\lceil","⌉":"\\rceil"})[l]??l,s=i?this.parseOmmlChildren(i):"";return`\\left${o(n)}${s}\\right${o(a)}`}case"m:m":{const t=Array.from(e.children).filter(n=>n.tagName==="m:mr");if(t.length===0)return"";let i="\\begin{matrix}";for(let n=0;n<t.length;n++){const a=Array.from(t[n].children).filter(s=>s.tagName==="m:e"),o=[];for(let s=0;s<a.length;s++)o.push(this.parseOmmlChildren(a[s]));i+=o.join(" & "),n<t.length-1&&(i+=" \\\\ ")}return i+="\\end{matrix}",i}case"m:bar":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"";return e.getElementsByTagName("m:barPr")[0]?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")==="bot"?`\\underline{${i}}`:`\\overline{${i}}`}case"m:acc":{const t=e.getElementsByTagName("m:accPr")[0],i=e.getElementsByTagName("m:e")[0],n=i?this.parseOmmlChildren(i):"";let a="\\hat";if(t){const o=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");o&&(a={"̂":"\\hat","~":"\\tilde","̃":"\\tilde","̌":"\\check","̆":"\\breve","́":"\\acute","̀":"\\grave","̇":"\\dot","̈":"\\ddot","̄":"\\bar","⃗":"\\vec"}[o]||"\\hat")}return`${a}{${n}}`}case"m:limLow":case"m:limUpp":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:lim")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return r==="m:limLow"?`${n}_{${a}}`:`${n}^{${a}}`}case"m:borderBox":{const t=Array.from(e.children).find(i=>i.tagName==="m:e");return`\\boxed{${t?this.parseOmmlChildren(t):""}}`}case"m:groupChr":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"",n=e.getElementsByTagName("m:groupChrPr")[0],a=n?.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");return n?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")!=="top"&&a!=="⏞"?`\\underbrace{${i}}`:`\\overbrace{${i}}`}case"m:func":{const t=Array.from(e.children).find(l=>l.tagName==="m:fName"),i=Array.from(e.children).find(l=>l.tagName==="m:e"),n=t?Array.from(t.children).find(l=>l.tagName==="m:limLow"):void 0;if(n){const l=Array.from(n.children).find(w=>w.tagName==="m:e"),c=Array.from(n.children).find(w=>w.tagName==="m:lim"),p=(l?.textContent??"").trim(),h=i?this.parseOmmlChildren(i):"",g=c?this.parseOmmlChildren(c):"",f=/^[A-Za-z]+$/.test(p)?`\\operatorname*{${p}}`:p;return`${["lim","max","min","sup","inf","liminf","limsup"].includes(p)?`\\${p}`:f}_{${g}} ${h}`}const a=(t?.textContent??"").trim(),o=i?this.parseOmmlChildren(i):"",s=hr.OMML_FUNCTION_NAMES;return s.includes(a)?`\\${a}{${o}}`:s.includes(a.toLowerCase())?`\\${a.toLowerCase()}{${o}}`:/^[A-Za-z]+$/.test(a)?`\\operatorname{${a}}{${o}}`:`${a}(${o})`}default:return this.parseOmmlChildren(e)}}static parseOmmlChildren(e){let r="";for(let t=0;t<e.children.length;t++){const i=e.children[t];i.tagName.endsWith("Pr")||i.tagName==="m:ctrlPr"||i.tagName==="m:t"||(r+=this.parseOmmlElement(i))}return r}static cleanMathText(e){const r={"𝐴":"A","𝐵":"B","𝐶":"C","𝐷":"D","𝐸":"E","𝐹":"F","𝐺":"G","𝐻":"H","𝐼":"I","𝐽":"J","𝐾":"K","𝐿":"L","𝑀":"M","𝑁":"N","𝑂":"O","𝑃":"P","𝑄":"Q","𝑅":"R","𝑆":"S","𝑇":"T","𝑈":"U","𝑉":"V","𝑊":"W","𝑋":"X","𝑌":"Y","𝑍":"Z","𝑎":"a","𝑏":"b","𝑐":"c","𝑑":"d","𝑒":"e","𝑓":"f","𝑔":"g",ℎ:"h","𝑖":"i","𝑗":"j","𝑘":"k","𝑙":"l","𝑚":"m","𝑛":"n","𝑜":"o","𝑝":"p","𝑞":"q","𝑟":"r","𝑠":"s","𝑡":"t","𝑢":"u","𝑣":"v","𝑤":"w","𝑥":"x","𝑦":"y","𝑧":"z",α:"\\alpha",β:"\\beta",γ:"\\gamma",δ:"\\delta",ε:"\\epsilon",ζ:"\\zeta",η:"\\eta",θ:"\\theta",ι:"\\iota",κ:"\\kappa",λ:"\\lambda",μ:"\\mu",ν:"\\nu",ξ:"\\xi",π:"\\pi",ρ:"\\rho",σ:"\\sigma",τ:"\\tau",υ:"\\upsilon",φ:"\\phi",χ:"\\chi",ψ:"\\psi",ω:"\\omega",Γ:"\\Gamma",Δ:"\\Delta",Θ:"\\Theta",Λ:"\\Lambda",Ξ:"\\Xi",Π:"\\Pi",Σ:"\\Sigma",Φ:"\\Phi",Ψ:"\\Psi",Ω:"\\Omega","∞":"\\infty","∂":"\\partial","∇":"\\nabla","±":"\\pm","∓":"\\mp","×":"\\times","÷":"\\div","≠":"\\neq","≈":"\\approx","≤":"\\leq","≥":"\\geq","∈":"\\in","∉":"\\notin","⊂":"\\subset","⊃":"\\supset","∪":"\\cup","∩":"\\cap","→":"\\rightarrow","←":"\\leftarrow","⇒":"\\Rightarrow","⇐":"\\Leftarrow","⇔":"\\Leftrightarrow","∀":"\\forall","∃":"\\exists","∄":"\\nexists","∴":"\\therefore","∵":"\\because","…":"\\ldots","⋯":"\\cdots","⋮":"\\vdots","⋱":"\\ddots"},t={"&":"\\&","%":"\\%","#":"\\#",$:"\\$","{":"\\{","}":"\\}"};let i="";for(const n of e){const a=r[n];a?i+=a.startsWith("\\")?`${a} `:a:i+=t[n]??n}return i}static async loadZipFromBlob(e){const r=typeof e.arrayBuffer=="function"?await e.arrayBuffer():e;return Er.loadAsync(r)}static async generateCompressedZipBlob(e){return e.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}static async toBlob(e,r,t){if(t?.onWarning){const d=this.pendingListNumberingChanges(e.children);d.length>0&&t.onWarning({code:"list_numbering_tracked_unsupported",message:`${d.length===1?"A list has":`${d.length} lists have`} a pending numbering restart or list-type change. Word cannot track that, so the .docx shows ${d.length===1?"it":"them"} as already applied, with no revision to accept or reject. Accept or reject ${d.length===1?"it":"them"} in Revise before exporting to keep the choice.`,blockIds:d})}Rr()||await zi();const i=await import("./index-BWdRWxoH.js"),{Document:n,Packer:a,Tab:o,TabStopType:s,LeaderType:l,CommentRangeStart:c,CommentRangeEnd:p,CommentReference:h,BookmarkStart:g,BookmarkEnd:f,Paragraph:w,TextRun:u,InsertedTextRun:m,DeletedTextRun:b,FootnoteReference:v,Header:y,Footer:T,ExternalHyperlink:O,InternalHyperlink:W,HeadingLevel:X,AlignmentType:D,PageOrientation:M,PageNumber:L,PageBreak:I,SectionType:B,UnderlineType:E,Table:S,TableRow:R,TableCell:z,WidthType:$,BorderStyle:j,ShadingType:K,ImportedXmlComponent:J,ImageRun:re,LevelFormat:k,LevelSuffix:H}=i,G=d=>{const x=`<root>${d}</root>`,C=J.fromXmlString(x),N=C.root?.[0];if(N?.root){for(const A of N.root)if(A?.rootKey?.startsWith("m:"))return A}return C},q=(d,x)=>{const C=d?.root;if(Array.isArray(C)){for(const N of C)if(N?.rootKey===x)return N;for(const N of C){if(N?.rootKey==="w:rPr"||N?.rootKey==="w:pPr"||N?.rootKey==="w:tblPr"||N?.rootKey==="w:trPr"||N?.rootKey==="w:tcPr")continue;const A=q(N,x);if(A)return A}}},Z=(d,x,C)=>{try{const N=q(d,x);if(!N||!Array.isArray(N.root))return;const A=(J.fromXmlString(`<root>${C}</root>`).root?.[0]?.root??[]).filter(V=>V?.rootKey&&V.rootKey!=="_attr");N.root.push(...A)}catch{}},be=d=>{try{const x=J.fromXmlString(`<root>${d}</root>`);for(const C of x.root?.[0]?.root??[])if(C?.rootKey&&C.rootKey!=="_attr")return C}catch{}return null},de=[],ve=[],Se=(d,x,C="w:pPr")=>{const N=de.length;de.push(x),Z(d,C,`<w:rvseOxmlAttrs w:val="${N}"/>`)},fe=Ee(e.pageLayout),et=rr(fe),ie=(d,x,C="only")=>{const N=(()=>{const _=Ee(Wr(e.pageLayout,d)).pageNumberStart;switch(C){case"middle":return d?.pageNumberStart;case"first":return d?.pageNumberStart??(_!==1?_:void 0);case"final":return e.pageLayout?.pageNumberRestart===!0?_:void 0;case"only":return e.pageLayout?.pageNumberRestart===!0||_!==1?_:void 0}})(),A=Ee(d),V=rr(A),P={...x&&x!=="nextPage"?{type:x==="continuous"?B.CONTINUOUS:x==="evenPage"?B.EVEN_PAGE:B.ODD_PAGE}:{},page:{size:{width:this.pxToTwips(A.orientation==="landscape"?V.pageHeight:V.pageWidth),height:this.pxToTwips(A.orientation==="landscape"?V.pageWidth:V.pageHeight),orientation:A.orientation==="landscape"?M.LANDSCAPE:M.PORTRAIT},margin:{top:this.pxToTwips(A.marginTopPx),right:this.pxToTwips(A.marginRightPx),bottom:this.pxToTwips(A.marginBottomPx),left:this.pxToTwips(A.marginLeftPx)},...(()=>{const _=Ee(Wr(e.pageLayout,d)).pageNumberFormat,Y={...N!==void 0?{start:N}:{},..._!=="decimal"?{formatType:_}:{}};return Object.keys(Y).length>0?{pageNumbers:Y}:{}})()}};return d?.columnCount&&d.columnCount>1&&(P.column={count:d.columnCount,...d.columnGapTwips!==void 0?{space:d.columnGapTwips}:{}}),!A.lineNumbering&&A.pleadingGrid?P.lineNumbers={countBy:1,start:1,restart:"newPage",distance:Math.round((A.pleadingGrid.distancePx??14)*15)}:A.lineNumbering&&(P.lineNumbers={countBy:A.lineNumbering.countBy,start:A.lineNumbering.start,restart:A.lineNumbering.restart,...A.lineNumbering.distancePx!==void 0?{distance:Math.round(A.lineNumbering.distancePx*15)}:{}}),P},he=ie(e.pageLayout),Ie=fe.pageNumberPosition.endsWith("right")?D.RIGHT:D.LEFT,Le=new w({alignment:Ie,children:[new u({children:[L.CURRENT]})]}),ke=Math.round((et.pageWidth-fe.marginLeftPx-fe.marginRightPx)*15),ct=d=>{const x=[],C=(P,_)=>(_.oxmlRPr&&Z(P,"w:rPr",_.oxmlRPr),P);for(const P of d.children){if(P.type!=="text")continue;const _=this.textNodeToDocx(P)[0]??{},Y=_e(_);if(P.marks?.field==="page"||P.marks?.field==="numPages"){x.push(new u({...Y,children:[P.marks.field==="page"?L.CURRENT:L.TOTAL_PAGES]}));continue}if(P.text)if(/[\t\n]/.test(P.text)&&!P.marks?.link)P.text.split(`
|
|
7
|
+
`).forEach((U,oe)=>{const te=[];U.split(" ").forEach((me,ee)=>{ee>0&&te.push(new o),me&&te.push(me)}),x.push(new u({children:te,...Y,...oe>0?{break:1}:{}}))});else if(P.marks?.link){const U={...Y};U.underline??(U.underline={type:E.SINGLE}),U.color??(U.color="2563EB");const oe=[C(new u({text:P.text,...U}),_)];x.push(P.marks.link.startsWith("#")?new W({anchor:P.marks.link.slice(1),children:oe}):new O({link:P.marks.link,children:oe}))}else if(_.revision){const U={text:P.text,...Y,id:Fe(_.revision.importedId),author:_.revision.author,date:_.revision.date};x.push(C(_.revision.kind==="delete"?new b(U):new m(U),_))}else x.push(C(new u({text:P.text,...Y}),_))}const N=d.children.some(P=>P.type==="text"&&P.text.includes(" ")),A={left:D.LEFT,center:D.CENTER,right:D.RIGHT,justify:D.JUSTIFIED},V=new w({children:x,...d.align&&A[d.align]?{alignment:A[d.align]}:{},...N?{tabStops:[{type:s.CENTER,position:Math.round(ke/2)},{type:s.RIGHT,position:ke}]}:{}});return d.oxmlPPr&&Z(V,"w:pPr",d.oxmlPPr),d.oxmlAttrs&&Se(V,d.oxmlAttrs),V},we=new Map,Pe=Hi(e),ce=Pe.sizes,De=d=>d.fit==="band"?ce.get(d):{width:d.width,height:d.height},Be=(d,x)=>d.fit!=="band"||x===void 0||!!Pe.sectionsShowing.get(d)?.has(x),Nt=(e.chromeImages??[]).some(d=>d.fit==="band"&&!!ce.get(d)&&(Pe.sectionsShowing.get(d)?.size??0)<Pe.sectionCount);for(const d of e.chromeImages??[]){if(!De(d))continue;const x=await this.resolveImageSourceForDocx(d.src);x&&we.set(d,x)}const Ke=d=>{const x=we.get(d),C=De(d);if(!x||!C)return null;try{return new w({...d.align==="center"?{alignment:D.CENTER}:d.align==="right"?{alignment:D.RIGHT}:{},children:[new re({type:x.type,data:x.data,...d.alt?{altText:{name:d.alt,description:d.alt,title:d.alt}}:{},transformation:{width:Math.max(1,Math.round(C.width)),height:Math.max(1,Math.round(C.height))}})]})}catch{return null}},tt=(d,x,C,N)=>{const A=P=>C?(e.chromeImages??[]).filter(_=>_.side===C&&_.slot===P&&(!N?.bandOnly||_.fit==="band")&&Be(_,N?.sectionIndex)).map(Ke).filter(_=>_!==null):[],V={};for(const P of["default","first","even"]){const _=[...(d?.[P]??[]).map(ct),...A(P)];_.length>0&&(V[P]=new x({children:_}))}return Object.keys(V).length>0?V:void 0},ft=(d,x)=>(e.chrome??[]).some(C=>C.slot===d&&(x==="any"||C.sectionIndex===void 0)&&(d==="first"||hn(C)))||Array.from(we.keys()).some(C=>C.slot===d),ge=!!(e.headers?.first||e.footers?.first)||ft("first","unscoped"),dt=!!(e.headers?.even||e.footers?.even)||ft("even","any");ge&&(he.titlePage=!0);const Ce={},ye=this.buildDocxNumberingConfig(e,{AlignmentType:D,LevelFormat:k,LevelSuffix:H}),rt=new Set,wt=new Set;for(const d of JSON.stringify(e).matchAll(/docxrev-(\d+)/g))wt.add(Number(d[1]));let Ze=1e5;const Fe=d=>{if(d!==void 0&&!rt.has(d))return rt.add(d),d;for(;rt.has(Ze)||wt.has(Ze);)Ze++;return rt.add(Ze),Ze};let Ve=!1;const _e=d=>{const x={};return d.bold!==void 0&&(x.bold=d.bold),d.italic!==void 0&&(x.italics=d.italic),d.underline&&(x.underline={type:d.underline==="NONE"?"none":E.SINGLE}),d.strike!==void 0&&(x.strike=d.strike),d.doubleStrike!==void 0&&(x.doubleStrike=d.doubleStrike),d.smallCaps!==void 0&&(x.smallCaps=d.smallCaps),d.allCaps!==void 0&&(d.smallCaps!==void 0?(x.snapToGrid=d.allCaps,Ve=!0):x.allCaps=d.allCaps),d.vanish===!0?x.vanish=!0:d.vanish===!1&&(x.specVanish=!0,Ve=!0),d.lang&&(x.language={value:d.lang}),d.characterSpacing?x.characterSpacing=d.characterSpacing:d.characterSpacing===0&&(x.imprint=!0,Ve=!0),d.superScript&&(x.superScript=!0),d.subScript&&(x.subScript=!0),d.baseline&&(x.emboss=!0,Ve=!0),d.rightToLeft&&(x.rightToLeft=!0),d.color&&(x.color=d.color),d.highlight&&(x.highlight=d.highlight),d.font&&(x.font=d.font.split(",")[0].replaceAll("'","").replaceAll('"',"")),d.size&&(x.size=d.size),d.characterStyle&&(x.style=d.characterStyle),x};let it=0,nt=1e5;const pt=new Set((e.sdtWrappers??[]).filter(d=>d.scope==="inline").map(d=>d.id)),ht=new Map,bt=[],Ne=[],ot=[],si=(d,x,C,N)=>{const A=`${d.name}\0${d.role}\0${d.rangeId}`,V=ht.get(A);if(V){V.wrapperIds.push(x);return}ht.set(A,{name:d.name,role:d.role,rangeId:d.rangeId,author:d.rangeAuthor??C,date:typeof d.rangeCreatedAt=="number"?new Date(d.rangeCreatedAt).toISOString():N,wrapperIds:[x]})},Xt=d=>{const x=P=>P?.sdtInline?.split(",").filter(_=>_&&pt.has(_))??[],C=new Map,N=d.children.flatMap((P,_)=>{if(P.mathOmml)return G(P.mathOmml);const Y={text:P.text,..._e(P)};P.break&&(Y.break=1),P.footnoteReference!==void 0&&(delete Y.text,Y.style??(Y.style="FootnoteReference"),Y.children=[new v(P.footnoteReference)]),P.rPrChange&&(Y.revision={id:Fe(P.rPrChange.importedId),author:P.rPrChange.author,date:P.rPrChange.date,..._e(P.rPrChange.prior)});const U=()=>{let ne;if(P.revision){const ae=Fe(P.revision.importedId),Re={...Y,id:ae,author:P.revision.author,date:P.revision.date};P.revision.kind==="delete"&&P.revision.layeredInsertion&&ot.push({deletionId:ae,insertionId:Fe(P.revision.layeredInsertion.importedId),author:P.revision.layeredInsertion.author,date:P.revision.layeredInsertion.date}),P.revision.move&&si(P.revision.move,ae,P.revision.author,P.revision.date),ne=P.revision.kind==="delete"?new b(Re):new m(Re)}else ne=new u(Y);return P.oxmlRPr&&Z(ne,"w:rPr",P.oxmlRPr),ne},oe=P.link?(()=>{Y.underline??(Y.underline={type:E.SINGLE}),Y.color??(Y.color="2563EB");const ne=[U()];return P.link.startsWith("#")?new W({anchor:P.link.slice(1),children:ne}):new O({link:P.link,children:ne})})():U(),te=[];for(const ne of wr.get(P)??[]){const ae=Oe.get(ne);ae!==void 0&&te.push(new c(ae))}const me=x(d.children[_-1]),ee=x(P),Ye=x(d.children[_+1]);for(const ne of[...ee].reverse()){if(me.includes(ne))continue;const ae={name:`__rvSdt:${ne}:${it++}`,numericId:nt++};C.set(ne,ae),te.push(new g(ae.name,ae.numericId))}for(const ne of Gt.get(P)??[])te.push(new g(ne,jt.get(ne)));for(const ne of Ut.get(P)??[]){const ae=be(Dt.get(ne).startXml);ae&&te.push(ae)}const He=Vt.has(d),se=P.fieldInstr;se&&!He&&d.children[_-1]?.fieldInstr!==se&&te.push(...Sr(se)),te.push(oe),se&&!He&&d.children[_+1]?.fieldInstr!==se&&te.push(...Ir());for(const ne of Kt.get(P)??[]){const ae=be(Dt.get(ne).endXml);ae&&te.push(ae)}for(const ne of Jt.get(P)??[])te.push(new f(jt.get(ne)));for(const ne of ee){if(Ye.includes(ne))continue;const ae=C.get(ne);ae&&(te.push(new f(ae.numericId)),C.delete(ne))}for(const ne of br.get(P)??[]){const ae=Oe.get(ne);ae!==void 0&&(te.push(new p(ae)),te.push(new u({children:[new h(ae)]})))}return te});for(const P of Ht.get(d.sourceBlockId??"")??[]){const _=Oe.get(P);_!==void 0&&(N.push(new c(_)),N.push(new p(_)),N.push(new u({children:[new h(_)]})))}if(Zt.has(d)&&N.unshift(...Sr(Zt.get(d))),d.inTableCell&&d.paragraphPropertiesChange){const P=`__rvPp:${bt.length}`,_=nt++;bt.push({pIndex:-1,marker:P,...d.paragraphPropertiesChange}),N.unshift(new g(P,_),new f(_))}if((d.inTableCell||d.inNote)&&d.paragraphMarkRevision){const P=`__rvPm:${Ne.length}`,_=nt++;Ne.push({name:P,...d.paragraphMarkRevision}),N.unshift(new g(P,_),new f(_))}xr.has(d)&&N.push(...Ir());const A={children:N};if(d.children.length>0&&d.children.every(P=>!P.text&&!P.break&&!P.mathOmml&&P.footnoteReference===void 0)){const P=d.children.find(_=>_.size||_.font);if(P){const{size:_,font:Y}=_e({size:P.size,font:P.font});A.run={..._?{size:_}:{},...Y?{font:Y}:{}}}}if(d.keepNext&&(A.keepNext=!0),d.keepLines&&(A.keepLines=!0),d.widowControl===!1&&(A.widowControl=!1),d.bidirectional!==void 0&&(A.bidirectional=d.bidirectional),d.tabStopsJson){const P=gn(d.tabStopsJson);if(P){const _={left:s.LEFT,right:s.RIGHT,center:s.CENTER,decimal:s.DECIMAL},Y={dot:l.DOT,hyphen:l.HYPHEN,underscore:l.UNDERSCORE};A.tabStops=P.map(U=>({type:_[U.align]??s.LEFT,position:Math.round(U.pos*15),...U.leader?{leader:Y[U.leader]}:{}}))}}if(d.bordersJson)try{const P=JSON.parse(d.bordersJson),_=U=>{switch(U){case"dashed":return j.DASHED;case"dotted":return j.DOTTED;case"double":return j.DOUBLE;case"none":return j.NONE;default:return j.SINGLE}},Y={};for(const U of["top","bottom","left","right"]){const oe=P[U];oe&&(Y[U]={style:_(oe.style),size:oe.style==="none"?0:Math.max(1,Math.round((oe.width??1)*6)),color:this.toDocxHex(oe.color)??"auto"})}Object.keys(Y).length>0&&(A.border=Y)}catch{}if(d.shadingFill){const P=this.toDocxHex(d.shadingFill);A.shading=P?{type:K.CLEAR,fill:P}:{type:K.CLEAR,fill:"auto",color:"auto"}}if(d.heading&&!d.styleId){const P={HEADING_1:X.HEADING_1,HEADING_2:X.HEADING_2,HEADING_3:X.HEADING_3,HEADING_4:X.HEADING_4,HEADING_5:X.HEADING_5,HEADING_6:X.HEADING_6};A.heading=P[d.heading]}if(d.alignment){const P={LEFT:D.LEFT,CENTER:D.CENTER,RIGHT:D.RIGHT,JUSTIFIED:D.JUSTIFIED};A.alignment=P[d.alignment]}d.styleId?A.style=d.styleId:d.style&&(A.style=d.style),d.lineSpacing!==void 0&&(A.spacing={...A.spacing,line:Math.round(d.lineSpacing*240)}),d.spacingBeforeTwips!==void 0&&(A.spacing={...A.spacing,before:d.spacingBeforeTwips}),d.spacingAfterTwips!==void 0&&(A.spacing={...A.spacing,after:d.spacingAfterTwips}),d.contextualSpacing&&(A.contextualSpacing=!0),d.indent&&(A.indent={...A.indent,...d.indent}),d.list&&(d.list.variant==="todo"?A.indent=this.getListIndentOptions(d.list.level):d.list.reference&&(A.numbering={reference:d.list.reference,level:d.list.level,instance:d.list.instance??0}));const V=new w(A);return d.oxmlPPr&&Z(V,"w:pPr",d.oxmlPPr),d.oxmlAttrs&&Se(V,d.oxmlAttrs),V},gr=d=>{const x=Number.isFinite(d.borderWidth)?Math.max(0,Math.round(d.borderWidth)):1,C=x>0?{style:j.SINGLE,size:Math.max(1,x*6),color:this.toDocxHex(d.borderColor)??"D1D5DB"}:{style:j.NONE,size:0,color:"auto"},N=ee=>{const Ye={single:j.SINGLE,dashed:j.DASHED,dotted:j.DOTTED,double:j.DOUBLE,none:j.NONE};return ee.style==="none"||ee.width<=0?{style:j.NONE,size:0,color:"auto"}:{style:Ye[ee.style]??j.SINGLE,size:Math.max(1,Math.round(ee.width*6)),color:this.toDocxHex(ee.color)??"auto"}},A=or(d.borders),V=A?{top:N(A.top??{style:"single",width:1,color:"#d1d5db"}),bottom:N(A.bottom??{style:"single",width:1,color:"#d1d5db"}),left:N(A.left??{style:"single",width:1,color:"#d1d5db"}),right:N(A.right??{style:"single",width:1,color:"#d1d5db"}),insideHorizontal:N(A.insideH??{style:"single",width:1,color:"#d1d5db"}),insideVertical:N(A.insideV??{style:"single",width:1,color:"#d1d5db"})}:void 0,P=d.rows.map(ee=>{const Ye=ee.cells.map((se,ne)=>{const ae=se.blocks??se.paragraphs,Re=ae.map(Me=>Me.type==="table"?gr(Me):Xt(Me));(Re.length===0||ae[ae.length-1]?.type==="table")&&Re.push(new w({}));const st=Math.max(d.columnWidths.length,1),Ci=se.colSpan??1,Ar=se.gridColumn??ne;let Tr=0;for(let Me=Ar;Me<Ar+Ci;Me++)Tr+=d.columnWidths[Me]||100/st;const je={children:Re,width:{size:Tr,type:$.PERCENTAGE}};se.verticalAlign&&(je.verticalAlign=se.verticalAlign==="middle"?"center":se.verticalAlign);const Ge=un(se.borders);if(Ge){const Me={};Ge.top&&(Me.top=N(Ge.top)),Ge.bottom&&(Me.bottom=N(Ge.bottom)),Ge.left&&(Me.left=N(Ge.left)),Ge.right&&(Me.right=N(Ge.right)),je.borders=Me}else V||(je.borders={top:C,bottom:C,left:C,right:C});const Pt=fn(se.padding);Pt&&(je.margins={marginUnitType:$.DXA,top:Math.round(Pt.top*15),bottom:Math.round(Pt.bottom*15),left:Math.round(Pt.left*15),right:Math.round(Pt.right*15)}),se.colSpan&&se.colSpan>1&&(je.columnSpan=se.colSpan),se.rowSpan&&se.rowSpan>1&&(je.rowSpan=se.rowSpan);const er=this.toDocxHex(se.backgroundColor);er?je.shading={type:K.SOLID,color:er,fill:er}:ee.isHeader&&!se.backgroundColor&&(je.shading={type:K.SOLID,color:"F9FAFB",fill:"F9FAFB"});const Mr=new z(je);return se.oxmlTcPr&&Z(Mr,"w:tcPr",se.oxmlTcPr),Mr}),He=new R({children:Ye,tableHeader:ee.isHeader===!0?!0:void 0});return ee.oxmlTrPr&&Z(He,"w:trPr",ee.oxmlTrPr),ee.oxmlAttrs&&Se(He,ee.oxmlAttrs,"w:trPr"),He}),_=typeof d.tableWidth=="number"&&Number.isFinite(d.tableWidth)&&d.tableWidth>0?Math.round(d.tableWidth*15):void 0,Y=_??9e3,U=d.columnWidths.filter(ee=>Number.isFinite(ee)&&ee>0).map(ee=>Math.max(1,Math.round(ee/100*Y))),oe=d.align==="center"?D.CENTER:d.align==="right"?D.RIGHT:d.align==="left"?D.LEFT:void 0,te=typeof d.cellPadding=="number"&&Number.isFinite(d.cellPadding)&&d.cellPadding>=0?{marginUnitType:$.DXA,top:Math.round(d.cellPadding*15),bottom:Math.round(d.cellPadding*15),left:Math.round(d.cellPadding*15),right:Math.round(d.cellPadding*15)}:void 0,me=new S({rows:P,width:_?{size:_,type:$.DXA}:{size:100,type:$.PERCENTAGE},...U.length===d.columnWidths.length&&U.length>0?{columnWidths:U}:{},...oe?{alignment:oe}:{},...te?{margins:te}:{},borders:V??{top:C,bottom:C,left:C,right:C,insideHorizontal:C,insideVertical:C}});return d.oxmlTblPr&&Z(me,"w:tblPr",d.oxmlTblPr),me},ai=d=>{const x=d.split(",")[1]||"";if(typeof atob!="function")throw new Error("Base64 decoding is unavailable in this environment");const C=atob(x),N=new Uint8Array(C.length);for(let A=0;A<C.length;A++)N[A]=C.charCodeAt(A);return N},li=d=>{if(d.renderDiagram)return d.diagramPngDataUrl?new w({children:[new re({type:"png",data:ai(d.diagramPngDataUrl),transformation:{width:Math.max(120,Math.round(d.diagramWidth||600)),height:Math.max(60,Math.round(d.diagramHeight||180))}})],spacing:{before:120,after:120}}):new w({children:[new u({text:"Diagram unavailable"})],spacing:{before:120,after:120}});const x=d.runs.map(N=>{const A={text:N.text,font:N.font||"Courier New"};return N.color&&(A.color=N.color),N.break&&(A.break=N.text.split(`
|
|
8
|
+
`).length-1,A.text=""),new u(A)}),C=this.toDocxHex(d.backgroundColor)??"F5F5F5";return new w({children:x,...d.styleId?{style:d.styleId}:{},shading:{type:K.SOLID,color:C,fill:C},spacing:{before:120,after:120}})},ci=d=>{if(!d.omml)return new w({children:[new u({text:d.content})],alignment:d.alignment==="center"?D.CENTER:d.alignment==="right"?D.RIGHT:D.LEFT});const x=G(d.omml);return new w({children:[x],alignment:d.alignment==="center"?D.CENTER:d.alignment==="right"?D.RIGHT:D.LEFT,spacing:{before:120,after:120}})},At=[],Tt=[],di=d=>{if(!d.anchorXml)return;const x=`__revise-anchor:${Tt.length}__`;return Tt.push({marker:x,anchorXml:d.anchorXml}),x},Mt=d=>({alignment:d.align==="center"?D.CENTER:d.align==="right"?D.RIGHT:D.LEFT,spacing:{before:120,after:120}}),pi=async d=>{const x=di(d);if(d.originalFormat&&d.originalDataUrl){const N=`__revise-original-media:${At.length}__`;return At.push({marker:N,format:d.originalFormat,dataUrl:d.originalDataUrl,alt:d.alt}),new w({children:[new re({type:"png",data:this.base64ToUint8Array(oi),altText:{name:d.alt||"Image",description:N,title:x??d.alt},transformation:{width:Math.max(1,Math.round(d.width)),height:Math.max(1,Math.round(d.height))}})],...Mt(d)})}if(d.src.match(/^data:image\/svg\+xml(;base64)?,/i)){const N=this.dataUrlToUint8Array(d.src);if(N){const A=Math.max(1,Math.round(d.width)),V=Math.max(1,Math.round(d.height)),P=await this.rasterizeSvgDataUrlToPng(d.src,A,V)??this.base64ToUint8Array(oi);return new w({children:[new re({type:"svg",data:N,fallback:{type:"png",data:P},altText:{name:d.alt||"Image",description:d.alt,title:x??d.alt},transformation:{width:A,height:V}})],...Mt(d)})}}const C=await this.resolveImageSourceForDocx(d.src);return C?new w({children:[new re({type:C.type,data:C.data,altText:{name:d.alt||"Image",description:d.alt,title:x??d.alt},transformation:{width:Math.max(1,Math.round(d.width)),height:Math.max(1,Math.round(d.height))}})],...Mt(d)}):new w({children:[new u({text:d.alt||"Image unavailable"})],...Mt(d)})},hi=()=>new w({children:[new I]}),yt=[...e.notes??[],...e.children.filter(d=>d.type==="footnote")],vt=new Map;for(const d of yt)vt.set(d.id,d.noteKind==="endnote"?"endnote":"footnote");const gi=yt.filter(d=>vt.get(d.id)==="footnote"),xt=yt.filter(d=>vt.get(d.id)==="endnote"),Et=new Map,gt=new Map;{const d=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(d);return}const C=x;if(C.type==="footnote")return;const N=C.marks?.footnoteRef;if(N){const A=vt.get(N)==="endnote"?gt:Et;A.has(N)||A.set(N,A.size+1)}d(C.children)};d(e.children.filter(x=>x.type!=="footnote"))}for(const d of xt)gt.has(d.id)||gt.set(d.id,gt.size+1);const Xe=e.comments??[],Oe=new Map,mt=new Set;for(const d of Xe){const x=d.importedId;Number.isSafeInteger(x)&&x>=0&&x<=2147483647&&!mt.has(x)&&(mt.add(x),Oe.set(d.id,x))}let qe=0;for(const d of Xe)if(!Oe.has(d.id)){for(;mt.has(qe);)qe++;Oe.set(d.id,qe),mt.add(qe++)}const St=new Map,mr=d=>{const x=new Map(Xe.map(A=>[A.id,A]));let C=d;const N=new Set;for(;C.parentId&&!N.has(C.id);){N.add(C.id);const A=x.get(C.parentId);if(!A)break;C=A}return C.id};for(const d of Xe){const x=mr(d),C=St.get(x)??[];C.includes(d.id)||C.push(d.id),St.set(x,C)}const mi=e.children.some(d=>d.type==="header-footer");let ze=yt.length>0||mi?{...e,children:e.children.filter(d=>d.type!=="footnote"&&d.type!=="header-footer")}:e;if(yt.length>0){ze=JSON.parse(JSON.stringify(ze));const d=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(d);return}const C=x,N=C.marks?.footnoteRef;if(N)if(vt.get(N)==="endnote"){const A=gt.get(N)??1;C.text=`__RVSE_EN_${A}__`,C.marks&&(delete C.marks.footnoteRef,C.marks.superscript=!0)}else C.text=String(Et.get(N)??1);d(C.children)};d(ze.children)}this.hasDocxMoveMarks(ze.children)&&(ze=JSON.parse(JSON.stringify(ze)),this.finalizeImportedMovePairs(ze.children));const ur=this.collectTableRevisionPatches(ze),zt=t?.graft?[]:void 0,It=this.toDocxFormatWithTables(ze,r,t?.headingPageNumbers,zt),kt=[],fr=d=>{for(const x of d){if(x.type==="paragraph"){kt.push(x);continue}for(const C of x.rows)for(const N of C.cells)fr(N.blocks??N.paragraphs)}};fr(It.filter(d=>d.type==="paragraph"||d.type==="table"));const wr=new Map,br=new Map,Ht=new Map,yr=[];{const d=[];for(const P of kt)d.push(...P.children);const x=P=>(P.text??"")===""&&!P.break&&!P.mathOmml&&P.footnoteReference===void 0&&!P.fieldInstr,C=new Map;for(const[P,_]of St)for(const Y of _)C.set(Y,P);const N=new Map;d.forEach((P,_)=>{const Y=new Set((P.comment?.split(",")??[]).filter(Boolean).map(U=>C.get(U)??U));for(const U of Y){const oe=N.get(U)??[],te=oe[oe.length-1];let me=!!te;for(let ee=te?te.lastIndex+1:_;ee<_;ee++)if(!x(d[ee])){me=!1;break}te&&me?(te.last=P,te.lastIndex=_):oe.push({first:P,last:P,lastIndex:_}),N.set(U,oe)}});const A=new Set,V=(P,_,Y)=>P.set(_,[...P.get(_)??[],...Y]);for(const[P,_]of N){const Y=St.get(P)??[P];Y.forEach(U=>A.add(U)),_.forEach((U,oe)=>{let te=Y;if(oe>0){if(!Oe.has(P))return;const me=`${P}\0fragment${oe}`;for(;mt.has(qe);)qe++;Oe.set(me,qe),mt.add(qe++),yr.push({cloneId:me,sourceId:P}),te=[me]}V(wr,U.first,te),V(br,U.last,te)})}for(const P of Xe){const _=P.anchorBlockId;if(!_||A.has(P.id))continue;const Y=St.get(P.id)??[P.id],U=Ht.get(_)??[];for(const oe of Y)U.includes(oe)||U.push(oe);Ht.set(_,U)}}const ui=new Map(Xe.map(d=>[d.id,d])),vr=[...Xe.map(d=>({id:d.id,record:d,isClone:!1})),...yr.map(({cloneId:d,sourceId:x})=>({id:d,record:ui.get(x),isClone:!0}))],jt=new Map,Gt=new Map,Jt=new Map;{const d=new Map,x=new Map;for(const N of kt)for(const A of N.children)for(const V of A.bookmark?.split(",")??[])V&&(d.has(V)||d.set(V,A),x.set(V,A));let C=1;for(const[N,A]of d)jt.set(N,C++),Gt.set(A,[...Gt.get(A)??[],N]);for(const[N,A]of x)Jt.set(A,[...Jt.get(A)??[],N])}const Ut=new Map,Kt=new Map,Dt=new Map((e.oxmlRanges??[]).filter(d=>d.startXml&&d.endXml).map(d=>[d.id,d]));if(Dt.size>0){const d=new Map,x=new Map;for(const C of kt)for(const N of C.children)for(const A of N.oxmlRange?.split(",")??[])!A||!Dt.has(A)||(d.has(A)||d.set(A,N),x.set(A,N));for(const[C,N]of d)Ut.set(N,[...Ut.get(N)??[],C]);for(const[C,N]of x)Kt.set(N,[...Kt.get(N)??[],C])}const fi=d=>{const x=d.children.filter(N=>(N.text??"")!==""||N.fieldInstr);if(x.length===0)return;const C=x[0].fieldInstr;if(!(!C||!/^TOC\b/i.test(C.trim())))return x.every(N=>N.fieldInstr===C)?C:void 0},Zt=new Map,xr=new Set,Vt=new Set;{let d,x=[];const C=()=>{d&&x.length>0&&(Zt.set(x[0],d),xr.add(x[x.length-1]),x.forEach(N=>Vt.add(N))),d=void 0,x=[]};for(const N of It){const A=N.type==="paragraph"?N:void 0,V=A?fi(A):void 0;if(A&&V&&V===d){x.push(A);continue}C(),A&&V&&(d=V,x=[A])}C()}const Bt=d=>{const x=`<root><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${d}</w:r></root>`,C=J.fromXmlString(x).root?.[0];if(C?.root){for(const N of C.root)if(N?.rootKey==="w:r")return N}},wi=d=>d.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),Sr=d=>[Bt('<w:fldChar w:fldCharType="begin"/>'),Bt(`<w:instrText xml:space="preserve"> ${wi(d)} </w:instrText>`),Bt('<w:fldChar w:fldCharType="separate"/>')].filter(Boolean),Ir=()=>[Bt('<w:fldChar w:fldCharType="end"/>')].filter(Boolean),bi=Vt.size>0||kt.some(d=>d.children.some(x=>x.fieldInstr)),yi=d=>{if(cr(d.xml))return new w({});try{const x=d.origin==="run"?`<root><w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r>${d.xml}</w:r></w:p></root>`:`<root>${d.xml}</root>`,C=J.fromXmlString(x).root?.[0];for(const N of C?.root??[])if(N?.rootKey&&N.rootKey!=="_attr")return N}catch{}return new w({})},kr=async d=>d.type==="table"?gr(d):d.type==="codeblock"?li(d):d.type==="mathblock"?ci(d):d.type==="pagebreak"?hi():d.type==="sectionbreak"?null:d.type==="image"?pi(d):d.type==="docxraw"?yi(d):Xt(d),vi=await Promise.all(It.map(kr)),qt={},Rt=new Map,Pr=d=>{for(const x of d)if(x.type==="paragraph"&&x.list?.reference){const C=`${x.list.reference}\0${x.list.instance??0}`;Rt.has(C)||Rt.set(C,x.list)}else if(x.type==="table")for(const C of x.rows)for(const N of C.cells)Pr(N.blocks??N.paragraphs)},Cr=async(d,x)=>{const C=this.toDocxFormatWithTables({...e,children:d.children},r);Pr(C);for(const A of C)A.type==="paragraph"&&(A.inNote=!0);const N=(await Promise.all(C.map(kr))).filter(A=>A!==null).map(A=>A);qt[String(x)]={children:N.length>0?N:[new w({})]}};let xi=Et.size;for(const d of gi){const x=Et.get(d.id)??++xi;await Cr(d,x)}const Nr=new Map;for(let d=0;d<xt.length;d++){const x=xt[d],C=1e6+d;Nr.set(x.id,C),await Cr(x,C)}const Yt=[...Rt.keys()],Si=Yt.map((d,x)=>Xt({type:"paragraph",children:[{text:`__RVSE_NOTE_NUM_${x}__`}],list:Rt.get(d)}));{const d=Lr(e.chrome??[]),x=tt(e.headers??d.headers,y,"header"),C=tt(e.footers??d.footers,T,"footer");x&&(Ce.headers=x),C&&(Ce.footers=C),e.watermark&&!Ce.headers&&(Ce.headers={default:new y({children:[new w({})]})}),fe.showPageNumbers&&(fe.pageNumberPosition.startsWith("top")&&!Ce.headers?Ce.headers={default:new y({children:[Le]})}:!fe.pageNumberPosition.startsWith("top")&&!Ce.footers&&(Ce.footers={default:new T({children:[Le]})}))}const Te=e.coreProperties??{},Ii={...Te.title!==void 0?{title:Te.title}:{},...Te.subject!==void 0?{subject:Te.subject}:{},...Te.creator!==void 0?{creator:Te.creator}:{},...Te.keywords!==void 0?{keywords:Te.keywords}:{},...Te.description!==void 0?{description:Te.description}:{},...Te.lastModifiedBy!==void 0?{lastModifiedBy:Te.lastModifiedBy}:{}},ki=new n({...Ii,...e.pageLayout?.blockSpacingPx!==void 0?{customProperties:[{name:"Revise.BlockSpacingPx",value:String(Ee(e.pageLayout).blockSpacingPx)}]}:{},numbering:ye,...bi?{features:{updateFields:!0}}:{},...dt?{evenAndOddHeaderAndFooters:!0}:{},...Xe.length>0?{comments:{children:vr.map(({id:d,record:x})=>({id:Oe.get(d),author:x.author,...x.initials?{initials:x.initials}:{},date:new Date(x.createdAt),children:(x.bodyMd||" ").split(/\n\n+/).map(C=>new w({children:[new u({text:C})]}))}))}}:{},...Object.keys(qt).length>0?{footnotes:qt}:{},styles:{default:{document:{run:{size:this.DEFAULT_RUN_SIZE_HALF_POINTS}},...this.buildExportHeadingDefaults()},paragraphStyles:this.buildExportParagraphStyles(e),characterStyles:this.buildExportCharacterStyles()},sections:(()=>{const d=e.chrome??[],x=ji(d),C=U=>{if(["header","footer"].some(te=>mn(d,te,"first",U)))return!0;if(!x)return ge;if(Array.from(we.keys()).some(te=>te.slot==="first"&&te.fit==="band"))return!0;const oe=Xr(d,U);return!!(oe.headers?.first||oe.footers?.first)},N=new Map,A=U=>{let oe="";if(!x){if(!Nt)return Ce;const se=(e.chromeImages??[]).flatMap((ae,Re)=>we.has(ae)&&!Be(ae,U)?[Re]:[]);if(se.length===0)return Ce;oe=se.join(",");const ne=N.get(oe);if(ne)return ne}const te=x?Xr(d,U):(()=>{const se=Lr(d);return{headers:e.headers??se.headers,footers:e.footers??se.footers}})(),me={sectionIndex:U,bandOnly:x},ee={},Ye=tt(te.headers,y,"header",me),He=tt(te.footers,T,"footer",me);Ye&&(ee.headers=Ye),He&&(ee.footers=He),e.watermark&&!ee.headers&&(ee.headers={default:new y({children:[new w({})]})}),fe.showPageNumbers&&(fe.pageNumberPosition.startsWith("top")&&!ee.headers?ee.headers={default:new y({children:[Le]})}:!fe.pageNumberPosition.startsWith("top")&&!ee.footers&&(ee.footers={default:new T({children:[Le]})}));for(const[se,ne,ae]of[["header","headers",y],["footer","footers",T]])for(const Re of["default","first","even"])ee[ne]?.[Re]||!(e.chromeImages??[]).some(st=>st.side===se&&st.slot===Re&&we.has(st)&&(!x||st.fit==="band")&&!Be(st,U))||(ee[ne]={...ee[ne]??{},[Re]:new ae({children:[new w({})]})});return x||N.set(oe,ee),ee},V=[];let P=[],_;It.forEach((U,oe)=>{if("type"in U&&U.type==="sectionbreak"){const me=U;ve.push(Gi(e.pageLayout,me.layout));const ee=ie(me.layout,_,V.length===0?"first":"middle");C(V.length)&&(ee.titlePage=!0),V.push({properties:ee,...A(V.length),children:P}),P=[],_=me.breakType;return}const te=vi[oe];te!=null&&P.push(te)}),ve.push(Ji(e.pageLayout));const Y=V.length===0?he:ie(e.pageLayout,_,"final");return C(V.length)?Y.titlePage=!0:x&&Y===he&&delete Y.titlePage,V.push({properties:Y,...A(V.length),children:[...P,...Si]}),V})()}),Pi=await this.stabilizeHyperlinkRelIds(await this.stabilizeAttributeWhitespace(await a.toBlob(ki))),Lt=[],Qt=[...bt];let ut=0;for(const d of It){if("type"in d&&d.type==="table")continue;if("type"in d&&d.type==="docxraw"){d.emitsParagraph&&ut++;continue}if("type"in d&&d.type==="sectionbreak"){const N=d.pendingDeletion;N&&Lt.push({pIndex:ut,kind:"merge",...N}),ut++;continue}const x=d.paragraphMarkRevision;x&&Lt.push({pIndex:ut,...x});const C=d.paragraphPropertiesChange;C&&Qt.push({pIndex:ut,...C}),ut++}let Q=Pi;if(ht.size>0&&(Q=await this.patchLinkedMoveRevisions(Q,Array.from(ht.values()))),Yt.length>0&&(Q=await this.patchNoteNumberingReferences(Q,Yt)),Ve&&(Q=await this.patchRunPropertyResetMarkers(Q)),Ne.length>0&&(Q=await this.patchMarkedParagraphMarkRevisions(Q,Ne.map(d=>({...d,id:Fe(d.importedId)})))),ot.length>0&&(Q=await this.patchLayeredDeletions(Q,ot)),de.length>0&&(Q=await this.applyOxmlAttrMarkers(Q,de)),ve.some(d=>d)&&(Q=await this.injectSectPrOpaquePayloads(Q,ve)),Tt.length>0)try{Q=await this.patchAnchoredImages(Q,Tt)}catch(d){console.warn("docx export: anchored-image restore failed; exporting images inline",d)}if(At.length>0)try{Q=await this.patchOriginalVectorImages(Q,At)}catch(d){console.warn("docx export: EMF/WMF original-media patch failed; exporting placeholder images",d)}if(Lt.length>0)try{Q=await this.patchParagraphMarkRevisions(Q,Lt,Fe)}catch(d){console.warn("docx export: paragraph-mark revision patch failed; exporting without pilcrow markup",d)}if(Qt.length>0)try{Q=await this.patchParagraphPropertyChanges(Q,Qt,Fe)}catch(d){console.warn("docx export: w:pPrChange patch failed; exporting without paragraph property-change markup",d)}if(ur.length>0)try{Q=await this.patchTableRevisions(Q,ur,Fe)}catch(d){console.warn("docx export: table revision patch failed; exporting table content without revision markup",d)}if(Xe.length>0)try{Q=await this.appendCommentsExtendedPart(Q,vr.map(({id:d,record:x,isClone:C})=>{const N=!C&&x.parentId?mr(x):void 0;return{numericId:Oe.get(d),resolved:x.resolved===!0,parentNumericId:N&&N!==x.id?Oe.get(N):void 0}}))}catch(d){console.warn("docx export: commentsExtended generation failed; comments export flat/unresolved",d)}if(xt.length>0)try{Q=await this.appendEndnotesPart(Q,xt.map(d=>({index:gt.get(d.id),note:d,syntheticFootnoteId:Nr.get(d.id)})))}catch(d){console.warn("docx export: endnotes part generation failed; endnote markers left in text",d)}if(e.sdtWrappers&&e.sdtWrappers.length>0)try{Q=await this.applySdtWrappers(Q,e)}catch(d){console.warn("docx export: content-control wrapping failed; content exported unwrapped",d)}if(e.coreProperties)try{Q=await this.patchCoreProperties(Q,Te)}catch(d){console.warn("docx export: core-property patch failed; library defaults kept",d)}if(e.stylesXml)try{Q=await this.mergeImportedStyles(Q,e.stylesXml)}catch(d){console.warn("docx export: styles.xml merge failed; imported named styles dropped",d)}if(e.watermark)try{Q=await this.injectWatermarkIntoHeaders(Q,e.watermark)}catch(d){console.warn("docx export: watermark header injection failed; exporting without watermark",d)}if(Ee(e.pageLayout).hyphenationEnabled)try{Q=await this.injectAutoHyphenationSetting(Q)}catch(d){console.warn("docx export: autoHyphenation setting injection failed",d)}try{Q=await this.stampApplicationProperty(Q)}catch(d){console.warn("docx export: application stamp failed; exporting without it",d)}if(t?.graft&&zt){const d=x=>{try{t.graft?.onOutcome?.(x)}catch{}};if(!e.docxSource)return console.warn("docx export: graft requested but document has no docxSource capture; exporting regenerated package"),d({mode:"regenerated",fallbackCode:"no-capture"}),Q;try{Q=await Ui({generatedBlob:Q,originalDocx:t.graft.originalDocx,doc:e,blockRanges:zt});const x=Ki(e);d({mode:x.fullyExact?"exact":"grafted",regeneratedBlockCount:x.regeneratedBlockIds.length,changedDomains:Object.entries(x.domains).filter(([,C])=>!C).map(([C])=>C)})}catch(x){const C=x instanceof Zi?x.code:"internalError";console.warn(`docx export: OOXML graft rejected [${C}]; exporting regenerated package`,x),d({mode:"regenerated",fallbackCode:C})}}return Q}static async patchNoteNumberingReferences(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");const a=new Map;n=n.replace(/<w:p\b[^>]*>[\s\S]*?<\/w:p>/g,l=>{const c=/__RVSE_NOTE_NUM_(\d+)__/.exec(l);if(!c)return l;const p=Number(c[1]),h=/<w:numId\b[^>]*w:val="([^"]+)"/.exec(l)?.[1],g=r[p];return g&&h&&!h.startsWith("{")&&a.set(g,h),""}),t.file("word/document.xml",n);const o=l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(const[l,c]of Object.entries(t.files)){if(!l.startsWith("word/")||!l.endsWith(".xml")||c.dir)continue;let p=await c.async("text"),h=!1;for(const[g,f]of a){const[w,u]=g.split("\0"),m=`{${w}-${u}}`,b=p.replace(new RegExp(`w:val="${o(m)}"`,"g"),`w:val="${f}"`);h||(h=b!==p),p=b}h&&t.file(l,p)}const s=await this.generateCompressedZipBlob(t);return new Blob([s],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectSectPrOpaquePayloads(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text"),a=0;n=n.replace(/<w:sectPr\b[^>]*>[\s\S]*?<\/w:sectPr>|<w:sectPr\b[^>]*\/>/g,c=>{const p=r[a++];return p?c.endsWith("/>")?`${c.slice(0,-2)}>${p}</w:sectPr>`:c.replace(/<\/w:sectPr>$/,`${p}</w:sectPr>`):c});const o=new DOMParser().parseFromString(n,"application/xml"),s=new Set(["w:lnNumType","w:pgNumType","w:cols","w:formProt","w:vAlign","w:noEndnote","w:titlePg","w:textDirection","w:bidi","w:rtlGutter","w:docGrid","w:printerSettings","w:sectPrChange"]);for(const c of Array.from(o.getElementsByTagName("w:sectPr"))){const p=Array.from(c.children).find(g=>g.tagName==="w:pgBorders"),h=Array.from(c.children).find(g=>s.has(g.tagName));p&&h&&c.insertBefore(p,h)}n=new XMLSerializer().serializeToString(o),t.file("word/document.xml",n);const l=await this.generateCompressedZipBlob(t);return new Blob([l],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeAttributeWhitespace(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}const{stabilizeSerializedXml:t}=await Promise.resolve().then(()=>bn);let i=!1;for(const[a,o]of Object.entries(r.files)){if(!a.endsWith(".xml")||o.dir)continue;const s=await o.async("text"),l=t(s);l!==s&&(r.file(a,l),i=!0)}if(!i)return e;const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeHyperlinkRelIds(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}let t=!1;for(const[n,a]of Object.entries(r.files)){const o=/^(.*)_rels\/([^/]+)\.rels$/.exec(n);if(!o||a.dir)continue;const s=`${o[1]}${o[2]}`,l=r.file(s);if(!l)continue;let c=await a.async("text");const p=[];for(const f of c.matchAll(/<Relationship\b[^>]*\/?>/g)){if(!/Type="[^"]*\/hyperlink"/.test(f[0]))continue;const w=/Id="([^"]+)"/.exec(f[0])?.[1];w&&p.push(w)}if(p.length===0)continue;let h=await l.async("text");const g=[...p].sort((f,w)=>{const u=h.indexOf(`"${f}"`),m=h.indexOf(`"${w}"`);return(u<0?1/0:u)-(m<0?1/0:m)});g.forEach((f,w)=>{f!==`rvseLnk${w+1}`&&(h=h.replaceAll(`r:id="${f}"`,`r:id="__rvseLnkTmp${w+1}__"`),c=c.replace(`Id="${f}"`,`Id="__rvseLnkTmp${w+1}__"`),t=!0)}),g.forEach((f,w)=>{h=h.replaceAll(`r:id="__rvseLnkTmp${w+1}__"`,`r:id="rvseLnk${w+1}"`),c=c.replace(`Id="__rvseLnkTmp${w+1}__"`,`Id="rvseLnk${w+1}"`)}),r.file(s,h),r.file(n,c)}if(!t)return e;const i=await this.generateCompressedZipBlob(r);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async applyOxmlAttrMarkers(e,r){const t=await this.loadZipFromBlob(e);for(const[n,a]of Object.entries(t.files)){if(!n.startsWith("word/")||!n.endsWith(".xml")||a.dir)continue;let o=await a.async("text");if(o.includes("<w:rvseOxmlAttrs ")){for(const s of["w:p","w:tr"])o=o.replace(new RegExp(`<${s}\\b([^>]*)>((?:(?!<${s}\\b)(?!</${s}>)[\\s\\S])*?)<w:rvseOxmlAttrs w:val="(\\d+)"/>`,"g"),(l,c,p,h)=>{const g=r[Number(h)];if(!g)return`<${s}${c}>${p}`;const f=new Set([...c.matchAll(/([\w:.-]+)=/g)].map(u=>u[1])),w=Vr(g,f);return`<${s}${c}${w}>${p}`});o=o.replace(/<w:rvseOxmlAttrs w:val="\d+"\/>/g,"").replace(/<w:pPr><\/w:pPr>|<w:pPr\/>/g,"").replace(/<w:trPr><\/w:trPr>|<w:trPr\/>/g,""),t.file(n,o)}}const i=await this.generateCompressedZipBlob(t);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchMarkedParagraphMarkRevisions(e,r){const t=await this.loadZipFromBlob(e),i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",n=new Map(r.map(o=>[o.name,o]));for(const o of["word/document.xml","word/footnotes.xml","word/endnotes.xml"]){const s=t.file(o);if(!s)continue;const l=await s.async("text");if(!l.includes("__rvPm:"))continue;const c=this.parseDocumentXml(l);if(!c)continue;const p=Array.from(c.getElementsByTagName("w:bookmarkStart"));for(const h of p){const g=n.get(h.getAttribute("w:name")??"");if(!g)continue;const f=h.getAttribute("w:id");let w=h.parentElement;for(;w&&w.tagName!=="w:p";)w=w.parentElement;for(const y of Array.from(c.getElementsByTagName("w:bookmarkEnd")))y.getAttribute("w:id")===f&&y.parentNode?.removeChild(y);if(h.parentNode?.removeChild(h),!w)continue;let u=Array.from(w.children).find(y=>y.tagName==="w:pPr");u||(u=c.createElementNS(i,"w:pPr"),w.insertBefore(u,w.firstChild));let m=Array.from(u.children).find(y=>y.tagName==="w:rPr");if(!m){m=c.createElementNS(i,"w:rPr");const y=Array.from(u.children).find(T=>T.tagName==="w:sectPr"||T.tagName==="w:pPrChange");u.insertBefore(m,y??null)}const b=g.kind==="split"||g.kind==="insert"?"w:ins":g.kind==="moveTo"?"w:moveTo":g.kind==="moveFrom"?"w:moveFrom":"w:del",v=c.createElementNS(i,b);v.setAttribute("w:id",String(g.id)),v.setAttribute("w:author",g.author),v.setAttribute("w:date",g.date),m.insertBefore(v,m.firstChild)}t.file(o,new XMLSerializer().serializeToString(c))}const a=await this.generateCompressedZipBlob(t);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLayeredDeletions(e,r){const t=o=>o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),i=new Map(r.map(o=>[o.deletionId,o])),n=await this.loadZipFromBlob(e);for(const[o,s]of Object.entries(n.files)){if(!o.startsWith("word/")||!o.endsWith(".xml")||s.dir)continue;const l=await s.async("text");if(!l.includes("<w:del "))continue;const c=l.replace(/<w:del\b[^>]*\bw:id="(\d+)"[^>]*(?<!\/)>[\s\S]*?<\/w:del>/g,(p,h)=>{const g=i.get(Number(h));return g?`<w:ins w:id="${g.insertionId}" w:author="${t(g.author)}" w:date="${g.date}">${p}</w:ins>`:p});c!==l&&n.file(o,c)}const a=await this.generateCompressedZipBlob(n);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchRunPropertyResetMarkers(e){const r=await this.loadZipFromBlob(e);for(const[i,n]of Object.entries(r.files)){if(!i.startsWith("word/")||!i.endsWith(".xml")||n.dir)continue;let a=await n.async("text");/<w:(?:specVanish|imprint|emboss|snapToGrid)\b/.test(a)&&(a=a.replace(/<w:specVanish\b[^>]*\/>/g,'<w:vanish w:val="false"/>').replace(/<w:imprint\b[^>]*\/>/g,'<w:spacing w:val="0"/>').replace(/<w:emboss\b[^>]*\/>/g,'<w:vertAlign w:val="baseline"/>').replace(/<w:snapToGrid\b([^>]*)\/>/g,(o,s)=>/\bw:val="(?:false|0|off)"/i.test(s)?'<w:caps w:val="false"/>':"<w:caps/>"),r.file(i,a))}const t=await this.generateCompressedZipBlob(r);return new Blob([t],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectAutoHyphenationSetting(e){const r=await this.loadZipFromBlob(e),t=r.file("word/settings.xml");if(!t)return e;let i=await t.async("text");if(i.includes("<w:autoHyphenation"))return e;i=i.replace(/<\/w:settings>/,"<w:autoHyphenation/></w:settings>"),r.file("word/settings.xml",i);const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}static dataUrlToUint8Array(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(!r)return;const t=r[3]||"";try{return r[2]?this.base64ToUint8Array(t):new TextEncoder().encode(decodeURIComponent(t))}catch{return}}static async resolveBinarySourceForDocx(e){const r=this.dataUrlToUint8Array(e);if(r)return r;if(typeof fetch=="function")try{const t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):void 0}catch{return}}static async rasterizeSvgDataUrlToPng(e,r,t){if(!(typeof document>"u"||typeof Image>"u"||typeof navigator<"u"&&navigator.userAgent?.includes("jsdom")))return new Promise(i=>{let n=!1;const a=l=>{n||(n=!0,i(l))},o=setTimeout(()=>a(void 0),3e3),s=new Image;s.onload=()=>{clearTimeout(o);try{const l=document.createElement("canvas");l.width=Math.max(1,Math.round(r)),l.height=Math.max(1,Math.round(t));const c=l.getContext("2d");if(!c){a(void 0);return}c.drawImage(s,0,0,l.width,l.height),l.toBlob(async p=>{if(!p){a(void 0);return}a(new Uint8Array(await p.arrayBuffer()))},"image/png")}catch{a(void 0)}},s.onerror=()=>{clearTimeout(o),a(void 0)},s.src=e})}static serializeXmlPreservingPrefixes(e){const r=new Map,t=(a,o)=>{const s=o.indexOf(":");if(s<=0)return;const l=o.slice(0,s);if(l==="xmlns"||l==="xml"||r.has(l))return;const c=a.lookupNamespaceURI(l);c&&r.set(l,c)},i=a=>{t(a,a.tagName);for(let o=0;o<a.attributes.length;o++)t(a,a.attributes[o].name);for(let o=0;o<a.children.length;o++)i(a.children[o])};i(e);const n=(a,o)=>{if(a.nodeType===3)return(a.nodeValue??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");if(a.nodeType!==1)return"";const s=a;let l=`<${s.tagName}`;const c=new Set;for(let h=0;h<s.attributes.length;h++){const g=s.attributes[h];g.name.startsWith("xmlns:")&&c.add(g.name.slice(6)),l+=` ${g.name}="${this.escapeXml(g.value)}"`}if(o)for(const[h,g]of r)c.has(h)||(l+=` xmlns:${h}="${this.escapeXml(g)}"`);const p=s.childNodes;if(p.length===0)return`${l}/>`;l+=">";for(let h=0;h<p.length;h++)l+=n(p[h],!1);return`${l}</${s.tagName}>`};return n(e,!0)}static async patchAnchoredImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("string"),a=!1;for(const o of r){const s=`title="${this.escapeXml(o.marker)}"`,l=n.indexOf(s);if(l===-1)continue;const c=()=>{n=n.replace(` ${s}`,""),a=!0},p=n.lastIndexOf("<wp:inline",l),h=n.indexOf("</wp:inline>",l);if(p===-1||h===-1){c();continue}const g=h+12,f=n.slice(p,g),w=Array.from(f.matchAll(/r:embed="([^"]+)"/g)).map(v=>v[1]);if(w.length===0){c();continue}let u=0,m=o.anchorXml.replace(/(r:(?:embed|link)=")[^"]*(")/g,(v,y,T)=>{const O=w[Math.min(u,w.length-1)];return u++,`${y}${O}${T}`});const b=f.match(/<wp:docPr\b[^>]*/)?.[0].match(/ descr="([^"]*)"/);m=m.replace(/<wp:docPr\b([^>]*?)(\/?>)/,(v,y,T)=>{const O=y.replace(/\s+descr="[^"]*"/,""),W=b?` descr="${b[1]}"`:"";return`<wp:docPr${O}${W}${T}`}),n=n.slice(0,p)+m+n.slice(g),a=!0}return a?(t.file("word/document.xml",n),this.generateCompressedZipBlob(t)):e}static async patchOriginalVectorImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml"),n=t.file("word/_rels/document.xml.rels"),a=t.file("[Content_Types].xml");if(!i||!n||!a)return e;let o=await i.async("string"),s=await n.async("string"),l=await a.async("string");const c=new Set;for(let p=0;p<r.length;p++){const h=r[p],g=await this.resolveBinarySourceForDocx(h.dataUrl);if(!g)continue;const f=this.escapeXml(h.marker),w=o.indexOf(f);if(w===-1)continue;const u=o.slice(w).match(/r:embed="([^"]+)"/);if(!u)continue;const m=u[1],b=`media/reviseOriginal${p}.${h.format}`,v=new RegExp(`(<Relationship\\b[^>]*\\bId="${m}"[^>]*\\bTarget=")[^"]*(")`),y=new RegExp(`(<Relationship\\b[^>]*\\bTarget=")[^"]*("[^>]*\\bId="${m}")`);if(v.test(s))s=s.replace(v,`$1${b}$2`);else if(y.test(s))s=s.replace(y,`$1${b}$2`);else continue;t.file(`word/${b}`,g),c.add(h.format),o=h.alt?o.replace(`descr="${f}"`,`descr="${this.escapeXml(h.alt)}"`):o.replace(` descr="${f}"`,"")}for(const p of c)new RegExp(`Extension="${p}"`).test(l)||(l=l.replace("</Types>",`<Default Extension="${p}" ContentType="image/x-${p}"/></Types>`));return t.file("word/document.xml",o),t.file("word/_rels/document.xml.rels",s),t.file("[Content_Types].xml",l),this.generateCompressedZipBlob(t)}static async injectWatermarkIntoHeaders(e,r){const t=Vi(r);if(!t)return e;const i=await this.loadZipFromBlob(e),n=Object.keys(i.files).filter(f=>/^word\/header\d+\.xml$/.test(f));if(n.length===0)return e;const a=f=>f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),o=468,s=Math.max(40,Math.round(o/Math.max(2,t.text.length*.55))),l=t.diagonal?"rotation:315;":"",c=t.fontSizePx?`${Math.max(1,Math.round(t.fontSizePx*.75))}pt`:"1pt",p=`<w:p><w:pPr><w:rPr><w:noProof/></w:rPr></w:pPr><w:r><w:rPr><w:noProof/></w:rPr><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w10="urn:schemas-microsoft-com:office:word"><v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" adj="10800" path="m@7,l@8,m@5,21600l@6,21600e"><v:formulas><v:f eqn="sum #0 0 10800"/><v:f eqn="prod #0 2 1"/><v:f eqn="sum 21600 0 @1"/><v:f eqn="sum 0 0 @2"/><v:f eqn="sum 21600 0 @3"/><v:f eqn="if @0 @3 0"/><v:f eqn="if @0 21600 @1"/><v:f eqn="if @0 0 @2"/><v:f eqn="if @0 @4 21600"/><v:f eqn="mid @5 @6"/><v:f eqn="mid @8 @5"/><v:f eqn="mid @7 @8"/><v:f eqn="mid @6 @7"/><v:f eqn="sum @6 0 @5"/></v:formulas><v:path textpathok="t" o:connecttype="custom" o:connectlocs="@9,0;@10,10800;@11,21600;@12,10800" o:connectangles="270,180,90,0"/><v:textpath on="t" fitshape="t"/><v:handles><v:h position="#0,bottomRight" xrange="6629,14971"/></v:handles><o:lock v:ext="edit" text="t" shapetype="t"/></v:shapetype><v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s2049" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:${o}pt;height:${s}pt;${l}z-index:-251654144;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowincell="f" fillcolor="${a(t.color)}" stroked="f"><v:fill opacity="${t.opacity===qi?Fr:t.opacity}"/><v:textpath style="font-family:"Calibri";font-size:${c}" string="${a(t.text)}"/></v:shape></w:pict></w:r></w:p>`;let h=!1;for(const f of n){const w=await i.file(f).async("text");if(w.includes("v:textpath"))continue;const u=w.replace(/(<w:hdr[^>]*>)/,`$1${p}`);u!==w&&(i.file(f,u),h=!0)}if(!h)return e;const g=await this.generateCompressedZipBlob(i);return new Blob([g],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async mergeImportedStyles(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/styles.xml");if(!i)return e;let n=await i.async("text");const a=r.match(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/)?.[0];a?/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/.test(n)?n=n.replace(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/,a):n=n.replace(/(<w:styles\b[^>]*>)/,`$1${a}`):n=n.replace(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/,"");const o=new Map;for(const u of r.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const m=u[0].match(/w:styleId="([^"]+)"/);m&&o.set(m[1],u[0])}if(o.size===0&&!a)return e;const s=new Set;n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const m=u.match(/w:styleId="([^"]+)"/),b=m?o.get(m[1]):void 0;return b?(s.add(m[1]),b):u});const l=[];for(const[u,m]of o)s.has(u)||l.push(m);n=n.replace(/<\/w:styles>/,`${l.join("")}</w:styles>`);const c=new Set,p=u=>{for(const m of u.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*w:val="([^"]+)"/g))c.add(m[1])};for(const u of Object.keys(t.files))/^word\/[^/]+\.xml$/.test(u)&&u!=="word/styles.xml"&&p(await t.file(u).async("text"));const h=new Map;for(const u of n.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const m=u[0].match(/w:styleId="([^"]+)"/);m&&h.set(m[1],u[0])}const g=(u,m)=>o.has(u)||/w:default="(?:1|true)"/.test(m.slice(0,m.indexOf(">")))||c.has(u);let f=!0;for(;f;){f=!1;for(const[u,m]of h)if(g(u,m))for(const b of m.matchAll(/<w:(?:basedOn|link|next)\b[^>]*w:val="([^"]+)"/g))c.has(b[1])||(c.add(b[1]),f=!0)}n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const m=u.match(/w:styleId="([^"]+)"/);return!m||g(m[1],u)?u:""}),t.file("word/styles.xml",n);const w=await this.generateCompressedZipBlob(t);return new Blob([w],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchCoreProperties(e,r){const t=await this.loadZipFromBlob(e),i=t.file("docProps/core.xml");if(!i)return e;let n=await i.async("text");const a=l=>l.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");for(const l of["created","modified"]){const c=r[l];if(!c)continue;const p=new RegExp(`(<dcterms:${l}\\b[^>]*>)[^<]*(</dcterms:${l}>)`);p.test(n)?n=n.replace(p,`$1${a(c)}$2`):n=n.replace(/<\/cp:coreProperties>/,`<dcterms:${l} xsi:type="dcterms:W3CDTF">${a(c)}</dcterms:${l}></cp:coreProperties>`)}const o=/<cp:revision>[^<]*<\/cp:revision>/;if(r.revision){const l=`<cp:revision>${a(r.revision)}</cp:revision>`;n=o.test(n)?n.replace(o,l):n.replace(/<\/cp:coreProperties>/,`${l}</cp:coreProperties>`)}else n=n.replace(o,"");for(const[l,c]of[["creator","dc:creator"],["lastModifiedBy","cp:lastModifiedBy"]])r[l]||(n=n.replace(new RegExp(`<${c}>[^<]*</${c}>`),""));t.file("docProps/core.xml",n);const s=await this.generateCompressedZipBlob(t);return new Blob([s],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stampApplicationProperty(e){const r=await this.loadZipFromBlob(e),t=r.file("docProps/app.xml");if(!t)return e;let i=await t.async("text");const n="<Application>Revise (revise.io)</Application>";if(/<Application[\s>]/.test(i))return e;if(/<Properties\b[^>]*\/>/.test(i))i=i.replace(/<Properties\b([^>]*)\/>/,`<Properties$1>${n}</Properties>`);else if(i.includes("</Properties>"))i=i.replace("</Properties>",`${n}</Properties>`);else return e;r.file("docProps/app.xml",i);const a=await this.generateCompressedZipBlob(r);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendCommentsExtendedPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/comments.xml");if(!i)return e;let n=await i.async("text");n.includes("xmlns:w14=")||(n=n.replace(/<w:comments /,'<w:comments xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" '));const a=p=>(268435456+p).toString(16).toUpperCase().padStart(8,"0");n=n.replace(/<w:comment\b([^>]*)>([\s\S]*?)<\/w:comment>/g,(p,h,g)=>{const f=h.match(/w:id="(\d+)"/);if(!f)return p;const w=a(parseInt(f[1],10)),u=g.lastIndexOf("<w:p");if(u===-1)return p;const m=g.slice(0,u)+g.slice(u).replace(/<w:p(\s|>)/,`<w:p w14:paraId="${w}"$1`);return`<w:comment${h}>${m}</w:comment>`}),t.file("word/comments.xml",n);const o='<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">'+r.map(({numericId:p,resolved:h,parentNumericId:g})=>`<w15:commentEx ${[`w15:paraId="${a(p)}"`,...g!==void 0?[`w15:paraIdParent="${a(g)}"`]:[],`w15:done="${h?"1":"0"}"`].join(" ")}/>`).join("")+"</w15:commentsEx>";t.file("word/commentsExtended.xml",o);const s=t.file("[Content_Types].xml");if(s){let p=await s.async("text");p.includes("/word/commentsExtended.xml")||(p=p.replace("</Types>",'<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"/></Types>'),t.file("[Content_Types].xml",p))}const l=t.file("word/_rels/document.xml.rels");if(l){let p=await l.async("text");p.includes("commentsExtended.xml")||(p=p.replace("</Relationships>",'<Relationship Id="rIdRvseCommentsEx" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",p))}const c=await this.generateCompressedZipBlob(t);return new Blob([c],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendEndnotesPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");for(const{index:u}of r){const m=`__RVSE_EN_${u}__`;for(const b of["w:t","w:delText"])n=n.replaceAll(`<${b} xml:space="preserve">${m}</${b}>`,`<w:endnoteReference w:id="${u}"/>`).replaceAll(`<${b}>${m}</${b}>`,`<w:endnoteReference w:id="${u}"/>`)}t.file("word/document.xml",n);const a=new Map;let o='<w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">';const s=t.file("word/footnotes.xml");if(s){let u=await s.async("text");const m=u.match(/<w:footnotes\b[^>]*>/)?.[0];m&&(o=m.replace(/<w:footnotes\b/,"<w:endnotes"));const b=new Set(r.map(y=>y.syntheticFootnoteId).filter(y=>y!==void 0));u=u.replace(/<w:footnote\b[^>]*>[\s\S]*?<\/w:footnote>/g,y=>{const T=/\bw:id="(-?\d+)"/.exec(y)?.[1],O=T?Number(T):NaN;if(!b.has(O))return y;const W=r.find(D=>D.syntheticFootnoteId===O);if(!W)return y;const X=y.replace(/^<w:footnote\b[^>]*>/,`<w:endnote w:id="${W.index}">`).replace(/<\/w:footnote>$/,"</w:endnote>").replaceAll("w:footnoteRef","w:endnoteRef").replaceAll("FootnoteReference","EndnoteReference").replaceAll("FootnoteText","EndnoteText");return a.set(O,X),""}),t.file("word/footnotes.xml",u);const v=t.file("word/_rels/footnotes.xml.rels");v&&t.file("word/_rels/endnotes.xml.rels",await v.async("text"))}const l=u=>u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),c=(u,m)=>{const b=u.marks??{},v=[];if(b.bold&&v.push("<w:b/>"),b.italic&&v.push("<w:i/>"),b.underline&&v.push('<w:u w:val="single"/>'),b.strikethrough&&v.push("<w:strike/>"),b.doubleStrikethrough&&v.push("<w:dstrike/>"),b.smallCaps&&v.push("<w:smallCaps/>"),b.allCaps&&v.push("<w:caps/>"),b.hidden&&v.push("<w:vanish/>"),b.color&&v.push(`<w:color w:val="${l(this.normalizeColor(b.color))}"/>`),b.backgroundColor&&v.push(`<w:highlight w:val="${l(b.backgroundColor)}"/>`),typeof b.fontSize=="number"&&b.fontSize>0&&v.push(`<w:sz w:val="${Math.max(2,Math.round(b.fontSize*this.DOCX_HALF_POINTS_PER_PX))}"/>`),b.fontFamily){const T=l(b.fontFamily.split(",")[0].replaceAll('"',"").replaceAll("'","").trim());v.push(`<w:rFonts w:ascii="${T}" w:hAnsi="${T}"/>`)}typeof b.letterSpacing=="number"&&Number.isFinite(b.letterSpacing)&&b.letterSpacing!==0&&v.push(`<w:spacing w:val="${Math.round(b.letterSpacing*15)}"/>`),b.superscript?v.push('<w:vertAlign w:val="superscript"/>'):b.subscript&&v.push('<w:vertAlign w:val="subscript"/>'),b.lang&&v.push(`<w:lang w:val="${l(b.lang)}"/>`);const y=m&&!/^\s/.test(u.text??"")?` ${u.text??""}`:u.text??"";return`<w:r>${v.length>0?`<w:rPr>${v.join("")}</w:rPr>`:""}<w:t xml:space="preserve">${l(y)}</w:t></w:r>`},p=r.sort((u,m)=>u.index-m.index).map(({index:u,note:m,syntheticFootnoteId:b})=>{const v=b!==void 0?a.get(b):void 0;if(v)return v;const y=m.children.filter(T=>T.type==="paragraph").map((T,O)=>'<w:p><w:pPr><w:pStyle w:val="EndnoteText"/></w:pPr><w:r><w:rPr><w:rStyle w:val="EndnoteReference"/></w:rPr><w:endnoteRef/></w:r>'+(T.children.filter(W=>(W.text??"")!=="").map((W,X)=>c(W,O===0&&X===0)).join("")||'<w:r><w:t xml:space="preserve"> </w:t></w:r>')+"</w:p>").join("");return`<w:endnote w:id="${u}">${y}</w:endnote>`}).join(""),h='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+o+'<w:endnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:endnote><w:endnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:endnote>'+p+"</w:endnotes>";t.file("word/endnotes.xml",h);const g=t.file("[Content_Types].xml");if(g){let u=await g.async("text");u.includes("/word/endnotes.xml")||(u=u.replace("</Types>",'<Override PartName="/word/endnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"/></Types>'),t.file("[Content_Types].xml",u))}const f=t.file("word/_rels/document.xml.rels");if(f){let u=await f.async("text");u.includes("endnotes.xml")||(u=u.replace("</Relationships>",'<Relationship Id="rIdRvseEndnotes" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes" Target="endnotes.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",u))}const w=await this.generateCompressedZipBlob(t);return new Blob([w],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static emittedBodySlotCount(e){switch(e.type){case"paragraph":case"table":case"code":case"math":case"image":case"page-break":case"section-break":return 1;case"list":return e.children.filter(r=>r.type==="list-item").length;default:return 0}}static async applySdtWrappers(e,r){const t=r.sdtWrappers??[];if(t.length===0)return e;const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o=this.parseDocumentXml(a);if(!o)return e;const s=o.getElementsByTagName("w:body")[0];if(!s)return e;const l="http://schemas.openxmlformats.org/wordprocessingml/2006/main",c=Array.from(s.children).filter(L=>L.tagName==="w:p"||L.tagName==="w:tbl"),p=r.children.filter(L=>L.type!=="footnote"&&L.type!=="header-footer"),h=new Map,g=[];let f=!0;{let L=0;p.forEach((I,B)=>{I.id&&h.set(I.id,B),g[B]=L,L+=this.emittedBodySlotCount(I)}),L!==c.length&&(console.warn(`docx export: content-control slot accounting mismatch (${L} computed vs ${c.length} body elements); exporting without sdt wrappers`),f=!1)}const w=L=>{if(L.blockIds&&L.blockIds.length>0)return L.blockIds;const I=L.startBlockId?h.get(L.startBlockId):void 0;if(I===void 0)return[];const B=Math.min(I+Math.max(1,L.blockCount??1),p.length);return p.slice(I,B).map(E=>E.id).filter(E=>!!E)};let u=!1;const m=new Map(t.map(L=>[L.id,L])),b=L=>this.parseDocumentXml(`<w:root xmlns:w="${l}">${L.prXml}</w:root>`)?.getElementsByTagName("w:sdtPr")[0]??void 0,v=(L,I)=>{const B=L[0].parentNode;if(!B)return;const E=o.createElementNS(l,"w:sdt"),S=o.createElementNS(l,"w:sdtContent");B.insertBefore(E,L[0]),E.appendChild(o.importNode(I,!0)),E.appendChild(S);for(const R of L)S.appendChild(R);u=!0};{const L=Array.from(o.getElementsByTagName("w:bookmarkStart")).filter(I=>(I.getAttribute("w:name")??"").startsWith("__rvSdt:"));if(L.length>0){const I=new Map;for(const S of Array.from(o.getElementsByTagName("w:bookmarkEnd"))){const R=S.getAttribute("w:id");R&&I.set(R,S)}const B=S=>{S.parentNode&&(S.parentNode.removeChild(S),u=!0)},E=[];for(const S of L){const R=(S.getAttribute("w:name")??"").slice(8).split(":")[0],z=I.get(S.getAttribute("w:id")??""),$=m.get(R);if(!z||!$||$.scope!=="inline"||z.parentNode!==S.parentNode||!S.parentNode){B(S),z&&B(z);continue}let j=0;for(let K=S.nextSibling;K&&K!==z;K=K.nextSibling)j++;E.push({record:$,start:S,end:z,covered:j})}E.sort((S,R)=>S.covered-R.covered);for(const S of E){const R=S.start.parentNode===S.end.parentNode&&S.start.parentNode?b(S.record):void 0;if(R){const z=[];for(let $=S.start.nextSibling;$&&$!==S.end;$=$.nextSibling)$.nodeType===1&&z.push($);z.length>0&&v(z,R)}B(S.start),B(S.end)}}}const y=new Map,T=new Map,O=new Map;f&&p.forEach((L,I)=>{if(L.type!=="table")return;const B=c[g[I]];if(!B||B.tagName!=="w:tbl")return;O.set(I,Array.from(B.children).filter(R=>R.tagName==="w:tr"));const E=L,S=Qe(E);E.children.forEach((R,z)=>{R.id&&y.set(R.id,{tableIndex:I,rowIndex:z});for(const $ of R.children)$.id&&T.set($.id,{tableIndex:I,rowIndex:z,gridCol:S.byId.get($.id)?.col??0})})});for(const L of t){if(L.scope!=="cell")continue;if(!f)break;const I=(L.blockIds??[]).map(S=>T.get(S)).filter(S=>!!S);if(I.length===0){console.warn(`docx export: content control ${L.id} has no surviving member blocks; dropping wrapper`);continue}const B=b(L);if(!B)continue;const E=new Map;for(const S of I){const R=`${S.tableIndex}:${S.rowIndex}`;E.set(R,[...E.get(R)??[],S])}for(const S of E.values()){const R=O.get(S[0].tableIndex)?.[S[0].rowIndex];if(!R)continue;const z=new Set(S.map(k=>k.gridCol)),$=Array.from(R.children).filter(k=>k.tagName==="w:tc"),j=[];let K=0;if($.forEach((k,H)=>{z.has(K)&&j.push(H);const G=this.getDirectChild(k,"w:tcPr"),q=G?this.getDirectChild(G,"w:gridSpan")?.getAttribute("w:val"):void 0,Z=q?parseInt(q,10):1;K+=Number.isFinite(Z)&&Z>0?Z:1}),j.length===0)continue;const J=j[0],re=j[j.length-1];v($.slice(J,re+1),B)}}for(const L of t){if(L.scope!=="row")continue;if(!f)break;const I=(L.blockIds??[]).map($=>y.get($)).filter($=>!!$);if(I.length===0){console.warn(`docx export: content control ${L.id} has no surviving member blocks; dropping wrapper`);continue}const B=b(L);if(!B)continue;const E=I[0].tableIndex,S=O.get(E);if(!S)continue;const R=I.filter($=>$.tableIndex===E).map($=>$.rowIndex).sort(($,j)=>$-j),z=S.slice(R[0],R[R.length-1]+1).filter($=>!!$.parentNode);z.length>0&&v(z,B)}const W=L=>{let I=0;const B=new Set([L.id]);let E=L;for(;E?.parentId&&!B.has(E.parentId);)B.add(E.parentId),E=m.get(E.parentId),E&&I++;return I},X=t.filter(L=>!L.scope||L.scope==="block").sort((L,I)=>W(I)-W(L));for(const L of X){if(!f)break;const I=w(L).map(j=>h.get(j)).filter(j=>j!==void 0).sort((j,K)=>j-K);if(I.length===0){console.warn(`docx export: content control ${L.id} has no surviving member blocks; dropping wrapper`);continue}const B=I[0],E=I[I.length-1],S=g[B];let R=0;for(let j=B;j<=E;j++)R+=this.emittedBodySlotCount(p[j]);if(R===0)continue;const z=[];for(const j of c.slice(S,S+R)){let K=j;for(;K.parentNode&&K.parentNode!==s&&K.parentNode.nodeType===1;)K=K.parentNode;K.parentNode===s&&!z.includes(K)&&z.push(K)}if(z.length===0)continue;const $=b(L);$&&v(z,$)}if(!u)return e;const D=new XMLSerializer().serializeToString(o);i.file("word/document.xml",D);const M=await this.generateCompressedZipBlob(i);return new Blob([M],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphMarkRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(a,"application/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=[];for(let g=0;g<l.children.length;g++)l.children[g].tagName==="w:p"&&c.push(l.children[g]);for(const g of r){const f=c[g.pIndex];if(!f)continue;let w=this.getDirectChild(f,"w:pPr");w||(w=s.createElementNS(o,"w:pPr"),f.insertBefore(w,f.firstChild));let u=this.getDirectChild(w,"w:rPr");if(!u){u=s.createElementNS(o,"w:rPr");const b=this.getDirectChild(w,"w:sectPr");b?w.insertBefore(u,b):w.appendChild(u)}const m=s.createElementNS(o,g.kind==="moveFrom"?"w:moveFrom":g.kind==="moveTo"?"w:moveTo":g.kind==="split"||g.kind==="insert"?"w:ins":"w:del");m.setAttributeNS(o,"w:id",String(t(g.importedId))),m.setAttributeNS(o,"w:author",g.author),m.setAttributeNS(o,"w:date",g.date),u.insertBefore(m,u.firstChild)}const p=new XMLSerializer().serializeToString(s);i.file("word/document.xml",p);const h=await this.generateCompressedZipBlob(i);return new Blob([h],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphPropertyChanges(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(a,"application/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=[];for(let w=0;w<l.children.length;w++)l.children[w].tagName==="w:p"&&c.push(l.children[w]);const p=(w,u)=>{const m=s.createElementNS(o,w);for(const[b,v]of Object.entries(u??{}))m.setAttributeNS(o,b,v);return m},h=w=>{const u=Array.from(s.getElementsByTagName("w:bookmarkStart")).find(v=>v.getAttribute("w:name")===w);if(!u)return;const m=u.getAttribute("w:id");let b=u.parentNode;for(;b&&b.tagName!=="w:p";)b=b.parentNode;for(const v of Array.from(s.getElementsByTagName("w:bookmarkEnd")))v.getAttribute("w:id")===m&&v.parentNode?.removeChild(v);return u.parentNode?.removeChild(u),b??void 0};for(const w of r){const u=w.marker?h(w.marker):c[w.pIndex];if(!u)continue;let m=this.getDirectChild(u,"w:pPr");m||(m=s.createElementNS(o,"w:pPr"),u.insertBefore(m,u.firstChild));const b=p("w:pPrChange",{"w:id":String(t(w.importedId)),"w:author":w.author,"w:date":w.date}),v=w.prior,y=s.createElementNS(o,"w:pPr");if(v.styleId&&y.appendChild(p("w:pStyle",{"w:val":v.styleId})),v.keepNext&&y.appendChild(p("w:keepNext")),v.keepLines&&y.appendChild(p("w:keepLines")),v.widowControl===!1&&y.appendChild(p("w:widowControl",{"w:val":"0"})),v.ilvl!==void 0){const T=this.getDirectChild(this.getDirectChild(m,"w:numPr")??m,"w:numId")?.getAttribute("w:val");if(T){const O=p("w:numPr");O.appendChild(p("w:ilvl",{"w:val":String(v.ilvl)})),O.appendChild(p("w:numId",{"w:val":T})),y.appendChild(O)}}if(v.bordersJson)try{const T=JSON.parse(v.bordersJson),O=s.createElementNS(o,"w:pBdr");for(const W of["top","left","bottom","right"]){const X=T[W];X&&O.appendChild(p(`w:${W}`,{"w:val":X.style||"single","w:sz":String(Math.max(2,Math.round((X.width??.5)*6))),"w:space":"1","w:color":(X.color||"#000000").replace(/^#/,"")}))}O.children.length>0&&y.appendChild(O)}catch{}v.shadingFill&&y.appendChild(p("w:shd",{"w:val":"clear","w:fill":this.toDocxHex(v.shadingFill)??"auto"})),v.direction&&y.appendChild(p("w:bidi",v.direction==="ltr"?{"w:val":"0"}:{})),(v.lineSpacing!==void 0||v.spaceBeforeTwips!==void 0||v.spaceAfterTwips!==void 0)&&y.appendChild(p("w:spacing",{...v.spaceBeforeTwips!==void 0?{"w:before":String(v.spaceBeforeTwips)}:{},...v.spaceAfterTwips!==void 0?{"w:after":String(v.spaceAfterTwips)}:{},...v.lineSpacing!==void 0?{"w:line":String(Math.round(v.lineSpacing*240)),"w:lineRule":"auto"}:{}})),(v.leftIndentTwips!==void 0||v.firstLineIndentTwips!==void 0)&&y.appendChild(p("w:ind",{...v.leftIndentTwips!==void 0?{"w:left":String(v.leftIndentTwips)}:{},...v.firstLineIndentTwips!==void 0?{"w:firstLine":String(v.firstLineIndentTwips)}:{}})),v.align&&y.appendChild(p("w:jc",{"w:val":v.align==="justify"?"both":v.align})),b.appendChild(y),m.appendChild(b)}const g=new XMLSerializer().serializeToString(s);i.file("word/document.xml",g);const f=await this.generateCompressedZipBlob(i);return new Blob([f],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLinkedMoveRevisions(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;const n=await i.async("text"),a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",o=new DOMParser().parseFromString(n,"application/xml"),s=(p,h)=>{const g=o.createElementNS(a,h);for(const f of Array.from(p.attributes))g.setAttributeNS(f.namespaceURI,f.name,f.value);for(;p.firstChild;)g.appendChild(p.firstChild);return p.replaceWith(g),g},l=(p,h,g)=>{const f=o.createElementNS(a,p);return f.setAttributeNS(a,"w:id",h.rangeId),g&&(f.setAttributeNS(a,"w:name",h.name),f.setAttributeNS(a,"w:author",h.author),f.setAttributeNS(a,"w:date",h.date)),f};for(const p of r){const h=p.role==="from"?"w:del":"w:ins",g=p.role==="from"?"w:moveFrom":"w:moveTo",f=new Set(p.wrapperIds.map(String)),w=Array.from(o.getElementsByTagName(h)).filter(y=>f.has(y.getAttribute("w:id")??""));if(w.length!==f.size)throw new Error(`linked move ${p.name}/${p.role}: expected ${f.size} temporary revision wrappers, found ${w.length}`);const u=w.map(y=>s(y,g)),m=u[0],b=u[u.length-1],v=p.role==="from"?"w:moveFromRange":"w:moveToRange";m.parentNode?.insertBefore(l(`${v}Start`,p,!0),m),b.parentNode?.insertBefore(l(`${v}End`,p,!1),b.nextSibling)}t.file("word/document.xml",new XMLSerializer().serializeToString(o));const c=await this.generateCompressedZipBlob(t);return new Blob([c],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchTableRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(a,"application/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=Array.from(l.getElementsByTagName("w:tbl")),p=(I,B)=>Array.from(I.children).filter(E=>E.tagName===B),h=(I,B)=>{const E=this.getDirectChild(I,B);if(E)return E;const S=s.createElementNS(o,B);return I.insertBefore(S,I.firstChild),S},g=(I,B)=>{const E=new DOMParser().parseFromString(I,"application/xml");if(!(E.getElementsByTagName("parsererror").length>0||E.documentElement?.tagName!==B))return s.importNode(E.documentElement,!0)},f=(I,B)=>{const E=g(B,"w:tblGrid");if(!E)return this.getDirectChild(I,"w:tblGrid");const S=this.getDirectChild(I,"w:tblGrid");if(S)S.replaceWith(E);else{const R=this.getDirectChild(I,"w:tblPr");I.insertBefore(E,R?.nextSibling??I.firstChild)}return E},w=(I,B)=>{const E=g(B,"w:tblPrEx");if(!E)return this.getDirectChild(I,"w:tblPrEx");const S=this.getDirectChild(I,"w:tblPrEx");return S?S.replaceWith(E):I.insertBefore(E,I.firstChild),E},u=(I,B,E)=>{const S=g(E,B);if(!S)return h(I,B);const R=this.getDirectChild(I,B);return R?R.replaceWith(S):I.insertBefore(S,I.firstChild),S},m={"w:tblPr":["w:tblStyle","w:tblpPr","w:tblOverlap","w:bidiVisual","w:tblStyleRowBandSize","w:tblStyleColBandSize","w:tblW","w:jc","w:tblCellSpacing","w:tblInd","w:tblBorders","w:shd","w:tblLayout","w:tblCellMar","w:tblLook","w:tblCaption","w:tblDescription","w:tblPrChange"],"w:trPr":["w:cnfStyle","w:divId","w:gridBefore","w:gridAfter","w:wBefore","w:wAfter","w:cantSplit","w:trHeight","w:tblHeader","w:tblCellSpacing","w:jc","w:hidden","w:ins","w:del","w:trPrChange"],"w:tcPr":["w:cnfStyle","w:tcW","w:gridSpan","w:hMerge","w:vMerge","w:tcBorders","w:shd","w:noWrap","w:tcMar","w:textDirection","w:tcFitText","w:vAlign","w:hideMark","w:headers","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]},b=(I,B,E,S)=>{const R=h(I,B),z=g(E,B);if(!z)return R;const $=[],j=Array.from(R.children),K=Array.from(z.children),J=new Set([...j.map(H=>H.tagName),...K.map(H=>H.tagName)]);for(const H of J){const G=S.has(H)?j:K.some(q=>q.tagName===H)?K:j;for(const q of G.filter(Z=>Z.tagName===H))$.push(s.importNode(q,!0))}const re=new Map(m[B].map((H,G)=>[H,G]));$.sort((H,G)=>(re.get(H.tagName)??Number.MAX_SAFE_INTEGER)-(re.get(G.tagName)??Number.MAX_SAFE_INTEGER));const k=s.createElementNS(o,B);for(const H of Array.from(z.attributes))k.setAttributeNS(H.namespaceURI,H.name,H.value);for(const H of $)k.appendChild(H);return R.replaceWith(k),k},v=new Map,y=(I,B)=>{const E=s.createElementNS(o,I),S=v;let R;return B.importedId===void 0&&B.revisionGroup&&(R=S.get(B.revisionGroup),R===void 0&&(R=t(),S.set(B.revisionGroup,R))),E.setAttributeNS(o,"w:id",String(B.importedId!==void 0?B.importedId:R??t())),E.setAttributeNS(o,"w:author",B.author),E.setAttributeNS(o,"w:date",B.date),E},T=(I,B)=>{let E=0;for(const S of p(I,"w:tc")){if(E===B)return S;const R=this.getDirectChild(S,"w:tcPr"),z=R?this.getDirectChild(R,"w:gridSpan")?.getAttribute("w:val"):void 0,$=z?Number(z):1;E+=Number.isFinite($)&&$>0?$:1}},O=(I,B)=>{const E=or(B);if(!E)return;const S=s.createElementNS(o,"w:tblBorders"),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],["insideH","insideH"],["insideV","insideV"]];for(const[z,$]of R){const j=E[z];if(!j)continue;const K=s.createElementNS(o,`w:${$}`);K.setAttributeNS(o,"w:val",j.style),K.setAttributeNS(o,"w:sz",String(Math.max(0,Math.round(j.width*6)))),K.setAttributeNS(o,"w:color",j.color.replace(/^#/,"")),S.appendChild(K)}S.children.length>0&&I.appendChild(S)},W=(I,B,E)=>{for(const S of p(I,B))S.remove();E&&I.appendChild(E)},X=(I,B)=>{const E=or(B);if(!E)return;const S=s.createElementNS(o,I),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],...I==="w:tblBorders"?[["insideH","insideH"],["insideV","insideV"]]:[]];for(const[z,$]of R){const j=E[z];if(!j)continue;const K=s.createElementNS(o,`w:${$}`);K.setAttributeNS(o,"w:val",j.style),K.setAttributeNS(o,"w:sz",String(Math.max(0,Math.round(j.width*6)))),K.setAttributeNS(o,"w:color",j.color.replace(/^#/,"")),S.appendChild(K)}return S.children.length>0?S:void 0},D=(I,B)=>{let E;if(typeof B=="number"&&Number.isFinite(B))E={top:B,right:B,bottom:B,left:B};else if(typeof B=="string")try{E=JSON.parse(B)}catch{return}if(!E)return;const S=s.createElementNS(o,I);for(const R of["top","right","bottom","left"]){const z=E[R];if(!Number.isFinite(z))continue;const $=s.createElementNS(o,`w:${R}`);$.setAttributeNS(o,"w:w",String(Math.round(z*15))),$.setAttributeNS(o,"w:type","dxa"),S.appendChild($)}return S.children.length>0?S:void 0},M=(I,B,E,S,R,z)=>{const $=J=>Object.prototype.hasOwnProperty.call(E??{},J)||Object.prototype.hasOwnProperty.call(S??{},J);if(B==="w:tblPr"){if($("tableWidth")){const J=E?.tableWidth;let re;typeof J=="number"&&Number.isFinite(J)&&(re=s.createElementNS(o,"w:tblW"),re.setAttributeNS(o,"w:w",String(Math.round(J*15))),re.setAttributeNS(o,"w:type","dxa")),W(I,"w:tblW",re)}if($("align")){const J=E?.align;let re;(J==="left"||J==="center"||J==="right")&&(re=s.createElementNS(o,"w:jc"),re.setAttributeNS(o,"w:val",J)),W(I,"w:jc",re)}if($("borders")&&W(I,"w:tblBorders",typeof E?.borders=="string"?X("w:tblBorders",E.borders):void 0),$("borderColor")||$("borderWidth")){let J=this.getDirectChild(I,"w:tblBorders");if(!J){J=s.createElementNS(o,"w:tblBorders");for(const re of["top","left","bottom","right","insideH","insideV"]){const k=s.createElementNS(o,`w:${re}`);k.setAttributeNS(o,"w:val","single"),J.appendChild(k)}I.appendChild(J)}for(const re of Array.from(J.children)){if($("borderColor")){const k=E?.borderColor;re.setAttributeNS(o,"w:color",typeof k=="string"&&k?k.replace(/^#/,""):"auto")}if($("borderWidth")){const k=E?.borderWidth;re.setAttributeNS(o,"w:sz",typeof k=="number"&&Number.isFinite(k)?String(Math.max(0,Math.round(k*6))):"4")}}}$("cellPadding")&&W(I,"w:tblCellMar",D("w:tblCellMar",E?.cellPadding))}else if(B==="w:tcPr"){if($("backgroundColor")){const J=E?.backgroundColor;let re;typeof J=="string"&&J&&(re=s.createElementNS(o,"w:shd"),re.setAttributeNS(o,"w:fill",J.replace(/^#/,""))),W(I,"w:shd",re)}if($("verticalAlign")){const J=E?.verticalAlign;let re;(J==="top"||J==="middle"||J==="bottom")&&(re=s.createElementNS(o,"w:vAlign"),re.setAttributeNS(o,"w:val",J==="middle"?"center":J)),W(I,"w:vAlign",re)}$("borders")&&W(I,"w:tcBorders",typeof E?.borders=="string"?X("w:tcBorders",E.borders):void 0),$("padding")&&W(I,"w:tcMar",D("w:tcMar",E?.padding))}if(B==="w:trPr"&&(J=>Object.prototype.hasOwnProperty.call(R??{},J)||Object.prototype.hasOwnProperty.call(z??{},J))("hasHeader")){const J=R?.hasHeader?s.createElementNS(o,"w:tblHeader"):void 0;W(I,"w:tblHeader",J)}const j=new Map(m[B].map((J,re)=>[J,re])),K=Array.from(I.children).sort((J,re)=>(j.get(J.tagName)??Number.MAX_SAFE_INTEGER)-(j.get(re.tagName)??Number.MAX_SAFE_INTEGER));for(const J of K)I.appendChild(J)};for(const I of r){const B=c[I.tableIndex];if(!B)continue;const E=p(B,"w:tr");I.propertyOverrides?.table&&b(B,"w:tblPr",I.propertyOverrides.table,new Set(["w:tblW","w:jc","w:tblBorders","w:tblCellMar"])),I.propertyOverrides?.grid&&f(B,I.propertyOverrides.grid);for(const S of I.propertyOverrides?.rows??[]){const R=E[S.rowIndex];R&&b(R,"w:trPr",S.xml,new Set(["w:tblHeader"]))}for(const S of I.propertyOverrides?.rowExceptions??[]){const R=E[S.rowIndex];R&&w(R,S.xml)}for(const S of I.propertyOverrides?.cells??[]){const R=E[S.rowIndex],z=R?T(R,S.gridColumn):void 0;z&&b(z,"w:tcPr",S.xml,new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign"]))}for(const S of I.rowProperties){const R=E[S.rowIndex];R&&(S.currentXml?u(R,"w:trPr",S.currentXml):M(h(R,"w:trPr"),"w:trPr",S.currentAttributes,S.priorAttributes,S.currentTableAttributes,S.priorTableAttributes))}for(const S of I.rowExceptionProperties){const R=E[S.rowIndex];R&&w(R,S.currentXml)}for(const S of I.cellProperties){const R=E[S.rowIndex],z=R?T(R,S.gridColumn):void 0;z&&(S.currentXml?u(z,"w:tcPr",S.currentXml):M(h(z,"w:tcPr"),"w:tcPr",S.currentAttributes,S.priorAttributes))}for(const S of I.rows){const R=E[S.rowIndex];R&&h(R,"w:trPr").appendChild(y(S.kind==="insert"?"w:ins":"w:del",S))}for(const S of I.cells){const R=E[S.rowIndex],z=R?T(R,S.gridColumn):void 0;z&&h(z,"w:tcPr").appendChild(y(S.kind==="insert"?"w:cellIns":"w:cellDel",S))}for(const S of I.merges){const R=E[S.rowIndex],z=R?T(R,S.gridColumn):void 0;if(!z)continue;const $=y("w:cellMerge",S);S.vMerge&&$.setAttributeNS(o,"w:vMerge",S.vMerge),S.vMergeOrig&&$.setAttributeNS(o,"w:vMergeOrig",S.vMergeOrig),h(z,"w:tcPr").appendChild($)}if(I.tableGrid){const S=f(B,I.tableGrid.currentXml);if(S){const R=y("w:tblGridChange",I.tableGrid),z=g(I.tableGrid.priorXml,"w:tblGrid");z&&R.appendChild(z),S.appendChild(R)}}for(const S of I.rowProperties){const R=E[S.rowIndex];if(!R)continue;const z=y("w:trPrChange",S),$=h(R,"w:trPr"),j=S.priorXml?g(S.priorXml,"w:trPr"):$.cloneNode(!0);if(j){if(!S.priorXml){for(const K of["w:ins","w:del","w:trPrChange"])for(const J of p(j,K))J.remove();M(j,"w:trPr",S.priorAttributes,S.currentAttributes,S.priorTableAttributes,S.currentTableAttributes)}z.appendChild(j)}$.appendChild(z)}for(const S of I.rowExceptionProperties){const R=E[S.rowIndex];if(!R)continue;const z=this.getDirectChild(R,"w:tblPrEx")??w(R,S.currentXml);if(!z)continue;const $=y("w:tblPrExChange",S),j=g(S.priorXml,"w:tblPrEx");j&&$.appendChild(j),z.appendChild($)}for(const S of I.cellProperties){const R=E[S.rowIndex],z=R?T(R,S.gridColumn):void 0;if(!z)continue;const $=y("w:tcPrChange",S),j=h(z,"w:tcPr"),K=S.priorXml?g(S.priorXml,"w:tcPr"):j.cloneNode(!0);if(K){if(!S.priorXml){for(const J of["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])for(const re of p(K,J))re.remove();M(K,"w:tcPr",S.priorAttributes,S.currentAttributes)}$.appendChild(K)}j.appendChild($)}if(I.tableProperties){const S=I.tableProperties.currentXml?u(B,"w:tblPr",I.tableProperties.currentXml):h(B,"w:tblPr");I.tableProperties.currentXml||M(S,"w:tblPr",I.tableProperties.currentAttributes,I.tableProperties.priorAttributes);const R=y("w:tblPrChange",I.tableProperties);let z;I.tableProperties.priorXml&&(z=g(I.tableProperties.priorXml,"w:tblPr")),z||(z=S.cloneNode(!0),M(z,"w:tblPr",I.tableProperties.priorAttributes,I.tableProperties.currentAttributes),I.tableProperties.priorBorders&&O(z,I.tableProperties.priorBorders)),R.appendChild(z),S.appendChild(R)}}i.file("word/document.xml",new XMLSerializer().serializeToString(s));const L=await this.generateCompressedZipBlob(i);return new Blob([L],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static inferDocumentFontFamily(e){if(!e?.children)return;const r=new Map;let t=0;const i=(o,s)=>{for(const l of o){if(l.type!=="text")continue;const c=l.text.length;if(c===0)continue;t+=c;const p=l.marks?.fontFamily??s;p&&r.set(p,(r.get(p)??0)+c)}};for(const o of e.children)if(o.type==="paragraph"){const s=o;i(o.children,s.fontFamily)}else if(o.type==="list")for(const s of o.children)i(s.children);if(t===0)return;let n,a=0;for(const[o,s]of r)s>a&&(n=o,a=s);return n&&a*2>t?n:void 0}static codeBlockStyleId(e){const r=(e??"").replace(/[^A-Za-z0-9]/g,"");return r?`${this.CODE_BLOCK_STYLE_ID}_${r}`:this.CODE_BLOCK_STYLE_ID}static buildExportHeadingDefaults(){const e=[["heading1",Ae.h1],["heading2",Ae.h2],["heading3",Ae.h3],["heading4",Ae.h4],["heading5",Ae.h5],["heading6",Ae.h6]];return Object.fromEntries(e.map(([r,t])=>[r,{run:{size:this.pxToDocxHalfPoints(t)}}]))}static buildExportParagraphStyles(e){const r=[],t=new Set,i=n=>{for(const a of n)if(a.type==="code"&&!a.renderDiagram)t.add(this.codeBlockStyleId(a.language));else if(a.type==="container"||a.type==="footnote"||a.type==="table-cell")i(a.children);else if(a.type==="table")for(const o of a.children)i(o.children)};if(i(e.children),e.notes&&i(e.notes),t.size>0){r.push({id:this.CODE_BLOCK_STYLE_ID,name:"Code Block",basedOn:"Normal",run:{font:"Courier New",size:this.pxToDocxHalfPoints(Ae.code)}});for(const n of t)n!==this.CODE_BLOCK_STYLE_ID&&r.push({id:n,name:`Code Block (${n.slice(this.CODE_BLOCK_STYLE_ID.length+1)})`,basedOn:this.CODE_BLOCK_STYLE_ID})}return r}static buildExportCharacterStyles(){return[{id:this.CODE_INLINE_STYLE_ID,name:"Code Inline",run:{font:"Courier New",highlight:"lightGray"}}]}static toDocxFormat(e){const r=[],t=this.inferDocumentFontFamily(e),i=this.resolveIndentStepPx(e),n=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=n,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(e.children,this.exportLinkedMoveSides);const a=this.collectTextlessMoveHalves(e.children);for(const o of e.children){if(a.destinations.has(o.id))continue;const s=a.sources.has(o.id)?this.withoutMoveState(o):o;s.type==="paragraph"?r.push(this.paragraphToDocx(s,t,i)):s.type==="list"?r.push(...this.listToDocxParagraphs(s,t,n)):s.type==="page-break"?r.push({type:"pagebreak"}):s.type==="toc"&&r.push(...this.tocBlockToDocxParagraphs(s,e))}return r}static tocBlockToDocxParagraphs(e,r,t){const i=Yi(e),n=Qi(r,e),a=Ee(r.pageLayout),o=rr(a),s=Math.max(o.pageWidth-a.marginLeftPx-a.marginRightPx,96),l=e.direction==="rtl",c=this.docxAlignmentForExport({type:"paragraph",id:e.id,children:[],direction:e.direction??"ltr",align:e.align??(l?"right":"left")}),p={bidirectional:l,alignment:c},h=JSON.stringify([{pos:Math.round(s),align:"right",leader:"dot"}]),g=e.fontFamily??this.inferDocumentFontFamily(r),f=this.toDocxHex(e.color),w={...g?{font:g}:{},...e.fontSize?{size:Math.round(e.fontSize*this.DOCX_HALF_POINTS_PER_PX)}:{},...f?{color:f}:{}};if(n.length===0)return[{type:"paragraph",...p,children:[{text:" ",fieldInstr:i,...w}]}];const u=24;return n.map(m=>({type:"paragraph",...p,children:[{text:`${m.text} `,fieldInstr:i,...w,...l?{rightToLeft:!0}:{}},...t?.has(m.blockId)?[{text:String(t.get(m.blockId)),fieldInstr:i,...w,rightToLeft:!1}]:[]],tabStopsJson:h,...m.level>1?{indent:{left:this.pxToTwips((m.level-1)*u)}}:{}}))}static toDocxFormatWithTables(e,r,t,i){const n=[],a=this.inferDocumentFontFamily(e);this.exportDefaultRunSizeHalfPoints=this.inferDefaultRunSizeHalfPoints(e);const o=r||en,s=this.resolveIndentStepPx(e),l=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=l,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(e.children,this.exportLinkedMoveSides);const c=this.styleExportContext(e),p=this.collectTextlessMoveHalves(e.children);for(const f of e.children){const w=n.length;if(p.destinations.has(f.id)){i?.push({blockId:f.id,start:w,count:0});continue}const u=p.sources.has(f.id)?this.withoutMoveState(f):f;if(u.type==="paragraph")n.push(this.styledParagraphToDocxWithMath(u,a,s,c));else if(u.type==="list")n.push(...this.listToDocxParagraphsWithMath(u,a,l));else if(u.type==="table")n.push(this.tableToDocxWithMath(u,a,s,c));else if(u.type==="code"){const m=this.legacyLatexCodeBlockAsMath(u);n.push(m?this.mathBlockToDocx(m):this.codeBlockToDocx(u,o))}else if(u.type==="math")n.push(this.mathBlockToDocx(u));else if(u.type==="image")n.push(this.imageBlockToDocx(u));else if(u.type==="page-break")n.push({type:"pagebreak"});else if(u.type==="section-break"){const m=u.diffState==="delete"&&u.suggestionId?/^docxrev-(\d+)$/.exec(u.suggestionId):null;n.push({type:"sectionbreak",...u.layout?{layout:u.layout}:{},...u.breakType?{breakType:u.breakType}:{},...u.diffState==="delete"?{pendingDeletion:{author:u.suggestionAuthorName??"Anonymous",date:new Date(u.suggestionCreatedAt??Date.now()).toISOString(),...m?{importedId:Number(m[1])}:{}}}:{}})}else u.type==="toc"?n.push(...this.tocBlockToDocxParagraphs(u,e,t)):u.type==="docx-raw"&&(cr(u.xml)?n.push(this.styledParagraphToDocxWithMath({type:"paragraph",id:u.id,children:[{type:"text",text:""}]},a,s,c)):n.push({type:"docxraw",sourceBlockId:u.id,xml:u.xml,origin:u.origin,emitsParagraph:u.origin==="run"}));i?.push({blockId:u.id,start:w,count:n.length-w})}const h=this.pxToTwips(Ee(e.pageLayout).blockSpacingPx),g=f=>{for(const w of f.rows)for(const u of w.cells){for(const m of u.paragraphs)m.spacingAfterTwips??(m.spacingAfterTwips=h),m.spacingBeforeTwips??(m.spacingBeforeTwips=0);for(const m of u.blocks??[])m.type==="paragraph"?(m.spacingAfterTwips??(m.spacingAfterTwips=h),m.spacingBeforeTwips??(m.spacingBeforeTwips=0)):g(m)}};for(const f of n)f.type==="paragraph"?f.styleProvidesSpacing||(f.spacingAfterTwips??(f.spacingAfterTwips=h),f.spacingBeforeTwips??(f.spacingBeforeTwips=0)):f.type==="table"&&g(f);return n}static applyExportParagraphSpacing(e,r){typeof r.spaceBefore=="number"&&(e.spacingBeforeTwips=this.pxToTwips(r.spaceBefore)),typeof r.spaceAfter=="number"&&(e.spacingAfterTwips=this.pxToTwips(r.spaceAfter)),r.contextualSpacing&&(e.contextualSpacing=!0)}static latexToOmml(e,r){const t=Rr();if(!t)return"";try{const i=t.renderToString(e,{output:"mathml",displayMode:r,throwOnError:!1});let n=Dn(i);return r&&(n=n.replace(qr,'<m:oMathPara xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:oMath>'),n=n.replace(/<\/m:oMath>$/,"</m:oMath></m:oMathPara>")),n}catch{return""}}static legacyLatexCodeBlockAsMath(e){const r=e.language?.trim().toLowerCase();return r!=="latex"&&r!=="latex-inline"||e.renderDiagram===!1?null:{type:"math",id:e.id,content:e.content||"",displayMode:r==="latex-inline"?"inline":"block",align:"center"}}static mathBlockToDocx(e){const r=e.displayMode!=="inline",t=e.align||"center",i=this.latexToOmml(e.content,r);return{type:"mathblock",content:e.content,displayMode:r,alignment:t,omml:i||void 0}}static imageBlockToDocx(e){return{type:"image",src:e.src,width:e.width,height:e.height,alt:e.alt,align:e.align,originalFormat:e.originalFormat,originalDataUrl:e.originalDataUrl,anchorXml:e.anchorXml}}static buildParagraphIndent(e,r){const t=e.leftIndent===0?0:tn(e.leftIndent),i=e.firstLineIndent===0?0:rn(e.firstLineIndent),n={};return t!==void 0&&(n.left=this.pxToTwips(ir(t,r))),i!==void 0&&(i<0?n.hanging=this.pxToTwips(ir(-i,r)):n.firstLine=this.pxToTwips(ir(i,r))),Object.keys(n).length>0?n:void 0}static headerRowIndexes(e){if(!e.hasHeader)return new Set;const r=new Set;try{const n=JSON.parse(e.structuralSuggestionRecords??"[]");for(const a of Array.isArray(n)?n:[])if(a?.type==="table-change")for(const o of a.tableRevision?.markers??[])o.kind==="row-delete"&&o.rowId&&r.add(o.rowId)}catch{}const t=new Set([0]),i=e.children.findIndex(n=>n.diffState!=="delete"&&!(n.id&&r.has(n.id)));return i>0&&t.add(i),t}static tableToDocx(e,r){const t=Qe(e),i=this.headerRowIndexes(e);return{type:"table",rows:e.children.map((n,a)=>{const o=i.has(a);return{cells:n.children.map(s=>{const l=[],c=[];for(const h of s.children)if(h.type==="paragraph"){const g=this.paragraphToDocx(h,r);g.inTableCell=!0,l.push(g),c.push(g)}else if(h.type==="list"){const g=this.listToDocxParagraphs(h,r,this.exportOrderedPlan);for(const f of g)f.inTableCell=!0;l.push(...g),c.push(...g)}else h.type==="table"&&c.push(this.tableToDocx(h,r));const p=t.byId.get(s.id);return{paragraphs:l,...c.some(h=>h.type==="table")?{blocks:c}:{},backgroundColor:s.backgroundColor,verticalAlign:s.verticalAlign,borders:s.borders,padding:s.padding,colSpan:p&&p.colSpan>1?p.colSpan:void 0,rowSpan:p&&p.rowSpan>1?p.rowSpan:void 0,gridColumn:p?.col,...s.oxmlTcPr?{oxmlTcPr:s.oxmlTcPr}:{}}}),isHeader:o,...n.oxmlAttrs?{oxmlAttrs:n.oxmlAttrs}:{},...n.oxmlTrPr?{oxmlTrPr:n.oxmlTrPr}:{}}}),columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static codeBlockToDocx(e,r){const t=e.content||"",i=e.language||"",n=nn(i);if(n&&e.renderDiagram!==!1&&n){const s=on({protocol:n,source:t,theme:sn(),maxWidth:900});return{type:"codeblock",content:"",language:i,runs:[],backgroundColor:r.background,renderDiagram:!0,diagramPngDataUrl:s?.dataUrl,diagramWidth:s?.width,diagramHeight:s?.height}}const a=i?an(t,i,r):null,o=[];if(a&&a.length>0)for(const s of a){const l=s.text.split(`
|
|
9
|
+
`);for(let c=0;c<l.length;c++)l[c]&&o.push({text:l[c],font:"Courier New",color:this.normalizeColor(s.color)}),c<l.length-1&&o.push({text:`
|
|
10
|
+
`,font:"Courier New",break:!0})}else{const s=t.split(`
|
|
11
|
+
`);for(let l=0;l<s.length;l++)s[l]&&o.push({text:s[l],font:"Courier New",color:this.normalizeColor(r.default)}),l<s.length-1&&o.push({text:`
|
|
12
|
+
`,font:"Courier New",break:!0})}return{type:"codeblock",content:t,language:i,styleId:this.codeBlockStyleId(i),runs:o,backgroundColor:r.background,renderDiagram:!1}}static createStyleMarksResolver(e){const r=e.stylesXml;if(!r)return;let t;const i=new Map,n="\0unstyled";return a=>{const o=a??n;if(i.has(o))return i.get(o);t??(t=this.parseStylesXml(r));const s=!this.styleChainDeclaresFont(a,t);if(!a){const c=s?{fontFamily:Or}:void 0;return i.set(o,c),c}const l=this.resolveRunMarks(void 0,a,{styles:t});return s&&!l.fontFamily&&(l.fontFamily=Or),i.set(o,l),l}}static styleChainDeclaresFont(e,r){return[...r.runDefault?[r.runDefault]:[],...this.resolveStyleChainRPr(this.effectiveParagraphStyleId(e,r),r,"paragraph")].some(t=>!!this.getDirectChild(t,"w:rFonts"))}static styleExportContext(e){return{stylesheet:e.stylesheet,styleMarksFor:this.createStyleMarksResolver(e)}}static styledParagraphToDocxWithMath(e,r,t,i){const n=e.styleId?ln(i.stylesheet,e.styleId)?.paragraphAttrs:void 0,a=this.stripStyleProvidedParagraphAttrs(e,n),o=i.styleMarksFor?.(e.styleId),s=this.paragraphToDocxWithMath(a,o?.fontFamily?void 0:r,t,o);return a.spaceAfter===void 0&&e.spaceAfter!==void 0&&(s.styleProvidesSpacing=!0),s}static stripStyleProvidedParagraphAttrs(e,r){if(!r)return e;const t={...e},i=(n,a)=>n!==void 0&&a!==void 0&&Math.abs(n-a)<.011;return t.align!==void 0&&t.align===r.align&&delete t.align,i(t.lineSpacing,r.lineSpacing)&&delete t.lineSpacing,i(t.spaceBefore,r.spaceBefore)&&i(t.spaceAfter,r.spaceAfter)&&(t.contextualSpacing??!1)===(r.contextualSpacing??!1)&&(delete t.spaceBefore,delete t.spaceAfter,delete t.contextualSpacing),t.keepNext===!0&&r.keepNext===!0&&delete t.keepNext,t.keepLines===!0&&r.keepLines===!0&&delete t.keepLines,t.widowControl===!1&&r.widowControl===!1&&delete t.widowControl,i(t.leftIndent,r.leftIndent)&&delete t.leftIndent,i(t.firstLineIndent,r.firstLineIndent)&&delete t.firstLineIndent,t.tabStops!==void 0&&t.tabStops===r.tabStops&&delete t.tabStops,t.borders!==void 0&&t.borders===r.borders&&delete t.borders,t.shading!==void 0&&t.shading===r.shading&&delete t.shading,t}static stripStyleProvidedMarks(e,r){if(!e||!r)return e;const t=n=>String(n).split(",")[0].replaceAll('"',"").replaceAll("'","").trim().toLowerCase(),i={...e};for(const n of Object.keys(r))i[n]!==void 0&&(n==="fontFamily"?t(i[n])===t(r[n]):i[n]===r[n])&&delete i[n];return i}static paragraphToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=this.exportDefaultRunSizeHalfPoints;(e.heading||i?.fontSize)&&(this.exportDefaultRunSizeHalfPoints=void 0);try{return this.paragraphToDocxWithMathInner(e,r,t,i)}finally{this.exportDefaultRunSizeHalfPoints=n}}static paragraphToDocxWithMathInner(e,r,t=this.resolveIndentStepPx(),i){const n={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(n.styleId=e.styleId),e.heading&&(n.heading=`HEADING_${e.heading}`);{const s=this.docxAlignmentForExport(e);s&&(n.alignment=s)}e.lineSpacing!==void 0&&(n.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(n,e),e.keepNext&&(n.keepNext=!0),e.keepLines&&(n.keepLines=!0),e.widowControl===!1&&(n.widowControl=!1),e.borders&&(n.bordersJson=e.borders),e.shading&&(n.shadingFill=e.shading),e.tabStops&&(n.tabStopsJson=e.tabStops),e.oxmlAttrs&&(n.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(n.oxmlPPr=e.oxmlPPr);const a=this.buildParagraphIndent(e,t);a&&(n.indent=a);const o=e;if(o.fontFamily&&(n.style=o.fontFamily),this.applyParagraphMarkRevisionInfo(n,e),this.applyParagraphPropertyChangeInfo(n,e,t),e.children.length===0)return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n;for(const s of this.dropReplacementSeparators(this.runRevisionsForBlockChange(e)))if(s.type==="text"){const l=i?{...s,marks:this.stripStyleProvidedMarks(s.marks,i)}:s,c=this.textNodeToDocxWithLatex(l,r);n.children.push(...c)}return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n}static docxAlignmentForExport(e){if(!e.align)return;const r=e.direction==="rtl"||e.direction===void 0&&Ot(this.paragraphNodeText(e))==="rtl",t=r&&e.align==="left"?"right":r&&e.align==="right"?"left":e.align;return{left:"LEFT",center:"CENTER",right:"RIGHT",justify:"JUSTIFIED"}[t]}static applyBidiExportFlags(e,r){const t=this.paragraphNodeText(r);if(r.direction==="ltr"){Ot(t)==="rtl"&&(e.bidirectional=!1);return}if(r.direction==="rtl"||r.direction===void 0&&Ot(t)==="rtl"){e.bidirectional=!0;for(const i of e.children)i.text&&cn(i.text)&&(i.rightToLeft=!0)}}static listToDocxParagraphsWithMath(e,r,t){e=this.listWithItemRevisions(e);const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const a of e.children){if(a.type!=="list-item")continue;const o=this.getClampedIndentLevel(a.indentLevel),s={type:"paragraph",sourceBlockId:a.id,children:[],lineSpacing:a.lineSpacing??e.lineSpacing,...typeof(a.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(a.spaceBefore??e.spaceBefore)}:{},...typeof(a.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(a.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",checked:e.variant==="todo"?!!a.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,a,n);if(s.list&&(s.list.label=l),e.variant==="todo"&&s.children.push({text:`${l} `}),a.children.length>0){for(const c of a.children)if(c.type==="text"){const p=this.textNodeToDocxWithLatex(c,r);s.children.push(...p)}}this.applyWholeBlockRevisionInfo(s,a.structuralSuggestionKind?a:e),this.applyParagraphPropertyChangeInfo(s,a,0),i.push(s)}return i}static tableToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=Qe(e),a=[],o=this.headerRowIndexes(e);for(let s=0;s<e.children.length;s++){const l=e.children[s],c=o.has(s),p=[];for(const h of l.children){const g=[],f=[];for(const u of h.children)if(u.type==="paragraph"){const m=i?this.styledParagraphToDocxWithMath(u,r,t,i):this.paragraphToDocxWithMath(u,r,t);m.inTableCell=!0,g.push(m),f.push(m)}else if(u.type==="list"){const m=this.listToDocxParagraphsWithMath(u,r,this.exportOrderedPlan);for(const b of m)b.inTableCell=!0;g.push(...m),f.push(...m)}else u.type==="table"&&f.push(this.tableToDocxWithMath(u,r,t,i));const w=n.byId.get(h.id);p.push({paragraphs:g,...f.some(u=>u.type==="table")?{blocks:f}:{},backgroundColor:h.backgroundColor,verticalAlign:h.verticalAlign,borders:h.borders,padding:h.padding,colSpan:w&&w.colSpan>1?w.colSpan:void 0,rowSpan:w&&w.rowSpan>1?w.rowSpan:void 0,gridColumn:w?.col,...h.oxmlTcPr?{oxmlTcPr:h.oxmlTcPr}:{}})}a.push({cells:p,isHeader:c,...l.oxmlAttrs?{oxmlAttrs:l.oxmlAttrs}:{},...l.oxmlTrPr?{oxmlTrPr:l.oxmlTrPr}:{}})}return{type:"table",rows:a,columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static applyParagraphMarkRevisionInfo(e,r){if(r.structuralSuggestionKind!=="split"&&r.structuralSuggestionKind!=="merge"||r.structuralSuggestionRole!=="before")return;let t="Anonymous",i=new Date().toISOString(),n;try{const o=JSON.parse(r.structuralSuggestionRecord??"{}");typeof o.agentName=="string"&&o.agentName.trim()?t=o.agentName.trim():o.authorType==="ai"&&(t="Revise Agent"),typeof o.createdAt=="number"&&(i=new Date(o.createdAt).toISOString())}catch{}const a=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null;a&&(n=Number(a[1])),e.paragraphMarkRevision={kind:r.structuralSuggestionKind,author:t,date:i,...n!==void 0?{importedId:n}:{}}}static applyWholeBlockRevisionInfo(e,r){if(r.structuralSuggestionKind!=="insert"&&r.structuralSuggestionKind!=="delete")return;const t=this.linkedMoveSideFor(r.structuralSuggestionId,r.structuralSuggestionKind);if(t&&!this.isInLinkedMoveRange(r,t.move.role)){const s={kind:r.structuralSuggestionKind,author:t.author,date:t.date};e.paragraphMarkRevision=s;for(const l of e.children)l.text&&(l.revision??(l.revision=s));return}if(t){e.paragraphMarkRevision={kind:t.move.role==="from"?"moveFrom":"moveTo",author:t.author,date:t.date};const s=/^\d+$/.test(t.move.wrapperId)?Number(t.move.wrapperId):void 0;e.children.length===0&&e.children.push({text:""});for(const l of e.children)l.revision??(l.revision={kind:r.structuralSuggestionKind,author:t.author,date:t.date,...s!==void 0?{importedId:s}:{},move:t.move});return}let i="Anonymous",n=new Date().toISOString();try{const s=JSON.parse(r.structuralSuggestionRecord??"{}");typeof s.agentName=="string"&&s.agentName.trim()?i=s.agentName.trim():s.authorType==="ai"&&(i=Ct),typeof s.createdAt=="number"&&(n=new Date(s.createdAt).toISOString())}catch{}const a=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,o={kind:r.structuralSuggestionKind,author:i,date:n,...a?{importedId:Number(a[1])}:{}};e.paragraphMarkRevision=o;for(const s of e.children){if(o.kind==="delete"&&s.revision?.kind==="insert"&&!s.revision.move&&!s.revision.layeredInsertion){s.revision={kind:"delete",author:i,date:n,layeredInsertion:{author:s.revision.author,date:s.revision.date,...s.revision.importedId!==void 0?{importedId:s.revision.importedId}:{}}};continue}s.revision??(s.revision=o)}}static applyParagraphPropertyChangeInfo(e,r,t){if(r.structuralSuggestionKind!=="change")return;let i;try{i=JSON.parse(r.structuralSuggestionRecord??"{}")}catch{return}if(i.type!=="block-change"||i.beforeBlock?.type!=="paragraph")return;const n=i.beforeBlock;let a="Anonymous";typeof i.agentName=="string"&&i.agentName.trim()?a=i.agentName.trim():i.authorType==="ai"&&(a=Ct);const o=typeof i.createdAt=="number"?new Date(i.createdAt).toISOString():new Date().toISOString(),s=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,l=this.buildParagraphIndent(n,t);e.paragraphPropertiesChange={author:a,date:o,...s?{importedId:Number(s[1])}:{},prior:{...typeof n.indentLevel=="number"?{ilvl:n.indentLevel}:{},...n.align?{align:n.align}:{},...l?.left!==void 0?{leftIndentTwips:l.left}:{},...l?.firstLine!==void 0?{firstLineIndentTwips:l.firstLine}:{},...n.lineSpacing!==void 0?{lineSpacing:n.lineSpacing}:{},...typeof n.spaceBefore=="number"?{spaceBeforeTwips:this.pxToTwips(n.spaceBefore)}:{},...typeof n.spaceAfter=="number"?{spaceAfterTwips:this.pxToTwips(n.spaceAfter)}:{},...n.keepNext?{keepNext:!0}:{},...n.keepLines?{keepLines:!0}:{},...n.widowControl===!1?{widowControl:!1}:{},...n.direction?{direction:n.direction}:{},...n.borders?{bordersJson:n.borders}:{},...n.shading?{shadingFill:n.shading}:{},...n.styleId?{styleId:n.styleId}:n.heading?{styleId:`Heading${n.heading}`}:{}}}}static collectTableRevisionPatches(e){const r=[];let t=0;const i=[],n=o=>{for(const s of o)if(s.type==="table"){i.push(s);for(const l of s.children)for(const c of l.children)n(c.children)}else s.type==="container"&&n(s.children)};n(e.children);const a=this.collectLinkedMoveSides(e.children);for(const o of i){const s=t++,l=o.diffState==="insert"||o.diffState==="delete"?o.diffState:void 0,c=l&&typeof o.suggestionId=="string"?a.get(o.suggestionId)?.[l==="delete"?"from":"to"]:void 0;if(l&&c){r.push({tableIndex:s,rows:o.children.map((y,T)=>({rowIndex:T,kind:l,author:c.author,date:c.date,revisionGroup:`${o.suggestionId}\0${l}`})),cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]});continue}let p=[];if(o.structuralSuggestionRecords)try{const y=JSON.parse(o.structuralSuggestionRecords);Array.isArray(y)&&(p=y.filter(T=>T?.type==="table-change"))}catch{}let h;if(o.docxTablePropertyOverrides)try{const y=JSON.parse(o.docxTablePropertyOverrides);y?.version===1&&(h=y)}catch{}if(p.length>0||h){const y={tableIndex:s,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},T=Qe(o),O=new Map(o.children.map((D,M)=>[D.id,M])),W=(D,M)=>{const L=M.author?.trim()||D.agentName?.trim()||(D.authorType==="ai"?Ct:"Anonymous"),I=typeof M.createdAt=="number"?M.createdAt:typeof D.createdAt=="number"?D.createdAt:Date.now(),B=M.revisionId??/^docxrev-(\d+)$/.exec(D.id)?.[1],E=typeof B=="string"&&/^\d+$/.test(B)?Number(B):void 0;return{author:L,date:new Date(I).toISOString(),revisionGroup:D.id,...E!==void 0?{importedId:E}:{}}},X=D=>{const M=D.map(I=>Number.isFinite(I)&&I>0?I:1),L=M.reduce((I,B)=>I+B,0)||1;return`<w:tblGrid xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${M.map(I=>`<w:gridCol w:w="${Math.max(1,Math.round(I/L*1e4))}"/>`).join("")}</w:tblGrid>`};if(h){const D={...h.table?{table:h.table}:{},...h.grid&&JSON.stringify(h.grid.columnWidths)===JSON.stringify(o.columnWidths)?{grid:h.grid.xml}:{},rows:[],rowExceptions:[],cells:[]};for(const[M,L]of Object.entries(h.rows??{})){const I=O.get(M);I!==void 0&&D.rows.push({rowIndex:I,xml:L})}for(const[M,L]of Object.entries(h.rowExceptions??{})){const I=O.get(M);I!==void 0&&D.rowExceptions.push({rowIndex:I,xml:L})}for(const[M,L]of Object.entries(h.cells??{})){const I=T.byId.get(M);I&&D.cells.push({rowIndex:I.row,gridColumn:I.col,xml:L})}y.propertyOverrides=D}for(const D of p){for(const M of D.tableRevision.markers){const L=W(D,M);if(M.kind==="row-insert"||M.kind==="row-delete"){const S=M.rowId?O.get(M.rowId):M.rowIndex;S!==void 0&&y.rows.push({rowIndex:S,kind:M.kind==="row-insert"?"insert":"delete",...L});continue}if(M.kind==="cell-insert"||M.kind==="cell-delete"){const S=M.cellId?T.byId.get(M.cellId):void 0,R=S?.row??M.rowIndex,z=S?.col??M.gridColumn;R!==void 0&&z!==void 0&&y.cells.push({rowIndex:R,gridColumn:z,kind:M.kind==="cell-insert"?"insert":"delete",...L});continue}if(M.kind==="cell-merge"){const S=M.rowId?O.get(M.rowId):M.rowIndex;S!==void 0&&M.gridColumn!==void 0&&y.merges.push({rowIndex:S,gridColumn:M.gridColumn,...L,...M.vMerge?{vMerge:M.vMerge}:{},...M.vMergeOrig?{vMergeOrig:M.vMergeOrig}:{}});continue}if(M.kind==="table-grid"&&M.currentPropertiesXml&&M.priorPropertiesXml){y.tableGrid={...L,currentXml:M.currentPropertiesXml,priorXml:M.priorPropertiesXml};continue}const I=D.tableRevision.operations.find(S=>S.kind==="properties"&&(M.kind==="table-properties"&&S.target==="table"||M.kind==="row-properties"&&S.target==="row"&&(!M.rowId||S.rowId===M.rowId)||M.kind==="row-exception-properties"&&S.target==="row-exception"&&(!M.rowId||S.rowId===M.rowId)||M.kind==="cell-properties"&&S.target==="cell"&&(!M.cellId||S.cellId===M.cellId))),B=M.currentPropertiesXml??(I?.kind==="properties"?I.currentPropertiesXml:void 0),E=M.priorPropertiesXml??(I?.kind==="properties"?I.priorPropertiesXml:void 0);if(M.kind==="table-properties")y.tableProperties={...L,...B?{currentXml:B}:{},...E?{priorXml:E}:{},...I?.kind==="properties"?{currentAttributes:I.currentAttributes,priorAttributes:I.priorAttributes}:{}};else if(M.kind==="row-properties"||M.kind==="row-exception-properties"){const S=M.rowId?O.get(M.rowId):M.rowIndex;S!==void 0&&(M.kind==="row-properties"?y.rowProperties:y.rowExceptionProperties).push({rowIndex:S,...L,currentXml:B??"",priorXml:E??"",...I?.kind==="properties"?{currentAttributes:I.currentAttributes,priorAttributes:I.priorAttributes,currentTableAttributes:I.currentTableAttributes,priorTableAttributes:I.priorTableAttributes}:{}})}else if(M.kind==="cell-properties"){const S=M.cellId?T.byId.get(M.cellId):void 0,R=S?.row??M.rowIndex,z=S?.col??M.gridColumn;R!==void 0&&z!==void 0&&y.cellProperties.push({rowIndex:R,gridColumn:z,...L,...B?{currentXml:B}:{},...E?{priorXml:E}:{},...I?.kind==="properties"?{currentAttributes:I.currentAttributes,priorAttributes:I.priorAttributes}:{}})}}if(!y.tableGrid){const M=D.tableRevision.operations.find(L=>L.kind==="grid");M?.kind==="grid"&&(y.tableGrid={...W(D,{}),currentXml:M.currentGridXml||X(M.currentColumnWidths),priorXml:M.priorGridXml||X(M.priorColumnWidths)})}}(y.rows.length||y.cells.length||y.merges.length||y.tableGrid||y.rowProperties.length||y.rowExceptionProperties.length||y.cellProperties.length||y.tableProperties||y.propertyOverrides)&&r.push(y);continue}if(o.structuralSuggestionKind!=="change"||!o.structuralSuggestionRecord)continue;let g;try{g=JSON.parse(o.structuralSuggestionRecord)}catch{continue}if(g.type!=="block-change"||g.beforeBlock?.type!=="table"||g.acceptedBlock?.type!=="table")continue;const f=/^docxrev-(\d+)$/.exec(o.structuralSuggestionId??"")?.[1],w=y=>{const T=typeof y?.author=="string"&&y.author.trim()?y.author.trim():typeof g.agentName=="string"&&g.agentName.trim()?g.agentName.trim():g.authorType==="ai"?Ct:"Anonymous",O=typeof y?.createdAt=="number"&&Number.isFinite(y.createdAt)?y.createdAt:typeof g.createdAt=="number"&&Number.isFinite(g.createdAt)?g.createdAt:Date.now(),W=y?.revisionId??f,X=typeof W=="string"&&/^\d+$/.test(W)?Number(W):void 0;return{author:T,date:new Date(O).toISOString(),...X!==void 0?{importedId:X}:{}}},u={tableIndex:s,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},m=g.docxTableRevisions,b=Qe(o),v=new Map(o.children.map((y,T)=>[y.id,T]));if(m?.version===1){for(const y of m.rows??[]){const T=v.get(y.rowId);T!==void 0&&u.rows.push({rowIndex:T,kind:y.kind,...w(y)})}for(const y of m.cells??[]){const T=b.byId.get(y.cellId);T&&u.cells.push({rowIndex:T.row,gridColumn:T.col,kind:y.kind,...w(y)})}for(const y of m.merges??[]){const T=v.get(y.rowId);T!==void 0&&u.merges.push({rowIndex:T,gridColumn:y.gridColumn,...w(y),...y.vMerge?{vMerge:y.vMerge}:{},...y.vMergeOrig?{vMergeOrig:y.vMergeOrig}:{}})}m.tableProperties&&(u.tableProperties={...w(m.tableProperties),...m.tableProperties.priorXml?{priorXml:m.tableProperties.priorXml}:{},...g.beforeBlock.borders?{priorBorders:g.beforeBlock.borders}:{}})}else{const y=new Set(g.beforeBlock.children.map(X=>X.id)),T=new Set(g.acceptedBlock.children.map(X=>X.id));for(let X=0;X<o.children.length;X++){const D=o.children[X];!y.has(D.id)&&T.has(D.id)?u.rows.push({rowIndex:X,kind:"insert",...w()}):y.has(D.id)&&!T.has(D.id)&&u.rows.push({rowIndex:X,kind:"delete",...w()})}const O=Qe(g.beforeBlock),W=Qe(g.acceptedBlock);for(const X of b.cells){const D=O.byId.has(X.cell.id),M=W.byId.has(X.cell.id);!D&&M?u.cells.push({rowIndex:X.row,gridColumn:X.col,kind:"insert",...w()}):D&&!M&&u.cells.push({rowIndex:X.row,gridColumn:X.col,kind:"delete",...w()});const L=O.byId.get(X.cell.id)?.rowSpan??1,I=W.byId.get(X.cell.id)?.rowSpan??1;if(I>L&&X.rowSpan>L)for(let B=L;B<Math.min(I,X.rowSpan);B++)u.merges.push({rowIndex:X.row+B,gridColumn:X.col,vMerge:"cont",...w()})}g.beforeBlock.borders!==g.acceptedBlock.borders&&(u.tableProperties={...w(),...g.beforeBlock.borders?{priorBorders:g.beforeBlock.borders}:{}})}(u.rows.length>0||u.cells.length>0||u.merges.length>0||u.tableProperties)&&r.push(u)}return r}static listWithItemRevisions(e){const r=s=>{try{return s?JSON.parse(s):null}catch{return null}},t=s=>{const l={...s};return delete l.structuralSuggestionId,delete l.structuralSuggestionKind,delete l.structuralSuggestionLabel,delete l.structuralSuggestionRecord,l},i=s=>JSON.stringify(s.flatMap(l=>{const c=JSON.stringify(Object.entries(l.marks??{}).filter(([p,h])=>!p.startsWith("suggestion")&&h!==void 0&&h!==null&&h!==!1).map(([p,h])=>[p,p==="fontFamily"&&typeof h=="string"?h.split(",")[0].replace(/['"]/g,"").trim().toLowerCase():h]).sort(([p],[h])=>String(p).localeCompare(String(h))));return Array.from(l.text,p=>`${p}${c}`)})),n=(s,l,c,p)=>{let h=t(s);const g={suggestionId:c,...p.authorType?{suggestionAuthorType:p.authorType}:{},...p.agentName?{suggestionAuthorName:p.agentName}:{},...p.createdAt!==void 0?{suggestionCreatedAt:p.createdAt}:{}},f=[...s.children,...l.children].some(m=>m.marks?.insertion||m.marks?.deletion||m.marks?.formatChange);if(l.children.length>0&&!f&&i(l.children)!==i(s.children)){const m=(b,v)=>b.map(y=>({...y,marks:{...y.marks,...g,[v]:!0}}));h={...h,children:[...m(l.children,"deletion"),...m(s.children,"insertion")]}}const w={};let u=!1;(l.indentLevel??0)!==(s.indentLevel??0)&&(w.indentLevel=l.indentLevel??0,u=!0);for(const m of this.LIST_ITEM_PROPERTY_FIELDS){const b=l[m]??e[m],v=s[m]??e[m];b!==void 0&&(w[m]=b),JSON.stringify(b)!==JSON.stringify(v)&&(u=!0)}return u&&(h={...h,structuralSuggestionId:c,structuralSuggestionKind:"change",structuralSuggestionRecord:JSON.stringify({type:"block-change",beforeBlock:{type:"paragraph",id:s.id,...w},agentName:p.agentName,authorType:p.authorType,createdAt:p.createdAt})}),h},a=e.structuralSuggestionKind==="change"?r(e.structuralSuggestionRecord):null,o=a?.type==="block-change"&&a.beforeBlock?.type==="list"?a.beforeBlock:null;if(o&&e.structuralSuggestionId){const s=e.structuralSuggestionId,l=a,c=(m,b)=>({...t(m),structuralSuggestionId:s,structuralSuggestionKind:b,structuralSuggestionRecord:JSON.stringify({agentName:l.agentName,authorType:l.authorType,createdAt:l.createdAt})}),p=new Set(e.children.map(m=>m.id)),h=new Map(o.children.map(m=>[m.id,m])),g=new Map;let f=null;for(const m of o.children)p.has(m.id)?f=m.id:g.set(f,[...g.get(f)??[],c(m,"delete")]);const w=[...g.get(null)??[]];for(const m of e.children){const b=h.get(m.id);w.push(b?n(m,b,s,l):c(m,"insert"),...g.get(m.id)??[])}const u={...e,children:w};return delete u.structuralSuggestionKind,u}return e.children.some(s=>s.structuralSuggestionKind==="change")?{...e,children:e.children.map(s=>{if(s.structuralSuggestionKind!=="change")return s;const l=r(s.structuralSuggestionRecord),c=l?.listItemSuggestion?.beforeItem;return!l||!c||!s.structuralSuggestionId?s:n(s,c.children.length>0?c:{...c,children:s.children},s.structuralSuggestionId,l)})}:e}static pendingListNumberingChanges(e){const r=[],t=i=>{if(i.type==="list"){if(i.structuralSuggestionKind==="change")try{const n=JSON.parse(i.structuralSuggestionRecord??"{}").beforeBlock;n?.type==="list"&&(n.variant!==i.variant||(n.startNumber??1)!==(i.startNumber??1)||(n.numberingFormat??null)!==(i.numberingFormat??null))&&r.push(i.id)}catch{}return}if(i.type==="table")for(const n of i.children)for(const a of n.children)a.children.forEach(t);else if("children"in i&&Array.isArray(i.children))for(const n of i.children)n&&typeof n=="object"&&"type"in n&&t(n)};return e.forEach(t),r}static pendingLinkChangeAsReplacement(e){const r=e.marks;if(!r?.formatChange||r.insertion||r.deletion)return null;let t;try{t=JSON.parse(r.suggestionPriorAttributes??"{}")}catch{return null}if((t.link??null)===(r.link??null))return null;const i=Object.fromEntries(Object.entries(r).filter(([a])=>a.startsWith("suggestion")&&a!=="suggestionPriorAttributes")),n=Object.fromEntries(Object.entries(r).filter(([a])=>a!=="formatChange"&&!a.startsWith("suggestion")));return[{...e,marks:{...t,...i,deletion:!0}},{...e,marks:{...n,...i,insertion:!0}}]}static runRevisionsForBlockChange(e){if(e.structuralSuggestionKind!=="change")return e.children;let r;try{r=JSON.parse(e.structuralSuggestionRecord??"{}")}catch{return e.children}const t=r.beforeBlock;if(r.type!=="block-change"||t?.type!=="paragraph")return e.children;const i=s=>s.map(l=>l.type==="text"?l.text:"\0").join("");if(i(t.children)!==i(e.children)||[...t.children,...e.children].some(s=>s.type!=="text"||s.marks?.insertion||s.marks?.deletion||s.marks?.formatChange))return e.children;const n=s=>JSON.stringify(s.map(l=>{const c=Object.fromEntries(Object.entries(l.marks??{}).filter(([p])=>!p.startsWith("suggestion")).sort(([p],[h])=>p.localeCompare(h)));return[l.text,c]}));if(n(t.children)===n(e.children))return e.children;const a={suggestionId:e.structuralSuggestionId,...r.authorType?{suggestionAuthorType:r.authorType}:{},...r.agentName?{suggestionAuthorName:r.agentName}:{},...r.createdAt!==void 0?{suggestionCreatedAt:r.createdAt}:{}},o=(s,l)=>s.map(c=>({...c,marks:{...c.marks,...a,[l]:!0}}));return[...o(t.children,"deletion"),...o(e.children,"insertion")]}static dropReplacementSeparators(e){return e.filter((r,t)=>{if(r.type!=="text")return!0;const i=r;if(i.marks?.insertion||i.marks?.deletion||!/^\s+$/.test(i.text))return!0;const n=e[t-1],a=e[t+1];return!(n?.type==="text"&&a?.type==="text"&&n.marks?.deletion&&a.marks?.insertion&&a.marks.suggestionId&&n.marks.suggestionId===a.marks.suggestionId)})}static textNodeToDocxWithLatex(e,r){if(e.marks?.latex){const t=this.latexToOmml(e.text,!1);return t?[{text:"",mathOmml:t}]:[{text:e.text}]}return this.textNodeToDocx(e,r)}static paragraphToDocx(e,r,t=this.resolveIndentStepPx()){const i={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(i.styleId=e.styleId),e.heading&&(i.heading=`HEADING_${e.heading}`);{const o=this.docxAlignmentForExport(e);o&&(i.alignment=o)}e.lineSpacing!==void 0&&(i.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(i,e),e.keepNext&&(i.keepNext=!0),e.keepLines&&(i.keepLines=!0),e.widowControl===!1&&(i.widowControl=!1),e.borders&&(i.bordersJson=e.borders),e.shading&&(i.shadingFill=e.shading),e.tabStops&&(i.tabStopsJson=e.tabStops),e.oxmlAttrs&&(i.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(i.oxmlPPr=e.oxmlPPr);const n=this.buildParagraphIndent(e,t);n&&(i.indent=n);const a=e;return a.fontFamily&&(i.style=a.fontFamily),this.applyParagraphMarkRevisionInfo(i,e),this.applyParagraphPropertyChangeInfo(i,e,t),e.children.length===0?(this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i):(this.dropReplacementSeparators(this.runRevisionsForBlockChange(e)).forEach(o=>{if(o.type==="text"){const s=this.textNodeToDocx(o,r);i.children.push(...s)}}),this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i)}static listToDocxParagraphs(e,r,t){e=this.listWithItemRevisions(e);const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const a of e.children){if(a.type!=="list-item")continue;const o=this.getClampedIndentLevel(a.indentLevel),s={type:"paragraph",sourceBlockId:a.id,children:[],lineSpacing:a.lineSpacing??e.lineSpacing,...typeof(a.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(a.spaceBefore??e.spaceBefore)}:{},...typeof(a.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(a.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",checked:e.variant==="todo"?!!a.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,a,n);s.list&&(s.list.label=l),e.variant==="todo"&&s.children.push({text:`${l} `}),a.children.length>0&&a.children.forEach(c=>{if(c.type==="text"){const p=this.textNodeToDocx(c,r);s.children.push(...p)}}),this.applyWholeBlockRevisionInfo(s,a.structuralSuggestionKind?a:e),this.applyParagraphPropertyChangeInfo(s,a,0),i.push(s)}return i}static marksToDocxRunOptions(e,r){const t={};if(e){e.bold!==void 0&&(t.bold=e.bold),e.italic!==void 0&&(t.italic=e.italic),e.underline!==void 0&&(t.underline=e.underline?"SINGLE":"NONE"),e.strikethrough!==void 0&&(t.strike=e.strikethrough),e.doubleStrikethrough!==void 0&&(t.doubleStrike=e.doubleStrikethrough),e.smallCaps!==void 0&&(t.smallCaps=e.smallCaps),e.allCaps!==void 0&&(t.allCaps=e.allCaps),e.hidden!==void 0&&(t.vanish=e.hidden),e.lang&&(t.lang=e.lang),typeof e.letterSpacing=="number"&&Number.isFinite(e.letterSpacing)&&(t.characterSpacing=Math.round(e.letterSpacing*15)),e.superscript&&(t.superScript=!0),e.subscript&&(t.subScript=!0),!e.superscript&&!e.subscript&&(e.superscript===!1||e.subscript===!1)&&(t.baseline=!0),e.color&&(t.color=this.normalizeColor(e.color)),e.backgroundColor&&(t.highlight=this.colorToHighlight(e.backgroundColor));const i=new Set(e.docxRunPropertyResets?.split(",").filter(Boolean)??[]);i.has("color")&&(t.color="auto"),i.has("highlight")&&(t.highlight="none"),e.fontFamily?t.font=e.fontFamily:e.code&&(t.font="Courier New",t.highlight="lightGray",t.characterStyle=this.CODE_INLINE_STYLE_ID),e.fontSize&&(t.size=this.pxToDocxHalfPoints(e.fontSize))}return t.size===void 0&&!e?.code&&this.exportDefaultRunSizeHalfPoints!==void 0&&(t.size=this.exportDefaultRunSizeHalfPoints),e&&(e.link&&(t.link=e.link),e.oxmlRPr&&(t.oxmlRPr=e.oxmlRPr)),!t.font&&r&&(t.font=r),t}static suggestionRevisionAttrs(e){const r=e.suggestionAuthorName?.trim()||(e.suggestionAuthorType==="ai"?"Revise Agent":"Anonymous"),t=new Date(typeof e.suggestionCreatedAt=="number"?e.suggestionCreatedAt:Date.now()).toISOString(),i=typeof e.suggestionId=="string"?/^docxrev-(\d+)$/.exec(e.suggestionId):null;return{author:r,date:t,...i?{importedId:Number(i[1])}:{}}}static textNodeToDocx(e,r){const t=this.pendingLinkChangeAsReplacement(e);if(t)return t.flatMap(o=>this.textNodeToDocx(o,r));const i=this.marksToDocxRunOptions(e.marks,r);if(e.marks?.comment&&(i.comment=e.marks.comment),e.marks?.bookmark&&(i.bookmark=e.marks.bookmark),e.marks?.oxmlRange&&(i.oxmlRange=e.marks.oxmlRange),e.marks?.sdtInline&&(i.sdtInline=e.marks.sdtInline),e.marks?.fieldInstr&&(i.fieldInstr=e.marks.fieldInstr),e.marks?.insertion||e.marks?.deletion){const o=this.parseDocxMoveMark(e.marks.docxMove),s=o&&/^\d+$/.test(o.wrapperId)?Number(o.wrapperId):void 0;let l;if(e.marks.deletion&&e.marks.layeredInsertion)try{const c=JSON.parse(e.marks.layeredInsertion),p=typeof c.id=="string"?/^docxrev-(\d+)$/.exec(c.id):null;l={author:c.authorName?.trim()||(c.authorType==="ai"?"Revise Agent":"Anonymous"),date:new Date(typeof c.createdAt=="number"?c.createdAt:Date.now()).toISOString(),...p?{importedId:Number(p[1])}:{}}}catch{l=void 0}i.revision={kind:e.marks.deletion?"delete":"insert",...this.suggestionRevisionAttrs(e.marks),...s!==void 0?{importedId:s}:{},...o?{move:o}:{},...l?{layeredInsertion:l}:{}}}else if(e.marks?.formatChange){let o={};try{o=JSON.parse(e.marks.suggestionPriorAttributes??"{}")}catch{o={}}i.rPrChange={...this.suggestionRevisionAttrs(e.marks),prior:this.marksToDocxRunOptions(o)}}if(e.marks?.footnoteRef){const o=parseInt(e.text,10);return[{...i,text:"",footnoteReference:Number.isFinite(o)&&o>0?o:1}]}const n=e.text.split(`
|
|
13
|
+
`),a=[];for(let o=0;o<n.length;o++){const s=n[o];(s||o===0)&&a.push({...i,text:s}),o<n.length-1&&a.push({...i,text:"",break:!0})}return a.length===0&&a.push({...i,text:""}),a}static getListIndentOptions(e){const r=Math.max(0,Math.min(2,Math.floor(e)));return{left:this.LIST_BASE_INDENT_TWIPS+r*this.LIST_INDENT_INCREMENT_TWIPS,hanging:this.LIST_HANGING_INDENT_TWIPS}}static getListLabel(e,r,t){const i=this.getClampedIndentLevel(r.indentLevel);if(e.variant==="unordered"){const n=["•","◦","▪"];return n[Math.min(i,n.length-1)]}return e.variant==="todo"?r.checked?"☒":"☐":this.computeOrderedLabel(e.startNumber??1,i,t)}static numberingFormatHash(e){let r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r+e.charCodeAt(t)|0;return(r>>>0).toString(36)}static buildOrderedNumberingExportPlan(e){const r=new Map,t=new Map,i=new Map,n=new Map,a=s=>{if(s.variant==="ordered")if(s.numberingChainId){const l=s.numberingChainId;let c=i.get(l);if(!c||s.startNumber!==void 0){const p=c?c.segmentIndex+1:0,h=`revise-chain-${l.replace(/[^A-Za-z0-9_-]/g,"")}-s${p}`;c={reference:h,segmentIndex:p},i.set(l,c),t.set(h,{start:s.startNumber??1,formatJson:s.numberingFormat})}r.set(s.id,{reference:c.reference,instance:0})}else{const l=s.startNumber??1,c=s.numberingFormat?`revise-ordered-${l}-f${this.numberingFormatHash(s.numberingFormat)}`:`revise-ordered-${l}`;t.has(c)||t.set(c,{start:l,formatJson:s.numberingFormat});const p=n.get(c)??0;n.set(c,p+1),r.set(s.id,{reference:c,instance:p})}},o=s=>{for(const l of s)if(l.type==="list")a(l);else if(l.type==="container"||l.type==="footnote")o(l.children);else if(l.type==="table")for(const c of l.children)for(const p of c.children)o(p.children)};return o(e.children),e.notes&&o(e.notes),{byListId:r,references:t}}static getDocxListReference(e){if(e.variant!=="todo")return e.variant==="unordered"?"revise-unordered":`revise-ordered-${e.startNumber??1}`}static buildDocxNumberingConfig(e,r){const t=[];let i=!1;const n=s=>{for(const l of s)if(l.type==="list"&&l.variant==="unordered")i=!0;else if(l.type==="container"||l.type==="footnote")n(l.children);else if(l.type==="table")for(const c of l.children)for(const p of c.children)n(p.children)};n(e.children),e.notes&&n(e.notes);const a=this.buildOrderedNumberingExportPlan(e).references;i&&t.push({reference:"revise-unordered",levels:[0,1,2].map(s=>({level:s,format:r.LevelFormat.BULLET,text:["•","◦","▪"][s],alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(s)}}}))});const o=s=>{switch((s||"decimal").trim()){case"lowerLetter":return r.LevelFormat.LOWER_LETTER;case"upperLetter":return r.LevelFormat.UPPER_LETTER;case"lowerRoman":return r.LevelFormat.LOWER_ROMAN;case"upperRoman":return r.LevelFormat.UPPER_ROMAN;case"decimalZero":return r.LevelFormat.DECIMAL_ZERO??r.LevelFormat.DECIMAL;case"bullet":return r.LevelFormat.BULLET;case"none":return r.LevelFormat.NONE??r.LevelFormat.DECIMAL;default:return r.LevelFormat.DECIMAL}};for(const[s,l]of a){const c=l.start,p=l.formatJson?(()=>{try{const h=JSON.parse(l.formatJson);return Array.isArray(h)?h:void 0}catch{return}})():void 0;if(p){t.push({reference:s,levels:[0,1,2].map(h=>({level:h,format:o(p[h]?.numFmt),text:p[h]?.lvlText??["%1.","%1.%2.","%1.%2.%3."][h],start:h===0?c:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(h)}}}))});continue}t.push({reference:s,levels:[{level:0,format:r.LevelFormat.DECIMAL,text:"%1.",start:c,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(0)}}},{level:1,format:r.LevelFormat.LOWER_LETTER,text:"%1 %2.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(1)}}},{level:2,format:r.LevelFormat.LOWER_ROMAN,text:"%1 %2 %3.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(2)}}}]})}return t.length>0?{config:t}:void 0}static computeOrderedLabel(e,r,t){return r<=0?(t.level0=Math.max(t.level0+1,e),t.level1=0,t.level2=0,`${t.level0}.`):r===1?(t.level0<e&&(t.level0=e),t.level1+=1,t.level2=0,`${t.level0} ${this.toAlphabetic(t.level1)}.`):(t.level0<e&&(t.level0=e),t.level1===0&&(t.level1=1),t.level2+=1,`${t.level0} ${this.toAlphabetic(t.level1)} ${this.toRoman(t.level2)}.`)}static toAlphabetic(e){let r=Math.max(1,e),t="";for(;r>0;)r-=1,t=String.fromCharCode(97+r%26)+t,r=Math.floor(r/26);return t}static toRoman(e){const r=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];let t=Math.max(1,e),i="";for(const[n,a]of r){for(;t>=n;)i+=a,t-=n;if(t===0)break}return i||"i"}static getClampedIndentLevel(e){if(!Number.isFinite(e))return 0;const r=Math.floor(e);return Math.max(0,Math.min(2,r))}static async resolveImageSourceForDocx(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(r){const t=r[1].toLowerCase(),i=this.docxImageTypeForMimeType(t);if(!i)return;const n=!!r[2],a=r[3]||"",o=n?this.base64ToUint8Array(a):new TextEncoder().encode(decodeURIComponent(a));return{type:i,data:o}}if(typeof fetch=="function")try{const t=await fetch(e);if(!t.ok)return;const i=await t.blob(),n=this.docxImageTypeForMimeType(i.type||this.inferMimeTypeFromPath(e)||"");return n?{type:n,data:new Uint8Array(await i.arrayBuffer())}:void 0}catch{return}}static base64ToUint8Array(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const r=atob(e),t=new Uint8Array(r.length);for(let i=0;i<r.length;i++)t[i]=r.charCodeAt(i);return t}static inferMimeTypeFromPath(e){const r=e.split("?")[0].toLowerCase();if(r.endsWith(".png"))return"image/png";if(r.endsWith(".jpg")||r.endsWith(".jpeg"))return"image/jpeg";if(r.endsWith(".gif"))return"image/gif";if(r.endsWith(".bmp"))return"image/bmp"}static docxImageTypeForMimeType(e){switch(e.toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/gif":return"gif";case"image/bmp":return"bmp";default:return}}static toDocxHex(e){return e?$r(e)?.slice(1).toUpperCase():void 0}static normalizeColor(e){return this.toDocxHex(e)??"000000"}static highlightValueToColor(e){return tr(e)??"yellow"}static colorToHighlight(e){const r=tr(e);if(r)return{yellow:"yellow",orange:"darkYellow",green:"green",blue:"blue",purple:"darkMagenta",pink:"magenta",gray:"lightGray"}[r]||"yellow";const t=this.normalizeColor(e);return{FFFF00:"yellow",FF0000:"red","00FF00":"green","0000FF":"blue",FFA500:"orange",FF00FF:"magenta","00FFFF":"cyan",808080:"darkGray",D3D3D3:"lightGray"}[t]||"yellow"}};ue.LIST_BASE_INDENT_TWIPS=720,ue.LIST_INDENT_INCREMENT_TWIPS=360,ue.LIST_HANGING_INDENT_TWIPS=360,ue.TWIPS_PER_INCH=1440,ue.TWIPS_PER_PX=ue.TWIPS_PER_INCH/96,ue.DOCX_HALF_POINTS_PER_PX=1.5,ue.DEFAULT_RUN_SIZE_HALF_POINTS=ue.pxToDocxHalfPoints(Ae.paragraph),ue.PAGE_SIZE_PRESETS=Object.entries(Ni).map(([F,e])=>({preset:F,width:Math.min(e.width,e.height),height:Math.max(e.width,e.height)})),ue.CORE_PROPERTY_LOCAL_NAMES=["title","creator","subject","keywords","description","lastModifiedBy","created","modified","revision"],ue.LIST_ITEM_PROPERTY_FIELDS=["spaceBefore","spaceAfter","lineSpacing","direction"],ue.TODO_MARKERS=[["☒ ",!0],["☐ ",!1],["[x] ",!0],["[X] ",!0],["[ ] ",!1]],ue.fallbackCommentState={},ue.sdtAncestorStack=[],ue.OXML_RANGE_PAIRS=new Map([["w:permStart","w:permEnd"]]),ue.UNTRACKABLE_MOVE_KINDS=new Set(["image","code","math","page-break","toc"]),ue.OMML_FUNCTION_NAMES=["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"],ue.CODE_BLOCK_STYLE_ID="CodeBlock",ue.CODE_INLINE_STYLE_ID="CodeInline";let Bn=ue;export{Bn as DocxConverter};
|