@betteroffice/docx 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +522 -3
  2. package/dist/{chunk-JHJLG4I6.mjs → chunk-5B4VMUXM.mjs} +1 -1
  3. package/dist/chunk-5JEQC76K.mjs +1 -0
  4. package/dist/chunk-7GJG6LLU.mjs +1 -0
  5. package/dist/chunk-FE6FWGBJ.mjs +1 -0
  6. package/dist/chunk-H5YYCN42.mjs +1 -0
  7. package/dist/chunk-NT2OYIJ4.mjs +57 -0
  8. package/dist/chunk-QE4ZDRKV.mjs +1 -0
  9. package/dist/chunk-VQXNED2P.mjs +2 -0
  10. package/dist/chunk-Z4HZIPBS.mjs +1 -0
  11. package/dist/collaboration/index.d.mts +8 -6
  12. package/dist/compareDocx-XXTZV4CG.mjs +1 -0
  13. package/dist/computeLayout-LWLAJWYA.mjs +1 -0
  14. package/dist/{content-CvEtPl0c.d.mts → content-BzoC6bSz.d.mts} +48 -8
  15. package/dist/core.d.mts +172 -9
  16. package/dist/core.mjs +1 -1
  17. package/dist/{displayListQueries-DF8F6fMl.d.mts → displayListQueries-BYFrBkw5.d.mts} +2 -2
  18. package/dist/docx/index.d.mts +5 -4
  19. package/dist/docx/index.mjs +1 -1
  20. package/dist/editor/index.d.mts +10 -8
  21. package/dist/editor/index.mjs +1 -1
  22. package/dist/{fontLoader-b8eicJKV.d.mts → fontLoader-CkXcPB1C.d.mts} +1 -1
  23. package/dist/{formatting-7zKCTu5a.d.mts → formatting-gqLFeJ9X.d.mts} +8 -0
  24. package/dist/{frameDelta-pA4jrQ1G.d.mts → frameDelta-CVt5FAXT.d.mts} +14 -3
  25. package/dist/generated/edit/docx_edit_bg.wasm +0 -0
  26. package/dist/generated/layout/docx_layout_bg.wasm +0 -0
  27. package/dist/generated/opc/ooxml_opc_bg.wasm +0 -0
  28. package/dist/generated/parse/docx_parse_bg.wasm +0 -0
  29. package/dist/{index-CHl2zLJ7.d.mts → index-BbZwdkPz.d.mts} +457 -29
  30. package/dist/layout/index.d.mts +6 -6
  31. package/dist/layout/index.mjs +1 -1
  32. package/dist/layout/pagination/index.d.mts +4 -4
  33. package/dist/layout/render/index.d.mts +12 -10
  34. package/dist/layout/render/index.mjs +1 -1
  35. package/dist/pagedExport-D3E4jZ-B.d.mts +907 -0
  36. package/dist/plugin-api/RenderedDomContext.d.mts +10 -9
  37. package/dist/plugin-api/RenderedDomContext.mjs +1 -1
  38. package/dist/plugin-api/index.d.mts +21 -4
  39. package/dist/plugin-api/resolveItemPositions.d.mts +3 -3
  40. package/dist/rezip-Bxiq4Z_R.d.mts +24 -0
  41. package/dist/{rustDisplayList-BJqaN9tt.d.mts → rustDisplayList-CwOoUn3t.d.mts} +2 -2
  42. package/dist/{rustMeasureSource-C0EZB055.d.mts → rustMeasureSource-CyBMcy1x.d.mts} +12 -4
  43. package/dist/{selectiveSave-CRh-_Y_C.d.mts → selectiveSave-r-NMK6aI.d.mts} +1 -22
  44. package/dist/styles/index.d.mts +2 -2
  45. package/dist/{styles-7e-mq3c-.d.mts → styles-AryxLAhx.d.mts} +1 -1
  46. package/dist/types/content.d.mts +2 -2
  47. package/dist/types/document.d.mts +6 -6
  48. package/dist/{types-C4A8mWjU.d.mts → types-B4jD0rrc.d.mts} +19 -2
  49. package/dist/utils/comments.d.mts +2 -2
  50. package/dist/utils/index.d.mts +7 -4
  51. package/dist/utils/index.mjs +1 -1
  52. package/dist/utils/stylePreview.d.mts +2 -2
  53. package/dist/wasm-G62X4WRW.mjs +1 -0
  54. package/dist/wasm-US6R7SWN.mjs +1 -0
  55. package/dist/wasm-edit.d.mts +246 -13
  56. package/dist/wasm-edit.mjs +1 -1
  57. package/dist/wasm-layout.d.mts +8 -1
  58. package/dist/wasm-layout.mjs +1 -1
  59. package/dist/yrs/index.d.mts +7 -5
  60. package/dist/yrs/index.mjs +1 -1
  61. package/dist/yrs/residentEngineWorker.mjs +1 -1
  62. package/package.json +2 -2
  63. package/dist/chunk-6LQJAKOC.mjs +0 -1
  64. package/dist/chunk-AFMVSI4Z.mjs +0 -57
  65. package/dist/chunk-GD4VNJ64.mjs +0 -1
  66. package/dist/chunk-WRWRCBLK.mjs +0 -1
  67. package/dist/chunk-WTFRNX5K.mjs +0 -1
  68. package/dist/wasm-7SOSHNGP.mjs +0 -1
  69. package/dist/wasm-ZQAVP7P2.mjs +0 -1
@@ -1 +1 @@
1
- export{a as residentCaretDeviceRect,b as residentCaretSnapshotForFrame}from'../chunk-J7LNO6SM.mjs';import {b as b$5}from'../chunk-OBQGPMPQ.mjs';import {d,a,b as b$3}from'../chunk-47Q2FMFF.mjs';import {b as b$2,p}from'../chunk-LTVVQMHB.mjs';import {c as c$1,b as b$4}from'../chunk-CTBUQRYQ.mjs';import {b as b$1,c}from'../chunk-6LQJAKOC.mjs';import'../chunk-ACGKK7IB.mjs';import'../chunk-5F6DLQZP.mjs';import {b}from'../chunk-TTRUPDAB.mjs';function Qn(e,t){let n=0,r=t.map(i=>{let o={paraId:i.paraId,length:Math.max(0,Math.trunc(i.length)),displayStart:n};return n+=o.length+2,o});return {story:e,paragraphs:r}}function De(e,t){let n=e.paragraphs.find(r=>r.paraId===t.paraId);return !n||t.story!==e.story?e.paragraphs[0]?.displayStart??0:n.displayStart+1+Math.min(Math.max(0,t.offset),n.length)}function er(e,t){if(e.paragraphs.length===0)return null;let n=Math.max(0,Math.trunc(t)),r=e.paragraphs[0];for(let i of e.paragraphs){if(i.displayStart>n)break;r=i;}return {story:e.story,paraId:r.paraId,offset:Math.min(Math.max(0,n-(r.displayStart+1)),r.length)}}function tr(e,t,n){return De(e,t)-De(e,n)}var At={bootstrap:15e3,sync:15e3,attachCanvases:15e3,buildFrame:5e3,applyInput:5e3,applyDelete:5e3};function Ft(){return new Worker(new URL("./residentEngineWorker.mjs",import.meta.url),{type:"module",name:"openooxml-resident-engine"})}var ce=class{constructor(t=Ft()){b(this,"worker",t);b(this,"pending",new Map);b(this,"nextId",1);b(this,"terminalError",null);b(this,"ready",false);b(this,"revision",0);b(this,"remoteVector",null);b(this,"appliedFontsRevision",null);this.worker.onmessage=n=>{let r=n.data;if(r.ok&&r.stateVector&&(this.remoteVector=new Uint8Array(r.stateVector)),!r.ok&&r.terminal){this.fail(new $(r.error));return}let i=this.pending.get(r.id);i&&(this.pending.delete(r.id),clearTimeout(i.timeout),r.ok?i.resolve(r):i.reject(Yt(r.error,r.residentUnavailable)));},this.worker.onerror=n=>{this.fail(new J(`Resident engine worker failed: ${n.message}`));},this.worker.onmessageerror=()=>{this.fail(new J("Resident engine worker returned an unreadable message"));};}isReady(){return this.ready}layoutRevision(){return this.revision}remoteStateVector(){return this.remoteVector}syncedFontsRevision(){return this.appliedFontsRevision}async bootstrap(t,n){let r=t.fontsRevision,i=await this.request({type:"bootstrap",snapshot:t,extras:n,expectedFrameEpoch:0},Je(t)),o=G(i);return this.recordSync(i,r),this.ready=true,this.revision=o.layoutRevision,o}async sync(t,n,r,i=false){let o=t.fontsRevision,a=await this.request({type:"sync",snapshot:t,extras:n,expectedFrameEpoch:r,paintCaret:i},Je(t)),l=G(a);return this.recordSync(a,o),this.ready=true,this.revision=l.layoutRevision,l}async buildFrame(t,n,r=false){return G(await this.request({type:"buildFrame",extras:t,expectedFrameEpoch:n,paintCaret:r}))}async applyInput(t,n,r,i=false,o=false){if(!this.ready)return {applied:false};try{return {applied:!0,...G(await this.request({type:"applyInput",text:t,selection:n,expectedFrameEpoch:r,profile:i,paintCaret:o}))}}catch(a){if(a instanceof $)return {applied:false};throw a}}async applyDelete(t,n,r,i=false,o=false){if(!this.ready)return {applied:false};try{return {applied:!0,...G(await this.request({type:"applyDelete",direction:t,selection:n,expectedFrameEpoch:r,profile:i,paintCaret:o}))}}catch(a){if(a instanceof $)return {applied:false};throw a}}eraseCaret(){if(this.terminalError)return;let n={id:this.nextId++,type:"eraseCaret"};this.worker.postMessage(n);}invalidate(t,n){if(this.terminalError)return;this.ready=false;let r=t.slice(),o={id:this.nextId++,type:"applyUpdate",update:r,selection:n};this.worker.postMessage(o,[r.buffer]);}async attachCanvases(t,n,r,i,o){let a=t.map(l=>l.canvas);await this.request({type:"attachCanvases",pages:t,activePageIds:n,devicePixelRatio:r,zoom:i,caretStyle:o},a);}destroy(){if(this.terminalError)return;let n={id:this.nextId++,type:"destroy"};this.worker.postMessage(n),this.fail(new J("Resident engine worker was destroyed"));}request(t,n=[]){if(this.terminalError)return Promise.reject(this.terminalError);let r=this.nextId++,i=At[t.type];return new Promise((o,a)=>{let l=setTimeout(()=>{this.fail(new J(`Resident engine worker did not answer ${t.type} within ${i}ms`));},i);this.pending.set(r,{resolve:o,reject:a,timeout:l}),this.worker.postMessage({...t,id:r},n);})}recordSync(t,n){this.appliedFontsRevision=n;}fail(t){this.terminalError=t,this.ready=false,this.worker.terminate();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(t);this.pending.clear();}},$=class extends Error{},J=class extends Error{};function Yt(e,t=false){return t?new $(e):new Error(e)}function Je(e){return [e.state.buffer,...e.fonts.map(t=>t.buffer)]}function G(e){if(!e.frame)throw new J("Resident engine worker response omitted its FrameDelta");if(!e.caret)throw new J("Resident engine worker response omitted its caret snapshot");if(e.selection===void 0)throw new J("Resident engine worker response omitted its selection");return {frame:new Uint8Array(e.frame),updates:(e.updates??[]).map(t=>new Uint8Array(t)),engineMs:e.engineMs??0,workerTotalMs:e.workerTotalMs??0,engineProfile:e.engineProfile,caret:e.caret,selection:e.selection,caretPainted:e.caretPainted??false,replayMs:e.replayMs??0,replayedPages:e.replayedPages??0,layoutRevision:e.layoutRevision??0}}function Mt(){return typeof Worker<"u"}function ne(e){return e.type==="rawXml"}function pe(e){return {sdtType:e.sdtType,id:e.id??null,alias:e.alias??null,tag:e.tag??null,lock:e.lock??null,placeholder:e.placeholder??null,showingPlaceholder:e.showingPlaceholder??false,dateFormat:e.dateFormat??null,listItems:e.listItems?JSON.stringify(e.listItems):null,checked:e.checked??null,dataBinding:e.dataBinding?JSON.stringify(e.dataBinding):null,rawPropertiesXml:e.rawPropertiesXml??null,rawEndPropertiesXml:e.rawEndPropertiesXml??null}}function fe(e){let t={sdtType:e.sdtType??"richText"};if(typeof e.id=="number"&&(t.id=e.id),e.alias!=null&&(t.alias=String(e.alias)),e.tag!=null&&(t.tag=String(e.tag)),e.lock!=null&&(t.lock=e.lock),e.placeholder!=null&&(t.placeholder=String(e.placeholder)),e.showingPlaceholder&&(t.showingPlaceholder=true),e.dateFormat!=null&&(t.dateFormat=String(e.dateFormat)),typeof e.listItems=="string"&&e.listItems)try{t.listItems=JSON.parse(e.listItems);}catch{}if(e.checked!=null&&(t.checked=e.checked),typeof e.dataBinding=="string"&&e.dataBinding)try{t.dataBinding=JSON.parse(e.dataBinding);}catch{}return e.rawPropertiesXml!=null&&(t.rawPropertiesXml=String(e.rawPropertiesXml)),e.rawEndPropertiesXml!=null&&(t.rawEndPropertiesXml=String(e.rawEndPropertiesXml)),t}function ge(e,t,n,r,i,o){let a=t?.pPr;if(!t?.tblStylePr?.some(I=>I.pPr))return a;let l=e.formatting?.look??t.tblPr?.look,d=(I,M)=>l?.[I]??(Number.parseInt(l?.value??(l?"0":"04A0"),16)&M)!==0,m=d("firstRow",32),u=d("lastRow",64),c=d("firstColumn",128),y=d("lastColumn",256),f=e.rows[n].formatting?.gridBefore??0;r+=f,i+=f;let h=!!m&&n===0,g=!!u&&n===e.rows.length-1,k=!!c&&r===0,w=!!y&&i===o,T=e.formatting?.styleRowBandSize??t.tblPr?.styleRowBandSize??1,v=e.formatting?.styleColBandSize??t.tblPr?.styleColBandSize??1,P=[];!d("noHBand",512)&&!h&&!g&&T>0&&P.push(Math.floor((n-+!!m)/T)%2===0?"band1Horz":"band2Horz"),!d("noVBand",1024)&&!k&&!w&&v>0&&P.push(Math.floor((r-+!!c)/v)%2===0?"band1Vert":"band2Vert");for(let[I,M]of [["firstCol",k],["lastCol",w],["firstRow",h],["lastRow",g],["nwCell",h&&k],["neCell",h&&w],["swCell",g&&k],["seCell",g&&w]])M&&P.push(I);for(let I of P)a=b$3(a,t.tblStylePr.find(M=>M.type===I)?.pPr);return a}function Ue(e){return Math.max(e.columnWidths?.length??0,...e.rows.map(t=>t.cells.reduce((n,r)=>n+(r.formatting?.gridSpan??1),(t.formatting?.gridBefore??0)+(t.formatting?.gridAfter??0))))}function E(e){if(Array.isArray(e))return e.map(E);if(e!==null&&typeof e=="object"){let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=E(r));return t}return e}var _t={styleId:"pStyle",_sectionProperties:"sectPr"},Bt=new Set(["paraId","textId","renderedPageBreakBefore","numPrFromStyle"]);function We(e){let t={};for(let[n,r]of Object.entries(e))Bt.has(n)||r===null||r===void 0||(t[_t[n]??n]=E(r));return t}var Ot=new Set(["columnWidths"]);function re(e,t=new Set){let n={};for(let[r,i]of Object.entries(e))t.has(r)||i===null||i===void 0||(n[r]=E(i));return n}function je(e){return re(e,Ot)}function ze(e){let t=e.columnWidths;return Array.isArray(t)?t.map(E):[]}function $e(e){return re(e)}function He(e,t){let n=re(e);return t&&(n.header=true),n}function me(e,t,n,r){return `${e}:t${t}:r${n}c${r}`}function Ve(e,t){return `${e}:sdt${t}`}function Ke(e){return re(e)}function oe(e){return `hf:${e}`}function Xe(e){return `fn:${e}`}function qe(e){return `en:${e}`}var Nt=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function H(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(H).join(",")}]`;if(typeof e=="object"){let t=e;return `{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${H(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Et(e,t){if(!e||!t)return e;let n=t.resolveRunStyle(e.styleId);return n?a(n,e):e}function Qe(e){if(!e)return [];let t=[],n=(a,l={})=>t.push({name:a,attrs:l});e.bold&&n("bold"),e.italic&&n("italic"),e.underline&&e.underline.style!=="none"&&n("underline",{style:e.underline.style,color:e.underline.color??null}),(e.strike||e.doubleStrike)&&n("strike",{double:e.doubleStrike||false}),e.color&&!e.color.auto&&n("textColor",{rgb:e.color.rgb??null,themeColor:e.color.themeColor??null,themeTint:e.color.themeTint??null,themeShade:e.color.themeShade??null});let r=e.shading?.fill,i=(!e.shading?.pattern||e.shading.pattern==="clear")&&r?.rgb&&!r.auto?p(r.rgb):void 0,o=e.highlight&&e.highlight!=="none"?e.highlight:i;return o&&n("highlight",{color:o}),(e.fontSize!=null||e.fontSizeCs!=null)&&n("fontSize",{size:e.fontSize??null,sizeCs:e.fontSizeCs??null}),e.fontFamily&&n("fontFamily",{ascii:e.fontFamily.ascii??null,hAnsi:e.fontFamily.hAnsi??null,eastAsia:e.fontFamily.eastAsia??null,cs:e.fontFamily.cs??null,asciiTheme:e.fontFamily.asciiTheme??null,hAnsiTheme:e.fontFamily.hAnsiTheme??null,eastAsiaTheme:e.fontFamily.eastAsiaTheme??null,csTheme:e.fontFamily.csTheme??null}),e.vertAlign==="superscript"?n("superscript"):e.vertAlign==="subscript"&&n("subscript"),e.allCaps&&n("allCaps"),e.smallCaps&&n("smallCaps"),(e.spacing!=null||e.position!=null||e.scale!=null||e.kerning!=null)&&n("characterSpacing",{spacing:e.spacing??null,position:e.position??null,scale:e.scale??null,kerning:e.kerning??null}),e.emboss&&n("emboss"),e.imprint&&n("imprint"),e.shadow&&n("textShadow"),e.emphasisMark&&e.emphasisMark!=="none"&&n("emphasisMark",{type:e.emphasisMark}),e.outline&&n("textOutline"),e.hidden&&n("hidden"),e.rtl&&n("rtl"),e.effect&&e.effect!=="none"&&n("textEffect",{effect:e.effect}),e.modernEffects&&n("modernTextEffects",{effects:e.modernEffects}),e.styleId&&n("runStyle",{styleId:e.styleId}),t}function et(e){let t={};for(let n of e)n.name==="comment"||n.name==="footnoteRef"||(Nt.has(n.name)?t[n.name]=true:n.name==="highlight"?t.highlight=n.attrs.color:n.name==="insertion"||n.name==="deletion"?t[n.name==="insertion"?"ins":"del"]=E({id:n.attrs.revisionId,author:n.attrs.author,date:n.attrs.date}):t[n.name]=E(n.attrs));return t}function Lt(e){return e.filter(t=>t.name!=="hyperlink"&&t.name!=="comment").map(t=>`${t.name}:${JSON.stringify(t.attrs)}`).sort().join("|")}function Dt(e,t){return [...e.filter(n=>n.name!==t.name),t]}function Z(e,t,n){return {kind:"text",text:e,attrs:et(t),pmSize:e.length,...n!==void 0?{commentId:n}:{},marks:[...t]}}function Y(e,t,n=[],r,i=1){return {kind:"embed",embedKind:e,payload:t,attrs:et(n),pmSize:i,...r!==void 0?{commentId:r}:{},marks:[...n]}}function tt(e,t,n){let r=e.formatting?.styleId?n?.getRunStyleOwnProperties(e.formatting.styleId):void 0,i=Qe(a(a(t,r),e.formatting)),o=e.formatting?.styleId,a$1=o?n?.getStyle(o)?.name:void 0;if([o,a$1].some(l=>/^(?:Followed)?Hyperlink$/i.test(l??""))){for(let[l,d]of [["color","textColor"],["underline","underline"]])if(e.formatting?.[l]===void 0&&r?.[l]!==void 0){let m=i.find(u=>u.name===d);m&&(m.attrs.inheritedHyperlink=true);}}return i}function Jt(e){let t=e.size?.width?b$4(e.size.width):void 0,n=e.size?.height?b$4(e.size.height):void 0,r=e.wrap.type,i=e.wrap.wrapText,o=e.position?.horizontal?.alignment,a;r==="inline"||r==="topAndBottom"?a="none":r==="square"||r==="tight"||r==="through"?i==="left"?a="right":i==="right"?a="left":o==="left"||o==="right"?a=o:a="none":a="none";let l=r==="inline"?"inline":r==="topAndBottom"?"block":b$5(r)||a&&a!=="none"?"float":"block",d=[];e.transform?.rotation&&d.push(`rotate(${e.transform.rotation}deg)`),e.transform?.flipH&&d.push("scaleX(-1)"),e.transform?.flipV&&d.push("scaleY(-1)");let m,u,c;if(e.outline?.width){m=Math.round(e.outline.width/914400*96*100)/100,e.outline.color?.rgb&&(u=`#${e.outline.color.rgb}`);let y={solid:"solid",dot:"dotted",dash:"dashed",lgDash:"dashed",dashDot:"dashed",lgDashDot:"dashed",lgDashDotDot:"dashed",sysDot:"dotted",sysDash:"dashed",sysDashDot:"dashed",sysDashDotDot:"dashed"};c=e.outline.style&&y[e.outline.style]||"solid";}return E({src:e.src||"",alt:e.alt??null,title:e.title??null,width:t??null,height:n??null,rId:e.rId??null,wrapType:r,displayMode:l,cssFloat:a??null,transform:d.length>0?d.join(" "):null,distTop:e.wrap.distT!=null?b$4(e.wrap.distT):null,distBottom:e.wrap.distB!=null?b$4(e.wrap.distB):null,distLeft:e.wrap.distL!=null?b$4(e.wrap.distL):null,distRight:e.wrap.distR!=null?b$4(e.wrap.distR):null,position:e.position?{relativeHeight:e.position.relativeHeight,horizontal:e.position.horizontal?{relativeTo:e.position.horizontal.relativeTo,posOffset:e.position.horizontal.posOffset,align:e.position.horizontal.alignment}:void 0,vertical:e.position.vertical?{relativeTo:e.position.vertical.relativeTo,posOffset:e.position.vertical.posOffset,align:e.position.vertical.alignment}:void 0}:null,borderWidth:m??null,borderColor:u??null,borderStyle:c??null,wrapText:i??null,hlinkHref:e.hlinkHref??null,cropTop:e.crop?.top??null,cropRight:e.crop?.right??null,cropBottom:e.crop?.bottom??null,cropLeft:e.crop?.left??null,shapeType:e.shapeType??null,opacity:e.opacity??null,effectExtentTop:e.padding?.top?b$4(e.padding.top):null,effectExtentBottom:e.padding?.bottom?b$4(e.padding.bottom):null,effectExtentLeft:e.padding?.left?b$4(e.padding.left):null,effectExtentRight:e.padding?.right?b$4(e.padding.right):null,layoutInCell:e.layoutInCell??null,allowOverlap:e.allowOverlap??null})}function Ut(e){return {shapeJson:JSON.stringify(e)}}function Wt(e){return E({chartJson:JSON.stringify(e),chartType:e.chartType??null,title:e.title??null,width:e.size?.width?b$4(e.size.width):320,height:e.size?.height?b$4(e.size.height):220,rId:e.rId??null,path:e.path??null})}function ee(e,t){let n="",r,i=e.type==="simpleField"?e.content:e.fieldResult;for(let l of i)if(l.type==="run"){for(let d of l.content)d.type==="text"&&(n+=d.text);!r&&l.formatting&&(r=l.formatting);}let o=r??(e.type==="complexField"?e.formatting:void 0),a$1=e.fieldTree?.displayMode??"result";return {payload:{fieldType:e.fieldType,instruction:e.instruction,displayText:n,fieldKind:e.type==="simpleField"?"simple":"complex",fldLock:e.fldLock??false,dirty:e.dirty??false,displayMode:a$1,hasCachedResult:n.length>0,fieldData:JSON.stringify(e),modelKind:"field"},marks:Qe(a(t,o))}}function ye(e){return {display:e.display,ommlXml:e.ommlXml,plainText:e.plainText||""}}function jt(e){return {name:"hyperlink",attrs:{href:e.href||(e.anchor?`#${e.anchor}`:""),tooltip:e.tooltip??null,rId:e.rId??null}}}function zt(e,t,n,r){let i=e.structuredResult?.inline??[],a=[...(e.type==="complexField"?e.structuredCode?.inline??[]:[]).map((c,y)=>({child:c,index:-y-1})),...i.map((c,y)=>({child:c,index:y}))];if(e.type!=="complexField"||!a.some(({child:c})=>c.type==="hyperlink"||c.type==="simpleField")){let c=ee(e,t);return [Y("field",c.payload,c.marks)]}let l=[],d=[];a.forEach(({child:c,index:y})=>{if(c.type!=="hyperlink"&&c.type!=="simpleField")return;let f=c.type==="simpleField"?ee(c,t):null,h=c.type==="hyperlink"?se(c,t,n):[Y("field",f.payload,f.marks)];d.push({index:y,items:h.map(g=>g.kind==="text"?{kind:"text",text:g.text,attributes:g.attrs}:{kind:"embed",embedKind:g.embedKind,payload:g.payload,attributes:g.attrs})});for(let g of h)g.attrs={...g.attrs,fieldResult:{id:r,index:y}};l.push(...h);});let m={...e,fieldResult:i.filter(c=>c.type==="run")},u=ee(m,t);return u.payload.fieldData=JSON.stringify(e),u.payload.resultProjection={id:r,children:d},l.push(Y("field",u.payload,u.marks)),l}function Ge(e,t,n,r){let i={name:"footnoteRef",attrs:{id:String(e),noteType:t}},o=[...n,i];return Y("noteRef",t==="endnote"?{endnoteRefId:e}:{footnoteRefId:e},o,r)}function nt(e,t,n){switch(e.type){case "text":return e.text?[Z(e.text,t,n)]:[];case "tab":return [Z(" ",t,n)];case "break":return e.breakType===void 0||e.breakType==="textWrapping"?[Y("break",{},t,n)]:[];case "softHyphen":return [Z("\xAD",t,n)];case "noBreakHyphen":return [Z("\u2011",t,n)];case "symbol":{let r=Number.parseInt(e.char,16);if(!Number.isInteger(r)||r<0||r>1114111)return [];let i={name:"fontFamily",attrs:{ascii:e.font||null,hAnsi:e.font||null,eastAsia:e.font||null,cs:e.font||null,asciiTheme:null,hAnsiTheme:null,eastAsiaTheme:null,csTheme:null}};return [Z(String.fromCodePoint(r),Dt(t,i),n)]}case "commentReference":return [Y("field",{fieldType:"COMMENT",instruction:"",displayText:"",fieldKind:"simple",fldLock:false,dirty:false,displayMode:"result",hasCachedResult:false,modelKind:"commentReference",...e.id!==void 0?{commentId:e.id}:{}})];case "drawing":return [Y("image",Jt(e.image))];case "horizontalRule":return [Y("horizontalRule",{rule:e.rule},t,n)];case "shape":return [Y("shape",Ut(e.shape))];case "chart":return [Y("chart",Wt(e.chart))];case "footnoteRef":return [Ge(e.id,"footnote",t,n)];case "endnoteRef":return [Ge(e.id,"endnote",t,n)];default:return []}}function ie(e,t,n,r,i=[]){let o=[...tt(e,t,n),...i];return e.content.flatMap(a=>nt(a,o,r))}function se(e,t,n,r=[]){let i=[],o=jt(e);for(let a of e.structuredChildren??e.children)if(a.type==="run"){let l=[...tt(a,t,n),...r,o];for(let d of a.content)i.push(...nt(d,l));}else if(a.type==="simpleField"||a.type==="complexField"){let l=ee(a,t);i.push(Y("field",l.payload,[...l.marks,...r,o]));}else a.type==="mathEquation"&&i.push(Y("math",ye(a),[...r,o]));return i}function $t(e,t,n){return {name:t,attrs:{revisionId:e.id,author:e.author,date:e.date??null,isMovePair:n}}}function Ht(e,t,n,r){let i=e.type==="insertion"||e.type==="moveTo"?"insertion":"deletion",o=$t(e.info,i,e.type==="moveFrom"||e.type==="moveTo"),a=[];for(let l of e.content)if(l.type==="run")a.push(...ie(l,t,n,r,[o]));else {let d=se(l,t,n,[o]);for(let m of d)r!==void 0&&(m.commentId=r);a.push(...d);}return a}function rt(e,t,n){let r=[],i=o=>{if(o.kind==="text"){if((o.text===" "?"tab":"text")==="tab"){r.push({kind:"tab",attrs:o.attrs});return}let l=r[r.length-1];l&&"text"in l&&H(l.attrs)===H(o.attrs)?l.text+=o.text:r.push({kind:"text",text:o.text,attrs:o.attrs});return}r.push({kind:o.embedKind,payload:o.payload,attrs:o.attrs});};for(let o of e.content)if(o.type==="run")ie(o,t,n).forEach(i);else if(o.type==="hyperlink")se(o,t,n).forEach(i);else if(o.type==="simpleField"||o.type==="complexField"){let a=ee(o,t);i(Y("field",a.payload,a.marks));}else o.type==="inlineSdt"?i(Y("sdt",rt(o,t,n))):o.type==="mathEquation"&&i(Y("math",ye(o)));return E({...pe(e.properties),propertiesJson:JSON.stringify(e.properties),content:r})}function Vt(e,t,n){let r=t?t.resolveParagraphStyle(e.formatting?.styleId).runFormatting:void 0;return a(r,n)}function Kt(e){let t=[];for(let n of e.content)n.type==="footnoteRefMark"?t.push("footnote"):n.type==="endnoteRefMark"&&t.push("endnote");return t}function Xt(e,t,n){let r=ie(e,t,n);if(r.some(d=>d.kind!=="text"&&d.embedKind!=="noteRef"))return null;let i=r.map(d=>Lt(d.marks));if(i.some(d=>d!==i[0]))return null;let o=Kt(e),a=r.map(d=>{if(d.kind==="text")return d.text;let m=d.payload.footnoteRefId??d.payload.endnoteRefId;return String(m??"")}).join(""),l=i[0];return {text:a,...o.length>0?{noteMarks:o}:{},...l!==void 0?{marksKey:l}:{},...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{}}}function qt(e,t,n,r,i){let o=e.formatting,a$1=o?.styleId,l=o?.indentFirstLine===0?void 0:o?.indentFirstLine,d=l??e.listRendering?.indentFirstLine??o?.indentFirstLine,m=l===void 0&&e.listRendering?.indentFirstLine!==void 0?e.listRendering.hangingIndent:o?.hangingIndent??e.listRendering?.hangingIndent,u={paraId:e.paraId??null,textId:e.textId??null,styleId:a$1??null,numPr:o?.numPr??null,numPrFromStyle:o?.numPrFromStyle??null,listNumFmt:e.listRendering?.numFmt??null,listIsBullet:e.listRendering?.isBullet??null,listMarker:e.listRendering?.marker??null,listMarkerHidden:e.listRendering?.markerHidden||null,listMarkerFontFamily:e.listRendering?.markerFontFamily||null,listMarkerFontSize:e.listRendering?.markerFontSize||null,listMarkerSuffix:e.listRendering?.markerSuffix||null,listLevelNumFmts:e.listRendering?.levelNumFmts||null,listAbstractNumId:e.listRendering?.abstractNumId??null,listStartOverride:e.listRendering?.startOverride??null,_originalFormatting:o??null};if(t){let h=t.resolveParagraphStyle(a$1,i),g=h.paragraphFormatting;u.alignment=o?.alignment??g?.alignment??null,u.spaceBefore=o?.spaceBefore??g?.spaceBefore??null,u.spaceAfter=o?.spaceAfter??g?.spaceAfter??null,u.spaceBeforeLines=o?.spaceBeforeLines??g?.spaceBeforeLines??null,u.spaceAfterLines=o?.spaceAfterLines??g?.spaceAfterLines??null,u.beforeAutospacing=o?.beforeAutospacing??g?.beforeAutospacing??null,u.afterAutospacing=o?.afterAutospacing??g?.afterAutospacing??null,u.lineSpacing=o?.lineSpacing??g?.lineSpacing??null,u.lineSpacingRule=o?.lineSpacingRule??g?.lineSpacingRule??null,u.spacingExplicit=o?.spacingExplicit||null,u.indentLeft=o?.indentLeft??e.listRendering?.indentLeft??g?.indentLeft??null,u.indentRight=o?.indentRight??g?.indentRight??null;let w=o?.numPr?.numId===0&&g?.numPr&&g.numPr.numId!==0?void 0:g;u.indentFirstLine=d??w?.indentFirstLine??null,u.hangingIndent=m??w?.hangingIndent??false,u.borders=o?.borders??g?.borders??null,u.shading=o?.shading??g?.shading??null,u.tabs=o?.tabs??g?.tabs??null,u.pageBreakBefore=o?.pageBreakBefore??g?.pageBreakBefore??null,u.keepNext=o?.keepNext??g?.keepNext??null,u.keepLines=o?.keepLines??g?.keepLines??null,u.widowControl=o?.widowControl??g?.widowControl??null,u.contextualSpacing=o?.contextualSpacing??g?.contextualSpacing??null,u.outlineLevel=o?.outlineLevel??g?.outlineLevel??null,u.bidi=o?.bidi??g?.bidi??null;let T=t.getDefaultCharacterStyle()?.rPr,v=T?a(h.runFormatting,T):h.runFormatting;u.defaultTextFormatting=a(v,Et(o?.runProperties,t))??null,!o?.numPr&&g?.numPr&&g.numPr.numId!==0&&(u.numPr=g.numPr,u.numPrFromStyle=g.numPr);}else u.alignment=o?.alignment??null,u.spaceBefore=o?.spaceBefore??null,u.spaceAfter=o?.spaceAfter??null,u.spaceBeforeLines=o?.spaceBeforeLines??null,u.spaceAfterLines=o?.spaceAfterLines??null,u.beforeAutospacing=o?.beforeAutospacing??null,u.afterAutospacing=o?.afterAutospacing??null,u.lineSpacing=o?.lineSpacing??null,u.lineSpacingRule=o?.lineSpacingRule??null,u.spacingExplicit=o?.spacingExplicit||null,u.indentLeft=o?.indentLeft??e.listRendering?.indentLeft??null,u.indentRight=o?.indentRight??null,u.indentFirstLine=d??null,u.hangingIndent=m??false,u.borders=o?.borders??null,u.shading=o?.shading??null,u.tabs=o?.tabs??null,u.pageBreakBefore=o?.pageBreakBefore??null,u.keepNext=o?.keepNext??null,u.keepLines=o?.keepLines??null,u.widowControl=o?.widowControl??null,u.outlineLevel=o?.outlineLevel??null,u.bidi=o?.bidi??null,u.defaultTextFormatting=o?.runProperties??null;if(e.sectionProperties){u._sectionProperties=e.sectionProperties;let h=e.sectionProperties.sectionStart;(h==="nextPage"||h==="continuous"||h==="oddPage"||h==="evenPage"||h==="nextColumn")&&(u.sectionBreakType=h);}e.renderedPageBreakBefore&&(u.renderedPageBreakBefore=true),Qt(e)&&(u.pageBreakBefore=true),e.pPrIns&&(u.pPrIns={revisionId:e.pPrIns.id,author:e.pPrIns.author,date:e.pPrIns.date??null}),e.pPrDel&&(u.pPrDel={revisionId:e.pPrDel.id,author:e.pPrDel.author,date:e.pPrDel.date??null}),e.propertyChanges?.length&&(u.pPrChange=e.propertyChanges);let c=[],y=0,f=0;for(let h of e.content)if(h.type==="bookmarkStart")c.push({id:h.id,name:h.name,kind:"start",offset:f,...h.colFirst!==void 0?{colFirst:h.colFirst}:{},...h.colLast!==void 0?{colLast:h.colLast}:{}});else if(h.type==="bookmarkEnd")c.push({id:h.id,kind:"end",offset:f});else {let g=Gt(h);for(let k=0;k<g;k+=1)f+=n[y]?.pmSize??0,y+=1;}return c.length>0&&(u.bookmarks=c),r?.length&&(u._originalRunBoundaries=r),u}var ot=new WeakMap;function Gt(e){return ot.get(e)??0}function Zt(e,t,n,r){let i=[],o=new Set,a=[],l=Vt(e,t,n);for(let[m,u]of e.content.entries()){let c=i.length,y=o.values().next().value;if(u.type==="commentRangeStart")o.add(u.id);else if(u.type==="commentRangeEnd")o.delete(u.id);else if(u.type==="run"){let f=Xt(u,l,t);f&&a?a.push(f):a=void 0,i.push(...ie(u,l,t,y));}else u.type==="hyperlink"?(a=void 0,i.push(...se(u,l,t))):u.type==="simpleField"||u.type==="complexField"?(a=void 0,i.push(...zt(u,l,t,m))):u.type==="inlineSdt"?(a=void 0,i.push(Y("sdt",rt(u,l,t),[],void 0,2))):u.type==="insertion"||u.type==="deletion"||u.type==="moveFrom"||u.type==="moveTo"?(a=void 0,i.push(...Ht(u,l,t,y))):u.type==="mathEquation"?(a=void 0,i.push(Y("math",ye(u)))):u.type!=="bookmarkStart"&&u.type!=="bookmarkEnd"&&u.type!=="rawXml"&&(a=void 0);ot.set(u,i.length-c);}let d=qt(e,t,i,a,r);return {units:i,ppr:We(d)}}function Q(e,t){for(let n of e.content)n.type==="break"&&n.breakType==="page"?t.push("pageBreak"):(n.type!=="text"||n.text.length>0)&&t.push("visible");}function be(e,t){for(let n of e)if(n.type==="run")Q(n,t);else if(n.type==="hyperlink")for(let r of n.children)r.type==="run"&&Q(r,t);else if(n.type==="simpleField")for(let r of n.content)r.type==="run"&&Q(r,t);else if(n.type==="complexField")for(let r of [...n.fieldCode,...n.fieldResult])Q(r,t);else if(n.type==="inlineSdt")be(n.content,t);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let r of n.content)r.type==="run"&&Q(r,t);else n.type==="mathEquation"&&t.push("visible");}function Qt(e){let t=[];return be(e.content,t),t[0]==="pageBreak"}function en(e){let t=[];be(e.content,t);let n=false,r=false;for(let i of t)if(i==="pageBreak"){if(r||n)return true;n=true;}else r=true;return false}function tn(e){let t=new Map,n=new Map;return e.rows.forEach((r,i)=>{let o=0,a=r.cells.map(d=>{let m=o;return o+=d.formatting?.gridSpan??1,{column:m,vMerge:d.formatting?.vMerge,key:`${i}-${m}`}});if(a.length>0&&a.every(d=>d.vMerge==="continue"&&n.has(d.column))){for(let d of a)n.delete(d.column),t.set(d.key,{rowSpan:1,skip:false});return}for(let d of a)if(d.vMerge==="restart")n.set(d.column,i),t.set(d.key,{rowSpan:1,skip:false});else if(d.vMerge==="continue"){let m=n.get(d.column);if(m===void 0)t.set(d.key,{rowSpan:1,skip:false});else {let u=t.get(`${m}-${d.column}`);u&&(u.rowSpan+=1),t.set(d.key,{rowSpan:1,skip:true});}}else n.delete(d.column),t.set(d.key,{rowSpan:1,skip:false});}),t}function he(e){return {revisionId:e.id,author:e.author,date:e.date??null}}function nn(e,t,n,r,i,o){let a=t?{top:n?t.top:t.insideH,bottom:r?t.bottom:t.insideH,left:i?t.left:t.insideV,right:o?t.right:t.insideV}:void 0;return a||e?.borders?{...a??{},...e?.borders??{}}:void 0}function Ze(e,t){let n=e.formatting,r=b$2(n?.shading?.fill,t.theme),i=n?.width?.value??t.gridWidth,o=n?.width?.type??(t.gridWidth!==void 0?"pct":null),a={colspan:n?.gridSpan??1,rowspan:t.rowspan,width:i??null,widthType:o,verticalAlign:n?.verticalAlign??null,backgroundColor:r??null,borders:nn(n,t.tableBorders,t.firstRow,t.lastRow,t.firstColumn,t.lastColumn)??null,margins:n?.margins?{top:n.margins.top?.value,bottom:n.margins.bottom?.value,left:n.margins.left?.value??(t.tableBidi?n.margins.end?.value:n.margins.start?.value),right:n.margins.right?.value??(t.tableBidi?n.margins.start?.value:n.margins.end?.value)}:t.defaultMargins??null,textDirection:n?.textDirection??null,noWrap:n?.noWrap??false,_originalFormatting:n??null,_originalResolvedFill:r??null};if(e.structuralChange){let l=e.structuralChange,d=he(l.info);l.type==="tableCellInsertion"?a.cellMarker={kind:"ins",info:d}:l.type==="tableCellDeletion"?a.cellMarker={kind:"del",info:d}:l.type==="tableCellMerge"&&(a.cellMarker={kind:"merge",info:d,vMerge:l.vMerge??"cont",...l.vMergeOrig?{vMergeOrig:l.vMergeOrig}:{}});}return e.propertyChanges?.length&&(a.tcPrChange=e.propertyChanges),{attrs:He(a,t.isHeader),content:e.content.length>0?e.content:[{type:"paragraph",content:[]}]}}function rn(e,t,n,r,i,o,a,l,d){let m={height:e.formatting?.height?.value??null,heightRule:e.formatting?.heightRule??null,isHeader:!!e.formatting?.header,_originalFormatting:e.formatting??null};e.structuralChange&&(e.structuralChange.type==="tableRowInsertion"?m.trIns=he(e.structuralChange.info):e.structuralChange.type==="tableRowDeletion"&&(m.trDel=he(e.structuralChange.info))),e.propertyChanges?.length&&(m.trPrChange=e.propertyChanges);let u=t.columnWidths,c=u?.reduce((g,k)=>g+k,0)??0,y=u?.length??Math.max(0,...t.rows.map(g=>g.cells.reduce((k,w)=>k+(w.formatting?.gridSpan??1),0))),f=0,h=[];return e.cells.forEach(g=>{let k=g.formatting?.gridSpan??1,w=f,T=r.get(`${n}-${w}`),v;if(u&&c>0){let P=0;for(let I=0;I<k&&w+I<u.length;I+=1)P+=u[w+I];v=Math.round(P/c*100);}f+=k,!T?.skip&&h.push({paragraphFormatting:ge(t,l,n,w,f,d),...Ze(g,{isHeader:n===0&&!!t.formatting?.look?.firstRow,rowspan:T?.rowSpan??1,gridWidth:v,firstRow:n===0,lastRow:n===t.rows.length-1,firstColumn:w===0,lastColumn:f===y,tableBorders:i,defaultMargins:o,theme:a,tableBidi:!!t.formatting?.bidi})});}),h.length===0&&h.push({paragraphFormatting:ge(t,l,n,0,y,d),...Ze({formatting:y>1?{gridSpan:y}:void 0,content:[{type:"paragraph",content:[]}]},{isHeader:n===0&&!!t.formatting?.look?.firstRow,rowspan:1,gridWidth:c>0?100:void 0,firstRow:n===0,lastRow:n===t.rows.length-1,firstColumn:true,lastColumn:true,tableBorders:i,defaultMargins:o,theme:a,tableBidi:!!t.formatting?.bidi})}),{attrs:$e(m),cells:h}}function on(e,t,n){let r=t?.getDefaultTableStyle(),i=e.formatting?.styleId,o=i??r?.styleId,a=o?t?.getStyle(o):void 0,l=e.formatting?.borders??a?.tblPr?.borders??r?.tblPr?.borders,d=e.formatting?.cellMargins??a?.tblPr?.cellMargins??r?.tblPr?.cellMargins,m=e.formatting?.bidi?d?.end:d?.start,u=e.formatting?.bidi?d?.start:d?.end,c=d?{top:d.top?.value,bottom:d.bottom?.value,left:d.left?.value??m?.value,right:d.right?.value??u?.value}:void 0,y=[],f=new Set,h=a;for(;h?.basedOn&&y.length<32&&!f.has(h.basedOn);)f.add(h.basedOn),y.unshift(h.basedOn),h=t?.getStyle(h.basedOn);let g={...e.formatting??{},styleCascade:{...i?{selectedStyleId:i}:{},...r?.styleId?{defaultStyleId:r.styleId}:{},...y.length>0?{basedOnStyleIds:y}:{}}},k={styleId:i??null,width:e.formatting?.width?.value??null,widthType:e.formatting?.width?.type??null,justification:e.formatting?.justification??null,columnWidths:e.columnWidths??null,tableLayout:e.formatting?.layout??null,floating:e.formatting?.floating??null,cellMargins:c??null,look:e.formatting?.look??null,bidi:e.formatting?.bidi||null,_originalFormatting:g};e.propertyChanges?.length&&(k.tblPrChange=e.propertyChanges);let w=tn(e),T=Ue(e);return {attrs:k,rows:e.rows.map((v,P)=>rn(v,e,P,w,l,c,n,a??r,T))}}function sn(e){return Ke(pe(e))}function an(e){let t=0;for(let n of e.units){let r=n.kind==="text"?n.text.length:1;if(n.commentId!==void 0&&n.commentId!==0){let i=e.commentCoverage.get(n.commentId),o=i?.[i.length-1];o&&o[1]===t?o[1]=t+r:i?i.push([t,t+r]):e.commentCoverage.set(n.commentId,[[t,t+r]]);}t+=r;}}function z(e,t,n,r){let i={storyId:t,units:[],commentCoverage:new Map};e.plans.push(i);let o=n.length>0?[...n]:[{type:"paragraph",content:[]}],a=0,l=0,d=0,m=null;for(let u of o){if(ne(u))continue;if(u.type==="paragraph"){let f=Zt(u,e.styleResolver,r.extraRunFormatting,r.tableParagraphFormatting);i.units.push(...f.units),i.units.push(Y("pilcrow",{...f.ppr,paraId:u.paraId||`${t}:p${d}`})),d+=1,r.includePageBreaks&&en(u)&&i.units.push(Y("pageBreak",{})),m="paragraph";continue}if(u.type==="table"){let f=a++,h=on(u,e.styleResolver,e.theme),g=h.rows.map((k,w)=>({trPr:k.attrs,cells:k.cells.map((T,v)=>({tcPr:T.attrs,story:me(t,f,w,v)}))}));i.units.push(Y("table",{tblPr:je(h.attrs),grid:ze(h.attrs),rows:g})),h.rows.forEach((k,w)=>{k.cells.forEach((T,v)=>{z(e,me(t,f,w,v),T.content,{includePageBreaks:false,appendBodyTail:false,seedComments:false,extraRunFormatting:T.extraRunFormatting,tableParagraphFormatting:T.paragraphFormatting});});}),m="table";continue}let c=l++,y=Ve(t,c);i.units.push(Y("blockSdt",{...sn(u.properties),story:y})),z(e,y,u.content,{includePageBreaks:r.includePageBreaks,appendBodyTail:false,seedComments:false,tableParagraphFormatting:r.tableParagraphFormatting}),m="blockSdt";}r.appendBodyTail&&(m==="table"||m==="blockSdt")&&i.units.push(Y("pilcrow",{hangingIndent:false,paraId:`${t}:p${d}`})),r.seedComments&&an(i);}function ln(e){let t=[{op:"delete",index:0,len:1}],n=0,r="",i={},o=H(i),a=()=>{r&&(t.push({op:"insert",index:n,text:r,attrs:i}),n+=r.length,r="");};for(let l of e)if(l.kind==="text"){let d=H(l.attrs);r&&d!==o&&a(),i=l.attrs,o=d,r+=l.text;}else a(),t.push({op:"insertEmbed",index:n,kind:l.embedKind,payload:l.payload,attrs:l.attrs}),n+=1;return a(),t}function dn(e,t){let n=ln(t.units);for(let[r,i]of t.commentCoverage)n.push({op:"setComment",id:String(r),ranges:i,author:"",date:"",body:null});e.applySeedRawOps(t.storyId,n);}function un(e,t){let n={styleResolver:t.package.styles?d(t.package.styles):null,theme:t.package.theme??null,plans:[]};z(n,"body",t.package.document.content,{includePageBreaks:true,appendBodyTail:true,seedComments:true});for(let[r,i]of t.package.headers??[])z(n,oe(r),i.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let[r,i]of t.package.footers??[])n.plans.some(o=>o.storyId===oe(r))||z(n,oe(r),i.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of t.package.footnotes??[])z(n,Xe(r.id),r.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of t.package.endnotes??[])z(n,qe(r.id),r.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let r of n.plans)e.createStory(r.storyId,"","Normal","left");for(let r of n.plans)dn(e,r);}var W=class extends Error{constructor(t){super(t),this.name="ContentControlValueError";}};function ae(e,t,n){let r=new RegExp(`<${t}\\b[^>]*>`).exec(e);if(!r)return;let i=new RegExp(`\\b${n}="([^"]*)"`).exec(r[0]);return i?i[1]:void 0}function ke(e,t,n,r){let o=new RegExp(`<${t}\\b[^>]*?(/?)>`).exec(e);if(!o)return e;let a=o[0],l=o[1]==="/",d=a.slice(1,l?-2:-1),u=new RegExp(`\\b${n}="[^"]*"`).test(d)?d.replace(new RegExp(`\\b${n}="[^"]*"`),()=>`${n}="${r}"`):`${d} ${n}="${r}"`;return e.replace(a,()=>`<${u}${l?"/>":">"}`)}function cn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function pn(e,t){if(!e)return t;let n=parseInt(e,16);return Number.isNaN(n)||n<0||n>1114111||n>=55296&&n<=57343?t:String.fromCodePoint(n)}function fn(e,t,n){let[r,i,o]=e.slice(0,10).split("-").map(c=>parseInt(c,10));if(!it(r,i,o))return e;let a=t&&t.trim()?t:"M/d/yyyy",l=c=>String(c).padStart(2,"0"),d=new Date(Date.UTC(r,i-1,o)),m=c=>{try{return new Intl.DateTimeFormat(n||"en",{month:c,timeZone:"UTC"}).format(d)}catch{return new Intl.DateTimeFormat("en",{month:c,timeZone:"UTC"}).format(d)}},u={yyyy:String(r),yy:String(r).slice(-2),MMMM:m("long"),MMM:m("short"),MM:l(i),M:String(i),dd:l(o),d:String(o)};return a.replace(/yyyy|yy|MMMM|MMM|MM|M|dd|d/g,c=>u[c])}function it(e,t,n){if(!e||!t||!n)return false;let r=new Date(Date.UTC(e,t-1,n));return r.getUTCFullYear()===e&&r.getUTCMonth()===t-1&&r.getUTCDate()===n}function Se(e,t){return e?{type:"paragraph",content:[{type:"run",content:[{type:"text",text:e}],...t?{formatting:{fontFamily:{ascii:t,hAnsi:t,eastAsia:t,cs:t}}}:{}}]}:{type:"paragraph",content:[]}}function gn(e){return e&&e.replace(/<w:showingPlcHdr\b[^>]*\/>/g,"").replace(/<w:showingPlcHdr\b[^>]*>[\s\S]*?<\/w:showingPlcHdr>/g,"")}function Re(e,t){let n=gn(t);return {...e,showingPlaceholder:false,rawPropertiesXml:(n??t)||void 0}}function we(e,t){let n=e.rawPropertiesXml??"";switch(t.kind){case "dropdown":{if(e.sdtType!=="dropDownList"&&e.sdtType!=="comboBox")throw new W(`Control is '${e.sdtType}', not a dropdown/combo box.`);let r=e.listItems?.find(m=>m.value===t.value||m.displayText===t.value);if(!r&&e.sdtType==="dropDownList")throw new W(`'${t.value}' is not one of the control's list items.`);let i=r?.value??t.value,o=r?.displayText??t.value,a=r?e.listItems?.indexOf(r):void 0,l=e.sdtType==="comboBox"?"w:comboBox":"w:dropDownList",d=ke(n,l,"w:lastValue",cn(i));return {properties:{...Re(e,d),listLastValue:i,controlState:{...e.controlState,value:o,selectedValue:i,selectedIndex:a,placeholder:false}},content:[Se(o)]}}case "checkbox":{if(e.sdtType!=="checkbox")throw new W(`Control is '${e.sdtType}', not a checkbox.`);if(ae(n,"w14:checked","w14:val")==null)throw new W("Checkbox control has no <w14:checked> state to update (not a Word checkbox).");let r=t.checked?"w14:checkedState":"w14:uncheckedState",i=pn(ae(n,r,"w14:val"),t.checked?"\u2612":"\u2610"),o=ae(n,r,"w14:font"),a=ke(n,"w14:checked","w14:val",t.checked?"1":"0");return {properties:{...Re(e,a),checked:t.checked,controlState:{...e.controlState,checked:t.checked,value:i,placeholder:false}},content:[Se(i,o)]}}case "date":{if(e.sdtType!=="date")throw new W(`Control is '${e.sdtType}', not a date control.`);let r=t.date.slice(0,10),[i,o,a]=/^\d{4}-\d{2}-\d{2}$/.test(r)?r.split("-").map(Number):[];if(!it(i,o,a))throw new W(`Date must be ISO yyyy-mm-dd, got '${t.date}'.`);let l=`${r}T00:00:00`,d=ke(n,"w:date","w:fullDate",l),m=e.dateState?.format??e.dateFormat??ae(n,"w:dateFormat","w:val"),u=e.dateState?.language,c=fn(r,m,u);return {properties:{...Re(e,d),dateFormat:m,dateState:{...e.dateState,fullDate:l,format:m},controlState:{...e.controlState,value:r,placeholder:false}},content:[Se(c)]}}}}function st(e){return e.numPrFromStyle!=null&&e.numPr!=null&&JSON.stringify(e.numPr)===JSON.stringify(e.numPrFromStyle)}function dt(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.alignment!==(n.alignment||void 0)&&(r.alignment=e.alignment||void 0),st(e)?(delete r.numPr,delete r.numPrFromStyle):e.numPr!==n.numPr&&JSON.stringify(e.numPr)!==JSON.stringify(n.numPr)&&(r.numPr=e.numPr||void 0,delete r.numPrFromStyle),e.styleId!==(n.styleId||void 0)&&(r.styleId=e.styleId||void 0),e.pageBreakBefore!==(n.pageBreakBefore||void 0)&&(r.pageBreakBefore=e.pageBreakBefore||void 0),e.widowControl!==(n.widowControl??void 0)&&(r.widowControl=e.widowControl??void 0),e.bidi!==(n.bidi||void 0)&&(r.bidi=e.bidi||void 0),r}if(e.alignment||e.spaceBefore!=null||e.spaceAfter!=null||e.spaceBeforeLines!=null||e.spaceAfterLines!=null||e.beforeAutospacing!=null||e.afterAutospacing!=null||e.lineSpacing||e.indentLeft||e.indentRight||e.indentFirstLine||e.numPr||e.styleId||e.borders||e.shading||e.tabs||e.outlineLevel!=null||e.contextualSpacing||e.pageBreakBefore||e.widowControl!=null||e.bidi)return {alignment:e.alignment||void 0,spaceBefore:e.spaceBefore??void 0,spaceAfter:e.spaceAfter??void 0,spaceBeforeLines:e.spaceBeforeLines??void 0,spaceAfterLines:e.spaceAfterLines??void 0,beforeAutospacing:e.beforeAutospacing??void 0,afterAutospacing:e.afterAutospacing??void 0,lineSpacing:e.lineSpacing||void 0,lineSpacingRule:e.lineSpacingRule||void 0,indentLeft:e.indentLeft||void 0,indentRight:e.indentRight||void 0,indentFirstLine:e.indentFirstLine||void 0,hangingIndent:e.hangingIndent||void 0,numPr:st(e)?void 0:e.numPr||void 0,styleId:e.styleId||void 0,borders:e.borders||void 0,shading:e.shading||void 0,tabs:e.tabs||void 0,outlineLevel:e.outlineLevel??void 0,contextualSpacing:e.contextualSpacing||void 0,pageBreakBefore:e.pageBreakBefore||void 0,widowControl:e.widowControl??void 0,bidi:e.bidi||void 0}}function ut(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.styleId!==(n.styleId||void 0)&&(r.styleId=e.styleId||void 0),e.justification!==(n.justification||void 0)&&(r.justification=e.justification||void 0),e.floating!==(n.floating||void 0)&&(r.floating=e.floating||void 0),e.tableLayout!==(n.layout||void 0)&&(r.layout=e.tableLayout||void 0),e.look!==(n.look||void 0)&&(r.look=e.look||void 0),e.bidi!==(n.bidi||void 0)&&(r.bidi=e.bidi||void 0),(e.width!==n.width?.value||e.widthType!==n.width?.type)&&(r.width=e.width!=null||e.widthType?{value:e.width??0,type:e.widthType||"dxa"}:void 0),e.cellMargins&&(r.cellMargins=at(e.cellMargins)),r}if(e.styleId||e.width!=null||e.widthType||e.justification||e.tableLayout||e.floating||e.cellMargins||e.look||e.bidi)return {styleId:e.styleId||void 0,width:e.width!=null||e.widthType?{value:e.width??0,type:e.widthType||"dxa"}:void 0,justification:e.justification||void 0,layout:e.tableLayout||void 0,floating:e.floating||void 0,cellMargins:e.cellMargins?at(e.cellMargins):void 0,look:e.look||void 0,bidi:e.bidi||void 0}}function at(e){return {top:e.top!=null?{value:e.top,type:"dxa"}:void 0,bottom:e.bottom!=null?{value:e.bottom,type:"dxa"}:void 0,left:e.left!=null?{value:e.left,type:"dxa"}:void 0,right:e.right!=null?{value:e.right,type:"dxa"}:void 0}}function ct(e){if(e._originalFormatting){let t=e._originalFormatting,n={...t};return e.height!==(t.height?.value||void 0)&&(n.height=e.height?{value:e.height,type:"dxa"}:void 0),e.heightRule!==(t.heightRule||void 0)&&(n.heightRule=e.heightRule||void 0),e.isHeader!==(t.header||void 0)&&(n.header=e.isHeader||void 0),n}if(!(!e.height&&!e.isHeader))return {height:e.height?{value:e.height,type:"dxa"}:void 0,heightRule:e.heightRule||void 0,header:e.isHeader||void 0}}function pt(e){if(e._originalFormatting){let n=e._originalFormatting,r={...n};return e.colspan>1&&(r.gridSpan=e.colspan),e.width!=null&&(r.width={value:e.width,type:e.widthType||"dxa"}),e.verticalAlign!==(n.verticalAlign||void 0)&&(r.verticalAlign=e.verticalAlign||void 0),e.backgroundColor?r.shading=e._originalResolvedFill===e.backgroundColor&&n.shading?n.shading:{fill:{rgb:e.backgroundColor}}:n.shading&&(r.shading=void 0),e.borders&&(r.borders=e.borders),e.margins&&(r.margins=lt(e.margins)),e.textDirection!==(n.textDirection||void 0)&&(r.textDirection=e.textDirection||void 0),r}if(e.colspan>1||e.rowspan>1||e.width!=null||e.verticalAlign||e.backgroundColor||e.borders||e.margins||e.textDirection)return {gridSpan:e.colspan>1?e.colspan:void 0,width:e.width!=null?{value:e.width,type:e.widthType||"dxa"}:void 0,verticalAlign:e.verticalAlign||void 0,textDirection:e.textDirection||void 0,shading:e.backgroundColor?{fill:{rgb:e.backgroundColor}}:void 0,borders:e.borders,margins:e.margins?lt(e.margins):void 0}}function lt(e){let t={};return e.top!=null&&(t.top={value:e.top,type:"dxa"}),e.bottom!=null&&(t.bottom={value:e.bottom,type:"dxa"}),e.left!=null&&(t.left={value:e.left,type:"dxa"}),e.right!=null&&(t.right={value:e.right,type:"dxa"}),t}var mn={paraId:null,textId:null,alignment:null,spaceBefore:null,spaceAfter:null,lineSpacing:null,lineSpacingRule:null,spacingExplicit:null,indentLeft:null,indentRight:null,indentFirstLine:null,hangingIndent:false,numPr:null,numPrFromStyle:null,listNumFmt:null,listIsBullet:null,listMarker:null,listMarkerHidden:null,listMarkerFontFamily:null,listMarkerFontSize:null,listMarkerSuffix:null,listLevelNumFmts:null,listAbstractNumId:null,listStartOverride:null,styleId:null,borders:null,shading:null,tabs:null,pageBreakBefore:null,renderedPageBreakBefore:null,keepNext:null,keepLines:null,widowControl:null,contextualSpacing:null,defaultTextFormatting:null,sectionBreakType:null,bidi:null,outlineLevel:null,bookmarks:null,_originalFormatting:null,_originalRunBoundaries:null,_sectionProperties:null,pPrIns:null,pPrDel:null,pPrChange:null},hn={styleId:null,width:null,widthType:null,justification:null,columnWidths:null,tableLayout:null,floating:null,cellMargins:null,look:null,bidi:null,_originalFormatting:null,tblPrChange:null},yn={height:null,heightRule:null,isHeader:false,_originalFormatting:null,trIns:null,trDel:null,trPrChange:null},bn={colspan:1,rowspan:1,colwidth:null,width:null,widthType:null,verticalAlign:null,backgroundColor:null,borders:null,margins:null,textDirection:null,noWrap:false,_originalFormatting:null,_originalResolvedFill:null,cellMarker:null,tcPrChange:null},kn=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function C(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function A(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function R(e){return typeof e=="string"?e:void 0}function de(e){if(Array.isArray(e))return e.map(de);let t=C(e);if(!t)return e;let n={};for(let[r,i]of Object.entries(t))i!=null&&(n[r]=de(i));return n}function j(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(j).join(",")}]`;let t=C(e);return t?`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${j(t[n])}`).join(",")}}`:JSON.stringify(e)}function X(e){let t={...e};return delete t.hyperlink,delete t.ins,delete t.del,t}function te(e){let t={};e.bold&&(t.bold=true,t.boldCs=true),e.italic&&(t.italic=true,t.italicCs=true);let n=C(e.underline);n&&n.inheritedHyperlink!==true&&(t.underline={style:R(n.style)||"single",color:C(n.color)??null});let r=C(e.strike);r&&(r.double?t.doubleStrike=true:t.strike=true);let i=C(e.textColor);i&&i.inheritedHyperlink!==true&&(t.color={rgb:R(i.rgb)??null,themeColor:i.themeColor??null,themeTint:R(i.themeTint)??null,themeShade:R(i.themeShade)??null}),typeof e.highlight=="string"&&(t.highlight=e.highlight);let o=C(e.fontSize);if(o){let f=A(o.size),h=A(o.sizeCs)??f;f!==void 0&&(t.fontSize=f),h!==void 0&&(t.fontSizeCs=h);}let a=C(e.fontFamily);if(a){let f=R(a.ascii);t.fontFamily={ascii:f??null,hAnsi:R(a.hAnsi)??null,eastAsia:R(a.eastAsia),cs:R(a.cs)||f,asciiTheme:a.asciiTheme??null,hAnsiTheme:R(a.hAnsiTheme),eastAsiaTheme:R(a.eastAsiaTheme),csTheme:R(a.csTheme)};}e.superscript&&(t.vertAlign="superscript"),e.subscript&&(t.vertAlign="subscript"),e.allCaps&&(t.allCaps=true),e.smallCaps&&(t.smallCaps=true);let l=C(e.characterSpacing);if(l){let f=A(l.spacing),h=A(l.position),g=A(l.scale),k=A(l.kerning);f!==void 0&&(t.spacing=f),h!==void 0&&(t.position=h),g!==void 0&&(t.scale=g),k!==void 0&&(t.kerning=k);}e.emboss&&(t.emboss=true),e.imprint&&(t.imprint=true),e.textShadow&&(t.shadow=true);let d=C(e.emphasisMark);d&&(t.emphasisMark=R(d.type)||"dot"),e.textOutline&&(t.outline=true),e.hidden&&(t.hidden=true),e.rtl&&(t.rtl=true);let m=C(e.textEffect);m&&(t.effect=R(m.effect)||"blinkBackground");let u=C(e.modernTextEffects);u?.effects&&(t.modernEffects=u.effects);let c=C(e.runStyle),y=R(c?.styleId);return y&&(t.styleId=y),t}function mt(e,t){let n=[],r="",i=()=>{r&&(n.push({type:"text",text:r}),r="");},o=t.fontFamily?[t.fontFamily.ascii,t.fontFamily.hAnsi,t.fontFamily.eastAsia,t.fontFamily.cs].filter(l=>!!l):[],a=o.length>0&&o.every(l=>l===o[0])?o[0]:null;for(let l of e){let d=l.codePointAt(0)??0;l==="\xAD"?(i(),n.push({type:"softHyphen"})):l==="\u2011"?(i(),n.push({type:"noBreakHyphen"})):a&&d>=61440&&d<=63743?(i(),n.push({type:"symbol",font:a,char:d.toString(16).toUpperCase().padStart(4,"0")})):r+=l;}return i(),n}function Ie(e,t){let n=te(X(t));return {type:"run",formatting:Object.keys(n).length>0?n:void 0,content:mt(e,n)}}function Sn(e,t){for(let n of t.content){let r=e.content[e.content.length-1];r?.type==="text"&&n.type==="text"?r.text+=n.text:e.content.push(n);}}function Rn(e){let t=0xcbf29ce484222325n;for(let n of new TextEncoder().encode(e))t=(t^BigInt(n))*0x100000001b3n,t&=0xffffffffffffffffn;return Number(t&(1n<<53n)-1n)}function xe(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t=Number(e);return Number.isFinite(t)?t:Rn(e)}return 0}function V(e,t=false){let n=C(e);if(!n)return null;let r=R(n.author)||"Unknown",i=R(n.date);return {id:xe(n.revisionId??n.id),author:r,...i?{date:i}:{}}}function wn(e){let t=C(e.hyperlink);if(!t)return null;let n=R(t.href)||"";return n.startsWith("#")?{type:"hyperlink",anchor:n.slice(1),tooltip:R(t.tooltip)||void 0,children:[]}:{type:"hyperlink",href:n,tooltip:R(t.tooltip)||void 0,rId:R(t.rId)||void 0,children:[]}}function xn(e){let t=C(e.hyperlink);return t?R(t.href)||"":null}function ve(e,t){let n=R(e.fieldData);if(n&&n.length<=2e6)try{let u=JSON.parse(n),c=u.type==="simpleField"?u.content:u.fieldResult;if((u.type==="simpleField"||u.type==="complexField")&&typeof u.instruction=="string"&&Array.isArray(c)){let y=R(e.displayMode);return u.fieldTree&&y&&(u.fieldTree.displayMode=y),u}}catch{}let r=te(X(t)),i={type:"run",content:[{type:"text",text:R(e.displayText)||""}],...Object.keys(r).length>0?{formatting:r}:{}},o=R(e.instruction)||"",a=R(e.fieldType)||"UNKNOWN",l=e.fldLock===true||void 0,d=e.dirty===true||void 0,m=R(e.displayMode)||"result";return e.fieldKind==="complex"?{type:"complexField",instruction:o,fieldType:a,fieldCode:[],fieldResult:[i],fldLock:l,dirty:d,fieldTree:{version:1,displayMode:m}}:{type:"simpleField",instruction:o,fieldType:a,content:[i],fldLock:l,dirty:d,fieldTree:{version:1,displayMode:m}}}function ht(e){return {type:"mathEquation",display:R(e.display)||"inline",ommlXml:R(e.ommlXml)||"",plainText:R(e.plainText)||void 0}}function Ae(e,t){let n=C(e.rule),r=A(n?.height);if(!n||r===void 0||n.width!=null&&A(n.width)===void 0||n.widthPercent!=null&&A(n.widthPercent)===void 0||typeof n.alignment!="string"||typeof n.noShade!="boolean"||typeof n.color!="string"||typeof n.xml!="string")throw new Error("Malformed horizontalRule embed payload");let i={width:A(n.width)??null,widthPercent:A(n.widthPercent)??null,height:r,alignment:n.alignment,noShade:n.noShade,color:n.color,xml:n.xml},o=te(X(t));return {type:"run",content:[{type:"horizontalRule",rule:i}],...Object.keys(o).length>0?{formatting:o}:{}}}function yt(e){let t=e,n={type:R(t.wrapType)||"inline"};t.distTop!==void 0&&(n.distT=c$1(Number(t.distTop))),t.distBottom!==void 0&&(n.distB=c$1(Number(t.distBottom))),t.distLeft!==void 0&&(n.distL=c$1(Number(t.distLeft))),t.distRight!==void 0&&(n.distR=c$1(Number(t.distRight))),t.wrapText&&(n.wrapText=t.wrapText);let r={type:"image",rId:R(t.rId)||"",src:R(t.src)||"",alt:R(t.alt)||void 0,title:R(t.title)||void 0,shapeType:R(t.shapeType)||void 0,size:{width:c$1(Number(t.width)||0),height:c$1(Number(t.height)||0)},wrap:n};if(t.transform){let a={},l=t.transform.match(/rotate\(([-\d.]+)deg\)/)?.[1];l&&(a.rotation=Number.parseFloat(l)),t.transform.includes("scaleX(-1)")&&(a.flipH=true),t.transform.includes("scaleY(-1)")&&(a.flipV=true),(a.rotation||a.flipH||a.flipV)&&(r.transform=a);}if(t.position?.horizontal&&t.position.vertical&&(r.position={relativeHeight:t.position.relativeHeight,horizontal:{relativeTo:t.position.horizontal.relativeTo||"column",alignment:t.position.horizontal.align,posOffset:t.position.horizontal.posOffset},vertical:{relativeTo:t.position.vertical.relativeTo||"paragraph",alignment:t.position.vertical.align,posOffset:t.position.vertical.posOffset}}),t.borderWidth&&t.borderWidth>0){let a={solid:"solid",dotted:"dot",dashed:"dash",double:"solid",groove:"solid",ridge:"solid",inset:"solid",outset:"solid"};r.outline={width:c$1(t.borderWidth),color:t.borderColor?{rgb:t.borderColor.replace("#","")}:void 0,style:t.borderStyle&&a[t.borderStyle]||"solid"};}t.hlinkHref&&(r.hlinkHref=t.hlinkHref);let i={};t.cropTop!=null&&(i.top=t.cropTop),t.cropRight!=null&&(i.right=t.cropRight),t.cropBottom!=null&&(i.bottom=t.cropBottom),t.cropLeft!=null&&(i.left=t.cropLeft),Object.keys(i).length>0&&(r.crop=i),t.opacity!=null&&t.opacity<1&&(r.opacity=t.opacity),t.layoutInCell!=null&&(r.layoutInCell=t.layoutInCell),t.allowOverlap!=null&&(r.allowOverlap=t.allowOverlap);let o={};return t.effectExtentTop&&(o.top=c$1(t.effectExtentTop)),t.effectExtentBottom&&(o.bottom=c$1(t.effectExtentBottom)),t.effectExtentLeft&&(o.left=c$1(t.effectExtentLeft)),t.effectExtentRight&&(o.right=c$1(t.effectExtentRight)),Object.keys(o).length>0&&(r.padding=o),{type:"run",content:[{type:"drawing",image:r}]}}function Tn(e){let t=R(e);if(!(!t||t.length>2e6))try{let n=JSON.parse(t);return n?.type!=="shape"||typeof n.shapeType!="string"?void 0:(C(n.size)||(n.size={width:0,height:0}),n)}catch{return}}function bt(e){let t=R(e.chartJson);if(!t)return null;try{let n=JSON.parse(t);return n?.type!=="chart"||typeof n.chartType!="string"?null:{type:"run",content:[{type:"chart",chart:n}]}}catch{return null}}function kt(e){let t=Tn(e.shapeJson)??{type:"shape",shapeType:"rect",size:{width:0,height:0}},n=R(e.shapeType);n&&(t.shapeType=n);let r=R(e.shapeId);if(r&&(t.id=r),e.width&&(t.size={...t.size,width:c$1(Number(e.width))}),e.height&&(t.size={...t.size,height:c$1(Number(e.height))}),Array.isArray(e.geometryPath)&&e.geometryPath.length>0&&(t.geometryPath=e.geometryPath),e.fillType==="gradient"&&typeof e.gradientStops=="string")try{let o=JSON.parse(e.gradientStops);t.fill={type:"gradient",gradient:{type:R(e.gradientType)||"linear",angle:A(e.gradientAngle)||void 0,stops:o.map(a=>({position:a.position,color:{rgb:a.color.replace("#","")}}))}};}catch{t.fill={type:"solid",color:{rgb:(R(e.fillColor)||"000000").replace("#","")}};}else typeof e.fillColor=="string"?t.fill={type:R(e.fillType)||"solid",color:{rgb:e.fillColor.replace("#","")}}:e.fillType==="none"&&(t.fill={type:"none"});if(typeof e.outlineWidth=="number"&&e.outlineWidth>0){let o={solid:"solid",dotted:"dot",dashed:"dash"},a=R(e.outlineStyle);t.outline={width:c$1(e.outlineWidth),color:typeof e.outlineColor=="string"?{rgb:e.outlineColor.replace("#","")}:void 0,style:a&&o[a]||"solid"};}let i={};if(typeof e.rotation=="number")i.rotation=e.rotation;else if(typeof e.transform=="string"){let o=e.transform.match(/rotate\(([-\d.]+)deg\)/)?.[1];o&&(i.rotation=Number.parseFloat(o));}return (e.flipH||String(e.transform||"").includes("scaleX(-1)"))&&(i.flipH=true),(e.flipV||String(e.transform||"").includes("scaleY(-1)"))&&(i.flipV=true),(i.rotation||i.flipH||i.flipV)&&(t.transform=i),{type:"run",content:[{type:"shape",shape:t}]}}function Cn(e){let t=fe(e),n=R(e.propertiesJson);if(n&&n.length<=1e6)try{let a=JSON.parse(n);a&&typeof a=="object"&&typeof a.sdtType=="string"&&(t=a);}catch{}let r=[];for(let a of Array.isArray(e.content)?e.content:[]){let l=C(a),d=R(l?.kind);if(!l||!d)continue;let m=C(l.attrs)??{};if(d==="text"){let u=R(l.text);u!==void 0&&r.push({kind:"text",text:u,attributes:m});continue}r.push({kind:"embed",embedKind:d,payload:C(l.payload)??{},attributes:m});}let i=Te(ue(r)),o=St(e.value);if(o)try{let a=we(t,o);t=a.properties;let l=a.content[0];i=Te(l?.type==="paragraph"?l.content:[]);}catch{}return {type:"inlineSdt",properties:t,content:i}}function Te(e){return e.filter(t=>t.type==="run"||t.type==="hyperlink"||t.type==="simpleField"||t.type==="complexField"||t.type==="inlineSdt"||t.type==="mathEquation")}function St(e){let t=C(e);return t?.kind==="checkbox"&&typeof t.checked=="boolean"?{kind:"checkbox",checked:t.checked}:t?.kind==="dropdown"&&typeof t.value=="string"?{kind:"dropdown",value:t.value}:t?.kind==="date"&&typeof t.date=="string"?{kind:"date",date:t.date}:null}function Rt(e){if(e.modelKind!=="commentReference")return null;let t=A(e.commentId);return {type:"run",content:[{type:"commentReference",...t!==void 0?{id:t}:{}}]}}function ft(e){if(e.kind==="text")return Ie(e.text,e.attributes);switch(e.embedKind){case "break":return {type:"run",content:[{type:"break",breakType:"textWrapping"}]};case "tab":return {type:"run",content:[{type:"tab"}]};case "image":return yt(e.payload);case "horizontalRule":return Ae(e.payload,e.attributes);case "shape":return kt(e.payload);case "chart":return bt(e.payload);case "field":return Rt(e.payload)??ve(e.payload,e.attributes);case "math":return ht(e.payload);case "sdt":return Cn(e.payload);case "noteRef":{let t=e.payload.footnoteRefId,n=e.payload.endnoteRefId;return {type:"run",content:[t!==void 0?{type:"footnoteRef",id:xe(t)}:{type:"endnoteRef",id:xe(n)}]}}default:return null}}function Pn(e,t){let n;if(e.kind==="embed"&&e.embedKind==="image")n=yt(e.payload);else if(e.kind==="embed"&&e.embedKind==="horizontalRule")n=Ae(e.payload,e.attributes);else if(e.kind==="embed"&&e.embedKind==="shape")n=kt(e.payload);else if(e.kind==="embed"&&e.embedKind==="chart")n=bt(e.payload)??{type:"run",content:[]};else if(e.kind==="text"){let o=te(X(e.attributes));n={type:"run",content:[{type:"text",text:e.text}],...Object.keys(o).length>0?{formatting:o}:{}};}else n={type:"run",content:[]};let i=(C(e.attributes.ins)??C(e.attributes.del))?.isMovePair===true;return e.attributes.ins?i?{type:"moveTo",info:t,content:[n]}:{type:"insertion",info:t,content:[n]}:i?{type:"moveFrom",info:t,content:[n]}:{type:"deletion",info:t,content:[n]}}function In(e,t){if(t.kind==="text"){e.children.push(Ie(t.text,t.attributes));return}if(t.embedKind==="break")e.children.push({type:"run",content:[{type:"break",breakType:"textWrapping"}]});else if(t.embedKind==="tab")e.children.push({type:"run",content:[{type:"tab"}]});else if(t.embedKind==="horizontalRule")e.children.push(Ae(t.payload,t.attributes));else if(t.embedKind==="field"){let n=Rt(t.payload)??ve(t.payload,t.attributes);n.type==="run"?e.children.push(n):(e.structuredChildren??(e.structuredChildren=[...e.children])).push(n);}else t.embedKind==="math"&&(e.structuredChildren??(e.structuredChildren=[...e.children])).push(ht(t.payload));}function gt(e){let t=[];for(let n of e){let r={...n.attributes};delete r.fieldResult;let i=n.kind==="embed"&&n.embedKind==="tab"?{kind:"text",text:" ",attributes:r}:{...n,attributes:r},o=t.at(-1);i.kind==="text"&&o?.kind==="text"&&j(o.attributes)===j(r)?o.text+=i.text:t.push(i);}return j(t)}function vn(e){let t=[];for(let[i,o]of e.entries()){if(o.kind!=="embed"||o.embedKind!=="field")continue;let a=A(C(o.payload.resultProjection)?.id);a!==void 0&&t.push({id:a,owner:o,position:i});}if(t.length===0)return e;let n=new Map,r=e.filter((i,o)=>{let a=C(i.attributes.fieldResult),l=A(a?.id),d=A(a?.index),m=t.find(f=>f.id===l&&f.position>o)?.owner;if(d===void 0||!m)return true;let u=n.get(m)??new Map,c=u.get(d)??[],y={...i.attributes};return delete y.fieldResult,c.push({...i,attributes:y}),u.set(d,c),n.set(m,u),false});for(let{owner:i}of t){let o=ve(i.payload,i.attributes);if(o.type!=="complexField")continue;let a=C(i.payload.resultProjection),l=Array.isArray(a?.children)?a.children:[],d=new Map;for(let c of l){let y=C(c),f=A(y?.index);if(f===void 0||!Array.isArray(y?.items))continue;let h=n.get(i)?.get(f)??[];if(gt(h)===gt(y.items))continue;let g=Te(ue(h)),k=f<0?o.structuredCode?.inline?.[-f-1]:o.structuredResult?.inline?.[f];k?.type==="hyperlink"&&g.length===1&&g[0]?.type==="hyperlink"&&(g[0]={...k,...g[0],structuredChildren:g[0].structuredChildren}),d.set(f,g);}if(d.size===0)continue;let m=(o.structuredResult?.inline??[]).flatMap((c,y)=>d.get(y)??[c]),u=o.structuredCode?.inline?.flatMap((c,y)=>d.get(-y-1)??[c]);o.structuredResult={...o.structuredResult,inline:m},u&&(o.structuredCode={...o.structuredCode,inline:u}),o.fieldTree&&(o.fieldTree.result={...o.fieldTree.result,inline:m},u&&(o.fieldTree.code={...o.fieldTree.code,inline:u})),o.fieldResult=m.flatMap(c=>c.type==="run"?[c]:c.type==="hyperlink"?c.children.filter(y=>y.type==="run"):[]),i.payload={...i.payload,fieldData:JSON.stringify(o)};}return r}function ue(e){e=vn(e);let t=[],n=null,r=null,i=null,o=()=>{n&&t.push(n),n=null,r=null;},a=()=>{i&&t.push(i),i=null;};for(let l of e){if(l.kind==="embed"&&l.embedKind==="noteRef"){o(),a();let c=ft(l);c&&t.push(c);continue}let d=V(l.attributes.ins??l.attributes.del);if(d){o(),a(),t.push(Pn(l,d));continue}let m=xn(l.attributes);if(m!==null){o();let c=i?i.href||(i.anchor?`#${i.anchor}`:""):null;(!i||c!==m)&&(a(),i=wn(l.attributes)),i&&In(i,l);continue}if(a(),l.kind==="text"){let c=j(X(l.attributes)),y=Ie(l.text,l.attributes);n&&r===c?Sn(n,y):(o(),n=y,r=c);continue}o();let u=ft(l);u&&t.push(u);}return o(),a(),t}function An(e){if(!e)return {};let t={};for(let n of e.split("|")){let r=n.indexOf(":");if(r<=0)return null;let i=n.slice(0,r),o;try{o=JSON.parse(n.slice(r+1));}catch{return null}i==="comment"||i==="footnoteRef"||(kn.has(i)?t[i]=true:i==="highlight"?t.highlight=o.color:i==="insertion"||i==="deletion"?t[i==="insertion"?"ins":"del"]=de({id:o.revisionId,author:o.author,date:o.date,isMovePair:o.isMovePair}):t[i]=de(o));}return t}function Fn(e){return e.noteMarks?.length?e.noteMarks.map(t=>({type:t==="endnote"?"endnoteRefMark":"footnoteRefMark"})):null}function Yn(e,t,n){if(!n?.length||!e.every(l=>l.type==="run"&&l.content.every(d=>d.type==="text"))||t.some(l=>l.kind!=="text"||l.attributes.hyperlink)||n.some(l=>l.noteMarks?.length&&l.text.length>0)||t.map(l=>l.kind==="text"?l.text:"").join("")!==n.map(l=>l.text).join(""))return e;let i=0,o=0,a=[];for(let l of n){let d=An(l.marksKey);if(!d)return e;a.push(d);let m=l.text.length;for(;m>0;){let u=t[i];if(u?.kind!=="text"||j(X(u.attributes))!==j(d))return e;let c=u.text.length-o,y=Math.min(m,c);m-=y,o+=y,o===u.text.length&&(i+=1,o=0);}}return i!==t.length||o!==0?e:n.map((l,d)=>{let m=l.text.length===0?l.formatting:te(a[d]),u={type:"run",content:Fn(l)??mt(l.text,m??{})};return m&&Object.keys(m).length>0&&(u.formatting=m),l.propertyChanges?.length&&(u.propertyChanges=l.propertyChanges),u})}function le(e){return e.content.reduce((t,n)=>n.type==="text"||n.type==="instrText"?t+n.text.length:n.type==="symbol"?t+n.char.length:n.type==="tab"||n.type==="softHyphen"||n.type==="noBreakHyphen"||n.type==="footnoteRef"||n.type==="endnoteRef"||n.type==="horizontalRule"?t+1:t,0)}function K(e){switch(e.type){case "run":return le(e);case "hyperlink":return e.children.reduce((t,n)=>t+(n.type==="run"?le(n):0),0);case "simpleField":return e.content.reduce((t,n)=>t+K(n),0);case "complexField":return e.fieldResult.reduce((t,n)=>t+le(n),0);case "inlineSdt":return e.content.reduce((t,n)=>t+K(n),0);case "insertion":case "deletion":case "moveFrom":case "moveTo":return e.content.reduce((t,n)=>t+(n.type==="run"?le(n):0),0);case "mathEquation":return e.plainText?.length??0;default:return 0}}function Mn(e,t){if(!e.content.every(i=>i.type==="text"))return [e,null];let n=e.content.map(i=>i.type==="text"?i.text:"").join(""),r=i=>i?{type:"run",...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{},content:[{type:"text",text:i}]}:null;return [r(n.slice(0,t)),r(n.slice(t))]}function Ce(e,t,n=r=>r.kind==="start"?{type:"commentRangeStart",id:r.id}:{type:"commentRangeEnd",id:r.id}){if(t.length===0)return e;let r=[...t].sort((d,m)=>d.offset-m.offset||(d.kind===m.kind?d.id-m.id:d.kind==="end"?-1:1)),i=[],o=0,a=0,l=d=>{for(;a<r.length&&r[a].offset===d;){let m=r[a++];i.push(n(m));}};l(0);for(let d of e){let m=K(d),u=r.slice(a).map(c=>c.offset).filter(c=>c>o&&c<o+m);if(d.type==="run"&&d.content.every(c=>c.type==="text")){let c=d,y=0;for(let f of u){if(!c)break;let[h,g]=Mn(c,f-o-y);h&&i.push(h),l(f),c=g,y=f-o;}c&&i.push(c);}else i.push(d);o+=m,l(o);}return l(o),i}function _n(e){if(!Array.isArray(e.bookmarks))return [];let t=[];for(let n of e.bookmarks){let r=C(n),i=A(r?.id);if(!r||i===void 0)continue;let o=A(r.offset)??0,a={name:R(r.name),colFirst:A(r.colFirst),colLast:A(r.colLast)};r.kind==="start"?t.push({id:i,kind:"start",offset:o,...a}):r.kind==="end"?t.push({id:i,kind:"end",offset:o,...a}):(t.push({id:i,kind:"start",offset:0,...a}),t.push({id:i,kind:"end",offset:Number.MAX_SAFE_INTEGER,...a}));}return t}function Bn(e,t){if(!t)return e;let n=e.reduce((o,a)=>o+K(a),0),r=[],i=0;for(let[o,a]of t.content.entries())a.type==="rawXml"&&r.push({id:o,kind:"start",offset:Math.min(i,n)}),i+=K(a);return Ce(e,r,o=>t.content[o.id])}function On(e){let t={...mn,...e};return t.styleId=e.pStyle??null,t._sectionProperties=e.sectPr??null,delete t.pStyle,delete t.sectPr,t}function Nn(e,t,n,r,i){let o=On(t),a=ue(n);a=Yn(a,n,Array.isArray(o._originalRunBoundaries)?o._originalRunBoundaries:void 0),a=Bn(a,i),a=Ce(a,r);let l=_n(t).map(c=>({...c,offset:c.offset===Number.MAX_SAFE_INTEGER?a.reduce((y,f)=>y+K(f),0):c.offset}));l.length>0&&(a=Ce(a,l,c=>{let y=c;return y.kind==="start"?{type:"bookmarkStart",id:y.id,name:y.name||"",...y.colFirst!==void 0?{colFirst:y.colFirst}:{},...y.colLast!==void 0?{colLast:y.colLast}:{},position:{offset:y.offset}}:{type:"bookmarkEnd",id:y.id,position:{offset:y.offset}}}));let d={type:"paragraph",paraId:e||void 0,textId:i?.textId,formatting:dt(o),content:a};i?.renderedPageBreakBefore&&(d.renderedPageBreakBefore=true);let m=V(t.pPrIns,true),u=V(t.pPrDel,true);return m&&(d.pPrIns=m),u&&(d.pPrDel=u),Array.isArray(t.pPrChange)&&t.pPrChange.length>0&&(d.propertyChanges=t.pPrChange),t.sectPr?d.sectionProperties=t.sectPr:t.sectionBreakType&&(d.sectionProperties={sectionStart:t.sectionBreakType}),d}function En(e){let t=e[0]?.cells,n=e[e.length-1]?.cells,r=t?.[0]?.formatting?.borders;if(!t||!n||!r)return;let i={top:r.top,left:r.left,bottom:n[0]?.formatting?.borders?.bottom,right:t[t.length-1]?.formatting?.borders?.right,insideH:e.length>1?r.bottom:void 0,insideV:t.length>1?r.right:void 0},o=Object.entries(i).filter(([,a])=>a!==void 0);return o.length>0?Object.fromEntries(o):void 0}function Ln(e){let t=new Map;e.forEach((r,i)=>{let o=0;for(let a of r.cells){let l=o;if(o+=a.formatting?.gridSpan??1,a.formatting?.vMerge){let d=t.get(l)??[];d.push({rowIndex:i,cell:a}),t.set(l,d);}}});let n=r=>{r.formatting&&(delete r.formatting.vMerge,Object.keys(r.formatting).length===0&&(r.formatting=void 0));};for(let r of t.values()){let i=null,o=0,a=-1,l=()=>{i&&o<2&&n(i),i=null,o=0;};for(let d of r){let m=d.cell.formatting?.vMerge;m==="restart"?(l(),i=d.cell,o=1,a=d.rowIndex):m==="continue"&&(i&&d.rowIndex===a+1?(o+=1,a=d.rowIndex):(l(),n(d.cell)));}l();}}function Dn(e,t){let n={...bn,...t.tcPr??{}},r=t.story&&e.storyIds.has(t.story)?e.storyToBlocks(t.story):[],i={type:"tableCell",formatting:pt(n),content:r},o=n.cellMarker;if(o){let a=V(o.info,true)??{id:0,author:"Unknown"};o.kind==="ins"?i.structuralChange={type:"tableCellInsertion",info:a}:o.kind==="del"?i.structuralChange={type:"tableCellDeletion",info:a}:i.structuralChange={type:"tableCellMerge",info:a,...o.vMerge?{vMerge:o.vMerge}:{},...o.vMergeOrig?{vMergeOrig:o.vMergeOrig}:{}};}return Array.isArray(n.tcPrChange)&&n.tcPrChange.length>0&&(i.propertyChanges=n.tcPrChange),i}function Jn(e,t){let n=Array.isArray(t.rows)?t.rows:[],r=[],i=[],o=0;n.forEach((f,h)=>{let g=0;for(let k of Array.isArray(f.cells)?f.cells:[]){for(;r[h]?.[g];)g+=1;let w=k.tcPr??{},T=A(w.rowspan)||1,v=A(w.colspan)||1;i.push({row:h,col:g,rowspan:T,colspan:v,cell:Dn(e,k)});for(let P=h;P<h+T;P+=1){r[P]??(r[P]=[]);for(let I=g;I<g+v;I+=1)r[P][I]=true;}g+=v,o=Math.max(o,g);}});let a=new Map(i.map(f=>[`${f.row}-${f.col}`,f])),l=new Map;for(let f of i)for(let h=f.row;h<f.row+f.rowspan;h+=1)for(let g=f.col;g<f.col+f.colspan;g+=1)l.set(`${h}-${g}`,f);let d=n.map((f,h)=>{let g=[];for(let P=0;P<o;){let I=a.get(`${h}-${P}`);if(I){let N={...I.cell.formatting??{}};I.colspan>1?N.gridSpan=I.colspan:delete N.gridSpan,I.rowspan>1?N.vMerge="restart":N.vMerge!=="restart"&&N.vMerge!=="continue"&&delete N.vMerge,g.push({...I.cell,formatting:Object.keys(N).length>0?N:void 0}),P+=I.colspan;continue}let M=l.get(`${h}-${P}`);if(!M){P+=1;continue}let S={...M.cell.formatting??{}};M.colspan>1?S.gridSpan=M.colspan:delete S.gridSpan,S.vMerge="continue",g.push({...M.cell,content:[],formatting:S}),P+=M.colspan;}let k={...yn,...f.trPr??{}},w={type:"tableRow",formatting:ct(k),cells:g},T=V(k.trIns,true),v=V(k.trDel,true);return T?w.structuralChange={type:"tableRowInsertion",info:T}:v&&(w.structuralChange={type:"tableRowDeletion",info:v}),Array.isArray(k.trPrChange)&&k.trPrChange.length>0&&(w.propertyChanges=k.trPrChange),w});Ln(d);let m=Array.isArray(t.grid)?t.grid.filter(f=>typeof f=="number"):[],u={...hn,...t.tblPr??{},columnWidths:m.length>0?m:void 0},c=ut(u);if(!c?.borders){let f=En(d);f&&(c={...c??{},borders:f});}let y={type:"table",columnWidths:u.columnWidths||void 0,formatting:c,rows:d};return Array.isArray(u.tblPrChange)&&u.tblPrChange.length>0&&(y.propertyChanges=u.tblPrChange),y}function Un(){return {type:"paragraph",content:[{type:"run",content:[{type:"break",breakType:"page"}]}]}}function Fe(e){return e.type==="insertion"||e.type==="deletion"||e.type==="moveFrom"||e.type==="moveTo"?e.content.length>0&&e.content.every(Fe):e.type==="run"&&e.content.length>0&&e.content.every(t=>t.type==="footnoteRefMark"||t.type==="endnoteRefMark")}function Wn(e){return e.some(t=>t.type==="paragraph"&&t.content.some(Fe))}function jn(e,t){if(Wn(e))return e;let n=t.find(d=>d.type==="paragraph")?.content??[],r=n.findIndex(d=>!Fe(d)),i=n.slice(0,r<0?n.length:r);if(i.length===0)return e;let o=e.findIndex(d=>d.type==="paragraph");if(o<0)return e;let a=e[o],l=[...e];return l[o]={...a,content:[...i,...a.content]},l}function zn(e){let t=new Map,n=r=>{for(let i of r)if(i.type==="paragraph")i.paraId&&!t.has(i.paraId)&&t.set(i.paraId,i);else if(i.type==="table")for(let o of i.rows)for(let a of o.cells)n(a.content);else i.type==="blockSdt"&&n(i.content);};n(e.package.document.content);for(let r of e.package.headers?.values()??[])n(r.content);for(let r of e.package.footers?.values()??[])n(r.content);for(let r of e.package.footnotes??[])n(r.content);for(let r of e.package.endnotes??[])n(r.content);return t}function $n(e){let t=new Map,n=(r,i)=>{t.set(r,i);let o=0,a=0;for(let l of i){if(l.type==="blockSdt"){n(`${r}:sdt${a++}`,l.content);continue}if(l.type!=="table")continue;let d=o++;l.rows.forEach((m,u)=>{m.cells.forEach((c,y)=>{n(`${r}:t${d}:r${u}c${y}`,c.content);});});}};n("body",e.package.document.content);for(let[r,i]of e.package.headers??[])n(`hf:${r}`,i.content);for(let[r,i]of e.package.footers??[])n(`hf:${r}`,i.content);for(let r of e.package.footnotes??[])n(`fn:${r.id}`,r.content);for(let r of e.package.endnotes??[])n(`en:${r.id}`,r.content);return t}function Hn(e,t){let n=new Map;for(let r of t??[]){let i;try{i=e.resolveComment(String(r.id));}catch{continue}let o=new Map;for(let a of i){let l=o.get(a.story)??[];l.push(a),o.set(a.story,l);}for(let[a,l]of o){if(l.length===0)continue;let d=Math.min(...l.map(c=>c.start)),m=Math.max(...l.map(c=>c.end)),u=n.get(a)??[];u.push({id:r.id,start:d,end:m}),n.set(a,u);}}return n}function Vn(e,t){let n=0;for(let r=0;r<t.length;r+=1){let i=t[r];if(!ne(i))continue;let o=t.slice(r+1).find(d=>d.type==="paragraph"&&d.paraId&&e.some(m=>m.type==="paragraph"&&m.paraId===d.paraId)),a=o?.type==="paragraph"?e.findIndex(d=>d.type==="paragraph"&&d.paraId===o.paraId):-1,l=a>=0?a:Math.min(r+n,e.length);e.splice(l,0,i),n=Math.max(0,l-r);}return e}var Pe=class{constructor(t,n){b(this,"session",t);b(this,"storyIds");b(this,"baseParagraphs");b(this,"baseStories");b(this,"comments");this.storyIds=new Set(t.storyIds()),this.baseParagraphs=zn(n),this.baseStories=$n(n),this.comments=Hn(t,n.package.document.comments);}storyToBlocks(t){let n=[],r=this.baseStories.get(t),i=r?.filter(f=>f.type==="paragraph"),o=this.session.storySegments(t),a=this.comments.get(t)??[],l=[],d=0,m=0,u=0,c=f=>{let h=[];for(let g of a)g.start>=d&&g.start<=f&&h.push({id:g.id,kind:"start",offset:g.start-d}),g.end>=d&&g.end<=f&&h.push({id:g.id,kind:"end",offset:g.end-d});return h},y=(f,h)=>{let g=0;for(let k=0;k<f.length;k+=1)f[k]===" "&&(k>g&&l.push({kind:"text",text:f.slice(g,k),attributes:h}),l.push({kind:"embed",embedKind:"tab",payload:{},attributes:h}),g=k+1);g<f.length&&l.push({kind:"text",text:f.slice(g),attributes:h});};for(let f of o){if(f.kind==="text"){y(f.text,f.attributes),u+=f.text.length;continue}if(f.kind==="pilcrow"){let h=`${t}:p${m}`,g=f.paraId===h&&!this.baseParagraphs.has(f.paraId)?"":f.paraId;n.push(Nn(g,f.properties,l,c(u),this.baseParagraphs.get(f.paraId)??(f.paraId===h?i?.[m]:void 0))),l=[],m+=1,u+=1,d=u;continue}if(f.embedKind==="table")n.push(Jn(this,f.payload));else if(f.embedKind==="blockSdt"){let h=R(f.payload.story),g=fe(f.payload),k=h&&this.storyIds.has(h)?this.storyToBlocks(h):[],w=St(f.payload.value);if(w)try{let T=we(g,w);g=T.properties,k=T.content;}catch{}n.push({type:"blockSdt",properties:g,content:k});}else if(f.embedKind==="opaque"){let h=C(f.payload.blob);if(h?.type==="pageBreak")n.push(Un());else {let g=r?.[n.length];h?.type==="blockSdt"&&g?.type==="blockSdt"&&n.push(g);}}else l.push(f);u+=1;}return l.length>0&&n.push({type:"paragraph",content:ue(l)}),Vn(n,r??[])}};function Kn(e,t,n={}){let r=new Pe(e,t),i=c=>n.storyIds===void 0||n.storyIds.has(c),o=r.storyIds.has("body")&&i("body")?r.storyToBlocks("body"):t.package.document.content,a=t.package.headers;a&&(n.storyIds===void 0||[...a.keys()].some(c=>i(`hf:${c}`)))&&(a=new Map([...a].map(([c,y])=>{let f=`hf:${c}`;return [c,r.storyIds.has(f)&&i(f)?{...y,content:r.storyToBlocks(f)}:y]})));let l=t.package.footers;l&&(n.storyIds===void 0||[...l.keys()].some(c=>i(`hf:${c}`)))&&(l=new Map([...l].map(([c,y])=>{let f=`hf:${c}`;return [c,r.storyIds.has(f)&&i(f)?{...y,content:r.storyToBlocks(f)}:y]})));let d=(c,y)=>n.storyIds===void 0||c?.some(h=>i(`${y}${h.id}`))?c?.map(h=>{let g=`${y}${h.id}`;return r.storyIds.has(g)&&i(g)?{...h,content:jn(r.storyToBlocks(g),h.content),verbatimXml:void 0}:h}):c,m=d(t.package.footnotes,"fn:"),u=d(t.package.endnotes,"en:");return {...t,package:{...t.package,document:{...t.package.document,content:o},...a?{headers:a}:{},...l?{footers:l}:{},...m?{footnotes:m}:{},...u?{endnotes:u}:{}}}}function Jr(e,t){return !e||!t?e===t:e.anchor.story===t.anchor.story&&e.anchor.paraId===t.anchor.paraId&&e.anchor.offset===t.anchor.offset&&e.head.story===t.head.story&&e.head.paraId===t.head.paraId&&e.head.offset===t.head.offset}function Xn(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}function wt(e){return JSON.stringify("revisionId"in e?{revisionId:e.revisionId}:{story:e.story,startPara:e.start.paraId,startOffset:e.start.offset,endPara:e.end.paraId,endOffset:e.end.offset})}function qn(e){return JSON.stringify(e.map(t=>({story:t.story,startPara:t.start.paraId,startOffset:t.start.offset,endPara:t.end.paraId,endOffset:t.end.offset})))}function xt(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function Gn(e,t){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("DOCX host metadata must be an object");let r=n;if(!Array.isArray(r.referencedFonts)||!r.referencedFonts.every(o=>typeof o=="string"))throw new TypeError("DOCX host referencedFonts must be a string array");let i=c(r.envelope,xt(t));return {document:i.document,referencedFonts:r.referencedFonts,embeddedFonts:i.embeddedFonts,...i.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:i.fontTableRelationshipsXml}}}function Zn(e,t){let n=new Map,r=[],i=false,o=false,a=0,l=0,d=false,m=false,u,c=null,y=[],f=new Map,h=new Map,g=null,k=false,w=0,T=0,v=false,P=null,I=()=>{u=void 0,c=null;},M=()=>{if(!(o||d||l!==0)){d=true;try{for(;!o&&r.length>0;){let s=r.shift();if(!s)break;for(let[p,b]of [...n]){if(o)return;if(n.get(p)===b)try{b(s.update.slice(),s.origin);}catch{}}}}finally{d=false,o&&(r.length=0);}}},S=s=>{I(),l+=1;try{return s()}finally{l-=1,l===0&&M();}},N=s=>s?{anchor:{...s.anchor},head:{...s.head}}:null,x=s=>{m||(e.track_undo(),m=true),s!==void 0&&e.select_story(s);},Tt=()=>{i||(e.set_update_observer((s,p)=>{p!==0&&p!==1||(r.push({update:s.slice(),origin:p===0?"local":"remote"}),M());}),i=true);},Ct=()=>{!i||n.size>0||o||(r.length=0,e.clear_update_observer(),i=false);},Ye=(s,p)=>{let b=s.slice(),F=S(()=>e.open_docx(b,p)),q=Gn(F,b);return P=b,q};return {clientId:t,registerFont:s=>{v||(e.clear_measure_fonts(),v=true);let p=e.register_measure_font(s);return y.push(s.slice()),T+=1,p},clearFonts:()=>{e.clear_measure_fonts(),y.length=0,h.clear(),T+=1,v=true;},measureParagraphJson:s=>{let p=e.measure_paragraph_json(s);return h.set(s,s),p},layoutDocumentJson:s=>{let p=e.layout_document_json(s);return g=s,k=false,w+=1,p},layoutFontRequirementsJson:s=>e.layout_font_requirements_json(s),layoutDocumentWithRegionsJson:s=>{let p=e.layout_document_with_regions_json(s);return g=s,k=true,w+=1,p},layoutDocumentWithRegionsRetainedJson:s=>{let p=e.layout_document_with_regions_retained_json(s);return g=s,k=true,w+=1,p},retainedKernelInputsJson:s=>{if(s!==w)throw new Error(`retained layout revision mismatch: expected ${s}, current ${w}`);return e.retained_kernel_inputs_json()},buildDisplayListJson:s=>e.build_display_list_json(s),buildDisplayListFrame:(s,p)=>e.build_display_list_frame(s,p),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),applyInput:(s,p)=>(x(),S(()=>e.apply_input(s,p))),applyDelete:(s,p)=>(x(),S(()=>e.apply_delete(s,p))),applyInputProfiled:(s,p)=>{x();let b=S(()=>e.apply_input_profiled(s,p)),F=JSON.parse(e.apply_input_profile_json());return {frame:b,profile:F}},applyDeleteProfiled:(s,p)=>{x();let b=S(()=>e.apply_delete_profiled(s,p)),F=JSON.parse(e.apply_input_profile_json());return {frame:b,profile:F}},residentWorkerSnapshot:s=>{if(!g||!k&&f.size===0)return null;let p=e.selection(),b=s?.knownFontsRevision===T,F=null;if(s?.knownStateVector)try{F=e.encode_diff(s.knownStateVector.slice());}catch{F=null;}return {clientId:t,state:F??e.encode_state(),selection:JSON.parse(p),fonts:b?[]:y.map(q=>q.slice()),fontsRevision:T,renderInputs:[...f].map(([q,Pt])=>({story:q,env:structuredClone(Pt)})),measureInputs:[...h.values()],layoutInput:g,layoutWithRegions:k,layoutRevision:w}},residentWorkerProbe:()=>!g||!k&&f.size===0?null:{layoutRevision:w},displayHitTestRegionsJson:(s,p,b)=>e.display_hit_test_regions_json(s,p,b),displayVerticalMoveJson:(s,p,b)=>e.display_vertical_move_json(s,p,b),displayRangeRectsJson:(s,p)=>e.display_range_rects_json(s,p),displayRangeRectsRegionJson:(s,p,b,F)=>e.display_range_rects_region_json(s,p,b,F),outlineGlyphJson:(s,p)=>e.outline_glyph_json(s,p),loadState:s=>S(()=>e.load(s)),seedFromDocx:s=>Ye(s,true),openDocx:Ye,materializeDocx:()=>{let s=P,p=e.materialize_docx();return !s||p===void 0?null:b$1(p,xt(s)).document},loadStories:s=>S(()=>JSON.parse(e.load_json(JSON.stringify(s)))),encodeState:()=>e.encode_state(),encodeStateVector:()=>e.encode_state_vector(),encodeStateAsUpdate:s=>s===void 0?e.encode_state():e.encode_diff(s.slice()),applyUpdate:s=>S(()=>JSON.parse(e.apply_update_with_inference(s))),applyLocalUpdate:s=>{x(),S(()=>e.apply_local_update(s));},onUpdate:s=>{if(o)throw new Error("yrs session is destroyed");if(typeof s!="function")throw new TypeError("update listener must be a function");let p=a++;n.set(p,s),Tt();let b=true;return ()=>{b&&(b=false,n.delete(p),Ct());}},encodeStickyPosition:s=>({story:s.story,encoded:e.encode_sticky_position(s.story,s.paraId,s.offset)}),resolveStickyPosition:s=>{try{return JSON.parse(e.resolve_sticky_position(s.story,s.encoded))}catch{return null}},setSelection:(s,p=s)=>{if(s.story!==p.story)throw new Error("yrs selection must stay inside one story");e.set_selection(s.story,s.paraId,s.offset,p.paraId,p.offset),u={anchor:{...s},head:{...p}};},selection:()=>(u!==void 0||(u=JSON.parse(e.selection())),N(u)),encodeSelection:()=>{let s=JSON.parse(e.encoded_selection());return s?{story:s.story,anchor:Uint8Array.from(s.anchor),head:Uint8Array.from(s.head)}:null},resolveSelection:s=>{try{return JSON.parse(e.resolve_encoded_selection(s.story,s.anchor,s.head))}catch{return null}},setCellSelection:s=>e.set_cell_selection(JSON.stringify(s)),cellSelection:()=>JSON.parse(e.cell_selection()),beginUndoCapture:x,historyStories:()=>e.history_stories(),undo:()=>S(()=>e.undo()),redo:()=>S(()=>e.redo()),canUndo:()=>e.can_undo(),canRedo:()=>e.can_redo(),createStory:(s,p,b="Normal",F="left")=>S(()=>JSON.parse(e.create_story(s,p,b,F))),deleteStory:s=>S(()=>e.delete_story(s)),insertTable:(s,p,b,F)=>(x(s.story),S(()=>JSON.parse(e.insert_table(s.story,s.paraId,s.offset,p,b,F?.name,F?.date)))),insertRow:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_row(JSON.stringify(s),p==="below",b?.name,b?.date)))),insertColumn:(s,p)=>(x(s.story),S(()=>JSON.parse(e.insert_column(JSON.stringify(s),p==="right")))),deleteRow:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.delete_row(JSON.stringify(s),p?.name,p?.date)))),deleteColumn:s=>(x(s.anchor.story),S(()=>JSON.parse(e.delete_column(JSON.stringify(s))))),deleteTable:s=>(x(s.story),S(()=>JSON.parse(e.delete_table(JSON.stringify(s))))),mergeCells:s=>(x(s.anchor.story),S(()=>JSON.parse(e.merge_cells(JSON.stringify(s))))),splitCell:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.split_cell(JSON.stringify(s),p,b)))),setCellShading:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_shading(JSON.stringify(s),p??void 0)))),setCellTextFormat:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_text_format(JSON.stringify(s),JSON.stringify(p))))),setCellBorders:(s,p)=>(x(s.anchor.story),S(()=>JSON.parse(e.set_cell_borders(JSON.stringify(s),JSON.stringify(p))))),setColumnWidth:(s,p)=>(x(s.story),S(()=>JSON.parse(e.set_column_width(JSON.stringify(s),p)))),setTableWidth:(s,p)=>(x(s.story),S(()=>JSON.parse(e.set_table_width(JSON.stringify(s),p)))),insertText:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_text(s.story,s.paraId,s.offset,p,b?.name,b?.date)))),deleteRange:(s,p)=>(x(s.story),S(()=>JSON.parse(e.delete_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p?.name,p?.date)))),replaceRange:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.replace_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p,b?.name,b?.date)))),splitParagraph:(s,p)=>(x(s.story),S(()=>JSON.parse(e.split_paragraph(s.story,s.paraId,s.offset,p?.name,p?.date)))),mergeParagraphs:(s,p,b)=>(x(s),S(()=>JSON.parse(e.merge_paragraphs(s,p,b?.name,b?.date)))),toggleMark:(s,p)=>{x(s.story),S(()=>e.toggle_mark(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},formatRange:(s,p)=>{x(s.story),S(()=>e.format_range(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},setHyperlink:(s,p)=>{x(s.story),S(()=>e.set_hyperlink(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p)));},clearFormatting:s=>{x(s.story),S(()=>e.clear_formatting(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset));},applyParagraphStyle:(s,p,b)=>{x(s.story),S(()=>e.apply_paragraph_style(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,p,b?.name,b?.date));},setParagraphAttrs:(s,p,b)=>{x(s.story),S(()=>e.set_paragraph_attrs(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset,JSON.stringify(p),b?.name,b?.date));},insertImage:(s,p,b)=>(x(s.story),S(()=>JSON.parse(e.insert_image(s.story,s.paraId,s.offset,JSON.stringify(p),b?.name,b?.date)))),setContentControlValue:(s,p)=>{x(),S(()=>e.set_content_control_value(s,JSON.stringify(p)));},setContentControlValueAt:(s,p)=>{x(s.story),S(()=>e.set_content_control_value_at(s.story,s.paraId,s.offset,JSON.stringify(p)));},clearContentControlValue:s=>{x(),S(()=>e.clear_content_control_value(s));},setImageGeometry:(s,p)=>{x(),S(()=>e.set_image_geometry(s,JSON.stringify(p)));},insertPageBreak:s=>{x(s.story),S(()=>e.insert_page_break(s.story,s.paraId,s.offset));},insertSectionBreak:(s,p)=>{x(s.story),S(()=>e.insert_section_break(s.story,s.paraId,s.offset,p));},insertWatermark:(s,p)=>{x(s.story),S(()=>e.insert_watermark(s.story,s.paraId,s.offset,JSON.stringify(p)));},applyRawOps:(s,p)=>S(()=>e.apply_raw_ops(s,JSON.stringify(p))),applySeedRawOps:(s,p)=>S(()=>e.apply_seed_raw_ops(s,JSON.stringify(p))),setParagraphAttr:(s,p,b)=>S(()=>e.set_paragraph_attr(s,p,JSON.stringify(b??null))),addComment:(s,p,b,F)=>S(()=>JSON.parse(e.add_comment(qn(s),p,b,JSON.stringify(F??null)))),acceptChange:s=>S(()=>JSON.parse(e.accept_change(wt(s)))),rejectChange:s=>S(()=>JSON.parse(e.reject_change(wt(s)))),selectionContext:s=>{let p=JSON.stringify(s);if(c?.key===p)return JSON.parse(c.json);let b=e.selection_context(s.story,s.start.paraId,s.start.offset,s.end.paraId,s.end.offset),F=JSON.parse(b);return c={key:p,json:b},F},listRevisions:()=>JSON.parse(e.list_revisions()),resolveComment:s=>JSON.parse(e.resolve_comment(s)),storyIds:()=>e.story_ids(),storyLength:s=>e.story_len(s),storyChecksum:s=>BigInt(e.story_checksum(s)),yrsBlocksForStory:(s,p={})=>{let b=e.yrs_blocks_for_story(s,JSON.stringify(p)),F=JSON.parse(b);return f.set(s,structuredClone(p)),F},paragraphs:s=>JSON.parse(e.paragraphs(s)),paragraphSpans:s=>JSON.parse(e.paragraph_spans(s)),storySegments:s=>JSON.parse(e.story_segments(s)),locateParagraph:(s,p)=>JSON.parse(e.locate_paragraph(s,p)),destroy:()=>{o||(o=true,n.clear(),r.length=0,i&&e.clear_update_observer(),e.free());}}}async function Ur(e){let t=e?.clientId??Xn(),n=await import('../wasm-7SOSHNGP.mjs');return await n.preloadEditWasm(),Zn(n.createEditSession(t),t)}export{ce as ResidentEngineWorkerClient,J as ResidentWorkerFailureError,Mt as canUseResidentEngineWorker,tr as compareYrsLocs,Qn as createYrsInputPositionMap,Ur as createYrsSession,er as displayPositionToYrsLoc,un as documentToYrs,Jr as sameYrsSelection,De as yrsLocToDisplayPosition,Kn as yrsToDocument};
1
+ import {f,g,c,a,d as d$2,e}from'../chunk-5JEQC76K.mjs';export{g as yrsToDocument}from'../chunk-5JEQC76K.mjs';export{a as residentCaretDeviceRect,b as residentCaretSnapshotForFrame}from'../chunk-J7LNO6SM.mjs';import {d as d$1}from'../chunk-VQXNED2P.mjs';import {b as b$5}from'../chunk-OBQGPMPQ.mjs';import {d,a as a$1,b as b$3}from'../chunk-47Q2FMFF.mjs';import {b as b$2,p}from'../chunk-LTVVQMHB.mjs';import {b as b$4}from'../chunk-CTBUQRYQ.mjs';import {b as b$1,c as c$1}from'../chunk-QE4ZDRKV.mjs';import'../chunk-HLDJMU3R.mjs';import'../chunk-ACGKK7IB.mjs';import'../chunk-5F6DLQZP.mjs';import {b}from'../chunk-TTRUPDAB.mjs';function Xt(e,r){let n=0,o=r.map(s=>{let a={paraId:s.paraId,length:Math.max(0,Math.trunc(s.length)),displayStart:n};return n+=a.length+2,a});return {story:e,paragraphs:o}}function Ce(e,r){let n=e.paragraphs.find(o=>o.paraId===r.paraId);return !n||r.story!==e.story?e.paragraphs[0]?.displayStart??0:n.displayStart+1+Math.min(Math.max(0,r.offset),n.length)}function Qt(e,r){if(e.paragraphs.length===0)return null;let n=Math.max(0,Math.trunc(r)),o=e.paragraphs[0];for(let s of e.paragraphs){if(s.displayStart>n)break;o=s;}return {story:e.story,paraId:o.paraId,offset:Math.min(Math.max(0,n-(o.displayStart+1)),o.length)}}function Zt(e,r,n){return Ce(e,r)-Ce(e,n)}var nt={bootstrap:15e3,sync:15e3,attachCanvases:15e3,buildFrame:5e3,applyInput:5e3,applyDelete:5e3};function ot(){return new Worker(new URL("./residentEngineWorker.mjs",import.meta.url),{type:"module",name:"openooxml-resident-engine"})}var oe=class{constructor(r=ot()){b(this,"worker",r);b(this,"pending",new Map);b(this,"nextId",1);b(this,"terminalError",null);b(this,"ready",false);b(this,"revision",0);b(this,"remoteVector",null);b(this,"appliedFontsRevision",null);this.worker.onmessage=n=>{let o=n.data;if(o.ok&&o.stateVector&&(this.remoteVector=new Uint8Array(o.stateVector)),!o.ok&&o.terminal){this.fail(new U(o.error));return}let s=this.pending.get(o.id);s&&(this.pending.delete(o.id),clearTimeout(s.timeout),o.ok?s.resolve(o):s.reject(at(o.error,o.residentUnavailable)));},this.worker.onerror=n=>{this.fail(new O(`Resident engine worker failed: ${n.message}`));},this.worker.onmessageerror=()=>{this.fail(new O("Resident engine worker returned an unreadable message"));};}isReady(){return this.ready}layoutRevision(){return this.revision}remoteStateVector(){return this.remoteVector}syncedFontsRevision(){return this.appliedFontsRevision}async bootstrap(r,n){let o=r.fontsRevision,s=await this.request({type:"bootstrap",snapshot:r,extras:n,expectedFrameEpoch:0},ve(r)),a=j(s);return this.recordSync(s,o),this.ready=true,this.revision=a.layoutRevision,a}async sync(r,n,o,s=false){let a=r.fontsRevision,d=await this.request({type:"sync",snapshot:r,extras:n,expectedFrameEpoch:o,paintCaret:s},ve(r)),u=j(d);return this.recordSync(d,a),this.ready=true,this.revision=u.layoutRevision,u}async buildFrame(r,n,o=false){return j(await this.request({type:"buildFrame",extras:r,expectedFrameEpoch:n,paintCaret:o}))}async applyInput(r,n,o,s=false,a=false){if(!this.ready)return {applied:false};try{return {applied:!0,...j(await this.request({type:"applyInput",text:r,selection:n,expectedFrameEpoch:o,profile:s,paintCaret:a}))}}catch(d){if(d instanceof U)return {applied:false};throw d}}async applyDelete(r,n,o,s=false,a=false){if(!this.ready)return {applied:false};try{return {applied:!0,...j(await this.request({type:"applyDelete",direction:r,selection:n,expectedFrameEpoch:o,profile:s,paintCaret:a}))}}catch(d){if(d instanceof U)return {applied:false};throw d}}eraseCaret(){if(this.terminalError)return;let n={id:this.nextId++,type:"eraseCaret"};this.worker.postMessage(n);}invalidate(r,n){if(this.terminalError)return;this.ready=false;let o=r.slice(),a={id:this.nextId++,type:"applyUpdate",update:o,selection:n};this.worker.postMessage(a,[o.buffer]);}async attachCanvases(r,n,o,s,a){let d=r.map(u=>u.canvas);await this.request({type:"attachCanvases",pages:r,activePageIds:n,devicePixelRatio:o,zoom:s,caretStyle:a},d);}destroy(){if(this.terminalError)return;let n={id:this.nextId++,type:"destroy"};this.worker.postMessage(n),this.fail(new O("Resident engine worker was destroyed"));}request(r,n=[]){if(this.terminalError)return Promise.reject(this.terminalError);let o=this.nextId++,s=nt[r.type];return new Promise((a,d)=>{let u=setTimeout(()=>{this.fail(new O(`Resident engine worker did not answer ${r.type} within ${s}ms`));},s);this.pending.set(o,{resolve:a,reject:d,timeout:u}),this.worker.postMessage({...r,id:o},n);})}recordSync(r,n){this.appliedFontsRevision=n;}fail(r){this.terminalError=r,this.ready=false,this.worker.terminate();for(let n of this.pending.values())clearTimeout(n.timeout),n.reject(r);this.pending.clear();}},U=class extends Error{},O=class extends Error{};function at(e,r=false){return r?new U(e):new Error(e)}function ve(e){return [e.state.buffer,...e.fonts.flatMap(r=>r instanceof Uint8Array?[r.buffer]:[])]}function j(e){if(!e.frame)throw new O("Resident engine worker response omitted its FrameDelta");if(!e.caret)throw new O("Resident engine worker response omitted its caret snapshot");if(e.selection===void 0)throw new O("Resident engine worker response omitted its selection");return {frame:new Uint8Array(e.frame),updates:(e.updates??[]).map(r=>new Uint8Array(r)),engineMs:e.engineMs??0,workerTotalMs:e.workerTotalMs??0,engineProfile:e.engineProfile,caret:e.caret,selection:e.selection,caretPainted:e.caretPainted??false,replayMs:e.replayMs??0,replayedPages:e.replayedPages??0,layoutRevision:e.layoutRevision??0}}function st(){return typeof Worker<"u"}function ae(e,r,n,o,s,a){let d=r?.pPr;if(!r?.tblStylePr?.some(T=>T.pPr))return d;let u=e.formatting?.look??r.tblPr?.look,c=(T,E)=>u?.[T]??(Number.parseInt(u?.value??(u?"0":"04A0"),16)&E)!==0,f=c("firstRow",32),l=c("lastRow",64),y=c("firstColumn",128),b=c("lastColumn",256),S=e.rows[n].formatting?.gridBefore??0;o+=S,s+=S;let h=!!f&&n===0,p=!!l&&n===e.rows.length-1,x=!!y&&o===0,C=!!b&&s===a,I=e.formatting?.styleRowBandSize??r.tblPr?.styleRowBandSize??1,w=e.formatting?.styleColBandSize??r.tblPr?.styleColBandSize??1,Y=[];!c("noHBand",512)&&!h&&!p&&I>0&&Y.push(Math.floor((n-+!!f)/I)%2===0?"band1Horz":"band2Horz"),!c("noVBand",1024)&&!x&&!C&&w>0&&Y.push(Math.floor((o-+!!y)/w)%2===0?"band1Vert":"band2Vert");for(let[T,E]of [["firstCol",x],["lastCol",C],["firstRow",h],["lastRow",p],["nwCell",h&&x],["neCell",h&&C],["swCell",p&&x],["seCell",p&&C]])E&&Y.push(T);for(let T of Y)d=b$3(d,r.tblStylePr.find(E=>E.type===T)?.pPr);return d}function Ie(e){return Math.max(e.columnWidths?.length??0,...e.rows.map(r=>r.cells.reduce((n,o)=>n+(o.formatting?.gridSpan??1),(r.formatting?.gridBefore??0)+(r.formatting?.gridAfter??0))))}function D(e){if(Array.isArray(e))return e.map(D);if(e!==null&&typeof e=="object"){let r={};for(let[n,o]of Object.entries(e))o!=null&&(r[n]=D(o));return r}return e}var it={styleId:"pStyle",_sectionProperties:"sectPr"},lt=new Set(["paraId","textId","renderedPageBreakBefore","numPrFromStyle"]);function Te(e){let r={};for(let[n,o]of Object.entries(e))lt.has(n)||o===null||o===void 0||(r[it[n]??n]=D(o));return r}var dt=new Set(["columnWidths"]);function K(e,r=new Set){let n={};for(let[o,s]of Object.entries(e))r.has(o)||s===null||s===void 0||(n[o]=D(s));return n}function Ye(e){return K(e,dt)}function we(e){let r=e.columnWidths;return Array.isArray(r)?r.map(D):[]}function _e(e){return K(e)}function Ae(e,r){let n=K(e);return r&&(n.header=true),n}function se(e,r,n,o){return `${e}:t${r}:r${n}c${o}`}function De(e,r){return `${e}:sdt${r}`}function Oe(e){return K(e)}function G(e){return `hf:${e}`}function Fe(e){return `fn:${e}`}function Me(e){return `en:${e}`}function ut(e){let r=e.package.settings?.compatibilityFlags?.compatibilityMode;return typeof r=="number"&&Number.isFinite(r)?Math.trunc(r):12}var pt=new Set(["bold","italic","superscript","subscript","allCaps","smallCaps","emboss","imprint","textShadow","textOutline","hidden","rtl"]);function W(e){if(e==null)return "null";if(Array.isArray(e))return `[${e.map(W).join(",")}]`;if(typeof e=="object"){let r=e;return `{${Object.keys(r).sort().map(n=>`${JSON.stringify(n)}:${W(r[n])}`).join(",")}}`}return JSON.stringify(e)}function ct(e,r){if(!e||!r)return e;let n=r.resolveRunStyle(e.styleId);return n?a$1(n,e):e}function Be(e){if(!e)return [];let r=[],n=(d,u={})=>r.push({name:d,attrs:u});e.bold&&n("bold"),e.italic&&n("italic"),e.underline&&e.underline.style!=="none"&&n("underline",{style:e.underline.style,color:e.underline.color??null}),(e.strike||e.doubleStrike)&&n("strike",{double:e.doubleStrike||false}),e.color&&!e.color.auto&&n("textColor",{rgb:e.color.rgb??null,themeColor:e.color.themeColor??null,themeTint:e.color.themeTint??null,themeShade:e.color.themeShade??null});let o=e.shading?.fill,s=(!e.shading?.pattern||e.shading.pattern==="clear")&&o?.rgb&&!o.auto?p(o.rgb):void 0,a=e.highlight&&e.highlight!=="none"?e.highlight:s;return a&&n("highlight",{color:a}),(e.fontSize!=null||e.fontSizeCs!=null)&&n("fontSize",{size:e.fontSize??null,sizeCs:e.fontSizeCs??null}),e.fontFamily&&n("fontFamily",{ascii:e.fontFamily.ascii??null,hAnsi:e.fontFamily.hAnsi??null,eastAsia:e.fontFamily.eastAsia??null,cs:e.fontFamily.cs??null,asciiTheme:e.fontFamily.asciiTheme??null,hAnsiTheme:e.fontFamily.hAnsiTheme??null,eastAsiaTheme:e.fontFamily.eastAsiaTheme??null,csTheme:e.fontFamily.csTheme??null}),e.vertAlign==="superscript"?n("superscript"):e.vertAlign==="subscript"&&n("subscript"),e.allCaps&&n("allCaps"),e.smallCaps&&n("smallCaps"),(e.spacing!=null||e.position!=null||e.scale!=null||e.kerning!=null)&&n("characterSpacing",{spacing:e.spacing??null,position:e.position??null,scale:e.scale??null,kerning:e.kerning??null}),e.emboss&&n("emboss"),e.imprint&&n("imprint"),e.shadow&&n("textShadow"),e.emphasisMark&&e.emphasisMark!=="none"&&n("emphasisMark",{type:e.emphasisMark}),e.outline&&n("textOutline"),e.hidden&&n("hidden"),e.rtl&&n("rtl"),e.snapToGrid===false&&r.push({name:"snapToGrid",attrs:{}}),e.effect&&e.effect!=="none"&&n("textEffect",{effect:e.effect}),e.modernEffects&&n("modernTextEffects",{effects:e.modernEffects}),e.styleId&&n("runStyle",{styleId:e.styleId}),r}function Le(e){let r={};for(let n of e)n.name==="comment"||n.name==="footnoteRef"||(pt.has(n.name)?r[n.name]=true:n.name==="snapToGrid"?r.snapToGrid=false:n.name==="highlight"?r.highlight=n.attrs.color:n.name==="insertion"||n.name==="deletion"?r[n.name==="insertion"?"ins":"del"]=D({id:n.attrs.revisionId,author:n.attrs.author,date:n.attrs.date}):r[n.name]=D(n.attrs));return r}function ft(e){return e.filter(r=>r.name!=="hyperlink"&&r.name!=="comment").map(r=>`${r.name}:${JSON.stringify(r.attrs)}`).sort().join("|")}function gt(e,r){return [...e.filter(n=>n.name!==r.name),r]}function z(e,r,n){return {kind:"text",text:e,attrs:Le(r),pmSize:e.length,...n!==void 0?{commentId:n}:{},marks:[...r]}}function v(e,r,n=[],o,s=1){return {kind:"embed",embedKind:e,payload:r,attrs:Le(n),pmSize:s,...o!==void 0?{commentId:o}:{},marks:[...n]}}function Ue(e,r,n){let o=e.formatting?.styleId?n?.getRunStyleOwnProperties(e.formatting.styleId):void 0,s=Be(a$1(a$1(r,o),e.formatting)),a=e.formatting?.styleId,d=a?n?.getStyle(a)?.name:void 0;if([a,d].some(u=>/^(?:Followed)?Hyperlink$/i.test(u??""))){for(let[u,c]of [["color","textColor"],["underline","underline"]])if(e.formatting?.[u]===void 0&&o?.[u]!==void 0){let f=s.find(l=>l.name===c);f&&(f.attrs.inheritedHyperlink=true);}}return s}function mt(e){let r=e.size?.width?b$4(e.size.width):void 0,n=e.size?.height?b$4(e.size.height):void 0,o=e.wrap.type,s=e.wrap.wrapText,a=e.position?.horizontal?.alignment,d;o==="inline"||o==="topAndBottom"?d="none":o==="square"||o==="tight"||o==="through"?s==="left"?d="right":s==="right"?d="left":a==="left"||a==="right"?d=a:d="none":d="none";let u=o==="inline"?"inline":o==="topAndBottom"?"block":b$5(o)||d&&d!=="none"?"float":"block",c=[];e.transform?.rotation&&c.push(`rotate(${e.transform.rotation}deg)`),e.transform?.flipH&&c.push("scaleX(-1)"),e.transform?.flipV&&c.push("scaleY(-1)");let f,l,y;if(e.outline?.width){f=Math.round(e.outline.width/914400*96*100)/100,e.outline.color?.rgb&&(l=`#${e.outline.color.rgb}`);let b={solid:"solid",dot:"dotted",dash:"dashed",lgDash:"dashed",dashDot:"dashed",lgDashDot:"dashed",lgDashDotDot:"dashed",sysDot:"dotted",sysDash:"dashed",sysDashDot:"dashed",sysDashDotDot:"dashed"};y=e.outline.style&&b[e.outline.style]||"solid";}return D({src:e.src||"",alt:e.alt??null,title:e.title??null,width:r??null,height:n??null,rId:e.rId??null,wrapType:o,displayMode:u,cssFloat:d??null,transform:c.length>0?c.join(" "):null,distTop:e.wrap.distT!=null?b$4(e.wrap.distT):null,distBottom:e.wrap.distB!=null?b$4(e.wrap.distB):null,distLeft:e.wrap.distL!=null?b$4(e.wrap.distL):null,distRight:e.wrap.distR!=null?b$4(e.wrap.distR):null,position:e.position?{relativeHeight:e.position.relativeHeight,horizontal:e.position.horizontal?{relativeTo:e.position.horizontal.relativeTo,posOffset:e.position.horizontal.posOffset,align:e.position.horizontal.alignment}:void 0,vertical:e.position.vertical?{relativeTo:e.position.vertical.relativeTo,posOffset:e.position.vertical.posOffset,align:e.position.vertical.alignment}:void 0}:null,borderWidth:f??null,borderColor:l??null,borderStyle:y??null,wrapText:s??null,hlinkHref:e.hlinkHref??null,cropTop:e.crop?.top??null,cropRight:e.crop?.right??null,cropBottom:e.crop?.bottom??null,cropLeft:e.crop?.left??null,shapeType:e.shapeType??null,opacity:e.opacity??null,effectExtentTop:e.padding?.top?b$4(e.padding.top):null,effectExtentBottom:e.padding?.bottom?b$4(e.padding.bottom):null,effectExtentLeft:e.padding?.left?b$4(e.padding.left):null,effectExtentRight:e.padding?.right?b$4(e.padding.right):null,layoutInCell:e.layoutInCell??null,allowOverlap:e.allowOverlap??null})}function yt(e){return {shapeJson:JSON.stringify(e)}}function ht(e){return D({chartJson:JSON.stringify(e),chartType:e.chartType??null,title:e.title??null,width:e.size?.width?b$4(e.size.width):320,height:e.size?.height?b$4(e.size.height):220,rId:e.rId??null,path:e.path??null})}function $(e,r){let n="",o,s=e.type==="simpleField"?e.content:e.fieldResult;for(let u of s)if(u.type==="run"){for(let c of u.content)c.type==="text"&&(n+=c.text);!o&&u.formatting&&(o=u.formatting);}let a=o??(e.type==="complexField"?e.formatting:void 0),d=e.fieldTree?.displayMode??"result";return {payload:{fieldType:e.fieldType,instruction:e.instruction,displayText:n,fieldKind:e.type==="simpleField"?"simple":"complex",fldLock:e.fldLock??false,dirty:e.dirty??false,displayMode:d,hasCachedResult:n.length>0,fieldData:JSON.stringify(e),modelKind:"field"},marks:Be(a$1(r,a))}}function de(e){return {display:e.display,ommlXml:e.ommlXml,plainText:e.plainText||""}}function bt(e){return {name:"hyperlink",attrs:{href:e.href||(e.anchor?`#${e.anchor}`:""),tooltip:e.tooltip??null,rId:e.rId??null}}}function St(e,r,n,o){let s=e.structuredResult?.inline??[],d=[...(e.type==="complexField"?e.structuredCode?.inline??[]:[]).map((y,b)=>({child:y,index:-b-1})),...s.map((y,b)=>({child:y,index:b}))];if(e.type!=="complexField"||!d.some(({child:y})=>y.type==="hyperlink"||y.type==="simpleField")){let y=$(e,r);return [v("field",y.payload,y.marks)]}let u=[],c=[];d.forEach(({child:y,index:b})=>{if(y.type!=="hyperlink"&&y.type!=="simpleField")return;let S=y.type==="simpleField"?$(y,r):null,h=y.type==="hyperlink"?Q(y,r,n):[v("field",S.payload,S.marks)];c.push({index:b,items:h.map(p=>p.kind==="text"?{kind:"text",text:p.text,attributes:p.attrs}:{kind:"embed",embedKind:p.embedKind,payload:p.payload,attributes:p.attrs})});for(let p of h)p.attrs={...p.attrs,fieldResult:{id:o,index:b}};u.push(...h);});let f={...e,fieldResult:s.filter(y=>y.type==="run")},l=$(f,r);return l.payload.fieldData=JSON.stringify(e),l.payload.resultProjection={id:o,children:c},u.push(v("field",l.payload,l.marks)),u}function Ee(e,r,n,o){let s={name:"footnoteRef",attrs:{id:String(e),noteType:r}},a=[...n,s];return v("noteRef",r==="endnote"?{endnoteRefId:e}:{footnoteRefId:e},a,o)}function ie(e){return e.filter(r=>r.name==="insertion"||r.name==="deletion")}function ue(e,r,n){switch(e.type){case "text":return e.text?[z(e.text,r,n)]:[];case "tab":return [z(" ",r,n)];case "break":return e.breakType===void 0||e.breakType==="textWrapping"?[v("break",{},r,n)]:[];case "softHyphen":return [z("\xAD",r,n)];case "noBreakHyphen":return [z("\u2011",r,n)];case "symbol":{let o=Number.parseInt(e.char,16);if(!Number.isInteger(o)||o<0||o>1114111)return [];let s={name:"fontFamily",attrs:{ascii:e.font||null,hAnsi:e.font||null,eastAsia:e.font||null,cs:e.font||null,asciiTheme:null,hAnsiTheme:null,eastAsiaTheme:null,csTheme:null}};return [z(String.fromCodePoint(o),gt(r,s),n)]}case "commentReference":return [v("field",{fieldType:"COMMENT",instruction:"",displayText:"",fieldKind:"simple",fldLock:false,dirty:false,displayMode:"result",hasCachedResult:false,modelKind:"commentReference",...e.id!==void 0?{commentId:e.id}:{}})];case "drawing":return [v("image",mt(e.image),ie(r))];case "horizontalRule":return [v("horizontalRule",{rule:e.rule},r,n)];case "shape":return [v("shape",yt(e.shape),ie(r))];case "chart":return [v("chart",ht(e.chart),ie(r))];case "footnoteRef":return [Ee(e.id,"footnote",r,n)];case "endnoteRef":return [Ee(e.id,"endnote",r,n)];default:return []}}function X(e,r,n,o,s=[]){let a=[...Ue(e,r,n),...s];return e.content.flatMap(d=>ue(d,a,o))}function Q(e,r,n,o=[]){let s=[],a=bt(e);for(let d of e.structuredChildren??e.children)if(d.type==="run"){let u=[...Ue(d,r,n),...o,a];for(let c of d.content)s.push(...ue(c,u));}else if(d.type==="simpleField"||d.type==="complexField"){let u=$(d,r);s.push(v("field",u.payload,[...u.marks,...o,a]));}else d.type==="mathEquation"&&s.push(v("math",de(d),[...o,a]));return s}function Rt(e,r,n){return {name:r,attrs:{revisionId:e.id,author:e.author,date:e.date??null,isMovePair:n}}}function xt(e,r,n,o){let s=e.type==="insertion"||e.type==="moveTo"?"insertion":"deletion",a=Rt(e.info,s,e.type==="moveFrom"||e.type==="moveTo"),d=[];for(let u of e.content)if(u.type==="run")d.push(...X(u,r,n,o,[a]));else {let c=Q(u,r,n,[a]);for(let f of c)o!==void 0&&(f.commentId=o);d.push(...c);}return d}function We(e,r,n){let o=[],s=a=>{if(a.kind==="text"){if((a.text===" "?"tab":"text")==="tab"){o.push({kind:"tab",attrs:a.attrs});return}let u=o[o.length-1];u&&"text"in u&&W(u.attrs)===W(a.attrs)?u.text+=a.text:o.push({kind:"text",text:a.text,attrs:a.attrs});return}o.push({kind:a.embedKind,payload:a.payload,attrs:a.attrs});};for(let a of e.content)if(a.type==="run")X(a,r,n).forEach(s);else if(a.type==="hyperlink")Q(a,r,n).forEach(s);else if(a.type==="simpleField"||a.type==="complexField"){let d=$(a,r);s(v("field",d.payload,d.marks));}else a.type==="inlineSdt"?s(v("sdt",We(a,r,n))):a.type==="mathEquation"&&s(v("math",de(a)));return D({...d$2(e.properties),propertiesJson:JSON.stringify(e.properties),content:o})}function kt(e,r,n){let o=r?r.resolveParagraphStyle(e.formatting?.styleId).runFormatting:void 0;return a$1(o,n)}function Pt(e){let r=[];for(let n of e.content)n.type==="footnoteRefMark"?r.push("footnote"):n.type==="endnoteRefMark"&&r.push("endnote");return r}function je(e){return e.map(r=>{if(r.kind==="text")return r.text;let n=r.payload.footnoteRefId??r.payload.endnoteRefId;return String(n??"")}).join("")}function Ne(e){return e.type!=="break"?null:e.breakType==="page"||e.breakType==="column"?e.breakType:null}function Ct(e){if(!e.content.some(o=>Ne(o)!==null))return [];let r=[],n=0;for(let o of e.content){let s=Ne(o);if(s!==null){r.push({offset:n,type:s});continue}n+=je(ue(o,[])).length;}return r}function vt(e,r,n){let o=X(e,r,n);if(o.some(c=>c.kind!=="text"&&c.embedKind!=="noteRef"))return null;let s=o.map(c=>ft(c.marks));if(s.some(c=>c!==s[0]))return null;let a=Pt(e),d=Ct(e),u=s[0];return {text:je(o),...a.length>0?{noteMarks:a}:{},...d.length>0?{breaks:d}:{},...u!==void 0?{marksKey:u}:{},...e.formatting?{formatting:e.formatting}:{},...e.propertyChanges?{propertyChanges:e.propertyChanges}:{}}}function It(e,r,n,o,s){let a=e.formatting,d=a?.styleId,u=a?.indentFirstLine===0?void 0:a?.indentFirstLine,c=u??e.listRendering?.indentFirstLine??a?.indentFirstLine,f=u===void 0&&e.listRendering?.indentFirstLine!==void 0?e.listRendering.hangingIndent:a?.hangingIndent??e.listRendering?.hangingIndent,l={paraId:e.paraId??null,textId:e.textId??null,styleId:d??null,numPr:a?.numPr??null,numPrFromStyle:a?.numPrFromStyle??null,listNumFmt:e.listRendering?.numFmt??null,listIsBullet:e.listRendering?.isBullet??null,listMarker:e.listRendering?.marker??null,listMarkerHidden:e.listRendering?.markerHidden||null,listMarkerFontFamily:e.listRendering?.markerFontFamily||null,listMarkerFontSize:e.listRendering?.markerFontSize||null,listMarkerBold:e.listRendering?.markerBold??null,listMarkerItalic:e.listRendering?.markerItalic??null,listMarkerColor:e.listRendering?.markerColor??null,listMarkerSuffix:e.listRendering?.markerSuffix||null,listLevelNumFmts:e.listRendering?.levelNumFmts||null,listAbstractNumId:e.listRendering?.abstractNumId??null,listStartOverride:e.listRendering?.startOverride??null,_originalFormatting:a??null};if(r){let h=r.resolveParagraphStyle(d,s),p=h.paragraphFormatting;l.alignment=a?.alignment??p?.alignment??null,l.spaceBefore=a?.spaceBefore??p?.spaceBefore??null,l.spaceAfter=a?.spaceAfter??p?.spaceAfter??null,l.spaceBeforeLines=a?.spaceBeforeLines??p?.spaceBeforeLines??null,l.spaceAfterLines=a?.spaceAfterLines??p?.spaceAfterLines??null,l.beforeAutospacing=a?.beforeAutospacing??p?.beforeAutospacing??null,l.afterAutospacing=a?.afterAutospacing??p?.afterAutospacing??null,l.lineSpacing=a?.lineSpacing??p?.lineSpacing??null,l.lineSpacingRule=a?.lineSpacingRule??p?.lineSpacingRule??null,l.spacingExplicit=a?.spacingExplicit||null,l.indentLeft=a?.indentLeft??e.listRendering?.indentLeft??p?.indentLeft??null,l.indentRight=a?.indentRight??p?.indentRight??null;let C=a?.numPr?.numId===0&&p?.numPr&&p.numPr.numId!==0?void 0:p;l.indentFirstLine=c??C?.indentFirstLine??null,l.hangingIndent=f??C?.hangingIndent??false,l.borders=a?.borders??p?.borders??null,l.shading=a?.shading??p?.shading??null,l.tabs=a?.tabs??p?.tabs??null,l.pageBreakBefore=a?.pageBreakBefore??p?.pageBreakBefore??null,l.keepNext=a?.keepNext??p?.keepNext??null,l.keepLines=a?.keepLines??p?.keepLines??null,l.widowControl=a?.widowControl??p?.widowControl??null,l.contextualSpacing=a?.contextualSpacing??p?.contextualSpacing??null,l.snapToGrid=a?.snapToGrid??p?.snapToGrid??null,l.autoSpaceDE=a?.autoSpaceDE??p?.autoSpaceDE??null,l.autoSpaceDN=a?.autoSpaceDN??p?.autoSpaceDN??null,l.outlineLevel=a?.outlineLevel??p?.outlineLevel??null,l.bidi=a?.bidi??p?.bidi??null;let I=r.getDefaultCharacterStyle()?.rPr,w=I?a$1(h.runFormatting,I):h.runFormatting;l.defaultTextFormatting=a$1(w,ct(a?.runProperties,r))??null,!a?.numPr&&p?.numPr&&p.numPr.numId!==0&&(l.numPr=p.numPr,l.numPrFromStyle=p.numPr);}else l.alignment=a?.alignment??null,l.spaceBefore=a?.spaceBefore??null,l.spaceAfter=a?.spaceAfter??null,l.spaceBeforeLines=a?.spaceBeforeLines??null,l.spaceAfterLines=a?.spaceAfterLines??null,l.beforeAutospacing=a?.beforeAutospacing??null,l.afterAutospacing=a?.afterAutospacing??null,l.lineSpacing=a?.lineSpacing??null,l.lineSpacingRule=a?.lineSpacingRule??null,l.spacingExplicit=a?.spacingExplicit||null,l.indentLeft=a?.indentLeft??e.listRendering?.indentLeft??null,l.indentRight=a?.indentRight??null,l.indentFirstLine=c??null,l.hangingIndent=f??false,l.borders=a?.borders??null,l.shading=a?.shading??null,l.tabs=a?.tabs??null,l.pageBreakBefore=a?.pageBreakBefore??null,l.keepNext=a?.keepNext??null,l.keepLines=a?.keepLines??null,l.widowControl=a?.widowControl??null,l.snapToGrid=a?.snapToGrid??null,l.autoSpaceDE=a?.autoSpaceDE??null,l.autoSpaceDN=a?.autoSpaceDN??null,l.outlineLevel=a?.outlineLevel??null,l.bidi=a?.bidi??null,l.defaultTextFormatting=a?.runProperties??null;if(e.sectionProperties){l._sectionProperties=e.sectionProperties;let h=e.sectionProperties.sectionStart;(h==="nextPage"||h==="continuous"||h==="oddPage"||h==="evenPage"||h==="nextColumn")&&(l.sectionBreakType=h);}e.renderedPageBreakBefore&&(l.renderedPageBreakBefore=true),wt(e)&&(l.pageBreakBeforeRun=true),e.pPrIns&&(l.pPrIns={revisionId:e.pPrIns.id,author:e.pPrIns.author,date:e.pPrIns.date??null}),e.pPrDel&&(l.pPrDel={revisionId:e.pPrDel.id,author:e.pPrDel.author,date:e.pPrDel.date??null}),e.propertyChanges?.length&&(l.pPrChange=e.propertyChanges);let y=[],b=0,S=0;for(let h of e.content)if(h.type==="bookmarkStart")y.push({id:h.id,name:h.name,kind:"start",offset:S,...h.colFirst!==void 0?{colFirst:h.colFirst}:{},...h.colLast!==void 0?{colLast:h.colLast}:{}});else if(h.type==="bookmarkEnd")y.push({id:h.id,kind:"end",offset:S});else {let p=Tt(h);for(let x=0;x<p;x+=1)S+=n[b]?.pmSize??0,b+=1;}return y.length>0&&(l.bookmarks=y),o?.length&&(l._originalRunBoundaries=o),l}var ze=new WeakMap;function Tt(e){return ze.get(e)??0}function Yt(e,r,n,o){let s=[],a=new Set,d=[],u=kt(e,r,n);for(let[f,l]of e.content.entries()){let y=s.length,b=a.values().next().value;if(l.type==="commentRangeStart")a.add(l.id);else if(l.type==="commentRangeEnd")a.delete(l.id);else if(l.type==="run"){let S=vt(l,u,r);S&&d?d.push(S):d=void 0,s.push(...X(l,u,r,b));}else if(l.type==="hyperlink"){d=void 0;let S=Q(l,u,r);for(let h of S)b!==void 0&&(h.commentId=b);s.push(...S);}else l.type==="simpleField"||l.type==="complexField"?(d=void 0,s.push(...St(l,u,r,f))):l.type==="inlineSdt"?(d=void 0,s.push(v("sdt",We(l,u,r),[],void 0,2))):l.type==="insertion"||l.type==="deletion"||l.type==="moveFrom"||l.type==="moveTo"?(d=void 0,s.push(...xt(l,u,r,b))):l.type==="mathEquation"?(d=void 0,s.push(v("math",de(l)))):l.type!=="bookmarkStart"&&l.type!=="bookmarkEnd"&&l.type!=="rawXml"&&(d=void 0);ze.set(l,s.length-y);}let c=It(e,r,s,d,o);return {units:s,ppr:Te(c)}}function H(e,r){for(let n of e.content)n.type==="break"&&n.breakType==="page"?r.push("pageBreak"):(n.type!=="text"||n.text.length>0)&&r.push("visible");}function pe(e,r){for(let n of e)if(n.type==="run")H(n,r);else if(n.type==="hyperlink")for(let o of n.children)o.type==="run"&&H(o,r);else if(n.type==="simpleField")for(let o of n.content)o.type==="run"&&H(o,r);else if(n.type==="complexField")for(let o of [...n.fieldCode,...n.fieldResult])H(o,r);else if(n.type==="inlineSdt")pe(n.content,r);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let o of n.content)o.type==="run"&&H(o,r);else n.type==="mathEquation"&&r.push("visible");}function wt(e){let r=[];return pe(e.content,r),r[0]==="pageBreak"}function _t(e){let r=[];pe(e.content,r);let n=false,o=false;for(let s of r)if(s==="pageBreak"){if(o||n)return true;n=true;}else o=true;return false}function At(e){let r=new Map,n=new Map;return e.rows.forEach((o,s)=>{let a=0,d=o.cells.map(c=>{let f=a;return a+=c.formatting?.gridSpan??1,{column:f,vMerge:c.formatting?.vMerge,key:`${s}-${f}`}});if(d.length>0&&d.every(c=>c.vMerge==="continue"&&n.has(c.column))){for(let c of d)n.delete(c.column),r.set(c.key,{rowSpan:1,skip:false});return}for(let c of d)if(c.vMerge==="restart")n.set(c.column,s),r.set(c.key,{rowSpan:1,skip:false});else if(c.vMerge==="continue"){let f=n.get(c.column);if(f===void 0)r.set(c.key,{rowSpan:1,skip:false});else {let l=r.get(`${f}-${c.column}`);l&&(l.rowSpan+=1),r.set(c.key,{rowSpan:1,skip:true});}}else n.delete(c.column),r.set(c.key,{rowSpan:1,skip:false});}),r}function le(e){return {revisionId:e.id,author:e.author,date:e.date??null}}function Dt(e,r,n,o,s,a){let d=r?{top:n?r.top:r.insideH,bottom:o?r.bottom:r.insideH,left:s?r.left:r.insideV,right:a?r.right:r.insideV}:void 0;return d||e?.borders?{...d??{},...e?.borders??{}}:void 0}function Je(e,r){let n=e.formatting,o=b$2(n?.shading?.fill,r.theme),s=n?.width?.value??r.gridWidth,a=n?.width?.type??(r.gridWidth!==void 0?"pct":null),d={colspan:n?.gridSpan??1,rowspan:r.rowspan,width:s??null,widthType:a,verticalAlign:n?.verticalAlign??null,backgroundColor:o??null,borders:Dt(n,r.tableBorders,r.firstRow,r.lastRow,r.firstColumn,r.lastColumn)??null,margins:n?.margins?{top:n.margins.top?.value,bottom:n.margins.bottom?.value,left:n.margins.left?.value??(r.tableBidi?n.margins.end?.value:n.margins.start?.value),right:n.margins.right?.value??(r.tableBidi?n.margins.start?.value:n.margins.end?.value)}:r.defaultMargins??null,textDirection:n?.textDirection??null,noWrap:n?.noWrap??false,_originalFormatting:n??null,_originalResolvedFill:o??null};if(e.structuralChange){let u=e.structuralChange,c=le(u.info);u.type==="tableCellInsertion"?d.cellMarker={kind:"ins",info:c}:u.type==="tableCellDeletion"?d.cellMarker={kind:"del",info:c}:u.type==="tableCellMerge"&&(d.cellMarker={kind:"merge",info:c,vMerge:u.vMerge??"cont",...u.vMergeOrig?{vMergeOrig:u.vMergeOrig}:{}});}return e.propertyChanges?.length&&(d.tcPrChange=e.propertyChanges),{attrs:Ae(d,r.isHeader),content:e.content.length>0?e.content:[{type:"paragraph",content:[]}]}}function Ot(e,r,n,o,s,a,d,u,c){let f={height:e.formatting?.height?.value??null,heightRule:e.formatting?.heightRule??null,isHeader:!!e.formatting?.header,_originalFormatting:e.formatting??null};e.structuralChange&&(e.structuralChange.type==="tableRowInsertion"?f.trIns=le(e.structuralChange.info):e.structuralChange.type==="tableRowDeletion"&&(f.trDel=le(e.structuralChange.info))),e.propertyChanges?.length&&(f.trPrChange=e.propertyChanges);let l=r.columnWidths,y=l?.reduce((p,x)=>p+x,0)??0,b=l?.length??Math.max(0,...r.rows.map(p=>p.cells.reduce((x,C)=>x+(C.formatting?.gridSpan??1),0))),S=0,h=[];return e.cells.forEach(p=>{let x=p.formatting?.gridSpan??1,C=S,I=o.get(`${n}-${C}`),w;if(l&&y>0){let Y=0;for(let T=0;T<x&&C+T<l.length;T+=1)Y+=l[C+T];w=Math.round(Y/y*100);}S+=x,!I?.skip&&h.push({paragraphFormatting:ae(r,u,n,C,S,c),...Je(p,{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:I?.rowSpan??1,gridWidth:w,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:C===0,lastColumn:S===b,tableBorders:s,defaultMargins:a,theme:d,tableBidi:!!r.formatting?.bidi})});}),h.length===0&&h.push({paragraphFormatting:ae(r,u,n,0,b,c),...Je({formatting:b>1?{gridSpan:b}:void 0,content:[{type:"paragraph",content:[]}]},{isHeader:n===0&&!!r.formatting?.look?.firstRow,rowspan:1,gridWidth:y>0?100:void 0,firstRow:n===0,lastRow:n===r.rows.length-1,firstColumn:true,lastColumn:true,tableBorders:s,defaultMargins:a,theme:d,tableBidi:!!r.formatting?.bidi})}),{attrs:_e(f),cells:h}}function Ft(e,r,n,o){let s=r?.getDefaultTableStyle(),a=e.formatting?.styleId,d=a??s?.styleId,u=d?r?.getStyle(d):void 0,c=e.formatting?.borders??u?.tblPr?.borders??s?.tblPr?.borders,f=e.formatting?.cellMargins??u?.tblPr?.cellMargins??s?.tblPr?.cellMargins,l=e.formatting?.bidi?f?.end:f?.start,y=e.formatting?.bidi?f?.start:f?.end,b=f?{top:f.top?.value,bottom:f.bottom?.value,left:f.left?.value??l?.value,right:f.right?.value??y?.value}:void 0,S=[],h=new Set,p=u;for(;p?.basedOn&&S.length<32&&!h.has(p.basedOn);)h.add(p.basedOn),S.unshift(p.basedOn),p=r?.getStyle(p.basedOn);let x={...e.formatting??{},styleCascade:{...a?{selectedStyleId:a}:{},...s?.styleId?{defaultStyleId:s.styleId}:{},...S.length>0?{basedOnStyleIds:S}:{}}},C={styleId:a??null,width:e.formatting?.width?.value??null,widthType:e.formatting?.width?.type??null,justification:e.formatting?.justification??null,columnWidths:e.columnWidths??null,tableLayout:e.formatting?.layout??null,floating:e.formatting?.floating??null,cellMargins:b??null,look:e.formatting?.look??null,bidi:e.formatting?.bidi||null,compatibilityMode:o===12?null:o,_originalFormatting:x};e.propertyChanges?.length&&(C.tblPrChange=e.propertyChanges);let I=At(e),w=Ie(e);return {attrs:C,rows:e.rows.map((Y,T)=>Ot(Y,e,T,I,c,b,n,u??s,w))}}function Mt(e){return Oe(d$2(e))}function Et(e){let r=0;for(let n of e.units){let o=n.kind==="text"?n.text.length:1;if(n.commentId!==void 0&&n.commentId!==0){let s=e.commentCoverage.get(n.commentId),a=s?.[s.length-1];a&&a[1]===r?a[1]=r+o:s?s.push([r,r+o]):e.commentCoverage.set(n.commentId,[[r,r+o]]);}r+=o;}}function He(e,r,n){if(c(n))return null;if(n.type==="paragraph"){let o=e.paragraph++;return !n.repeatedParaId&&n.paraId||`${r}:p${o}`}return n.type==="table"?`${r}:t${e.table++}`:De(r,e.sdt++)}function Nt(e){return /^\d+$/.test(e.trim())}function Jt(e){let r=e.structuredResult?.blocks??[],n=r[r.length-1];return !n||n.type!=="paragraph"||(n.content?.length??0)>0?null:r.length}function Bt(e,r,n,o,s,a){for(let d of e){if(d.kind!=="embed"||d.embedKind!=="field")continue;let u=d.payload.instruction;if(typeof u!="string"||!Nt(u))continue;let c=d.payload.fieldData;if(typeof c!="string")continue;let f;try{f=JSON.parse(c);}catch{continue}let l=Jt(f);if(l===null||o+1+l>n.length)continue;let y={...s},b=[];for(let S=0;S<l;S+=1){let h=n[o+1+S],p=He(y,r,h);p!==null&&(h.type==="table"&&a.set(o+1+S,p),b.push(p));}b.length>0&&(d.payload.fieldResultBlocks=b);}}function J(e,r,n,o){let s={storyId:r,units:[],commentCoverage:new Map};e.plans.push(s);let a=n.length>0,d=a?[...n]:[{type:"paragraph",content:[]}],u={paragraph:0,table:0,sdt:0},c$1=new Map,f=null;for(let[l,y]of d.entries()){if(c(y))continue;let b=u.table,S=He(u,r,y);if(S===null)continue;if(y.type==="paragraph"){let p=Yt(y,e.styleResolver,o.extraRunFormatting,o.tableParagraphFormatting);Bt(p.units,r,d,l,u,c$1),s.units.push(...p.units),s.units.push(v("pilcrow",{...p.ppr,...a&&y.paraId?{sourceParaId:y.paraId}:{},...a?{}:{paraOrigin:"synthetic"},paraId:S})),o.includePageBreaks&&_t(y)&&s.units.push(v("pageBreak",{})),f="paragraph";continue}if(y.type==="table"){let p=Ft(y,e.styleResolver,e.theme,e.compatibilityMode),x=p.rows.map((I,w)=>({trPr:I.attrs,cells:I.cells.map((Y,T)=>({tcPr:Y.attrs,story:se(r,b,w,T)}))})),C=c$1.get(l);s.units.push(v("table",{tblPr:Ye(p.attrs),grid:we(p.attrs),rows:x,...C===void 0?{}:{blockId:C}})),p.rows.forEach((I,w)=>{I.cells.forEach((Y,T)=>{J(e,se(r,b,w,T),Y.content,{includePageBreaks:false,appendBodyTail:false,seedComments:false,extraRunFormatting:Y.extraRunFormatting,tableParagraphFormatting:Y.paragraphFormatting});});}),f="table";continue}let h=S;s.units.push(v("blockSdt",{...Mt(y.properties),story:h})),J(e,h,y.content,{includePageBreaks:o.includePageBreaks,appendBodyTail:false,seedComments:false,tableParagraphFormatting:o.tableParagraphFormatting}),f="blockSdt";}o.appendBodyTail&&(f==="table"||f==="blockSdt")&&s.units.push(v("pilcrow",{hangingIndent:false,paraId:`${r}:p${u.paragraph}`,paraOrigin:"synthetic"})),o.seedComments&&Et(s);}function Lt(e){let r=[{op:"delete",index:0,len:1}],n=0,o="",s={},a=W(s),d=()=>{o&&(r.push({op:"insert",index:n,text:o,attrs:s}),n+=o.length,o="");};for(let u of e)if(u.kind==="text"){let c=W(u.attrs);o&&c!==a&&d(),s=u.attrs,a=c,o+=u.text;}else d(),r.push({op:"insertEmbed",index:n,kind:u.embedKind,payload:u.payload,attrs:u.attrs}),n+=1;return d(),r}function Ut(e,r){let n=Lt(r.units);for(let[o,s]of r.commentCoverage)n.push({op:"setComment",id:String(o),ranges:s,author:"",date:"",body:null});e.applySeedRawOps(r.storyId,n);}function Wt(e,r,n={}){f(e,"all");let o={styleResolver:r.package.styles?d(r.package.styles):null,theme:r.package.theme??null,plans:[],compatibilityMode:ut(r)};J(o,"body",r.package.document.content,{includePageBreaks:true,appendBodyTail:true,seedComments:true});for(let[s,a]of r.package.headers??[])J(o,G(s),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let[s,a]of r.package.footers??[])o.plans.some(d=>d.storyId===G(s))||J(o,G(s),a.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of r.package.footnotes??[])J(o,Fe(s.id),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of r.package.endnotes??[])J(o,Me(s.id),s.content,{includePageBreaks:false,appendBodyTail:false,seedComments:true});for(let s of o.plans)e.createStory(s.storyId,"","Normal","left");for(let s of o.plans)Ut(e,s);e.beginOpening(n.generation);}function jt(e){let r=e.package;return [r.document.content,...[...r.headers?.values()??[]].map(n=>n.content),...[...r.footers?.values()??[]].map(n=>n.content),...(r.footnotes??[]).map(n=>n.content),...(r.endnotes??[]).map(n=>n.content)]}var zt="word/comments.xml";function $e(e){if(Array.isArray(e)&&e.length>0&&e.every(n=>n?.type==="paragraph"))return e;let r=typeof e=="string"?e:"";return [{type:"paragraph",formatting:{},content:r?[{type:"run",formatting:{},content:[{type:"text",text:r}]}]:[]}]}function Ht(e,r){let n=r.package.document.comments??[],o=new Map(e.listComments().map(f=>[f.id,f])),s=false,a=n.map(f=>{let l=o.get(String(f.id));return o.delete(String(f.id)),!l||!l.author&&!l.date&&l.body==null?f:(s=true,{...f,...l.author?{author:l.author}:{},...l.date?{date:l.date}:{},...l.body==null?{}:{content:$e(l.body)}})}),d=new Set(n.map(f=>f.id)),u=new Map,c=Math.max(0,...d)+1;for(let f of o.values()){s=true;let l=/^\d+$/.test(f.id)?Number(f.id):Number.NaN;if(!Number.isSafeInteger(l)||d.has(l)){for(;d.has(c);)c+=1;l=c;}d.add(l),String(l)!==f.id&&u.set(l,f.id),a.push({id:l,author:f.author,...f.date?{date:f.date}:{},content:$e(f.body)});}return {comments:a,sessionIds:u,changed:s}}function $t(e$1,r){let n=new Map(r.paragraphs.flatMap(a=>a.session?[[a.session.paraId,a]]:[])),o=[],s=a=>{for(let d of a)if(d.type==="table")for(let u of d.rows)for(let c of u.cells)s(c.content);else if(d.type==="blockSdt")s(d.content);else if(d.type==="paragraph"&&d.paraId){let u=e(d),c=u===void 0?void 0:n.get(u);if(!c?.session||!c.persisted)continue;o.push({session:c.session,persisted:{...c.persisted,paraId:d.paraId}});}};for(let a of jt(e$1))s(a);return o}function qe(e){return {identities:e.paragraphIdentities(),plan:e.paragraphSavePlan()}}async function Ve(e,r,n,o,s={},a=()=>true){let d={...n.plan,patchedParts:n.plan.patchedParts.filter(({part:p})=>a(p))},u=$t(r,n.identities),{buffer:c}=await d$1(r,o,s,void 0,void 0,d),f=new Uint8Array(c),l=e.writtenParagraphIds(f),y=(p,x)=>l[p]?.includes(x.toUpperCase())??false,b=u.filter(({persisted:p})=>y(p.story.partUri,p.paraId)),S=new Set(e.recordSavedParagraphIds([...b.map(({session:p,persisted:x})=>[p.paraId,x.paraId]),...d.assignments.filter(({part:p,paraId:x})=>y(`/${p}`,x)).map(({part:p,ordinal:x,paraId:C})=>[`/${p}#${x}`,C])]).map(([p,x])=>`${p}\0${x}`)),h=({session:p,persisted:x})=>S.has(`${p.paraId}\0${x.paraId}`);return {bytes:f,paragraphs:b.filter(p=>!h(p)),conflicts:b.filter(h)}}async function qt(e,r={}){let n=e.materializeDocx();if(!n?.originalBuffer)throw new Error("saveYrsDocx requires a session opened from DOCX bytes");let o=qe(e),s=Ht(e,n),a=g(e,s.changed?{...n,package:{...n.package,document:{...n.package.document,comments:s.comments}}}:n,{commentIds:s.sessionIds});return Ve(e,a,o,n.originalBuffer,r,d=>!s.changed||d!==zt)}function wr(e,r){return !e||!r?e===r:e.anchor.story===r.anchor.story&&e.anchor.paraId===r.anchor.paraId&&e.anchor.offset===r.anchor.offset&&e.head.story===r.head.story&&e.head.paraId===r.head.paraId&&e.head.offset===r.head.offset}function Vt(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}function Ke(e){return JSON.stringify("revisionId"in e?{revisionId:e.revisionId}:{story:e.story,startPara:e.start.paraId,startOffset:e.start.offset,endPara:e.end.paraId,endOffset:e.end.offset})}function Ge(e){return JSON.stringify(e.map(r=>({story:r.story,startPara:r.start.paraId,startOffset:r.start.offset,endPara:r.end.paraId,endOffset:r.end.offset})))}function Xe(e){return e.kind==="search"?e.within.story:e.story}function Qe(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function Kt(e,r){let n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new TypeError("DOCX host metadata must be an object");let o=n;if(!Array.isArray(o.referencedFonts)||!o.referencedFonts.every(a=>typeof a=="string"))throw new TypeError("DOCX host referencedFonts must be a string array");let s=c$1(o.envelope,Qe(r));return {document:s.document,referencedFonts:o.referencedFonts,embeddedFonts:s.embeddedFonts,...s.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:s.fontTableRelationshipsXml}}}function Gt(e,r){let n=new Map,o=[],s=false,a$1=false,d=0,u=0,c=false,f$1=false,l,y=null,b=[],S=new Map,h=new Map,p=null,x=false,C=0,I=0,w=false,Y=null,T=()=>{l=void 0,y=null;},E=()=>{if(!(a$1||c||u!==0)){c=true;try{for(;!a$1&&o.length>0;){let t=o.shift();if(!t)break;for(let[i,g]of [...n]){if(a$1)return;if(n.get(i)===g)try{g(t.update.slice(),t.origin);}catch{}}}}finally{c=false,a$1&&(o.length=0);}}},m=t=>{T(),u+=1;try{return t()}finally{u-=1,u===0&&E();}},ce=t=>t?{anchor:{...t.anchor},head:{...t.head}}:null,R=t=>{f$1||(e.track_undo(),f$1=true),t!==void 0&&(e.select_story(t),P(t));},P=t=>{f(Z,t);},_=t=>(P(t.createdStoryIds),P(t.deletedStoryIds),P(t.changedStoryIds),t),q=()=>(l!==void 0?l:JSON.parse(e.selection()))?.head.story??"all",Ze=()=>{s||(e.set_update_observer((t,i)=>{i!==0&&i!==1||(o.push({update:t.slice(),origin:i===0?"local":"remote"}),E());}),s=true);},et=()=>{!s||n.size>0||a$1||(o.length=0,e.clear_update_observer(),s=false);},fe=(t,i,g={})=>{let k=t.slice();P("all");let F=m(()=>e.open_docx(k,i,g.generation)),ee=Kt(F,k);return Y=k,ee},Z={clientId:r,registerFont:t=>{w||(e.clear_measure_fonts(),w=true);let i=e.register_measure_font(t);return b.push(t.slice()),I+=1,i},registerSubstituteFont:(t,i)=>{let g=e.register_substitute_measure_font(t,i);return g===t||(b.push({substituteOf:t,family:i}),I+=1),g},clearFonts:()=>{e.clear_measure_fonts(),b.length=0,h.clear(),I+=1,w=true;},measureParagraphJson:t=>{let i=e.measure_paragraph_json(t);return h.set(t,t),i},layoutDocumentJson:t=>{let i=e.layout_document_json(t);return p=t,x=false,C+=1,i},layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsJson:t=>{let i=e.layout_document_with_regions_json(t);return p=t,x=true,C+=1,i},layoutDocumentWithRegionsRetainedJson:t=>{let i=e.layout_document_with_regions_retained_json(t);return p=t,x=true,C+=1,i},retainedKernelInputsJson:t=>{if(t!==C)throw new Error(`retained layout revision mismatch: expected ${t}, current ${C}`);return e.retained_kernel_inputs_json()},buildDisplayListJson:t=>e.build_display_list_json(t),buildDisplayListFrame:(t,i)=>e.build_display_list_frame(t,i),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),applyInput:(t,i)=>(R(),P(q()),m(()=>e.apply_input(t,i))),applyDelete:(t,i)=>(R(),P(q()),m(()=>e.apply_delete(t,i))),applyInputProfiled:(t,i)=>{R(),P(q());let g=m(()=>e.apply_input_profiled(t,i)),k=JSON.parse(e.apply_input_profile_json());return {frame:g,profile:k}},applyDeleteProfiled:(t,i)=>{R(),P(q());let g=m(()=>e.apply_delete_profiled(t,i)),k=JSON.parse(e.apply_input_profile_json());return {frame:g,profile:k}},residentWorkerSnapshot:t=>{if(!p||!x&&S.size===0)return null;let i=e.selection(),g=t?.knownFontsRevision===I,k=null;if(t?.knownStateVector)try{k=e.encode_diff(t.knownStateVector.slice());}catch{k=null;}return {clientId:r,state:k??e.encode_state(),selection:JSON.parse(i),fonts:g?[]:b.map(F=>F instanceof Uint8Array?F.slice():{...F}),fontsRevision:I,renderInputs:[...S].map(([F,ee])=>({story:F,env:structuredClone(ee)})),measureInputs:[...h.values()],layoutInput:p,layoutWithRegions:x,layoutRevision:C}},residentWorkerProbe:()=>!p||!x&&S.size===0?null:{layoutRevision:C},displayHitTestRegionsJson:(t,i,g)=>e.display_hit_test_regions_json(t,i,g),displayVerticalMoveJson:(t,i,g)=>e.display_vertical_move_json(t,i,g),displayRangeRectsJson:(t,i)=>e.display_range_rects_json(t,i),displayRangeRectsRegionJson:(t,i,g,k)=>e.display_range_rects_region_json(t,i,g,k),outlineGlyphJson:(t,i)=>e.outline_glyph_json(t,i),loadState:t=>{P("all"),m(()=>e.load(t));},seedFromDocx:(t,i)=>fe(t,true,i),openDocx:fe,beginOpening:t=>m(()=>e.begin_opening(t)),materializeDocx:()=>{let t=Y,i=e.materialize_docx();return !t||i===void 0?null:b$1(i,Qe(t)).document},loadStories:t=>(P(t.map(i=>i.storyId)),m(()=>JSON.parse(e.load_json(JSON.stringify(t))))),encodeState:()=>e.encode_state(),encodeStateVector:()=>e.encode_state_vector(),encodeStateAsUpdate:t=>t===void 0?e.encode_state():e.encode_diff(t.slice()),applyUpdate:t=>(P("all"),m(()=>JSON.parse(e.apply_update_with_inference(t)))),applyLocalUpdate:t=>{R(),P("all"),m(()=>e.apply_local_update(t));},onUpdate:t=>{if(a$1)throw new Error("yrs session is destroyed");if(typeof t!="function")throw new TypeError("update listener must be a function");let i=d++;n.set(i,t),Ze();let g=true;return ()=>{g&&(g=false,n.delete(i),et());}},encodeStickyPosition:t=>({story:t.story,encoded:e.encode_sticky_position(t.story,t.paraId,t.offset)}),resolveStickyPosition:t=>{try{return JSON.parse(e.resolve_sticky_position(t.story,t.encoded))}catch{return null}},setSelection:(t,i=t)=>{if(t.story!==i.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,i.paraId,i.offset),l={anchor:{...t},head:{...i}};},selection:()=>(l!==void 0||(l=JSON.parse(e.selection())),ce(l)),encodeSelection:()=>{let t=JSON.parse(e.encoded_selection());return t?{story:t.story,anchor:Uint8Array.from(t.anchor),head:Uint8Array.from(t.head)}:null},resolveSelection:t=>{try{return JSON.parse(e.resolve_encoded_selection(t.story,t.anchor,t.head))}catch{return null}},setCellSelection:t=>e.set_cell_selection(JSON.stringify(t)),cellSelection:()=>JSON.parse(e.cell_selection()),beginUndoCapture:R,addUndoBoundary:()=>e.add_undo_boundary(),setUndoCaptureMode:t=>e.set_undo_capture_mode(t),undoCaptureMode:()=>e.undo_capture_mode(),historyStories:()=>e.history_stories(),undo:()=>m(()=>{let t=e.undo();return t&&P(e.history_stories()),t}),redo:()=>m(()=>{let t=e.redo();return t&&P(e.history_stories()),t}),canUndo:()=>e.can_undo(),canRedo:()=>e.can_redo(),createStory:(t,i,g="Normal",k="left")=>(P(t),m(()=>JSON.parse(e.create_story(t,i,g,k)))),deleteStory:t=>(P(t),m(()=>e.delete_story(t))),insertTable:(t,i,g,k)=>(R(t.story),m(()=>_(JSON.parse(e.insert_table(t.story,t.paraId,t.offset,i,g,k?.name,k?.date))))),insertRow:(t,i,g)=>(R(t.story),m(()=>_(JSON.parse(e.insert_row(JSON.stringify(t),i==="below",g?.name,g?.date))))),insertColumn:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.insert_column(JSON.stringify(t),i==="right"))))),deleteRow:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.delete_row(JSON.stringify(t),i?.name,i?.date))))),deleteColumn:t=>(R(t.anchor.story),m(()=>_(JSON.parse(e.delete_column(JSON.stringify(t)))))),deleteTable:t=>(R(t.story),m(()=>_(JSON.parse(e.delete_table(JSON.stringify(t)))))),mergeCells:t=>(R(t.anchor.story),m(()=>_(JSON.parse(e.merge_cells(JSON.stringify(t)))))),splitCell:(t,i,g)=>(R(t.story),m(()=>_(JSON.parse(e.split_cell(JSON.stringify(t),i,g))))),setCellShading:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_shading(JSON.stringify(t),i??void 0))))),setCellTextFormat:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_text_format(JSON.stringify(t),JSON.stringify(i)))))),setCellBorders:(t,i)=>(R(t.anchor.story),m(()=>_(JSON.parse(e.set_cell_borders(JSON.stringify(t),JSON.stringify(i)))))),setColumnWidth:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.set_column_width(JSON.stringify(t),i))))),setTableWidth:(t,i)=>(R(t.story),m(()=>_(JSON.parse(e.set_table_width(JSON.stringify(t),i))))),insertText:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.insert_text(t.story,t.paraId,t.offset,i,g?.name,g?.date)))),deleteRange:(t,i)=>(R(t.story),m(()=>JSON.parse(e.delete_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i?.name,i?.date)))),replaceRange:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.replace_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,g?.name,g?.date)))),splitParagraph:(t,i)=>(R(t.story),m(()=>JSON.parse(e.split_paragraph(t.story,t.paraId,t.offset,i?.name,i?.date)))),mergeParagraphs:(t,i,g)=>(R(t),m(()=>JSON.parse(e.merge_paragraphs(t,i,g?.name,g?.date)))),toggleMark:(t,i)=>{R(t.story),m(()=>e.toggle_mark(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},formatRange:(t,i)=>{R(t.story),m(()=>e.format_range(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},setHyperlink:(t,i)=>{R(t.story),m(()=>e.set_hyperlink(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i)));},clearFormatting:t=>{R(t.story),m(()=>e.clear_formatting(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset));},applyParagraphStyle:(t,i,g)=>{R(t.story),m(()=>e.apply_paragraph_style(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,i,g?.name,g?.date));},setParagraphAttrs:(t,i,g)=>{R(t.story),m(()=>e.set_paragraph_attrs(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset,JSON.stringify(i),g?.name,g?.date));},insertImage:(t,i,g)=>(R(t.story),m(()=>JSON.parse(e.insert_image(t.story,t.paraId,t.offset,JSON.stringify(i),g?.name,g?.date)))),setContentControlValue:(t,i)=>{R(),P("all"),m(()=>e.set_content_control_value(t,JSON.stringify(i)));},setContentControlValueAt:(t,i)=>{R(t.story),typeof i=="string"&&P("all"),m(()=>e.set_content_control_value_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},clearContentControlValue:t=>{R(),P("all"),m(()=>e.clear_content_control_value(t));},setImageGeometry:(t,i)=>{R(),P("all"),m(()=>e.set_image_geometry(t,JSON.stringify(i)));},setImageGeometryAt:(t,i)=>{R(t.story),m(()=>e.set_image_geometry_at(t.story,t.paraId,t.offset,JSON.stringify(i)));},insertPageBreak:t=>{R(t.story),m(()=>e.insert_page_break(t.story,t.paraId,t.offset));},insertSectionBreak:(t,i)=>{R(t.story),m(()=>e.insert_section_break(t.story,t.paraId,t.offset,i));},insertWatermark:(t,i)=>{R(t.story),m(()=>e.insert_watermark(t.story,t.paraId,t.offset,JSON.stringify(i)));},applyRawOps:(t,i)=>{let g=i.some(k=>k.op==="insertEmbed"&&k.kind==="pilcrow"||k.op==="setEmbedAttr"&&k.key==="paraId");P(g?"all":t),m(()=>e.apply_raw_ops(t,JSON.stringify(i)));},applySeedRawOps:(t,i)=>{P(t),m(()=>e.apply_seed_raw_ops(t,JSON.stringify(i)));},setParagraphAttr:(t,i,g)=>{P("all"),m(()=>e.set_paragraph_attr(t,i,JSON.stringify(g??null)));},addComment:(t,i,g,k)=>(P(t.map(F=>F.story)),m(()=>JSON.parse(e.add_comment(Ge(t),i,g,JSON.stringify(k??null))))),setCommentRanges:(t,i)=>{R(),m(()=>{e.set_comment_ranges(t,Ge(i)),P("all");});},acceptChange:t=>(P("all"),m(()=>JSON.parse(e.accept_change(Ke(t))))),rejectChange:t=>(P("all"),m(()=>JSON.parse(e.reject_change(Ke(t))))),selectionContext:t=>{let i=JSON.stringify(t);if(y?.key===i)return JSON.parse(y.json);let g=e.selection_context(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset),k=JSON.parse(g);return y={key:i,json:g},k},listRevisions:()=>JSON.parse(e.list_revisions()),resolveComment:t=>JSON.parse(e.resolve_comment(t)),listComments:()=>JSON.parse(e.list_comments()),storyIds:()=>e.story_ids(),storyLength:t=>e.story_len(t),storyChecksum:t=>BigInt(e.story_checksum(t)),yrsBlocksForStory:(t,i={})=>{let g=e.yrs_blocks_for_story(t,JSON.stringify(i)),k=JSON.parse(g);return S.set(t,structuredClone(i)),k},paragraphs:t=>JSON.parse(e.paragraphs(t)),searchText:(t,i={})=>{if(!t)return [];let g=i.limit??Number.POSITIVE_INFINITY;if(!Number.isSafeInteger(g)&&g!==Number.POSITIVE_INFINITY||g<0)throw new RangeError("search limit must be a non-negative safe integer");return JSON.parse(e.search_text(t,i.caseSensitive??false,Number.isFinite(g)?Math.min(g,4294967295):void 0))},paragraphSpans:t=>JSON.parse(e.paragraph_spans(t)),storySegments:t=>JSON.parse(e.story_segments(t)),locateParagraph:(t,i)=>JSON.parse(e.locate_paragraph(t,i)),paragraphIdentities:()=>JSON.parse(e.paragraph_identities()),persistParagraphIds:()=>(P("all"),m(()=>JSON.parse(e.persist_paragraph_ids()))),resolveParagraphAnchor:t=>JSON.parse(e.resolve_paragraph_anchor(JSON.stringify(t))),storyParagraphIds:t=>JSON.parse(e.story_paragraph_ids(t)),paragraphSavePlan:()=>JSON.parse(e.paragraph_save_plan()),recordSavedParagraphIds:t=>m(()=>JSON.parse(e.record_saved_paragraph_ids(JSON.stringify(t)))),writtenParagraphIds:t=>JSON.parse(e.written_paragraph_ids(t)),exportStructured:t=>JSON.parse(e.export_structured_json(JSON.stringify(t))),exportMarkdown:t=>JSON.parse(e.export_markdown_json(JSON.stringify(t))),exportStructuredWithPages:t=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),void 0)),exportStructuredWithPagesFor:(t,i)=>JSON.parse(e.export_structured_with_pages_json(JSON.stringify(t),i)),exportSnapshotWithPrivateFonts:(t,i,g,k)=>JSON.parse(e.export_snapshot_with_private_fonts_json(t,i,g,JSON.stringify(k))),headings:t=>JSON.parse(e.headings_json(t)),listContentControls:(t={})=>JSON.parse(e.list_content_controls_json(JSON.stringify(t))),findContentControls:(t,i={})=>JSON.parse(e.find_content_controls_json(JSON.stringify(t),JSON.stringify(i))),version:()=>e.version(),readParagraphs:t=>JSON.parse(e.read_paragraphs_json(JSON.stringify(t))),findText:t=>JSON.parse(e.find_text_json(JSON.stringify(t))),validateEdits:t=>JSON.parse(e.validate_edits_json(JSON.stringify(t))),applyEdits:t=>m(()=>{let i=JSON.parse(e.apply_edits_json(JSON.stringify(t)));return i.ok&&i.applied&&P(i.changedStories),i}),formatTextTarget:(t,i)=>(R(Xe(t)),m(()=>JSON.parse(e.format_text_target_json(JSON.stringify(t),JSON.stringify(i))))),commentTextTarget:(t,i)=>(P(Xe(t)),m(()=>JSON.parse(e.comment_text_target_json(JSON.stringify(t),JSON.stringify({...i,body:i.body??null}))))),selectionText:t=>JSON.parse(e.selection_text_json(t.story,t.start.paraId,t.start.offset,t.end.paraId,t.end.offset)),destroy:()=>{a$1||(a$1=true,n.clear(),o.length=0,s&&e.clear_update_observer(),e.free());}};return a(Z,{compareDocx:(t,i,g)=>{P("all");let k=m(()=>e.compare_docx_json(t,i,g));return Y=t.slice(),k},finishComparedDocx:t=>e.finish_compared_docx_json(t),failComparedDocx:t=>e.fail_compared_docx_json(t)}),Z}async function _r(e){let r=e?.clientId??Vt(),n=await import('../wasm-US6R7SWN.mjs');return await n.preloadEditWasm(),Gt(n.createEditSession(r),r)}export{oe as ResidentEngineWorkerClient,O as ResidentWorkerFailureError,st as canUseResidentEngineWorker,qe as captureSessionSave,Zt as compareYrsLocs,Xt as createYrsInputPositionMap,_r as createYrsSession,Qt as displayPositionToYrsLoc,Wt as documentToYrs,wr as sameYrsSelection,qt as saveYrsDocx,Ve as writeSessionSave,Ce as yrsLocToDisplayPosition};
@@ -1 +1 @@
1
- import'../chunk-EUUIJVM6.mjs';import {b,a as a$2}from'../chunk-J7LNO6SM.mjs';import {a as a$3,b as b$1}from'../chunk-GD4VNJ64.mjs';import {u as u$1,s,a as a$1,g,j as j$1,i}from'../chunk-PGMXWI5X.mjs';import'../chunk-5F6DLQZP.mjs';import'../chunk-TTRUPDAB.mjs';async function q(){await a$3();let e=b$1(le()),o=new Set,r=false,i=false,l=false,c=()=>{l||(e.track_undo(),l=true);},R=()=>{r||(e.set_update_observer((t,n)=>{if(!(n!==0&&n!==1))for(let d of [...o])d(t,n===0?"local":"remote");}),r=true);};return {registerFont:t=>e.register_measure_font(t),clearFonts:()=>e.clear_measure_fonts(),encodeStateVector:()=>e.encode_state_vector(),measureParagraphJson:t=>e.measure_paragraph_json(t),layoutDocumentJson:t=>e.layout_document_json(t),layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsRetainedJson:t=>e.layout_document_with_regions_retained_json(t),buildDisplayListFrame:(t,n)=>e.build_display_list_frame(t,n),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),selection:()=>JSON.parse(e.selection()),applyInput:(t,n)=>(c(),e.apply_input(t,n)),applyDelete:(t,n)=>(c(),e.apply_delete(t,n)),applyInputProfiled:(t,n)=>{c();let d=e.apply_input_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:d,profile:s}},applyDeleteProfiled:(t,n)=>{c();let d=e.apply_delete_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:d,profile:s}},outlineGlyphJson:(t,n)=>e.outline_glyph_json(t,n),loadState:t=>e.load(t),applyUpdate:t=>JSON.parse(e.apply_update_with_inference(t)),onUpdate:t=>(o.add(t),R(),()=>o.delete(t)),setSelection:(t,n=t)=>{if(t.story!==n.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,n.paraId,n.offset);},yrsBlocksForStory:(t,n={})=>JSON.parse(e.yrs_blocks_for_story(t,JSON.stringify(n))),destroy:()=>{i||(i=true,o.clear(),r&&e.clear_update_observer(),e.free());}}}function le(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}var ae=self,a=null,E=null,u=[],z=0,L=-1,ee=Promise.resolve(),f=null,D=null,h=new Map,k=new Map,S=new Set,w=new Set,B=1,U=1,O={color:"#000",width:2},v=null,y=null,P=null,J=null,C=new Set,Y=null;ae.onmessage=e=>{ee=ee.then(()=>{if(Y)throw Y;return pe(e.data)}).catch(o=>{if(o instanceof WebAssembly.RuntimeError){Y=o,_({id:e.data.id,ok:false,error:`Resident engine worker trapped: ${o.message}`,terminal:true});return}_({id:e.data.id,ok:false,error:o instanceof Error?o.message:String(o)});});};async function pe(e){if(e.type==="destroy"){re();return}if(e.type==="bootstrap"){re(),a=await q(),te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r);return}if(e.type==="eraseCaret"){v=null,y!==null&&await M(false),_({id:e.id,ok:true});return}if(!a)throw new Error("Resident engine worker is not initialized");if(e.type==="sync"){E?.(),E=null,te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="buildFrame"){u=[];let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="applyUpdate"){a.applyUpdate(e.update),e.selection&&a.setSelection(e.selection.anchor,e.selection.head);return}if(e.type==="attachCanvases"){let r=h.size>0&&(B!==e.devicePixelRatio||U!==e.zoom),i=new Set(e.pages.map(l=>l.pageId));for(let l of e.activePageIds)w.has(l)||i.add(l);for(let{pageId:l,canvas:c}of e.pages)h.set(l,c);w=new Set(e.activePageIds),B=e.devicePixelRatio,U=e.zoom,O=e.caretStyle;for(let[l,c]of h)w.has(l)||(c.width=0,c.height=0,k.delete(l),oe(l));await M(r?true:i),_({id:e.id,ok:true});return}a.setSelection(e.selection.anchor,e.selection.head),u=[];let o=performance.now();try{let r=e.type==="applyDelete"?e.profile?a.applyDeleteProfiled(e.direction,e.expectedFrameEpoch):{frame:a.applyDelete(e.direction,e.expectedFrameEpoch),profile:void 0}:e.profile?a.applyInputProfiled(e.text,e.expectedFrameEpoch):{frame:a.applyInput(e.text,e.expectedFrameEpoch),profile:void 0};await x(e.id,r.frame,performance.now()-o,u,r.profile,o,!0,e.paintCaret);}catch(r){if(r instanceof WebAssembly.RuntimeError)throw r;let i=r instanceof Error?r.message:String(r);_({id:e.id,ok:false,error:i,residentUnavailable:i.includes("resident input state is not ready")});}finally{u=[];}}function te(e){if(!a)throw new Error("Resident engine worker is not initialized");if(a.loadState(e.state),e.fontsRevision!==L){a.clearFonts();for(let o of e.fonts)a.registerFont(o);L=e.fontsRevision;}for(let{story:o,env:r}of e.renderInputs)a.yrsBlocksForStory(o,r);for(let o of e.measureInputs)a.measureParagraphJson(o);e.layoutWithRegions?a.layoutDocumentWithRegionsRetainedJson(e.layoutInput):a.layoutDocumentJson(e.layoutInput),e.selection&&a.setSelection(e.selection.anchor,e.selection.head),z=e.layoutRevision,u=[];}function ne(){a&&(E=a.onUpdate(e=>u.push(e.slice())));}function re(){E?.(),E=null,a?.destroy(),a=null,u=[],z=0,L=-1,f=null,D=null,h.clear(),k.clear(),S.clear(),w.clear(),v=null,y=null,P=null,J=null,C.clear();}function oe(e){C.delete(e),y===e&&(y=null,P=null);}async function x(e,o,r,i=u,l,c=performance.now(),R=false,t=false){f=u$1(f,s(o));for(let p of f.damagedPageIds)S.add(p.toString());f={...f,pages:f.pages.map(p=>({...p,primitiveIds:p.primitiveIds.slice()}))};let n=a?.residentCaretSnapshot();if(!n||!b(n,f))throw new Error("Resident caret snapshot does not match the produced frame");if(R&&!n.caretRect)throw new Error("Resident input frame omitted collapsed caret geometry");let d=a?.selection()??null;v=t?n.caretRect??null:null;let s$1=new Set(f.pages.map(p=>p.pageId.toString()));for(let p of S)s$1.has(p)||S.delete(p);for(let p of h.keys())s$1.has(p)||(h.delete(p),k.delete(p),oe(p));let F=performance.now(),{replayedPages:W,caretPainted:A}=await M(false),b$1=performance.now()-F,I=j(o),g=i.map(j),m=a?j(a.encodeStateVector()):void 0;_({id:e,ok:true,frame:I,updates:g,engineMs:r,workerTotalMs:performance.now()-c,engineProfile:l,caret:n,selection:d,caretPainted:A,replayMs:b$1,replayedPages:W,layoutRevision:z,...m?{stateVector:m}:{}},[I,...g,...m?[m]:[]]);}async function M(e){let o=e===true?w:e;if(o)for(let n of o)S.add(n);if(!f||h.size===0)return {replayedPages:0,caretPainted:false};!D&&a&&(D=new a$1({provider:(n,d)=>a.outlineGlyphJson(n,d)}));let r=v&&w.has(v.pageId)?v:null,i$1=r?a$2(r,O,B,U):null,l=r&&i$1?`${r.pageId}|${i$1.x}|${i$1.y}|${i$1.width}|${i$1.height}|${O.color}`:null,c=[];for(let n=0;n<f.pages.length;n+=1){let s=f.pages[n].pageId.toString();if(!w.has(s))continue;let F=S.has(s),W=s===r?.pageId&&!(y===s&&P===l),A=s===y&&s!==r?.pageId;if(!F&&!W&&!A)continue;let b=h.get(s),I=f.displayList.pages[n];if(!b||!I)continue;let g$1=s,m=k.get(g$1);m||(m=new OffscreenCanvas(1,1),k.set(g$1,m));let p=m;if(!F&&C.has(g$1)){c.push(Promise.resolve({canvas:b,buffer:p,pageId:g$1}));continue}c.push(g(p,I,{glyphCache:D??void 0},B,U).then(()=>({canvas:b,buffer:p,pageId:g$1})));}let R=await Promise.all(c).catch(async n=>{throw await Promise.allSettled(c),n}),t=r!==null&&y===r.pageId&&P===l;for(let{canvas:n,buffer:d,pageId:s}of R)r&&i$1&&s===r.pageId?(J||(J=new OffscreenCanvas(1,1)),j$1(n,d,J,{...i$1,color:O.color}),C.add(s),y=s,P=l,t=true):(i(n,d),C.delete(s),y===s&&(y=null,P=null)),S.delete(s);return {replayedPages:R.length,caretPainted:t}}function j(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function _(e,o=[]){ae.postMessage(e,o);}
1
+ import'../chunk-EUUIJVM6.mjs';import {b as b$1,a as a$2}from'../chunk-J7LNO6SM.mjs';import {a as a$3,b as b$2}from'../chunk-Z4HZIPBS.mjs';import {u as u$1,s,a as a$1,g,j as j$1,i}from'../chunk-PGMXWI5X.mjs';import'../chunk-5F6DLQZP.mjs';import'../chunk-TTRUPDAB.mjs';async function q(){await a$3();let e=b$2(le()),o=new Set,r=false,i=false,l=false,c=()=>{l||(e.track_undo(),l=true);},R=()=>{r||(e.set_update_observer((t,n)=>{if(!(n!==0&&n!==1))for(let p of [...o])p(t,n===0?"local":"remote");}),r=true);};return {registerFont:t=>e.register_measure_font(t),registerSubstituteFont:(t,n)=>e.register_substitute_measure_font(t,n),clearFonts:()=>e.clear_measure_fonts(),encodeStateVector:()=>e.encode_state_vector(),measureParagraphJson:t=>e.measure_paragraph_json(t),layoutDocumentJson:t=>e.layout_document_json(t),layoutFontRequirementsJson:t=>e.layout_font_requirements_json(t),layoutDocumentWithRegionsRetainedJson:t=>e.layout_document_with_regions_retained_json(t),buildDisplayListFrame:(t,n)=>e.build_display_list_frame(t,n),residentCaretSnapshot:()=>JSON.parse(e.resident_caret_snapshot_json()),selection:()=>JSON.parse(e.selection()),applyInput:(t,n)=>(c(),e.apply_input(t,n)),applyDelete:(t,n)=>(c(),e.apply_delete(t,n)),applyInputProfiled:(t,n)=>{c();let p=e.apply_input_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:p,profile:s}},applyDeleteProfiled:(t,n)=>{c();let p=e.apply_delete_profiled(t,n),s=JSON.parse(e.apply_input_profile_json());return {frame:p,profile:s}},outlineGlyphJson:(t,n)=>e.outline_glyph_json(t,n),loadState:t=>e.load(t),applyUpdate:t=>JSON.parse(e.apply_update_with_inference(t)),onUpdate:t=>(o.add(t),R(),()=>o.delete(t)),setSelection:(t,n=t)=>{if(t.story!==n.story)throw new Error("yrs selection must stay inside one story");e.set_selection(t.story,t.paraId,t.offset,n.paraId,n.offset);},yrsBlocksForStory:(t,n={})=>JSON.parse(e.yrs_blocks_for_story(t,JSON.stringify(n))),destroy:()=>{i||(i=true,o.clear(),r&&e.clear_update_observer(),e.free());}}}function le(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return Math.floor(Math.random()*4294967295)}var ae=self,a=null,E=null,u=[],z=0,L=-1,ee=Promise.resolve(),d=null,O=null,h=new Map,F=new Map,S=new Set,w=new Set,U=1,B=1,D={color:"#000",width:2},_=null,y=null,P=null,J=null,C=new Set,Y=null;ae.onmessage=e=>{ee=ee.then(()=>{if(Y)throw Y;return fe(e.data)}).catch(o=>{if(o instanceof WebAssembly.RuntimeError){Y=o,b({id:e.data.id,ok:false,error:`Resident engine worker trapped: ${o.message}`,terminal:true});return}b({id:e.data.id,ok:false,error:o instanceof Error?o.message:String(o)});});};async function fe(e){if(e.type==="destroy"){re();return}if(e.type==="bootstrap"){re(),a=await q(),te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r);return}if(e.type==="eraseCaret"){_=null,y!==null&&await M(false),b({id:e.id,ok:true});return}if(!a)throw new Error("Resident engine worker is not initialized");if(e.type==="sync"){E?.(),E=null,te(e.snapshot),ne();let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="buildFrame"){u=[];let r=performance.now(),i=a.buildDisplayListFrame(e.extras,e.expectedFrameEpoch);await x(e.id,i,performance.now()-r,u,void 0,r,false,e.paintCaret);return}if(e.type==="applyUpdate"){a.applyUpdate(e.update),e.selection&&a.setSelection(e.selection.anchor,e.selection.head);return}if(e.type==="attachCanvases"){let r=h.size>0&&(U!==e.devicePixelRatio||B!==e.zoom),i=new Set(e.pages.map(l=>l.pageId));for(let l of e.activePageIds)w.has(l)||i.add(l);for(let{pageId:l,canvas:c}of e.pages)h.set(l,c);w=new Set(e.activePageIds),U=e.devicePixelRatio,B=e.zoom,D=e.caretStyle;for(let[l,c]of h)w.has(l)||(c.width=0,c.height=0,F.delete(l),oe(l));await M(r?true:i),b({id:e.id,ok:true});return}a.setSelection(e.selection.anchor,e.selection.head),u=[];let o=performance.now();try{let r=e.type==="applyDelete"?e.profile?a.applyDeleteProfiled(e.direction,e.expectedFrameEpoch):{frame:a.applyDelete(e.direction,e.expectedFrameEpoch),profile:void 0}:e.profile?a.applyInputProfiled(e.text,e.expectedFrameEpoch):{frame:a.applyInput(e.text,e.expectedFrameEpoch),profile:void 0};await x(e.id,r.frame,performance.now()-o,u,r.profile,o,!0,e.paintCaret);}catch(r){if(r instanceof WebAssembly.RuntimeError)throw r;let i=r instanceof Error?r.message:String(r);b({id:e.id,ok:false,error:i,residentUnavailable:i.includes("resident input state is not ready")});}finally{u=[];}}function te(e){if(!a)throw new Error("Resident engine worker is not initialized");if(a.loadState(e.state),e.fontsRevision!==L){a.clearFonts();for(let o of e.fonts)o instanceof Uint8Array?a.registerFont(o):a.registerSubstituteFont(o.substituteOf,o.family);L=e.fontsRevision;}for(let{story:o,env:r}of e.renderInputs)a.yrsBlocksForStory(o,r);for(let o of e.measureInputs)a.measureParagraphJson(o);e.layoutWithRegions?a.layoutDocumentWithRegionsRetainedJson(e.layoutInput):a.layoutDocumentJson(e.layoutInput),e.selection&&a.setSelection(e.selection.anchor,e.selection.head),z=e.layoutRevision,u=[];}function ne(){a&&(E=a.onUpdate(e=>u.push(e.slice())));}function re(){E?.(),E=null,a?.destroy(),a=null,u=[],z=0,L=-1,d=null,O=null,h.clear(),F.clear(),S.clear(),w.clear(),_=null,y=null,P=null,J=null,C.clear();}function oe(e){C.delete(e),y===e&&(y=null,P=null);}async function x(e,o,r,i=u,l,c=performance.now(),R=false,t=false){d=u$1(d,s(o));for(let f of d.damagedPageIds)S.add(f.toString());d={...d,pages:d.pages.map(f=>({...f,primitiveIds:f.primitiveIds.slice()}))};let n=a?.residentCaretSnapshot();if(!n||!b$1(n,d))throw new Error("Resident caret snapshot does not match the produced frame");if(R&&!n.caretRect)throw new Error("Resident input frame omitted collapsed caret geometry");let p=a?.selection()??null;_=t?n.caretRect??null:null;let s$1=new Set(d.pages.map(f=>f.pageId.toString()));for(let f of S)s$1.has(f)||S.delete(f);for(let f of h.keys())s$1.has(f)||(h.delete(f),F.delete(f),oe(f));let k=performance.now(),{replayedPages:W,caretPainted:A}=await M(false),v=performance.now()-k,I=j(o),g=i.map(j),m=a?j(a.encodeStateVector()):void 0;b({id:e,ok:true,frame:I,updates:g,engineMs:r,workerTotalMs:performance.now()-c,engineProfile:l,caret:n,selection:p,caretPainted:A,replayMs:v,replayedPages:W,layoutRevision:z,...m?{stateVector:m}:{}},[I,...g,...m?[m]:[]]);}async function M(e){let o=e===true?w:e;if(o)for(let n of o)S.add(n);if(!d||h.size===0)return {replayedPages:0,caretPainted:false};!O&&a&&(O=new a$1({provider:(n,p)=>a.outlineGlyphJson(n,p)}));let r=_&&w.has(_.pageId)?_:null,i$1=r?a$2(r,D,U,B):null,l=r&&i$1?`${r.pageId}|${i$1.x}|${i$1.y}|${i$1.width}|${i$1.height}|${D.color}`:null,c=[];for(let n=0;n<d.pages.length;n+=1){let s=d.pages[n].pageId.toString();if(!w.has(s))continue;let k=S.has(s),W=s===r?.pageId&&!(y===s&&P===l),A=s===y&&s!==r?.pageId;if(!k&&!W&&!A)continue;let v=h.get(s),I=d.displayList.pages[n];if(!v||!I)continue;let g$1=s,m=F.get(g$1);m||(m=new OffscreenCanvas(1,1),F.set(g$1,m));let f=m;if(!k&&C.has(g$1)){c.push(Promise.resolve({canvas:v,buffer:f,pageId:g$1}));continue}c.push(g(f,I,{glyphCache:O??void 0},U,B).then(()=>({canvas:v,buffer:f,pageId:g$1})));}let R=await Promise.all(c).catch(async n=>{throw await Promise.allSettled(c),n}),t=r!==null&&y===r.pageId&&P===l;for(let{canvas:n,buffer:p,pageId:s}of R)r&&i$1&&s===r.pageId?(J||(J=new OffscreenCanvas(1,1)),j$1(n,p,J,{...i$1,color:D.color}),C.add(s),y=s,P=l,t=true):(i(n,p),C.delete(s),y===s&&(y=null,P=null)),S.delete(s);return {replayedPages:R.length,caretPainted:t}}function j(e){return e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}function b(e,o=[]){ae.postMessage(e,o);}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@betteroffice/docx",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "sideEffects": [
5
5
  "**/residentEngineWorker.*"
6
6
  ],
@@ -217,7 +217,7 @@
217
217
  }
218
218
  },
219
219
  "devDependencies": {
220
- "@betteroffice/fonts": "0.2.0",
220
+ "@betteroffice/fonts": "0.3.0",
221
221
  "tsup": "^8.0.1",
222
222
  "typescript": "^6.0.3",
223
223
  "@types/bun": "^1.0.0",
@@ -1 +0,0 @@
1
- import {b as b$1,c as c$1,h as h$1}from'./chunk-ACGKK7IB.mjs';function B(n){return n.length>=4&&(n[0]===73&&n[1]===73&&n[2]===42&&n[3]===0||n[0]===77&&n[1]===77&&n[2]===0&&n[3]===42)}function R(n,e,t,r){if(!B(n))return {bytes:n,mimeType:e,dataUrl:t};if(n.byteLength>33554432)throw new Error("TIFF image exceeds the browser transfer budget");let o=r(n);return {bytes:o,mimeType:"image/png",dataUrl:`data:image/png;base64,${N(o)}`}}function N(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e)}var U=new Set(["__proto__","constructor","prototype"]);function Z(n,e){return O(b$1(new Uint8Array(n),JSON.stringify(e)),n)}function O(n,e){return C(JSON.parse(n),e)}function C(n,e){h(n,"wire");let t=c(n,"wire");if(p(t,["wireVersion","document","embeddedFontParts","fontTableRelationshipsXml","canonicalBase64","canonicalSha256"],"wire",["fontTableRelationshipsXml","canonicalBase64","canonicalSha256"]),t.wireVersion!==1)throw new TypeError("wire.wireVersion must be 1");let r=X(t.document,e),o=I(t.embeddedFontParts);if((t.canonicalBase64!==void 0||t.canonicalSha256!==void 0)&&(t.canonicalBase64===void 0||t.canonicalSha256===void 0))throw new TypeError("wire canonical fields must be present together");let i=t.canonicalSha256===void 0?void 0:d(t.canonicalSha256,"wire.canonicalSha256");if(i!==void 0&&!/^[0-9a-f]{64}$/.test(i))throw new TypeError("wire.canonicalSha256 is invalid");return {wireVersion:1,document:r,embeddedFonts:o,...t.fontTableRelationshipsXml===void 0?{}:{fontTableRelationshipsXml:d(t.fontTableRelationshipsXml,"wire.fontTableRelationshipsXml")},...t.canonicalBase64===void 0?{}:{rustCanonicalBytes:b(d(t.canonicalBase64,"wire.canonicalBase64")),rustCanonicalSha256:i}}}function X(n,e){let t=c(n,"wire.document");p(t,["package","templateVariables","warnings"],"wire.document",["templateVariables","warnings"]);let o={package:_(t.package),originalBuffer:e};return t.warnings!==void 0&&(o.warnings=J(t.warnings,"wire.document.warnings")),o}function _(n){let e=c(n,"wire.document.package");p(e,["document","styles","theme","numbering","settings","fontTable","headerEntries","footerEntries","footnotes","endnotes","footnoteSeparators","endnoteSeparators","relationshipEntries","mediaEntries","chartEntries"],"wire.document.package",["styles","headerEntries","footerEntries","footnotes","endnotes","footnoteSeparators","endnoteSeparators"]);let o={document:V(e.document),theme:c(e.theme,"wire.document.package.theme"),numbering:c(e.numbering,"wire.document.package.numbering"),settings:c(e.settings,"wire.document.package.settings"),fontTable:c(e.fontTable,"wire.document.package.fontTable"),relationships:x(e.relationshipEntries,"wire.document.package.relationshipEntries"),media:j(e.mediaEntries),charts:g(e.chartEntries,"wire.document.package.chartEntries",(a,i)=>c(a,i))};e.styles!==void 0&&(o.styles=c(e.styles,"wire.document.package.styles"));for(let[a,i]of [["headerEntries","headers"],["footerEntries","footers"]]){let s=e[a];s!==void 0&&(o[i]=g(s,`wire.document.package.${a}`,(f,u)=>c(f,u)));}return e.footnotes!==void 0&&(o.footnotes=m(e.footnotes,"wire.document.package.footnotes")),e.endnotes!==void 0&&(o.endnotes=m(e.endnotes,"wire.document.package.endnotes")),e.footnoteSeparators!==void 0&&(o.footnoteSeparators=m(e.footnoteSeparators,"wire.document.package.footnoteSeparators")),e.endnoteSeparators!==void 0&&(o.endnoteSeparators=m(e.endnoteSeparators,"wire.document.package.endnoteSeparators")),o}function V(n){let e="wire.document.package.document",t=c(n,e);if(p(t,["content","sections","finalSectionProperties","customRootBindings","comments"],e,["sections","finalSectionProperties","customRootBindings","comments"]),!Array.isArray(t.content))throw new TypeError(`${e}.content must be an array`);t.content.forEach((o,a)=>c(o,`${e}.content[${a}]`));let r={content:t.content};if(t.sections!==void 0){if(!Array.isArray(t.sections))throw new TypeError(`${e}.sections must be an array`);r.sections=t.sections.map((o,a)=>{let i=`${e}.sections[${a}]`,s=c(o,i);p(s,["id","properties","contentStart","contentEnd"],i,["id"]);let f=P(s.contentStart,`${i}.contentStart`),u=P(s.contentEnd,`${i}.contentEnd`);if(f>u||u>r.content.length)throw new TypeError(`${i} has an invalid content range`);return {...s.id===void 0?{}:{id:d(s.id,`${i}.id`)},properties:c(s.properties,`${i}.properties`),content:r.content.slice(f,u)}});}return t.finalSectionProperties!==void 0&&(r.finalSectionProperties=c(t.finalSectionProperties,`${e}.finalSectionProperties`)),t.customRootBindings!==void 0&&(r.customRootBindings=m(t.customRootBindings,`${e}.customRootBindings`)),t.comments!==void 0&&(r.comments=m(t.comments,`${e}.comments`)),r}function x(n,e){return g(n,e,(t,r,o)=>W(t,r,o))}function j(n){let e="wire.document.package.mediaEntries";if(!Array.isArray(n))throw new TypeError(`${e} must be an array`);let t=new Map,r=new Map;for(let o=0;o<n.length;o+=1){let a=`${e}[${o}]`,i=n[o];if(!Array.isArray(i)||i.length!==2)throw new TypeError(`${a} must be a key/value pair`);let s=d(i[0],`${a}[0]`);if(t.has(s))throw new TypeError(`${e} contains duplicate key ${JSON.stringify(s)}`);let f=`${a}[1]`,u=c(i[1],f);p(u,["path","filename","mimeType","base64","dataUrl"],f,["filename"]);let l=d(u.path,`${f}.path`),w=r.get(l);if(!w){let D=b(d(u.base64,`${f}.base64`)),y=R(D,d(u.mimeType,`${f}.mimeType`),d(u.dataUrl,`${f}.dataUrl`),h$1),k={path:l,...u.filename===void 0?{}:{filename:d(u.filename,`${f}.filename`)},mimeType:y.mimeType,data:M(y.bytes),dataUrl:y.dataUrl};w=k,r.set(l,k);}t.set(s,w);}return t}function I(n){let e="wire.embeddedFontParts";if(!Array.isArray(n))throw new TypeError(`${e} must be an array`);let t=new Map;return n.forEach((r,o)=>{let a=`${e}[${o}]`,i=c(r,a);p(i,["path","base64"],a);let s=d(i.path,`${a}.path`);if(t.has(s))throw new TypeError(`${e} contains duplicate key ${JSON.stringify(s)}`);t.set(s,M(b(d(i.base64,`${a}.base64`))));}),t}function g(n,e,t){if(!Array.isArray(n))throw new TypeError(`${e} must be an array`);let r=new Map;return n.forEach((o,a)=>{let i=`${e}[${a}]`;if(!Array.isArray(o)||o.length!==2)throw new TypeError(`${i} must be a key/value pair`);let s=d(o[0],`${i}[0]`);if(r.has(s))throw new TypeError(`${e} contains duplicate key ${JSON.stringify(s)}`);r.set(s,t(o[1],`${i}[1]`,s));}),r}function J(n,e){if(!Array.isArray(n))throw new TypeError(`${e} must be an array`);return n.map((t,r)=>d(t,`${e}[${r}]`))}function m(n,e){if(!Array.isArray(n))throw new TypeError(`${e} must be an array`);return n.forEach((t,r)=>c(t,`${e}[${r}]`)),n}function M(n){return Uint8Array.from(n).buffer}function P(n,e){let t=H(n,e);if(!Number.isSafeInteger(t)||t<0)throw new TypeError(`${e} must be a non-negative safe integer`);return t}function v(n,e="word/_rels/document.xml.rels"){let t=JSON.parse(c$1(new TextEncoder().encode(n),e));h(t,"relationshipPart");let r=c(t,"relationshipPart");return p(r,["path","relationships","canonicalBase64","canonicalSha256"],"relationshipPart"),d(r.path,"relationshipPart.path"),x(r.relationships,"relationshipPart.relationships")}function W(n,e,t){let r=c(n,e);p(r,["id","type","target","targetMode"],e,["targetMode"]);let o=d(r.id,`${e}.id`);if(o!==t)throw new TypeError(`${e}.id does not match its map key`);let a={id:o,type:d(r.type,`${e}.type`),target:d(r.target,`${e}.target`)};if(r.targetMode!==void 0){if(r.targetMode!=="External"&&r.targetMode!=="Internal")throw new TypeError(`${e}.targetMode is invalid`);a.targetMode=r.targetMode;}return a}function h(n,e,t=new WeakSet){if(!(n===null||typeof n!="object")){if(t.has(n))throw new TypeError(`${e} contains a cycle`);t.add(n);try{for(let r of Object.keys(n)){if(U.has(r))throw new TypeError(`${e} contains forbidden key ${r}`);h(n[r],`${e}.${r}`,t);}}finally{t.delete(n);}}}function c(n,e){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(`${e} must be an object`);return n}function p(n,e,t,r=[]){let o=new Set(e);for(let i of Object.keys(n))if(!o.has(i))throw new TypeError(`${t} contains unknown key ${i}`);let a=new Set(r);for(let i of e)if(!a.has(i)&&!Object.prototype.hasOwnProperty.call(n,i))throw new TypeError(`${t} is missing ${i}`)}function d(n,e){if(typeof n!="string")throw new TypeError(`${e} must be a string`);return n}function H(n,e){if(typeof n!="number"||!Number.isFinite(n))throw new TypeError(`${e} must be a finite number`);return n}function b(n){let e;try{e=atob(n);}catch{throw new TypeError("wire canonicalBase64 is invalid")}let t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}export{Z as a,O as b,C as c,v as d};
@@ -1,57 +0,0 @@
1
- import {a as a$2,B as B$1,u}from'./chunk-JHJLG4I6.mjs';import {a as a$3}from'./chunk-6LQJAKOC.mjs';import {a,b as b$1,c}from'./chunk-HLDJMU3R.mjs';import {a as a$1,d,e,f as f$1,g}from'./chunk-ACGKK7IB.mjs';async function we(e,t={}){await a(),await a$1();let r=e instanceof ArrayBuffer?e:await a$2(e),o=t.onProgress??(()=>{});try{o("Extracting DOCX...",0);let n=a$3(r,Z(t));return q(t,o),await K(n,t.preloadFonts??!0,o),o("Assembling document...",95),o("Complete",100),n.document}catch(n){let s=n instanceof Error?n.message:String(n);if(s.startsWith("Failed to parse DOCX: "))throw n;let a=Q(s),c=a.code==="Container"?s.replace(/^container error: /,""):s,m=new Error(`Failed to parse DOCX: ${c}`,{cause:n});throw Object.assign(m,a),m}}function Z(e){return {parseHeadersFooters:e.parseHeadersFooters??true,parseNotes:e.parseNotes??true,detectVariables:false,includeCanonical:false}}function q(e,t){t("Extracted DOCX",10),t("Parsing relationships...",10),t("Parsed relationships",15),t("Parsing theme...",15),t("Parsed theme",20),t("Parsing styles...",20),t("Parsed styles",30),t("Parsing numbering...",30),t("Parsed numbering",35),t("Processing media files...",35),t("Processed media",40),t("Parsing document body...",40),t("Parsed document body",55),e.parseHeadersFooters??true?(t("Parsing headers/footers...",55),t("Parsed headers/footers",65)):t("Skipping headers/footers",65),e.parseNotes??true?(t("Parsing footnotes/endnotes...",65),t("Parsed footnotes/endnotes",75)):t("Skipping footnotes/endnotes",75),t("Parsing comments...",75),t("Parsed comments",80);}async function K(e,t,r){if(!t){r("Skipping font loading",95);return}r("Loading fonts...",80),await G(e.document.package.theme??null,e.document.package.styles,e.document.package.document),await B$1(e.document.package.fontTable,e.embeddedFonts,e.fontTableRelationshipsXml),r("Loaded fonts",95);}async function G(e,t,r){let o=new Set;e?.fontScheme?.majorFont?.latin&&o.add(e.fontScheme.majorFont.latin),e?.fontScheme?.minorFont?.latin&&o.add(e.fontScheme.minorFont.latin),t?.docDefaults?.rPr?.fontFamily?.ascii&&o.add(t.docDefaults.rPr.fontFamily.ascii);for(let n of t?.styles??[])n.rPr?.fontFamily?.ascii&&o.add(n.rPr.fontFamily.ascii),n.rPr?.fontFamily?.hAnsi&&o.add(n.rPr.fontFamily.hAnsi);for(let n of r.content)if(n.type==="paragraph")for(let s of n.content)s.type==="run"&&(s.formatting?.fontFamily?.ascii&&o.add(s.formatting.fontFamily.ascii),s.formatting?.fontFamily?.hAnsi&&o.add(s.formatting.fontFamily.hAnsi));if(o.size!==0)try{await u([...o]);}catch(n){console.warn("Failed to load some fonts:",n);}}function Q(e){let t=/(?:unsafe XML|resource limit .* exceeded|malformed XML|invalid relationship) in ([^:]+)(?::| at)/.exec(e)?.[1],r=/ at byte (\d+):/.exec(e)?.[1];return {code:e.startsWith("unsafe XML")?"UnsafeXml":e.startsWith("resource limit")?"ResourceLimit":e.startsWith("malformed XML")?"MalformedXml":e.startsWith("invalid relationship")?"Relationship":e.startsWith("container error")?"Container":e.startsWith("wire.")?"Wire":"Parse",...t?{part:t}:{},...r?{offset:Number(r)}:{}}}var ee={seed:"0".repeat(64),now:"2000-01-01T00:00:00.000Z"};function B(e$1,t){let r=JSON.stringify({...t,determinism:ee}),o=e$1==="S10"?d(r):e$1==="S11"?e(r):f$1(r),n=JSON.parse(o);if(!n||typeof n!="object")throw new TypeError(`${e$1} Rust serializer returned a non-object response`);let s=n;if(s.wireVersion!==1||s.family!==t.family||typeof s.xml!="string")throw new TypeError(`invalid ${e$1} Rust serializer response for ${String(t.family)}`);return s.xml}function be(e){return B("S12",{family:"document",body:e.package.document})}function Te(e){let t=B("S12",{family:"document",body:e}),r="<w:body>",o="</w:body>",n=t.indexOf(r),s=t.lastIndexOf(o);if(n<0||s<n)throw new Error("Rust document serializer omitted w:body");return t.slice(n+r.length,s)}function ke(e){return B("S10",{family:"section",properties:e})}var M={image:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image",hyperlink:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink",header:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/header",footer:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer",footnotes:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes",endnotes:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes",styles:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",numbering:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",fontTable:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable",theme:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",settings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings",webSettings:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings",oleObject:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject",chart:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart",diagramData:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/diagramData",officeDocument:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",coreProperties:"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties",extendedProperties:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties",customProperties:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties",customXml:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml",comments:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",commentsExtended:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",commentsIds:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",commentsExtensible:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible"};var te=new TextEncoder,re=new TextDecoder("utf-8",{ignoreBOM:true});function l(e){return typeof e=="string"?te.encode(e):e instanceof Uint8Array?e:new Uint8Array(e)}function S(e){return e?re.decode(e):void 0}function I(e){let t=c(Object.fromEntries(e)),r=new ArrayBuffer(t.byteLength);return new Uint8Array(r).set(t),r}function E(e){return e.startsWith("/")?e.slice(1):`word/${e}`}function L(e){let t=[{relsPath:"word/_rels/document.xml.rels",blocks:e.package.document.content}],r=c=>(c??[]).flatMap(m=>m.content),o=[...r(e.package.footnoteSeparators),...r(e.package.footnotes)];o.length>0&&t.push({relsPath:"word/_rels/footnotes.xml.rels",blocks:o});let n=[...r(e.package.endnoteSeparators),...r(e.package.endnotes)];n.length>0&&t.push({relsPath:"word/_rels/endnotes.xml.rels",blocks:n});let s=e.package.relationships;if(!s)return t;let a=(c,m)=>{if(c)for(let[p,y]of c.entries()){let d=s.get(p);if(!d||d.type!==m||!d.target)continue;let w=E(d.target).replace(/^word\//,"");t.push({relsPath:`word/_rels/${w}.rels`,blocks:y.content});}};return a(e.package.headers,M.header),a(e.package.footers,M.footer),t}async function oe(e){let t=await crypto.subtle.digest("SHA-256",Uint8Array.from(e).buffer);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}async function A(e,t,r={},o,n){await a(),await a$1();let s=n??{seed:await oe(new Uint8Array(t)),now:new Date().toISOString()};ie(s);let a$2=e.package,c={determinism:s,document:a$2.document,headerEntries:[...a$2.headers?.entries()??[]],footerEntries:[...a$2.footers?.entries()??[]],footnotes:a$2.footnotes??[],endnotes:a$2.endnotes??[],footnoteSeparators:a$2.footnoteSeparators??[],endnoteSeparators:a$2.endnoteSeparators??[],relationshipEntries:[...a$2.relationships?.entries()??[]],...a$2.numbering===void 0?{}:{numbering:a$2.numbering},options:{updateModifiedDate:r.updateModifiedDate??true,...r.modifiedBy===void 0?{}:{modifiedBy:r.modifiedBy}},...o===void 0?{}:{selective:{changedParaIds:[...o.changedParaIds]}}};F(c,"save");let m=g(JSON.stringify(c),new Uint8Array(t)),p=ce(m);return o||ne(e,t,p),{buffer:p,determinism:s}}function ne(e,t,r){let o=b$1(new Uint8Array(t)),n=b$1(new Uint8Array(r));for(let c of L(e)){let m=S(o[c.relsPath])??"",p=S(n[c.relsPath])??"",y=new Set(b(m).map(i=>f(i,"Id"))),d=b(p).filter(i=>f(i,"Type")?.endsWith("/image")).map(i=>f(i,"Id")).filter(i=>!!i&&!y.has(i)),x=Y(c.blocks);if(x.length>d.length)throw new Error(`Rust save image mutation mismatch in ${c.relsPath}: ${x.length} model images, ${d.length} relationships`);x.forEach((i,u)=>{i.rId=d[u];});let w=b(p).filter(i=>f(i,"Type")?.endsWith("/hyperlink")&&f(i,"TargetMode")==="External");for(let i of C(c.blocks)){if(!i.href){j(p,i.rId)||(i.rId=void 0);continue}let u=w.find(T=>se(f(T,"Target")??"")===i.href),D=u&&f(u,"Id");D&&(i.rId=D);}}let s=e.package.headers,a=e.package.relationships;if(!(!s||!a))for(let[c,m]of s){let p=m.watermark;if(!p||p.kind!=="picture")continue;let y=a.get(c);if(!y?.target)continue;let x=`word/_rels/${E(y.target).replace(/^word\//,"")}.rels`,w=S(n[x])??"";if(j(w,p.relId))continue;let i=p.mediaPath?.split("/").pop(),u=b(w).find(T=>{if(!f(T,"Type")?.endsWith("/image"))return false;let J=f(T,"Target")?.split("/").pop();return i?J===i:true}),D=u&&f(u,"Id");D&&(p.relId=D);}}function Y(e){let t=[],r=o=>{for(let n of o.content)n.type==="drawing"&&n.image.src?.startsWith("data:")&&!n.image.rId&&t.push(n.image);};for(let o of e)if(o.type==="paragraph"){for(let n of o.content)if(n.type==="run")r(n);else if(n.type==="insertion"||n.type==="deletion"||n.type==="moveFrom"||n.type==="moveTo")for(let s of n.content)s.type==="run"&&r(s);}else if(o.type==="table")for(let n of o.rows)for(let s of n.cells)t.push(...Y(s.content));return t}function C(e){let t=[];for(let r of e)if(r.type==="paragraph")for(let o of r.content)o.type==="hyperlink"&&(o.href||o.rId)&&!o.anchor&&t.push(o);else if(r.type==="table")for(let o of r.rows)for(let n of o.cells)t.push(...C(n.content));else r.type==="blockSdt"&&t.push(...C(r.content));return t}function b(e){return [...e.matchAll(/<Relationship\b[^>]*\/?>/g)].map(t=>t[0])}function f(e,t){return e.match(new RegExp(`\\b${t}="([^"]*)"`))?.[1]}function j(e,t){if(t)return b(e).find(r=>f(r,"Id")===t)}function se(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(t,r)=>String.fromCodePoint(Number(r))).replace(/&#x([0-9A-Fa-f]+);/g,(t,r)=>String.fromCodePoint(parseInt(r,16))).replace(/&amp;/g,"&")}function ie(e){if(!/^[0-9a-f]{64}$/i.test(e.seed))throw new TypeError("Rust save determinism seed must be a SHA-256 hex digest");if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e.now))throw new TypeError("Rust save clock must be a UTC ISO-8601 millisecond timestamp")}var ae=new Set(["__proto__","constructor","prototype"]);function F(e,t,r=new WeakSet){if(!(e===null||typeof e!="object")){if(r.has(e))throw new TypeError(`${t} contains a cycle`);if(r.add(e),Array.isArray(e))e.forEach((o,n)=>F(o,`${t}[${n}]`,r));else for(let o of Object.keys(e)){if(ae.has(o))throw new TypeError(`${t} contains forbidden key ${o}`);F(e[o],`${t}.${o}`,r);}r.delete(e);}}function ce(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function V(){let e=new Map;e.set("[Content_Types].xml",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2
- <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
3
- <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
4
- <Default Extension="xml" ContentType="application/xml"/>
5
- <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
6
- <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
7
- <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
8
- <Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>
9
- </Types>`)),e.set("_rels/.rels",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
10
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
11
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
12
- <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
13
- <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
14
- </Relationships>`)),e.set("word/_rels/document.xml.rels",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
15
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
16
- <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
17
- </Relationships>`)),e.set("word/document.xml",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
18
- <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
19
- <w:body>
20
- <w:p>
21
- <w:r>
22
- <w:t></w:t>
23
- </w:r>
24
- </w:p>
25
- <w:sectPr>
26
- <w:pgSz w:w="12240" w:h="15840"/>
27
- <w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720" w:gutter="0"/>
28
- </w:sectPr>
29
- </w:body>
30
- </w:document>`)),e.set("word/styles.xml",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
31
- <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
32
- <w:docDefaults>
33
- <w:rPrDefault>
34
- <w:rPr>
35
- <w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/>
36
- <w:sz w:val="22"/>
37
- </w:rPr>
38
- </w:rPrDefault>
39
- <w:pPrDefault>
40
- <w:pPr>
41
- <w:spacing w:after="200" w:line="276" w:lineRule="auto"/>
42
- </w:pPr>
43
- </w:pPrDefault>
44
- </w:docDefaults>
45
- <w:style w:type="paragraph" w:default="1" w:styleId="Normal">
46
- <w:name w:val="Normal"/>
47
- </w:style>
48
- </w:styles>`));let t=new Date().toISOString();return e.set("docProps/core.xml",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
49
- <cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
50
- <dc:creator>OpenOOXML DOCX Editor</dc:creator>
51
- <dcterms:created xsi:type="dcterms:W3CDTF">${t}</dcterms:created>
52
- <dcterms:modified xsi:type="dcterms:W3CDTF">${t}</dcterms:modified>
53
- </cp:coreProperties>`)),e.set("docProps/app.xml",l(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
54
- <Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
55
- <Application>OpenOOXML DOCX Editor</Application>
56
- <AppVersion>1.0.0</AppVersion>
57
- </Properties>`)),I(e)}async function pe(e,t={}){if(!e.originalBuffer)throw new Error("Cannot repack document: no original buffer for round-trip. Use createDocx() for new documents.");return (await A(e,e.originalBuffer,t)).buffer}function me(e){return new Map(Object.entries(b$1(new Uint8Array(e))))}async function Ve(e,t,r={}){return fe(me(e),t,r)}async function fe(e,t,r={}){for(let[o,n]of t)e.set(o,l(n));return I(e)}async function Je(e){let t=await V();return pe({...e,originalBuffer:t})}async function Ge(e,t,r){if(!le(e,t,r))return null;try{return (await A(e,t,{updateModifiedDate:!0},{changedParaIds:r.changedParaIds})).buffer}catch{return null}}function le(e,t,r){return r.structuralChange||r.hasUntrackedChanges||!t?false:!O(e.package.document.content)}function O(e){let t=r=>r.content.some(o=>o.type==="drawing"&&o.image?.src?.startsWith("data:")&&!o.image.rId);for(let r of e)if(r.type==="paragraph")for(let o of r.content){if(o.type==="run"&&t(o)||o.type==="hyperlink"&&o.href&&!o.rId&&!o.anchor)return true;if(o.type==="insertion"||o.type==="deletion"||o.type==="moveFrom"||o.type==="moveTo"){for(let n of o.content)if(n.type==="run"&&t(n))return true}}else if(r.type==="table"){for(let o of r.rows)for(let n of o.cells)if(O(n.content))return true}else if(r.type==="blockSdt"&&O(r.content))return true;return false}export{we as a,be as b,Te as c,ke as d,M as e,pe as f,Ve as g,Je as h,Ge as i};