@ansonlai/docx-redline-js 0.5.1 → 0.5.2

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 Ja=Object.create;var To=Object.defineProperty;var qa=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var ts=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var rs=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Za(t))!es.call(e,o)&&o!==r&&To(e,o,{get:()=>t[o],enumerable:!(n=qa(t,o))||n.enumerable});return e};var So=(e,t,r)=>(r=e!=null?Ja(Qa(e)):{},rs(t||!e||!e.__esModule?To(r,"default",{value:e,enumerable:!0}):r,e));var En=ts((Tf,Rt)=>{var A=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},K=-1,q=1,D=0;A.Diff=function(e,t){return[e,t]};A.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 A.Diff(D,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 u=this.diff_compute_(e,t,i,o);return s&&u.unshift(new A.Diff(D,s)),l&&u.push(new A.Diff(D,l)),this.diff_cleanupMerge(u),u};A.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new A.Diff(q,t)];if(!t)return[new A.Diff(K,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 A.Diff(q,i.substring(0,s)),new A.Diff(D,a),new A.Diff(q,i.substring(s+a.length))],e.length>t.length&&(o[0][0]=o[2][0]=K),o;if(a.length==1)return[new A.Diff(K,e),new A.Diff(q,t)];var l=this.diff_halfMatch_(e,t);if(l){var u=l[0],c=l[1],f=l[2],m=l[3],d=l[4],p=this.diff_main(u,f,r,n),b=this.diff_main(c,m,r,n);return p.concat([new A.Diff(D,d)],b)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};A.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 A.Diff(D,""));for(var a=0,s=0,l=0,u="",c="";a<i.length;){switch(i[a][0]){case q:l++,c+=i[a][1];break;case K:s++,u+=i[a][1];break;case D:if(s>=1&&l>=1){i.splice(a-s-l,s+l),a=a-s-l;for(var f=this.diff_main(u,c,!1,r),m=f.length-1;m>=0;m--)i.splice(a,0,f[m]);a=a+f.length}l=0,s=0,u="",c="";break}a++}return i.pop(),i};A.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),u=new Array(s),c=0;c<s;c++)l[c]=-1,u[c]=-1;l[a+1]=0,u[a+1]=0;for(var f=n-o,m=f%2!=0,d=0,p=0,b=0,h=0,g=0;g<i&&!(new Date().getTime()>r);g++){for(var w=-g+d;w<=g-p;w+=2){var x=a+w,N;w==-g||w!=g&&l[x-1]<l[x+1]?N=l[x+1]:N=l[x-1]+1;for(var T=N-w;N<n&&T<o&&e.charAt(N)==t.charAt(T);)N++,T++;if(l[x]=N,N>n)p+=2;else if(T>o)d+=2;else if(m){var y=a+f-w;if(y>=0&&y<s&&u[y]!=-1){var v=n-u[y];if(N>=v)return this.diff_bisectSplit_(e,t,N,T,r)}}}for(var E=-g+b;E<=g-h;E+=2){var y=a+E,v;E==-g||E!=g&&u[y-1]<u[y+1]?v=u[y+1]:v=u[y-1]+1;for(var P=v-E;v<n&&P<o&&e.charAt(n-v-1)==t.charAt(o-P-1);)v++,P++;if(u[y]=v,v>n)h+=2;else if(P>o)b+=2;else if(!m){var x=a+f-E;if(x>=0&&x<s&&l[x]!=-1){var N=l[x],T=a+N-x;if(v=n-v,N>=v)return this.diff_bisectSplit_(e,t,N,T,r)}}}}return[new A.Diff(K,e),new A.Diff(q,t)]};A.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),u=this.diff_main(i,a,!1,o),c=this.diff_main(s,l,!1,o);return u.concat(c)};A.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var u="",c=0,f=-1,m=r.length;f<l.length-1;){f=l.indexOf(`
2
- `,c),f==-1&&(f=l.length-1);var d=l.substring(c,f+1);(n.hasOwnProperty?n.hasOwnProperty(d):n[d]!==void 0)?u+=String.fromCharCode(n[d]):(m==i&&(d=l.substring(c),f=l.length),u+=String.fromCharCode(m),n[d]=m,r[m++]=d),c=f+1}return u}var i=4e4,a=o(e);i=65535;var s=o(t);return{chars1:a,chars2:s,lineArray:r}};A.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("")}};A.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};A.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};A.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++)}};A.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,b,h){for(var g=p.substring(h,h+Math.floor(p.length/4)),w=-1,x="",N,T,y,v;(w=b.indexOf(g,w+1))!=-1;){var E=o.diff_commonPrefix(p.substring(h),b.substring(w)),P=o.diff_commonSuffix(p.substring(0,h),b.substring(0,w));x.length<P+E&&(x=b.substring(w-P,w)+b.substring(w,w+E),N=p.substring(0,h-P),T=p.substring(h+E),y=b.substring(0,w-P),v=b.substring(w+E))}return x.length*2>=p.length?[N,T,y,v,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 u,c,f,m;e.length>t.length?(u=l[0],c=l[1],f=l[2],m=l[3]):(f=l[0],m=l[1],u=l[2],c=l[3]);var d=l[4];return[u,c,f,m,d]};A.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=0,s=0,l=0,u=0;i<e.length;)e[i][0]==D?(r[n++]=i,a=l,s=u,l=0,u=0,o=e[i][1]):(e[i][0]==q?l+=e[i][1].length:u+=e[i][1].length,o&&o.length<=Math.max(a,s)&&o.length<=Math.max(l,u)&&(e.splice(r[n-1],0,new A.Diff(K,o)),e[r[n-1]+1][0]=q,n--,n--,i=n>0?r[n-1]:-1,a=0,s=0,l=0,u=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]==K&&e[i][0]==q){var c=e[i-1][1],f=e[i][1],m=this.diff_commonOverlap_(c,f),d=this.diff_commonOverlap_(f,c);m>=d?(m>=c.length/2||m>=f.length/2)&&(e.splice(i,0,new A.Diff(D,f.substring(0,m))),e[i-1][1]=c.substring(0,c.length-m),e[i+1][1]=f.substring(m),i++):(d>=c.length/2||d>=f.length/2)&&(e.splice(i,0,new A.Diff(D,c.substring(0,d))),e[i-1][0]=q,e[i-1][1]=f.substring(0,f.length-d),e[i+1][0]=K,e[i+1][1]=c.substring(d),i++),i++}i++}};A.prototype.diff_cleanupSemanticLossless=function(e){function t(d,p){if(!d||!p)return 6;var b=d.charAt(d.length-1),h=p.charAt(0),g=b.match(A.nonAlphaNumericRegex_),w=h.match(A.nonAlphaNumericRegex_),x=g&&b.match(A.whitespaceRegex_),N=w&&h.match(A.whitespaceRegex_),T=x&&b.match(A.linebreakRegex_),y=N&&h.match(A.linebreakRegex_),v=T&&d.match(A.blanklineEndRegex_),E=y&&p.match(A.blanklineStartRegex_);return v||E?5:T||y?4:g&&!x&&N?3:x||N?2:g||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==D&&e[r+1][0]==D){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,u=o,c=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,u=o,c=i)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=u,c?e[r+1][1]=c:(e.splice(r+1,1),r--))}r++}};A.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;A.whitespaceRegex_=/\s/;A.linebreakRegex_=/[\r\n]/;A.blanklineEndRegex_=/\n\r?\n$/;A.blanklineStartRegex_=/^\r?\n\r?\n/;A.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=!1,s=!1,l=!1,u=!1;i<e.length;)e[i][0]==D?(e[i][1].length<this.Diff_EditCost&&(l||u)?(r[n++]=i,a=l,s=u,o=e[i][1]):(n=0,o=null),l=u=!1):(e[i][0]==K?u=!0:l=!0,o&&(a&&s&&l&&u||o.length<this.Diff_EditCost/2&&a+s+l+u==3)&&(e.splice(r[n-1],0,new A.Diff(K,o)),e[r[n-1]+1][0]=q,n--,o=null,a&&s?(l=u=!0,n=0):(n--,i=n>0?r[n-1]:-1,l=u=!1),t=!0)),i++;t&&this.diff_cleanupMerge(e)};A.prototype.diff_cleanupMerge=function(e){e.push(new A.Diff(D,""));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 K:r++,o+=e[t][1],t++;break;case D: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]==D?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new A.Diff(D,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 A.Diff(K,o)),t++),i.length&&(e.splice(t,0,new A.Diff(q,i)),t++),t++):t!==0&&e[t-1][0]==D?(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]==D&&e[t+1][0]==D&&(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)};A.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]!==K&&(n+=e[a][1].length),!(r>t));a++)o=r,i=n;return e.length!=a&&e[a][0]===K?i:i+(t-o)};A.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],u=l.replace(r,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(i,"&para;<br>");switch(s){case q:t[a]='<ins style="background:#e6ffe6;">'+u+"</ins>";break;case K:t[a]='<del style="background:#ffe6e6;">'+u+"</del>";break;case D:t[a]="<span>"+u+"</span>";break}}return t.join("")};A.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("")};A.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==K&&(t[r]=e[r][1]);return t.join("")};A.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 K:n+=a.length;break;case D:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};A.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 K:t[r]="-"+e[r][1].length;break;case D:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};A.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 A.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 u=e.substring(o,o+=l);i[a].charAt(0)=="="?r[n++]=new A.Diff(D,u):r[n++]=new A.Diff(K,u);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};A.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};A.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(N,T){var y=N/t.length,v=Math.abs(r-T);return o.Match_Distance?y+v/o.Match_Distance:v?1:y}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 u,c,f=t.length+e.length,m,d=0;d<t.length;d++){for(u=0,c=f;u<c;)i(d,r+c)<=a?u=c:f=c,c=Math.floor((f-u)/2+u);f=c;var p=Math.max(1,r-c+1),b=Math.min(r+c,e.length)+t.length,h=Array(b+2);h[b+1]=(1<<d)-1;for(var g=b;g>=p;g--){var w=n[e.charAt(g-1)];if(d===0?h[g]=(h[g+1]<<1|1)&w:h[g]=(h[g+1]<<1|1)&w|((m[g+1]|m[g])<<1|1)|m[g+1],h[g]&l){var x=i(d,g-1);if(x<=a)if(a=x,s=g-1,s>r)p=Math.max(1,2*r-s);else break}}if(i(d+1,r)>a)break;m=h}return s};A.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};A.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 A.Diff(D,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new A.Diff(D,i)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+i.length,e.length2+=o.length+i.length}};A.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 A.patch_obj,s=0,l=0,u=0,c=n,f=n,m=0;m<o.length;m++){var d=o[m][0],p=o[m][1];switch(!s&&d!==D&&(a.start1=l,a.start2=u),d){case q:a.diffs[s++]=o[m],a.length2+=p.length,f=f.substring(0,u)+p+f.substring(u);break;case K:a.length1+=p.length,a.diffs[s++]=o[m],f=f.substring(0,u)+f.substring(u+p.length);break;case D: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,c),i.push(a),a=new A.patch_obj,s=0,c=f,l=u);break}d!==q&&(l+=p.length),d!==K&&(u+=p.length)}return s&&(this.patch_addContext_(a,c),i.push(a)),i};A.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new A.patch_obj;o.diffs=[];for(var i=0;i<n.diffs.length;i++)o.diffs[i]=new A.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};A.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,u=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),a),l!=-1&&(u=this.match_main(t,s.substring(s.length-this.Match_MaxBits),a+s.length-this.Match_MaxBits),(u==-1||l>=u)&&(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 c;if(u==-1?c=t.substring(l,l+s.length):c=t.substring(l,u+this.Match_MaxBits),s==c)t=t.substring(0,l)+this.diff_text2(e[i].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,c,!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 b=e[i].diffs[p];b[0]!==D&&(d=this.diff_xIndex(f,m)),b[0]===q?t=t.substring(0,l+d)+b[1]+t.substring(l+d):b[0]===K&&(t=t.substring(0,l+d)+t.substring(l+this.diff_xIndex(f,m+b[1].length))),b[0]!==K&&(m+=b[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};A.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]!=D)i.unshift(new A.Diff(D,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]!=D)i.push(new A.Diff(D,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};A.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 A.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 A.Diff(D,a)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var u=n.diffs[0][0],c=n.diffs[0][1];u===q?(s.length2+=c.length,i+=c.length,s.diffs.push(n.diffs.shift()),l=!1):u===K&&s.diffs.length==1&&s.diffs[0][0]==D&&c.length>2*t?(s.length1+=c.length,o+=c.length,l=!1,s.diffs.push(new A.Diff(u,c)),n.diffs.shift()):(c=c.substring(0,t-s.length1-this.Patch_Margin),s.length1+=c.length,o+=c.length,u===D?(s.length2+=c.length,i+=c.length):l=!1,s.diffs.push(new A.Diff(u,c)),c==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(c.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]===D?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new A.Diff(D,f))),l||e.splice(++r,0,s)}}};A.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};A.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 A.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 A.Diff(K,l));else if(s=="+")a.diffs.push(new A.Diff(q,l));else if(s==" ")a.diffs.push(new A.Diff(D,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};A.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};A.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 K:n="-";break;case D:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
- `}return r.join("").replace(/%20/g," ")};Rt.exports=A;Rt.exports.diff_match_patch=A;Rt.exports.DIFF_DELETE=K;Rt.exports.DIFF_INSERT=q;Rt.exports.DIFF_EQUAL=D});var Sr=console,mn=Object.freeze({silent:0,error:1,warn:2,info:3}),ns=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",dn=ns;function os(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(mn,t)?t:dn}function pn(e){return mn[dn]>=mn[e]}function is(e,t={}){Sr=e||console,t.level&&(dn=os(t.level))}function k(...e){pn("info")&&(Sr.log||(()=>{}))(...e)}function Le(...e){pn("warn")&&(Sr.warn||(()=>{}))(...e)}function te(...e){pn("error")&&(Sr.error||(()=>{}))(...e)}var Vt=globalThis.DOMParser,Gt=globalThis.XMLSerializer;function as(e={}){e.DOMParser&&(Vt=e.DOMParser),e.XMLSerializer&&(Gt=e.XMLSerializer)}function ss(e={}){if(!Vt&&globalThis.DOMParser&&(Vt=globalThis.DOMParser),!Vt)throw new Error("DOMParser is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Vt(e)}function fe(){if(!Gt&&globalThis.XMLSerializer&&(Gt=globalThis.XMLSerializer),!Gt)throw new Error("XMLSerializer is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Gt}function Eo(e,t="text/xml"){let r=W(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function ls(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function W(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"?te("[XmlAdapter] XML fatal parse error:",a):(r.push(a),Le(`[XmlAdapter] XML ${o||"warning"}:`,a))};try{let i=ss({onError:n}).parseFromString(e,t),a=ls(i);if(!i?.documentElement||a){let s=a?.textContent||"Could not parse XML input.";return te("[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 te("[XmlAdapter] XML parse error:",i),{doc:null,error:{code:"PARSE_ERROR",message:i},warnings:r}}}function oe(e){return fe().serializeToString(e)}var Io=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Ao=Io(),Po="Unknown";function cs(e){Ao=typeof e=="string"&&e.trim()?e.trim():Io()}function me(){return Ao}function us(e){Po=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function gn(){return Po}var fs=[{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 fs){let l,u=s.regex.source||s.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),c="g"+(s.regex.ignoreCase?"i":""),f=new RegExp(u,c);for(;(l=f.exec(e))!==null;)n.push({start:l.index,end:l.index+l[0].length,fullMatch:l[0],innerText:s.isEscaped?ms(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),u=r.length;r+=l.cleanText;let c=r.length;t.push({start:u,end:c,format:s.format});for(let f of l.formatHints)t.push({start:u+f.start,end:u+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 hn(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function ms(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var Er=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Ro=new RegExp(`^(\\s*)((?:${Er})\\s+)`),Co=new RegExp(`^(\\s*)((?:${Er})\\s*)`),ds=new RegExp(`^(\\s*)((?:${Er})\\s+)`,"m"),ps=new RegExp(`^(\\s*)((?:${Er})\\s*)`,"m");function wn(e){return typeof e!="string"?!1:e.includes(`
6
- `)&&ds.test(e)}function Kt(e){return typeof e!="string"?!1:e.includes(`
7
- `)&&ps.test(e.trim())}function Be(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Co:Ro;return e.match(n)}function Ue(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Co:Ro;return e.replace(n,"")}function Oo(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Yt(e){let t=String(e||"").trim();return Oo(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 gs(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function Jt(e,t={}){let r=Be(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=Oo(n);return{line:String(e||""),text:Ue(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/i)),markerType:a,listType:a,numberingStyle:Yt(n),outlineLevel:a==="numbered"?gs(n):null}}var S="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var Oe=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),F=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"}),St=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),_o=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),V=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),we=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function xe(e){return e?e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;"):""}var bn=1e3,ko=2147483647,Mo=1e4,hs=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Lo=new WeakMap;function ws(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return hs.has(t)?!e.namespaceURI||e.namespaceURI===S||String(e.nodeName||"").startsWith("w:"):!1}function bs(e){let t=e?.getAttributeNS?.(S,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var he=class{constructor(t=bn){this.startValue=Number.isInteger(t)&&t>=0?t:bn,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(ws(o)){let a=bs(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=ko-Mo;return this.nextId=r>=i?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=ko-Mo;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}},qt=new he;function Ir(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof he&&Lo.set(r,t),t}function Ye(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Lo.get(t)||null}function nt(e,t=bn){let r=new he(t);return r.seed(e),Ir(e,r),r}function Bo(){return qt.next()}function Ar(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():me(),o=t instanceof he?t:Ye(t)||qt,i=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(i,r||"structural"),{id:i,author:n,date:Ar()}}function Pr(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():me(),n=t instanceof he?t:Ye(t)||qt,o=Ar(),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 Et(e,t=qt){let r=t instanceof he?t:qt,n=r.seed(e);return Ir(e,r),n}function Fo(e,t){return e<t-1}function It(e,t,r){return Fo(t,r)?e+`
8
- `:e}function mt(e,t,r){return Fo(t,r)?e+1:e}function Zt(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 le(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 Ne(e,t,r,n=`w:${r}`){let o=le(e,t,r);return o.length>0?o:Zt(e,n)}function ve(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 xn(e){return Array.from(e?.childNodes||[])}function $o(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Nn(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var vn=0;function Pt(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}:W(e,"application/xml"),a=i.doc;if(i.error||!a)return te("OOXML parse error:",i.error?.message),{runModel:r,acceptedText:n,pPr:null,error:i.error};let s=ne(a);if(s)return te("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=le(a,S,"p");return l.length===0?(Le("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):Do(l,{includeParagraphBoundaries:!0})}catch(i){return te("Error ingesting OOXML:",i),{runModel:r,acceptedText:n,pPr:null}}}function yn(e){return e?Do([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function Qt(e){let t=re(e,S,"pPr");if(!t)return null;let r=re(t,S,"numPr");if(!r)return null;let n=re(r,S,"numId"),o=re(r,S,"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 Do(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],u=re(l,S,"pPr");s===0&&(a=u),n.push({kind:F.PARAGRAPH_START,pPrElement:u||null,startOffset:i,endOffset:i,text:""});let c=At(l,i,n);o+=c.text,i=o.length,r&&(o=It(o,s,e.length),i=mt(i,s,e.length))}return{runModel:n,acceptedText:o,pPr:a}}function At(e,t,r){let n=t,o="",i=xs(r);for(let a of xn(e)){if(Nn(a,S,"pPr")||Nn(a,S,"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 xs(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${vn++}`,i=re(r,S,"sdtPr"),a=re(r,S,"sdtContent");e.push({kind:F.CONTAINER_START,containerKind:St.SDT,containerId:o,propertiesXml:i?oe(i):"",startOffset:n,endOffset:n,text:""});let s=a?At(a,n,e):{offset:n,text:""};return e.push({kind:F.CONTAINER_END,containerKind:St.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${vn++}`;e.push({kind:F.CONTAINER_START,containerKind:St.SMART_TAG,containerId:o,propertiesXml:$o(r),startOffset:n,endOffset:n,text:""});let i=At(r,n,e);return e.push({kind:F.CONTAINER_END,containerKind:St.SMART_TAG,containerId:o,startOffset:i.offset,endOffset:i.offset,text:""}),i}),t.set("del",(r,n)=>{let o=Xo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Xo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>At(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:F.BOOKMARK,nodeXml:oe(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:F.BOOKMARK,nodeXml:oe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:F.BOOKMARK,nodeXml:oe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>At(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${vn++}`,i=r.getAttribute("r:id")||"",a=r.getAttribute("w:anchor")||"";e.push({kind:F.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:i,anchor:a}),startOffset:n,endOffset:n,text:""});let s=At(r,n,e);return e.push({kind:F.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=Ns(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Ns(e,t){let r=ve(e,S,"rPr"),n=r?oe(r):"",o="";for(let i of xn(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:F.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Xo(e,t){let r=e.getAttribute("w:author")||"",n="",o=le(e,S,"delText");for(let a of o)n+=a.textContent||"";let i=le(e,S,"r");for(let a of i){let s=le(a,S,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:F.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:oe(e)}:null}function Sn(e){let t=re(e,S,"tblGrid"),r=t?le(t,S,"gridCol"):[],n=Ne(e,S,"tr"),o=n.length,i=n.reduce((c,f)=>{let m=Ne(f,S,"tc");return Math.max(c,m.length)},0),a=r.length||i,s=Array.from({length:o},()=>Array.from({length:a},()=>null)),l=new Map,u=new Map;for(let c=0;c<n.length;c++){let f=n[c],m=Ne(f,S,"tc"),d=0;for(let p=0;p<m.length;p++){let b=m[p],h=re(b,S,"tcPr");for(;d<a&&s[c][d]!==null;)d++;if(d>=a)break;let g=h?re(h,S,"gridSpan")||ae(h,"w:gridSpan"):null,w=parseInt(g?.getAttribute("w:val")||"1",10),x=h?re(h,S,"vMerge")||ae(h,"w:vMerge"):null,N=x?.getAttribute("w:val"),T=x!==null,y;if(T&&N!=="restart"){let v=u.get(d);v?(v.cell.rowSpan++,y={gridRow:c,gridCol:d,rowSpan:0,colSpan:w,tcNode:b,blocks:[],tcPrXml:Tn(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:v.cell}):y=vs(c,d,w,b,h)}else{let v=zo(b);if(y={gridRow:c,gridCol:d,rowSpan:1,colSpan:w,tcNode:b,blocks:v,tcPrXml:Tn(h),isMergeOrigin:T&&N==="restart",isMergeContinuation:!1,getText:()=>v.map(E=>E.acceptedText).join(`
10
- `)},T&&N==="restart")for(let E=0;E<w;E++)u.set(d+E,{originRow:c,cell:y});else for(let E=0;E<w;E++)u.delete(d+E)}for(let v=0;v<w;v++){let E=d+v;E<a&&(s[c][E]=y,l.set(`${c},${E}`,y))}d+=w}}return{rowCount:o,colCount:a,grid:s,cellMap:l,tblPrXml:ys(e),tblGridXml:Ts(e),trPrList:Array.from(n).map(c=>Ss(c))}}function vs(e,t,r,n,o){let i=zo(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:i,tcPrXml:Tn(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>i.map(a=>a.acceptedText).join(`
11
- `)}}function zo(e){return Ne(e,S,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:i}=yn(r);return{runModel:n,acceptedText:o,pPr:i}})}function Tn(e){return e?oe(e):"<w:tcPr/>"}function ys(e){let t=re(e,S,"tblPr");return t?oe(t):"<w:tblPr/>"}function Ts(e){let t=re(e,S,"tblGrid");return t?oe(t):"<w:tblGrid/>"}function Ss(e){let t=re(e,S,"trPr");return t?oe(t):"<w:trPr/>"}var jo=So(En(),1);var Es=65536,Rr=262144,Cr=1,Or=55296-Cr,Is=8192,As=Or+Is,In=class extends Error{constructor(t=Rr){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Ho(e){return e?.code==="DIFF_TOKEN_LIMIT"}function Ps(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 jo.diff_match_patch;return r.Diff_Timeout=t,r}function Wo(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 Rs(e,t,r={}){let n=[],o=new Map,i=r.maxTokens??Rr;if(!Number.isInteger(i)||i<1||i>Rr)throw new RangeError(`maxTokens must be an integer from 1 to ${Rr}.`);function a(f){let m="",d=[];for(let p of f){let b=o.get(p);if(b===void 0){if(n.length>=i)throw new In(i);b=n.length,n.push(p),o.set(p,b)}d.push(b),m+=String.fromCodePoint(Es+b)}return{chars:m,tokenIds:d}}let s=Wo(e),l=Wo(t),u=a(s),c=a(l);return{chars1:u.chars,chars2:c.chars,wordArray:n,tokenIds1:u.tokenIds,tokenIds2:c.tokenIds}}function Cs(e){let t=e<Or?Cr+e:57344+(e-Or);return String.fromCharCode(t)}function Os(e){if(e>=Cr&&e<55296)return e-Cr;if(e>=57344&&e<=65535)return Or+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function Uo(e){let t="";for(let r of e)t+=Cs(r);return t}function ks(e,t){return e.map(([r,n])=>{let o=[];for(let i=0;i<n.length;i++){let a=Os(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 Ms(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=c=>c.map(f=>r[f]).join(""),s=[];n&&s.push([0,a(e.slice(0,n))]);let l=e.slice(n,e.length-i),u=t.slice(n,t.length-i);return l.length&&s.push([-1,a(l)]),u.length&&s.push([1,a(u)]),i&&s.push([0,a(e.slice(e.length-i))]),s}function er(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}=Rs(e,t,r);if(o.length>As)return Ms(i,a,o);let s=Ps(r),l=s.diff_main(Uo(i),Uo(a));return n&&s.diff_cleanupSemantic(l),ks(l,o)}function kr(e,t,r={}){if(e===t)return[{type:Oe.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:Oe.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:Oe.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=er(e,t,r),o=[],i=0;for(let[a,s]of n)a===0?(o.push({type:Oe.EQUAL,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===-1?(o.push({type:Oe.DELETE,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===1&&o.push({type:Oe.INSERT,startOffset:i,endOffset:i,text:s});return o}var _s=/\s+xmlns:[^=]+="[^"]*"/g;function Mr(e,t){let r=Ds(t),n=[],o=0;for(let i of e){if(i.kind!==F.TEXT&&i.kind!==F.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 u=r[a];if(u>=i.endOffset)break;u>s&&(l=!0,n.push({...i,text:i.text.slice(s-i.startOffset,u-i.startOffset),startOffset:s,endOffset:u}),s=u),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 _r(e,t,r){let{generateRedlines:n,author:o}=r,i=[],a=new Set,s=zs(t),l=$s(e),u=Xs(s.nonInsertOps),c={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let m of e){if(m.kind===F.CONTAINER_START){c.containerStack.push(m.containerId),i.push({...m});continue}if(m.kind===F.CONTAINER_END){c.containerStack.pop(),i.push({...m});continue}if(m.kind===F.PARAGRAPH_START){c.currentParagraphPPrXml=typeof m.pPrXml=="string"?m.pPrXml:"",c.currentParagraphPPrElement=m.pPrElement||null,i.push({...m}),c.lastParagraphStartIndex=i.length-1;continue}if(m.kind===F.BOOKMARK||m.kind===F.DELETION){i.push({...m});continue}let d=u(m.startOffset,m.endOffset),p=s.insertOpsByStartOffset.get(m.startOffset)||[];for(let b of p)a.has(b)||(a.add(b),Ls({insertOp:b,splitModel:e,styleLookup:l,patchedModel:i,state:c,options:r,generateRedlines:n,author:o}));if(!d||d.type===Oe.EQUAL){i.push({...m,containerContext:c.containerStack.length>0?c.containerStack[c.containerStack.length-1]:null});continue}d.type===Oe.DELETE&&n&&i.push({...m,kind:F.DELETION,author:o,containerContext:c.containerStack.length>0?c.containerStack[c.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?F.INSERTION:F.TEXT,text:m.text,rPrXml:d?.rPrXml||"",startOffset:m.startOffset,endOffset:m.startOffset+m.text.length,author:n?o:void 0})}return i}function Ls(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:i,generateRedlines:a,author:s}=e,l=t.text.split(`
12
- `),u=Fs(r,t.startOffset,t.text);for(let c=0;c<l.length;c++){let f=Bs(l[c],i.numberingService,o),m=f.lineText;if(c>0){let d=Vo(o);f.isListLine&&f.numId&&(d=i.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:F.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,k(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(m.length>0||c>0)&&n.push({kind:a?F.INSERTION:F.TEXT,text:m,rPrXml:u?.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 Bs(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=Be(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,u=Math.floor(s/l),c=Vo(r),f=Ue(e,{allowZeroSpaceAfterMarker:!0}),m=c.match(/w:numId w:val="(\d+)"/),d=c.match(/w:ilvl w:val="(\d+)"/),p=m?m[1]:null,b=d?parseInt(d[1],10):0,h=t.getOrCreateNumId({type:i.format},{numId:p,type:"unknown"}),g=i.format==="outline"?Math.min(8,i.depth):Math.min(8,u+b);return{lineText:f,isListLine:!0,numId:h,ilvl:g}}function Vo(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=oe(e.currentParagraphPPrElement).replace(_s,""),e.currentParagraphPPrXml):""}function Fs(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 $s(e){let t=e.filter(o=>o.kind===F.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 Xs(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 Ds(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 zs(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===Oe.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 Jo="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Ws="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Us="http://schemas.microsoft.com/office/2006/xmlPackage",Go="http://schemas.openxmlformats.org/package/2006/relationships",js='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',Ko='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Hs=`
13
- <w:numbering xmlns:w="${Jo}">
1
+ var Qa=Object.create;var To=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var rs=Object.getPrototypeOf,ns=Object.prototype.hasOwnProperty;var os=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var is=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ts(t))!ns.call(e,o)&&o!==r&&To(e,o,{get:()=>t[o],enumerable:!(n=es(t,o))||n.enumerable});return e};var So=(e,t,r)=>(r=e!=null?Qa(rs(e)):{},is(t||!e||!e.__esModule?To(r,"default",{value:e,enumerable:!0}):r,e));var En=os((Af,Rt)=>{var A=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},K=-1,Z=1,D=0;A.Diff=function(e,t){return[e,t]};A.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 A.Diff(D,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 u=this.diff_compute_(e,t,i,o);return s&&u.unshift(new A.Diff(D,s)),l&&u.push(new A.Diff(D,l)),this.diff_cleanupMerge(u),u};A.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new A.Diff(Z,t)];if(!t)return[new A.Diff(K,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 A.Diff(Z,i.substring(0,s)),new A.Diff(D,a),new A.Diff(Z,i.substring(s+a.length))],e.length>t.length&&(o[0][0]=o[2][0]=K),o;if(a.length==1)return[new A.Diff(K,e),new A.Diff(Z,t)];var l=this.diff_halfMatch_(e,t);if(l){var u=l[0],c=l[1],f=l[2],m=l[3],d=l[4],p=this.diff_main(u,f,r,n),b=this.diff_main(c,m,r,n);return p.concat([new A.Diff(D,d)],b)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};A.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 A.Diff(D,""));for(var a=0,s=0,l=0,u="",c="";a<i.length;){switch(i[a][0]){case Z:l++,c+=i[a][1];break;case K:s++,u+=i[a][1];break;case D:if(s>=1&&l>=1){i.splice(a-s-l,s+l),a=a-s-l;for(var f=this.diff_main(u,c,!1,r),m=f.length-1;m>=0;m--)i.splice(a,0,f[m]);a=a+f.length}l=0,s=0,u="",c="";break}a++}return i.pop(),i};A.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),u=new Array(s),c=0;c<s;c++)l[c]=-1,u[c]=-1;l[a+1]=0,u[a+1]=0;for(var f=n-o,m=f%2!=0,d=0,p=0,b=0,h=0,g=0;g<i&&!(new Date().getTime()>r);g++){for(var w=-g+d;w<=g-p;w+=2){var x=a+w,N;w==-g||w!=g&&l[x-1]<l[x+1]?N=l[x+1]:N=l[x-1]+1;for(var T=N-w;N<n&&T<o&&e.charAt(N)==t.charAt(T);)N++,T++;if(l[x]=N,N>n)p+=2;else if(T>o)d+=2;else if(m){var y=a+f-w;if(y>=0&&y<s&&u[y]!=-1){var v=n-u[y];if(N>=v)return this.diff_bisectSplit_(e,t,N,T,r)}}}for(var I=-g+b;I<=g-h;I+=2){var y=a+I,v;I==-g||I!=g&&u[y-1]<u[y+1]?v=u[y+1]:v=u[y-1]+1;for(var P=v-I;v<n&&P<o&&e.charAt(n-v-1)==t.charAt(o-P-1);)v++,P++;if(u[y]=v,v>n)h+=2;else if(P>o)b+=2;else if(!m){var x=a+f-I;if(x>=0&&x<s&&l[x]!=-1){var N=l[x],T=a+N-x;if(v=n-v,N>=v)return this.diff_bisectSplit_(e,t,N,T,r)}}}}return[new A.Diff(K,e),new A.Diff(Z,t)]};A.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),u=this.diff_main(i,a,!1,o),c=this.diff_main(s,l,!1,o);return u.concat(c)};A.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(l){for(var u="",c=0,f=-1,m=r.length;f<l.length-1;){f=l.indexOf(`
2
+ `,c),f==-1&&(f=l.length-1);var d=l.substring(c,f+1);(n.hasOwnProperty?n.hasOwnProperty(d):n[d]!==void 0)?u+=String.fromCharCode(n[d]):(m==i&&(d=l.substring(c),f=l.length),u+=String.fromCharCode(m),n[d]=m,r[m++]=d),c=f+1}return u}var i=4e4,a=o(e);i=65535;var s=o(t);return{chars1:a,chars2:s,lineArray:r}};A.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("")}};A.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};A.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};A.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++)}};A.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,b,h){for(var g=p.substring(h,h+Math.floor(p.length/4)),w=-1,x="",N,T,y,v;(w=b.indexOf(g,w+1))!=-1;){var I=o.diff_commonPrefix(p.substring(h),b.substring(w)),P=o.diff_commonSuffix(p.substring(0,h),b.substring(0,w));x.length<P+I&&(x=b.substring(w-P,w)+b.substring(w,w+I),N=p.substring(0,h-P),T=p.substring(h+I),y=b.substring(0,w-P),v=b.substring(w+I))}return x.length*2>=p.length?[N,T,y,v,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 u,c,f,m;e.length>t.length?(u=l[0],c=l[1],f=l[2],m=l[3]):(f=l[0],m=l[1],u=l[2],c=l[3]);var d=l[4];return[u,c,f,m,d]};A.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=0,s=0,l=0,u=0;i<e.length;)e[i][0]==D?(r[n++]=i,a=l,s=u,l=0,u=0,o=e[i][1]):(e[i][0]==Z?l+=e[i][1].length:u+=e[i][1].length,o&&o.length<=Math.max(a,s)&&o.length<=Math.max(l,u)&&(e.splice(r[n-1],0,new A.Diff(K,o)),e[r[n-1]+1][0]=Z,n--,n--,i=n>0?r[n-1]:-1,a=0,s=0,l=0,u=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]==K&&e[i][0]==Z){var c=e[i-1][1],f=e[i][1],m=this.diff_commonOverlap_(c,f),d=this.diff_commonOverlap_(f,c);m>=d?(m>=c.length/2||m>=f.length/2)&&(e.splice(i,0,new A.Diff(D,f.substring(0,m))),e[i-1][1]=c.substring(0,c.length-m),e[i+1][1]=f.substring(m),i++):(d>=c.length/2||d>=f.length/2)&&(e.splice(i,0,new A.Diff(D,c.substring(0,d))),e[i-1][0]=Z,e[i-1][1]=f.substring(0,f.length-d),e[i+1][0]=K,e[i+1][1]=c.substring(d),i++),i++}i++}};A.prototype.diff_cleanupSemanticLossless=function(e){function t(d,p){if(!d||!p)return 6;var b=d.charAt(d.length-1),h=p.charAt(0),g=b.match(A.nonAlphaNumericRegex_),w=h.match(A.nonAlphaNumericRegex_),x=g&&b.match(A.whitespaceRegex_),N=w&&h.match(A.whitespaceRegex_),T=x&&b.match(A.linebreakRegex_),y=N&&h.match(A.linebreakRegex_),v=T&&d.match(A.blanklineEndRegex_),I=y&&p.match(A.blanklineStartRegex_);return v||I?5:T||y?4:g&&!x&&N?3:x||N?2:g||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==D&&e[r+1][0]==D){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,u=o,c=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,u=o,c=i)}e[r-1][1]!=l&&(l?e[r-1][1]=l:(e.splice(r-1,1),r--),e[r][1]=u,c?e[r+1][1]=c:(e.splice(r+1,1),r--))}r++}};A.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;A.whitespaceRegex_=/\s/;A.linebreakRegex_=/[\r\n]/;A.blanklineEndRegex_=/\n\r?\n$/;A.blanklineStartRegex_=/^\r?\n\r?\n/;A.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,i=0,a=!1,s=!1,l=!1,u=!1;i<e.length;)e[i][0]==D?(e[i][1].length<this.Diff_EditCost&&(l||u)?(r[n++]=i,a=l,s=u,o=e[i][1]):(n=0,o=null),l=u=!1):(e[i][0]==K?u=!0:l=!0,o&&(a&&s&&l&&u||o.length<this.Diff_EditCost/2&&a+s+l+u==3)&&(e.splice(r[n-1],0,new A.Diff(K,o)),e[r[n-1]+1][0]=Z,n--,o=null,a&&s?(l=u=!0,n=0):(n--,i=n>0?r[n-1]:-1,l=u=!1),t=!0)),i++;t&&this.diff_cleanupMerge(e)};A.prototype.diff_cleanupMerge=function(e){e.push(new A.Diff(D,""));for(var t=0,r=0,n=0,o="",i="",a;t<e.length;)switch(e[t][0]){case Z:n++,i+=e[t][1],t++;break;case K:r++,o+=e[t][1],t++;break;case D: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]==D?e[t-r-n-1][1]+=i.substring(0,a):(e.splice(0,0,new A.Diff(D,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 A.Diff(K,o)),t++),i.length&&(e.splice(t,0,new A.Diff(Z,i)),t++),t++):t!==0&&e[t-1][0]==D?(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]==D&&e[t+1][0]==D&&(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)};A.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]!==Z&&(r+=e[a][1].length),e[a][0]!==K&&(n+=e[a][1].length),!(r>t));a++)o=r,i=n;return e.length!=a&&e[a][0]===K?i:i+(t-o)};A.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],u=l.replace(r,"&amp;").replace(n,"&lt;").replace(o,"&gt;").replace(i,"&para;<br>");switch(s){case Z:t[a]='<ins style="background:#e6ffe6;">'+u+"</ins>";break;case K:t[a]='<del style="background:#ffe6e6;">'+u+"</del>";break;case D:t[a]="<span>"+u+"</span>";break}}return t.join("")};A.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Z&&(t[r]=e[r][1]);return t.join("")};A.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==K&&(t[r]=e[r][1]);return t.join("")};A.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 Z:r+=a.length;break;case K:n+=a.length;break;case D:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};A.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Z:t[r]="+"+encodeURI(e[r][1]);break;case K:t[r]="-"+e[r][1].length;break;case D:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};A.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 A.Diff(Z,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 u=e.substring(o,o+=l);i[a].charAt(0)=="="?r[n++]=new A.Diff(D,u):r[n++]=new A.Diff(K,u);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};A.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};A.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(N,T){var y=N/t.length,v=Math.abs(r-T);return o.Match_Distance?y+v/o.Match_Distance:v?1:y}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 u,c,f=t.length+e.length,m,d=0;d<t.length;d++){for(u=0,c=f;u<c;)i(d,r+c)<=a?u=c:f=c,c=Math.floor((f-u)/2+u);f=c;var p=Math.max(1,r-c+1),b=Math.min(r+c,e.length)+t.length,h=Array(b+2);h[b+1]=(1<<d)-1;for(var g=b;g>=p;g--){var w=n[e.charAt(g-1)];if(d===0?h[g]=(h[g+1]<<1|1)&w:h[g]=(h[g+1]<<1|1)&w|((m[g+1]|m[g])<<1|1)|m[g+1],h[g]&l){var x=i(d,g-1);if(x<=a)if(a=x,s=g-1,s>r)p=Math.max(1,2*r-s);else break}}if(i(d+1,r)>a)break;m=h}return s};A.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};A.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 A.Diff(D,o));var i=t.substring(e.start2+e.length1,e.start2+e.length1+n);i&&e.diffs.push(new A.Diff(D,i)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+i.length,e.length2+=o.length+i.length}};A.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 A.patch_obj,s=0,l=0,u=0,c=n,f=n,m=0;m<o.length;m++){var d=o[m][0],p=o[m][1];switch(!s&&d!==D&&(a.start1=l,a.start2=u),d){case Z:a.diffs[s++]=o[m],a.length2+=p.length,f=f.substring(0,u)+p+f.substring(u);break;case K:a.length1+=p.length,a.diffs[s++]=o[m],f=f.substring(0,u)+f.substring(u+p.length);break;case D: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,c),i.push(a),a=new A.patch_obj,s=0,c=f,l=u);break}d!==Z&&(l+=p.length),d!==K&&(u+=p.length)}return s&&(this.patch_addContext_(a,c),i.push(a)),i};A.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new A.patch_obj;o.diffs=[];for(var i=0;i<n.diffs.length;i++)o.diffs[i]=new A.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};A.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,u=-1;if(s.length>this.Match_MaxBits?(l=this.match_main(t,s.substring(0,this.Match_MaxBits),a),l!=-1&&(u=this.match_main(t,s.substring(s.length-this.Match_MaxBits),a+s.length-this.Match_MaxBits),(u==-1||l>=u)&&(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 c;if(u==-1?c=t.substring(l,l+s.length):c=t.substring(l,u+this.Match_MaxBits),s==c)t=t.substring(0,l)+this.diff_text2(e[i].diffs)+t.substring(l+s.length);else{var f=this.diff_main(s,c,!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 b=e[i].diffs[p];b[0]!==D&&(d=this.diff_xIndex(f,m)),b[0]===Z?t=t.substring(0,l+d)+b[1]+t.substring(l+d):b[0]===K&&(t=t.substring(0,l+d)+t.substring(l+this.diff_xIndex(f,m+b[1].length))),b[0]!==K&&(m+=b[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};A.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]!=D)i.unshift(new A.Diff(D,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]!=D)i.push(new A.Diff(D,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};A.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 A.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 A.Diff(D,a)));n.diffs.length!==0&&s.length1<t-this.Patch_Margin;){var u=n.diffs[0][0],c=n.diffs[0][1];u===Z?(s.length2+=c.length,i+=c.length,s.diffs.push(n.diffs.shift()),l=!1):u===K&&s.diffs.length==1&&s.diffs[0][0]==D&&c.length>2*t?(s.length1+=c.length,o+=c.length,l=!1,s.diffs.push(new A.Diff(u,c)),n.diffs.shift()):(c=c.substring(0,t-s.length1-this.Patch_Margin),s.length1+=c.length,o+=c.length,u===D?(s.length2+=c.length,i+=c.length):l=!1,s.diffs.push(new A.Diff(u,c)),c==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(c.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]===D?s.diffs[s.diffs.length-1][1]+=f:s.diffs.push(new A.Diff(D,f))),l||e.splice(++r,0,s)}}};A.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};A.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 A.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 A.Diff(K,l));else if(s=="+")a.diffs.push(new A.Diff(Z,l));else if(s==" ")a.diffs.push(new A.Diff(D,l));else{if(s=="@")break;if(s!=="")throw new Error('Invalid patch mode "'+s+'" in: '+l)}n++}}return t};A.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};A.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 Z:n="+";break;case K:n="-";break;case D:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
5
+ `}return r.join("").replace(/%20/g," ")};Rt.exports=A;Rt.exports.diff_match_patch=A;Rt.exports.DIFF_DELETE=K;Rt.exports.DIFF_INSERT=Z;Rt.exports.DIFF_EQUAL=D});var Sr=console,mn=Object.freeze({silent:0,error:1,warn:2,info:3}),as=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",dn=as;function ss(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(mn,t)?t:dn}function pn(e){return mn[dn]>=mn[e]}function ls(e,t={}){Sr=e||console,t.level&&(dn=ss(t.level))}function k(...e){pn("info")&&(Sr.log||(()=>{}))(...e)}function Le(...e){pn("warn")&&(Sr.warn||(()=>{}))(...e)}function te(...e){pn("error")&&(Sr.error||(()=>{}))(...e)}var Vt=globalThis.DOMParser,Gt=globalThis.XMLSerializer;function cs(e={}){e.DOMParser&&(Vt=e.DOMParser),e.XMLSerializer&&(Gt=e.XMLSerializer)}function us(e={}){if(!Vt&&globalThis.DOMParser&&(Vt=globalThis.DOMParser),!Vt)throw new Error("DOMParser is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Vt(e)}function me(){if(!Gt&&globalThis.XMLSerializer&&(Gt=globalThis.XMLSerializer),!Gt)throw new Error("XMLSerializer is not configured. Call configureXmlProvider({ DOMParser, XMLSerializer }) first.");return new Gt}function Eo(e,t="text/xml"){let r=U(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function fs(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function U(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"?te("[XmlAdapter] XML fatal parse error:",a):(r.push(a),Le(`[XmlAdapter] XML ${o||"warning"}:`,a))};try{let i=us({onError:n}).parseFromString(e,t),a=fs(i);if(!i?.documentElement||a){let s=a?.textContent||"Could not parse XML input.";return te("[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 te("[XmlAdapter] XML parse error:",i),{doc:null,error:{code:"PARSE_ERROR",message:i},warnings:r}}}function oe(e){return me().serializeToString(e)}var Io=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Ao=Io(),Po="Unknown";function ms(e){Ao=typeof e=="string"&&e.trim()?e.trim():Io()}function de(){return Ao}function ds(e){Po=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function gn(){return Po}var ps=[{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 ps){let l,u=s.regex.source||s.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),c="g"+(s.regex.ignoreCase?"i":""),f=new RegExp(u,c);for(;(l=f.exec(e))!==null;)n.push({start:l.index,end:l.index+l[0].length,fullMatch:l[0],innerText:s.isEscaped?gs(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),u=r.length;r+=l.cleanText;let c=r.length;t.push({start:u,end:c,format:s.format});for(let f of l.formatHints)t.push({start:u+f.start,end:u+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 hn(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function gs(e){return e?e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#039;/g,"'"):""}var Er=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Ro=new RegExp(`^(\\s*)((?:${Er})\\s+)`),Co=new RegExp(`^(\\s*)((?:${Er})\\s*)`),hs=new RegExp(`^(\\s*)((?:${Er})\\s+)`,"m"),ws=new RegExp(`^(\\s*)((?:${Er})\\s*)`,"m");function wn(e){return typeof e!="string"?!1:e.includes(`
6
+ `)&&hs.test(e)}function Kt(e){return typeof e!="string"?!1:e.includes(`
7
+ `)&&ws.test(e.trim())}function Be(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Co:Ro;return e.match(n)}function Ue(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Co:Ro;return e.replace(n,"")}function Oo(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function Yt(e){let t=String(e||"").trim();return Oo(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 bs(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function Jt(e,t={}){let r=Be(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=Oo(n);return{line:String(e||""),text:Ue(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/i)),markerType:a,listType:a,numberingStyle:Yt(n),outlineLevel:a==="numbered"?bs(n):null}}var S="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var Oe=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),$=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"}),St=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),_o=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"}),we=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 bn=1e3,ko=2147483647,Mo=1e4,xs=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Lo=new WeakMap;function Ns(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return xs.has(t)?!e.namespaceURI||e.namespaceURI===S||String(e.nodeName||"").startsWith("w:"):!1}function vs(e){let t=e?.getAttributeNS?.(S,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var he=class{constructor(t=bn){this.startValue=Number.isInteger(t)&&t>=0?t:bn,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(Ns(o)){let a=vs(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=ko-Mo;return this.nextId=r>=i?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=ko-Mo;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}},qt=new he;function Ir(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof he&&Lo.set(r,t),t}function Ye(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Lo.get(t)||null}function nt(e,t=bn){let r=new he(t);return r.seed(e),Ir(e,r),r}function Bo(){return qt.next()}function Ar(e=new Date){return e.toISOString()}function ie(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():de(),o=t instanceof he?t:Ye(t)||qt,i=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(i,r||"structural"),{id:i,author:n,date:Ar()}}function Pr(e,t=null){let r=typeof e=="string"&&e.trim()?e.trim():de(),n=t instanceof he?t:Ye(t)||qt,o=Ar(),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 Et(e,t=qt){let r=t instanceof he?t:qt,n=r.seed(e);return Ir(e,r),n}function Fo(e,t){return e<t-1}function It(e,t,r){return Fo(t,r)?e+`
8
+ `:e}function mt(e,t,r){return Fo(t,r)?e+1:e}function Zt(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 le(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=le(e,t,r);return o.length>0?o:Zt(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 xn(e){return Array.from(e?.childNodes||[])}function $o(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function Nn(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var vn=0;function Pt(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}:U(e,"application/xml"),a=i.doc;if(i.error||!a)return te("OOXML parse error:",i.error?.message),{runModel:r,acceptedText:n,pPr:null,error:i.error};let s=ne(a);if(s)return te("OOXML parse error:",s.textContent),{runModel:r,acceptedText:n,pPr:null};let l=le(a,S,"p");return l.length===0?(Le("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):Do(l,{includeParagraphBoundaries:!0})}catch(i){return te("Error ingesting OOXML:",i),{runModel:r,acceptedText:n,pPr:null}}}function yn(e){return e?Do([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function Qt(e){let t=re(e,S,"pPr");if(!t)return null;let r=re(t,S,"numPr");if(!r)return null;let n=re(r,S,"numId"),o=re(r,S,"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 Do(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],u=re(l,S,"pPr");s===0&&(a=u),n.push({kind:$.PARAGRAPH_START,pPrElement:u||null,startOffset:i,endOffset:i,text:""});let c=At(l,i,n);o+=c.text,i=o.length,r&&(o=It(o,s,e.length),i=mt(i,s,e.length))}return{runModel:n,acceptedText:o,pPr:a}}function At(e,t,r){let n=t,o="",i=ys(r);for(let a of xn(e)){if(Nn(a,S,"pPr")||Nn(a,S,"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 ys(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${vn++}`,i=re(r,S,"sdtPr"),a=re(r,S,"sdtContent");e.push({kind:$.CONTAINER_START,containerKind:St.SDT,containerId:o,propertiesXml:i?oe(i):"",startOffset:n,endOffset:n,text:""});let s=a?At(a,n,e):{offset:n,text:""};return e.push({kind:$.CONTAINER_END,containerKind:St.SDT,containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("smartTag",(r,n)=>{let o=`smartTag_${vn++}`;e.push({kind:$.CONTAINER_START,containerKind:St.SMART_TAG,containerId:o,propertiesXml:$o(r),startOffset:n,endOffset:n,text:""});let i=At(r,n,e);return e.push({kind:$.CONTAINER_END,containerKind:St.SMART_TAG,containerId:o,startOffset:i.offset,endOffset:i.offset,text:""}),i}),t.set("del",(r,n)=>{let o=Xo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Xo(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>At(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:$.BOOKMARK,nodeXml:oe(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:$.BOOKMARK,nodeXml:oe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:$.BOOKMARK,nodeXml:oe(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>At(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${vn++}`,i=r.getAttribute("r:id")||"",a=r.getAttribute("w:anchor")||"";e.push({kind:$.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:i,anchor:a}),startOffset:n,endOffset:n,text:""});let s=At(r,n,e);return e.push({kind:$.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:s.offset,endOffset:s.offset,text:""}),s}),t.set("r",(r,n)=>{let o=Ts(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Ts(e,t){let r=ye(e,S,"rPr"),n=r?oe(r):"",o="";for(let i of xn(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:$.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Xo(e,t){let r=e.getAttribute("w:author")||"",n="",o=le(e,S,"delText");for(let a of o)n+=a.textContent||"";let i=le(e,S,"r");for(let a of i){let s=le(a,S,"delText");for(let l of s)n+=l.textContent||""}return n?{kind:$.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:oe(e)}:null}function Sn(e){let t=re(e,S,"tblGrid"),r=t?le(t,S,"gridCol"):[],n=ve(e,S,"tr"),o=n.length,i=n.reduce((c,f)=>{let m=ve(f,S,"tc");return Math.max(c,m.length)},0),a=r.length||i,s=Array.from({length:o},()=>Array.from({length:a},()=>null)),l=new Map,u=new Map;for(let c=0;c<n.length;c++){let f=n[c],m=ve(f,S,"tc"),d=0;for(let p=0;p<m.length;p++){let b=m[p],h=re(b,S,"tcPr");for(;d<a&&s[c][d]!==null;)d++;if(d>=a)break;let g=h?re(h,S,"gridSpan")||ae(h,"w:gridSpan"):null,w=parseInt(g?.getAttribute("w:val")||"1",10),x=h?re(h,S,"vMerge")||ae(h,"w:vMerge"):null,N=x?.getAttribute("w:val"),T=x!==null,y;if(T&&N!=="restart"){let v=u.get(d);v?(v.cell.rowSpan++,y={gridRow:c,gridCol:d,rowSpan:0,colSpan:w,tcNode:b,blocks:[],tcPrXml:Tn(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:v.cell}):y=Ss(c,d,w,b,h)}else{let v=zo(b);if(y={gridRow:c,gridCol:d,rowSpan:1,colSpan:w,tcNode:b,blocks:v,tcPrXml:Tn(h),isMergeOrigin:T&&N==="restart",isMergeContinuation:!1,getText:()=>v.map(I=>I.acceptedText).join(`
10
+ `)},T&&N==="restart")for(let I=0;I<w;I++)u.set(d+I,{originRow:c,cell:y});else for(let I=0;I<w;I++)u.delete(d+I)}for(let v=0;v<w;v++){let I=d+v;I<a&&(s[c][I]=y,l.set(`${c},${I}`,y))}d+=w}}return{rowCount:o,colCount:a,grid:s,cellMap:l,tblPrXml:Es(e),tblGridXml:Is(e),trPrList:Array.from(n).map(c=>As(c))}}function Ss(e,t,r,n,o){let i=zo(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:i,tcPrXml:Tn(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>i.map(a=>a.acceptedText).join(`
11
+ `)}}function zo(e){return ve(e,S,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:i}=yn(r);return{runModel:n,acceptedText:o,pPr:i}})}function Tn(e){return e?oe(e):"<w:tcPr/>"}function Es(e){let t=re(e,S,"tblPr");return t?oe(t):"<w:tblPr/>"}function Is(e){let t=re(e,S,"tblGrid");return t?oe(t):"<w:tblGrid/>"}function As(e){let t=re(e,S,"trPr");return t?oe(t):"<w:trPr/>"}var jo=So(En(),1);var Ps=65536,Rr=262144,Cr=1,Or=55296-Cr,Rs=8192,Cs=Or+Rs,In=class extends Error{constructor(t=Rr){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Ho(e){return e?.code==="DIFF_TOKEN_LIMIT"}function Vo(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 jo.diff_match_patch;return r.Diff_Timeout=t,r}function Wo(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 Os(e,t,r={}){let n=[],o=new Map,i=r.maxTokens??Rr;if(!Number.isInteger(i)||i<1||i>Rr)throw new RangeError(`maxTokens must be an integer from 1 to ${Rr}.`);function a(f){let m="",d=[];for(let p of f){let b=o.get(p);if(b===void 0){if(n.length>=i)throw new In(i);b=n.length,n.push(p),o.set(p,b)}d.push(b),m+=String.fromCodePoint(Ps+b)}return{chars:m,tokenIds:d}}let s=Wo(e),l=Wo(t),u=a(s),c=a(l);return{chars1:u.chars,chars2:c.chars,wordArray:n,tokenIds1:u.tokenIds,tokenIds2:c.tokenIds}}function ks(e){let t=e<Or?Cr+e:57344+(e-Or);return String.fromCharCode(t)}function Ms(e){if(e>=Cr&&e<55296)return e-Cr;if(e>=57344&&e<=65535)return Or+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function Uo(e){let t="";for(let r of e)t+=ks(r);return t}function _s(e,t){return e.map(([r,n])=>{let o=[];for(let i=0;i<n.length;i++){let a=Ms(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 Ls(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=c=>c.map(f=>r[f]).join(""),s=[];n&&s.push([0,a(e.slice(0,n))]);let l=e.slice(n,e.length-i),u=t.slice(n,t.length-i);return l.length&&s.push([-1,a(l)]),u.length&&s.push([1,a(u)]),i&&s.push([0,a(e.slice(e.length-i))]),s}function er(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}=Os(e,t,r);if(o.length>Cs)return Ls(i,a,o);let s=Vo(r),l=s.diff_main(Uo(i),Uo(a));return n&&s.diff_cleanupSemantic(l),_s(l,o)}function Go(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=Vo().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function kr(e,t,r={}){if(e===t)return[{type:Oe.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:Oe.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:Oe.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=er(e,t,r),o=[],i=0;for(let[a,s]of n)a===0?(o.push({type:Oe.EQUAL,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===-1?(o.push({type:Oe.DELETE,startOffset:i,endOffset:i+s.length,text:s}),i+=s.length):a===1&&o.push({type:Oe.INSERT,startOffset:i,endOffset:i,text:s});return o}var Bs=/\s+xmlns:[^=]+="[^"]*"/g;function Mr(e,t){let r=Ws(t),n=[],o=0;for(let i of e){if(i.kind!==$.TEXT&&i.kind!==$.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 u=r[a];if(u>=i.endOffset)break;u>s&&(l=!0,n.push({...i,text:i.text.slice(s-i.startOffset,u-i.startOffset),startOffset:s,endOffset:u}),s=u),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 _r(e,t,r){let{generateRedlines:n,author:o}=r,i=[],a=new Set,s=Us(t),l=Ds(e),u=zs(s.nonInsertOps),c={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let m of e){if(m.kind===$.CONTAINER_START){c.containerStack.push(m.containerId),i.push({...m});continue}if(m.kind===$.CONTAINER_END){c.containerStack.pop(),i.push({...m});continue}if(m.kind===$.PARAGRAPH_START){c.currentParagraphPPrXml=typeof m.pPrXml=="string"?m.pPrXml:"",c.currentParagraphPPrElement=m.pPrElement||null,i.push({...m}),c.lastParagraphStartIndex=i.length-1;continue}if(m.kind===$.BOOKMARK||m.kind===$.DELETION){i.push({...m});continue}let d=u(m.startOffset,m.endOffset),p=s.insertOpsByStartOffset.get(m.startOffset)||[];for(let b of p)a.has(b)||(a.add(b),Fs({insertOp:b,splitModel:e,styleLookup:l,patchedModel:i,state:c,options:r,generateRedlines:n,author:o}));if(!d||d.type===Oe.EQUAL){i.push({...m,containerContext:c.containerStack.length>0?c.containerStack[c.containerStack.length-1]:null});continue}d.type===Oe.DELETE&&n&&i.push({...m,kind:$.DELETION,author:o,containerContext:c.containerStack.length>0?c.containerStack[c.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?$.INSERTION:$.TEXT,text:m.text,rPrXml:d?.rPrXml||"",startOffset:m.startOffset,endOffset:m.startOffset+m.text.length,author:n?o:void 0})}return i}function Fs(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:i,generateRedlines:a,author:s}=e,l=t.text.split(`
12
+ `),u=Xs(r,t.startOffset,t.text);for(let c=0;c<l.length;c++){let f=$s(l[c],i.numberingService,o),m=f.lineText;if(c>0){let d=Ko(o);f.isListLine&&f.numId&&(d=i.numberingService.buildListPPr(f.numId,f.ilvl)),n.push({kind:$.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,k(`[Patching] Converted current paragraph to list item: numId=${f.numId}, ilvl=${f.ilvl}`)}(m.length>0||c>0)&&n.push({kind:a?$.INSERTION:$.TEXT,text:m,rPrXml:u?.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 $s(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=Be(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,u=Math.floor(s/l),c=Ko(r),f=Ue(e,{allowZeroSpaceAfterMarker:!0}),m=c.match(/w:numId w:val="(\d+)"/),d=c.match(/w:ilvl w:val="(\d+)"/),p=m?m[1]:null,b=d?parseInt(d[1],10):0,h=t.getOrCreateNumId({type:i.format},{numId:p,type:"unknown"}),g=i.format==="outline"?Math.min(8,i.depth):Math.min(8,u+b);return{lineText:f,isListLine:!0,numId:h,ilvl:g}}function Ko(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=oe(e.currentParagraphPPrElement).replace(Bs,""),e.currentParagraphPPrXml):""}function Xs(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 Ds(e){let t=e.filter(o=>o.kind===$.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 zs(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 Ws(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 Us(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===Oe.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 Zo="http://schemas.openxmlformats.org/wordprocessingml/2006/main",js="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Hs="http://schemas.microsoft.com/office/2006/xmlPackage",Yo="http://schemas.openxmlformats.org/package/2006/relationships",Vs='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',Jo='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Gs=`
13
+ <w:numbering xmlns:w="${Zo}">
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 Ja=Object.create;var To=Object.defineProperty;var qa=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 Vs(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function qo(e,t=!0){let r=t?` xmlns:r="${Ws}"`:"";return`<w:document xmlns:w="${Jo}"${r}><w:body>${e}</w:body></w:document>`}function Yo(e){return`
22
+ </w:numbering>`.trim();function Ks(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function Qo(e,t=!0){let r=t?` xmlns:r="${js}"`:"";return`<w:document xmlns:w="${Zo}"${r}><w:body>${e}</w:body></w:document>`}function qo(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
- ${Vs(e)}
25
+ ${Ks(e)}
26
26
  </pkg:xmlData>
27
- </pkg:part>`}function Zo(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
- <pkg:package xmlns:pkg="${Us}">
27
+ </pkg:part>`}function ei(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
28
+ <pkg:package xmlns:pkg="${Hs}">
29
29
  <pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
30
30
  <pkg:xmlData>
31
- <Relationships xmlns="${Go}">
32
- ${js}
31
+ <Relationships xmlns="${Yo}">
32
+ ${Vs}
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="${Go}">
38
+ <Relationships xmlns="${Yo}">
39
39
  ${t}
40
40
  </Relationships>
41
41
  </pkg:xmlData>
@@ -45,7 +45,7 @@ var Ja=Object.create;var To=Object.defineProperty;var qa=Object.getOwnPropertyDe
45
45
  ${e}
46
46
  </pkg:xmlData>
47
47
  </pkg:part>
48
- </pkg:package>`}function Qo(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=qo(i,!0),s="",l="";return n?(s=Ko,l+=Yo(n)):r&&(s=Ko,l+=Yo(Hs)),Zo(a,s,l)}function ei(e){let t=qo(e,!0);return Zo(t)}var Gs=/\s+xmlns:[^=]+="[^"]*"/g;function Fe(e,t,r=[],n={}){let o=Ks(n),{generateRedlines:i}=o,a=[],s="",l=null,u=[];function c(){if(u.length>0||a.length===0){let f="";s?f=dt(s):l?(s=dt(oe(l)),f=s):t&&(typeof t=="string"?f=t:f=oe(t),f=dt(f)),a.push(`<w:p>${f}${u.join("")}</w:p>`),u=[]}}for(let f of e)switch(f.kind){case F.PARAGRAPH_START:(u.length>0||a.length>0)&&c(),s=f.pPrXml||"",l=f.pPrElement||null;break;case F.TEXT:u.push(ti(f,r,o));break;case F.DELETION:i&&u.push(Ys(f,o));break;case F.INSERTION:i?u.push(Js(f,r,o)):u.push(ti(f,r,o));break;case F.BOOKMARK:case F.HYPERLINK:f.nodeXml&&u.push(dt(f.nodeXml));break;case F.CONTAINER_START:if(f.containerKind==="sdt")u.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")u.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}"`:"";u.push(`<w:hyperlink${d}${p}>`)}break;case F.CONTAINER_END:f.containerKind==="sdt"?u.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?u.push("</w:smartTag>"):f.containerKind==="hyperlink"&&u.push("</w:hyperlink>");break;default:Le("Unknown run kind:",f.kind)}return c(),a.join("")}function Ks(e){if(typeof e=="string")return{author:me(),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():me(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function ti(e,t,r={}){let n=Ke(t,e.startOffset,e.endOffset),o=r?.font??null,i=e.rPrXml?dt(e.rPrXml):"";if(o&&(i=An(i,o)),n.length===0)return ot(e.text,i);let a=[],s=0,l=e.text,u=e.startOffset;for(let c of n){let f=Math.max(0,c.start-u),m=Math.min(l.length,c.end-u);f>s&&a.push(ot(l.slice(s,f),i));let d=ri(i,c.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">${xe(e)}</w:t></w:r>`:""}function Ys(e,t={}){let r=ie(t.author??me(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?dt(e.rPrXml):"";return n&&(o=An(o,n)),`<w:del w:id="${r.id}" w:author="${xe(r.author)}" w:date="${r.date}"><w:r>${o}<w:delText xml:space="preserve">${xe(e.text)}</w:delText></w:r></w:del>`}function Js(e,t,r={}){let n=ie(r.author??me(),r.revisionIdAllocator,"ins"),o=r.font??null,i=Ke(t,e.startOffset,e.endOffset),a="",s=e.rPrXml?dt(e.rPrXml):"";if(o&&(s=An(s,o)),i.length===0)a=ot(e.text,s);else{let l=0,u=e.text,c=e.startOffset;for(let f of i){let m=Math.max(0,f.start-c),d=Math.min(u.length,f.end-c);m>l&&(a+=ot(u.slice(l,m),s));let p=ri(s,f.format);a+=ot(u.slice(m,d),p),l=d}l<u.length&&(a+=ot(u.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${xe(n.author)}" w:date="${n.date}">`+a+"</w:ins>"}function An(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 ri(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=qs(t);return Qo(e,r)}function qs(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function dt(e){return e?e.replace(Gs,""):""}function Pn(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){Pn(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||V.BULLET;if(r&&Pn(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let i=this.contextMap.get(n);if(Pn(i))return i;this.contextMap.delete(n)}if(n===V.OUTLINE)return"3";if(n===V.DECIMAL)return"2";if(n===V.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==V.DECIMAL&&n!==V.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||we.PERIOD}]}),this.contextMap.set(i,a),a}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:V.BULLET,suffix:we.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:V.BULLET,suffix:we.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:V.OUTLINE,suffix:we.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:V.LOWER_ALPHA,suffix:we.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?V.LOWER_ROMAN:V.UPPER_ROMAN,suffix:we.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:V.DECIMAL,suffix:we.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:V.DECIMAL,suffix:we.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:V.LOWER_ALPHA,suffix:we.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:V.UPPER_ALPHA,suffix:we.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?V.LOWER_ROMAN:V.UPPER_ROMAN,suffix:we.PERIOD,depth:0}:/^\d+/.test(r)?{format:V.DECIMAL,suffix:we.PERIOD,depth:0}:{format:V.BULLET,suffix:we.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[V.DECIMAL]:"decimal",[V.LOWER_ALPHA]:"lowerLetter",[V.UPPER_ALPHA]:"upperLetter",[V.LOWER_ROMAN]:"lowerRoman",[V.UPPER_ROMAN]:"upperRoman",[V.BULLET]:"bullet",[V.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===V.BULLET)return"\u2022";let o=`%${n+1}`;if(t===V.OUTLINE)return Array(n+1).fill(0).map((i,a)=>`%${a+1}`).join(".")+".";switch(r){case we.PERIOD:return`${o}.`;case we.PAREN_RIGHT:return`${o})`;case we.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
48
+ </pkg:package>`}function ti(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=Qo(i,!0),s="",l="";return n?(s=Jo,l+=qo(n)):r&&(s=Jo,l+=qo(Gs)),ei(a,s,l)}function ri(e){let t=Qo(e,!0);return ei(t)}var Ys=/\s+xmlns:[^=]+="[^"]*"/g;function Fe(e,t,r=[],n={}){let o=Js(n),{generateRedlines:i}=o,a=[],s="",l=null,u=[];function c(){if(u.length>0||a.length===0){let f="";s?f=dt(s):l?(s=dt(oe(l)),f=s):t&&(typeof t=="string"?f=t:f=oe(t),f=dt(f)),a.push(`<w:p>${f}${u.join("")}</w:p>`),u=[]}}for(let f of e)switch(f.kind){case $.PARAGRAPH_START:(u.length>0||a.length>0)&&c(),s=f.pPrXml||"",l=f.pPrElement||null;break;case $.TEXT:u.push(ni(f,r,o));break;case $.DELETION:i&&u.push(qs(f,o));break;case $.INSERTION:i?u.push(Zs(f,r,o)):u.push(ni(f,r,o));break;case $.BOOKMARK:case $.HYPERLINK:f.nodeXml&&u.push(dt(f.nodeXml));break;case $.CONTAINER_START:if(f.containerKind==="sdt")u.push(`<w:sdt>${f.propertiesXml}<w:sdtContent>`);else if(f.containerKind==="smartTag")u.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}"`:"";u.push(`<w:hyperlink${d}${p}>`)}break;case $.CONTAINER_END:f.containerKind==="sdt"?u.push("</w:sdtContent></w:sdt>"):f.containerKind==="smartTag"?u.push("</w:smartTag>"):f.containerKind==="hyperlink"&&u.push("</w:hyperlink>");break;default:Le("Unknown run kind:",f.kind)}return c(),a.join("")}function Js(e){if(typeof e=="string")return{author:de(),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():de(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function ni(e,t,r={}){let n=Ke(t,e.startOffset,e.endOffset),o=r?.font??null,i=e.rPrXml?dt(e.rPrXml):"";if(o&&(i=An(i,o)),n.length===0)return ot(e.text,i);let a=[],s=0,l=e.text,u=e.startOffset;for(let c of n){let f=Math.max(0,c.start-u),m=Math.min(l.length,c.end-u);f>s&&a.push(ot(l.slice(s,f),i));let d=oi(i,c.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 qs(e,t={}){let r=ie(t.author??de(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?dt(e.rPrXml):"";return n&&(o=An(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 Zs(e,t,r={}){let n=ie(r.author??de(),r.revisionIdAllocator,"ins"),o=r.font??null,i=Ke(t,e.startOffset,e.endOffset),a="",s=e.rPrXml?dt(e.rPrXml):"";if(o&&(s=An(s,o)),i.length===0)a=ot(e.text,s);else{let l=0,u=e.text,c=e.startOffset;for(let f of i){let m=Math.max(0,f.start-c),d=Math.min(u.length,f.end-c);m>l&&(a+=ot(u.slice(l,m),s));let p=oi(s,f.format);a+=ot(u.slice(m,d),p),l=d}l<u.length&&(a+=ot(u.slice(l),s))}return`<w:ins w:id="${n.id}" w:author="${Ne(n.author)}" w:date="${n.date}">`+a+"</w:ins>"}function An(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 oi(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=Qs(t);return ti(e,r)}function Qs(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function dt(e){return e?e.replace(Ys,""):""}function Pn(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){Pn(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||G.BULLET;if(r&&Pn(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let i=this.contextMap.get(n);if(Pn(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||we.PERIOD}]}),this.contextMap.set(i,a),a}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:G.BULLET,suffix:we.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:G.BULLET,suffix:we.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:G.OUTLINE,suffix:we.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:G.LOWER_ALPHA,suffix:we.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:we.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:G.DECIMAL,suffix:we.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:G.DECIMAL,suffix:we.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:G.LOWER_ALPHA,suffix:we.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:G.UPPER_ALPHA,suffix:we.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?G.LOWER_ROMAN:G.UPPER_ROMAN,suffix:we.PERIOD,depth:0}:/^\d+/.test(r)?{format:G.DECIMAL,suffix:we.PERIOD,depth:0}:{format:G.BULLET,suffix:we.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 we.PERIOD:return`${o}.`;case we.PAREN_RIGHT:return`${o})`;case we.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
49
49
  <w:pPr>${n.includeListParagraphStyle===!0?`
50
50
  <w:pStyle w:val="ListParagraph"/>`:""}
51
51
  <w:numPr>
@@ -123,53 +123,55 @@ var Ja=Object.create;var To=Object.defineProperty;var qa=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(),c=`<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 b=e.hasHeader&&p===0,h=f[p]||[],g="";for(let x=0;x<s;x++){let N=h[x]||"",{cleanText:T,formatHints:y}=Ie(N),v=[{kind:r&&!i?F.INSERTION:F.TEXT,text:T,rPrXml:b?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:T.length}],E=Fe(v,null,y,{author:n,generateRedlines:r,revisionIdAllocator:o});g+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${E}</w:tc>`}m+=`<w:tr>${b?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${g}</w:tr>`}let d=`<w:tbl>${l}${c}${m}</w:tbl>`;return a&&(d=`<w:ins w:id="${a.id}" w:author="${xe(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 u=a[l];for(let c=0;c<e.colCount;c++){let f=e.grid[l]?.[c],m=u?.[c];f&&(f.isMergeContinuation||c>f.gridCol||m!==void 0&&f.getText()!==m&&r.push({type:"cell_modify",gridRow:l,gridCol:c,originalCell:f,newText:m}))}}return r}function oi(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,a=Zs(t),s="";for(let u=0;u<e.rowCount;u++){let c=a.rowDeleteByRow.get(u)||null;if(c&&!n)continue;let f="",m=0;for(;m<e.colCount;){let p=e.grid[u][m];if(!p){m++;continue}if(p.isMergeContinuation){m++;continue}let b=a.cellModifyByCoordinate.get(`${u}:${m}`)||null,h;b?h=Qs(p,b.newText,r):h=el(p.blocks),f+=tl(p,h,r),m+=p.colSpan}let d=e.trPrList[u]||"<w:trPr/>";if(c&&n){let p=ie(o,i),b=`<w:del w:id="${p.id}" w:author="${xe(p.author)}" w:date="${p.date}"/>`;d.includes("</w:trPr>")?d=d.replace("</w:trPr>",`${b}</w:trPr>`):d=`<w:trPr>${b}</w:trPr>`}s+=`<w:tr>${d}${f}</w:tr>`}let l=a.rowInsertOperations;for(let u of l){let c="",f=n?ie(o,i):null;for(let d of u.cells){let{cleanText:p,formatHints:b}=Ie(d),h=[{kind:n?F.INSERTION:F.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],g=Fe(h,null,b,{author:o,generateRedlines:n,revisionIdAllocator:i});c+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${g}</w:tc>`}let m="<w:trPr/>";n&&(m=`<w:trPr><w:ins w:id="${f.id}" w:author="${xe(f.author)}" w:date="${f.date}"/></w:trPr>`),s+=`<w:tr>${m}${c}</w:tr>`}return`
126
+ `.trim(),c=`<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 b=e.hasHeader&&p===0,h=f[p]||[],g="";for(let x=0;x<s;x++){let N=h[x]||"",{cleanText:T,formatHints:y}=Ie(N),v=[{kind:r&&!i?$.INSERTION:$.TEXT,text:T,rPrXml:b?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:T.length}],I=Fe(v,null,y,{author:n,generateRedlines:r,revisionIdAllocator:o});g+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${I}</w:tc>`}m+=`<w:tr>${b?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>"}${g}</w:tr>`}let d=`<w:tbl>${l}${c}${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 ii(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 u=a[l];for(let c=0;c<e.colCount;c++){let f=e.grid[l]?.[c],m=u?.[c];f&&(f.isMergeContinuation||c>f.gridCol||m!==void 0&&f.getText()!==m&&r.push({type:"cell_modify",gridRow:l,gridCol:c,originalCell:f,newText:m}))}}return r}function ai(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,a=el(t),s="";for(let u=0;u<e.rowCount;u++){let c=a.rowDeleteByRow.get(u)||null;if(c&&!n)continue;let f="",m=0;for(;m<e.colCount;){let p=e.grid[u][m];if(!p){m++;continue}if(p.isMergeContinuation){m++;continue}let b=a.cellModifyByCoordinate.get(`${u}:${m}`)||null,h;b?h=tl(p,b.newText,r):h=rl(p.blocks),f+=nl(p,h,r),m+=p.colSpan}let d=e.trPrList[u]||"<w:trPr/>";if(c&&n){let p=ie(o,i),b=`<w:del w:id="${p.id}" w:author="${Ne(p.author)}" w:date="${p.date}"/>`;d.includes("</w:trPr>")?d=d.replace("</w:trPr>",`${b}</w:trPr>`):d=`<w:trPr>${b}</w:trPr>`}s+=`<w:tr>${d}${f}</w:tr>`}let l=a.rowInsertOperations;for(let u of l){let c="",f=n?ie(o,i):null;for(let d of u.cells){let{cleanText:p,formatHints:b}=Ie(d),h=[{kind:n?$.INSERTION:$.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],g=Fe(h,null,b,{author:o,generateRedlines:n,revisionIdAllocator:i});c+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${g}</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}${c}</w:tr>`}return`
127
127
  <w:tbl>
128
128
  ${e.tblPrXml}
129
129
  ${e.tblGridXml}
130
130
  ${s}
131
131
  </w:tbl>
132
- `}function Zs(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 Qs(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,{cleanText:a,formatHints:s}=Ie(t),l=e.getText(),u=kr(l,a),c=e.blocks[0]||{runModel:[],pPr:null},f=Mr(c.runModel,u),m=_r(f,u,{generateRedlines:n,author:o,formatHints:s});return Fe(m,c.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:i})}function el(e){return e.map(t=>Fe(t.runModel,t.pPr,[],{})).join("")}function tl(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 $e(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===S&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function C(e,t){return typeof e.createElementNS=="function"?e.createElementNS(S,t):e.createElement(t)}function ii(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(S,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>I(n,t))}var ai=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function Lr(e){return ai.some(t=>ii(e,t).length>0)}function Rn(e){if(!e)return[];let t=new Set;for(let r of ai)for(let n of ii(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(S,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function rl(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 de(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:rl(e.oxml)}}async function Ct(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:i=!0,author:a="AI",font:s=null,revisionIdAllocator:l=null,numberingService:u}=e,c=ol(t),f=nl(c),m=f.map(v=>v.raw),d=[],p=sl(n),b=si(n,p),h=si(n,p,["rFonts","kern","position","rtl","cs","lang"]),g=[];if(i){if(n&&n.length>0)g=n.filter(v=>v.kind==="text"||v.kind==="run").map(v=>({...v,kind:"deletion",author:a}));else if(o&&o.trim().length>0){let v=o.trim();g=[{kind:"deletion",text:v,author:a,startOffset:0,endOffset:v.length}]}}if(i&&g.length>0){let v=li(p,"del",a,l),E=Fe(g,v,[],{author:a,generateRedlines:i,revisionIdAllocator:l});d.push(E)}let w=Cn(m);k(`[ListGen] Detected indentation step: ${w} spaces/chars`);let x=f.find(v=>v.marker)?.marker||"",{format:N}=u.detectNumberingFormat(x);k(`[ListGen] Detected primary marker: "${x}", format: ${N}`);for(let v=0;v<f.length;v++){let E=il(f,v);if(E){let L=$e(E.tableText);if(L.headers.length>0||L.rows.length>0){d.push(pt(L,{generateRedlines:i,author:a,revisionIdAllocator:l,trackAsBlock:!0})),v=E.endIndex;continue}}let P=f[v],B=al(P,w,r,u,i,a,s,l,b,h);d.push(B.ooxml)}let T=u.generateNumberingXml(),y=d.join("");return k(`[ListGen] \u2705 Generated OOXML for ${d.length} paragraphs, total length: ${y.length}`),k(`[ListGen] First 200 chars: ${y.substring(0,200)}...`),{ooxml:y,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:T}}function Cn(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 nl(e){return e.split(`
134
- `).filter(t=>t.trim().length>0).map(t=>{let r=Be(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 ol(e){let t=String(e||"").split(`
132
+ `}function el(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 tl(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:i=null}=r,{cleanText:a,formatHints:s}=Ie(t),l=e.getText(),u=kr(l,a),c=e.blocks[0]||{runModel:[],pPr:null},f=Mr(c.runModel,u),m=_r(f,u,{generateRedlines:n,author:o,formatHints:s});return Fe(m,c.pPr,s,{author:o,generateRedlines:n,revisionIdAllocator:i})}function rl(e){return e.map(t=>Fe(t.runModel,t.pPr,[],{})).join("")}function nl(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 $e(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 E(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===S&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function C(e,t){return typeof e.createElementNS=="function"?e.createElementNS(S,t):e.createElement(t)}function si(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(S,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>E(n,t))}var li=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function Lr(e){return li.some(t=>si(e,t).length>0)}function Rn(e){if(!e)return[];let t=new Set;for(let r of li)for(let n of si(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(S,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function ol(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 ue(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:ol(e.oxml)}}async function Ct(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:i=!0,author:a="AI",font:s=null,revisionIdAllocator:l=null,numberingService:u}=e,c=al(t),f=il(c),m=f.map(v=>v.raw),d=[],p=cl(n),b=ci(n,p),h=ci(n,p,["rFonts","kern","position","rtl","cs","lang"]),g=[];if(i){if(n&&n.length>0)g=n.filter(v=>v.kind==="text"||v.kind==="run").map(v=>({...v,kind:"deletion",author:a}));else if(o&&o.trim().length>0){let v=o.trim();g=[{kind:"deletion",text:v,author:a,startOffset:0,endOffset:v.length}]}}if(i&&g.length>0){let v=ui(p,"del",a,l),I=Fe(g,v,[],{author:a,generateRedlines:i,revisionIdAllocator:l});d.push(I)}let w=Cn(m);k(`[ListGen] Detected indentation step: ${w} spaces/chars`);let x=f.find(v=>v.marker)?.marker||"",{format:N}=u.detectNumberingFormat(x);k(`[ListGen] Detected primary marker: "${x}", format: ${N}`);for(let v=0;v<f.length;v++){let I=sl(f,v);if(I){let L=$e(I.tableText);if(L.headers.length>0||L.rows.length>0){d.push(pt(L,{generateRedlines:i,author:a,revisionIdAllocator:l,trackAsBlock:!0})),v=I.endIndex;continue}}let P=f[v],B=ll(P,w,r,u,i,a,s,l,b,h);d.push(B.ooxml)}let T=u.generateNumberingXml(),y=d.join("");return k(`[ListGen] \u2705 Generated OOXML for ${d.length} paragraphs, total length: ${y.length}`),k(`[ListGen] First 200 chars: ${y.substring(0,200)}...`),{ooxml:y,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:T}}function Cn(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 il(e){return e.split(`
134
+ `).filter(t=>t.trim().length>0).map(t=>{let r=Be(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
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=Be(a);if(!l)return e;let u=Ue(a),c=Be(u);if(!c)return e;let f=(l[2]||"").trim(),m=(c[2]||"").trim();if(!f||!m||f===m)return e;let p=`${l[1]||""}${u.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 k(`[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 al(e,t,r,n,o,i,a,s,l,u){let c="",f="",m=l;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),g=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],x=w[h-1]||w[w.length-1];f=e.headerMatch[2].trim(),c=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${g}"/><w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr></w:pPr>`,m=ll(u,`<w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),g=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,x=h.format==="outline"?Math.min(8,h.depth):Math.min(8,g+w);f=Ue(e.raw);let N=n.getOrCreateNumId({type:h.format},r);c=n.buildListPPr(N,x)}else f=e.raw;o&&(c=li(c||"<w:pPr/>","ins",i,s));let{cleanText:d,formatHints:p}=Ie(f),b=[];return b.push({kind:o?"insertion":"run",text:d,rPrXml:m,author:i,startOffset:0,endOffset:d.length}),{ooxml:Fe(b,c,p,{author:i,generateRedlines:o,font:a,revisionIdAllocator:s})}}function sl(e){let t=(e||[]).find(r=>r.kind===F.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function si(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(i=>(i.kind===F.TEXT||i.kind==="text")&&i.rPrXml).map(i=>i.rPrXml);t&&n.push(typeof t=="string"?t:oe(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 ll(...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 li(e,t,r,n){let o=ie(r,n),i,a;if(e?.nodeType===1)i=e.cloneNode(!0),a=i.ownerDocument;else{let u=typeof e=="string"&&e.trim()?e:"<w:pPr/>",c=W(`<w:root xmlns:w="${S}">${u}</w:root>`);if(!c.doc)throw new Error(c.error?.message||"Could not parse paragraph properties for list revision");a=c.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(u=>u.nodeType===1&&u.localName==="rPr");s||(s=C(a,"w:rPr"),i.appendChild(s));let l=C(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),oe(i)}var cl=new Set(["officeonline","officeweb","web"]);function ul(e){return e?cl.has(String(e).toLowerCase()):!1}function fl(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function ml(){return new Promise(e=>setTimeout(e,0))}var tr=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??gn(),this.isWebPlatform=t.isWebPlatform??ul(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:[]}:W(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:u,pPr:c}=Pt(t,{xmlDoc:a}),f=s?Qt(s):null;k(`[Reconcile] Ingested ${l.length} runs, ${u.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(u.length,r?.length||0));let{cleanText:m,formatHints:d}=Ie(r);k(`[Reconcile] Preprocessed: ${d.length} format hints`),await this.maybeYield(l.length,Math.max(u.length,m.length));let p=wn(m),b=Kt(m),h=p||b;if(!p&&b&&k("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),u===m&&d.length===0&&!h)return k("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let g=Math.max(u.length,m.length)<this.disableSemanticCleanupOverChars,w=kr(u,m,{cleanupSemantic:g});g||k("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(u.length,m.length));let x=l.filter(P=>P.kind===F.PARAGRAPH_START).length,N=wn(u)||Kt(u),T=h&&N&&x>1&&u!==m;if(k(`[Reconcile] isTargetList: ${h}, paragraphCount: ${x}`),T)k("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return k("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),k(`[Reconcile] cleanText preview: ${m.substring(0,100)}...`),k(`[Reconcile] acceptedText preview: ${u.substring(0,100)}...`),this.executeListGeneration(m,f,l);k(`[Reconcile] Computed ${w.length} diff operations`);let y=Mr(l,w);k(`[Reconcile] Split into ${y.length} runs`);let v=_r(y,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:d,numberingService:this.numberingService});k(`[Reconcile] Patched model has ${v.length} runs`),await this.maybeYield(v.length,Math.max(u.length,m.length));let E=Fe(v,c,d,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let P=this.validateBasic(E);P.isValid||o.push(...P.errors)}return{ooxml:E,isValid:o.length===0,warnings:o}}catch(i){return te("[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=W(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&&fl()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await ml())}wrapForInsertion(t,r={}){return it(t,r)}async executeListGeneration(t,r,n,o=""){return Ct({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 Cn(t)}executeTableGeneration(t){let r=$e(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:pt(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var ci=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function ui(e){return!e||e.trim().length===0}function fi(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function dl(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function On(e){return ui(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":fi(e)?"table":Be(e)?"list":"paragraph"}function Br(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
136
+ `)}function sl(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 ll(e,t,r,n,o,i,a,s,l,u){let c="",f="",m=l;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),g=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],x=w[h-1]||w[w.length-1];f=e.headerMatch[2].trim(),c=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${g}"/><w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr></w:pPr>`,m=ul(u,`<w:rPr><w:b/><w:sz w:val="${x}"/><w:szCs w:val="${x}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),g=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,x=h.format==="outline"?Math.min(8,h.depth):Math.min(8,g+w);f=Ue(e.raw);let N=n.getOrCreateNumId({type:h.format},r);c=n.buildListPPr(N,x)}else f=e.raw;o&&(c=ui(c||"<w:pPr/>","ins",i,s));let{cleanText:d,formatHints:p}=Ie(f),b=[];return b.push({kind:o?"insertion":"run",text:d,rPrXml:m,author:i,startOffset:0,endOffset:d.length}),{ooxml:Fe(b,c,p,{author:i,generateRedlines:o,font:a,revisionIdAllocator:s})}}function cl(e){let t=(e||[]).find(r=>r.kind===$.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function ci(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(i=>(i.kind===$.TEXT||i.kind==="text")&&i.rPrXml).map(i=>i.rPrXml);t&&n.push(typeof t=="string"?t:oe(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 ul(...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 ui(e,t,r,n){let o=ie(r,n),i,a;if(e?.nodeType===1)i=e.cloneNode(!0),a=i.ownerDocument;else{let u=typeof e=="string"&&e.trim()?e:"<w:pPr/>",c=U(`<w:root xmlns:w="${S}">${u}</w:root>`);if(!c.doc)throw new Error(c.error?.message||"Could not parse paragraph properties for list revision");a=c.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(u=>u.nodeType===1&&u.localName==="rPr");s||(s=C(a,"w:rPr"),i.appendChild(s));let l=C(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),oe(i)}var fl=new Set(["officeonline","officeweb","web"]);function ml(e){return e?fl.has(String(e).toLowerCase()):!1}function dl(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function pl(){return new Promise(e=>setTimeout(e,0))}var tr=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??gn(),this.isWebPlatform=t.isWebPlatform??ml(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:[]}:U(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:u,pPr:c}=Pt(t,{xmlDoc:a}),f=s?Qt(s):null;k(`[Reconcile] Ingested ${l.length} runs, ${u.length} chars, numbering:`,f),await this.maybeYield(l.length,Math.max(u.length,r?.length||0));let{cleanText:m,formatHints:d}=Ie(r);k(`[Reconcile] Preprocessed: ${d.length} format hints`),await this.maybeYield(l.length,Math.max(u.length,m.length));let p=wn(m),b=Kt(m),h=p||b;if(!p&&b&&k("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),u===m&&d.length===0&&!h)return k("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let g=Math.max(u.length,m.length)<this.disableSemanticCleanupOverChars,w=kr(u,m,{cleanupSemantic:g});g||k("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(l.length,Math.max(u.length,m.length));let x=l.filter(P=>P.kind===$.PARAGRAPH_START).length,N=wn(u)||Kt(u),T=h&&N&&x>1&&u!==m;if(k(`[Reconcile] isTargetList: ${h}, paragraphCount: ${x}`),T)k("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return k("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),k(`[Reconcile] cleanText preview: ${m.substring(0,100)}...`),k(`[Reconcile] acceptedText preview: ${u.substring(0,100)}...`),this.executeListGeneration(m,f,l);k(`[Reconcile] Computed ${w.length} diff operations`);let y=Mr(l,w);k(`[Reconcile] Split into ${y.length} runs`);let v=_r(y,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:d,numberingService:this.numberingService});k(`[Reconcile] Patched model has ${v.length} runs`),await this.maybeYield(v.length,Math.max(u.length,m.length));let I=Fe(v,c,d,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let P=this.validateBasic(I);P.isValid||o.push(...P.errors)}return{ooxml:I,isValid:o.length===0,warnings:o}}catch(i){return te("[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=U(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&&dl()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await pl())}wrapForInsertion(t,r={}){return it(t,r)}async executeListGeneration(t,r,n,o=""){return Ct({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 Cn(t)}executeTableGeneration(t){let r=$e(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:pt(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator}),isValid:!0,warnings:[],includeNumbering:!1}}};var fi=/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/;function mi(e){return!e||e.trim().length===0}function di(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function gl(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function On(e){return mi(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":di(e)?"table":Be(e)?"list":"paragraph"}function Br(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(ui(r[i])){i++;continue}let l=On(r[i]),u=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&&fi(r[i]);)m.push(r[i].trim()),i++;let d=m.length>1&&ci.test(m[1]),p=m.filter(b=>!ci.test(b)).map(b=>dl(b).length);d||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:u,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:u,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:u,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(`
139
+ `),n=[],o=[],i=0;for(;i<r.length;){if(mi(r[i])){i++;continue}let l=On(r[i]),u=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&&di(r[i]);)m.push(r[i].trim()),i++;let d=m.length>1&&fi.test(m[1]),p=m.filter(b=>!fi.test(b)).map(b=>gl(b).length);d||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:u,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:u,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:u,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
140
  `)});continue}if(l==="list"){let m=[];for(;i<r.length&&On(r[i])==="list";)m.push(r[i].trimEnd()),i++;n.push({type:"list",items:m.length,markdown:m.join(`
141
141
  `)});continue}let c=[];for(;i<r.length&&On(r[i])==="paragraph";)c.push(r[i].trim()),i++;let f=c.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(`
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 pl(e,t,r={}){let n=Br(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 rr=["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 Ot(e,t){let r=rr.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=rr.indexOf(i.nodeName);if((a===-1?999:a)>n){e.insertBefore(t,i),o=!0;break}}o||e.appendChild(t)}function gl(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 u=[];for(let c of Array.from(t.childNodes))l.has(c.nodeName)&&u.push(c);for(let c of u)t.removeChild(c)}if(o){let u=C(e,"w:b");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u);let c=C(e,"w:bCs");c.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,c)}if(i){let u=C(e,"w:i");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u);let c=C(e,"w:iCs");c.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,c)}if(a){let u=C(e,"w:u");u.setAttribute("w:val",n==="add"?"single":"none"),Ot(t,u)}if(s){let u=C(e,"w:strike");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u)}}function mi(e,t,r){gl(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=Fr(r,!1)),r.nodeName==="w:i"&&(t.italic=Fr(r,!1)),r.nodeName==="w:u"&&(t.underline=Fr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Fr(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 Fr(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 di="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function je(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===di&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function hl(e){return!e||e.nodeType!==1||e.namespaceURI!==di?!1:e.localName==="del"||e.localName==="moveFrom"}function pi(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||hl(n))continue;if(je(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 ke(e){let t=new Set(["comment","footnote","endnote"]);return le(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 gi(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],i=pi(o);for(let a of i){let s=ae(a,"w:rPr");Array.from(a.childNodes||[]).forEach(l=>{if(je(l,"t")){let u=l.textContent||"";u.length>0&&(t.push({charStart:r,charEnd:r+u.length,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=u.length)}else(je(l,"br")||je(l,"cr")||je(l,"tab")||je(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=1)})}r=mt(r,n,e.length)}return{textSpans:t,charOffset:r}}function wl(e,t,r,n,o,i=null){let a=null;for(let u of Array.from(e.childNodes))if(je(u,"rPr")){a=u;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 u of Array.from(e.childNodes))if(je(u,"t")){let c=u.textContent||"";if(c.length>0){let f=l,m=l+c.length;n.push({charStart:f,charEnd:m,textElement:u,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 hi(e){let t=[],r=[],n=0,o=ke(e);for(let i=0;i<o.length;i++){let a=o[i],s=null;for(let c of Array.from(a.childNodes))if(je(c,"pPr")){for(let f of Array.from(c.childNodes))if(je(f,"rPr")){s=f;break}break}let l=qe(s);l.hasFormatting&&k(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let u=pi(a);for(let c of u)n=wl(c,a,n,r,t,l);n=mt(n,i,o.length)}return k(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}function gt(e,t,r,n,o=null){let i=C(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 wi(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function bl(e,t){let r=wi(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=C(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function xl(e,t){let r=wi(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=C(e,"w:rPr"),t.appendChild(r)),r}function bi(e,t,r,n,o=null){let i=bl(e,t),a=xl(e,i);for(let u of Array.from(a.childNodes||[]))u.nodeType===1&&(u.localName==="ins"||u.localName==="del"||u.nodeName==="w:ins"||u.nodeName==="w:del")&&a.removeChild(u);let s=C(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 xi(e,t,r,n=null){return bi(e,t,r,"ins",n)}function nr(e,t,r,n=null){return bi(e,t,r,"del",n)}function at(e,t,r,n){let o=C(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Ni(e,o,t),o;let i=C(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function $r(e,t,r,n,o,i,a){if(!t)return[];let s=new Set([0,t.length]);for(let c of n){let f=Math.max(0,c.start-o),m=Math.min(t.length,c.end-o);f>=0&&f<t.length&&s.add(f),m>0&&m<=t.length&&s.add(m)}let l=Array.from(s).sort((c,f)=>c-f),u=[];for(let c=0;c<l.length-1;c++){let f=l[c],m=l[c+1],d=t.slice(f,m);if(!d)continue;let p=o+f,b=o+m,h=n.filter(x=>x.start<=p&&x.end>=b),g={...qe(r)};h.forEach(x=>{x.format&&Object.assign(g,x.format)});let w=h.length>0?kt(e,r,g,i,a):r?.cloneNode(!0)||null;u.push(kn(e,d,w,!1))}return u}function kn(e,t,r,n){let o=C(e,"w:r");if(r&&o.appendChild(r),!n)return Ni(e,o,t),o;let i=C(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function Ni(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let i of o){if(!i)continue;if(i===" "){t.appendChild(C(e,"w:tab"));continue}if(i===`
144
- `){t.appendChild(C(e,"w:br"));continue}if(i==="\u2011"){t.appendChild(C(e,"w:noBreakHyphen"));continue}let a=C(e,"w:t");/^\s|\s$/.test(i)&&a.setAttribute("xml:space","preserve"),a.textContent=i,t.appendChild(a)}}function kt(e,t,r,n,o){let i=C(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&&Nl(e,i,n,t);let s=(l,u,c=null,f="0")=>{let m=C(e,l);u?c&&m.setAttribute("w:val",c):f&&m.setAttribute("w:val",f);let d=rr.indexOf(l),p=d===-1?999:d,b=!1;for(let h of Array.from(i.childNodes)){if(h.nodeType!==1)continue;let g=rr.indexOf(h.nodeName);if((g===-1?999:g)>p){i.insertBefore(m,h),b=!0;break}}b||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 Mn(e,t,r,n,o){let i=C(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 s=C(e,"w:rPr");Array.from((o||t).childNodes).forEach(c=>{c.nodeName!=="w:rPrChange"&&s.appendChild(c.cloneNode(!0))}),i.appendChild(s);let u=ae(t,"w:rPrChange");return u&&t.removeChild(u),t.appendChild(i),i}function Nl(e,t,r,n){Mn(e,t,r,null,n||t)}var vl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Mt(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===vl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Xr(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),u=yl(l),c=_n(u),f=c.trim();o.push({paragraph:a,spans:l,text:u,normalizedText:c,normalizedTrim:f,startOffset:i}),i+=c.length,i=mt(i,s,t.length)}),o}function vi(e,t){if(!t)return null;let r=_n(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 yi(e,t){let r=_n(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 u=l.startOffset,c=l.normalizedText.length;if(s>=u&&s<=u+c){o=l,i=s-u;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 Ti(e){let t=e;for(;t;){if(Mt(t,"p"))return t;t=t.parentNode}return null}function yl(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Mt(n,"t")?t+=r.textElement.textContent||"":Mt(n,"tab")?t+=" ":Mt(n,"br")||Mt(n,"cr")?t+=`
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 hl(e,t,r={}){let n=Br(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 rr=["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 Ot(e,t){let r=rr.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=rr.indexOf(i.nodeName);if((a===-1?999:a)>n){e.insertBefore(t,i),o=!0;break}}o||e.appendChild(t)}function wl(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 u=[];for(let c of Array.from(t.childNodes))l.has(c.nodeName)&&u.push(c);for(let c of u)t.removeChild(c)}if(o){let u=C(e,"w:b");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u);let c=C(e,"w:bCs");c.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,c)}if(i){let u=C(e,"w:i");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u);let c=C(e,"w:iCs");c.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,c)}if(a){let u=C(e,"w:u");u.setAttribute("w:val",n==="add"?"single":"none"),Ot(t,u)}if(s){let u=C(e,"w:strike");u.setAttribute("w:val",n==="add"?"1":"0"),Ot(t,u)}}function pi(e,t,r){wl(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=Fr(r,!1)),r.nodeName==="w:i"&&(t.italic=Fr(r,!1)),r.nodeName==="w:u"&&(t.underline=Fr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Fr(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 Fr(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 gi="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function je(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===gi&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function bl(e){return!e||e.nodeType!==1||e.namespaceURI!==gi?!1:e.localName==="del"||e.localName==="moveFrom"}function hi(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||bl(n))continue;if(je(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 ke(e){let t=new Set(["comment","footnote","endnote"]);return le(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 wi(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],i=hi(o);for(let a of i){let s=ae(a,"w:rPr");Array.from(a.childNodes||[]).forEach(l=>{if(je(l,"t")){let u=l.textContent||"";u.length>0&&(t.push({charStart:r,charEnd:r+u.length,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=u.length)}else(je(l,"br")||je(l,"cr")||je(l,"tab")||je(l,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:l,runElement:a,paragraph:o,container:a.parentNode,rPr:s}),r+=1)})}r=mt(r,n,e.length)}return{textSpans:t,charOffset:r}}function xl(e,t,r,n,o,i=null){let a=null;for(let u of Array.from(e.childNodes))if(je(u,"rPr")){a=u;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 u of Array.from(e.childNodes))if(je(u,"t")){let c=u.textContent||"";if(c.length>0){let f=l,m=l+c.length;n.push({charStart:f,charEnd:m,textElement:u,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 bi(e){let t=[],r=[],n=0,o=ke(e);for(let i=0;i<o.length;i++){let a=o[i],s=null;for(let c of Array.from(a.childNodes))if(je(c,"pPr")){for(let f of Array.from(c.childNodes))if(je(f,"rPr")){s=f;break}break}let l=qe(s);l.hasFormatting&&k(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(l)}`);let u=hi(a);for(let c of u)n=xl(c,a,n,r,t,l);n=mt(n,i,o.length)}return k(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}function gt(e,t,r,n,o=null){let i=C(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 xi(e,t){return Array.from(e?.childNodes||[]).find(r=>r.nodeType===1&&(r.localName===t||r.nodeName===`w:${t}`))||null}function Nl(e,t){let r=xi(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=C(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function vl(e,t){let r=xi(t,"rPr");return r?t.lastChild!==r&&t.appendChild(r):(r=C(e,"w:rPr"),t.appendChild(r)),r}function Ni(e,t,r,n,o=null){let i=Nl(e,t),a=vl(e,i);for(let u of Array.from(a.childNodes||[]))u.nodeType===1&&(u.localName==="ins"||u.localName==="del"||u.nodeName==="w:ins"||u.nodeName==="w:del")&&a.removeChild(u);let s=C(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 vi(e,t,r,n=null){return Ni(e,t,r,"ins",n)}function nr(e,t,r,n=null){return Ni(e,t,r,"del",n)}function at(e,t,r,n){let o=C(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return yi(e,o,t),o;let i=C(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function $r(e,t,r,n,o,i,a){if(!t)return[];let s=new Set([0,t.length]);for(let c of n){let f=Math.max(0,c.start-o),m=Math.min(t.length,c.end-o);f>=0&&f<t.length&&s.add(f),m>0&&m<=t.length&&s.add(m)}let l=Array.from(s).sort((c,f)=>c-f),u=[];for(let c=0;c<l.length-1;c++){let f=l[c],m=l[c+1],d=t.slice(f,m);if(!d)continue;let p=o+f,b=o+m,h=n.filter(x=>x.start<=p&&x.end>=b),g={...qe(r)};h.forEach(x=>{x.format&&Object.assign(g,x.format)});let w=h.length>0?kt(e,r,g,i,a):r?.cloneNode(!0)||null;u.push(kn(e,d,w,!1))}return u}function kn(e,t,r,n){let o=C(e,"w:r");if(r&&o.appendChild(r),!n)return yi(e,o,t),o;let i=C(e,n?"w:delText":"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=t,o.appendChild(i),o}function yi(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let i of o){if(!i)continue;if(i===" "){t.appendChild(C(e,"w:tab"));continue}if(i===`
144
+ `){t.appendChild(C(e,"w:br"));continue}if(i==="\u2011"){t.appendChild(C(e,"w:noBreakHyphen"));continue}let a=C(e,"w:t");/^\s|\s$/.test(i)&&a.setAttribute("xml:space","preserve"),a.textContent=i,t.appendChild(a)}}function kt(e,t,r,n,o){let i=C(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&&yl(e,i,n,t);let s=(l,u,c=null,f="0")=>{let m=C(e,l);u?c&&m.setAttribute("w:val",c):f&&m.setAttribute("w:val",f);let d=rr.indexOf(l),p=d===-1?999:d,b=!1;for(let h of Array.from(i.childNodes)){if(h.nodeType!==1)continue;let g=rr.indexOf(h.nodeName);if((g===-1?999:g)>p){i.insertBefore(m,h),b=!0;break}}b||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 Mn(e,t,r,n,o){let i=C(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 s=C(e,"w:rPr");Array.from((o||t).childNodes).forEach(c=>{c.nodeName!=="w:rPrChange"&&s.appendChild(c.cloneNode(!0))}),i.appendChild(s);let u=ae(t,"w:rPrChange");return u&&t.removeChild(u),t.appendChild(i),i}function yl(e,t,r,n){Mn(e,t,r,null,n||t)}var Tl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Mt(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Tl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Xr(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),u=Sl(l),c=_n(u),f=c.trim();o.push({paragraph:a,spans:l,text:u,normalizedText:c,normalizedTrim:f,startOffset:i}),i+=c.length,i=mt(i,s,t.length)}),o}function Ti(e,t){if(!t)return null;let r=_n(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 Si(e,t){let r=_n(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 u=l.startOffset,c=l.normalizedText.length;if(s>=u&&s<=u+c){o=l,i=s-u;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 Ei(e){let t=e;for(;t;){if(Mt(t,"p"))return t;t=t.parentNode}return null}function Sl(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;Mt(n,"t")?t+=r.textElement.textContent||"":Mt(n,"tab")?t+=" ":Mt(n,"br")||Mt(n,"cr")?t+=`
146
146
  `:Mt(n,"noBreakHyphen")&&(t+="\u2011")}return t}function _n(e){return e?e.replace(/\r/g,`
147
- `).replace(/\u00a0/g," "):""}function Si(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 u=n[a],c=Tl(e,l,u);if(!c){a++;continue}i.push(c[0]),l=c[1],a++}i.push(l)}return i}function Tl(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 u=at(e,s,t.rPr,!1),c=at(e,l,t.rPr,!1);o.insertBefore(u,n),o.insertBefore(c,n),o.removeChild(n);let f=u.getElementsByTagName("w:t")[0],m=c.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:u},{...t,charStart:r,textElement:m,runElement:c}]}var Sl="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function El(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Sl&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Il(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 Ei(e,t,r,n,o,i=!0){let a=!1,s=new Set;k(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let l of r){let u=l.run;if(s.has(u)||(s.add(u),!u.parentNode))continue;k("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let c=ae(u,"w:rPr");c||(c=C(e,"w:rPr"),u.insertBefore(c,u.firstChild)),i&&Mn(e,c,o||me()),mi(e,c,l.format),a=!0}return a?(k("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(k("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function Al(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 c=Si(e,t,l).slice().sort((m,d)=>m.charStart-d.charStart||m.charEnd-d.charEnd),f=Pl(r);for(let m of c){if(!m||!m.textElement||!El(m.textElement,"t"))continue;let d=f(m.charStart,m.charEnd);if(d.length===0)continue;let p=hn(...d.map(B=>B.format)),b={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=m.format||qe(m.rPr),g={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(B=>b[B]!==g[B])||s.has(m.runElement)||(s.add(m.runElement),!(m.textElement.textContent||""))||!m.runElement.parentNode)continue;let y=m.runElement,v=ae(y,"w:rPr"),E=kt(e,v,b,o||me(),i),P=v;if(!P)y.insertBefore(E,y.firstChild);else{for(;P.firstChild;)P.removeChild(P.firstChild);Array.from(E.childNodes).forEach(B=>P.appendChild(B))}a=!0}return{oxml:n.serializeToString(e),hasChanges:a}}function Ii(e,t,r,n,o,i=!0,a=null){let s=Il(a),l=s.paragraphs||ke(e),u=s.textSpans||[];if(s.textSpans||({textSpans:u}=gi(l)),!u||u.length===0)return Le("[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 c=s.paragraphInfos||Xr(e,l,u),{targetInfo:f,matchOffset:m}=yi(c,t);if(!f||!f.spans||f.spans.length===0)return Le("[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(h=>({...h,charStart:h.charStart-d,charEnd:h.charEnd-d})),b=r.map(h=>({...h,start:h.start+m,end:h.end+m}));return Al(e,p,b,n,o,i)}function Pl(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 Dr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function ht(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let i=Dr(o);if(n==="accepted"&&(i==="del"||i==="moveFrom")||n==="rejected"&&(i==="ins"||i==="moveTo"))return!1;o=o.parentNode}return!0}function wt(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!ht(e,n,r))return"";let o="",i=a=>{for(let s of Array.from(a?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==S||!ht(s,n,r))continue;let l=Dr(s);l==="t"||l==="delText"&&r==="rejected"?o+=s.textContent||"":l==="tab"?o+=" ":l==="br"||l==="cr"?o+=`
147
+ `).replace(/\u00a0/g," "):""}function Ii(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 u=n[a],c=El(e,l,u);if(!c){a++;continue}i.push(c[0]),l=c[1],a++}i.push(l)}return i}function El(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 u=at(e,s,t.rPr,!1),c=at(e,l,t.rPr,!1);o.insertBefore(u,n),o.insertBefore(c,n),o.removeChild(n);let f=u.getElementsByTagName("w:t")[0],m=c.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:f,runElement:u},{...t,charStart:r,textElement:m,runElement:c}]}var Il="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Al(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Il&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Pl(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 Ai(e,t,r,n,o,i=!0){let a=!1,s=new Set;k(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let l of r){let u=l.run;if(s.has(u)||(s.add(u),!u.parentNode))continue;k("[OxmlEngine] Processing run for surgical format removal, format:",l.format);let c=ae(u,"w:rPr");c||(c=C(e,"w:rPr"),u.insertBefore(c,u.firstChild)),i&&Mn(e,c,o||de()),pi(e,c,l.format),a=!0}return a?(k("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(k("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function Rl(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 c=Ii(e,t,l).slice().sort((m,d)=>m.charStart-d.charStart||m.charEnd-d.charEnd),f=Cl(r);for(let m of c){if(!m||!m.textElement||!Al(m.textElement,"t"))continue;let d=f(m.charStart,m.charEnd);if(d.length===0)continue;let p=hn(...d.map(B=>B.format)),b={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=m.format||qe(m.rPr),g={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(B=>b[B]!==g[B])||s.has(m.runElement)||(s.add(m.runElement),!(m.textElement.textContent||""))||!m.runElement.parentNode)continue;let y=m.runElement,v=ae(y,"w:rPr"),I=kt(e,v,b,o||de(),i),P=v;if(!P)y.insertBefore(I,y.firstChild);else{for(;P.firstChild;)P.removeChild(P.firstChild);Array.from(I.childNodes).forEach(B=>P.appendChild(B))}a=!0}return{oxml:n.serializeToString(e),hasChanges:a}}function Pi(e,t,r,n,o,i=!0,a=null){let s=Pl(a),l=s.paragraphs||ke(e),u=s.textSpans||[];if(s.textSpans||({textSpans:u}=wi(l)),!u||u.length===0)return Le("[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 c=s.paragraphInfos||Xr(e,l,u),{targetInfo:f,matchOffset:m}=Si(c,t);if(!f||!f.spans||f.spans.length===0)return Le("[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(h=>({...h,charStart:h.charStart-d,charEnd:h.charEnd-d})),b=r.map(h=>({...h,start:h.start+m,end:h.end+m}));return Rl(e,p,b,n,o,i)}function Cl(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 Dr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function ht(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let i=Dr(o);if(n==="accepted"&&(i==="del"||i==="moveFrom")||n==="rejected"&&(i==="ins"||i==="moveTo"))return!1;o=o.parentNode}return!0}function wt(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!ht(e,n,r))return"";let o="",i=a=>{for(let s of Array.from(a?.childNodes||[])){if(s?.nodeType!==1||s.namespaceURI&&s.namespaceURI!==S||!ht(s,n,r))continue;let l=Dr(s);l==="t"||l==="delText"&&r==="rejected"?o+=s.textContent||"":l==="tab"?o+=" ":l==="br"||l==="cr"?o+=`
148
148
  `:l==="noBreakHyphen"?o+="\u2011":l==="softHyphen"?o+="\xAD":i(s)}};return i(e),o}var st=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function zr(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!==S)continue;let b=Dr(p);if(b==="pPr"||b==="rPr")continue;let h=m;b==="ins"?h={kind:"insertion",author:st(p,"author")||void 0,revisionId:st(p,"id")||void 0}:b==="del"?h={kind:"deletion",author:st(p,"author")||void 0,revisionId:st(p,"id")||void 0}:b==="moveFrom"?h={kind:"move_from",author:st(p,"author")||void 0,revisionId:st(p,"id")||void 0}:b==="moveTo"&&(h={kind:"move_to",author:st(p,"author")||void 0,revisionId:st(p,"id")||void 0});let g=d;b==="r"&&(g=p);let w=null,x=h?h.kind:"baseline",N=h?.author,T=h?.revisionId;b==="t"?w=p.textContent||"":b==="delText"?(w=p.textContent||"",h||(x="deletion")):b==="tab"?w=" ":b==="br"||b==="cr"?w=`
149
- `:b==="noBreakHyphen"?w="\u2011":b==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:x,author:N,revisionId:T,carrier:g||p,carrierContainer:(g||p)?.parentNode||null}):n(p,h,g)}}let o=Dr(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,b=s.carrier===f.carrier,h=i&&s.carrierContainer===f.carrierContainer;m&&d&&p&&(b||h)?s.text+=f.text:(a.push(s),s={...f})}s&&a.push(s);let l=0,u=0,c=[];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,b=d?u:null;m&&(l+=f.text.length),d&&(u+=f.text.length);let h={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:b};f.author!==void 0&&(h.author=f.author),f.revisionId!==void 0&&(h.revisionId=f.revisionId),c.push(h)}return c}function Te(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=zr(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 Rl="http://schemas.microsoft.com/office/word/2010/wordml";function Ai(e,t,r={}){let{targetParagraphId:n=null}=r,o=Ne(e,S,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let a=ke(e).filter(l=>{let u=l.parentNode;for(;u;){if(I(u,"tc"))return!0;u=u.parentNode}return!1});k(`[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(u=>{let c=Ol(u);return c&&c.toUpperCase()===l})||null,s?k(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):k(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let l=t.trim();if(!s){for(let u of a)if(Te(u).trim()===l){s=u,k(`[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 or(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 k(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),k(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),Cl(o)}function Cl(e){return ei(e)}function Ol(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Rl,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Ln(e){return I(e,"t")?e.textContent||"":I(e,"br")||I(e,"cr")?`
150
- `:I(e,"tab")?" ":I(e,"noBreakHyphen")?"\u2011":I(e,"softHyphen")?"\xAD":""}function Bn(e){return I(e,"t")||I(e,"br")||I(e,"cr")||I(e,"tab")||I(e,"noBreakHyphen")||I(e,"softHyphen")}function Pi(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+=ir(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+=ir(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+=ir(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+=ir(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+=ir(s,n,i,t.length,r).text);t=It(t,o,e.length)}),{fullText:t,textSpans:r}}function ir(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 u=l.textContent||"";if(u.length===0)continue;o.push({charStart:a,charEnd:a+u.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=u.length,s.push(u)}else if(Bn(l)){let u=Ln(l);o.push({charStart:a,charEnd:a+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=1,s.push(u)}return{text:s.join("")}}function Ri(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 ar(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=Dn(e.ends,t);for(;o<e.spans.length;){let i=e.spans[o];if(i.charStart>=r)break;n(i),o++}}function Fn(e,t){if(e.spans.length===0)return null;let r=Dn(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function $n(e,t){let r=kl(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Xn(e,t){let r=Dn(e.ends,t)-1;return r>=0?e.spans[r]:null}function Dn(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 kl(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 Ci(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=Fn(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,i=$n(e,t)||(t>0?Xn(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}}function lt(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof he?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(S,"w:id",a):i.setAttribute("w:id",a)}return e}var Ml=new Set(["ins"]);function _t(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(I(n,"rPr")||!Bn(n))continue;let o=Ln(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function He(e){return e.length===0?0:e[e.length-1].end}function Ve(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 u=s-a.start,c=l-a.start,f=a.text.slice(u,c);i.push(Bl(e,a.node,f,o))}),i}function sr(e,t,r){let n=C(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function bt(e,t,r,n,o){if(n.length===0)return null;let i=sr(e,n,o);return t.insertBefore(i,r),i}function ki(e,t,r,n=null){let o=Ll(t);if(!Ml.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins 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")?He(_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),u=0;for(let m of i){if(!I(m,"r")){(u<=r?s:l).appendChild(m.cloneNode(!0));continue}let d=_t(m),p=He(d),b=u+p;if(b<=r)s.appendChild(m.cloneNode(!0));else if(u>=r)l.appendChild(m.cloneNode(!0));else{let h=r-u,g=Array.from(m.childNodes||[]).find(T=>I(T,"rPr"))||null,w=Ve(e,d,0,h,!1),x=Ve(e,d,h,p,!1);s.appendChild(sr(e,w,g));let N=sr(e,x,g);lt(N,Oi(e,n)),l.appendChild(N)}u=b}let c=Oi(e,n),f=c.next();return _l(l,"id",String(f)),c._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function Oi(e,t){return t instanceof he?t:Ye(e)||nt(e)}function _l(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(S,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function Ll(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Bl(e,t,r,n){if(n){let i=C(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"))return t.cloneNode(!0);let o=C(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function _i(e,t,r,n,o,i,a){if(o.length===0)return!1;let s=t.rPr,l=qe(s),u={...l};if(o.forEach(y=>Object.assign(u,y.format)),!["bold","italic","underline","strikethrough"].some(y=>!!u[y]!==l[y]))return!1;let m=t.runElement.parentNode;if(!m)return!1;let d=t.textElement.textContent||"",p=t.charStart,b=r-p,h=n-p,g=d.substring(0,b),w=d.substring(b,h),x=d.substring(h);if(g.length>0){let y=at(e,g,s,!1);m.insertBefore(y,t.runElement)}let N=kt(e,s,u,i,a),T=kn(e,w,N,!1);if(m.insertBefore(T,t.runElement),x.length>0){let y=at(e,x,s,!1);m.insertBefore(y,t.runElement)}return m.removeChild(t.runElement),!0}function Li(e,t,r,n,o,i,a=null){let s=[];if(ar(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 u=[];l.forEach((d,p)=>{let b=p.parentNode;if(!b)return;let h=_t(p);if(h.length===0)return;let g=1/0,w=-1/0;d.forEach(x=>{let N=h.find(v=>v.node===x.textElement);if(!N)return;let T=Math.max(0,r-x.charStart),y=Math.min(x.charEnd-x.charStart,n-x.charStart);y<=T||(g=Math.min(g,N.start+T),w=Math.max(w,N.start+y))}),!(!Number.isFinite(g)||w<=g)&&u.push({runElement:p,parent:b,rPr:d[0].rPr,beforePieces:Ve(e,h,0,g,!1),deletedPieces:Ve(e,h,g,w,!0),afterPieces:Ve(e,h,w,He(h),!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(b,"ins")?Bi(t,b):null})});let c=[];for(let d of u){let p=c[c.length-1],b=p?.[p.length-1];b&&b.parent===d.parent&&$l(b.runElement)===d.runElement?p.push(d):c.push([d])}let f=!1,m=!1;for(let d of c){let p=d[0],b=null;if(i&&d.some(w=>w.deletedPieces.length>0)){let w=a?m?{...a,id:ie(o,e,"del").id}:a:null;m=!0,b=gt(e,"del",null,o,w)}for(let w of d){let{parent:x,runElement:N}=w;bt(e,x,N,w.beforePieces,w.rPr),b&&w===p&&x.insertBefore(b,N),b&&w.deletedPieces.length>0&&b.appendChild(sr(e,w.deletedPieces,w.rPr)),bt(e,x,N,w.afterPieces,w.rPr),x.removeChild(N),f=!0}let h=I(p.parent,"ins")?p.parent:null,g=Math.max(...d.map(w=>w.globalEnd));if(h&&g===n){let w=p.carrierGlobalStart,x=d.filter(T=>T.globalStart<n).reduce((T,y)=>T+y.deletedPieces.reduce((v,E)=>v+(E.textContent||"").length,0),0),N=Math.max(0,n-w-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:N,rPr:p.rPr})}}return f}function Un(e,t,r,n,o,i=[],a=0,s=!0,l=null,u=null,c=null,f="merge-same-author"){let m=t.revisionInsertionAnchors?.get(r)||null;if(m&&f==="slice-cross-author"&&Xl(m.carrier)&&Wn(m.carrier,o))return t.revisionInsertionAnchors.delete(r),zn(e,m.carrier,m.splitOffset,n,m.rPr,o,i,a,s,u);if(!c){let N=Fn(t,r);if(!N&&r>0&&(N=$n(t,r)),!N&&r>0&&(N=Xn(t,r)),!N&&t.spans.length>0&&(N=t.spans[t.spans.length-1]),!N)return l?(xt(e,l,null,n,null,o,i,a,s,u),!0):!1;let T=N.runElement.parentNode;if(!T)return l?(xt(e,l,null,n,N.rPr,o,i,a,s,u),!0):!1;if(s&&f==="slice-cross-author"&&Wn(T,o))return zn(e,T,Mi(t,T,r),n,N.rPr,o,i,a,s,u);let y=_t(N.runElement),v=y.find(B=>B.node===N.textElement),E=v?v.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:He(y);if(E>0&&E<He(y)){let B=Ve(e,y,0,E,!1),L=Ve(e,y,E,He(y),!1);return bt(e,T,N.runElement,B,N.rPr),xt(e,T,N.runElement,n,N.rPr,o,i,a,s,u),bt(e,T,N.runElement,L,N.rPr),T.removeChild(N.runElement),!0}let P=r<=N.charStart?N.runElement:N.runElement.nextSibling;return xt(e,T,P,n,N.rPr,o,i,a,s,u),!0}let d=Ci(t,r,l),p=d.leftSpan&&I(d.leftSpan.runElement?.parentNode,"hyperlink"),b=d.rightSpan&&I(d.rightSpan.runElement?.parentNode,"hyperlink"),h=d.containingSpan&&I(d.containingSpan.runElement?.parentNode,"hyperlink");if(c.hyperlink==="outside"){if(d.isInterior&&h)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(c.hyperlink==="inside"&&!p&&!b&&!h)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let g=null;if(c.formatting==="none"?g=null:c.formatting==="right"?g=d.rightSpan?.rPr||null:c.formatting==="left"?g=d.leftSpan?.rPr||null:g=(d.containingSpan||d.leftSpan||d.rightSpan)?.rPr||null,d.isInterior){let N=d.containingSpan,T=N.runElement.parentNode||l;if(!T)return!1;let y=_t(N.runElement),v=y.find(P=>P.node===N.textElement),E=v?v.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:He(y);if(E>0&&E<He(y)){let P=Ve(e,y,0,E,!1),B=Ve(e,y,E,He(y),!1);return bt(e,T,N.runElement,P,N.rPr),xt(e,T,N.runElement,n,g,o,i,a,s,u),bt(e,T,N.runElement,B,N.rPr),T.removeChild(N.runElement),!0}}let w=null,x=null;if(c.hyperlink==="outside"){if(b){let N=d.rightSpan.runElement.parentNode;w=N.parentNode||l,x=N}else if(p){let N=d.leftSpan.runElement.parentNode;w=N.parentNode||l,x=N.nextSibling}}else c.hyperlink==="inside"&&(b?(w=d.rightSpan.runElement.parentNode,x=d.rightSpan.runElement):p&&(w=d.leftSpan.runElement.parentNode,x=d.leftSpan.runElement.nextSibling));if(w||(d.rightSpan?(w=d.rightSpan.runElement.parentNode||l,x=d.rightSpan.runElement):d.leftSpan?(w=d.leftSpan.runElement.parentNode||l,x=d.leftSpan.runElement.nextSibling):(w=l,x=null)),c.bookmark&&w&&(c.bookmark==="outside"?(x&&I(x.previousSibling,"bookmarkStart")&&(x=x.previousSibling),d.leftSpan&&I(d.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=d.leftSpan.runElement.nextSibling.nextSibling)):c.bookmark==="inside"&&(x&&I(x,"bookmarkStart")&&(x=x.nextSibling),d.leftSpan&&I(d.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=d.leftSpan.runElement.nextSibling))),c.comment&&w)if(c.comment==="outside"){if(x&&I(x.previousSibling,"commentRangeStart")&&(x=x.previousSibling),d.leftSpan&&I(d.leftSpan.runElement.nextSibling,"commentRangeEnd")){let N=d.leftSpan.runElement.nextSibling.nextSibling;N&&(I(N,"commentReference")||I(N,"r"))&&Array.from(N.childNodes||[]).some(y=>I(y,"commentReference"))&&(N=N.nextSibling),x=N}}else c.comment==="inside"&&(x&&I(x,"commentRangeStart")&&(x=x.nextSibling),d.leftSpan&&I(d.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(x=d.leftSpan.runElement.nextSibling));if(s&&c.revision==="coalesce_same_author"){let N=null,T=null;if(d.leftSpan&&I(d.leftSpan.runElement.parentNode,"ins")){let y=d.leftSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(S,"author"))===o&&(N=y,T=d.leftSpan.runElement.nextSibling)}else if(d.rightSpan&&I(d.rightSpan.runElement.parentNode,"ins")){let y=d.rightSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(S,"author"))===o&&(N=y,T=d.rightSpan.runElement)}if(N){let y=at(e,n,g,!1);return N.insertBefore(y,T),!0}}return s&&f==="slice-cross-author"&&Wn(w,o)?zn(e,w,Mi(t,w,r),n,g,o,i,a,s,u):(xt(e,w,x,n,g,o,i,a,s,u),!0)}function zn(e,t,r,n,o,i,a,s,l,u){let c=t.parentNode;if(!c)return!1;let{leftCarrier:f,rightCarrier:m}=ki(e,t,r);return f&&c.insertBefore(f,t),xt(e,c,t,n,Fl(o),i,a,s,l,u),m&&c.insertBefore(m,t),c.removeChild(t),!0}function Fl(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 Mi(e,t,r){let n=Bi(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 Bi(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 Wn(e,t){return I(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(S,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function $l(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Xl(e){return!!e?.parentNode}function xt(e,t,r,n,o,i,a,s,l,u=null){let c=Ke(a,s,s+n.length);if(c.length===0){let m=at(e,n,o,!1);if(l){let d=gt(e,"ins",m,i,u);t.insertBefore(d,r)}else t.insertBefore(m,r);return}let f=$r(e,n,o,c,s,i,l);if(l){let m=gt(e,"ins",null,i,u);f.forEach(d=>m.appendChild(d)),t.insertBefore(m,r)}else f.forEach(m=>t.insertBefore(m,r))}function Dl(e,t,r,n=!1){let o=[];if(ar(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 u=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 b of Array.from(p.childNodes||[]))if(b.nodeType===1){let h=b.localName||b.nodeName.replace(/^.*:/,"");if(u.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let c=o[o.length-1].runElement,f=i;for(;f&&f!==c;){if(f!==i){let d=f.localName||f.nodeName.replace(/^.*:/,"");if(u.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(u.has(p)||p==="fldChar")return!0;for(let b of Array.from(d.childNodes||[]))if(b.nodeType===1&&m(b))return!0;return!1}return m(i.previousSibling)||m(c.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Fi(e,t,r,n,o,i,a=!0,s=null,l={},u={}){let c=s?[s]:ke(e),{fullText:f,textSpans:m}=Pi(c),d=er(f,r,l),p=Ri(m),b=u.pairReplacements===!0,h=[],g=0,w=0,x=!1;for(let N=0;N<d.length;N++){let[T,y]=d[N];if(T===0){let v=y.length,E=g,P=g+v;ar(p,E,P,B=>{let L=Math.max(B.charStart,E),z=Math.min(B.charEnd,P),j=z-L,O=L-E,H=w+O,R=H+j,_=Ke(i,H,R);_i(e,B,L,z,_,o,a)&&(x=!0)}),g+=v,w+=v}else if(T===-1){let v=N+1<d.length&&d[N+1][0]===1,E=!1,P=null,B=null;if(b&&a&&v&&d[N+1][1].replace(/\n/g," ").trim().length>0){let j=Dl(p,g,g+y.length,u?.existingRevisions==="slice-cross-author");if(j.safe){let O=Pr(o,e);P={id:O.deletionId,author:O.author,date:O.date},B={id:O.insertionId,author:O.author,date:O.date},E=!0}else j.structuralBoundary&&h.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(Li(e,p,g,g+y.length,o,a,P)&&(x=!0),g+=y.length,E){N++;let[,L]=d[N],z=L.replace(/\n/g," ");if(z.trim().length>0){let j=Un(e,p,g,z,o,i,w,a,c[0]||null,B,u?.insertionAffinity||null,u?.existingRevisions||"merge-same-author");if(j&&typeof j=="object"&&j.error)return de({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:j.error});j===!0&&(x=!0)}w+=L.length}}else if(T===1){let v=y.replace(/\n/g," ");if(v.trim().length>0){let E=Un(e,p,g,v,o,i,w,a,c[0]||null,null,u?.insertionAffinity||null,u?.existingRevisions||"merge-same-author");if(E&&typeof E=="object"&&E.error)return de({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:E.error});E===!0&&(x=!0)}w+=y.length}}return de({oxml:n.serializeToString(e),hasChanges:x,...h.length>0?{warnings:[...new Set(h)]}:{}})}var Xi=So(En(),1);var Di=new Xi.diff_match_patch;function zi(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function zl(e,t){return e?.getAttributeNS?.(S,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function $i(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 Wl(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 Wi(e,t,r=null){let n=e.documentElement,o=I(n,"body")||zi(n)==="package",i=r||ke(e),a=ve(e,S,"body");!a&&o&&(a=n);let s="",l=[],u=[],c=[],f=new Map,m=new Map,d=new Set,p={nextCharCode:57344},b=new Set;i.forEach((L,z)=>{let j=s.length;Array.from(L.childNodes).forEach(_=>{s=Gl(_,s,l,c,f,m,p,d)}),s=It(s,z,i.length);let O=s.length,H=ve(L,S,"pPr"),R=L.parentNode;R&&b.add(R),u.push({start:j,end:O,pPr:H,container:R||a})});let h="";for(let L=0;L<s.length;L++){let z=s[L];h+=d.has(z)?`
152
- `:z}let g=Hl(h,t,c);g=jl(h,s,g,d),m.forEach((L,z)=>{let j=z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");g=g.replace(new RegExp(j,"g"),L)}),g=Vl(s,g,f);let w=new Map;b.forEach(L=>{w.set(L,e.createDocumentFragment())}),a&&!w.has(a)&&w.set(a,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let x=new Map,N=new Set(u.map(L=>L.start)),T=$i(u),y=$i(l),v=Wl(c);return{paragraphs:i,body:a||e,paragraphMap:u,paragraphStarts:N,propertyMap:l,sentinelMap:c,sentinelMapByStart:v,referenceMap:f,tokenToCharMap:m,containerFragments:w,replacementContainers:x,originalFullText:s,processedModifiedText:g,getParagraphInfo:L=>{let z=T.at(L);return z||(u.length>0?u[u.length-1]:{start:0,end:0,pPr:null,container:a||e})},getRunProperties:L=>{let z=y.at(L);return z?{rPr:z.rPr,wrapper:z.wrapper}:{rPr:null}},getPropertySpanLength:(L,z)=>{let j=y.at(L);return j?Math.min(j.end-L,z):1},isParagraphStart:L=>N.has(L)}}function Ui(e,t){let r=ke(e);if(r.length===0)return[];let n=ji(t),o=r.map(Ul);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 u="";for(let c=l;c<r.length;c++)if(u+=(c===l?"":`
153
- `)+o[c],a(u)===s)return r.slice(l,c+1)}}return null}function ji(e){return String(e??"").replace(/\r\n?/g,`
154
- `).replace(/\u00a0/g," ")}function Ul(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+=`
155
- `:I(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),ji(t)}function jl(e,t,r,n){if(n.size===0)return r;let o=Di.diff_main(e,r),i=0,a="";for(let[s,l]of o)if(s===0){for(let u=0;u<l.length;u++){let c=t[i+u];a+=n.has(c)?c:l[u]}i+=l.length}else s===-1?i+=l.length:a+=l;return a}function Hl(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=Di.diff_main(o,t),l=0,u="",c=(f,m)=>{let d=a.get(f)||[];for(let p of d)p.emitted||m&&p.affinity!==m||(u+=p.char,p.emitted=!0)};for(let[f,m]of s){if(f===1){c(l,"left"),u+=m;continue}for(let d=0;d<m.length;d++)c(l),f===0&&(u+=m[d]),l++}return c(l),u}function Vl(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 Gl(e,t,r,n,o,i,a,s){return I(e,"r")?Kl(e,t,r,n,o,i,a,s):I(e,"hyperlink")?Yl(e,t,r):I(e,"sdt")||I(e,"oMath")||zi(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 Kl(e,t,r,n,o,i,a,s){let l=t,u=ve(e,S,"rPr");return Array.from(e.childNodes).forEach(c=>{if(I(c,"t")){let f=c.textContent||"";f.length>0&&(r.push({start:l.length,end:l.length+f.length,rPr:u}),l+=f)}else if(I(c,"br")||I(c,"cr")){let f=String.fromCharCode(a.nextCharCode++);o.set(f,c),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:u})}else if(I(c,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:u});else if(I(c,"noBreakHyphen"))l+="\u2011",r.push({start:l.length-1,end:l.length,rPr:u});else if(["drawing","pict","object","fldChar","instrText","sym"].some(f=>I(c,f))){let f=ve(c,S,"txbxContent"),m=I(c,"pict")&&!!f,d=I(c,"fldChar")||I(c,"instrText"),p=I(c,"fldChar")?c.getAttributeNS?.(S,"fldCharType")||c.getAttribute("w:fldCharType")||c.getAttribute("fldCharType"):null;n.push({start:l.length,node:c,wrapInRun:!0,rPr:u,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:u})}else if(I(c,"footnoteReference")||I(c,"endnoteReference")){let f=zl(c,"id");if(f){let d=`{{__${I(c,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(a.nextCharCode++);o.set(p,c),i.set(d,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:u})}}else I(c,"commentReference")&&n.push({start:l.length,node:c,isCommentMarker:!0})}),l}function Yl(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!I(o,"r"))return;let i=ve(o,S,"rPr");Ne(o,S,"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 Vi(e,t,r,n,o,i,a=!0,s={}){let{paragraphs:l,containerFragments:u,sentinelMapByStart:c,referenceMap:f,replacementContainers:m,getParagraphInfo:d,getRunProperties:p,getPropertySpanLength:b,isParagraphStart:h}=r,g=R=>{let _=C(e,"w:p");if(R){let $=R.cloneNode(!0),Z=ve($,S,"sectPr");Z&&$.removeChild(Z),_.appendChild($)}return _},w=d(0),x=g(w.pPr),N=u.get(w.container);N&&N.appendChild(x);let T=0,y=0,v=s?.pairReplacements===!0,E=null,P=null,B=new WeakSet;for(let R=0;R<t.length;R++){let[_,$]=t[R];if(_===0||_===-1){let Z=_===0?"equal":"delete";if(_===0)E=null,P=null;else if(E===null){E=T;let Q=!1;for(let ee=R+1;ee<t.length;ee++){if(t[ee][0]===1){Q=!0;break}if(t[ee][0]===0)break}v&&a&&Q&&(P=Pr(o,e))}let G=0;for(;G<$.length;){let Q=T+G,ee=p(Q),We=b(Q,$.length-G),yr=$.substring(G,G+We);x=Hi(e,yr,Z,ee.rPr,ee.wrapper,Q,x,u,c,f,m,d,g,o,i,y,a,B,P).currentParagraph,_===0&&(y+=We),G+=We}T+=$.length;continue}if(_===1){let Z=E!==null?E:T>0&&!h(T)?T-1:T,G=p(Z);x=Hi(e,$,"insert",G.rPr,G.wrapper,T,x,u,c,f,m,d,g,o,i,y,a,B,P,E!==null).currentParagraph,y+=$.length,E=null,P=null}}a&&u.forEach(R=>{Array.from(R.childNodes).forEach(_=>{if(I(_,"p")){let $=Array.from(_.getElementsByTagNameNS(S,"t")).length>0,Z=Array.from(_.getElementsByTagNameNS(S,"delText")).length>0;l.length===1&&!$&&(Z||r.originalFullText.trim()!=="")&&nr(e,_,o)}})}),u.forEach(R=>{let _=Array.from(R.childNodes).filter($=>I($,"p"));if(_.length>1){let $=_[0],Z=_[_.length-1],G=ve($,S,"pPr"),Q=G?ve(G,S,"sectPr"):null;if(Q){G.removeChild(Q);let ee=ve(Z,S,"pPr");ee||(ee=C(e,"w:pPr"),Z.insertBefore(ee,Z.firstChild||null)),ee.appendChild(Q)}}});let L=new Set(l),z=new Map;l.forEach(R=>{let _=R.parentNode;if(!_||z.has(_))return;let $=R.nextSibling;for(;$&&L.has($);)$=$.nextSibling;z.set(_,$)}),l.forEach(R=>{R.parentNode&&R.parentNode.removeChild(R)});let j=!1,O="";return u.forEach((R,_)=>{let $=m.get(_),Z=$||_;if(Z.nodeType===9){j=!0,R.childNodes.length===1?Z.appendChild(R.firstChild):O=Array.from(R.childNodes).map(Q=>n.serializeToString(Q)).join("");return}let G=$?null:z.get(_);G&&G.parentNode===Z?Z.insertBefore(R,G):Z.appendChild(R)}),{oxml:j&&O?O:n.serializeToString(e),hasChanges:!0}}function Hi(e,t,r,n,o,i,a,s,l,u,c,f,m,d,p=[],b=0,h=!0,g=new WeakSet,w=null,x=!1){let N=i,T=b,y=a,v=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(P=>{let B=l.get(N)||[],L=B.filter(O=>O.isCommentMarker&&!g.has(O.node)),z=x?new Set(L.filter(O=>I(O.node,"commentRangeEnd")).map(O=>O.node.getAttributeNS?.(S,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id"))):new Set;if(L.forEach(O=>{g.add(O.node);let H=O.node.getAttributeNS?.(S,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id");if(x&&z.has(H)&&(I(O.node,"commentRangeEnd")||I(O.node,"commentReference"))){v.push(O.node);return}if(I(O.node,"commentReference")){let R=C(e,"w:r");R.appendChild(O.node.cloneNode(!0)),y.appendChild(R)}else y.appendChild(O.node.cloneNode(!0))}),P===`
156
- `){let O=f(N+1),H=m(O.pPr);h&&r==="insert"?xi(e,y,d):h&&r==="delete"&&nr(e,y,d);let R=s.get(O.container);R&&(R.appendChild(H),y=H),N++,r!=="delete"&&T++;return}if(P==="\uFFFC"){let O=B.find(H=>!H.isCommentMarker)||B[0];if(O){let H=O.node.cloneNode(!0);if(O.isTextBox&&O.originalContainer){let R=ve(H,S,"txbxContent");if(R){for(;R.firstChild;)R.removeChild(R.firstChild);c.set(O.originalContainer,R)}}if(O.wrapInRun){let R=C(e,"w:r");O.rPr&&R.appendChild(O.rPr.cloneNode(!0)),R.appendChild(H),y.appendChild(R)}else y.appendChild(H)}N++,r!=="delete"&&T++;return}if(u.has(P)){if(r!=="delete"){let O=u.get(P);if(O){let H=O.cloneNode(!0),R=C(e,"w:r");n&&R.appendChild(n.cloneNode(!0)),R.appendChild(H),y.appendChild(R)}}N++,r!=="delete"&&T++;return}if(P.length===0)return;let j=y;if(o){let O=o.cloneNode(!1);j=O,y.appendChild(O)}if(r==="delete"){let O=C(e,"w:r");n&&O.appendChild(n.cloneNode(!0));let H=C(e,"w:delText");if(H.setAttribute("xml:space","preserve"),H.textContent=P,O.appendChild(H),h){let R=null;if(w){let $=w.usedDeletionId?ie(d,e,"del").id:w.deletionId;w.usedDeletionId=!0,R={id:$,author:w.author,date:w.date}}let _=gt(e,"del",O,d,R);j.appendChild(_)}}else{let O=Ke(p,T,T+P.length),H=$r(e,P,n,O,T,d,h);if(r==="insert"&&h){let R=null;if(w){let $=w.usedInsertionId?ie(d,e,"ins").id:w.insertionId;w.usedInsertionId=!0,R={id:$,author:w.author,date:w.date}}let _=gt(e,"ins",null,d,R);H.forEach($=>_.appendChild($)),j.appendChild(_)}else H.forEach(R=>j.appendChild(R))}r!=="delete"&&(T+=P.length),N+=P.length}),v.forEach(P=>{if(I(P,"commentReference")){let B=C(e,"w:r");B.appendChild(P.cloneNode(!0)),y.appendChild(B)}else y.appendChild(P.cloneNode(!0))}),{currentParagraph:y}}function jn(e,t,r,n,o,i,a=!0,s={},l={}){let u=Ui(e,t);if(u===null)return de({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 c=Wi(e,r,u);if(c.paragraphs.length===0)return de({oxml:n.serializeToString(e),hasChanges:!1});let f=er(c.originalFullText,c.processedModifiedText,s);return de(Vi(e,f,c,n,o,i,a,l))}function Xe(e,t){return de({oxml:e.serializeToString(t),hasChanges:!1})}function Gi(e,t,r,n,o,i=!0){let a=Ne(e,S,"tbl"),s=$e(t),l=s.rows.length>0||s.headers.length>0;if(a.length===0||!l)return Xe(r,e);let u=a[0],c=Sn(u),f=ni(c,s);if(f.length===0)return Xe(r,e);let m={generateRedlines:i,author:o,revisionIdAllocator:Ye(e)},d=oi(c,f,m),p=`<root xmlns:w="${S}">${d}</root>`,b=W(p,"application/xml").doc;if(!b)return Xe(r,e);let h=ne(b);if(h)return te("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),Xe(r,e);let g=ve(b,S,"tbl");if(!g)return te("[OxmlEngine] No table found in reconciled OOXML"),Xe(r,e);let w=e.importNode(g,!0);return u.parentNode.replaceChild(w,u),de({oxml:r.serializeToString(e),hasChanges:!0})}function Ki(e,t,r,n,o,i){let a=Ye(e),s=$e(t);if(!s||s.rows.length===0&&s.headers.length===0)return k("[OxmlEngine] Failed to parse table data from Markdown"),Xe(r,e);let l=pt(s,{generateRedlines:i,author:o,revisionIdAllocator:a}),u=W(`<root xmlns:w="${S}">${l}</root>`,"application/xml").doc;if(!u)return Xe(r,e);let c=ne(u);if(c)return te("[OxmlEngine] Failed to parse generated table OOXML:",c.textContent),Xe(r,e);let f=re(u,S,"tbl");if(f||(f=re(u,S,"ins")),!f)return te("[OxmlEngine] No table element found in generated OOXML"),Xe(r,e);let m=e,d=le(m,S,"p");if(d.length===0)return k("[OxmlEngine] No paragraphs found to replace"),Xe(r,m);let p=d[0],b=p.parentNode;if(b&&b.nodeType===9){let g=W(`<w:document xmlns:w="${S}"><w:body/></w:document>`,"application/xml").doc;if(!g)return Xe(r,m);let w=re(g,S,"body");d.forEach(x=>w.appendChild(g.importNode(x,!0))),m=g,Ir(m,a),d=le(m,S,"p"),p=d[0],b=p.parentNode}let h=m.importNode(f,!0);return i?d.forEach(g=>{nr(m,g,o),le(g,S,"r").forEach(x=>{le(x,S,"t").forEach(v=>{let E=v.textContent||"";if(E.trim()){let P=C(m,"w:delText");P.textContent=E,v.parentNode.replaceChild(P,v)}});let T=C(m,"w:del"),y=ie(o,m,"del");T.setAttribute("w:id",String(y.id)),T.setAttribute("w:author",y.author),T.setAttribute("w:date",y.date),x.parentNode.insertBefore(T,x),T.appendChild(x)})}):d.slice(1).forEach(g=>g.parentNode.removeChild(g)),b.insertBefore(h,p),i||b.removeChild(p),k("[OxmlEngine] Text-to-table transformation complete"),de({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 Wr(e){return typeof e=="string"?e.trim().toLowerCase():""}function Jl(e){return!!e&&e.nodeType===1}function De(e,t){return Jl(e)&&e.namespaceURI===S&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function be(e,t){return Array.from(e.getElementsByTagNameNS(S,t))}function Hn(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Wr(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 Pe(e,t){if(t.allAuthors)return!0;let r=Wr(Ze(e,"author"));return!!r&&r===t.normalizedAuthor}function Vn(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=W(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let a=`<w:body xmlns:w="${S}">${r}</w:body>`,s=W(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:fe(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function ue(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Ur(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function Yi(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Ji(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(`
157
- `)}function ql(e){let t=0,r=be(e,"ins");for(let n of r){if(!n.parentNode||Hr(n))continue;let o=Yi(n);for(;De(o,"ins")&&Wr(Ze(o,"author"))===Wr(Ze(n,"author"))&&Ji(o)===Ji(n);){let i=Yi(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=i}}return t}function jr(e){let t=e?.parentNode;return De(t,"trPr")&&De(t?.parentNode,"tr")}function Hr(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return De(t,"rPr")&&De(r,"pPr")&&De(n,"p")}function Qi(e){return Hr(e)?e.parentNode.parentNode.parentNode:null}function Zl(e){let t=e?.nextSibling||null;for(;t;){if(De(t,"p"))return t;t=t.nextSibling}return null}function ea(e){if(!e?.parentNode)return!1;let t=Zl(e);if(!t)return De(e.parentNode,"tc")&&be(e.parentNode,"p").length<=1?!1:ue(e);let r=Array.from(e.childNodes||[]).filter(o=>!De(o,"pPr")),n=t.firstChild||null;De(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return ue(e)}function Gn(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=Vn(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 c of be(i,"ins"))if(!(!c.parentNode||!Pe(c,n))){if(Hr(c)){ue(c)&&(s+=1);continue}if(jr(c)){ue(c)&&(s+=1);continue}Ur(c)&&(s+=1)}for(let c of be(i,"del")){if(!c.parentNode||!Pe(c,n))continue;let f=Qi(c);if(f){ea(f)&&(s+=1);continue}if(jr(c)){let m=c.parentNode?.parentNode;ue(m)&&(s+=1);continue}ue(c)&&(s+=1)}for(let c of be(i,"moveFrom"))!c.parentNode||!Pe(c,n)||ue(c)&&(s+=1);for(let c of be(i,"moveTo"))!c.parentNode||!Pe(c,n)||Ur(c)&&(s+=1);s+=ta(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let c of l)for(let f of be(i,c))!f.parentNode||!Pe(f,n)||ue(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(c=>a.serializeToString(c)).join(""):a.serializeToString(i),hasChanges:s>0,acceptedCount:s,warnings:r}}function qi(e,t){for(let r of Array.from(t.getElementsByTagNameNS(S,"delText"))){let n=C(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 Ql(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!==S)return ue(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===S&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return ue(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=ec(r.ownerDocument,a);r.appendChild(s)}return!0}function ec(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function Zi(e,t,r){let n=new Set;for(let o of be(e,t)){if(!Pe(o,r))continue;let i=Ze(o,"id");i&&n.add(i)}return n}function ta(e,t){let r=0,n=Zi(e,"moveFromRangeStart",t),o=Zi(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 u of be(e,a)){if(!u.parentNode)continue;let c=Ze(u,"id");c&&(t.allAuthors||s.has(c)||l&&Pe(u,t))&&ue(u)&&(r+=1)}return r}function Kn(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=Vn(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 c of be(i,"ins")){if(!c.parentNode||!Pe(c,n))continue;let f=Qi(c);if(f){ea(f)&&(s+=1);continue}if(jr(c)){let m=c.parentNode?.parentNode;ue(m)&&(s+=1);continue}ue(c)&&(s+=1)}for(let c of be(i,"del"))if(!(!c.parentNode||!Pe(c,n))){if(Hr(c)){ue(c)&&(s+=1);continue}if(jr(c)){ue(c)&&(s+=1);continue}qi(i,c),Ur(c)&&(s+=1)}for(let c of be(i,"moveFrom"))!c.parentNode||!Pe(c,n)||(qi(i,c),Ur(c)&&(s+=1));for(let c of be(i,"moveTo"))!c.parentNode||!Pe(c,n)||ue(c)&&(s+=1);s+=ta(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let c of l)for(let f of be(i,c))!f.parentNode||!Pe(f,n)||Ql(f,c)&&(s+=1);return ql(i),{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(c=>a.serializeToString(c)).join(""):a.serializeToString(i),hasChanges:s>0,rejectedCount:s,warnings:r}}function tc(e,t){let r=new Set,n=be(e,"comment");for(let o of n){if(!Pe(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)||ue(n)&&(r+=1)}return r}function nc(e){return De(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!==S)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 be(e,o)){if(!i.parentNode)continue;let a=Ze(i,"id");if(!(!a||!t.has(a))){if(o==="commentReference"&&nc(i.parentNode)){ue(i.parentNode)&&(r+=1);continue}ue(i)&&(r+=1)}}return r}function ic(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=Vn(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}=tc(i,n);if(n.allAuthors)for(let f of["commentRangeStart","commentRangeEnd","commentReference"])for(let m of be(i,f)){let d=Ze(m,"id");d&&s.add(d)}let u=rc(l,s),c=oc(i,s);return{oxml:a.serializeToString(i),hasChanges:u>0||c>0,commentsRemoved:u,referencesRemoved:c,warnings:r}}var ac=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:ac[t]||null,...r}))}function sc(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Ne(e,S,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))}async function Yn(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||me(),l=fe(),u=[],c=[],f=!1,m=n.existingRevisions||"merge-same-author",d=m==="accept-all-first-keep-normalized",p=X=>{let M={...X};f&&M.hasChanges===!1&&M.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Previous revisions by the same author were reverted to baseline."]):d?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Existing revisions were accepted before redlining."]):M.oxml=o);let J=[...u,...c,...Array.isArray(M.warnings)?M.warnings:[]];return J.length>0&&(M.warnings=[...new Set(J)]),M.status||(M.status=M.hasChanges?"ok":"no-op"),de(M)},b=()=>p(f&&d?{oxml:i,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),h=W(o,"text/xml");u=h.warnings;let g=h.doc,w=g?ne(g):null;if(h.error||w){let X=h.error?.message||w?.textContent||"Could not parse OOXML input.";return te("[OxmlEngine] XML parse error:",X),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:X}})}let x=n?._revisionIdAllocator instanceof he?n._revisionIdAllocator:new he;if(Et(g,x),Lr(g))if(m==="merge-same-author"||m==="slice-cross-author"){let X=Rn(g),M=String(s||"").trim().toLowerCase();if(X.length>0&&X.every(se=>se.trim().toLowerCase()===M)){let se=sc(g);if(se.length>0)return p({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:se}});k("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let ye=Kn(o,{author:s});if(ye.status==="error")return p(ye);i=ye.oxml,f=!0;let Ht=W(i,"text/xml");u.push(...Ht.warnings),g=Ht.doc;let vo=g?ne(g):null;if(Ht.error||vo){let Tr=Ht.error?.message||vo?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return te("[OxmlEngine] XML parse error after rejecting same-author revisions:",Tr),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Tr}})}if(Lr(g))return p({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."}});Et(g,x);let yo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:ke(g);t=yo.length>0?yo.map(Tr=>Te(Tr)).join(`
158
- `):""}else{if(m==="merge-same-author")return k("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${X.length?X.join(", "):"unattributed"}). Pass existingRevisions: "accept-all-first" or resolve revisions first.`}});if(["moveFrom","moveTo"].some(ye=>Ne(g,S,ye).length>0))return p({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});k("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){k("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let X=Gn(o,{allAuthors:!0});if(X.status==="error")return p(X);i=X.oxml,f=!0;let M=W(i,"text/xml");u.push(...M.warnings),g=M.doc;let J=g?ne(g):null;if(M.error||J){let se=M.error?.message||J?.textContent||"Could not parse OOXML after accepting existing revisions.";return te("[OxmlEngine] XML parse error after accepting existing revisions:",se),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:se}})}Et(g,x)}else return k("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let N=Ai(g,t,n);if(N.hasTableWrapper&&N.targetParagraph&&!n._isolatedTableCell){k("[OxmlEngine] Isolating table-cell paragraph before diff");let X=or(g,N.targetParagraph,l),M=await Yn(X,t,r,{...n,_isolatedTableCell:!0});return!M.hasChanges&&M.status==="no-op"?b():M}let T=n.sanitizeInput===!0?Jn(r):r;T!==r&&c.push("Input was sanitized; pass sanitizeInput: false to disable.");let y=null;if(n.structuredContent!==!1)if(y=Br(T),y.valid)y.requiresStructuredContent&&(T=y.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let X=y.issues.map(M=>`${M.code}: ${M.message}`).join(" ");return p({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:X},warnings:y.issues.map(M=>M.message)})}y=null}let{cleanText:v,formatHints:E}=Ie(T),P=v.trim()!==t.trim(),B=E.length>0,{existingFormatHints:L,textSpans:z,paragraphs:j}=hi(g),O=L.length>0,H=z.map(X=>ra(X)).join(""),R=t.includes(`
159
- `)||t.includes("\r")?t.split(/\r?\n/).map(Vr).filter(Boolean).every(X=>j.some(M=>{let J=z.filter(se=>se.paragraph===M).map(ra).join("");return Vr(J).includes(X)})):H.includes(t.trim())||H.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Vr(H).includes(Vr(t));if(P&&typeof t=="string"&&t.trim()&&!R)return k("[OxmlEngine] Target text not found in OOXML"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let _=null,$=()=>(_||(_=Xr(g,j,z)),_),Z=(X=null)=>{let M=Ii(g,t,E,l,s,a,X);return M.useNativeApi?(k("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),jn(g,t,v,l,s,E,a)):M};k(`[OxmlEngine] Text changes: ${P}, New format hints: ${E.length}, Existing format hints: ${L.length}`);let G=n.removeFormatting===!0&&!P&&!B&&O;if(!P&&!B&&!O)return Qe(n,"noChange"),k("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),b();if(!P&&!B&&O&&!G)return k("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),b();if(G){Qe(n,"formatOnly",{removeFormatting:!0}),k("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let X=N,M=X.targetParagraph||null;if(!M){let ye=vi($(),t);ye&&(M=ye.paragraph)}let J=L;M&&(J=L.filter(ye=>Ti(ye.run)===M));let se=Ei(g,z,J,l,s,a);return X.hasTableWrapper&&M?p({oxml:or(g,M,l),hasChanges:se.hasChanges}):p(se)}if(!P&&B){Qe(n,"formatOnly",{removeFormatting:!1}),k(`[OxmlEngine] Format-only change detected: ${E.length} format hints`);let X=N,M={textSpans:z,paragraphs:j,paragraphInfos:$()};if(X.hasTableWrapper&&X.targetParagraph){k("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let J=Z(M);return k("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),p({oxml:or(g,X.targetParagraph,l),hasChanges:J.hasChanges})}return p(Z(M))}let ee=Ne(g,S,"tbl").length>0,We=/^\|.+\|/.test(v.trim())&&v.includes(`
160
- `),yr=Kt(v),xo=n.structuredContent!==!1&&y?.requiresStructuredContent===!0,ft=N,No=ee||m==="slice-cross-author";k(`[OxmlEngine] Mode: ${No?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${E.length}, isMarkdownTable: ${We}, isTargetList: ${yr}, isTableCellParagraph: ${ft.isTableCellParagraph}`);try{if(We&&!ee)return Qe(n,"table",{transformation:"text-to-table"}),k("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),p(Ki(g,v,l,null,s,a));if(ee&&We)return Qe(n,"table",{transformation:"table-reconciliation"}),p(Gi(g,v,l,null,s,a));if(No){Qe(n,"surgical",{tableScoped:ee});let X=ft.hasTableWrapper&&ft.targetParagraph?ft.targetParagraph:null;X&&k("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let M=Fi(g,t,v,l,s,E,a,X,{},n);return ft.hasTableWrapper&&M.hasChanges&&ft.targetParagraph?(k("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),p({oxml:or(g,ft.targetParagraph,l),hasChanges:!0})):p(M)}if(yr||xo){let X=Ne(g,S,"p"),M=X.length===1;Qe(n,M?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:X.length}),k(`[OxmlEngine] \u{1F3AF} Using ${M?"direct list generation":"compatibility pipeline"} for list reconciliation`);let J;if(M){let se=Pt(i,{xmlDoc:g}),ye=Qt(X[0]);J=await Ct({cleanText:v,numberingContext:ye,originalRunModel:se.runModel,originalText:se.acceptedText,generateRedlines:a,author:s,font:n.font||null,revisionIdAllocator:x,numberingService:new Je})}else J=await new tr({author:s,generateRedlines:a,revisionIdAllocator:x}).execute(i,T,{xmlDoc:g});if(J.error?.code==="DIFF_TOKEN_LIMIT")return p({oxml:o,hasChanges:!1,status:"error",error:J.error});if(J.isValid&&J.ooxml&&J.ooxml!==i){let se=J.includeNumbering===!0;k(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${se}`);let ye=it(J.ooxml,{includeNumbering:se,numberingXml:J.numberingXml});return k(`[OxmlEngine] \u2705 Wrapped OOXML length: ${ye.length}`),p({oxml:ye,hasChanges:!0,...Array.isArray(J.warnings)?{warnings:J.warnings}:{}})}return b()}return Qe(n,"reconstruction"),p(jn(g,t,v,l,s,E,a,{},n))}catch(X){if(Ho(X))return p({oxml:o,hasChanges:!1,status:"error",error:{code:X.code,message:X.message}});throw X}}function Vr(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function ra(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
161
- `:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function Jn(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 W(e,"application/xml").doc}function Nt(e){return oe(e)}function Gr(e){return Array.from(e||[])}function lr(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Re(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Ce="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function na(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Gr(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Gr(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Gr(e.getElementsByTagName(t))}function ce(e){return e?Te(e):""}function Se(e){if(!e)return[];let t=na(e,"body"),r=t.length>0?t[0]:e;return na(r,"p")}function vt(e){return e&&Gr(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Lt(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:Te(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:Se(e.ownerDocument||e).indexOf(e)+1,i=t.paragraphId===void 0?vt(e):t.paragraphId,a=typeof t.inTable=="boolean"?t.inTable:cr(e),l=`${i||""}${o}${a?"table":"body"}${r==="rejected"?"rejected":""}${n}`,u=2166136261;for(let c=0;c<l.length;c++)u^=l.charCodeAt(c),u=Math.imul(u,16777619)>>>0;return`fnv1a32:${u.toString(16).padStart(8,"0")}`}function oa(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=Se(e),o=[],i=new Map,a=new Map,s=new Map;for(let l=0;l<n.length;l++){let u=n[l],c=Te(u,{revisionView:r}),f=vt(u),m=cr(u),d=U(c),p=Object.freeze({paragraph:u,index:l+1,paragraphId:f,text:c,normalizedText:d,revisionView:r,fingerprint:Lt(u,{text:c,index:l+1,paragraphId:f,inTable:m,revisionView:r}),inTable:m});o.push(p),i.set(u,p),f&&!a.has(f)&&a.set(f,p),d&&(s.has(d)||s.set(d,[]),s.get(d).push(p))}for(let[l,u]of s)s.set(l,Object.freeze(u));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:i,byId:a,byNormalizedText:s})}function U(e){return String(e||"").replace(/\s+/g," ").trim()}function Qn(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
162
- `)}function eo(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 lc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function cc(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 ia(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:Se(e)[t-1]||null}function Bt(e,t,r=Ce){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Kr(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,i=o?null:Se(e),a=String(t||"").trim();if(!a)return null;let s=o?o.find(u=>u.text.trim()===a)?.paragraph:i.find(u=>ce(u).trim()===a);if(s)return s;let l=U(a);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:i.find(u=>U(ce(u))===l)||null}function qn(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,i=o?.entries||null,a=i?null:Se(e),s=String(t||"").trim();if(!s)return null;let l=Kr(e,s,{paragraphMetadataIndex:o});if(l)return l;let u=U(s),c=i?i.find(h=>h.normalizedText.length>10&&u.startsWith(h.normalizedText))?.paragraph||null:a.find(h=>{let g=U(ce(h));return g.length>10&&u.startsWith(g)});if(c)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ce(c).trim().slice(0,60)}..."`),c;let f=i?i.find(h=>h.normalizedText.length>15&&u.includes(h.normalizedText))?.paragraph||null:a.find(h=>{let g=U(ce(h));return g.length>15&&u.includes(g)});if(f)return n(`[Fuzzy] Contains match: "${ce(f).trim().slice(0,60)}..."`),f;let m=0,d=null,p=new Set(u.toLowerCase().split(/\s+/).filter(h=>h.length>2)),b=i?.length??a.length;for(let h=0;h<b;h++){let g=i?.[h]?.paragraph??a[h],w=(i?.[h]?.text??ce(g)).trim();if(!w)continue;let T=U(w).toLowerCase().split(/\s+/).filter(y=>y.length>2).filter(y=>p.has(y)).length/Math.max(p.size,1);T>m&&T>.5&&(m=T,d=g)}return d?(n(`[Fuzzy] Best word-overlap match (${(m*100).toFixed(0)}%): "${ce(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=eo(i?.index??i?.paragraphIndex??t.targetRef),u=t.strictAmbiguity===!0,c=t.paragraphMetadataIndex||null;if(c&&c.revisionView!==a?c=t.metadataIndices?.[a]||oa(e,{revisionView:a}):c||(c=oa(e,{revisionView:a})),i?.paragraphId){let m=fc(e,i.paragraphId,c);if(!m)throw Re("TARGET_NOT_FOUND",`Target paragraphId not found: "${i.paragraphId}".`);let d=c?.byParagraph?.get(m)||null,p=d?.index??Se(e).indexOf(m)+1,b=d?.fingerprint||Lt(m,{revisionView:a}),h=d?.inTable??cr(m),g=d?.normalizedText||U(Te(m,{revisionView:a}));if(l!=null&&l!==p)throw Re("TARGET_INDEX_MISMATCH",`Target paragraphId "${i.paragraphId}" (index ${p}) does not match requested index ${l}.`,d?[Ge(d)]:null);if(i.fingerprint&&i.fingerprint!==b)throw Re("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.`,d?[Ge(d)]:null);if(typeof i.inTable=="boolean"&&i.inTable!==h)throw Re("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" does not match the requested table context.`,d?[Ge(d)]:null);if(s&&g!==U(s))throw Re("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.`,d?[Ge(d)]:null);if(i.occurrence!=null){let x=Yr(e,s||g,c),N=x.findIndex(T=>T.paragraph===m)+1;if(N===0||N!==i.occurrence)throw Re("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${N}, not requested occurrence ${i.occurrence}.`,x.map(Ge))}return{paragraph:m,resolvedBy:"paragraph_id"}}let f=[];if(s){let m=Yr(e,s,c);if(f=uc(m,i),i?.fingerprint&&m.length>0&&f.length===0)throw Re("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",m.map(Ge));if(typeof i?.inTable=="boolean"&&m.length>0&&f.length===0)throw Re("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",m.map(Ge));if(i?.occurrence){let d=f[i.occurrence-1]||null;if(!d)throw Re("TARGET_NOT_FOUND",`Target occurrence ${i.occurrence} was not found.`,f.map(Ge));return{paragraph:d.paragraph,resolvedBy:"occurrence"}}if(u){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 Re("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(Ge));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Re("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(Ge));if(f.length===0)throw lr(`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=ia(e,l,c);if(m){let d=c?.byParagraph?.get(m)||null;if(i?.fingerprint&&i.fingerprint!==d?.fingerprint)throw Re("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof i?.inTable=="boolean"&&i.inTable!==d?.inTable)throw Re("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=Kr(e,s,{paragraphMetadataIndex:c}),b=(d?.text||Te(m,{revisionView:a})).trim(),h=U(b),g=U(s),w=h!==g;if(w&&p&&p!==m)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let x=qn(e,s,{onInfo:r,paragraphMetadataIndex:c});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&&!u){let m=Kr(e,s,{paragraphMetadataIndex:c});if(m){let p=f.length;if(p>1){let b=`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(b),{paragraph:m,resolvedBy:"strict_text",warnings:[b]}}return{paragraph:m,resolvedBy:"strict_text"}}let d=qn(e,s,{onInfo:r,paragraphMetadataIndex:c});if(d)return{paragraph:d,resolvedBy:"fuzzy_text"}}throw lr(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function cr(e){return!!Bt(e,"tbl")}function Yr(e,t,r=null){let n=U(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=Se(e),s=[];for(let l=0;l<a.length;l++){let u=a[l],c=Te(u,{revisionView:i}).trim();c&&U(c)===n&&s.push({paragraph:u,index:l+1,inTable:cr(u),paragraphId:vt(u),fingerprint:Lt(u,{text:c,index:l+1,revisionView:i}),text:c,revisionView:i})}return s}function Ge(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 fc(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Se(e).find(n=>vt(n)===t)||null:null}function mc(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 dc(e,t=null){let r=t?.entries||null,n=r?null:Se(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??ce(s)).trim();o.set(a+1,{text:l,normalizedText:r?.[a]?.normalizedText??U(l),inTable:r?.[a]?.inTable??cr(s)})}return o}function Zn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=aa(e,t),o=eo(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=U(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||U(ce(n.paragraph)))===l)return n;let c=[];if(a&&c.push(a),i.text){let m=U(i.text);m&&!c.some(d=>U(d)===m)&&c.push(i.text)}let f=null;for(let m of c){let d=Yr(e,m,t.paragraphMetadataIndex||null),p=mc(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 lr(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function pc(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=Zn(e,{targetRef:t,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!l)return null;let u=Zn(e,{targetRef:r,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!u)return null;let c=Array.from(e.getElementsByTagNameNS("*","p")),f=c.indexOf(l),m=c.indexOf(u);if(f<0||m<f)return null;let d=c.slice(f,m+1);if(d.length===0)return null;let p=d[0]?.parentNode||null;return!p||!d.every(b=>b&&b.parentNode===p)?null:d}function Jr(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Ce,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function sa(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Ce,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function ca(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Ue(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function ua(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=Jt(i,{indentSpaces:2});if(a){n=!0,r.push({kind:"list",markerType:a.markerType,level:a.level,marker:a.marker,outlineLevel:a.outlineLevel,text:ca(a.text)});continue}r.push({kind:"text",text:i.trim()})}return{items:r,hasListMarkers:n}}function la(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function ur(e,t){return U(e)===U(t)}function qr(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function gc(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 ur(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let i=n.level||0;return o.some(s=>(s.level||0)>i)?!1:ur(n.text,t)}return!1}function hc(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 wc(e,t,r,n){let o=e[0],i=e.slice(1).filter(a=>a.kind==="list");if(o?.kind==="text"&&ur(o.text,t)&&i.length>0){let a=i[0].level;return i.map(s=>({ilvl:qr(s,r,a),markerType:s.markerType||n,text:s.text}))}if(e.every(a=>a.kind==="list")){let a=e[0];if(!a||!ur(a.text,t))return null;let s=a.level;return e.slice(1).map(l=>({ilvl:qr(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=Jr(e,"pPr");if(!t)return null;let r=Jr(t,"numPr");if(!r)return null;let n=Jr(r,"numId");if(!n)return null;let o=sa(n);if(!o||o==="0")return null;let i=Jr(r,"ilvl"),a=sa(i),s=Number.parseInt(a||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function fa(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===Ce&&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 bc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
163
- `)||!tt(e))return null;let s=fa(e);if(!s||s.length===0)return null;let l=ua(i);if(!l.hasListMarkers||l.items.length<2)return null;let u=U(r.currentParagraphText||ce(e)),f=l.items.filter(v=>v.kind==="list")[0]?.markerType||"bullet",m=s.map(v=>({paragraph:v,list:tt(v),text:String(ce(v)||"").trim()})),d=s.indexOf(e);if(d<0)return null;let p=Math.min(...m.map(v=>v.list?.ilvl??0)),b=m.map(v=>la((v.list?.ilvl??0)-p,f,v.text)),h=null,g=l.items[0],w=l.items.slice(1).filter(v=>v.kind==="list");if(g?.kind==="text"&&ur(g.text,u)&&w.length>0){let v=Math.max(0,(m[d].list?.ilvl??0)-p),E=w[0].level;h=[{level:v,markerType:f,text:m[d].text},...w.map(P=>({level:qr(P,v,E),markerType:P.markerType||f,text:P.text}))]}else if(l.items.every(v=>v.kind==="list")){let v=Math.max(0,(m[d].list?.ilvl??0)-p),E=l.items[0].level;h=l.items.map(P=>({level:qr(P,v,E),markerType:P.markerType||f,text:P.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let x=h.map(v=>la(v.level,v.markerType,v.text)),N=b.slice(0,d).concat(x).concat(b.slice(d+1)),T=b.join(`
149
+ `:b==="noBreakHyphen"?w="\u2011":b==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:x,author:N,revisionId:T,carrier:g||p,carrierContainer:(g||p)?.parentNode||null}):n(p,h,g)}}let o=Dr(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,b=s.carrier===f.carrier,h=i&&s.carrierContainer===f.carrierContainer;m&&d&&p&&(b||h)?s.text+=f.text:(a.push(s),s={...f})}s&&a.push(s);let l=0,u=0,c=[];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,b=d?u:null;m&&(l+=f.text.length),d&&(u+=f.text.length);let h={text:f.text,kind:f.kind,acceptedStart:p,rejectedStart:b};f.author!==void 0&&(h.author=f.author),f.revisionId!==void 0&&(h.revisionId=f.revisionId),c.push(h)}return c}function be(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=zr(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 Ol="http://schemas.microsoft.com/office/word/2010/wordml";function Ri(e,t,r={}){let{targetParagraphId:n=null}=r,o=ve(e,S,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let a=ke(e).filter(l=>{let u=l.parentNode;for(;u;){if(E(u,"tc"))return!0;u=u.parentNode}return!1});k(`[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(u=>{let c=Ml(u);return c&&c.toUpperCase()===l})||null,s?k(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):k(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let l=t.trim();if(!s){for(let u of a)if(be(u).trim()===l){s=u,k(`[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 or(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 k(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),k(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),kl(o)}function kl(e){return ri(e)}function Ml(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(Ol,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function Ln(e){return E(e,"t")?e.textContent||"":E(e,"br")||E(e,"cr")?`
150
+ `:E(e,"tab")?" ":E(e,"noBreakHyphen")?"\u2011":E(e,"softHyphen")?"\xAD":""}function Bn(e){return E(e,"t")||E(e,"br")||E(e,"cr")||E(e,"tab")||E(e,"noBreakHyphen")||E(e,"softHyphen")}function Ci(e){let t="",r=[];return e.forEach((n,o)=>{let i=n.parentNode;for(let a=n.firstChild;a;a=a.nextSibling)if(E(a,"r"))t+=ir(a,n,i,t.length,r).text;else if(E(a,"hyperlink"))for(let s=a.firstChild;s;s=s.nextSibling)E(s,"r")&&(t+=ir(s,n,i,t.length,r).text);else if(E(a,"ins"))for(let s=a.firstChild;s;s=s.nextSibling)E(s,"r")&&(t+=ir(s,n,i,t.length,r).text);else if(E(a,"sdt")){let s=Array.from(a.childNodes||[]).find(l=>E(l,"sdtContent"));if(s)for(let l=s.firstChild;l;l=l.nextSibling)E(l,"r")&&(t+=ir(l,n,i,t.length,r).text)}else if(E(a,"smartTag"))for(let s=a.firstChild;s;s=s.nextSibling)E(s,"r")&&(t+=ir(s,n,i,t.length,r).text);t=It(t,o,e.length)}),{fullText:t,textSpans:r}}function ir(e,t,r,n,o){let i=ae(e,"w:rPr"),a=n,s=[];for(let l=e.firstChild;l;l=l.nextSibling)if(E(l,"t")){let u=l.textContent||"";if(u.length===0)continue;o.push({charStart:a,charEnd:a+u.length,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=u.length,s.push(u)}else if(Bn(l)){let u=Ln(l);o.push({charStart:a,charEnd:a+1,textElement:l,runElement:e,paragraph:t,container:r,rPr:i}),a+=1,s.push(u)}return{text:s.join("")}}function Oi(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 ar(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=Dn(e.ends,t);for(;o<e.spans.length;){let i=e.spans[o];if(i.charStart>=r)break;n(i),o++}}function Fn(e,t){if(e.spans.length===0)return null;let r=Dn(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function $n(e,t){let r=_l(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Xn(e,t){let r=Dn(e.ends,t)-1;return r>=0?e.spans[r]:null}function Dn(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 _l(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 ki(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=Fn(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,i=$n(e,t)||(t>0?Xn(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}}function lt(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof he?t:Ye(r)||nt(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let i of o){if(!E(i,"rPrChange"))continue;let a=String(n.next());typeof i.setAttributeNS=="function"?i.setAttributeNS(S,"w:id",a):i.setAttribute("w:id",a)}return e}var Ll=new Set(["ins"]);function _t(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(E(n,"rPr")||!Bn(n))continue;let o=Ln(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function He(e){return e.length===0?0:e[e.length-1].end}function Ve(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 u=s-a.start,c=l-a.start,f=a.text.slice(u,c);i.push($l(e,a.node,f,o))}),i}function sr(e,t,r){let n=C(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function bt(e,t,r,n,o){if(n.length===0)return null;let i=sr(e,n,o);return t.insertBefore(i,r),i}function _i(e,t,r,n=null){let o=Fl(t);if(!Ll.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins 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+(E(d,"r")?He(_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),u=0;for(let m of i){if(!E(m,"r")){(u<=r?s:l).appendChild(m.cloneNode(!0));continue}let d=_t(m),p=He(d),b=u+p;if(b<=r)s.appendChild(m.cloneNode(!0));else if(u>=r)l.appendChild(m.cloneNode(!0));else{let h=r-u,g=Array.from(m.childNodes||[]).find(T=>E(T,"rPr"))||null,w=Ve(e,d,0,h,!1),x=Ve(e,d,h,p,!1);s.appendChild(sr(e,w,g));let N=sr(e,x,g);lt(N,Mi(e,n)),l.appendChild(N)}u=b}let c=Mi(e,n),f=c.next();return Bl(l,"id",String(f)),c._receiptCollector?.recordRevision(f,o),{leftCarrier:s,rightCarrier:l}}function Mi(e,t){return t instanceof he?t:Ye(e)||nt(e)}function Bl(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(S,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function Fl(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function $l(e,t,r,n){if(n){let i=C(e,"w:delText");return i.setAttribute("xml:space","preserve"),i.textContent=r,i}if(E(t,"t")){let i=t.cloneNode(!1);return i.textContent=r,/^\s|\s$/.test(r)&&i.setAttribute("xml:space","preserve"),i}if(r===`
151
+ `&&(E(t,"br")||E(t,"cr"))||r===" "&&E(t,"tab")||r==="\u2011"&&E(t,"noBreakHyphen"))return t.cloneNode(!0);let o=C(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Bi(e,t,r,n,o,i,a){if(o.length===0)return!1;let s=t.rPr,l=qe(s),u={...l};if(o.forEach(y=>Object.assign(u,y.format)),!["bold","italic","underline","strikethrough"].some(y=>!!u[y]!==l[y]))return!1;let m=t.runElement.parentNode;if(!m)return!1;let d=t.textElement.textContent||"",p=t.charStart,b=r-p,h=n-p,g=d.substring(0,b),w=d.substring(b,h),x=d.substring(h);if(g.length>0){let y=at(e,g,s,!1);m.insertBefore(y,t.runElement)}let N=kt(e,s,u,i,a),T=kn(e,w,N,!1);if(m.insertBefore(T,t.runElement),x.length>0){let y=at(e,x,s,!1);m.insertBefore(y,t.runElement)}return m.removeChild(t.runElement),!0}function Fi(e,t,r,n,o,i,a=null){let s=[];if(ar(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 u=[];l.forEach((d,p)=>{let b=p.parentNode;if(!b)return;let h=_t(p);if(h.length===0)return;let g=1/0,w=-1/0;d.forEach(x=>{let N=h.find(v=>v.node===x.textElement);if(!N)return;let T=Math.max(0,r-x.charStart),y=Math.min(x.charEnd-x.charStart,n-x.charStart);y<=T||(g=Math.min(g,N.start+T),w=Math.max(w,N.start+y))}),!(!Number.isFinite(g)||w<=g)&&u.push({runElement:p,parent:b,rPr:d[0].rPr,beforePieces:Ve(e,h,0,g,!1),deletedPieces:Ve(e,h,g,w,!0),afterPieces:Ve(e,h,w,He(h),!1),globalStart:Math.max(r,Math.min(...d.map(x=>x.charStart))),globalEnd:Math.min(n,Math.max(...d.map(x=>x.charEnd))),carrierGlobalStart:E(b,"ins")?$i(t,b):null})});let c=[];for(let d of u){let p=c[c.length-1],b=p?.[p.length-1];b&&b.parent===d.parent&&zl(b.runElement)===d.runElement?p.push(d):c.push([d])}let f=!1,m=!1;for(let d of c){let p=d[0],b=null;if(i&&d.some(w=>w.deletedPieces.length>0)){let w=a?m?{...a,id:ie(o,e,"del").id}:a:null;m=!0,b=gt(e,"del",null,o,w)}for(let w of d){let{parent:x,runElement:N}=w;bt(e,x,N,w.beforePieces,w.rPr),b&&w===p&&x.insertBefore(b,N),b&&w.deletedPieces.length>0&&b.appendChild(sr(e,w.deletedPieces,w.rPr)),bt(e,x,N,w.afterPieces,w.rPr),x.removeChild(N),f=!0}let h=E(p.parent,"ins")?p.parent:null,g=Math.max(...d.map(w=>w.globalEnd));if(h&&g===n){let w=p.carrierGlobalStart,x=d.filter(T=>T.globalStart<n).reduce((T,y)=>T+y.deletedPieces.reduce((v,I)=>v+(I.textContent||"").length,0),0),N=Math.max(0,n-w-x);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:N,rPr:p.rPr})}}return f}function Un(e,t,r,n,o,i=[],a=0,s=!0,l=null,u=null,c=null,f="merge-same-author"){let m=t.revisionInsertionAnchors?.get(r)||null;if(m&&f==="slice-cross-author"&&Wl(m.carrier)&&Wn(m.carrier,o))return t.revisionInsertionAnchors.delete(r),zn(e,m.carrier,m.splitOffset,n,m.rPr,o,i,a,s,u);if(!c){let N=Fn(t,r);if(!N&&r>0&&(N=$n(t,r)),!N&&r>0&&(N=Xn(t,r)),!N&&t.spans.length>0&&(N=t.spans[t.spans.length-1]),!N)return l?(xt(e,l,null,n,null,o,i,a,s,u),!0):!1;let T=N.runElement.parentNode;if(!T)return l?(xt(e,l,null,n,N.rPr,o,i,a,s,u),!0):!1;let y=!(s&&f==="slice-cross-author"&&Dl(T,o));if(s&&f==="slice-cross-author"&&Wn(T,o))return zn(e,T,Li(t,T,r),n,N.rPr,o,i,a,s,u);let v=_t(N.runElement),I=v.find(L=>L.node===N.textElement),P=I?I.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:He(v);if(P>0&&P<He(v)){let L=Ve(e,v,0,P,!1),z=Ve(e,v,P,He(v),!1);return bt(e,T,N.runElement,L,N.rPr),xt(e,T,N.runElement,n,N.rPr,o,i,a,y,u),bt(e,T,N.runElement,z,N.rPr),T.removeChild(N.runElement),!0}let B=r<=N.charStart?N.runElement:N.runElement.nextSibling;return xt(e,T,B,n,N.rPr,o,i,a,y,u),!0}let d=ki(t,r,l),p=d.leftSpan&&E(d.leftSpan.runElement?.parentNode,"hyperlink"),b=d.rightSpan&&E(d.rightSpan.runElement?.parentNode,"hyperlink"),h=d.containingSpan&&E(d.containingSpan.runElement?.parentNode,"hyperlink");if(c.hyperlink==="outside"){if(d.isInterior&&h)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(c.hyperlink==="inside"&&!p&&!b&&!h)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let g=null;if(c.formatting==="none"?g=null:c.formatting==="right"?g=d.rightSpan?.rPr||null:c.formatting==="left"?g=d.leftSpan?.rPr||null:g=(d.containingSpan||d.leftSpan||d.rightSpan)?.rPr||null,d.isInterior){let N=d.containingSpan,T=N.runElement.parentNode||l;if(!T)return!1;let y=_t(N.runElement),v=y.find(P=>P.node===N.textElement),I=v?v.start+Math.max(0,Math.min(r-N.charStart,N.charEnd-N.charStart)):r<=N.charStart?0:He(y);if(I>0&&I<He(y)){let P=Ve(e,y,0,I,!1),B=Ve(e,y,I,He(y),!1);return bt(e,T,N.runElement,P,N.rPr),xt(e,T,N.runElement,n,g,o,i,a,s,u),bt(e,T,N.runElement,B,N.rPr),T.removeChild(N.runElement),!0}}let w=null,x=null;if(c.hyperlink==="outside"){if(b){let N=d.rightSpan.runElement.parentNode;w=N.parentNode||l,x=N}else if(p){let N=d.leftSpan.runElement.parentNode;w=N.parentNode||l,x=N.nextSibling}}else c.hyperlink==="inside"&&(b?(w=d.rightSpan.runElement.parentNode,x=d.rightSpan.runElement):p&&(w=d.leftSpan.runElement.parentNode,x=d.leftSpan.runElement.nextSibling));if(w||(d.rightSpan?(w=d.rightSpan.runElement.parentNode||l,x=d.rightSpan.runElement):d.leftSpan?(w=d.leftSpan.runElement.parentNode||l,x=d.leftSpan.runElement.nextSibling):(w=l,x=null)),c.bookmark&&w&&(c.bookmark==="outside"?(x&&E(x.previousSibling,"bookmarkStart")&&(x=x.previousSibling),d.leftSpan&&E(d.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=d.leftSpan.runElement.nextSibling.nextSibling)):c.bookmark==="inside"&&(x&&E(x,"bookmarkStart")&&(x=x.nextSibling),d.leftSpan&&E(d.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=d.leftSpan.runElement.nextSibling))),c.comment&&w)if(c.comment==="outside"){if(x&&E(x.previousSibling,"commentRangeStart")&&(x=x.previousSibling),d.leftSpan&&E(d.leftSpan.runElement.nextSibling,"commentRangeEnd")){let N=d.leftSpan.runElement.nextSibling.nextSibling;N&&(E(N,"commentReference")||E(N,"r"))&&Array.from(N.childNodes||[]).some(y=>E(y,"commentReference"))&&(N=N.nextSibling),x=N}}else c.comment==="inside"&&(x&&E(x,"commentRangeStart")&&(x=x.nextSibling),d.leftSpan&&E(d.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(x=d.leftSpan.runElement.nextSibling));if(s&&c.revision==="coalesce_same_author"){let N=null,T=null;if(d.leftSpan&&E(d.leftSpan.runElement.parentNode,"ins")){let y=d.leftSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(S,"author"))===o&&(N=y,T=d.leftSpan.runElement.nextSibling)}else if(d.rightSpan&&E(d.rightSpan.runElement.parentNode,"ins")){let y=d.rightSpan.runElement.parentNode;(y.getAttribute("w:author")||y.getAttributeNS(S,"author"))===o&&(N=y,T=d.rightSpan.runElement)}if(N){let y=at(e,n,g,!1);return N.insertBefore(y,T),!0}}return s&&f==="slice-cross-author"&&Wn(w,o)?zn(e,w,Li(t,w,r),n,g,o,i,a,s,u):(xt(e,w,x,n,g,o,i,a,s,u),!0)}function zn(e,t,r,n,o,i,a,s,l,u){let c=t.parentNode;if(!c)return!1;let{leftCarrier:f,rightCarrier:m}=_i(e,t,r);return f&&c.insertBefore(f,t),xt(e,c,t,n,Xl(o),i,a,s,l,u),m&&c.insertBefore(m,t),c.removeChild(t),!0}function Xl(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>E(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Li(e,t,r){let n=$i(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 $i(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 Wn(e,t){return E(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(S,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function Dl(e,t){return E(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(S,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function zl(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Wl(e){return!!e?.parentNode}function xt(e,t,r,n,o,i,a,s,l,u=null){let c=Ke(a,s,s+n.length);if(c.length===0){let m=at(e,n,o,!1);if(l){let d=gt(e,"ins",m,i,u);t.insertBefore(d,r)}else t.insertBefore(m,r);return}let f=$r(e,n,o,c,s,i,l);if(l){let m=gt(e,"ins",null,i,u);f.forEach(d=>m.appendChild(d)),t.insertBefore(m,r)}else f.forEach(m=>t.insertBefore(m,r))}function Ul(e,t,r,n=!1){let o=[];if(ar(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 u=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 b of Array.from(p.childNodes||[]))if(b.nodeType===1){let h=b.localName||b.nodeName.replace(/^.*:/,"");if(u.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let c=o[o.length-1].runElement,f=i;for(;f&&f!==c;){if(f!==i){let d=f.localName||f.nodeName.replace(/^.*:/,"");if(u.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(u.has(p)||p==="fldChar")return!0;for(let b of Array.from(d.childNodes||[]))if(b.nodeType===1&&m(b))return!0;return!1}return m(i.previousSibling)||m(c.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Di(e,t,r,n,o,i,a=!0,s=null,l={},u={}){let c=s?[s]:ke(e),{fullText:f,textSpans:m}=Ci(c),p=(u.existingRevisions==="slice-cross-author"?Go(f,r):null)||er(f,r,l),b=Oi(m),h=u.pairReplacements===!0,g=[],w=0,x=0,N=!1;for(let v=0;v<p.length;v++){let[I,P]=p[v];if(I===0){let B=P.length,L=w,z=w+B;ar(b,L,z,V=>{let O=Math.max(V.charStart,L),W=Math.min(V.charEnd,z),R=W-O,_=O-L,F=x+_,J=F+R,H=Ke(i,F,J);Bi(e,V,O,W,H,o,a)&&(N=!0)}),w+=B,x+=B}else if(I===-1){let B=v+1<p.length&&p[v+1][0]===1,L=!1,z=null,V=null;if(h&&a&&B&&p[v+1][1].replace(/\n/g," ").length>0){let R=Ul(b,w,w+P.length,u?.existingRevisions==="slice-cross-author");if(R.safe){let _=Pr(o,e);z={id:_.deletionId,author:_.author,date:_.date},V={id:_.insertionId,author:_.author,date:_.date},L=!0}else R.structuralBoundary&&g.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(Fi(e,b,w,w+P.length,o,a,z)&&(N=!0),w+=P.length,L){v++;let[,O]=p[v],W=O.replace(/\n/g," ");if(W.length>0){let R=Un(e,b,w,W,o,i,x,a,c[0]||null,V,u?.insertionAffinity||null,u?.existingRevisions||"merge-same-author");if(R&&typeof R=="object"&&R.error)return ue({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:R.error});R===!0&&(N=!0)}x+=O.length}}else if(I===1){let B=P.replace(/\n/g," ");if(B.length>0){let L=Un(e,b,w,B,o,i,x,a,c[0]||null,null,u?.insertionAffinity||null,u?.existingRevisions||"merge-same-author");if(L&&typeof L=="object"&&L.error)return ue({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:L.error});L===!0&&(N=!0)}x+=P.length}}let T=c.map(v=>be(v)).join(`
152
+ `),y=String(r).replace(/\r\n/g,`
153
+ `);if(u.existingRevisions==="slice-cross-author"&&T!==y){let v=jl(y,T);return ue({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:v,expectedExcerpt:Xi(y,v),actualExcerpt:Xi(T,v)},...g.length>0?{warnings:[...new Set(g)]}:{}})}return ue({oxml:n.serializeToString(e),hasChanges:N,...g.length>0?{warnings:[...new Set(g)]}:{}})}function jl(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 Xi(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}var Wi=So(En(),1);var Ui=new Wi.diff_match_patch;function ji(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Hl(e,t){return e?.getAttributeNS?.(S,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function zi(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 Vl(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 Hi(e,t,r=null){let n=e.documentElement,o=E(n,"body")||ji(n)==="package",i=r||ke(e),a=ye(e,S,"body");!a&&o&&(a=n);let s="",l=[],u=[],c=[],f=new Map,m=new Map,d=new Set,p={nextCharCode:57344},b=new Set;i.forEach((L,z)=>{let V=s.length;Array.from(L.childNodes).forEach(_=>{s=ql(_,s,l,c,f,m,p,d)}),s=It(s,z,i.length);let O=s.length,W=ye(L,S,"pPr"),R=L.parentNode;R&&b.add(R),u.push({start:V,end:O,pPr:W,container:R||a})});let h="";for(let L=0;L<s.length;L++){let z=s[L];h+=d.has(z)?`
154
+ `:z}let g=Yl(h,t,c);g=Kl(h,s,g,d),m.forEach((L,z)=>{let V=z.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");g=g.replace(new RegExp(V,"g"),L)}),g=Jl(s,g,f);let w=new Map;b.forEach(L=>{w.set(L,e.createDocumentFragment())}),a&&!w.has(a)&&w.set(a,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let x=new Map,N=new Set(u.map(L=>L.start)),T=zi(u),y=zi(l),v=Vl(c);return{paragraphs:i,body:a||e,paragraphMap:u,paragraphStarts:N,propertyMap:l,sentinelMap:c,sentinelMapByStart:v,referenceMap:f,tokenToCharMap:m,containerFragments:w,replacementContainers:x,originalFullText:s,processedModifiedText:g,getParagraphInfo:L=>{let z=T.at(L);return z||(u.length>0?u[u.length-1]:{start:0,end:0,pPr:null,container:a||e})},getRunProperties:L=>{let z=y.at(L);return z?{rPr:z.rPr,wrapper:z.wrapper}:{rPr:null}},getPropertySpanLength:(L,z)=>{let V=y.at(L);return V?Math.min(V.end-L,z):1},isParagraphStart:L=>N.has(L)}}function Vi(e,t){let r=ke(e);if(r.length===0)return[];let n=Gi(t),o=r.map(Gl);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 u="";for(let c=l;c<r.length;c++)if(u+=(c===l?"":`
155
+ `)+o[c],a(u)===s)return r.slice(l,c+1)}}return null}function Gi(e){return String(e??"").replace(/\r\n?/g,`
156
+ `).replace(/\u00a0/g," ")}function Gl(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(E(o,"pPr")||E(o,"del")||E(o,"moveFrom")||(E(o,"t")?t+=o.textContent||"":E(o,"tab")?t+=" ":E(o,"br")||E(o,"cr")?t+=`
157
+ `:E(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),Gi(t)}function Kl(e,t,r,n){if(n.size===0)return r;let o=Ui.diff_main(e,r),i=0,a="";for(let[s,l]of o)if(s===0){for(let u=0;u<l.length;u++){let c=t[i+u];a+=n.has(c)?c:l[u]}i+=l.length}else s===-1?i+=l.length:a+=l;return a}function Yl(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=Ui.diff_main(o,t),l=0,u="",c=(f,m)=>{let d=a.get(f)||[];for(let p of d)p.emitted||m&&p.affinity!==m||(u+=p.char,p.emitted=!0)};for(let[f,m]of s){if(f===1){c(l,"left"),u+=m;continue}for(let d=0;d<m.length;d++)c(l),f===0&&(u+=m[d]),l++}return c(l),u}function Jl(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 ql(e,t,r,n,o,i,a,s){return E(e,"r")?Zl(e,t,r,n,o,i,a,s):E(e,"hyperlink")?Ql(e,t,r):E(e,"sdt")||E(e,"oMath")||ji(e)==="oMath"||E(e,"bookmarkStart")||E(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((E(e,"commentRangeStart")||E(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function Zl(e,t,r,n,o,i,a,s){let l=t,u=ye(e,S,"rPr");return Array.from(e.childNodes).forEach(c=>{if(E(c,"t")){let f=c.textContent||"";f.length>0&&(r.push({start:l.length,end:l.length+f.length,rPr:u}),l+=f)}else if(E(c,"br")||E(c,"cr")){let f=String.fromCharCode(a.nextCharCode++);o.set(f,c),s.add(f),l+=f,r.push({start:l.length-1,end:l.length,rPr:u})}else if(E(c,"tab"))l+=" ",r.push({start:l.length-1,end:l.length,rPr:u});else if(E(c,"noBreakHyphen"))l+="\u2011",r.push({start:l.length-1,end:l.length,rPr:u});else if(["drawing","pict","object","fldChar","instrText","sym"].some(f=>E(c,f))){let f=ye(c,S,"txbxContent"),m=E(c,"pict")&&!!f,d=E(c,"fldChar")||E(c,"instrText"),p=E(c,"fldChar")?c.getAttributeNS?.(S,"fldCharType")||c.getAttribute("w:fldCharType")||c.getAttribute("fldCharType"):null;n.push({start:l.length,node:c,wrapInRun:!0,rPr:u,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:u})}else if(E(c,"footnoteReference")||E(c,"endnoteReference")){let f=Hl(c,"id");if(f){let d=`{{__${E(c,"footnoteReference")?"FN":"EN"}_${f}__}}`,p=String.fromCharCode(a.nextCharCode++);o.set(p,c),i.set(d,p),l+=p,r.push({start:l.length-1,end:l.length,rPr:u})}}else E(c,"commentReference")&&n.push({start:l.length,node:c,isCommentMarker:!0})}),l}function Ql(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!E(o,"r"))return;let i=ye(o,S,"rPr");ve(o,S,"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 Yi(e,t,r,n,o,i,a=!0,s={}){let{paragraphs:l,containerFragments:u,sentinelMapByStart:c,referenceMap:f,replacementContainers:m,getParagraphInfo:d,getRunProperties:p,getPropertySpanLength:b,isParagraphStart:h}=r,g=R=>{let _=C(e,"w:p");if(R){let F=R.cloneNode(!0),J=ye(F,S,"sectPr");J&&F.removeChild(J),_.appendChild(F)}return _},w=d(0),x=g(w.pPr),N=u.get(w.container);N&&N.appendChild(x);let T=0,y=0,v=s?.pairReplacements===!0,I=null,P=null,B=new WeakSet;for(let R=0;R<t.length;R++){let[_,F]=t[R];if(_===0||_===-1){let J=_===0?"equal":"delete";if(_===0)I=null,P=null;else if(I===null){I=T;let Q=!1;for(let ee=R+1;ee<t.length;ee++){if(t[ee][0]===1){Q=!0;break}if(t[ee][0]===0)break}v&&a&&Q&&(P=Pr(o,e))}let H=0;for(;H<F.length;){let Q=T+H,ee=p(Q),We=b(Q,F.length-H),yr=F.substring(H,H+We);x=Ki(e,yr,J,ee.rPr,ee.wrapper,Q,x,u,c,f,m,d,g,o,i,y,a,B,P).currentParagraph,_===0&&(y+=We),H+=We}T+=F.length;continue}if(_===1){let J=I!==null?I:T>0&&!h(T)?T-1:T,H=p(J);x=Ki(e,F,"insert",H.rPr,H.wrapper,T,x,u,c,f,m,d,g,o,i,y,a,B,P,I!==null).currentParagraph,y+=F.length,I=null,P=null}}a&&u.forEach(R=>{Array.from(R.childNodes).forEach(_=>{if(E(_,"p")){let F=Array.from(_.getElementsByTagNameNS(S,"t")).length>0,J=Array.from(_.getElementsByTagNameNS(S,"delText")).length>0;l.length===1&&!F&&(J||r.originalFullText.trim()!=="")&&nr(e,_,o)}})}),u.forEach(R=>{let _=Array.from(R.childNodes).filter(F=>E(F,"p"));if(_.length>1){let F=_[0],J=_[_.length-1],H=ye(F,S,"pPr"),Q=H?ye(H,S,"sectPr"):null;if(Q){H.removeChild(Q);let ee=ye(J,S,"pPr");ee||(ee=C(e,"w:pPr"),J.insertBefore(ee,J.firstChild||null)),ee.appendChild(Q)}}});let L=new Set(l),z=new Map;l.forEach(R=>{let _=R.parentNode;if(!_||z.has(_))return;let F=R.nextSibling;for(;F&&L.has(F);)F=F.nextSibling;z.set(_,F)}),l.forEach(R=>{R.parentNode&&R.parentNode.removeChild(R)});let V=!1,O="";return u.forEach((R,_)=>{let F=m.get(_),J=F||_;if(J.nodeType===9){V=!0,R.childNodes.length===1?J.appendChild(R.firstChild):O=Array.from(R.childNodes).map(Q=>n.serializeToString(Q)).join("");return}let H=F?null:z.get(_);H&&H.parentNode===J?J.insertBefore(R,H):J.appendChild(R)}),{oxml:V&&O?O:n.serializeToString(e),hasChanges:!0}}function Ki(e,t,r,n,o,i,a,s,l,u,c,f,m,d,p=[],b=0,h=!0,g=new WeakSet,w=null,x=!1){let N=i,T=b,y=a,v=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(P=>{let B=l.get(N)||[],L=B.filter(O=>O.isCommentMarker&&!g.has(O.node)),z=x?new Set(L.filter(O=>E(O.node,"commentRangeEnd")).map(O=>O.node.getAttributeNS?.(S,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id"))):new Set;if(L.forEach(O=>{g.add(O.node);let W=O.node.getAttributeNS?.(S,"id")||O.node.getAttribute?.("w:id")||O.node.getAttribute?.("id");if(x&&z.has(W)&&(E(O.node,"commentRangeEnd")||E(O.node,"commentReference"))){v.push(O.node);return}if(E(O.node,"commentReference")){let R=C(e,"w:r");R.appendChild(O.node.cloneNode(!0)),y.appendChild(R)}else y.appendChild(O.node.cloneNode(!0))}),P===`
158
+ `){let O=f(N+1),W=m(O.pPr);h&&r==="insert"?vi(e,y,d):h&&r==="delete"&&nr(e,y,d);let R=s.get(O.container);R&&(R.appendChild(W),y=W),N++,r!=="delete"&&T++;return}if(P==="\uFFFC"){let O=B.find(W=>!W.isCommentMarker)||B[0];if(O){let W=O.node.cloneNode(!0);if(O.isTextBox&&O.originalContainer){let R=ye(W,S,"txbxContent");if(R){for(;R.firstChild;)R.removeChild(R.firstChild);c.set(O.originalContainer,R)}}if(O.wrapInRun){let R=C(e,"w:r");O.rPr&&R.appendChild(O.rPr.cloneNode(!0)),R.appendChild(W),y.appendChild(R)}else y.appendChild(W)}N++,r!=="delete"&&T++;return}if(u.has(P)){if(r!=="delete"){let O=u.get(P);if(O){let W=O.cloneNode(!0),R=C(e,"w:r");n&&R.appendChild(n.cloneNode(!0)),R.appendChild(W),y.appendChild(R)}}N++,r!=="delete"&&T++;return}if(P.length===0)return;let V=y;if(o){let O=o.cloneNode(!1);V=O,y.appendChild(O)}if(r==="delete"){let O=C(e,"w:r");n&&O.appendChild(n.cloneNode(!0));let W=C(e,"w:delText");if(W.setAttribute("xml:space","preserve"),W.textContent=P,O.appendChild(W),h){let R=null;if(w){let F=w.usedDeletionId?ie(d,e,"del").id:w.deletionId;w.usedDeletionId=!0,R={id:F,author:w.author,date:w.date}}let _=gt(e,"del",O,d,R);V.appendChild(_)}}else{let O=Ke(p,T,T+P.length),W=$r(e,P,n,O,T,d,h);if(r==="insert"&&h){let R=null;if(w){let F=w.usedInsertionId?ie(d,e,"ins").id:w.insertionId;w.usedInsertionId=!0,R={id:F,author:w.author,date:w.date}}let _=gt(e,"ins",null,d,R);W.forEach(F=>_.appendChild(F)),V.appendChild(_)}else W.forEach(R=>V.appendChild(R))}r!=="delete"&&(T+=P.length),N+=P.length}),v.forEach(P=>{if(E(P,"commentReference")){let B=C(e,"w:r");B.appendChild(P.cloneNode(!0)),y.appendChild(B)}else y.appendChild(P.cloneNode(!0))}),{currentParagraph:y}}function jn(e,t,r,n,o,i,a=!0,s={},l={}){let u=Vi(e,t);if(u===null)return ue({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 c=Hi(e,r,u);if(c.paragraphs.length===0)return ue({oxml:n.serializeToString(e),hasChanges:!1});let f=er(c.originalFullText,c.processedModifiedText,s);return ue(Yi(e,f,c,n,o,i,a,l))}function Xe(e,t){return ue({oxml:e.serializeToString(t),hasChanges:!1})}function Ji(e,t,r,n,o,i=!0){let a=ve(e,S,"tbl"),s=$e(t),l=s.rows.length>0||s.headers.length>0;if(a.length===0||!l)return Xe(r,e);let u=a[0],c=Sn(u),f=ii(c,s);if(f.length===0)return Xe(r,e);let m={generateRedlines:i,author:o,revisionIdAllocator:Ye(e)},d=ai(c,f,m),p=`<root xmlns:w="${S}">${d}</root>`,b=U(p,"application/xml").doc;if(!b)return Xe(r,e);let h=ne(b);if(h)return te("[OxmlEngine] Failed to parse reconciled table OOXML:",h.textContent),Xe(r,e);let g=ye(b,S,"tbl");if(!g)return te("[OxmlEngine] No table found in reconciled OOXML"),Xe(r,e);let w=e.importNode(g,!0);return u.parentNode.replaceChild(w,u),ue({oxml:r.serializeToString(e),hasChanges:!0})}function qi(e,t,r,n,o,i){let a=Ye(e),s=$e(t);if(!s||s.rows.length===0&&s.headers.length===0)return k("[OxmlEngine] Failed to parse table data from Markdown"),Xe(r,e);let l=pt(s,{generateRedlines:i,author:o,revisionIdAllocator:a}),u=U(`<root xmlns:w="${S}">${l}</root>`,"application/xml").doc;if(!u)return Xe(r,e);let c=ne(u);if(c)return te("[OxmlEngine] Failed to parse generated table OOXML:",c.textContent),Xe(r,e);let f=re(u,S,"tbl");if(f||(f=re(u,S,"ins")),!f)return te("[OxmlEngine] No table element found in generated OOXML"),Xe(r,e);let m=e,d=le(m,S,"p");if(d.length===0)return k("[OxmlEngine] No paragraphs found to replace"),Xe(r,m);let p=d[0],b=p.parentNode;if(b&&b.nodeType===9){let g=U(`<w:document xmlns:w="${S}"><w:body/></w:document>`,"application/xml").doc;if(!g)return Xe(r,m);let w=re(g,S,"body");d.forEach(x=>w.appendChild(g.importNode(x,!0))),m=g,Ir(m,a),d=le(m,S,"p"),p=d[0],b=p.parentNode}let h=m.importNode(f,!0);return i?d.forEach(g=>{nr(m,g,o),le(g,S,"r").forEach(x=>{le(x,S,"t").forEach(v=>{let I=v.textContent||"";if(I.trim()){let P=C(m,"w:delText");P.textContent=I,v.parentNode.replaceChild(P,v)}});let T=C(m,"w:del"),y=ie(o,m,"del");T.setAttribute("w:id",String(y.id)),T.setAttribute("w:author",y.author),T.setAttribute("w:date",y.date),x.parentNode.insertBefore(T,x),T.appendChild(x)})}):d.slice(1).forEach(g=>g.parentNode.removeChild(g)),b.insertBefore(h,p),i||b.removeChild(p),k("[OxmlEngine] Text-to-table transformation complete"),ue({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 Wr(e){return typeof e=="string"?e.trim().toLowerCase():""}function ec(e){return!!e&&e.nodeType===1}function De(e,t){return ec(e)&&e.namespaceURI===S&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function xe(e,t){return Array.from(e.getElementsByTagNameNS(S,t))}function Hn(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=Wr(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 Pe(e,t){if(t.allAuthors)return!0;let r=Wr(Ze(e,"author"));return!!r&&r===t.normalizedAuthor}function Vn(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=U(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let a=`<w:body xmlns:w="${S}">${r}</w:body>`,s=U(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:me(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function fe(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Ur(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function Zi(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Qi(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||Hr(n))continue;let o=Zi(n);for(;De(o,"ins")&&Wr(Ze(o,"author"))===Wr(Ze(n,"author"))&&Qi(o)===Qi(n);){let i=Zi(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=i}}return t}function jr(e){let t=e?.parentNode;return De(t,"trPr")&&De(t?.parentNode,"tr")}function Hr(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return De(t,"rPr")&&De(r,"pPr")&&De(n,"p")}function ra(e){return Hr(e)?e.parentNode.parentNode.parentNode:null}function rc(e){let t=e?.nextSibling||null;for(;t;){if(De(t,"p"))return t;t=t.nextSibling}return null}function na(e){if(!e?.parentNode)return!1;let t=rc(e);if(!t)return De(e.parentNode,"tc")&&xe(e.parentNode,"p").length<=1?!1:fe(e);let r=Array.from(e.childNodes||[]).filter(o=>!De(o,"pPr")),n=t.firstChild||null;De(n,"pPr")&&(n=n.nextSibling||null);for(let o of r)t.insertBefore(o,n);return fe(e)}function Gn(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=Vn(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 c of xe(i,"ins"))if(!(!c.parentNode||!Pe(c,n))){if(Hr(c)){fe(c)&&(s+=1);continue}if(jr(c)){fe(c)&&(s+=1);continue}Ur(c)&&(s+=1)}for(let c of xe(i,"del")){if(!c.parentNode||!Pe(c,n))continue;let f=ra(c);if(f){na(f)&&(s+=1);continue}if(jr(c)){let m=c.parentNode?.parentNode;fe(m)&&(s+=1);continue}fe(c)&&(s+=1)}for(let c of xe(i,"moveFrom"))!c.parentNode||!Pe(c,n)||fe(c)&&(s+=1);for(let c of xe(i,"moveTo"))!c.parentNode||!Pe(c,n)||Ur(c)&&(s+=1);s+=oa(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let c of l)for(let f of xe(i,c))!f.parentNode||!Pe(f,n)||fe(f)&&(s+=1);return{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(c=>a.serializeToString(c)).join(""):a.serializeToString(i),hasChanges:s>0,acceptedCount:s,warnings:r}}function ea(e,t){for(let r of Array.from(t.getElementsByTagNameNS(S,"delText"))){let n=C(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 nc(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!==S)return fe(e);let o=Array.from(e.childNodes||[]).find(a=>a.nodeType===1&&a.namespaceURI===S&&String(a.localName||"").toLowerCase()===n.toLowerCase());if(!o)return fe(e);let i=Array.from(o.childNodes||[]);for(;r.firstChild;)r.removeChild(r.firstChild);for(let a of i){let s=oc(r.ownerDocument,a);r.appendChild(s)}return!0}function oc(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function ta(e,t,r){let n=new Set;for(let o of xe(e,t)){if(!Pe(o,r))continue;let i=Ze(o,"id");i&&n.add(i)}return n}function oa(e,t){let r=0,n=ta(e,"moveFromRangeStart",t),o=ta(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 u of xe(e,a)){if(!u.parentNode)continue;let c=Ze(u,"id");c&&(t.allAuthors||s.has(c)||l&&Pe(u,t))&&fe(u)&&(r+=1)}return r}function Kn(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=Vn(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 c of xe(i,"ins")){if(!c.parentNode||!Pe(c,n))continue;let f=ra(c);if(f){na(f)&&(s+=1);continue}if(jr(c)){let m=c.parentNode?.parentNode;fe(m)&&(s+=1);continue}fe(c)&&(s+=1)}for(let c of xe(i,"del"))if(!(!c.parentNode||!Pe(c,n))){if(Hr(c)){fe(c)&&(s+=1);continue}if(jr(c)){fe(c)&&(s+=1);continue}ea(i,c),Ur(c)&&(s+=1)}for(let c of xe(i,"moveFrom"))!c.parentNode||!Pe(c,n)||(ea(i,c),Ur(c)&&(s+=1));for(let c of xe(i,"moveTo"))!c.parentNode||!Pe(c,n)||fe(c)&&(s+=1);s+=oa(i,n);let l=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let c of l)for(let f of xe(i,c))!f.parentNode||!Pe(f,n)||nc(f,c)&&(s+=1);return tc(i),{oxml:o.isFragmentWrapped?Array.from(i.documentElement.childNodes).map(c=>a.serializeToString(c)).join(""):a.serializeToString(i),hasChanges:s>0,rejectedCount:s,warnings:r}}function ic(e,t){let r=new Set,n=xe(e,"comment");for(let o of n){if(!Pe(o,t))continue;let i=Ze(o,"id");i&&r.add(i)}return{targetIds:r,commentNodes:n}}function ac(e,t){let r=0;for(let n of e){let o=Ze(n,"id");!o||!t.has(o)||fe(n)&&(r+=1)}return r}function sc(e){return De(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!==S)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function lc(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"&&sc(i.parentNode)){fe(i.parentNode)&&(r+=1);continue}fe(i)&&(r+=1)}}return r}function cc(e,t={}){let r=[],n=Hn(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=Vn(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}=ic(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 u=ac(l,s),c=lc(i,s);return{oxml:a.serializeToString(i),hasChanges:u>0||c>0,commentsRemoved:u,referencesRemoved:c,warnings:r}}var uc=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:uc[t]||null,...r}))}function fc(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of ve(e,S,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))}async function Yn(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||de(),l=me(),u=[],c=[],f=!1,m=n.existingRevisions||"merge-same-author",d=m==="accept-all-first-keep-normalized",p=X=>{let M={...X};f&&M.hasChanges===!1&&M.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Previous revisions by the same author were reverted to baseline."]):d?(M.oxml=i,M.hasChanges=!0,M.warnings=[...Array.isArray(M.warnings)?M.warnings:[],"Existing revisions were accepted before redlining."]):M.oxml=o);let q=[...u,...c,...Array.isArray(M.warnings)?M.warnings:[]];return q.length>0&&(M.warnings=[...new Set(q)]),M.status||(M.status=M.hasChanges?"ok":"no-op"),ue(M)},b=()=>p(f&&d?{oxml:i,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),h=U(o,"text/xml");u=h.warnings;let g=h.doc,w=g?ne(g):null;if(h.error||w){let X=h.error?.message||w?.textContent||"Could not parse OOXML input.";return te("[OxmlEngine] XML parse error:",X),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:X}})}let x=n?._revisionIdAllocator instanceof he?n._revisionIdAllocator:new he;if(Et(g,x),Lr(g))if(m==="merge-same-author"||m==="slice-cross-author"){let X=Rn(g),M=String(s||"").trim().toLowerCase();if(X.length>0&&X.every(se=>se.trim().toLowerCase()===M)){let se=fc(g);if(se.length>0)return p({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:se}});k("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let Te=Kn(o,{author:s});if(Te.status==="error")return p(Te);i=Te.oxml,f=!0;let Ht=U(i,"text/xml");u.push(...Ht.warnings),g=Ht.doc;let vo=g?ne(g):null;if(Ht.error||vo){let Tr=Ht.error?.message||vo?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return te("[OxmlEngine] XML parse error after rejecting same-author revisions:",Tr),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Tr}})}if(Lr(g))return p({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."}});Et(g,x);let yo=g.documentElement&&String(g.documentElement.localName||"").toLowerCase()==="p"?[g.documentElement]:ke(g);t=yo.length>0?yo.map(Tr=>be(Tr)).join(`
160
+ `):""}else{if(m==="merge-same-author")return k("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${X.length?X.join(", "):"unattributed"}). Pass existingRevisions: "accept-all-first" or resolve revisions first.`}});if(["moveFrom","moveTo"].some(Te=>ve(g,S,Te).length>0))return p({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});k("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){k("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let X=Gn(o,{allAuthors:!0});if(X.status==="error")return p(X);i=X.oxml,f=!0;let M=U(i,"text/xml");u.push(...M.warnings),g=M.doc;let q=g?ne(g):null;if(M.error||q){let se=M.error?.message||q?.textContent||"Could not parse OOXML after accepting existing revisions.";return te("[OxmlEngine] XML parse error after accepting existing revisions:",se),p({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:se}})}Et(g,x)}else return k("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let N=Ri(g,t,n);if(N.hasTableWrapper&&N.targetParagraph&&!n._isolatedTableCell){k("[OxmlEngine] Isolating table-cell paragraph before diff");let X=or(g,N.targetParagraph,l),M=await Yn(X,t,r,{...n,_isolatedTableCell:!0});return!M.hasChanges&&M.status==="no-op"?b():M}let T=n.sanitizeInput===!0?Jn(r):r;T!==r&&c.push("Input was sanitized; pass sanitizeInput: false to disable.");let y=null;if(n.structuredContent!==!1)if(y=Br(T),y.valid)y.requiresStructuredContent&&(T=y.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let X=y.issues.map(M=>`${M.code}: ${M.message}`).join(" ");return p({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:X},warnings:y.issues.map(M=>M.message)})}y=null}let{cleanText:v,formatHints:I}=Ie(T),P=m==="slice-cross-author"?v!==t:v.trim()!==t.trim(),B=I.length>0,{existingFormatHints:L,textSpans:z,paragraphs:V}=bi(g),O=L.length>0,W=z.map(X=>ia(X)).join(""),R=t.includes(`
161
+ `)||t.includes("\r")?t.split(/\r?\n/).map(Vr).filter(Boolean).every(X=>V.some(M=>{let q=z.filter(se=>se.paragraph===M).map(ia).join("");return Vr(q).includes(X)})):W.includes(t.trim())||W.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||Vr(W).includes(Vr(t));if(P&&typeof t=="string"&&t.trim()&&!R)return k("[OxmlEngine] Target text not found in OOXML"),p({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let _=null,F=()=>(_||(_=Xr(g,V,z)),_),J=(X=null)=>{let M=Pi(g,t,I,l,s,a,X);return M.useNativeApi?(k("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),jn(g,t,v,l,s,I,a)):M};k(`[OxmlEngine] Text changes: ${P}, New format hints: ${I.length}, Existing format hints: ${L.length}`);let H=n.removeFormatting===!0&&!P&&!B&&O;if(!P&&!B&&!O)return Qe(n,"noChange"),k("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),b();if(!P&&!B&&O&&!H)return k("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),b();if(H){Qe(n,"formatOnly",{removeFormatting:!0}),k("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let X=N,M=X.targetParagraph||null;if(!M){let Te=Ti(F(),t);Te&&(M=Te.paragraph)}let q=L;M&&(q=L.filter(Te=>Ei(Te.run)===M));let se=Ai(g,z,q,l,s,a);return X.hasTableWrapper&&M?p({oxml:or(g,M,l),hasChanges:se.hasChanges}):p(se)}if(!P&&B){Qe(n,"formatOnly",{removeFormatting:!1}),k(`[OxmlEngine] Format-only change detected: ${I.length} format hints`);let X=N,M={textSpans:z,paragraphs:V,paragraphInfos:F()};if(X.hasTableWrapper&&X.targetParagraph){k("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let q=J(M);return k("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),p({oxml:or(g,X.targetParagraph,l),hasChanges:q.hasChanges})}return p(J(M))}let ee=ve(g,S,"tbl").length>0,We=/^\|.+\|/.test(v.trim())&&v.includes(`
162
+ `),yr=Kt(v),xo=n.structuredContent!==!1&&y?.requiresStructuredContent===!0,ft=N,No=ee||m==="slice-cross-author";k(`[OxmlEngine] Mode: ${No?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${I.length}, isMarkdownTable: ${We}, isTargetList: ${yr}, isTableCellParagraph: ${ft.isTableCellParagraph}`);try{if(We&&!ee)return Qe(n,"table",{transformation:"text-to-table"}),k("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),p(qi(g,v,l,null,s,a));if(ee&&We)return Qe(n,"table",{transformation:"table-reconciliation"}),p(Ji(g,v,l,null,s,a));if(No){Qe(n,"surgical",{tableScoped:ee});let X=ft.hasTableWrapper&&ft.targetParagraph?ft.targetParagraph:null;X&&k("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let M=Di(g,t,v,l,s,I,a,X,{},n);return M.status==="error"&&M.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?p({...M,oxml:o,hasChanges:!1}):ft.hasTableWrapper&&M.hasChanges&&ft.targetParagraph?(k("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),p({oxml:or(g,ft.targetParagraph,l),hasChanges:!0})):p(M)}if(yr||xo){let X=ve(g,S,"p"),M=X.length===1;Qe(n,M?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:X.length}),k(`[OxmlEngine] \u{1F3AF} Using ${M?"direct list generation":"compatibility pipeline"} for list reconciliation`);let q;if(M){let se=Pt(i,{xmlDoc:g}),Te=Qt(X[0]);q=await Ct({cleanText:v,numberingContext:Te,originalRunModel:se.runModel,originalText:se.acceptedText,generateRedlines:a,author:s,font:n.font||null,revisionIdAllocator:x,numberingService:new Je})}else q=await new tr({author:s,generateRedlines:a,revisionIdAllocator:x}).execute(i,T,{xmlDoc:g});if(q.error?.code==="DIFF_TOKEN_LIMIT")return p({oxml:o,hasChanges:!1,status:"error",error:q.error});if(q.isValid&&q.ooxml&&q.ooxml!==i){let se=q.includeNumbering===!0;k(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${se}`);let Te=it(q.ooxml,{includeNumbering:se,numberingXml:q.numberingXml});return k(`[OxmlEngine] \u2705 Wrapped OOXML length: ${Te.length}`),p({oxml:Te,hasChanges:!0,...Array.isArray(q.warnings)?{warnings:q.warnings}:{}})}return b()}return Qe(n,"reconstruction"),p(jn(g,t,v,l,s,I,a,{},n))}catch(X){if(Ho(X))return p({oxml:o,hasChanges:!1,status:"error",error:{code:X.code,message:X.message}});throw X}}function Vr(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function ia(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 Jn(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 U(e,"application/xml").doc}function Nt(e){return oe(e)}function Gr(e){return Array.from(e||[])}function lr(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function Re(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var Ce="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function aa(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Gr(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Gr(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Gr(e.getElementsByTagName(t))}function ce(e){return e?be(e):""}function Se(e){if(!e)return[];let t=aa(e,"body"),r=t.length>0?t[0]:e;return aa(r,"p")}function vt(e){return e&&Gr(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Lt(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:be(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:Se(e.ownerDocument||e).indexOf(e)+1,i=t.paragraphId===void 0?vt(e):t.paragraphId,a=typeof t.inTable=="boolean"?t.inTable:cr(e),l=`${i||""}${o}${a?"table":"body"}${r==="rejected"?"rejected":""}${n}`,u=2166136261;for(let c=0;c<l.length;c++)u^=l.charCodeAt(c),u=Math.imul(u,16777619)>>>0;return`fnv1a32:${u.toString(16).padStart(8,"0")}`}function sa(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=Se(e),o=[],i=new Map,a=new Map,s=new Map;for(let l=0;l<n.length;l++){let u=n[l],c=be(u,{revisionView:r}),f=vt(u),m=cr(u),d=j(c),p=Object.freeze({paragraph:u,index:l+1,paragraphId:f,text:c,normalizedText:d,revisionView:r,fingerprint:Lt(u,{text:c,index:l+1,paragraphId:f,inTable:m,revisionView:r}),inTable:m});o.push(p),i.set(u,p),f&&!a.has(f)&&a.set(f,p),d&&(s.has(d)||s.set(d,[]),s.get(d).push(p))}for(let[l,u]of s)s.set(l,Object.freeze(u));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:i,byId:a,byNormalizedText:s})}function j(e){return String(e||"").replace(/\s+/g," ").trim()}function Qn(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
164
+ `)}function eo(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 mc(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function dc(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 la(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:Se(e)[t-1]||null}function Bt(e,t,r=Ce){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Kr(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,i=o?null:Se(e),a=String(t||"").trim();if(!a)return null;let s=o?o.find(u=>u.text.trim()===a)?.paragraph:i.find(u=>ce(u).trim()===a);if(s)return s;let l=j(a);return n?.byNormalizedText?n.byNormalizedText.get(l)?.[0]?.paragraph||null:i.find(u=>j(ce(u))===l)||null}function qn(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,i=o?.entries||null,a=i?null:Se(e),s=String(t||"").trim();if(!s)return null;let l=Kr(e,s,{paragraphMetadataIndex:o});if(l)return l;let u=j(s),c=i?i.find(h=>h.normalizedText.length>10&&u.startsWith(h.normalizedText))?.paragraph||null:a.find(h=>{let g=j(ce(h));return g.length>10&&u.startsWith(g)});if(c)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${ce(c).trim().slice(0,60)}..."`),c;let f=i?i.find(h=>h.normalizedText.length>15&&u.includes(h.normalizedText))?.paragraph||null:a.find(h=>{let g=j(ce(h));return g.length>15&&u.includes(g)});if(f)return n(`[Fuzzy] Contains match: "${ce(f).trim().slice(0,60)}..."`),f;let m=0,d=null,p=new Set(u.toLowerCase().split(/\s+/).filter(h=>h.length>2)),b=i?.length??a.length;for(let h=0;h<b;h++){let g=i?.[h]?.paragraph??a[h],w=(i?.[h]?.text??ce(g)).trim();if(!w)continue;let T=j(w).toLowerCase().split(/\s+/).filter(y=>y.length>2).filter(y=>p.has(y)).length/Math.max(p.size,1);T>m&&T>.5&&(m=T,d=g)}return d?(n(`[Fuzzy] Best word-overlap match (${(m*100).toFixed(0)}%): "${ce(d).trim().slice(0,60)}..."`),d):null}function ca(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=eo(i?.index??i?.paragraphIndex??t.targetRef),u=t.strictAmbiguity===!0,c=t.paragraphMetadataIndex||null;if(c&&c.revisionView!==a?c=t.metadataIndices?.[a]||sa(e,{revisionView:a}):c||(c=sa(e,{revisionView:a})),i?.paragraphId){let m=gc(e,i.paragraphId,c);if(!m)throw Re("TARGET_NOT_FOUND",`Target paragraphId not found: "${i.paragraphId}".`);let d=c?.byParagraph?.get(m)||null,p=d?.index??Se(e).indexOf(m)+1,b=d?.fingerprint||Lt(m,{revisionView:a}),h=d?.inTable??cr(m),g=d?.normalizedText||j(be(m,{revisionView:a}));if(l!=null&&l!==p)throw Re("TARGET_INDEX_MISMATCH",`Target paragraphId "${i.paragraphId}" (index ${p}) does not match requested index ${l}.`,d?[Ge(d)]:null);if(i.fingerprint&&i.fingerprint!==b)throw Re("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches its source fingerprint.`,d?[Ge(d)]:null);if(typeof i.inTable=="boolean"&&i.inTable!==h)throw Re("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" does not match the requested table context.`,d?[Ge(d)]:null);if(s&&g!==j(s))throw Re("TARGET_TEXT_MISMATCH",`Target paragraphId "${i.paragraphId}" no longer matches the supplied text.`,d?[Ge(d)]:null);if(i.occurrence!=null){let x=Yr(e,s||g,c),N=x.findIndex(T=>T.paragraph===m)+1;if(N===0||N!==i.occurrence)throw Re("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${i.paragraphId}" matches occurrence ${N}, not requested occurrence ${i.occurrence}.`,x.map(Ge))}return{paragraph:m,resolvedBy:"paragraph_id"}}let f=[];if(s){let m=Yr(e,s,c);if(f=pc(m,i),i?.fingerprint&&m.length>0&&f.length===0)throw Re("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",m.map(Ge));if(typeof i?.inTable=="boolean"&&m.length>0&&f.length===0)throw Re("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",m.map(Ge));if(i?.occurrence){let d=f[i.occurrence-1]||null;if(!d)throw Re("TARGET_NOT_FOUND",`Target occurrence ${i.occurrence} was not found.`,f.map(Ge));return{paragraph:d.paragraph,resolvedBy:"occurrence"}}if(u){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 Re("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`,f.map(Ge));if(f.length===1)return{paragraph:f[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(f.length>1)throw Re("AMBIGUOUS_TARGET",`Target text matched ${f.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,f.map(Ge));if(f.length===0)throw lr(`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=la(e,l,c);if(m){let d=c?.byParagraph?.get(m)||null;if(i?.fingerprint&&i.fingerprint!==d?.fingerprint)throw Re("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${l}].`);if(typeof i?.inTable=="boolean"&&i.inTable!==d?.inTable)throw Re("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${l}] does not match requested table context.`);if(s){let p=Kr(e,s,{paragraphMetadataIndex:c}),b=(d?.text||be(m,{revisionView:a})).trim(),h=j(b),g=j(s),w=h!==g;if(w&&p&&p!==m)return r(`[Target] [P${l}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let x=qn(e,s,{onInfo:r,paragraphMetadataIndex:c});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&&!u){let m=Kr(e,s,{paragraphMetadataIndex:c});if(m){let p=f.length;if(p>1){let b=`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(b),{paragraph:m,resolvedBy:"strict_text",warnings:[b]}}return{paragraph:m,resolvedBy:"strict_text"}}let d=qn(e,s,{onInfo:r,paragraphMetadataIndex:c});if(d)return{paragraph:d,resolvedBy:"fuzzy_text"}}throw lr(s?`Target paragraph not found: "${s}"`:l?`Target paragraph reference not found: [P${l}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function cr(e){return!!Bt(e,"tbl")}function Yr(e,t,r=null){let n=j(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=Se(e),s=[];for(let l=0;l<a.length;l++){let u=a[l],c=be(u,{revisionView:i}).trim();c&&j(c)===n&&s.push({paragraph:u,index:l+1,inTable:cr(u),paragraphId:vt(u),fingerprint:Lt(u,{text:c,index:l+1,revisionView:i}),text:c,revisionView:i})}return s}function Ge(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function pc(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 gc(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:Se(e).find(n=>vt(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 wc(e,t=null){let r=t?.entries||null,n=r?null:Se(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??ce(s)).trim();o.set(a+1,{text:l,normalizedText:r?.[a]?.normalizedText??j(l),inTable:r?.[a]?.inTable??cr(s)})}return o}function Zn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=ca(e,t),o=eo(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=j(s);if(!l||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||j(ce(n.paragraph)))===l)return n;let c=[];if(a&&c.push(a),i.text){let m=j(i.text);m&&!c.some(d=>j(d)===m)&&c.push(i.text)}let f=null;for(let m of c){let d=Yr(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 lr(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function bc(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=Zn(e,{targetRef:t,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!l)return null;let u=Zn(e,{targetRef:r,opType:o,targetRefSnapshot:i,onInfo:a,onWarn:s})?.paragraph;if(!u)return null;let c=Array.from(e.getElementsByTagNameNS("*","p")),f=c.indexOf(l),m=c.indexOf(u);if(f<0||m<f)return null;let d=c.slice(f,m+1);if(d.length===0)return null;let p=d[0]?.parentNode||null;return!p||!d.every(b=>b&&b.parentNode===p)?null:d}function Jr(e,t){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let r=e.getElementsByTagNameNS(Ce,t);if(r.length>0)return r[0];let n=e.getElementsByTagNameNS("*",t);return n.length>0?n[0]:null}function ua(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(Ce,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function ma(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Ue(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function da(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=Jt(i,{indentSpaces:2});if(a){n=!0,r.push({kind:"list",markerType:a.markerType,level:a.level,marker:a.marker,outlineLevel:a.outlineLevel,text:ma(a.text)});continue}r.push({kind:"text",text:i.trim()})}return{items:r,hasListMarkers:n}}function fa(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function ur(e,t){return j(e)===j(t)}function qr(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function xc(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 ur(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let i=n.level||0;return o.some(s=>(s.level||0)>i)?!1:ur(n.text,t)}return!1}function Nc(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 vc(e,t,r,n){let o=e[0],i=e.slice(1).filter(a=>a.kind==="list");if(o?.kind==="text"&&ur(o.text,t)&&i.length>0){let a=i[0].level;return i.map(s=>({ilvl:qr(s,r,a),markerType:s.markerType||n,text:s.text}))}if(e.every(a=>a.kind==="list")){let a=e[0];if(!a||!ur(a.text,t))return null;let s=a.level;return e.slice(1).map(l=>({ilvl:qr(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=Jr(e,"pPr");if(!t)return null;let r=Jr(t,"numPr");if(!r)return null;let n=Jr(r,"numId");if(!n)return null;let o=ua(n);if(!o||o==="0")return null;let i=Jr(r,"ilvl"),a=ua(i),s=Number.parseInt(a||"0",10);return{numId:String(o),ilvl:Number.isFinite(s)?s:0}}function pa(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===Ce&&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 yc(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=pa(e);if(!s||s.length===0)return null;let l=da(i);if(!l.hasListMarkers||l.items.length<2)return null;let u=j(r.currentParagraphText||ce(e)),f=l.items.filter(v=>v.kind==="list")[0]?.markerType||"bullet",m=s.map(v=>({paragraph:v,list:tt(v),text:String(ce(v)||"").trim()})),d=s.indexOf(e);if(d<0)return null;let p=Math.min(...m.map(v=>v.list?.ilvl??0)),b=m.map(v=>fa((v.list?.ilvl??0)-p,f,v.text)),h=null,g=l.items[0],w=l.items.slice(1).filter(v=>v.kind==="list");if(g?.kind==="text"&&ur(g.text,u)&&w.length>0){let v=Math.max(0,(m[d].list?.ilvl??0)-p),I=w[0].level;h=[{level:v,markerType:f,text:m[d].text},...w.map(P=>({level:qr(P,v,I),markerType:P.markerType||f,text:P.text}))]}else if(l.items.every(v=>v.kind==="list")){let v=Math.max(0,(m[d].list?.ilvl??0)-p),I=l.items[0].level;h=l.items.map(P=>({level:qr(P,v,I),markerType:P.markerType||f,text:P.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let x=h.map(v=>fa(v.level,v.markerType,v.text)),N=b.slice(0,d).concat(x).concat(b.slice(d+1)),T=b.join(`
164
166
  `),y=N.join(`
165
- `);return y===T?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:T,modifiedText:y})}function xc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
166
- `))return null;let a=tt(e);if(!a)return null;let s=ua(i);if(!s.hasListMarkers||s.items.length<2)return null;let l=U(r.currentParagraphText||ce(e)),c=s.items.filter(d=>d.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,a.ilvl),m=wc(s.items,l,f,c);return!m||m.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(gc(s.items,l,f)&&(m=hc(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 fr(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
167
- `),n=[];for(let a of r){if(!a.trim())continue;let s=Jt(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 to(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function Nc(e,t,r){let n=new Map,o=[];for(let i of e){let a=Math.max(0,Number(i?.level)||0);for(let c of Array.from(n.keys()))c>a&&n.delete(c);let s=(n.get(a)||0)+1;n.set(a,s);let l=yc(s,t,r),u=" ".repeat(a*4);o.push(`${u}${l} ${i.text||""}`.trimEnd())}return o.join(`
168
- `)}function vc(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(),u=null,c=Be(l,{allowZeroSpaceAfterMarker:!0});return c&&(u=c[2].trim()||null,l=Ue(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:u}})}function yc(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${ma(e,!1)}.`;case"upperAlpha":return`${ma(e,!0)}.`;case"lowerRoman":return`${da(e,!1)}.`;case"upperRoman":return`${da(e,!0)}.`;default:return`${e}.`}}function ma(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 da(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 Zr(e){let t=String(e||"");if(!t.trim()||t.includes(`
169
- `))return null;let r=fr(t);if(!r||!to(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"?Yt(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:i,startAt:Sc(o,i),contentText:String(n.text||"").trim(),normalizedContent:U(String(n.text||""))}}function Tc(e){let t=Zr(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function Sc(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 Ec(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 Ic(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 Ac(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function Ft(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 Pc(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 u=l.ownerDocument;if(!u)continue;let c=Ft(l,"pPr");if(c||(c=C(u,"w:pPr"),l.insertBefore(c,l.firstChild)),o){let p=Ft(c,"pPrChange");p&&c.removeChild(p)}if(i){let p=Ft(c,"listPr");p&&c.removeChild(p)}let f=Ft(c,"numPr");f||(f=C(u,"w:numPr"),c.appendChild(f));let m=Ft(f,"ilvl");m||(m=C(u,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=Ft(f,"numId");d||(d=C(u,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function Rc(e){let t=W(e,"application/xml").doc;return!t||ne(t)?null:Se(t)[0]||null}function Cc(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function Oc(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function $t(e,t){let r=Oc(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function pa(e,t){e.setAttribute("w:val",String(t))}function kc(e){let t=W(e,"application/xml").doc;if(!t||ne(t))return null;let o=Se(t)[0]||null;if(!o)return null;let i=Array.from(o.getElementsByTagNameNS("*","numId"));for(let a of i){let s=$t(a,["w:val","val"]);if(s!=null)return String(s)}return null}function Mc(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=fe(),a=W(e,"application/xml").doc;if(!a||ne(a))return e;let u=Array.from(a.getElementsByTagNameNS("*","num")).find(p=>{let b=$t(p,["w:numId","numId"]);return b!=null&&String(b)===String(t)});if(!u)return e;let c=Array.from(u.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=$t(c,["w:val","val"]),m=Array.from(u.getElementsByTagNameNS("*","lvlOverride")).find(p=>$t(p,["w:ilvl","ilvl"])===0)||null;m||(m=C(a,"w:lvlOverride"),m.setAttribute("w:ilvl","0"),u.appendChild(m));let d=Array.from(m.getElementsByTagNameNS("*","startOverride"))[0]||null;if(d||(d=C(a,"w:startOverride"),m.appendChild(d)),pa(d,r),o&&f!=null){let b=Array.from(a.getElementsByTagNameNS("*","abstractNum")).find(h=>{let g=$t(h,["w:abstractNumId","abstractNumId"]);return g!=null&&g===f})||null;if(b){let h=Array.from(b.getElementsByTagNameNS("*","lvl")).find(w=>$t(w,["w:ilvl","ilvl"])===0)||null;h||(h=C(a,"w:lvl"),h.setAttribute("w:ilvl","0"),b.appendChild(h));let g=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;g||(g=C(a,"w:start"),h.insertBefore(g,h.firstChild)),pa(g,r)}}return i.serializeToString(a)}function ro(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=Rc(t);if(!i)return null;let a=tt(i);if(a&&!o)return null;let s=Ie(n).cleanText||n,l=Zr(n)||Zr(s);if(!l)return null;let u=Zr(r),c=U(r)===U(s),f=!!u&&u.type===l.type&&u.normalizedContent===l.normalizedContent;return!c&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!a,startAt:l.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,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await Ct({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=Cc(i),s=kc(a),l=Mc(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),u=o?.isValid!==!1;return!a||!u?{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 _c=new Set(["ins","del","rPrChange","pPrChange"]),Lc=/^\d{4}-\d{2}-\d{2}T/;function ct(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function yt(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>ct(r)===t)}function Tt(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function Bc(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function Fc(e){return ct(e.parentNode)==="rPr"}function $c(e){let t=r=>{let n=Eo(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="${S}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function Xc(e){let t=[],r=(c,f,m)=>t.push({code:c,severity:f,message:m});if(typeof e!="string"||e.trim()==="")return r("PARSE_ERROR","error","Input is not a non-empty OOXML string."),{valid:!1,issues:t};let{doc:n,error:o}=$c(e);if(!n)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${o}`),{valid:!1,issues:t};let i=yt(n,"ins"),a=yt(n,"del"),s=i.concat(a);for(let c of yt(n,"p")){let f=Array.from(c.getElementsByTagName("*")).find(m=>m!==c&&ct(m)==="p");f&&r("NESTED_PARAGRAPH","error",`<${c.nodeName}> contains nested <${f.nodeName}>.`)}for(let c of yt(n,"body")){let f=Array.from(c.childNodes||[]).filter(d=>d.nodeType===1),m=f.map((d,p)=>ct(d)==="sectPr"?p:-1).filter(d=>d>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==f.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let c of s){let m=Array.from(c.getElementsByTagName("*")).filter(d=>d!==c&&["ins","del"].includes(ct(d))).find(d=>ct(c)!=="ins"||ct(d)!=="del"?!0:d.parentNode!==c);m&&r("NESTED_REVISION","error",`<${c.nodeName}> (w:id="${Tt(c,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let c of a)yt(c,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${Tt(c,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let c of s){let f=[];Tt(c,"id")||f.push("w:id"),Tt(c,"author")||f.push("w:author"),Lc.test(Tt(c,"date"))||f.push("w:date"),f.length>0&&r("MISSING_REVISION_METADATA","error",`<${c.nodeName}> is missing or has malformed ${f.join(", ")}.`)}let l=new Set;for(let c of Array.from(n.getElementsByTagName("*"))){if(!_c.has(ct(c)))continue;let f=Tt(c,"id");f&&(l.has(f)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${f} appears more than once.`),l.add(f))}let u=yt(n,"t").concat(yt(n,"delText"));for(let c of u){let f=c.textContent||"";/^\s|\s$/.test(f)&&Bc(c)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${c.nodeName}> has boundary whitespace without xml:space="preserve".`),f===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${c.nodeName}> is empty.`)}for(let c of s){if(Fc(c))continue;Array.from(c.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${c.nodeName}> (w:id="${Tt(c,"id")}") wraps no content.`)}return{valid:!t.some(c=>c.severity==="error"),issues:t}}function en(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Ce&&r.localName===t):[]}function Dc(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function zc(e){let t=en(e,"tr"),r=t.map(o=>en(o,"tc").map(a=>{let s=en(a,"p");return s.length===0?U(ce(a)):s.map(u=>U(ce(u))).filter(Boolean).join(`
170
- `)})),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 Wc(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=>Dc(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
171
- `)}function Uc(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>U(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function ga(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 jc(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ce;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!==Ce||i.localName!=="p"){i=s;continue}let l=String(n(i)||"").trim();if(!l){if(o.length>1)break;i=s;continue}if(!ga(l))break;o.push(i),i=s}return o.length>1?o:null}function Hc(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},i=String(t||"");if(!i.includes(`
172
- `)||Qn(i))return null;let a=i.split(/\r?\n/g).map(N=>N.trim()).filter(Boolean);if(a.length<2)return null;let s=r.tableElement||Bt(e,"tbl"),l=Bt(e,"tr"),u=Bt(e,"tc");if(!s||!l||!u)return null;let c=U(r.currentParagraphText||ce(e)),f=U(a[0]);if(c&&f&&f!==c)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}=zc(s);if(m.length===0||p===0)return null;let b=d.indexOf(l),g=en(l,"tc").indexOf(u);if(b<0||g<0||g>=p)return null;m[b][g]=a[0];let w=Uc(m[b]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let N=1;N<a.length;N++){let T=b+N,y=a[N];if(T<m.length&&!U(m[T][g]))if(w)for(let v=0;v<p;v++)U(m[T][v])||(m[T][v]=y);else m[T][g]=y;else{let v=new Array(p).fill("");if(w)for(let E=0;E<p;E++)v[E]=y;else v[g]=y;m.splice(Math.min(T,m.length),0,v)}}let x=Wc(m,p);return x?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),x):null}function Xt(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 Dt(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 Vc(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 c=et(e),f=Array.from(c.getElementsByTagNameNS("*","abstractNum")),m=Array.from(c.getElementsByTagNameNS("*","num"));for(let d of f){let p=Xt(d,["w:abstractNumId","abstractNumId"]);p!=null&&i.add(p)}for(let d of m){let p=Xt(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),u=Math.max(r,s+1);return{nextNumId:Dt(l,o,n),nextAbstractNumId:Dt(u,i,n),usedNumIds:o,usedAbstractNumIds:i,minId:r,maxPreferred:n}}function Gc(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=Dt(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=Dt(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function dr(e,t="num"){let r=Gc(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=Dt(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=Dt(o+1,r.usedNumIds,r.maxPreferred)),o)}function Kc(e){let t=dr(e,"num"),r=dr(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function no(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function tn(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Ce&&e.localName===t)}function ha(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(i=>i&&i.nodeType===1&&i.namespaceURI===Ce),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 Yc(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function mr(e,t){let r=Yc(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function wa(e,t,r){e?.setAttribute?.(t,String(r))}function oo(e,t){e?.setAttribute?.("w:val",String(t))}function Jc(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)oo(o,t)}}function qc(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=mr(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function Zc(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 u=Array.from({length:l+1},(f,m)=>`%${m+1}`).join(".")+".",c=720*(l+1);return`
167
+ `);return y===T?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:s,originalText:T,modifiedText:y})}function Tc(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=da(i);if(!s.hasListMarkers||s.items.length<2)return null;let l=j(r.currentParagraphText||ce(e)),c=s.items.filter(d=>d.kind==="list")[0]?.markerType||"bullet",f=Math.max(0,a.ilvl),m=vc(s.items,l,f,c);return!m||m.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(xc(s.items,l,f)&&(m=Nc(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 fr(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=Jt(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 to(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function Sc(e,t,r){let n=new Map,o=[];for(let i of e){let a=Math.max(0,Number(i?.level)||0);for(let c of Array.from(n.keys()))c>a&&n.delete(c);let s=(n.get(a)||0)+1;n.set(a,s);let l=Ic(s,t,r),u=" ".repeat(a*4);o.push(`${u}${l} ${i.text||""}`.trimEnd())}return o.join(`
170
+ `)}function Ec(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(),u=null,c=Be(l,{allowZeroSpaceAfterMarker:!0});return c&&(u=c[2].trim()||null,l=Ue(l,{allowZeroSpaceAfterMarker:!0})),{text:l.trim(),level:s,removedMarker:u}})}function Ic(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${ga(e,!1)}.`;case"upperAlpha":return`${ga(e,!0)}.`;case"lowerRoman":return`${ha(e,!1)}.`;case"upperRoman":return`${ha(e,!0)}.`;default:return`${e}.`}}function ga(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 ha(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 Zr(e){let t=String(e||"");if(!t.trim()||t.includes(`
171
+ `))return null;let r=fr(t);if(!r||!to(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"?Yt(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:i,startAt:Pc(o,i),contentText:String(n.text||"").trim(),normalizedContent:j(String(n.text||""))}}function Ac(e){let t=Zr(e);return t?String(t.contentText||"").trim():String(e||"").trim()}function Pc(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 Rc(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 Cc(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 Oc(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function Ft(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 kc(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 u=l.ownerDocument;if(!u)continue;let c=Ft(l,"pPr");if(c||(c=C(u,"w:pPr"),l.insertBefore(c,l.firstChild)),o){let p=Ft(c,"pPrChange");p&&c.removeChild(p)}if(i){let p=Ft(c,"listPr");p&&c.removeChild(p)}let f=Ft(c,"numPr");f||(f=C(u,"w:numPr"),c.appendChild(f));let m=Ft(f,"ilvl");m||(m=C(u,"w:ilvl"),f.appendChild(m)),m.setAttribute("w:val",String(n));let d=Ft(f,"numId");d||(d=C(u,"w:numId"),f.appendChild(d)),d.setAttribute("w:val",String(r)),s++}return s}function Mc(e){let t=U(e,"application/xml").doc;return!t||ne(t)?null:Se(t)[0]||null}function _c(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function Lc(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function $t(e,t){let r=Lc(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function wa(e,t){e.setAttribute("w:val",String(t))}function Bc(e){let t=U(e,"application/xml").doc;if(!t||ne(t))return null;let o=Se(t)[0]||null;if(!o)return null;let i=Array.from(o.getElementsByTagNameNS("*","numId"));for(let a of i){let s=$t(a,["w:val","val"]);if(s!=null)return String(s)}return null}function Fc(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,i=me(),a=U(e,"application/xml").doc;if(!a||ne(a))return e;let u=Array.from(a.getElementsByTagNameNS("*","num")).find(p=>{let b=$t(p,["w:numId","numId"]);return b!=null&&String(b)===String(t)});if(!u)return e;let c=Array.from(u.getElementsByTagNameNS("*","abstractNumId"))[0]||null,f=$t(c,["w:val","val"]),m=Array.from(u.getElementsByTagNameNS("*","lvlOverride")).find(p=>$t(p,["w:ilvl","ilvl"])===0)||null;m||(m=C(a,"w:lvlOverride"),m.setAttribute("w:ilvl","0"),u.appendChild(m));let d=Array.from(m.getElementsByTagNameNS("*","startOverride"))[0]||null;if(d||(d=C(a,"w:startOverride"),m.appendChild(d)),wa(d,r),o&&f!=null){let b=Array.from(a.getElementsByTagNameNS("*","abstractNum")).find(h=>{let g=$t(h,["w:abstractNumId","abstractNumId"]);return g!=null&&g===f})||null;if(b){let h=Array.from(b.getElementsByTagNameNS("*","lvl")).find(w=>$t(w,["w:ilvl","ilvl"])===0)||null;h||(h=C(a,"w:lvl"),h.setAttribute("w:ilvl","0"),b.appendChild(h));let g=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;g||(g=C(a,"w:start"),h.insertBefore(g,h.firstChild)),wa(g,r)}}return i.serializeToString(a)}function ro(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=Mc(t);if(!i)return null;let a=tt(i);if(a&&!o)return null;let s=Ie(n).cleanText||n,l=Zr(n)||Zr(s);if(!l)return null;let u=Zr(r),c=j(r)===j(s),f=!!u&&u.type===l.type&&u.normalizedContent===l.normalizedContent;return!c&&!f?null:{listInput:`${l.marker} ${l.contentText}`.trim(),numberingKey:`${l.type}:${l.numberingStyle}:single`,originalText:r,wasListParagraph:!!a,startAt:l.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,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await Ct({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=_c(i),s=Bc(a),l=Fc(o?.numberingXml||null,s,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),u=o?.isValid!==!1;return!a||!u?{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 $c=new Set(["ins","del","rPrChange","pPrChange"]),Xc=/^\d{4}-\d{2}-\d{2}T/;function ct(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function yt(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>ct(r)===t)}function Tt(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function Dc(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function zc(e){return ct(e.parentNode)==="rPr"}function Wc(e){let t=r=>{let n=Eo(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="${S}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function Uc(e){let t=[],r=(c,f,m)=>t.push({code:c,severity:f,message:m});if(typeof e!="string"||e.trim()==="")return r("PARSE_ERROR","error","Input is not a non-empty OOXML string."),{valid:!1,issues:t};let{doc:n,error:o}=Wc(e);if(!n)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${o}`),{valid:!1,issues:t};let i=yt(n,"ins"),a=yt(n,"del"),s=i.concat(a);for(let c of yt(n,"p")){let f=Array.from(c.getElementsByTagName("*")).find(m=>m!==c&&ct(m)==="p");f&&r("NESTED_PARAGRAPH","error",`<${c.nodeName}> contains nested <${f.nodeName}>.`)}for(let c of yt(n,"body")){let f=Array.from(c.childNodes||[]).filter(d=>d.nodeType===1),m=f.map((d,p)=>ct(d)==="sectPr"?p:-1).filter(d=>d>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==f.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let c of s){let m=Array.from(c.getElementsByTagName("*")).filter(d=>d!==c&&["ins","del"].includes(ct(d))).find(d=>ct(c)!=="ins"||ct(d)!=="del"?!0:d.parentNode!==c);m&&r("NESTED_REVISION","error",`<${c.nodeName}> (w:id="${Tt(c,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let c of a)yt(c,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${Tt(c,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let c of s){let f=[];Tt(c,"id")||f.push("w:id"),Tt(c,"author")||f.push("w:author"),Xc.test(Tt(c,"date"))||f.push("w:date"),f.length>0&&r("MISSING_REVISION_METADATA","error",`<${c.nodeName}> is missing or has malformed ${f.join(", ")}.`)}let l=new Set;for(let c of Array.from(n.getElementsByTagName("*"))){if(!$c.has(ct(c)))continue;let f=Tt(c,"id");f&&(l.has(f)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${f} appears more than once.`),l.add(f))}let u=yt(n,"t").concat(yt(n,"delText"));for(let c of u){let f=c.textContent||"";/^\s|\s$/.test(f)&&Dc(c)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${c.nodeName}> has boundary whitespace without xml:space="preserve".`),f===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${c.nodeName}> is empty.`)}for(let c of s){if(zc(c))continue;Array.from(c.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${c.nodeName}> (w:id="${Tt(c,"id")}") wraps no content.`)}return{valid:!t.some(c=>c.severity==="error"),issues:t}}function en(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===Ce&&r.localName===t):[]}function jc(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Hc(e){let t=en(e,"tr"),r=t.map(o=>en(o,"tc").map(a=>{let s=en(a,"p");return s.length===0?j(ce(a)):s.map(u=>j(ce(u))).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 Vc(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=>jc(l)).join(" | ")} |`;return[a(n),a(o),...i.map(a)].join(`
173
+ `)}function Gc(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>j(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function ba(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 Kc(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:ce;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!==Ce||i.localName!=="p"){i=s;continue}let l=String(n(i)||"").trim();if(!l){if(o.length>1)break;i=s;continue}if(!ba(l))break;o.push(i),i=s}return o.length>1?o:null}function Yc(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
+ `)||Qn(i))return null;let a=i.split(/\r?\n/g).map(N=>N.trim()).filter(Boolean);if(a.length<2)return null;let s=r.tableElement||Bt(e,"tbl"),l=Bt(e,"tr"),u=Bt(e,"tc");if(!s||!l||!u)return null;let c=j(r.currentParagraphText||ce(e)),f=j(a[0]);if(c&&f&&f!==c)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}=Hc(s);if(m.length===0||p===0)return null;let b=d.indexOf(l),g=en(l,"tc").indexOf(u);if(b<0||g<0||g>=p)return null;m[b][g]=a[0];let w=Gc(m[b]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let N=1;N<a.length;N++){let T=b+N,y=a[N];if(T<m.length&&!j(m[T][g]))if(w)for(let v=0;v<p;v++)j(m[T][v])||(m[T][v]=y);else m[T][g]=y;else{let v=new Array(p).fill("");if(w)for(let I=0;I<p;I++)v[I]=y;else v[g]=y;m.splice(Math.min(T,m.length),0,v)}}let x=Vc(m,p);return x?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),x):null}function Xt(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 Dt(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 Jc(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 c=et(e),f=Array.from(c.getElementsByTagNameNS("*","abstractNum")),m=Array.from(c.getElementsByTagNameNS("*","num"));for(let d of f){let p=Xt(d,["w:abstractNumId","abstractNumId"]);p!=null&&i.add(p)}for(let d of m){let p=Xt(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),u=Math.max(r,s+1);return{nextNumId:Dt(l,o,n),nextAbstractNumId:Dt(u,i,n),usedNumIds:o,usedAbstractNumIds:i,minId:r,maxPreferred:n}}function qc(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=Dt(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=Dt(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function dr(e,t="num"){let r=qc(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=Dt(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=Dt(o+1,r.usedNumIds,r.maxPreferred)),o)}function Zc(e){let t=dr(e,"num"),r=dr(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function no(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function tn(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===Ce&&e.localName===t)}function xa(e,t,r){if(!e||!t)return;let n=Array.from(e.childNodes||[]).filter(i=>i&&i.nodeType===1&&i.namespaceURI===Ce),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 Qc(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function mr(e,t){let r=Qc(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Na(e,t,r){e?.setAttribute?.(t,String(r))}function oo(e,t){e?.setAttribute?.("w:val",String(t))}function eu(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)oo(o,t)}}function tu(e){for(let t of e||[]){let r=Array.from(t?.getElementsByTagNameNS?.("*","numId")||[]);for(let n of r){let o=mr(n,["w:val","val"]);if(o!=null)return String(o)}}return null}function ru(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 u=Array.from({length:l+1},(f,m)=>`%${m+1}`).join(".")+".",c=720*(l+1);return`
173
175
  <w:lvl w:ilvl="${l}">
174
176
  <w:start w:val="1"/>
175
177
  <w:numFmt w:val="decimal"/>
@@ -188,25 +190,25 @@ var Ja=Object.create;var To=Object.defineProperty;var qa=Object.getOwnPropertyDe
188
190
  <w:startOverride w:val="${i}"/>
189
191
  </w:lvlOverride>
190
192
  </w:num>
191
- </w:numbering>`.trim()}function Qc(e,t,r){let n=et(e);if(no(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(u=>u?.cloneNode?u.cloneNode(!0):u):[]};let o=new Map,i=new Map,a=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let u of a){let c=mr(u,["w:abstractNumId","abstractNumId"]);if(c==null)continue;let f=dr(r,"abstract");f!=null&&(o.set(c,f),wa(u,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let u of s){let c=mr(u,["w:numId","numId"]);if(c==null)continue;let f=dr(r,"num");if(f==null)continue;i.set(c,f),wa(u,"w:numId",f);let m=Array.from(u.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(m){let d=mr(m,["w:val","val"]);d!=null&&o.has(d)&&oo(m,o.get(d))}}let l=Array.isArray(t)?t.map(u=>u?.cloneNode?u.cloneNode(!0):u):[];for(let u of l){let c=Array.from(u?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of c){let m=mr(f,["w:val","val"]);m!=null&&i.has(m)&&oo(f,i.get(m))}}return{numberingXml:Nt(n),replacementNodes:l}}function eu(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(no(o)||no(i))return r;let a=o.documentElement,s=i.documentElement;if(!a||!s)return r;let l=new Set(Array.from(a.childNodes||[]).filter(c=>tn(c,"abstractNum")).map(c=>Xt(c,["w:abstractNumId","abstractNumId"])).filter(c=>c!=null)),u=new Set(Array.from(a.childNodes||[]).filter(c=>tn(c,"num")).map(c=>Xt(c,["w:numId","numId"])).filter(c=>c!=null));for(let c of Array.from(s.childNodes||[])){if(!tn(c,"abstractNum"))continue;let f=Xt(c,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(ha(a,o.importNode(c,!0),"abstract"),l.add(f))}for(let c of Array.from(s.childNodes||[])){if(!tn(c,"num"))continue;let f=Xt(c,["w:numId","numId"]);f==null||u.has(f)||(ha(a,o.importNode(c,!0),"num"),u.add(f))}return Nt(o)}catch{return r}}function tu(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!ne(e)}function ba(e){let t=W(e,"application/xml");return t.error||tu(t.doc)?{...t,doc:null}:t}function xa(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(S,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function io(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===S&&n.localName===t)return n;return null}function ut(e,t){return Array.from(e?.getElementsByTagNameNS?.(S,t)||[])}function pr(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function ru(e){let t=io(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=ut(t,"rStyle")[0]||null,n=pr(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),i=n.includes("italic")||n.includes("emphasis");return{bold:ut(t,"b").length>0||o,italic:ut(t,"i").length>0||i}}function Na(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(S,"r")||[]);for(let n of r){if(!ht(n,e,"accepted"))continue;let o=wt(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...ru(n)})}return t}function ao(e){return String(e||"").replace(/\r/g,"").split(`
193
+ </w:numbering>`.trim()}function nu(e,t,r){let n=et(e);if(no(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(u=>u?.cloneNode?u.cloneNode(!0):u):[]};let o=new Map,i=new Map,a=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let u of a){let c=mr(u,["w:abstractNumId","abstractNumId"]);if(c==null)continue;let f=dr(r,"abstract");f!=null&&(o.set(c,f),Na(u,"w:abstractNumId",f))}let s=Array.from(n.getElementsByTagNameNS("*","num"));for(let u of s){let c=mr(u,["w:numId","numId"]);if(c==null)continue;let f=dr(r,"num");if(f==null)continue;i.set(c,f),Na(u,"w:numId",f);let m=Array.from(u.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(m){let d=mr(m,["w:val","val"]);d!=null&&o.has(d)&&oo(m,o.get(d))}}let l=Array.isArray(t)?t.map(u=>u?.cloneNode?u.cloneNode(!0):u):[];for(let u of l){let c=Array.from(u?.getElementsByTagNameNS?.("*","numId")||[]);for(let f of c){let m=mr(f,["w:val","val"]);m!=null&&i.has(m)&&oo(f,i.get(m))}}return{numberingXml:Nt(n),replacementNodes:l}}function ou(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(no(o)||no(i))return r;let a=o.documentElement,s=i.documentElement;if(!a||!s)return r;let l=new Set(Array.from(a.childNodes||[]).filter(c=>tn(c,"abstractNum")).map(c=>Xt(c,["w:abstractNumId","abstractNumId"])).filter(c=>c!=null)),u=new Set(Array.from(a.childNodes||[]).filter(c=>tn(c,"num")).map(c=>Xt(c,["w:numId","numId"])).filter(c=>c!=null));for(let c of Array.from(s.childNodes||[])){if(!tn(c,"abstractNum"))continue;let f=Xt(c,["w:abstractNumId","abstractNumId"]);f==null||l.has(f)||(xa(a,o.importNode(c,!0),"abstract"),l.add(f))}for(let c of Array.from(s.childNodes||[])){if(!tn(c,"num"))continue;let f=Xt(c,["w:numId","numId"]);f==null||u.has(f)||(xa(a,o.importNode(c,!0),"num"),u.add(f))}return Nt(o)}catch{return r}}function iu(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!ne(e)}function va(e){let t=U(e,"application/xml");return t.error||iu(t.doc)?{...t,doc:null}:t}function ya(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(S,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function io(e,t){let r=Array.from(e?.childNodes||[]);for(let n of r)if(n?.nodeType===1&&n.namespaceURI===S&&n.localName===t)return n;return null}function ut(e,t){return Array.from(e?.getElementsByTagNameNS?.(S,t)||[])}function pr(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function au(e){let t=io(e,"rPr");if(!t)return{bold:!1,italic:!1};let r=ut(t,"rStyle")[0]||null,n=pr(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),i=n.includes("italic")||n.includes("emphasis");return{bold:ut(t,"b").length>0||o,italic:ut(t,"i").length>0||i}}function Ta(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(S,"r")||[]);for(let n of r){if(!ht(n,e,"accepted"))continue;let o=wt(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...au(n)})}return t}function ao(e){return String(e||"").replace(/\r/g,"").split(`
192
194
  `).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
193
- `).trim()}function nu(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 ou(e){let t=io(e,"pPr");if(!t)return null;let r=ut(t,"pStyle")[0]||null,n=pr(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=ut(t,"outlineLvl")[0]||null,i=pr(o,["w:val","val"]),a=Number.parseInt(i,10);return Number.isInteger(a)&&a>=0?Math.min(a+1,6):null}function iu(e){let t=io(e,"pPr");if(!t)return null;let r=ut(t,"numPr")[0]||null;if(!r)return null;let n=ut(r,"ilvl")[0]||null,o=ut(r,"numId")[0]||null,i=Number.parseInt(pr(n,["w:val","val"]),10),a=pr(o,["w:val","val"]);return{level:Number.isInteger(i)&&i>=0?i:0,marker:a==="1"?"-":"1."}}function au(e){let t=Na(e).map(r=>r.text).join("");return ao(t)}function su(e){let r=Na(e).map(a=>nu(a.text,a)).join(""),n=ao(r);if(!n)return"";let o=ou(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let i=iu(e);return i?`${" ".repeat(i.level)}${i.marker} ${n}`:n}function lu(e){return va(e).text}function va(e){let t=ba(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:ao(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(au).join(`
195
+ `).trim()}function su(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 lu(e){let t=io(e,"pPr");if(!t)return null;let r=ut(t,"pStyle")[0]||null,n=pr(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=ut(t,"outlineLvl")[0]||null,i=pr(o,["w:val","val"]),a=Number.parseInt(i,10);return Number.isInteger(a)&&a>=0?Math.min(a+1,6):null}function cu(e){let t=io(e,"pPr");if(!t)return null;let r=ut(t,"numPr")[0]||null;if(!r)return null;let n=ut(r,"ilvl")[0]||null,o=ut(r,"numId")[0]||null,i=Number.parseInt(pr(n,["w:val","val"]),10),a=pr(o,["w:val","val"]);return{level:Number.isInteger(i)&&i>=0?i:0,marker:a==="1"?"-":"1."}}function uu(e){let t=Ta(e).map(r=>r.text).join("");return ao(t)}function fu(e){let r=Ta(e).map(a=>su(a.text,a)).join(""),n=ao(r);if(!n)return"";let o=lu(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let i=cu(e);return i?`${" ".repeat(i.level)}${i.marker} ${n}`:n}function mu(e){return Sa(e).text}function Sa(e){let t=va(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=ya(r);return n.length===0?{text:ao(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(uu).join(`
194
196
 
195
- `).trim(),status:"ok",warnings:t.warnings}}function cu(e){return ya(e).text}function ya(e){let t=ba(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(su).join(`
197
+ `).trim(),status:"ok",warnings:t.warnings}}function du(e){return Ea(e).text}function Ea(e){let t=va(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=ya(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(fu).join(`
196
198
 
197
- `).trim(),status:"ok",warnings:t.warnings}}var zt=new TextEncoder;function Ta(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=zt.encode("docx-redline-revision-token\0"),n=1,o=zt.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 b=Ta(String(d));if(a.has(b))throw new Error(`Duplicate normalized entry path detected: "${b}"`);a.add(b);let h;typeof p=="string"?h=zt.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),i.push({name:b,nameBytes:zt.encode(b),payloadBytes:h})}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 u=new Uint8Array(l),c=new DataView(u.buffer,u.byteOffset,u.byteLength),f=0;u.set(r,f),f+=r.length,c.setUint32(f,n,!1),f+=4,c.setUint32(f,o.length,!1),f+=4,u.set(o,f),f+=o.length,c.setUint32(f,i.length,!1),f+=4;for(let m of i)c.setUint32(f,m.nameBytes.length,!1),f+=4,u.set(m.nameBytes,f),f+=m.nameBytes.length,c.setUint32(f,m.payloadBytes.length,!1),f+=4,u.set(m.payloadBytes,f),f+=m.payloadBytes.length;return{framing:u,scope:e,version:n,coveredParts:i.map(m=>m.name)}}async function Sa({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(u=>u.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 lo({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 rn(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=rn(e);return Sa({scope:"document-parts",entries:r,digestFn:t.digestFn})}function fu(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 mu(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=zt.encode(r),i=zt.encode(n),a=0;for(let s=0;s<o.length;s++)a|=o[s]^i[s];return a===0}var Y=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",ze=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(S,t)||[]),pe=(e,t)=>ze(e,t)[0]||null;function du(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===S))return!0;r=r.parentNode}return!1}function nn(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=W(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 pu(e){let t=pe(pe(e,"pPr"),"numPr");if(!t)return null;let r=Y(pe(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(Y(pe(t,"ilvl"),"val")||"0",10)||0}}function gu(e){let t=new Map;for(let n of ze(e,"abstractNum")){let o=new Map;for(let i of ze(n,"lvl")){let a=Number.parseInt(Y(i,"ilvl")||"0",10)||0;o.set(a,{start:Number.parseInt(Y(pe(i,"start"),"val")||"1",10)||1,format:Y(pe(i,"numFmt"),"val")||"decimal",text:Y(pe(i,"lvlText"),"val")||`%${a+1}.`})}t.set(Y(n,"abstractNumId"),o)}let r=new Map;for(let n of ze(e,"num")){let o=Y(pe(n,"abstractNumId"),"val"),i=new Map(t.get(o)||[]);for(let a of ze(n,"lvlOverride")){let s=Number.parseInt(Y(a,"ilvl")||"0",10)||0,l=pe(a,"lvl"),u={...i.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(u.start=Number.parseInt(Y(pe(l,"start"),"val")||String(u.start),10)||u.start,u.format=Y(pe(l,"numFmt"),"val")||u.format,u.text=Y(pe(l,"lvlText"),"val")||u.text);let c=pe(a,"startOverride");c&&(u.start=Number.parseInt(Y(c,"val")||String(u.start),10)||u.start),i.set(s,u)}r.set(Y(n,"numId"),i)}return r}function Ea(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 Ia(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 hu(e,t){return t==="lowerLetter"?Ea(e,!1):t==="upperLetter"?Ea(e,!0):t==="lowerRoman"?Ia(e).toLowerCase():t==="upperRoman"?Ia(e):String(e)}function wu(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,u)=>{let c=Number(u)-1,f=o.get(c)||a;return hu(i[c]??f.start,f.format)});return{...n,label:s,format:a.format}}}function bu(e){let t=pe(e,"pPr"),n=Y(pe(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(Y(pe(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function xu(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let u of ze(e,s))r.push({type:l,id:Y(u,"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(S,"tbl")).indexOf(i)+1,rowIndex:Array.from(i.getElementsByTagNameNS(S,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(S,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Nu(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of ze(e,r))Y(n,"author")&&t.add(Y(n,"author"));return[...t].sort()}function vu(e){let t=new Map;for(let r of ze(e,"comment")){let n=ze(r,"p");t.set(Y(r,"id"),{id:Y(r,"id"),author:Y(r,"author")||null,date:Y(r,"date")||null,text:n.map(o=>Te(o)).join(`
198
- `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function yu(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 Tu(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 u=l.localName;if(!(t==="accepted"&&(u==="del"||u==="moveFrom")||t==="rejected"&&(u==="ins"||u==="moveTo")))if(u==="commentRangeStart")r.set(Y(l,"id"),{text:""});else if(u==="commentRangeEnd"){let c=Y(l,"id");r.has(c)&&(n.set(c,r.get(c).text),r.delete(c))}else u==="r"?i(wt(l,{revisionView:t,boundary:o})):a(l)}};return e.forEach((s,l)=>{o=s,a(s),l<e.length-1&&r.size&&i(`
199
- `)}),n}function Su(e,t={}){let r=nn(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=nn(e?.commentsXml,"word/comments.xml"),o=nn(e?.commentsExtendedXml,"word/commentsExtended.xml"),i=nn(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=vu(n.doc);yu(s,o.doc);let l=wu(i.doc),u=null,c=Se(r.doc),f=Tu(c,t.revisionView||"accepted"),m=c.map((g,w)=>{let x=Te(g,{revisionView:t.revisionView||"accepted"}),N=bu(g);N&&(u={level:N,text:x});let T=[...new Set([...ze(g,"commentRangeStart"),...ze(g,"commentReference")].map(H=>Y(H,"id")).filter(Boolean))],y=Nu(g),v=l(pu(g)),E=Y(pe(pe(g,"pPr"),"pStyle"),"val")||null,P=xu(g,x),B=w+1,L=v?.label&&v.format!=="bullet"?v.label:null,z=u?.text||null,j=[L,z,x.slice(0,t.excerptLength||120)].filter(Boolean).join(" \u2014 "),O=zr(g);return{index:B,ref:`P${B}`,paragraphId:vt(g),fingerprint:Lt(g),text:x,exactText:x,excerpt:x.slice(0,t.excerptLength||120),humanReference:j,inTable:du(g,"tc"),table:P.table,styleId:E,headingLevel:N,nearestHeading:u,list:v,structuralReferences:P.references,hasRevisions:y.length>0,revisionAuthors:y,commentIds:T,segments:O}});for(let g of m)for(let w of g.commentIds){let x=s.get(w)||{id:w,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=g.index),x.targetRef??(x.targetRef=g.ref),x.anchoredText??(x.anchoredText=f.get(w)||g.text),s.set(w,x)}if(t.revisedOnly&&(m=m.filter(g=>g.hasRevisions)),t.inTable!=null&&(m=m.filter(g=>g.inTable===!!t.inTable)),t.skipEmpty&&(m=m.filter(g=>g.text.length>0)),t.search){let g=String(t.search).toLowerCase();m=m.filter(w=>w.text.toLowerCase().includes(g))}if(Array.isArray(t.indexes)){let g=new Set(t.indexes);m=m.filter(w=>g.has(w.index))}if(t.range){let g=Number(t.range.start??t.range[0]),w=Number(t.range.end??t.range[1]);m=m.filter(x=>x.index>=g&&x.index<=w)}let d=[...new Set(m.flatMap(g=>g.revisionAuthors))].sort(),p=rn(e),b=p.map(g=>g.name).sort(),h=null;return typeof t.digestFn=="function"&&(h=lo({scope:"document-parts",entries:p,digestFn:t.digestFn})),{status:"ok",revisionToken:h,coveredParts:b,paragraphs:m,comments:[...s.values()],revisionAuthors:d,commentAuthors:[...new Set([...s.values()].map(g=>g.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:s.size,revisedParagraphs:m.filter(g=>g.hasRevisions).length},warnings:a}}var on="http://schemas.microsoft.com/office/word/2010/wordml",rt="http://schemas.microsoft.com/office/word/2012/wordml";function co(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 gr(e,t,r,n,o=co(e)){let i=t.split(" ").map(l=>l[0]).join("").toUpperCase()||"AI",a=xe(r),s=xe(t);return`<w:comment w:id="${e}" w:author="${s}" w:date="${n}" w:initials="${i}">
200
- <w:p w14:paraId="${xe(o)}" xmlns:w14="${on}">
199
+ `).trim(),status:"ok",warnings:t.warnings}}var zt=new TextEncoder;function Ia(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=zt.encode("docx-redline-revision-token\0"),n=1,o=zt.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 b=Ia(String(d));if(a.has(b))throw new Error(`Duplicate normalized entry path detected: "${b}"`);a.add(b);let h;typeof p=="string"?h=zt.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),i.push({name:b,nameBytes:zt.encode(b),payloadBytes:h})}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 u=new Uint8Array(l),c=new DataView(u.buffer,u.byteOffset,u.byteLength),f=0;u.set(r,f),f+=r.length,c.setUint32(f,n,!1),f+=4,c.setUint32(f,o.length,!1),f+=4,u.set(o,f),f+=o.length,c.setUint32(f,i.length,!1),f+=4;for(let m of i)c.setUint32(f,m.nameBytes.length,!1),f+=4,u.set(m.nameBytes,f),f+=m.nameBytes.length,c.setUint32(f,m.payloadBytes.length,!1),f+=4,u.set(m.payloadBytes,f),f+=m.payloadBytes.length;return{framing:u,scope:e,version:n,coveredParts:i.map(m=>m.name)}}async function Aa({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(u=>u.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 lo({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 rn(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 pu(e,t={}){let r=rn(e);return Aa({scope:"document-parts",entries:r,digestFn:t.digestFn})}function gu(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=zt.encode(r),i=zt.encode(n),a=0;for(let s=0;s<o.length;s++)a|=o[s]^i[s];return a===0}var Y=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",ze=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(S,t)||[]),pe=(e,t)=>ze(e,t)[0]||null;function wu(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===S))return!0;r=r.parentNode}return!1}function nn(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=U(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 bu(e){let t=pe(pe(e,"pPr"),"numPr");if(!t)return null;let r=Y(pe(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(Y(pe(t,"ilvl"),"val")||"0",10)||0}}function xu(e){let t=new Map;for(let n of ze(e,"abstractNum")){let o=new Map;for(let i of ze(n,"lvl")){let a=Number.parseInt(Y(i,"ilvl")||"0",10)||0;o.set(a,{start:Number.parseInt(Y(pe(i,"start"),"val")||"1",10)||1,format:Y(pe(i,"numFmt"),"val")||"decimal",text:Y(pe(i,"lvlText"),"val")||`%${a+1}.`})}t.set(Y(n,"abstractNumId"),o)}let r=new Map;for(let n of ze(e,"num")){let o=Y(pe(n,"abstractNumId"),"val"),i=new Map(t.get(o)||[]);for(let a of ze(n,"lvlOverride")){let s=Number.parseInt(Y(a,"ilvl")||"0",10)||0,l=pe(a,"lvl"),u={...i.get(s)||{start:1,format:"decimal",text:`%${s+1}.`}};l&&(u.start=Number.parseInt(Y(pe(l,"start"),"val")||String(u.start),10)||u.start,u.format=Y(pe(l,"numFmt"),"val")||u.format,u.text=Y(pe(l,"lvlText"),"val")||u.text);let c=pe(a,"startOverride");c&&(u.start=Number.parseInt(Y(c,"val")||String(u.start),10)||u.start),i.set(s,u)}r.set(Y(n,"numId"),i)}return r}function Pa(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 Ra(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 Nu(e,t){return t==="lowerLetter"?Pa(e,!1):t==="upperLetter"?Pa(e,!0):t==="lowerRoman"?Ra(e).toLowerCase():t==="upperRoman"?Ra(e):String(e)}function vu(e){let t=e?xu(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,u)=>{let c=Number(u)-1,f=o.get(c)||a;return Nu(i[c]??f.start,f.format)});return{...n,label:s,format:a.format}}}function yu(e){let t=pe(e,"pPr"),n=Y(pe(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(Y(pe(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function Tu(e,t){let r=[];for(let[s,l]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let u of ze(e,s))r.push({type:l,id:Y(u,"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(S,"tbl")).indexOf(i)+1,rowIndex:Array.from(i.getElementsByTagNameNS(S,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(S,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Su(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of ze(e,r))Y(n,"author")&&t.add(Y(n,"author"));return[...t].sort()}function Eu(e){let t=new Map;for(let r of ze(e,"comment")){let n=ze(r,"p");t.set(Y(r,"id"),{id:Y(r,"id"),author:Y(r,"author")||null,date:Y(r,"date")||null,text:n.map(o=>be(o)).join(`
200
+ `),paraId:n[0]?.getAttribute?.("w14:paraId")||n[0]?.getAttribute?.("paraId")||null})}return t}function Iu(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 Au(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 u=l.localName;if(!(t==="accepted"&&(u==="del"||u==="moveFrom")||t==="rejected"&&(u==="ins"||u==="moveTo")))if(u==="commentRangeStart")r.set(Y(l,"id"),{text:""});else if(u==="commentRangeEnd"){let c=Y(l,"id");r.has(c)&&(n.set(c,r.get(c).text),r.delete(c))}else u==="r"?i(wt(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 Pu(e,t={}){let r=nn(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=nn(e?.commentsXml,"word/comments.xml"),o=nn(e?.commentsExtendedXml,"word/commentsExtended.xml"),i=nn(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=Eu(n.doc);Iu(s,o.doc);let l=vu(i.doc),u=null,c=Se(r.doc),f=Au(c,t.revisionView||"accepted"),m=c.map((g,w)=>{let x=be(g,{revisionView:t.revisionView||"accepted"}),N=yu(g);N&&(u={level:N,text:x});let T=[...new Set([...ze(g,"commentRangeStart"),...ze(g,"commentReference")].map(W=>Y(W,"id")).filter(Boolean))],y=Su(g),v=l(bu(g)),I=Y(pe(pe(g,"pPr"),"pStyle"),"val")||null,P=Tu(g,x),B=w+1,L=v?.label&&v.format!=="bullet"?v.label:null,z=u?.text||null,V=[L,z,x.slice(0,t.excerptLength||120)].filter(Boolean).join(" \u2014 "),O=zr(g);return{index:B,ref:`P${B}`,paragraphId:vt(g),fingerprint:Lt(g),text:x,exactText:x,excerpt:x.slice(0,t.excerptLength||120),humanReference:V,inTable:wu(g,"tc"),table:P.table,styleId:I,headingLevel:N,nearestHeading:u,list:v,structuralReferences:P.references,hasRevisions:y.length>0,revisionAuthors:y,commentIds:T,segments:O}});for(let g of m)for(let w of g.commentIds){let x=s.get(w)||{id:w,author:null,date:null,text:""};x.paragraphIndex??(x.paragraphIndex=g.index),x.targetRef??(x.targetRef=g.ref),x.anchoredText??(x.anchoredText=f.get(w)||g.text),s.set(w,x)}if(t.revisedOnly&&(m=m.filter(g=>g.hasRevisions)),t.inTable!=null&&(m=m.filter(g=>g.inTable===!!t.inTable)),t.skipEmpty&&(m=m.filter(g=>g.text.length>0)),t.search){let g=String(t.search).toLowerCase();m=m.filter(w=>w.text.toLowerCase().includes(g))}if(Array.isArray(t.indexes)){let g=new Set(t.indexes);m=m.filter(w=>g.has(w.index))}if(t.range){let g=Number(t.range.start??t.range[0]),w=Number(t.range.end??t.range[1]);m=m.filter(x=>x.index>=g&&x.index<=w)}let d=[...new Set(m.flatMap(g=>g.revisionAuthors))].sort(),p=rn(e),b=p.map(g=>g.name).sort(),h=null;return typeof t.digestFn=="function"&&(h=lo({scope:"document-parts",entries:p,digestFn:t.digestFn})),{status:"ok",revisionToken:h,coveredParts:b,paragraphs:m,comments:[...s.values()],revisionAuthors:d,commentAuthors:[...new Set([...s.values()].map(g=>g.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:s.size,revisedParagraphs:m.filter(g=>g.hasRevisions).length},warnings:a}}var on="http://schemas.microsoft.com/office/word/2010/wordml",rt="http://schemas.microsoft.com/office/word/2012/wordml";function co(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 gr(e,t,r,n,o=co(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="${on}">
201
203
  <w:r><w:t>${a}</w:t></w:r>
202
204
  </w:p>
203
205
  </w:comment>`}function uo(e){if(!e||e.length===0)return`<w:comments xmlns:w="${S}"></w:comments>`;let t=e.map(r=>gr(r.id,r.author,r.content,r.date,r.paraId)).join(`
204
206
  `);return`<w:comments xmlns:w="${S}">
205
207
  ${t}
206
- </w:comments>`}function Aa(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${xe(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${xe(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${rt}">${t}</w15:commentsEx>`}function an(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Zt(e,"w:r"),o=[],i="";for(let a of n){if(!ht(a,e,r))continue;let s=i.length,l=wt(a,{revisionView:r,boundary:e});i+=l,o.push({run:a,start:s,end:i.length})}return{fullText:i,runOffsets:o}}function Pa(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 Ra(e){return String(e).replace(/[ \u00a0]/g," ")}function wr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Ca(e,t,r){let n=null,o=null,i=0,a=0;for(let{run:s,start:l,end:u}of e.runOffsets)t.start>=l&&t.start<u&&(n=s,i=t.start-l),t.end>l&&t.end<=u&&(o=s,a=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:i,endRun:o,endOffset:a}}function Oa(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 ka(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(Oa(n,["del"]))return{found:!1,error:wr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Oa(n,["moveFrom","moveTo"]))return{found:!1,error:wr("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function fo(e,t){let r=String(t??""),n=Pa(e.fullText,r);if(n.length>1)return{found:!1,error:wr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Ca(e,n[0],"exact_anchor");if(s)return ka(e,s)}let o=Ra(r),i=Ra(e.fullText),a=Pa(i,o);if(a.length>1)return{found:!1,error:wr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Ca(e,a[0],"space_equivalent_anchor");if(s)return ka(e,s)}return{found:!1,error:wr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function hr(e,t,r,n,o=!1){let i=C(e,"w:r");if(t){let s=t.cloneNode(!0);o||lt(s,n),i.appendChild(s)}let a=C(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,i.appendChild(a),i}function Ma(e,t,r,n,o=null,i=null,a=null){let s=o||an(t),l=a||fo(s,r);if(!l.found||!l.startRun)return!1;let u=C(e,"w:commentRangeStart");u.setAttribute("w:id",String(n));let c=C(e,"w:commentRangeEnd");c.setAttribute("w:id",String(n));let f=C(e,"w:r"),m=C(e,"w:commentReference");if(m.setAttribute("w:id",String(n)),f.appendChild(m),l.startRun===l.endRun){let h=l.startRun,g=ae(h,"w:t");if(!g)return h.parentNode.insertBefore(u,h),h.nextSibling?(h.parentNode.insertBefore(c,h.nextSibling),c.parentNode.insertBefore(f,c.nextSibling)):(h.parentNode.appendChild(c),h.parentNode.appendChild(f)),!0;let w=g.textContent||"",x=w.substring(0,l.startOffset),N=w.substring(l.startOffset,l.endOffset),T=w.substring(l.endOffset),y=ae(h,"w:rPr"),v=h.parentNode;return x&&(v.insertBefore(hr(e,y,x,i,!0),h),lt(y,i)),v.insertBefore(u,h),g.textContent=N,h.nextSibling?v.insertBefore(c,h.nextSibling):v.appendChild(c),v.insertBefore(f,c.nextSibling||null),T&&v.insertBefore(hr(e,y,T,i),f.nextSibling||null),!0}let d=ae(l.startRun,"w:t");if(d&&l.startOffset>0){let h=d.textContent||"",g=h.substring(0,l.startOffset),w=h.substring(l.startOffset);if(g){let x=ae(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(hr(e,x,g,i,!0),l.startRun),lt(x,i)}d.textContent=w}l.startRun.parentNode.insertBefore(u,l.startRun);let p=l.endRun||l.startRun,b=ae(p,"w:t");if(b&&l.endOffset<(b.textContent||"").length){let h=b.textContent||"",g=h.substring(0,l.endOffset),w=h.substring(l.endOffset);if(b.textContent=g,w){let x=ae(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(hr(e,x,w,i),p.nextSibling):p.parentNode.appendChild(hr(e,x,w,i))}}return p.nextSibling?(p.parentNode.insertBefore(c,p.nextSibling),c.parentNode.insertBefore(f,c.nextSibling)):(p.parentNode.appendChild(c),p.parentNode.appendChild(f)),!0}var Wt="http://schemas.microsoft.com/office/2006/xmlPackage",br="http://schemas.openxmlformats.org/package/2006/relationships";function _a(e,t){let r=fe(),n=W(e,"text/xml"),o=n.doc,i=o?ne(o):null;if(n.error||i)return te("[CommentEngine] Failed to parse package:",n.error?.message||i?.textContent),e;let a=o.documentElement,s=o.createElementNS(Wt,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(Wt,"pkg:xmlData"),u=W(t,"text/xml").doc;if(!u)return e;l.appendChild(o.importNode(u.documentElement,!0)),s.appendChild(l),a.appendChild(s);let f=le(a,Wt,"part").find(m=>m.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let m=le(f,Wt,"xmlData");if(m.length>0){let d=le(m[0],br,"Relationships");if(d.length>0){let p=d[0],b=le(p,br,"Relationship");if(!b.some(g=>g.getAttribute("Type")?.includes("comments"))){let g=0;b.forEach(x=>{let N=x.getAttribute("Id"),T=parseInt(N?.replace("rId","")||"0",10);T>g&&(g=T)});let w=o.createElementNS(br,"Relationship");w.setAttribute("Id",`rId${g+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let m=o.createElementNS(Wt,"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(Wt,"pkg:xmlData"),p=o.createElementNS(br,"Relationships"),b=o.createElementNS(br,"Relationship");b.setAttribute("Id","rId1"),b.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),b.setAttribute("Target","comments.xml"),p.appendChild(b),d.appendChild(p),m.appendChild(d),a.appendChild(m)}return r.serializeToString(o)}function Eu(e,t){let r=W(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 Iu(e,t,r={}){let n=r?.author||me(),o=Ar(),i=[],a=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let u=fe(),c=Eu(e,h=>`Failed to parse OXML: ${h}`);if(i.push(...c.warnings||[]),!c.xmlDoc)return te("[CommentEngine] Parse failure:",c.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:c.error,warnings:[...i,c.warning]};let f=c.xmlDoc,m=nt(f),d=Zt(f,"w:p");k(`[CommentEngine] Found ${d.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let g=h.paragraphIndex-1;if(g<0||g>=d.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${d.length})`;i.push(w),l.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(g,(p.get(g)||0)+1)}let b=new Map;for(let[h,g]of t.entries()){let w=g.paragraphIndex-1;if(w<0||w>=d.length)continue;let x=d[w],N=b.get(w);N||(N=an(x),b.set(w,N));let T=String(g.textToFind??""),y=fo(N,T),v=(p.get(w)||1)-1;if(p.set(w,v),!y.found){let B={...y.error,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(B),i.push(B.message),v===0&&b.delete(w);continue}let E=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Bo();if(!Ma(f,x,T,E,N,m,y)){let B={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${g.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(B),i.push(B.message),v===0&&b.delete(w);continue}a.push({id:E,content:g.commentContent,author:n,date:o}),s.push({requestIndex:h+1,paragraphIndex:g.paragraphIndex,text:T,resolvedBy:y.resolvedBy,start:y.start,end:y.end}),v>0?b.set(w,an(x)):b.delete(w)}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:u.serializeToString(f),hasChanges:!0,commentsXml:uo(a),commentsApplied:a.length,placedComments:a,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function Au(e,t){return _a(e,t)}var La="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function xr(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function sn(e,t){let r=W(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 Pu(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=xr(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=xr(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function Ba(e,t){let r=co(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 Ru({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=sn(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let l=s.doc,u=Array.from(l.getElementsByTagNameNS("*","comment")).find(N=>xr(N,"w:id","id")===String(r));if(!u)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${r}' was not found.`}};let c=null;if(t){let N=sn(t,"word/commentsExtended.xml");if(N.error)return{status:"error",error:N.error};c=N.doc}let f=Pu(l,c),m=Array.from(u.getElementsByTagNameNS(La,"p"))[0]||Array.from(u.getElementsByTagNameNS("*","p"))[0];if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${r}' has no paragraph.`}};let d=xr(m,"w14:paraId","paraId");d?d=d.toUpperCase():(d=Ba(r,f),m.setAttributeNS(on,"w14:paraId",d));let p=Ba(n,f),b=sn(`<w:comments xmlns:w="${La}" xmlns:w14="${on}">${gr(n,i,o,a,p)}</w:comments>`,"reply comment");l.documentElement.appendChild(l.importNode(b.doc.documentElement.firstChild,!0)),c||(c=sn(Aa([]),"word/commentsExtended.xml").doc);let h=c.documentElement;if(!Array.from(h.getElementsByTagNameNS("*","commentEx")).some(N=>xr(N,"w15:paraId","paraId").toUpperCase()===d)){let N=c.createElementNS(rt,"w15:commentEx");N.setAttributeNS(rt,"w15:paraId",d),N.setAttributeNS(rt,"w15:done","0"),h.appendChild(N)}let w=c.createElementNS(rt,"w15:commentEx");w.setAttributeNS(rt,"w15:paraId",p),w.setAttributeNS(rt,"w15:paraIdParent",d),w.setAttributeNS(rt,"w15:done","0"),h.appendChild(w);let x=fe();return{status:"ok",hasChanges:!0,commentsXml:x.serializeToString(l),commentsExtendedXml:x.serializeToString(c),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:n,parentCommentId:String(r),paraId:p,parentParaId:d}}function Ut(e){e?.parentNode&&e.parentNode.removeChild(e)}function Fa(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(Ut)});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(Ut)})}return r.children.length>0?r:null}function Cu(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 u=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(u))}for(let l of s){let u=l.getElementsByTagNameNS(o,"t"),c=Array.from(u).map(f=>f.textContent).join("");if(c.includes(t)||c===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let m=f[0],d=Fa(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Ut(m)}}}return Nt(n)}var Ou={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 ku(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=Ou[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||me(),l=t;l?l=t.cloneNode(!0):l=C(e,"w:rPr");let u=null;a&&(u=C(e,"w:rPr"),Array.from(l.childNodes).forEach(m=>{m.nodeName!=="w:rPrChange"&&u.appendChild(m.cloneNode(!0))}));let c=l.getElementsByTagNameNS(o,"highlight");Array.from(c).forEach(Ut);let f=C(e,"w:highlight");if(f.setAttributeNS(o,"w:val",i),l.appendChild(f),a&&u){let m=C(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(u);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(Ut),l.appendChild(m)}return l}function Mu(e,t,r="yellow",n={}){if(!t||!e)return e;let o=et(e);if(!o)return e;let i;n?._revisionIdAllocator instanceof he?(i=n._revisionIdAllocator,Et(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")),u=new WeakSet,c=(f,m,d)=>{let p=f.cloneNode(!0);u.has(f)?lt(p,i):u.add(f);let b=p.getElementsByTagNameNS(a,"t");Array.from(b).forEach(Ut);let h=C(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=m,p.appendChild(h),d){let g=p.getElementsByTagNameNS(a,"rPr"),w=g.length>0?g[0]:null,x=ku(o,w,r,n);w?p.replaceChild(x,w):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 w=m.indexOf(t,p);if(w===-1)break;d.push(w),p=w+t.length}if(d.length===0)continue;let b=f.parentNode;if(!b){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),g=0;for(let w of d)w>g&&h.appendChild(c(f,m.slice(g,w),!1)),h.appendChild(c(f,m.slice(w,w+t.length),!0)),g=w+t.length;g<m.length&&h.appendChild(c(f,m.slice(g),!1)),b.replaceChild(h,f)}return Nt(o)}var Ee="http://schemas.openxmlformats.org/wordprocessingml/2006/main",_u="http://schemas.openxmlformats.org/package/2006/content-types",Lu="http://schemas.openxmlformats.org/package/2006/relationships",Xa="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",Da="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",za="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",Wa="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",Ua="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",ja="application/vnd.ms-word.commentsExtended+xml",$a="word/document.xml",ln="word/numbering.xml",Nr="word/comments.xml",mo="word/commentsExtended.xml",Me="[Content_Types].xml",_e="word/_rels/document.xml.rels";function ge(e,t="xml"){let r=W(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 cn(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ee&&e.localName==="sectPr"}function go(e){return e.getElementsByTagNameNS("*","body")[0]||null}function Ha(e){for(let t of Array.from(e.childNodes||[]))if(cn(t))return t;return null}function Bu(e,t){let r=Ha(e);r?e.insertBefore(t,r):e.appendChild(t)}function Va(e){let t=go(e);if(!t)return;let r=Ha(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function Fu(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(u=>u.nodeType===1&&u.namespaceURI===Ee&&u.localName==="p");for(let u of l)i.insertBefore(u,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function po(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function $u(e){let t=fe(),r=ge(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>po(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&&!cn(f)):[a],u=n.find(f=>po(f)==="/word/numbering.xml"),c=null;if(u){let f=u.getElementsByTagNameNS("*","xmlData")[0],m=f?Array.from(f.childNodes||[]).find(d=>d.nodeType===1):null;m&&(c=t.serializeToString(m))}return{replacementNodes:l,numberingXml:c,sourceType:"package"}}function Xu(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 $u(e);if(e.includes("<w:document")){let o=ge(e,"document OOXML"),i=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:i?Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&!cn(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ee}">${e}</root>`,r=ge(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 ho(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(_u,"Override");return i.setAttribute("PartName",t),i.setAttribute("ContentType",r),e.documentElement.appendChild(i),!0}function wo(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,i=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(i.some(c=>(c.getAttribute("Type")||"")===t))return!1;let s=0;for(let c of i){let f=c.getAttribute("Id")||"",m=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(m)&&(s=Math.max(s,m))}let l=`rId${s+1}`,u=e.createElementNS(Lu,"Relationship");return u.setAttribute("Id",l),u.setAttribute("Type",t),u.setAttribute("Target",r),o.appendChild(u),n?._receiptCollector?n._receiptCollector.recordRelationship(l):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(l),!0}async function Ae(e,t){let r=e.file(t);return r?r.async("string"):null}async function Du(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:Le,a=(Array.isArray(t)?t:[t]).filter(Boolean);if(a.length===0)return;let s=await Ae(e,ln);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(ln,l);let u=fe(),c=await Ae(e,Me);if(c){let m=ge(c,Me);ho(m,"/word/numbering.xml",Da)&&e.file(Me,u.serializeToString(m))}let f=await Ae(e,_e);if(f){let m=ge(f,_e);wo(m,Xa,"numbering.xml",r)&&e.file(_e,u.serializeToString(m))}}async function zu(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=fe(),i=await Ae(e,Nr);if(!i||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Nr,t);else{let l=ge(i,"word/comments.xml (existing)"),u=ge(t,"word/comments.xml (incoming)"),c=l.documentElement,f=new Set(Array.from(c.getElementsByTagNameNS(Ee,"comment")).map(m=>m.getAttribute("w:id")||m.getAttribute("id")).filter(Boolean));for(let m of Array.from(u.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}`);c.appendChild(l.importNode(m,!0))}e.file(Nr,o.serializeToString(l))}let a=await Ae(e,Me);if(a){let l=ge(a,Me);ho(l,"/word/comments.xml",Wa)&&e.file(Me,o.serializeToString(l))}let s=await Ae(e,_e);if(s){let l=ge(s,_e);wo(l,za,"comments.xml",r)&&e.file(_e,o.serializeToString(l))}}async function Wu(e,t,r={}){if(!t)return;ge(t,"word/commentsExtended.xml"),e.file(mo,t);let n=fe(),o=await Ae(e,Me);if(o){let a=ge(o,Me);ho(a,"/word/commentsExtended.xml",ja)&&e.file(Me,n.serializeToString(a))}let i=await Ae(e,_e);if(i){let a=ge(i,_e);wo(a,Ua,"commentsExtended.xml",r)&&e.file(_e,n.serializeToString(a))}}async function Uu(e){let t=await Ae(e,$a);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=ge(t,$a);Va(r);let n=go(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),i=o.map((h,g)=>({node:h,index:g})).filter(h=>cn(h.node)).map(h=>h.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 h of Array.from(a))for(let g of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(g.namespaceURI===Ee&&g.localName==="p"&&Array.from(g.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,u=await Ae(e,ln),c=await Ae(e,Nr),f=await Ae(e,mo);if(f&&!c)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(u)ge(u,ln);else if(s)throw new Error("Validation failed: numbering used but part missing");if(c){let h=ge(c,Nr),g=(R,_)=>Array.from(R.getElementsByTagNameNS(Ee,_)).map($=>$.getAttribute("w:id")||$.getAttribute("id")).filter($=>$!==""),w=new Set(g(r,"commentRangeStart")),x=new Set(g(r,"commentRangeEnd")),N=new Set(g(r,"commentReference")),T=g(h,"comment"),y=new Set(T),v=R=>Array.from(R).sort((_,$)=>Number(_)-Number($)||_.localeCompare($)),E=(R,_)=>v(new Set(Array.from(R).filter($=>!_.has($)))),P=v(new Set(T.filter((R,_)=>T.indexOf(R)!==_)));if(P.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${P.join(", ")}`);let B=E(w,x),L=E(x,w);if(B.length>0||L.length>0){let R=[];throw B.length>0&&R.push(`start without end: ${B.join(", ")}`),L.length>0&&R.push(`end without start: ${L.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let z=E(new Set([...w,...x]),N);if(z.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${z.join(", ")}`);let j=E(new Set([...w,...x,...N]),y);if(j.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${j.join(", ")}`);let O=new Set;if(f){let R=ge(f,mo),_=new Map;for(let G of Array.from(h.getElementsByTagNameNS("*","comment"))){let Q=G.getAttribute("w:id")||G.getAttribute("id"),ee=Array.from(G.getElementsByTagNameNS("*","p"))[0],We=ee?.getAttribute("w14:paraId")||ee?.getAttribute("paraId");We&&_.set(We.toUpperCase(),Q)}let $=new Set(_.keys()),Z=new Set;for(let G of Array.from(R.getElementsByTagNameNS("*","commentEx"))){let Q=G.getAttribute("w15:paraId")||G.getAttribute("paraId"),ee=G.getAttribute("w15:paraIdParent")||G.getAttribute("paraIdParent");if(!Q||!$.has(Q.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${Q||"(missing)"}`);if(Z.has(Q.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${Q}`);if(Z.add(Q.toUpperCase()),ee){if(!$.has(ee.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${ee}`);O.add(_.get(Q.toUpperCase()))}}}let H=E(new Set([...y].filter(R=>!O.has(R))),N);if(H.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${H.join(", ")}`)}else if(l)throw new Error("Validation failed: comments used but part missing");let m=await Ae(e,Me);if(!m)throw new Error(`Validation failed: missing ${Me}`);let d=ge(m,Me),p=await Ae(e,_e);if(!p)throw new Error(`Validation failed: missing ${_e}`);let b=ge(p,_e);if(u){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===Da),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Xa);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!g)throw new Error("Validation failed: numbering rel missing")}if(c){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===Wa),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===za);if(!h)throw new Error("Validation failed: comments CT override missing");if(!g)throw new Error("Validation failed: comments rel missing")}if(f){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(w.getAttribute("ContentType")||"")===ja),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Ua);if(!h)throw new Error("Validation failed: commentsExtended CT override missing");if(!g)throw new Error("Validation failed: commentsExtended rel missing")}}var jt=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 Ka(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
207
- `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function ju(e={}){let t=e.originalText||"",r=Ka(e.newContent||""),n=fr(r)||{type:"text",items:[]};return r.includes(`
208
- `)&&n.type!=="text"?{kind:jt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:Ga(t),hasInlineFormatting:un(r),hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:Ga(t)?un(r)?{kind:jt.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:{kind:jt.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:fn(r)?{kind:jt.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:un(r),hasBlockElements:!0,hasMarkdownTable:vr(r)}}:{kind:jt.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:un(r),hasBlockElements:!1,hasMarkdownTable:vr(r)}}}function Ga(e){return!e||e.trim().length===0}function vr(e){if(!e||!e.includes("|"))return!1;let t=$e(e);return t.rows.length>0||t.headers.length>0}function un(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function fn(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),u=e.includes(`
208
+ </w:comments>`}function Ca(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 an(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Zt(e,"w:r"),o=[],i="";for(let a of n){if(!ht(a,e,r))continue;let s=i.length,l=wt(a,{revisionView:r,boundary:e});i+=l,o.push({run:a,start:s,end:i.length})}return{fullText:i,runOffsets:o}}function Oa(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 ka(e){return String(e).replace(/[ \u00a0]/g," ")}function wr(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Ma(e,t,r){let n=null,o=null,i=0,a=0;for(let{run:s,start:l,end:u}of e.runOffsets)t.start>=l&&t.start<u&&(n=s,i=t.start-l),t.end>l&&t.end<=u&&(o=s,a=t.end-l);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:i,endRun:o,endOffset:a}}function _a(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 La(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(_a(n,["del"]))return{found:!1,error:wr("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(_a(n,["moveFrom","moveTo"]))return{found:!1,error:wr("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function fo(e,t){let r=String(t??""),n=Oa(e.fullText,r);if(n.length>1)return{found:!1,error:wr("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let s=Ma(e,n[0],"exact_anchor");if(s)return La(e,s)}let o=ka(r),i=ka(e.fullText),a=Oa(i,o);if(a.length>1)return{found:!1,error:wr("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${a.length} locations in the target paragraph.`,a)};if(a.length===1){let s=Ma(e,a[0],"space_equivalent_anchor");if(s)return La(e,s)}return{found:!1,error:wr("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function hr(e,t,r,n,o=!1){let i=C(e,"w:r");if(t){let s=t.cloneNode(!0);o||lt(s,n),i.appendChild(s)}let a=C(e,"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=r,i.appendChild(a),i}function Ba(e,t,r,n,o=null,i=null,a=null){let s=o||an(t),l=a||fo(s,r);if(!l.found||!l.startRun)return!1;let u=C(e,"w:commentRangeStart");u.setAttribute("w:id",String(n));let c=C(e,"w:commentRangeEnd");c.setAttribute("w:id",String(n));let f=C(e,"w:r"),m=C(e,"w:commentReference");if(m.setAttribute("w:id",String(n)),f.appendChild(m),l.startRun===l.endRun){let h=l.startRun,g=ae(h,"w:t");if(!g)return h.parentNode.insertBefore(u,h),h.nextSibling?(h.parentNode.insertBefore(c,h.nextSibling),c.parentNode.insertBefore(f,c.nextSibling)):(h.parentNode.appendChild(c),h.parentNode.appendChild(f)),!0;let w=g.textContent||"",x=w.substring(0,l.startOffset),N=w.substring(l.startOffset,l.endOffset),T=w.substring(l.endOffset),y=ae(h,"w:rPr"),v=h.parentNode;return x&&(v.insertBefore(hr(e,y,x,i,!0),h),lt(y,i)),v.insertBefore(u,h),g.textContent=N,h.nextSibling?v.insertBefore(c,h.nextSibling):v.appendChild(c),v.insertBefore(f,c.nextSibling||null),T&&v.insertBefore(hr(e,y,T,i),f.nextSibling||null),!0}let d=ae(l.startRun,"w:t");if(d&&l.startOffset>0){let h=d.textContent||"",g=h.substring(0,l.startOffset),w=h.substring(l.startOffset);if(g){let x=ae(l.startRun,"w:rPr");l.startRun.parentNode.insertBefore(hr(e,x,g,i,!0),l.startRun),lt(x,i)}d.textContent=w}l.startRun.parentNode.insertBefore(u,l.startRun);let p=l.endRun||l.startRun,b=ae(p,"w:t");if(b&&l.endOffset<(b.textContent||"").length){let h=b.textContent||"",g=h.substring(0,l.endOffset),w=h.substring(l.endOffset);if(b.textContent=g,w){let x=ae(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(hr(e,x,w,i),p.nextSibling):p.parentNode.appendChild(hr(e,x,w,i))}}return p.nextSibling?(p.parentNode.insertBefore(c,p.nextSibling),c.parentNode.insertBefore(f,c.nextSibling)):(p.parentNode.appendChild(c),p.parentNode.appendChild(f)),!0}var Wt="http://schemas.microsoft.com/office/2006/xmlPackage",br="http://schemas.openxmlformats.org/package/2006/relationships";function Fa(e,t){let r=me(),n=U(e,"text/xml"),o=n.doc,i=o?ne(o):null;if(n.error||i)return te("[CommentEngine] Failed to parse package:",n.error?.message||i?.textContent),e;let a=o.documentElement,s=o.createElementNS(Wt,"pkg:part");s.setAttribute("pkg:name","/word/comments.xml"),s.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let l=o.createElementNS(Wt,"pkg:xmlData"),u=U(t,"text/xml").doc;if(!u)return e;l.appendChild(o.importNode(u.documentElement,!0)),s.appendChild(l),a.appendChild(s);let f=le(a,Wt,"part").find(m=>m.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(f){let m=le(f,Wt,"xmlData");if(m.length>0){let d=le(m[0],br,"Relationships");if(d.length>0){let p=d[0],b=le(p,br,"Relationship");if(!b.some(g=>g.getAttribute("Type")?.includes("comments"))){let g=0;b.forEach(x=>{let N=x.getAttribute("Id"),T=parseInt(N?.replace("rId","")||"0",10);T>g&&(g=T)});let w=o.createElementNS(br,"Relationship");w.setAttribute("Id",`rId${g+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let m=o.createElementNS(Wt,"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(Wt,"pkg:xmlData"),p=o.createElementNS(br,"Relationships"),b=o.createElementNS(br,"Relationship");b.setAttribute("Id","rId1"),b.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),b.setAttribute("Target","comments.xml"),p.appendChild(b),d.appendChild(p),m.appendChild(d),a.appendChild(m)}return r.serializeToString(o)}function Ru(e,t){let r=U(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 Cu(e,t,r={}){let n=r?.author||de(),o=Ar(),i=[],a=[],s=[],l=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let u=me(),c=Ru(e,h=>`Failed to parse OXML: ${h}`);if(i.push(...c.warnings||[]),!c.xmlDoc)return te("[CommentEngine] Parse failure:",c.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:c.error,warnings:[...i,c.warning]};let f=c.xmlDoc,m=nt(f),d=Zt(f,"w:p");k(`[CommentEngine] Found ${d.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let g=h.paragraphIndex-1;if(g<0||g>=d.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${d.length})`;i.push(w),l.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(g,(p.get(g)||0)+1)}let b=new Map;for(let[h,g]of t.entries()){let w=g.paragraphIndex-1;if(w<0||w>=d.length)continue;let x=d[w],N=b.get(w);N||(N=an(x),b.set(w,N));let T=String(g.textToFind??""),y=fo(N,T),v=(p.get(w)||1)-1;if(p.set(w,v),!y.found){let B={...y.error,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(B),i.push(B.message),v===0&&b.delete(w);continue}let I=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():Bo();if(!Ba(f,x,T,I,N,m,y)){let B={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${g.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:g.paragraphIndex};l.push(B),i.push(B.message),v===0&&b.delete(w);continue}a.push({id:I,content:g.commentContent,author:n,date:o}),s.push({requestIndex:h+1,paragraphIndex:g.paragraphIndex,text:T,resolvedBy:y.resolvedBy,start:y.start,end:y.end}),v>0?b.set(w,an(x)):b.delete(w)}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:u.serializeToString(f),hasChanges:!0,commentsXml:uo(a),commentsApplied:a.length,placedComments:a,warnings:i,resolvedAnchors:s,...l.length>0?{status:"error",error:l[0],errors:l}:{}}}function Ou(e,t){return Fa(e,t)}var $a="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function xr(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function sn(e,t){let r=U(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 ku(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=xr(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=xr(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function Xa(e,t){let r=co(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 Mu({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=sn(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let l=s.doc,u=Array.from(l.getElementsByTagNameNS("*","comment")).find(N=>xr(N,"w:id","id")===String(r));if(!u)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${r}' was not found.`}};let c=null;if(t){let N=sn(t,"word/commentsExtended.xml");if(N.error)return{status:"error",error:N.error};c=N.doc}let f=ku(l,c),m=Array.from(u.getElementsByTagNameNS($a,"p"))[0]||Array.from(u.getElementsByTagNameNS("*","p"))[0];if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${r}' has no paragraph.`}};let d=xr(m,"w14:paraId","paraId");d?d=d.toUpperCase():(d=Xa(r,f),m.setAttributeNS(on,"w14:paraId",d));let p=Xa(n,f),b=sn(`<w:comments xmlns:w="${$a}" xmlns:w14="${on}">${gr(n,i,o,a,p)}</w:comments>`,"reply comment");l.documentElement.appendChild(l.importNode(b.doc.documentElement.firstChild,!0)),c||(c=sn(Ca([]),"word/commentsExtended.xml").doc);let h=c.documentElement;if(!Array.from(h.getElementsByTagNameNS("*","commentEx")).some(N=>xr(N,"w15:paraId","paraId").toUpperCase()===d)){let N=c.createElementNS(rt,"w15:commentEx");N.setAttributeNS(rt,"w15:paraId",d),N.setAttributeNS(rt,"w15:done","0"),h.appendChild(N)}let w=c.createElementNS(rt,"w15:commentEx");w.setAttributeNS(rt,"w15:paraId",p),w.setAttributeNS(rt,"w15:paraIdParent",d),w.setAttributeNS(rt,"w15:done","0"),h.appendChild(w);let x=me();return{status:"ok",hasChanges:!0,commentsXml:x.serializeToString(l),commentsExtendedXml:x.serializeToString(c),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:n,parentCommentId:String(r),paraId:p,parentParaId:d}}function Ut(e){e?.parentNode&&e.parentNode.removeChild(e)}function Da(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(Ut)});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(Ut)})}return r.children.length>0?r:null}function _u(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 u=l.getElementsByTagNameNS(o,"r");s.push(...Array.from(u))}for(let l of s){let u=l.getElementsByTagNameNS(o,"t"),c=Array.from(u).map(f=>f.textContent).join("");if(c.includes(t)||c===t){let f=l.getElementsByTagNameNS(o,"rPr");if(f.length>0){let m=f[0],d=Da(m,r);d?m.parentNode&&m.parentNode.replaceChild(d,m):Ut(m)}}}return Nt(n)}var Lu={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 Bu(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",i=Lu[r.toLowerCase()]||"yellow",a=n?.generateRedlines??!1,s=n?.author||de(),l=t;l?l=t.cloneNode(!0):l=C(e,"w:rPr");let u=null;a&&(u=C(e,"w:rPr"),Array.from(l.childNodes).forEach(m=>{m.nodeName!=="w:rPrChange"&&u.appendChild(m.cloneNode(!0))}));let c=l.getElementsByTagNameNS(o,"highlight");Array.from(c).forEach(Ut);let f=C(e,"w:highlight");if(f.setAttributeNS(o,"w:val",i),l.appendChild(f),a&&u){let m=C(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(u);let p=l.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(Ut),l.appendChild(m)}return l}function Fu(e,t,r="yellow",n={}){if(!t||!e)return e;let o=et(e);if(!o)return e;let i;n?._revisionIdAllocator instanceof he?(i=n._revisionIdAllocator,Et(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")),u=new WeakSet,c=(f,m,d)=>{let p=f.cloneNode(!0);u.has(f)?lt(p,i):u.add(f);let b=p.getElementsByTagNameNS(a,"t");Array.from(b).forEach(Ut);let h=C(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=m,p.appendChild(h),d){let g=p.getElementsByTagNameNS(a,"rPr"),w=g.length>0?g[0]:null,x=Bu(o,w,r,n);w?p.replaceChild(x,w):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 w=m.indexOf(t,p);if(w===-1)break;d.push(w),p=w+t.length}if(d.length===0)continue;let b=f.parentNode;if(!b){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),g=0;for(let w of d)w>g&&h.appendChild(c(f,m.slice(g,w),!1)),h.appendChild(c(f,m.slice(w,w+t.length),!0)),g=w+t.length;g<m.length&&h.appendChild(c(f,m.slice(g),!1)),b.replaceChild(h,f)}return Nt(o)}var Ee="http://schemas.openxmlformats.org/wordprocessingml/2006/main",$u="http://schemas.openxmlformats.org/package/2006/content-types",Xu="http://schemas.openxmlformats.org/package/2006/relationships",Wa="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering",Ua="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml",ja="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",Ha="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",Va="http://schemas.microsoft.com/office/2011/relationships/commentsExtended",Ga="application/vnd.ms-word.commentsExtended+xml",za="word/document.xml",ln="word/numbering.xml",Nr="word/comments.xml",mo="word/commentsExtended.xml",Me="[Content_Types].xml",_e="word/_rels/document.xml.rels";function ge(e,t="xml"){let r=U(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 cn(e){return!!e&&e.nodeType===1&&e.namespaceURI===Ee&&e.localName==="sectPr"}function go(e){return e.getElementsByTagNameNS("*","body")[0]||null}function Ka(e){for(let t of Array.from(e.childNodes||[]))if(cn(t))return t;return null}function Du(e,t){let r=Ka(e);r?e.insertBefore(t,r):e.appendChild(t)}function Ya(e){let t=go(e);if(!t)return;let r=Ka(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function zu(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(u=>u.nodeType===1&&u.namespaceURI===Ee&&u.localName==="p");for(let u of l)i.insertBefore(u,s),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function po(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function Wu(e){let t=me(),r=ge(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(f=>po(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&&!cn(f)):[a],u=n.find(f=>po(f)==="/word/numbering.xml"),c=null;if(u){let f=u.getElementsByTagNameNS("*","xmlData")[0],m=f?Array.from(f.childNodes||[]).find(d=>d.nodeType===1):null;m&&(c=t.serializeToString(m))}return{replacementNodes:l,numberingXml:c,sourceType:"package"}}function Uu(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 Wu(e);if(e.includes("<w:document")){let o=ge(e,"document OOXML"),i=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:i?Array.from(i.childNodes||[]).filter(s=>s.nodeType===1&&!cn(s)):Array.from(o.childNodes||[]).filter(s=>s.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${Ee}">${e}</root>`,r=ge(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 ho(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($u,"Override");return i.setAttribute("PartName",t),i.setAttribute("ContentType",r),e.documentElement.appendChild(i),!0}function wo(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,i=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(i.some(c=>(c.getAttribute("Type")||"")===t))return!1;let s=0;for(let c of i){let f=c.getAttribute("Id")||"",m=Number.parseInt(f.replace(/^rId/i,""),10);Number.isFinite(m)&&(s=Math.max(s,m))}let l=`rId${s+1}`,u=e.createElementNS(Xu,"Relationship");return u.setAttribute("Id",l),u.setAttribute("Type",t),u.setAttribute("Target",r),o.appendChild(u),n?._receiptCollector?n._receiptCollector.recordRelationship(l):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(l),!0}async function Ae(e,t){let r=e.file(t);return r?r.async("string"):null}async function ju(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:Le,a=(Array.isArray(t)?t:[t]).filter(Boolean);if(a.length===0)return;let s=await Ae(e,ln);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(ln,l);let u=me(),c=await Ae(e,Me);if(c){let m=ge(c,Me);ho(m,"/word/numbering.xml",Ua)&&e.file(Me,u.serializeToString(m))}let f=await Ae(e,_e);if(f){let m=ge(f,_e);wo(m,Wa,"numbering.xml",r)&&e.file(_e,u.serializeToString(m))}}async function Hu(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=me(),i=await Ae(e,Nr);if(!i||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(Nr,t);else{let l=ge(i,"word/comments.xml (existing)"),u=ge(t,"word/comments.xml (incoming)"),c=l.documentElement,f=new Set(Array.from(c.getElementsByTagNameNS(Ee,"comment")).map(m=>m.getAttribute("w:id")||m.getAttribute("id")).filter(Boolean));for(let m of Array.from(u.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}`);c.appendChild(l.importNode(m,!0))}e.file(Nr,o.serializeToString(l))}let a=await Ae(e,Me);if(a){let l=ge(a,Me);ho(l,"/word/comments.xml",Ha)&&e.file(Me,o.serializeToString(l))}let s=await Ae(e,_e);if(s){let l=ge(s,_e);wo(l,ja,"comments.xml",r)&&e.file(_e,o.serializeToString(l))}}async function Vu(e,t,r={}){if(!t)return;ge(t,"word/commentsExtended.xml"),e.file(mo,t);let n=me(),o=await Ae(e,Me);if(o){let a=ge(o,Me);ho(a,"/word/commentsExtended.xml",Ga)&&e.file(Me,n.serializeToString(a))}let i=await Ae(e,_e);if(i){let a=ge(i,_e);wo(a,Va,"commentsExtended.xml",r)&&e.file(_e,n.serializeToString(a))}}async function Gu(e){let t=await Ae(e,za);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=ge(t,za);Ya(r);let n=go(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),i=o.map((h,g)=>({node:h,index:g})).filter(h=>cn(h.node)).map(h=>h.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 h of Array.from(a))for(let g of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(g.namespaceURI===Ee&&g.localName==="p"&&Array.from(g.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,u=await Ae(e,ln),c=await Ae(e,Nr),f=await Ae(e,mo);if(f&&!c)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(u)ge(u,ln);else if(s)throw new Error("Validation failed: numbering used but part missing");if(c){let h=ge(c,Nr),g=(R,_)=>Array.from(R.getElementsByTagNameNS(Ee,_)).map(F=>F.getAttribute("w:id")||F.getAttribute("id")).filter(F=>F!==""),w=new Set(g(r,"commentRangeStart")),x=new Set(g(r,"commentRangeEnd")),N=new Set(g(r,"commentReference")),T=g(h,"comment"),y=new Set(T),v=R=>Array.from(R).sort((_,F)=>Number(_)-Number(F)||_.localeCompare(F)),I=(R,_)=>v(new Set(Array.from(R).filter(F=>!_.has(F)))),P=v(new Set(T.filter((R,_)=>T.indexOf(R)!==_)));if(P.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${P.join(", ")}`);let B=I(w,x),L=I(x,w);if(B.length>0||L.length>0){let R=[];throw B.length>0&&R.push(`start without end: ${B.join(", ")}`),L.length>0&&R.push(`end without start: ${L.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${R.join("; ")})`)}let z=I(new Set([...w,...x]),N);if(z.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${z.join(", ")}`);let V=I(new Set([...w,...x,...N]),y);if(V.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${V.join(", ")}`);let O=new Set;if(f){let R=ge(f,mo),_=new Map;for(let H of Array.from(h.getElementsByTagNameNS("*","comment"))){let Q=H.getAttribute("w:id")||H.getAttribute("id"),ee=Array.from(H.getElementsByTagNameNS("*","p"))[0],We=ee?.getAttribute("w14:paraId")||ee?.getAttribute("paraId");We&&_.set(We.toUpperCase(),Q)}let F=new Set(_.keys()),J=new Set;for(let H of Array.from(R.getElementsByTagNameNS("*","commentEx"))){let Q=H.getAttribute("w15:paraId")||H.getAttribute("paraId"),ee=H.getAttribute("w15:paraIdParent")||H.getAttribute("paraIdParent");if(!Q||!F.has(Q.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${Q||"(missing)"}`);if(J.has(Q.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${Q}`);if(J.add(Q.toUpperCase()),ee){if(!F.has(ee.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${ee}`);O.add(_.get(Q.toUpperCase()))}}}let W=I(new Set([...y].filter(R=>!O.has(R))),N);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 Ae(e,Me);if(!m)throw new Error(`Validation failed: missing ${Me}`);let d=ge(m,Me),p=await Ae(e,_e);if(!p)throw new Error(`Validation failed: missing ${_e}`);let b=ge(p,_e);if(u){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===Ua),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Wa);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!g)throw new Error("Validation failed: numbering rel missing")}if(c){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===Ha),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===ja);if(!h)throw new Error("Validation failed: comments CT override missing");if(!g)throw new Error("Validation failed: comments rel missing")}if(f){let h=Array.from(d.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml"&&(w.getAttribute("ContentType")||"")===Ga),g=Array.from(b.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Va);if(!h)throw new Error("Validation failed: commentsExtended CT override missing");if(!g)throw new Error("Validation failed: commentsExtended rel missing")}}var jt=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 qa(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
209
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r")}function Ku(e={}){let t=e.originalText||"",r=qa(e.newContent||""),n=fr(r)||{type:"text",items:[]};return r.includes(`
210
+ `)&&n.type!=="text"?{kind:jt.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:Ja(t),hasInlineFormatting:un(r),hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:Ja(t)?un(r)?{kind:jt.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:{kind:jt.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:fn(r),hasMarkdownTable:vr(r)}}:fn(r)?{kind:jt.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:un(r),hasBlockElements:!0,hasMarkdownTable:vr(r)}}:{kind:jt.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:un(r),hasBlockElements:!1,hasMarkdownTable:vr(r)}}}function Ja(e){return!e||e.trim().length===0}function vr(e){if(!e||!e.includes("|"))return!1;let t=$e(e);return t.rows.length>0||t.headers.length>0}function un(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function fn(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),u=e.includes(`
209
211
 
210
- `);return t||r||n||o||i||a||s||l||u}function Hu(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 bo=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 Vu(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 Gu(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,u;for(;(u=l.exec(e.documentXml))!==null;)n.add(u[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let l=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,u;for(;(u=l.exec(e.commentsXml))!==null;)o.add(u[1])}let i=new Set,a=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
211
- `);if(a){let l=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,u;for(;(u=l.exec(a))!==null;)i.add(u[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,u;for(;(u=l.exec(e.documentXml))!==null;)i.add(u[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,u;for(;(u=l.exec(e.relationshipsXml))!==null;)s.add(u[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let u of l.revisionItems)if(u.partName==="word/document.xml"&&!n.has(String(u.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${u.id}' (kind: ${u.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let u of l.commentIds)if(!o.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${u}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let u of l.numberingIds)if(!i.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${u}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let u of l.relationshipIds)if(!s.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${u}' was not found in document.xml.rels.`}}}}return{valid:!0}}async function Ya(e,t,r,n={}){let o=await Yn(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let i=Array.isArray(o?.warnings)?o.warnings:[];return de({...o,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function Mh(e,t,r,n={}){let o=typeof e=="string"?e:"",i=typeof r=="string"?r:String(r||""),a;try{a=$e(i)}catch{a={headers:[],rows:[]}}return(a?.headers?.length||0)>0||(a?.rows?.length||0)>0?{...await Ya(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function _h(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,i=n.sanitizeInput===!0?Jn(r):r,a=i!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=ro({oxml:e,originalText:t,modifiedText:i,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,u=[];if(s&&l){let b=await Qr(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(b?.hasChanges&&b?.oxml){let h=it(b.oxml,{includeNumbering:b.includeNumbering??!0,numberingXml:b.numberingXml}),g=Array.isArray(b?.warnings)?b.warnings:[];return de({oxml:h,hasChanges:!0,warnings:[...a,...g],listStructuralFallbackApplied:!0,listStructuralFallbackKey:b.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:b.numberingXml||null})}u=Array.isArray(b?.warnings)?b.warnings:[]}let c=await Ya(e,t,r,n);if(!s)return{...c,warnings:[...Array.isArray(c?.warnings)?c.warnings:[],...u],listStructuralFallbackApplied:!1};if(l)return{...c,warnings:[...Array.isArray(c?.warnings)?c.warnings:[],...u],listStructuralFallbackApplied:!1};if(c?.hasChanges)return{...c,listStructuralFallbackApplied:!1};let f=await Qr(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let b=Array.isArray(c?.warnings)?c.warnings:[],h=Array.isArray(f?.warnings)?f.warnings:[];return{...c,warnings:[...b,...h],listStructuralFallbackApplied:!1}}let m=it(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),d=Array.isArray(c?.warnings)?c.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return de({...c,oxml:m,hasChanges:!0,warnings:[...d,...u,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{St as ContainerKind,_o as ContentType,Oe as DiffOp,S as NS_W,Je as NumberingService,bo as ReceiptCollector,tr as ReconciliationPipeline,jt as RoutePlanKind,F as RunKind,Ce as WORD_MAIN_NS,Gn as acceptTrackedChangesInOoxml,Br as analyzeStructuredContent,Ru as applyCommentReplyToParts,Cu as applyFormattingRemovalToOoxml,Mu as applyHighlightToOoxml,Ya as applyRedlineToOxml,_h as applyRedlineToOxmlWithListFallback,mu as areRevisionTokensEqual,gr as buildCommentElement,uo as buildCommentsPartXml,Zc as buildExplicitDecimalMultilevelNumberingXml,Nc as buildListMarkdown,ju as buildReconciliationPlan,so as buildRevisionTokenFraming,ro as buildSingleLineListStructuralFallbackPlan,dc as buildTargetReferenceSnapshot,Ac as clearSingleLineListFallbackExplicitSequence,fa as collectContiguousListParagraphBlock,uu as computeDocumentPartsRevisionToken,Sa as computeRevisionToken,lo as computeRevisionTokenSync,is as configureLogger,as as configureXmlProvider,Lr as containsTrackedChanges,Vc as createDynamicNumberingIdState,Vu as createEmptyReceipt,Lt as createParagraphFingerprint,ic as deleteCommentsByAuthorInOoxml,Pc as enforceListBindingOnParagraphNodes,zu as ensureCommentsArtifactsInZip,Wu as ensureCommentsExtendedArtifactsInZip,Du as ensureNumberingArtifactsInZip,xe as escapeXml,Qr as executeSingleLineListStructuralFallback,Te as extractCanonicalParagraphText,rn as extractDocumentPartsEntries,qc as extractFirstParagraphNumId,Hu as extractParagraphIdFromOoxml,zr as extractParagraphRevisionSegments,Xu as extractReplacementNodesFromOoxml,Bt as findContainingWordElement,qn as findParagraphByBestTextMatch,ia as findParagraphByReference,Kr as findParagraphByStrictText,Yr as findStrictTargetCandidates,pt as generateTableOoxml,go as getBodyElementFromDocument,me as getDefaultAuthor,Se as getDocumentParagraphNodes,po as getPackagePartName,vt as getParagraphId,tt as getParagraphListInfo,ce as getParagraphText,gn as getPlatform,Rn as getTrackedChangeAuthors,to as hasListItems,Yt as inferNumberingStyleFromMarker,jc as inferTableReplacementParagraphBlock,Pt as ingestOoxml,cu as ingestWordOoxmlToMarkdown,ya as ingestWordOoxmlToMarkdownResult,lu as ingestWordOoxmlToPlainText,va as ingestWordOoxmlToPlainTextResult,Iu as injectCommentsIntoOoxml,Au as injectCommentsIntoPackage,Bu as insertBodyElementBeforeSectPr,Su as inspectDocumentParts,ga as isLikelyStructuredTableSourceParagraph,Qn as isMarkdownTableText,ht as isNodeVisibleInRevisionView,eu as mergeNumberingXmlBySchemaOrder,Va as normalizeBodySectionOrderStandalone,Ka as normalizeContentEscapesForRouting,vc as normalizeListItemsWithLevels,Ta as normalizeOpcEntryName,U as normalizeWhitespaceForTargeting,Jc as overwriteParagraphNumIds,fr as parseMarkdownListContent,et as parseOoxml,W as parseOoxmlSafe,eo as parseParagraphReference,xc as planListInsertionOnlyEdit,pl as planStructuredReplacement,Ie as preprocessMarkdown,wt as readCanonicalRunText,Mh as reconcileMarkdownTableOoxml,Gu as reconcileReceiptsAgainstOutput,Ic as recordSingleLineListFallbackExplicitSequence,Kn as rejectTrackedChangesInOoxml,Qc as remapNumberingPayloadForDocument,Fa as removeFormattingFromRPr,dr as reserveNextNumberingId,Kc as reserveNextNumberingIdPair,pc as resolveParagraphRangeByRefs,Ec as resolveSingleLineListFallbackNumberingAction,aa as resolveTargetParagraph,Zn as resolveTargetParagraphWithSnapshot,Jn as sanitizeAiResponse,Fu as sanitizeNestedParagraphsInTables,Nt as serializeOoxml,Fe as serializeToOoxml,cs as setDefaultAuthor,us as setPlatform,cc as splitLeadingParagraphMarker,lc as stripLeadingParagraphMarker,ca as stripRedundantLeadingListMarkers,Tc as stripSingleLineListMarkerPrefix,bc as synthesizeExpandedListScopeEdit,Hc as synthesizeTableMarkdownFromMultilineCellEdit,Uu as validateDocxPackage,Xc as validateRedlineOoxml,fu as validateRevisionToken,it as wrapInDocumentFragment};
212
+ `);return t||r||n||o||i||a||s||l||u}function Yu(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 bo=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 Ju(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 qu(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,u;for(;(u=l.exec(e.documentXml))!==null;)n.add(u[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let l=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,u;for(;(u=l.exec(e.commentsXml))!==null;)o.add(u[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,u;for(;(u=l.exec(a))!==null;)i.add(u[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let l=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,u;for(;(u=l.exec(e.documentXml))!==null;)i.add(u[1])}let s=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let l=/<Relationship\b[^>]*?\bId="([^"]+)"/g,u;for(;(u=l.exec(e.relationshipsXml))!==null;)s.add(u[1])}for(let l of r){if(Array.isArray(l.revisionItems)){for(let u of l.revisionItems)if(u.partName==="word/document.xml"&&!n.has(String(u.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${u.id}' (kind: ${u.kind}) was not found in word/document.xml.`}}}if(Array.isArray(l.commentIds)){for(let u of l.commentIds)if(!o.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${u}' was not found in word/comments.xml.`}}}if(Array.isArray(l.numberingIds)){for(let u of l.numberingIds)if(!i.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${u}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(l.relationshipIds)){for(let u of l.relationshipIds)if(!s.has(String(u)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${u}' was not found in document.xml.rels.`}}}}return{valid:!0}}async function Za(e,t,r,n={}){let o=await Yn(e,t,r,n);if(o?.useNativeApi&&typeof o?.oxml!="string"){let i=Array.isArray(o?.warnings)?o.warnings:[];return ue({...o,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return o}async function $h(e,t,r,n={}){let o=typeof e=="string"?e:"",i=typeof r=="string"?r:String(r||""),a;try{a=$e(i)}catch{a={headers:[],rows:[]}}return(a?.headers?.length||0)>0||(a?.rows?.length||0)>0?{...await Za(o,t||"",i,n),isMarkdownTable:!0,tableData:a}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function Xh(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,i=n.sanitizeInput===!0?Jn(r):r,a=i!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],s=ro({oxml:e,originalText:t,modifiedText:i,allowExistingList:o}),l=n.preferListStructuralFallback!==!1,u=[];if(s&&l){let b=await Qr(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(b?.hasChanges&&b?.oxml){let h=it(b.oxml,{includeNumbering:b.includeNumbering??!0,numberingXml:b.numberingXml}),g=Array.isArray(b?.warnings)?b.warnings:[];return ue({oxml:h,hasChanges:!0,warnings:[...a,...g],listStructuralFallbackApplied:!0,listStructuralFallbackKey:b.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:b.numberingXml||null})}u=Array.isArray(b?.warnings)?b.warnings:[]}let c=await Za(e,t,r,n);if(!s)return{...c,warnings:[...Array.isArray(c?.warnings)?c.warnings:[],...u],listStructuralFallbackApplied:!1};if(l)return{...c,warnings:[...Array.isArray(c?.warnings)?c.warnings:[],...u],listStructuralFallbackApplied:!1};if(c?.hasChanges)return{...c,listStructuralFallbackApplied:!1};let f=await Qr(s,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!f?.hasChanges||!f?.oxml){let b=Array.isArray(c?.warnings)?c.warnings:[],h=Array.isArray(f?.warnings)?f.warnings:[];return{...c,warnings:[...b,...h],listStructuralFallbackApplied:!1}}let m=it(f.oxml,{includeNumbering:f.includeNumbering??!0,numberingXml:f.numberingXml}),d=Array.isArray(c?.warnings)?c.warnings:[],p=Array.isArray(f?.warnings)?f.warnings:[];return ue({...c,oxml:m,hasChanges:!0,warnings:[...d,...u,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:f.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:f.numberingXml||null})}export{St as ContainerKind,_o as ContentType,Oe as DiffOp,S as NS_W,Je as NumberingService,bo as ReceiptCollector,tr as ReconciliationPipeline,jt as RoutePlanKind,$ as RunKind,Ce as WORD_MAIN_NS,Gn as acceptTrackedChangesInOoxml,Br as analyzeStructuredContent,Mu as applyCommentReplyToParts,_u as applyFormattingRemovalToOoxml,Fu as applyHighlightToOoxml,Za as applyRedlineToOxml,Xh as applyRedlineToOxmlWithListFallback,hu as areRevisionTokensEqual,gr as buildCommentElement,uo as buildCommentsPartXml,ru as buildExplicitDecimalMultilevelNumberingXml,Sc as buildListMarkdown,Ku as buildReconciliationPlan,so as buildRevisionTokenFraming,ro as buildSingleLineListStructuralFallbackPlan,wc as buildTargetReferenceSnapshot,Oc as clearSingleLineListFallbackExplicitSequence,pa as collectContiguousListParagraphBlock,pu as computeDocumentPartsRevisionToken,Aa as computeRevisionToken,lo as computeRevisionTokenSync,ls as configureLogger,cs as configureXmlProvider,Lr as containsTrackedChanges,Jc as createDynamicNumberingIdState,Ju as createEmptyReceipt,Lt as createParagraphFingerprint,cc as deleteCommentsByAuthorInOoxml,kc as enforceListBindingOnParagraphNodes,Hu as ensureCommentsArtifactsInZip,Vu as ensureCommentsExtendedArtifactsInZip,ju as ensureNumberingArtifactsInZip,Ne as escapeXml,Qr as executeSingleLineListStructuralFallback,be as extractCanonicalParagraphText,rn as extractDocumentPartsEntries,tu as extractFirstParagraphNumId,Yu as extractParagraphIdFromOoxml,zr as extractParagraphRevisionSegments,Uu as extractReplacementNodesFromOoxml,Bt as findContainingWordElement,qn as findParagraphByBestTextMatch,la as findParagraphByReference,Kr as findParagraphByStrictText,Yr as findStrictTargetCandidates,pt as generateTableOoxml,go as getBodyElementFromDocument,de as getDefaultAuthor,Se as getDocumentParagraphNodes,po as getPackagePartName,vt as getParagraphId,tt as getParagraphListInfo,ce as getParagraphText,gn as getPlatform,Rn as getTrackedChangeAuthors,to as hasListItems,Yt as inferNumberingStyleFromMarker,Kc as inferTableReplacementParagraphBlock,Pt as ingestOoxml,du as ingestWordOoxmlToMarkdown,Ea as ingestWordOoxmlToMarkdownResult,mu as ingestWordOoxmlToPlainText,Sa as ingestWordOoxmlToPlainTextResult,Cu as injectCommentsIntoOoxml,Ou as injectCommentsIntoPackage,Du as insertBodyElementBeforeSectPr,Pu as inspectDocumentParts,ba as isLikelyStructuredTableSourceParagraph,Qn as isMarkdownTableText,ht as isNodeVisibleInRevisionView,ou as mergeNumberingXmlBySchemaOrder,Ya as normalizeBodySectionOrderStandalone,qa as normalizeContentEscapesForRouting,Ec as normalizeListItemsWithLevels,Ia as normalizeOpcEntryName,j as normalizeWhitespaceForTargeting,eu as overwriteParagraphNumIds,fr as parseMarkdownListContent,et as parseOoxml,U as parseOoxmlSafe,eo as parseParagraphReference,Tc as planListInsertionOnlyEdit,hl as planStructuredReplacement,Ie as preprocessMarkdown,wt as readCanonicalRunText,$h as reconcileMarkdownTableOoxml,qu as reconcileReceiptsAgainstOutput,Cc as recordSingleLineListFallbackExplicitSequence,Kn as rejectTrackedChangesInOoxml,nu as remapNumberingPayloadForDocument,Da as removeFormattingFromRPr,dr as reserveNextNumberingId,Zc as reserveNextNumberingIdPair,bc as resolveParagraphRangeByRefs,Rc as resolveSingleLineListFallbackNumberingAction,ca as resolveTargetParagraph,Zn as resolveTargetParagraphWithSnapshot,Jn as sanitizeAiResponse,zu as sanitizeNestedParagraphsInTables,Nt as serializeOoxml,Fe as serializeToOoxml,ms as setDefaultAuthor,ds as setPlatform,dc as splitLeadingParagraphMarker,mc as stripLeadingParagraphMarker,ma as stripRedundantLeadingListMarkers,Ac as stripSingleLineListMarkerPrefix,yc as synthesizeExpandedListScopeEdit,Yc as synthesizeTableMarkdownFromMultilineCellEdit,Gu as validateDocxPackage,Uc as validateRedlineOoxml,gu as validateRevisionToken,it as wrapInDocumentFragment};
212
214
  //# sourceMappingURL=docx-redline-js.esm.min.js.map