@ansonlai/docx-redline-js 0.7.1 → 0.8.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.
@@ -1,16 +1,16 @@
1
- var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var vs=Object.getOwnPropertyNames;var ys=Object.getPrototypeOf,Ss=Object.prototype.hasOwnProperty;var Ts=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Es=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vs(t))!Ss.call(e,o)&&o!==r&&$o(e,o,{get:()=>t[o],enumerable:!(n=Ns(t,o))||n.enumerable});return e};var Xo=(e,t,r)=>(r=e!=null?xs(ys(e)):{},Es(t||!e||!e.__esModule?$o(r,"default",{value:e,enumerable:!0}):r,e));var Ln=Ts((tm,Mt)=>{var P=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},J=-1,Q=1,U=0;P.Diff=function(e,t){return[e,t]};P.prototype.diff_main=function(e,t,r,n){typeof n>"u"&&(this.Diff_Timeout<=0?n=Number.MAX_VALUE:n=new Date().getTime()+this.Diff_Timeout*1e3);var o=n;if(e==null||t==null)throw new Error("Null input. (diff_main)");if(e==t)return e?[new P.Diff(U,e)]:[];typeof r>"u"&&(r=!0);var i=r,a=this.diff_commonPrefix(e,t),s=e.substring(0,a);e=e.substring(a),t=t.substring(a),a=this.diff_commonSuffix(e,t);var l=e.substring(e.length-a);e=e.substring(0,e.length-a),t=t.substring(0,t.length-a);var c=this.diff_compute_(e,t,i,o);return s&&c.unshift(new P.Diff(U,s)),l&&c.push(new P.Diff(U,l)),this.diff_cleanupMerge(c),c};P.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new P.Diff(Q,t)];if(!t)return[new P.Diff(J,e)];var i=e.length>t.length?e:t,a=e.length>t.length?t:e,s=i.indexOf(a);if(s!=-1)return o=[new P.Diff(Q,i.substring(0,s)),new P.Diff(U,a),new P.Diff(Q,i.substring(s+a.length))],e.length>t.length&&(o[0][0]=o[2][0]=J),o;if(a.length==1)return[new P.Diff(J,e),new P.Diff(Q,t)];var l=this.diff_halfMatch_(e,t);if(l){var c=l[0],u=l[1],f=l[2],m=l[3],d=l[4],p=this.diff_main(c,f,r,n),h=this.diff_main(u,m,r,n);return p.concat([new P.Diff(U,d)],h)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};P.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,i=this.diff_main(e,t,!1,r);this.diff_charsToLines_(i,o),this.diff_cleanupSemantic(i),i.push(new P.Diff(U,""));for(var a=0,s=0,l=0,c="",u="";a<i.length;){switch(i[a][0]){case Q:l++,u+=i[a][1];break;case J:s++,c+=i[a][1];break;case U:if(s>=1&&l>=1){i.splice(a-s-l,s+l),a=a-s-l;for(var f=this.diff_main(c,u,!1,r),m=f.length-1;m>=0;m--)i.splice(a,0,f[m]);a=a+f.length}l=0,s=0,c="",u="";break}a++}return i.pop(),i};P.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,i=Math.ceil((n+o)/2),a=i,s=2*i,l=new Array(s),c=new Array(s),u=0;u<s;u++)l[u]=-1,c[u]=-1;l[a+1]=0,c[a+1]=0;for(var f=n-o,m=f%2!=0,d=0,p=0,h=0,w=0,b=0;b<i&&!(new Date().getTime()>r);b++){for(var g=-b+d;g<=b-p;g+=2){var x=a+g,v;g==-b||g!=b&&l[x-1]<l[x+1]?v=l[x+1]:v=l[x-1]+1;for(var N=v-g;v<n&&N<o&&e.charAt(v)==t.charAt(N);)v++,N++;if(l[x]=v,v>n)p+=2;else if(N>o)d+=2;else if(m){var S=a+f-g;if(S>=0&&S<s&&c[S]!=-1){var y=n-c[S];if(v>=y)return this.diff_bisectSplit_(e,t,v,N,r)}}}for(var T=-b+h;T<=b-w;T+=2){var S=a+T,y;T==-b||T!=b&&c[S-1]<c[S+1]?y=c[S+1]:y=c[S-1]+1;for(var A=y-T;y<n&&A<o&&e.charAt(n-y-1)==t.charAt(o-A-1);)y++,A++;if(c[S]=y,y>n)w+=2;else if(A>o)h+=2;else if(!m){var x=a+f-T;if(x>=0&&x<s&&l[x]!=-1){var v=l[x],N=a+v-x;if(y=n-y,v>=y)return this.diff_bisectSplit_(e,t,v,N,r)}}}}return[new P.Diff(J,e),new P.Diff(Q,t)]};P.prototype.diff_bisectSplit_=function(e,t,r,n,o){var i=e.substring(0,r),a=t.substring(0,n),s=e.substring(r),l=t.substring(n),c=this.diff_main(i,a,!1,o),u=this.diff_main(s,l,!1,o);return c.concat(u)};P.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var c="",u=0,f=-1,m=r.length;f<l.length-1;){f=l.indexOf(`
2
- `,u),f==-1&&(f=l.length-1);var d=l.substring(u,f+1);(n.hasOwnProperty?n.hasOwnProperty(d):n[d]!==void 0)?c+=String.fromCharCode(n[d]):(m==i&&(d=l.substring(u),f=l.length),c+=String.fromCharCode(m),n[d]=m,r[m++]=d),u=f+1}return c}var i=4e4,a=o(e);i=65535;var s=o(t);return{chars1:a,chars2:s,lineArray:r}};P.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],i=0;i<n.length;i++)o[i]=t[n.charCodeAt(i)];e[r][1]=o.join("")}};P.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,i=0;r<o;)e.substring(i,o)==t.substring(i,o)?(r=o,i=r):n=o,o=Math.floor((n-r)/2+r);return o};P.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,i=0;r<o;)e.substring(e.length-o,e.length-i)==t.substring(t.length-o,t.length-i)?(r=o,i=r):n=o,o=Math.floor((n-r)/2+r);return o};P.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var i=0,a=1;;){var s=e.substring(o-a),l=t.indexOf(s);if(l==-1)return i;a+=l,(l==0||e.substring(o-a)==t.substring(0,a))&&(i=a,a++)}};P.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function i(p,h,w){for(var b=p.substring(w,w+Math.floor(p.length/4)),g=-1,x="",v,N,S,y;(g=h.indexOf(b,g+1))!=-1;){var T=o.diff_commonPrefix(p.substring(w),h.substring(g)),A=o.diff_commonSuffix(p.substring(0,w),h.substring(0,g));x.length<A+T&&(x=h.substring(g-A,g)+h.substring(g,g+T),v=p.substring(0,w-A),N=p.substring(w+T),S=h.substring(0,g-A),y=h.substring(g+T))}return x.length*2>=p.length?[v,N,S,y,x]:null}var a=i(r,n,Math.ceil(r.length/4)),s=i(r,n,Math.ceil(r.length/2)),l;if(!a&&!s)return null;s?a?l=a[4].length>s[4].length?a:s:l=s:l=a;var c,u,f,m;e.length>t.length?(c=l[0],u=l[1],f=l[2],m=l[3]):(f=l[0],m=l[1],c=l[2],u=l[3]);var d=l[4];return[c,u,f,m,d]};P.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=0,s=0,l=0,c=0;i<e.length;)e[i][0]==U?(r[n++]=i,a=l,s=c,l=0,c=0,o=e[i][1]):(e[i][0]==Q?l+=e[i][1].length:c+=e[i][1].length,o&&o.length<=Math.max(a,s)&&o.length<=Math.max(l,c)&&(e.splice(r[n-1],0,new P.Diff(J,o)),e[r[n-1]+1][0]=Q,n--,n--,i=n>0?r[n-1]:-1,a=0,s=0,l=0,c=0,o=null,t=!0)),i++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),i=1;i<e.length;){if(e[i-1][0]==J&&e[i][0]==Q){var u=e[i-1][1],f=e[i][1],m=this.diff_commonOverlap_(u,f),d=this.diff_commonOverlap_(f,u);m>=d?(m>=u.length/2||m>=f.length/2)&&(e.splice(i,0,new P.Diff(U,f.substring(0,m))),e[i-1][1]=u.substring(0,u.length-m),e[i+1][1]=f.substring(m),i++):(d>=u.length/2||d>=f.length/2)&&(e.splice(i,0,new P.Diff(U,u.substring(0,d))),e[i-1][0]=Q,e[i-1][1]=f.substring(0,f.length-d),e[i+1][0]=J,e[i+1][1]=u.substring(d),i++),i++}i++}};P.prototype.diff_cleanupSemanticLossless=function(e){function t(d,p){if(!d||!p)return 6;var h=d.charAt(d.length-1),w=p.charAt(0),b=h.match(P.nonAlphaNumericRegex_),g=w.match(P.nonAlphaNumericRegex_),x=b&&h.match(P.whitespaceRegex_),v=g&&w.match(P.whitespaceRegex_),N=x&&h.match(P.linebreakRegex_),S=v&&w.match(P.linebreakRegex_),y=N&&d.match(P.blanklineEndRegex_),T=S&&p.match(P.blanklineStartRegex_);return y||T?5:N||S?4:b&&!x&&v?3:x||v?2:b||g?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==U&&e[r+1][0]==U){var n=e[r-1][1],o=e[r][1],i=e[r+1][1],a=this.diff_commonSuffix(n,o);if(a){var s=o.substring(o.length-a);n=n.substring(0,n.length-a),o=s+o.substring(0,o.length-a),i=s+i}for(var l=n,c=o,u=i,f=t(n,o)+t(o,i);o.charAt(0)===i.charAt(0);){n+=o.charAt(0),o=o.substring(1)+i.charAt(0),i=i.substring(1);var m=t(n,o)+t(o,i);m>=f&&(f=m,l=n,c=o,u=i)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=c,u?e[r+1][1]=u:(e.splice(r+1,1),r--))}r++}};P.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;P.whitespaceRegex_=/\s/;P.linebreakRegex_=/[\r\n]/;P.blanklineEndRegex_=/\n\r?\n$/;P.blanklineStartRegex_=/^\r?\n\r?\n/;P.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=!1,s=!1,l=!1,c=!1;i<e.length;)e[i][0]==U?(e[i][1].length<this.Diff_EditCost&&(l||c)?(r[n++]=i,a=l,s=c,o=e[i][1]):(n=0,o=null),l=c=!1):(e[i][0]==J?c=!0:l=!0,o&&(a&&s&&l&&c||o.length<this.Diff_EditCost/2&&a+s+l+c==3)&&(e.splice(r[n-1],0,new P.Diff(J,o)),e[r[n-1]+1][0]=Q,n--,o=null,a&&s?(l=c=!0,n=0):(n--,i=n>0?r[n-1]:-1,l=c=!1),t=!0)),i++;t&&this.diff_cleanupMerge(e)};P.prototype.diff_cleanupMerge=function(e){e.push(new P.Diff(U,""));for(var t=0,r=0,n=0,o="",i="",a;t<e.length;)switch(e[t][0]){case Q:n++,i+=e[t][1],t++;break;case J:r++,o+=e[t][1],t++;break;case U:r+n>1?(r!==0&&n!==0&&(a=this.diff_commonPrefix(i,o),a!==0&&(t-r-n>0&&e[t-r-n-1][0]==U?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new P.Diff(U,i.substring(0,a))),t++),i=i.substring(a),o=o.substring(a)),a=this.diff_commonSuffix(i,o),a!==0&&(e[t][1]=i.substring(i.length-a)+e[t][1],i=i.substring(0,i.length-a),o=o.substring(0,o.length-a))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new P.Diff(J,o)),t++),i.length&&(e.splice(t,0,new P.Diff(Q,i)),t++),t++):t!==0&&e[t-1][0]==U?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",i="";break}e[e.length-1][1]===""&&e.pop();var s=!1;for(t=1;t<e.length-1;)e[t-1][0]==U&&e[t+1][0]==U&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),s=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),s=!0)),t++;s&&this.diff_cleanupMerge(e)};P.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,i=0,a;for(a=0;a<e.length&&(e[a][0]!==Q&&(r+=e[a][1].length),e[a][0]!==J&&(n+=e[a][1].length),!(r>t));a++)o=r,i=n;return e.length!=a&&e[a][0]===J?i:i+(t-o)};P.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,i=/\n/g,a=0;a<e.length;a++){var s=e[a][0],l=e[a][1],c=l.replace(r,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(i,"&para;<br>");switch(s){case Q:t[a]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case J:t[a]='<del style="background:#ffe6e6;">'+c+"</del>";break;case U:t[a]="<span>"+c+"</span>";break}}return t.join("")};P.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Q&&(t[r]=e[r][1]);return t.join("")};P.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==J&&(t[r]=e[r][1]);return t.join("")};P.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var i=e[o][0],a=e[o][1];switch(i){case Q:r+=a.length;break;case J:n+=a.length;break;case U:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};P.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Q:t[r]="+"+encodeURI(e[r][1]);break;case J:t[r]="-"+e[r][1].length;break;case U:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};P.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,i=t.split(/\t/g),a=0;a<i.length;a++){var s=i[a].substring(1);switch(i[a].charAt(0)){case"+":try{r[n++]=new P.Diff(Q,decodeURI(s))}catch{throw new Error("Illegal escape in diff_fromDelta: "+s)}break;case"-":case"=":var l=parseInt(s,10);if(isNaN(l)||l<0)throw new Error("Invalid number in diff_fromDelta: "+s);var c=e.substring(o,o+=l);i[a].charAt(0)=="="?r[n++]=new P.Diff(U,c):r[n++]=new P.Diff(J,c);break;default:if(i[a])throw new Error("Invalid diff operation in diff_fromDelta: "+i[a])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};P.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};P.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function i(v,N){var S=v/t.length,y=Math.abs(r-N);return o.Match_Distance?S+y/o.Match_Distance:y?1:S}var a=this.Match_Threshold,s=e.indexOf(t,r);s!=-1&&(a=Math.min(i(0,s),a),s=e.lastIndexOf(t,r+t.length),s!=-1&&(a=Math.min(i(0,s),a)));var l=1<<t.length-1;s=-1;for(var c,u,f=t.length+e.length,m,d=0;d<t.length;d++){for(c=0,u=f;c<u;)i(d,r+u)<=a?c=u:f=u,u=Math.floor((f-c)/2+c);f=u;var p=Math.max(1,r-u+1),h=Math.min(r+u,e.length)+t.length,w=Array(h+2);w[h+1]=(1<<d)-1;for(var b=h;b>=p;b--){var g=n[e.charAt(b-1)];if(d===0?w[b]=(w[b+1]<<1|1)&g:w[b]=(w[b+1]<<1|1)&g|((m[b+1]|m[b])<<1|1)|m[b+1],w[b]&l){var x=i(d,b-1);if(x<=a)if(a=x,s=b-1,s>r)p=Math.max(1,2*r-s);else break}}if(i(d+1,r)>a)break;m=w}return s};P.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};P.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var o=t.substring(e.start2-n,e.start2);o&&e.diffs.unshift(new P.Diff(U,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new P.Diff(U,i)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+i.length,e.length2+=o.length+i.length}};P.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var i=[],a=new P.patch_obj,s=0,l=0,c=0,u=n,f=n,m=0;m<o.length;m++){var d=o[m][0],p=o[m][1];switch(!s&&d!==U&&(a.start1=l,a.start2=c),d){case Q:a.diffs[s++]=o[m],a.length2+=p.length,f=f.substring(0,c)+p+f.substring(c);break;case J:a.length1+=p.length,a.diffs[s++]=o[m],f=f.substring(0,c)+f.substring(c+p.length);break;case U:p.length<=2*this.Patch_Margin&&s&&o.length!=m+1?(a.diffs[s++]=o[m],a.length1+=p.length,a.length2+=p.length):p.length>=2*this.Patch_Margin&&s&&(this.patch_addContext_(a,u),i.push(a),a=new P.patch_obj,s=0,u=f,l=c);break}d!==Q&&(l+=p.length),d!==J&&(c+=p.length)}return s&&(this.patch_addContext_(a,u),i.push(a)),i};P.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new P.patch_obj;o.diffs=[];for(var i=0;i<n.diffs.length;i++)o.diffs[i]=new P.Diff(n.diffs[i][0],n.diffs[i][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};P.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],i=0;i<e.length;i++){var a=e[i].start2+n,s=this.diff_text1(e[i].diffs),l,c=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),a),l!=-1&&(c=this.match_main(t,s.substring(s.length-this.Match_MaxBits),a+s.length-this.Match_MaxBits),(c==-1||l>=c)&&(l=-1))):l=this.match_main(t,s,a),l==-1)o[i]=!1,n-=e[i].length2-e[i].length1;else{o[i]=!0,n=l-a;var u;if(c==-1?u=t.substring(l,l+s.length):u=t.substring(l,c+this.Match_MaxBits),s==u)t=t.substring(0,l)+this.diff_text2(e[i].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,u,!1);if(s.length>this.Match_MaxBits&&this.diff_levenshtein(f)/s.length>this.Patch_DeleteThreshold)o[i]=!1;else{this.diff_cleanupSemanticLossless(f);for(var m=0,d,p=0;p<e[i].diffs.length;p++){var h=e[i].diffs[p];h[0]!==U&&(d=this.diff_xIndex(f,m)),h[0]===Q?t=t.substring(0,l+d)+h[1]+t.substring(l+d):h[0]===J&&(t=t.substring(0,l+d)+t.substring(l+this.diff_xIndex(f,m+h[1].length))),h[0]!==J&&(m+=h[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};P.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],i=o.diffs;if(i.length==0||i[0][0]!=U)i.unshift(new P.Diff(U,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>i[0][1].length){var a=t-i[0][1].length;i[0][1]=r.substring(i[0][1].length)+i[0][1],o.start1-=a,o.start2-=a,o.length1+=a,o.length2+=a}if(o=e[e.length-1],i=o.diffs,i.length==0||i[i.length-1][0]!=U)i.push(new P.Diff(U,r)),o.length1+=t,o.length2+=t;else if(t>i[i.length-1][1].length){var a=t-i[i.length-1][1].length;i[i.length-1][1]+=r.substring(0,a),o.length1+=a,o.length2+=a}return r};P.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,i=n.start2,a="";n.diffs.length!==0;){var s=new P.patch_obj,l=!0;for(s.start1=o-a.length,s.start2=i-a.length,a!==""&&(s.length1=s.length2=a.length,s.diffs.push(new P.Diff(U,a)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],u=n.diffs[0][1];c===Q?(s.length2+=u.length,i+=u.length,s.diffs.push(n.diffs.shift()),l=!1):c===J&&s.diffs.length==1&&s.diffs[0][0]==U&&u.length>2*t?(s.length1+=u.length,o+=u.length,l=!1,s.diffs.push(new P.Diff(c,u)),n.diffs.shift()):(u=u.substring(0,t-s.length1-this.Patch_Margin),s.length1+=u.length,o+=u.length,c===U?(s.length2+=u.length,i+=u.length):l=!1,s.diffs.push(new P.Diff(c,u)),u==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(u.length))}a=this.diff_text2(s.diffs),a=a.substring(a.length-this.Patch_Margin);var f=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);f!==""&&(s.length1+=f.length,s.length2+=f.length,s.diffs.length!==0&&s.diffs[s.diffs.length-1][0]===U?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new P.Diff(U,f))),l||e.splice(++r,0,s)}}};P.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};P.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
3
- `),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var i=r[n].match(o);if(!i)throw new Error("Invalid patch string: "+r[n]);var a=new P.patch_obj;for(t.push(a),a.start1=parseInt(i[1],10),i[2]===""?(a.start1--,a.length1=1):i[2]=="0"?a.length1=0:(a.start1--,a.length1=parseInt(i[2],10)),a.start2=parseInt(i[3],10),i[4]===""?(a.start2--,a.length2=1):i[4]=="0"?a.length2=0:(a.start2--,a.length2=parseInt(i[4],10)),n++;n<r.length;){var s=r[n].charAt(0);try{var l=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+l)}if(s=="-")a.diffs.push(new P.Diff(J,l));else if(s=="+")a.diffs.push(new P.Diff(Q,l));else if(s==" ")a.diffs.push(new P.Diff(U,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};P.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};P.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
4
- `],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case Q:n="+";break;case J:n="-";break;case U:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
- `}return r.join("").replace(/%20/g," ")};Mt.exports=P;Mt.exports.diff_match_patch=P;Mt.exports.DIFF_DELETE=J;Mt.exports.DIFF_INSERT=Q;Mt.exports.DIFF_EQUAL=U});var Or=console,yn=Object.freeze({silent:0,error:1,warn:2,info:3}),As=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Sn=As;function Is(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(yn,t)?t:Sn}function Tn(e){return yn[Sn]>=yn[e]}function Ps(e,t={}){Or=e||console,t.level&&(Sn=Is(t.level))}function L(...e){Tn("info")&&(Or.log||(()=>{}))(...e)}function Be(...e){Tn("warn")&&(Or.warn||(()=>{}))(...e)}function ee(...e){Tn("error")&&(Or.error||(()=>{}))(...e)}var Jt=globalThis.DOMParser,qt=globalThis.XMLSerializer;function Rs(e={}){e.DOMParser&&(Jt=e.DOMParser),e.XMLSerializer&&(qt=e.XMLSerializer)}function Cs(e={}){if(!Jt&&globalThis.DOMParser&&(Jt=globalThis.DOMParser),!Jt)throw new Error("DOMParser is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Jt(e)}function de(){if(!qt&&globalThis.XMLSerializer&&(qt=globalThis.XMLSerializer),!qt)throw new Error("XMLSerializer is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new qt}function Do(e,t="text/xml"){let r=j(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Os(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function j(e,t="application/xml"){let r=[];if(typeof e!="string"||e.trim()==="")return{doc:null,error:{code:"PARSE_ERROR",message:"Input is not a non-empty XML string."},warnings:r};let n=(o,i)=>{let a=String(i||"XML parser diagnostic.");o==="fatalError"?ee("[XmlAdapter] XML fatal parse error:",a):(r.push(a),Be(`[XmlAdapter] XML ${o||"warning"}:`,a))};try{let i=Cs({onError:n}).parseFromString(e,t),a=Os(i);if(!i?.documentElement||a){let s=a?.textContent||"Could not parse XML input.";return ee("[XmlAdapter] XML parse error:",s),{doc:null,error:{code:"PARSE_ERROR",message:s},warnings:r}}return{doc:i,error:null,warnings:r}}catch(o){let i=o?.message||String(o||"Could not parse XML input.");return ee("[XmlAdapter] XML parse error:",i),{doc:null,error:{code:"PARSE_ERROR",message:i},warnings:r}}}function te(e){return de().serializeToString(e)}var zo=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Wo=zo(),Uo="Unknown";function ks(e){Wo=typeof e=="string"&&e.trim()?e.trim():zo()}function pe(){return Wo}function Ms(e){Uo=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function En(){return Uo}var _s=[{regex:/<b>(.+?)<\/b>/i,format:{bold:!0}},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0}},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0}},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0}},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0}},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0}},{regex:/<strike>(.+?)<\/strike>/i,format:{strikethrough:!0}},{regex:/<del>(.+?)<\/del>/i,format:{strikethrough:!0}},{regex:/&lt;b&gt;(.+?)&lt;\/b&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;strong&gt;(.+?)&lt;\/strong&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;i&gt;(.+?)&lt;\/i&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;em&gt;(.+?)&lt;\/em&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;u&gt;(.+?)&lt;\/u&gt;/i,format:{underline:!0},isEscaped:!0},{regex:/&lt;s&gt;(.+?)&lt;\/s&gt;/i,format:{strikethrough:!0},isEscaped:!0},{regex:/\*\*\*(.+?)\*\*\*/,format:{bold:!0,italic:!0}},{regex:/\*\*\+\+(.+?)\+\+\*\*/,format:{bold:!0,underline:!0}},{regex:/\*\*(.+?)\*\*/,format:{bold:!0}},{regex:/__(.+?)__/,format:{bold:!0}},{regex:/\+\+(.+?)\+\+/,format:{underline:!0}},{regex:/~~(.+?)~~/,format:{strikethrough:!0}},{regex:/~(.+?)~/,format:{strikethrough:!0}},{regex:/\*(?!\*)(.+?)\*(?!\*)/,format:{italic:!0}},{regex:/_(?!_)(.+?)_(?!_)/,format:{italic:!0}}];function Ie(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let s of _s){let l,c=s.regex.source||s.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),u="g"+(s.regex.ignoreCase?"i":""),f=new RegExp(c,u);for(;(l=f.exec(e))!==null;)n.push({start:l.index,end:l.index+l[0].length,fullMatch:l[0],innerText:s.isEscaped?Ls(l[1]):l[1],format:s.format}),l.index===f.lastIndex&&f.lastIndex++}n.sort((s,l)=>s.start-l.start||l.end-s.end);let o=[],i=0;for(let s of n)s.start>=i&&(o.push(s),i=s.end);let a=0;for(let s of o){r+=e.slice(a,s.start);let l=Ie(s.innerText),c=r.length;r+=l.cleanText;let u=r.length;t.push({start:c,end:u,format:s.format});for(let f of l.formatHints)t.push({start:c+f.start,end:c+f.end,format:f.format});a=s.end}return r+=e.slice(a),{cleanText:r,formatHints:t}}function Ke(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function An(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Ls(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var kr=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,jo=new RegExp(`^(\\s*)((?:${kr})\\s+)`),Ho=new RegExp(`^(\\s*)((?:${kr})\\s*)`),Bs=new RegExp(`^(\\s*)((?:${kr})\\s+)`,"m"),Fs=new RegExp(`^(\\s*)((?:${kr})\\s*)`,"m");function In(e){return typeof e!="string"?!1:e.includes(`
6
- `)&&Bs.test(e)}function Zt(e){return typeof e!="string"?!1:e.includes(`
7
- `)&&Fs.test(e.trim())}function Fe(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ho:jo;return e.match(n)}function je(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ho:jo;return e.replace(n,"")}function Vo(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Qt(e){let t=String(e||"").trim();return Vo(t)==="bullet"?"bullet":/^\d+(?:\.\d+)*\.?$/.test(t)||/^\(\d+\)$/.test(t)?"decimal":/^[ivxlcdm]+\.$/.test(t)?"lowerRoman":/^[IVXLCDM]{2,}\.$/.test(t)?"upperRoman":/^[a-z]\.$/.test(t)?"lowerAlpha":/^[A-Z]\.$/.test(t)?"upperAlpha":"decimal"}function $s(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function er(e,t={}){let r=Fe(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,i=Math.max(1,Number(t.indentSpaces)||2),a=Vo(n);return{line:String(e||""),text:je(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/i)),markerType:a,listType:a,numberingStyle:Qt(n),outlineLevel:a==="numbered"?$s(n):null}}var E="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var ke=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),D=Object.freeze({TEXT:"run",DELETION:"deletion",INSERTION:"insertion",HYPERLINK:"hyperlink",BOOKMARK:"bookmark",FIELD:"field",CONTAINER_START:"container_start",CONTAINER_END:"container_end",PARAGRAPH_START:"paragraph_start"}),Pt=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),Yo=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),G=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),be=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Ne(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var Pn=1e3,Go=2147483647,Ko=1e4,Xs=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Jo=new WeakMap;function Ds(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Xs.has(t)?!e.namespaceURI||e.namespaceURI===E||String(e.nodeName||"").startsWith("w:"):!1}function zs(e){let t=e?.getAttributeNS?.(E,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var we=class{constructor(t=Pn){this.startValue=Number.isInteger(t)&&t>=0?t:Pn,this.nextId=this.startValue,this.occupiedIds=new Set}seed(t){let r=-1,n=t?.nodeType===9?t.documentElement:t,o=n||null;for(;o;){if(Ds(o)){let a=zs(o);a!=null&&(this.occupiedIds.add(a),r=Math.max(r,a))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let i=Go-Ko;return this.nextId=r>=i?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Go-Ko;for(this.nextId>=t&&(this.nextId=this.startValue);this.occupiedIds.has(this.nextId);)this.nextId+=1,this.nextId>=t&&(this.nextId=this.startValue)}next(){this.advanceToAvailableId();let t=this.nextId;return this.occupiedIds.add(t),this.nextId+=1,t}},tr=new we;function Mr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof we&&Jo.set(r,t),t}function Ye(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Jo.get(t)||null}function nt(e,t=Pn){let r=new we(t);return r.seed(e),Mr(e,r),r}function qo(){return tr.next()}function _r(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():pe(),o=t instanceof we?t:Ye(t)||tr,i=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(i,r||"structural"),{id:i,author:n,date:_r()}}function rr(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():pe(),n=t instanceof we?t:Ye(t)||tr,o=_r(),i=n.next(),a=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(i,"del"),n._receiptCollector.recordRevision(a,"ins")),{deletionId:i,insertionId:a,author:r,date:o}}function Rt(e,t=tr){let r=t instanceof we?t:tr,n=r.seed(e);return Mr(e,r),n}function Zo(e,t){return e<t-1}function Ct(e,t,r){return Zo(t,r)?e+`
8
- `:e}function pt(e,t,r){return Zo(t,r)?e+1:e}function nr(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function ae(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function ce(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function re(e,t,r){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let n=e.getElementsByTagNameNS(t,r);return n.length>0?n[0]:null}function ve(e,t,r,n=`w:${r}`){let o=ce(e,t,r);return o.length>0?o:nr(e,n)}function ye(e,t,r,n=`w:${r}`){let o=re(e,t,r);return o||ae(e,n)}function ne(e){return ae(e,"parsererror")}function Rn(e){return Array.from(e?.childNodes||[])}function Qo(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Cn(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var On=0;function kt(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let i=o?{doc:o,error:null}:j(e,"application/xml"),a=i.doc;if(i.error||!a)return ee("OOXML parse error:",i.error?.message),{runModel:r,acceptedText:n,pPr:null,error:i.error};let s=ne(a);if(s)return ee("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=ce(a,E,"p");return l.length===0?(Be("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):ti(l,{includeParagraphBoundaries:!0})}catch(i){return ee("Error ingesting OOXML:",i),{runModel:r,acceptedText:n,pPr:null}}}function kn(e){return e?ti([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function or(e){let t=re(e,E,"pPr");if(!t)return null;let r=re(t,E,"numPr");if(!r)return null;let n=re(r,E,"numId"),o=re(r,E,"ilvl");if(!n)return null;let i=n.getAttribute("w:val");if(!/^\d+$/.test(i)||Number.parseInt(i,10)===0)return null;let a=i==="1"?"bullet":i==="2"?"numbered":"unknown";return{numId:i,ilvl:parseInt(o?.getAttribute("w:val")||"0",10),type:a}}function ti(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",i=0,a=null;for(let s=0;s<e.length;s++){let l=e[s],c=re(l,E,"pPr");s===0&&(a=c),n.push({kind:D.PARAGRAPH_START,pPrElement:c||null,startOffset:i,endOffset:i,text:""});let u=Ot(l,i,n);o+=u.text,i=o.length,r&&(o=Ct(o,s,e.length),i=pt(i,s,e.length))}return{runModel:n,acceptedText:o,pPr:a}}function Ot(e,t,r){let n=t,o="",i=Ws(r);for(let a of Rn(e)){if(Cn(a,E,"pPr")||Cn(a,E,"proofErr"))continue;let s=i.get(a.localName);if(!s)continue;let l=s(a,n);n=l.offset,o+=l.text}return{offset:n,text:o}}function Ws(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${On++}`,i=re(r,E,"sdtPr"),a=re(r,E,"sdtContent");e.push({kind:D.CONTAINER_START,containerKind:Pt.SDT,containerId:o,propertiesXml:i?te(i):"",startOffset:n,endOffset:n,text:""});let s=a?Ot(a,n,e):{offset:n,text:""};return e.push({kind:D.CONTAINER_END,containerKind:Pt.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${On++}`;e.push({kind:D.CONTAINER_START,containerKind:Pt.SMART_TAG,containerId:o,propertiesXml:Qo(r),startOffset:n,endOffset:n,text:""});let i=Ot(r,n,e);return e.push({kind:D.CONTAINER_END,containerKind:Pt.SMART_TAG,containerId:o,startOffset:i.offset,endOffset:i.offset,text:""}),i}),t.set("del",(r,n)=>{let o=ei(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=ei(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Ot(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:D.BOOKMARK,nodeXml:te(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:D.BOOKMARK,nodeXml:te(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:D.BOOKMARK,nodeXml:te(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Ot(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${On++}`,i=r.getAttribute("r:id")||"",a=r.getAttribute("w:anchor")||"";e.push({kind:D.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:i,anchor:a}),startOffset:n,endOffset:n,text:""});let s=Ot(r,n,e);return e.push({kind:D.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=Us(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Us(e,t){let r=ye(e,E,"rPr"),n=r?te(r):"",o="";for(let i of Rn(e)){let a=i.nodeName;a.endsWith(":t")||a==="t"?o+=i.textContent||"":a.endsWith(":br")||a==="br"||a.endsWith(":cr")||a==="cr"?o+=`
9
- `:a.endsWith(":tab")||a==="tab"?o+=" ":a.endsWith(":noBreakHyphen")||a==="noBreakHyphen"?o+="\u2011":(a.endsWith(":softHyphen")||a==="softHyphen")&&(o+="\xAD")}return o?{kind:D.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function ei(e,t){let r=e.getAttribute("w:author")||"",n="",o=ce(e,E,"delText");for(let a of o)n+=a.textContent||"";let i=ce(e,E,"r");for(let a of i){let s=ce(a,E,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:D.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:te(e)}:null}function _n(e){let t=re(e,E,"tblGrid"),r=t?ce(t,E,"gridCol"):[],n=ve(e,E,"tr"),o=n.length,i=n.reduce((u,f)=>{let m=ve(f,E,"tc");return Math.max(u,m.length)},0),a=r.length||i,s=Array.from({length:o},()=>Array.from({length:a},()=>null)),l=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],m=ve(f,E,"tc"),d=0;for(let p=0;p<m.length;p++){let h=m[p],w=re(h,E,"tcPr");for(;d<a&&s[u][d]!==null;)d++;if(d>=a)break;let b=w?re(w,E,"gridSpan")||ae(w,"w:gridSpan"):null,g=parseInt(b?.getAttribute("w:val")||"1",10),x=w?re(w,E,"vMerge")||ae(w,"w:vMerge"):null,v=x?.getAttribute("w:val"),N=x!==null,S;if(N&&v!=="restart"){let y=c.get(d);y?(y.cell.rowSpan++,S={gridRow:u,gridCol:d,rowSpan:0,colSpan:g,tcNode:h,blocks:[],tcPrXml:Mn(w),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:y.cell}):S=js(u,d,g,h,w)}else{let y=ri(h);if(S={gridRow:u,gridCol:d,rowSpan:1,colSpan:g,tcNode:h,blocks:y,tcPrXml:Mn(w),isMergeOrigin:N&&v==="restart",isMergeContinuation:!1,getText:()=>y.map(T=>T.acceptedText).join(`
10
- `)},N&&v==="restart")for(let T=0;T<g;T++)c.set(d+T,{originRow:u,cell:S});else for(let T=0;T<g;T++)c.delete(d+T)}for(let y=0;y<g;y++){let T=d+y;T<a&&(s[u][T]=S,l.set(`${u},${T}`,S))}d+=g}}return{rowCount:o,colCount:a,grid:s,cellMap:l,tblPrXml:Hs(e),tblGridXml:Vs(e),trPrList:Array.from(n).map(u=>Gs(u))}}function js(e,t,r,n,o){let i=ri(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:i,tcPrXml:Mn(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>i.map(a=>a.acceptedText).join(`
11
- `)}}function ri(e){return ve(e,E,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:i}=kn(r);return{runModel:n,acceptedText:o,pPr:i}})}function Mn(e){return e?te(e):"<w:tcPr/>"}function Hs(e){let t=re(e,E,"tblPr");return t?te(t):"<w:tblPr/>"}function Vs(e){let t=re(e,E,"tblGrid");return t?te(t):"<w:tblGrid/>"}function Gs(e){let t=re(e,E,"trPr");return t?te(t):"<w:trPr/>"}var ii=Xo(Ln(),1);var Ks=65536,Lr=262144,Br=1,Fr=55296-Br,Ys=8192,Js=Fr+Ys,Bn=class extends Error{constructor(t=Lr){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function ai(e){return e?.code==="DIFF_TOKEN_LIMIT"}function Fn(e={}){let t=e.diffTimeoutSeconds??0;if(!Number.isFinite(t)||t<0)throw new TypeError("diffTimeoutSeconds must be a finite non-negative number.");let r=new ii.diff_match_patch;return r.Diff_Timeout=t,r}function ni(e){let t=[],r=e.match(/^\s+/);r&&t.push(r[0]);let n=/(\S+)(\s*)/g;n.lastIndex=r?.[0].length||0;let o;for(;(o=n.exec(e))!==null;)o[1]&&t.push(o[1]),o[2]&&t.push(o[2]);return t}function qs(e,t,r={}){let n=[],o=new Map,i=r.maxTokens??Lr;if(!Number.isInteger(i)||i<1||i>Lr)throw new RangeError(`maxTokens must be an integer from 1 to ${Lr}.`);function a(f){let m="",d=[];for(let p of f){let h=o.get(p);if(h===void 0){if(n.length>=i)throw new Bn(i);h=n.length,n.push(p),o.set(p,h)}d.push(h),m+=String.fromCodePoint(Ks+h)}return{chars:m,tokenIds:d}}let s=ni(e),l=ni(t),c=a(s),u=a(l);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function Zs(e){let t=e<Fr?Br+e:57344+(e-Fr);return String.fromCharCode(t)}function Qs(e){if(e>=Br&&e<55296)return e-Br;if(e>=57344&&e<=65535)return Fr+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function oi(e){let t="";for(let r of e)t+=Zs(r);return t}function el(e,t){return e.map(([r,n])=>{let o=[];for(let i=0;i<n.length;i++){let a=Qs(n.charCodeAt(i));if(a>=t.length)throw new RangeError(`BMP diff token ${a} has no mapping.`);o.push(t[a])}return[r,o.join("")]})}function tl(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let i=0;for(;i<o-n&&e[e.length-1-i]===t[t.length-1-i];)i++;let a=u=>u.map(f=>r[f]).join(""),s=[];n&&s.push([0,a(e.slice(0,n))]);let l=e.slice(n,e.length-i),c=t.slice(n,t.length-i);return l.length&&s.push([-1,a(l)]),c.length&&s.push([1,a(c)]),i&&s.push([0,a(e.slice(e.length-i))]),s}function ir(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:o,tokenIds1:i,tokenIds2:a}=qs(e,t,r);if(o.length>Js)return tl(i,a,o);let s=Fn(r),l=s.diff_main(oi(i),oi(a));return n&&s.diff_cleanupSemantic(l),el(l,o)}function si(e,t,r={}){return e===t?[[0,e]]:Fn(r).diff_main(e,t)}function li(e,t){if(e===t)return[[0,e]];if(!e)return[[1,t]];let r=0;for(let o=0;o<t.length&&r<e.length;o++)t[o]===e[r]&&r++;if(r!==e.length)return null;let n=Fn().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function $r(e,t,r={}){if(e===t)return[{type:ke.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:ke.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:ke.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=ir(e,t,r),o=[],i=0;for(let[a,s]of n)a===0?(o.push({type:ke.EQUAL,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===-1?(o.push({type:ke.DELETE,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===1&&o.push({type:ke.INSERT,startOffset:i,endOffset:i,text:s});return o}var rl=/\s+xmlns:[^=]+="[^"]*"/g;function Xr(e,t){let r=ll(t),n=[],o=0;for(let i of e){if(i.kind!==D.TEXT&&i.kind!==D.HYPERLINK){n.push(i);continue}for(;o<r.length&&r[o]<=i.startOffset;)o++;let a=o,s=i.startOffset,l=!1;for(;a<r.length;){let c=r[a];if(c>=i.endOffset)break;c>s&&(l=!0,n.push({...i,text:i.text.slice(s-i.startOffset,c-i.startOffset),startOffset:s,endOffset:c}),s=c),a++}if(o=a,!l){n.push(i);continue}n.push({...i,text:i.text.slice(s-i.startOffset),startOffset:s,endOffset:i.endOffset})}return n}function Dr(e,t,r){let{generateRedlines:n,author:o}=r,i=[],a=new Set,s=cl(t),l=al(e),c=sl(s.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let m of e){if(m.kind===D.CONTAINER_START){u.containerStack.push(m.containerId),i.push({...m});continue}if(m.kind===D.CONTAINER_END){u.containerStack.pop(),i.push({...m});continue}if(m.kind===D.PARAGRAPH_START){u.currentParagraphPPrXml=typeof m.pPrXml=="string"?m.pPrXml:"",u.currentParagraphPPrElement=m.pPrElement||null,i.push({...m}),u.lastParagraphStartIndex=i.length-1;continue}if(m.kind===D.BOOKMARK||m.kind===D.DELETION){i.push({...m});continue}let d=c(m.startOffset,m.endOffset),p=s.insertOpsByStartOffset.get(m.startOffset)||[];for(let h of p)a.has(h)||(a.add(h),nl({insertOp:h,splitModel:e,styleLookup:l,patchedModel:i,state:u,options:r,generateRedlines:n,author:o}));if(!d||d.type===ke.EQUAL){i.push({...m,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}d.type===ke.DELETE&&n&&i.push({...m,kind:D.DELETION,author:o,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(m=>m.endOffset)):0;for(let m of s.sortedInsertOps){if(m.startOffset<f||a.has(m))continue;let d=e[e.length-1];i.push({kind:n?D.INSERTION:D.TEXT,text:m.text,rPrXml:d?.rPrXml||"",startOffset:m.startOffset,endOffset:m.startOffset+m.text.length,author:n?o:void 0})}return i}function nl(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:i,generateRedlines:a,author:s}=e,l=t.text.split(`
12
- `),c=il(r,t.startOffset,t.text);for(let u=0;u<l.length;u++){let f=ol(l[u],i.numberingService,o),m=f.lineText;if(u>0){let d=ci(o);f.isListLine&&f.numId&&(d=i.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:D.PARAGRAPH_START,pPrXml:d,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&o.lastParagraphStartIndex>=0){let d=i.numberingService.buildListPPr(f.numId,f.ilvl);n[o.lastParagraphStartIndex].pPrXml=d,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=d,o.currentParagraphPPrElement=null,L(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(m.length>0||u>0)&&n.push({kind:a?D.INSERTION:D.TEXT,text:m,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+m.length,author:a?s:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function ol(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=Fe(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),i=t.detectNumberingFormat(o),a=e.match(/^(\s*)/),s=a?a[1].length:0,l=s>=4?4:2,c=Math.floor(s/l),u=ci(r),f=je(e,{allowZeroSpaceAfterMarker:!0}),m=u.match(/w:numId w:val="(\d+)"/),d=u.match(/w:ilvl w:val="(\d+)"/),p=m?m[1]:null,h=d?parseInt(d[1],10):0,w=t.getOrCreateNumId({type:i.format},{numId:p,type:"unknown"}),b=i.format==="outline"?Math.min(8,i.depth):Math.min(8,c+h);return{lineText:f,isListLine:!0,numId:w,ilvl:b}}function ci(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=te(e.currentParagraphPPrElement).replace(rl,""),e.currentParagraphPPrXml):""}function il(e,t,r){let n=e.findRunBefore(t),o=e.findRunAfter(t);return!n&&!o?null:n?o?r&&r.endsWith(" ")?o:(r&&r.startsWith(" "),n):n:o}function al(e){let t=e.filter(o=>o.kind===D.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let i=0,a=n.length-1,s=-1;for(;i<=a;){let l=i+a>>1;n[l]<=o?(s=l,i=l+1):a=l-1}return s>=0?t[s]:null},findRunAfter(o){let i=0,a=r.length-1,s=-1;for(;i<=a;){let l=i+a>>1;r[l]>=o?(s=l,a=l-1):i=l+1}return s>=0?t[s]:null}}}function sl(e){let t=0;return(r,n)=>{for(;t<e.length&&e[t].endOffset<=r;)t++;let o=e[t];return o&&o.startOffset<=r&&o.endOffset>=n?o:null}}function ll(e){let t=new Set;for(let r of e)t.add(r.startOffset),t.add(r.endOffset);return Array.from(t).sort((r,n)=>r-n)}function cl(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===ke.INSERT){t.has(o.startOffset)||t.set(o.startOffset,[]),t.get(o.startOffset).push(o),n.push(o);continue}r.push(o)}return r.sort((o,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),n.sort((o,i)=>o.startOffset-i.startOffset||o.endOffset-i.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var di="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ul="http://schemas.openxmlformats.org/officeDocument/2006/relationships",fl="http://schemas.microsoft.com/office/2006/xmlPackage",ui="http://schemas.openxmlformats.org/package/2006/relationships",ml='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',fi='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var dl=`
13
- <w:numbering xmlns:w="${di}">
1
+ var Ou=Object.create;var Ji=Object.defineProperty;var _u=Object.getOwnPropertyDescriptor;var ku=Object.getOwnPropertyNames;var Mu=Object.getPrototypeOf,Lu=Object.prototype.hasOwnProperty;var Bu=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Du=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ku(t))!Lu.call(e,a)&&a!==r&&Ji(e,a,{get:()=>t[a],enumerable:!(n=_u(t,a))||n.enumerable});return e};var Qi=(e,t,r)=>(r=e!=null?Ou(Mu(e)):{},Du(t||!e||!e.__esModule?Ji(r,"default",{value:e,enumerable:!0}):r,e));var Ro=Bu((sh,$r)=>{var F=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},fe=-1,me=1,Q=0;F.Diff=function(e,t){return[e,t]};F.prototype.diff_main=function(e,t,r,n){typeof n>"u"&&(this.Diff_Timeout<=0?n=Number.MAX_VALUE:n=new Date().getTime()+this.Diff_Timeout*1e3);var a=n;if(e==null||t==null)throw new Error("Null input. (diff_main)");if(e==t)return e?[new F.Diff(Q,e)]:[];typeof r>"u"&&(r=!0);var o=r,i=this.diff_commonPrefix(e,t),l=e.substring(0,i);e=e.substring(i),t=t.substring(i),i=this.diff_commonSuffix(e,t);var s=e.substring(e.length-i);e=e.substring(0,e.length-i),t=t.substring(0,t.length-i);var c=this.diff_compute_(e,t,o,a);return l&&c.unshift(new F.Diff(Q,l)),s&&c.push(new F.Diff(Q,s)),this.diff_cleanupMerge(c),c};F.prototype.diff_compute_=function(e,t,r,n){var a;if(!e)return[new F.Diff(me,t)];if(!t)return[new F.Diff(fe,e)];var o=e.length>t.length?e:t,i=e.length>t.length?t:e,l=o.indexOf(i);if(l!=-1)return a=[new F.Diff(me,o.substring(0,l)),new F.Diff(Q,i),new F.Diff(me,o.substring(l+i.length))],e.length>t.length&&(a[0][0]=a[2][0]=fe),a;if(i.length==1)return[new F.Diff(fe,e),new F.Diff(me,t)];var s=this.diff_halfMatch_(e,t);if(s){var c=s[0],u=s[1],f=s[2],d=s[3],m=s[4],p=this.diff_main(c,f,r,n),h=this.diff_main(u,d,r,n);return p.concat([new F.Diff(Q,m)],h)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};F.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var a=n.lineArray,o=this.diff_main(e,t,!1,r);this.diff_charsToLines_(o,a),this.diff_cleanupSemantic(o),o.push(new F.Diff(Q,""));for(var i=0,l=0,s=0,c="",u="";i<o.length;){switch(o[i][0]){case me:s++,u+=o[i][1];break;case fe:l++,c+=o[i][1];break;case Q:if(l>=1&&s>=1){o.splice(i-l-s,l+s),i=i-l-s;for(var f=this.diff_main(c,u,!1,r),d=f.length-1;d>=0;d--)o.splice(i,0,f[d]);i=i+f.length}s=0,l=0,c="",u="";break}i++}return o.pop(),o};F.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,a=t.length,o=Math.ceil((n+a)/2),i=o,l=2*o,s=new Array(l),c=new Array(l),u=0;u<l;u++)s[u]=-1,c[u]=-1;s[i+1]=0,c[i+1]=0;for(var f=n-a,d=f%2!=0,m=0,p=0,h=0,g=0,v=0;v<o&&!(new Date().getTime()>r);v++){for(var w=-v+m;w<=v-p;w+=2){var y=i+w,x;w==-v||w!=v&&s[y-1]<s[y+1]?x=s[y+1]:x=s[y-1]+1;for(var b=x-w;x<n&&b<a&&e.charAt(x)==t.charAt(b);)x++,b++;if(s[y]=x,x>n)p+=2;else if(b>a)m+=2;else if(d){var I=i+f-w;if(I>=0&&I<l&&c[I]!=-1){var N=n-c[I];if(x>=N)return this.diff_bisectSplit_(e,t,x,b,r)}}}for(var T=-v+h;T<=v-g;T+=2){var I=i+T,N;T==-v||T!=v&&c[I-1]<c[I+1]?N=c[I+1]:N=c[I-1]+1;for(var S=N-T;N<n&&S<a&&e.charAt(n-N-1)==t.charAt(a-S-1);)N++,S++;if(c[I]=N,N>n)g+=2;else if(S>a)h+=2;else if(!d){var y=i+f-T;if(y>=0&&y<l&&s[y]!=-1){var x=s[y],b=i+x-y;if(N=n-N,x>=N)return this.diff_bisectSplit_(e,t,x,b,r)}}}}return[new F.Diff(fe,e),new F.Diff(me,t)]};F.prototype.diff_bisectSplit_=function(e,t,r,n,a){var o=e.substring(0,r),i=t.substring(0,n),l=e.substring(r),s=t.substring(n),c=this.diff_main(o,i,!1,a),u=this.diff_main(l,s,!1,a);return c.concat(u)};F.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function a(s){for(var c="",u=0,f=-1,d=r.length;f<s.length-1;){f=s.indexOf(`
2
+ `,u),f==-1&&(f=s.length-1);var m=s.substring(u,f+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==o&&(m=s.substring(u),f=s.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),u=f+1}return c}var o=4e4,i=a(e);o=65535;var l=a(t);return{chars1:i,chars2:l,lineArray:r}};F.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],a=[],o=0;o<n.length;o++)a[o]=t[n.charCodeAt(o)];e[r][1]=a.join("")}};F.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),a=n,o=0;r<a;)e.substring(o,a)==t.substring(o,a)?(r=a,o=r):n=a,a=Math.floor((n-r)/2+r);return a};F.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),a=n,o=0;r<a;)e.substring(e.length-a,e.length-o)==t.substring(t.length-a,t.length-o)?(r=a,o=r):n=a,a=Math.floor((n-r)/2+r);return a};F.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var a=Math.min(r,n);if(e==t)return a;for(var o=0,i=1;;){var l=e.substring(a-i),s=t.indexOf(l);if(s==-1)return o;i+=s,(s==0||e.substring(a-i)==t.substring(0,i))&&(o=i,i++)}};F.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var a=this;function o(p,h,g){for(var v=p.substring(g,g+Math.floor(p.length/4)),w=-1,y="",x,b,I,N;(w=h.indexOf(v,w+1))!=-1;){var T=a.diff_commonPrefix(p.substring(g),h.substring(w)),S=a.diff_commonSuffix(p.substring(0,g),h.substring(0,w));y.length<S+T&&(y=h.substring(w-S,w)+h.substring(w,w+T),x=p.substring(0,g-S),b=p.substring(g+T),I=h.substring(0,w-S),N=h.substring(w+T))}return y.length*2>=p.length?[x,b,I,N,y]:null}var i=o(r,n,Math.ceil(r.length/4)),l=o(r,n,Math.ceil(r.length/2)),s;if(!i&&!l)return null;l?i?s=i[4].length>l[4].length?i:l:s=l:s=i;var c,u,f,d;e.length>t.length?(c=s[0],u=s[1],f=s[2],d=s[3]):(f=s[0],d=s[1],c=s[2],u=s[3]);var m=s[4];return[c,u,f,d,m]};F.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,a=null,o=0,i=0,l=0,s=0,c=0;o<e.length;)e[o][0]==Q?(r[n++]=o,i=s,l=c,s=0,c=0,a=e[o][1]):(e[o][0]==me?s+=e[o][1].length:c+=e[o][1].length,a&&a.length<=Math.max(i,l)&&a.length<=Math.max(s,c)&&(e.splice(r[n-1],0,new F.Diff(fe,a)),e[r[n-1]+1][0]=me,n--,n--,o=n>0?r[n-1]:-1,i=0,l=0,s=0,c=0,a=null,t=!0)),o++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),o=1;o<e.length;){if(e[o-1][0]==fe&&e[o][0]==me){var u=e[o-1][1],f=e[o][1],d=this.diff_commonOverlap_(u,f),m=this.diff_commonOverlap_(f,u);d>=m?(d>=u.length/2||d>=f.length/2)&&(e.splice(o,0,new F.Diff(Q,f.substring(0,d))),e[o-1][1]=u.substring(0,u.length-d),e[o+1][1]=f.substring(d),o++):(m>=u.length/2||m>=f.length/2)&&(e.splice(o,0,new F.Diff(Q,u.substring(0,m))),e[o-1][0]=me,e[o-1][1]=f.substring(0,f.length-m),e[o+1][0]=fe,e[o+1][1]=u.substring(m),o++),o++}o++}};F.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var h=m.charAt(m.length-1),g=p.charAt(0),v=h.match(F.nonAlphaNumericRegex_),w=g.match(F.nonAlphaNumericRegex_),y=v&&h.match(F.whitespaceRegex_),x=w&&g.match(F.whitespaceRegex_),b=y&&h.match(F.linebreakRegex_),I=x&&g.match(F.linebreakRegex_),N=b&&m.match(F.blanklineEndRegex_),T=I&&p.match(F.blanklineStartRegex_);return N||T?5:b||I?4:v&&!y&&x?3:y||x?2:v||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==Q&&e[r+1][0]==Q){var n=e[r-1][1],a=e[r][1],o=e[r+1][1],i=this.diff_commonSuffix(n,a);if(i){var l=a.substring(a.length-i);n=n.substring(0,n.length-i),a=l+a.substring(0,a.length-i),o=l+o}for(var s=n,c=a,u=o,f=t(n,a)+t(a,o);a.charAt(0)===o.charAt(0);){n+=a.charAt(0),a=a.substring(1)+o.charAt(0),o=o.substring(1);var d=t(n,a)+t(a,o);d>=f&&(f=d,s=n,c=a,u=o)}e[r-1][1]!=s&&(s?e[r-1][1]=s:(e.splice(r-1,1),r--),e[r][1]=c,u?e[r+1][1]=u:(e.splice(r+1,1),r--))}r++}};F.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;F.whitespaceRegex_=/\s/;F.linebreakRegex_=/[\r\n]/;F.blanklineEndRegex_=/\n\r?\n$/;F.blanklineStartRegex_=/^\r?\n\r?\n/;F.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,a=null,o=0,i=!1,l=!1,s=!1,c=!1;o<e.length;)e[o][0]==Q?(e[o][1].length<this.Diff_EditCost&&(s||c)?(r[n++]=o,i=s,l=c,a=e[o][1]):(n=0,a=null),s=c=!1):(e[o][0]==fe?c=!0:s=!0,a&&(i&&l&&s&&c||a.length<this.Diff_EditCost/2&&i+l+s+c==3)&&(e.splice(r[n-1],0,new F.Diff(fe,a)),e[r[n-1]+1][0]=me,n--,a=null,i&&l?(s=c=!0,n=0):(n--,o=n>0?r[n-1]:-1,s=c=!1),t=!0)),o++;t&&this.diff_cleanupMerge(e)};F.prototype.diff_cleanupMerge=function(e){e.push(new F.Diff(Q,""));for(var t=0,r=0,n=0,a="",o="",i;t<e.length;)switch(e[t][0]){case me:n++,o+=e[t][1],t++;break;case fe:r++,a+=e[t][1],t++;break;case Q:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(o,a),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==Q?e[t-r-n-1][1]+=o.substring(0,i):(e.splice(0,0,new F.Diff(Q,o.substring(0,i))),t++),o=o.substring(i),a=a.substring(i)),i=this.diff_commonSuffix(o,a),i!==0&&(e[t][1]=o.substring(o.length-i)+e[t][1],o=o.substring(0,o.length-i),a=a.substring(0,a.length-i))),t-=r+n,e.splice(t,r+n),a.length&&(e.splice(t,0,new F.Diff(fe,a)),t++),o.length&&(e.splice(t,0,new F.Diff(me,o)),t++),t++):t!==0&&e[t-1][0]==Q?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,a="",o="";break}e[e.length-1][1]===""&&e.pop();var l=!1;for(t=1;t<e.length-1;)e[t-1][0]==Q&&e[t+1][0]==Q&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),l=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),l=!0)),t++;l&&this.diff_cleanupMerge(e)};F.prototype.diff_xIndex=function(e,t){var r=0,n=0,a=0,o=0,i;for(i=0;i<e.length&&(e[i][0]!==me&&(r+=e[i][1].length),e[i][0]!==fe&&(n+=e[i][1].length),!(r>t));i++)a=r,o=n;return e.length!=i&&e[i][0]===fe?o:o+(t-a)};F.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,a=/>/g,o=/\n/g,i=0;i<e.length;i++){var l=e[i][0],s=e[i][1],c=s.replace(r,"&amp;").replace(n,"&lt;").replace(a,"&gt;").replace(o,"&para;<br>");switch(l){case me:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case fe:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case Q:t[i]="<span>"+c+"</span>";break}}return t.join("")};F.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==me&&(t[r]=e[r][1]);return t.join("")};F.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==fe&&(t[r]=e[r][1]);return t.join("")};F.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,a=0;a<e.length;a++){var o=e[a][0],i=e[a][1];switch(o){case me:r+=i.length;break;case fe:n+=i.length;break;case Q:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};F.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case me:t[r]="+"+encodeURI(e[r][1]);break;case fe:t[r]="-"+e[r][1].length;break;case Q:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};F.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,a=0,o=t.split(/\t/g),i=0;i<o.length;i++){var l=o[i].substring(1);switch(o[i].charAt(0)){case"+":try{r[n++]=new F.Diff(me,decodeURI(l))}catch{throw new Error("Illegal escape in diff_fromDelta: "+l)}break;case"-":case"=":var s=parseInt(l,10);if(isNaN(s)||s<0)throw new Error("Invalid number in diff_fromDelta: "+l);var c=e.substring(a,a+=s);o[i].charAt(0)=="="?r[n++]=new F.Diff(Q,c):r[n++]=new F.Diff(fe,c);break;default:if(o[i])throw new Error("Invalid diff operation in diff_fromDelta: "+o[i])}}if(a!=e.length)throw new Error("Delta length ("+a+") does not equal source text length ("+e.length+").");return r};F.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};F.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),a=this;function o(x,b){var I=x/t.length,N=Math.abs(r-b);return a.Match_Distance?I+N/a.Match_Distance:N?1:I}var i=this.Match_Threshold,l=e.indexOf(t,r);l!=-1&&(i=Math.min(o(0,l),i),l=e.lastIndexOf(t,r+t.length),l!=-1&&(i=Math.min(o(0,l),i)));var s=1<<t.length-1;l=-1;for(var c,u,f=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,u=f;c<u;)o(m,r+u)<=i?c=u:f=u,u=Math.floor((f-c)/2+c);f=u;var p=Math.max(1,r-u+1),h=Math.min(r+u,e.length)+t.length,g=Array(h+2);g[h+1]=(1<<m)-1;for(var v=h;v>=p;v--){var w=n[e.charAt(v-1)];if(m===0?g[v]=(g[v+1]<<1|1)&w:g[v]=(g[v+1]<<1|1)&w|((d[v+1]|d[v])<<1|1)|d[v+1],g[v]&s){var y=o(m,v-1);if(y<=i)if(i=y,l=v-1,l>r)p=Math.max(1,2*r-l);else break}}if(o(m+1,r)>i)break;d=g}return l};F.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};F.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var a=t.substring(e.start2-n,e.start2);a&&e.diffs.unshift(new F.Diff(Q,a));var o=t.substring(e.start2+e.length1,e.start2+e.length1+n);o&&e.diffs.push(new F.Diff(Q,o)),e.start1-=a.length,e.start2-=a.length,e.length1+=a.length+o.length,e.length2+=a.length+o.length}};F.prototype.patch_make=function(e,t,r){var n,a;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,a=this.diff_main(n,t,!0),a.length>2&&(this.diff_cleanupSemantic(a),this.diff_cleanupEfficiency(a));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")a=e,n=this.diff_text1(a);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,a=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,a=r;else throw new Error("Unknown call format to patch_make.");if(a.length===0)return[];for(var o=[],i=new F.patch_obj,l=0,s=0,c=0,u=n,f=n,d=0;d<a.length;d++){var m=a[d][0],p=a[d][1];switch(!l&&m!==Q&&(i.start1=s,i.start2=c),m){case me:i.diffs[l++]=a[d],i.length2+=p.length,f=f.substring(0,c)+p+f.substring(c);break;case fe:i.length1+=p.length,i.diffs[l++]=a[d],f=f.substring(0,c)+f.substring(c+p.length);break;case Q:p.length<=2*this.Patch_Margin&&l&&a.length!=d+1?(i.diffs[l++]=a[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&l&&(this.patch_addContext_(i,u),o.push(i),i=new F.patch_obj,l=0,u=f,s=c);break}m!==me&&(s+=p.length),m!==fe&&(c+=p.length)}return l&&(this.patch_addContext_(i,u),o.push(i)),o};F.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],a=new F.patch_obj;a.diffs=[];for(var o=0;o<n.diffs.length;o++)a.diffs[o]=new F.Diff(n.diffs[o][0],n.diffs[o][1]);a.start1=n.start1,a.start2=n.start2,a.length1=n.length1,a.length2=n.length2,t[r]=a}return t};F.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,a=[],o=0;o<e.length;o++){var i=e[o].start2+n,l=this.diff_text1(e[o].diffs),s,c=-1;if(l.length>this.Match_MaxBits?(s=this.match_main(t,l.substring(0,this.Match_MaxBits),i),s!=-1&&(c=this.match_main(t,l.substring(l.length-this.Match_MaxBits),i+l.length-this.Match_MaxBits),(c==-1||s>=c)&&(s=-1))):s=this.match_main(t,l,i),s==-1)a[o]=!1,n-=e[o].length2-e[o].length1;else{a[o]=!0,n=s-i;var u;if(c==-1?u=t.substring(s,s+l.length):u=t.substring(s,c+this.Match_MaxBits),l==u)t=t.substring(0,s)+this.diff_text2(e[o].diffs)+t.substring(s+l.length);else{var f=this.diff_main(l,u,!1);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(f)/l.length>this.Patch_DeleteThreshold)a[o]=!1;else{this.diff_cleanupSemanticLossless(f);for(var d=0,m,p=0;p<e[o].diffs.length;p++){var h=e[o].diffs[p];h[0]!==Q&&(m=this.diff_xIndex(f,d)),h[0]===me?t=t.substring(0,s+m)+h[1]+t.substring(s+m):h[0]===fe&&(t=t.substring(0,s+m)+t.substring(s+this.diff_xIndex(f,d+h[1].length))),h[0]!==fe&&(d+=h[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,a]};F.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var a=e[0],o=a.diffs;if(o.length==0||o[0][0]!=Q)o.unshift(new F.Diff(Q,r)),a.start1-=t,a.start2-=t,a.length1+=t,a.length2+=t;else if(t>o[0][1].length){var i=t-o[0][1].length;o[0][1]=r.substring(o[0][1].length)+o[0][1],a.start1-=i,a.start2-=i,a.length1+=i,a.length2+=i}if(a=e[e.length-1],o=a.diffs,o.length==0||o[o.length-1][0]!=Q)o.push(new F.Diff(Q,r)),a.length1+=t,a.length2+=t;else if(t>o[o.length-1][1].length){var i=t-o[o.length-1][1].length;o[o.length-1][1]+=r.substring(0,i),a.length1+=i,a.length2+=i}return r};F.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var a=n.start1,o=n.start2,i="";n.diffs.length!==0;){var l=new F.patch_obj,s=!0;for(l.start1=a-i.length,l.start2=o-i.length,i!==""&&(l.length1=l.length2=i.length,l.diffs.push(new F.Diff(Q,i)));n.diffs.length!==0&&l.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],u=n.diffs[0][1];c===me?(l.length2+=u.length,o+=u.length,l.diffs.push(n.diffs.shift()),s=!1):c===fe&&l.diffs.length==1&&l.diffs[0][0]==Q&&u.length>2*t?(l.length1+=u.length,a+=u.length,s=!1,l.diffs.push(new F.Diff(c,u)),n.diffs.shift()):(u=u.substring(0,t-l.length1-this.Patch_Margin),l.length1+=u.length,a+=u.length,c===Q?(l.length2+=u.length,o+=u.length):s=!1,l.diffs.push(new F.Diff(c,u)),u==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(u.length))}i=this.diff_text2(l.diffs),i=i.substring(i.length-this.Patch_Margin);var f=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);f!==""&&(l.length1+=f.length,l.length2+=f.length,l.diffs.length!==0&&l.diffs[l.diffs.length-1][0]===Q?l.diffs[l.diffs.length-1][1]+=f:l.diffs.push(new F.Diff(Q,f))),s||e.splice(++r,0,l)}}};F.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};F.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
3
+ `),n=0,a=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var o=r[n].match(a);if(!o)throw new Error("Invalid patch string: "+r[n]);var i=new F.patch_obj;for(t.push(i),i.start1=parseInt(o[1],10),o[2]===""?(i.start1--,i.length1=1):o[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(o[2],10)),i.start2=parseInt(o[3],10),o[4]===""?(i.start2--,i.length2=1):o[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(o[4],10)),n++;n<r.length;){var l=r[n].charAt(0);try{var s=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+s)}if(l=="-")i.diffs.push(new F.Diff(fe,s));else if(l=="+")i.diffs.push(new F.Diff(me,s));else if(l==" ")i.diffs.push(new F.Diff(Q,s));else{if(l=="@")break;if(l!=="")throw new Error('Invalid patch mode "'+l+'" in: '+s)}n++}}return t};F.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};F.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
4
+ `],n,a=0;a<this.diffs.length;a++){switch(this.diffs[a][0]){case me:n="+";break;case fe:n="-";break;case Q:n=" ";break}r[a+1]=n+encodeURI(this.diffs[a][1])+`
5
+ `}return r.join("").replace(/%20/g," ")};$r.exports=F;$r.exports.diff_match_patch=F;$r.exports.DIFF_DELETE=fe;$r.exports.DIFF_INSERT=me;$r.exports.DIFF_EQUAL=Q});import{DOMParser as zu,XMLSerializer as Xu}from"@xmldom/xmldom";var sa=console,go=Object.freeze({silent:0,error:1,warn:2,info:3}),Fu=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",ho=Fu;function $u(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(go,t)?t:ho}function wo(e){return go[ho]>=go[e]}function Uu(e,t={}){sa=e||console,t.level&&(ho=$u(t.level))}function V(...e){wo("info")&&(sa.log||(()=>{}))(...e)}function mt(...e){wo("warn")&&(sa.warn||(()=>{}))(...e)}function ye(...e){wo("error")&&(sa.error||(()=>{}))(...e)}var es=null,ts=null;function Vu(e={}){"DOMParser"in e&&(es=e.DOMParser),"XMLSerializer"in e&&(ts=e.XMLSerializer)}function Wu(){return es||globalThis.DOMParser||zu}function ju(){return ts||globalThis.XMLSerializer||Xu}function Ku(e={}){let t=Wu();if(!t)throw new Error("DOMParser is not configured and no fallback XML parser is available.");return new t(e)}function ce(){let e=ju();if(!e)throw new Error("XMLSerializer is not configured and no fallback XML serializer is available.");return new e}function rs(e,t="text/xml"){let r=j(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Hu(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function j(e,t="application/xml"){let r=[];if(typeof e!="string"||e.trim()==="")return{doc:null,error:{code:"PARSE_ERROR",message:"Input is not a non-empty XML string."},warnings:r};let n=(a,o)=>{let i=String(o||"XML parser diagnostic.");a==="fatalError"?ye("[XmlAdapter] XML fatal parse error:",i):(r.push(i),mt(`[XmlAdapter] XML ${a||"warning"}:`,i))};try{let o=Ku({onError:n}).parseFromString(e,t),i=Hu(o);if(!o?.documentElement||i){let l=i?.textContent||"Could not parse XML input.";return ye("[XmlAdapter] XML parse error:",l),{doc:null,error:{code:"PARSE_ERROR",message:l},warnings:r}}return{doc:o,error:null,warnings:r}}catch(a){let o=a?.message||String(a||"Could not parse XML input.");return ye("[XmlAdapter] XML parse error:",o),{doc:null,error:{code:"PARSE_ERROR",message:o},warnings:r}}}function xe(e){return ce().serializeToString(e)}var ns=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",as=ns(),os="Unknown";function Gu(e){as=typeof e=="string"&&e.trim()?e.trim():ns()}function re(){return as}function qu(e){os=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function vo(){return os}var Yu=[{regex:/<b>(.+?)<\/b>/i,format:{bold:!0}},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0}},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0}},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0}},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0}},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0}},{regex:/<strike>(.+?)<\/strike>/i,format:{strikethrough:!0}},{regex:/<del>(.+?)<\/del>/i,format:{strikethrough:!0}},{regex:/&lt;b&gt;(.+?)&lt;\/b&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;strong&gt;(.+?)&lt;\/strong&gt;/i,format:{bold:!0},isEscaped:!0},{regex:/&lt;i&gt;(.+?)&lt;\/i&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;em&gt;(.+?)&lt;\/em&gt;/i,format:{italic:!0},isEscaped:!0},{regex:/&lt;u&gt;(.+?)&lt;\/u&gt;/i,format:{underline:!0},isEscaped:!0},{regex:/&lt;s&gt;(.+?)&lt;\/s&gt;/i,format:{strikethrough:!0},isEscaped:!0},{regex:/\*\*\*(.+?)\*\*\*/,format:{bold:!0,italic:!0}},{regex:/\*\*\+\+(.+?)\+\+\*\*/,format:{bold:!0,underline:!0}},{regex:/\*\*(.+?)\*\*/,format:{bold:!0}},{regex:/__(.+?)__/,format:{bold:!0}},{regex:/\+\+(.+?)\+\+/,format:{underline:!0}},{regex:/~~(.+?)~~/,format:{strikethrough:!0}},{regex:/~(.+?)~/,format:{strikethrough:!0}},{regex:/\*(?!\*)(.+?)\*(?!\*)/,format:{italic:!0}},{regex:/_(?!_)(.+?)_(?!_)/,format:{italic:!0}}];function Ge(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let l of Yu){let s,c=l.regex.source||l.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),u="g"+(l.regex.ignoreCase?"i":""),f=new RegExp(c,u);for(;(s=f.exec(e))!==null;)n.push({start:s.index,end:s.index+s[0].length,fullMatch:s[0],innerText:l.isEscaped?Zu(s[1]):s[1],format:l.format}),s.index===f.lastIndex&&f.lastIndex++}n.sort((l,s)=>l.start-s.start||s.end-l.end);let a=[],o=0;for(let l of n)l.start>=o&&(a.push(l),o=l.end);let i=0;for(let l of a){r+=e.slice(i,l.start);let s=Ge(l.innerText),c=r.length;r+=s.cleanText;let u=r.length;t.push({start:c,end:u,format:l.format});for(let f of s.formatHints)t.push({start:c+f.start,end:c+f.end,format:f.format});i=l.end}return r+=e.slice(i),{cleanText:r,formatHints:t}}function Ot(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function yo(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function Zu(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var la=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,is=new RegExp(`^(\\s*)((?:${la})\\s+)`),ss=new RegExp(`^(\\s*)((?:${la})\\s*)`),Ju=new RegExp(`^(\\s*)((?:${la})\\s+)`,"m"),Qu=new RegExp(`^(\\s*)((?:${la})\\s*)`,"m");function xo(e){return typeof e!="string"?!1:e.includes(`
6
+ `)&&Ju.test(e)}function dn(e){return typeof e!="string"?!1:e.includes(`
7
+ `)&&Qu.test(e.trim())}function pt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?ss:is;return e.match(n)}function Tt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?ss:is;return e.replace(n,"")}function ls(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function mn(e){let t=String(e||"").trim();return ls(t)==="bullet"?"bullet":/^\d+(?:\.\d+)*\.?$/.test(t)||/^\(\d+\)$/.test(t)?"decimal":/^[ivxlcdm]+\.$/.test(t)?"lowerRoman":/^[IVXLCDM]{2,}\.$/.test(t)?"upperRoman":/^[a-z]\.$/.test(t)?"lowerAlpha":/^[A-Z]\.$/.test(t)?"upperAlpha":"decimal"}function ef(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function pn(e,t={}){let r=pt(String(e||""),t);if(!r)return null;let n=r[2].trim(),a=(r[1]||"").length,o=Math.max(1,Number(t.indentSpaces)||2),i=ls(n);return{line:String(e||""),text:Tt(String(e||""),t),marker:n,indent:a,level:Math.min(8,Math.floor(a/o)),markerType:i,listType:i,numberingStyle:mn(n),outlineLevel:i==="numbered"?ef(n):null}}var M="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var st=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),q=Object.freeze({TEXT:"run",DELETION:"deletion",INSERTION:"insertion",HYPERLINK:"hyperlink",BOOKMARK:"bookmark",FIELD:"field",CONTAINER_START:"container_start",CONTAINER_END:"container_end",PARAGRAPH_START:"paragraph_start"}),Lr=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),fs=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),se=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),Le=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Ue(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var bo=1e3,cs=2147483647,us=1e4,tf=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),ds=new WeakMap;function rf(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return tf.has(t)?!e.namespaceURI||e.namespaceURI===M||String(e.nodeName||"").startsWith("w:"):!1}function nf(e){let t=e?.getAttributeNS?.(M,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var Se=class{constructor(t=bo){this.startValue=Number.isInteger(t)&&t>=0?t:bo,this.nextId=this.startValue,this.occupiedIds=new Set}seed(t){let r=-1,n=t?.nodeType===9?t.documentElement:t,a=n||null;for(;a;){if(rf(a)){let i=nf(a);i!=null&&(this.occupiedIds.add(i),r=Math.max(r,i))}if(a.firstChild){a=a.firstChild;continue}for(;a&&a!==n&&!a.nextSibling;)a=a.parentNode;a=a&&a!==n?a.nextSibling:null}let o=cs-us;return this.nextId=r>=o?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=cs-us;for(this.nextId>=t&&(this.nextId=this.startValue);this.occupiedIds.has(this.nextId);)this.nextId+=1,this.nextId>=t&&(this.nextId=this.startValue)}next(){this.advanceToAvailableId();let t=this.nextId;return this.occupiedIds.add(t),this.nextId+=1,t}},gn=new Se;function Kt(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof Se&&ds.set(r,t),t}function _t(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&ds.get(t)||null}function Ht(e,t=bo){let r=new Se(t);return r.seed(e),Kt(e,r),r}function ms(){return gn.next()}function ca(e=new Date){return e.toISOString()}function ae(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():re(),a=t instanceof Se?t:_t(t)||gn,o=a.next();return a._receiptCollector&&a._receiptCollector.recordRevision(o,r||"structural"),{id:o,author:n,date:ca()}}function hn(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():re(),n=t instanceof Se?t:_t(t)||gn,a=ca(),o=n.next(),i=n.next();return n._receiptCollector&&(n._receiptCollector.recordRevision(o,"del"),n._receiptCollector.recordRevision(i,"ins")),{deletionId:o,insertionId:i,author:r,date:a}}function kt(e,t=gn){let r=t instanceof Se?t:gn,n=r.seed(e);return Kt(e,r),n}function ps(e,t){return e<t-1}function Br(e,t,r){return ps(t,r)?e+`
8
+ `:e}function cr(e,t,r){return ps(t,r)?e+1:e}function wn(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function Ee(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function Pe(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function be(e,t,r){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let n=e.getElementsByTagNameNS(t,r);return n.length>0?n[0]:null}function ze(e,t,r,n=`w:${r}`){let a=Pe(e,t,r);return a.length>0?a:wn(e,n)}function Xe(e,t,r,n=`w:${r}`){let a=be(e,t,r);return a||Ee(e,n)}function Ne(e){return Ee(e,"parsererror")}function No(e){return Array.from(e?.childNodes||[])}function gs(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Io(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var To=0;function Fr(e,t={}){let r=[],n="",a=t.xmlDoc||null;if(!e&&!a)return{runModel:r,acceptedText:n,pPr:null};try{let o=a?{doc:a,error:null}:j(e,"application/xml"),i=o.doc;if(o.error||!i)return ye("OOXML parse error:",o.error?.message),{runModel:r,acceptedText:n,pPr:null,error:o.error};let l=Ne(i);if(l)return ye("OOXML parse error:",l.textContent),{runModel:r,acceptedText:n,pPr:null};let s=Pe(i,M,"p");return s.length===0?(mt("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):ws(s,{includeParagraphBoundaries:!0})}catch(o){return ye("Error ingesting OOXML:",o),{runModel:r,acceptedText:n,pPr:null}}}function So(e){return e?ws([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function vn(e){let t=be(e,M,"pPr");if(!t)return null;let r=be(t,M,"numPr");if(!r)return null;let n=be(r,M,"numId"),a=be(r,M,"ilvl");if(!n)return null;let o=n.getAttribute("w:val");if(!/^\d+$/.test(o)||Number.parseInt(o,10)===0)return null;let i=o==="1"?"bullet":o==="2"?"numbered":"unknown";return{numId:o,ilvl:parseInt(a?.getAttribute("w:val")||"0",10),type:i}}function ws(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],a="",o=0,i=null;for(let l=0;l<e.length;l++){let s=e[l],c=be(s,M,"pPr");l===0&&(i=c),n.push({kind:q.PARAGRAPH_START,pPrElement:c||null,startOffset:o,endOffset:o,text:""});let u=Dr(s,o,n);a+=u.text,o=a.length,r&&(a=Br(a,l,e.length),o=cr(o,l,e.length))}return{runModel:n,acceptedText:a,pPr:i}}function Dr(e,t,r){let n=t,a="",o=af(r);for(let i of No(e)){if(Io(i,M,"pPr")||Io(i,M,"proofErr"))continue;let l=o.get(i.localName);if(!l)continue;let s=l(i,n);n=s.offset,a+=s.text}return{offset:n,text:a}}function af(e){let t=new Map;t.set("sdt",(r,n)=>{let a=`sdt_${To++}`,o=be(r,M,"sdtPr"),i=be(r,M,"sdtContent");e.push({kind:q.CONTAINER_START,containerKind:Lr.SDT,containerId:a,propertiesXml:o?xe(o):"",startOffset:n,endOffset:n,text:""});let l=i?Dr(i,n,e):{offset:n,text:""};return e.push({kind:q.CONTAINER_END,containerKind:Lr.SDT,containerId:a,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("smartTag",(r,n)=>{let a=`smartTag_${To++}`;e.push({kind:q.CONTAINER_START,containerKind:Lr.SMART_TAG,containerId:a,propertiesXml:gs(r),startOffset:n,endOffset:n,text:""});let o=Dr(r,n,e);return e.push({kind:q.CONTAINER_END,containerKind:Lr.SMART_TAG,containerId:a,startOffset:o.offset,endOffset:o.offset,text:""}),o}),t.set("del",(r,n)=>{let a=hs(r,n);return a&&e.push(a),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let a=hs(r,n);return a&&e.push(a),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Dr(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,a)=>(e.push({kind:q.BOOKMARK,nodeXml:xe(n),startOffset:a,endOffset:a,text:""}),{offset:a,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:q.BOOKMARK,nodeXml:xe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:q.BOOKMARK,nodeXml:xe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Dr(r,n,e)),t.set("hyperlink",(r,n)=>{let a=`hyperlink_${To++}`,o=r.getAttribute("r:id")||"",i=r.getAttribute("w:anchor")||"";e.push({kind:q.CONTAINER_START,containerKind:"hyperlink",containerId:a,propertiesXml:JSON.stringify({rId:o,anchor:i}),startOffset:n,endOffset:n,text:""});let l=Dr(r,n,e);return e.push({kind:q.CONTAINER_END,containerKind:"hyperlink",containerId:a,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("r",(r,n)=>{let a=of(r,n);return!a||!a.text?{offset:n,text:""}:(e.push(a),{offset:n+a.text.length,text:a.text})}),t}function of(e,t){let r=Xe(e,M,"rPr"),n=r?xe(r):"",a="";for(let o of No(e)){let i=o.nodeName;i.endsWith(":t")||i==="t"?a+=o.textContent||"":i.endsWith(":br")||i==="br"||i.endsWith(":cr")||i==="cr"?a+=`
9
+ `:i.endsWith(":tab")||i==="tab"?a+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?a+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(a+="\xAD")}return a?{kind:q.TEXT,text:a,rPrXml:n,startOffset:t,endOffset:t+a.length}:null}function hs(e,t){let r=e.getAttribute("w:author")||"",n="",a=Pe(e,M,"delText");for(let i of a)n+=i.textContent||"";let o=Pe(e,M,"r");for(let i of o){let l=Pe(i,M,"delText");for(let s of l)n+=s.textContent||""}return n?{kind:q.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:xe(e)}:null}function Ao(e){let t=be(e,M,"tblGrid"),r=t?Pe(t,M,"gridCol"):[],n=ze(e,M,"tr"),a=n.length,o=n.reduce((u,f)=>{let d=ze(f,M,"tc");return Math.max(u,d.length)},0),i=r.length||o,l=Array.from({length:a},()=>Array.from({length:i},()=>null)),s=new Map,c=new Map;for(let u=0;u<n.length;u++){let f=n[u],d=ze(f,M,"tc"),m=0;for(let p=0;p<d.length;p++){let h=d[p],g=be(h,M,"tcPr");for(;m<i&&l[u][m]!==null;)m++;if(m>=i)break;let v=g?be(g,M,"gridSpan")||Ee(g,"w:gridSpan"):null,w=parseInt(v?.getAttribute("w:val")||"1",10),y=g?be(g,M,"vMerge")||Ee(g,"w:vMerge"):null,x=y?.getAttribute("w:val"),b=y!==null,I;if(b&&x!=="restart"){let N=c.get(m);N?(N.cell.rowSpan++,I={gridRow:u,gridCol:m,rowSpan:0,colSpan:w,tcNode:h,blocks:[],tcPrXml:Eo(g),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:N.cell}):I=sf(u,m,w,h,g)}else{let N=vs(h);if(I={gridRow:u,gridCol:m,rowSpan:1,colSpan:w,tcNode:h,blocks:N,tcPrXml:Eo(g),isMergeOrigin:b&&x==="restart",isMergeContinuation:!1,getText:()=>N.map(T=>T.acceptedText).join(`
10
+ `)},b&&x==="restart")for(let T=0;T<w;T++)c.set(m+T,{originRow:u,cell:I});else for(let T=0;T<w;T++)c.delete(m+T)}for(let N=0;N<w;N++){let T=m+N;T<i&&(l[u][T]=I,s.set(`${u},${T}`,I))}m+=w}}return{rowCount:a,colCount:i,grid:l,cellMap:s,tblPrXml:lf(e),tblGridXml:cf(e),trPrList:Array.from(n).map(u=>uf(u))}}function sf(e,t,r,n,a){let o=vs(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:o,tcPrXml:Eo(a),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>o.map(i=>i.acceptedText).join(`
11
+ `)}}function vs(e){return ze(e,M,"p").map(r=>{let{runModel:n,acceptedText:a,pPr:o}=So(r);return{runModel:n,acceptedText:a,pPr:o}})}function Eo(e){return e?xe(e):"<w:tcPr/>"}function lf(e){let t=be(e,M,"tblPr");return t?xe(t):"<w:tblPr/>"}function cf(e){let t=be(e,M,"tblGrid");return t?xe(t):"<w:tblGrid/>"}function uf(e){let t=be(e,M,"trPr");return t?xe(t):"<w:trPr/>"}var bs=Qi(Ro(),1);var ff=65536,ua=262144,fa=1,da=55296-fa,df=8192,mf=da+df,Po=class extends Error{constructor(t=ua){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Ns(e){return e?.code==="DIFF_TOKEN_LIMIT"}function Co(e={}){let t=e.diffTimeoutSeconds??0;if(!Number.isFinite(t)||t<0)throw new TypeError("diffTimeoutSeconds must be a finite non-negative number.");let r=new bs.diff_match_patch;return r.Diff_Timeout=t,r}function ys(e){let t=[],r=e.match(/^\s+/);r&&t.push(r[0]);let n=/(\S+)(\s*)/g;n.lastIndex=r?.[0].length||0;let a;for(;(a=n.exec(e))!==null;)a[1]&&t.push(a[1]),a[2]&&t.push(a[2]);return t}function pf(e,t,r={}){let n=[],a=new Map,o=r.maxTokens??ua;if(!Number.isInteger(o)||o<1||o>ua)throw new RangeError(`maxTokens must be an integer from 1 to ${ua}.`);function i(f){let d="",m=[];for(let p of f){let h=a.get(p);if(h===void 0){if(n.length>=o)throw new Po(o);h=n.length,n.push(p),a.set(p,h)}m.push(h),d+=String.fromCodePoint(ff+h)}return{chars:d,tokenIds:m}}let l=ys(e),s=ys(t),c=i(l),u=i(s);return{chars1:c.chars,chars2:u.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:u.tokenIds}}function gf(e){let t=e<da?fa+e:57344+(e-da);return String.fromCharCode(t)}function hf(e){if(e>=fa&&e<55296)return e-fa;if(e>=57344&&e<=65535)return da+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function xs(e){let t="";for(let r of e)t+=gf(r);return t}function wf(e,t){return e.map(([r,n])=>{let a=[];for(let o=0;o<n.length;o++){let i=hf(n.charCodeAt(o));if(i>=t.length)throw new RangeError(`BMP diff token ${i} has no mapping.`);a.push(t[i])}return[r,a.join("")]})}function vf(e,t,r){let n=0,a=Math.min(e.length,t.length);for(;n<a&&e[n]===t[n];)n++;let o=0;for(;o<a-n&&e[e.length-1-o]===t[t.length-1-o];)o++;let i=u=>u.map(f=>r[f]).join(""),l=[];n&&l.push([0,i(e.slice(0,n))]);let s=e.slice(n,e.length-o),c=t.slice(n,t.length-o);return s.length&&l.push([-1,i(s)]),c.length&&l.push([1,i(c)]),o&&l.push([0,i(e.slice(e.length-o))]),l}function yn(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:a,tokenIds1:o,tokenIds2:i}=pf(e,t,r);if(a.length>mf)return vf(o,i,a);let l=Co(r),s=l.diff_main(xs(o),xs(i));return n&&l.diff_cleanupSemantic(s),wf(s,a)}function Is(e,t,r={}){return e===t?[[0,e]]:Co(r).diff_main(e,t)}function Ts(e,t){if(e===t)return[[0,e]];if(!e)return[[1,t]];let r=0;for(let a=0;a<t.length&&r<e.length;a++)t[a]===e[r]&&r++;if(r!==e.length)return null;let n=Co().diff_main(e,t);return n.some(([a])=>a===-1)?null:n}function ma(e,t,r={}){if(e===t)return[{type:st.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:st.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:st.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=yn(e,t,r),a=[],o=0;for(let[i,l]of n)i===0?(a.push({type:st.EQUAL,startOffset:o,endOffset:o+l.length,text:l}),o+=l.length):i===-1?(a.push({type:st.DELETE,startOffset:o,endOffset:o+l.length,text:l}),o+=l.length):i===1&&a.push({type:st.INSERT,startOffset:o,endOffset:o,text:l});return a}var yf=/\s+xmlns:[^=]+="[^"]*"/g;function pa(e,t){let r=Sf(t),n=[],a=0;for(let o of e){if(o.kind!==q.TEXT&&o.kind!==q.HYPERLINK){n.push(o);continue}for(;a<r.length&&r[a]<=o.startOffset;)a++;let i=a,l=o.startOffset,s=!1;for(;i<r.length;){let c=r[i];if(c>=o.endOffset)break;c>l&&(s=!0,n.push({...o,text:o.text.slice(l-o.startOffset,c-o.startOffset),startOffset:l,endOffset:c}),l=c),i++}if(a=i,!s){n.push(o);continue}n.push({...o,text:o.text.slice(l-o.startOffset),startOffset:l,endOffset:o.endOffset})}return n}function ga(e,t,r){let{generateRedlines:n,author:a}=r,o=[],i=new Set,l=Ef(t),s=If(e),c=Tf(l.nonInsertOps),u={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let d of e){if(d.kind===q.CONTAINER_START){u.containerStack.push(d.containerId),o.push({...d});continue}if(d.kind===q.CONTAINER_END){u.containerStack.pop(),o.push({...d});continue}if(d.kind===q.PARAGRAPH_START){u.currentParagraphPPrXml=typeof d.pPrXml=="string"?d.pPrXml:"",u.currentParagraphPPrElement=d.pPrElement||null,o.push({...d}),u.lastParagraphStartIndex=o.length-1;continue}if(d.kind===q.BOOKMARK||d.kind===q.DELETION){o.push({...d});continue}let m=c(d.startOffset,d.endOffset),p=l.insertOpsByStartOffset.get(d.startOffset)||[];for(let h of p)i.has(h)||(i.add(h),xf({insertOp:h,splitModel:e,styleLookup:s,patchedModel:o,state:u,options:r,generateRedlines:n,author:a}));if(!m||m.type===st.EQUAL){o.push({...d,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null});continue}m.type===st.DELETE&&n&&o.push({...d,kind:q.DELETION,author:a,containerContext:u.containerStack.length>0?u.containerStack[u.containerStack.length-1]:null})}let f=e.length>0?Math.max(...e.map(d=>d.endOffset)):0;for(let d of l.sortedInsertOps){if(d.startOffset<f||i.has(d))continue;let m=e[e.length-1];o.push({kind:n?q.INSERTION:q.TEXT,text:d.text,rPrXml:m?.rPrXml||"",startOffset:d.startOffset,endOffset:d.startOffset+d.text.length,author:n?a:void 0})}return o}function xf(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:a,options:o,generateRedlines:i,author:l}=e,s=t.text.split(`
12
+ `),c=Nf(r,t.startOffset,t.text);for(let u=0;u<s.length;u++){let f=bf(s[u],o.numberingService,a),d=f.lineText;if(u>0){let m=Ss(a);f.isListLine&&f.numId&&(m=o.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:q.PARAGRAPH_START,pPrXml:m,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),a.currentParagraphPPrXml=m,a.currentParagraphPPrElement=null,a.lastParagraphStartIndex=n.length-1}else if(f.isListLine&&f.numId&&a.lastParagraphStartIndex>=0){let m=o.numberingService.buildListPPr(f.numId,f.ilvl);n[a.lastParagraphStartIndex].pPrXml=m,n[a.lastParagraphStartIndex].pPrElement=null,a.currentParagraphPPrXml=m,a.currentParagraphPPrElement=null,V(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(d.length>0||u>0)&&n.push({kind:i?q.INSERTION:q.TEXT,text:d,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+d.length,author:i?l:void 0,containerContext:a.containerStack.length>0?a.containerStack[a.containerStack.length-1]:null})}}function bf(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=pt(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let a=n[2].trim(),o=t.detectNumberingFormat(a),i=e.match(/^(\s*)/),l=i?i[1].length:0,s=l>=4?4:2,c=Math.floor(l/s),u=Ss(r),f=Tt(e,{allowZeroSpaceAfterMarker:!0}),d=u.match(/w:numId w:val="(\d+)"/),m=u.match(/w:ilvl w:val="(\d+)"/),p=d?d[1]:null,h=m?parseInt(m[1],10):0,g=t.getOrCreateNumId({type:o.format},{numId:p,type:"unknown"}),v=o.format==="outline"?Math.min(8,o.depth):Math.min(8,c+h);return{lineText:f,isListLine:!0,numId:g,ilvl:v}}function Ss(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=xe(e.currentParagraphPPrElement).replace(yf,""),e.currentParagraphPPrXml):""}function Nf(e,t,r){let n=e.findRunBefore(t),a=e.findRunAfter(t);return!n&&!a?null:n?a?r&&r.endsWith(" ")?a:(r&&r.startsWith(" "),n):n:a}function If(e){let t=e.filter(a=>a.kind===q.TEXT),r=t.map(a=>a.startOffset),n=t.map(a=>a.endOffset);return{findRunBefore(a){let o=0,i=n.length-1,l=-1;for(;o<=i;){let s=o+i>>1;n[s]<=a?(l=s,o=s+1):i=s-1}return l>=0?t[l]:null},findRunAfter(a){let o=0,i=r.length-1,l=-1;for(;o<=i;){let s=o+i>>1;r[s]>=a?(l=s,i=s-1):o=s+1}return l>=0?t[l]:null}}}function Tf(e){let t=0;return(r,n)=>{for(;t<e.length&&e[t].endOffset<=r;)t++;let a=e[t];return a&&a.startOffset<=r&&a.endOffset>=n?a:null}}function Sf(e){let t=new Set;for(let r of e)t.add(r.startOffset),t.add(r.endOffset);return Array.from(t).sort((r,n)=>r-n)}function Ef(e){let t=new Map,r=[],n=[];for(let a of e){if(a.type===st.INSERT){t.has(a.startOffset)||t.set(a.startOffset,[]),t.get(a.startOffset).push(a),n.push(a);continue}r.push(a)}return r.sort((a,o)=>a.startOffset-o.startOffset||a.endOffset-o.endOffset),n.sort((a,o)=>a.startOffset-o.startOffset||a.endOffset-o.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var Ps="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Af="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Rf="http://schemas.microsoft.com/office/2006/xmlPackage",Es="http://schemas.openxmlformats.org/package/2006/relationships",Pf='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',As='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Cf=`
13
+ <w:numbering xmlns:w="${Ps}">
14
14
  <w:abstractNum w:abstractNumId="0">
15
15
  <w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="&#8226;"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
16
16
  </w:abstractNum>
@@ -19,23 +19,23 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
19
19
  </w:abstractNum>
20
20
  <w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
21
21
  <w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>
22
- </w:numbering>`.trim();function pl(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function pi(e,t=!0){let r=t?` xmlns:r="${ul}"`:"";return`<w:document xmlns:w="${di}"${r}><w:body>${e}</w:body></w:document>`}function mi(e){return`
22
+ </w:numbering>`.trim();function Of(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function Cs(e,t=!0){let r=t?` xmlns:r="${Af}"`:"";return`<w:document xmlns:w="${Ps}"${r}><w:body>${e}</w:body></w:document>`}function Rs(e){return`
23
23
  <pkg:part pkg:name="/word/numbering.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml">
24
24
  <pkg:xmlData>
25
- ${pl(e)}
25
+ ${Of(e)}
26
26
  </pkg:xmlData>
27
- </pkg:part>`}function gi(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
- <pkg:package xmlns:pkg="${fl}">
27
+ </pkg:part>`}function Os(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
+ <pkg:package xmlns:pkg="${Rf}">
29
29
  <pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
30
30
  <pkg:xmlData>
31
- <Relationships xmlns="${ui}">
32
- ${ml}
31
+ <Relationships xmlns="${Es}">
32
+ ${Pf}
33
33
  </Relationships>
34
34
  </pkg:xmlData>
35
35
  </pkg:part>
36
36
  <pkg:part pkg:name="/word/_rels/document.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
37
37
  <pkg:xmlData>
38
- <Relationships xmlns="${ui}">
38
+ <Relationships xmlns="${Es}">
39
39
  ${t}
40
40
  </Relationships>
41
41
  </pkg:xmlData>
@@ -45,7 +45,7 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
45
45
  ${e}
46
46
  </pkg:xmlData>
47
47
  </pkg:part>
48
- </pkg:package>`}function hi(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,i=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,a=pi(i,!0),s="",l="";return n?(s=fi,l+=mi(n)):r&&(s=fi,l+=mi(dl)),gi(a,s,l)}function wi(e){let t=pi(e,!0);return gi(t)}var gl=/\s+xmlns:[^=]+="[^"]*"/g;function $e(e,t,r=[],n={}){let o=hl(n),{generateRedlines:i}=o,a=[],s="",l=null,c=[];function u(){if(c.length>0||a.length===0){let f="";s?f=gt(s):l?(s=gt(te(l)),f=s):t&&(typeof t=="string"?f=t:f=te(t),f=gt(f)),a.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case D.PARAGRAPH_START:(c.length>0||a.length>0)&&u(),s=f.pPrXml||"",l=f.pPrElement||null;break;case D.TEXT:c.push(bi(f,r,o));break;case D.DELETION:i&&c.push(wl(f,o));break;case D.INSERTION:i?c.push(bl(f,r,o)):c.push(bi(f,r,o));break;case D.BOOKMARK:case D.HYPERLINK:f.nodeXml&&c.push(gt(f.nodeXml));break;case D.CONTAINER_START:if(f.containerKind==="sdt")c.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")c.push(`<w:smartTag ${f.propertiesXml}>`);else if(f.containerKind==="hyperlink"){let m=JSON.parse(f.propertiesXml),d=m.rId?` r:id="${m.rId}"`:"",p=m.anchor?` w:anchor="${m.anchor}"`:"";c.push(`<w:hyperlink${d}${p}>`)}break;case D.CONTAINER_END:f.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?c.push("</w:smartTag>"):f.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:Be("Unknown run kind:",f.kind)}return u(),a.join("")}function hl(e){if(typeof e=="string")return{author:pe(),generateRedlines:!0,font:e,revisionIdAllocator:null};let t=e&&typeof e=="object"?e:{};return{author:typeof t.author=="string"&&t.author.trim()?t.author.trim():pe(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function bi(e,t,r={}){let n=Ke(t,e.startOffset,e.endOffset),o=r?.font??null,i=e.rPrXml?gt(e.rPrXml):"";if(o&&(i=$n(i,o)),n.length===0)return ot(e.text,i);let a=[],s=0,l=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),m=Math.min(l.length,u.end-c);f>s&&a.push(ot(l.slice(s,f),i));let d=xi(i,u.format);a.push(ot(l.slice(f,m),d)),s=m}return s<l.length&&a.push(ot(l.slice(s),i)),a.join("")}function ot(e,t){return e?`<w:r>${t||""}<w:t xml:space="preserve">${Ne(e)}</w:t></w:r>`:""}function wl(e,t={}){let r=ie(t.author??pe(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?gt(e.rPrXml):"";return n&&(o=$n(o,n)),`<w:del w:id="${r.id}" w:author="${Ne(r.author)}" w:date="${r.date}"><w:r>${o}<w:delText xml:space="preserve">${Ne(e.text)}</w:delText></w:r></w:del>`}function bl(e,t,r={}){let n=ie(r.author??pe(),r.revisionIdAllocator,"ins"),o=r.font??null,i=Ke(t,e.startOffset,e.endOffset),a="",s=e.rPrXml?gt(e.rPrXml):"";if(o&&(s=$n(s,o)),i.length===0)a=ot(e.text,s);else{let l=0,c=e.text,u=e.startOffset;for(let f of i){let m=Math.max(0,f.start-u),d=Math.min(c.length,f.end-u);m>l&&(a+=ot(c.slice(l,m),s));let p=xi(s,f.format);a+=ot(c.slice(m,d),p),l=d}l<c.length&&(a+=ot(c.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${Ne(n.author)}" w:date="${n.date}">`+a+"</w:ins>"}function $n(e,t){if(!t)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),r.includes("<w:rFonts")?r=r.replace(/<w:rFonts[^>]*\/>/,`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`):r=`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`+r,`<w:rPr>${r}</w:rPr>`}function xi(e,t){if(!t||Object.keys(t).length===0)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),t.bold&&!r.includes("<w:b")&&(r="<w:b/>"+r),t.italic&&!r.includes("<w:i")&&(r="<w:i/>"+r),t.underline&&!r.includes("<w:u")&&(r='<w:u w:val="single"/>'+r),t.strikethrough&&!r.includes("<w:strike")&&(r="<w:strike/>"+r),`<w:rPr>${r}</w:rPr>`}function it(e,t={}){let r=xl(t);return hi(e,r)}function xl(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function gt(e){return e?e.replace(gl,""):""}function Xn(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var Je=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){Xn(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||G.BULLET;if(r&&Xn(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let i=this.contextMap.get(n);if(Xn(i))return i;this.contextMap.delete(n)}if(n===G.OUTLINE)return"3";if(n===G.DECIMAL)return"2";if(n===G.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==G.DECIMAL&&n!==G.BULLET){let i=`custom_${n}`;if(this.contextMap.has(i))return this.contextMap.get(i);let a=String(this.nextNumId++);return this.customConfigs.push({numId:a,levels:[{format:n,suffix:t.suffix||be.PERIOD}]}),this.contextMap.set(i,a),a}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:G.BULLET,suffix:be.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:G.BULLET,suffix:be.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:G.OUTLINE,suffix:be.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:G.LOWER_ALPHA,suffix:be.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:be.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:G.DECIMAL,suffix:be.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:G.DECIMAL,suffix:be.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:G.LOWER_ALPHA,suffix:be.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:G.UPPER_ALPHA,suffix:be.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:be.PERIOD,depth:0}:/^\d+/.test(r)?{format:G.DECIMAL,suffix:be.PERIOD,depth:0}:{format:G.BULLET,suffix:be.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[G.DECIMAL]:"decimal",[G.LOWER_ALPHA]:"lowerLetter",[G.UPPER_ALPHA]:"upperLetter",[G.LOWER_ROMAN]:"lowerRoman",[G.UPPER_ROMAN]:"upperRoman",[G.BULLET]:"bullet",[G.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===G.BULLET)return"\u2022";let o=`%${n+1}`;if(t===G.OUTLINE)return Array(n+1).fill(0).map((i,a)=>`%${a+1}`).join(".")+".";switch(r){case be.PERIOD:return`${o}.`;case be.PAREN_RIGHT:return`${o})`;case be.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
48
+ </pkg:package>`}function _s(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:a=!0}=t,o=a?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,i=Cs(o,!0),l="",s="";return n?(l=As,s+=Rs(n)):r&&(l=As,s+=Rs(Cf)),Os(i,l,s)}function ks(e){let t=Cs(e,!0);return Os(t)}var _f=/\s+xmlns:[^=]+="[^"]*"/g;function gt(e,t,r=[],n={}){let a=kf(n),{generateRedlines:o}=a,i=[],l="",s=null,c=[];function u(){if(c.length>0||i.length===0){let f="";l?f=ur(l):s?(l=ur(xe(s)),f=l):t&&(typeof t=="string"?f=t:f=xe(t),f=ur(f)),i.push(`<w:p>${f}${c.join("")}</w:p>`),c=[]}}for(let f of e)switch(f.kind){case q.PARAGRAPH_START:(c.length>0||i.length>0)&&u(),l=f.pPrXml||"",s=f.pPrElement||null;break;case q.TEXT:c.push(Ms(f,r,a));break;case q.DELETION:o&&c.push(Mf(f,a));break;case q.INSERTION:o?c.push(Lf(f,r,a)):c.push(Ms(f,r,a));break;case q.BOOKMARK:case q.HYPERLINK:f.nodeXml&&c.push(ur(f.nodeXml));break;case q.CONTAINER_START:if(f.containerKind==="sdt")c.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")c.push(`<w:smartTag ${f.propertiesXml}>`);else if(f.containerKind==="hyperlink"){let d=JSON.parse(f.propertiesXml),m=d.rId?` r:id="${d.rId}"`:"",p=d.anchor?` w:anchor="${d.anchor}"`:"";c.push(`<w:hyperlink${m}${p}>`)}break;case q.CONTAINER_END:f.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?c.push("</w:smartTag>"):f.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:mt("Unknown run kind:",f.kind)}return u(),i.join("")}function kf(e){if(typeof e=="string")return{author:re(),generateRedlines:!0,font:e,revisionIdAllocator:null};let t=e&&typeof e=="object"?e:{};return{author:typeof t.author=="string"&&t.author.trim()?t.author.trim():re(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function Ms(e,t,r={}){let n=Ot(t,e.startOffset,e.endOffset),a=r?.font??null,o=e.rPrXml?ur(e.rPrXml):"";if(a&&(o=Oo(o,a)),n.length===0)return Gt(e.text,o);let i=[],l=0,s=e.text,c=e.startOffset;for(let u of n){let f=Math.max(0,u.start-c),d=Math.min(s.length,u.end-c);f>l&&i.push(Gt(s.slice(l,f),o));let m=Ls(o,u.format);i.push(Gt(s.slice(f,d),m)),l=d}return l<s.length&&i.push(Gt(s.slice(l),o)),i.join("")}function Gt(e,t){return e?`<w:r>${t||""}<w:t xml:space="preserve">${Ue(e)}</w:t></w:r>`:""}function Mf(e,t={}){let r=ae(t.author??re(),t.revisionIdAllocator,"del"),n=t.font??null,a=e.rPrXml?ur(e.rPrXml):"";return n&&(a=Oo(a,n)),`<w:del w:id="${r.id}" w:author="${Ue(r.author)}" w:date="${r.date}"><w:r>${a}<w:delText xml:space="preserve">${Ue(e.text)}</w:delText></w:r></w:del>`}function Lf(e,t,r={}){let n=ae(r.author??re(),r.revisionIdAllocator,"ins"),a=r.font??null,o=Ot(t,e.startOffset,e.endOffset),i="",l=e.rPrXml?ur(e.rPrXml):"";if(a&&(l=Oo(l,a)),o.length===0)i=Gt(e.text,l);else{let s=0,c=e.text,u=e.startOffset;for(let f of o){let d=Math.max(0,f.start-u),m=Math.min(c.length,f.end-u);d>s&&(i+=Gt(c.slice(s,d),l));let p=Ls(l,f.format);i+=Gt(c.slice(d,m),p),s=m}s<c.length&&(i+=Gt(c.slice(s),l))}return`<w:ins w:id="${n.id}" w:author="${Ue(n.author)}" w:date="${n.date}">`+i+"</w:ins>"}function Oo(e,t){if(!t)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),r.includes("<w:rFonts")?r=r.replace(/<w:rFonts[^>]*\/>/,`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`):r=`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`+r,`<w:rPr>${r}</w:rPr>`}function Ls(e,t){if(!t||Object.keys(t).length===0)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),t.bold&&!r.includes("<w:b")&&(r="<w:b/>"+r),t.italic&&!r.includes("<w:i")&&(r="<w:i/>"+r),t.underline&&!r.includes("<w:u")&&(r='<w:u w:val="single"/>'+r),t.strikethrough&&!r.includes("<w:strike")&&(r="<w:strike/>"+r),`<w:rPr>${r}</w:rPr>`}function qt(e,t={}){let r=Bf(t);return _s(e,r)}function Bf(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function ur(e){return e?e.replace(_f,""):""}function _o(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var Mt=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){_o(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||se.BULLET;if(r&&_o(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let o=this.contextMap.get(n);if(_o(o))return o;this.contextMap.delete(n)}if(n===se.OUTLINE)return"3";if(n===se.DECIMAL)return"2";if(n===se.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==se.DECIMAL&&n!==se.BULLET){let o=`custom_${n}`;if(this.contextMap.has(o))return this.contextMap.get(o);let i=String(this.nextNumId++);return this.customConfigs.push({numId:i,levels:[{format:n,suffix:t.suffix||Le.PERIOD}]}),this.contextMap.set(o,i),i}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:se.BULLET,suffix:Le.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:se.BULLET,suffix:Le.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let a=n[1].split(".").length-1;return{format:se.OUTLINE,suffix:Le.PERIOD,depth:a}}return/^\([a-z]\)$/.test(r)?{format:se.LOWER_ALPHA,suffix:Le.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?se.LOWER_ROMAN:se.UPPER_ROMAN,suffix:Le.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:se.DECIMAL,suffix:Le.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:se.DECIMAL,suffix:Le.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:se.LOWER_ALPHA,suffix:Le.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:se.UPPER_ALPHA,suffix:Le.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?se.LOWER_ROMAN:se.UPPER_ROMAN,suffix:Le.PERIOD,depth:0}:/^\d+/.test(r)?{format:se.DECIMAL,suffix:Le.PERIOD,depth:0}:{format:se.BULLET,suffix:Le.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[se.DECIMAL]:"decimal",[se.LOWER_ALPHA]:"lowerLetter",[se.UPPER_ALPHA]:"upperLetter",[se.LOWER_ROMAN]:"lowerRoman",[se.UPPER_ROMAN]:"upperRoman",[se.BULLET]:"bullet",[se.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===se.BULLET)return"\u2022";let a=`%${n+1}`;if(t===se.OUTLINE)return Array(n+1).fill(0).map((o,i)=>`%${i+1}`).join(".")+".";switch(r){case Le.PERIOD:return`${a}.`;case Le.PAREN_RIGHT:return`${a})`;case Le.PAREN_BOTH:return`(${a})`;default:return a}}buildListPPr(t,r,n={}){return`
49
49
  <w:pPr>${n.includeListParagraphStyle===!0?`
50
50
  <w:pStyle w:val="ListParagraph"/>`:""}
51
51
  <w:numPr>
@@ -56,15 +56,15 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
56
56
  `}generateNumberingXml(t=[]){let r=[...this.customConfigs,...t],n=`
57
57
  <w:abstractNum w:abstractNumId="0">
58
58
  <w:multiLevelType w:val="hybridMultilevel"/>
59
- ${[0,1,2,3,4,5,6,7,8].map(l=>`
60
- <w:lvl w:ilvl="${l}">
59
+ ${[0,1,2,3,4,5,6,7,8].map(s=>`
60
+ <w:lvl w:ilvl="${s}">
61
61
  <w:start w:val="1"/>
62
- <w:numFmt w:val="${l%3===0?"bullet":l%3===1?"circle":"square"}"/>
63
- <w:lvlText w:val="${l%3===0?"\u2022":l%3===1?"\u25CB":"\u25A0"}"/>
62
+ <w:numFmt w:val="${s%3===0?"bullet":s%3===1?"circle":"square"}"/>
63
+ <w:lvlText w:val="${s%3===0?"\u2022":s%3===1?"\u25CB":"\u25A0"}"/>
64
64
  <w:lvlJc w:val="left"/>
65
- <w:pPr><w:ind w:left="${720*(l+1)}" w:hanging="360"/></w:pPr>
65
+ <w:pPr><w:ind w:left="${720*(s+1)}" w:hanging="360"/></w:pPr>
66
66
  </w:lvl>`).join("")}
67
- </w:abstractNum>`,o=`
67
+ </w:abstractNum>`,a=`
68
68
  <w:abstractNum w:abstractNumId="1">
69
69
  <w:multiLevelType w:val="multilevel"/>
70
70
  <w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
@@ -72,7 +72,7 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
72
72
  <w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="lowerRoman"/><w:lvlText w:val="(%3)"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2160" w:hanging="360"/></w:pPr></w:lvl>
73
73
  <w:lvl w:ilvl="3"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="(%4)"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2880" w:hanging="360"/></w:pPr></w:lvl>
74
74
  <w:lvl w:ilvl="4"><w:start w:val="1"/><w:numFmt w:val="lowerLetter"/><w:lvlText w:val="%5."/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="3600" w:hanging="360"/></w:pPr></w:lvl>
75
- </w:abstractNum>`,i=`
75
+ </w:abstractNum>`,o=`
76
76
  <w:abstractNum w:abstractNumId="2">
77
77
  <w:multiLevelType w:val="multilevel"/>
78
78
  <w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
@@ -80,26 +80,26 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
80
80
  <w:lvl w:ilvl="2"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2160" w:hanging="360"/></w:pPr></w:lvl>
81
81
  <w:lvl w:ilvl="3"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="2880" w:hanging="360"/></w:pPr></w:lvl>
82
82
  <w:lvl w:ilvl="4"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1.%2.%3.%4.%5"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="3600" w:hanging="360"/></w:pPr></w:lvl>
83
- </w:abstractNum>`,a="",s="";return r.forEach((l,c)=>{let u=10+c;a+=`
83
+ </w:abstractNum>`,i="",l="";return r.forEach((s,c)=>{let u=10+c;i+=`
84
84
  <w:abstractNum w:abstractNumId="${u}">
85
85
  <w:multiLevelType w:val="multilevel"/>
86
- ${l.levels.map((f,m)=>`
87
- <w:lvl w:ilvl="${m}">
86
+ ${s.levels.map((f,d)=>`
87
+ <w:lvl w:ilvl="${d}">
88
88
  <w:start w:val="1"/>
89
89
  <w:numFmt w:val="${this.formatToOoxmlNumFmt(f.format)}"/>
90
- <w:lvlText w:val="${this.suffixToOoxmlLevelText(f.format,f.suffix,m)}"/>
90
+ <w:lvlText w:val="${this.suffixToOoxmlLevelText(f.format,f.suffix,d)}"/>
91
91
  <w:lvlJc w:val="left"/>
92
- <w:pPr><w:ind w:left="${720*(m+1)}" w:hanging="360"/></w:pPr>
92
+ <w:pPr><w:ind w:left="${720*(d+1)}" w:hanging="360"/></w:pPr>
93
93
  </w:lvl>`).join("")}
94
- </w:abstractNum>`,s+=`
95
- <w:num w:numId="${l.numId}">
94
+ </w:abstractNum>`,l+=`
95
+ <w:num w:numId="${s.numId}">
96
96
  <w:abstractNumId w:val="${u}"/>
97
97
  </w:num>`}),`
98
98
  <w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
99
99
  ${n}
100
+ ${a}
100
101
  ${o}
101
102
  ${i}
102
- ${a}
103
103
  <w:num w:numId="1">
104
104
  <w:abstractNumId w:val="0"/>
105
105
  </w:num>
@@ -109,8 +109,8 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
109
109
  <w:num w:numId="3">
110
110
  <w:abstractNumId w:val="2"/>
111
111
  </w:num>
112
- ${s}
113
- </w:numbering>`}};function ht(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:i=!1}=t,a=r&&i?ie(n,o):null,s=e.headers?.length||e.rows?.[0]?.length||1,l=`
112
+ ${l}
113
+ </w:numbering>`}};function fr(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:a=null,trackAsBlock:o=!1}=t,i=r&&o?ae(n,a):null,l=e.headers?.length||e.rows?.[0]?.length||1,s=`
114
114
  <w:tblPr>
115
115
  <w:tblW w:w="5000" w:type="pct"/>
116
116
  <w:tblBorders>
@@ -123,92 +123,105 @@ var xs=Object.create;var $o=Object.defineProperty;var Ns=Object.getOwnPropertyDe
123
123
  </w:tblBorders>
124
124
  <w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
125
125
  </w:tblPr>
126
- `.trim(),u=`<w:tblGrid>${Array(s).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,m="";for(let p=0;p<f.length;p++){let h=e.hasHeader&&p===0,w=f[p]||[],b="";for(let x=0;x<s;x++){let v=w[x]||"",{cleanText:N,formatHints:S}=Ie(v),y=[{kind:r&&!i?D.INSERTION:D.TEXT,text:N,rPrXml:h?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:N.length}],T=$e(y,null,S,{author:n,generateRedlines:r,revisionIdAllocator:o});b+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${T}</w:tc>`}m+=`<w:tr>${h?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${b}</w:tr>`}let d=`<w:tbl>${l}${u}${m}</w:tbl>`;return a&&(d=`<w:ins w:id="${a.id}" w:author="${Ne(a.author)}" w:date="${a.date}">${d}</w:ins>`),d}function Ni(e,t){let r=[],{headers:n,rows:o,hasHeader:i}=t,a=i?[n,...o]:o,s=Math.max(e.rowCount,a.length);for(let l=0;l<s;l++){if(l>=e.rowCount&&a[l]){r.push({type:"row_insert",gridRow:l,cells:a[l]});continue}if(l<e.rowCount&&!a[l]){r.push({type:"row_delete",gridRow:l});continue}let c=a[l];for(let u=0;u<e.colCount;u++){let f=e.grid[l]?.[u],m=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||m!==void 0&&f.getText()!==m&&r.push({type:"cell_modify",gridRow:l,gridCol:u,originalCell:f,newText:m}))}}return r}function vi(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,a=Nl(t),s="";for(let c=0;c<e.rowCount;c++){let u=a.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",m=0;for(;m<e.colCount;){let p=e.grid[c][m];if(!p){m++;continue}if(p.isMergeContinuation){m++;continue}let h=a.cellModifyByCoordinate.get(`${c}:${m}`)||null,w;h?w=vl(p,h.newText,r):w=yl(p.blocks),f+=Sl(p,w,r),m+=p.colSpan}let d=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=ie(o,i),h=`<w:del w:id="${p.id}" w:author="${Ne(p.author)}" w:date="${p.date}"/>`;d.includes("</w:trPr>")?d=d.replace("</w:trPr>",`${h}</w:trPr>`):d=`<w:trPr>${h}</w:trPr>`}s+=`<w:tr>${d}${f}</w:tr>`}let l=a.rowInsertOperations;for(let c of l){let u="",f=n?ie(o,i):null;for(let d of c.cells){let{cleanText:p,formatHints:h}=Ie(d),w=[{kind:n?D.INSERTION:D.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],b=$e(w,null,h,{author:o,generateRedlines:n,revisionIdAllocator:i});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${b}</w:tc>`}let m="<w:trPr/>";n&&(m=`<w:trPr><w:ins w:id="${f.id}" w:author="${Ne(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${m}${u}</w:tr>`}return`
126
+ `.trim(),u=`<w:tblGrid>${Array(l).fill("<w:gridCol/>").join("")}</w:tblGrid>`,f=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let p=0;p<f.length;p++){let h=e.hasHeader&&p===0,g=f[p]||[],v="";for(let y=0;y<l;y++){let x=g[y]||"",{cleanText:b,formatHints:I}=Ge(x),N=[{kind:r&&!o?q.INSERTION:q.TEXT,text:b,rPrXml:h?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:b.length}],T=gt(N,null,I,{author:n,generateRedlines:r,revisionIdAllocator:a});v+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${T}</w:tc>`}d+=`<w:tr>${h?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${v}</w:tr>`}let m=`<w:tbl>${s}${u}${d}</w:tbl>`;return i&&(m=`<w:ins w:id="${i.id}" w:author="${Ue(i.author)}" w:date="${i.date}">${m}</w:ins>`),m}function Bs(e,t){let r=[],{headers:n,rows:a,hasHeader:o}=t,i=o?[n,...a]:a,l=Math.max(e.rowCount,i.length);for(let s=0;s<l;s++){if(s>=e.rowCount&&i[s]){r.push({type:"row_insert",gridRow:s,cells:i[s]});continue}if(s<e.rowCount&&!i[s]){r.push({type:"row_delete",gridRow:s});continue}let c=i[s];for(let u=0;u<e.colCount;u++){let f=e.grid[s]?.[u],d=c?.[u];f&&(f.isMergeContinuation||u>f.gridCol||d!==void 0&&f.getText()!==d&&r.push({type:"cell_modify",gridRow:s,gridCol:u,originalCell:f,newText:d}))}}return r}function Ds(e,t,r){let{generateRedlines:n,author:a,revisionIdAllocator:o=null}=r,i=Df(t),l="";for(let c=0;c<e.rowCount;c++){let u=i.rowDeleteByRow.get(c)||null;if(u&&!n)continue;let f="",d=0;for(;d<e.colCount;){let p=e.grid[c][d];if(!p){d++;continue}if(p.isMergeContinuation){d++;continue}let h=i.cellModifyByCoordinate.get(`${c}:${d}`)||null,g;h?g=Ff(p,h.newText,r):g=$f(p.blocks),f+=Uf(p,g,r),d+=p.colSpan}let m=e.trPrList[c]||"<w:trPr/>";if(u&&n){let p=ae(a,o),h=`<w:del w:id="${p.id}" w:author="${Ue(p.author)}" w:date="${p.date}"/>`;m.includes("</w:trPr>")?m=m.replace("</w:trPr>",`${h}</w:trPr>`):m=`<w:trPr>${h}</w:trPr>`}l+=`<w:tr>${m}${f}</w:tr>`}let s=i.rowInsertOperations;for(let c of s){let u="",f=n?ae(a,o):null;for(let m of c.cells){let{cleanText:p,formatHints:h}=Ge(m),g=[{kind:n?q.INSERTION:q.TEXT,text:p,rPrXml:"",author:a,startOffset:0,endOffset:p.length}],v=gt(g,null,h,{author:a,generateRedlines:n,revisionIdAllocator:o});u+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${v}</w:tc>`}let d="<w:trPr/>";n&&(d=`<w:trPr><w:ins w:id="${f.id}" w:author="${Ue(f.author)}" w:date="${f.date}"/></w:trPr>`),l+=`<w:tr>${d}${u}</w:tr>`}return`
127
127
  <w:tbl>
128
128
  ${e.tblPrXml}
129
129
  ${e.tblGridXml}
130
- ${s}
130
+ ${l}
131
131
  </w:tbl>
132
- `}function Nl(e){let t=new Map,r=new Map,n=[];for(let o of e)o.type==="row_delete"?t.set(o.gridRow,o):o.type==="cell_modify"?r.set(`${o.gridRow}:${o.gridCol}`,o):o.type==="row_insert"&&n.push(o);return n.sort((o,i)=>o.gridRow-i.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function vl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,{cleanText:a,formatHints:s}=Ie(t),l=e.getText(),c=$r(l,a),u=e.blocks[0]||{runModel:[],pPr:null},f=Xr(u.runModel,c),m=Dr(f,c,{generateRedlines:n,author:o,formatHints:s});return $e(m,u.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:i})}function yl(e){return e.map(t=>$e(t.runModel,t.pPr,[],{})).join("")}function Sl(e,t,r){let n=e.tcPrXml;return e.colSpan>1&&!n.includes("gridSpan")?n=n.replace("</w:tcPr>",`<w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`):e.colSpan>1&&n==="<w:tcPr/>"&&(n=`<w:tcPr><w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`),e.rowSpan>1&&e.isMergeOrigin&&!n.includes("vMerge")?n=n.replace("</w:tcPr>",'<w:vMerge w:val="restart"/></w:tcPr>'):e.rowSpan>1&&e.isMergeOrigin&&n==="<w:tcPr/>"&&(n='<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>'),`<w:tc>${n}${t}</w:tc>`}function Xe(e){let t=e.split(`
133
- `).map(a=>a.trim()).filter(a=>a.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=a=>{let s=a.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(s)},n=t.some(r),i=t.filter(a=>!r(a)).map(a=>a.split("|").slice(1,-1).map(s=>s.trim()));return n?{headers:i[0]||[],rows:i.slice(1),hasHeader:!0}:{headers:[],rows:i,hasHeader:!1}}function I(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===E&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function O(e,t){return typeof e.createElementNS=="function"?e.createElementNS(E,t):e.createElement(t)}function yi(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(E,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>I(n,t))}var Si=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function zr(e){return Si.some(t=>yi(e,t).length>0)}function Dn(e){if(!e)return[];let t=new Set;for(let r of Si)for(let n of yi(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(E,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function Tl(e){let t=String(e||"").trim();return/^<\?xml\b[^>]*>\s*<pkg:package\b/i.test(t)||/^<pkg:package\b/i.test(t)?"package":/^<\?xml\b[^>]*>\s*<(?:w:)?document\b/i.test(t)||/^<(?:w:)?document\b/i.test(t)?"document":"fragment"}function se(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:Tl(e.oxml)}}async function _t(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:i=!0,author:a="AI",font:s=null,revisionIdAllocator:l=null,numberingService:c}=e,u=Al(t),f=El(u),m=f.map(y=>y.raw),d=[],p=Rl(n),h=Ti(n,p),w=Ti(n,p,["rFonts","kern","position","rtl","cs","lang"]),b=[];if(i){if(n&&n.length>0)b=n.filter(y=>y.kind==="text"||y.kind==="run").map(y=>({...y,kind:"deletion",author:a}));else if(o&&o.trim().length>0){let y=o.trim();b=[{kind:"deletion",text:y,author:a,startOffset:0,endOffset:y.length}]}}if(i&&b.length>0){let y=Ei(p,"del",a,l),T=$e(b,y,[],{author:a,generateRedlines:i,revisionIdAllocator:l});d.push(T)}let g=zn(m);L(`[ListGen] Detected indentation step: ${g} spaces/chars`);let x=f.find(y=>y.marker)?.marker||"",{format:v}=c.detectNumberingFormat(x);L(`[ListGen] Detected primary marker: "${x}", format: ${v}`);for(let y=0;y<f.length;y++){let T=Il(f,y);if(T){let _=Xe(T.tableText);if(_.headers.length>0||_.rows.length>0){d.push(ht(_,{generateRedlines:i,author:a,revisionIdAllocator:l,trackAsBlock:!0})),y=T.endIndex;continue}}let A=f[y],M=Pl(A,g,r,c,i,a,s,l,h,w);d.push(M.ooxml)}let N=c.generateNumberingXml(),S=d.join("");return L(`[ListGen] \u2705 Generated OOXML for ${d.length} paragraphs, total length: ${S.length}`),L(`[ListGen] First 200 chars: ${S.substring(0,200)}...`),{ooxml:S,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:N}}function zn(e){let t=e.map(n=>n.match(/^(\s*)/)[0].length).filter(n=>n>0).sort((n,o)=>n-o);if(t.length===0)return 2;let r=t[0];for(let n=1;n<t.length;n++){let o=t[n]-t[n-1];o>0&&o<r&&(r=o)}return r||2}function El(e){return e.split(`
134
- `).filter(t=>t.trim().length>0).map(t=>{let r=Fe(t),n=t.match(/^\s*(#{1,9})\s+(.*)/);return{raw:t,marker:r?r[2].trim():"",headerMatch:n,indentSize:t.match(/^(\s*)/)?.[1].length||0,isTableLine:/^\s*\|/.test(t),isTableSeparator:/^\s*\|?[\s:-]*-[-\s|:]*\|?\s*$/.test(t)}})}function Al(e){let t=String(e||"").split(`
135
- `),r=t.map((a,s)=>({line:a,index:s})).filter(a=>a.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:a,index:s}of r){let l=Fe(a);if(!l)return e;let c=je(a),u=Fe(c);if(!u)return e;let f=(l[2]||"").trim(),m=(u[2]||"").trim();if(!f||!m||f===m)return e;let p=`${l[1]||""}${c.trimStart()}`;n.push({index:s,rewritten:p}),o++}if(o<2)return e;let i=t.slice();for(let a of n)i[a.index]=a.rewritten;return L(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),i.join(`
136
- `)}function Il(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],i=t;for(;i<e.length&&e[i].isTableLine;)o.push(e[i].raw),i++;return{tableText:o.join(`
137
- `),endIndex:i-1}}function Pl(e,t,r,n,o,i,a,s,l,c){let u="",f="",m=l;if(e.headerMatch){let w=Math.min(e.headerMatch[1].length,9),b=Math.min(w-1,8),g=[32,28,26,24,22,20,20,20,20],x=g[w-1]||g[g.length-1];f=e.headerMatch[2].trim(),u=`<w:pPr><w:pStyle w:val="Heading${w}"/><w:outlineLvl w:val="${b}"/><w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr></w:pPr>`,m=Cl(c,`<w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr>`)}else if(e.marker){let w=n.detectNumberingFormat(e.marker),b=t>0?Math.floor(e.indentSize/t):0,g=r?.ilvl||0,x=w.format==="outline"?Math.min(8,w.depth):Math.min(8,b+g);f=je(e.raw);let v=n.getOrCreateNumId({type:w.format},r);u=n.buildListPPr(v,x)}else f=e.raw;o&&(u=Ei(u||"<w:pPr/>","ins",i,s));let{cleanText:d,formatHints:p}=Ie(f),h=[];return h.push({kind:o?"insertion":"run",text:d,rPrXml:m,author:i,startOffset:0,endOffset:d.length}),{ooxml:$e(h,u,p,{author:i,generateRedlines:o,font:a,revisionIdAllocator:s})}}function Rl(e){let t=(e||[]).find(r=>r.kind===D.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function Ti(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(i=>(i.kind===D.TEXT||i.kind==="text")&&i.rPrXml).map(i=>i.rPrXml);t&&n.push(typeof t=="string"?t:te(t));let o=[];for(let i of r){let a=null;for(let s of n)if(a=String(s||"").match(new RegExp(`<w:${i}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${i}>)`)),a)break;a&&o.push(a[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function Cl(...e){let t=e.map(r=>String(r||"").replace(/^\s*<w:rPr[^>]*>|<\/w:rPr>\s*$/g,"")).filter(Boolean).join("");return t?`<w:rPr>${t}</w:rPr>`:""}function Ei(e,t,r,n){let o=ie(r,n),i,a;if(e?.nodeType===1)i=e.cloneNode(!0),a=i.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=j(`<w:root xmlns:w="${E}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");a=u.doc,i=Array.from(a.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!i||!a)throw new Error("List paragraph properties are unavailable");let s=Array.from(i.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");s||(s=O(a,"w:rPr"),i.appendChild(s));let l=O(a,t==="del"?"w:del":"w:ins");return l.setAttribute("w:id",String(o.id)),l.setAttribute("w:author",o.author),l.setAttribute("w:date",o.date),s.appendChild(l),te(i)}var Ol=new Set(["officeonline","officeweb","web"]);function kl(e){return e?Ol.has(String(e).toLowerCase()):!1}function Ml(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function _l(){return new Promise(e=>setTimeout(e,0))}var ar=class{constructor(t={}){this.generateRedlines=t.generateRedlines??!0,this.author=t.author??"AI",this.validateOutput=t.validateOutput??!0,this.validationMode=t.validationMode??"auto",this.numberingService=t.numberingService||new Je,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??En(),this.isWebPlatform=t.isWebPlatform??kl(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let o=[];try{let i=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:j(t,"application/xml");if(i.error||!i.doc)return{ooxml:t,isValid:!1,status:"error",error:i.error,warnings:i.warnings||[]};o.push(...i.warnings||[]);let a=i.doc,s=re(a,"*","p"),{runModel:l,acceptedText:c,pPr:u}=kt(t,{xmlDoc:a}),f=s?or(s):null;L(`[Reconcile] Ingested ${l.length} runs, ${c.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(c.length,r?.length||0));let{cleanText:m,formatHints:d}=Ie(r);L(`[Reconcile] Preprocessed: ${d.length} format hints`),await this.maybeYield(l.length,Math.max(c.length,m.length));let p=In(m),h=Zt(m),w=p||h;if(!p&&h&&L("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===m&&d.length===0&&!w)return L("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let b=Math.max(c.length,m.length)<this.disableSemanticCleanupOverChars,g=$r(c,m,{cleanupSemantic:b});b||L("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(c.length,m.length));let x=l.filter(A=>A.kind===D.PARAGRAPH_START).length,v=In(c)||Zt(c),N=w&&v&&x>1&&c!==m;if(L(`[Reconcile] isTargetList: ${w}, paragraphCount: ${x}`),N)L("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(w)return L("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),L(`[Reconcile] cleanText preview: ${m.substring(0,100)}...`),L(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(m,f,l);L(`[Reconcile] Computed ${g.length} diff operations`);let S=Xr(l,g);L(`[Reconcile] Split into ${S.length} runs`);let y=Dr(S,g,{generateRedlines:this.generateRedlines,author:this.author,formatHints:d,numberingService:this.numberingService});L(`[Reconcile] Patched model has ${y.length} runs`),await this.maybeYield(y.length,Math.max(c.length,m.length));let T=$e(y,u,d,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let A=this.validateBasic(T);A.isValid||o.push(...A.errors)}return{ooxml:T,isValid:o.length===0,warnings:o}}catch(i){return ee("[Reconcile] Pipeline error:",i),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${i.message}`],error:i?.code?{code:i.code,message:i.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,o=j(n,"application/xml"),i=o.doc;if(o.error||!i)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let a=ne(i);a&&r.push("Generated OOXML is not well-formed XML: "+a.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&Ml()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await _l())}wrapForInsertion(t,r={}){return it(t,r)}async executeListGeneration(t,r,n,o=""){return _t({cleanText:t,numberingContext:r,originalRunModel:n,originalText:o,generateRedlines:this.generateRedlines,author:this.author,font:this.font,revisionIdAllocator:this.revisionIdAllocator,numberingService:this.numberingService})}detectIndentationStep(t){return zn(t)}executeTableGeneration(t){let r=Xe(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:ht(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var Ai=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function Ii(e){return!e||e.trim().length===0}function Pi(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Ll(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function Wn(e){return Ii(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":Pi(e)?"table":Fe(e)?"list":"paragraph"}function Wr(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
132
+ `}function Df(e){let t=new Map,r=new Map,n=[];for(let a of e)a.type==="row_delete"?t.set(a.gridRow,a):a.type==="cell_modify"?r.set(`${a.gridRow}:${a.gridCol}`,a):a.type==="row_insert"&&n.push(a);return n.sort((a,o)=>a.gridRow-o.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function Ff(e,t,r){let{generateRedlines:n,author:a,revisionIdAllocator:o=null}=r,{cleanText:i,formatHints:l}=Ge(t),s=e.getText(),c=ma(s,i),u=e.blocks[0]||{runModel:[],pPr:null},f=pa(u.runModel,c),d=ga(f,c,{generateRedlines:n,author:a,formatHints:l});return gt(d,u.pPr,l,{author:a,generateRedlines:n,revisionIdAllocator:o})}function $f(e){return e.map(t=>gt(t.runModel,t.pPr,[],{})).join("")}function Uf(e,t,r){let n=e.tcPrXml;return e.colSpan>1&&!n.includes("gridSpan")?n=n.replace("</w:tcPr>",`<w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`):e.colSpan>1&&n==="<w:tcPr/>"&&(n=`<w:tcPr><w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`),e.rowSpan>1&&e.isMergeOrigin&&!n.includes("vMerge")?n=n.replace("</w:tcPr>",'<w:vMerge w:val="restart"/></w:tcPr>'):e.rowSpan>1&&e.isMergeOrigin&&n==="<w:tcPr/>"&&(n='<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>'),`<w:tc>${n}${t}</w:tc>`}function et(e){let t=e.split(`
133
+ `).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let l=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)+\|?$/.test(l)},n=t.some(r),o=t.filter(i=>!r(i)).map(i=>i.split("|").slice(1,-1).map(l=>l.trim()));return n?{headers:o[0]||[],rows:o.slice(1),hasHeader:!0}:{headers:[],rows:o,hasHeader:!1}}function B(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===M&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function L(e,t){return typeof e.createElementNS=="function"?e.createElementNS(M,t):e.createElement(t)}function Fs(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(M,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>B(n,t))}var $s=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function Yt(e){return $s.some(t=>Fs(e,t).length>0)}function dr(e){if(!e)return[];let t=new Set;for(let r of $s)for(let n of Fs(e,r)){let a=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(M,"author"):null);a&&typeof a=="string"&&a.trim()&&t.add(a.trim())}return[...t].sort()}function zf(e){let t=String(e||"").trim();return/^<\?xml\b[^>]*>\s*<pkg:package\b/i.test(t)||/^<pkg:package\b/i.test(t)?"package":/^<\?xml\b[^>]*>\s*<(?:w:)?document\b/i.test(t)||/^<(?:w:)?document\b/i.test(t)?"document":"fragment"}function we(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:zf(e.oxml)}}async function Ur(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:a="",generateRedlines:o=!0,author:i="AI",font:l=null,revisionIdAllocator:s=null,numberingService:c}=e,u=Vf(t),f=Xf(u),d=f.map(N=>N.raw),m=[],p=Kf(n),h=Us(n,p),g=Us(n,p,["rFonts","kern","position","rtl","cs","lang"]),v=[];if(o){if(n&&n.length>0)v=n.filter(N=>N.kind==="text"||N.kind==="run").map(N=>({...N,kind:"deletion",author:i}));else if(a&&a.trim().length>0){let N=a.trim();v=[{kind:"deletion",text:N,author:i,startOffset:0,endOffset:N.length}]}}if(o&&v.length>0){let N=zs(p,"del",i,s),T=gt(v,N,[],{author:i,generateRedlines:o,revisionIdAllocator:s});m.push(T)}let w=ko(d);V(`[ListGen] Detected indentation step: ${w} spaces/chars`);let y=f.find(N=>N.marker)?.marker||"",{format:x}=c.detectNumberingFormat(y);V(`[ListGen] Detected primary marker: "${y}", format: ${x}`);for(let N=0;N<f.length;N++){let T=Wf(f,N);if(T){let _=et(T.tableText);if(_.headers.length>0||_.rows.length>0){m.push(fr(_,{generateRedlines:o,author:i,revisionIdAllocator:s,trackAsBlock:!0})),N=T.endIndex;continue}}let S=f[N],E=jf(S,w,r,c,o,i,l,s,h,g);m.push(E.ooxml)}let b=c.generateNumberingXml(),I=m.join("");return V(`[ListGen] \u2705 Generated OOXML for ${m.length} paragraphs, total length: ${I.length}`),V(`[ListGen] First 200 chars: ${I.substring(0,200)}...`),{ooxml:I,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:b}}function ko(e){let t=e.map(n=>n.match(/^(\s*)/)[0].length).filter(n=>n>0).sort((n,a)=>n-a);if(t.length===0)return 2;let r=t[0];for(let n=1;n<t.length;n++){let a=t[n]-t[n-1];a>0&&a<r&&(r=a)}return r||2}function Xf(e){return e.split(`
134
+ `).filter(t=>t.trim().length>0).map(t=>{let r=pt(t),n=t.match(/^\s*(#{1,9})\s+(.*)/);return{raw:t,marker:r?r[2].trim():"",headerMatch:n,indentSize:t.match(/^(\s*)/)?.[1].length||0,isTableLine:/^\s*\|/.test(t),isTableSeparator:/^\s*\|?[\s:-]*-[-\s|:]*\|?\s*$/.test(t)}})}function Vf(e){let t=String(e||"").split(`
135
+ `),r=t.map((i,l)=>({line:i,index:l})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],a=0;for(let{line:i,index:l}of r){let s=pt(i);if(!s)return e;let c=Tt(i),u=pt(c);if(!u)return e;let f=(s[2]||"").trim(),d=(u[2]||"").trim();if(!f||!d||f===d)return e;let p=`${s[1]||""}${c.trimStart()}`;n.push({index:l,rewritten:p}),a++}if(a<2)return e;let o=t.slice();for(let i of n)o[i.index]=i.rewritten;return V(`[ListGen] Normalized ${a} composite list markers (e.g., "- A." -> "A.").`),o.join(`
136
+ `)}function Wf(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let a=[],o=t;for(;o<e.length&&e[o].isTableLine;)a.push(e[o].raw),o++;return{tableText:a.join(`
137
+ `),endIndex:o-1}}function jf(e,t,r,n,a,o,i,l,s,c){let u="",f="",d=s;if(e.headerMatch){let g=Math.min(e.headerMatch[1].length,9),v=Math.min(g-1,8),w=[32,28,26,24,22,20,20,20,20],y=w[g-1]||w[w.length-1];f=e.headerMatch[2].trim(),u=`<w:pPr><w:pStyle w:val="Heading${g}"/><w:outlineLvl w:val="${v}"/><w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr></w:pPr>`,d=Hf(c,`<w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr>`)}else if(e.marker){let g=n.detectNumberingFormat(e.marker),v=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,y=g.format==="outline"?Math.min(8,g.depth):Math.min(8,v+w);f=Tt(e.raw);let x=n.getOrCreateNumId({type:g.format},r);u=n.buildListPPr(x,y)}else f=e.raw;a&&(u=zs(u||"<w:pPr/>","ins",o,l));let{cleanText:m,formatHints:p}=Ge(f),h=[];return h.push({kind:a?"insertion":"run",text:m,rPrXml:d,author:o,startOffset:0,endOffset:m.length}),{ooxml:gt(h,u,p,{author:o,generateRedlines:a,font:i,revisionIdAllocator:l})}}function Kf(e){let t=(e||[]).find(r=>r.kind===q.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function Us(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(o=>(o.kind===q.TEXT||o.kind==="text")&&o.rPrXml).map(o=>o.rPrXml);t&&n.push(typeof t=="string"?t:xe(t));let a=[];for(let o of r){let i=null;for(let l of n)if(i=String(l||"").match(new RegExp(`<w:${o}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${o}>)`)),i)break;i&&a.push(i[0])}return a.length>0?`<w:rPr>${a.join("")}</w:rPr>`:""}function Hf(...e){let t=e.map(r=>String(r||"").replace(/^\s*<w:rPr[^>]*>|<\/w:rPr>\s*$/g,"")).filter(Boolean).join("");return t?`<w:rPr>${t}</w:rPr>`:""}function zs(e,t,r,n){let a=ae(r,n),o,i;if(e?.nodeType===1)o=e.cloneNode(!0),i=o.ownerDocument;else{let c=typeof e=="string"&&e.trim()?e:"<w:pPr/>",u=j(`<w:root xmlns:w="${M}">${c}</w:root>`);if(!u.doc)throw new Error(u.error?.message||"Could not parse paragraph properties for list revision");i=u.doc,o=Array.from(i.documentElement.childNodes||[]).find(f=>f.nodeType===1&&f.localName==="pPr")}if(!o||!i)throw new Error("List paragraph properties are unavailable");let l=Array.from(o.childNodes||[]).find(c=>c.nodeType===1&&c.localName==="rPr");l||(l=L(i,"w:rPr"),o.appendChild(l));let s=L(i,t==="del"?"w:del":"w:ins");return s.setAttribute("w:id",String(a.id)),s.setAttribute("w:author",a.author),s.setAttribute("w:date",a.date),l.appendChild(s),xe(o)}var Gf=new Set(["officeonline","officeweb","web"]);function qf(e){return e?Gf.has(String(e).toLowerCase()):!1}function Yf(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function Zf(){return new Promise(e=>setTimeout(e,0))}var xn=class{constructor(t={}){this.generateRedlines=t.generateRedlines??!0,this.author=t.author??"AI",this.validateOutput=t.validateOutput??!0,this.validationMode=t.validationMode??"auto",this.numberingService=t.numberingService||new Mt,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??vo(),this.isWebPlatform=t.isWebPlatform??qf(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let a=[];try{let o=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:j(t,"application/xml");if(o.error||!o.doc)return{ooxml:t,isValid:!1,status:"error",error:o.error,warnings:o.warnings||[]};a.push(...o.warnings||[]);let i=o.doc,l=be(i,"*","p"),{runModel:s,acceptedText:c,pPr:u}=Fr(t,{xmlDoc:i}),f=l?vn(l):null;V(`[Reconcile] Ingested ${s.length} runs, ${c.length} chars, numbering:`,f),await this.maybeYield(s.length,Math.max(c.length,r?.length||0));let{cleanText:d,formatHints:m}=Ge(r);V(`[Reconcile] Preprocessed: ${m.length} format hints`),await this.maybeYield(s.length,Math.max(c.length,d.length));let p=xo(d),h=dn(d),g=p||h;if(!p&&h&&V("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===d&&m.length===0&&!g)return V("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let v=Math.max(c.length,d.length)<this.disableSemanticCleanupOverChars,w=ma(c,d,{cleanupSemantic:v});v||V("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(s.length,Math.max(c.length,d.length));let y=s.filter(S=>S.kind===q.PARAGRAPH_START).length,x=xo(c)||dn(c),b=g&&x&&y>1&&c!==d;if(V(`[Reconcile] isTargetList: ${g}, paragraphCount: ${y}`),b)V("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(g)return V("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),V(`[Reconcile] cleanText preview: ${d.substring(0,100)}...`),V(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(d,f,s);V(`[Reconcile] Computed ${w.length} diff operations`);let I=pa(s,w);V(`[Reconcile] Split into ${I.length} runs`);let N=ga(I,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:m,numberingService:this.numberingService});V(`[Reconcile] Patched model has ${N.length} runs`),await this.maybeYield(N.length,Math.max(c.length,d.length));let T=gt(N,u,m,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let S=this.validateBasic(T);S.isValid||a.push(...S.errors)}return{ooxml:T,isValid:a.length===0,warnings:a}}catch(o){return ye("[Reconcile] Pipeline error:",o),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${o.message}`],error:o?.code?{code:o.code,message:o.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,a=j(n,"application/xml"),o=a.doc;if(a.error||!o)return r.push("Generated OOXML is not well-formed XML: "+(a.error?.message||"parse error")),{isValid:!1,errors:r};let i=Ne(o);i&&r.push("Generated OOXML is not well-formed XML: "+i.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&Yf()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await Zf())}wrapForInsertion(t,r={}){return qt(t,r)}async executeListGeneration(t,r,n,a=""){return Ur({cleanText:t,numberingContext:r,originalRunModel:n,originalText:a,generateRedlines:this.generateRedlines,author:this.author,font:this.font,revisionIdAllocator:this.revisionIdAllocator,numberingService:this.numberingService})}detectIndentationStep(t){return ko(t)}executeTableGeneration(t){let r=et(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:fr(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var Xs=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function Vs(e){return!e||e.trim().length===0}function Ws(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function Jf(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function Mo(e){return Vs(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":Ws(e)?"table":pt(e)?"list":"paragraph"}function ha(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
138
138
  `):String(e??"")).split(`
139
- `),n=[],o=[],i=0;for(;i<r.length;){if(Ii(r[i])){i++;continue}let l=Wn(r[i]),c=i+1;if(l==="heading"){let m=r[i].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:m[1].length,text:m[2],markdown:r[i].trim()}),i++;continue}if(l==="table"){let m=[];for(;i<r.length&&Pi(r[i]);)m.push(r[i].trim()),i++;let d=m.length>1&&Ai.test(m[1]),p=m.filter(h=>!Ai.test(h)).map(h=>Ll(h).length);d||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?o.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&o.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:d,markdown:m.join(`
140
- `)});continue}if(l==="list"){let m=[];for(;i<r.length&&Wn(r[i])==="list";)m.push(r[i].trimEnd()),i++;n.push({type:"list",items:m.length,markdown:m.join(`
141
- `)});continue}let u=[];for(;i<r.length&&Wn(r[i])==="paragraph";)u.push(r[i].trim()),i++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let a={heading:0,paragraph:0,list:0,table:0};for(let l of n)a[l.type]=(a[l.type]||0)+1;let s=n.map(l=>l.markdown).join(`
139
+ `),n=[],a=[],o=0;for(;o<r.length;){if(Vs(r[o])){o++;continue}let s=Mo(r[o]),c=o+1;if(s==="heading"){let d=r[o].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:d[1].length,text:d[2],markdown:r[o].trim()}),o++;continue}if(s==="table"){let d=[];for(;o<r.length&&Ws(r[o]);)d.push(r[o].trim()),o++;let m=d.length>1&&Xs.test(d[1]),p=d.filter(h=>!Xs.test(h)).map(h=>Jf(h).length);m||a.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?a.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&a.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:m,markdown:d.join(`
140
+ `)});continue}if(s==="list"){let d=[];for(;o<r.length&&Mo(r[o])==="list";)d.push(r[o].trimEnd()),o++;n.push({type:"list",items:d.length,markdown:d.join(`
141
+ `)});continue}let u=[];for(;o<r.length&&Mo(r[o])==="paragraph";)u.push(r[o].trim()),o++;let f=u.join(" ").trim();n.push({type:"paragraph",text:f,markdown:f})}let i={heading:0,paragraph:0,list:0,table:0};for(let s of n)i[s.type]=(i[s.type]||0)+1;let l=n.map(s=>s.markdown).join(`
142
142
 
143
- `);return{valid:o.every(l=>l.severity!=="error"),normalizedMarkdown:s,blocks:n,issues:o,counts:a,requiresStructuredContent:n.length>1||n.some(l=>l.type==="heading"||l.type==="table"||l.type==="list"&&l.items>1)}}function Bl(e,t,r={}){let n=Wr(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var sr=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function Lt(e,t){let r=sr.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let i of Array.from(e.childNodes)){if(i.nodeType!==1)continue;let a=sr.indexOf(i.nodeName);if((a===-1?999:a)>n){e.insertBefore(t,i),o=!0;break}}o||e.appendChild(t)}function Fl(e,t,r,n){if(!t||!r)return;let o=!!r.bold,i=!!r.italic,a=!!r.underline,s=!!r.strikethrough,l=new Set;if(o&&(l.add("w:b"),l.add("w:bCs")),i&&(l.add("w:i"),l.add("w:iCs")),a&&l.add("w:u"),s&&l.add("w:strike"),l.size>0){let c=[];for(let u of Array.from(t.childNodes))l.has(u.nodeName)&&c.push(u);for(let u of c)t.removeChild(u)}if(o){let c=O(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=O(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(i){let c=O(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c);let u=O(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,u)}if(a){let c=O(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Lt(t,c)}if(s){let c=O(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Lt(t,c)}}function Ri(e,t,r){Fl(e,t,r,"remove")}function qe(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=Ur(r,!1)),r.nodeName==="w:i"&&(t.italic=Ur(r,!1)),r.nodeName==="w:u"&&(t.underline=Ur(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Ur(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let o=n.toLowerCase();(o.includes("bold")||o.includes("strong"))&&(t.bold=!0),(o.includes("italic")||o.includes("emphasis"))&&(t.italic=!0),o.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function Ur(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var Ci="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function He(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Ci&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function $l(e){return!e||e.nodeType!==1||e.namespaceURI!==Ci?!1:e.localName==="del"||e.localName==="moveFrom"}function Oi(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||$l(n))continue;if(He(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let i=o.length-1;i>=0;i-=1)r.push(o[i])}return t}function Pe(e){let t=new Set(["comment","footnote","endnote"]);return ce(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let i=String(o.localName||"").toLowerCase();if(t.has(i))return!1;o=o.parentNode}return!0})}function ki(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],i=Oi(o);for(let a of i){let s=ae(a,"w:rPr");Array.from(a.childNodes||[]).forEach(l=>{if(He(l,"t")){let c=l.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=c.length)}else(He(l,"br")||He(l,"cr")||He(l,"tab")||He(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=1)})}r=pt(r,n,e.length)}return{textSpans:t,charOffset:r}}function Xl(e,t,r,n,o,i=null){let a=null;for(let c of Array.from(e.childNodes))if(He(c,"rPr")){a=c;break}let s=qe(a);i&&(i.bold&&!s.bold&&(s.bold=!0),i.italic&&!s.italic&&(s.italic=!0),i.underline&&!s.underline&&(s.underline=!0),i.strikethrough&&!s.strikethrough&&(s.strikethrough=!0)),s.hasFormatting=s.bold||s.italic||s.underline||s.strikethrough;let l=r;for(let c of Array.from(e.childNodes))if(He(c,"t")){let u=c.textContent||"";if(u.length>0){let f=l,m=l+u.length;n.push({charStart:f,charEnd:m,textElement:c,runElement:e,paragraph:t,rPr:a,format:{...s}}),s.hasFormatting&&o.push({start:f,end:m,format:{...s},run:e,rPr:a}),l=m}}return l}function Mi(e){let t=[],r=[],n=0,o=Pe(e);for(let i=0;i<o.length;i++){let a=o[i],s=null;for(let u of Array.from(a.childNodes))if(He(u,"pPr")){for(let f of Array.from(u.childNodes))if(He(f,"rPr")){s=f;break}break}let l=qe(s);l.hasFormatting&&L(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let c=Oi(a);for(let u of c)n=Xl(u,a,n,r,t,l);n=pt(n,i,o.length)}return L(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var Dl=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function jr(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())Dl.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function at(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof we?t:Ye(r)||nt(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let i of o){if(!I(i,"rPrChange"))continue;let a=String(n.next());typeof i.setAttributeNS=="function"?i.setAttributeNS(E,"w:id",a):i.setAttribute("w:id",a),n._receiptCollector?.recordRevision(Number(a),"rPrChange")}return e}function wt(e,t,r,n,o=null){let i=O(e,t==="ins"?"w:ins":"w:del"),a=o||ie(n,e,t==="ins"?"ins":"del");return i.setAttribute("w:id",String(a.id)),i.setAttribute("w:author",a.author),i.setAttribute("w:date",a.date),r&&i.appendChild(r),i}function _i(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function zl(e,t){let r=_i(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=O(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function Wl(e,t){let r=_i(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=O(e,"w:rPr"),t.appendChild(r)),r}function Li(e,t,r,n,o=null){let i=zl(e,t),a=Wl(e,i);for(let c of Array.from(a.childNodes||[]))c.nodeType===1&&(c.localName==="ins"||c.localName==="del"||c.nodeName==="w:ins"||c.nodeName==="w:del")&&a.removeChild(c);let s=O(e,n==="ins"?"w:ins":"w:del"),l=o||ie(r,e,n==="ins"?"ins":"del");return s.setAttribute("w:id",String(l.id)),s.setAttribute("w:author",l.author),s.setAttribute("w:date",l.date),a.appendChild(s),s}function Bi(e,t,r,n=null){return Li(e,t,r,"ins",n)}function lr(e,t,r,n=null){return Li(e,t,r,"del",n)}function st(e,t,r,n){let o=O(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Fi(e,o,t),o;let i=O(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function Hr(e,t,r,n,o,i,a){if(!t)return[];let s=new Set([0,t.length]);for(let u of n){let f=Math.max(0,u.start-o),m=Math.min(t.length,u.end-o);f>=0&&f<t.length&&s.add(f),m>0&&m<=t.length&&s.add(m)}let l=Array.from(s).sort((u,f)=>u-f),c=[];for(let u=0;u<l.length-1;u++){let f=l[u],m=l[u+1],d=t.slice(f,m);if(!d)continue;let p=o+f,h=o+m,w=n.filter(x=>x.start<=p&&x.end>=h),b={...qe(r)};w.forEach(x=>{x.format&&Object.assign(b,x.format)});let g=w.length>0?Bt(e,r,b,i,a):r?.cloneNode(!0)||null;c.push(Un(e,d,g,!1))}return c}function Un(e,t,r,n){let o=O(e,"w:r");if(r&&o.appendChild(r),!n)return Fi(e,o,t),o;let i=O(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function Fi(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let i of o){if(!i)continue;if(i===" "){t.appendChild(O(e,"w:tab"));continue}if(i===`
144
- `){t.appendChild(O(e,"w:br"));continue}if(i==="\u2011"){t.appendChild(O(e,"w:noBreakHyphen"));continue}let a=O(e,"w:t");/^\s|\s$/.test(i)&&a.setAttribute("xml:space","preserve"),a.textContent=i,t.appendChild(a)}}function Bt(e,t,r,n,o){let i=O(e,"w:rPr");t&&Array.from(t.childNodes).forEach(l=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(l.nodeName)||i.appendChild(l.cloneNode(!0))});let a=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&Ul(e,i,n,t);let s=(l,c,u=null,f="0")=>{let m=O(e,l);c?u&&m.setAttribute("w:val",u):f&&m.setAttribute("w:val",f);let d=sr.indexOf(l),p=d===-1?999:d,h=!1;for(let w of Array.from(i.childNodes)){if(w.nodeType!==1)continue;let b=sr.indexOf(w.nodeName);if((b===-1?999:b)>p){i.insertBefore(m,w),h=!0;break}}h||i.appendChild(m)};return s("w:b",!!a.bold,"1","0"),s("w:bCs",!!a.bold,"1","0"),s("w:i",!!a.italic,"1","0"),s("w:iCs",!!a.italic,"1","0"),s("w:u",!!a.underline,"single","none"),s("w:strike",!!a.strikethrough,"1","0"),i}function jn(e,t,r,n,o){let i=O(e,"w:rPrChange"),a=ie(r,e,"rPrChange");i.setAttribute("w:id",String(a.id)),i.setAttribute("w:author",a.author),i.setAttribute("w:date",n||a.date);let l=jr(o||t)||O(e,"w:rPr");i.appendChild(l);let c=ae(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(i),i}function Ul(e,t,r,n){jn(e,t,r,null,n||t)}var jl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Ft(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===jl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Vr(e,t,r){let n=new Map;for(let a of r)!a||!a.paragraph||(n.has(a.paragraph)||n.set(a.paragraph,[]),n.get(a.paragraph).push(a));let o=[],i=0;return t.forEach((a,s)=>{let l=(n.get(a)||[]).slice().sort((m,d)=>m.charStart-d.charStart),c=Hl(l),u=Hn(c),f=u.trim();o.push({paragraph:a,spans:l,text:c,normalizedText:u,normalizedTrim:f,startOffset:i}),i+=u.length,i=pt(i,s,t.length)}),o}function $i(e,t){if(!t)return null;let r=Hn(t),n=r.trim();if(!n)return null;for(let o of e)if(o.normalizedText===r)return o;for(let o of e)if(o.normalizedTrim===n)return o;return null}function Xi(e,t){let r=Hn(t),n=r.trim(),o=null,i=0;for(let a of e)if(a.normalizedText===r)return o=a,{targetInfo:o,matchOffset:i};if(n.length>0){for(let a of e)if(a.normalizedTrim===n)return o=a,{targetInfo:o,matchOffset:i}}if(n.length>0){let s=e.map(l=>l.normalizedText).join(`
145
- `).indexOf(n);if(s!==-1)for(let l of e){let c=l.startOffset,u=l.normalizedText.length;if(s>=c&&s<=c+u){o=l,i=s-c;break}}}if(!o&&e.length===1&&r.length>0){let a=e[0],s=a.normalizedTrim||"";if(s.length>0){let l=r.indexOf(s);l>=0&&(o=a,i=-l)}}return{targetInfo:o,matchOffset:i}}function Di(e){let t=e;for(;t;){if(Ft(t,"p"))return t;t=t.parentNode}return null}function Hl(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Ft(n,"t")?t+=r.textElement.textContent||"":Ft(n,"tab")?t+=" ":Ft(n,"br")||Ft(n,"cr")?t+=`
146
- `:Ft(n,"noBreakHyphen")&&(t+="\u2011")}return t}function Hn(e){return e?e.replace(/\r/g,`
147
- `).replace(/\u00a0/g," "):""}function zi(e,t,r){let n=Array.from(new Set(r)).sort((s,l)=>s-l);if(n.length===0||t.length===0)return[...t];let o=[...t].sort((s,l)=>s.charStart-l.charStart||s.charEnd-l.charEnd),i=[],a=0;for(let s of o){for(;a<n.length&&n[a]<=s.charStart;)a++;let l=s;for(;a<n.length&&n[a]<l.charEnd;){let c=n[a],u=Vl(e,l,c);if(!u){a++;continue}i.push(u[0]),l=u[1],a++}i.push(l)}return i}function Vl(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let i=t.textElement.textContent||"",a=r-t.charStart,s=i.substring(0,a),l=i.substring(a);if(s.length===0||l.length===0)return null;let c=st(e,s,t.rPr,!1),u=st(e,l,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(u,n),o.removeChild(n);let f=c.getElementsByTagName("w:t")[0],m=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:m,runElement:u}]}var Gl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Kl(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Gl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Yl(e){return Array.isArray(e)?{textSpans:e,paragraphs:null,paragraphInfos:null}:!e||typeof e!="object"?{textSpans:null,paragraphs:null,paragraphInfos:null}:{textSpans:Array.isArray(e.textSpans)?e.textSpans:null,paragraphs:Array.isArray(e.paragraphs)?e.paragraphs:null,paragraphInfos:Array.isArray(e.paragraphInfos)?e.paragraphInfos:null}}function Wi(e,t,r,n,o,i=!0){let a=!1,s=new Set;L(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let l of r){let c=l.run;if(s.has(c)||(s.add(c),!c.parentNode))continue;L("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let u=ae(c,"w:rPr");u||(u=O(e,"w:rPr"),c.insertBefore(u,c.firstChild)),i&&jn(e,u,o||pe()),Ri(e,u,l.format),a=!0}return a?(L("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(L("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function Jl(e,t,r,n,o,i=!0){let a=!1,s=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let l=[];for(let m of r)l.push(m.start,m.end);let u=zi(e,t,l).slice().sort((m,d)=>m.charStart-d.charStart||m.charEnd-d.charEnd),f=ql(r);for(let m of u){if(!m||!m.textElement||!Kl(m.textElement,"t"))continue;let d=f(m.charStart,m.charEnd);if(d.length===0)continue;let p=An(...d.map(M=>M.format)),h={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},w=m.format||qe(m.rPr),b={bold:!!w.bold,italic:!!w.italic,underline:!!w.underline,strikethrough:!!w.strikethrough};if(!["bold","italic","underline","strikethrough"].some(M=>h[M]!==b[M])||s.has(m.runElement)||(s.add(m.runElement),!(m.textElement.textContent||""))||!m.runElement.parentNode)continue;let S=m.runElement,y=ae(S,"w:rPr"),T=Bt(e,y,h,o||pe(),i),A=y;if(!A)S.insertBefore(T,S.firstChild);else{for(;A.firstChild;)A.removeChild(A.firstChild);Array.from(T.childNodes).forEach(M=>A.appendChild(M))}a=!0}return{oxml:n.serializeToString(e),hasChanges:a}}function Ui(e,t,r,n,o,i=!0,a=null){let s=Yl(a),l=s.paragraphs||Pe(e),c=s.textSpans||[];if(s.textSpans||({textSpans:c}=ki(l)),!c||c.length===0)return Be("[OxmlEngine] No spans available for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};if(!r||r.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let u=s.paragraphInfos||Vr(e,l,c),{targetInfo:f,matchOffset:m}=Xi(u,t);if(!f||!f.spans||f.spans.length===0)return Be("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let d=f.spans[0].charStart,p=f.spans.map(w=>({...w,charStart:w.charStart-d,charEnd:w.charEnd-d})),h=r.map(w=>({...w,start:w.start+m,end:w.end+m}));return Jl(e,p,h,n,o,i)}function ql(e){let t=(e||[]).slice().sort((o,i)=>o.start-i.start||o.end-i.end),r=[],n=0;return(o,i)=>{for(;n<t.length&&t[n].start<i;)r.push(t[n]),n++;for(let a=r.length-1;a>=0;a--)r[a].end<=o&&r.splice(a,1);return r.filter(a=>a.start<i&&a.end>o)}}function Gr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function bt(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let i=Gr(o);if(n==="accepted"&&(i==="del"||i==="moveFrom")||n==="rejected"&&(i==="ins"||i==="moveTo"))return!1;o=o.parentNode}return!0}function xt(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!bt(e,n,r))return"";let o="",i=a=>{for(let s of Array.from(a?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==E||!bt(s,n,r))continue;let l=Gr(s);l==="t"||l==="delText"&&r==="rejected"?o+=s.textContent||"":l==="tab"?o+=" ":l==="br"||l==="cr"?o+=`
148
- `:l==="noBreakHyphen"?o+="\u2011":l==="softHyphen"?o+="\xAD":i(s)}};return i(e),o}var lt=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Kr(e,t={}){if(!e)return[];let r=[];function n(f,m,d){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==E)continue;let h=Gr(p);if(h==="pPr"||h==="rPr")continue;let w=m;h==="ins"?w={kind:"insertion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="del"?w={kind:"deletion",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="moveFrom"?w={kind:"move_from",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0}:h==="moveTo"&&(w={kind:"move_to",author:lt(p,"author")||void 0,revisionId:lt(p,"id")||void 0});let b=d;h==="r"&&(b=p);let g=null,x=w?w.kind:"baseline",v=w?.author,N=w?.revisionId;h==="t"?g=p.textContent||"":h==="delText"?(g=p.textContent||"",w||(x="deletion")):h==="tab"?g=" ":h==="br"||h==="cr"?g=`
149
- `:h==="noBreakHyphen"?g="\u2011":h==="softHyphen"&&(g="\xAD"),g!==null?g.length>0&&r.push({text:g,kind:x,author:v,revisionId:N,carrier:b||p,carrierContainer:(b||p)?.parentNode||null}):n(p,w,b)}}let o=Gr(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let i=t.mergeRuns!==!1,a=[],s=null;for(let f of r){if(!s){s={...f};continue}let m=s.kind===f.kind,d=s.author===f.author,p=s.revisionId===f.revisionId,h=s.carrier===f.carrier,w=i&&s.carrierContainer===f.carrierContainer;m&&d&&p&&(h||w)?s.text+=f.text:(a.push(s),s={...f})}s&&a.push(s);let l=0,c=0,u=[];for(let f of a){let m=f.kind!=="deletion"&&f.kind!=="move_from",d=f.kind!=="insertion"&&f.kind!=="move_to",p=m?l:null,h=d?c:null;m&&(l+=f.text.length),d&&(c+=f.text.length);let w={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:h};f.author!==void 0&&(w.author=f.author),f.revisionId!==void 0&&(w.revisionId=f.revisionId),u.push(w)}return u}function fe(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Kr(e,t);return r==="rejected"?n.filter(o=>o.rejectedStart!==null).map(o=>o.text).join(""):n.filter(o=>o.acceptedStart!==null).map(o=>o.text).join("")}var Zl="http://schemas.microsoft.com/office/word/2010/wordml";function ji(e,t,r={}){let{targetParagraphId:n=null}=r,o=ve(e,E,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let a=Pe(e).filter(l=>{let c=l.parentNode;for(;c;){if(I(c,"tc"))return!0;c=c.parentNode}return!1});L(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${a.length} paragraphs in cells`);let s=null;if(n){let l=String(n).toUpperCase();s=a.find(c=>{let u=ec(c);return u&&u.toUpperCase()===l})||null,s?L(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):L(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let l=t.trim();if(!s){for(let c of a)if(fe(c).trim()===l){s=c,L(`[OxmlEngine] Found target paragraph by text match: "${l.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:a.length>0,targetParagraph:s,paragraphs:a,paragraph:s||a[0]||null,tableElement:o[0]}}function cr(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let i of n){if(!i)continue;let a=r.serializeToString(i);a=a.replace(/\s+xmlns:w="[^"]*"/g,""),a=a.replace(/\s+xmlns:r="[^"]*"/g,""),a=a.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=a}return L(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),L(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),Ql(o)}function Ql(e){return wi(e)}function ec(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Zl,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Vn(e){return I(e,"t")||I(e,"delText")?e.textContent||"":I(e,"br")||I(e,"cr")?`
150
- `:I(e,"tab")?" ":I(e,"noBreakHyphen")?"\u2011":I(e,"softHyphen")?"\xAD":""}function Gn(e){return I(e,"t")||I(e,"delText")||I(e,"br")||I(e,"cr")||I(e,"tab")||I(e,"noBreakHyphen")||I(e,"softHyphen")}function Yr(e){let t="",r=[];return e.forEach((n,o)=>{let i=n.parentNode;for(let a=n.firstChild;a;a=a.nextSibling)if(I(a,"r"))t+=ur(a,n,i,t.length,r).text;else if(I(a,"hyperlink"))for(let s=a.firstChild;s;s=s.nextSibling)I(s,"r")&&(t+=ur(s,n,i,t.length,r).text);else if(I(a,"ins"))for(let s=a.firstChild;s;s=s.nextSibling)I(s,"r")&&(t+=ur(s,n,i,t.length,r).text);else if(I(a,"sdt")){let s=Array.from(a.childNodes||[]).find(l=>I(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)I(l,"r")&&(t+=ur(l,n,i,t.length,r).text)}else if(I(a,"smartTag"))for(let s=a.firstChild;s;s=s.nextSibling)I(s,"r")&&(t+=ur(s,n,i,t.length,r).text);t=Ct(t,o,e.length)}),{fullText:t,textSpans:r}}function ur(e,t,r,n,o){let i=ae(e,"w:rPr"),a=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(I(l,"t")){let c=l.textContent||"";if(c.length===0)continue;o.push({charStart:a,charEnd:a+c.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=c.length,s.push(c)}else if(Gn(l)){let c=Vn(l);o.push({charStart:a,charEnd:a+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=1,s.push(c)}return{text:s.join("")}}function Jr(e){let t=e.slice().sort((o,i)=>o.charStart-i.charStart||o.charEnd-i.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function fr(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=qn(e.ends,t);for(;o<e.spans.length;){let i=e.spans[o];if(i.charStart>=r)break;n(i),o++}}function Kn(e,t){if(e.spans.length===0)return null;let r=qn(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function Yn(e,t){let r=tc(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Jn(e,t){let r=qn(e.ends,t)-1;return r>=0?e.spans[r]:null}function qn(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<=t?r=o+1:n=o}return r}function tc(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<t?r=o+1:n=o}return r}function Hi(e,t,r=null){if(!e||!e.spans||e.spans.length===0)return{leftSpan:null,rightSpan:null,containingSpan:null,isInterior:!1,fallbackParagraph:r};let n=Kn(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,i=Yn(e,t)||(t>0?Jn(e,t):null),a=e.spans.find(s=>s.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:i,rightSpan:a,containingSpan:n,isInterior:o,fallbackParagraph:r}}var rc=new Set(["ins","del"]);function $t(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(I(n,"rPr")||!Gn(n))continue;let o=Vn(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function Ve(e){return e.length===0?0:e[e.length-1].end}function Ge(e,t,r,n,o){let i=[];return n<=r||t.forEach(a=>{let s=Math.max(r,a.start),l=Math.min(n,a.end);if(l<=s)return;let c=s-a.start,u=l-a.start,f=a.text.slice(c,u);i.push(ac(e,a.node,f,o))}),i}function mr(e,t,r){let n=O(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function Nt(e,t,r,n,o){if(n.length===0)return null;let i=mr(e,n,o);return t.insertBefore(i,r),i}function Vi(e,t,r,n=null){let o=ic(t);if(!rc.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let i=Array.from(t.childNodes||[]),a=i.reduce((m,d)=>m+(I(d,"r")?Ve($t(d)):0),0);if(r>a)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${a}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===a)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let s=t.cloneNode(!1),l=t.cloneNode(!1),c=0;for(let m of i){if(!I(m,"r")){(c<=r?s:l).appendChild(m.cloneNode(!0));continue}let d=$t(m),p=Ve(d),h=c+p;if(h<=r)s.appendChild(m.cloneNode(!0));else if(c>=r)l.appendChild(m.cloneNode(!0));else{let w=r-c,b=Array.from(m.childNodes||[]).find(S=>I(S,"rPr"))||null,g=o==="del",x=Ge(e,d,0,w,g),v=Ge(e,d,w,p,g);s.appendChild(mr(e,x,b));let N=mr(e,v,b);l.appendChild(N)}c=h}let u=nc(e,n);at(l,u);let f=u.next();return oc(l,"id",String(f)),u._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function nc(e,t){return t instanceof we?t:Ye(e)||nt(e)}function oc(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(E,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function ic(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function ac(e,t,r,n){if(n&&(I(t,"delText")||I(t,"t"))){let i=O(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}if(I(t,"t")){let i=t.cloneNode(!1);return i.textContent=r,/^\s|\s$/.test(r)&&i.setAttribute("xml:space","preserve"),i}if(r===`
151
- `&&(I(t,"br")||I(t,"cr"))||r===" "&&I(t,"tab")||r==="\u2011"&&I(t,"noBreakHyphen")||r==="\xAD"&&I(t,"softHyphen"))return t.cloneNode(!0);if(n){let i=O(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}let o=O(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Yi(e,t,r,n,o,i,a){if(o.length===0)return!1;let s=t.rPr,l=qe(s),c={...l};if(o.forEach(S=>Object.assign(c,S.format)),!["bold","italic","underline","strikethrough"].some(S=>!!c[S]!==l[S]))return!1;let m=t.runElement.parentNode;if(!m)return!1;let d=t.textElement.textContent||"",p=t.charStart,h=r-p,w=n-p,b=d.substring(0,h),g=d.substring(h,w),x=d.substring(w);if(b.length>0){let S=st(e,b,s,!1);m.insertBefore(S,t.runElement)}let v=Bt(e,s,c,i,a),N=Un(e,g,v,!1);if(m.insertBefore(N,t.runElement),x.length>0){let S=st(e,x,s,!1);m.insertBefore(S,t.runElement)}return m.removeChild(t.runElement),!0}function eo(e,t,r,n,o,i,a=null){let s=[];if(fr(t,r,n,d=>{s.push(d)}),s.length===0)return!1;let l=new Map;s.forEach(d=>{d.runElement?.parentNode&&(l.has(d.runElement)||l.set(d.runElement,[]),l.get(d.runElement).push(d))});let c=[];l.forEach((d,p)=>{let h=p.parentNode;if(!h)return;let w=$t(p);if(w.length===0)return;let b=1/0,g=-1/0;d.forEach(x=>{let v=w.find(y=>y.node===x.textElement);if(!v)return;let N=Math.max(0,r-x.charStart),S=Math.min(x.charEnd-x.charStart,n-x.charStart);S<=N||(b=Math.min(b,v.start+N),g=Math.max(g,v.start+S))}),!(!Number.isFinite(b)||g<=b)&&c.push({runElement:p,parent:h,rPr:d[0].rPr,beforePieces:Ge(e,w,0,b,!1),deletedPieces:Ge(e,w,b,g,!0),afterPieces:Ge(e,w,g,Ve(w),!1),globalStart:Math.max(r,Math.min(...d.map(x=>x.charStart))),globalEnd:Math.min(n,Math.max(...d.map(x=>x.charEnd))),carrierGlobalStart:I(h,"ins")?Ji(t,h):null})});let u=[];for(let d of c){let p=u[u.length-1],h=p?.[p.length-1];h&&h.parent===d.parent&&cc(h.runElement)===d.runElement?p.push(d):u.push([d])}let f=!1,m=!1;for(let d of u){let p=d[0],h=null;if(i&&d.some(g=>g.deletedPieces.length>0)){let g=a?m?{...a,id:ie(o,e,"del").id}:a:null;m=!0,h=wt(e,"del",null,o,g)}for(let g of d){let{parent:x,runElement:v}=g;Nt(e,x,v,g.beforePieces,g.rPr),h&&g===p&&x.insertBefore(h,v),h&&g.deletedPieces.length>0&&h.appendChild(mr(e,g.deletedPieces,g.rPr));let N=Nt(e,x,v,g.afterPieces,g.rPr);g.globalEnd===n&&!I(x,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:x,referenceNode:N||v.nextSibling,rPr:g.rPr})),x.removeChild(v),f=!0}let w=I(p.parent,"ins")?p.parent:null,b=Math.max(...d.map(g=>g.globalEnd));if(w&&b===n){let g=p.carrierGlobalStart,x=d.filter(N=>N.globalStart<n).reduce((N,S)=>N+S.deletedPieces.reduce((y,T)=>y+(T.textContent||"").length,0),0),v=Math.max(0,n-g-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:w,splitOffset:v,rPr:p.rPr})}}return f}function Xt(e,t,r,n,o,i=[],a=0,s=!0,l=null,c=null,u=null,f="merge-same-author"){let m=t.revisionInsertionAnchors?.get(r)||null;if(m&&f==="slice-cross-author"&&Ki(m.carrier)&&Qn(m.carrier,o))return t.revisionInsertionAnchors.delete(r),Zn(e,m.carrier,m.splitOffset,n,m.rPr,o,i,a,s,c);let d=t.replacementInsertionAnchors?.get(r)||null;if(d&&!u&&Ki(d.parent)&&(!d.referenceNode||d.referenceNode.parentNode===d.parent))return t.replacementInsertionAnchors.delete(r),ct(e,d.parent,d.referenceNode,n,d.rPr,o,i,a,s,c),!0;if(!u){let N=Kn(t,r);if(!N&&r>0&&(N=Yn(t,r)),!N&&r>0&&(N=Jn(t,r)),!N&&t.spans.length>0&&(N=t.spans[t.spans.length-1]),!N)return l?(ct(e,l,null,n,null,o,i,a,s,c),!0):!1;let S=N.runElement.parentNode;if(!S)return l?(ct(e,l,null,n,N.rPr,o,i,a,s,c),!0):!1;let y=!(s&&f==="slice-cross-author"&&lc(S,o));if(s&&f==="slice-cross-author"&&Qn(S,o))return Zn(e,S,Gi(t,S,r),n,N.rPr,o,i,a,s,c);let T=$t(N.runElement),A=T.find(F=>F.node===N.textElement),M=A?A.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ve(T);if(M>0&&M<Ve(T)){let F=Ge(e,T,0,M,!1),X=Ge(e,T,M,Ve(T),!1);return Nt(e,S,N.runElement,F,N.rPr),ct(e,S,N.runElement,n,N.rPr,o,i,a,y,c),Nt(e,S,N.runElement,X,N.rPr),S.removeChild(N.runElement),!0}let _=r<=N.charStart?N.runElement:N.runElement.nextSibling;return ct(e,S,_,n,N.rPr,o,i,a,y,c),!0}let p=Hi(t,r,l),h=p.leftSpan&&I(p.leftSpan.runElement?.parentNode,"hyperlink"),w=p.rightSpan&&I(p.rightSpan.runElement?.parentNode,"hyperlink"),b=p.containingSpan&&I(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&b)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!h&&!w&&!b)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let g=null;if(u.formatting==="none"?g=null:u.formatting==="right"?g=p.rightSpan?.rPr||null:u.formatting==="left"?g=p.leftSpan?.rPr||null:g=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let N=p.containingSpan,S=N.runElement.parentNode||l;if(!S)return!1;let y=$t(N.runElement),T=y.find(M=>M.node===N.textElement),A=T?T.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:Ve(y);if(A>0&&A<Ve(y)){let M=Ge(e,y,0,A,!1),_=Ge(e,y,A,Ve(y),!1);return Nt(e,S,N.runElement,M,N.rPr),ct(e,S,N.runElement,n,g,o,i,a,s,c),Nt(e,S,N.runElement,_,N.rPr),S.removeChild(N.runElement),!0}}let x=null,v=null;if(u.hyperlink==="outside"){if(w){let N=p.rightSpan.runElement.parentNode;x=N.parentNode||l,v=N}else if(h){let N=p.leftSpan.runElement.parentNode;x=N.parentNode||l,v=N.nextSibling}}else u.hyperlink==="inside"&&(w?(x=p.rightSpan.runElement.parentNode,v=p.rightSpan.runElement):h&&(x=p.leftSpan.runElement.parentNode,v=p.leftSpan.runElement.nextSibling));if(x||(p.rightSpan?(x=p.rightSpan.runElement.parentNode||l,v=p.rightSpan.runElement):p.leftSpan?(x=p.leftSpan.runElement.parentNode||l,v=p.leftSpan.runElement.nextSibling):(x=l,v=null)),u.bookmark&&x&&(u.bookmark==="outside"?(v&&I(v.previousSibling,"bookmarkStart")&&(v=v.previousSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(v=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(v&&I(v,"bookmarkStart")&&(v=v.nextSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(v=p.leftSpan.runElement.nextSibling))),u.comment&&x)if(u.comment==="outside"){if(v&&I(v.previousSibling,"commentRangeStart")&&(v=v.previousSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let N=p.leftSpan.runElement.nextSibling.nextSibling;N&&(I(N,"commentReference")||I(N,"r"))&&Array.from(N.childNodes||[]).some(y=>I(y,"commentReference"))&&(N=N.nextSibling),v=N}}else u.comment==="inside"&&(v&&I(v,"commentRangeStart")&&(v=v.nextSibling),p.leftSpan&&I(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(v=p.leftSpan.runElement.nextSibling));if(s&&u.revision==="coalesce_same_author"){let N=null,S=null;if(p.leftSpan&&I(p.leftSpan.runElement.parentNode,"ins")){let y=p.leftSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(N=y,S=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&I(p.rightSpan.runElement.parentNode,"ins")){let y=p.rightSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(E,"author"))===o&&(N=y,S=p.rightSpan.runElement)}if(N){let y=st(e,n,g,!1);return N.insertBefore(y,S),!0}}return s&&f==="slice-cross-author"&&Qn(x,o)?Zn(e,x,Gi(t,x,r),n,g,o,i,a,s,c):(ct(e,x,v,n,g,o,i,a,s,c),!0)}function Zn(e,t,r,n,o,i,a,s,l,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:m}=Vi(e,t,r);return f&&u.insertBefore(f,t),ct(e,u,t,n,sc(o),i,a,s,l,c),m&&u.insertBefore(m,t),u.removeChild(t),!0}function sc(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>I(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Gi(e,t,r){let n=Ji(e,t),o=e.spans.filter(i=>i.runElement?.parentNode===t).reduce((i,a)=>i+(a.charEnd-a.charStart),0);return Math.max(0,Math.min(r-n,o))}function Ji(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function Qn(e,t){return I(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function lc(e,t){return I(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(E,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function cc(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Ki(e){return!!e?.parentNode}function ct(e,t,r,n,o,i,a,s,l,c=null){let u=Ke(a,s,s+n.length);if(u.length===0){let m=st(e,n,o,!1);if(l){let d=wt(e,"ins",m,i,c);t.insertBefore(d,r)}else t.insertBefore(m,r);return}let f=Hr(e,n,o,u,s,i,l);if(l){let m=wt(e,"ins",null,i,c);f.forEach(d=>m.appendChild(d)),t.insertBefore(m,r)}else f.forEach(m=>t.insertBefore(m,r))}function qi(e,t,r,n=!1){let o=[];if(fr(e,t,r,d=>o.push(d)),o.length===0)return{safe:!1};let i=o[0].runElement,a=i?.parentNode;if(!a)return{safe:!1};if(!o.every(d=>d.runElement?.parentNode===a))return{safe:!1,structuralBoundary:!0};let l=a.localName||a.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(l)||l==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let d of o){let p=d.runElement;for(let h of Array.from(p.childNodes||[]))if(h.nodeType===1){let w=h.localName||h.nodeName.replace(/^.*:/,"");if(c.has(w)||w==="fldChar")return{safe:!1,structuralBoundary:!0}}}let u=o[o.length-1].runElement,f=i;for(;f&&f!==u;){if(f!==i){let d=f.localName||f.nodeName.replace(/^.*:/,"");if(c.has(d))return{safe:!1,structuralBoundary:!0}}f=f.nextSibling}function m(d){if(!d||d.nodeType!==1)return!1;let p=d.localName||d.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let h of Array.from(d.childNodes||[]))if(h.nodeType===1&&m(h))return!0;return!1}return m(i.previousSibling)||m(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function ea(e,t,r,n,o,i,a=!0,s=null,l={},c={}){let u=s?[s]:Pe(e),{fullText:f,textSpans:m}=Yr(u),d=c.existingRevisions==="slice-cross-author"?li(f,r):null,p=d||fc(ir(f,r,l),l),h=Jr(m),w=c.pairReplacements===!0,b=[],g=0,x=0,v=!1,N=d?dc(d):[];if(N.length>1&&i.length===0)for(let T of N.slice().reverse()){let A=Yr(u).textSpans,M=Jr(A),_=T.text.replace(/\n/g," ");if(_.length===0)continue;let F=Xt(e,M,T.originalPos,_,o,i,T.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(v=!0)}else if(i.length===0){let T=mc(p);for(let A of T.reverse()){let M=Jr(Yr(u).textSpans);if(A.type==="insert"){let X=Xt(e,M,A.start,A.text.replace(/\n/g," "),o,i,A.newPos,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(v=!0);continue}let _=null,F=null;if(A.type==="replace"&&w&&a&&A.text.replace(/\n/g," ")){let X=qi(M,A.start,A.end,c?.existingRevisions==="slice-cross-author");if(X.safe){let C=rr(o,e);_={id:C.deletionId,author:C.author,date:C.date},F={id:C.insertionId,author:C.author,date:C.date}}else X.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,M,A.start,A.end,o,a,_)&&(v=!0),A.type==="replace"){let X=Xt(e,M,A.end,A.text.replace(/\n/g," "),o,i,A.newPos,a,u[0]||null,F,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(X&&typeof X=="object"&&X.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:X.error});X===!0&&(v=!0)}}}else for(let T=0;T<p.length;T++){let[A,M]=p[T];if(A===0){let _=M.length,F=g,X=g+_;fr(h,F,X,C=>{let W=Math.max(C.charStart,F),R=Math.min(C.charEnd,X),B=R-W,$=W-F,K=x+$,V=K+B,Y=Ke(i,K,V);Yi(e,C,W,R,Y,o,a)&&(v=!0)}),g+=_,x+=_}else if(A===-1){let _=T+1<p.length&&p[T+1][0]===1,F=!1,X=null,C=null;if(w&&a&&_&&p[T+1][1].replace(/\n/g," ").length>0){let B=qi(h,g,g+M.length,c?.existingRevisions==="slice-cross-author");if(B.safe){let $=rr(o,e);X={id:$.deletionId,author:$.author,date:$.date},C={id:$.insertionId,author:$.author,date:$.date},F=!0}else B.structuralBoundary&&b.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(eo(e,h,g,g+M.length,o,a,X)&&(v=!0),g+=M.length,F){T++;let[,W]=p[T],R=W.replace(/\n/g," ");if(R.length>0){let B=Xt(e,h,g,R,o,i,x,a,u[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(B&&typeof B=="object"&&B.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:B.error});B===!0&&(v=!0)}x+=W.length}}else if(A===1){let _=M.replace(/\n/g," ");if(_.length>0){let F=Xt(e,h,g,_,o,i,x,a,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(F&&typeof F=="object"&&F.error)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:F.error});F===!0&&(v=!0)}x+=M.length}}let S=u.map(T=>fe(T)).join(`
152
- `),y=String(r).replace(/\r\n/g,`
153
- `);if(c.existingRevisions==="slice-cross-author"&&S!==y){let T=uc(y,S);return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Generated OOXML accepted-view text does not match the requested modified text; the mutation was rejected.",mismatchOffset:T,expectedExcerpt:Zi(y,T),actualExcerpt:Zi(S,T),expectedCodePoint:Qi(y,T),actualCodePoint:Qi(S,T)},...b.length>0?{warnings:[...new Set(b)]}:{}})}return se({oxml:n.serializeToString(e),hasChanges:v,...b.length>0?{warnings:[...new Set(b)]}:{}})}function uc(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return n;return r}function Zi(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Qi(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function fc(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,i]=e[n],a=e[n+1];if(o===-1&&a?.[0]===1&&i!==a[1]&&i.length===a[1].length&&i.replace(/\u00a0/g," ")===a[1].replace(/\u00a0/g," ")){r.push(...si(i,a[1],t)),n++;continue}r.push([o,i])}return r}function mc(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[i,a]=e[o];if(i===0){r+=a.length,n+=a.length;continue}if(i===-1){let s=e[o+1];s?.[0]===1?(t.push({type:"replace",start:r,end:r+a.length,newPos:n,text:s[1]}),r+=a.length,n+=s[1].length,o++):(t.push({type:"delete",start:r,end:r+a.length,newPos:n,text:""}),r+=a.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:a}),n+=a.length}return t}function dc(e){let t=[],r=0,n=0;for(let[o,i]of e)o===0?(r+=i.length,n+=i.length):o===-1?r+=i.length:o===1&&(t.push({originalPos:r,newPos:n,text:i}),n+=i.length);return t}var ra=Xo(Ln(),1);var na=new ra.diff_match_patch;function oa(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function pc(e,t){return e?.getAttributeNS?.(E,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function ta(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,i=t-1;for(;o<=i;){let a=Math.floor((o+i)/2);e[a].end<=r?o=a+1:i=a-1}t=o}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function gc(e){let t=new Map;return e.forEach(r=>{t.has(r.start)||t.set(r.start,[]),t.get(r.start).push(r)}),t}function ia(e,t,r=null){let n=e.documentElement,o=I(n,"body")||oa(n)==="package",i=r||Pe(e),a=ye(e,E,"body");!a&&o&&(a=n);let s="",l=[],c=[],u=[],f=new Map,m=new Map,d=new Set,p={nextCharCode:57344},h=new Set;i.forEach((_,F)=>{let X=s.length;Array.from(_.childNodes).forEach(B=>{s=Nc(B,s,l,u,f,m,p,d)}),s=Ct(s,F,i.length);let C=s.length,W=ye(_,E,"pPr"),R=_.parentNode;R&&h.add(R),c.push({start:X,end:C,pPr:W,container:R||a})});let w="";for(let _=0;_<s.length;_++){let F=s[_];w+=d.has(F)?`
154
- `:F}let b=bc(w,t,u);b=wc(w,s,b,d),m.forEach((_,F)=>{let X=F.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");b=b.replace(new RegExp(X,"g"),_)}),b=xc(s,b,f);let g=new Map;h.forEach(_=>{g.set(_,e.createDocumentFragment())}),a&&!g.has(a)&&g.set(a,e.createDocumentFragment()),g.has(e)||g.set(e,e.createDocumentFragment());let x=new Map,v=new Set(c.map(_=>_.start)),N=ta(c),S=ta(l),y=gc(u);return{paragraphs:i,body:a||e,paragraphMap:c,paragraphStarts:v,propertyMap:l,sentinelMap:u,sentinelMapByStart:y,referenceMap:f,tokenToCharMap:m,containerFragments:g,replacementContainers:x,originalFullText:s,processedModifiedText:b,getParagraphInfo:_=>{let F=N.at(_);return F||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:a||e})},getRunProperties:_=>{let F=S.at(_);return F?{rPr:F.rPr,wrapper:F.wrapper}:{rPr:null}},getPropertySpanLength:(_,F)=>{let X=S.at(_);return X?Math.min(X.end-_,F):1},isParagraphStart:_=>v.has(_)}}function aa(e,t){let r=Pe(e);if(r.length===0)return[];let n=sa(t),o=r.map(hc);if(!n){let a=o.findIndex(s=>s==="");return a>=0?[r[a]]:null}if(r.length===1&&o[0]==="")return r;let i=[a=>a,a=>a.trim(),a=>a.replace(/\s+/g," ").trim()];for(let a of i){let s=a(n);for(let l=0;l<r.length;l++){let c="";for(let u=l;u<r.length;u++)if(c+=(u===l?"":`
155
- `)+o[u],a(c)===s)return r.slice(l,u+1)}}return null}function sa(e){return String(e??"").replace(/\r\n?/g,`
156
- `).replace(/\u00a0/g," ")}function hc(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(I(o,"pPr")||I(o,"del")||I(o,"moveFrom")||(I(o,"t")?t+=o.textContent||"":I(o,"tab")?t+=" ":I(o,"br")||I(o,"cr")?t+=`
157
- `:I(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),sa(t)}function wc(e,t,r,n){if(n.size===0)return r;let o=na.diff_main(e,r),i=0,a="";for(let[s,l]of o)if(s===0){for(let c=0;c<l.length;c++){let u=t[i+c];a+=n.has(u)?u:l[c]}i+=l.length}else s===-1?i+=l.length:a+=l;return a}function bc(e,t,r){let n=new Map;if(r.forEach(f=>{f.zeroWidth&&n.set(f.start,f)}),n.size===0)return t;let o="",i=0,a=new Map;for(let f=0;f<e.length;f++){let m=n.get(f);if(m){a.has(i)||a.set(i,[]),a.get(i).push({char:e[f],affinity:m.affinity||"right",emitted:!1});continue}o+=e[f],i++}let s=na.diff_main(o,t),l=0,c="",u=(f,m)=>{let d=a.get(f)||[];for(let p of d)p.emitted||m&&p.affinity!==m||(c+=p.char,p.emitted=!0)};for(let[f,m]of s){if(f===1){u(l,"left"),c+=m;continue}for(let d=0;d<m.length;d++)u(l),f===0&&(c+=m[d]),l++}return u(l),c}function xc(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let i=e.indexOf(o);if(i<0)continue;let a=e.slice(0,i),s=e.slice(i+o.length);if(a&&n.startsWith(a)){n=`${n.slice(0,a.length)}${o}${n.slice(a.length)}`;continue}if(s&&n.endsWith(s)){let l=n.length-s.length;n=`${n.slice(0,l)}${o}${n.slice(l)}`}}return n}function Nc(e,t,r,n,o,i,a,s){return I(e,"r")?vc(e,t,r,n,o,i,a,s):I(e,"hyperlink")?yc(e,t,r):I(e,"sdt")||I(e,"oMath")||oa(e)==="oMath"||I(e,"bookmarkStart")||I(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((I(e,"commentRangeStart")||I(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function vc(e,t,r,n,o,i,a,s){let l=t,c=ye(e,E,"rPr");return Array.from(e.childNodes).forEach(u=>{if(I(u,"t")){let f=u.textContent||"";f.length>0&&(r.push({start:l.length,end:l.length+f.length,rPr:c}),l+=f)}else if(I(u,"br")||I(u,"cr")){let f=String.fromCharCode(a.nextCharCode++);o.set(f,u),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:c})}else if(I(u,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:c});else if(I(u,"noBreakHyphen"))l+="\u2011",r.push({start:l.length-1,end:l.length,rPr:c});else if(["drawing","pict","object","fldChar","instrText","sym"].some(f=>I(u,f))){let f=ye(u,E,"txbxContent"),m=I(u,"pict")&&!!f,d=I(u,"fldChar")||I(u,"instrText"),p=I(u,"fldChar")?u.getAttributeNS?.(E,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:l.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:d,affinity:p==="end"?"left":"right",isTextBox:m,originalContainer:m?f:void 0}),l+="\uFFFC",r.push({start:l.length-1,end:l.length,rPr:c})}else if(I(u,"footnoteReference")||I(u,"endnoteReference")){let f=pc(u,"id");if(f){let d=`{{__${I(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(a.nextCharCode++);o.set(p,u),i.set(d,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:c})}}else I(u,"commentReference")&&n.push({start:l.length,node:u,isCommentMarker:!0})}),l}function yc(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!I(o,"r"))return;let i=ye(o,E,"rPr");ve(o,E,"t").forEach(s=>{let l=s.textContent||"";l.length!==0&&(r.push({start:n.length,end:n.length+l.length,rPr:i,wrapper:e}),n+=l)})}),n}function ca(e,t,r,n,o,i,a=!0,s={}){let{paragraphs:l,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:m,getParagraphInfo:d,getRunProperties:p,getPropertySpanLength:h,isParagraphStart:w}=r,b=R=>{let B=O(e,"w:p");if(R){let $=R.cloneNode(!0),K=ye($,E,"sectPr");K&&$.removeChild(K),B.appendChild($)}return B},g=d(0),x=b(g.pPr),v=c.get(g.container);v&&v.appendChild(x);let N=0,S=0,y=s?.pairReplacements===!0,T=null,A=null,M=new WeakSet;for(let R=0;R<t.length;R++){let[B,$]=t[R];if(B===0||B===-1){let K=B===0?"equal":"delete";if(B===0)T=null,A=null;else if(T===null){T=N;let Y=!1;for(let oe=R+1;oe<t.length;oe++){if(t[oe][0]===1){Y=!0;break}if(t[oe][0]===0)break}y&&a&&Y&&(A=rr(o,e))}let V=0;for(;V<$.length;){let Y=N+V,oe=p(Y),mt=h(Y,$.length-V),It=$.substring(V,V+mt);x=la(e,It,K,oe.rPr,oe.wrapper,Y,x,c,u,f,m,d,b,o,i,S,a,M,A).currentParagraph,B===0&&(S+=mt),V+=mt}N+=$.length;continue}if(B===1){let K=T!==null?T:N>0&&!w(N)?N-1:N,V=p(K);x=la(e,$,"insert",V.rPr,V.wrapper,N,x,c,u,f,m,d,b,o,i,S,a,M,A,T!==null).currentParagraph,S+=$.length,T=null,A=null}}a&&c.forEach(R=>{Array.from(R.childNodes).forEach(B=>{if(I(B,"p")){let $=Array.from(B.getElementsByTagNameNS(E,"t")).length>0,K=Array.from(B.getElementsByTagNameNS(E,"delText")).length>0;l.length===1&&!$&&(K||r.originalFullText.trim()!=="")&&lr(e,B,o)}})}),c.forEach(R=>{let B=Array.from(R.childNodes).filter($=>I($,"p"));if(B.length>1){let $=B[0],K=B[B.length-1],V=ye($,E,"pPr"),Y=V?ye(V,E,"sectPr"):null;if(Y){V.removeChild(Y);let oe=ye(K,E,"pPr");oe||(oe=O(e,"w:pPr"),K.insertBefore(oe,K.firstChild||null)),oe.appendChild(Y)}}});let _=new Set(l),F=new Map;l.forEach(R=>{let B=R.parentNode;if(!B||F.has(B))return;let $=R.nextSibling;for(;$&&_.has($);)$=$.nextSibling;F.set(B,$)}),l.forEach(R=>{R.parentNode&&R.parentNode.removeChild(R)});let X=!1,C="";return c.forEach((R,B)=>{let $=m.get(B),K=$||B;if(K.nodeType===9){X=!0,R.childNodes.length===1?K.appendChild(R.firstChild):C=Array.from(R.childNodes).map(Y=>n.serializeToString(Y)).join("");return}let V=$?null:F.get(B);V&&V.parentNode===K?K.insertBefore(R,V):K.appendChild(R)}),{oxml:X&&C?C:n.serializeToString(e),hasChanges:!0}}function la(e,t,r,n,o,i,a,s,l,c,u,f,m,d,p=[],h=0,w=!0,b=new WeakSet,g=null,x=!1){let v=i,N=h,S=a,y=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(A=>{let M=l.get(v)||[],_=M.filter(C=>C.isCommentMarker&&!b.has(C.node)),F=x?new Set(_.filter(C=>I(C.node,"commentRangeEnd")).map(C=>C.node.getAttributeNS?.(E,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id"))):new Set;if(_.forEach(C=>{b.add(C.node);let W=C.node.getAttributeNS?.(E,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id");if(x&&F.has(W)&&(I(C.node,"commentRangeEnd")||I(C.node,"commentReference"))){y.push(C.node);return}if(I(C.node,"commentReference")){let R=O(e,"w:r");R.appendChild(C.node.cloneNode(!0)),S.appendChild(R)}else S.appendChild(C.node.cloneNode(!0))}),A===`
158
- `){let C=f(v+1),W=m(C.pPr);w&&r==="insert"?Bi(e,S,d):w&&r==="delete"&&lr(e,S,d);let R=s.get(C.container);R&&(R.appendChild(W),S=W),v++,r!=="delete"&&N++;return}if(A==="\uFFFC"){let C=M.find(W=>!W.isCommentMarker)||M[0];if(C){let W=C.node.cloneNode(!0);if(C.isTextBox&&C.originalContainer){let R=ye(W,E,"txbxContent");if(R){for(;R.firstChild;)R.removeChild(R.firstChild);u.set(C.originalContainer,R)}}if(C.wrapInRun){let R=O(e,"w:r");C.rPr&&R.appendChild(C.rPr.cloneNode(!0)),R.appendChild(W),S.appendChild(R)}else S.appendChild(W)}v++,r!=="delete"&&N++;return}if(c.has(A)){if(r!=="delete"){let C=c.get(A);if(C){let W=C.cloneNode(!0),R=O(e,"w:r");n&&R.appendChild(n.cloneNode(!0)),R.appendChild(W),S.appendChild(R)}}v++,r!=="delete"&&N++;return}if(A.length===0)return;let X=S;if(o){let C=o.cloneNode(!1);X=C,S.appendChild(C)}if(r==="delete"){let C=O(e,"w:r");n&&C.appendChild(n.cloneNode(!0));let W=O(e,"w:delText");if(W.setAttribute("xml:space","preserve"),W.textContent=A,C.appendChild(W),w){let R=null;if(g){let $=g.usedDeletionId?ie(d,e,"del").id:g.deletionId;g.usedDeletionId=!0,R={id:$,author:g.author,date:g.date}}let B=wt(e,"del",C,d,R);X.appendChild(B)}}else{let C=Ke(p,N,N+A.length),W=Hr(e,A,n,C,N,d,w);if(r==="insert"&&w){let R=null;if(g){let $=g.usedInsertionId?ie(d,e,"ins").id:g.insertionId;g.usedInsertionId=!0,R={id:$,author:g.author,date:g.date}}let B=wt(e,"ins",null,d,R);W.forEach($=>B.appendChild($)),X.appendChild(B)}else W.forEach(R=>X.appendChild(R))}r!=="delete"&&(N+=A.length),v+=A.length}),y.forEach(A=>{if(I(A,"commentReference")){let M=O(e,"w:r");M.appendChild(A.cloneNode(!0)),S.appendChild(M)}else S.appendChild(A.cloneNode(!0))}),{currentParagraph:S}}function to(e,t,r,n,o,i,a=!0,s={},l={}){let c=aa(e,t);if(c===null)return se({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PARTIAL_TARGET",message:"Original text did not identify a complete contiguous paragraph range for reconstruction."}});let u=ia(e,r,c);if(u.paragraphs.length===0)return se({oxml:n.serializeToString(e),hasChanges:!1});let f=ir(u.originalFullText,u.processedModifiedText,s);return se(ca(e,f,u,n,o,i,a,l))}function De(e,t){return se({oxml:e.serializeToString(t),hasChanges:!1})}function ua(e,t,r,n,o,i=!0){let a=ve(e,E,"tbl"),s=Xe(t),l=s.rows.length>0||s.headers.length>0;if(a.length===0||!l)return De(r,e);let c=a[0],u=_n(c),f=Ni(u,s);if(f.length===0)return De(r,e);let m={generateRedlines:i,author:o,revisionIdAllocator:Ye(e)},d=vi(u,f,m),p=`<root xmlns:w="${E}">${d}</root>`,h=j(p,"application/xml").doc;if(!h)return De(r,e);let w=ne(h);if(w)return ee("[OxmlEngine] Failed to parse reconciled table OOXML:",w.textContent),De(r,e);let b=ye(h,E,"tbl");if(!b)return ee("[OxmlEngine] No table found in reconciled OOXML"),De(r,e);let g=e.importNode(b,!0);return c.parentNode.replaceChild(g,c),se({oxml:r.serializeToString(e),hasChanges:!0})}function fa(e,t,r,n,o,i){let a=Ye(e),s=Xe(t);if(!s||s.rows.length===0&&s.headers.length===0)return L("[OxmlEngine] Failed to parse table data from Markdown"),De(r,e);let l=ht(s,{generateRedlines:i,author:o,revisionIdAllocator:a}),c=j(`<root xmlns:w="${E}">${l}</root>`,"application/xml").doc;if(!c)return De(r,e);let u=ne(c);if(u)return ee("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),De(r,e);let f=re(c,E,"tbl");if(f||(f=re(c,E,"ins")),!f)return ee("[OxmlEngine] No table element found in generated OOXML"),De(r,e);let m=e,d=ce(m,E,"p");if(d.length===0)return L("[OxmlEngine] No paragraphs found to replace"),De(r,m);let p=d[0],h=p.parentNode;if(h&&h.nodeType===9){let b=j(`<w:document xmlns:w="${E}"><w:body/></w:document>`,"application/xml").doc;if(!b)return De(r,m);let g=re(b,E,"body");d.forEach(x=>g.appendChild(b.importNode(x,!0))),m=b,Mr(m,a),d=ce(m,E,"p"),p=d[0],h=p.parentNode}let w=m.importNode(f,!0);return i?d.forEach(b=>{lr(m,b,o),ce(b,E,"r").forEach(x=>{ce(x,E,"t").forEach(y=>{let T=y.textContent||"";if(T.trim()){let A=O(m,"w:delText");A.textContent=T,y.parentNode.replaceChild(A,y)}});let N=O(m,"w:del"),S=ie(o,m,"del");N.setAttribute("w:id",String(S.id)),N.setAttribute("w:author",S.author),N.setAttribute("w:date",S.date),x.parentNode.insertBefore(N,x),N.appendChild(x)})}):d.slice(1).forEach(b=>b.parentNode.removeChild(b)),h.insertBefore(w,p),i||h.removeChild(p),L("[OxmlEngine] Text-to-table transformation complete"),se({oxml:r.serializeToString(m),hasChanges:!0})}function Ze(e,t){if(!e||!e.attributes)return"";for(let r of Array.from(e.attributes))if((r.localName||"").toLowerCase()===t.toLowerCase())return String(r.value||"");return String(e.getAttribute?.(`w:${t}`)||e.getAttribute?.(t)||"")}function qr(e){return typeof e=="string"?e.trim().toLowerCase():""}function Sc(e){return!!e&&e.nodeType===1}function ze(e,t){return Sc(e)&&e.namespaceURI===E&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function xe(e,t){return Array.from(e.getElementsByTagNameNS(E,t))}function ro(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=qr(e?.author);return t?{valid:!0,allAuthors:!1,normalizedAuthor:t}:{valid:!1,allAuthors:!1,normalizedAuthor:"",warning:"No author provided. Pass { author } or set { allAuthors: true }."}}function Ce(e,t){if(t.allAuthors)return!0;let r=qr(Ze(e,"author"));return!!r&&r===t.normalizedAuthor}function no(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=j(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let a=`<w:body xmlns:w="${E}">${r}</w:body>`,s=j(a,"application/xml");s.error||(o=s,n=!0)}let i=o.doc?ne(o.doc):null;if(o.error||i){let a=o.error?.message||i?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${a}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:a}}}return{xmlDoc:o.doc,serializer:de(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function me(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Zr(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function ma(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function da(e){return Array.from(e?.attributes||[]).filter(t=>String(t.localName||t.name||"").toLowerCase()!=="id").map(t=>`${t.namespaceURI||""}|${t.localName||t.name}=${t.value}`).sort().join(`
159
- `)}function Tc(e){let t=0,r=xe(e,"ins");for(let n of r){if(!n.parentNode||en(n))continue;let o=ma(n);for(;ze(o,"ins")&&qr(Ze(o,"author"))===qr(Ze(n,"author"))&&da(o)===da(n);){let i=ma(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=i}}return t}function Qr(e){let t=e?.parentNode;return ze(t,"trPr")&&ze(t?.parentNode,"tr")}function en(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return ze(t,"rPr")&&ze(r,"pPr")&&ze(n,"p")}function ha(e){return en(e)?e.parentNode.parentNode.parentNode:null}function Ec(e){let t=e?.nextSibling||null;for(;t;){if(ze(t,"p"))return t;t=t.nextSibling}return null}function wa(e){if(!e?.parentNode)return!1;let t=Ec(e);if(!t)return ze(e.parentNode,"tc")&&xe(e.parentNode,"p").length<=1?!1:me(e);let r=Array.from(e.childNodes||[]).filter(o=>!ze(o,"pPr")),n=t.firstChild||null;ze(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return me(e)}function oo(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let s=0;for(let u of xe(i,"ins"))if(!(!u.parentNode||!Ce(u,n))){if(en(u)){me(u)&&(s+=1);continue}if(Qr(u)){me(u)&&(s+=1);continue}Zr(u)&&(s+=1)}for(let u of xe(i,"del")){if(!u.parentNode||!Ce(u,n))continue;let f=ha(u);if(f){wa(f)&&(s+=1);continue}if(Qr(u)){let m=u.parentNode?.parentNode;me(m)&&(s+=1);continue}me(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||me(u)&&(s+=1);for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||Zr(u)&&(s+=1);s+=ba(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of xe(i,u))!f.parentNode||!Ce(f,n)||me(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(u=>a.serializeToString(u)).join(""):a.serializeToString(i),hasChanges:s>0,acceptedCount:s,warnings:r}}function pa(e,t){for(let r of Array.from(t.getElementsByTagNameNS(E,"delText"))){let n=O(e,"w:t"),o=r.getAttribute("xml:space");for(o&&n.setAttribute("xml:space",o);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function Ac(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==E)return me(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===E&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return me(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=Ic(r.ownerDocument,a);r.appendChild(s)}return!0}function Ic(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function ga(e,t,r){let n=new Set;for(let o of xe(e,t)){if(!Ce(o,r))continue;let i=Ze(o,"id");i&&n.add(i)}return n}function ba(e,t){let r=0,n=ga(e,"moveFromRangeStart",t),o=ga(e,"moveToRangeStart",t),i=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[a,s,l]of i)for(let c of xe(e,a)){if(!c.parentNode)continue;let u=Ze(c,"id");u&&(t.allAuthors||s.has(u)||l&&Ce(c,t))&&me(c)&&(r+=1)}return r}function io(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let s=0;for(let u of xe(i,"ins")){if(!u.parentNode||!Ce(u,n))continue;let f=ha(u);if(f){wa(f)&&(s+=1);continue}if(Qr(u)){let m=u.parentNode?.parentNode;me(m)&&(s+=1);continue}me(u)&&(s+=1)}for(let u of xe(i,"del"))if(!(!u.parentNode||!Ce(u,n))){if(en(u)){me(u)&&(s+=1);continue}if(Qr(u)){me(u)&&(s+=1);continue}pa(i,u),Zr(u)&&(s+=1)}for(let u of xe(i,"moveFrom"))!u.parentNode||!Ce(u,n)||(pa(i,u),Zr(u)&&(s+=1));for(let u of xe(i,"moveTo"))!u.parentNode||!Ce(u,n)||me(u)&&(s+=1);s+=ba(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of l)for(let f of xe(i,u))!f.parentNode||!Ce(f,n)||Ac(f,u)&&(s+=1);return Tc(i),{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(u=>a.serializeToString(u)).join(""):a.serializeToString(i),hasChanges:s>0,rejectedCount:s,warnings:r}}function Pc(e,t){let r=new Set,n=xe(e,"comment");for(let o of n){if(!Ce(o,t))continue;let i=Ze(o,"id");i&&r.add(i)}return{targetIds:r,commentNodes:n}}function Rc(e,t){let r=0;for(let n of e){let o=Ze(n,"id");!o||!t.has(o)||me(n)&&(r+=1)}return r}function Cc(e){return ze(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==E)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Oc(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let i of xe(e,o)){if(!i.parentNode)continue;let a=Ze(i,"id");if(!(!a||!t.has(a))){if(o==="commentReference"&&Cc(i.parentNode)){me(i.parentNode)&&(r+=1);continue}me(i)&&(r+=1)}}return r}function kc(e,t={}){let r=[],n=ro(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=no(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:i,serializer:a}=o;r.push(...o.warnings||[]);let{targetIds:s,commentNodes:l}=Pc(i,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let m of xe(i,f)){let d=Ze(m,"id");d&&s.add(d)}let c=Rc(l,s),u=Oc(i,s);return{oxml:a.serializeToString(i),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var Mc=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function Qe(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Mc[t]||null,...r}))}var _c=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function Me(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function dr(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function ao(e,t){return dr(e).find(r=>Me(r)===t)||null}function so(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function tn(e){return String(e||"").trim().toLowerCase()}function Lc(e){return Me(e)!=="r"?!1:dr(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Me(t)))}function lo(e){return _c.has(Me(e))||Lc(e)}function co(e){return Me(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Me(e))?dr(e).filter(r=>!lo(r)&&Me(r)!=="sdtPr").every(co):!1}function xa(e){let t=ao(e,"pPr"),r=ao(t,"rPr");return ao(r,"del")}function Bc(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=Me(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let i=Me(n);if(i==="del"||i==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function Na(e,t){let r=xa(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=so(r,"author")||null,o=!n||tn(n)!==tn(t),a=dr(e).filter(s=>!lo(s)).every(co);return{matches:o&&a,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:a,ownerAuthor:n,markDeletion:r}}function va(e){let t=Me(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Me(n)==="p"),r=[];for(let n of t){let o=xa(n);if(!o)continue;let i=so(o,"author")||null,a=dr(n).filter(c=>!lo(c)),s=a.filter(c=>Me(c)!=="ins"||!Bc(c)?!1:tn(so(c,"author"))!==tn(i)),l=a.every(c=>co(c)||s.includes(c));s.length>0&&l&&r.push({paragraph:n,markDeletion:o,ownerAuthor:i,foreignInsertions:s})}return r}function Fc(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of ve(e,E,r)){let o=n.getAttribute?.("w:id")||n.getAttribute?.("id");o!==""&&t.add(o)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function vt(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===E&&r.localName===t)||null}function $c(e,t){let r=vt(vt(vt(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(E,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(E,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(E,"date")||""}}function Xc(e,t){let r=e.cloneNode(!1),n=vt(e,"pPr");return n&&r.appendChild(jr(n)),t.serializeToString(r)}function Dc(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=j(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:Pe(r.doc)[0];if(!n)return e;let o=vt(n,"pPr");o||(o=O(r.doc,"w:pPr"),n.insertBefore(o,n.firstChild));let i=vt(o,"rPr");if(i||(i=O(r.doc,"w:rPr"),o.appendChild(i)),!vt(i,"ins")){let a=O(r.doc,"w:ins");t.id&&a.setAttribute("w:id",t.id),a.setAttribute("w:author",t.author),t.date&&a.setAttribute("w:date",t.date),i.appendChild(a)}return te(r.doc)}async function uo(e,t,r,n={}){let o=e,i=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let a=n.generateRedlines??!0,s=n.author||pe(),l=de(),c=[],u=[],f=!1,m=null,d=n.existingRevisions||"merge-same-author",p=d==="accept-all-first-keep-normalized",h=z=>{let k={...z};f&&k.hasChanges===!1&&k.status!=="error"&&(d==="merge-same-author"||d==="slice-cross-author"?(k.oxml=i,k.hasChanges=!0,k.warnings=[...Array.isArray(k.warnings)?k.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(k.oxml=i,k.hasChanges=!0,k.warnings=[...Array.isArray(k.warnings)?k.warnings:[],"Existing revisions were accepted before redlining."]):k.oxml=o);let Z=[...c,...u,...Array.isArray(k.warnings)?k.warnings:[]];return Z.length>0&&(k.warnings=[...new Set(Z)]),k.status||(k.status=k.hasChanges?"ok":"no-op"),m&&k.hasChanges&&typeof k.oxml=="string"&&(k.oxml=Dc(k.oxml,m)),se(k)},w=()=>h(f&&p?{oxml:i,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),b=j(o,"text/xml");c=b.warnings;let g=b.doc,x=g?ne(g):null;if(b.error||x){let z=b.error?.message||x?.textContent||"Could not parse OOXML input.";return ee("[OxmlEngine] XML parse error:",z),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:z}})}let v=n?._revisionIdAllocator instanceof we?n._revisionIdAllocator:new we;Rt(g,v);let N=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);if(N.length===1&&r.length>0){let z=Na(N[0],s);if(z.matches){let k=z.ownerAuthor||"unattributed";return h({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${k}). Use explicit paragraph restoration when supported.`,ownerAuthor:k}})}}if(zr(g))if(d==="merge-same-author"||d==="slice-cross-author"){let z=Dn(g),k=String(s||"").trim().toLowerCase();if(z.length>0&&z.every(le=>le.trim().toLowerCase()===k)){let le=Fc(g);if(le.length>0)return h({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:le}});L("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let Ae=N.length===1?N[0]:null;m=$c(Ae,s);let Yt=io(o,{author:s});if(Yt.status==="error")return h(Yt);i=m&&!String(Yt.oxml||"").trim()?Xc(Ae,l):Yt.oxml,f=!0;let Rr=j(i,"text/xml");c.push(...Rr.warnings),g=Rr.doc;let Bo=g?ne(g):null;if(Rr.error||Bo){let Cr=Rr.error?.message||Bo?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return ee("[OxmlEngine] XML parse error after rejecting same-author revisions:",Cr),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Cr}})}if(zr(g))return h({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});Rt(g,v);let Fo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:Pe(g);t=Fo.length>0?Fo.map(Cr=>fe(Cr)).join(`
160
- `):""}else{if(d==="merge-same-author")return L("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${z.length?z.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:z,currentPolicy:d}});if(["moveFrom","moveTo"].some(Ae=>ve(g,E,Ae).length>0))return h({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});L("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(d==="accept-all-first"||d==="accept-all-first-keep-normalized"){L("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let z=oo(o,{allAuthors:!0});if(z.status==="error")return h(z);i=z.oxml,f=!0;let k=j(i,"text/xml");c.push(...k.warnings),g=k.doc;let Z=g?ne(g):null;if(k.error||Z){let le=k.error?.message||Z?.textContent||"Could not parse OOXML after accepting existing revisions.";return ee("[OxmlEngine] XML parse error after accepting existing revisions:",le),h({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:le}})}Rt(g,v)}else return L("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let S=ji(g,t,n);if(S.hasTableWrapper&&S.targetParagraph&&!n._isolatedTableCell){L("[OxmlEngine] Isolating table-cell paragraph before diff");let z=cr(g,S.targetParagraph,l),k=await uo(z,t,r,{...n,_isolatedTableCell:!0});return!k.hasChanges&&k.status==="no-op"?w():k}let y=n.sanitizeInput===!0?fo(r):r;y!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let T=null;if(n.structuredContent!==!1)if(T=Wr(y),T.valid)T.requiresStructuredContent&&(y=T.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let z=T.issues.map(k=>`${k.code}: ${k.message}`).join(" ");return h({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:z},warnings:T.issues.map(k=>k.message)})}T=null}let{cleanText:A,formatHints:M}=Ie(y),_=d==="slice-cross-author"?A!==t:A.trim()!==t.trim(),F=M.length>0,{existingFormatHints:X,textSpans:C,paragraphs:W}=Mi(g),R=X.length>0,B=C.map(z=>ya(z)).join(""),$=t.includes(`
161
- `)||t.includes("\r")?t.split(/\r?\n/).map(rn).filter(Boolean).every(z=>W.some(k=>{let Z=C.filter(le=>le.paragraph===k).map(ya).join("");return rn(Z).includes(z)})):B.includes(t.trim())||B.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||rn(B).includes(rn(t));if(_&&typeof t=="string"&&t.trim()&&!$)return L("[OxmlEngine] Target text not found in OOXML"),h({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let K=null,V=()=>(K||(K=Vr(g,W,C)),K),Y=(z=null)=>{let k=Ui(g,t,M,l,s,a,z);return k.useNativeApi?(L("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),to(g,t,A,l,s,M,a)):k};L(`[OxmlEngine] Text changes: ${_}, New format hints: ${M.length}, Existing format hints: ${X.length}`);let oe=n.removeFormatting===!0&&!_&&!F&&R;if(!_&&!F&&!R)return Qe(n,"noChange"),L("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),w();if(!_&&!F&&R&&!oe)return L("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),w();if(oe){Qe(n,"formatOnly",{removeFormatting:!0}),L("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let z=S,k=z.targetParagraph||null;if(!k){let Ae=$i(V(),t);Ae&&(k=Ae.paragraph)}let Z=X;k&&(Z=X.filter(Ae=>Di(Ae.run)===k));let le=Wi(g,C,Z,l,s,a);return z.hasTableWrapper&&k?h({oxml:cr(g,k,l),hasChanges:le.hasChanges}):h(le)}if(!_&&F){Qe(n,"formatOnly",{removeFormatting:!1}),L(`[OxmlEngine] Format-only change detected: ${M.length} format hints`);let z=S,k={textSpans:C,paragraphs:W,paragraphInfos:V()};if(z.hasTableWrapper&&z.targetParagraph){L("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let Z=Y(k);return L("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),h({oxml:cr(g,z.targetParagraph,l),hasChanges:Z.hasChanges})}return h(Y(k))}let It=ve(g,E,"tbl").length>0,Pr=/^\|.+\|/.test(A.trim())&&A.includes(`
162
- `),_o=Zt(A),bs=n.structuredContent!==!1&&T?.requiresStructuredContent===!0,dt=S,Lo=It||d==="slice-cross-author";L(`[OxmlEngine] Mode: ${Lo?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${M.length}, isMarkdownTable: ${Pr}, isTargetList: ${_o}, isTableCellParagraph: ${dt.isTableCellParagraph}`);try{if(Pr&&!It)return Qe(n,"table",{transformation:"text-to-table"}),L("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),h(fa(g,A,l,null,s,a));if(It&&Pr)return Qe(n,"table",{transformation:"table-reconciliation"}),h(ua(g,A,l,null,s,a));if(Lo){Qe(n,"surgical",{tableScoped:It});let z=dt.hasTableWrapper&&dt.targetParagraph?dt.targetParagraph:null;z&&L("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let k=ea(g,t,A,l,s,M,a,z,{},n);return k.status==="error"&&k.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?h({...k,oxml:o,hasChanges:!1}):dt.hasTableWrapper&&k.hasChanges&&dt.targetParagraph?(L("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),h({oxml:cr(g,dt.targetParagraph,l),hasChanges:!0})):h(k)}if(_o||bs){let z=ve(g,E,"p"),k=z.length===1;Qe(n,k?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:z.length}),L(`[OxmlEngine] \u{1F3AF} Using ${k?"direct list generation":"compatibility pipeline"} for list reconciliation`);let Z;if(k){let le=kt(i,{xmlDoc:g}),Ae=or(z[0]);Z=await _t({cleanText:A,numberingContext:Ae,originalRunModel:le.runModel,originalText:le.acceptedText,generateRedlines:a,author:s,font:n.font||null,revisionIdAllocator:v,numberingService:new Je})}else Z=await new ar({author:s,generateRedlines:a,revisionIdAllocator:v}).execute(i,y,{xmlDoc:g});if(Z.error?.code==="DIFF_TOKEN_LIMIT")return h({oxml:o,hasChanges:!1,status:"error",error:Z.error});if(Z.isValid&&Z.ooxml&&Z.ooxml!==i){let le=Z.includeNumbering===!0;L(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${le}`);let Ae=it(Z.ooxml,{includeNumbering:le,numberingXml:Z.numberingXml});return L(`[OxmlEngine] \u2705 Wrapped OOXML length: ${Ae.length}`),h({oxml:Ae,hasChanges:!0,...Array.isArray(Z.warnings)?{warnings:Z.warnings}:{}})}return w()}return Qe(n,"reconstruction"),h(to(g,t,A,l,s,M,a,{},n))}catch(z){if(ai(z))return h({oxml:o,hasChanges:!1,status:"error",error:{code:z.code,message:z.message}});throw z}}function rn(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function ya(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
163
- `:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function fo(e){return String(e??"").replace(/^(?:Here is the redline:|Here is the text:|Sure, I can help:|Here's the updated text:)[ \t]*\r?\n/i,"")}function et(e){return j(e,"application/xml").doc}function yt(e){return te(e)}function nn(e){return Array.from(e||[])}function pr(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Se(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Oe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Sa(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=nn(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=nn(e.getElementsByTagName(`w:${t}`));return r.length>0?r:nn(e.getElementsByTagName(t))}function ue(e){return e?fe(e):""}function Te(e){if(!e)return[];let t=Sa(e,"body"),r=t.length>0?t[0]:e;return Sa(r,"p")}function Tt(e){return e&&nn(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function St(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:fe(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:Te(e.ownerDocument||e).indexOf(e)+1,i=t.paragraphId===void 0?Tt(e):t.paragraphId,a=typeof t.inTable=="boolean"?t.inTable:gr(e),l=`${i||""}${o}${a?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let u=0;u<l.length;u++)c^=l.charCodeAt(u),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function Ta(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=Te(e),o=[],i=new Map,a=new Map,s=new Map;for(let l=0;l<n.length;l++){let c=n[l],u=fe(c,{revisionView:r}),f=Tt(c),m=gr(c),d=H(u),p=Object.freeze({paragraph:c,index:l+1,paragraphId:f,text:u,normalizedText:d,revisionView:r,fingerprint:St(c,{text:u,index:l+1,paragraphId:f,inTable:m,revisionView:r}),inTable:m});o.push(p),i.set(c,p),f&&!a.has(f)&&a.set(f,p),d&&(s.has(d)||s.set(d,[]),s.get(d).push(p))}for(let[l,c]of s)s.set(l,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:i,byId:a,byNormalizedText:s})}function H(e){return String(e||"").replace(/\s+/g," ").trim()}function go(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
164
- `)}function ho(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function zc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function Wc(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function Ea(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:Te(e)[t-1]||null}function Dt(e,t,r=Oe){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function on(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,i=o?null:Te(e),a=String(t||"").trim();if(!a)return null;let s=o?o.find(c=>c.text.trim()===a)?.paragraph:i.find(c=>ue(c).trim()===a);if(s)return s;let l=H(a);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:i.find(c=>H(ue(c))===l)||null}function mo(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,i=o?.entries||null,a=i?null:Te(e),s=String(t||"").trim();if(!s)return null;let l=on(e,s,{paragraphMetadataIndex:o});if(l)return l;let c=H(s),u=i?i.find(w=>w.normalizedText.length>10&&c.startsWith(w.normalizedText))?.paragraph||null:a.find(w=>{let b=H(ue(w));return b.length>10&&c.startsWith(b)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ue(u).trim().slice(0,60)}..."`),u;let f=i?i.find(w=>w.normalizedText.length>15&&c.includes(w.normalizedText))?.paragraph||null:a.find(w=>{let b=H(ue(w));return b.length>15&&c.includes(b)});if(f)return n(`[Fuzzy] Contains match: "${ue(f).trim().slice(0,60)}..."`),f;let m=0,d=null,p=new Set(c.toLowerCase().split(/\s+/).filter(w=>w.length>2)),h=i?.length??a.length;for(let w=0;w<h;w++){let b=i?.[w]?.paragraph??a[w],g=(i?.[w]?.text??ue(b)).trim();if(!g)continue;let N=H(g).toLowerCase().split(/\s+/).filter(S=>S.length>2).filter(S=>p.has(S)).length/Math.max(p.size,1);N>m&&N>.5&&(m=N,d=b)}return d?(n(`[Fuzzy] Best word-overlap match (${(m*100).toFixed(0)}%): "${ue(d).trim().slice(0,60)}..."`),d):null}function Aa(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",i=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,a=i?.revisionView==="rejected"?"rejected":"accepted",s=String(i?.exactText??i?.text??t.targetText??"").trim(),l=ho(i?.index??i?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==a?u=t.metadataIndices?.[a]||Ta(e,{revisionView:a}):u||(u=Ta(e,{revisionView:a})),i?.paragraphId){let m=jc(e,i.paragraphId,u);if(!m)throw Se("TARGET_NOT_FOUND",`Target paragraphId not found: "${i.paragraphId}".`);let d=u?.byParagraph?.get(m)||null,p=d?.index??Te(e).indexOf(m)+1,h=d?.fingerprint||St(m,{revisionView:a}),w=d?.inTable??gr(m),b=d?.normalizedText||H(fe(m,{revisionView:a}));if(l!=null&&l!==p)throw Se("TARGET_INDEX_MISMATCH",`Target paragraphId "${i.paragraphId}" (index ${p}) does not match requested index ${l}.`,d?[We(d)]:null);if(i.fingerprint&&i.fingerprint!==h){let g=a==="rejected"?"accepted":"rejected",x=St(m,{revisionView:g}),v=i.fingerprint===x?` The supplied fingerprint matches the ${g} view; set target.revisionView to "${g}" or use a fingerprint extracted from the ${a} view.`:"";throw Se("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.${v}`,d?[We(d)]:null)}if(typeof i.inTable=="boolean"&&i.inTable!==w)throw Se("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" does not match the requested table context.`,d?[We(d)]:null);if(s&&b!==H(s)){let g=a==="rejected"?"accepted":"rejected",v=H(fe(m,{revisionView:g}))===H(s)?` The supplied text matches the ${g} view; set target.revisionView to "${g}".`:"";throw Se("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.${v}`,d?[We(d)]:null)}if(i.occurrence!=null){let x=an(e,s||b,u),v=x.findIndex(N=>N.paragraph===m)+1;if(v===0||v!==i.occurrence)throw Se("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${v}, not requested occurrence ${i.occurrence}.`,x.map(We))}return{paragraph:m,resolvedBy:"paragraph_id"}}if(i?.fingerprint&&!s&&!l){let m=(u?.entries||[]).filter(d=>d.fingerprint===i.fingerprint);if(typeof i.inTable=="boolean"&&(m=m.filter(d=>d.inTable===i.inTable)),m.length===1)return{paragraph:m[0].paragraph,resolvedBy:"fingerprint"};throw m.length>1?Se("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",m.map(We)):Se("TARGET_NOT_FOUND",`Target fingerprint not found: "${i.fingerprint}".`)}let f=[];if(s){let m=an(e,s,u);if(f=Uc(m,i),i?.fingerprint&&m.length>0&&f.length===0)throw Se("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",m.map(We));if(typeof i?.inTable=="boolean"&&m.length>0&&f.length===0)throw Se("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",m.map(We));if(i?.occurrence){let d=f[i.occurrence-1]||null;if(!d)throw Se("TARGET_NOT_FOUND",`Target occurrence ${i.occurrence} was not found.`,f.map(We));return{paragraph:d.paragraph,resolvedBy:"occurrence"}}if(c){if(l){let d=f.find(p=>p.index===l)||null;if(d)return{paragraph:d.paragraph,resolvedBy:"ref"};if(i?.fingerprint&&f.length>0)throw Se("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(We));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Se("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(We));if(f.length===0)throw pr(`Target paragraph not found: "${s}"`)}if(!l&&f.length===1)return{paragraph:f[0].paragraph,resolvedBy:i?.fingerprint?"fingerprint":"strict_text"}}if(l){let m=Ea(e,l,u);if(m){let d=u?.byParagraph?.get(m)||null;if(i?.fingerprint&&i.fingerprint!==d?.fingerprint)throw Se("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof i?.inTable=="boolean"&&i.inTable!==d?.inTable)throw Se("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=on(e,s,{paragraphMetadataIndex:u}),h=(d?.text||fe(m,{revisionView:a})).trim(),w=H(h),b=H(s),g=w!==b;if(g&&p&&p!==m)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(g){let x=mo(e,s,{onInfo:r,paragraphMetadataIndex:u});if(x&&x!==m)return r(`[Target] [P${l}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:x,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${l}] fallback for ${o}; target text drifted.`)}else p&&p!==m&&r(`[Target] [P${l}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${l}] fallback for ${o}.`);return{paragraph:m,resolvedBy:"ref"}}n(`[WARN] Target reference [P${l}] not found; falling back to text matching for ${o}.`)}if(s&&!c){let m=on(e,s,{paragraphMetadataIndex:u});if(m){let p=f.length;if(p>1){let h=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(h),{paragraph:m,resolvedBy:"strict_text",warnings:[h]}}return{paragraph:m,resolvedBy:"strict_text"}}let d=mo(e,s,{onInfo:r,paragraphMetadataIndex:u});if(d)return{paragraph:d,resolvedBy:"fuzzy_text"}}throw pr(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function gr(e){return!!Dt(e,"tbl")}function an(e,t,r=null){let n=H(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,i=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===i)return Array.from(o.byNormalizedText.get(n)||[]);let a=Te(e),s=[];for(let l=0;l<a.length;l++){let c=a[l],u=fe(c,{revisionView:i}).trim();u&&H(u)===n&&s.push({paragraph:c,index:l+1,inTable:gr(c),paragraphId:Tt(c),fingerprint:St(c,{text:u,index:l+1,revisionView:i}),text:u,revisionView:i})}return s}function We(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function Uc(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function jc(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Te(e).find(n=>Tt(n)===t)||null:null}function Hc(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(i=>i.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,i)=>Math.abs(o.index-t)-Math.abs(i.index-t)),n[0]||null}function Vc(e,t=null){let r=t?.entries||null,n=r?null:Te(e),o=new Map,i=r?.length??n.length;for(let a=0;a<i;a++){let s=r?.[a]?.paragraph??n[a],l=(r?.[a]?.text??ue(s)).trim();o.set(a+1,{text:l,normalizedText:r?.[a]?.normalizedText??H(l),inTable:r?.[a]?.inTable??gr(s)})}return o}function po(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=Aa(e,t),o=ho(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let i=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!i)return n;let a=String(t.targetText||"").trim(),s=a||i.text||"",l=H(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||H(ue(n.paragraph)))===l)return n;let u=[];if(a&&u.push(a),i.text){let m=H(i.text);m&&!u.some(d=>H(d)===m)&&u.push(i.text)}let f=null;for(let m of u){let d=an(e,m,t.paragraphMetadataIndex||null),p=Hc(d,o,i.inTable);if(p&&(f||(f=p),p.paragraph!==n.paragraph)){f=p;break}}if(f&&f.paragraph!==n.paragraph){let m=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${m}.`),{paragraph:f.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw pr(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function Gc(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",i=n?.targetRefSnapshot||null,a=typeof n?.onInfo=="function"?n.onInfo:()=>{},s=typeof n?.onWarn=="function"?n.onWarn:()=>{},l=po(e,{targetRef:t,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!l)return null;let c=po(e,{targetRef:r,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!c)return null;let u=Array.from(e.getElementsByTagNameNS("*","p")),f=u.indexOf(l),m=u.indexOf(c);if(f<0||m<f)return null;let d=u.slice(f,m+1);if(d.length===0)return null;let p=d[0]?.parentNode||null;return!p||!d.every(h=>h&&h.parentNode===p)?null:d}function sn(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Oe,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function Ia(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Oe,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function Ra(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=je(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function Ca(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let i=o.trimEnd();if(!i.trim())continue;let a=er(i,{indentSpaces:2});if(a){n=!0,r.push({kind:"list",markerType:a.markerType,level:a.level,marker:a.marker,outlineLevel:a.outlineLevel,text:Ra(a.text)});continue}r.push({kind:"text",text:i.trim()})}return{items:r,hasListMarkers:n}}function Pa(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function hr(e,t){return H(e)===H(t)}function ln(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function Kc(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(i=>i.kind==="list");if(o.length===0||o.some(i=>i.markerType!=="bullet")||o.some(i=>Number.isInteger(i.outlineLevel)))return!1;if(n?.kind==="text")return hr(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let i=n.level||0;return o.some(s=>(s.level||0)>i)?!1:hr(n.text,t)}return!1}function Yc(e,t){return e.map(r=>{let n=Math.max(0,(r.ilvl||0)-t);return{...r,ilvl:Math.min(8,t+1+n)}})}function Jc(e,t,r,n){let o=e[0],i=e.slice(1).filter(a=>a.kind==="list");if(o?.kind==="text"&&hr(o.text,t)&&i.length>0){let a=i[0].level;return i.map(s=>({ilvl:ln(s,r,a),markerType:s.markerType||n,text:s.text}))}if(e.every(a=>a.kind==="list")){let a=e[0];if(!a||!hr(a.text,t))return null;let s=a.level;return e.slice(1).map(l=>({ilvl:ln(l,r,s),markerType:l.markerType||n,text:l.text})).filter(l=>l.text)}return null}function tt(e){if(!e)return null;let t=sn(e,"pPr");if(!t)return null;let r=sn(t,"numPr");if(!r)return null;let n=sn(r,"numId");if(!n)return null;let o=Ia(n);if(!o||o==="0")return null;let i=sn(r,"ilvl"),a=Ia(i),s=Number.parseInt(a||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function Oa(e){let t=tt(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(s=>s&&s.nodeType===1&&s.namespaceURI===Oe&&s.localName==="p"),o=n.indexOf(e);if(o<0)return null;let i=o;for(;i>0;){let s=tt(n[i-1]);if(!s||s.numId!==t.numId)break;i--}let a=o;for(;a<n.length-1;){let s=tt(n[a+1]);if(!s||s.numId!==t.numId)break;a++}return n.slice(i,a+1)}function qc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
165
- `)||!tt(e))return null;let s=Oa(e);if(!s||s.length===0)return null;let l=Ca(i);if(!l.hasListMarkers||l.items.length<2)return null;let c=H(r.currentParagraphText||ue(e)),f=l.items.filter(y=>y.kind==="list")[0]?.markerType||"bullet",m=s.map(y=>({paragraph:y,list:tt(y),text:String(ue(y)||"").trim()})),d=s.indexOf(e);if(d<0)return null;let p=Math.min(...m.map(y=>y.list?.ilvl??0)),h=m.map(y=>Pa((y.list?.ilvl??0)-p,f,y.text)),w=null,b=l.items[0],g=l.items.slice(1).filter(y=>y.kind==="list");if(b?.kind==="text"&&hr(b.text,c)&&g.length>0){let y=Math.max(0,(m[d].list?.ilvl??0)-p),T=g[0].level;w=[{level:y,markerType:f,text:m[d].text},...g.map(A=>({level:ln(A,y,T),markerType:A.markerType||f,text:A.text}))]}else if(l.items.every(y=>y.kind==="list")){let y=Math.max(0,(m[d].list?.ilvl??0)-p),T=l.items[0].level;w=l.items.map(A=>({level:ln(A,y,T),markerType:A.markerType||f,text:A.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let x=w.map(y=>Pa(y.level,y.markerType,y.text)),v=h.slice(0,d).concat(x).concat(h.slice(d+1)),N=h.join(`
166
- `),S=v.join(`
167
- `);return S===N?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:N,modifiedText:S})}function Zc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
168
- `))return null;let a=tt(e);if(!a)return null;let s=Ca(i);if(!s.hasListMarkers||s.items.length<2)return null;let l=H(r.currentParagraphText||ue(e)),u=s.items.filter(d=>d.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,a.ilvl),m=Jc(s.items,l,f,u);return!m||m.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(Kc(s.items,l,f)&&(m=Yc(m,f),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:a.numId,entries:m})}function wr(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
169
- `),n=[];for(let a of r){if(!a.trim())continue;let s=er(a,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(s){n.push({type:s.markerType,level:s.level,text:s.text.trim(),marker:s.marker});continue}n.push({type:"text",level:0,text:a.trim()})}if(n.length===0)return null;let o=n.some(a=>a.type==="numbered"),i=n.some(a=>a.type==="bullet");return{type:o?"numbered":i?"bullet":"text",items:n}}function wo(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function Qc(e,t,r){let n=new Map,o=[];for(let i of e){let a=Math.max(0,Number(i?.level)||0);for(let u of Array.from(n.keys()))u>a&&n.delete(u);let s=(n.get(a)||0)+1;n.set(a,s);let l=tu(s,t,r),c=" ".repeat(a*4);o.push(`${c}${l} ${i.text||""}`.trimEnd())}return o.join(`
170
- `)}function eu(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),i=o.match(/^(\s*)/),a=i?i[1].length:0,s=Math.floor(a/r),l=o.trim(),c=null,u=Fe(l,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,l=je(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:c}})}function tu(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${ka(e,!1)}.`;case"upperAlpha":return`${ka(e,!0)}.`;case"lowerRoman":return`${Ma(e,!1)}.`;case"upperRoman":return`${Ma(e,!0)}.`;default:return`${e}.`}}function ka(e,t=!1){let r=Math.max(1,Number(e)||1),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function Ma(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],o="";for(let[i,a]of n)for(;r>=i;)o+=a,r-=i;return t?o:o.toLowerCase()}function cn(e){let t=String(e||"");if(!t.trim()||t.includes(`
171
- `))return null;let r=wr(t);if(!r||!wo(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),i=n.type==="numbered"?Qt(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:i,startAt:nu(o,i),contentText:String(n.text||"").trim(),normalizedContent:H(String(n.text||""))}}function ru(e){let t=cn(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function nu(e,t){if(t!=="decimal")return null;let r=String(e||"").trim().match(/^(\d+)\.?$/);if(!r)return null;let n=Number.parseInt(r[1],10);return Number.isFinite(n)&&n>0?n:null}function ou(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let i=o.get(r)||null;return i&&i.numId!=null&&Number.isInteger(i.nextStartAt)&&i.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(i.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function iu(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function au(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function zt(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function su(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,i=t?.removeListPropertyNode!==!1,a=(Array.isArray(e)?e:[]).filter(l=>l&&l.nodeType===1&&l.localName==="p"),s=0;for(let l of a){let c=l.ownerDocument;if(!c)continue;let u=zt(l,"pPr");if(u||(u=O(c,"w:pPr"),l.insertBefore(u,l.firstChild)),o){let p=zt(u,"pPrChange");p&&u.removeChild(p)}if(i){let p=zt(u,"listPr");p&&u.removeChild(p)}let f=zt(u,"numPr");f||(f=O(c,"w:numPr"),u.appendChild(f));let m=zt(f,"ilvl");m||(m=O(c,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=zt(f,"numId");d||(d=O(c,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function lu(e){let t=j(e,"application/xml").doc;return!t||ne(t)?null:Te(t)[0]||null}function cu(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function uu(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Wt(e,t){let r=uu(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function _a(e,t){e.setAttribute("w:val",String(t))}function fu(e){let t=j(e,"application/xml").doc;if(!t||ne(t))return null;let o=Te(t)[0]||null;if(!o)return null;let i=Array.from(o.getElementsByTagNameNS("*","numId"));for(let a of i){let s=Wt(a,["w:val","val"]);if(s!=null)return String(s)}return null}function mu(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=de(),a=j(e,"application/xml").doc;if(!a||ne(a))return e;let c=Array.from(a.getElementsByTagNameNS("*","num")).find(p=>{let h=Wt(p,["w:numId","numId"]);return h!=null&&String(h)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=Wt(u,["w:val","val"]),m=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Wt(p,["w:ilvl","ilvl"])===0)||null;m||(m=O(a,"w:lvlOverride"),m.setAttribute("w:ilvl","0"),c.appendChild(m));let d=Array.from(m.getElementsByTagNameNS("*","startOverride"))[0]||null;if(d||(d=O(a,"w:startOverride"),m.appendChild(d)),_a(d,r),o&&f!=null){let h=Array.from(a.getElementsByTagNameNS("*","abstractNum")).find(w=>{let b=Wt(w,["w:abstractNumId","abstractNumId"]);return b!=null&&b===f})||null;if(h){let w=Array.from(h.getElementsByTagNameNS("*","lvl")).find(g=>Wt(g,["w:ilvl","ilvl"])===0)||null;w||(w=O(a,"w:lvl"),w.setAttribute("w:ilvl","0"),h.appendChild(w));let b=Array.from(w.getElementsByTagNameNS("*","start"))[0]||null;b||(b=O(a,"w:start"),w.insertBefore(b,w.firstChild)),_a(b,r)}}return i.serializeToString(a)}function bo(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let i=lu(t);if(!i)return null;let a=tt(i);if(a&&!o)return null;let s=Ie(n).cleanText||n,l=cn(n)||cn(s);if(!l)return null;let c=cn(r),u=H(r)===H(s),f=!!c&&c.type===l.type&&c.normalizedContent===l.normalizedContent;return!u&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!a,startAt:l.startAt}}async function un(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await _t({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new Je}),i=o?.oxml||o?.ooxml||"",a=cu(i),s=fu(a),l=mu(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!a||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:a,numberingXml:l,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}var du=new Set(["ins","del","rPrChange","pPrChange"]),pu=/^\d{4}-\d{2}-\d{2}T/;function ut(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Et(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>ut(r)===t)}function At(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function gu(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function hu(e){return ut(e.parentNode)==="rPr"}function wu(e){let t=r=>{let n=Do(r),o=n.getElementsByTagName("parsererror")[0];if(o)throw new Error(o.textContent||"XML parse error");return n};try{return{doc:t(e)}}catch{try{return{doc:t(`<w:root xmlns:w="${E}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function bu(e){let t=[],r=(f,m,d)=>t.push({code:f,severity:m,message:d}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:i}=n?{doc:e.nodeType===9?e:e.ownerDocument}:wu(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${i}`),{valid:!1,issues:t};let a=Et(o,"ins"),s=Et(o,"del"),l=a.concat(s);for(let f of Et(o,"p")){let m=Array.from(f.getElementsByTagName("*")).find(d=>d!==f&&ut(d)==="p");m&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${m.nodeName}>.`)}for(let f of Et(o,"body")){let m=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),d=m.map((p,h)=>ut(p)==="sectPr"?h:-1).filter(p=>p>=0);d.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):d.length===1&&d[0]!==m.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let f of l){let d=Array.from(f.getElementsByTagName("*")).filter(p=>p!==f&&["ins","del"].includes(ut(p))).find(p=>ut(f)!=="ins"||ut(p)!=="del"?!0:p.parentNode!==f);d&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${At(f,"id")}") contains invalid nested <${d.nodeName}>.`)}for(let f of s)Et(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${At(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of l){let m=[];At(f,"id")||m.push("w:id"),At(f,"author")||m.push("w:author"),pu.test(At(f,"date"))||m.push("w:date"),m.length>0&&r("MISSING_REVISION_METADATA","error",`<${f.nodeName}> is missing or has malformed ${m.join(", ")}.`)}let c=new Set;for(let f of Array.from(o.getElementsByTagName("*"))){if(!du.has(ut(f)))continue;let m=At(f,"id");m&&(c.has(m)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${m} appears more than once.`),c.add(m))}let u=Et(o,"t").concat(Et(o,"delText"));for(let f of u){let m=f.textContent||"";/^\s|\s$/.test(m)&&gu(f)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${f.nodeName}> has boundary whitespace without xml:space="preserve".`),m===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${f.nodeName}> is empty.`)}for(let f of l){if(hu(f))continue;Array.from(f.childNodes||[]).some(d=>d.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${At(f,"id")}") wraps no content.`)}for(let f of va(o)){let m=f.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${m} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(f=>f.severity==="error"),issues:t}}function fn(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Oe&&r.localName===t):[]}function xu(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Nu(e){let t=fn(e,"tr"),r=t.map(o=>fn(o,"tc").map(a=>{let s=fn(a,"p");return s.length===0?H(ue(a)):s.map(c=>H(ue(c))).filter(Boolean).join(`
172
- `)})),n=r.reduce((o,i)=>Math.max(o,i.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function vu(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(s=>{let l=Array.isArray(s)?s.slice(0,t):[];for(;l.length<t;)l.push("");return l}),n=r[0],o=new Array(t).fill("---"),i=r.slice(1),a=s=>`| ${s.map(l=>xu(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
173
- `)}function yu(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>H(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function La(e){let t=String(e||"").trim();return t?!!(/^and$/i.test(t)||/^\[.*\]$/.test(t)||/^\(.*\)$/.test(t)||/:\s*$/.test(t)||t.length<=90&&!/[.!?]$/.test(t)&&/[:\[\]()]/.test(t)||/^[\[(]/.test(t)):!1}function Su(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ue;if(!e||!e.parentNode)return null;let o=[e],i=e.nextSibling,a=0;for(;i&&a<r;){a+=1;let s=i.nextSibling;if(i.nodeType!==1||i.namespaceURI!==Oe||i.localName!=="p"){i=s;continue}let l=String(n(i)||"").trim();if(!l){if(o.length>1)break;i=s;continue}if(!La(l))break;o.push(i),i=s}return o.length>1?o:null}function Tu(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
174
- `)||go(i))return null;let a=i.split(/\r?\n/g).map(v=>v.trim()).filter(Boolean);if(a.length<2)return null;let s=r.tableElement||Dt(e,"tbl"),l=Dt(e,"tr"),c=Dt(e,"tc");if(!s||!l||!c)return null;let u=H(r.currentParagraphText||ue(e)),f=H(a[0]);if(u&&f&&f!==u)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:m,rowElements:d,columnCount:p}=Nu(s);if(m.length===0||p===0)return null;let h=d.indexOf(l),b=fn(l,"tc").indexOf(c);if(h<0||b<0||b>=p)return null;m[h][b]=a[0];let g=yu(m[h]);g&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let v=1;v<a.length;v++){let N=h+v,S=a[v];if(N<m.length&&!H(m[N][b]))if(g)for(let y=0;y<p;y++)H(m[N][y])||(m[N][y]=S);else m[N][b]=S;else{let y=new Array(p).fill("");if(g)for(let T=0;T<p;T++)y[T]=S;else y[b]=S;m.splice(Math.min(N,m.length),0,y)}}let x=vu(m,p);return x?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),x):null}function Ut(e,t){if(!e||!Array.isArray(t))return null;for(let r of t){let n=e.getAttribute(r);if(n==null||n==="")continue;let o=Number.parseInt(String(n),10);if(Number.isFinite(o))return o}return null}function jt(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let i=1;i<=r;i+=1)if(!o.has(i))return i}return n}function Eu(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,i=new Set;if(String(e||"").trim())try{let u=et(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),m=Array.from(u.getElementsByTagNameNS("*","num"));for(let d of f){let p=Ut(d,["w:abstractNumId","abstractNumId"]);p!=null&&i.add(p)}for(let d of m){let p=Ut(d,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let a=o.size>0?Math.max(...o):0,s=i.size>0?Math.max(...i):0,l=Math.max(r,a+1),c=Math.max(r,s+1);return{nextNumId:jt(l,o,n),nextAbstractNumId:jt(c,i,n),usedNumIds:o,usedAbstractNumIds:i,minId:r,maxPreferred:n}}function Au(e){return!e||typeof e!="object"?null:(e.usedNumIds instanceof Set||(e.usedNumIds=new Set),e.usedAbstractNumIds instanceof Set||(e.usedAbstractNumIds=new Set),(!Number.isInteger(e.minId)||e.minId<1)&&(e.minId=1),(!Number.isInteger(e.maxPreferred)||e.maxPreferred<e.minId)&&(e.maxPreferred=32767),(!Number.isInteger(e.nextNumId)||e.nextNumId<e.minId)&&(e.nextNumId=e.minId),(!Number.isInteger(e.nextAbstractNumId)||e.nextAbstractNumId<e.minId)&&(e.nextAbstractNumId=e.minId),e.nextNumId=jt(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=jt(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function xr(e,t="num"){let r=Au(e);if(!r)return null;let n=t==="abstract",o=n?r.nextAbstractNumId:r.nextNumId;return!Number.isInteger(o)||o<1?null:(n?(r.usedAbstractNumIds.add(o),r.nextAbstractNumId=jt(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=jt(o+1,r.usedNumIds,r.maxPreferred)),o)}function Iu(e){let t=xr(e,"num"),r=xr(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function xo(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function mn(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Oe&&e.localName===t)}function Ba(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(i=>i&&i.nodeType===1&&i.namespaceURI===Oe),o=null;r==="abstract"?o=n.find(i=>i.localName==="num"||i.localName==="numIdMacAtCleanup")||null:o=n.find(i=>i.localName==="numIdMacAtCleanup")||null,o?e.insertBefore(t,o):e.appendChild(t)}function Pu(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function br(e,t){let r=Pu(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Fa(e,t,r){e?.setAttribute?.(t,String(r))}function No(e,t){e?.setAttribute?.("w:val",String(t))}function Ru(e,t){if(!(!Array.isArray(e)||t==null))for(let r of e){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let o of n)No(o,t)}}function Cu(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=br(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function Ou(e,t,r){let n=String(e),o=String(t),i=Number.isInteger(r)&&r>0?r:1,a=Array.from({length:9},(s,l)=>{let c=Array.from({length:l+1},(f,m)=>`%${m+1}`).join(".")+".",u=720*(l+1);return`
175
- <w:lvl w:ilvl="${l}">
143
+ `);return{valid:a.every(s=>s.severity!=="error"),normalizedMarkdown:l,blocks:n,issues:a,counts:i,requiresStructuredContent:n.length>1||n.some(s=>s.type==="heading"||s.type==="table"||s.type==="list"&&s.items>1)}}function Qf(e,t,r={}){let n=ha(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var bn=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function Be(e,t){let r=bn.indexOf(t.nodeName),n=r===-1?999:r,a=!1;for(let o of Array.from(e.childNodes)){if(o.nodeType!==1)continue;let i=bn.indexOf(o.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,o),a=!0;break}}a||e.appendChild(t)}function ed(e,t,r,n){if(!t||!r)return;let a=!!r.bold,o=!!r.italic,i=!!r.underline,l=!!r.strikethrough,s=new Set;if(a&&(s.add("w:b"),s.add("w:bCs")),o&&(s.add("w:i"),s.add("w:iCs")),i&&s.add("w:u"),l&&s.add("w:strike"),s.size>0){let c=[];for(let u of Array.from(t.childNodes))s.has(u.nodeName)&&c.push(u);for(let u of c)t.removeChild(u)}if(a){let c=L(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c);let u=L(e,"w:bCs");u.setAttribute("w:val",n==="add"?"1":"0"),Be(t,u)}if(o){let c=L(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c);let u=L(e,"w:iCs");u.setAttribute("w:val",n==="add"?"1":"0"),Be(t,u)}if(i){let c=L(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Be(t,c)}if(l){let c=L(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Be(t,c)}}function Ks(e,t,r){ed(e,t,r,"remove")}function St(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=mr(r,!1)),r.nodeName==="w:i"&&(t.italic=mr(r,!1)),r.nodeName==="w:u"&&(t.underline=mr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=mr(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let a=n.toLowerCase();(a.includes("bold")||a.includes("strong"))&&(t.bold=!0),(a.includes("italic")||a.includes("emphasis"))&&(t.italic=!0),a.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function mr(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var js=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function Zt(e,t){let r=js.indexOf(t.nodeName),n=r===-1?999:r,a=!1;for(let o of Array.from(e.childNodes)){if(o.nodeType!==1)continue;let i=js.indexOf(o.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,o),a=!0;break}}a||e.appendChild(t)}function Hs(e,t){if(!t)return!1;let r=St(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let a=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:highlight"||l.localName==="highlight")),o=a?a.getAttribute("w:val")||a.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((o||null)!==i)return!0}if(t.color!==void 0){let a=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:color"||l.localName==="color")),o=a?a.getAttribute("w:val")||a.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((o?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let a=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:sz"||l.localName==="sz")),o=a?a.getAttribute("w:val")||a.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(o!==i)return!0}if(t.fontFamily!==void 0){let a=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:rFonts"||l.localName==="rFonts")),o=a?a.getAttribute("w:ascii")||a.getAttribute("ascii"):null,i=t.fontFamily||null;if(o!==i)return!0}return!1}function Gs(e,t,r){if(!t||!r)return;let n=o=>{let i=[];for(let l of Array.from(t.childNodes))l.nodeType===1&&o.includes(l.nodeName)&&i.push(l);for(let l of i)t.removeChild(l)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let o=L(e,"w:b");o.setAttribute("w:val",r.bold?"1":"0"),Be(t,o);let i=L(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),Be(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let o=L(e,"w:i");o.setAttribute("w:val",r.italic?"1":"0"),Be(t,o);let i=L(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),Be(t,i)}if(r.underline!==void 0){n(["w:u"]);let o=L(e,"w:u");o.setAttribute("w:val",r.underline?"single":"none"),Be(t,o)}let a=r.strike!==void 0?r.strike:r.strikethrough;if(a!==void 0){n(["w:strike","w:dstrike"]);let o=L(e,"w:strike");o.setAttribute("w:val",a?"1":"0"),Be(t,o)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let o=L(e,"w:highlight");o.setAttribute("w:val",String(r.highlight).toLowerCase()),Be(t,o)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let o=L(e,"w:color");o.setAttribute("w:val",String(r.color).replace(/^#/,"")),Be(t,o)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let o=String(r.fontSize),i=L(e,"w:sz");i.setAttribute("w:val",o),Be(t,i);let l=L(e,"w:szCs");l.setAttribute("w:val",o),Be(t,l)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let o=L(e,"w:rFonts");o.setAttribute("w:ascii",r.fontFamily),o.setAttribute("w:hAnsi",r.fontFamily),o.setAttribute("w:cs",r.fontFamily),Be(t,o)}}function qs(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(a=>a.nodeType===1&&(a.nodeName==="w:jc"||a.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(a=>a.nodeType===1&&(a.nodeName==="w:keepNext"||a.localName==="keepNext"));if((r?mr(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(a=>a.nodeType===1&&(a.nodeName==="w:keepLines"||a.localName==="keepLines"));if((r?mr(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(a=>a.nodeType===1&&(a.nodeName==="w:pageBreakBefore"||a.localName==="pageBreakBefore"));if((r?mr(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(a=>a.nodeType===1&&(a.nodeName==="w:pStyle"||a.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}return!1}function Ys(e,t,r){if(!t||!r)return;let n=a=>{let o=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&a.includes(i.nodeName)&&o.push(i);for(let i of o)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let a=L(e,"w:jc");a.setAttribute("w:val",r.alignment),Zt(t,a)}if(r.keepNext!==void 0){n(["w:keepNext"]);let a=L(e,"w:keepNext");r.keepNext||a.setAttribute("w:val","0"),Zt(t,a)}if(r.keepLines!==void 0){n(["w:keepLines"]);let a=L(e,"w:keepLines");r.keepLines||a.setAttribute("w:val","0"),Zt(t,a)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let a=L(e,"w:pageBreakBefore");r.pageBreakBefore||a.setAttribute("w:val","0"),Zt(t,a)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let a=L(e,"w:pStyle");a.setAttribute("w:val",r.style),Zt(t,a)}}var Zs="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Et(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Zs&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function td(e){return!e||e.nodeType!==1||e.namespaceURI!==Zs?!1:e.localName==="del"||e.localName==="moveFrom"}function Js(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||td(n))continue;if(Et(n,"r")){t.push(n);continue}let a=Array.from(n.childNodes||[]);for(let o=a.length-1;o>=0;o-=1)r.push(a[o])}return t}function qe(e){let t=new Set(["comment","footnote","endnote"]);return Pe(e,"*","p").filter(n=>{let a=n.parentNode;for(;a&&a.nodeName;){let o=String(a.localName||"").toLowerCase();if(t.has(o))return!1;a=a.parentNode}return!0})}function Qs(e){let t=[],r=0;for(let n=0;n<e.length;n++){let a=e[n],o=Js(a);for(let i of o){let l=Ee(i,"w:rPr");Array.from(i.childNodes||[]).forEach(s=>{if(Et(s,"t")){let c=s.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:s,runElement:i,paragraph:a,container:i.parentNode,rPr:l}),r+=c.length)}else(Et(s,"br")||Et(s,"cr")||Et(s,"tab")||Et(s,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:s,runElement:i,paragraph:a,container:i.parentNode,rPr:l}),r+=1)})}r=cr(r,n,e.length)}return{textSpans:t,charOffset:r}}function rd(e,t,r,n,a,o=null){let i=null;for(let c of Array.from(e.childNodes))if(Et(c,"rPr")){i=c;break}let l=St(i);o&&(o.bold&&!l.bold&&(l.bold=!0),o.italic&&!l.italic&&(l.italic=!0),o.underline&&!l.underline&&(l.underline=!0),o.strikethrough&&!l.strikethrough&&(l.strikethrough=!0)),l.hasFormatting=l.bold||l.italic||l.underline||l.strikethrough;let s=r;for(let c of Array.from(e.childNodes))if(Et(c,"t")){let u=c.textContent||"";if(u.length>0){let f=s,d=s+u.length;n.push({charStart:f,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...l}}),l.hasFormatting&&a.push({start:f,end:d,format:{...l},run:e,rPr:i}),s=d}}return s}function el(e){let t=[],r=[],n=0,a=qe(e);for(let o=0;o<a.length;o++){let i=a[o],l=null;for(let u of Array.from(i.childNodes))if(Et(u,"pPr")){for(let f of Array.from(u.childNodes))if(Et(f,"rPr")){l=f;break}break}let s=St(l);s.hasFormatting&&V(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(s)}`);let c=Js(i);for(let u of c)n=rd(u,i,n,r,t,s);n=cr(n,o,a.length)}return V(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:a}}var nd=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function lt(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())nd.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function At(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof Se?t:_t(r)||Ht(r),a=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let o of a){if(!B(o,"rPrChange"))continue;let i=String(n.next());typeof o.setAttributeNS=="function"?o.setAttributeNS(M,"w:id",i):o.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function pr(e,t,r,n,a=null){let o=L(e,t==="ins"?"w:ins":"w:del"),i=a||ae(n,e,t==="ins"?"ins":"del");return o.setAttribute("w:id",String(i.id)),o.setAttribute("w:author",i.author),o.setAttribute("w:date",i.date),r&&o.appendChild(r),o}function tl(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function ad(e,t){let r=tl(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=L(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function od(e,t){let r=tl(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=L(e,"w:rPr"),t.appendChild(r)),r}function rl(e,t,r,n,a=null){let o=ad(e,t),i=od(e,o);for(let c of Array.from(i.childNodes||[]))c.nodeType===1&&(c.localName==="ins"||c.localName==="del"||c.nodeName==="w:ins"||c.nodeName==="w:del")&&i.removeChild(c);let l=L(e,n==="ins"?"w:ins":"w:del"),s=a||ae(r,e,n==="ins"?"ins":"del");return l.setAttribute("w:id",String(s.id)),l.setAttribute("w:author",s.author),l.setAttribute("w:date",s.date),i.appendChild(l),l}function zr(e,t,r,n=null){return rl(e,t,r,"ins",n)}function gr(e,t,r,n=null){return rl(e,t,r,"del",n)}function Jt(e,t,r,n){let a=L(e,"w:r");if(r&&a.appendChild(r.cloneNode(!0)),!n)return nl(e,a,t),a;let o=L(e,n?"w:delText":"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=t,a.appendChild(o),a}function wa(e,t,r,n,a,o,i){if(!t)return[];let l=new Set([0,t.length]);for(let u of n){let f=Math.max(0,u.start-a),d=Math.min(t.length,u.end-a);f>=0&&f<t.length&&l.add(f),d>0&&d<=t.length&&l.add(d)}let s=Array.from(l).sort((u,f)=>u-f),c=[];for(let u=0;u<s.length-1;u++){let f=s[u],d=s[u+1],m=t.slice(f,d);if(!m)continue;let p=a+f,h=a+d,g=n.filter(y=>y.start<=p&&y.end>=h),v={...St(r)};g.forEach(y=>{y.format&&Object.assign(v,y.format)});let w=g.length>0?Xr(e,r,v,o,i):r?.cloneNode(!0)||null;c.push(Lo(e,m,w,!1))}return c}function Lo(e,t,r,n){let a=L(e,"w:r");if(r&&a.appendChild(r),!n)return nl(e,a,t),a;let o=L(e,n?"w:delText":"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=t,a.appendChild(o),a}function nl(e,t,r){let a=String(r||"").split(/(\t|\n|\u2011)/);for(let o of a){if(!o)continue;if(o===" "){t.appendChild(L(e,"w:tab"));continue}if(o===`
144
+ `){t.appendChild(L(e,"w:br"));continue}if(o==="\u2011"){t.appendChild(L(e,"w:noBreakHyphen"));continue}let i=L(e,"w:t");/^\s|\s$/.test(o)&&i.setAttribute("xml:space","preserve"),i.textContent=o,t.appendChild(i)}}function Xr(e,t,r,n,a){let o=L(e,"w:rPr");t&&Array.from(t.childNodes).forEach(s=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(s.nodeName)||o.appendChild(s.cloneNode(!0))});let i=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&a&&id(e,o,n,t);let l=(s,c,u=null,f="0")=>{let d=L(e,s);c?u&&d.setAttribute("w:val",u):f&&d.setAttribute("w:val",f);let m=bn.indexOf(s),p=m===-1?999:m,h=!1;for(let g of Array.from(o.childNodes)){if(g.nodeType!==1)continue;let v=bn.indexOf(g.nodeName);if((v===-1?999:v)>p){o.insertBefore(d,g),h=!0;break}}h||o.appendChild(d)};return l("w:b",!!i.bold,"1","0"),l("w:bCs",!!i.bold,"1","0"),l("w:i",!!i.italic,"1","0"),l("w:iCs",!!i.italic,"1","0"),l("w:u",!!i.underline,"single","none"),l("w:strike",!!i.strikethrough,"1","0"),o}function Nn(e,t,r,n,a){let o=L(e,"w:rPrChange"),i=ae(r,e,"rPrChange");o.setAttribute("w:id",String(i.id)),o.setAttribute("w:author",i.author),o.setAttribute("w:date",n||i.date);let s=lt(a||t)||L(e,"w:rPr");o.appendChild(s);let c=Ee(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(o),o}function id(e,t,r,n){Nn(e,t,r,null,n||t)}function al(e,t,r,n,a){let o=L(e,"w:pPrChange"),i=ae(r,e,"pPrChange");o.setAttribute("w:id",String(i.id)),o.setAttribute("w:author",i.author),o.setAttribute("w:date",n||i.date);let s=lt(a||t)||L(e,"w:pPr");o.appendChild(s);let c=Array.from(t.childNodes).find(u=>u.nodeType===1&&(u.nodeName==="w:pPrChange"||u.localName==="pPrChange"));return c&&t.removeChild(c),t.appendChild(o),o}var sd="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Vr(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===sd&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function va(e,t,r){let n=new Map;for(let i of r)!i||!i.paragraph||(n.has(i.paragraph)||n.set(i.paragraph,[]),n.get(i.paragraph).push(i));let a=[],o=0;return t.forEach((i,l)=>{let s=(n.get(i)||[]).slice().sort((d,m)=>d.charStart-m.charStart),c=ld(s),u=Bo(c),f=u.trim();a.push({paragraph:i,spans:s,text:c,normalizedText:u,normalizedTrim:f,startOffset:o}),o+=u.length,o=cr(o,l,t.length)}),a}function ol(e,t){if(!t)return null;let r=Bo(t),n=r.trim();if(!n)return null;for(let a of e)if(a.normalizedText===r)return a;for(let a of e)if(a.normalizedTrim===n)return a;return null}function il(e,t){let r=Bo(t),n=r.trim(),a=null,o=0;for(let i of e)if(i.normalizedText===r)return a=i,{targetInfo:a,matchOffset:o};if(n.length>0){for(let i of e)if(i.normalizedTrim===n)return a=i,{targetInfo:a,matchOffset:o}}if(n.length>0){let l=e.map(s=>s.normalizedText).join(`
145
+ `).indexOf(n);if(l!==-1)for(let s of e){let c=s.startOffset,u=s.normalizedText.length;if(l>=c&&l<=c+u){a=s,o=l-c;break}}}if(!a&&e.length===1&&r.length>0){let i=e[0],l=i.normalizedTrim||"";if(l.length>0){let s=r.indexOf(l);s>=0&&(a=i,o=-s)}}return{targetInfo:a,matchOffset:o}}function sl(e){let t=e;for(;t;){if(Vr(t,"p"))return t;t=t.parentNode}return null}function ld(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Vr(n,"t")?t+=r.textElement.textContent||"":Vr(n,"tab")?t+=" ":Vr(n,"br")||Vr(n,"cr")?t+=`
146
+ `:Vr(n,"noBreakHyphen")&&(t+="\u2011")}return t}function Bo(e){return e?e.replace(/\r/g,`
147
+ `).replace(/\u00a0/g," "):""}function ll(e,t,r){let n=Array.from(new Set(r)).sort((l,s)=>l-s);if(n.length===0||t.length===0)return[...t];let a=[...t].sort((l,s)=>l.charStart-s.charStart||l.charEnd-s.charEnd),o=[],i=0;for(let l of a){for(;i<n.length&&n[i]<=l.charStart;)i++;let s=l;for(;i<n.length&&n[i]<s.charEnd;){let c=n[i],u=cd(e,s,c);if(!u){i++;continue}o.push(u[0]),s=u[1],i++}o.push(s)}return o}function cd(e,t,r){let n=t.runElement,a=n.parentNode;if(!a)return null;let o=t.textElement.textContent||"",i=r-t.charStart,l=o.substring(0,i),s=o.substring(i);if(l.length===0||s.length===0)return null;let c=Jt(e,l,t.rPr,!1),u=Jt(e,s,t.rPr,!1);a.insertBefore(c,n),a.insertBefore(u,n),a.removeChild(n);let f=c.getElementsByTagName("w:t")[0],d=u.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:c},{...t,charStart:r,textElement:d,runElement:u}]}var ud="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function fd(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===ud&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function dd(e){return Array.isArray(e)?{textSpans:e,paragraphs:null,paragraphInfos:null}:!e||typeof e!="object"?{textSpans:null,paragraphs:null,paragraphInfos:null}:{textSpans:Array.isArray(e.textSpans)?e.textSpans:null,paragraphs:Array.isArray(e.paragraphs)?e.paragraphs:null,paragraphInfos:Array.isArray(e.paragraphInfos)?e.paragraphInfos:null}}function cl(e,t,r,n,a,o=!0){let i=!1,l=new Set;V(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let s of r){let c=s.run;if(l.has(c)||(l.add(c),!c.parentNode))continue;V("[OxmlEngine] Processing run for surgical format removal, format:",s.format);let u=Ee(c,"w:rPr");u||(u=L(e,"w:rPr"),c.insertBefore(u,c.firstChild)),o&&Nn(e,u,a||re()),Ks(e,u,s.format),i=!0}return i?(V("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(V("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function md(e,t,r,n,a,o=!0){let i=!1,l=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let s=[];for(let d of r)s.push(d.start,d.end);let u=ll(e,t,s).slice().sort((d,m)=>d.charStart-m.charStart||d.charEnd-m.charEnd),f=pd(r);for(let d of u){if(!d||!d.textElement||!fd(d.textElement,"t"))continue;let m=f(d.charStart,d.charEnd);if(m.length===0)continue;let p=yo(...m.map(E=>E.format)),h={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},g=d.format||St(d.rPr),v={bold:!!g.bold,italic:!!g.italic,underline:!!g.underline,strikethrough:!!g.strikethrough};if(!["bold","italic","underline","strikethrough"].some(E=>h[E]!==v[E])||l.has(d.runElement)||(l.add(d.runElement),!(d.textElement.textContent||""))||!d.runElement.parentNode)continue;let I=d.runElement,N=Ee(I,"w:rPr"),T=Xr(e,N,h,a||re(),o),S=N;if(!S)I.insertBefore(T,I.firstChild);else{for(;S.firstChild;)S.removeChild(S.firstChild);Array.from(T.childNodes).forEach(E=>S.appendChild(E))}i=!0}return{oxml:n.serializeToString(e),hasChanges:i}}function ul(e,t,r,n,a,o=!0,i=null){let l=dd(i),s=l.paragraphs||qe(e),c=l.textSpans||[];if(l.textSpans||({textSpans:c}=Qs(s)),!c||c.length===0)return mt("[OxmlEngine] No spans available for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};if(!r||r.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let u=l.paragraphInfos||va(e,s,c),{targetInfo:f,matchOffset:d}=il(u,t);if(!f||!f.spans||f.spans.length===0)return mt("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let m=f.spans[0].charStart,p=f.spans.map(g=>({...g,charStart:g.charStart-m,charEnd:g.charEnd-m})),h=r.map(g=>({...g,start:g.start+d,end:g.end+d}));return md(e,p,h,n,a,o)}function pd(e){let t=(e||[]).slice().sort((a,o)=>a.start-o.start||a.end-o.end),r=[],n=0;return(a,o)=>{for(;n<t.length&&t[n].start<o;)r.push(t[n]),n++;for(let i=r.length-1;i>=0;i--)r[i].end<=a&&r.splice(i,1);return r.filter(i=>i.start<o&&i.end>a)}}function ya(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function hr(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,a=e;for(;a&&a!==t;){let o=ya(a);if(n==="accepted"&&(o==="del"||o==="moveFrom")||n==="rejected"&&(o==="ins"||o==="moveTo"))return!1;a=a.parentNode}return!0}function wr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!hr(e,n,r))return"";let a="",o=i=>{for(let l of Array.from(i?.childNodes||[])){if(l?.nodeType!==1||l.namespaceURI&&l.namespaceURI!==M||!hr(l,n,r))continue;let s=ya(l);s==="t"||s==="delText"&&r==="rejected"?a+=l.textContent||"":s==="tab"?a+=" ":s==="br"||s==="cr"?a+=`
148
+ `:s==="noBreakHyphen"?a+="\u2011":s==="softHyphen"?a+="\xAD":o(l)}};return o(e),a}var Qt=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function xa(e,t={}){if(!e)return[];let r=[];function n(f,d,m){for(let p of Array.from(f?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==M)continue;let h=ya(p);if(h==="pPr"||h==="rPr")continue;let g=d;h==="ins"?g={kind:"insertion",author:Qt(p,"author")||void 0,revisionId:Qt(p,"id")||void 0}:h==="del"?g={kind:"deletion",author:Qt(p,"author")||void 0,revisionId:Qt(p,"id")||void 0}:h==="moveFrom"?g={kind:"move_from",author:Qt(p,"author")||void 0,revisionId:Qt(p,"id")||void 0}:h==="moveTo"&&(g={kind:"move_to",author:Qt(p,"author")||void 0,revisionId:Qt(p,"id")||void 0});let v=m;h==="r"&&(v=p);let w=null,y=g?g.kind:"baseline",x=g?.author,b=g?.revisionId;h==="t"?w=p.textContent||"":h==="delText"?(w=p.textContent||"",g||(y="deletion")):h==="tab"?w=" ":h==="br"||h==="cr"?w=`
149
+ `:h==="noBreakHyphen"?w="\u2011":h==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:y,author:x,revisionId:b,carrier:v||p,carrierContainer:(v||p)?.parentNode||null}):n(p,g,v)}}let a=ya(e)==="r"?e:null;if(n(e,null,a),r.length===0)return[];let o=t.mergeRuns!==!1,i=[],l=null;for(let f of r){if(!l){l={...f};continue}let d=l.kind===f.kind,m=l.author===f.author,p=l.revisionId===f.revisionId,h=l.carrier===f.carrier,g=o&&l.carrierContainer===f.carrierContainer;d&&m&&p&&(h||g)?l.text+=f.text:(i.push(l),l={...f})}l&&i.push(l);let s=0,c=0,u=[];for(let f of i){let d=f.kind!=="deletion"&&f.kind!=="move_from",m=f.kind!=="insertion"&&f.kind!=="move_to",p=d?s:null,h=m?c:null;d&&(s+=f.text.length),m&&(c+=f.text.length);let g={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:h};f.author!==void 0&&(g.author=f.author),f.revisionId!==void 0&&(g.revisionId=f.revisionId),u.push(g)}return u}function te(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=xa(e,t);return r==="rejected"?n.filter(a=>a.rejectedStart!==null).map(a=>a.text).join(""):n.filter(a=>a.acceptedStart!==null).map(a=>a.text).join("")}var gd="http://schemas.microsoft.com/office/word/2010/wordml";function fl(e,t,r={}){let{targetParagraphId:n=null}=r,a=ze(e,M,"tbl");if(a.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let i=qe(e).filter(s=>{let c=s.parentNode;for(;c;){if(B(c,"tc"))return!0;c=c.parentNode}return!1});V(`[OxmlEngine] Table wrapper detected: ${a.length} tables, ${i.length} paragraphs in cells`);let l=null;if(n){let s=String(n).toUpperCase();l=i.find(c=>{let u=wd(c);return u&&u.toUpperCase()===s})||null,l?V(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):V(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let s=t.trim();if(!l){for(let c of i)if(te(c).trim()===s){l=c,V(`[OxmlEngine] Found target paragraph by text match: "${s.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:i.length>0,targetParagraph:l,paragraphs:i,paragraph:l||i[0]||null,tableElement:a[0]}}function In(e,t,r){let n=Array.isArray(t)?t:[t],a="";for(let o of n){if(!o)continue;let i=r.serializeToString(o);i=i.replace(/\s+xmlns:w="[^"]*"/g,""),i=i.replace(/\s+xmlns:r="[^"]*"/g,""),i=i.replace(/\s+xmlns:wp="[^"]*"/g,""),a+=i}return V(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),V(`[OxmlEngine] Paragraph XML preview: ${a.substring(0,200)}...`),hd(a)}function hd(e){return ks(e)}function wd(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(gd,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Do(e){return B(e,"t")||B(e,"delText")?e.textContent||"":B(e,"br")||B(e,"cr")?`
150
+ `:B(e,"tab")?" ":B(e,"noBreakHyphen")?"\u2011":B(e,"softHyphen")?"\xAD":""}function Fo(e){return B(e,"t")||B(e,"delText")||B(e,"br")||B(e,"cr")||B(e,"tab")||B(e,"noBreakHyphen")||B(e,"softHyphen")}function ba(e){let t="",r=[];return e.forEach((n,a)=>{let o=n.parentNode;for(let i=n.firstChild;i;i=i.nextSibling)if(B(i,"r"))t+=Tn(i,n,o,t.length,r).text;else if(B(i,"hyperlink"))for(let l=i.firstChild;l;l=l.nextSibling)B(l,"r")&&(t+=Tn(l,n,o,t.length,r).text);else if(B(i,"ins"))for(let l=i.firstChild;l;l=l.nextSibling)B(l,"r")&&(t+=Tn(l,n,o,t.length,r).text);else if(B(i,"sdt")){let l=Array.from(i.childNodes||[]).find(s=>B(s,"sdtContent"));if(l)for(let s=l.firstChild;s;s=s.nextSibling)B(s,"r")&&(t+=Tn(s,n,o,t.length,r).text)}else if(B(i,"smartTag"))for(let l=i.firstChild;l;l=l.nextSibling)B(l,"r")&&(t+=Tn(l,n,o,t.length,r).text);t=Br(t,a,e.length)}),{fullText:t,textSpans:r}}function Tn(e,t,r,n,a){let o=Ee(e,"w:rPr"),i=n,l=[];for(let s=e.firstChild;s;s=s.nextSibling)if(B(s,"t")){let c=s.textContent||"";if(c.length===0)continue;a.push({charStart:i,charEnd:i+c.length,textElement:s,runElement:e,paragraph:t,container:r,rPr:o}),i+=c.length,l.push(c)}else if(Fo(s)){let c=Do(s);a.push({charStart:i,charEnd:i+1,textElement:s,runElement:e,paragraph:t,container:r,rPr:o}),i+=1,l.push(c)}return{text:l.join("")}}function Na(e){let t=e.slice().sort((a,o)=>a.charStart-o.charStart||a.charEnd-o.charEnd),r=t.map(a=>a.charStart),n=t.map(a=>a.charEnd);return{spans:t,starts:r,ends:n}}function Sn(e,t,r,n){if(r<=t||e.spans.length===0)return;let a=Xo(e.ends,t);for(;a<e.spans.length;){let o=e.spans[a];if(o.charStart>=r)break;n(o),a++}}function $o(e,t){if(e.spans.length===0)return null;let r=Xo(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function Uo(e,t){let r=vd(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function zo(e,t){let r=Xo(e.ends,t)-1;return r>=0?e.spans[r]:null}function Xo(e,t){let r=0,n=e.length;for(;r<n;){let a=r+n>>1;e[a]<=t?r=a+1:n=a}return r}function vd(e,t){let r=0,n=e.length;for(;r<n;){let a=r+n>>1;e[a]<t?r=a+1:n=a}return r}function dl(e,t,r=null){if(!e||!e.spans||e.spans.length===0)return{leftSpan:null,rightSpan:null,containingSpan:null,isInterior:!1,fallbackParagraph:r};let n=$o(e,t),a=n!==null&&t>n.charStart&&t<n.charEnd,o=Uo(e,t)||(t>0?zo(e,t):null),i=e.spans.find(l=>l.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:o,rightSpan:i,containingSpan:n,isInterior:a,fallbackParagraph:r}}var yd=new Set(["ins","del"]);function Lt(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(B(n,"rPr")||!Fo(n))continue;let a=Do(n);a.length!==0&&(t.push({node:n,start:r,end:r+a.length,text:a}),r+=a.length)}return t}function ct(e){return e.length===0?0:e[e.length-1].end}function Rt(e,t,r,n,a){let o=[];return n<=r||t.forEach(i=>{let l=Math.max(r,i.start),s=Math.min(n,i.end);if(s<=l)return;let c=l-i.start,u=s-i.start,f=i.text.slice(c,u);o.push(Id(e,i.node,f,a))}),o}function En(e,t,r){let n=L(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(a=>n.appendChild(a)),n}function vr(e,t,r,n,a){if(n.length===0)return null;let o=En(e,n,a);return t.insertBefore(o,r),o}function Ia(e,t,r,n=null){let a=Nd(t);if(!yd.has(a))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let o=Array.from(t.childNodes||[]),i=o.reduce((d,m)=>d+(B(m,"r")?ct(Lt(m)):0),0);if(r>i)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${i}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===i)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let l=t.cloneNode(!1),s=t.cloneNode(!1),c=0;for(let d of o){if(!B(d,"r")){(c<=r?l:s).appendChild(d.cloneNode(!0));continue}let m=Lt(d),p=ct(m),h=c+p;if(h<=r)l.appendChild(d.cloneNode(!0));else if(c>=r)s.appendChild(d.cloneNode(!0));else{let g=r-c,v=Array.from(d.childNodes||[]).find(I=>B(I,"rPr"))||null,w=a==="del",y=Rt(e,m,0,g,w),x=Rt(e,m,g,p,w);l.appendChild(En(e,y,v));let b=En(e,x,v);s.appendChild(b)}c=h}let u=xd(e,n);At(s,u);let f=u.next();return bd(s,"id",String(f)),u._receiptCollector?.recordRevision(f,a),{leftCarrier:l,rightCarrier:s}}function xd(e,t){return t instanceof Se?t:_t(e)||Ht(e)}function bd(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(M,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function Nd(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Id(e,t,r,n){if(n&&(B(t,"delText")||B(t,"t"))){let o=L(e,"w:delText");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}if(B(t,"t")){let o=t.cloneNode(!1);return o.textContent=r,/^\s|\s$/.test(r)&&o.setAttribute("xml:space","preserve"),o}if(r===`
151
+ `&&(B(t,"br")||B(t,"cr"))||r===" "&&B(t,"tab")||r==="\u2011"&&B(t,"noBreakHyphen")||r==="\xAD"&&B(t,"softHyphen"))return t.cloneNode(!0);if(n){let o=L(e,"w:delText");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}let a=L(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}function gl(e,t,r,n,a,o,i){if(a.length===0)return!1;let l=t.rPr,s=St(l),c={...s};if(a.forEach(I=>Object.assign(c,I.format)),!["bold","italic","underline","strikethrough"].some(I=>!!c[I]!==s[I]))return!1;let d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,h=r-p,g=n-p,v=m.substring(0,h),w=m.substring(h,g),y=m.substring(g);if(v.length>0){let I=Jt(e,v,l,!1);d.insertBefore(I,t.runElement)}let x=Xr(e,l,c,o,i),b=Lo(e,w,x,!1);if(d.insertBefore(b,t.runElement),y.length>0){let I=Jt(e,y,l,!1);d.insertBefore(I,t.runElement)}return d.removeChild(t.runElement),!0}function jo(e,t,r,n,a,o,i=null){let l=[];if(Sn(t,r,n,m=>{l.push(m)}),l.length===0)return!1;let s=new Map;l.forEach(m=>{m.runElement?.parentNode&&(s.has(m.runElement)||s.set(m.runElement,[]),s.get(m.runElement).push(m))});let c=[];s.forEach((m,p)=>{let h=p.parentNode;if(!h)return;let g=Lt(p);if(g.length===0)return;let v=1/0,w=-1/0;m.forEach(y=>{let x=g.find(N=>N.node===y.textElement);if(!x)return;let b=Math.max(0,r-y.charStart),I=Math.min(y.charEnd-y.charStart,n-y.charStart);I<=b||(v=Math.min(v,x.start+b),w=Math.max(w,x.start+I))}),!(!Number.isFinite(v)||w<=v)&&c.push({runElement:p,parent:h,rPr:m[0].rPr,beforePieces:Rt(e,g,0,v,!1),deletedPieces:Rt(e,g,v,w,!0),afterPieces:Rt(e,g,w,ct(g),!1),globalStart:Math.max(r,Math.min(...m.map(y=>y.charStart))),globalEnd:Math.min(n,Math.max(...m.map(y=>y.charEnd))),carrierGlobalStart:B(h,"ins")?hl(t,h):null})});let u=[];for(let m of c){let p=u[u.length-1],h=p?.[p.length-1];h&&h.parent===m.parent&&Ed(h.runElement)===m.runElement?p.push(m):u.push([m])}let f=!1,d=!1;for(let m of u){let p=m[0],h=null;if(o&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ae(a,e,"del").id}:i:null;d=!0,h=pr(e,"del",null,a,w)}for(let w of m){let{parent:y,runElement:x}=w;vr(e,y,x,w.beforePieces,w.rPr),h&&w===p&&y.insertBefore(h,x),h&&w.deletedPieces.length>0&&h.appendChild(En(e,w.deletedPieces,w.rPr));let b=vr(e,y,x,w.afterPieces,w.rPr);w.globalEnd===n&&!B(y,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:y,referenceNode:b||x.nextSibling,rPr:w.rPr})),y.removeChild(x),f=!0}let g=B(p.parent,"ins")?p.parent:null,v=Math.max(...m.map(w=>w.globalEnd));if(g&&v===n){let w=p.carrierGlobalStart,y=m.filter(b=>b.globalStart<n).reduce((b,I)=>b+I.deletedPieces.reduce((N,T)=>N+(T.textContent||"").length,0),0),x=Math.max(0,n-w-y);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:g,splitOffset:x,rPr:p.rPr})}}return f}function Wr(e,t,r,n,a,o=[],i=0,l=!0,s=null,c=null,u=null,f="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&f==="slice-cross-author"&&pl(d.carrier)&&Wo(d.carrier,a))return t.revisionInsertionAnchors.delete(r),Vo(e,d.carrier,d.splitOffset,n,d.rPr,a,o,i,l,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!u&&pl(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),er(e,m.parent,m.referenceNode,n,m.rPr,a,o,i,l,c),!0;if(!u){let b=$o(t,r);if(!b&&r>0&&(b=Uo(t,r)),!b&&r>0&&(b=zo(t,r)),!b&&t.spans.length>0&&(b=t.spans[t.spans.length-1]),!b)return s?(er(e,s,null,n,null,a,o,i,l,c),!0):!1;let I=b.runElement.parentNode;if(!I)return s?(er(e,s,null,n,b.rPr,a,o,i,l,c),!0):!1;let N=!(l&&f==="slice-cross-author"&&Sd(I,a));if(l&&f==="slice-cross-author"&&Wo(I,a))return Vo(e,I,ml(t,I,r),n,b.rPr,a,o,i,l,c);let T=Lt(b.runElement),S=T.find(A=>A.node===b.textElement),E=S?S.start+Math.max(0,Math.min(r-b.charStart,b.charEnd-b.charStart)):r<=b.charStart?0:ct(T);if(E>0&&E<ct(T)){let A=Rt(e,T,0,E,!1),R=Rt(e,T,E,ct(T),!1);return vr(e,I,b.runElement,A,b.rPr),er(e,I,b.runElement,n,b.rPr,a,o,i,N,c),vr(e,I,b.runElement,R,b.rPr),I.removeChild(b.runElement),!0}let _=r<=b.charStart?b.runElement:b.runElement.nextSibling;return er(e,I,_,n,b.rPr,a,o,i,N,c),!0}let p=dl(t,r,s),h=p.leftSpan&&B(p.leftSpan.runElement?.parentNode,"hyperlink"),g=p.rightSpan&&B(p.rightSpan.runElement?.parentNode,"hyperlink"),v=p.containingSpan&&B(p.containingSpan.runElement?.parentNode,"hyperlink");if(u.hyperlink==="outside"){if(p.isInterior&&v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(u.hyperlink==="inside"&&!h&&!g&&!v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(u.formatting==="none"?w=null:u.formatting==="right"?w=p.rightSpan?.rPr||null:u.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let b=p.containingSpan,I=b.runElement.parentNode||s;if(!I)return!1;let N=Lt(b.runElement),T=N.find(E=>E.node===b.textElement),S=T?T.start+Math.max(0,Math.min(r-b.charStart,b.charEnd-b.charStart)):r<=b.charStart?0:ct(N);if(S>0&&S<ct(N)){let E=Rt(e,N,0,S,!1),_=Rt(e,N,S,ct(N),!1);return vr(e,I,b.runElement,E,b.rPr),er(e,I,b.runElement,n,w,a,o,i,l,c),vr(e,I,b.runElement,_,b.rPr),I.removeChild(b.runElement),!0}}let y=null,x=null;if(u.hyperlink==="outside"){if(g){let b=p.rightSpan.runElement.parentNode;y=b.parentNode||s,x=b}else if(h){let b=p.leftSpan.runElement.parentNode;y=b.parentNode||s,x=b.nextSibling}}else u.hyperlink==="inside"&&(g?(y=p.rightSpan.runElement.parentNode,x=p.rightSpan.runElement):h&&(y=p.leftSpan.runElement.parentNode,x=p.leftSpan.runElement.nextSibling));if(y||(p.rightSpan?(y=p.rightSpan.runElement.parentNode||s,x=p.rightSpan.runElement):p.leftSpan?(y=p.leftSpan.runElement.parentNode||s,x=p.leftSpan.runElement.nextSibling):(y=s,x=null)),u.bookmark&&y&&(u.bookmark==="outside"?(x&&B(x.previousSibling,"bookmarkStart")&&(x=x.previousSibling),p.leftSpan&&B(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=p.leftSpan.runElement.nextSibling.nextSibling)):u.bookmark==="inside"&&(x&&B(x,"bookmarkStart")&&(x=x.nextSibling),p.leftSpan&&B(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=p.leftSpan.runElement.nextSibling))),u.comment&&y)if(u.comment==="outside"){if(x&&B(x.previousSibling,"commentRangeStart")&&(x=x.previousSibling),p.leftSpan&&B(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let b=p.leftSpan.runElement.nextSibling.nextSibling;b&&(B(b,"commentReference")||B(b,"r"))&&Array.from(b.childNodes||[]).some(N=>B(N,"commentReference"))&&(b=b.nextSibling),x=b}}else u.comment==="inside"&&(x&&B(x,"commentRangeStart")&&(x=x.nextSibling),p.leftSpan&&B(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(x=p.leftSpan.runElement.nextSibling));if(l&&u.revision==="coalesce_same_author"){let b=null,I=null;if(p.leftSpan&&B(p.leftSpan.runElement.parentNode,"ins")){let N=p.leftSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(M,"author"))===a&&(b=N,I=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&B(p.rightSpan.runElement.parentNode,"ins")){let N=p.rightSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(M,"author"))===a&&(b=N,I=p.rightSpan.runElement)}if(b){let N=Jt(e,n,w,!1);return b.insertBefore(N,I),!0}}return l&&f==="slice-cross-author"&&Wo(y,a)?Vo(e,y,ml(t,y,r),n,w,a,o,i,l,c):(er(e,y,x,n,w,a,o,i,l,c),!0)}function Vo(e,t,r,n,a,o,i,l,s,c){let u=t.parentNode;if(!u)return!1;let{leftCarrier:f,rightCarrier:d}=Ia(e,t,r);return f&&u.insertBefore(f,t),er(e,u,t,n,Td(a),o,i,l,s,c),d&&u.insertBefore(d,t),u.removeChild(t),!0}function Td(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>B(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function ml(e,t,r){let n=hl(e,t),a=e.spans.filter(o=>o.runElement?.parentNode===t).reduce((o,i)=>o+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,a))}function hl(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function Wo(e,t){return B(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(M,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function Sd(e,t){return B(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(M,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function Ed(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function pl(e){return!!e?.parentNode}function er(e,t,r,n,a,o,i,l,s,c=null){let u=Ot(i,l,l+n.length);if(u.length===0){let d=Jt(e,n,a,!1);if(s){let m=pr(e,"ins",d,o,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let f=wa(e,n,a,u,l,o,s);if(s){let d=pr(e,"ins",null,o,c);f.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else f.forEach(d=>t.insertBefore(d,r))}function wl(e,t,r,n=!1){let a=[];if(Sn(e,t,r,m=>a.push(m)),a.length===0)return{safe:!1};let o=a[0].runElement,i=o?.parentNode;if(!i)return{safe:!1};if(!a.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let s=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(s)||s==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of a){let p=m.runElement;for(let h of Array.from(p.childNodes||[]))if(h.nodeType===1){let g=h.localName||h.nodeName.replace(/^.*:/,"");if(c.has(g)||g==="fldChar")return{safe:!1,structuralBoundary:!0}}}let u=a[a.length-1].runElement,f=o;for(;f&&f!==u;){if(f!==o){let m=f.localName||f.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}f=f.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let h of Array.from(m.childNodes||[]))if(h.nodeType===1&&d(h))return!0;return!1}return d(o.previousSibling)||d(u.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function xl(e,t,r,n,a,o,i=!0,l=null,s={},c={}){let u=l?[l]:qe(e),{fullText:f,textSpans:d}=ba(u),m=c.existingRevisions==="slice-cross-author"?Ts(f,r):null,p=m||Rd(yn(f,r,s),s),h=Na(d),g=c.pairReplacements===!0,v=[],w=0,y=0,x=!1,b=m?Cd(m):[];if(b.length>1&&o.length===0)for(let T of b.slice().reverse()){let S=ba(u).textSpans,E=Na(S),_=T.text.replace(/\n/g," ");if(_.length===0)continue;let A=Wr(e,E,T.originalPos,_,a,o,T.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(A&&typeof A=="object"&&A.error)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:A.error});A===!0&&(x=!0)}else if(o.length===0){let T=Pd(p);for(let S of T.reverse()){let E=Na(ba(u).textSpans);if(S.type==="insert"){let R=Wr(e,E,S.start,S.text.replace(/\n/g," "),a,o,S.newPos,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(R&&typeof R=="object"&&R.error)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:R.error});R===!0&&(x=!0);continue}let _=null,A=null;if(S.type==="replace"&&g&&i&&S.text.replace(/\n/g," ")){let R=wl(E,S.start,S.end,c?.existingRevisions==="slice-cross-author");if(R.safe){let O=hn(a,e);_={id:O.deletionId,author:O.author,date:O.date},A={id:O.insertionId,author:O.author,date:O.date}}else R.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(jo(e,E,S.start,S.end,a,i,_)&&(x=!0),S.type==="replace"){let R=Wr(e,E,S.end,S.text.replace(/\n/g," "),a,o,S.newPos,i,u[0]||null,A,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(R&&typeof R=="object"&&R.error)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:R.error});R===!0&&(x=!0)}}}else for(let T=0;T<p.length;T++){let[S,E]=p[T];if(S===0){let _=E.length,A=w,R=w+_;Sn(h,A,R,O=>{let P=Math.max(O.charStart,A),C=Math.min(O.charEnd,R),k=C-P,D=P-A,z=y+D,H=z+k,G=Ot(o,z,H);gl(e,O,P,C,G,a,i)&&(x=!0)}),w+=_,y+=_}else if(S===-1){let _=T+1<p.length&&p[T+1][0]===1,A=!1,R=null,O=null;if(g&&i&&_&&p[T+1][1].replace(/\n/g," ").length>0){let k=wl(h,w,w+E.length,c?.existingRevisions==="slice-cross-author");if(k.safe){let D=hn(a,e);R={id:D.deletionId,author:D.author,date:D.date},O={id:D.insertionId,author:D.author,date:D.date},A=!0}else k.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(jo(e,h,w,w+E.length,a,i,R)&&(x=!0),w+=E.length,A){T++;let[,P]=p[T],C=P.replace(/\n/g," ");if(C.length>0){let k=Wr(e,h,w,C,a,o,y,i,u[0]||null,O,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(k&&typeof k=="object"&&k.error)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:k.error});k===!0&&(x=!0)}y+=P.length}}else if(S===1){let _=E.replace(/\n/g," ");if(_.length>0){let A=Wr(e,h,w,_,a,o,y,i,u[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(A&&typeof A=="object"&&A.error)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:A.error});A===!0&&(x=!0)}y+=E.length}}let I=u.map(T=>te(T)).join(`
152
+ `),N=String(r).replace(/\r\n/g,`
153
+ `);if(c.existingRevisions==="slice-cross-author"&&I!==N){let T=Ad(N,I);return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Generated OOXML accepted-view text does not match the requested modified text; the mutation was rejected.",mismatchOffset:T,expectedExcerpt:vl(N,T),actualExcerpt:vl(I,T),expectedCodePoint:yl(N,T),actualCodePoint:yl(I,T)},...v.length>0?{warnings:[...new Set(v)]}:{}})}return we({oxml:n.serializeToString(e),hasChanges:x,...v.length>0?{warnings:[...new Set(v)]}:{}})}function Ad(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return n;return r}function vl(e,t,r=40){let n=Math.max(0,t-r),a=Math.min(e.length,t+r);return e.slice(n,a)}function yl(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Rd(e,t){let r=[];for(let n=0;n<e.length;n++){let[a,o]=e[n],i=e[n+1];if(a===-1&&i?.[0]===1&&o!==i[1]&&o.length===i[1].length&&o.replace(/\u00a0/g," ")===i[1].replace(/\u00a0/g," ")){r.push(...Is(o,i[1],t)),n++;continue}r.push([a,o])}return r}function Pd(e){let t=[],r=0,n=0;for(let a=0;a<e.length;a++){let[o,i]=e[a];if(o===0){r+=i.length,n+=i.length;continue}if(o===-1){let l=e[a+1];l?.[0]===1?(t.push({type:"replace",start:r,end:r+i.length,newPos:n,text:l[1]}),r+=i.length,n+=l[1].length,a++):(t.push({type:"delete",start:r,end:r+i.length,newPos:n,text:""}),r+=i.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:i}),n+=i.length}return t}function Cd(e){let t=[],r=0,n=0;for(let[a,o]of e)a===0?(r+=o.length,n+=o.length):a===-1?r+=o.length:a===1&&(t.push({originalPos:r,newPos:n,text:o}),n+=o.length);return t}var Nl=Qi(Ro(),1);var Il=new Nl.diff_match_patch;function Tl(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Od(e,t){return e?.getAttributeNS?.(M,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function bl(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let a=0,o=t-1;for(;a<=o;){let i=Math.floor((a+o)/2);e[i].end<=r?a=i+1:o=i-1}t=a}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function _d(e){let t=new Map;return e.forEach(r=>{t.has(r.start)||t.set(r.start,[]),t.get(r.start).push(r)}),t}function Sl(e,t,r=null){let n=e.documentElement,a=B(n,"body")||Tl(n)==="package",o=r||qe(e),i=Xe(e,M,"body");!i&&a&&(i=n);let l="",s=[],c=[],u=[],f=new Map,d=new Map,m=new Set,p={nextCharCode:57344},h=new Set;o.forEach((_,A)=>{let R=l.length;Array.from(_.childNodes).forEach(k=>{l=Dd(k,l,s,u,f,d,p,m)}),l=Br(l,A,o.length);let O=l.length,P=Xe(_,M,"pPr"),C=_.parentNode;C&&h.add(C),c.push({start:R,end:O,pPr:P,container:C||i})});let g="";for(let _=0;_<l.length;_++){let A=l[_];g+=m.has(A)?`
154
+ `:A}let v=Ld(g,t,u);v=Md(g,l,v,m),d.forEach((_,A)=>{let R=A.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");v=v.replace(new RegExp(R,"g"),_)}),v=Bd(l,v,f);let w=new Map;h.forEach(_=>{w.set(_,e.createDocumentFragment())}),i&&!w.has(i)&&w.set(i,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let y=new Map,x=new Set(c.map(_=>_.start)),b=bl(c),I=bl(s),N=_d(u);return{paragraphs:o,body:i||e,paragraphMap:c,paragraphStarts:x,propertyMap:s,sentinelMap:u,sentinelMapByStart:N,referenceMap:f,tokenToCharMap:d,containerFragments:w,replacementContainers:y,originalFullText:l,processedModifiedText:v,getParagraphInfo:_=>{let A=b.at(_);return A||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:i||e})},getRunProperties:_=>{let A=I.at(_);return A?{rPr:A.rPr,wrapper:A.wrapper}:{rPr:null}},getPropertySpanLength:(_,A)=>{let R=I.at(_);return R?Math.min(R.end-_,A):1},isParagraphStart:_=>x.has(_)}}function Ta(e,t){let r=qe(e);if(r.length===0)return[];let n=El(t),a=r.map(kd);if(!n){let i=a.findIndex(l=>l==="");return i>=0?[r[i]]:null}if(r.length===1&&a[0]==="")return r;let o=[i=>i,i=>i.trim(),i=>i.replace(/\s+/g," ").trim()];for(let i of o){let l=i(n);for(let s=0;s<r.length;s++){let c="";for(let u=s;u<r.length;u++)if(c+=(u===s?"":`
155
+ `)+a[u],i(c)===l)return r.slice(s,u+1)}}return null}function El(e){return String(e??"").replace(/\r\n?/g,`
156
+ `).replace(/\u00a0/g," ")}function kd(e){let t="",r=n=>{for(let a of Array.from(n?.childNodes||[]))a.nodeType===1&&(B(a,"pPr")||B(a,"del")||B(a,"moveFrom")||(B(a,"t")?t+=a.textContent||"":B(a,"tab")?t+=" ":B(a,"br")||B(a,"cr")?t+=`
157
+ `:B(a,"noBreakHyphen")?t+="\u2011":r(a)))};return r(e),El(t)}function Md(e,t,r,n){if(n.size===0)return r;let a=Il.diff_main(e,r),o=0,i="";for(let[l,s]of a)if(l===0){for(let c=0;c<s.length;c++){let u=t[o+c];i+=n.has(u)?u:s[c]}o+=s.length}else l===-1?o+=s.length:i+=s;return i}function Ld(e,t,r){let n=new Map;if(r.forEach(f=>{f.zeroWidth&&n.set(f.start,f)}),n.size===0)return t;let a="",o=0,i=new Map;for(let f=0;f<e.length;f++){let d=n.get(f);if(d){i.has(o)||i.set(o,[]),i.get(o).push({char:e[f],affinity:d.affinity||"right",emitted:!1});continue}a+=e[f],o++}let l=Il.diff_main(a,t),s=0,c="",u=(f,d)=>{let m=i.get(f)||[];for(let p of m)p.emitted||d&&p.affinity!==d||(c+=p.char,p.emitted=!0)};for(let[f,d]of l){if(f===1){u(s,"left"),c+=d;continue}for(let m=0;m<d.length;m++)u(s),f===0&&(c+=d[m]),s++}return u(s),c}function Bd(e,t,r){let n=t;for(let a of r.keys()){if(n.includes(a))continue;let o=e.indexOf(a);if(o<0)continue;let i=e.slice(0,o),l=e.slice(o+a.length);if(i&&n.startsWith(i)){n=`${n.slice(0,i.length)}${a}${n.slice(i.length)}`;continue}if(l&&n.endsWith(l)){let s=n.length-l.length;n=`${n.slice(0,s)}${a}${n.slice(s)}`}}return n}function Dd(e,t,r,n,a,o,i,l){return B(e,"r")?Fd(e,t,r,n,a,o,i,l):B(e,"hyperlink")?$d(e,t,r):B(e,"sdt")||B(e,"oMath")||Tl(e)==="oMath"||B(e,"bookmarkStart")||B(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((B(e,"commentRangeStart")||B(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function Fd(e,t,r,n,a,o,i,l){let s=t,c=Xe(e,M,"rPr");return Array.from(e.childNodes).forEach(u=>{if(B(u,"t")){let f=u.textContent||"";f.length>0&&(r.push({start:s.length,end:s.length+f.length,rPr:c}),s+=f)}else if(B(u,"br")||B(u,"cr")){let f=String.fromCharCode(i.nextCharCode++);a.set(f,u),l.add(f),s+=f,r.push({start:s.length-1,end:s.length,rPr:c})}else if(B(u,"tab"))s+=" ",r.push({start:s.length-1,end:s.length,rPr:c});else if(B(u,"noBreakHyphen"))s+="\u2011",r.push({start:s.length-1,end:s.length,rPr:c});else if(["drawing","pict","object","fldChar","instrText","sym"].some(f=>B(u,f))){let f=Xe(u,M,"txbxContent"),d=B(u,"pict")&&!!f,m=B(u,"fldChar")||B(u,"instrText"),p=B(u,"fldChar")?u.getAttributeNS?.(M,"fldCharType")||u.getAttribute("w:fldCharType")||u.getAttribute("fldCharType"):null;n.push({start:s.length,node:u,wrapInRun:!0,rPr:c,zeroWidth:m,affinity:p==="end"?"left":"right",isTextBox:d,originalContainer:d?f:void 0}),s+="\uFFFC",r.push({start:s.length-1,end:s.length,rPr:c})}else if(B(u,"footnoteReference")||B(u,"endnoteReference")){let f=Od(u,"id");if(f){let m=`{{__${B(u,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(i.nextCharCode++);a.set(p,u),o.set(m,p),s+=p,r.push({start:s.length-1,end:s.length,rPr:c})}}else B(u,"commentReference")&&n.push({start:s.length,node:u,isCommentMarker:!0})}),s}function $d(e,t,r){let n=t;return Array.from(e.childNodes).forEach(a=>{if(!B(a,"r"))return;let o=Xe(a,M,"rPr");ze(a,M,"t").forEach(l=>{let s=l.textContent||"";s.length!==0&&(r.push({start:n.length,end:n.length+s.length,rPr:o,wrapper:e}),n+=s)})}),n}function Rl(e,t,r,n,a,o,i=!0,l={}){let{paragraphs:s,containerFragments:c,sentinelMapByStart:u,referenceMap:f,replacementContainers:d,getParagraphInfo:m,getRunProperties:p,getPropertySpanLength:h,isParagraphStart:g}=r,v=C=>{let k=L(e,"w:p");if(C){let D=C.cloneNode(!0),z=Xe(D,M,"sectPr");z&&D.removeChild(z),k.appendChild(D)}return k},w=m(0),y=v(w.pPr),x=c.get(w.container);x&&x.appendChild(y);let b=0,I=0,N=l?.pairReplacements===!0,T=null,S=null,E=new WeakSet;for(let C=0;C<t.length;C++){let[k,D]=t[C];if(k===0||k===-1){let z=k===0?"equal":"delete";if(k===0)T=null,S=null;else if(T===null){T=b;let G=!1;for(let Z=C+1;Z<t.length;Z++){if(t[Z][0]===1){G=!0;break}if(t[Z][0]===0)break}N&&i&&G&&(S=hn(a,e))}let H=0;for(;H<D.length;){let G=b+H,Z=p(G),pe=h(G,D.length-H),ue=D.substring(H,H+pe);y=Al(e,ue,z,Z.rPr,Z.wrapper,G,y,c,u,f,d,m,v,a,o,I,i,E,S).currentParagraph,k===0&&(I+=pe),H+=pe}b+=D.length;continue}if(k===1){let z=T!==null?T:b>0&&!g(b)?b-1:b,H=p(z);y=Al(e,D,"insert",H.rPr,H.wrapper,b,y,c,u,f,d,m,v,a,o,I,i,E,S,T!==null).currentParagraph,I+=D.length,T=null,S=null}}i&&c.forEach(C=>{Array.from(C.childNodes).forEach(k=>{if(B(k,"p")){let D=Array.from(k.getElementsByTagNameNS(M,"t")).length>0,z=Array.from(k.getElementsByTagNameNS(M,"delText")).length>0;s.length===1&&!D&&(z||r.originalFullText.trim()!=="")&&gr(e,k,a)}})}),c.forEach(C=>{let k=Array.from(C.childNodes).filter(D=>B(D,"p"));if(k.length>1){let D=k[0],z=k[k.length-1],H=Xe(D,M,"pPr"),G=H?Xe(H,M,"sectPr"):null;if(G){H.removeChild(G);let Z=Xe(z,M,"pPr");Z||(Z=L(e,"w:pPr"),z.insertBefore(Z,z.firstChild||null)),Z.appendChild(G)}}});let _=new Set(s),A=new Map;s.forEach(C=>{let k=C.parentNode;if(!k||A.has(k))return;let D=C.nextSibling;for(;D&&_.has(D);)D=D.nextSibling;A.set(k,D)}),s.forEach(C=>{C.parentNode&&C.parentNode.removeChild(C)});let R=!1,O="";return c.forEach((C,k)=>{let D=d.get(k),z=D||k;if(z.nodeType===9){R=!0,C.childNodes.length===1?z.appendChild(C.firstChild):O=Array.from(C.childNodes).map(G=>n.serializeToString(G)).join("");return}let H=D?null:A.get(k);H&&H.parentNode===z?z.insertBefore(C,H):z.appendChild(C)}),{oxml:R&&O?O:n.serializeToString(e),hasChanges:!0}}function Al(e,t,r,n,a,o,i,l,s,c,u,f,d,m,p=[],h=0,g=!0,v=new WeakSet,w=null,y=!1){let x=o,b=h,I=i,N=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(S=>{let E=s.get(x)||[],_=E.filter(O=>O.isCommentMarker&&!v.has(O.node)),A=y?new Set(_.filter(O=>B(O.node,"commentRangeEnd")).map(O=>O.node.getAttributeNS?.(M,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id"))):new Set;if(_.forEach(O=>{v.add(O.node);let P=O.node.getAttributeNS?.(M,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id");if(y&&A.has(P)&&(B(O.node,"commentRangeEnd")||B(O.node,"commentReference"))){N.push(O.node);return}if(B(O.node,"commentReference")){let C=L(e,"w:r");C.appendChild(O.node.cloneNode(!0)),I.appendChild(C)}else I.appendChild(O.node.cloneNode(!0))}),S===`
158
+ `){let O=f(x+1),P=d(O.pPr);g&&r==="insert"?zr(e,I,m):g&&r==="delete"&&gr(e,I,m);let C=l.get(O.container);C&&(C.appendChild(P),I=P),x++,r!=="delete"&&b++;return}if(S==="\uFFFC"){let O=E.find(P=>!P.isCommentMarker)||E[0];if(O){let P=O.node.cloneNode(!0);if(O.isTextBox&&O.originalContainer){let C=Xe(P,M,"txbxContent");if(C){for(;C.firstChild;)C.removeChild(C.firstChild);u.set(O.originalContainer,C)}}if(O.wrapInRun){let C=L(e,"w:r");O.rPr&&C.appendChild(O.rPr.cloneNode(!0)),C.appendChild(P),I.appendChild(C)}else I.appendChild(P)}x++,r!=="delete"&&b++;return}if(c.has(S)){if(r!=="delete"){let O=c.get(S);if(O){let P=O.cloneNode(!0),C=L(e,"w:r");n&&C.appendChild(n.cloneNode(!0)),C.appendChild(P),I.appendChild(C)}}x++,r!=="delete"&&b++;return}if(S.length===0)return;let R=I;if(a){let O=a.cloneNode(!1);R=O,I.appendChild(O)}if(r==="delete"){let O=L(e,"w:r");n&&O.appendChild(n.cloneNode(!0));let P=L(e,"w:delText");if(P.setAttribute("xml:space","preserve"),P.textContent=S,O.appendChild(P),g){let C=null;if(w){let D=w.usedDeletionId?ae(m,e,"del").id:w.deletionId;w.usedDeletionId=!0,C={id:D,author:w.author,date:w.date}}let k=pr(e,"del",O,m,C);R.appendChild(k)}}else{let O=Ot(p,b,b+S.length),P=wa(e,S,n,O,b,m,g);if(r==="insert"&&g){let C=null;if(w){let D=w.usedInsertionId?ae(m,e,"ins").id:w.insertionId;w.usedInsertionId=!0,C={id:D,author:w.author,date:w.date}}let k=pr(e,"ins",null,m,C);P.forEach(D=>k.appendChild(D)),R.appendChild(k)}else P.forEach(C=>R.appendChild(C))}r!=="delete"&&(b+=S.length),x+=S.length}),N.forEach(S=>{if(B(S,"commentReference")){let E=L(e,"w:r");E.appendChild(S.cloneNode(!0)),I.appendChild(E)}else I.appendChild(S.cloneNode(!0))}),{currentParagraph:I}}function Ko(e,t,r,n,a,o,i=!0,l={},s={}){let c=Ta(e,t);if(c===null)return we({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PARTIAL_TARGET",message:"Original text did not identify a complete contiguous paragraph range for reconstruction."}});let u=Sl(e,r,c);if(u.paragraphs.length===0)return we({oxml:n.serializeToString(e),hasChanges:!1});let f=yn(u.originalFullText,u.processedModifiedText,l);return we(Rl(e,f,u,n,a,o,i,s))}function ht(e,t){return we({oxml:e.serializeToString(t),hasChanges:!1})}function Pl(e,t,r,n,a,o=!0){let i=ze(e,M,"tbl"),l=et(t),s=l.rows.length>0||l.headers.length>0;if(i.length===0||!s)return ht(r,e);let c=i[0],u=Ao(c),f=Bs(u,l);if(f.length===0)return ht(r,e);let d={generateRedlines:o,author:a,revisionIdAllocator:_t(e)},m=Ds(u,f,d),p=`<root xmlns:w="${M}">${m}</root>`,h=j(p,"application/xml").doc;if(!h)return ht(r,e);let g=Ne(h);if(g)return ye("[OxmlEngine] Failed to parse reconciled table OOXML:",g.textContent),ht(r,e);let v=Xe(h,M,"tbl");if(!v)return ye("[OxmlEngine] No table found in reconciled OOXML"),ht(r,e);let w=e.importNode(v,!0);return c.parentNode.replaceChild(w,c),we({oxml:r.serializeToString(e),hasChanges:!0})}function Cl(e,t,r,n,a,o){let i=_t(e),l=et(t);if(!l||l.rows.length===0&&l.headers.length===0)return V("[OxmlEngine] Failed to parse table data from Markdown"),ht(r,e);let s=fr(l,{generateRedlines:o,author:a,revisionIdAllocator:i}),c=j(`<root xmlns:w="${M}">${s}</root>`,"application/xml").doc;if(!c)return ht(r,e);let u=Ne(c);if(u)return ye("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),ht(r,e);let f=be(c,M,"tbl");if(f||(f=be(c,M,"ins")),!f)return ye("[OxmlEngine] No table element found in generated OOXML"),ht(r,e);let d=e,m=Pe(d,M,"p");if(m.length===0)return V("[OxmlEngine] No paragraphs found to replace"),ht(r,d);let p=m[0],h=p.parentNode;if(h&&h.nodeType===9){let v=j(`<w:document xmlns:w="${M}"><w:body/></w:document>`,"application/xml").doc;if(!v)return ht(r,d);let w=be(v,M,"body");m.forEach(y=>w.appendChild(v.importNode(y,!0))),d=v,Kt(d,i),m=Pe(d,M,"p"),p=m[0],h=p.parentNode}let g=d.importNode(f,!0);return o?m.forEach(v=>{gr(d,v,a),Pe(v,M,"r").forEach(y=>{Pe(y,M,"t").forEach(N=>{let T=N.textContent||"";if(T.trim()){let S=L(d,"w:delText");S.textContent=T,N.parentNode.replaceChild(S,N)}});let b=L(d,"w:del"),I=ae(a,d,"del");b.setAttribute("w:id",String(I.id)),b.setAttribute("w:author",I.author),b.setAttribute("w:date",I.date),y.parentNode.insertBefore(b,y),b.appendChild(y)})}):m.slice(1).forEach(v=>v.parentNode.removeChild(v)),h.insertBefore(g,p),o||h.removeChild(p),V("[OxmlEngine] Text-to-table transformation complete"),we({oxml:r.serializeToString(d),hasChanges:!0})}function Bt(e,t){if(!e||!e.attributes)return"";for(let r of Array.from(e.attributes))if((r.localName||"").toLowerCase()===t.toLowerCase())return String(r.value||"");return String(e.getAttribute?.(`w:${t}`)||e.getAttribute?.(t)||"")}function Sa(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ud(e){return!!e&&e.nodeType===1}function wt(e,t){return Ud(e)&&e.namespaceURI===M&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function De(e,t){return Array.from(e.getElementsByTagNameNS(M,t))}function Ho(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Sa(e?.author);return t?{valid:!0,allAuthors:!1,normalizedAuthor:t}:{valid:!1,allAuthors:!1,normalizedAuthor:"",warning:"No author provided. Pass { author } or set { allAuthors: true }."}}function tt(e,t){if(t.allAuthors)return!0;let r=Sa(Bt(e,"author"));return!!r&&r===t.normalizedAuthor}function Go(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,a=j(r,"application/xml");if(a.error&&(a.error.message.includes("HierarchyRequestError")||a.error.message.includes("Only one element"))){let i=`<w:body xmlns:w="${M}">${r}</w:body>`,l=j(i,"application/xml");l.error||(a=l,n=!0)}let o=a.doc?Ne(a.doc):null;if(a.error||o){let i=a.error?.message||o?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${i}`,warnings:a.warnings,error:{code:"PARSE_ERROR",message:i}}}return{xmlDoc:a.doc,serializer:ce(),isFragmentWrapped:n,warning:null,warnings:a.warnings,error:null}}function Oe(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Ea(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function Ol(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function _l(e){return Array.from(e?.attributes||[]).filter(t=>String(t.localName||t.name||"").toLowerCase()!=="id").map(t=>`${t.namespaceURI||""}|${t.localName||t.name}=${t.value}`).sort().join(`
159
+ `)}function zd(e){let t=0,r=De(e,"ins");for(let n of r){if(!n.parentNode||Ra(n))continue;let a=Ol(n);for(;wt(a,"ins")&&Sa(Bt(a,"author"))===Sa(Bt(n,"author"))&&_l(a)===_l(n);){let o=Ol(a);for(;a.firstChild;)n.appendChild(a.firstChild);a.parentNode?.removeChild(a),t+=1,a=o}}return t}function Aa(e){let t=e?.parentNode;return wt(t,"trPr")&&wt(t?.parentNode,"tr")}function Ra(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return wt(t,"rPr")&&wt(r,"pPr")&&wt(n,"p")}function Ll(e){return Ra(e)?e.parentNode.parentNode.parentNode:null}function Xd(e){let t=e?.nextSibling||null;for(;t;){if(wt(t,"p"))return t;t=t.nextSibling}return null}function Bl(e){if(!e?.parentNode)return!1;let t=Xd(e);if(!t)return wt(e.parentNode,"tc")&&De(e.parentNode,"p").length<=1?!1:Oe(e);let r=Array.from(e.childNodes||[]).filter(a=>!wt(a,"pPr")),n=t.firstChild||null;wt(n,"pPr")&&(n=n.nextSibling||null);for(let a of r)t.insertBefore(a,n);return Oe(e)}function yr(e,t={}){let r=[],n=Ho(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let a=Go(e,"Failed to parse OOXML");if(!a.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:a.error,warnings:[...a.warnings||[],a.warning]};let{xmlDoc:o,serializer:i}=a;r.push(...a.warnings||[]);let l=0;for(let u of De(o,"ins"))if(!(!u.parentNode||!tt(u,n))){if(Ra(u)){Oe(u)&&(l+=1);continue}if(Aa(u)){Oe(u)&&(l+=1);continue}Ea(u)&&(l+=1)}for(let u of De(o,"del")){if(!u.parentNode||!tt(u,n))continue;let f=Ll(u);if(f){Bl(f)&&(l+=1);continue}if(Aa(u)){let d=u.parentNode?.parentNode;Oe(d)&&(l+=1);continue}Oe(u)&&(l+=1)}for(let u of De(o,"moveFrom"))!u.parentNode||!tt(u,n)||Oe(u)&&(l+=1);for(let u of De(o,"moveTo"))!u.parentNode||!tt(u,n)||Ea(u)&&(l+=1);l+=Dl(o,n);let s=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of s)for(let f of De(o,u))!f.parentNode||!tt(f,n)||Oe(f)&&(l+=1);return{oxml:a.isFragmentWrapped?Array.from(o.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(o),hasChanges:l>0,acceptedCount:l,warnings:r}}function kl(e,t){for(let r of Array.from(t.getElementsByTagNameNS(M,"delText"))){let n=L(e,"w:t"),a=r.getAttribute("xml:space");for(a&&n.setAttribute("xml:space",a);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function Vd(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==M)return Oe(e);let a=Array.from(e.childNodes||[]).find(i=>i.nodeType===1&&i.namespaceURI===M&&String(i.localName||"").toLowerCase()===n.toLowerCase());if(!a)return Oe(e);let o=Array.from(a.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let i of o){let l=Wd(r.ownerDocument,i);r.appendChild(l)}return!0}function Wd(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function Ml(e,t,r){let n=new Set;for(let a of De(e,t)){if(!tt(a,r))continue;let o=Bt(a,"id");o&&n.add(o)}return n}function Dl(e,t){let r=0,n=Ml(e,"moveFromRangeStart",t),a=Ml(e,"moveToRangeStart",t),o=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",a,!0],["moveToRangeEnd",a,!1]];for(let[i,l,s]of o)for(let c of De(e,i)){if(!c.parentNode)continue;let u=Bt(c,"id");u&&(t.allAuthors||l.has(u)||s&&tt(c,t))&&Oe(c)&&(r+=1)}return r}function tr(e,t={}){let r=[],n=Ho(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let a=Go(e,"Failed to parse OOXML");if(!a.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:a.error,warnings:[...a.warnings||[],a.warning]};let{xmlDoc:o,serializer:i}=a;r.push(...a.warnings||[]);let l=0;for(let u of De(o,"ins")){if(!u.parentNode||!tt(u,n))continue;let f=Ll(u);if(f){Bl(f)&&(l+=1);continue}if(Aa(u)){let d=u.parentNode?.parentNode;Oe(d)&&(l+=1);continue}Oe(u)&&(l+=1)}for(let u of De(o,"del"))if(!(!u.parentNode||!tt(u,n))){if(Ra(u)){Oe(u)&&(l+=1);continue}if(Aa(u)){Oe(u)&&(l+=1);continue}kl(o,u),Ea(u)&&(l+=1)}for(let u of De(o,"moveFrom"))!u.parentNode||!tt(u,n)||(kl(o,u),Ea(u)&&(l+=1));for(let u of De(o,"moveTo"))!u.parentNode||!tt(u,n)||Oe(u)&&(l+=1);l+=Dl(o,n);let s=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of s)for(let f of De(o,u))!f.parentNode||!tt(f,n)||Vd(f,u)&&(l+=1);return zd(o),{oxml:a.isFragmentWrapped?Array.from(o.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(o),hasChanges:l>0,rejectedCount:l,warnings:r}}function jd(e,t){let r=new Set,n=De(e,"comment");for(let a of n){if(!tt(a,t))continue;let o=Bt(a,"id");o&&r.add(o)}return{targetIds:r,commentNodes:n}}function Kd(e,t){let r=0;for(let n of e){let a=Bt(n,"id");!a||!t.has(a)||Oe(n)&&(r+=1)}return r}function Hd(e){return wt(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==M)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Gd(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let a of n)for(let o of De(e,a)){if(!o.parentNode)continue;let i=Bt(o,"id");if(!(!i||!t.has(i))){if(a==="commentReference"&&Hd(o.parentNode)){Oe(o.parentNode)&&(r+=1);continue}Oe(o)&&(r+=1)}}return r}function qo(e,t={}){let r=[],n=Ho(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let a=Go(e,"Failed to parse OOXML");if(!a.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:a.error,warnings:[...a.warnings||[],a.warning]};let{xmlDoc:o,serializer:i}=a;r.push(...a.warnings||[]);let{targetIds:l,commentNodes:s}=jd(o,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of De(o,f)){let m=Bt(d,"id");m&&l.add(m)}let c=Kd(s,l),u=Gd(o,l);return{oxml:i.serializeToString(o),hasChanges:c>0||u>0,commentsRemoved:c,referencesRemoved:u,warnings:r}}var qd=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function Dt(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:qd[t]||null,...r}))}var Yd=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function Fe(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function An(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function xr(e,t){return An(e).find(r=>Fe(r)===t)||null}function Pa(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Ca(e){return String(e||"").trim().toLowerCase()}function Zd(e){return Fe(e)!=="r"?!1:An(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Fe(t)))}function Yo(e){return Yd.has(Fe(e))||Zd(e)}function Zo(e){return Fe(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Fe(e))?An(e).filter(r=>!Yo(r)&&Fe(r)!=="sdtPr").every(Zo):!1}function Jd(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let a=Fe(n),o=Pa(n,"id");a==="moveFromRangeStart"&&o!==""&&r.add(o),a==="moveFromRangeEnd"&&o!==""&&r.delete(o)}return!1}function Fl(e){let t=xr(e,"pPr"),r=xr(t,"rPr");return xr(r,"del")}function Qd(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=Fe(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,a=!1;for(;n&&n!==e;){let o=Fe(n);if(o==="del"||o==="moveFrom"){a=!0;break}n=n.parentNode}if(!a&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function rr(e,t){let r=Fl(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=Pa(r,"author")||null,a=!n||Ca(n)!==Ca(t),i=An(e).filter(l=>!Yo(l)).every(Zo);return{matches:a&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:a,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function br(e,t={}){let r=xr(e,"pPr");if(xr(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(Fe(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(Jd(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(Fe(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let a=e?.parentNode||null;for(;a&&Fe(a)!=="tr";)a=a.parentNode;let o=xr(a,"trPr");if(o&&xr(o,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||Fe(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function $l(e){let t=Fe(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Fe(n)==="p"),r=[];for(let n of t){let a=Fl(n);if(!a)continue;let o=Pa(a,"author")||null,i=An(n).filter(c=>!Yo(c)),l=i.filter(c=>Fe(c)!=="ins"||!Qd(c)?!1:Ca(Pa(c,"author"))!==Ca(o)),s=i.every(c=>Zo(c)||l.includes(c));l.length>0&&s&&r.push({paragraph:n,markDeletion:a,ownerAuthor:o,foreignInsertions:l})}return r}function em(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of ze(e,M,r)){let a=n.getAttribute?.("w:id")||n.getAttribute?.("id");a!==""&&t.add(a)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Nr(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===M&&r.localName===t)||null}function tm(e,t){let r=Nr(Nr(Nr(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(M,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(M,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(M,"date")||""}}function rm(e,t){let r=e.cloneNode(!1),n=Nr(e,"pPr");return n&&r.appendChild(lt(n)),t.serializeToString(r)}function nm(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=j(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:qe(r.doc)[0];if(!n)return e;let a=Nr(n,"pPr");a||(a=L(r.doc,"w:pPr"),n.insertBefore(a,n.firstChild));let o=Nr(a,"rPr");if(o||(o=L(r.doc,"w:rPr"),a.appendChild(o)),!Nr(o,"ins")){let i=L(r.doc,"w:ins");t.id&&i.setAttribute("w:id",t.id),i.setAttribute("w:author",t.author),t.date&&i.setAttribute("w:date",t.date),o.appendChild(i)}return xe(r.doc)}async function Rn(e,t,r,n={}){let a=e,o=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,l=n.author||re(),s=ce(),c=[],u=[],f=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",h=X=>{let U={...X};f&&U.hasChanges===!1&&U.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(U.oxml=o,U.hasChanges=!0,U.warnings=[...Array.isArray(U.warnings)?U.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(U.oxml=o,U.hasChanges=!0,U.warnings=[...Array.isArray(U.warnings)?U.warnings:[],"Existing revisions were accepted before redlining."]):U.oxml=a);let $=[...c,...u,...Array.isArray(U.warnings)?U.warnings:[]];return $.length>0&&(U.warnings=[...new Set($)]),U.status||(U.status=U.hasChanges?"ok":"no-op"),d&&U.hasChanges&&typeof U.oxml=="string"&&(U.oxml=nm(U.oxml,d)),we(U)},g=()=>h(f&&p?{oxml:o,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:a,hasChanges:!1}),v=j(a,"text/xml");c=v.warnings;let w=v.doc,y=w?Ne(w):null;if(v.error||y){let X=v.error?.message||y?.textContent||"Could not parse OOXML input.";return ye("[OxmlEngine] XML parse error:",X),h({oxml:a,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:X}})}let x=n?._revisionIdAllocator instanceof Se?n._revisionIdAllocator:new Se;kt(w,x);let b=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:qe(w);if(b.length===1&&r.length>0){let X=rr(b[0],l);if(X.matches){let U=X.ownerAuthor||"unattributed";return h({oxml:a,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${U}). Use explicit paragraph restoration when supported.`,ownerAuthor:U}})}}if(Yt(w))if(m==="merge-same-author"||m==="slice-cross-author"){let X=dr(w),U=String(l||"").trim().toLowerCase();if(X.length>0&&X.every(K=>K.trim().toLowerCase()===U)){let K=em(w);if(K.length>0)return h({oxml:a,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:K}});V("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let ee=b.length===1?b[0]:null;d=tm(ee,l);let je=tr(a,{author:l});if(je.status==="error")return h(je);o=d&&!String(je.oxml||"").trim()?rm(ee,s):je.oxml,f=!0;let Qe=j(o,"text/xml");c.push(...Qe.warnings),w=Qe.doc;let oa=w?Ne(w):null;if(Qe.error||oa){let ia=Qe.error?.message||oa?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return ye("[OxmlEngine] XML parse error after rejecting same-author revisions:",ia),h({oxml:a,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:ia}})}if(Yt(w))return h({oxml:a,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});kt(w,x);let Zi=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:qe(w);t=Zi.length>0?Zi.map(ia=>te(ia)).join(`
160
+ `):""}else{if(m==="merge-same-author")return V("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),h({oxml:a,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${X.length?X.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:X,currentPolicy:m}});if(["moveFrom","moveTo"].some(ee=>ze(w,M,ee).length>0))return h({oxml:a,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});V("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){V("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let X=yr(a,{allAuthors:!0});if(X.status==="error")return h(X);o=X.oxml,f=!0;let U=j(o,"text/xml");c.push(...U.warnings),w=U.doc;let $=w?Ne(w):null;if(U.error||$){let K=U.error?.message||$?.textContent||"Could not parse OOXML after accepting existing revisions.";return ye("[OxmlEngine] XML parse error after accepting existing revisions:",K),h({oxml:a,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:K}})}kt(w,x)}else return V("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),h({oxml:a,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let I=fl(w,t,n);if(I.hasTableWrapper&&I.targetParagraph&&!n._isolatedTableCell){V("[OxmlEngine] Isolating table-cell paragraph before diff");let X=In(w,I.targetParagraph,s),U=await Rn(X,t,r,{...n,_isolatedTableCell:!0});return!U.hasChanges&&U.status==="no-op"?g():U}let N=n.sanitizeInput===!0?Jo(r):r;N!==r&&u.push("Input was sanitized; pass sanitizeInput: false to disable.");let T=null;if(n.structuredContent!==!1)if(T=ha(N),T.valid)T.requiresStructuredContent&&(N=T.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let X=T.issues.map(U=>`${U.code}: ${U.message}`).join(" ");return h({oxml:a,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:X},warnings:T.issues.map(U=>U.message)})}T=null}let{cleanText:S,formatHints:E}=Ge(N),_=m==="slice-cross-author"?S!==t:S.trim()!==t.trim(),A=E.length>0,{existingFormatHints:R,textSpans:O,paragraphs:P}=el(w),C=R.length>0,k=O.map(X=>Ul(X)).join(""),D=t.includes(`
161
+ `)||t.includes("\r")?t.split(/\r?\n/).map(Oa).filter(Boolean).every(X=>P.some(U=>{let $=O.filter(K=>K.paragraph===U).map(Ul).join("");return Oa($).includes(X)})):k.includes(t.trim())||k.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Oa(k).includes(Oa(t));if(_&&typeof t=="string"&&t.trim()&&!D)return V("[OxmlEngine] Target text not found in OOXML"),h({oxml:a,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let z=null,H=()=>(z||(z=va(w,P,O)),z),G=(X=null)=>{let U=ul(w,t,E,s,l,i,X);return U.useNativeApi?(V("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),Ko(w,t,S,s,l,E,i)):U};V(`[OxmlEngine] Text changes: ${_}, New format hints: ${E.length}, Existing format hints: ${R.length}`);let Z=n.removeFormatting===!0&&!_&&!A&&C;if(!_&&!A&&!C)return Dt(n,"noChange"),V("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),g();if(!_&&!A&&C&&!Z)return V("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),g();if(Z){Dt(n,"formatOnly",{removeFormatting:!0}),V("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let X=I,U=X.targetParagraph||null;if(!U){let ee=ol(H(),t);ee&&(U=ee.paragraph)}let $=R;U&&($=R.filter(ee=>sl(ee.run)===U));let K=cl(w,O,$,s,l,i);return X.hasTableWrapper&&U?h({oxml:In(w,U,s),hasChanges:K.hasChanges}):h(K)}if(!_&&A){Dt(n,"formatOnly",{removeFormatting:!1}),V(`[OxmlEngine] Format-only change detected: ${E.length} format hints`);let X=I,U={textSpans:O,paragraphs:P,paragraphInfos:H()};if(X.hasTableWrapper&&X.targetParagraph){V("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let $=G(U);return V("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),h({oxml:In(w,X.targetParagraph,s),hasChanges:$.hasChanges})}return h(G(U))}let ue=ze(w,M,"tbl").length>0,W=/^\|.+\|/.test(S.trim())&&S.includes(`
162
+ `),J=dn(S),Re=n.structuredContent!==!1&&T?.requiresStructuredContent===!0,le=I,ge=ue||m==="slice-cross-author";V(`[OxmlEngine] Mode: ${ge?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${E.length}, isMarkdownTable: ${W}, isTargetList: ${J}, isTableCellParagraph: ${le.isTableCellParagraph}`);try{if(W&&!ue)return Dt(n,"table",{transformation:"text-to-table"}),V("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),h(Cl(w,S,s,null,l,i));if(ue&&W)return Dt(n,"table",{transformation:"table-reconciliation"}),h(Pl(w,S,s,null,l,i));if(ge){Dt(n,"surgical",{tableScoped:ue});let X=le.hasTableWrapper&&le.targetParagraph?le.targetParagraph:null;X&&V("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let U=xl(w,t,S,s,l,E,i,X,{},n);return U.status==="error"&&U.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?h({...U,oxml:a,hasChanges:!1}):le.hasTableWrapper&&U.hasChanges&&le.targetParagraph?(V("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),h({oxml:In(w,le.targetParagraph,s),hasChanges:!0})):h(U)}if(J||Re){let X=ze(w,M,"p"),U=X.length===1;Dt(n,U?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:X.length}),V(`[OxmlEngine] \u{1F3AF} Using ${U?"direct list generation":"compatibility pipeline"} for list reconciliation`);let $;if(U){let K=Fr(o,{xmlDoc:w}),ee=vn(X[0]);$=await Ur({cleanText:S,numberingContext:ee,originalRunModel:K.runModel,originalText:K.acceptedText,generateRedlines:i,author:l,font:n.font||null,revisionIdAllocator:x,numberingService:new Mt})}else $=await new xn({author:l,generateRedlines:i,revisionIdAllocator:x}).execute(o,N,{xmlDoc:w});if($.error?.code==="DIFF_TOKEN_LIMIT")return h({oxml:a,hasChanges:!1,status:"error",error:$.error});if($.isValid&&$.ooxml&&$.ooxml!==o){let K=$.includeNumbering===!0;V(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${K}`);let ee=qt($.ooxml,{includeNumbering:K,numberingXml:$.numberingXml});return V(`[OxmlEngine] \u2705 Wrapped OOXML length: ${ee.length}`),h({oxml:ee,hasChanges:!0,...Array.isArray($.warnings)?{warnings:$.warnings}:{}})}return g()}return Dt(n,"reconstruction"),h(Ko(w,t,S,s,l,E,i,{},n))}catch(X){if(Ns(X))return h({oxml:a,hasChanges:!1,status:"error",error:{code:X.code,message:X.message}});throw X}}function Oa(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function Ul(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
163
+ `:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function Jo(e){return String(e??"").replace(/^(?:Here is the redline:|Here is the text:|Sure, I can help:|Here's the updated text:)[ \t]*\r?\n/i,"")}function Ft(e){return j(e,"application/xml").doc}function Ir(e){return xe(e)}function _a(e){return Array.from(e||[])}function Pn(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Ke(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Ae="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function zl(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=_a(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=_a(e.getElementsByTagName(`w:${t}`));return r.length>0?r:_a(e.getElementsByTagName(t))}function ve(e){return e?te(e):""}function oe(e){if(!e)return[];let t=zl(e,"body"),r=t.length>0?t[0]:e;return zl(r,"p")}function $e(e){return e&&_a(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function rt(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:te(e,{revisionView:r}),a=Number.isInteger(t.index)?t.index:oe(e.ownerDocument||e).indexOf(e)+1,o=t.paragraphId===void 0?$e(e):t.paragraphId,i=typeof t.inTable=="boolean"?t.inTable:On(e),s=`${o||""}${a}${i?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let u=0;u<s.length;u++)c^=s.charCodeAt(u),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function Pt(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=oe(e),a=[],o=new Map,i=new Map,l=new Map;for(let s=0;s<n.length;s++){let c=n[s],u=te(c,{revisionView:r}),f=$e(c),d=On(c),m=Y(u),p=Object.freeze({paragraph:c,index:s+1,paragraphId:f,text:u,normalizedText:m,revisionView:r,fingerprint:rt(c,{text:u,index:s+1,paragraphId:f,inTable:d,revisionView:r}),inTable:d});a.push(p),o.set(c,p),f&&!i.has(f)&&i.set(f,p),m&&(l.has(m)||l.set(m,[]),l.get(m).push(p))}for(let[s,c]of l)l.set(s,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(a),byParagraph:o,byId:i,byNormalizedText:l})}function Y(e){return String(e||"").replace(/\s+/g," ").trim()}function Tr(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
164
+ `)}function ei(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function am(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function om(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function Xl(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:oe(e)[t-1]||null}function Ve(e,t,r=Ae){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function ka(e,t,r={}){let n=r.paragraphMetadataIndex||null,a=n?.entries||null,o=a?null:oe(e),i=String(t||"").trim();if(!i)return null;let l=a?a.find(c=>c.text.trim()===i)?.paragraph:o.find(c=>ve(c).trim()===i);if(l)return l;let s=Y(i);return n?.byNormalizedText?n.byNormalizedText.get(s)?.[0]?.paragraph||null:o.find(c=>Y(ve(c))===s)||null}function Qo(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},a=r.paragraphMetadataIndex||null,o=a?.entries||null,i=o?null:oe(e),l=String(t||"").trim();if(!l)return null;let s=ka(e,l,{paragraphMetadataIndex:a});if(s)return s;let c=Y(l),u=o?o.find(g=>g.normalizedText.length>10&&c.startsWith(g.normalizedText))?.paragraph||null:i.find(g=>{let v=Y(ve(g));return v.length>10&&c.startsWith(v)});if(u)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ve(u).trim().slice(0,60)}..."`),u;let f=o?o.find(g=>g.normalizedText.length>15&&c.includes(g.normalizedText))?.paragraph||null:i.find(g=>{let v=Y(ve(g));return v.length>15&&c.includes(v)});if(f)return n(`[Fuzzy] Contains match: "${ve(f).trim().slice(0,60)}..."`),f;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(g=>g.length>2)),h=o?.length??i.length;for(let g=0;g<h;g++){let v=o?.[g]?.paragraph??i[g],w=(o?.[g]?.text??ve(v)).trim();if(!w)continue;let b=Y(w).toLowerCase().split(/\s+/).filter(I=>I.length>2).filter(I=>p.has(I)).length/Math.max(p.size,1);b>d&&b>.5&&(d=b,m=v)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${ve(m).trim().slice(0,60)}..."`),m):null}function Sr(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},a=t.opType||"operation",o=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=o?.revisionView==="rejected"?"rejected":"accepted",l=String(o?.exactText??o?.text??t.targetText??"").trim(),s=ei(o?.index??o?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,u=t.paragraphMetadataIndex||null;if(u&&u.revisionView!==i?u=t.metadataIndices?.[i]||Pt(e,{revisionView:i}):u||(u=Pt(e,{revisionView:i})),o?.paragraphId){let d=sm(e,o.paragraphId,u);if(!d)throw Ke("TARGET_NOT_FOUND",`Target paragraphId not found: "${o.paragraphId}".`);let m=u?.byParagraph?.get(d)||null,p=m?.index??oe(e).indexOf(d)+1,h=m?.fingerprint||rt(d,{revisionView:i}),g=m?.inTable??On(d),v=m?.normalizedText||Y(te(d,{revisionView:i}));if(s!=null&&s!==p)throw Ke("TARGET_INDEX_MISMATCH",`Target paragraphId "${o.paragraphId}" (index ${p}) does not match requested index ${s}.`,m?[vt(m)]:null);if(o.fingerprint&&o.fingerprint!==h){let w=i==="rejected"?"accepted":"rejected",y=rt(d,{revisionView:w}),x=o.fingerprint===y?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw Ke("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${o.paragraphId}" no longer matches its source fingerprint.${x}`,m?[vt(m)]:null)}if(typeof o.inTable=="boolean"&&o.inTable!==g)throw Ke("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${o.paragraphId}" does not match the requested table context.`,m?[vt(m)]:null);if(l&&v!==Y(l)){let w=i==="rejected"?"accepted":"rejected",x=Y(te(d,{revisionView:w}))===Y(l)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw Ke("TARGET_TEXT_MISMATCH",`Target paragraphId "${o.paragraphId}" no longer matches the supplied text.${x}`,m?[vt(m)]:null)}if(o.occurrence!=null){let y=Ma(e,l||v,u),x=y.findIndex(b=>b.paragraph===d)+1;if(x===0||x!==o.occurrence)throw Ke("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${o.paragraphId}" matches occurrence ${x}, not requested occurrence ${o.occurrence}.`,y.map(vt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(o?.fingerprint&&!l&&!s){let d=(u?.entries||[]).filter(m=>m.fingerprint===o.fingerprint);if(typeof o.inTable=="boolean"&&(d=d.filter(m=>m.inTable===o.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?Ke("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(vt)):Ke("TARGET_NOT_FOUND",`Target fingerprint not found: "${o.fingerprint}".`)}let f=[];if(l){let d=Ma(e,l,u);if(f=im(d,o),o?.fingerprint&&d.length>0&&f.length===0)throw Ke("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(vt));if(typeof o?.inTable=="boolean"&&d.length>0&&f.length===0)throw Ke("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(vt));if(o?.occurrence){let m=f[o.occurrence-1]||null;if(!m)throw Ke("TARGET_NOT_FOUND",`Target occurrence ${o.occurrence} was not found.`,f.map(vt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(s){let m=f.find(p=>p.index===s)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(o?.fingerprint&&f.length>0)throw Ke("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`,f.map(vt));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Ke("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(vt));if(f.length===0)throw Pn(`Target paragraph not found: "${l}"`)}if(!s&&f.length===1)return{paragraph:f[0].paragraph,resolvedBy:o?.fingerprint?"fingerprint":"strict_text"}}if(s){let d=Xl(e,s,u);if(d){let m=u?.byParagraph?.get(d)||null;if(o?.fingerprint&&o.fingerprint!==m?.fingerprint)throw Ke("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`);if(typeof o?.inTable=="boolean"&&o.inTable!==m?.inTable)throw Ke("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${s}] does not match requested table context.`);if(l){let p=ka(e,l,{paragraphMetadataIndex:u}),h=(m?.text||te(d,{revisionView:i})).trim(),g=Y(h),v=Y(l),w=g!==v;if(w&&p&&p!==d)return r(`[Target] [P${s}] drifted for ${a}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let y=Qo(e,l,{onInfo:r,paragraphMetadataIndex:u});if(y&&y!==d)return r(`[Target] [P${s}] drifted for ${a}; using fuzzy text rematch.`),{paragraph:y,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${s}] fallback for ${a}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${s}] disambiguated duplicate target text for ${a}.`)}else r(`[Target] Using [P${s}] fallback for ${a}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${s}] not found; falling back to text matching for ${a}.`)}if(l&&!c){let d=ka(e,l,{paragraphMetadataIndex:u});if(d){let p=f.length;if(p>1){let h=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(h),{paragraph:d,resolvedBy:"strict_text",warnings:[h]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=Qo(e,l,{onInfo:r,paragraphMetadataIndex:u});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw Pn(l?`Target paragraph not found: "${l}"`:s?`Target paragraph reference not found: [P${s}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function On(e){return!!Ve(e,"tbl")}function Ma(e,t,r=null){let n=Y(t);if(!n)return[];let a=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,o=r?.revisionView||a?.revisionView||"accepted";if(a?.byNormalizedText&&a.revisionView===o)return Array.from(a.byNormalizedText.get(n)||[]);let i=oe(e),l=[];for(let s=0;s<i.length;s++){let c=i[s],u=te(c,{revisionView:o}).trim();u&&Y(u)===n&&l.push({paragraph:c,index:s+1,inTable:On(c),paragraphId:$e(c),fingerprint:rt(c,{text:u,index:s+1,revisionView:o}),text:u,revisionView:o})}return l}function vt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function im(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function sm(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:oe(e).find(n=>$e(n)===t)||null:null}function lm(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let a=n.filter(o=>o.inTable===r);a.length>0&&(n=a)}return Number.isInteger(t)&&t>0&&n.sort((a,o)=>Math.abs(a.index-t)-Math.abs(o.index-t)),n[0]||null}function ti(e,t=null){let r=t?.entries||null,n=r?null:oe(e),a=new Map,o=r?.length??n.length;for(let i=0;i<o;i++){let l=r?.[i]?.paragraph??n[i],s=(r?.[i]?.text??ve(l)).trim();a.set(i+1,{text:s,normalizedText:r?.[i]?.normalizedText??Y(s),inTable:r?.[i]?.inTable??On(l)})}return a}function Cn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=Sr(e,t),a=ei(t.targetRef);if(!a||n?.resolvedBy!=="ref")return n;let o=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(a)||null;if(!o)return n;let i=String(t.targetText||"").trim(),l=i||o.text||"",s=Y(l);if(!s||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||Y(ve(n.paragraph)))===s)return n;let u=[];if(i&&u.push(i),o.text){let d=Y(o.text);d&&!u.some(m=>Y(m)===d)&&u.push(o.text)}let f=null;for(let d of u){let m=Ma(e,d,t.paragraphMetadataIndex||null),p=lm(m,a,o.inTable);if(p&&(f||(f=p),p.paragraph!==n.paragraph)){f=p;break}}if(f&&f.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${a}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:f.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw Pn(`Target paragraph [P${a}] no longer matches its batch-start anchor.`)}function jr(e,t,r,n={}){if(!e||!t||!r)return null;let a=n?.opType||"redline",o=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},l=typeof n?.onWarn=="function"?n.onWarn:()=>{},s=Cn(e,{targetRef:t,opType:a,targetRefSnapshot:o,onInfo:i,onWarn:l})?.paragraph;if(!s)return null;let c=Cn(e,{targetRef:r,opType:a,targetRefSnapshot:o,onInfo:i,onWarn:l})?.paragraph;if(!c)return null;let u=Array.from(e.getElementsByTagNameNS("*","p")),f=u.indexOf(s),d=u.indexOf(c);if(f<0||d<f)return null;let m=u.slice(f,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(h=>h&&h.parentNode===p)?null:m}function La(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",a=typeof t=="string"&&t.includes(`
165
+ `),o=r.targetEndParagraph||null,i=Ve(e,"tc");if(i){if(n&&Array.from(i.childNodes).filter(c=>B(c,"p")).length<=1)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete the sole terminal paragraph of a table cell."};if(o&&Ve(o,"tc")!==i)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across different table cells."}}else if(o&&Ve(o,"tc"))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across table boundaries."};if(e.getElementsByTagNameNS(Ae,"sectPr").length>0&&n)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete paragraph containing section properties (w:sectPr)."};if(o){let s=e;for(;s&&s!==o;){if(B(s,"p")&&s.getElementsByTagNameNS(Ae,"sectPr").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across section break."};s=s.nextSibling}}if(a){if(e.getElementsByTagNameNS(Ae,"fldSimple").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph containing a simple field instruction (w:fldSimple)."};let c=Array.from(e.getElementsByTagNameNS(Ae,"fldChar"));if(c.length>0){let p=0;for(let h of c){let g=h.getAttributeNS(Ae,"fldCharType")||h.getAttribute("w:fldCharType");g==="begin"?p++:g==="end"&&(p=Math.max(0,p-1))}if(p>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph across an unclosed field instruction."}}let u=Array.from(e.getElementsByTagNameNS(Ae,"bookmarkStart")),f=Array.from(e.getElementsByTagNameNS(Ae,"bookmarkEnd")),d=new Set(u.map(p=>p.getAttributeNS(Ae,"id")||p.getAttribute("w:id"))),m=new Set(f.map(p=>p.getAttributeNS(Ae,"id")||p.getAttribute("w:id")));for(let p of d)if(p&&!m.has(p))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:`Refusing to split paragraph across open bookmark range (ID: ${p}).`}}return{valid:!0}}function Ba(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Ae,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function Vl(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Ae,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function Er(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Tt(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function jl(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let a of t){let o=a.trimEnd();if(!o.trim())continue;let i=pn(o,{indentSpaces:2});if(i){n=!0,r.push({kind:"list",markerType:i.markerType,level:i.level,marker:i.marker,outlineLevel:i.outlineLevel,text:Er(i.text)});continue}r.push({kind:"text",text:o.trim()})}return{items:r,hasListMarkers:n}}function Wl(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function _n(e,t){return Y(e)===Y(t)}function Da(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function cm(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],a=e.slice(1).filter(o=>o.kind==="list");if(a.length===0||a.some(o=>o.markerType!=="bullet")||a.some(o=>Number.isInteger(o.outlineLevel)))return!1;if(n?.kind==="text")return _n(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let o=n.level||0;return a.some(l=>(l.level||0)>o)?!1:_n(n.text,t)}return!1}function um(e,t){return e.map(r=>{let n=Math.max(0,(r.ilvl||0)-t);return{...r,ilvl:Math.min(8,t+1+n)}})}function fm(e,t,r,n){let a=e[0],o=e.slice(1).filter(i=>i.kind==="list");if(a?.kind==="text"&&_n(a.text,t)&&o.length>0){let i=o[0].level;return o.map(l=>({ilvl:Da(l,r,i),markerType:l.markerType||n,text:l.text}))}if(e.every(i=>i.kind==="list")){let i=e[0];if(!i||!_n(i.text,t))return null;let l=i.level;return e.slice(1).map(s=>({ilvl:Da(s,r,l),markerType:s.markerType||n,text:s.text})).filter(s=>s.text)}return null}function nt(e){if(!e)return null;let t=Ba(e,"pPr");if(!t)return null;let r=Ba(t,"numPr");if(!r)return null;let n=Ba(r,"numId");if(!n)return null;let a=Vl(n);if(!a||a==="0")return null;let o=Ba(r,"ilvl"),i=Vl(o),l=Number.parseInt(i||"0",10);return{numId:String(a),ilvl:Number.isFinite(l)?l:0}}function Kl(e){let t=nt(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(l=>l&&l.nodeType===1&&l.namespaceURI===Ae&&l.localName==="p"),a=n.indexOf(e);if(a<0)return null;let o=a;for(;o>0;){let l=nt(n[o-1]);if(!l||l.numId!==t.numId)break;o--}let i=a;for(;i<n.length-1;){let l=nt(n[i+1]);if(!l||l.numId!==t.numId)break;i++}return n.slice(o,i+1)}function ri(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},a=typeof r.onWarn=="function"?r.onWarn:()=>{},o=String(t||"");if(!o.includes(`
166
+ `)||!nt(e))return null;let l=Kl(e);if(!l||l.length===0)return null;let s=jl(o);if(!s.hasListMarkers||s.items.length<2)return null;let c=Y(r.currentParagraphText||ve(e)),f=s.items.filter(N=>N.kind==="list")[0]?.markerType||"bullet",d=l.map(N=>({paragraph:N,list:nt(N),text:String(ve(N)||"").trim()})),m=l.indexOf(e);if(m<0)return null;let p=Math.min(...d.map(N=>N.list?.ilvl??0)),h=d.map(N=>Wl((N.list?.ilvl??0)-p,f,N.text)),g=null,v=s.items[0],w=s.items.slice(1).filter(N=>N.kind==="list");if(v?.kind==="text"&&_n(v.text,c)&&w.length>0){let N=Math.max(0,(d[m].list?.ilvl??0)-p),T=w[0].level;g=[{level:N,markerType:f,text:d[m].text},...w.map(S=>({level:Da(S,N,T),markerType:S.markerType||f,text:S.text}))]}else if(s.items.every(N=>N.kind==="list")){let N=Math.max(0,(d[m].list?.ilvl??0)-p),T=s.items[0].level;g=s.items.map(S=>({level:Da(S,N,T),markerType:S.markerType||f,text:S.text}))}else return a("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let y=g.map(N=>Wl(N.level,N.markerType,N.text)),x=h.slice(0,m).concat(y).concat(h.slice(m+1)),b=h.join(`
167
+ `),I=x.join(`
168
+ `);return I===b?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:l,originalText:b,modifiedText:I})}function ni(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},a=typeof r.onWarn=="function"?r.onWarn:()=>{},o=String(t||"");if(!o.includes(`
169
+ `))return null;let i=nt(e);if(!i)return null;let l=jl(o);if(!l.hasListMarkers||l.items.length<2)return null;let s=Y(r.currentParagraphText||ve(e)),u=l.items.filter(m=>m.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,i.ilvl),d=fm(l.items,s,f,u);return!d||d.length===0?(a("[List] Could not derive insertion-only entries from multiline list edit."),null):(cm(l.items,s,f)&&(d=um(d,f),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:i.numId,entries:d})}function kn(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
170
+ `),n=[];for(let i of r){if(!i.trim())continue;let l=pn(i,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(l){n.push({type:l.markerType,level:l.level,text:l.text.trim(),marker:l.marker});continue}n.push({type:"text",level:0,text:i.trim()})}if(n.length===0)return null;let a=n.some(i=>i.type==="numbered"),o=n.some(i=>i.type==="bullet");return{type:a?"numbered":o?"bullet":"text",items:n}}function ai(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function dm(e,t,r){let n=new Map,a=[];for(let o of e){let i=Math.max(0,Number(o?.level)||0);for(let u of Array.from(n.keys()))u>i&&n.delete(u);let l=(n.get(i)||0)+1;n.set(i,l);let s=pm(l,t,r),c=" ".repeat(i*4);a.push(`${c}${s} ${o.text||""}`.trimEnd())}return a.join(`
171
+ `)}function mm(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let a=String(n??""),o=a.match(/^(\s*)/),i=o?o[1].length:0,l=Math.floor(i/r),s=a.trim(),c=null,u=pt(s,{allowZeroSpaceAfterMarker:!0});return u&&(c=u[2].trim()||null,s=Tt(s,{allowZeroSpaceAfterMarker:!0})),{text:s.trim(),level:l,removedMarker:c}})}function pm(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${Hl(e,!1)}.`;case"upperAlpha":return`${Hl(e,!0)}.`;case"lowerRoman":return`${Gl(e,!1)}.`;case"upperRoman":return`${Gl(e,!0)}.`;default:return`${e}.`}}function Hl(e,t=!1){let r=Math.max(1,Number(e)||1),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function Gl(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],a="";for(let[o,i]of n)for(;r>=o;)a+=i,r-=o;return t?a:a.toLowerCase()}function Fa(e){let t=String(e||"");if(!t.trim()||t.includes(`
172
+ `))return null;let r=kn(t);if(!r||!ai(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let a=String(n.marker||"").trim(),o=n.type==="numbered"?mn(a||"1."):"bullet";return{type:n.type,marker:a,numberingStyle:o,startAt:gm(a,o),contentText:String(n.text||"").trim(),normalizedContent:Y(String(n.text||""))}}function oi(e){let t=Fa(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function gm(e,t){if(t!=="decimal")return null;let r=String(e||"").trim().match(/^(\d+)\.?$/);if(!r)return null;let n=Number.parseInt(r[1],10);return Number.isFinite(n)&&n>0?n:null}function $a(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let a=t?.explicitByNumberingKey;if(!(a instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let o=a.get(r)||null;return o&&o.numId!=null&&Number.isInteger(o.nextStartAt)&&o.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(o.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function Ua(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function Mn(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function Kr(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function za(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,a=t?.clearParagraphPropertyChanges!==!1,o=t?.removeListPropertyNode!==!1,i=(Array.isArray(e)?e:[]).filter(s=>s&&s.nodeType===1&&s.localName==="p"),l=0;for(let s of i){let c=s.ownerDocument;if(!c)continue;let u=Kr(s,"pPr");if(u||(u=L(c,"w:pPr"),s.insertBefore(u,s.firstChild)),a){let p=Kr(u,"pPrChange");p&&u.removeChild(p)}if(o){let p=Kr(u,"listPr");p&&u.removeChild(p)}let f=Kr(u,"numPr");f||(f=L(c,"w:numPr"),u.appendChild(f));let d=Kr(f,"ilvl");d||(d=L(c,"w:ilvl"),f.appendChild(d)),d.setAttribute("w:val",String(n));let m=Kr(f,"numId");m||(m=L(c,"w:numId"),f.appendChild(m)),m.setAttribute("w:val",String(r)),l++}return l}function hm(e){let t=j(e,"application/xml").doc;return!t||Ne(t)?null:oe(t)[0]||null}function wm(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function vm(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Hr(e,t){let r=vm(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function ql(e,t){e.setAttribute("w:val",String(t))}function ym(e){let t=j(e,"application/xml").doc;if(!t||Ne(t))return null;let a=oe(t)[0]||null;if(!a)return null;let o=Array.from(a.getElementsByTagNameNS("*","numId"));for(let i of o){let l=Hr(i,["w:val","val"]);if(l!=null)return String(l)}return null}function xm(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let a=n.setAbstractStartOverride!==!1,o=ce(),i=j(e,"application/xml").doc;if(!i||Ne(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let h=Hr(p,["w:numId","numId"]);return h!=null&&String(h)===String(t)});if(!c)return e;let u=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=Hr(u,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Hr(p,["w:ilvl","ilvl"])===0)||null;d||(d=L(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=L(i,"w:startOverride"),d.appendChild(m)),ql(m,r),a&&f!=null){let h=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(g=>{let v=Hr(g,["w:abstractNumId","abstractNumId"]);return v!=null&&v===f})||null;if(h){let g=Array.from(h.getElementsByTagNameNS("*","lvl")).find(w=>Hr(w,["w:ilvl","ilvl"])===0)||null;g||(g=L(i,"w:lvl"),g.setAttribute("w:ilvl","0"),h.appendChild(g));let v=Array.from(g.getElementsByTagNameNS("*","start"))[0]||null;v||(v=L(i,"w:start"),g.insertBefore(v,g.firstChild)),ql(v,r)}}return o.serializeToString(i)}function Gr(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),a=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let o=hm(t);if(!o)return null;let i=nt(o);if(i&&!a)return null;let l=Ge(n).cleanText||n,s=Fa(n)||Fa(l);if(!s)return null;let c=Fa(r),u=Y(r)===Y(l),f=!!c&&c.type===s.type&&c.normalizedContent===s.normalizedContent;return!u&&!f?null:{listInput:`${s.marker} ${s.contentText}`.trim(),numberingKey:`${s.type}:${s.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,startAt:s.startAt}}async function qr(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,a=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await Ur({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new Mt}),o=a?.oxml||a?.ooxml||"",i=wm(o),l=ym(i),s=xm(a?.numberingXml||null,l,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=a?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:s,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}var bm=new Set(["ins","del","rPrChange","pPrChange"]),Nm=/^\d{4}-\d{2}-\d{2}T/;function nr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Ar(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>nr(r)===t)}function Rr(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function Im(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function Tm(e){return nr(e.parentNode)==="rPr"}function Sm(e){let t=r=>{let n=rs(r),a=n.getElementsByTagName("parsererror")[0];if(a)throw new Error(a.textContent||"XML parse error");return n};try{return{doc:t(e)}}catch{try{return{doc:t(`<w:root xmlns:w="${M}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function yt(e){let t=[],r=(f,d,m)=>t.push({code:f,severity:d,message:m}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:a,error:o}=n?{doc:e.nodeType===9?e:e.ownerDocument}:Sm(e);if(!a)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${o}`),{valid:!1,issues:t};let i=Ar(a,"ins"),l=Ar(a,"del"),s=i.concat(l);for(let f of Ar(a,"p")){let d=Array.from(f.getElementsByTagName("*")).find(m=>m!==f&&nr(m)==="p");d&&r("NESTED_PARAGRAPH","error",`<${f.nodeName}> contains nested <${d.nodeName}>.`)}for(let f of Ar(a,"body")){let d=Array.from(f.childNodes||[]).filter(p=>p.nodeType===1),m=d.map((p,h)=>nr(p)==="sectPr"?h:-1).filter(p=>p>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==d.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let f of s){let m=Array.from(f.getElementsByTagName("*")).filter(p=>p!==f&&["ins","del"].includes(nr(p))).find(p=>nr(f)!=="ins"||nr(p)!=="del"?!0:p.parentNode!==f);m&&r("NESTED_REVISION","error",`<${f.nodeName}> (w:id="${Rr(f,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let f of l)Ar(f,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${Rr(f,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let f of s){let d=[];Rr(f,"id")||d.push("w:id"),Rr(f,"author")||d.push("w:author"),Nm.test(Rr(f,"date"))||d.push("w:date"),d.length>0&&r("MISSING_REVISION_METADATA","error",`<${f.nodeName}> is missing or has malformed ${d.join(", ")}.`)}let c=new Set;for(let f of Array.from(a.getElementsByTagName("*"))){if(!bm.has(nr(f)))continue;let d=Rr(f,"id");d&&(c.has(d)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${d} appears more than once.`),c.add(d))}let u=Ar(a,"t").concat(Ar(a,"delText"));for(let f of u){let d=f.textContent||"";/^\s|\s$/.test(d)&&Im(f)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${f.nodeName}> has boundary whitespace without xml:space="preserve".`),d===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${f.nodeName}> is empty.`)}for(let f of s){if(Tm(f))continue;Array.from(f.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${f.nodeName}> (w:id="${Rr(f,"id")}") wraps no content.`)}for(let f of $l(a)){let d=f.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${d} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(f=>f.severity==="error"),issues:t}}function Xa(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Ae&&r.localName===t):[]}function Em(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Am(e){let t=Xa(e,"tr"),r=t.map(a=>Xa(a,"tc").map(i=>{let l=Xa(i,"p");return l.length===0?Y(ve(i)):l.map(c=>Y(ve(c))).filter(Boolean).join(`
173
+ `)})),n=r.reduce((a,o)=>Math.max(a,o.length),0);return r.forEach(a=>{for(;a.length<n;)a.push("")}),{matrix:r,rowElements:t,columnCount:n}}function Rm(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(l=>{let s=Array.isArray(l)?l.slice(0,t):[];for(;s.length<t;)s.push("");return s}),n=r[0],a=new Array(t).fill("---"),o=r.slice(1),i=l=>`| ${l.map(s=>Em(s)).join(" | ")} |`;return[i(n),i(a),...o.map(i)].join(`
174
+ `)}function Pm(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>Y(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function Yl(e){let t=String(e||"").trim();return t?!!(/^and$/i.test(t)||/^\[.*\]$/.test(t)||/^\(.*\)$/.test(t)||/:\s*$/.test(t)||t.length<=90&&!/[.!?]$/.test(t)&&/[:\[\]()]/.test(t)||/^[\[(]/.test(t)):!1}function ii(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ve;if(!e||!e.parentNode)return null;let a=[e],o=e.nextSibling,i=0;for(;o&&i<r;){i+=1;let l=o.nextSibling;if(o.nodeType!==1||o.namespaceURI!==Ae||o.localName!=="p"){o=l;continue}let s=String(n(o)||"").trim();if(!s){if(a.length>1)break;o=l;continue}if(!Yl(s))break;a.push(o),o=l}return a.length>1?a:null}function si(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},a=typeof r.onWarn=="function"?r.onWarn:()=>{},o=String(t||"");if(!o.includes(`
175
+ `)||Tr(o))return null;let i=o.split(/\r?\n/g).map(x=>x.trim()).filter(Boolean);if(i.length<2)return null;let l=r.tableElement||Ve(e,"tbl"),s=Ve(e,"tr"),c=Ve(e,"tc");if(!l||!s||!c)return null;let u=Y(r.currentParagraphText||ve(e)),f=Y(i[0]);if(u&&f&&f!==u)return a("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=Am(l);if(d.length===0||p===0)return null;let h=m.indexOf(s),v=Xa(s,"tc").indexOf(c);if(h<0||v<0||v>=p)return null;d[h][v]=i[0];let w=Pm(d[h]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let x=1;x<i.length;x++){let b=h+x,I=i[x];if(b<d.length&&!Y(d[b][v]))if(w)for(let N=0;N<p;N++)Y(d[b][N])||(d[b][N]=I);else d[b][v]=I;else{let N=new Array(p).fill("");if(w)for(let T=0;T<p;T++)N[T]=I;else N[v]=I;d.splice(Math.min(b,d.length),0,N)}}let y=Rm(d,p);return y?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),y):null}function Yr(e,t){if(!e||!Array.isArray(t))return null;for(let r of t){let n=e.getAttribute(r);if(n==null||n==="")continue;let a=Number.parseInt(String(n),10);if(Number.isFinite(a))return a}return null}function Zr(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,a=t instanceof Set?t:new Set;for(;a.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let o=1;o<=r;o+=1)if(!a.has(o))return o}return n}function ui(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,a=new Set,o=new Set;if(String(e||"").trim())try{let u=Ft(e),f=Array.from(u.getElementsByTagNameNS("*","abstractNum")),d=Array.from(u.getElementsByTagNameNS("*","num"));for(let m of f){let p=Yr(m,["w:abstractNumId","abstractNumId"]);p!=null&&o.add(p)}for(let m of d){let p=Yr(m,["w:numId","numId"]);p!=null&&a.add(p)}}catch{}let i=a.size>0?Math.max(...a):0,l=o.size>0?Math.max(...o):0,s=Math.max(r,i+1),c=Math.max(r,l+1);return{nextNumId:Zr(s,a,n),nextAbstractNumId:Zr(c,o,n),usedNumIds:a,usedAbstractNumIds:o,minId:r,maxPreferred:n}}function Cm(e){return!e||typeof e!="object"?null:(e.usedNumIds instanceof Set||(e.usedNumIds=new Set),e.usedAbstractNumIds instanceof Set||(e.usedAbstractNumIds=new Set),(!Number.isInteger(e.minId)||e.minId<1)&&(e.minId=1),(!Number.isInteger(e.maxPreferred)||e.maxPreferred<e.minId)&&(e.maxPreferred=32767),(!Number.isInteger(e.nextNumId)||e.nextNumId<e.minId)&&(e.nextNumId=e.minId),(!Number.isInteger(e.nextAbstractNumId)||e.nextAbstractNumId<e.minId)&&(e.nextAbstractNumId=e.minId),e.nextNumId=Zr(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=Zr(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function Bn(e,t="num"){let r=Cm(e);if(!r)return null;let n=t==="abstract",a=n?r.nextAbstractNumId:r.nextNumId;return!Number.isInteger(a)||a<1?null:(n?(r.usedAbstractNumIds.add(a),r.nextAbstractNumId=Zr(a+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(a),r.nextNumId=Zr(a+1,r.usedNumIds,r.maxPreferred)),a)}function Wa(e){let t=Bn(e,"num"),r=Bn(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function li(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function Va(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Ae&&e.localName===t)}function Zl(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(o=>o&&o.nodeType===1&&o.namespaceURI===Ae),a=null;r==="abstract"?a=n.find(o=>o.localName==="num"||o.localName==="numIdMacAtCleanup")||null:a=n.find(o=>o.localName==="numIdMacAtCleanup")||null,a?e.insertBefore(t,a):e.appendChild(t)}function Om(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function Ln(e,t){let r=Om(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Jl(e,t,r){e?.setAttribute?.(t,String(r))}function ci(e,t){e?.setAttribute?.("w:val",String(t))}function ja(e,t){if(!(!Array.isArray(e)||t==null))for(let r of e){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let a of n)ci(a,t)}}function Ka(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let a=Ln(n,["w:val","val"]);if(a!=null)return String(a)}}return null}function Ha(e,t,r){let n=String(e),a=String(t),o=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(l,s)=>{let c=Array.from({length:s+1},(f,d)=>`%${d+1}`).join(".")+".",u=720*(s+1);return`
176
+ <w:lvl w:ilvl="${s}">
176
177
  <w:start w:val="1"/>
177
178
  <w:numFmt w:val="decimal"/>
178
179
  <w:lvlText w:val="${c}"/>
179
180
  <w:lvlJc w:val="left"/>
180
181
  <w:pPr><w:ind w:left="${u}" w:hanging="360"/></w:pPr>
181
182
  </w:lvl>`}).join("");return`
182
- <w:numbering xmlns:w="${Oe}">
183
- <w:abstractNum w:abstractNumId="${o}">
183
+ <w:numbering xmlns:w="${Ae}">
184
+ <w:abstractNum w:abstractNumId="${a}">
184
185
  <w:multiLevelType w:val="multilevel"/>
185
- ${a}
186
+ ${i}
186
187
  </w:abstractNum>
187
188
  <w:num w:numId="${n}">
188
- <w:abstractNumId w:val="${o}"/>
189
+ <w:abstractNumId w:val="${a}"/>
189
190
  <w:lvlOverride w:ilvl="0">
190
- <w:startOverride w:val="${i}"/>
191
+ <w:startOverride w:val="${o}"/>
191
192
  </w:lvlOverride>
192
193
  </w:num>
193
- </w:numbering>`.trim()}function ku(e,t,r){let n=et(e);if(xo(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,i=new Map,a=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of a){let u=br(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=xr(r,"abstract");f!=null&&(o.set(u,f),Fa(c,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of s){let u=br(c,["w:numId","numId"]);if(u==null)continue;let f=xr(r,"num");if(f==null)continue;i.set(u,f),Fa(c,"w:numId",f);let m=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(m){let d=br(m,["w:val","val"]);d!=null&&o.has(d)&&No(m,o.get(d))}}let l=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of l){let u=Array.from(c?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of u){let m=br(f,["w:val","val"]);m!=null&&i.has(m)&&No(f,i.get(m))}}return{numberingXml:yt(n),replacementNodes:l}}function Mu(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let o=et(r),i=et(n);if(xo(o)||xo(i))return r;let a=o.documentElement,s=i.documentElement;if(!a||!s)return r;let l=new Set(Array.from(a.childNodes||[]).filter(u=>mn(u,"abstractNum")).map(u=>Ut(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(a.childNodes||[]).filter(u=>mn(u,"num")).map(u=>Ut(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(s.childNodes||[])){if(!mn(u,"abstractNum"))continue;let f=Ut(u,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(Ba(a,o.importNode(u,!0),"abstract"),l.add(f))}for(let u of Array.from(s.childNodes||[])){if(!mn(u,"num"))continue;let f=Ut(u,["w:numId","numId"]);f==null||c.has(f)||(Ba(a,o.importNode(u,!0),"num"),c.add(f))}return yt(o)}catch{return r}}function _u(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!ne(e)}function $a(e){let t=j(e,"application/xml");return t.error||_u(t.doc)?{...t,doc:null}:t}function Xa(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(E,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function vo(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===E&&n.localName===t)return n;return null}function ft(e,t){return Array.from(e?.getElementsByTagNameNS?.(E,t)||[])}function Nr(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function Lu(e){let t=vo(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=ft(t,"rStyle")[0]||null,n=Nr(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),i=n.includes("italic")||n.includes("emphasis");return{bold:ft(t,"b").length>0||o,italic:ft(t,"i").length>0||i}}function Da(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(E,"r")||[]);for(let n of r){if(!bt(n,e,"accepted"))continue;let o=xt(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...Lu(n)})}return t}function yo(e){return String(e||"").replace(/\r/g,"").split(`
194
+ </w:numbering>`.trim()}function Ga(e,t,r){let n=Ft(e);if(li(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let a=new Map,o=new Map,i=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of i){let u=Ln(c,["w:abstractNumId","abstractNumId"]);if(u==null)continue;let f=Bn(r,"abstract");f!=null&&(a.set(u,f),Jl(c,"w:abstractNumId",f))}let l=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of l){let u=Ln(c,["w:numId","numId"]);if(u==null)continue;let f=Bn(r,"num");if(f==null)continue;o.set(u,f),Jl(c,"w:numId",f);let d=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(d){let m=Ln(d,["w:val","val"]);m!=null&&a.has(m)&&ci(d,a.get(m))}}let s=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of s){let u=Array.from(c?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of u){let d=Ln(f,["w:val","val"]);d!=null&&o.has(d)&&ci(f,o.get(d))}}return{numberingXml:Ir(n),replacementNodes:s}}function fi(e,t){let r=String(e||""),n=String(t||"");if(!n.trim())return r;if(!r.trim())return n;try{let a=Ft(r),o=Ft(n);if(li(a)||li(o))return r;let i=a.documentElement,l=o.documentElement;if(!i||!l)return r;let s=new Set(Array.from(i.childNodes||[]).filter(u=>Va(u,"abstractNum")).map(u=>Yr(u,["w:abstractNumId","abstractNumId"])).filter(u=>u!=null)),c=new Set(Array.from(i.childNodes||[]).filter(u=>Va(u,"num")).map(u=>Yr(u,["w:numId","numId"])).filter(u=>u!=null));for(let u of Array.from(l.childNodes||[])){if(!Va(u,"abstractNum"))continue;let f=Yr(u,["w:abstractNumId","abstractNumId"]);f==null||s.has(f)||(Zl(i,a.importNode(u,!0),"abstract"),s.add(f))}for(let u of Array.from(l.childNodes||[])){if(!Va(u,"num"))continue;let f=Yr(u,["w:numId","numId"]);f==null||c.has(f)||(Zl(i,a.importNode(u,!0),"num"),c.add(f))}return Ir(a)}catch{return r}}function _m(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!Ne(e)}function Ql(e){let t=j(e,"application/xml");return t.error||_m(t.doc)?{...t,doc:null}:t}function ec(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(M,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function di(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===M&&n.localName===t)return n;return null}function ar(e,t){return Array.from(e?.getElementsByTagNameNS?.(M,t)||[])}function Dn(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function km(e){let t=di(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=ar(t,"rStyle")[0]||null,n=Dn(r,["w:val","val"]).toLowerCase(),a=n.includes("strong")||n.includes("bold"),o=n.includes("italic")||n.includes("emphasis");return{bold:ar(t,"b").length>0||a,italic:ar(t,"i").length>0||o}}function tc(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(M,"r")||[]);for(let n of r){if(!hr(n,e,"accepted"))continue;let a=wr(n,{boundary:e,revisionView:"accepted"});a&&t.push({text:a,...km(n)})}return t}function mi(e){return String(e||"").replace(/\r/g,"").split(`
194
195
  `).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
195
- `).trim()}function Bu(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let o=n[1]||"",i=n[2]||"",a=n[3]||"";if(!i.trim())return r;let s=i;return t.bold&&t.italic?s=`***${i}***`:t.bold?s=`**${i}**`:t.italic&&(s=`*${i}*`),`${o}${s}${a}`}function Fu(e){let t=vo(e,"pPr");if(!t)return null;let r=ft(t,"pStyle")[0]||null,n=Nr(r,["w:val","val"]);if(n){let s=n.match(/^heading\s*([1-9])$/i);if(s){let l=Number.parseInt(s[1],10);if(Number.isInteger(l))return Math.min(Math.max(l,1),6)}}let o=ft(t,"outlineLvl")[0]||null,i=Nr(o,["w:val","val"]),a=Number.parseInt(i,10);return Number.isInteger(a)&&a>=0?Math.min(a+1,6):null}function $u(e){let t=vo(e,"pPr");if(!t)return null;let r=ft(t,"numPr")[0]||null;if(!r)return null;let n=ft(r,"ilvl")[0]||null,o=ft(r,"numId")[0]||null,i=Number.parseInt(Nr(n,["w:val","val"]),10),a=Nr(o,["w:val","val"]);return{level:Number.isInteger(i)&&i>=0?i:0,marker:a==="1"?"-":"1."}}function Xu(e){let t=Da(e).map(r=>r.text).join("");return yo(t)}function Du(e){let r=Da(e).map(a=>Bu(a.text,a)).join(""),n=yo(r);if(!n)return"";let o=Fu(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let i=$u(e);return i?`${" ".repeat(i.level)}${i.marker} ${n}`:n}function zu(e){return za(e).text}function za(e){let t=$a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Xa(r);return n.length===0?{text:yo(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Xu).join(`
196
+ `).trim()}function Mm(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let a=n[1]||"",o=n[2]||"",i=n[3]||"";if(!o.trim())return r;let l=o;return t.bold&&t.italic?l=`***${o}***`:t.bold?l=`**${o}**`:t.italic&&(l=`*${o}*`),`${a}${l}${i}`}function Lm(e){let t=di(e,"pPr");if(!t)return null;let r=ar(t,"pStyle")[0]||null,n=Dn(r,["w:val","val"]);if(n){let l=n.match(/^heading\s*([1-9])$/i);if(l){let s=Number.parseInt(l[1],10);if(Number.isInteger(s))return Math.min(Math.max(s,1),6)}}let a=ar(t,"outlineLvl")[0]||null,o=Dn(a,["w:val","val"]),i=Number.parseInt(o,10);return Number.isInteger(i)&&i>=0?Math.min(i+1,6):null}function Bm(e){let t=di(e,"pPr");if(!t)return null;let r=ar(t,"numPr")[0]||null;if(!r)return null;let n=ar(r,"ilvl")[0]||null,a=ar(r,"numId")[0]||null,o=Number.parseInt(Dn(n,["w:val","val"]),10),i=Dn(a,["w:val","val"]);return{level:Number.isInteger(o)&&o>=0?o:0,marker:i==="1"?"-":"1."}}function Dm(e){let t=tc(e).map(r=>r.text).join("");return mi(t)}function Fm(e){let r=tc(e).map(i=>Mm(i.text,i)).join(""),n=mi(r);if(!n)return"";let a=Lm(e);if(a!=null)return`${"#".repeat(a)} ${n}`;let o=Bm(e);return o?`${" ".repeat(o.level)}${o.marker} ${n}`:n}function $m(e){return rc(e).text}function rc(e){let t=Ql(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=ec(r);return n.length===0?{text:mi(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Dm).join(`
196
197
 
197
- `).trim(),status:"ok",warnings:t.warnings}}function Wu(e){return Wa(e).text}function Wa(e){let t=$a(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Xa(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(Du).join(`
198
+ `).trim(),status:"ok",warnings:t.warnings}}function Um(e){return nc(e).text}function nc(e){let t=Ql(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=ec(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(Fm).join(`
198
199
 
199
- `).trim(),status:"ok",warnings:t.warnings}}var Ht=new TextEncoder;function Ua(e){if(typeof e!="string")throw new TypeError(`Entry name must be a string, got ${typeof e}`);let t=e.replace(/\\/g,"/");for(t=t.replace(/^\/+/,"");t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+/g,"/"),!t)throw new Error(`Invalid empty entry name: "${e}"`);return t}function So({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=Ht.encode("docx-redline-revision-token\0"),n=1,o=Ht.encode(e),i=[],a=new Set,s=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let m of s){if(!m)continue;let d=Array.isArray(m)?m[0]:m.name,p=Array.isArray(m)?m[1]:m.payload??m.bytes;if(d==null)continue;let h=Ua(String(d));if(a.has(h))throw new Error(`Duplicate normalized entry path detected: "${h}"`);a.add(h);let w;typeof p=="string"?w=Ht.encode(p):p instanceof Uint8Array?w=p:p&&typeof p.length=="number"?w=new Uint8Array(p):w=new Uint8Array(0),i.push({name:h,nameBytes:Ht.encode(h),payloadBytes:w})}i.sort((m,d)=>m.name<d.name?-1:m.name>d.name?1:0);let l=r.length+4+4+o.length+4;for(let m of i)l+=4+m.nameBytes.length+4+m.payloadBytes.length;let c=new Uint8Array(l),u=new DataView(c.buffer,c.byteOffset,c.byteLength),f=0;c.set(r,f),f+=r.length,u.setUint32(f,n,!1),f+=4,u.setUint32(f,o.length,!1),f+=4,c.set(o,f),f+=o.length,u.setUint32(f,i.length,!1),f+=4;for(let m of i)u.setUint32(f,m.nameBytes.length,!1),f+=4,c.set(m.nameBytes,f),f+=m.nameBytes.length,u.setUint32(f,m.payloadBytes.length,!1),f+=4,c.set(m.payloadBytes,f),f+=m.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:i.map(m=>m.name)}}async function ja({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:i}=So({scope:e,entries:t}),a="";if(typeof r=="function")a=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let s=await globalThis.crypto.subtle.digest("SHA-256",n),l=new Uint8Array(s);a=Array.from(l).map(c=>c.toString(16).padStart(2,"0")).join("")}else throw new Error("No crypto provider available for SHA-256 revision token computation.");return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function To({scope:e,entries:t=[],digestFn:r}){if(typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn.");let{framing:n,coveredParts:o,version:i}=So({scope:e,entries:t}),a=r(n);return{algorithm:"sha256",version:i,scope:e,value:a,coveredParts:o}}function dn(e){let t=[];if(e?.documentXml&&t.push({name:"word/document.xml",payload:e.documentXml}),e?.commentsXml&&t.push({name:"word/comments.xml",payload:e.commentsXml}),e?.commentsExtendedXml&&t.push({name:"word/commentsExtended.xml",payload:e.commentsExtendedXml}),e?.numberingXml&&t.push({name:"word/numbering.xml",payload:e.numberingXml}),e?.stylesXml&&t.push({name:"word/styles.xml",payload:e.stylesXml}),e?.parts instanceof Map)for(let[r,n]of e.parts.entries())t.push({name:r,payload:n});else if(e?.additionalParts&&typeof e.additionalParts=="object")for(let[r,n]of Object.entries(e.additionalParts))t.push({name:r,payload:n});return t}async function Uu(e,t={}){let r=dn(e);return ja({scope:"document-parts",entries:r,digestFn:t.digestFn})}function ju(e){return!e||typeof e!="object"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token must be an object."}}:e.algorithm!=="sha256"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token algorithm: "${e.algorithm}". Expected "sha256".`}}:e.version!==1?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token version: "${e.version}". Expected 1.`}}:e.scope!=="document-parts"&&e.scope!=="package"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token scope: "${e.scope}". Expected "document-parts" or "package".`}}:typeof e.value!="string"||!/^[0-9a-f]{64}$/i.test(e.value.trim())?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token value must be a 64-character hex string."}}:{valid:!0}}function Hu(e,t){if(typeof e!="string"||typeof t!="string")return!1;let r=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(r.length!==n.length)return!1;let o=Ht.encode(r),i=Ht.encode(n),a=0;for(let s=0;s<o.length;s++)a|=o[s]^i[s];return a===0}var q=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",Ue=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(E,t)||[]),ge=(e,t)=>Ue(e,t)[0]||null;function Ha(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===E))return!0;r=r.parentNode}return!1}function pn(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=j(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Vu(e){let t=ge(ge(e,"pPr"),"numPr");if(!t)return null;let r=q(ge(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(q(ge(t,"ilvl"),"val")||"0",10)||0}}function Gu(e){let t=new Map;for(let n of Ue(e,"abstractNum")){let o=new Map;for(let i of Ue(n,"lvl")){let a=Number.parseInt(q(i,"ilvl")||"0",10)||0;o.set(a,{start:Number.parseInt(q(ge(i,"start"),"val")||"1",10)||1,format:q(ge(i,"numFmt"),"val")||"decimal",text:q(ge(i,"lvlText"),"val")||`%${a+1}.`})}t.set(q(n,"abstractNumId"),o)}let r=new Map;for(let n of Ue(e,"num")){let o=q(ge(n,"abstractNumId"),"val"),i=new Map(t.get(o)||[]);for(let a of Ue(n,"lvlOverride")){let s=Number.parseInt(q(a,"ilvl")||"0",10)||0,l=ge(a,"lvl"),c={...i.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(c.start=Number.parseInt(q(ge(l,"start"),"val")||String(c.start),10)||c.start,c.format=q(ge(l,"numFmt"),"val")||c.format,c.text=q(ge(l,"lvlText"),"val")||c.text);let u=ge(a,"startOverride");u&&(c.start=Number.parseInt(q(u,"val")||String(c.start),10)||c.start),i.set(s,c)}r.set(q(n,"numId"),i)}return r}function Va(e,t){let r=Math.max(1,e),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function Ga(e){let t=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],r=e,n="";for(let[o,i]of t)for(;r>=o;)n+=i,r-=o;return n}function Ku(e,t){return t==="lowerLetter"?Va(e,!1):t==="upperLetter"?Va(e,!0):t==="lowerRoman"?Ga(e).toLowerCase():t==="upperRoman"?Ga(e):String(e)}function Yu(e){let t=e?Gu(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let i=r.get(n.numId)||[],a=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};i[n.level]=i[n.level]==null?a.start:i[n.level]+1,i.length=n.level+1,r.set(n.numId,i);let s=a.text.replace(/%([1-9])/g,(l,c)=>{let u=Number(c)-1,f=o.get(u)||a;return Ku(i[u]??f.start,f.format)});return{...n,label:s,format:a.format}}}function Ju(e){let t=ge(e,"pPr"),n=q(ge(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(q(ge(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function qu(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of Ue(e,s))r.push({type:l,id:q(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let i=o?.parentNode;for(;i&&i.localName!=="tbl";)i=i.parentNode;let a=e.ownerDocument;return{references:r,table:i?{tableIndex:Array.from(a.getElementsByTagNameNS(E,"tbl")).indexOf(i)+1,rowIndex:Array.from(i.getElementsByTagNameNS(E,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(E,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Ka(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of Ue(e,r))q(n,"author")&&t.add(q(n,"author"));return[...t].sort()}function Zu(e){let t=new Map;for(let r of Ue(e,"comment")){let n=Ue(r,"p");t.set(q(r,"id"),{id:q(r,"id"),author:q(r,"author")||null,date:q(r,"date")||null,text:n.map(o=>fe(o)).join(`
200
- `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function Qu(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let o=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",i=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",a=r.get(o.toUpperCase());a&&(a.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",i&&(a.parentParaId=i,a.parentCommentId=r.get(i.toUpperCase())?.id||null))}}function ef(e,t){let r=new Map,n=new Map,o=null,i=s=>{for(let l of r.values())l.text+=s},a=s=>{for(let l of Array.from(s?.childNodes||[])){if(l?.nodeType!==1)continue;let c=l.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(q(l,"id"),{text:""});else if(c==="commentRangeEnd"){let u=q(l,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?i(xt(l,{revisionView:t,boundary:o})):a(l)}};return e.forEach((s,l)=>{o=s,a(s),l<e.length-1&&r.size&&i(`
201
- `)}),n}function tf(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(h=>h.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(h=>p.has(h.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let i=r.length,a=Number.isInteger(t.after)&&t.after>0?t.after:null,s=a==null?r:r.filter(p=>p.index>a),l=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=l==null?s:s.slice(0,l),u=c.length<s.length,f=Number.isInteger(t.around)&&t.around>0?t.around:0,m=!!t.search||f>0||l!=null||a!=null,d=c;if(f>0&&t.search){let p=new Set(c.map(b=>b.index)),h=new Map;for(let b of c){let g=Math.max(n,b.index-f),x=Math.min(o,b.index+f);for(let v=g;v<=x;v++){if(p.has(v))continue;let N=h.get(v)||[];N.push(b.index),h.set(v,N)}}let w=new Set([...p,...h.keys()]);d=e.filter(b=>w.has(b.index)).map(b=>p.has(b.index)?{...b,selectionRole:"match"}:{...b,selectionRole:"context",contextFor:h.get(b.index)||[]})}else m&&(d=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:d,...m?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:i,returnedMatches:c.length,returnedParagraphs:d.length,truncated:u,nextAfter:u&&c.length>0?c[c.length-1].index:null,...l!=null?{limit:l}:{},...a!=null?{after:a}:{},...f>0?{around:f}:{}}}:{}}}function rf(e,t={}){let r=pn(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=pn(e?.commentsXml,"word/comments.xml"),o=pn(e?.commentsExtendedXml,"word/commentsExtended.xml"),i=pn(e?.numberingXml,"word/numbering.xml"),a=[...r.warnings||[]];n.error&&a.push(n.error.message),o.error&&a.push(o.error.message),i.error&&a.push(i.error.message);let s=Zu(n.doc);Qu(s,o.doc);let l=Yu(i.doc),c=null,u=Te(r.doc),f=t.revisionView==="rejected"?"rejected":"accepted",m=ef(u,f),d=u.map((x,v)=>{let N=fe(x,{revisionView:f}),S=Ju(x);S&&(c={level:S,text:N});let y=[...new Set([...Ue(x,"commentRangeStart"),...Ue(x,"commentReference")].map($=>q($,"id")).filter(Boolean))],T=Ka(x),A=l(Vu(x)),M=q(ge(ge(x,"pPr"),"pStyle"),"val")||null,_=qu(x,N),F=v+1,X=A?.label&&A.format!=="bullet"?A.label:null,C=c?.text||null,W=N.slice(0,t.excerptLength||120),R=S?N:X?[X,C].filter(Boolean).join(" \u2014 "):C?[C,W].filter(Boolean).join(" \u2014 "):W,B=Kr(x);return{index:F,ref:`P${F}`,paragraphId:Tt(x),fingerprint:St(x,{text:N,index:F,revisionView:f}),revisionView:f,text:N,exactText:N,excerpt:W,humanReference:R,provision:X,inTable:Ha(x,"tc"),table:_.table,styleId:M,headingLevel:S,nearestHeading:c,list:A,structuralReferences:_.references,hasRevisions:T.length>0,revisionAuthors:T,commentIds:y,segments:B}});for(let x of d)for(let v of x.commentIds){let N=s.get(v)||{id:v,author:null,date:null,text:""};N.paragraphIndex??(N.paragraphIndex=x.index),N.targetRef??(N.targetRef=x.ref),N.anchoredText??(N.anchoredText=m.get(v)||x.text),s.set(v,N)}let p=tf(d,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let x=String(t.search).toLowerCase(),v=f==="accepted"?"rejected":"accepted",N=1,S=u.length;t.range&&(N=Number(t.range.start??t.range[0]),S=Number(t.range.end??t.range[1]));let y=0;for(let T=0;T<u.length;T++){let A=T+1;if(t.range&&(A<N||A>S)||Array.isArray(t.indexes)&&!t.indexes.includes(A))continue;let M=u[T];if(t.inTable!=null&&Ha(M,"tc")!==!!t.inTable||t.revisedOnly&&Ka(M).length===0)continue;let _=fe(M,{revisionView:v});t.skipEmpty&&_.length===0||_.toLowerCase().includes(x)&&y++}y>0&&(p.selection.hint=f==="accepted"?`0 matches in accepted view, but ${y} match${y===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${y} match${y===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}d=p.paragraphs;let h=[...new Set(d.flatMap(x=>x.revisionAuthors))].sort(),w=dn(e),b=w.map(x=>x.name).sort(),g=null;return typeof t.digestFn=="function"&&(g=To({scope:"document-parts",entries:w,digestFn:t.digestFn})),{status:"ok",revisionToken:g,coveredParts:b,paragraphs:d,...p.selection?{selection:p.selection}:{},comments:[...s.values()],revisionAuthors:h,commentAuthors:[...new Set([...s.values()].map(x=>x.author).filter(Boolean))].sort(),counts:{paragraphs:d.length,comments:s.size,revisedParagraphs:d.filter(x=>x.hasRevisions).length},warnings:a}}var gn="http://schemas.microsoft.com/office/word/2010/wordml",rt="http://schemas.microsoft.com/office/word/2012/wordml";function Eo(e){let t=Number.parseInt(String(e),10);return(Number.isFinite(t)?1879048192+(t>>>0)>>>0:1879048192).toString(16).toUpperCase().padStart(8,"0").slice(-8)}function vr(e,t,r,n,o=Eo(e)){let i=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",a=Ne(r),s=Ne(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${i}">
202
- <w:p w14:paraId="${Ne(o)}" xmlns:w14="${gn}">
203
- <w:r><w:t>${a}</w:t></w:r>
200
+ `).trim(),status:"ok",warnings:t.warnings}}var zm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Xm=new TextEncoder;function Fn(e){let t;if(typeof e=="string")t=Xm.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,a=Math.ceil((r+9)/64)*64,o=new Uint8Array(a);o.set(t,0),o[r]=128;let i=new DataView(o.buffer,o.byteOffset,o.byteLength),l=Math.floor(n/4294967296),s=n>>>0;i.setUint32(a-8,l,!1),i.setUint32(a-4,s,!1);let c=1779033703,u=3144134277,f=1013904242,d=2773480762,m=1359893119,p=2600822924,h=528734635,g=1541459225,v=new Uint32Array(64);for(let y=0;y<a;y+=64){for(let A=0;A<16;A++)v[A]=i.getUint32(y+A*4,!1);for(let A=16;A<64;A++){let R=v[A-15],O=(R>>>7|R<<25)^(R>>>18|R<<14)^R>>>3,P=v[A-2],C=(P>>>17|P<<15)^(P>>>19|P<<13)^P>>>10;v[A]=v[A-16]+O+v[A-7]+C|0}let x=c,b=u,I=f,N=d,T=m,S=p,E=h,_=g;for(let A=0;A<64;A++){let R=(T>>>6|T<<26)^(T>>>11|T<<21)^(T>>>25|T<<7),O=T&S^~T&E,P=_+R+O+zm[A]+v[A]|0,C=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),k=x&b^x&I^b&I,D=C+k|0;_=E,E=S,S=T,T=N+P|0,N=I,I=b,b=x,x=P+D|0}c=c+x|0,u=u+b|0,f=f+I|0,d=d+N|0,m=m+T|0,p=p+S|0,h=h+E|0,g=g+_|0}let w=y=>(y>>>0).toString(16).padStart(8,"0");return w(c)+w(u)+w(f)+w(d)+w(m)+w(p)+w(h)+w(g)}var Jr=new TextEncoder;function ac(e){if(typeof e!="string")throw new TypeError(`Entry name must be a string, got ${typeof e}`);let t=e.replace(/\\/g,"/");for(t=t.replace(/^\/+/,"");t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+/g,"/"),!t)throw new Error(`Invalid empty entry name: "${e}"`);return t}function pi({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=Jr.encode("docx-redline-revision-token\0"),n=1,a=Jr.encode(e),o=[],i=new Set,l=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of l){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let h=ac(String(m));if(i.has(h))throw new Error(`Duplicate normalized entry path detected: "${h}"`);i.add(h);let g;typeof p=="string"?g=Jr.encode(p):p instanceof Uint8Array?g=p:p&&typeof p.length=="number"?g=new Uint8Array(p):g=new Uint8Array(0),o.push({name:h,nameBytes:Jr.encode(h),payloadBytes:g})}o.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let s=r.length+4+4+a.length+4;for(let d of o)s+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(s),u=new DataView(c.buffer,c.byteOffset,c.byteLength),f=0;c.set(r,f),f+=r.length,u.setUint32(f,n,!1),f+=4,u.setUint32(f,a.length,!1),f+=4,c.set(a,f),f+=a.length,u.setUint32(f,o.length,!1),f+=4;for(let d of o)u.setUint32(f,d.nameBytes.length,!1),f+=4,c.set(d.nameBytes,f),f+=d.nameBytes.length,u.setUint32(f,d.payloadBytes.length,!1),f+=4,c.set(d.payloadBytes,f),f+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:o.map(d=>d.name)}}async function oc({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:a,version:o}=pi({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let l=await globalThis.crypto.subtle.digest("SHA-256",n),s=new Uint8Array(l);i=Array.from(s).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=Fn(n);return{algorithm:"sha256",version:o,scope:e,value:i,coveredParts:a}}function $n({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:a,version:o}=pi({scope:e,entries:t}),i=typeof r=="function"?r(n):Fn(n);return{algorithm:"sha256",version:o,scope:e,value:i,coveredParts:a}}function qa(e){let t=[];if(e?.documentXml&&t.push({name:"word/document.xml",payload:e.documentXml}),e?.commentsXml&&t.push({name:"word/comments.xml",payload:e.commentsXml}),e?.commentsExtendedXml&&t.push({name:"word/commentsExtended.xml",payload:e.commentsExtendedXml}),e?.numberingXml&&t.push({name:"word/numbering.xml",payload:e.numberingXml}),e?.stylesXml&&t.push({name:"word/styles.xml",payload:e.stylesXml}),e?.parts instanceof Map)for(let[r,n]of e.parts.entries())t.push({name:r,payload:n});else if(e?.additionalParts&&typeof e.additionalParts=="object")for(let[r,n]of Object.entries(e.additionalParts))t.push({name:r,payload:n});return t}async function Un(e,t={}){let r=qa(e);return oc({scope:"document-parts",entries:r,digestFn:t.digestFn})}function Pr(e){return!e||typeof e!="object"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token must be an object."}}:e.algorithm!=="sha256"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token algorithm: "${e.algorithm}". Expected "sha256".`}}:e.version!==1?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token version: "${e.version}". Expected 1.`}}:e.scope!=="document-parts"&&e.scope!=="package"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token scope: "${e.scope}". Expected "document-parts" or "package".`}}:typeof e.value!="string"||!/^[0-9a-f]{64}$/i.test(e.value.trim())?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token value must be a 64-character hex string."}}:{valid:!0}}function Cr(e,t){if(typeof e!="string"||typeof t!="string")return!1;let r=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(r.length!==n.length)return!1;let a=Jr.encode(r),o=Jr.encode(n),i=0;for(let l=0;l<a.length;l++)i|=a[l]^o[l];return i===0}var de=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",xt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(M,t)||[]),ke=(e,t)=>xt(e,t)[0]||null;function ic(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===M))return!0;r=r.parentNode}return!1}function Ya(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=j(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Vm(e){let t=ke(ke(e,"pPr"),"numPr");if(!t)return null;let r=de(ke(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(de(ke(t,"ilvl"),"val")||"0",10)||0}}function Wm(e){let t=new Map;for(let n of xt(e,"abstractNum")){let a=new Map;for(let o of xt(n,"lvl")){let i=Number.parseInt(de(o,"ilvl")||"0",10)||0;a.set(i,{start:Number.parseInt(de(ke(o,"start"),"val")||"1",10)||1,format:de(ke(o,"numFmt"),"val")||"decimal",text:de(ke(o,"lvlText"),"val")||`%${i+1}.`})}t.set(de(n,"abstractNumId"),a)}let r=new Map;for(let n of xt(e,"num")){let a=de(ke(n,"abstractNumId"),"val"),o=new Map(t.get(a)||[]);for(let i of xt(n,"lvlOverride")){let l=Number.parseInt(de(i,"ilvl")||"0",10)||0,s=ke(i,"lvl"),c={...o.get(l)||{start:1,format:"decimal",text:`%${l+1}.`}};s&&(c.start=Number.parseInt(de(ke(s,"start"),"val")||String(c.start),10)||c.start,c.format=de(ke(s,"numFmt"),"val")||c.format,c.text=de(ke(s,"lvlText"),"val")||c.text);let u=ke(i,"startOverride");u&&(c.start=Number.parseInt(de(u,"val")||String(c.start),10)||c.start),o.set(l,c)}r.set(de(n,"numId"),o)}return r}function sc(e,t){let r=Math.max(1,e),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function lc(e){let t=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]],r=e,n="";for(let[a,o]of t)for(;r>=a;)n+=o,r-=a;return n}function jm(e,t){return t==="lowerLetter"?sc(e,!1):t==="upperLetter"?sc(e,!0):t==="lowerRoman"?lc(e).toLowerCase():t==="upperRoman"?lc(e):String(e)}function Km(e){let t=e?Wm(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let a=t.get(String(n.numId));if(!a)return{...n,label:null,format:null};let o=r.get(n.numId)||[],i=a.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};o[n.level]=o[n.level]==null?i.start:o[n.level]+1,o.length=n.level+1,r.set(n.numId,o);let l=i.text.replace(/%([1-9])/g,(s,c)=>{let u=Number(c)-1,f=a.get(u)||i;return jm(o[u]??f.start,f.format)});return{...n,label:l,format:i.format}}}function Hm(e){let t=ke(e,"pPr"),n=de(ke(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let a=Number.parseInt(de(ke(t,"outlineLvl"),"val"),10);return Number.isInteger(a)?Math.min(a+1,6):null}function Gm(e,t){let r=[];for(let[l,s]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of xt(e,l))r.push({type:s,id:de(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let a=n?.parentNode;for(;a&&a.localName!=="tr";)a=a.parentNode;let o=a?.parentNode;for(;o&&o.localName!=="tbl";)o=o.parentNode;let i=e.ownerDocument;return{references:r,table:o?{tableIndex:Array.from(i.getElementsByTagNameNS(M,"tbl")).indexOf(o)+1,rowIndex:Array.from(o.getElementsByTagNameNS(M,"tr")).indexOf(a)+1,cellIndex:Array.from(a.getElementsByTagNameNS(M,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function cc(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of xt(e,r))de(n,"author")&&t.add(de(n,"author"));return[...t].sort()}function qm(e){let t=new Map;for(let r of xt(e,"comment")){let n=xt(r,"p");t.set(de(r,"id"),{id:de(r,"id"),author:de(r,"author")||null,date:de(r,"date")||null,text:n.map(a=>te(a)).join(`
201
+ `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function Ym(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let a=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",o=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",i=r.get(a.toUpperCase());i&&(i.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",o&&(i.parentParaId=o,i.parentCommentId=r.get(o.toUpperCase())?.id||null))}}function Zm(e,t){let r=new Map,n=new Map,a=null,o=l=>{for(let s of r.values())s.text+=l},i=l=>{for(let s of Array.from(l?.childNodes||[])){if(s?.nodeType!==1)continue;let c=s.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(de(s,"id"),{text:""});else if(c==="commentRangeEnd"){let u=de(s,"id");r.has(u)&&(n.set(u,r.get(u).text),r.delete(u))}else c==="r"?o(wr(s,{revisionView:t,boundary:a})):i(s)}};return e.forEach((l,s)=>{a=l,i(l),s<e.length-1&&r.size&&o(`
202
+ `)}),n}function Jm(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(h=>h.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(h=>p.has(h.index))}let n=1,a=e.length;t.range&&(n=Number(t.range.start??t.range[0]),a=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=a));let o=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,l=i==null?r:r.filter(p=>p.index>i),s=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=s==null?l:l.slice(0,s),u=c.length<l.length,f=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||f>0||s!=null||i!=null,m=c;if(f>0&&t.search){let p=new Set(c.map(v=>v.index)),h=new Map;for(let v of c){let w=Math.max(n,v.index-f),y=Math.min(a,v.index+f);for(let x=w;x<=y;x++){if(p.has(x))continue;let b=h.get(x)||[];b.push(v.index),h.set(x,b)}}let g=new Set([...p,...h.keys()]);m=e.filter(v=>g.has(v.index)).map(v=>p.has(v.index)?{...v,selectionRole:"match"}:{...v,selectionRole:"context",contextFor:h.get(v.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:o,returnedMatches:c.length,returnedParagraphs:m.length,truncated:u,nextAfter:u&&c.length>0?c[c.length-1].index:null,...s!=null?{limit:s}:{},...i!=null?{after:i}:{},...f>0?{around:f}:{}}}:{}}}function gi(e,t={}){let r=Ya(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=Ya(e?.commentsXml,"word/comments.xml"),a=Ya(e?.commentsExtendedXml,"word/commentsExtended.xml"),o=Ya(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),a.error&&i.push(a.error.message),o.error&&i.push(o.error.message);let l=qm(n.doc);Ym(l,a.doc);let s=Km(o.doc),c=null,u=oe(r.doc),f=t.revisionView==="rejected"?"rejected":"accepted",d=Zm(u,f),m=u.map((y,x)=>{let b=te(y,{revisionView:f}),I=Hm(y);I&&(c={level:I,text:b});let N=[...new Set([...xt(y,"commentRangeStart"),...xt(y,"commentReference")].map(D=>de(D,"id")).filter(Boolean))],T=cc(y),S=s(Vm(y)),E=de(ke(ke(y,"pPr"),"pStyle"),"val")||null,_=Gm(y,b),A=x+1,R=S?.label&&S.format!=="bullet"?S.label:null,O=c?.text||null,P=b.slice(0,t.excerptLength||120),C=I?b:R?[R,O].filter(Boolean).join(" \u2014 "):O?[O,P].filter(Boolean).join(" \u2014 "):P,k=xa(y);return{index:A,ref:`P${A}`,paragraphId:$e(y),fingerprint:rt(y,{text:b,index:A,revisionView:f}),revisionView:f,text:b,exactText:b,excerpt:P,humanReference:C,provision:R,inTable:ic(y,"tc"),table:_.table,styleId:E,headingLevel:I,nearestHeading:c,list:S,structuralReferences:_.references,hasRevisions:T.length>0,revisionAuthors:T,commentIds:N,segments:k}});for(let y of m)for(let x of y.commentIds){let b=l.get(x)||{id:x,author:null,date:null,text:""};b.paragraphIndex??(b.paragraphIndex=y.index),b.targetRef??(b.targetRef=y.ref),b.anchoredText??(b.anchoredText=d.get(x)||y.text),l.set(x,b)}let p=Jm(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let y=String(t.search).toLowerCase(),x=f==="accepted"?"rejected":"accepted",b=1,I=u.length;t.range&&(b=Number(t.range.start??t.range[0]),I=Number(t.range.end??t.range[1]));let N=0;for(let T=0;T<u.length;T++){let S=T+1;if(t.range&&(S<b||S>I)||Array.isArray(t.indexes)&&!t.indexes.includes(S))continue;let E=u[T];if(t.inTable!=null&&ic(E,"tc")!==!!t.inTable||t.revisedOnly&&cc(E).length===0)continue;let _=te(E,{revisionView:x});t.skipEmpty&&_.length===0||_.toLowerCase().includes(y)&&N++}N>0&&(p.selection.hint=f==="accepted"?`0 matches in accepted view, but ${N} match${N===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${N} match${N===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let h=[...new Set(m.flatMap(y=>y.revisionAuthors))].sort(),g=qa(e),v=g.map(y=>y.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=$n({scope:"document-parts",entries:g,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:v,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...l.values()],revisionAuthors:h,commentAuthors:[...new Set([...l.values()].map(y=>y.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:l.size,revisedParagraphs:m.filter(y=>y.hasRevisions).length},warnings:i}}var Za="http://schemas.microsoft.com/office/word/2010/wordml",$t="http://schemas.microsoft.com/office/word/2012/wordml";function hi(e){let t=Number.parseInt(String(e),10);return(Number.isFinite(t)?1879048192+(t>>>0)>>>0:1879048192).toString(16).toUpperCase().padStart(8,"0").slice(-8)}function zn(e,t,r,n,a=hi(e)){let o=t.split(" ").map(s=>s[0]).join("").toUpperCase()||"AI",i=Ue(r),l=Ue(t);return`<w:comment w:id="${e}" w:author="${l}" w:date="${n}" w:initials="${o}">
203
+ <w:p w14:paraId="${Ue(a)}" xmlns:w14="${Za}">
204
+ <w:r><w:t>${i}</w:t></w:r>
204
205
  </w:p>
205
- </w:comment>`}function Ao(e){if(!e||e.length===0)return`<w:comments xmlns:w="${E}"></w:comments>`;let t=e.map(r=>vr(r.id,r.author,r.content,r.date,r.paraId)).join(`
206
- `);return`<w:comments xmlns:w="${E}">
206
+ </w:comment>`}function wi(e){if(!e||e.length===0)return`<w:comments xmlns:w="${M}"></w:comments>`;let t=e.map(r=>zn(r.id,r.author,r.content,r.date,r.paraId)).join(`
207
+ `);return`<w:comments xmlns:w="${M}">
207
208
  ${t}
208
- </w:comments>`}function Ya(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Ne(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Ne(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${rt}">${t}</w15:commentsEx>`}function hn(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=nr(e,"w:r"),o=[],i="";for(let a of n){if(!bt(a,e,r))continue;let s=i.length,l=xt(a,{revisionView:r,boundary:e});i+=l,o.push({run:a,start:s,end:i.length})}return{fullText:i,runOffsets:o}}function Ja(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function qa(e){return String(e).replace(/[ \u00a0]/g," ")}function Sr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Za(e,t,r){let n=null,o=null,i=0,a=0;for(let{run:s,start:l,end:c}of e.runOffsets)t.start>=l&&t.start<c&&(n=s,i=t.start-l),t.end>l&&t.end<=c&&(o=s,a=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:i,endRun:o,endOffset:a}}function Qa(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let o=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(o))return{node:n,tag:o};n=n.parentNode}return null}function es(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(Qa(n,["del"]))return{found:!1,error:Sr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Qa(n,["moveFrom","moveTo"]))return{found:!1,error:Sr("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function Io(e,t){let r=String(t??""),n=Ja(e.fullText,r);if(n.length>1)return{found:!1,error:Sr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Za(e,n[0],"exact_anchor");if(s)return es(e,s)}let o=qa(r),i=qa(e.fullText),a=Ja(i,o);if(a.length>1)return{found:!1,error:Sr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Za(e,a[0],"space_equivalent_anchor");if(s)return es(e,s)}return{found:!1,error:Sr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function yr(e,t,r,n,o=!1){let i=O(e,"w:r");if(t){let s=t.cloneNode(!0);o||at(s,n),i.appendChild(s)}let a=O(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,i.appendChild(a),i}function ts(e,t,r,n,o=null,i=null,a=null){let s=o||hn(t),l=a||Io(s,r);if(!l.found||!l.startRun)return!1;let c=O(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=O(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=O(e,"w:r"),m=O(e,"w:commentReference");if(m.setAttribute("w:id",String(n)),f.appendChild(m),l.startRun===l.endRun){let w=l.startRun,b=ae(w,"w:t");if(!b)return w.parentNode.insertBefore(c,w),w.nextSibling?(w.parentNode.insertBefore(u,w.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(w.parentNode.appendChild(u),w.parentNode.appendChild(f)),!0;let g=b.textContent||"",x=g.substring(0,l.startOffset),v=g.substring(l.startOffset,l.endOffset),N=g.substring(l.endOffset),S=ae(w,"w:rPr"),y=w.parentNode;return x&&(y.insertBefore(yr(e,S,x,i,!0),w),at(S,i)),y.insertBefore(c,w),b.textContent=v,w.nextSibling?y.insertBefore(u,w.nextSibling):y.appendChild(u),y.insertBefore(f,u.nextSibling||null),N&&y.insertBefore(yr(e,S,N,i),f.nextSibling||null),!0}let d=ae(l.startRun,"w:t");if(d&&l.startOffset>0){let w=d.textContent||"",b=w.substring(0,l.startOffset),g=w.substring(l.startOffset);if(b){let x=ae(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(yr(e,x,b,i,!0),l.startRun),at(x,i)}d.textContent=g}l.startRun.parentNode.insertBefore(c,l.startRun);let p=l.endRun||l.startRun,h=ae(p,"w:t");if(h&&l.endOffset<(h.textContent||"").length){let w=h.textContent||"",b=w.substring(0,l.endOffset),g=w.substring(l.endOffset);if(h.textContent=b,g){let x=ae(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(yr(e,x,g,i),p.nextSibling):p.parentNode.appendChild(yr(e,x,g,i))}}return p.nextSibling?(p.parentNode.insertBefore(u,p.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(p.parentNode.appendChild(u),p.parentNode.appendChild(f)),!0}var Vt="http://schemas.microsoft.com/office/2006/xmlPackage",Tr="http://schemas.openxmlformats.org/package/2006/relationships";function rs(e,t){let r=de(),n=j(e,"text/xml"),o=n.doc,i=o?ne(o):null;if(n.error||i)return ee("[CommentEngine] Failed to parse package:",n.error?.message||i?.textContent),e;let a=o.documentElement,s=o.createElementNS(Vt,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(Vt,"pkg:xmlData"),c=j(t,"text/xml").doc;if(!c)return e;l.appendChild(o.importNode(c.documentElement,!0)),s.appendChild(l),a.appendChild(s);let f=ce(a,Vt,"part").find(m=>m.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let m=ce(f,Vt,"xmlData");if(m.length>0){let d=ce(m[0],Tr,"Relationships");if(d.length>0){let p=d[0],h=ce(p,Tr,"Relationship");if(!h.some(b=>b.getAttribute("Type")?.includes("comments"))){let b=0;h.forEach(x=>{let v=x.getAttribute("Id"),N=parseInt(v?.replace("rId","")||"0",10);N>b&&(b=N)});let g=o.createElementNS(Tr,"Relationship");g.setAttribute("Id",`rId${b+1}`),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g)}}}}else{let m=o.createElementNS(Vt,"pkg:part");m.setAttribute("pkg:name","/word/_rels/document.xml.rels"),m.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let d=o.createElementNS(Vt,"pkg:xmlData"),p=o.createElementNS(Tr,"Relationships"),h=o.createElementNS(Tr,"Relationship");h.setAttribute("Id","rId1"),h.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),h.setAttribute("Target","comments.xml"),p.appendChild(h),d.appendChild(p),m.appendChild(d),a.appendChild(m)}return r.serializeToString(o)}function nf(e,t){let r=j(e,"text/xml"),n=r.doc?ne(r.doc):null;if(r.error||n){let o=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(o),warnings:r.warnings,error:{code:"PARSE_ERROR",message:o}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function of(e,t,r={}){let n=r?.author||pe(),o=_r(),i=[],a=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=de(),u=nf(e,w=>`Failed to parse OXML: ${w}`);if(i.push(...u.warnings||[]),!u.xmlDoc)return ee("[CommentEngine] Parse failure:",u.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:u.error,warnings:[...i,u.warning]};let f=u.xmlDoc,m=nt(f),d=nr(f,"w:p");L(`[CommentEngine] Found ${d.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let w of t){let b=w.paragraphIndex-1;if(b<0||b>=d.length){let g=`Paragraph ${w.paragraphIndex} out of range (1-${d.length})`;i.push(g),l.push({code:"TARGET_NOT_FOUND",message:g,paragraphIndex:w.paragraphIndex});continue}p.set(b,(p.get(b)||0)+1)}let h=new Map;for(let[w,b]of t.entries()){let g=b.paragraphIndex-1;if(g<0||g>=d.length)continue;let x=d[g],v=h.get(g);v||(v=hn(x),h.set(g,v));let N=String(b.textToFind??""),S=Io(v,N),y=(p.get(g)||1)-1;if(p.set(g,y),!S.found){let M={...S.error,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(M),i.push(M.message),y===0&&h.delete(g);continue}let T=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():qo();if(!ts(f,x,N,T,v,m,S)){let M={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${b.paragraphIndex}.`,requestIndex:w+1,paragraphIndex:b.paragraphIndex};l.push(M),i.push(M.message),y===0&&h.delete(g);continue}a.push({id:T,content:b.commentContent,author:n,date:o}),s.push({requestIndex:w+1,paragraphIndex:b.paragraphIndex,text:N,resolvedBy:S.resolvedBy,start:S.start,end:S.end}),y>0?h.set(g,hn(x)):h.delete(g)}return a.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}:{oxml:c.serializeToString(f),hasChanges:!0,commentsXml:Ao(a),commentsApplied:a.length,placedComments:a,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function af(e,t){return rs(e,t)}var ns="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Er(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function wn(e,t){let r=j(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function sf(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=Er(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=Er(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function os(e,t){let r=Eo(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}function lf({commentsXml:e,commentsExtendedXml:t=null,parentCommentId:r,commentId:n,commentContent:o,author:i,date:a=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let s=wn(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let l=s.doc,c=Array.from(l.getElementsByTagNameNS("*","comment")).find(v=>Er(v,"w:id","id")===String(r));if(!c)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${r}' was not found.`}};let u=null;if(t){let v=wn(t,"word/commentsExtended.xml");if(v.error)return{status:"error",error:v.error};u=v.doc}let f=sf(l,u),m=Array.from(c.getElementsByTagNameNS(ns,"p"))[0]||Array.from(c.getElementsByTagNameNS("*","p"))[0];if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${r}' has no paragraph.`}};let d=Er(m,"w14:paraId","paraId");d?d=d.toUpperCase():(d=os(r,f),m.setAttributeNS(gn,"w14:paraId",d));let p=os(n,f),h=wn(`<w:comments xmlns:w="${ns}" xmlns:w14="${gn}">${vr(n,i,o,a,p)}</w:comments>`,"reply comment");l.documentElement.appendChild(l.importNode(h.doc.documentElement.firstChild,!0)),u||(u=wn(Ya([]),"word/commentsExtended.xml").doc);let w=u.documentElement;if(!Array.from(w.getElementsByTagNameNS("*","commentEx")).some(v=>Er(v,"w15:paraId","paraId").toUpperCase()===d)){let v=u.createElementNS(rt,"w15:commentEx");v.setAttributeNS(rt,"w15:paraId",d),v.setAttributeNS(rt,"w15:done","0"),w.appendChild(v)}let g=u.createElementNS(rt,"w15:commentEx");g.setAttributeNS(rt,"w15:paraId",p),g.setAttributeNS(rt,"w15:paraIdParent",d),g.setAttributeNS(rt,"w15:done","0"),w.appendChild(g);let x=de();return{status:"ok",hasChanges:!0,commentsXml:x.serializeToString(l),commentsExtendedXml:x.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:n,parentCommentId:String(r),paraId:p,parentParaId:d}}function Gt(e){e?.parentNode&&e.parentNode.removeChild(e)}function is(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(o=>{r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(Gt)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let i=n[o];i&&r.querySelectorAll(`${i}, ${i.replace("w:","")}`).forEach(Gt)})}return r.children.length>0?r:null}function cf(e,t,r){if(!t||!e)return e;let n=et(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=n.getElementsByTagNameNS(o,"r"),a=n.getElementsByTagNameNS(o,"ins"),s=[...Array.from(i)];for(let l of a){let c=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(c))}for(let l of s){let c=l.getElementsByTagNameNS(o,"t"),u=Array.from(c).map(f=>f.textContent).join("");if(u.includes(t)||u===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let m=f[0],d=is(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Gt(m)}}}return yt(n)}var uf={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function ff(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=uf[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||pe(),l=t;l?l=t.cloneNode(!0):l=O(e,"w:rPr");let c=null;a&&(c=O(e,"w:rPr"),Array.from(l.childNodes).forEach(m=>{m.nodeName!=="w:rPrChange"&&c.appendChild(m.cloneNode(!0))}));let u=l.getElementsByTagNameNS(o,"highlight");Array.from(u).forEach(Gt);let f=O(e,"w:highlight");if(f.setAttributeNS(o,"w:val",i),l.appendChild(f),a&&c){let m=O(e,"w:rPrChange"),d=ie(s,e);m.setAttribute("w:id",String(d.id)),m.setAttribute("w:author",d.author),m.setAttribute("w:date",d.date),m.appendChild(c);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(Gt),l.appendChild(m)}return l}function mf(e,t,r="yellow",n={}){if(!t||!e)return e;let o=et(e);if(!o)return e;let i;n?._revisionIdAllocator instanceof we?(i=n._revisionIdAllocator,Rt(o,i)):i=nt(o);let a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=f=>{let m=f.getElementsByTagNameNS(a,"t");return Array.from(m).map(d=>d.textContent).join("")},l=Array.from(o.getElementsByTagNameNS(a,"r")),c=new WeakSet,u=(f,m,d)=>{let p=f.cloneNode(!0);c.has(f)?at(p,i):c.add(f);let h=p.getElementsByTagNameNS(a,"t");Array.from(h).forEach(Gt);let w=O(o,"w:t");if(w.setAttribute("xml:space","preserve"),w.textContent=m,p.appendChild(w),d){let b=p.getElementsByTagNameNS(a,"rPr"),g=b.length>0?b[0]:null,x=ff(o,g,r,n);g?p.replaceChild(x,g):p.insertBefore(x,p.firstChild)}return p};for(let f of l){let m=s(f);if(!m)continue;let d=[],p=0;for(;p<=m.length-t.length;){let g=m.indexOf(t,p);if(g===-1)break;d.push(g),p=g+t.length}if(d.length===0)continue;let h=f.parentNode;if(!h){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let w=o.createDocumentFragment(),b=0;for(let g of d)g>b&&w.appendChild(u(f,m.slice(b,g),!1)),w.appendChild(u(f,m.slice(g,g+t.length),!0)),b=g+t.length;b<m.length&&w.appendChild(u(f,m.slice(b),!1)),h.replaceChild(w,f)}return yt(o)}var Ee="http://schemas.openxmlformats.org/wordprocessingml/2006/main",df="http://schemas.openxmlformats.org/package/2006/content-types",pf="http://schemas.openxmlformats.org/package/2006/relationships",ss="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",ls="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",cs="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",us="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",fs="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",ms="application/vnd.ms-word.commentsExtended+xml",as="word/document.xml",bn="word/numbering.xml",Ar="word/comments.xml",Po="word/commentsExtended.xml",_e="[Content_Types].xml",Le="word/_rels/document.xml.rels";function he(e,t="xml"){let r=j(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function xn(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ee&&e.localName==="sectPr"}function Co(e){return e.getElementsByTagNameNS("*","body")[0]||null}function ds(e){for(let t of Array.from(e.childNodes||[]))if(xn(t))return t;return null}function gf(e,t){let r=ds(e);r?e.insertBefore(t,r):e.appendChild(t)}function ps(e){let t=Co(e);if(!t)return;let r=ds(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function hf(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(Ee,"tc"),o=0;for(let i of Array.from(n)){let a=Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===Ee&&s.localName==="p");for(let s of a){let l=Array.from(s.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===Ee&&c.localName==="p");for(let c of l)i.insertBefore(c,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function Ro(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function wf(e){let t=de(),r=he(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>Ro(f)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let i=o.getElementsByTagNameNS("*","xmlData")[0];if(!i)throw new Error("Package document part missing pkg:xmlData");let a=Array.from(i.childNodes||[]).find(f=>f.nodeType===1);if(!a)throw new Error("Package document part missing XML payload");let s=a.getElementsByTagNameNS("*","body")[0],l=s?Array.from(s.childNodes||[]).filter(f=>f.nodeType===1&&!xn(f)):[a],c=n.find(f=>Ro(f)==="/word/numbering.xml"),u=null;if(c){let f=c.getElementsByTagNameNS("*","xmlData")[0],m=f?Array.from(f.childNodes||[]).find(d=>d.nodeType===1):null;m&&(u=t.serializeToString(m))}return{replacementNodes:l,numberingXml:u,sourceType:"package"}}function bf(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return wf(e);if(e.includes("<w:document")){let o=he(e,"document OOXML"),i=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:i?Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&!xn(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ee}">${e}</root>`,r=he(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(o=>o.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function Oo(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(a=>(a.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let i=e.createElementNS(df,"Override");return i.setAttribute("PartName",t),i.setAttribute("ContentType",r),e.documentElement.appendChild(i),!0}function ko(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,i=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(i.some(u=>(u.getAttribute("Type")||"")===t))return!1;let s=0;for(let u of i){let f=u.getAttribute("Id")||"",m=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(m)&&(s=Math.max(s,m))}let l=`rId${s+1}`,c=e.createElementNS(pf,"Relationship");return c.setAttribute("Id",l),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(l):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(l),!0}async function Re(e,t){let r=e.file(t);return r?r.async("string"):null}async function xf(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=typeof r?.mergeNumberingXml=="function"?r.mergeNumberingXml:null,i=typeof r?.onWarn=="function"?r.onWarn:Be,a=(Array.isArray(t)?t:[t]).filter(Boolean);if(a.length===0)return;let s=await Re(e,bn);s&&!o&&i("[Deprecation] Replacing an existing numbering.xml without mergeNumberingXml is deprecated and will throw in the next major version.");let l=s||null;for(let m of a){if(!l){l=m;continue}l=o?o(l,m):m}n(s?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(bn,l);let c=de(),u=await Re(e,_e);if(u){let m=he(u,_e);Oo(m,"/word/numbering.xml",ls)&&e.file(_e,c.serializeToString(m))}let f=await Re(e,Le);if(f){let m=he(f,Le);ko(m,ss,"numbering.xml",r)&&e.file(Le,c.serializeToString(m))}}async function Nf(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=de(),i=await Re(e,Ar);if(!i||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Ar,t);else{let l=he(i,"word/comments.xml (existing)"),c=he(t,"word/comments.xml (incoming)"),u=l.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(Ee,"comment")).map(m=>m.getAttribute("w:id")||m.getAttribute("id")).filter(Boolean));for(let m of Array.from(c.documentElement.getElementsByTagNameNS(Ee,"comment"))){let d=m.getAttribute("w:id")||m.getAttribute("id");if(d&&f.has(d))throw new Error(`Duplicate comment id: ${d}`);u.appendChild(l.importNode(m,!0))}e.file(Ar,o.serializeToString(l))}let a=await Re(e,_e);if(a){let l=he(a,_e);Oo(l,"/word/comments.xml",us)&&e.file(_e,o.serializeToString(l))}let s=await Re(e,Le);if(s){let l=he(s,Le);ko(l,cs,"comments.xml",r)&&e.file(Le,o.serializeToString(l))}}async function vf(e,t,r={}){if(!t)return;he(t,"word/commentsExtended.xml"),e.file(Po,t);let n=de(),o=await Re(e,_e);if(o){let a=he(o,_e);Oo(a,"/word/commentsExtended.xml",ms)&&e.file(_e,n.serializeToString(a))}let i=await Re(e,Le);if(i){let a=he(i,Le);ko(a,fs,"commentsExtended.xml",r)&&e.file(Le,n.serializeToString(a))}}async function yf(e){let t=await Re(e,as);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=he(t,as);ps(r);let n=Co(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(w=>w.nodeType===1),i=o.map((w,b)=>({node:w,index:b})).filter(w=>xn(w.node)).map(w=>w.index);if(i.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(i.length===1&&i[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let a=r.getElementsByTagNameNS(Ee,"tc");for(let w of Array.from(a))for(let b of Array.from(w.childNodes||[]).filter(g=>g.nodeType===1))if(b.namespaceURI===Ee&&b.localName==="p"&&Array.from(b.childNodes||[]).some(x=>x.nodeType===1&&x.namespaceURI===Ee&&x.localName==="p"))throw new Error("Validation failed: nested w:p");let s=r.getElementsByTagNameNS(Ee,"numPr").length>0,l=r.getElementsByTagNameNS(Ee,"commentRangeStart").length>0||r.getElementsByTagNameNS(Ee,"commentRangeEnd").length>0||r.getElementsByTagNameNS(Ee,"commentReference").length>0,c=await Re(e,bn),u=await Re(e,Ar),f=await Re(e,Po);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)he(c,bn);else if(s)throw new Error("Validation failed: numbering used but part missing");if(u){let w=he(u,Ar),b=(R,B)=>Array.from(R.getElementsByTagNameNS(Ee,B)).map($=>$.getAttribute("w:id")||$.getAttribute("id")).filter($=>$!==""),g=new Set(b(r,"commentRangeStart")),x=new Set(b(r,"commentRangeEnd")),v=new Set(b(r,"commentReference")),N=b(w,"comment"),S=new Set(N),y=R=>Array.from(R).sort((B,$)=>Number(B)-Number($)||B.localeCompare($)),T=(R,B)=>y(new Set(Array.from(R).filter($=>!B.has($)))),A=y(new Set(N.filter((R,B)=>N.indexOf(R)!==B)));if(A.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${A.join(", ")}`);let M=T(g,x),_=T(x,g);if(M.length>0||_.length>0){let R=[];throw M.length>0&&R.push(`start without end: ${M.join(", ")}`),_.length>0&&R.push(`end without start: ${_.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let F=T(new Set([...g,...x]),v);if(F.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${F.join(", ")}`);let X=T(new Set([...g,...x,...v]),S);if(X.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${X.join(", ")}`);let C=new Set;if(f){let R=he(f,Po),B=new Map;for(let V of Array.from(w.getElementsByTagNameNS("*","comment"))){let Y=V.getAttribute("w:id")||V.getAttribute("id"),oe=Array.from(V.getElementsByTagNameNS("*","p"))[0],mt=oe?.getAttribute("w14:paraId")||oe?.getAttribute("paraId");mt&&B.set(mt.toUpperCase(),Y)}let $=new Set(B.keys()),K=new Set;for(let V of Array.from(R.getElementsByTagNameNS("*","commentEx"))){let Y=V.getAttribute("w15:paraId")||V.getAttribute("paraId"),oe=V.getAttribute("w15:paraIdParent")||V.getAttribute("paraIdParent");if(!Y||!$.has(Y.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${Y||"(missing)"}`);if(K.has(Y.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${Y}`);if(K.add(Y.toUpperCase()),oe){if(!$.has(oe.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${oe}`);C.add(B.get(Y.toUpperCase()))}}}let W=T(new Set([...S].filter(R=>!C.has(R))),v);if(W.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${W.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let m=await Re(e,_e);if(!m)throw new Error(`Validation failed: missing ${_e}`);let d=he(m,_e),p=await Re(e,Le);if(!p)throw new Error(`Validation failed: missing ${Le}`);let h=he(p,Le);if(c){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(g.getAttribute("ContentType")||"")===ls),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===ss);if(!w)throw new Error("Validation failed: numbering CT override missing");if(!b)throw new Error("Validation failed: numbering rel missing")}if(u){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(g.getAttribute("ContentType")||"")===us),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===cs);if(!w)throw new Error("Validation failed: comments CT override missing");if(!b)throw new Error("Validation failed: comments rel missing")}if(f){let w=Array.from(d.getElementsByTagNameNS("*","Override")).some(g=>(g.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(g.getAttribute("ContentType")||"")===ms),b=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(g=>(g.getAttribute("Type")||"")===fs);if(!w)throw new Error("Validation failed: commentsExtended CT override missing");if(!b)throw new Error("Validation failed: commentsExtended rel missing")}}var Kt=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function hs(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
209
- `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function Sf(e={}){let t=e.originalText||"",r=hs(e.newContent||""),n=wr(r)||{type:"text",items:[]};return r.includes(`
210
- `)&&n.type!=="text"?{kind:Kt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:gs(t),hasInlineFormatting:Nn(r),hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:gs(t)?Nn(r)?{kind:Kt.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:{kind:Kt.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:vn(r),hasMarkdownTable:Ir(r)}}:vn(r)?{kind:Kt.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Nn(r),hasBlockElements:!0,hasMarkdownTable:Ir(r)}}:{kind:Kt.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:Nn(r),hasBlockElements:!1,hasMarkdownTable:Ir(r)}}}function gs(e){return!e||e.trim().length===0}function Ir(e){if(!e||!e.includes("|"))return!1;let t=Xe(e);return t.rows.length>0||t.headers.length>0}function Nn(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function vn(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),i=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),a=/^[\s]*\([a-z]\)\s+/m.test(e),s=/\|.*\|.*\n/.test(e),l=/^#{1,9}\s/m.test(e),c=e.includes(`
209
+ </w:comments>`}function uc(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Ue(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Ue(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${$t}">${t}</w15:commentsEx>`}function Qr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=wn(e,"w:r"),a=[],o="";for(let i of n){if(!hr(i,e,r))continue;let l=o.length,s=wr(i,{revisionView:r,boundary:e});o+=s,a.push({run:i,start:l,end:o.length})}return{fullText:o,runOffsets:a}}function fc(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function dc(e){return String(e).replace(/[ \u00a0]/g," ")}function Vn(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function mc(e,t,r){let n=null,a=null,o=0,i=0;for(let{run:l,start:s,end:c}of e.runOffsets)t.start>=s&&t.start<c&&(n=l,o=t.start-s),t.end>s&&t.end<=c&&(a=l,i=t.end-s);return!n||!a?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:o,endRun:a,endOffset:i}}function pc(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let a=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(a))return{node:n,tag:a};n=n.parentNode}return null}function gc(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(pc(n,["del"]))return{found:!1,error:Vn("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(pc(n,["moveFrom","moveTo"]))return{found:!1,error:Vn("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function Wn(e,t){let r=String(t??""),n=fc(e.fullText,r);if(n.length>1)return{found:!1,error:Vn("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let l=mc(e,n[0],"exact_anchor");if(l)return gc(e,l)}let a=dc(r),o=dc(e.fullText),i=fc(o,a);if(i.length>1)return{found:!1,error:Vn("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let l=mc(e,i[0],"space_equivalent_anchor");if(l)return gc(e,l)}return{found:!1,error:Vn("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function Xn(e,t,r,n,a=!1){let o=L(e,"w:r");if(t){let l=t.cloneNode(!0);a||At(l,n),o.appendChild(l)}let i=L(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,o.appendChild(i),o}function hc(e,t,r,n,a=null,o=null,i=null){let l=a||Qr(t),s=i||Wn(l,r);if(!s.found||!s.startRun)return!1;let c=L(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let u=L(e,"w:commentRangeEnd");u.setAttribute("w:id",String(n));let f=L(e,"w:r"),d=L(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),f.appendChild(d),s.startRun===s.endRun){let g=s.startRun,v=Ee(g,"w:t");if(!v)return g.parentNode.insertBefore(c,g),g.nextSibling?(g.parentNode.insertBefore(u,g.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(g.parentNode.appendChild(u),g.parentNode.appendChild(f)),!0;let w=v.textContent||"",y=w.substring(0,s.startOffset),x=w.substring(s.startOffset,s.endOffset),b=w.substring(s.endOffset),I=Ee(g,"w:rPr"),N=g.parentNode;return y&&(N.insertBefore(Xn(e,I,y,o,!0),g),At(I,o)),N.insertBefore(c,g),v.textContent=x,g.nextSibling?N.insertBefore(u,g.nextSibling):N.appendChild(u),N.insertBefore(f,u.nextSibling||null),b&&N.insertBefore(Xn(e,I,b,o),f.nextSibling||null),!0}let m=Ee(s.startRun,"w:t");if(m&&s.startOffset>0){let g=m.textContent||"",v=g.substring(0,s.startOffset),w=g.substring(s.startOffset);if(v){let y=Ee(s.startRun,"w:rPr");s.startRun.parentNode.insertBefore(Xn(e,y,v,o,!0),s.startRun),At(y,o)}m.textContent=w}s.startRun.parentNode.insertBefore(c,s.startRun);let p=s.endRun||s.startRun,h=Ee(p,"w:t");if(h&&s.endOffset<(h.textContent||"").length){let g=h.textContent||"",v=g.substring(0,s.endOffset),w=g.substring(s.endOffset);if(h.textContent=v,w){let y=Ee(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(Xn(e,y,w,o),p.nextSibling):p.parentNode.appendChild(Xn(e,y,w,o))}}return p.nextSibling?(p.parentNode.insertBefore(u,p.nextSibling),u.parentNode.insertBefore(f,u.nextSibling)):(p.parentNode.appendChild(u),p.parentNode.appendChild(f)),!0}var en="http://schemas.microsoft.com/office/2006/xmlPackage",jn="http://schemas.openxmlformats.org/package/2006/relationships";function wc(e,t){let r=ce(),n=j(e,"text/xml"),a=n.doc,o=a?Ne(a):null;if(n.error||o)return ye("[CommentEngine] Failed to parse package:",n.error?.message||o?.textContent),e;let i=a.documentElement,l=a.createElementNS(en,"pkg:part");l.setAttribute("pkg:name","/word/comments.xml"),l.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let s=a.createElementNS(en,"pkg:xmlData"),c=j(t,"text/xml").doc;if(!c)return e;s.appendChild(a.importNode(c.documentElement,!0)),l.appendChild(s),i.appendChild(l);let f=Pe(i,en,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let d=Pe(f,en,"xmlData");if(d.length>0){let m=Pe(d[0],jn,"Relationships");if(m.length>0){let p=m[0],h=Pe(p,jn,"Relationship");if(!h.some(v=>v.getAttribute("Type")?.includes("comments"))){let v=0;h.forEach(y=>{let x=y.getAttribute("Id"),b=parseInt(x?.replace("rId","")||"0",10);b>v&&(v=b)});let w=a.createElementNS(jn,"Relationship");w.setAttribute("Id",`rId${v+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=a.createElementNS(en,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=a.createElementNS(en,"pkg:xmlData"),p=a.createElementNS(jn,"Relationships"),h=a.createElementNS(jn,"Relationship");h.setAttribute("Id","rId1"),h.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),h.setAttribute("Target","comments.xml"),p.appendChild(h),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(a)}function Qm(e,t){let r=j(e,"text/xml"),n=r.doc?Ne(r.doc):null;if(r.error||n){let a=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(a),warnings:r.warnings,error:{code:"PARSE_ERROR",message:a}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function vi(e,t,r={}){let n=r?.author||re(),a=ca(),o=[],i=[],l=[],s=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=ce(),u=Qm(e,g=>`Failed to parse OXML: ${g}`);if(o.push(...u.warnings||[]),!u.xmlDoc)return ye("[CommentEngine] Parse failure:",u.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:u.error,warnings:[...o,u.warning]};let f=u.xmlDoc,d=Ht(f),m=wn(f,"w:p");V(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let g of t){let v=g.paragraphIndex-1;if(v<0||v>=m.length){let w=`Paragraph ${g.paragraphIndex} out of range (1-${m.length})`;o.push(w),s.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:g.paragraphIndex});continue}p.set(v,(p.get(v)||0)+1)}let h=new Map;for(let[g,v]of t.entries()){let w=v.paragraphIndex-1;if(w<0||w>=m.length)continue;let y=m[w],x=h.get(w);x||(x=Qr(y),h.set(w,x));let b=String(v.textToFind??""),I=Wn(x,b),N=(p.get(w)||1)-1;if(p.set(w,N),!I.found){let E={...I.error,requestIndex:g+1,paragraphIndex:v.paragraphIndex};s.push(E),o.push(E.message),N===0&&h.delete(w);continue}let T=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():ms();if(!hc(f,y,b,T,x,d,I)){let E={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${v.paragraphIndex}.`,requestIndex:g+1,paragraphIndex:v.paragraphIndex};s.push(E),o.push(E.message),N===0&&h.delete(w);continue}i.push({id:T,content:v.commentContent,author:n,date:a}),l.push({requestIndex:g+1,paragraphIndex:v.paragraphIndex,text:b,resolvedBy:I.resolvedBy,start:I.start,end:I.end}),N>0?h.set(w,Qr(y)):h.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:o,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}:{oxml:c.serializeToString(f),hasChanges:!0,commentsXml:wi(i),commentsApplied:i.length,placedComments:i,warnings:o,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}}function ep(e,t){return wc(e,t)}var vc="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Kn(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function Ja(e,t){let r=j(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function tp(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let a=Kn(n,"w14:paraId","paraId");a&&r.add(a.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let a=Kn(n,"w15:paraId","paraId");a&&r.add(a.toUpperCase())}return r}function yc(e,t){let r=hi(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}function yi({commentsXml:e,commentsExtendedXml:t=null,parentCommentId:r,commentId:n,commentContent:a,author:o,date:i=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let l=Ja(e,"word/comments.xml");if(l.error)return{status:"error",error:l.error};let s=l.doc,c=Array.from(s.getElementsByTagNameNS("*","comment")).find(x=>Kn(x,"w:id","id")===String(r));if(!c)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${r}' was not found.`}};let u=null;if(t){let x=Ja(t,"word/commentsExtended.xml");if(x.error)return{status:"error",error:x.error};u=x.doc}let f=tp(s,u),d=Array.from(c.getElementsByTagNameNS(vc,"p"))[0]||Array.from(c.getElementsByTagNameNS("*","p"))[0];if(!d)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${r}' has no paragraph.`}};let m=Kn(d,"w14:paraId","paraId");m?m=m.toUpperCase():(m=yc(r,f),d.setAttributeNS(Za,"w14:paraId",m));let p=yc(n,f),h=Ja(`<w:comments xmlns:w="${vc}" xmlns:w14="${Za}">${zn(n,o,a,i,p)}</w:comments>`,"reply comment");s.documentElement.appendChild(s.importNode(h.doc.documentElement.firstChild,!0)),u||(u=Ja(uc([]),"word/commentsExtended.xml").doc);let g=u.documentElement;if(!Array.from(g.getElementsByTagNameNS("*","commentEx")).some(x=>Kn(x,"w15:paraId","paraId").toUpperCase()===m)){let x=u.createElementNS($t,"w15:commentEx");x.setAttributeNS($t,"w15:paraId",m),x.setAttributeNS($t,"w15:done","0"),g.appendChild(x)}let w=u.createElementNS($t,"w15:commentEx");w.setAttributeNS($t,"w15:paraId",p),w.setAttributeNS($t,"w15:paraIdParent",m),w.setAttributeNS($t,"w15:done","0"),g.appendChild(w);let y=ce();return{status:"ok",hasChanges:!0,commentsXml:y.serializeToString(s),commentsExtendedXml:y.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:n,parentCommentId:String(r),paraId:p,parentParaId:m}}function tn(e){e?.parentNode&&e.parentNode.removeChild(e)}function xc(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(a=>{r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(tn)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(a=>{let o=n[a];o&&r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(tn)})}return r.children.length>0?r:null}function rp(e,t,r){if(!t||!e)return e;let n=Ft(e);if(!n)return e;let a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",o=n.getElementsByTagNameNS(a,"r"),i=n.getElementsByTagNameNS(a,"ins"),l=[...Array.from(o)];for(let s of i){let c=s.getElementsByTagNameNS(a,"r");l.push(...Array.from(c))}for(let s of l){let c=s.getElementsByTagNameNS(a,"t"),u=Array.from(c).map(f=>f.textContent).join("");if(u.includes(t)||u===t){let f=s.getElementsByTagNameNS(a,"rPr");if(f.length>0){let d=f[0],m=xc(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):tn(d)}}}return Ir(n)}var np={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function ap(e,t,r="yellow",n={}){let a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",o=np[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,l=n?.author||re(),s=t;s?s=t.cloneNode(!0):s=L(e,"w:rPr");let c=null;i&&(c=L(e,"w:rPr"),Array.from(s.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let u=s.getElementsByTagNameNS(a,"highlight");Array.from(u).forEach(tn);let f=L(e,"w:highlight");if(f.setAttributeNS(a,"w:val",o),s.appendChild(f),i&&c){let d=L(e,"w:rPrChange"),m=ae(l,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=s.getElementsByTagNameNS(a,"rPrChange");Array.from(p).forEach(tn),s.appendChild(d)}return s}function xi(e,t,r="yellow",n={}){if(!t||!e)return e;let a=Ft(e);if(!a)return e;let o;n?._revisionIdAllocator instanceof Se?(o=n._revisionIdAllocator,kt(a,o)):o=Ht(a);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",l=f=>{let d=f.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},s=Array.from(a.getElementsByTagNameNS(i,"r")),c=new WeakSet,u=(f,d,m)=>{let p=f.cloneNode(!0);c.has(f)?At(p,o):c.add(f);let h=p.getElementsByTagNameNS(i,"t");Array.from(h).forEach(tn);let g=L(a,"w:t");if(g.setAttribute("xml:space","preserve"),g.textContent=d,p.appendChild(g),m){let v=p.getElementsByTagNameNS(i,"rPr"),w=v.length>0?v[0]:null,y=ap(a,w,r,n);w?p.replaceChild(y,w):p.insertBefore(y,p.firstChild)}return p};for(let f of s){let d=l(f);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let h=f.parentNode;if(!h){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let g=a.createDocumentFragment(),v=0;for(let w of m)w>v&&g.appendChild(u(f,d.slice(v,w),!1)),g.appendChild(u(f,d.slice(w,w+t.length),!0)),v=w+t.length;v<d.length&&g.appendChild(u(f,d.slice(v),!1)),h.replaceChild(g,f)}return Ir(a)}var He="http://schemas.openxmlformats.org/wordprocessingml/2006/main",op="http://schemas.openxmlformats.org/package/2006/content-types",ip="http://schemas.openxmlformats.org/package/2006/relationships",Nc="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",Ic="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",Tc="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",Sc="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",Ec="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",Ac="application/vnd.ms-word.commentsExtended+xml",bc="word/document.xml",Qa="word/numbering.xml",Hn="word/comments.xml",bi="word/commentsExtended.xml",ut="[Content_Types].xml",ft="word/_rels/document.xml.rels";function Me(e,t="xml"){let r=j(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function eo(e){return!!e&&e.nodeType===1&&e.namespaceURI===He&&e.localName==="sectPr"}function Ii(e){return e.getElementsByTagNameNS("*","body")[0]||null}function Rc(e){for(let t of Array.from(e.childNodes||[]))if(eo(t))return t;return null}function sp(e,t){let r=Rc(e);r?e.insertBefore(t,r):e.appendChild(t)}function to(e){let t=Ii(e);if(!t)return;let r=Rc(t);if(!r)return;let n=r.nextSibling;for(;n;){let a=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=a}}function lp(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(He,"tc"),a=0;for(let o of Array.from(n)){let i=Array.from(o.childNodes||[]).filter(l=>l.nodeType===1&&l.namespaceURI===He&&l.localName==="p");for(let l of i){let s=Array.from(l.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===He&&c.localName==="p");for(let c of s)o.insertBefore(c,l),a+=1}}return a>0&&r(`[Sanitize] Fixed ${a} nested w:p element(s) in table cells`),a}function Ni(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function cp(e){let t=ce(),r=Me(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),a=n.find(f=>Ni(f)==="/word/document.xml");if(!a)throw new Error("Package output missing /word/document.xml part");let o=a.getElementsByTagNameNS("*","xmlData")[0];if(!o)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(o.childNodes||[]).find(f=>f.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let l=i.getElementsByTagNameNS("*","body")[0],s=l?Array.from(l.childNodes||[]).filter(f=>f.nodeType===1&&!eo(f)):[i],c=n.find(f=>Ni(f)==="/word/numbering.xml"),u=null;if(c){let f=c.getElementsByTagNameNS("*","xmlData")[0],d=f?Array.from(f.childNodes||[]).find(m=>m.nodeType===1):null;d&&(u=t.serializeToString(d))}return{replacementNodes:s,numberingXml:u,sourceType:"package"}}function Ti(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return cp(e);if(e.includes("<w:document")){let a=Me(e,"document OOXML"),o=a.getElementsByTagNameNS("*","body")[0];return{replacementNodes:o?Array.from(o.childNodes||[]).filter(l=>l.nodeType===1&&!eo(l)):Array.from(a.childNodes||[]).filter(l=>l.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${He}">${e}</root>`,r=Me(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(a=>a.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function Si(e,t,r){let a=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(a)return(a.getAttribute("ContentType")||"")===r?!1:(a.setAttribute("ContentType",r),!0);let o=e.createElementNS(op,"Override");return o.setAttribute("PartName",t),o.setAttribute("ContentType",r),e.documentElement.appendChild(o),!0}function Ei(e,t,r,n={}){let a=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,o=Array.from(a.getElementsByTagNameNS("*","Relationship"));if(o.some(u=>(u.getAttribute("Type")||"")===t))return!1;let l=0;for(let u of o){let f=u.getAttribute("Id")||"",d=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(d)&&(l=Math.max(l,d))}let s=`rId${l+1}`,c=e.createElementNS(ip,"Relationship");return c.setAttribute("Id",s),c.setAttribute("Type",t),c.setAttribute("Target",r),a.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(s):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(s),!0}async function Ye(e,t){let r=e.file(t);return r?r.async("string"):null}async function Ai(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},a=typeof r?.mergeNumberingXml=="function"?r.mergeNumberingXml:null,o=typeof r?.onWarn=="function"?r.onWarn:mt,i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0)return;let l=await Ye(e,Qa);l&&!a&&o("[Deprecation] Replacing an existing numbering.xml without mergeNumberingXml is deprecated and will throw in the next major version.");let s=l||null;for(let d of i){if(!s){s=d;continue}s=a?a(s,d):d}n(l?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(Qa,s);let c=ce(),u=await Ye(e,ut);if(u){let d=Me(u,ut);Si(d,"/word/numbering.xml",Ic)&&e.file(ut,c.serializeToString(d))}let f=await Ye(e,ft);if(f){let d=Me(f,ft);Ei(d,Nc,"numbering.xml",r)&&e.file(ft,c.serializeToString(d))}}async function Ri(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let a=ce(),o=await Ye(e,Hn);if(!o||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Hn,t);else{let s=Me(o,"word/comments.xml (existing)"),c=Me(t,"word/comments.xml (incoming)"),u=s.documentElement,f=new Set(Array.from(u.getElementsByTagNameNS(He,"comment")).map(d=>d.getAttribute("w:id")||d.getAttribute("id")).filter(Boolean));for(let d of Array.from(c.documentElement.getElementsByTagNameNS(He,"comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m&&f.has(m))throw new Error(`Duplicate comment id: ${m}`);u.appendChild(s.importNode(d,!0))}e.file(Hn,a.serializeToString(s))}let i=await Ye(e,ut);if(i){let s=Me(i,ut);Si(s,"/word/comments.xml",Sc)&&e.file(ut,a.serializeToString(s))}let l=await Ye(e,ft);if(l){let s=Me(l,ft);Ei(s,Tc,"comments.xml",r)&&e.file(ft,a.serializeToString(s))}}async function Pi(e,t,r={}){if(!t)return;Me(t,"word/commentsExtended.xml"),e.file(bi,t);let n=ce(),a=await Ye(e,ut);if(a){let i=Me(a,ut);Si(i,"/word/commentsExtended.xml",Ac)&&e.file(ut,n.serializeToString(i))}let o=await Ye(e,ft);if(o){let i=Me(o,ft);Ei(i,Ec,"commentsExtended.xml",r)&&e.file(ft,n.serializeToString(i))}}async function rn(e){let t=await Ye(e,bc);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=Me(t,bc);to(r);let n=Ii(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let a=Array.from(n.childNodes||[]).filter(g=>g.nodeType===1),o=a.map((g,v)=>({node:g,index:v})).filter(g=>eo(g.node)).map(g=>g.index);if(o.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(o.length===1&&o[0]!==a.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(He,"tc");for(let g of Array.from(i))for(let v of Array.from(g.childNodes||[]).filter(w=>w.nodeType===1))if(v.namespaceURI===He&&v.localName==="p"&&Array.from(v.childNodes||[]).some(y=>y.nodeType===1&&y.namespaceURI===He&&y.localName==="p"))throw new Error("Validation failed: nested w:p");let l=r.getElementsByTagNameNS(He,"numPr").length>0,s=r.getElementsByTagNameNS(He,"commentRangeStart").length>0||r.getElementsByTagNameNS(He,"commentRangeEnd").length>0||r.getElementsByTagNameNS(He,"commentReference").length>0,c=await Ye(e,Qa),u=await Ye(e,Hn),f=await Ye(e,bi);if(f&&!u)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)Me(c,Qa);else if(l)throw new Error("Validation failed: numbering used but part missing");if(u){let g=Me(u,Hn),v=(C,k)=>Array.from(C.getElementsByTagNameNS(He,k)).map(D=>D.getAttribute("w:id")||D.getAttribute("id")).filter(D=>D!==""),w=new Set(v(r,"commentRangeStart")),y=new Set(v(r,"commentRangeEnd")),x=new Set(v(r,"commentReference")),b=v(g,"comment"),I=new Set(b),N=C=>Array.from(C).sort((k,D)=>Number(k)-Number(D)||k.localeCompare(D)),T=(C,k)=>N(new Set(Array.from(C).filter(D=>!k.has(D)))),S=N(new Set(b.filter((C,k)=>b.indexOf(C)!==k)));if(S.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${S.join(", ")}`);let E=T(w,y),_=T(y,w);if(E.length>0||_.length>0){let C=[];throw E.length>0&&C.push(`start without end: ${E.join(", ")}`),_.length>0&&C.push(`end without start: ${_.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${C.join("; ")})`)}let A=T(new Set([...w,...y]),x);if(A.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${A.join(", ")}`);let R=T(new Set([...w,...y,...x]),I);if(R.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${R.join(", ")}`);let O=new Set;if(f){let C=Me(f,bi),k=new Map;for(let H of Array.from(g.getElementsByTagNameNS("*","comment"))){let G=H.getAttribute("w:id")||H.getAttribute("id"),Z=Array.from(H.getElementsByTagNameNS("*","p"))[0],pe=Z?.getAttribute("w14:paraId")||Z?.getAttribute("paraId");pe&&k.set(pe.toUpperCase(),G)}let D=new Set(k.keys()),z=new Set;for(let H of Array.from(C.getElementsByTagNameNS("*","commentEx"))){let G=H.getAttribute("w15:paraId")||H.getAttribute("paraId"),Z=H.getAttribute("w15:paraIdParent")||H.getAttribute("paraIdParent");if(!G||!D.has(G.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${G||"(missing)"}`);if(z.has(G.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${G}`);if(z.add(G.toUpperCase()),Z){if(!D.has(Z.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${Z}`);O.add(k.get(G.toUpperCase()))}}}let P=T(new Set([...I].filter(C=>!O.has(C))),x);if(P.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${P.join(", ")}`)}else if(s)throw new Error("Validation failed: comments used but part missing");let d=await Ye(e,ut);if(!d)throw new Error(`Validation failed: missing ${ut}`);let m=Me(d,ut),p=await Ye(e,ft);if(!p)throw new Error(`Validation failed: missing ${ft}`);let h=Me(p,ft);if(c){let g=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===Ic),v=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Nc);if(!g)throw new Error("Validation failed: numbering CT override missing");if(!v)throw new Error("Validation failed: numbering rel missing")}if(u){let g=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===Sc),v=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Tc);if(!g)throw new Error("Validation failed: comments CT override missing");if(!v)throw new Error("Validation failed: comments rel missing")}if(f){let g=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(w.getAttribute("ContentType")||"")===Ac),v=Array.from(h.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Ec);if(!g)throw new Error("Validation failed: commentsExtended CT override missing");if(!v)throw new Error("Validation failed: commentsExtended rel missing")}}var nn=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function Cc(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
210
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function up(e={}){let t=e.originalText||"",r=Cc(e.newContent||""),n=kn(r)||{type:"text",items:[]};return r.includes(`
211
+ `)&&n.type!=="text"?{kind:nn.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:Pc(t),hasInlineFormatting:ro(r),hasBlockElements:no(r),hasMarkdownTable:Gn(r)}}:Pc(t)?ro(r)?{kind:nn.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:no(r),hasMarkdownTable:Gn(r)}}:{kind:nn.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:no(r),hasMarkdownTable:Gn(r)}}:no(r)?{kind:nn.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:ro(r),hasBlockElements:!0,hasMarkdownTable:Gn(r)}}:{kind:nn.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:ro(r),hasBlockElements:!1,hasMarkdownTable:Gn(r)}}}function Pc(e){return!e||e.trim().length===0}function Gn(e){if(!e||!e.includes("|"))return!1;let t=et(e);return t.rows.length>0||t.headers.length>0}function ro(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function no(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),a=/^[\s]*[A-Za-z]\.\s+/m.test(e),o=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),i=/^[\s]*\([a-z]\)\s+/m.test(e),l=/\|.*\|.*\n/.test(e),s=/^#{1,9}\s/m.test(e),c=e.includes(`
211
212
 
212
- `);return t||r||n||o||i||a||s||l||c}function Tf(e){if(!e||typeof e!="string")return null;let t=e.match(/\b(?:w14:paraId|w:paraId|paraId)="([^"]+)"/i);return t?t[1]:null}var Mo=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let o=String(t);this.activeReceipt.revisionItems.some(i=>i.id===o&&i.kind===r&&i.partName===n)||this.activeReceipt.revisionItems.push({id:o,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function Ef(e,t=null,r=null,n="not_attempted"){return{operationIndex:typeof e=="number"?e:1,...t?{operationId:String(t)}:{},attemptedDisposition:n,finalDisposition:n,committed:!1,...r?{authorUsed:String(r)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}function Af(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(l=>l&&l.committed===!0&&l.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)n.add(c[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let l=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=l.exec(e.commentsXml))!==null;)o.add(c[1])}let i=new Set,a=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
213
- `);if(a){let l=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=l.exec(a))!==null;)i.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=l.exec(e.documentXml))!==null;)i.add(c[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=l.exec(e.relationshipsXml))!==null;)s.add(c[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let c of l.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let c of l.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let c of l.numberingIds)if(!i.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let c of l.relationshipIds)if(!s.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}async function ws(e,t,r,n={}){let o=await uo(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let i=Array.isArray(o?.warnings)?o.warnings:[];return se({...o,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function ww(e,t,r,n={}){let o=typeof e=="string"?e:"",i=typeof r=="string"?r:String(r||""),a;try{a=Xe(i)}catch{a={headers:[],rows:[]}}return(a?.headers?.length||0)>0||(a?.rows?.length||0)>0?{...await ws(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function bw(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,i=n.sanitizeInput===!0?fo(r):r,a=i!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=bo({oxml:e,originalText:t,modifiedText:i,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,c=[];if(s&&l){let h=await un(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(h?.hasChanges&&h?.oxml){let w=it(h.oxml,{includeNumbering:h.includeNumbering??!0,numberingXml:h.numberingXml}),b=Array.isArray(h?.warnings)?h.warnings:[];return se({oxml:w,hasChanges:!0,warnings:[...a,...b],listStructuralFallbackApplied:!0,listStructuralFallbackKey:h.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:h.numberingXml||null})}c=Array.isArray(h?.warnings)?h.warnings:[]}let u=await ws(e,t,r,n);if(!s)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(l)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(u?.hasChanges)return{...u,listStructuralFallbackApplied:!1};let f=await un(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let h=Array.isArray(u?.warnings)?u.warnings:[],w=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...h,...w],listStructuralFallbackApplied:!1}}let m=it(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),d=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return se({...u,oxml:m,hasChanges:!0,warnings:[...d,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{Pt as ContainerKind,Yo as ContentType,ke as DiffOp,E as NS_W,Je as NumberingService,Mo as ReceiptCollector,ar as ReconciliationPipeline,Kt as RoutePlanKind,D as RunKind,Oe as WORD_MAIN_NS,oo as acceptTrackedChangesInOoxml,Wr as analyzeStructuredContent,lf as applyCommentReplyToParts,cf as applyFormattingRemovalToOoxml,mf as applyHighlightToOoxml,ws as applyRedlineToOxml,bw as applyRedlineToOxmlWithListFallback,Hu as areRevisionTokensEqual,vr as buildCommentElement,Ao as buildCommentsPartXml,Ou as buildExplicitDecimalMultilevelNumberingXml,Qc as buildListMarkdown,Sf as buildReconciliationPlan,So as buildRevisionTokenFraming,bo as buildSingleLineListStructuralFallbackPlan,Vc as buildTargetReferenceSnapshot,au as clearSingleLineListFallbackExplicitSequence,Oa as collectContiguousListParagraphBlock,Uu as computeDocumentPartsRevisionToken,ja as computeRevisionToken,To as computeRevisionTokenSync,Ps as configureLogger,Rs as configureXmlProvider,zr as containsTrackedChanges,Eu as createDynamicNumberingIdState,Ef as createEmptyReceipt,St as createParagraphFingerprint,kc as deleteCommentsByAuthorInOoxml,su as enforceListBindingOnParagraphNodes,Nf as ensureCommentsArtifactsInZip,vf as ensureCommentsExtendedArtifactsInZip,xf as ensureNumberingArtifactsInZip,Ne as escapeXml,un as executeSingleLineListStructuralFallback,fe as extractCanonicalParagraphText,dn as extractDocumentPartsEntries,Cu as extractFirstParagraphNumId,Tf as extractParagraphIdFromOoxml,Kr as extractParagraphRevisionSegments,bf as extractReplacementNodesFromOoxml,Dt as findContainingWordElement,mo as findParagraphByBestTextMatch,Ea as findParagraphByReference,on as findParagraphByStrictText,an as findStrictTargetCandidates,ht as generateTableOoxml,Co as getBodyElementFromDocument,pe as getDefaultAuthor,Te as getDocumentParagraphNodes,Ro as getPackagePartName,Tt as getParagraphId,tt as getParagraphListInfo,ue as getParagraphText,En as getPlatform,Dn as getTrackedChangeAuthors,wo as hasListItems,Qt as inferNumberingStyleFromMarker,Su as inferTableReplacementParagraphBlock,kt as ingestOoxml,Wu as ingestWordOoxmlToMarkdown,Wa as ingestWordOoxmlToMarkdownResult,zu as ingestWordOoxmlToPlainText,za as ingestWordOoxmlToPlainTextResult,of as injectCommentsIntoOoxml,af as injectCommentsIntoPackage,gf as insertBodyElementBeforeSectPr,rf as inspectDocumentParts,La as isLikelyStructuredTableSourceParagraph,go as isMarkdownTableText,bt as isNodeVisibleInRevisionView,Mu as mergeNumberingXmlBySchemaOrder,ps as normalizeBodySectionOrderStandalone,hs as normalizeContentEscapesForRouting,eu as normalizeListItemsWithLevels,Ua as normalizeOpcEntryName,H as normalizeWhitespaceForTargeting,Ru as overwriteParagraphNumIds,wr as parseMarkdownListContent,et as parseOoxml,j as parseOoxmlSafe,ho as parseParagraphReference,Zc as planListInsertionOnlyEdit,Bl as planStructuredReplacement,Ie as preprocessMarkdown,xt as readCanonicalRunText,ww as reconcileMarkdownTableOoxml,Af as reconcileReceiptsAgainstOutput,iu as recordSingleLineListFallbackExplicitSequence,io as rejectTrackedChangesInOoxml,ku as remapNumberingPayloadForDocument,is as removeFormattingFromRPr,xr as reserveNextNumberingId,Iu as reserveNextNumberingIdPair,Gc as resolveParagraphRangeByRefs,ou as resolveSingleLineListFallbackNumberingAction,Aa as resolveTargetParagraph,po as resolveTargetParagraphWithSnapshot,fo as sanitizeAiResponse,hf as sanitizeNestedParagraphsInTables,yt as serializeOoxml,$e as serializeToOoxml,ks as setDefaultAuthor,Ms as setPlatform,Wc as splitLeadingParagraphMarker,zc as stripLeadingParagraphMarker,Ra as stripRedundantLeadingListMarkers,ru as stripSingleLineListMarkerPrefix,qc as synthesizeExpandedListScopeEdit,Tu as synthesizeTableMarkdownFromMultilineCellEdit,yf as validateDocxPackage,bu as validateRedlineOoxml,ju as validateRevisionToken,it as wrapInDocumentFragment};
213
+ `);return t||r||n||a||o||i||l||s||c}function fp(e){if(!e||typeof e!="string")return null;let t=e.match(/\b(?:w14:paraId|w:paraId|paraId)="([^"]+)"/i);return t?t[1]:null}var qn=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let a=String(t);this.activeReceipt.revisionItems.some(o=>o.id===a&&o.kind===r&&o.partName===n)||this.activeReceipt.revisionItems.push({id:a,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function Ce(e,t=null,r=null,n="not_attempted"){return{operationIndex:typeof e=="number"?e:1,...t?{operationId:String(t)}:{},attemptedDisposition:n,finalDisposition:n,committed:!1,...r?{authorUsed:String(r)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}function Yn(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(s=>s&&s.committed===!0&&s.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)n.add(c[1])}let a=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let s=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.commentsXml))!==null;)a.add(c[1])}let o=new Set,i=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
214
+ `);if(i){let s=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=s.exec(i))!==null;)o.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)o.add(c[1])}let l=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let s=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=s.exec(e.relationshipsXml))!==null;)l.add(c[1])}for(let s of r){if(Array.isArray(s.revisionItems)){for(let c of s.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(s.commentIds)){for(let c of s.commentIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(s.numberingIds)){for(let c of s.numberingIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(s.relationshipIds)){for(let c of s.relationshipIds)if(!l.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var dp=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function mp(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let a=n?.code||"UNKNOWN";r.set(a,(r.get(a)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,a])=>({code:n,count:a}))}}function pp(e){return dp[e]||["operation","manual_document_resolution","inspect_error"]}function bt(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[a,o,i]=pp(n),l={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(l[m]=p);let u={action:i,sameArgumentsSafe:!1,requiresReinspection:o==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:o==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},f=mp(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||a,category:r.category||o,...l,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...f?{issueSummary:f}:{},recovery:u}}function or({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:a=null}={}){let o=Number.isInteger(a)?a:Math.max(r.length,n.length),i=new Set(r.map(f=>f?.index).filter(Number.isInteger)),l=r.filter(f=>f?.status==="error").map(f=>f.index).filter(Number.isInteger),s=n.filter(f=>f?.committed===!0).map(f=>f.operationIndex).filter(Number.isInteger),c=[];for(let f=1;f<=o;f+=1)i.has(f)||c.push(f);let u=t||e||s.length===0?"original":"output";return{base:u,committedIndexes:s,failedIndexes:l,unattemptedIndexes:c,replayWholeBatch:u==="original",sameArgumentsSafe:!1}}function Or(e,t,r){return bt({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function ao(e,t,r,n,a={}){return bt({code:e,message:t,field:r,...a,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function gp(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let a=e.indexOf(t,n);if(a<0)break;r.push(a),n=a+1}return r}function Zn(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function hp(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let a=!0;for(let o=0;o<t.length;o+=1){let i=e[n+o],l=t[o];if(i!==l&&!Zn(i,l)){a=!1;break}}a&&r.push(n)}return r}function wp(e,t){let r=gp(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:hp(e,t),matchMode:"space_equivalent"}}function vp(e,t,r){let n=r.split(""),a=0;for(;a<t.length&&a<r.length&&(t[a]===r[a]||Zn(t[a],r[a]));)Zn(e[a],r[a])&&(n[a]=e[a]),a+=1;let o=t.length-1,i=r.length-1;for(;o>=a&&i>=a&&(t[o]===r[i]||Zn(t[o],r[i]));)Zn(e[o],r[i])&&(n[i]=e[o]),o-=1,i-=1;return n.join("")}function yp(e,t,r){let n=Math.max(0,t-40),a=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,a)}}function Oc(e,t,r,n=120){let a=String(e??""),o=Math.max(0,Math.min(a.length,t)),i=Math.max(o,Math.min(a.length,r)),l=Math.floor((o+i)/2),s=Math.max(0,l-Math.floor(n/2)),c=Math.min(a.length,s+n);s=Math.max(0,c-n);let u=s>0?"\u2026":"",f=c<a.length?"\u2026":"",d=Math.max(0,n-u.length-f.length);return`${u}${a.slice(s,s+d)}${f}`}function oo(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:Or("replacements must be a non-empty array.",t,r)};let n=[];for(let a=0;a<e.length;a+=1){let o=e[a],i=`${t}[${a}]`;if(!o||typeof o!="object"||Array.isArray(o))return{ok:!1,error:Or(`${i} must be an object.`,i,r)};if(typeof o.find!="string"||o.find.length===0)return{ok:!1,error:Or(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof o.replace!="string")return{ok:!1,error:Or(`${i}.replace must be a string.`,`${i}.replace`,r)};if(o.find===o.replace)return{ok:!1,error:Or(`${i} must change the matched text.`,i,r)};let l=o.occurrence==null?null:Number(o.occurrence);if(l!=null&&(!Number.isInteger(l)||l<1))return{ok:!1,error:Or(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:o.find,replace:o.replace,...l==null?{}:{occurrence:l}})}return{ok:!0,replacements:n}}function _c(e,t,r="replacements",n={}){let a=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:Or("Localized replacements require string source text.",r,a)};let o=oo(t,r,{invalidCode:a});if(!o.ok)return o;let i=[];for(let u=0;u<o.replacements.length;u+=1){let f=o.replacements[u],d=`${r}[${u}]`,m=f.occurrence??null,{offsets:p,matchMode:h}=wp(e,f.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:ao("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${f.find}".`:`Occurrence ${m} of patch source was not found: "${f.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:ao("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>yp(e,w,f.find.length))})};let g=p[(m||1)-1],v=e.slice(g,g+f.find.length);i.push({requestIndex:u,start:g,end:g+f.find.length,find:f.find,replace:f.replace,effectiveReplace:h==="space_equivalent"?vp(v,f.find,f.replace):f.replace,matchMode:h,occurrence:m||1})}i.sort((u,f)=>u.start-f.start||u.end-f.end||u.requestIndex-f.requestIndex);let l=[];for(let u of i){let f=l.at(-1);if(f&&u.start===f.start&&u.end===f.end){if(u.effectiveReplace!==f.effectiveReplace)return{ok:!1,error:ao("CONFLICTING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};continue}if(f&&u.start<f.end)return{ok:!1,error:ao("OVERLAPPING_PATCHES",`Localized replacements ${f.requestIndex+1} and ${u.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[f.requestIndex+1,u.requestIndex+1]})};l.push(u)}let s=0,c="";for(let u of l)c+=e.slice(s,u.start),c+=u.effectiveReplace,s=u.end;return c+=e.slice(s),{ok:!0,desiredText:c,replacements:l.map(u=>({requestIndex:u.requestIndex+1,start:u.start,end:u.end,find:u.find,replace:u.replace,matchMode:u.matchMode,occurrence:u.occurrence,removedLength:u.end-u.start,insertedLength:u.effectiveReplace.length}))}}function kc(e,t,r={},n=null){if(!e||typeof e!="object")return null;let a=String(e.sourceText??""),o=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],l=0,s=i.map(c=>{let u=c.start+l,f=u+c.replace.length;return l+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:Oc(a,c.start,c.end),afterExcerpt:Oc(o,u,f)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:s,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===o}}}var xp=new Set(["redline","replace","format","character-format","paragraph-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","highlight"]),Mc=Object.freeze(["merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function Jn(e){return Mc.includes(e)}function Nt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function he(e){return typeof e=="string"&&e.trim().length>0}function bp(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function io(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Nt(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:he(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:he(e.fingerprint)?e.fingerprint.trim():he(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:he(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function Ze(e){let t=Nt(e)?e:{},r=bp(t),n=r==="restore"?"rejected":"accepted",a=io(t.target,t.targetRef,n),o=t.targetEnd!=null?io(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:he(t.operationId)?t.operationId.trim():null,captureKey:he(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Nt(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:a,targetEndDescriptor:o,target:a.text,targetRef:a.index,targetEndRef:o?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function Ut(e){if(!Nt(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!xp.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=Ze(e);if(Nt(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Nt(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!he(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!he(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Nt(e.target)&&e.target.captureRef!=null&&(!he(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Nt(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(r.operationKind!=="comment_reply"&&!he(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!he(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let a=typeof r.modified=="string",o=r.replacements!==void 0;if(a===o)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(o){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||""))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=oo(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(l=>/\r|\n/.test(l.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!he(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!he(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let a=e.modified!==void 0,o=e.replacements!==void 0,i=he(r.modified),l=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(he);if(a&&o)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(a&&!i&&!l)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!a&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(o){let s=oo(r.replacements);if(!s.ok)return{valid:!1,error:s.error};if(s.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=s.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.existingRevisions!=null&&!Jn(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${Mc.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Nt(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:a,hyperlink:o,revision:i,bookmark:l,comment:s}=r.insertionAffinity;if(a!=null&&!["left","right","none"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(o!=null&&!["inside","outside","preserve"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!he(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!he(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!he(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="highlight"){if(!he(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!he(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!he(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(!Nt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}return r.operationKind==="paragraph-format"&&!Nt(r.properties)?{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}}:r.author!=null&&!he(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function dt(e,t,r){return he(e?.author)?e.author.trim():he(t)?t.trim():he(r)?r.trim():"Author"}var ir=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=ce(),this.parseResult=j(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new qn,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof Se?r._revisionIdAllocator:new Se,this.revisionIdAllocator._receiptCollector=this.receiptCollector,kt(this.document,this.revisionIdAllocator),Kt(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=ti(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:Lc(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?Lc(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,Kt(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=Pt(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function Lc(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function an(e,t={}){let r=t?._revisionIdAllocator instanceof Se?t._revisionIdAllocator:new Se;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),kt(e,r),Kt(e,r),r}function Bc(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function Dc(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let a of n)r.set(...a);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var Np=new Set(["redline","restore","rejected-insert"]),Ip=new Set(["highlight","format","paragraph-format"]);function Tp(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function Sp(e,t){return!!t&&oe(e).includes(t)}function Ep(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var Ci=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let a=`S${this.nextId++}`;return this.entries.set(a,{sourceId:a,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,a),a}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:Sp(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=oe(t);return new Map(Array.from(this.entries,([n,a])=>[n,{paragraphIndex:r.indexOf(a.paragraph),consumed:a.consumed,consumedByOperation:a.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=oe(t);for(let[a,o]of this.entries){let i=r instanceof Map?r.get(a):null;o.consumed=i?.consumed===!0,o.consumedByOperation=i?.consumedByOperation||null,o.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,o.paragraph&&this.idsByNode.set(o.paragraph,a)}}commitMutation(t,r,n,a){let o=this.entries.get(t);if(!o||!Array.isArray(r)||!r.includes(o.paragraph))return;let i=Ep(n),l=o.paragraphId?i.filter(c=>$e(c)===o.paragraphId):[],s=l.length===1?l[0]:i.length===1?i[0]:null;if(s){o.paragraph=s,this.idsByNode.set(s,t);return}o.paragraph=null,o.consumed=!0,o.consumedByOperation=a}};function Ap(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function Fc(e,t,r,n,a,o={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";a[i]||(a[i]=Pt(e,{revisionView:i}));let l=a[i],s=Sr(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:l,metadataIndices:a,onInfo:o.onInfo,onWarn:o.onWarn}),c=l.byParagraph.get(s.paragraph);return{paragraph:s.paragraph,resolvedBy:s.resolvedBy,metadata:Ap(c,i)}}function $c(e,t,r,n,a){return{code:e,message:t,operationIndexes:r.map(o=>o.index).sort((o,i)=>o-i),target:n,recovery:{action:a,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}}}function on(e,t=[],r={}){let n=Array.isArray(t)?t:[],a=r.strictTargets!==!1,o=new Ci(e),i={accepted:Pt(e,{revisionView:"accepted"}),rejected:null},l=[],s=[];for(let p=0;p<n.length;p+=1){let h=n[p],g=Ut(h),v=g.operation||Ze(h),w={index:p+1,operationKind:v.operationKind,operationId:v.operationId,sourceIds:[],warnings:[]},y={...h},x=v.targetDescriptor?.occurrence!=null&&!v.targetDescriptor?.paragraphId&&!v.targetDescriptor?.fingerprint,b=typeof v.targetDescriptor?.text=="string"&&/\r|\n/.test(v.targetDescriptor.text)&&!v.targetEndDescriptor;if((x||b)&&(w.dynamic=!0),g.valid&&v.operationKind!=="comment_reply"&&!v.targetDescriptor?.captureRef&&!w.dynamic)try{let I=Fc(e,v.targetDescriptor,v.operationKind,a,i,{onInfo:r.onInfo,onWarn:S=>w.warnings.push(String(S))}),N=o.register(I.paragraph,I.metadata);if(w.sourceIds.push(N),w.resolvedBy=I.resolvedBy,w.resolvedTarget=I.metadata,y._compiledSourceId=N,y._compiledResolvedBy=I.resolvedBy,w.warnings.length>0&&(y._compiledWarnings=w.warnings),Array.isArray(v.replacements)){let S=_c(I.metadata.text,v.replacements);if(!S.ok)throw Object.assign(new Error(S.error.message),S.error);y.modified=S.desiredText,delete y.replacements,y._localizedReplacementCompilation={sourceText:I.metadata.text,desiredText:S.desiredText,replacements:S.replacements};let E=Ut(y);if(!E.valid)throw Object.assign(new Error(E.error.message),E.error)}else if(v.operationKind==="restore"&&h.modified===void 0){y.modified=I.metadata.text;let S=Ut(y);if(!S.valid)throw Object.assign(new Error(S.error.message),S.error)}let T=v.targetEndDescriptor||(v.targetEndRef!=null?io(null,v.targetEndRef,v.targetDescriptor.revisionView):null);if(T){let S=Fc(e,T,v.operationKind,a,i,{onInfo:r.onInfo,onWarn:O=>w.warnings.push(String(O))}),E=o.register(S.paragraph,S.metadata);y._compiledSourceEndId=E;let _=oe(e),A=_.indexOf(I.paragraph),R=_.indexOf(S.paragraph);if(A<0||R<A)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let O of _.slice(A,R+1)){let C=(i[v.targetDescriptor.revisionView]||i.accepted).byParagraph.get(O);w.sourceIds.push(o.register(O,C||{}))}w.sourceIds=[...new Set(w.sourceIds)],w.resolvedTargetEnd=S.metadata}}catch(I){w.error=Tp(I)}l.push(w),s.push(y)}let c=new Set(s.map(p=>p?.captureKey).filter(Boolean)),u=1;for(let p of l){if(p.error?.code!=="TARGET_NOT_FOUND")continue;let h=p.index-1,v=Ze(n[h]).targetDescriptor?.text;if(!v)continue;let w=n.flatMap((I,N)=>N===h||typeof I?.modified!="string"?[]:I.modified.split(/\r?\n/).map(S=>S.trim()).filter(Boolean).includes(v.trim())?[{candidate:I,producerIndex:N}]:[]);if(w.length!==1)continue;let[{candidate:y,producerIndex:x}]=w,b=y.captureKey||s[x].captureKey;if(!b){do b=`__batch_created_${u++}`;while(c.has(b));c.add(b),s[x].captureKey=b}s[h].target={captureRef:b,select:v},delete s[h]._compiledSourceId,delete s[h]._compiledResolvedBy,delete p.error,p.sourceIds=[],p.resolvedBy="created_content_dependency",p.createdByOperation=x+1,p.captureRef=b}let f=new Map;for(let p of l)if(!(p.error||p.dynamic))for(let h of p.sourceIds)f.has(h)||f.set(h,[]),f.get(h).push(p);let d=[],m=new Set;for(let[p,h]of f){let g=h.filter(w=>Np.has(w.operationKind)),v=h.filter(w=>Ip.has(w.operationKind));if(g.length>1){let w=`text:${g.map(y=>y.index).sort().join(",")}`;m.has(w)||(m.add(w),d.push($c("OVERLAPPING_SOURCE_TARGETS",`Operations ${g.map(y=>y.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,g,o.describe(p),"consolidate_operations")))}if(g.length>0&&v.length>0){let w=[...g,...v],y=`format:${w.map(x=>x.index).sort().join(",")}`;m.has(y)||(m.add(y),d.push($c("REVISION_ORDER_CONFLICT",`Operations ${w.map(x=>x.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,w,o.describe(p),"split_or_consolidate_operations")))}}return{valid:d.length===0&&l.every(p=>!p.error),compiledOperations:s,bindings:l,conflicts:d,registry:o}}function Uc(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function sn(e=[],t=[]){let r=new Map;for(let n of t||[]){let a=Uc(n);r.set(a,(r.get(a)||0)+1)}return(e||[]).filter(n=>{let a=Uc(n),o=r.get(a)||0;return o===0?!0:(r.set(a,o-1),!1)})}function ln(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var Rp=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,zc=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function Pp(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function Cp(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let a=n.match(Rp);if(!a)return null;let o=a[2],i=/^[-*+\u2022]$/.test(o)?"bullet":"numbered";r.push({marker:o,markerType:i,level:Math.floor((a[1]||"").length/2),outlineLevel:i==="numbered"?Pp(o):null,text:Er(a[3])})}return r.length>=2?r:null}function Xc(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=Cp(t);if(!r)return null;let n=e.map(d=>Y(ve(d))),a=r.map(d=>Y(d.text));if(n.some(d=>!d)||a.some(d=>!d))return null;let o=e.map(d=>nt(d));if(o.some(d=>!d||!d.numId))return null;let i=String(o[0].numId);if(o.some(d=>String(d.numId)!==i))return null;let l=[],s=0;for(let d=0;d<a.length&&s<n.length;d+=1)a[d]===n[s]&&(l.push({originalIndex:s,modifiedIndex:d}),s+=1);if(s!==n.length)return null;let c=new Set(l.map(d=>d.modifiedIndex)),u=[];for(let d=0;d<r.length;d+=1)c.has(d)||u.push(d);if(u.length===0)return null;let f=r[0]?.level||0;return u.map(d=>{let m=l.find(x=>x.modifiedIndex>d)||null,p=[...l].reverse().find(x=>x.modifiedIndex<d)||null,h=m||p;if(!h)return null;let g=o[h.originalIndex]||o[0];if(!g)return null;let v=r[d],w=Math.max(0,v.level-f),y=Number.isInteger(v.outlineLevel)?v.outlineLevel:null;return{text:v.text,markerType:v.markerType,ilvl:y??Math.max(0,(g.ilvl||0)+w),numId:String(g.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function Op(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function _p(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(zc.source,zc.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function Vc(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
215
+ `))return null;let a=Y(r),o=s=>Er(String(s||"").trim()).trim(),i=(s,c)=>{let u=o(c),f=Y(u);return!u||u===r||Op(u)<6||_p(u)||a&&f.includes(a)?null:{position:s,text:u}};if(n.endsWith(r)){let s=i("before",n.slice(0,-r.length));if(s)return s}if(n.startsWith(r)){let s=i("after",n.slice(r.length));if(s)return s}let l=Y(n);if(!a||a===l)return null;if(l.endsWith(a)){let s=i("before",l.slice(0,-a.length));if(s)return s}if(l.startsWith(a)){let s=i("after",l.slice(a.length));if(s)return s}return null}function Wc(e,t){let r=String(e||"").trim(),n=String(t||"");if(!r||!n||!n.includes(`
216
+ `))return null;let a=n.split(/\r?\n/g).map(l=>String(l||"").trim()).filter(Boolean);if(a.length<2)return null;let o=l=>Y(String(l||"")),i=o(r);if(o(a[a.length-1])===i){let l=a.slice(0,-1).filter(Boolean);if(l.length>0)return{position:"before",paragraphs:l}}if(o(a[0])===i){let l=a.slice(1).filter(Boolean);if(l.length>0)return{position:"after",paragraphs:l}}return null}function zt(e,t){let r=new Error(t);return r.code=e,r}function jc(e,t,r){let n=[],a=!1,o=!1;for(let m of r||[])m&&(m.localName==="tbl"?(a=!0,n.push(...Array.from(m.getElementsByTagNameNS(M,"p")))):m.localName==="p"&&(m.getElementsByTagNameNS(M,"numPr").length>0&&(o=!0),n.push(m)));let i=a?"table":o?"list":n.length>1?"range":"paragraph",l=[],s=[],c=[],u=[],f=e.document,d=oe(f);for(let m of n){let p=$e(m)||"";l.push(p);let h=te(m);c.push(h);let g=d.indexOf(m)+1;s.push(rt(m,{text:h,paragraphId:p||null,index:g>0?g:void 0,inTable:a||!!Ve(m,"tbl")}));let v=m.parentNode?.localName||"body";u.push(`${v}/${m.localName}`)}return{captureKey:t.captureKey,operationIndex:typeof t.index=="number"?t.index:0,kind:i,generatedParagraphIds:l,fingerprints:s,expectedText:c,structuralPathHints:u,stale:!1}}function Kc(e,t){if(!e||!(e instanceof Map)||!Array.isArray(t)||t.length===0)return;let r=new Set;for(let n of t)if(n){if(n.localName==="p"){let a=$e(n);a&&r.add(a)}else if(typeof n.getElementsByTagNameNS=="function")for(let a of Array.from(n.getElementsByTagNameNS(M,"p"))){let o=$e(a);o&&r.add(o)}}if(r.size!==0)for(let[,n]of e)n.stale||n.generatedParagraphIds.some(a=>a&&r.has(a))&&(n.stale=!0)}function Hc(e,t,r,n="redline",a={}){let o=r?.captureRef;if(!o)throw zt("INVALID_OPERATION","Operation target is missing captureRef.");if(!t||!t.captureTable||!t.captureTable.has(o))throw zt("CAPTURE_NOT_FOUND",`Capture "${o}" was not found in the session capture table.`);let i=t.captureTable.get(o);if(i.stale)throw zt("CAPTURE_STALE",`Capture "${o}" is stale; the captured content was modified or removed.`);let l=t.getParagraphMetadataIndex(),s=[];for(let d=0;d<i.expectedText.length;d++){let m=i.generatedParagraphIds[d],p=i.expectedText[d],h=null;if(m&&l.byId.has(m)&&(h=l.byId.get(m).paragraph),!h){let v=l.entries.find(w=>w.text===p||w.fingerprint===i.fingerprints[d]);v&&(h=v.paragraph)}if(!h||!h.parentNode)throw i.stale=!0,zt("CAPTURE_STALE",`Capture "${o}" is stale; paragraph ${d+1} was removed from the document.`);let g=te(h);if(g!==p)throw i.stale=!0,zt("CAPTURE_STALE",`Capture "${o}" is stale; paragraph ${d+1} content drifted from "${p}" to "${g}".`);s.push(h)}if(s.length===0)throw i.stale=!0,zt("CAPTURE_STALE",`Capture "${o}" is stale; no live paragraphs found.`);let c=r.select;if(c==null||c===""){if(s.length===1)return{paragraph:s[0],resolvedBy:"capture"};throw zt("AMBIGUOUS_CAPTURE_SELECTION",`Capture "${o}" contains ${s.length} paragraphs; target.select is required to disambiguate.`)}let u=[],f=String(c).trim();if(f===":first"||f==="first")u=[s[0]];else if(f===":last"||f==="last")u=[s[s.length-1]];else if(/^\d+$/.test(f)){let d=parseInt(f,10);d>=1&&d<=s.length&&(u=[s[d-1]])}else{let d=s.filter(m=>te(m).trim()===f);d.length>0?u=d:u=s.filter(m=>te(m).includes(f))}if(u.length===0)throw zt("TARGET_NOT_FOUND",`Target selection "${c}" was not found in capture "${o}".`);if(u.length>1)throw zt("AMBIGUOUS_CAPTURE_SELECTION",`Target selection "${c}" matched ${u.length} paragraphs in capture "${o}".`);return{paragraph:u[0],resolvedBy:"capture"}}var ne="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Bi="http://schemas.microsoft.com/office/word/2010/wordml";function Gc(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.(ne,r)||[])){let a=n.getAttribute("w:id")||n.getAttribute("id");a!==""&&t.add(a)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function qc(e,t){return!t||typeof t!="object"?[]:e.map(r=>t[r]).filter(Boolean)}function _r(e,t={}){let r=t?._documentOperationSession||null;return r?.valid&&r.document?{xmlDoc:r.document,serializer:r.serializer,operationSession:r}:{xmlDoc:j(e,"application/xml").doc,serializer:ce(),operationSession:null}}function at(e,t,r,n){return n?r:t.serializeToString(e)}async function ea(e,t,r,n={}){let a=await Rn(e,t,r,n);return a?.useNativeApi&&typeof a?.oxml!="string"?we({...a,oxml:e,hasChanges:!1,warnings:[...Array.isArray(a?.warnings)?a.warnings:[],"Standalone mode cannot execute native Word API fallback for this operation."]}):a}async function kp(e,t,r,n={}){let a=typeof e=="string"?e:"",o=typeof r=="string"?r:String(r||""),i;try{i=et(o)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await ea(a,t||"",o,n),isMarkdownTable:!0,tableData:i}:{oxml:a,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}function Qn(e){return ve(e)}function Yc(e,t=96){let r=String(e??"");return(r.length>t?`${r.slice(0,t)}\u2026`:r).replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\u00a0/g,"\\u00A0").replace(/\u202f/g,"\\u202F").replace(/\u2060/g,"\\u2060")}function so(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Mp(e,t){let r=String(e??""),n=String(t??"");if(r===n)return{mode:"exact"};let a=[],o=Math.min(r.length,n.length);for(let l=0;l<o&&a.length<8;l++)r[l]!==n[l]&&a.push({offset:l,sourceCodePoint:so(r,l),requestedCodePoint:so(n,l)});return r.length!==n.length&&a.length<8&&a.push({offset:o,sourceCodePoint:so(r,o),requestedCodePoint:so(n,o)}),{mode:r.length===n.length&&r.replace(/\u00a0/g," ")===n.replace(/\u00a0/g," ")?"space_equivalent":"normalized",differences:a,sourceExcerpt:Yc(r),requestedExcerpt:Yc(n)}}function Oi(e,t,r,n,a){let o=a?.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",i=r?.revisionView===o?r:null,l=i?.index??oe(e).indexOf(t)+1,s=i?.paragraphId??$e(t),c=i?.inTable??!!Ve(t,"tbl"),u=i?.text??te(t,{revisionView:o}),f=i?.fingerprint??rt(t,{text:u,index:l,paragraphId:s,inTable:c,revisionView:o});return{index:l,paragraphId:s,text:u,fingerprint:f,revisionView:o,inTable:c,targetTextMatch:Mp(u,a?.targetDescriptor?.text??a?.targetDescriptor?.exactText??n)}}function Xt(e,t,r,n,a=null,o={}){let i=typeof o?.onInfo=="function"?o.onInfo:()=>{},l=typeof o?.onWarn=="function"?o.onWarn:()=>{},s=o?._documentOperationSession||null,c=s?.getParagraphMetadataIndex?.()||null;if(o?._compiledSourceId&&o?._sourceTargetRegistry){let f=o._sourceTargetRegistry.resolve(o._compiledSourceId,e);if(f?.error||!f?.paragraph)return f;if(f.resolvedBy=o._compiledResolvedBy||f.resolvedBy,o?._resolutionCapture){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(o._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:Oi(e,d,m,t,o)})}return f}if(o?.targetDescriptor?.captureRef)try{let f=Hc(e,s,o.targetDescriptor,n,o);if(o?._resolutionCapture&&f?.paragraph){let d=f.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(o._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:Oi(e,d,m,t,o)})}return f}catch(f){return{error:{code:typeof f?.code=="string"&&f.code?f.code:"TARGET_NOT_FOUND",message:f?.message||String(f)}}}let u=Cn(e,{targetText:t,targetRef:r,opType:n,targetRefSnapshot:a?.targetRefSnapshot||null,targetDescriptor:o?.targetDescriptor||null,strictAmbiguity:o?.strictTargets===!0,paragraphMetadataIndex:c,onInfo:i,onWarn:l});if(o?._resolutionCapture&&u?.paragraph){let f=u.paragraph,d=c?.byParagraph?.get(f)||null;Object.assign(o._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:Oi(e,f,d,t,o)})}return u}function kr(e){return Ti(e)}function Lp(e,t){if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||!t.includes("Paragraph expanded to list fragment"))return e;let r=e[e.length-1];return!r||r.localName!=="p"||Array.from(r.childNodes||[]).some(a=>a.nodeType===1&&a.localName!=="pPr")?e:e.slice(0,-1)}function ot(e){to(e)}function Bp(e){for(let t of Array.from(e?.getElementsByTagNameNS?.(ne,"proofErr")||[]))t.parentNode?.removeChild(t)}function Dp(e){e&&Bp(e)}function Je(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI===ne&&r.localName===t)||null}function Fp(e,t){if(!e||!t)return null;let n=Array.from(e.getElementsByTagNameNS(ne,"tbl")).indexOf(t);return n>=0?n+1:null}function $p(e){return String(e||"").replace(/\r\n/g,`
217
+ `).split(`
218
+ `).map(t=>t.trim()).filter(Boolean).join(`
219
+ `)}function Up(e,t,r){let n=Fp(e,t);if(!Number.isInteger(n)||n<1)return null;let a=$p(r);return a?`table:${n}|payload:${a}`:null}function zp(e,t,r,n){let a=Je(t,"pPr");a||(a=L(e,"w:pPr"),t.insertBefore(a,t.firstChild));let o=Je(a,"numPr");o||(o=L(e,"w:numPr"),a.appendChild(o));let i=Je(o,"ilvl");i||(i=L(e,"w:ilvl"),o.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let l=Je(o,"numId");l||(l=L(e,"w:numId"),o.appendChild(l)),l.setAttribute("w:val",String(n))}function ki(e,t,r,n,a,o={}){let i=o.generateRedlines!==!1,l=L(e,"w:p"),s=Je(t,"pPr");s&&l.appendChild(lt(s)),zp(e,l,r.ilvl,r.numId),i&&zr(e,l,a);let c=L(e,"w:r"),u=Array.from(t.getElementsByTagNameNS(ne,"r"))[0]||null,f=u?Je(u,"rPr"):null;f&&c.appendChild(lt(f));let d=L(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ae(a,e),h=L(e,"w:ins");h.setAttribute("w:id",String(p.id)),h.setAttribute("w:author",p.author),h.setAttribute("w:date",p.date),h.appendChild(c),l.appendChild(h)}else l.appendChild(c);return l}function _i(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${ne}"><w:body>${r}</w:body></w:document>`}function Xp({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:a}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let o=t[0].parentNode;if(!o||t.some(l=>l.parentNode!==o))return!1;let i=t[t.length-1].nextSibling;for(let l of r){let s=l.insertBeforeOriginalIndex!=null?t[l.insertBeforeOriginalIndex]:t[t.length-1];if(!s)return!1;let c=ki(e,s,{ilvl:l.ilvl,markerType:l.markerType,numId:l.numId,text:l.text},n?ae(a,e):null,a,{generateRedlines:n});l.insertBeforeOriginalIndex!=null?o.insertBefore(c,s):o.insertBefore(c,i)}return ot(e),!0}function Vp(e,t,r,n,a={}){let o=a.generateRedlines!==!1,i=L(e,"w:p"),l=L(e,"w:r"),s=L(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&s.setAttribute("xml:space","preserve"),s.textContent=c,l.appendChild(s),o){a.trackParagraphMark===!0&&zr(e,i,n);let u=r||ae(n,e,"ins"),f=L(e,"w:ins");f.setAttribute("w:id",String(u.id)),f.setAttribute("w:author",u.author),f.setAttribute("w:date",u.date),f.appendChild(l),i.appendChild(f)}else i.appendChild(l);return i}function Wp(e,t){let r=L(e,"w:p"),n=Je(t,"pPr");n&&r.appendChild(lt(n));let a=L(e,"w:r"),o=Array.from(t.getElementsByTagNameNS(ne,"r"))[0]||null,i=o?Je(o,"rPr"):null;i&&a.appendChild(lt(i));let l=L(e,"w:t");return l.textContent="",a.appendChild(l),r.appendChild(a),r}function eu(e,t,r,n,a={}){let o=L(e,"w:p"),i=a.sanitizeParagraphProperties===!0?tu(e,t):lt(Je(t,"pPr"));i&&o.appendChild(i),a.paragraphId&&o.setAttributeNS(Bi,"w14:paraId",a.paragraphId),a.trackParagraphMark===!0&&zr(e,o,n);let l=L(e,"w:ins"),s=r||ae(n,e,"ins");l.setAttribute("w:id",String(s.id)),l.setAttribute("w:author",s.author),l.setAttribute("w:date",s.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===ne&&c.localName==="pPr"||l.appendChild(c.cloneNode(!0));return o.appendChild(l),o}async function jp(e,t,r,n,a,o={}){let i=o.generateRedlines!==!1,l=ce(),s=Wp(e,t),c=l.serializeToString(s),u=await ea(c,"",String(r||""),{author:a,generateRedlines:!1}),f=null;return typeof u?.oxml=="string"&&(f=(kr(u.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===ne&&m.localName==="p")||null),f?i?eu(e,f,n,a,o):f:Vp(e,r,n,a,{...o,generateRedlines:i})}function Di(e){let t=new Set;for(let r of e||[]){let n=Array.from(r?.getElementsByTagNameNS?.("*","numId")||[]);for(let a of n){let o=a.getAttribute("w:val")||a.getAttribute("val");o!=null&&o!==""&&t.add(String(o))}}return Array.from(t)}function Zc(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===ne&&r.localName==="r"?Lt(r).map(n=>n.text).join(""):""),"")}function Kp(e,t,r){let n=0,a=-1;for(let o=0;o<r;o++){if(a=e.indexOf(t,n),a<0)return-1;n=a+Math.max(t.length,1)}return a}function Hp(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let a=e.indexOf(t,n);if(a<0)break;r+=1,n=a+t.length}return r}function Gp(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===ne&&n.localName==="r"))return!0;for(let a of Array.from(n.childNodes||[]))if(!(a.nodeType!==1||a.namespaceURI!==ne)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(a.localName))return!0}return!1}function qp(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===ne&&n.localName==="r"))continue;let a=ct(Lt(n));if(t<=r+a)return lt(Je(n,"rPr"));r+=a}return null}var Yp=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function Mi(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Jc(e){return String(e||"").trim().toLowerCase()}function Zp(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===ne&&r.localName==="p")return r;r=r[t]||null}return null}function tu(e,t){let r=Je(t,"pPr"),n=L(e,"w:pPr");if(!r)return n;for(let a of Array.from(r.childNodes||[]))a.nodeType!==1||a.namespaceURI!==ne||Yp.has(a.localName)&&n.appendChild(e.importNode(a,!0));return n}function Jp(e){let t=[],r=new Set;for(let a of Array.from(e?.getElementsByTagNameNS?.(ne,"bookmarkStart")||[])){let o=Mi(a,"name")||"(unnamed)";r.add(o)}for(let a of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${a}`);let n=new Set;for(let a of["commentRangeStart","commentRangeEnd","commentReference"])for(let o of Array.from(e?.getElementsByTagNameNS?.(ne,a)||[])){let i=Mi(o,"id");i!==""&&n.add(i)}for(let a of n)t.push(`RESTORATION_DROPPED_COMMENT:${a}`);return t}function Qp(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(ne,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(ne,"r")||[]))Array.from(r.childNodes||[]).some(a=>a.nodeType===1&&a.namespaceURI===ne&&a.localName!=="rPr")||r.parentNode?.removeChild(r)}function eg(e,t,r){let n=tr(r.serializeToString(t),{allAuthors:!0}),o=j(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(ne,"p")?.[0]||null;if(!o)return null;let i=L(e,"w:p");i.appendChild(tu(e,t));for(let l of Array.from(o.childNodes||[]))l.nodeType===1&&l.namespaceURI===ne&&l.localName==="pPr"||i.appendChild(e.importNode(l,!0));return Qp(i),i}async function tg(e,t,r,n,a){let o=te(t);if(o===r)return t;let i=await ea(a.serializeToString(t),o,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let s=(kr(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===ne&&c.localName==="p");return s?e.importNode(s,!0):null}function rg(e,t){let r=new Set(oe(e).map(a=>a.getAttributeNS?.(Bi,"paraId")||a.getAttribute?.("w14:paraId")||"").filter(Boolean).map(a=>a.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function ng(e,t,r,n){let a=e.documentElement;return a&&!a.getAttribute("xmlns:w14")&&a.setAttribute("xmlns:w14",Bi),eu(e,t,null,r,{paragraphId:rg(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function ag(e,t){let r=Je(e,"pPr"),n=Je(r,"rPr"),a=Je(n,"ins");return!!a&&Jc(Mi(a,"author"))===Jc(t)}function og(e,t){let r=[],n=e;for(let a=0;a<t;a++){if(n=Zp(n,"nextSibling"),!n)return[];r.push(n)}return r}function Li(e){let t=j(e,"application/xml");return t.error||!t.doc?null:oe(t.doc).map(r=>te(r))}function ig(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function lo(e,t){let r=t==="accept"?yr(e,{allAuthors:!0}):tr(e,{allAuthors:!0});return Li(r.oxml)}function sg(e,t,r,n){let a=j(e,"application/xml");if(a.error||!a.doc)return null;let o=a.doc,i=oe(o),l=i[t+n.length-1]||null;if(!l?.parentNode)return null;for(let c of[...r].sort((u,f)=>f-u)){let u=i[c];u?.parentNode?.removeChild(u)}let s=l.nextSibling;for(let c of n)l.parentNode.insertBefore(o.importNode(c,!0),s);return ce().serializeToString(o)}function lg(e,t,r,n,a,o=[]){let i=yt(e),l=yt(t),s=sn(l.issues,i.issues),c=o.flatMap(m=>yt(ce().serializeToString(m)).issues.filter(p=>p.severity==="error")),u=ln(s);if(u.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:s,envelopeIssues:c,message:[...u,...c].map(m=>m.message).join(" ")};let f=sg(e,r,n,a);if(!f)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",Li(f),Li(t)],["accept-all",lo(f,"accept"),lo(t,"accept")],["reject-all",lo(e,"reject"),lo(t,"reject")]];for(let[m,p,h]of d)if(!ig(p,h))return{valid:!1,stage:m,expected:p,actual:h,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function ru(e,t,r,n,a,o=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:u}=_r(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=Xt(c,t,o,"insert",i,l);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=f.paragraph;if(!rr(d,a).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=br(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let h=te(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&Hp(h,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let g=Kp(h,r.exactText,r.occurrence);if(g<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let v=g+r.offset,w=Array.from(d.childNodes||[]).filter(k=>k?.nodeType===1&&k.namespaceURI===ne&&k.localName==="del");if(w.some(k=>Gp(d,k)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let y=0,x=null,b=0;for(let k of w){let D=Zc(k).length;if(v>=y&&v<=y+D){x=k,b=v-y;break}y+=D}if(!x||w.map(Zc).join("")!==h)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let I=qp(x,b),{leftCarrier:N,rightCarrier:T}=Ia(c,x,b,l._revisionIdAllocator||null),S=L(c,"w:ins"),E=ae(a,l._revisionIdAllocator||c,"ins");S.setAttribute("w:id",String(E.id)),S.setAttribute("w:author",E.author),S.setAttribute("w:date",E.date);let _=L(c,"w:r");I&&_.appendChild(I);let A=L(c,"w:t");/^\s|\s$/.test(n)&&A.setAttribute("xml:space","preserve"),A.textContent=n,_.appendChild(A),S.appendChild(_);let R=x.parentNode;N&&R.insertBefore(N,x),R.insertBefore(S,x),T&&R.insertBefore(T,x),l?._mutationRemovedNodes?.push(x),R.removeChild(x),l?._mutationLiveNodes?.push(d,S),u?.invalidateParagraphMetadata?.();let O=s.serializeToString(c),P=te(d,{revisionView:"rejected"}),C=te(d,{revisionView:"accepted"});return P!==h||!C.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:O,hasChanges:!0,status:"ok"}}async function nu(e,t,r,n,a=null,o=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:u}=_r(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let f=Xt(c,t,a,"restore",i,l);if(f?.error||!f?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:f?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=f.paragraph,m=[d];if(l._compiledSourceEndId){let R=Xt(c,l.targetEndDescriptor?.text||"",o,"restore",i,{...l,_compiledSourceId:l._compiledSourceEndId}),O=R?.paragraph?oe(c):[],P=O.indexOf(d),C=O.indexOf(R?.paragraph);m=P>=0&&C>=P?O.slice(P,C+1):null}else if(o)m=jr(c,a,o,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:l.onInfo,onWarn:l.onWarn});else if(l.targetEndDescriptor){let R=Xt(c,l.targetEndDescriptor.text,l.targetEndDescriptor.index,"restore",i,{...l,targetDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceEndId||null}),O=R?.paragraph?oe(c):[],P=O.indexOf(d),C=O.indexOf(R?.paragraph);m=P>=0&&C>=P?O.slice(P,C+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(R=>R.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let h=d.parentNode;if(!h||m.some(R=>R.parentNode!==h))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let R of m){let O=br(R);if(O?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:O};let P=rr(R,n);if(!P.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:P.hasParagraphMarkDeletion&&!P.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...P.ownerAuthor?{ownerAuthor:P.ownerAuthor}:{}}};let C=O||br(R);if(C)return{documentXml:e,hasChanges:!1,status:"error",error:C}}let g=m[m.length-1],v=og(g,m.length),w=v.length===m.length&&v.every(R=>ag(R,n));if(w&&v.every((R,O)=>te(R)===p[O]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let y=s.serializeToString(c),x=oe(c),b=x.indexOf(d),I=w?v.map(R=>x.indexOf(R)):[],N=[],T=[];for(let R=0;R<m.length;R++){let O=m[R];T.push(...Jp(O));let P=eg(c,O,s),C=P?await tg(c,P,p[R],n,s):null;if(!C)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${R+1} from its rejected revision view.`}};N.push(C)}let S=N.map(R=>{let O=c.importNode(R,!0);return ng(c,O,n,u)}),E=g.nextSibling;for(let R of S)h.insertBefore(R,E);if(w)for(let R of v)l?._mutationRemovedNodes?.push(R),R.parentNode?.removeChild(R);l?._mutationLiveNodes?.push(...S),ot(c);let _=s.serializeToString(c),A=lg(y,_,b,I,N,S);return A.valid?{documentXml:at(c,s,e,u),hasChanges:!0,status:"ok",numberingXml:null,...T.length>0?{warnings:[...new Set(T)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:A.code||"PATCH_ROUNDTRIP_MISMATCH",message:A.message,stage:A.stage,...A.generatedIssues?{generatedIssues:A.generatedIssues}:{},...A.envelopeIssues?{envelopeIssues:A.envelopeIssues}:{},...A.expected?{expected:A.expected}:{},...A.actual?{actual:A.actual}:{}}}}async function cg({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:a,currentParagraphText:o,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!a)return null;let m=t.serializeToString(a),p=Gr({oxml:m,originalText:o,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let h=oi(p.listInput||i);if(!h)return null;f("[List] Applying explicit numeric header conversion with direct list binding.");let g=await ea(t.serializeToString(a),o,h,{author:l,generateRedlines:u,_revisionIdAllocator:c});if(!g?.hasChanges||typeof g?.oxml!="string")return null;let w=kr(g.oxml).replacementNodes,y=$a(p,s?.listFallbackSequenceState||null),x=p.startAt,b=s?.numberingIdState||null,I=null,N=null;if(y.type==="explicitReuse"&&y.numId)I=String(y.numId),f(`[List] Reusing explicit-start list sequence (${y.numberingKey} -> numId ${I}, next ${x+1}).`);else{let S=Wa(b);if(!S)return null;I=String(S.numId),N=Ha(S.numId,S.abstractNumId,x),y.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${y.numberingKey} -> numId ${I}).`),f(`[List] Using isolated explicit-start numbering (start ${x}, numId ${I}, abstractNumId ${S.abstractNumId}).`)}p.numberingKey&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(p.numberingKey),y.type==="explicitStartNew"||y.type==="explicitReuse"?Ua(s?.listFallbackSequenceState||null,y.numberingKey||p.numberingKey,I,x):Mn(s?.listFallbackSequenceState||null,y.numberingKey||p.numberingKey),za(w,{numId:I,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0});let T=a.parentNode;if(!T)return null;for(let S of w){let E=e.importNode(S,!0);let _=T.insertBefore(E,a);d?._mutationLiveNodes?.push(_)}if(d?._mutationRemovedNodes?.push(a),T.removeChild(a),ot(e),n?.receiptCollector&&N){let S=Di(d?._mutationLiveNodes);for(let E of S)n.receiptCollector.recordNumbering(E)}return{documentXml:at(e,t,r,n),hasChanges:!0,numberingXml:N}}async function ug({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:a,currentParagraphText:o,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:u=!0,onInfo:f=()=>{},options:d={}}){if(!a)return null;let m=t.serializeToString(a),p=Gr({oxml:m,originalText:o,modifiedText:i,allowExistingList:!1});if(!p)return null;f("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let h=await qr(p,{author:l,generateRedlines:u,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!h?.hasChanges||!h?.oxml)return f("[List] Structural list fallback produced no valid OOXML payload."),null;let g=kr(h.oxml),v=g.replacementNodes,w=g.numberingXml||h?.numberingXml||null,y=Number.isInteger(p?.startAt)&&p.startAt>0,x=h?.listStructuralFallbackKey||p?.numberingKey||null,b=$a(p,s?.listFallbackSequenceState||null);if(y){let N=p.startAt,T=null,S=s?.numberingIdState||null;if(b.type==="explicitReuse"&&b.numId)T=String(b.numId),w=null,f(`[List] Reusing explicit-start list sequence (${b.numberingKey} -> numId ${T}, next ${N+1}).`);else if(S){let E=Wa(S);if(!E)return null;ja(v,E.numId),T=String(E.numId),w=Ha(E.numId,E.abstractNumId,N),b.type==="explicitStartNew"&&f(`[List] Started explicit-start list sequence (${b.numberingKey} -> numId ${E.numId}).`),f(`[List] Using isolated explicit-start numbering (start ${N}, numId ${E.numId}, abstractNumId ${E.abstractNumId}).`)}else{let E=Ka(v);T=E?String(E):null,f(`[List] Using isolated list numbering with explicit start ${N}${E?` (numId ${E})`:""}.`)}x&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(x),b.type==="explicitStartNew"||b.type==="explicitReuse"?Ua(s?.listFallbackSequenceState||null,b.numberingKey||x,T,N):Mn(s?.listFallbackSequenceState||null,b.numberingKey||x),T&&za(v,{numId:T,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0})}else{if(w&&s?.numberingIdState){let N=Ga(w,v,s.numberingIdState);v=N.replacementNodes,w=N.numberingXml}Mn(s?.listFallbackSequenceState||null,b.numberingKey||x)}if(!y&&s?.listFallbackSharedNumIdByKey instanceof Map){let N=x?s.listFallbackSharedNumIdByKey.get(x):null;if(N)ja(v,N),w=null,f(`[List] Reusing shared list numbering (${x} -> numId ${N}).`);else if(x){let T=Ka(v);T&&(s.listFallbackSharedNumIdByKey.set(x,T),f(`[List] Captured shared list numbering (${x} -> numId ${T}).`))}}let I=a.parentNode;if(!I)return null;for(let N of v){let T=e.importNode(N,!0);let S=I.insertBefore(T,a);d?._mutationLiveNodes?.push(S)}if(d?._mutationRemovedNodes?.push(a),I.removeChild(a),ot(e),n?.receiptCollector&&w){let N=Di(d?._mutationLiveNodes);for(let T of N)n.receiptCollector.recordNumbering(T)}return{documentXml:at(e,t,r,n),hasChanges:!0,numberingXml:w}}async function au(e,t,r,n,a=null,o=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},u=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=_r(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||an(d,l),h=Xt(d,t,a,"redline",i,{...l,onInfo:c,onWarn:u});if(h?.error||!h?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:h?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let g=h.paragraph;if(typeof r=="string"&&r.length>0){let $=rr(g,n);if($.matches){let K=$.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${K}). Use explicit paragraph restoration when supported.`,ownerAuthor:K}}}}Dp(g);let v=Qn(g);if(r===""){let $=Gc(g);if($.length>0){let K=qc($,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:$,...K.length>0?{comments:K}:{}}}}}let w=La(g,r,l);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let y=Yt(g),x=l.existingRevisions||"merge-same-author";if(y&&x!=="accept-all-first"&&x!=="accept-all-first-keep-normalized")if(x==="merge-same-author"||x==="slice-cross-author"){let $=dr(g),K=String(n||"").trim().toLowerCase(),ee=$.length>0&&$.every(Qe=>Qe.trim().toLowerCase()===K);if(!ee&&x==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${$.length?$.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:$,currentPolicy:x}};let je=ee?Gc(g):[];if(je.length>0){let Qe=qc(je,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:je,...Qe.length>0?{comments:Qe}:{}}}}if(!ee&&(g.getElementsByTagNameNS(ne,"moveFrom").length>0||g.getElementsByTagNameNS(ne,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let $=g.getElementsByTagNameNS(ne,"del").length>0,K=g.getElementsByTagNameNS(ne,"moveFrom").length>0||g.getElementsByTagNameNS(ne,"moveTo").length>0;return $?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:K?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&v===""&&!(y&&x==="merge-same-author"))return s?(gr(d,g,n,ae(n,d)),l?._mutationLiveNodes?.push(g)):(l?._mutationRemovedNodes?.push(g),g.parentNode?.removeChild(g)),ot(d),{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:null};let b=Ve(g,"tbl"),N=!!b&&!o&&typeof r=="string"&&r.includes(`
220
+ `)&&!Tr(r)?Up(d,b,r):null,T=i?.tableStructuralRedlineKeys instanceof Set?i.tableStructuralRedlineKeys:null;if(N&&T?.has(N))return c("[Table] Skipping duplicate table-structural redline for the same table/payload in this turn."),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:["Skipped duplicate table-structural redline in the same turn."]};let E=(b?si(g,r,{tableElement:b,currentParagraphText:v,onInfo:c,onWarn:u}):null)||r,_=!!b&&Tr(E),A=Tr(E),R=o?jr(d,a,o,{opType:"redline",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:c,onWarn:u}):typeof t=="string"&&/\r?\n/.test(t)?Ta(d,t):null,O=Array.isArray(R)&&R.length>0;if(!_&&O){let $=Xc(R,E);if($&&$.length>0){c(`[List] Applying explicit-range insertion-only heuristic (${$.length} new item(s)).`);for(let ee of $)c(`[List] Explicit-range insertion: ilvl=${ee.ilvl}, markerType=${ee.markerType}, text="${String(ee.text||"").slice(0,80)}${String(ee.text||"").length>80?"\u2026":""}"`);if(Xp({xmlDoc:d,explicitRangeParagraphs:R,insertionEntries:$,generateRedlines:s,author:n}))return{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:null}}}let P=null;!R&&!_&&A&&(P=ii(g,{getParagraphText:Qn}),P?.length>1&&c(`[Table] Heuristic range expansion selected ${P.length} paragraph(s) for replacement.`));let C=nt(g);if(C&&typeof E=="string"&&!E.includes(`
221
+ `)){let $=Er(E);$&&$!==E.trim()&&(c("[List] Stripped redundant manual list marker prefix from single-line list item edit."),E=$)}_&&c("[Table] Markdown table edit detected in table cell target; applying reconciliation at table scope.");let k=l.explicitStructuredContent===!0,D=!k&&!_&&!O&&C?Vc(v,E):null;if(D){c(`[List] Applying single-paragraph list adjacency insertion heuristic (${D.position}).`);let $=g.parentNode;if(!$)throw new Error("Target paragraph has no parent for adjacency list insertion");let K=ki(d,g,{ilvl:C.ilvl,numId:C.numId,markerType:"numbered",text:D.text},s?ae(n,d):null,n,{generateRedlines:s}),ee=D.position==="before"?g:g.nextSibling;return $.insertBefore(K,ee),l?._mutationLiveNodes?.push(K),ot(d),{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:null}}let z=!k&&!_&&!O&&!C?Wc(v,E):null;if(z){c(`[Text] Applying single-paragraph plain adjacency insertion heuristic (${z.position}, count=${z.paragraphs.length}).`);let $=g.parentNode;if(!$)throw new Error("Target paragraph has no parent for plain adjacency insertion");let K=z.position==="before"?g:g.nextSibling;for(let ee of z.paragraphs){let je=await jp(d,g,ee,s?ae(n,d):null,n,{generateRedlines:s}),Qe=d.importNode(je,!0);let oa=$.insertBefore(Qe,K);l?._mutationLiveNodes?.push(oa)}return ot(d),{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:null}}let H=!k&&!_&&!O?ni(g,E,{currentParagraphText:v,onInfo:c,onWarn:u}):null;if(H&&H.entries.length>0){c(`[List] Applying insertion-only list redline heuristic (${H.entries.length} new item(s)).`);for(let ee of H.entries)c(`[List] Insertion entry resolved: ilvl=${ee.ilvl}, markerType=${ee.markerType}, text="${String(ee.text||"").slice(0,80)}${String(ee.text||"").length>80?"\u2026":""}"`);let $=g.parentNode;if(!$)throw new Error("Target paragraph has no parent for list insertion");let K=g.nextSibling;for(let ee of H.entries){let je=ki(d,g,{...ee,numId:H.numId},s?ae(n,d):null,n,{generateRedlines:s});$.insertBefore(je,K),l?._mutationLiveNodes?.push(je)}return ot(d),{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:null}}let G=!k&&!_&&!O?ri(g,E,{currentParagraphText:v,onInfo:c,onWarn:u}):null,Z=!!G&&Array.isArray(G.paragraphs)&&G.paragraphs.length>0;if(Z&&(E=G.modifiedText),!k&&!_&&!Z&&!O){let $=await cg({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:g,currentParagraphText:v,modifiedText:E,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if($)return $;let K=await ug({xmlDoc:d,serializer:f,documentXml:e,operationSession:m,targetParagraph:g,currentParagraphText:v,modifiedText:E,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(K)return K}let pe=Z?G.originalText:R?R.map($=>Qn($)).join(`
222
+ `):P?P.map($=>Qn($)).join(`
223
+ `):v||t,ue=_?f.serializeToString(b):Z?_i(G.paragraphs,f):R?_i(R,f):P?_i(P,f):f.serializeToString(g),W=A?await kp(ue,pe,E,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,_revisionIdAllocator:p,_isolatedTableCell:_}):await ea(ue,pe,E,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,pairReplacements:l.pairReplacements===!0,insertionAffinity:l.insertionAffinity||null,_revisionIdAllocator:p,_isolatedTableCell:_});if(!W?.hasChanges)return{documentXml:e,hasChanges:!1,numberingXml:null,status:W?.status||"no-op",error:W?.error};if(W.useNativeApi&&!W.oxml){let $="Format-only fallback requires native Word API; browser demo skipped this operation.";return u(`[WARN] ${$}`),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:[$]}}if(typeof W.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed redline operation");let J=kr(W.oxml),Re=Lp(J.replacementNodes,W.warnings),le=J.numberingXml;if(le&&i?.numberingIdState){let $=Ga(le,Re,i.numberingIdState);Re=$.replacementNodes,le=$.numberingXml}let ge=_?[b]:Z?G.paragraphs:R||P||[g],X=ge[0],U=X.parentNode;for(let $ of Re){let K=d.importNode($,!0);let ee=U.insertBefore(K,X);l?._mutationLiveNodes?.push(ee)}for(let $ of ge)$&&$.parentNode===U&&(l?._mutationRemovedNodes?.push($),U.removeChild($));if(ot(d),N&&T&&(_||b)&&T.add(N),m?.receiptCollector&&le){let $=Di(l?._mutationLiveNodes);for(let K of $)m.receiptCollector.recordNumbering(K)}return{documentXml:at(d,f,e,m),hasChanges:!0,numberingXml:le,status:"ok",...Array.isArray(W.warnings)&&W.warnings.length>0?{warnings:W.warnings}:{}}}async function ou(e,t,r,n,a,o=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},u=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=_r(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||an(d,l),h=Xt(d,t,o,"highlight",i,{...l,onInfo:c,onWarn:u});if(h?.error||!h?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:h?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let g=h.paragraph,v=f.serializeToString(g),w=xi(v,r,n,{generateRedlines:s,author:a,_revisionIdAllocator:p});if(!w||w===v)return{documentXml:e,hasChanges:!1};let{replacementNodes:y}=kr(w),x=g.parentNode;for(let b of y){let I=d.importNode(b,!0);let N=x.insertBefore(I,g);l?._mutationLiveNodes?.push(N)}return l?._mutationRemovedNodes?.push(g),x.removeChild(g),ot(d),{documentXml:at(d,f,e,m),hasChanges:!0}}async function iu(e,t,r,n,a,o=null,i=null,l={}){let s=typeof l?.onInfo=="function"?l.onInfo:()=>{},c=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=_r(e,l);if(!f)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||an(f,l);let m=Xt(f,t,o,"comment",i,{...l,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,h=u.serializeToString(p),g=typeof r=="string"&&r.length>0?r:Qn(p),v=vi(h,[{paragraphIndex:1,textToFind:g,commentContent:n}],{author:a,commentIdAllocator:l.commentIdAllocator});if(v.status==="error"||v.error||!v.commentsApplied)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:v.error||{code:"ANCHOR_INSERTION_FAILED",message:"The comment anchor was not applied to the resolved paragraph."},warnings:v.warnings||[]};let{replacementNodes:w}=kr(v.oxml),y=p.parentNode;for(let x of w){let b=f.importNode(x,!0);let I=y.insertBefore(b,p);l?._mutationLiveNodes?.push(I)}if(l?._mutationRemovedNodes?.push(p),y.removeChild(p),ot(f),d?.receiptCollector&&Array.isArray(v.placedComments))for(let x of v.placedComments)d.receiptCollector.recordComment(x.id);return{documentXml:at(f,u,e,d),hasChanges:!0,commentsXml:v.commentsXml||null,warnings:v.warnings||[],resolvedAnchor:v.resolvedAnchors?.[0]||null}}function Qc(e,t,r,n){let a=t.cloneNode(!0),o=t.cloneNode(!0);At(o,n);let i=d=>{if(d.nodeType!==1)return!1;let m=d.localName||d.nodeName.replace(/^w:/,"");return["t","tab","br","noBreakHyphen","delText"].includes(m)};Array.from(a.childNodes).forEach(d=>{i(d)&&a.removeChild(d)}),Array.from(o.childNodes).forEach(d=>{i(d)&&o.removeChild(d)});let l="";for(let d of Array.from(t.childNodes)){if(d.nodeType!==1)continue;let m=d.localName||d.nodeName.replace(/^w:/,"");m==="t"?l+=d.textContent||"":m==="tab"?l+=" ":m==="br"?l+=`
224
+ `:m==="noBreakHyphen"&&(l+="\u2011")}let s=l.slice(0,r),c=l.slice(r),u=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let h of p)if(h)if(h===" ")d.appendChild(L(e,"w:tab"));else if(h===`
225
+ `)d.appendChild(L(e,"w:br"));else if(h==="\u2011")d.appendChild(L(e,"w:noBreakHyphen"));else{let g=L(e,"w:t");/^\s|\s$/.test(h)&&g.setAttribute("xml:space","preserve"),g.textContent=h,d.appendChild(g)}};u(a,s),u(o,c);let f=t.parentNode;return f.insertBefore(a,t),f.insertBefore(o,t),f.removeChild(t),[a,o]}async function su(e,t,r,n={},a,o=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},u=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:f,xmlDoc:d,operationSession:m}=_r(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||an(d,l),h=Xt(d,t,o,"format",i,{...l,onInfo:c,onWarn:u});if(h?.error||!h?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:h?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let g=h.paragraph,w=(()=>{let R=[],O=Array.from(g.getElementsByTagNameNS(ne,"r"));for(let P of O){let C=P.parentNode,k=!1;for(;C&&C!==g;){if(C.nodeType===1&&(C.localName==="del"||C.nodeName==="w:del")){k=!0;break}C=C.parentNode}if(k)continue;let D="";for(let z of Array.from(P.childNodes)){if(z.nodeType!==1)continue;let H=z.localName||z.nodeName.replace(/^w:/,"");H==="t"?D+=z.textContent||"":H==="tab"?D+=" ":H==="br"?D+=`
226
+ `:H==="noBreakHyphen"&&(D+="\u2011")}D.length>0&&R.push({run:P,text:D})}return R})(),y="",x=[];for(let R of w){let O=y.length;y+=R.text;let P=y.length;x.push({...R,start:O,end:P})}let I=l.targetDescriptor?.occurrence??null,N=-1;if(I!=null&&I>0){let R=0,O=0;for(;O<=y.length-r.length;){let P=y.indexOf(r,O);if(P===-1)break;if(R++,R===I){N=P;break}O=P+1}}else N=y.indexOf(r);if(N===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let T=N+r.length,S=[];for(let R of x)if(R.start<N&&R.end>N){let O=N-R.start,[P,C]=Qc(d,R.run,O,p);S.push({run:P,start:R.start,end:N,text:R.text.slice(0,O)}),S.push({run:C,start:N,end:R.end,text:R.text.slice(O)})}else S.push(R);let E=[];for(let R of S)if(R.start<T&&R.end>T){let O=T-R.start,[P,C]=Qc(d,R.run,O,p);E.push({run:P,start:R.start,end:T,text:R.text.slice(0,O)}),E.push({run:C,start:T,end:R.end,text:R.text.slice(O)})}else E.push(R);let _=E.filter(R=>R.start>=N&&R.end<=T),A=!1;for(let R of _){let O=R.run.getElementsByTagNameNS(ne,"rPr")[0]||null;if(Hs(O,n)){A=!0;break}}if(!A)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let R of _){let O=R.run,P=O.getElementsByTagNameNS(ne,"rPr")[0];P||(P=L(d,"w:rPr"),O.insertBefore(P,O.firstChild));let C=O.parentNode,k=!1;for(;C&&C!==g;){if(C.nodeType===1&&(C.localName==="ins"||C.nodeName==="w:ins")){(C.getAttribute("w:author")||C.getAttributeNS(ne,"author"))===(a||re())&&(k=!0);break}C=C.parentNode}let D=k&&l.formattingRevisionPolicy==="coalesce-own-insertion";s&&!D&&Nn(d,P,a||re()),Gs(d,P,n)}return ot(d),l?._mutationLiveNodes?.push(g),{documentXml:at(d,f,e,m),hasChanges:!0,status:"ok"}}async function lu(e,t,r={},n,a=null,o=null,i={}){let l=i.generateRedlines!==!1,s=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:u,xmlDoc:f,operationSession:d}=_r(e,i);if(!f)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||an(f,i);let m=Xt(f,t,a,"paragraph-format",o,{...i,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,h=p.getElementsByTagNameNS(ne,"pPr")[0];return h||(h=L(f,"w:pPr"),p.insertBefore(h,p.firstChild)),qs(h,r)?(l&&al(f,h,n||re()),Ys(f,h,r),ot(f),i?._mutationLiveNodes?.push(p),{documentXml:at(f,u,e,d),hasChanges:!0,status:"ok"}):{documentXml:e,hasChanges:!1,status:"no-op"}}function Ie(e,t={}){return bt(e,t)}async function Fi(e,t,r,n=null,a={}){let o=typeof a._operationIndex=="number"?a._operationIndex:1,i={operationIndex:o,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},l=Ut(t);if(!l.valid){let g=dt(t,r,re());return{documentXml:e,hasChanges:!1,status:"error",error:Ie(l.error,i),operationType:Ze(t).operationKind,authorUsed:g,receipt:Ce(o,t?.operationId,g,"refused")}}let s=l.operation||Ze(t),c=dt(s,r,re());if(s.operationKind!=="comment_reply"&&s.operationKind!=="rejected-insert"&&s.operationKind!=="restore"&&(s.targetDescriptor?.revisionView==="rejected"||s.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Ie({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};if(!a?._documentOperationSession&&a?.expectedRevision){let g=Pr(a.expectedRevision);if(!g.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ie({code:g.error?.code||"INVALID_REVISION_TOKEN",message:g.error?.message||"Invalid revision token."},i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};if(a.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Ie({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${a.expectedRevision.scope}'.`},i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};let v=await Un({documentXml:e,commentsXml:n?.commentsXml||a.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||a.commentsExtendedXml,numberingXml:n?.numberingXml||a.numberingXml,stylesXml:n?.stylesXml||a.stylesXml},a);if(!Cr(v.value,a.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Ie({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${a.expectedRevision.value}', current is '${v.value}'.`,expectedRevision:a.expectedRevision,currentRevision:v},i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")}}let u=a?._documentOperationSession instanceof ir?a._documentOperationSession:new ir(e,a);if(!u.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ie(u.parseResult.error,i),warnings:u.parseResult.warnings,operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};if(Array.isArray(s.replacements)||s.operationKind==="restore"&&t?.modified===void 0){let g=on(u.document,[t],{strictTargets:a.strictTargets!==!1,onInfo:a.onInfo,onWarn:a.onWarn}),v=g.bindings[0]?.error||g.conflicts[0]||null;if(v)return{documentXml:e,hasChanges:!1,status:"error",error:Ie(v,i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};let w=Ut(g.compiledOperations[0]);if(!w.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ie(w.error,i),operationType:s.operationKind,authorUsed:c,receipt:Ce(o,s.operationId,c,"refused")};u.sourceTargetRegistry=g.registry,s=w.operation}let f={},d=null,m=u.createSavepoint();u.receiptCollector?.beginOperation(o,s.operationId,c);let p=Array.isArray(s._compiledWarnings)?[...s._compiledWarnings]:[],h={...a,...typeof s.generateRedlines=="boolean"?{generateRedlines:s.generateRedlines}:{},...s.existingRevisions?{existingRevisions:s.existingRevisions}:{},structuredContent:typeof s.structuredContent=="boolean"?s.structuredContent:a.structuredContent!==!1,explicitStructuredContent:s.structuredContent===!0,pairReplacements:typeof s.pairReplacements=="boolean"?s.pairReplacements:a.pairReplacements!==!1,...s.insertionAffinity?{insertionAffinity:s.insertionAffinity}:{},...s.formattingRevisionPolicy?{formattingRevisionPolicy:s.formattingRevisionPolicy}:{},targetDescriptor:s.targetDescriptor,targetEndDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceId||null,_compiledSourceEndId:s._compiledSourceEndId||null,_compiledResolvedBy:s._compiledResolvedBy||null,_sourceTargetRegistry:u.sourceTargetRegistry||null,_resolutionCapture:f,_revisionIdAllocator:u.revisionIdAllocator,_documentOperationSession:u,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:g=>{typeof a?.onInfo=="function"&&a.onInfo(g)},onWarn:g=>{p.push(String(g)),typeof a?.onWarn=="function"&&a.onWarn(g)}};try{let g;if(s.operationKind==="comment_reply"){let y=u.commentsXml||n?.commentsXml||a.commentsXml,x=u.commentsExtendedXml||n?.commentsExtendedXml||a.commentsExtendedXml,b=typeof a.commentIdAllocator=="function"?a.commentIdAllocator():null;if(b==null&&y){let I=[...y.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(N=>Number(N[1]));b=(I.length?Math.max(...I):-1)+1}b==null?g={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(g=yi({commentsXml:y,commentsExtendedXml:x,parentCommentId:s.parentCommentId,commentId:b,commentContent:s.commentContent,author:c,date:s.date||new Date().toISOString()}),g.documentXml=e,g.hasChanges&&u.receiptCollector&&u.receiptCollector.recordComment(b))}else s.operationKind==="highlight"?g=await ou(e,s.target,s.textToHighlight,s.color,c,s.targetRef,n,h):s.operationKind==="comment"?g=await iu(e,s.target,s.textToComment,s.commentContent,c,s.targetRef,n,h):s.operationKind==="format"?g=await su(e,s.target,s.textToFormat,s.properties,c,s.targetRef,n,h):s.operationKind==="paragraph-format"?g=await lu(e,s.target,s.properties,c,s.targetRef,n,h):s.operationKind==="rejected-insert"?g=await ru(e,s.target,s.anchor,s.modified,c,s.targetRef,n,h):s.operationKind==="restore"?g=await nu(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,h):g=await au(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,h);if((s.operationKind==="comment"||s.operationKind==="comment_reply")&&g?.hasChanges!==!0&&g?.status!=="error"&&!g?.error&&(g={...g,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),p.length>0&&g){let y=Array.from(new Set([...Array.isArray(g.warnings)?g.warnings:[],...p]));g.warnings=y}let v=g?.status==="error"||!!g?.error,w=null;if(v||g?.hasChanges!==!0){u.restoreSavepoint(m);let y=v?"refused":"no_change";if(w=Ce(o,s.operationId,c,y),Array.isArray(g?.warnings))for(let x of g.warnings)w.warnings.push(String(x))}else{let y=yt(m.document),x=yt(u.document),b=sn(x.issues,y.issues),I=ln(b);if(I.length>0){u.restoreSavepoint(m),w=Ce(o,s.operationId,c,"refused");let N=[...new Set(I.map(T=>T.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Ie({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${N}).`,generatedIssues:I},i),operationType:s.operationKind,authorUsed:c,receipt:w,...f}}if(u.markMutationCommitted(s.operationKind!=="comment_reply"),s._compiledSourceId&&u.sourceTargetRegistry&&u.sourceTargetRegistry.commitMutation(s._compiledSourceId,h._mutationRemovedNodes,h._mutationLiveNodes,o),s._localizedReplacementCompilation){let N=null;if(s.operationKind==="restore"){let T=h._mutationLiveNodes.find(S=>S?.localName==="p");T&&(N=te(T,{revisionView:"accepted"}))}else if(s._compiledSourceId&&u.sourceTargetRegistry){let T=u.sourceTargetRegistry.resolve(s._compiledSourceId,u.document);T.paragraph&&(N=te(T.paragraph,{revisionView:"accepted"}))}d=kc(s._localizedReplacementCompilation,N,f.resolvedTarget||{},s._speculativeContext||null)}if(s.captureKey&&u.captureTable&&u.captureTable.set(s.captureKey,jc(u,s,h._mutationLiveNodes)),h._mutationRemovedNodes?.length>0&&u.captureTable&&Kc(u.captureTable,h._mutationRemovedNodes),f.resolvedTarget&&u.receiptCollector?.recordAffectedTarget(f.resolvedTarget),Array.isArray(g.warnings))for(let N of g.warnings)u.receiptCollector?.recordWarning(N);if(w=u.receiptCollector?.commitOperation("applied"),g.documentXml=u.deferSerialization?u.currentDocumentXml:u.serializeCurrent(),!u.deferSerialization&&w){let N=Yn({documentXml:g.documentXml,commentsXml:g.commentsXml||null,numberingXml:g.numberingXml||null},[w]);if(!N.valid)return u.restoreSavepoint(m),w.finalDisposition="rolled_back",w.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Ie(N.error,i),warnings:[N.error.message],operationType:s.operationKind,authorUsed:c,receipt:w,...f}}}return g?.error&&(g.error=Ie(g.error,i)),{...g,operationType:s.operationKind,authorUsed:c,receipt:w,...d?{change:d}:{},...f}}catch(g){u.restoreSavepoint(m);let v=Ie(g,i),w=Ce(o,s.operationId,c,"refused");return w.warnings.push(v.message),{documentXml:e,hasChanges:!1,status:"error",error:v,warnings:[v.message],operationType:s.operationKind,authorUsed:c,receipt:w,...f}}}var cu="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function uu(e){return e?.type==="comment"||e?.type==="comment_reply"?0:1}function co(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.captureKey??u?.targetDescriptor?.captureKey;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=f.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),a=Array.from({length:t.length},()=>new Set),o=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let u=t[c],f=u?.target?.captureRef??u?.targetDescriptor?.captureRef;if(f!=null){if(typeof f!="string"||!f.trim()||f.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=f.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};o[c].has(m)||(o[c].add(m),a[m].add(c),n[c]++);let p=Ze(u).operationKind;p!=="comment"&&p!=="comment_reply"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:u?.target?.select??u?.targetDescriptor?.select??null}))}}for(let[c,u]of i){if(u.length<2)continue;let f=u.map(m=>m.select),d=new Set(f);if(!(f.every(m=>typeof m=="string"&&m.length>0)&&d.size===f.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${u.map(m=>m.index+1).join(", ")}.`,operationIndexes:u.map(m=>m.index+1),captureRef:c}}}let l=[];for(let c=0;c<t.length;c++)n[c]===0&&l.push({operation:t[c],index:c});let s=[];for(;l.length>0;){l.sort((u,f)=>uu(u.operation)-uu(f.operation)||u.index-f.index);let c=l.shift();s.push(c);for(let u of a[c.index])n[u]--,n[u]===0&&l.push({operation:t[u],index:u})}return s.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:s,captureProducers:r}}function fg(e,t){if(!t)return e;if(!e)return t;let r=j(e,"application/xml")?.doc,n=j(t,"application/xml")?.doc;if(!r||!n)return e;let a=ce(),o=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(cu,"comment")).map(l=>l.getAttribute("w:id")||l.getAttribute("id")).filter(Boolean));for(let l of Array.from(n.getElementsByTagNameNS(cu,"comment"))){let s=l.getAttribute("w:id")||l.getAttribute("id");s&&i.has(s)||(o.appendChild(r.importNode(l,!0)),s&&i.add(s))}return a.serializeToString(r)}async function $i(e,t,r,n=null,a={}){let o=Array.isArray(t)?t:[],i=re(),l=()=>o.map((A,R)=>Ce(R+1,A?.operationId,dt(A,r,i),"not_attempted")),s=(A,R={})=>{let O=l();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:O,executionOrder:[],authorsUsed:[],...a.atomic===!0?{rolledBack:!0}:{},status:"error",error:Ie(A),retryPlan:or({atomic:a.atomic===!0,rolledBack:a.atomic===!0,results:[],receipts:O,operationCount:o.length}),...R}};if(a.existingRevisions!=null&&!Jn(a.existingRevisions))return s({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(a.existingRevisions)}".`,field:"existingRevisions"});if(a?.expectedRevision){let A=Pr(a.expectedRevision);if(!A.valid)return s({code:A.error?.code||"INVALID_REVISION_TOKEN",message:A.error?.message||"Invalid revision token."});if(a.expectedRevision.scope!=="document-parts")return s({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${a.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:a.expectedRevision.scope});let R=await Un({documentXml:e,commentsXml:n?.commentsXml||a.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||a.commentsExtendedXml,numberingXml:n?.numberingXml||a.numberingXml,stylesXml:n?.stylesXml||a.stylesXml},a);if(!Cr(R.value,a.expectedRevision.value))return s({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${a.expectedRevision.value}', current is '${R.value}'.`,expectedRevision:a.expectedRevision,currentRevision:R})}let c=a?._documentOperationSession instanceof ir?a._documentOperationSession:new ir(e,{...a,_deferDocumentSerialization:!0});if(!c.valid)return s(c.parseResult.error,{warnings:c.parseResult.warnings});let u=on(c.document,o,{strictTargets:a.strictTargets!==!1,onInfo:a.onInfo,onWarn:a.onWarn});if(c.sourceTargetRegistry=u.registry,u.conflicts.length>0){let A=new Map;for(let P of u.conflicts)for(let C of P.operationIndexes)A.has(C)||A.set(C,P);let R=Array.from(A,([P,C])=>{let k=o[P-1],D=dt(k,r,i),z=Ie(C,{operationIndex:P,...k?.operationId?{operationId:k.operationId}:{}});return{index:P,type:k?.type||"redline",operationType:Ze(k).operationKind,status:"error",authorUsed:D,error:z,receipt:Ce(P,k?.operationId,D,"refused")}}).sort((P,C)=>P.index-C.index),O=o.map((P,C)=>R.find(D=>D.index===C+1)?.receipt||Ce(C+1,P?.operationId,dt(P,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:R,receipts:O,executionOrder:[],authorsUsed:[],rolledBack:a.atomic===!0,status:"error",error:Ie(u.conflicts[0]),conflicts:u.conflicts.map(P=>Ie(P)),retryPlan:or({atomic:a.atomic===!0,rolledBack:a.atomic===!0,results:R,receipts:O,operationCount:o.length})}}let f=u.compiledOperations,d=co(f);if(!d.valid)return s(d.error);let m=d.scheduled,p=a.atomic===!0,h=a.continueOnError!==!1,g=Bc(n);g.targetRefSnapshot instanceof Map||(g.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=g,o.some(A=>A?.type==="comment_reply")&&(c.commentsXml=g.commentsXml||a.commentsXml||null,c.commentsExtendedXml=g.commentsExtendedXml||a.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let v=!1,w=c.results,y=c.executionOrder,x=c.authorsUsed,b=!1;for(let{operation:A,index:R}of m){y.push(R+1);let O=u.bindings[R];if(O?.error){b=!0;let P=dt(A,r,i),C=Ce(R+1,A?.operationId,P,"refused"),k=Ie(O.error,{operationIndex:R+1,...A?.operationId?{operationId:A.operationId}:{}});if(C.warnings.push(k.message),w.push({index:R+1,type:A?.type||"redline",status:"error",operationType:Ze(A).operationKind,authorUsed:P,warnings:[k.message],error:k,receipt:C}),!h)break;continue}try{let P=await Fi(c.currentDocumentXml,A,r,g,{...a,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:R+1});v=v||P.hasChanges===!0,c.commentsXml=P.commentsXmlMode==="replace"?P.commentsXml||c.commentsXml:fg(c.commentsXml,P.commentsXml||null),c.commentsExtendedXml=(P.commentsExtendedXmlMode==="replace",P.commentsExtendedXml||c.commentsExtendedXml),P.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),P.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),P.numberingXml&&c.numberingXmlParts.push(P.numberingXml);let C=P.status==="error"||!!P.error;if(b=b||C,!C&&P.hasChanges&&P.authorUsed&&x.add(P.authorUsed),w.push({index:R+1,type:A?.type||"redline",status:C?"error":P.hasChanges?"applied":"no_change",operationType:P.operationType||"redline",authorUsed:P.authorUsed,...P.resolvedBy?{resolvedBy:P.resolvedBy}:{},...P.resolvedTarget?{resolvedTarget:P.resolvedTarget}:{},...P.resolvedAnchor?{resolvedAnchor:P.resolvedAnchor}:{},...P.change?{change:P.change}:{},...Array.isArray(P.warnings)&&P.warnings.length>0?{warnings:P.warnings}:{},...P.error?{error:P.error}:{},...P.receipt?{receipt:P.receipt}:{}}),C&&!h)break}catch(P){let C=Ie(P,{operationIndex:R+1,...A?.operationId?{operationId:A.operationId}:{}});b=!0;let k=dt(A,r,re()),D=Ce(R+1,A?.operationId,k,"refused");if(D.warnings.push(C.message),w.push({index:R+1,type:A?.type||"redline",status:"error",operationType:Ze(A).operationKind,authorUsed:k,warnings:[C.message],error:C,receipt:D}),!h)break}}w.sort((A,R)=>A.index-R.index);let I=[];for(let A=0;A<o.length;A++){let R=A+1,O=w.find(P=>P.index===R);if(O?.receipt)I.push(O.receipt);else{let P=Ce(R,o[A]?.operationId,dt(o[A],r,i),"not_attempted");I.push(P)}}let N=p&&b,T=e,S=null;if(!N&&v)try{T=c.serializeCurrent()}catch(A){S=Ie(A),N=!0}let E=null;if(!N&&v){let A=Yn({documentXml:T,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},I);A.valid||(E=A.error,p&&(N=!0))}if(N){for(let A of w)A.receipt&&A.receipt.attemptedDisposition==="applied"&&(A.receipt.finalDisposition="rolled_back",A.receipt.committed=!1),A.change&&(A.change.finalDisposition="rolled_back",A.change.committed=!1);for(let A of I)A.attemptedDisposition==="applied"&&(A.finalDisposition="rolled_back",A.committed=!1)}else{for(let A of w)A.receipt&&A.receipt.attemptedDisposition==="applied"&&(A.receipt.committed=!0,A.receipt.finalDisposition="applied"),A.change&&(A.change.finalDisposition="applied",A.change.committed=!0);for(let A of I)A.attemptedDisposition==="applied"&&(A.committed=!0,A.finalDisposition="applied")}N||Dc(n,g);let _={documentXml:N?c.rollback():T,hasChanges:N?!1:v,commentsXml:N?null:c.commentsXml,commentsExtendedXml:N?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:N?[]:c.numberingXmlParts,results:[...w].sort((A,R)=>(A.index||0)-(R.index||0)),receipts:I.sort((A,R)=>A.operationIndex-R.operationIndex),executionOrder:y,authorsUsed:N?[]:Array.from(x),...N?{rolledBack:!0,status:"error",error:Ie({code:E?E.code:S?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:E?.message||S?.message||"Atomic batch rolled back because one or more operations failed."})}:E?{status:"error",error:Ie(E)}:b?{status:v?"partial":"error",error:Ie({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(_.status==="error"||_.status==="partial")&&(_.retryPlan=or({atomic:p,rolledBack:N,results:_.results,receipts:_.receipts,operationCount:o.length})),_}function cn(e,t={}){return bt(e,t)}function dg(e){return e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function mg(e,t,r,n,a=null,o="accepted"){let i=a?.byParagraph?.get(t)||null,l=i?null:oe(e),s=i?.text??te(t,{revisionView:o}),c=Y(n||""),u=Y(s);return{resolvedBy:r,resolvedTarget:{index:i?.index??l.indexOf(t)+1,paragraphId:i?.paragraphId??$e(t),text:s,fingerprint:i?.fingerprint??rt(t,{text:s,revisionView:o}),inTable:i?.inTable??!!Ve(t,"tbl"),revisionView:o},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===s,normalizedTextMatch:!!c&&c===u,suppliedText:n||"",actualText:s,revisionView:o}}}function fu(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let a=n.getAttribute("w:id")||n.getAttribute("id");a!==""&&t.add(a)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Ui(e,t,r,n={}){if(n.existingRevisions!=null&&!Jn(n.existingRevisions))return{valid:!1,status:"error",error:cn({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=j(e,"application/xml");if(a.error||!a.doc)return{valid:!1,status:"error",error:cn(a.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=a.doc,i={accepted:Pt(o,{revisionView:"accepted"}),rejected:null},l=Array.isArray(t)?t:[],s=on(o,l,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=co(s.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:cn(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let u=n.strictTargets!==!1,f=[],d=new Set,m=!1,p=!1;for(let y=0;y<l.length;y++){let x=l[y],b=s.bindings[y],I=s.compiledOperations[y],N=!b?.error&&I?._localizedReplacementCompilation?I:x,T=Ut(N),S=Ze(x),E=T.operation||S,_=dt(E,r,re());if(d.add(_),!T.valid){f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:"error",authorUsed:_,error:T.error});continue}if(m=m||E.operationKind==="comment"||E.operationKind==="comment_reply",p=p||dg(E),E.operationKind==="comment_reply"){let O=String(E.parentCommentId),P=n._existingCommentDetails?.[O];f.push(P?{index:y+1,type:x.type,operationType:E.operationKind,status:"ready",authorUsed:_,resolvedBy:"parent_comment",parentCommentId:O}:{index:y+1,type:x.type,operationType:E.operationKind,status:"error",authorUsed:_,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${O}' was not found.`}});continue}if(E.targetDescriptor?.captureRef){f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:"deferred",authorUsed:_,resolvedBy:"capture",captureRef:E.targetDescriptor.captureRef,...E.targetDescriptor.select?{select:E.targetDescriptor.select}:{}});continue}if(b?.error){f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:"error",authorUsed:_,error:b.error});continue}if(b?.createdByOperation){f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:"deferred",authorUsed:_,resolvedBy:"created_content_dependency",captureRef:b.captureRef,select:E.targetDescriptor.text,createdByOperation:b.createdByOperation});continue}let A=E.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",R=A==="rejected"?i.rejected||(i.rejected=Pt(o,{revisionView:"rejected"})):i.accepted;try{let O;if(b.dynamic)O=Sr(o,{targetText:E.target,targetRef:E.targetRef,targetDescriptor:E.targetDescriptor,opType:E.operationKind,strictAmbiguity:u,paragraphMetadataIndex:R,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let J=s.registry.resolve(b.sourceIds[0],o);if(J.error)throw Object.assign(new Error(J.error.message),J.error);O={paragraph:J.paragraph,resolvedBy:b.resolvedBy,warnings:b.warnings}}let P=O.paragraph,C=mg(o,P,O.resolvedBy,E.target,R,A),k=C.resolvedTarget.text,D=E.operationKind==="comment"?E.textToComment||k:E.operationKind==="highlight"?E.textToHighlight:E.operationKind==="format"?E.textToFormat:null,z=E.operationKind==="comment"&&D!=null?Wn(Qr(P,{revisionView:A}),D):null,H=D==null||(z?z.found:k.includes(D)),G=Yt(P),Z=E.existingRevisions||n.existingRevisions||"merge-same-author",ue=E.operationKind==="redline"&&E.modified===""?fu(P):[],W=null;if(E.operationKind==="restore"){let J=E.targetEndRef?jr(o,E.targetRef,E.targetEndRef,{opType:"restore",targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn}):[P];if(!E.targetEndRef&&E.targetEndDescriptor){let le=Sr(o,{targetText:E.targetEndDescriptor.text,targetRef:E.targetEndDescriptor.index,targetDescriptor:E.targetEndDescriptor,opType:"restore",strictAmbiguity:u,paragraphMetadataIndex:R,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),ge=oe(o),X=ge.indexOf(P),U=ge.indexOf(le?.paragraph);J=X>=0&&U>=X?ge.slice(X,U+1):null}let Re=Array.isArray(E.modified)?E.modified:[E.modified];if(!J||J[0]!==P||Re.length!==J.length)W={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let le of J){let ge=br(le);if(ge?.code==="UNSUPPORTED_MOVE_REVISION"){W=ge;break}let X=rr(le,_),U=X.matches?ge||br(le):null;if(!X.matches){W={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...X.ownerAuthor?{ownerAuthor:X.ownerAuthor}:{}};break}if(U){W=U;break}}}else if(!H)W=z?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${D}".`};else if(ue.length>0){let J=ue.map(Re=>n._existingCommentDetails?.[Re]).filter(Boolean);W={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:ue,...J.length>0?{comments:J}:{}}}else if(E.operationKind==="redline"&&G&&Z!=="accept-all-first"&&Z!=="accept-all-first-keep-normalized")if(Z==="merge-same-author"||Z==="slice-cross-author"){let J=dr(P),Re=String(_||"").trim().toLowerCase(),le=J.length>0&&J.every(ge=>ge.trim().toLowerCase()===Re);if(!le&&Z==="merge-same-author")W={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${J.length?J.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:J,currentPolicy:Z};else if(le){let ge=fu(P);if(ge.length>0){let X=ge.map(U=>n._existingCommentDetails?.[U]).filter(Boolean);W={code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:ge,...X.length>0?{comments:X}:{}}}}else(P.getElementsByTagNameNS(M,"moveFrom").length>0||P.getElementsByTagNameNS(M,"moveTo").length>0)&&(W={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let J=P.getElementsByTagNameNS(M,"del").length>0,Re=P.getElementsByTagNameNS(M,"moveFrom").length>0||P.getElementsByTagNameNS(M,"moveTo").length>0;J?W={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:Re?W={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:W={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!W&&E.operationKind==="redline"){let J=La(P,E.modified,n);J.valid||(W={code:J.code,message:J.message})}f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:W?"error":"ready",authorUsed:_,...C,anchor:D==null?null:{text:D,found:H,...z?.found?{resolvedBy:z.resolvedBy,start:z.start,end:z.end}:{},...!z?.found&&Array.isArray(z?.error?.candidates)?{candidates:z.error.candidates}:{}},hasRevisions:G,existingRevisions:Z,...O?.warnings?.length?{warnings:O.warnings}:{},...W?{error:W}:{}})}catch(O){f.push({index:y+1,type:x?.type||"redline",operationType:E.operationKind,status:"error",authorUsed:_,error:cn(O)})}}let h=s.conflicts,g=f.map(y=>y.error?{...y,error:cn(y.error,{operationIndex:y.index,...l[y.index-1]?.operationId?{operationId:l[y.index-1].operationId}:{}})}:y),v=h.map(y=>cn(y)),w=g.some(y=>y.status==="error");return{valid:!w&&v.length===0,status:!w&&v.length===0?"ok":"error",results:g,conflicts:v,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var We=Uint8Array,it=Uint16Array,Gi=Int32Array,uo=new We([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),fo=new We([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Wi=new We([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),gu=function(e,t){for(var r=new it(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var a=new Gi(r[30]),n=1;n<30;++n)for(var o=r[n];o<r[n+1];++o)a[o]=o-r[n]<<5|n;return{b:r,r:a}},hu=gu(uo,2),wu=hu.b,ji=hu.r;wu[28]=258,ji[258]=28;var vu=gu(fo,0),pg=vu.b,du=vu.r,Ki=new it(32768);for(ie=0;ie<32768;++ie)Vt=(ie&43690)>>1|(ie&21845)<<1,Vt=(Vt&52428)>>2|(Vt&13107)<<2,Vt=(Vt&61680)>>4|(Vt&3855)<<4,Ki[ie]=((Vt&65280)>>8|(Vt&255)<<8)>>1;var Vt,ie,Ct=(function(e,t,r){for(var n=e.length,a=0,o=new it(t);a<n;++a)e[a]&&++o[e[a]-1];var i=new it(t);for(a=1;a<t;++a)i[a]=i[a-1]+o[a-1]<<1;var l;if(r){l=new it(1<<t);var s=15-t;for(a=0;a<n;++a)if(e[a])for(var c=a<<4|e[a],u=t-e[a],f=i[e[a]-1]++<<u,d=f|(1<<u)-1;f<=d;++f)l[Ki[f]>>s]=c}else for(l=new it(n),a=0;a<n;++a)e[a]&&(l[a]=Ki[i[e[a]-1]++]>>15-e[a]);return l}),sr=new We(288);for(ie=0;ie<144;++ie)sr[ie]=8;var ie;for(ie=144;ie<256;++ie)sr[ie]=9;var ie;for(ie=256;ie<280;++ie)sr[ie]=7;var ie;for(ie=280;ie<288;++ie)sr[ie]=8;var ie,na=new We(32);for(ie=0;ie<32;++ie)na[ie]=5;var ie,gg=Ct(sr,9,0),hg=Ct(sr,9,1),wg=Ct(na,5,0),vg=Ct(na,5,1),zi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},It=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},Xi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},qi=function(e){return(e+7)/8|0},yu=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new We(e.subarray(t,r))};var yg=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],jt=function(e,t,r){var n=new Error(t||yg[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,jt),!r)throw n;return n},xg=function(e,t,r,n){var a=e.length,o=n?n.length:0;if(!a||t.f&&!t.l)return r||new We(0);var i=!r,l=i||t.i!=2,s=t.i;i&&(r=new We(a*3));var c=function(U){var $=r.length;if(U>$){var K=new We(Math.max($*2,U));K.set(r),r=K}},u=t.f||0,f=t.p||0,d=t.b||0,m=t.l,p=t.d,h=t.m,g=t.n,v=a*8;do{if(!m){u=It(e,f,1);var w=It(e,f+1,3);if(f+=3,w)if(w==1)m=hg,p=vg,h=9,g=5;else if(w==2){var I=It(e,f,31)+257,N=It(e,f+10,15)+4,T=I+It(e,f+5,31)+1;f+=14;for(var S=new We(T),E=new We(19),_=0;_<N;++_)E[Wi[_]]=It(e,f+_*3,7);f+=N*3;for(var A=zi(E),R=(1<<A)-1,O=Ct(E,A,1),_=0;_<T;){var P=O[It(e,f,R)];f+=P&15;var y=P>>4;if(y<16)S[_++]=y;else{var C=0,k=0;for(y==16?(k=3+It(e,f,3),f+=2,C=S[_-1]):y==17?(k=3+It(e,f,7),f+=3):y==18&&(k=11+It(e,f,127),f+=7);k--;)S[_++]=C}}var D=S.subarray(0,I),z=S.subarray(I);h=zi(D),g=zi(z),m=Ct(D,h,1),p=Ct(z,g,1)}else jt(1);else{var y=qi(f)+4,x=e[y-4]|e[y-3]<<8,b=y+x;if(b>a){s&&jt(0);break}l&&c(d+x),r.set(e.subarray(y,b),d),t.b=d+=x,t.p=f=b*8,t.f=u;continue}if(f>v){s&&jt(0);break}}l&&c(d+131072);for(var H=(1<<h)-1,G=(1<<g)-1,Z=f;;Z=f){var C=m[Xi(e,f)&H],pe=C>>4;if(f+=C&15,f>v){s&&jt(0);break}if(C||jt(2),pe<256)r[d++]=pe;else if(pe==256){Z=f,m=null;break}else{var ue=pe-254;if(pe>264){var _=pe-257,W=uo[_];ue=It(e,f,(1<<W)-1)+wu[_],f+=W}var J=p[Xi(e,f)&G],Re=J>>4;J||jt(3),f+=J&15;var z=pg[Re];if(Re>3){var W=fo[Re];z+=Xi(e,f)&(1<<W)-1,f+=W}if(f>v){s&&jt(0);break}l&&c(d+131072);var le=d+ue;if(d<z){var ge=o-z,X=Math.min(z,le);for(ge+d<0&&jt(3);d<X;++d)r[d]=n[ge+d]}for(;d<le;++d)r[d]=r[d-z]}}t.l=m,t.p=Z,t.b=d,t.f=u,m&&(u=1,t.m=h,t.d=p,t.n=g)}while(!u);return d!=r.length&&i?yu(r,0,d):r.subarray(0,d)},Wt=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},ta=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Vi=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var a=r.length,o=r.slice();if(!a)return{t:bu,l:0};if(a==1){var i=new We(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(b,I){return b.f-I.f}),r.push({s:-1,f:25001});var l=r[0],s=r[1],c=0,u=1,f=2;for(r[0]={s:-1,f:l.f+s.f,l,r:s};u!=a-1;)l=r[r[c].f<r[f].f?c++:f++],s=r[c!=u&&r[c].f<r[f].f?c++:f++],r[u++]={s:-1,f:l.f+s.f,l,r:s};for(var d=o[0].s,n=1;n<a;++n)o[n].s>d&&(d=o[n].s);var m=new it(d+1),p=Hi(r[u-1],m,0);if(p>t){var n=0,h=0,g=p-t,v=1<<g;for(o.sort(function(I,N){return m[N.s]-m[I.s]||I.f-N.f});n<a;++n){var w=o[n].s;if(m[w]>t)h+=v-(1<<p-m[w]),m[w]=t;else break}for(h>>=g;h>0;){var y=o[n].s;m[y]<t?h-=1<<t-m[y]++-1:++n}for(;n>=0&&h;--n){var x=o[n].s;m[x]==t&&(--m[x],++h)}p=t}return{t:new We(m),l:p}},Hi=function(e,t,r){return e.s==-1?Math.max(Hi(e.l,t,r+1),Hi(e.r,t,r+1)):t[e.s]=r},mu=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new it(++t),n=0,a=e[0],o=1,i=function(s){r[n++]=s},l=1;l<=t;++l)if(e[l]==a&&l!=t)++o;else{if(!a&&o>2){for(;o>138;o-=138)i(32754);o>2&&(i(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(i(a),--o;o>6;o-=6)i(8304);o>2&&(i(o-3<<5|8208),o=0)}for(;o--;)i(a);o=1,a=e[l]}return{c:r.subarray(0,n),n:t}},ra=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},xu=function(e,t,r){var n=r.length,a=qi(t+2);e[a]=n&255,e[a+1]=n>>8,e[a+2]=e[a]^255,e[a+3]=e[a+1]^255;for(var o=0;o<n;++o)e[a+o+4]=r[o];return(a+4+n)*8},pu=function(e,t,r,n,a,o,i,l,s,c,u){Wt(t,u++,r),++a[256];for(var f=Vi(a,15),d=f.t,m=f.l,p=Vi(o,15),h=p.t,g=p.l,v=mu(d),w=v.c,y=v.n,x=mu(h),b=x.c,I=x.n,N=new it(19),T=0;T<w.length;++T)++N[w[T]&31];for(var T=0;T<b.length;++T)++N[b[T]&31];for(var S=Vi(N,7),E=S.t,_=S.l,A=19;A>4&&!E[Wi[A-1]];--A);var R=c+5<<3,O=ra(a,sr)+ra(o,na)+i,P=ra(a,d)+ra(o,h)+i+14+3*A+ra(N,E)+2*N[16]+3*N[17]+7*N[18];if(s>=0&&R<=O&&R<=P)return xu(t,u,e.subarray(s,s+c));var C,k,D,z;if(Wt(t,u,1+(P<O)),u+=2,P<O){C=Ct(d,m,0),k=d,D=Ct(h,g,0),z=h;var H=Ct(E,_,0);Wt(t,u,y-257),Wt(t,u+5,I-1),Wt(t,u+10,A-4),u+=14;for(var T=0;T<A;++T)Wt(t,u+3*T,E[Wi[T]]);u+=3*A;for(var G=[w,b],Z=0;Z<2;++Z)for(var pe=G[Z],T=0;T<pe.length;++T){var ue=pe[T]&31;Wt(t,u,H[ue]),u+=E[ue],ue>15&&(Wt(t,u,pe[T]>>5&127),u+=pe[T]>>12)}}else C=gg,k=sr,D=wg,z=na;for(var T=0;T<l;++T){var W=n[T];if(W>255){var ue=W>>18&31;ta(t,u,C[ue+257]),u+=k[ue+257],ue>7&&(Wt(t,u,W>>23&31),u+=uo[ue]);var J=W&31;ta(t,u,D[J]),u+=z[J],J>3&&(ta(t,u,W>>5&8191),u+=fo[J])}else ta(t,u,C[W]),u+=k[W]}return ta(t,u,C[256]),u+k[256]},bg=new Gi([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),bu=new We(0),Ng=function(e,t,r,n,a,o){var i=o.z||e.length,l=new We(n+i+5*(1+Math.ceil(i/7e3))+a),s=l.subarray(n,l.length-a),c=o.l,u=(o.r||0)&7;if(t){u&&(s[0]=o.r>>3);for(var f=bg[t-1],d=f>>13,m=f&8191,p=(1<<r)-1,h=o.p||new it(32768),g=o.h||new it(p+1),v=Math.ceil(r/3),w=2*v,y=function(ee){return(e[ee]^e[ee+1]<<v^e[ee+2]<<w)&p},x=new Gi(25e3),b=new it(288),I=new it(32),N=0,T=0,S=o.i||0,E=0,_=o.w||0,A=0;S+2<i;++S){var R=y(S),O=S&32767,P=g[R];if(h[O]=P,g[R]=O,_<=S){var C=i-S;if((N>7e3||E>24576)&&(C>423||!c)){u=pu(e,s,0,x,b,I,T,E,A,S-A,u),E=N=T=0,A=S;for(var k=0;k<286;++k)b[k]=0;for(var k=0;k<30;++k)I[k]=0}var D=2,z=0,H=m,G=O-P&32767;if(C>2&&R==y(S-G))for(var Z=Math.min(d,C)-1,pe=Math.min(32767,S),ue=Math.min(258,C);G<=pe&&--H&&O!=P;){if(e[S+D]==e[S+D-G]){for(var W=0;W<ue&&e[S+W]==e[S+W-G];++W);if(W>D){if(D=W,z=G,W>Z)break;for(var J=Math.min(G,W-2),Re=0,k=0;k<J;++k){var le=S-G+k&32767,ge=h[le],X=le-ge&32767;X>Re&&(Re=X,P=le)}}}O=P,P=h[O],G+=O-P&32767}if(z){x[E++]=268435456|ji[D]<<18|du[z];var U=ji[D]&31,$=du[z]&31;T+=uo[U]+fo[$],++b[257+U],++I[$],_=S+D,++N}else x[E++]=e[S],++b[e[S]]}}for(S=Math.max(S,_);S<i;++S)x[E++]=e[S],++b[e[S]];u=pu(e,s,c,x,b,I,T,E,A,S-A,u),c||(o.r=u&7|s[u/8|0]<<3,u-=7,o.h=g,o.p=h,o.i=S,o.w=_)}else{for(var S=o.w||0;S<i+c;S+=65535){var K=S+65535;K>=i&&(s[u/8|0]=c,K=i),u=xu(s,u+1,e.subarray(S,K))}o.i=i}return yu(l,0,n+qi(u)+a)};var Ig=function(e,t,r,n,a){if(!a&&(a={l:1},t.dictionary)){var o=t.dictionary.subarray(-32768),i=new We(o.length+e.length);i.set(o),i.set(e,o.length),e=i,a.w=o.length}return Ng(e,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,a)};function Nu(e,t){return Ig(e,t||{},0,0)}function Iu(e,t){return xg(e,{i:2},t&&t.out,t&&t.dictionary)}var Tg=typeof TextDecoder<"u"&&new TextDecoder,Sg=0;try{Tg.decode(bu,{stream:!0}),Sg=1}catch{}var Su=new TextEncoder,Eu=new TextDecoder("utf-8"),Eg=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function Ag(e){let t=4294967295;for(let r=0;r<e.length;r++)t=Eg[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function un(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return Su.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function Tu(e){let t=0;for(let a=0;a<e.length;a++)t+=e[a].length;let r=new Uint8Array(t),n=0;for(let a=0;a<e.length;a++)r.set(e[a],n),n+=e[a].length;return r}function fn(e){let t=un(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,a=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=a;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let o=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(o===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let l=new Map,s=i;for(let c=0;c<o;c++){if(s+46>t.length||r.getUint32(s,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let u=r.getUint16(s+8,!0),f=r.getUint16(s+10,!0);if(u&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(s+20,!0),m=r.getUint16(s+28,!0),p=r.getUint16(s+30,!0),h=r.getUint16(s+32,!0),g=r.getUint32(s+42,!0);if(s+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let v=Eu.decode(t.subarray(s+46,s+46+m));if(g+30>t.length||r.getUint32(g,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(g+26,!0),y=r.getUint16(g+28,!0),x=g+30+w+y;if(x+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let b=t.subarray(x,x+d);if(f!==0&&f!==8)throw new Error(`Unsupported DOCX compression method: ${f}.`);let I=f===8?Iu(b):new Uint8Array(b);l.set(v,I),s+=46+m+p+h}return l}function Au(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],a=0;for(let[s,c]of t){let u=Su.encode(s),f=un(c),d=Nu(f,{level:9}),m=d.length<f.length?8:0,p=m===8?d:f,h=Ag(f),g=new Uint8Array(30),v=new DataView(g.buffer,g.byteOffset,30);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(8,m,!0),v.setUint16(12,23585,!0),v.setUint32(14,h,!0),v.setUint32(18,p.length,!0),v.setUint32(22,f.length,!0),v.setUint16(26,u.length,!0),v.setUint16(28,0,!0),r.push(g,u,p);let w=new Uint8Array(46),y=new DataView(w.buffer,w.byteOffset,46);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(10,m,!0),y.setUint16(14,23585,!0),y.setUint32(16,h,!0),y.setUint32(20,p.length,!0),y.setUint32(24,f.length,!0),y.setUint16(28,u.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint32(42,a,!0),n.push(w,u),a+=g.length+u.length+p.length}let o=Tu(n),i=new Uint8Array(22),l=new DataView(i.buffer,i.byteOffset,22);return l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,o.length,!0),l.setUint32(16,a,!0),Tu([...r,o,i])}var Mr=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,un(r)),this;let n=this.entries.get(t);return n?{async:async a=>a==="string"?Eu.decode(n):new Uint8Array(n)}:null}};var aa=new TextEncoder,Rg=new TextDecoder("utf-8"),_e=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:Rg.decode(r):null},mo=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function Te(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function Pg(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Ru(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),a=new Map(n.map(i=>[i.operationIndex,i])),o=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:a.get(i.index)||r(i.receipt)}:{}}));return{results:o,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:or({atomic:!0,rolledBack:!0,results:o,receipts:n,operationCount:t})}}function Yi(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=fn(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=fn(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=fn(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=fn(un(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return $n({scope:"package",entries:t})}function Cg(e){let r=(`${_e(e,"word/document.xml")||""} ${_e(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,a)=>Math.max(n,Number(a.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function Pu(e){let t=_e(e,"word/comments.xml");if(!t)return{};let r=j(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let a of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let o=a.getAttribute("w:id")||a.getAttribute("id");o!==""&&(n[o]={id:o,author:a.getAttribute("w:author")||a.getAttribute("author")||"",text:String(a.textContent||"").trim(),paraId:Array.from(a.getElementsByTagNameNS("*","p"))[0]?.getAttribute("w14:paraId")||null})}return n}function lr(e,t,r){let n=Te(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:bt({code:t,message:r}),retryPlan:or({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>Te(e)}}var po=class{constructor(t){this.originalBytes=un(t),this.entries=fn(this.originalBytes)}get originalBuffer(){return Te(this.originalBytes)}inspect(t={}){let r=t.digestFn||(n=>Fn(n));return gi({documentXml:_e(this.entries,"word/document.xml"),commentsXml:_e(this.entries,"word/comments.xml"),commentsExtendedXml:_e(this.entries,"word/commentsExtended.xml"),numberingXml:_e(this.entries,"word/numbering.xml"),stylesXml:_e(this.entries,"word/styles.xml")},{...t,digestFn:r})}getRevisionToken(){return Yi(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=re(),n={}){return Ui(_e(this.entries,"word/document.xml"),t,r||re(),{...n,_existingCommentDetails:Pu(this.entries)})}toUint8Array(){return Au(this.entries)}toBuffer(){return Te(this.toUint8Array())}async applyOperations(t,r={}){let n=u=>{let f=[],d=[],m=Te(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:f,receipts:d,artifactsChanged:[],error:bt(u),retryPlan:or({atomic:!0,rolledBack:!0,results:f,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>Te(this.originalBytes)}};if(r?.expectedRevision){let u=Pr(r.expectedRevision);if(!u.valid)return n({code:u.error?.code||"INVALID_REVISION_TOKEN",message:u.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let f=Yi(this.entries);if(!Cr(f.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${f.value}'.`,expectedRevision:r.expectedRevision,currentRevision:f})}let a=this.entries,o=mo(a),i=new Mr(o),l=_e(o,"word/document.xml"),s=[],c=null;try{if(!l)throw new Error("Missing word/document.xml.");s=yt(l).issues.map(N=>({source:"word/document.xml",...N}));try{await rn(new Mr(mo(a)))}catch(N){s.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:N.message})}let f={numberingIdState:ui(_e(o,"word/numbering.xml")||void 0),commentsXml:_e(o,"word/comments.xml"),commentsExtendedXml:_e(o,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||re(),h=c=await $i(l,t,p,f,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:Pu(o),commentIdAllocator:Cg(o)});if(h.rolledBack||h.status==="error"){let N=Te(this.originalBytes);return{...h,...Ru(h,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:N,toBuffer:()=>Te(this.originalBytes)}}if(!h.hasChanges){let N=Te(this.originalBytes);return{...h,status:h.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:N,toBuffer:()=>Te(this.originalBytes)}}o.set("word/document.xml",aa.encode(h.documentXml)),await Ai(i,h.numberingXmlParts,{mergeNumberingXml:fi});let g=_e(o,"word/comments.xml"),v=h.commentsXml||g;await Ri(i,v,{replaceExisting:h.commentsXmlMode==="replace"||!h.commentsXml&&!!g});let w=_e(o,"word/commentsExtended.xml"),y=h.commentsExtendedXml||w;if(await Pi(i,y,{replaceExisting:h.commentsExtendedXmlMode==="replace"||!h.commentsExtendedXml&&!!w}),r.validate!==!1){let T=yt(h.documentXml).issues.map(_=>({source:"word/document.xml",..._}));try{await rn(i)}catch(_){T.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:_.message})}let S=sn(T,s),E=ln(S);if(E.length){let _=[...new Set(E.map(A=>A.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${_}); these are generated-output issues, not pre-existing input issues.`),{issues:E})}}this.entries=o;let x=this.toUint8Array();this.originalBytes=x;let b=Te(x),I=[...o].filter(([N,T])=>!a.has(N)||!Pg(T,a.get(N))).map(([N])=>N);return{...h,status:h.status||"ok",written:!0,artifactsChanged:I,validation:{originalIssues:s,generatedIssues:[]},uint8Array:x,toUint8Array:()=>new Uint8Array(x),buffer:b,inspection:this.inspect(),toBuffer:()=>Te(x)}}catch(u){this.entries=a;let f=u.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:u.message}],d=Ru(c,Array.isArray(t)?t.length:0),m=Te(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:bt({code:"PACKAGE_OPERATION_FAILED",message:u.message,stage:"package",issues:f}),validation:{originalIssues:s,generatedIssues:f},issues:f,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>Te(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?yr:t==="reject"?tr:null;if(!n)return lr(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let a=this.originalBytes,o=mo(this.entries),i=new Mr(o),l=n(_e(o,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(l.status==="error"||l.error)return lr(a,l.error?.code||"REVISION_OPERATION_FAILED",l.error?.message||"Revision operation failed.");if(!l.hasChanges){let u=Te(a);return{...l,status:"ok",written:!1,artifactsChanged:[],uint8Array:a,toUint8Array:()=>new Uint8Array(a),buffer:u,toBuffer:()=>Te(a)}}o.set("word/document.xml",aa.encode(l.oxml));try{r.validate!==!1&&await rn(i)}catch(u){return lr(a,"PACKAGE_VALIDATION",u.message)}this.entries=o;let s=this.toUint8Array();this.originalBytes=s;let c=Te(s);return{...l,status:"ok",written:!0,artifactsChanged:["word/document.xml"],uint8Array:s,toUint8Array:()=>new Uint8Array(s),buffer:c,toBuffer:()=>Te(s)}}async deleteComments(t={}){let r=this.originalBytes,n=mo(this.entries),a=_e(n,"word/comments.xml"),o=Te(r);if(!a)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:o,toBuffer:()=>Te(r)};let i=j(a,"application/xml");if(!i.doc||i.error)return lr(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let l=y=>t.allAuthors===!0||(y.getAttribute("w:author")||y.getAttribute("author"))===t.author,s=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(l).map(y=>y.getAttribute("w:id")||y.getAttribute("id")).filter(Boolean));if(!s.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:o,toBuffer:()=>Te(r)};let c=_e(n,"word/commentsExtended.xml"),u=null,f=new Set;if(c){if(u=j(c,"application/xml"),!u.doc||u.error)return lr(r,"PARSE_ERROR",u.error?.message||"Could not parse commentsExtended.xml.");let y=new Map;for(let b of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let I=b.getAttribute("w:id")||b.getAttribute("id"),N=Array.from(b.getElementsByTagNameNS("*","p"))[0],T=N?.getAttribute("w14:paraId")||N?.getAttribute("paraId");T&&y.set(T.toUpperCase(),I)}for(let[b,I]of y)s.has(I)&&f.add(b);let x=!0;for(;x;){x=!1;for(let b of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let I=(b.getAttribute("w15:paraId")||b.getAttribute("paraId")||"").toUpperCase(),N=(b.getAttribute("w15:paraIdParent")||b.getAttribute("paraIdParent")||"").toUpperCase();N&&f.has(N)&&!f.has(I)&&(f.add(I),y.has(I)&&s.add(y.get(I)),x=!0)}}}let d=qo(a,{author:t.author,allAuthors:t.allAuthors===!0}),m=j(d.oxml,"application/xml");if(!m.doc||m.error)return lr(r,"PARSE_ERROR",m.error?.message||"Could not parse updated comments.xml.");for(let y of Array.from(m.doc.getElementsByTagNameNS("*","comment"))){let x=y.getAttribute("w:id")||y.getAttribute("id");s.has(x)&&y.parentNode?.removeChild(y)}let p=j(_e(n,"word/document.xml"),"application/xml");if(!p.doc||p.error)return lr(r,"PARSE_ERROR",p.error?.message||"Could not parse document.xml.");let h=0;for(let y of["commentRangeStart","commentRangeEnd","commentReference"])for(let x of Array.from(p.doc.getElementsByTagNameNS("*",y))){let b=x.getAttribute("w:id")||x.getAttribute("id");if(!s.has(b)||!x.parentNode)continue;let I=x.parentNode;I.removeChild(x),h+=1,y==="commentReference"&&I.localName==="r"&&!Array.from(I.childNodes||[]).some(N=>N.nodeType===1&&N.localName!=="rPr")&&I.parentNode?.removeChild(I)}let g=ce();if(n.set("word/comments.xml",aa.encode(g.serializeToString(m.doc))),u?.doc){for(let y of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let x=(y.getAttribute("w15:paraId")||y.getAttribute("paraId")||"").toUpperCase();f.has(x)&&y.parentNode?.removeChild(y)}n.set("word/commentsExtended.xml",aa.encode(g.serializeToString(u.doc)))}n.set("word/document.xml",aa.encode(g.serializeToString(p.doc)));try{t.validate!==!1&&await rn(new Mr(n))}catch(y){return lr(r,"PACKAGE_VALIDATION",y.message)}this.entries=n;let v=this.toUint8Array();this.originalBytes=v;let w=Te(v);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:s.size,referencesRemoved:h,artifactsChanged:["word/document.xml","word/comments.xml",...u?.doc?["word/commentsExtended.xml"]:[]],uint8Array:v,toUint8Array:()=>new Uint8Array(v),buffer:w,toBuffer:()=>Te(v)}}};function Og(e){return new po(e)}async function Cu(e,t,r,n={}){let a=await Rn(e,t,r,n);if(a?.useNativeApi&&typeof a?.oxml!="string"){let o=Array.isArray(a?.warnings)?a.warnings:[];return we({...a,oxml:e,hasChanges:!1,warnings:[...o,"Standalone mode cannot execute native Word API fallback for this operation."]})}return a}async function PI(e,t,r,n={}){let a=typeof e=="string"?e:"",o=typeof r=="string"?r:String(r||""),i;try{i=et(o)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await Cu(a,t||"",o,n),isMarkdownTable:!0,tableData:i}:{oxml:a,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function CI(e,t,r,n={}){let a=n.listFallbackAllowExistingList!==!1,o=n.sanitizeInput===!0?Jo(r):r,i=o!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],l=Gr({oxml:e,originalText:t,modifiedText:o,allowExistingList:a}),s=n.preferListStructuralFallback!==!1,c=[];if(l&&s){let h=await qr(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(h?.hasChanges&&h?.oxml){let g=qt(h.oxml,{includeNumbering:h.includeNumbering??!0,numberingXml:h.numberingXml}),v=Array.isArray(h?.warnings)?h.warnings:[];return we({oxml:g,hasChanges:!0,warnings:[...i,...v],listStructuralFallbackApplied:!0,listStructuralFallbackKey:h.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:h.numberingXml||null})}c=Array.isArray(h?.warnings)?h.warnings:[]}let u=await Cu(e,t,r,n);if(!l)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(s)return{...u,warnings:[...Array.isArray(u?.warnings)?u.warnings:[],...c],listStructuralFallbackApplied:!1};if(u?.hasChanges)return{...u,listStructuralFallbackApplied:!1};let f=await qr(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let h=Array.isArray(u?.warnings)?u.warnings:[],g=Array.isArray(f?.warnings)?f.warnings:[];return{...u,warnings:[...h,...g],listStructuralFallbackApplied:!1}}let d=qt(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),m=Array.isArray(u?.warnings)?u.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return we({...u,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{Lr as ContainerKind,fs as ContentType,st as DiffOp,po as DocxDocument,M as NS_W,Mt as NumberingService,qn as ReceiptCollector,xn as ReconciliationPipeline,nn as RoutePlanKind,q as RunKind,Ae as WORD_MAIN_NS,yr as acceptTrackedChangesInOoxml,ha as analyzeStructuredContent,yi as applyCommentReplyToParts,rp as applyFormattingRemovalToOoxml,xi as applyHighlightToOoxml,Cu as applyRedlineToOxml,CI as applyRedlineToOxmlWithListFallback,Cr as areRevisionTokensEqual,zn as buildCommentElement,wi as buildCommentsPartXml,Ha as buildExplicitDecimalMultilevelNumberingXml,dm as buildListMarkdown,up as buildReconciliationPlan,pi as buildRevisionTokenFraming,Gr as buildSingleLineListStructuralFallbackPlan,ti as buildTargetReferenceSnapshot,Mn as clearSingleLineListFallbackExplicitSequence,Kl as collectContiguousListParagraphBlock,Un as computeDocumentPartsRevisionToken,Yi as computePackageRevisionToken,oc as computeRevisionToken,$n as computeRevisionTokenSync,Uu as configureLogger,Vu as configureXmlProvider,Yt as containsTrackedChanges,ui as createDynamicNumberingIdState,Ce as createEmptyReceipt,rt as createParagraphFingerprint,qo as deleteCommentsByAuthorInOoxml,za as enforceListBindingOnParagraphNodes,Ri as ensureCommentsArtifactsInZip,Pi as ensureCommentsExtendedArtifactsInZip,Ai as ensureNumberingArtifactsInZip,Ue as escapeXml,qr as executeSingleLineListStructuralFallback,te as extractCanonicalParagraphText,qa as extractDocumentPartsEntries,Ka as extractFirstParagraphNumId,fp as extractParagraphIdFromOoxml,xa as extractParagraphRevisionSegments,Ti as extractReplacementNodesFromOoxml,Ve as findContainingWordElement,Qo as findParagraphByBestTextMatch,Xl as findParagraphByReference,ka as findParagraphByStrictText,Ma as findStrictTargetCandidates,fr as generateTableOoxml,Ii as getBodyElementFromDocument,re as getDefaultAuthor,oe as getDocumentParagraphNodes,Ni as getPackagePartName,$e as getParagraphId,nt as getParagraphListInfo,ve as getParagraphText,vo as getPlatform,dr as getTrackedChangeAuthors,ai as hasListItems,mn as inferNumberingStyleFromMarker,ii as inferTableReplacementParagraphBlock,Fr as ingestOoxml,Um as ingestWordOoxmlToMarkdown,nc as ingestWordOoxmlToMarkdownResult,$m as ingestWordOoxmlToPlainText,rc as ingestWordOoxmlToPlainTextResult,vi as injectCommentsIntoOoxml,ep as injectCommentsIntoPackage,sp as insertBodyElementBeforeSectPr,gi as inspectDocumentParts,Yl as isLikelyStructuredTableSourceParagraph,Tr as isMarkdownTableText,hr as isNodeVisibleInRevisionView,fi as mergeNumberingXmlBySchemaOrder,to as normalizeBodySectionOrderStandalone,Cc as normalizeContentEscapesForRouting,mm as normalizeListItemsWithLevels,ac as normalizeOpcEntryName,Y as normalizeWhitespaceForTargeting,Og as openDocx,ja as overwriteParagraphNumIds,kn as parseMarkdownListContent,Ft as parseOoxml,j as parseOoxmlSafe,ei as parseParagraphReference,ni as planListInsertionOnlyEdit,Qf as planStructuredReplacement,Ge as preprocessMarkdown,wr as readCanonicalRunText,PI as reconcileMarkdownTableOoxml,Yn as reconcileReceiptsAgainstOutput,Ua as recordSingleLineListFallbackExplicitSequence,tr as rejectTrackedChangesInOoxml,Ga as remapNumberingPayloadForDocument,xc as removeFormattingFromRPr,Bn as reserveNextNumberingId,Wa as reserveNextNumberingIdPair,jr as resolveParagraphRangeByRefs,$a as resolveSingleLineListFallbackNumberingAction,Sr as resolveTargetParagraph,Cn as resolveTargetParagraphWithSnapshot,Jo as sanitizeAiResponse,lp as sanitizeNestedParagraphsInTables,Ir as serializeOoxml,gt as serializeToOoxml,Gu as setDefaultAuthor,qu as setPlatform,om as splitLeadingParagraphMarker,am as stripLeadingParagraphMarker,Er as stripRedundantLeadingListMarkers,oi as stripSingleLineListMarkerPrefix,ri as synthesizeExpandedListScopeEdit,si as synthesizeTableMarkdownFromMultilineCellEdit,rn as validateDocxPackage,yt as validateRedlineOoxml,Pr as validateRevisionToken,qt as wrapInDocumentFragment};
214
227
  //# sourceMappingURL=docx-redline-js.esm.min.js.map