cenitu-table 0.3.0 → 0.4.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,197 @@
1
+ "use strict";var Kn=Object.defineProperty;var qn=(n,t,e)=>t in n?Kn(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var v=(n,t,e)=>qn(n,typeof t!="symbol"?t+"":t,e);const O=(n,t,e=0)=>e*17179869184+n*16384+t,Ne=n=>{const t=Math.floor(n/17179869184),e=n-t*17179869184;return{row:Math.floor(e/16384),col:e%16384,sheet:t}};function zt(n){let t="",e=n+1;for(;e>0;){const s=(e-1)%26;t=String.fromCharCode(65+s)+t,e=Math.floor((e-1)/26)}return t}function se(n){let t=0;for(const e of n.toUpperCase()){const s=e.charCodeAt(0);if(s<65||s>90)return-1;t=t*26+(s-64)}return t-1}const Zn=/^\$?([A-Za-z]{1,3})\$?(\d+)$/;function Ye(n){const t=Zn.exec(n.trim());if(!t)return;const e=se(t[1]),s=Number(t[2])-1;if(!(e<0||e>=16384||s<0||s>=1048576))return{row:s,col:e}}const $e=({row:n,col:t})=>`${zt(t)}${n+1}`;function Ks(n,t){return{start:{row:Math.min(n.row,t.row),col:Math.min(n.col,t.col)},end:{row:Math.max(n.row,t.row),col:Math.max(n.col,t.col)}}}const Gn=(n,t,e)=>t>=n.start.row&&t<=n.end.row&&e>=n.start.col&&e<=n.end.col,Qn=/^[\p{L}_][\p{L}\p{N}_.]*$/u;function qs(n){return Qn.test(n)&&!Ye(n)&&!/^(TRUE|FALSE)$/i.test(n)?n:`'${n.replace(/'/g,"''")}'`}function ue(n,t={}){var r,i;const e=n.rowAbs?n.row:n.row+(((r=t.base)==null?void 0:r.row)??0),s=n.colAbs?n.col:n.col+(((i=t.base)==null?void 0:i.col)??0);return e<0||s<0?"#REF!":`${n.colAbs?"$":""}${zt(s)}${n.rowAbs?"$":""}${e+1}`}function hs(n,t){var e;return n.sheet===void 0?"":qs(((e=t.sheetName)==null?void 0:e.call(t,n.sheet))??`Sheet${n.sheet+1}`)+"!"}function Qt(n,t={}){const e=s=>Qt(s,t);switch(n.type){case"number":return String(n.value);case"string":return`"${n.value.replace(/"/g,'""')}"`;case"bool":return n.value?"TRUE":"FALSE";case"error":return n.code;case"ref":{const s=ue(n,t);return s==="#REF!"?s:hs(n,t)+s}case"range":{const s=ue(n.start,t),r=ue(n.end,t);return s==="#REF!"||r==="#REF!"?"#REF!":`${hs(n.start,t)}${s}:${r}`}case"name":return n.name;case"unary":return n.op+e(n.arg);case"percent":return e(n.arg)+"%";case"binary":return e(n.left)+n.op+e(n.right);case"paren":return`(${e(n.expr)})`;case"call":return`${n.name}(${n.args.map(e).join(",")})`}}function lt(n,t){switch(n.type){case"ref":case"range":case"name":return t(n);case"unary":case"percent":return lt(n.arg,t);case"binary":return lt(n.left,t),lt(n.right,t);case"paren":return lt(n.expr,t);case"call":for(const e of n.args)lt(e,t)}}function Nt(n,t){switch(n.type){case"unary":case"percent":return Nt(n.arg,t);case"binary":return Nt(n.left,t),Nt(n.right,t);case"paren":return Nt(n.expr,t);case"call":t(n.name);for(const e of n.args)Nt(e,t)}}function $t(n,t){switch(n.type){case"ref":case"range":case"name":return t(n);case"unary":case"percent":return n.arg=$t(n.arg,t),n;case"binary":return n.left=$t(n.left,t),n.right=$t(n.right,t),n;case"paren":return n.expr=$t(n.expr,t),n;case"call":for(let e=0;e<n.args.length;e++)n.args[e]=$t(n.args[e],t);return n;default:return n}}const Zs=["#DIV/0!","#VALUE!","#REF!","#NAME?","#N/A","#NUM!","#NULL!","#ERROR!","#CYCLE!","#SPILL!","#CALC!"];class ct{constructor(t,e){this.code=t,this.message=e}toString(){return this.code}}class z{constructor(t,e){this.values=t,this.origin=e}get height(){return this.values.length}get width(){var t;return((t=this.values[0])==null?void 0:t.length)??0}*flat(){for(const t of this.values)yield*t}}const w=n=>n instanceof ct,S=(n,t)=>new ct(n,t);function V(n){return typeof n=="string"&&n.length>1&&n[0]==="="}function at(n){if(n==null||n==="")return null;if(typeof n!="string")return n;if(n[0]==="'")return n.slice(1);const t=Ct(n);if(t!==void 0)return t;const e=n.toUpperCase();return e==="TRUE"?!0:e==="FALSE"?!1:n}const Jn=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?%?$/;function Ct(n){const t=n.trim();if(Jn.test(t))return t.endsWith("%")?Number(t.slice(0,-1))/100:Number(t)}function B(n){return!Number.isFinite(n)||Number.isInteger(n)?n:Number(n.toPrecision(15))}function K(n){if(w(n))return n;if(n===null)return 0;if(typeof n=="number")return n;if(typeof n=="boolean")return n?1:0;const t=Ct(n);return t===void 0?S("#VALUE!",`"${n}" is not a number`):t}function rt(n){return w(n)?n:n===null?"":typeof n=="boolean"?n?"TRUE":"FALSE":typeof n=="number"?Ke(n):n}function dt(n){if(w(n))return n;if(n===null)return!1;if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;const t=n.toUpperCase();return t==="TRUE"?!0:t==="FALSE"?!1:S("#VALUE!",`"${n}" is not a boolean`)}function Ke(n){return String(B(n))}function T(n){return n instanceof z?n.height===1&&n.width===1?n.values[0][0]:S("#VALUE!","Range used where a single value is expected"):n}const us=n=>typeof n=="number"?0:typeof n=="string"?1:2;function P(n,t){n===null&&(n=t===null?0:typeof t=="string"?"":typeof t=="boolean"?!1:0),t===null&&(t=typeof n=="string"?"":typeof n=="boolean"?!1:0);const e=us(n),s=us(t);if(e!==s)return e-s;if(typeof n=="string"){const o=n.toLowerCase(),l=t.toLowerCase();return o<l?-1:o>l?1:0}const r=Number(n),i=Number(t);return r<i?-1:r>i?1:0}const Gs=n=>n instanceof z&&(n.height!==1||n.width!==1),tt=n=>n instanceof z?n:new z([[n]]);function At(n,t){let e=0,s=0;for(const i of n)Gs(i)&&(e=Math.max(e,i.height),s=Math.max(s,i.width));if(e===0)return t(...n.map(T));const r=[];for(let i=0;i<e;i++){const o=[];for(let l=0;l<s;l++)o.push(t(...n.map(a=>tr(a,i,l))));r.push(o)}return new z(r)}function tr(n,t,e){if(!(n instanceof z))return n;const s=n.height===1?0:t,r=n.width===1?0:e;return s<n.height&&r<n.width?n.values[s][r]:S("#N/A")}const Qs=(n,t)=>n.values.map(e=>e[t]);function Le(n){return new z(Array.from({length:n.width},(t,e)=>Qs(n,e)))}const ne=new Map;function b(n,t){const e=typeof t=="function"?{impl:t}:t;ne.set(n.toUpperCase(),nr(n.toUpperCase(),e))}function er(n){ne.delete(n.toUpperCase())}const ze=n=>ne.get(n.toUpperCase()),sr=()=>[...ne.keys()].sort();function nr(n,t){const{minArgs:e=0,maxArgs:s=1/0}=t,r=i=>i<e||i>s?S("#VALUE!",`Wrong number of arguments to ${n}`):void 0;return{...t,impl:t.impl&&((i,o)=>r(i.length)??t.impl(i,o)),lazy:t.lazy&&((i,o)=>r(i.length)??t.lazy(i,o))}}const Q=n=>K(T(n));function wt(n){const t=[];for(const e of n)if(e instanceof z)for(const s of e.flat()){if(w(s))return s;typeof s=="number"&&t.push(s)}else{if(e===null)continue;const s=K(e);if(w(s))return s;t.push(s)}return t}function G(n){return t=>At(t,(...e)=>{const s=[];for(const i of e){const o=K(i);if(w(o))return o;s.push(o)}const r=n(...s);return w(r)?r:Number.isFinite(r)?B(r):S("#NUM!")})}function Vt(n){return t=>At(t,(...e)=>{const s=[];for(const r of e){const i=rt(r);if(w(i))return i;s.push(i)}return n(...s)})}const mt=n=>n instanceof z?n:new z([[n]]);class re{constructor(){v(this,"sum",0);v(this,"comp",0)}add(t){const e=this.sum+t;this.comp+=Math.abs(this.sum)>=Math.abs(t)?this.sum-e+t:t-e+this.sum,this.sum=e}get value(){return this.sum+this.comp}}const Jt=n=>{const t=new re;return n.forEach(e=>t.add(e)),t.value};function rr(n,t){const e=Math.pow(10,Math.trunc(t));return B(Math.sign(n)*Math.round(Math.abs(n)*e+1e-9)/e)}function qe(n,t=!0){let e="";for(let s=0;s<n.length;s++){const r=n[s];r==="~"&&s+1<n.length?e+=ds(n[++s]):r==="*"?e+="[\\s\\S]*":r==="?"?e+="[\\s\\S]":e+=ds(r)}return new RegExp(t?`^${e}$`:e,"i")}const ds=n=>n.replace(/[.*+?^${}()|[\]\\/-]/g,"\\$&"),Js=n=>/[*?~]/.test(n);function Ze(n){if(typeof n!="string")return r=>r!==null&&!w(r)&&P(r,n)===0;const t=/^(<=|>=|<>|=|<|>)?(.*)$/s.exec(n),e=t[1]??"=",s=at(t[2]);if(s===null)return e==="<>"?r=>r!==null&&r!=="":r=>r===null||r==="";if(typeof s=="string"&&(e==="="||e==="<>")&&Js(s)){const r=qe(s);return e==="="?i=>typeof i=="string"&&r.test(i):i=>!(typeof i=="string"&&r.test(i))}return r=>{if(w(r)||e!=="="&&e!=="<>"&&(r===null||typeof r!=typeof s)||e==="="&&r===null)return!1;const i=P(r,s);switch(e){case"=":return i===0;case"<>":return i!==0;case"<":return i<0;case"<=":return i<=0;case">":return i>0;default:return i>=0}}}function tn(n,t){let e=0,s=n.length-1,r=-1;for(;e<=s;){const i=e+s>>1,o=n[i];o===null||P(o,t)<=0?(o!==null&&typeof o==typeof t&&(r=i),e=i+1):s=i-1}return r}function en(n,t){const e=typeof t=="string"?Ze("="+t):void 0;return n.findIndex(s=>e?e(s):s!==null&&!w(s)&&P(s,t)===0)}function sn(n,t){const e=T(n[0]);if(w(e))return e;const s=mt(n[1]),r=Q(n[2]);if(w(r))return r;const i=n.length>3?dt(T(n[3])):!0;if(w(i))return i;const o=t?s.width:s.height,l=Math.trunc(r);if(l<1)return S("#VALUE!");if(l>o)return S("#REF!");const a=t?s.values.map(h=>h[0]):s.values[0],c=i?tn(a,e):en(a,e);return c<0?S("#N/A"):t?s.values[c][l-1]:s.values[l-1][c]}function Ge(n,t){var a;const e=mt(n[0]),s=T(n[1]);if(w(s))return s;const r=n[2]!==void 0?mt(n[2]):e,i=Ze(s),o=new re;let l=0;for(let c=0;c<e.height;c++)for(let h=0;h<e.width;h++){if(!i(e.values[c][h]))continue;if(t==="count"){l++;continue}const u=((a=r.values[c])==null?void 0:a[h])??null;if(w(u))return u;typeof u=="number"&&(o.add(u),l++)}return t==="count"?l:t==="sum"?B(o.value):l===0?S("#DIV/0!"):B(o.value/l)}b("SUM",{aggregate:!0,impl:n=>{const t=wt(n);return w(t)?t:B(Jt(t))}});b("AVERAGE",{minArgs:1,aggregate:!0,impl:n=>{const t=wt(n);return w(t)?t:t.length===0?S("#DIV/0!"):B(Jt(t)/t.length)}});b("MIN",{aggregate:!0,impl:n=>{const t=wt(n);return w(t)?t:t.length?Math.min(...t):0}});b("MAX",{aggregate:!0,impl:n=>{const t=wt(n);return w(t)?t:t.length?Math.max(...t):0}});b("COUNT",{aggregate:!0,impl:n=>{let t=0;for(const e of n)if(e instanceof z)for(const s of e.flat())typeof s=="number"&&t++;else e!==null&&!w(K(e))&&t++;return t}});b("COUNTA",{aggregate:!0,impl:n=>{let t=0;for(const e of n)if(e instanceof z)for(const s of e.flat())s!==null&&t++;else e!==null&&t++;return t}});b("COUNTBLANK",{minArgs:1,maxArgs:1,impl:([n])=>{let t=0;for(const e of mt(n).flat())(e===null||e==="")&&t++;return t}});b("IF",{minArgs:2,maxArgs:3,lazy:(n,t)=>{const e=t.evaluate(n[0]);if(Gs(e)){const r=t.evaluate(n[1]),i=n.length>2?t.evaluate(n[2]):!1;return At([e,r,i],(o,l,a)=>{const c=dt(o);return w(c)?c:c?l:a})}const s=dt(T(e));return w(s)?s:s?t.evaluate(n[1]):n.length>2?t.evaluate(n[2]):!1}});b("IFERROR",{minArgs:2,maxArgs:2,lazy:(n,t)=>{const e=t.evaluate(n[0]);return w(e)?t.evaluate(n[1]):e}});b("IFNA",{minArgs:2,maxArgs:2,lazy:(n,t)=>{const e=t.evaluate(n[0]);return w(e)&&e.code==="#N/A"?t.evaluate(n[1]):e}});function Qe(n,t,e){let s=e,r=!1;for(const i of n){const o=i instanceof z?[...i.flat()].filter(l=>typeof l!="string"&&l!==null):[i];for(const l of o){const a=dt(l);if(w(a))return a;s=t(s,a),r=!0}}return r?s:S("#VALUE!")}b("AND",{minArgs:1,aggregate:!0,impl:n=>Qe(n,(t,e)=>t&&e,!0)});b("OR",{minArgs:1,aggregate:!0,impl:n=>Qe(n,(t,e)=>t||e,!1)});b("NOT",{minArgs:1,maxArgs:1,impl:([n])=>{const t=dt(T(n));return w(t)?t:!t}});b("ABS",{minArgs:1,maxArgs:1,impl:G(Math.abs)});b("INT",{minArgs:1,maxArgs:1,impl:G(Math.floor)});b("SQRT",{minArgs:1,maxArgs:1,impl:G(Math.sqrt)});b("POWER",{minArgs:2,maxArgs:2,impl:G(Math.pow)});b("PI",{maxArgs:0,impl:()=>Math.PI});b("MOD",{minArgs:2,maxArgs:2,impl:n=>{const[t,e]=n.map(Q);return w(t)?t:w(e)?e:e===0?S("#DIV/0!"):B(t-e*Math.floor(t/e))}});b("ROUND",{minArgs:1,maxArgs:2,impl:G((n,t=0)=>rr(n,t))});b("ROUNDUP",{minArgs:1,maxArgs:2,impl:G((n,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(n)*Math.ceil(Math.abs(n)*e-1e-9)/e})});b("ROUNDDOWN",{minArgs:1,maxArgs:2,impl:G((n,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.sign(n)*Math.floor(Math.abs(n)*e+1e-9)/e})});b("CONCATENATE",{minArgs:1,impl:Vt((...n)=>n.join(""))});b("CONCAT",{minArgs:1,impl:n=>{let t="";for(const e of n)for(const s of mt(e).flat()){const r=rt(s);if(w(r))return r;t+=r}return t}});b("LEN",{minArgs:1,maxArgs:1,impl:Vt(n=>n.length)});b("UPPER",{minArgs:1,maxArgs:1,impl:Vt(n=>n.toUpperCase())});b("LOWER",{minArgs:1,maxArgs:1,impl:Vt(n=>n.toLowerCase())});b("TRIM",{minArgs:1,maxArgs:1,impl:Vt(n=>n.trim().replace(/ {2,}/g," "))});b("LEFT",{minArgs:1,maxArgs:2,impl:n=>{const t=rt(T(n[0])),e=n.length>1?Q(n[1]):1;return w(t)?t:w(e)?e:e<0?S("#VALUE!"):t.slice(0,e)}});b("RIGHT",{minArgs:1,maxArgs:2,impl:n=>{const t=rt(T(n[0])),e=n.length>1?Q(n[1]):1;return w(t)?t:w(e)?e:e<0?S("#VALUE!"):e===0?"":t.slice(-e)}});b("MID",{minArgs:3,maxArgs:3,impl:n=>{const t=rt(T(n[0])),e=Q(n[1]),s=Q(n[2]);return w(t)?t:w(e)?e:w(s)?s:e<1||s<0?S("#VALUE!"):t.substr(e-1,s)}});b("ISBLANK",{minArgs:1,maxArgs:1,impl:([n])=>T(n)===null});b("ISNUMBER",{minArgs:1,maxArgs:1,impl:([n])=>typeof T(n)=="number"});b("ISTEXT",{minArgs:1,maxArgs:1,impl:([n])=>typeof T(n)=="string"});b("ISERROR",{minArgs:1,maxArgs:1,impl:([n])=>w(T(n))});b("NA",{maxArgs:0,impl:()=>S("#N/A")});b("VLOOKUP",{minArgs:3,maxArgs:4,impl:n=>sn(n,!0)});b("HLOOKUP",{minArgs:3,maxArgs:4,impl:n=>sn(n,!1)});b("INDEX",{minArgs:2,maxArgs:3,impl:n=>{const t=mt(n[0]),e=Q(n[1]),s=n.length>2?Q(n[2]):1;if(w(e))return e;if(w(s))return s;const[r,i]=t.height===1&&n.length===2?[1,e]:[e,s];return r<1||i<1||r>t.height||i>t.width?S("#REF!"):t.values[r-1][i-1]}});b("MATCH",{minArgs:2,maxArgs:3,impl:n=>{const t=T(n[0]);if(w(t))return t;const e=mt(n[1]);if(e.height>1&&e.width>1)return S("#N/A");const s=[...e.flat()],r=n.length>2?Q(n[2]):1;if(w(r))return r;let i;if(r===0)i=en(s,t);else if(r>0)i=tn(s,t);else{i=-1;for(let o=0;o<s.length&&(s[o]!==null&&P(s[o],t)>=0);o++)i=o}return i<0?S("#N/A"):i+1}});b("SUMIF",{minArgs:2,maxArgs:3,impl:n=>Ge(n,"sum")});b("COUNTIF",{minArgs:2,maxArgs:2,impl:n=>Ge(n,"count")});b("AVERAGEIF",{minArgs:2,maxArgs:3,impl:n=>Ge(n,"average")});b("SUMPRODUCT",{minArgs:1,impl:n=>{const t=n.map(mt),{height:e,width:s}=t[0];if(t.some(i=>i.height!==e||i.width!==s))return S("#VALUE!");const r=new re;for(let i=0;i<e;i++)for(let o=0;o<s;o++){let l=1;for(const a of t){const c=a.values[i][o];if(w(c))return c;l*=typeof c=="number"?c:0}r.add(l)}return B(r.value)}});const Je=864e5,nn=25569,te=60;function rn(n,t,e){const s=new Date(0);return s.setUTCFullYear(n,t-1,e),s}function on(n,t){return rn(n,t+1,0).getUTCDate()}function Tt(n,t,e){if(n===1900&&t===2&&e===29)return te;const s=Math.round(rn(n,t,e).getTime()/Je)+nn;return s<=te?s-1:s}function gt(n){const t=Math.floor(n);if(t===te)return{year:1900,month:2,day:29};const e=new Date(((t<te?t+1:t)-nn)*Je);return{year:e.getUTCFullYear(),month:e.getUTCMonth()+1,day:e.getUTCDate()}}const ir=/^(\d{4})-(\d{1,2})-(\d{1,2})$/,or=/^(\d{1,2})([./])(\d{1,2})\2(\d{4})$/;function ie(n){const t=n.trim();let e=ir.exec(t),s;if(e?s=[Number(e[1]),Number(e[2]),Number(e[3])]:(e=or.exec(t))&&(s=[Number(e[4]),Number(e[3]),Number(e[1])]),!s)return;const[r,i,o]=s;if(!(r<1900||i<1||i>12||o<1||o>on(r,i)))return Tt(r,i,o)}const vt=(n,t=2)=>String(n).padStart(t,"0");function ts(n,t="YYYY-MM-DD"){const{year:e,month:s,day:r}=gt(n),i=Math.round((n-Math.floor(n))*86400),o={YYYY:vt(e,4),YY:vt(e%100),MM:vt(s),M:String(s),DD:vt(r),D:String(r),HH:vt(Math.floor(i/3600)%24),mm:vt(Math.floor(i/60)%60),ss:vt(i%60)};return t.replace(/YYYY|YY|MM|M|DD|D|HH|mm|ss/g,l=>o[l])}function ln(n,t=new Date){const e=Tt(t.getFullYear(),t.getMonth()+1,t.getDate());if(!n)return e;const s=((t.getHours()*60+t.getMinutes())*60+t.getSeconds())*1e3+t.getMilliseconds();return e+s/Je}let an=()=>new Date,cn=Math.random;function lr(n){an=n??(()=>new Date)}function ar(n){cn=n??Math.random}const hn=()=>an(),un=()=>cn();function St(n){const t=T(n);if(typeof t=="string"){const s=ie(t);if(s!==void 0)return s}const e=K(t);return w(e)?e:e<0?S("#NUM!","Negative date"):Math.floor(e)}function oe(n){const t=K(T(n));return w(t)?t:Math.trunc(t)}function cr(n,t){const e=[];for(const s of n){const r=t(s);if(w(r))return r;e.push(r)}return e}const es=n=>t=>{const e=St(t[0]);return w(e)?e:n(gt(e))};function dn(n,t,e){const{year:s,month:r,day:i}=gt(n),o=s*12+(r-1)+t,l=Math.floor(o/12),a=o-l*12+1,c=on(l,a),h=Tt(l,a,e?c:Math.min(i,c));return h<1?S("#NUM!"):h}b("DATE",{minArgs:3,maxArgs:3,impl:n=>{const t=cr(n,oe);if(w(t))return t;let[e]=t;if(e<0||e>9999)return S("#NUM!");e<1900&&(e+=1900);const s=Tt(e,t[1],t[2]);return s<0?S("#NUM!"):s}});b("YEAR",{minArgs:1,maxArgs:1,impl:es(n=>n.year)});b("MONTH",{minArgs:1,maxArgs:1,impl:es(n=>n.month)});b("DAY",{minArgs:1,maxArgs:1,impl:es(n=>n.day)});b("TODAY",{maxArgs:0,volatile:!0,impl:()=>ln(!1,hn())});b("NOW",{maxArgs:0,volatile:!0,impl:()=>ln(!0,hn())});b("WEEKDAY",{minArgs:1,maxArgs:2,impl:n=>{const t=St(n[0]),e=n.length>1?oe(n[1]):1;if(w(t))return t;if(w(e))return e;const s=((t-1)%7+7)%7;switch(e){case 1:return s+1;case 2:return(s+6)%7+1;case 3:return(s+6)%7;default:return S("#NUM!")}}});b("EDATE",{minArgs:2,maxArgs:2,impl:n=>{const t=St(n[0]),e=oe(n[1]);return w(t)?t:w(e)?e:dn(t,e,!1)}});b("EOMONTH",{minArgs:2,maxArgs:2,impl:n=>{const t=St(n[0]),e=oe(n[1]);return w(t)?t:w(e)?e:dn(t,e,!0)}});b("DAYS",{minArgs:2,maxArgs:2,impl:n=>{const[t,e]=n.map(St);return w(t)?t:w(e)?e:t-e}});b("DATEDIF",{minArgs:3,maxArgs:3,impl:n=>{const t=St(n[0]),e=St(n[1]),s=rt(T(n[2]));if(w(t))return t;if(w(e))return e;if(w(s))return s;if(t>e)return S("#NUM!","Start date is after end date");const r=gt(t),i=gt(e),o=(i.year-r.year)*12+(i.month-r.month)-(i.day<r.day?1:0);switch(s.toUpperCase()){case"D":return e-t;case"M":return o;case"Y":return Math.floor(o/12);case"YM":return o%12;default:return S("#NUM!",`Unknown DATEDIF unit "${s}"`)}}});const ft=(n,t)=>B(n/t);b("CEILING",{minArgs:1,maxArgs:2,impl:G((n,t=1)=>t===0?0:n>0&&t<0?S("#NUM!"):t<0?-Math.ceil(ft(-n,-t))*-t:Math.ceil(ft(n,t))*t)});b("FLOOR",{minArgs:1,maxArgs:2,impl:G((n,t=1)=>t===0?n===0?0:S("#DIV/0!"):n>0&&t<0?S("#NUM!"):t<0?-Math.floor(ft(-n,-t))*-t:Math.floor(ft(n,t))*t)});b("CEILING.MATH",{minArgs:1,maxArgs:3,impl:G((n,t=1,e=0)=>{const s=Math.abs(t);return s===0?0:n<0&&e!==0?-Math.ceil(ft(-n,s))*s:Math.ceil(ft(n,s))*s})});b("FLOOR.MATH",{minArgs:1,maxArgs:3,impl:G((n,t=1,e=0)=>{const s=Math.abs(t);return s===0?0:n<0&&e!==0?-Math.floor(ft(-n,s))*s:Math.floor(ft(n,s))*s})});b("MROUND",{minArgs:2,maxArgs:2,impl:G((n,t)=>{if(t===0)return 0;if(n*t<0)return S("#NUM!");const e=ft(n,t);return Math.sign(e)*Math.round(Math.abs(e))*t})});b("TRUNC",{minArgs:1,maxArgs:2,impl:G((n,t=0)=>{const e=Math.pow(10,Math.trunc(t));return Math.trunc(B(n*e))/e})});b("SIGN",{minArgs:1,maxArgs:1,impl:G(n=>Math.sign(n))});b("PRODUCT",{minArgs:1,aggregate:!0,impl:n=>{const t=wt(n);if(w(t))return t;if(t.length===0)return 0;const e=t.reduce((s,r)=>s*r,1);return Number.isFinite(e)?B(e):S("#NUM!")}});b("RAND",{maxArgs:0,volatile:!0,impl:()=>un()});b("RANDBETWEEN",{minArgs:2,maxArgs:2,volatile:!0,impl:G((n,t)=>{const e=Math.ceil(n),s=Math.floor(t);return e>s?S("#NUM!"):e+Math.floor(un()*(s-e+1))})});function pt(n,t){return{minArgs:n,aggregate:!0,impl:e=>{const s=wt(e);if(w(s))return s;const r=t(s);return w(r)?r:Number.isFinite(r)?B(r):S("#NUM!")}}}function hr(n){if(n.length===0)return S("#NUM!");const t=[...n].sort((s,r)=>s-r),e=t.length>>1;return t.length%2?t[e]:(t[e-1]+t[e])/2}function fn(n){const t=new Map;for(const r of n)t.set(r,(t.get(r)??0)+1);let e,s=1;for(const[r,i]of t)i>s&&(e=r,s=i);return e===void 0?S("#N/A"):e}function It(n,t){const e=n.length;if(e<(t?2:1))return S("#DIV/0!");const s=Jt(n)/e;return Jt(n.map(r=>(r-s)*(r-s)))/(t?e-1:e)}const ss=n=>w(n)?n:Math.sqrt(n);b("MEDIAN",pt(1,hr));b("MODE.SNGL",pt(1,fn));b("MODE",pt(1,fn));b("VAR.S",pt(1,n=>It(n,!0)));b("VAR",pt(1,n=>It(n,!0)));b("VAR.P",pt(1,n=>It(n,!1)));b("STDEV.S",pt(1,n=>ss(It(n,!0))));b("STDEV",pt(1,n=>ss(It(n,!0))));b("STDEV.P",pt(1,n=>ss(It(n,!1))));function pn(n,t){const e=wt([n[0]]);if(w(e))return e;const s=Q(n[1]);if(w(s))return s;const r=Math.ceil(s);return r<1||r>e.length?S("#NUM!"):[...e].sort((o,l)=>t?l-o:o-l)[r-1]}b("LARGE",{minArgs:2,maxArgs:2,aggregate:!0,impl:n=>pn(n,!0)});b("SMALL",{minArgs:2,maxArgs:2,aggregate:!0,impl:n=>pn(n,!1)});function mn(n){const t=K(T(n[0]));if(w(t))return t;const e=wt([n[1]]);if(w(e))return e;const s=n.length>2?Q(n[2]):0;return w(s)?s:e.includes(t)?1+e.filter(r=>s===0?r>t:r<t).length:S("#N/A")}b("RANK.EQ",{minArgs:2,maxArgs:3,aggregate:!0,impl:mn});b("RANK",{minArgs:2,maxArgs:3,aggregate:!0,impl:mn});function ur(n,t){const e=gn(t);let s=e[0],r=n<0;n<0&&e.length>1&&e[1]!==""?(s=e[1],r=!1):n===0&&e.length>2&&e[2]!==""&&(s=e[2]);const i=ns(s);if(i.some(a=>a.kind==="date"))return gr(n<0&&!r?-n:n,i);const o=Math.abs(n);if(i.length===0||/^general$/i.test(s.trim()))return(r?"-":"")+Ke(o);const l=mr(o,i);return r&&/[1-9]/.test(l)?"-"+l:l}function dr(n,t){const e=gn(t),s=e.length>3?e[3]:e.length===1&&fr(e[0])?e[0]:void 0;if(s!==void 0)return ns(s).map(r=>r.kind==="lit"?r.text:r.kind==="ph"&&r.ch==="@"?n:"").join("")}const fr=n=>ns(n).some(t=>t.kind==="ph"&&t.ch==="@");function gn(n){const t=[];let e="";for(let s=0;s<n.length;s++){const r=n[s];if(r==='"'){const i=n.indexOf('"',s+1),o=i<0?n.length:i;e+=n.slice(s,o+1),s=o}else r==="\\"&&s+1<n.length?e+=r+n[++s]:r===";"?(t.push(e),e=""):e+=r}return t.push(e),t}const pr=/^(am\/pm|a\/p|y+|m+|d+|h+|s+)/i;function ns(n){const t=[];for(let e=0;e<n.length;e++){const s=n[e],r=n.slice(e);if(s==='"'){const i=n.indexOf('"',e+1),o=i<0?n.length:i;t.push({kind:"lit",text:n.slice(e+1,o)}),e=o}else if(s==="\\")e+1<n.length&&t.push({kind:"lit",text:n[++e]});else if(s==="_")e++,t.push({kind:"lit",text:" "});else if(s==="*")e++;else if(s==="["){const i=n.indexOf("]",e);e=i<0?n.length:i}else if("0#?.,%@".includes(s))t.push({kind:"ph",ch:s});else if((s==="E"||s==="e")&&/^[eE][+-]0/.test(r))t.push({kind:"ph",ch:"E"+r[1]}),e++;else{const i=pr.exec(r);i?(t.push({kind:"date",text:i[0]}),e+=i[0].length-1):t.push({kind:"lit",text:s})}}return t}const fs=n=>n.kind==="ph"&&(n.ch==="0"||n.ch==="#"||n.ch==="?");function mr(n,t){var C;const e=t.findIndex(fs);if(e<0)return t.map(y=>y.kind==="lit"?y.text:y.kind==="ph"&&y.ch==="%"?"%":"").join("");let s=t.length-1;for(;!fs(t[s]);)s--;for(;s+1<t.length&&t[s+1].kind==="ph"&&",.".includes(t[s+1].ch);)s++;let r=n;for(const y of t)y.kind==="ph"&&y.ch==="%"&&(r*=100);const i=t.slice(e,s+1).filter(y=>y.kind==="ph"),o=i.findIndex(y=>y.ch.startsWith("E")),l=o<0?i:i.slice(0,o),a=l.findIndex(y=>y.ch==="."),c=(a<0?l:l.slice(0,a)).map(y=>y.ch).join(""),h=a<0?"":l.slice(a+1).map(y=>y.ch).join("").replace(/[^0#?]/g,""),u=c.replace(/[^0#?]/g,""),d=/[0#?],+[0#?]/.test(c);r/=Math.pow(1e3,((C=/,+$/.exec(c))==null?void 0:C[0].length)??0);let p;if(o>=0){const y=i.slice(o),m=Math.max(y.slice(1).filter($=>$.ch==="0").length,1),f=y[0].ch[1];let x=r===0?0:Math.floor(Math.log10(r))-Math.max(u.length-1,0),A=r/Math.pow(10,x);const k=de(A,u,h,!1,a>=0);Number(k.replace(/,/g,""))>=Math.pow(10,Math.max(u.length,1))&&(x++,A=r/Math.pow(10,x));const F=String(Math.abs(x)).padStart(m,"0");p=de(A,u,h,!1,a>=0)+"E"+(x<0?"-":f==="+"?"+":"")+F}else p=de(r,u,h,d,a>=0);const g=y=>y.kind==="lit"?y.text:y.kind==="ph"&&",.%".includes(y.ch)?y.ch:"";return t.slice(0,e).map(g).join("")+p+t.slice(s+1).map(g).join("")}function de(n,t,e,s,r){const i=e.length,o=e.lastIndexOf("0")+1,l=(t.match(/0/g)??[]).length,a=Math.pow(10,i),c=B(Math.round(n*a+1e-9*Math.sign(n))/a);let[h,u=""]=c.toFixed(i).split(".");for(;u.length>o&&u.endsWith("0");)u=u.slice(0,-1);return h==="0"&&l===0&&(h=""),h=h.padStart(l,"0"),s&&(h=h.replace(/\B(?=(\d{3})+(?!\d))/g,",")),h+(r?"."+u:"")}const fe=["January","February","March","April","May","June","July","August","September","October","November","December"],ps=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Et=n=>String(n).padStart(2,"0");function gr(n,t){if(n<0)return;const e=Math.round(n*86400),s=Math.floor(e/86400),r=e-s*86400,{year:i,month:o,day:l}=gt(s),a=Math.floor(r/3600),c=Math.floor(r/60)%60,h=r%60,u=t.some(g=>g.kind==="date"&&/^a/i.test(g.text)),d=((s-1)%7+7)%7,p=(g,C)=>{for(let y=g+C;y>=0&&y<t.length;y+=C){const m=t[y];if(m.kind==="date")return m.text[0].toLowerCase()}};return t.map((g,C)=>{if(g.kind==="lit")return g.text;if(g.kind==="ph")return g.ch==="@"?"":g.ch;const y=g.text,m=y.toLowerCase(),f=y.length;switch(m[0]){case"y":return f<=2?Et(i%100):String(i).padStart(4,"0");case"m":return f<=2&&(p(C,-1)==="h"||p(C,1)==="s")?f===2?Et(c):String(c):f===1?String(o):f===2?Et(o):f===3?fe[o-1].slice(0,3):f===5?fe[o-1][0]:fe[o-1];case"d":return f===1?String(l):f===2?Et(l):f===3?ps[d].slice(0,3):ps[d];case"h":{const x=u?(a+11)%12+1:a;return f>=2?Et(x):String(x)}case"s":return f>=2?Et(h):String(h);default:{const x=a>=12;if(m==="a/p")return x?y[2]==="P"?"P":"p":y[0];const A=y.slice(0,2),k=y.slice(3,5);return x?k:A}}}).join("")}const wn=32767;function yt(n){return t=>At(t,(...e)=>e.find(w)??n(...e))}function J(n){return rt(n)}function Ht(n){const t=K(n);return w(t)?t:Math.trunc(t)}function yn(n){const t=n.trim(),e=Ct(t);if(e!==void 0)return e;if(/^[+-]?\d{1,3}(,\d{3})+(\.\d*)?%?$/.test(t))return Ct(t.replace(/,/g,""));const s=ie(t);if(s!==void 0)return s;const r=/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(t);if(r&&Number(r[2])<60&&Number(r[3]??0)<60)return(Number(r[1])*3600+Number(r[2])*60+Number(r[3]??0))/86400}b("TEXT",{minArgs:2,maxArgs:2,impl:yt((n,t)=>{const e=J(t);if(w(e))return e;if(typeof n=="boolean")return n?"TRUE":"FALSE";let s;if(typeof n=="string"){const r=yn(n);if(r===void 0)return dr(n,e)??n;s=r}else s=n??0;return ur(s,e)??S("#VALUE!","Value cannot be formatted as a date")})});b("VALUE",{minArgs:1,maxArgs:1,impl:yt(n=>typeof n=="number"?n:n===null?0:typeof n=="boolean"?S("#VALUE!"):yn(n)??S("#VALUE!",`"${n}" is not a number`))});function vn(n){return yt((t,e,s=1)=>{const r=J(t),i=J(e),o=Ht(s);if(w(r))return r;if(w(i))return i;if(w(o))return o;if(o<1||o>Math.max(i.length,1))return S("#VALUE!");let l;if(n)l=i.indexOf(r,o-1);else if(Js(r)){const a=qe(r,!1).exec(i.slice(o-1));l=a?a.index+o-1:-1}else l=i.toLowerCase().indexOf(r.toLowerCase(),o-1);return l<0?S("#VALUE!","Text not found"):l+1})}b("FIND",{minArgs:2,maxArgs:3,impl:vn(!0)});b("SEARCH",{minArgs:2,maxArgs:3,impl:vn(!1)});b("SUBSTITUTE",{minArgs:3,maxArgs:4,impl:yt((n,t,e,s)=>{const r=J(n),i=J(t),o=J(e);if(w(r))return r;if(w(i))return i;if(w(o))return o;if(i==="")return r;if(s===void 0)return r.split(i).join(o);const l=Ht(s);if(w(l))return l;if(l<1)return S("#VALUE!");let a=-1;for(let c=0;c<l;c++)if(a=r.indexOf(i,a+(c===0?0:i.length)),a<0)return r;return r.slice(0,a)+o+r.slice(a+i.length)})});b("REPLACE",{minArgs:4,maxArgs:4,impl:yt((n,t,e,s)=>{const r=J(n),i=Ht(t),o=Ht(e),l=J(s);return w(r)?r:w(i)?i:w(o)?o:w(l)?l:i<1||o<0?S("#VALUE!"):r.slice(0,i-1)+l+r.slice(i-1+o)})});b("REPT",{minArgs:2,maxArgs:2,impl:yt((n,t)=>{const e=J(n),s=Ht(t);return w(e)?e:w(s)?s:s<0||e.length*s>wn?S("#VALUE!"):e.repeat(s)})});b("PROPER",{minArgs:1,maxArgs:1,impl:yt(n=>{const t=J(n);if(w(t))return t;let e="",s=!1;for(const r of t){const i=new RegExp("\\p{L}","u").test(r);e+=i?s?r.toLowerCase():r.toUpperCase():r,s=i}return e})});b("EXACT",{minArgs:2,maxArgs:2,impl:yt((n,t)=>{const e=J(n),s=J(t);return w(e)?e:w(s)?s:e===s})});b("TEXTJOIN",{minArgs:3,impl:n=>{const t=[];for(const i of tt(n[0]).flat()){const o=rt(i);if(w(o))return o;t.push(o)}const e=dt(T(n[1]));if(w(e))return e;const s=[];for(const i of n.slice(2))for(const o of tt(i).flat()){if(w(o))return o;const l=rt(o);e&&l===""||s.push(l)}let r=s[0]??"";for(let i=1;i<s.length;i++)r+=(t.length?t[(i-1)%t.length]:"")+s[i];return r.length>wn?S("#VALUE!"):r}});function Bt(n,t){const e=t!=="count",s=n.slice(e?1:0);if(s.length===0||s.length%2)return S("#VALUE!","Criteria come in range/criterion pairs");const r=[];for(let u=0;u<s.length;u+=2){const d=T(s[u+1]);if(w(d))return d;r.push({range:tt(s[u]),test:Ze(d)})}const i=e?tt(n[0]):r[0].range,{height:o,width:l}=i;if(r.some(u=>u.range.height!==o||u.range.width!==l))return S("#VALUE!","Criteria ranges must have the same size");const a=new re;let c=0,h;for(let u=0;u<o;u++)for(let d=0;d<l;d++){if(!r.every(g=>g.test(g.range.values[u][d])))continue;if(!e){c++;continue}const p=i.values[u][d];if(w(p))return p;typeof p=="number"&&(a.add(p),c++,(h===void 0||(t==="max"?p>h:p<h))&&(h=p))}switch(t){case"count":return c;case"sum":return B(a.value);case"average":return c===0?S("#DIV/0!"):B(a.value/c);default:return h??0}}b("SUMIFS",{minArgs:3,impl:n=>Bt(n,"sum")});b("COUNTIFS",{minArgs:2,impl:n=>Bt(n,"count")});b("AVERAGEIFS",{minArgs:3,impl:n=>Bt(n,"average")});b("MAXIFS",{minArgs:3,impl:n=>Bt(n,"max")});b("MINIFS",{minArgs:3,impl:n=>Bt(n,"min")});b("ISNA",{minArgs:1,maxArgs:1,impl:([n])=>{const t=T(n);return w(t)&&t.code==="#N/A"}});b("ISLOGICAL",{minArgs:1,maxArgs:1,impl:([n])=>typeof T(n)=="boolean"});b("XOR",{minArgs:1,aggregate:!0,impl:n=>Qe(n,(t,e)=>t!==e,!1)});b("IFS",{minArgs:2,lazy:(n,t)=>{if(n.length%2)return S("#VALUE!","IFS needs test/value pairs");for(let e=0;e<n.length;e+=2){const s=dt(T(t.evaluate(n[e])));if(w(s))return s;if(s)return t.evaluate(n[e+1])}return S("#N/A","No test was true")}});function wr(n,t){return n!==null&&t!==null&&typeof n!=typeof t?!1:P(n,t)===0}b("SWITCH",{minArgs:3,lazy:(n,t)=>{const e=T(t.evaluate(n[0]));if(w(e))return e;const s=Math.floor((n.length-1)/2);for(let r=0;r<s;r++){const i=1+2*r,o=T(t.evaluate(n[i]));if(w(o))return o;if(wr(e,o))return t.evaluate(n[i+1])}return n.length%2===0?t.evaluate(n[n.length-1]):S("#N/A","No case matched")}});const yr=(n,t)=>n!==null&&!w(n)&&typeof n==typeof t;function vr(n,t,e,s){const r=n.map((l,a)=>a);s<0&&r.reverse();const i=e===2&&typeof t=="string"?qe(t):void 0;let o=-1;for(const l of r){const a=n[l];if(yr(a,t)){if(i?i.test(a):P(a,t)===0)return l;e===-1&&P(a,t)<0&&(o<0||P(a,n[o])>0)&&(o=l),e===1&&P(a,t)>0&&(o<0||P(a,n[o])<0)&&(o=l)}}return o}b("XLOOKUP",{minArgs:3,maxArgs:6,impl:n=>{const t=T(n[0]);if(w(t))return t;const e=tt(n[1]),s=tt(n[2]);if(e.width!==1&&e.height!==1)return S("#VALUE!","Lookup array must be one row or column");const r=e.width===1&&(e.height>1||s.height===1),i=r?e.height:e.width;if((r?s.height:s.width)!==i)return S("#VALUE!","Arrays must have the same length");const o=n.length>3&&n[3]!==null?n[3]:void 0,l=n.length>4&&n[4]!==null?Q(n[4]):0,a=n.length>5&&n[5]!==null?Q(n[5]):1;if(w(l))return l;if(w(a))return a;if(![0,-1,1,2].includes(l)||![1,-1,2,-2].includes(a))return S("#VALUE!");const c=r?Qs(e,0):e.values[0],h=vr(c,t,l,a);return h<0?o??S("#N/A"):r?s.width===1?s.values[h][0]:new z([s.values[h]]):s.height===1?s.values[0][h]:new z(s.values.map(u=>[u[h]]))}});b("CHOOSE",{minArgs:2,lazy:(n,t)=>{const e=K(T(t.evaluate(n[0])));if(w(e))return e;const s=Math.trunc(e);return s<1||s>=n.length?S("#VALUE!","CHOOSE index out of range"):t.evaluate(n[s])}});b("ROW",{maxArgs:1,positional:!0,lazy:(n,t)=>{if(n.length===0)return t.row+1;const e=t.reference(n[0]);return e?e.height===1?e.row+1:new z(Array.from({length:e.height},(s,r)=>[e.row+r+1])):bn(t.evaluate(n[0]))}});b("COLUMN",{maxArgs:1,positional:!0,lazy:(n,t)=>{if(n.length===0)return t.col+1;const e=t.reference(n[0]);return e?e.width===1?e.col+1:new z([Array.from({length:e.width},(s,r)=>e.col+r+1)]):bn(t.evaluate(n[0]))}});const bn=n=>w(n)?n:S("#VALUE!","Argument must be a reference");function xn(n){return{minArgs:1,maxArgs:1,lazy:(t,e)=>{const s=e.reference(t[0]);if(s)return n(s);const r=e.evaluate(t[0]);return w(r)?r:n(r instanceof z?r:{height:1,width:1})}}}b("ROWS",xn(n=>n.height));b("COLUMNS",xn(n=>n.width));const rs=()=>S("#CALC!","The result is an empty array");function _t(n,t,e){if(n.length<=t||n[t]===null)return e;const s=K(T(n[t]));return w(s)?s:Math.trunc(s)}function Te(n,t){return n.length<=t||n[t]===null?!1:dt(T(n[t]))}function le(n,t){return t?{rows:Le(n).values,rebuild:e=>Le(new z(e))}:{rows:n.values,rebuild:e=>new z(e)}}function br(n,t){const e=n??0,s=t??0,r=w(e),i=w(s);return r||i?r&&i?0:r?1:-1:P(e,s)}b("FILTER",{minArgs:2,maxArgs:3,impl:n=>{const t=tt(n[0]),e=tt(n[1]);let s;if(e.width===1&&e.height===t.height)s=!1;else if(e.height===1&&e.width===t.width)s=!0;else return S("#VALUE!","FILTER include must match the array height or width");const r=[...e.flat()],{rows:i,rebuild:o}=le(t,s),l=[];for(let a=0;a<i.length;a++){const c=r[a];if(typeof c=="string")return S("#VALUE!");const h=dt(c);if(w(h))return h;h&&l.push(i[a])}return l.length===0?n.length>2?n[2]:rs():o(l)}});function An(n){return w(n)||n===1||n===-1?n:S("#VALUE!","Sort order must be 1 or -1")}function Cn(n,t){const e=n.map((s,r)=>r);return e.sort((s,r)=>{for(const i of t){const o=br(i.values[s],i.values[r]);if(o!==0)return o*i.order}return s-r}),e.map(s=>n[s])}b("SORT",{minArgs:1,maxArgs:4,impl:n=>{var l;const t=tt(n[0]),e=_t(n,1,1),s=An(_t(n,2,1)),r=Te(n,3);if(w(e))return e;if(w(s))return s;if(w(r))return r;const{rows:i,rebuild:o}=le(t,r);return e<1||e>(((l=i[0])==null?void 0:l.length)??0)?S("#VALUE!","Sort index out of range"):o(Cn(i,[{values:i.map(a=>a[e-1]),order:s}]))}});b("SORTBY",{minArgs:2,impl:n=>{const t=tt(n[0]);let e;const s=[];for(let o=1;o<n.length;o+=2){const l=tt(n[o]),a=l.height===1&&l.width===t.width&&!(l.width===1&&l.height===t.height);if(!(a||l.width===1&&l.height===t.height)||e!==void 0&&e!==a)return S("#VALUE!","SORTBY arrays must match the array");e=a;const h=An(_t(n,o+1,1));if(w(h))return h;s.push({values:[...l.flat()],order:h})}const{rows:r,rebuild:i}=le(t,e??!1);return i(Cn(r,s))}});function xr(n){return n===null?"n:0":w(n)?"e:"+n.code:typeof n=="string"?"s:"+n.toLowerCase():(typeof n=="number"?"n:":"b:")+String(n)}b("UNIQUE",{minArgs:1,maxArgs:3,impl:n=>{const t=Te(n,1),e=Te(n,2);if(w(t))return t;if(w(e))return e;const{rows:s,rebuild:r}=le(tt(n[0]),t),i=new Map;for(const l of s){const a=l.map(xr).join("\0"),c=i.get(a);c?c.count++:i.set(a,{row:l,count:1})}const o=[...i.values()].filter(l=>!e||l.count===1).map(l=>l.row);return o.length?r(o):rs()}});b("SEQUENCE",{minArgs:1,maxArgs:4,impl:n=>{const t=_t(n,0,1),e=_t(n,1,1);if(w(t))return t;if(w(e))return e;const s=n.length>2&&n[2]!==null?K(T(n[2])):1,r=n.length>3&&n[3]!==null?K(T(n[3])):1;return w(s)?s:w(r)?r:t<0||e<0||t>1048576||e>16384?S("#VALUE!"):t===0||e===0?rs():t*e>1048576?S("#NUM!","SEQUENCE is too large"):new z(Array.from({length:t},(i,o)=>Array.from({length:e},(l,a)=>B(s+r*(o*e+a)))))}});b("TRANSPOSE",{minArgs:1,maxArgs:1,impl:([n])=>n instanceof z?Le(n):n});function Ie(n,t,e,s,r,i){const o=[];for(let l=e;l<=r;l++){const a=[];for(let c=s;c<=i;c++)a.push(n.getCellValue(t,l,c));o.push(a)}return new z(o,{sheet:t,row:e,col:s})}const ms=(n,t)=>t.getCellValue(n.sheet??t.sheet,n.rowAbs?n.row:n.row+t.row,n.colAbs?n.col:n.col+t.col);function st(n,t){switch(n.type){case"number":return n.value;case"string":return n.value;case"bool":return n.value;case"error":return S(n.code);case"ref":return ms(n,t);case"range":{const{start:e,end:s}=n,r=e.sheet??t.sheet,i=e.rowAbs?e.row:e.row+t.row,o=s.rowAbs?s.row:s.row+t.row,l=e.colAbs?e.col:e.col+t.col,a=s.colAbs?s.col:s.col+t.col,[c,h,u,d]=[Math.min(i,o),Math.max(i,o),Math.min(l,a),Math.max(l,a)];return t.getRange?t.getRange(r,c,u,h,d):Ie(t,r,c,u,h,d)}case"name":return n.name===""?null:t.resolveName?t.resolveName(n.name):S("#NAME?",`Unknown name "${n.name}"`);case"paren":return st(n.expr,t);case"unary":{const e=st(n.arg,t);return e instanceof z?At([e],s=>gs(n.op,s)):gs(n.op,e)}case"percent":{const e=st(n.arg,t);return e instanceof z?At([e],ws):ws(e)}case"binary":{const e=st(n.left,t),s=st(n.right,t);if(!(e instanceof z)&&!(s instanceof z))return ys(n.op,e,s);const r=n.op;return At([e,s],(i,o)=>ys(r,i,o))}case"call":{const e=ze(n.name);if(!e)return S("#NAME?",`Unknown function ${n.name}`);const s={evaluate:i=>st(i,t),sheet:t.sheet,row:t.row,col:t.col,reference:i=>Sn(i,t)};if(e.lazy)return e.lazy(n.args,s);const r=n.args.map(i=>e.aggregate&&i.type==="ref"?new z([[ms(i,t)]]):st(i,t));return e.impl(r,s)}}}function Sn(n,t){if(n.type==="paren")return Sn(n.expr,t);if(n.type==="ref"){const e=n.rowAbs?n.row:n.row+t.row,s=n.colAbs?n.col:n.col+t.col;return{sheet:n.sheet??t.sheet,row:e,col:s,height:1,width:1}}if(n.type==="range"||n.type==="name"){const e=st(n,t);if(e instanceof z&&e.origin)return{...e.origin,height:e.height,width:e.width}}}function gs(n,t){const e=K(t);return w(e)||n==="+"?e:-e}function ws(n){const t=K(n);return w(t)?t:t/100}function ys(n,t,e){if(w(t))return t;if(w(e))return e;switch(n){case"&":{const o=rt(t),l=rt(e);return w(o)?o:w(l)?l:o+l}case"=":return P(t,e)===0;case"<>":return P(t,e)!==0;case"<":return P(t,e)<0;case"<=":return P(t,e)<=0;case">":return P(t,e)>0;case">=":return P(t,e)>=0}const s=K(t),r=K(e);if(w(s))return s;if(w(r))return r;let i;switch(n){case"+":i=s+r;break;case"-":i=s-r;break;case"*":i=s*r;break;case"/":if(r===0)return S("#DIV/0!");i=s/r;break;case"^":if(s===0&&r===0)return S("#NUM!");i=Math.pow(s,r);break;default:return S("#ERROR!",`Unknown operator ${n}`)}return Number.isFinite(i)?B(i):S("#NUM!")}class W extends Error{constructor(t,e){super(t),this.pos=e}}const Ar=/(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/y,Cr=/[\p{L}_][\p{L}\p{N}_.]*/uy,Sr=/([\p{L}_][\p{L}\p{N}_.]*)!/uy,Er=/[\p{L}_]/u,vs=/(\$?)([A-Za-z]{1,3})(\$?)(\d+)/y,Mr=["<=",">=","<>"],kr="+-*/^&=<>%(),;:";function Rr(n){const t=[];let e=0;const s=i=>(i.lastIndex=e,i.exec(n));for(;e<n.length;){const i=n[e];if(i===" "||i===" "||i===`
2
+ `||i==="\r"){e++;continue}if(i>="0"&&i<="9"||i==="."&&/\d/.test(n[e+1]??"")){const l=s(Ar);t.push({type:"number",value:Number(l[0]),pos:e}),e+=l[0].length;continue}if(i==='"'){const l=e;let a="";for(e++;;){if(e>=n.length)throw new W("Unterminated string",l);if(n[e]==='"'){if(n[e+1]==='"'){a+='"',e+=2;continue}e++;break}a+=n[e++]}t.push({type:"string",value:a,pos:l});continue}if(i==="#"){const l=Zs.find(a=>n.startsWith(a,e)||n.toUpperCase().startsWith(a,e));if(!l)throw new W("Unknown error literal",e);t.push({type:"error",value:l,pos:e}),e+=l.length;continue}if(i==="'"){const l=e;let a="";for(e++;;){if(e>=n.length)throw new W("Unterminated sheet name",l);if(n[e]==="'"){if(n[e+1]==="'"){a+="'",e+=2;continue}e++;break}a+=n[e++]}if(n[e]!=="!")throw new W('Expected "!" after sheet name',e);e=r(a,l,e+1);continue}if(i==="$"||Er.test(i)){const l=i==="$"?null:s(Sr);if(l){e=r(l[1],e,e+l[0].length);continue}const a=bs(n,e),c=i==="$"?null:s(Cr);if(c&&Fr(n,e+c[0].length)==="("){t.push({type:"func",value:c[0].toUpperCase(),pos:e}),e+=c[0].length;continue}if(a&&(!c||a.length>=c[0].length)){t.push({...a.token,pos:e}),e+=a.length;continue}if(!c)throw new W("Invalid reference",e);const h=c[0].toUpperCase();h==="TRUE"||h==="FALSE"?t.push({type:"bool",value:h==="TRUE",pos:e}):t.push({type:"name",value:c[0],pos:e}),e+=c[0].length;continue}const o=n.slice(e,e+2);if(Mr.includes(o)){t.push({type:"op",value:o,pos:e}),e+=2;continue}if(kr.includes(i)){t.push({type:"op",value:i===";"?",":i,pos:e}),e++;continue}throw new W(`Unexpected character "${i}"`,e)}return t.push({type:"eof",pos:n.length}),t;function r(i,o,l){const a=bs(n,l);if(!a)throw new W('Expected cell reference after "!"',l);return t.push({...a.token,sheet:i,pos:o}),l+a.length}}function Fr(n,t){for(;t<n.length&&n[t]===" ";)t++;return n[t]}function bs(n,t){vs.lastIndex=t;const e=vs.exec(n);if(!e||/[\p{L}\p{N}_]/u.test(n[t+e[0].length]??""))return;const s=se(e[2]),r=Number(e[4])-1;if(!(s<0||s>=16384||r<0||r>=1048576))return{length:e[0].length,token:{type:"ref",row:r,col:s,colAbs:e[1]==="$",rowAbs:e[3]==="$"}}}const Dr={"=":1,"<>":1,"<":1,"<=":1,">":1,">=":1,"&":2,"+":3,"-":3,"*":4,"/":4,"^":5};function Oe(n,t={}){var y,m;const e=Rr(n),s=((y=t.base)==null?void 0:y.row)??0,r=((m=t.base)==null?void 0:m.col)??0;let i=0;const o=(f,x)=>({type:"ref",row:f.rowAbs?f.row:f.row-s,col:f.colAbs?f.col:f.col-r,rowAbs:f.rowAbs,colAbs:f.colAbs,...x===void 0?{}:{sheet:x}}),l=()=>e[i],a=()=>e[i++],c=(f,x)=>f.type==="op"&&f.value===x,h=f=>{const x=a();if(!c(x,f))throw new W(`Expected "${f}"`,x.pos)};function u(f){let x=d();for(;;){const A=l();if(A.type!=="op")break;const k=Dr[A.value];if(k===void 0||k<f)break;a();const F=u(k+1);x={type:"binary",op:A.value,left:x,right:F}}return x}function d(){const f=l();if(c(f,"-")||c(f,"+"))return a(),{type:"unary",op:c(f,"-")?"-":"+",arg:d()};let x=p();for(;c(l(),"%");)a(),x={type:"percent",arg:x};return x}function p(){var x,A;const f=a();switch(f.type){case"number":return{type:"number",value:f.value};case"string":return{type:"string",value:f.value};case"bool":return{type:"bool",value:f.value};case"error":return{type:"error",code:f.value};case"name":return{type:"name",name:f.value};case"ref":{const k=f.sheet===void 0||(x=t.resolveSheet)==null?void 0:x.call(t,f.sheet),F=f.sheet!==void 0&&k===void 0,$=o(f,k);if(!c(l(),":"))return F?{type:"error",code:"#REF!"}:$;a();const L=a();if(L.type!=="ref")throw new W('Expected cell reference after ":"',L.pos);if(L.sheet!==void 0&&L.sheet.toUpperCase()!==((A=f.sheet)==null?void 0:A.toUpperCase()))throw new W("A range cannot span sheets",L.pos);return F?{type:"error",code:"#REF!"}:{type:"range",start:$,end:o(L,k)}}case"func":{h("(");const k=[];if(!c(l(),")"))for(;c(l(),",")||c(l(),")")?k.push({type:"name",name:""}):k.push(u(1)),!!c(l(),",");)a();return h(")"),{type:"call",name:f.value,args:k}}case"op":if(f.value==="("){const k=u(1);return h(")"),{type:"paren",expr:k}}throw new W(`Unexpected "${f.value}"`,f.pos);case"eof":throw new W("Unexpected end of formula",f.pos)}}const g=u(1),C=l();if(C.type!=="eof")throw new W("Unexpected token",C.pos);return g}const ee=-1;class Nr{constructor(t){v(this,"sheet");v(this,"axis");this.ch=t,this.sheet=t.sheet,this.axis=t.axis}index(t){return Ue(this.ch,t)}span(t,e){return Lr(this.ch,t,e)}}class $r{constructor(t,e,s,r,i){this.sheet=t,this.axis=e,this.start=s,this.count=r,this.target=i}index(t){const{start:e,count:s,target:r}=this,i=e+s;return r>i?t<e||t>=r?t:t<i?t+r-i:t-s:t<r||t>=i?t:t>=e?t-(e-r):t+s}span(t,e){const s=this.index(t),r=this.index(e);return s<=r?[s,r]:[r,s]}}function En(n,t,e){return e>n+t?{start:e-t,count:t,target:n}:e<n?{start:e,count:t,target:n+t}:{start:n,count:t,target:e}}function Mn(n,t,e,s){return s[0]-t!==s[1]-e||t!==e&&s[0]!==n.index(t)}function Ue(n,t){return t<n.index?t:n.remove?t<n.index+n.count?ee:t-n.count:t+n.count}function Lr(n,t,e){if(!n.remove)return[Ue(n,t),Ue(n,e)];const s=n.index+n.count;if(!(t>=n.index&&e<s))return[t<n.index?t:t<s?n.index:t-n.count,e<n.index?e:e<s?n.index-1:e-n.count]}const Pe=()=>({type:"error",code:"#REF!"});class zr{constructor(t){v(this,"text",!1);v(this,"meaning",!1);v(this,"homeSheet",0);v(this,"homeBefore",0);v(this,"homeAfter",0);v(this,"isRow");this.map=t,this.isRow=t.axis==="row"}adjust(t,e,s,r){return this.text=this.meaning=!1,this.homeSheet=e,this.homeBefore=s,this.homeAfter=r,this.walk(t)}walk(t){switch(t.type){case"ref":return this.ref(t);case"range":return this.range(t);case"unary":case"percent":return t.arg=this.walk(t.arg),t;case"binary":return t.left=this.walk(t.left),t.right=this.walk(t.right),t;case"paren":return t.expr=this.walk(t.expr),t;case"call":for(let e=0;e<t.args.length;e++)t.args[e]=this.walk(t.args[e]);return t;default:return t}}absolute(t){return this.isRow?t.rowAbs?t.row:t.row+this.homeBefore:t.colAbs?t.col:t.col+this.homeBefore}store(t,e){this.isRow?t.row=t.rowAbs?e:e-this.homeAfter:t.col=t.colAbs?e:e-this.homeAfter}ref(t){const e=this.absolute(t),s=(t.sheet??this.homeSheet)===this.map.sheet?this.map.index(e):e;return s===ee?(this.text=this.meaning=!0,Pe()):(s!==e&&(this.text=!0),this.store(t,s),t)}range(t){const e=this.absolute(t.start),s=this.absolute(t.end);let r=e,i=s;if((t.start.sheet??this.homeSheet)===this.map.sheet){const o=e<=s?e:s,l=e<=s?s:e,a=this.map.span(o,l);if(!a)return this.text=this.meaning=!0,Pe();Mn(this.map,o,l,a)&&(this.meaning=!0),(a[0]!==o||a[1]!==l)&&(this.text=!0),r=e<=s?a[0]:a[1],i=e<=s?a[1]:a[0]}return this.store(t.start,r),this.store(t.end,i),t}}function xs(n,t,e,s){const r=n.axis==="row",i=n.index+n.count,o=a=>r?a.rowAbs?a.row:a.row+s:a.colAbs?a.col:a.col+s;let l=!1;return lt(t,a=>{if(!(l||a.type==="name"||((a.type==="ref"?a:a.start).sheet??e)!==n.sheet))if(a.type==="ref"){const h=o(a);l=h>=n.index&&h<i}else{const h=o(a.start),u=o(a.end);l=Math.min(h,u)<i&&Math.max(h,u)>=n.index}}),l}function Tr(n,t,e){let s=!1;return{ast:$t(n,i=>{const o=i.type==="ref"?i.sheet:i.type==="range"?i.start.sheet:void 0;return i.type==="name"||(o??e)!==t?i:(s=!0,Pe())}),changed:s}}const Z=n=>Math.floor(n/17179869184),j=n=>Math.floor(n%17179869184/16384),Y=n=>n%16384,As=(n,t,e,s)=>`${n},${t}:${e},${s}`,Ir=/^[\p{L}_][\p{L}\p{N}_.]*$/u,Or=64;class ut{constructor(){v(this,"sheetNames",[]);v(this,"sheetIds",new Map);v(this,"sheetData",[]);v(this,"rangeIndex",[]);v(this,"names",new Map);v(this,"unresolved",new Set);v(this,"evaluatingNames",new Set);v(this,"listeners",new Set);v(this,"batchDepth",0);v(this,"pendingKeys",new Set);v(this,"dirty",new Set);v(this,"volatiles",new Set);v(this,"anchors",new Set);v(this,"trace",null);v(this,"spillSeeds",new Set);v(this,"spillDirty",new Set);v(this,"ctx",{sheet:0,row:0,col:0,getCellValue:(t,e,s)=>{var r,i;return((i=(r=this.sheetData[t])==null?void 0:r.get(O(e,s,t)))==null?void 0:i.value)??null},resolveName:t=>this.nameValue(t),getRange:(t,e,s,r,i)=>{const o=this.rangeCache;if(!o)return Ie(this.ctx,t,e,s,r,i);const l=`${t}!${e},${s}:${r},${i}`;let a=o.get(l);return a||o.set(l,a=Ie(this.ctx,t,e,s,r,i)),a}});v(this,"rangeCache",null);this.createSheet("Sheet1")}static buildEmpty(){return new ut}static buildFromArray(t,e="Sheet1"){const s=new ut;return e!=="Sheet1"&&s.renameSheet(0,e),s.batch(()=>s.setCellContents({row:0,col:0},t)),s}static buildFromSheets(t){const e=new ut,s=Object.keys(t);return s.length===0?(e.removeSheet(0),e):(e.renameSheet(0,s[0]),s.slice(1).forEach(r=>e.addSheet(r)),e.batch(()=>s.forEach((r,i)=>e.setCellContents({row:0,col:0,sheet:i},t[r]))),e)}addSheet(t){const e=t??this.unusedSheetName();this.checkSheetName(e);const s=this.createSheet(e);return this.batch(()=>this.reresolve()),s}removeSheet(t){const e=this.requireSheet(t);return this.batch(()=>{var r,i;const s=new Set;for(const o of e.values())o.removed=!0,(r=o.dependents)==null||r.forEach(l=>s.add(l));(i=this.rangeIndex[t])==null||i.forEach(o=>o.dependents.forEach(l=>s.add(l)));for(const o of e.values())this.unlink(o),this.unresolved.delete(o),this.anchors.delete(o);this.sheetIds.delete(this.sheetNames[t].toUpperCase()),this.sheetNames[t]=void 0,this.sheetData[t]=void 0,this.rangeIndex[t]=void 0;for(const o of s){if(o.removed||!o.ast)continue;const{ast:l,changed:a}=Tr(o.ast,t,this.homeSheet(o));a&&(this.unlink(o),o.ast=l,o.textDirty=!0,this.link(o),this.dirty.add(o))}})}renameSheet(t,e){this.requireSheet(t);const s=this.sheetNames[t];if(s!==e){s.toUpperCase()!==e.toUpperCase()&&this.checkSheetName(e),this.sheetIds.delete(s.toUpperCase()),this.sheetIds.set(e.toUpperCase(),t),this.sheetNames[t]=e;for(const r of this.formulaRecords())r.crossSheet&&!r.textDirty&&Ur(r.ast,t)&&(r.textDirty=!0);this.batch(()=>this.reresolve())}}getSheetNames(){return this.sheetNames.filter(t=>t!==void 0)}getSheetId(t){return this.sheetIds.get(t.toUpperCase())}getSheetName(t){return this.sheetNames[t]}doesSheetExist(t){return this.getSheetId(t)!==void 0}countSheets(){return this.sheetIds.size}isItPossibleToAddNamedExpression(t){return Ir.test(t)&&!Ye(t)&&!/^(TRUE|FALSE)$/i.test(t)&&!ze(t)&&!this.isNameDefined(t)}addNamedExpression(t,e){if(!this.isItPossibleToAddNamedExpression(t))throw new Error(`Cannot add named expression "${t}"`);return this.batch(()=>{const s=this.nameRecord(t);s.name=t,this.names.delete(t.toUpperCase()),this.names.set(t.toUpperCase(),s),this.setNameExpression(s,e)})}changeNamedExpression(t,e){const s=this.definedName(t);return this.batch(()=>this.setNameExpression(s,e))}removeNamedExpression(t){const e=this.definedName(t);return this.batch(()=>{this.unlink(e),this.unresolved.delete(e),e.raw=null,e.ast=void 0,e.value=null,this.dirty.add(e),this.collectPlaceholder(e)})}getNamedExpressionValue(t){if(!this.isNameDefined(t))return;const e=this.nameValue(t);return e instanceof z?e.values:this.finalize(e)}getNamedExpressionFormula(t){const e=this.names.get(t.toUpperCase());return e&&e.raw!==null?this.textOf(e):void 0}listNamedExpressions(){return[...this.names.values()].filter(t=>t.raw!==null).map(t=>t.name)}getCellValue({row:t,col:e,sheet:s=0}){var r;return((r=this.recordAt(O(t,e,s)))==null?void 0:r.value)??null}getCellSerialized({row:t,col:e,sheet:s=0}){const r=this.recordAt(O(t,e,s));return r?this.textOf(r):null}getCellFormula(t){const e=this.getCellSerialized(t);return V(e)?e:void 0}doesCellHaveFormula(t){return this.getCellFormula(t)!==void 0}getCellType({row:t,col:e,sheet:s=0}){const r=this.recordAt(O(t,e,s));return!r||r.raw===null?"EMPTY":V(r.raw)?"FORMULA":"VALUE"}getSpillRange({row:t,col:e,sheet:s=0}){var h;const r=this.recordAt(O(t,e,s)),i=(r==null?void 0:r.spillOwner)??r;if(!(i!=null&&i.spillArea)||!((h=i.spillCells)!=null&&h.length))return;const{r0:o,c0:l,r1:a,c1:c}=i.spillArea;return{start:Rt(s,o,l),end:Rt(s,a,c)}}getSheetDimensions(t=0){var r;let e=0,s=0;for(const i of((r=this.sheetData[t])==null?void 0:r.values())??[])i.raw===null&&!i.spillOwner||(s=Math.max(s,j(i.key)+1),e=Math.max(e,Y(i.key)+1));return{width:e,height:s}}getSheetValues(t=0){return this.dump(t,e=>(e==null?void 0:e.value)??null)}getSheetSerialized(t=0){return this.dump(t,e=>e?this.textOf(e):null)}getCellPrecedents({row:t,col:e,sheet:s=0}){const r=this.recordAt(O(t,e,s));if(!(r!=null&&r.ast))return[];const i=[];return lt(r.ast,o=>{if(o.type==="ref")i.push(Rt(o.sheet??s,Mt(o,t),kt(o,e)));else if(o.type==="range"){const l=o.start.sheet??s,[a,c]=Wt(Mt(o.start,t),Mt(o.end,t)),[h,u]=Wt(kt(o.start,e),kt(o.end,e));i.push({start:Rt(l,a,h),end:Rt(l,c,u)})}}),i}getCellDependents({row:t,col:e,sheet:s=0}){const r=O(t,e,s),i=new Set,o=l=>{var a;i.has(l)||(i.add(l),l.key<0&&((a=l.dependents)==null||a.forEach(o)))};return this.forEachDependent(this.recordAt(r),r,o),[...i].filter(l=>l.key>=0).map(l=>Rt(Z(l.key),j(l.key),Y(l.key)))}calculateFormula(t,e=0){try{const s=this.parse(pe(t),0,0);return this.finalize(st(s,{...this.ctx,sheet:e,row:0,col:0}))}catch(s){if(s instanceof W)return S("#ERROR!",s.message);throw s}}validateFormula(t){try{return this.parse(pe(t),0,0),!0}catch{return!1}}setCellContents(t,e){const s=t.sheet??0;return this.requireSheet(s),this.batch(()=>{Array.isArray(e)?e.forEach((r,i)=>r.forEach((o,l)=>this.writeCell(s,t.row+i,t.col+l,o))):this.writeCell(s,t.row,t.col,e)})}setSheetContent(t,e=0){const s=this.requireSheet(e);return this.batch(()=>{for(const r of[...s.values()])r.raw!==null&&this.writeCell(e,j(r.key),Y(r.key),null);this.setCellContents({row:0,col:0,sheet:e},t)})}batch(t){this.batchDepth++;try{t()}finally{this.batchDepth--}if(this.batchDepth>0)return[];const e=this.pendingKeys,s=this.dirty;this.pendingKeys=new Set,this.dirty=new Set;const r=this.recalculate(e,s);return r.length&&this.listeners.forEach(i=>i(r)),r}addRows(t,e,s=0){return this.restructure({sheet:s,axis:"row",index:t,count:e,remove:!1})}removeRows(t,e,s=0){return this.restructure({sheet:s,axis:"row",index:t,count:e,remove:!0})}addColumns(t,e,s=0){return this.restructure({sheet:s,axis:"col",index:t,count:e,remove:!1})}removeColumns(t,e,s=0){return this.restructure({sheet:s,axis:"col",index:t,count:e,remove:!0})}moveRows(t,e,s,r=0){return this.move("row",t,e,s,r)}moveColumns(t,e,s,r=0){return this.move("col",t,e,s,r)}inverseMove(t,e,s){return En(t,e,s)}recalculateVolatile(){return this.batch(()=>{})}captureRemoval(t,e,s,r=0){this.requireSheet(r);const i={sheet:r,axis:t,index:e,count:s},o=t==="row",l={sheet:r,axis:t,index:e,count:s,cells:[],names:[]};this.sheetData.forEach((a,c)=>{if(a)for(const h of a.values()){if(h.raw===null)continue;const u=o?j(h.key):Y(h.key),d=c===r&&u>=e&&u<e+s,p=!!h.ast&&(c===r||!!h.crossSheet)&&xs(i,h.ast,c,u);(d||p)&&l.cells.push({address:{sheet:c,row:j(h.key),col:Y(h.key)},raw:this.textOf(h)})}});for(const a of this.names.values())a.ast&&a.raw!==null&&xs(i,a.ast,-1,0)&&l.names.push({name:a.name,raw:this.textOf(a)});return l}restoreRemoval(t){return this.batch(()=>{t.axis==="row"?this.addRows(t.index,t.count,t.sheet):this.addColumns(t.index,t.count,t.sheet);for(const e of t.cells)this.setCellContents(e.address,e.raw);for(const e of t.names)this.changeNamedExpression(e.name,e.raw)})}shiftFormula(t,e,s){if(!V(t))return t;const r=[],i=this.sheetNames.length;let o;try{o=Oe(pe(t),{resolveSheet:a=>this.getSheetId(a)??i+r.push(a)-1})}catch{return t}return"="+Qt(o,{base:{row:e,col:s},sheetName:a=>a<i?this.sheetNames[a]:r[a-i]})}on(t,e){t==="valuesUpdated"&&this.listeners.add(e)}off(t,e){t==="valuesUpdated"&&this.listeners.delete(e)}destroy(){this.sheetData.forEach(t=>t==null?void 0:t.clear()),this.rangeIndex=[],this.names.clear(),this.unresolved.clear(),this.listeners.clear(),this.volatiles.clear(),this.anchors.clear()}createSheet(t){const e=this.sheetNames.length;return this.sheetNames.push(t),this.sheetIds.set(t.toUpperCase(),e),this.sheetData.push(new Map),this.rangeIndex.push(void 0),e}checkSheetName(t){if(t.trim()==="")throw new Error("Sheet name cannot be empty");if(this.doesSheetExist(t))throw new Error(`Sheet "${t}" already exists`)}unusedSheetName(){for(let t=this.countSheets()+1;;t++)if(!this.doesSheetExist(`Sheet${t}`))return`Sheet${t}`}requireSheet(t){const e=this.sheetData[t];if(!e)throw new Error(`There is no sheet with id ${t}`);return e}recordAt(t){var e;return(e=this.sheetData[Z(t)])==null?void 0:e.get(t)}homeSheet(t){return t.key>=0?Z(t.key):-1}*formulaRecords(){for(const t of this.sheetData)if(t)for(const e of t.values())e.ast&&(yield e);for(const t of this.names.values())t.ast&&(yield t)}textOf(t){if(t.textDirty&&t.ast){const e=t.key>=0?{row:j(t.key),col:Y(t.key)}:void 0;t.raw="="+Qt(t.ast,{base:e,sheetName:s=>this.sheetNames[s]}),t.textDirty=!1}return t.raw}dump(t,e){const s=this.sheetData[t],{width:r,height:i}=this.getSheetDimensions(t);return Array.from({length:i},(o,l)=>Array.from({length:r},(a,c)=>e(s==null?void 0:s.get(O(l,c,t)))))}parse(t,e,s,r){return Oe(t,{base:{row:e,col:s},resolveSheet:i=>{const o=this.getSheetId(i);return r&&(r.crossSheet=!0,o===void 0&&(r.unresolved=!0,this.unresolved.add(r))),o}})}writeCell(t,e,s,r){var c;const i=this.requireSheet(t),o=O(e,s,t);let l=i.get(o);const a=r==null||r==="";a&&(l!=null&&l.spillOwner)||(l&&(l.spillOwner=void 0,l.spillArea&&this.dropSpill(l).forEach(h=>this.pendingKeys.add(h)),this.unlink(l),this.unresolved.delete(l),l.ast=void 0,l.textDirty=l.crossSheet=l.unresolved=!1),a?(c=l==null?void 0:l.dependents)!=null&&c.size?(l.raw=null,l.value=null):l&&(i.delete(o),l.removed=!0):(l||i.set(o,l={key:o,raw:r,value:null}),l.raw=r,V(r)?this.compile(l):l.value=at(r)),this.pendingKeys.add(o))}compile(t){t.value=null;try{t.ast=this.parse(t.raw.slice(1),j(t.key),Y(t.key),t),this.link(t)}catch(e){if(!(e instanceof W))throw e;t.value=S("#ERROR!",e.message)}}setNameExpression(t,e){if(this.unlink(t),this.unresolved.delete(t),t.raw=e??null,t.ast=void 0,t.textDirty=t.unresolved=!1,t.value=at(e),V(e))try{const s=this.parse(e.slice(1),0,0,t),r=this.sheetNames.findIndex(i=>i!==void 0);lt(s,i=>{const o=i.type==="ref"?i:i.type==="range"?i.start:void 0;!o||o.sheet!==void 0||(o.sheet=r,i.type==="range"&&(i.end.sheet=r),t.textDirty=!0)}),t.ast=s,t.crossSheet=!0,t.value=null,this.link(t)}catch(s){if(!(s instanceof W))throw s;t.value=S("#ERROR!",s.message)}this.dirty.add(t)}reresolve(){for(const t of[...this.unresolved]){if(this.unresolved.delete(t),t.removed)continue;const e=this.textOf(t);t.key<0?this.setNameExpression(t,e):(this.unlink(t),t.ast=void 0,t.crossSheet=t.unresolved=!1,this.compile(t),this.dirty.add(t))}}isNameDefined(t){const e=this.names.get(t.toUpperCase());return e!==void 0&&e.raw!==null}definedName(t){if(!this.isNameDefined(t))throw new Error(`Named expression "${t}" does not exist`);return this.names.get(t.toUpperCase())}nameRecord(t){const e=t.toUpperCase();let s=this.names.get(e);return s||this.names.set(e,s={key:-1,raw:null,value:null,name:t}),s}nameValue(t){const e=this.names.get(t.toUpperCase());if(!e||e.raw===null)return S("#NAME?",`Unknown name "${t}"`);if(!e.ast)return e.value;if(this.evaluatingNames.has(e))return S("#CYCLE!");this.evaluatingNames.add(e);try{return st(e.ast,{...this.ctx,sheet:-1,row:0,col:0})}finally{this.evaluatingNames.delete(e)}}ensureCell(t,e,s){const r=this.sheetData[t];if(!r||e<0||s<0)return;const i=O(e,s,t);let o=r.get(i);return o||r.set(i,o={key:i,raw:null,value:null}),o}rangeEntry(t,e,s,r,i){var c;const o=(c=this.rangeIndex)[t]??(c[t]=new Map),l=As(e,s,r,i);let a=o.get(l);return a||o.set(l,a={sheet:t,r0:e,c0:s,r1:r,c1:i,id:l,dependents:new Set}),a}link(t){if(!t.ast)return;const e=this.homeSheet(t),s=t.key>=0?j(t.key):0,r=t.key>=0?Y(t.key):0,i=[],o=[],l=a=>{a&&(i.push(a),(a.dependents??(a.dependents=new Set)).add(t))};lt(t.ast,a=>{if(a.type==="name")a.name!==""&&l(this.nameRecord(a.name));else if(a.type==="ref")l(this.ensureCell(a.sheet??e,Mt(a,s),kt(a,r)));else{const c=a.start.sheet??e;if(!this.sheetData[c])return;const[h,u]=Wt(Mt(a.start,s),Mt(a.end,s)),[d,p]=Wt(kt(a.start,r),kt(a.end,r)),g=this.rangeEntry(c,h,d,u,p);g.dependents.add(t),o.push(g)}}),t.precedents=i.length?i:void 0,t.rangeDeps=o.length?o:void 0,t.volatile=t.positional=!1,Nt(t.ast,a=>{const c=ze(a);c!=null&&c.volatile&&(t.volatile=!0),c!=null&&c.positional&&(t.positional=!0)}),t.volatile&&this.volatiles.add(t)}unlink(t){var e;if(t.precedents)for(const s of t.precedents)(e=s.dependents)==null||e.delete(t),this.collectPlaceholder(s);if(t.rangeDeps)for(const s of t.rangeDeps){s.dependents.delete(t);const r=this.rangeIndex[s.sheet];s.dependents.size===0&&(r==null?void 0:r.get(s.id))===s&&r.delete(s.id)}t.precedents=t.rangeDeps=void 0,this.volatiles.delete(t)}collectPlaceholder(t){var e;if(!(t.raw!==null||t.removed||(e=t.dependents)!=null&&e.size||t.spillOwner)){if(t.key<0){const s=t.name.toUpperCase();this.names.get(s)===t&&this.names.delete(s)}else{const s=this.sheetData[Z(t.key)];(s==null?void 0:s.get(t.key))===t&&s.delete(t.key)}t.removed=!0}}forEachDependent(t,e,s,r=!1){var a,c;if((a=t==null?void 0:t.dependents)==null||a.forEach(s),r&&((c=t==null?void 0:t.spillCells)!=null&&c.length)&&this.forEachSpillDependent(t,s),e<0)return;const i=this.rangeIndex[Z(e)];if(!(i!=null&&i.size))return;const o=j(e),l=Y(e);for(const h of i.values())o>=h.r0&&o<=h.r1&&l>=h.c0&&l<=h.c1&&h.dependents.forEach(s)}recalculate(t,e){var l;const s=this.trace=new Map;let r=t,i=this.volatiles.size?[...e,...this.volatiles]:e;try{for(let a=1;this.spillSeeds=new Set,this.spillDirty=new Set,this.evaluatePass(r,i),!(!this.spillSeeds.size&&!this.spillDirty.size);a++){if(a===Or){for(const c of this.spillDirty)this.unspill(c),c.value=S("#SPILL!","Spill does not settle");break}r=this.spillSeeds,i=this.spillDirty}}finally{this.trace=null}const o=new Map;for(const a of t)this.sheetData[Z(a)]&&o.set(a,{address:Ne(a),value:((l=this.recordAt(a))==null?void 0:l.value)??null});for(const[a,c]of s)a.key<0||t.has(a.key)||!this.sheetData[Z(a.key)]||Cs(c,a.value)||a.removed&&this.recordAt(a.key)||o.set(a.key,{address:Ne(a.key),value:a.value});return[...o.values()]}evaluatePass(t,e){const s=this.trace,r=new Map,i=[],o=u=>{u.removed||r.has(u)||(r.set(u,0),i.push(u),s.has(u)||s.set(u,u.value))},l=(u,d)=>{u!=null&&u.ast?o(u):this.forEachDependent(u,d,o)};for(const u of t)l(this.recordAt(u),u),this.anchors.size&&this.forEachAnchorCovering(u,o);for(const u of e)u.removed||l(u,u.key);const a=new Map;for(let u=0;u<i.length;u++){const d=i[u],p=[];this.forEachDependent(d,d.key,g=>{g.removed||(o(g),p.push(g),r.set(g,r.get(g)+1))},!0),p.length&&a.set(d,p)}const c=i.filter(u=>r.get(u)===0),h=this.ctx;this.rangeCache=new Map;try{for(;c.length;){const u=c.pop();r.set(u,-1),u.key>=0&&(h.sheet=Z(u.key),h.row=j(u.key),h.col=Y(u.key),this.assign(u,st(u.ast,h)));for(const d of a.get(u)??[]){const p=r.get(d)-1;r.set(d,p),p===0&&c.push(d)}}}finally{this.rangeCache=null}for(const u of i)r.get(u)!==-1&&(u.spillArea&&this.unspill(u,!1),u.value=S("#CYCLE!"))}finalize(t){if(t instanceof z&&(t.height===0||t.width===0))return S("#CALC!","The result is an empty array");const e=T(t);return e===null?0:e}assign(t,e){if(e instanceof z&&e.height>0&&e.width>0&&(e.height>1||e.width>1)){this.spill(t,e);return}t.spillArea&&this.unspill(t),t.value=this.finalize(e)}spill(t,e){const s=Z(t.key),r=j(t.key),i=Y(t.key),o={r0:r,c0:i,r1:r+e.height-1,c1:i+e.width-1};t.spillArea=o,this.anchors.add(t);const l=this.sheetData[s];if(o.r1>=1048576||o.c1>=16384||this.isBlocked(t,o,l)){this.touchAnchors(this.clearSpill(t),t),t.value=S("#SPILL!","The spill range is not empty");return}const a=new Set(t.spillCells),c=[],h=[];for(let u=0;u<e.height;u++)for(let d=0;d<e.width;d++){if(u===0&&d===0)continue;const p=O(r+u,i+d,s);let g=l.get(p);g||l.set(p,g={key:p,raw:null,value:null});const C=this.finalize(e.values[u][d]);if(g.spillOwner===t){if(a.delete(g),Cs(g.value,C)){c.push(g);continue}}else g.spillOwner=t,h.push(p),this.spillSeeds.add(p);this.noteBefore(g),g.value=C,c.push(g)}for(const u of a)u.spillOwner!==t||u.removed||(this.vacate(u),h.push(u.key));t.spillCells=c,this.touchAnchors(h,t),this.rangeCache=new Map,t.value=this.finalize(e.values[0][0])}isBlocked(t,e,s){const r=Z(t.key);for(let i=e.r0;i<=e.r1;i++)for(let o=e.c0;o<=e.c1;o++){const l=s.get(O(i,o,r));if(l&&l!==t&&(l.raw!==null||l.spillOwner&&l.spillOwner!==t))return!0}return!1}unspill(t,e=!0){const s=this.clearSpill(t);e&&this.touchAnchors(s,t),this.anchors.delete(t),t.spillArea=void 0}dropSpill(t){const e=this.clearSpill(t);return this.anchors.delete(t),t.spillArea=void 0,e}clearSpill(t){const e=[];for(const s of t.spillCells??[])s.spillOwner!==t||s.removed||(this.vacate(s),e.push(s.key));return t.spillCells=void 0,e}vacate(t){this.noteBefore(t),t.spillOwner=void 0,t.value=null,this.collectPlaceholder(t)}noteBefore(t){this.trace&&!this.trace.has(t)&&this.trace.set(t,t.value)}touchAnchors(t,e){if(!(this.anchors.size<2||t.length===0))for(const s of t)this.forEachAnchorCovering(s,r=>{r!==e&&this.spillDirty.add(r)})}forEachAnchorCovering(t,e){const s=Z(t),r=j(t),i=Y(t);for(const o of this.anchors){const l=o.spillArea;o.key!==t&&Z(o.key)===s&&r>=l.r0&&r<=l.r1&&i>=l.c0&&i<=l.c1&&e(o)}}forEachSpillDependent(t,e){var a;let s=1/0,r=1/0,i=-1,o=-1;for(const c of t.spillCells){if(c.spillOwner!==t||c.removed)continue;(a=c.dependents)==null||a.forEach(e);const h=j(c.key),u=Y(c.key);h<s&&(s=h),h>i&&(i=h),u<r&&(r=u),u>o&&(o=u)}const l=this.rangeIndex[Z(t.key)];if(!(i<0||!(l!=null&&l.size)))for(const c of l.values())c.r0<=i&&c.r1>=s&&c.c0<=o&&c.c1>=r&&c.dependents.forEach(e)}restructure(t){return this.requireSheet(t.sheet),t.count<=0?[]:this.remap(new Nr(t))}move(t,e,s,r,i){this.requireSheet(i);const o=t==="row"?1048576:16384;if(![e,s,r].every(Number.isInteger)||e<0||s<0||r<0||e+s>o||r>o)throw new RangeError(`Invalid move of ${s} ${t==="row"?"rows":"columns"} from ${e} to ${r}`);return s===0||r>=e&&r<=e+s?[]:this.remap(new $r(i,t,e,s,r))}remap(t){const e=this.requireSheet(t.sheet),s=t.axis==="row";return this.batch(()=>{const r=new zr(t),i=[],o=(d,p,g,C)=>{d.ast=r.adjust(d.ast,p,g,C),r.text&&(d.textDirty=!0),r.meaning?i.push(d):d.positional&&(r.text||g!==C)&&this.dirty.add(d)};this.sheetData.forEach((d,p)=>{if(!(!d||p===t.sheet))for(const g of d.values())g.ast&&g.crossSheet&&o(g,p,s?j(g.key):Y(g.key),s?j(g.key):Y(g.key))});for(const d of this.names.values())d.ast&&o(d,-1,0,0);const l=new Map,a=[],c=t.sheet*17179869184;e.forEach((d,p)=>{const g=p-c,C=Math.floor(g/16384),y=g-C*16384,m=s?C:y,f=t.index(m);if(f===ee){d.removed=!0,a.push(d);return}d.ast&&o(d,t.sheet,m,f),f!==m&&(d.key=s?p+(f-m)*16384:p+(f-m)),l.set(d.key,d)}),this.sheetData[t.sheet]=l;const h=[];for(const d of a)this.unlink(d),this.unresolved.delete(d),d.spillArea&&h.push(...this.dropSpill(d));for(const d of this.anchors)Z(d.key)===t.sheet&&this.dirty.add(d);const u=this.rangeIndex[t.sheet];if(u){const d=new Map;for(const p of u.values()){const[g,C]=s?[p.r0,p.r1]:[p.c0,p.c1],y=t.span(g,C);!y||Mn(t,g,C,y)||(s?[p.r0,p.r1]=y:[p.c0,p.c1]=y,p.id=As(p.r0,p.c0,p.r1,p.c1),d.set(p.id,p))}this.rangeIndex[t.sheet]=d}for(const d of i)d.removed||(this.unlink(d),this.link(d),this.dirty.add(d));if(this.pendingKeys.size){const d=this.pendingKeys;this.pendingKeys=new Set;for(const p of d){if(Z(p)!==t.sheet){this.pendingKeys.add(p);continue}const g=j(p),C=Y(p),y=t.index(s?g:C);y!==ee&&this.pendingKeys.add(s?O(y,C,t.sheet):O(g,y,t.sheet))}}h.forEach(d=>this.pendingKeys.add(d))})}}const pe=n=>n.startsWith("=")?n.slice(1):n,Mt=(n,t)=>n.rowAbs?n.row:n.row+t,kt=(n,t)=>n.colAbs?n.col:n.col+t,Wt=(n,t)=>n<=t?[n,t]:[t,n];function Rt(n,t,e){return n===0?{row:t,col:e}:{row:t,col:e,sheet:n}}function Ur(n,t){let e=!1;return lt(n,s=>{(s.type==="ref"&&s.sheet===t||s.type==="range"&&s.start.sheet===t)&&(e=!0)}),e}function Cs(n,t){return n instanceof Object&&t instanceof Object?n.code===t.code:n===t}function Pr(n,t,e){const s=n.length,r=[],i=n.every(a=>typeof a=="number")?n:null,o=i&&s>=2?kn(i):void 0,l=Hr(n);for(let a=0;a<t;a++){if(i&&o!==void 0){r.push(_r(i[s-1]+o*(a+1)));continue}if(l){const u=a+1;r.push(`${l.prefix}${l.last+l.step*u}${l.suffix}`);continue}const c=a%s,h=n[c];r.push(V(h)?e(h,c,s+a):h)}return r}function kn(n){const t=n[1]-n[0];for(let e=2;e<n.length;e++)if(Math.abs(n[e]-n[e-1]-t)>1e-9)return;return t}const Ss=/^(.*?)(\d+)(\D*)$/;function Hr(n){if(!n.every(o=>typeof o=="string"&&!V(o)&&Ss.test(o)))return;const t=n.map(o=>Ss.exec(o)),{1:e,3:s}=t[0];if(!t.every(o=>o[1]===e&&o[3]===s))return;const r=t.map(o=>Number(o[2])),i=r.length>=2?kn(r):1;if(i!==void 0)return{prefix:e,suffix:s,last:r[r.length-1],step:i}}const _r=n=>Number(n.toPrecision(15));class Ft{constructor(t,e,s){v(this,"sizes");v(this,"prefix",null);this.defaultSize=e,this.sizes=Array.from({length:t},(r,i)=>Array.isArray(s)?s[i]??e:s??e)}get count(){return this.sizes.length}get total(){return this.offset(this.count)}size(t){return this.sizes[t]??this.defaultSize}setSize(t,e){this.sizes[t]=e,this.prefix=null}offset(t){if(!this.prefix){const e=new Float64Array(this.sizes.length+1);for(let s=0;s<this.sizes.length;s++)e[s+1]=e[s]+this.sizes[s];this.prefix=e}return this.prefix[Math.max(0,Math.min(t,this.sizes.length))]}indexAt(t){if(this.count===0)return 0;let e=0,s=this.count-1;for(;e<s;){const r=e+s+1>>1;this.offset(r)<=t?e=r:s=r-1}return e}insert(t,e){this.sizes.splice(t,0,...Array(e).fill(this.defaultSize)),this.prefix=null}remove(t,e){this.sizes.splice(t,e),this.prefix=null}resize(t){t>this.count?this.insert(this.count,t-this.count):t<this.count&&this.remove(t,this.count-t)}}const Rn=n=>n.length>0&&n.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t));function Vr(n,t){let e=n;for(const s of t.split(".")){if(e===null||typeof e!="object")return;e=e[s]}return e}function Br(n,t,e){const s=t.split(".");let r=n;for(const i of s.slice(0,-1))(r[i]===null||typeof r[i]!="object")&&(r[i]={}),r=r[i];r[s[s.length-1]]=e}function Xr(n){return n==null?null:typeof n=="number"||typeof n=="string"||typeof n=="boolean"?n:n instanceof Date?Tt(n.getFullYear(),n.getMonth()+1,n.getDate()):String(n)}class ae{constructor(t,e,s){this.objects=t,this.fields=e,this.schema=s}static create(t,e,s){const r=e.some(i=>i!==void 0)?[...e]:Object.keys(t[0]??(s==null?void 0:s())??{});return new ae(t,r,s)}toRows(){return this.objects.map(t=>this.fields.map(e=>e===void 0?null:Xr(Vr(t,e))))}write(t,e,s){const r=this.fields[e];if(r!==void 0){for(;this.objects.length<=t;)this.objects.push(this.newRow());Br(this.objects[t],r,s)}}insertRows(t,e){this.objects.splice(t,0,...Array.from({length:e},()=>this.newRow()))}removeRows(t,e){this.objects.splice(t,e)}ensureRows(t){for(;this.objects.length<t;)this.objects.push(this.newRow())}insertCols(t,e){t<=this.fields.length&&this.fields.splice(t,0,...Array(e))}removeCols(t,e){this.fields.splice(t,e)}snapshot(){return{objects:[...this.objects],fields:[...this.fields]}}restore(t){this.objects.splice(0,this.objects.length,...t.objects),this.fields=[...t.fields]}newRow(){return this.schema?this.schema():{}}}function Wr(n){let t="";return n.bold&&(t+=" ct-b"),n.italic&&(t+=" ct-i"),n.underline&&(t+=" ct-u"),n.strike&&(t+=" ct-s"),n.wrap&&(t+=" ct-wrap"),n.align&&(t+=` ct-al-${n.align[0]}`),t}const Es=new Map;function jr(n,t){const e=`${n}|${JSON.stringify(t)}`;let s=Es.get(e);return s||(s=new Intl.NumberFormat(n,{style:t.style??"decimal",currency:t.style==="currency"?t.currency??"TRY":void 0,minimumFractionDigits:t.minimumFractionDigits,maximumFractionDigits:t.maximumFractionDigits??(t.style==="currency"||t.style==="percent"?void 0:Math.max(t.minimumFractionDigits??0,10)),useGrouping:t.useGrouping??!0}),Es.set(e,s)),s}const is=n=>n!=null&&n.startsWith("tr")||n!=null&&n.startsWith("de")?"DD.MM.YYYY":"YYYY-MM-DD";function Ms(n,t,e){return t.type==="checkbox"?{text:n===!0?"☑":"☐",kind:"check"}:n==null?{text:""}:n instanceof ct?{text:n.code,kind:"err"}:typeof n=="number"?t.type==="date"?{text:ts(n,t.dateFormat??is(e)),kind:"date"}:t.numericFormat?{text:jr(e,t.numericFormat).format(n),kind:"num"}:{text:Ke(n),kind:"num"}:typeof n=="boolean"?{text:n?"TRUE":"FALSE",kind:"bool"}:{text:n}}function jt(n,t,e){return n==null?"":t.type==="date"&&typeof n=="number"?ts(n,t.dateFormat??is(e)):String(n)}function me(n,t={}){if(n==="")return null;if(n.length>1&&n[0]==="=")return n;if(t.type==="date")return ie(n.trim())??n;if(t.type==="checkbox"){const s=at(n);return typeof s=="boolean"?s:typeof s=="number"?s!==0:n}if(t.type==="numeric"){const s=n.trim();if(/^[+-]?\d{1,3}(\.\d{3})*(,\d+)?$/.test(s)||/^[+-]?\d+,\d+$/.test(s)){const r=Ct(s.replace(/\./g,"").replace(",","."));if(r!==void 0)return r}}if(t.type==="dropdown"||t.type==="text")return(t.type==="text"?void 0:Ct(n))??n;const e=at(n);return typeof e=="number"||typeof e=="boolean"?e:n}function ks(n,t,e,s,r){if(t==null||t==="")return;if(!V(t)){if(e.type==="numeric"&&typeof n!="number")return"Not a number";if(e.type==="date"&&typeof n!="number")return"Not a date";if(e.type==="dropdown"&&e.strict!==!1&&e.source&&!e.source.includes(String(n)))return"Not in list"}const i=e.validator;if(!i)return;if(i instanceof RegExp)return i.test(String(n??""))?void 0:"Invalid value";const o=i(n,s,r);return o===!0?void 0:typeof o=="string"?o:"Invalid value"}const ge=n=>!!n.validator||n.type==="numeric"||n.type==="date"||n.type==="dropdown",Yr=[25,50,100];function Kr(n,t){return{page:1,pageSize:t[0],sort:[],filters:{},...n}}const qr=(n,t)=>Math.max(1,Math.ceil(n/t));function Zr(n,t,e,s){const r=n.createElement("div");r.className="ct-menu-section";const i=n.createElement("div");i.className="ct-menu-title",i.textContent=t.filterByValue,r.append(i);const o=(h,u,d)=>{const p=n.createElement("input");return p.type=h,p.value=d,p.setAttribute("aria-label",u),p};if(e.kind==="text"){const h=o("text",t.filterByValue,(s==null?void 0:s.kind)==="text"?s.value:"");return r.append(h),{el:r,read:()=>h.value?{kind:"text",value:h.value}:null}}if(e.kind==="date"){const h=(s==null?void 0:s.kind)==="date"?s:void 0,u=o("date",t.dateFrom,(h==null?void 0:h.from)??""),d=o("date",t.dateTo,(h==null?void 0:h.to)??"");return r.append(u,d),{el:r,read:()=>u.value||d.value?{kind:"date",...u.value&&{from:u.value},...d.value&&{to:d.value}}:null}}if(e.kind==="boolean"){const h=n.createElement("select");return h.setAttribute("aria-label",t.filterByValue),h.append(new Option(t.none,""),new Option(t.yes,"true"),new Option(t.no,"false")),h.value=(s==null?void 0:s.kind)==="boolean"?String(s.value):"",r.append(h),{el:r,read:()=>h.value?{kind:"boolean",value:h.value==="true"}:null}}const l=new Set((s==null?void 0:s.kind)==="list"?s.values:[]),a=n.createElement("div");a.className="ct-menu-list";const c=e.options.map(h=>{const u=n.createElement("label"),d=n.createElement("input");return d.type="checkbox",d.checked=l.has(h.value),u.append(d,n.createTextNode(h.label??h.value)),a.append(u),[h.value,d]});return r.append(a),{el:r,read:()=>{const h=c.filter(([,u])=>u.checked).map(([u])=>u);return h.length?{kind:"list",values:h}:null}}}class Gr{constructor(t,e,s,r,i){v(this,"el");v(this,"actions");v(this,"range");v(this,"size");v(this,"position");v(this,"prev");v(this,"next");this.m=e,this.el=t.createElement("div"),this.el.className="ct-pager",this.el.setAttribute("role","navigation"),this.actions=t.createElement("div"),this.actions.className="ct-pager-actions",this.range=t.createElement("span"),this.range.setAttribute("aria-live","polite"),this.size=t.createElement("select"),this.size.setAttribute("aria-label",e.pageSize);for(const l of s)this.size.append(new Option(String(l),String(l)));this.size.addEventListener("change",()=>i(Number(this.size.value))),this.position=t.createElement("span");const o=(l,a,c)=>{const h=t.createElement("button");return h.type="button",h.className="ct-btn",h.textContent=l,h.setAttribute("aria-label",a),h.addEventListener("click",()=>r(c)),h};this.prev=o("‹",e.previous,-1),this.next=o("›",e.next,1),this.el.append(this.actions,this.range,this.size,this.prev,this.position,this.next)}update(t,e){this.size.value=String(t.pageSize);const s=e??0,r=qr(s,t.pageSize),i=s?(t.page-1)*t.pageSize+1:0;this.range.textContent=this.m.pagerRange.replace("{from}",String(i)).replace("{to}",String(Math.min(t.page*t.pageSize,s))).replace("{total}",String(s)),this.position.textContent=`${t.page} / ${r}`,this.prev.disabled=t.page<=1,this.next.disabled=t.page>=r}}const Qr=["contains","notContains","equals","notEquals","greaterThan","greaterOrEqual","lessThan","lessOrEqual","isEmpty","isNotEmpty"],Rs=1e3;function Fs(n){var C,y,m,f,x,A;const t=n.anchor.ownerDocument,e=n.messages,s=t.createElement("div");s.className="ct-menu",s.setAttribute("role","dialog"),s.setAttribute("aria-label",e.columnMenu);const r=(k,F,$)=>{const L=t.createElement("button");return L.type="button",L.className=F,L.textContent=k,L.addEventListener("click",$),L};if(n.sortable){const k=t.createElement("div");k.className="ct-menu-section",k.append(r(e.sortAsc,`ct-menu-item${n.sort==="asc"?" ct-on":""}`,()=>(n.onSort("asc"),g())),r(e.sortDesc,`ct-menu-item${n.sort==="desc"?" ct-on":""}`,()=>(n.onSort("desc"),g()))),n.sortedElsewhere&&k.append(r(e.sortThenAsc,"ct-menu-item",()=>(n.onSort("asc",!0),g())),r(e.sortThenDesc,"ct-menu-item",()=>(n.onSort("desc",!0),g()))),n.sort&&k.append(r(e.sortClear,"ct-menu-item",()=>(n.onSort(null),g()))),s.append(k)}let i=()=>{};const o=k=>{const F=t.createElement("div");F.className="ct-menu-footer",F.append(r(e.clearFilter,"ct-menu-link",()=>(k(),g())),r(e.cancel,"ct-btn",()=>g()),r(e.ok,"ct-btn ct-primary",()=>i())),s.append(F)},l=n.server;if(l){const k=Zr(t,e,l.def,l.value);s.append(k.el),i=()=>{l.onFilter(k.read()),g()},o(()=>l.onFilter(null))}else if(n.filterable){const k=t.createElement("div");k.className="ct-menu-section";const F=t.createElement("div");F.className="ct-menu-title",F.textContent=e.filterByCondition;const $=t.createElement("select");$.append(new Option(e.none,""));for(const U of Qr)$.append(new Option(e[U],U));$.value=((y=(C=n.filter)==null?void 0:C.condition)==null?void 0:y.op)??"";const L=t.createElement("input");L.type="text",L.value=((f=(m=n.filter)==null?void 0:m.condition)==null?void 0:f.value)??"";const H=()=>{L.hidden=!$.value||$.value==="isEmpty"||$.value==="isNotEmpty"};$.addEventListener("change",H),H(),k.append(F,$,L);const X=t.createElement("div");X.className="ct-menu-section";const _=t.createElement("div");_.className="ct-menu-title",_.textContent=e.filterByValue;const R=t.createElement("input");R.type="search",R.placeholder=e.search;const E=t.createElement("div");E.className="ct-menu-list";const D=new Set(((x=n.filter)==null?void 0:x.values)??n.values),M=n.values.slice(0,Rs),N=[],I=(U,et)=>{const it=t.createElement("label"),Xt=t.createElement("input");return Xt.type="checkbox",Xt.checked=et,it.append(Xt,t.createTextNode(U)),[it,Xt]},[q,cs]=I(e.selectAll,M.every(U=>D.has(U)));cs.addEventListener("change",()=>N.forEach(([,U,et])=>!et.hidden&&(U.checked=cs.checked))),E.append(q);for(const U of M){const[et,it]=I(U===""?e.blanks:U,D.has(U));N.push([U,it,et]),E.append(et)}R.addEventListener("input",()=>{const U=R.value.toLocaleLowerCase(n.locale);N.forEach(([et,,it])=>it.hidden=!et.toLocaleLowerCase(n.locale).includes(U))}),X.append(_,R,E),s.append(k,X),i=()=>{const U={};$.value&&(U.condition={op:$.value,value:L.value});const et=N.filter(([,it])=>it.checked).map(([it])=>it);et.length<N.length&&(U.values=[...et,...n.values.slice(Rs)]),n.onFilter(U.condition||U.values?U:null),g()},o(()=>n.onFilter(null))}t.body.append(s);const a=n.anchor.getBoundingClientRect(),c=s.offsetWidth||240,h=Math.max(8,Math.min(a.right-c,(((A=t.defaultView)==null?void 0:A.innerWidth)??1024)-c-8));s.style.left=`${h}px`,s.style.top=`${a.bottom+2}px`;const u=k=>{s.contains(k.target)||g()},d=k=>{k.key==="Escape"?(k.stopPropagation(),g()):k.key==="Enter"&&(n.filterable||l)&&k.target.tagName!=="BUTTON"&&i()};t.addEventListener("mousedown",u,!0),s.addEventListener("keydown",d);let p=!1;function g(){p||(p=!0,t.removeEventListener("mousedown",u,!0),s.remove(),n.onClose())}return g}function Fn(n){return n.replace(/"[^"]*"|\\.|_.|\*./g,"").replace(/\[(?![hms]+\])[^\]]*\]/gi,"")}function ce(n){if(!n)return!1;const t=n.split(";")[0];return/[dmyhs]/i.test(Fn(t).replace(/General/gi,""))}const Jr=/[-/.:, $+()!^&'~{}<>=]/;function Dn(n){const t={YYYY:"yyyy",YY:"yy",MM:"mm",M:"m",DD:"dd",D:"d",HH:"hh",mm:"mm",ss:"ss"};let e="";const s=/YYYY|YY|MM|M|DD|D|HH|mm|ss/g;let r=0;for(let i=s.exec(n);i;i=s.exec(n))e+=Ds(n.slice(r,i.index))+t[i[0]],r=i.index+i[0].length;return e+Ds(n.slice(r))}function Ds(n){let t="";for(const e of n)t+=Jr.test(e)?e:`\\${e}`;return t}const ti=n=>n?`"${n.replace(/"/g,"")}"`:"";function we(n,t,e){return e<=0?n:`${n}.${"0".repeat(t)}${"#".repeat(Math.max(0,e-t))}`}function ei(n,t){var i;const e=n.style??"decimal",s=n.useGrouping===!1?"0":"#,##0";if(e==="percent"){const o=n.minimumFractionDigits??n.maximumFractionDigits??0;return`${we(s,o,n.maximumFractionDigits??o)}%`}if(e==="currency"){const o=new Intl.NumberFormat(t,{style:"currency",currency:n.currency??"TRY"}),l=o.resolvedOptions(),a=n.minimumFractionDigits??l.minimumFractionDigits??2,c=Math.max(a,n.maximumFractionDigits??l.maximumFractionDigits??a),h=o.formatToParts(1),u=h.findIndex(y=>y.type==="currency"),d=h.findIndex(y=>y.type==="integer"),p=ti(((i=h[u])==null?void 0:i.value)??n.currency??""),g=h.slice(Math.min(u,d)+1,Math.max(u,d)).some(y=>y.type==="literal")?" ":"",C=we(s,a,c);return u<d?`${p}${g}${C}`:`${C}${g}${p}`}if(n.minimumFractionDigits===void 0&&n.maximumFractionDigits===void 0)return;const r=n.minimumFractionDigits??0;return we(s,r,Math.max(r,n.maximumFractionDigits??r))}function Nn(n,t){if(n.formatCode)return n.formatCode;if(n.type==="date")return Dn(n.dateFormat??is(t));if(n.numericFormat)return ei(n.numericFormat,t)}const ot=(n,t=2)=>String(n).padStart(t,"0");function $n(n,t,e){const s=t.split(";")[0],{year:r,month:i,day:o}=gt(n);let l=Math.round((n-Math.floor(n))*86400);l>=86400&&(l=86399);const a=Math.floor(l/3600),c=Math.floor(l/60)%60,h=l%60,u=/AM\/PM|A\/P/i.test(Fn(s)),d=a%12===0?12:a%12,p=new Date(Date.UTC(2e3,0,1));p.setUTCFullYear(r,i-1,o);const g=f=>new Intl.DateTimeFormat(e,{...f,timeZone:"UTC"}).format(p),C=/"([^"]*)"|\\(.)|_(.)|\*(.)|\[(h+|m+|s+)\]|\[[^\]]*\]|AM\/PM|A\/P|y+|m+|d+|h+|s+|./gi,y=[];for(let f=C.exec(s);f;f=C.exec(s))y.push(f[0]);let m="";return y.forEach((f,x)=>{const A=f.toLowerCase();if(f[0]==='"')m+=f.slice(1,-1);else if(f[0]==="\\")m+=f[1];else if(f[0]==="_")m+=" ";else if(f[0]==="*")m+="";else if(/^\[h+\]$/i.test(f))m+=ot(Math.floor(n)*24+a,A.length-2);else if(/^\[m+\]$/i.test(f))m+=ot(Math.floor(n*1440),A.length-2);else if(/^\[s+\]$/i.test(f))m+=ot(Math.floor(n*86400),A.length-2);else if(f[0]==="[")m+="";else if(A==="am/pm")m+=a<12?"AM":"PM";else if(A==="a/p")m+=a<12?"A":"P";else if(A[0]==="y")m+=A.length<=2?ot(r%100):ot(r,4);else if(A[0]==="d")m+=A.length===1?String(o):A.length===2?ot(o):g({weekday:A.length===3?"short":"long"});else if(A[0]==="h")m+=A.length===1?String(u?d:a):ot(u?d:a);else if(A[0]==="s")m+=A.length===1?String(h):ot(h);else if(A[0]==="m"){const k=y.slice(0,x).reverse().find(L=>/^(\[?h+\]?|[dmys]+)$/i.test(L)),F=y.slice(x+1).find(L=>/^(\[?s+\]?|[dmyh]+)$/i.test(L));(!!k&&/h/i.test(k)||!!F&&/s/i.test(F))&&A.length<=2?m+=A.length===1?String(c):ot(c):A.length===1?m+=String(i):A.length===2?m+=ot(i):m+=g({month:A.length===3?"short":A.length===4?"long":"narrow"})}else m+=f}),m}const si=/^[=+\-@\t\r]/;function ni(n,t){return n.includes(t)||/["\r\n]/.test(n)||/^\s|\s$/.test(n)}const ri=(n,t)=>ni(n,t)?`"${n.replace(/"/g,'""')}"`:n;function ii(n,t,e,s){var i,o;const r=(o=(i=n.values)==null?void 0:i[t])==null?void 0:o[e];return r!==void 0?r:V(s)?s:at(s)}function Ln(n,t={}){var p,g,C,y;const e=t.delimiter??",",s=t.lineEnding??`\r
3
+ `,r=t.decimalSeparator??".",i=t.values==="raw",o=t.escapeFormulas!==!1,l=m=>o&&si.test(m)?`'${m}`:m,a=Math.max(n.data.length,((p=n.values)==null?void 0:p.length)??0);let c=0;for(let m=0;m<a;m++)c=Math.max(c,((g=n.data[m])==null?void 0:g.length)??0,((y=(C=n.values)==null?void 0:C[m])==null?void 0:y.length)??0);const h=(m,f)=>{var k,F,$;const x=(k=n.data[m])==null?void 0:k[f];if(i)return x==null?"":typeof x=="boolean"?x?"TRUE":"FALSE":typeof x=="string"?V(x)?x:l(x):u(x);const A=ii(n,m,f,x);if(A==null)return"";if(A instanceof ct)return A.code;if(typeof A=="boolean")return A?"TRUE":"FALSE";if(typeof A=="number"){if(t.values==="formatted"&&n.text)return n.text(m,f);const L=($=(F=n.format)==null?void 0:F.call(n,m,f))==null?void 0:$.numberFormat;return ce(L)&&Number.isFinite(A)&&A>=0?$n(A,L,t.locale):u(A)}return A===x&&V(x)?A:l(A)},u=m=>{if(typeof m=="string")return m;const f=String(B(m));return r==="."?f:f.replace(".",r)},d=[];for(let m=0;m<a;m++){const f=[];for(let x=0;x<c;x++)f.push(ri(h(m,x),e));d.push(f.join(e))}return(t.bom===!1?"":"\uFEFF")+d.join(s)}const zn="text/csv;charset=utf-8";function He(n,t,e){const s=new Blob([n],{type:e}),r=URL.createObjectURL(s),i=document.createElement("a");i.href=r,i.download=t,i.style.display="none",document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),0)}const oi=new RegExp("[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F￾￿]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]","g"),li={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"};function nt(n){return n.replace(oi,"").replace(/[&<>"']/g,t=>li[t])}function _e(n){let t="";for(const[e,s]of Object.entries(n))s===void 0||s===!1||(t+=` ${e}="${s===!0?"1":nt(String(s))}"`);return t}const ht=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4
+ `,ai="http://schemas.openxmlformats.org/spreadsheetml/2006/main",ci={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"@":49};function Ns(n){if(!n)return;let t=/^#?([0-9a-f]{6})$/i.exec(n.trim());return t?`FF${t[1].toUpperCase()}`:(t=/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(n.trim()),t?`FF${(t[1]+t[1]+t[2]+t[2]+t[3]+t[3]).toUpperCase()}`:void 0)}class ye{constructor(t){v(this,"items",[]);v(this,"index",new Map);t.forEach(e=>this.add(e))}add(t){let e=this.index.get(t);return e===void 0&&(e=this.items.push(t)-1,this.index.set(t,e)),e}}const $s=(n,t,e,s,r)=>`<font>${n?"<b/>":""}${t?"<i/>":""}${r?"<strike/>":""}${e?"<u/>":""}<sz val="11"/>${s?`<color rgb="${s}"/>`:""}<name val="Calibri"/><family val="2"/></font>`;class hi{constructor(){v(this,"fonts",new ye([$s()]));v(this,"fills",new ye(['<fill><patternFill patternType="none"/></fill>','<fill><patternFill patternType="gray125"/></fill>']));v(this,"numFmts",new Map);v(this,"xfs",new ye(['<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>']))}numFmtId(t){const e=ci[t];if(e!==void 0)return e;let s=this.numFmts.get(t);return s===void 0&&this.numFmts.set(t,s=164+this.numFmts.size),s}styleId(t){if(!t)return 0;const e=t.numberFormat?this.numFmtId(t.numberFormat):0,s=Ns(t.color),r=t.bold||t.italic||t.underline||t.strike||s?this.fonts.add($s(t.bold,t.italic,t.underline,s,t.strike)):0,i=Ns(t.background),o=i?this.fills.add(`<fill><patternFill patternType="solid"><fgColor rgb="${i}"/><bgColor indexed="64"/></patternFill></fill>`):0,l=t.align||t.wrap?`<alignment${_e({horizontal:t.align,wrapText:t.wrap})}/>`:"",a=`<xf${_e({numFmtId:e,fontId:r,fillId:o,borderId:0,xfId:0,applyNumberFormat:e>0,applyFont:r>0,applyFill:o>0,applyAlignment:!!l})}`+(l?`>${l}</xf>`:"/>");return this.xfs.add(a)}toXml(){const t=[...this.numFmts].map(([s,r])=>`<numFmt numFmtId="${r}" formatCode="${nt(s)}"/>`).join(""),e=(s,r)=>`<${s} count="${r.length}">${r.join("")}</${s}>`;return ht+`<styleSheet xmlns="${ai}">`+(this.numFmts.size?`<numFmts count="${this.numFmts.size}">${t}</numFmts>`:"")+e("fonts",this.fonts.items)+e("fills",this.fills.items)+'<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>'+e("cellXfs",this.xfs.items)+'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles><dxfs count="0"/><tableStyles count="0"/></styleSheet>'}}let Ut;function ui(){if(Ut)return Ut;Ut=new Uint32Array(256);for(let n=0;n<256;n++){let t=n;for(let e=0;e<8;e++)t=t&1?3988292384^t>>>1:t>>>1;Ut[n]=t>>>0}return Ut}function he(n){const t=ui();let e=4294967295;for(let s=0;s<n.length;s++)e=t[(e^n[s])&255]^e>>>8;return(e^4294967295)>>>0}function di(n){const t=Math.max(1980,n.getFullYear());return{time:n.getHours()<<11|n.getMinutes()<<5|n.getSeconds()>>1,date:t-1980<<9|n.getMonth()+1<<5|n.getDate()}}const Tn=0,fi=8,Ls=2048;function In(n,t){if(n.length>65535)throw new RangeError("Too many ZIP entries");const{time:e,date:s}=di(t);let r=0,i=0;for(const p of n)r+=30+p.name.length+p.payload.length,i+=46+p.name.length;if(r+i+22>4294967295)throw new RangeError("ZIP archive too large (no ZIP64 support)");const o=new Uint8Array(r+i+22),l=new DataView(o.buffer),a=[];let c=0;const h=p=>(l.setUint16(c,p,!0),c+=2),u=p=>(l.setUint32(c,p>>>0,!0),c+=4);for(const p of n)a.push(c),u(67324752),h(20),h(Ls),h(p.method),h(e),h(s),u(p.crc),u(p.payload.length),u(p.size),h(p.name.length),h(0),o.set(p.name,c),c+=p.name.length,o.set(p.payload,c),c+=p.payload.length;const d=c;return n.forEach((p,g)=>{u(33639248),h(20),h(20),h(Ls),h(p.method),h(e),h(s),u(p.crc),u(p.payload.length),u(p.size),h(p.name.length),h(0),h(0),h(0),h(0),u(0),u(a[g]),o.set(p.name,c),c+=p.name.length}),u(101010256),h(0),h(0),h(n.length),h(n.length),u(i),u(d),h(0),o}const On=new TextEncoder;function Un(n,t=new Date){return In(n.map(e=>({name:On.encode(e.path),crc:he(e.data),size:e.data.length,method:Tn,payload:e.data})),t)}async function pi(n){const t=new Blob([n]).stream().pipeThrough(new CompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}const mi=()=>typeof CompressionStream=="function";async function Pn(n,t=new Date){const e=mi(),s=[];for(const r of n){let i=r.data,o=Tn;if(e&&r.data.length>0)try{const l=await pi(r.data);l.length<r.data.length&&(i=l,o=fi)}catch{}s.push({name:On.encode(r.path),crc:he(r.data),size:r.data.length,method:o,payload:i})}return In(s,t)}const Hn="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",os="http://schemas.openxmlformats.org/spreadsheetml/2006/main",xt="http://schemas.openxmlformats.org/officeDocument/2006/relationships",ve="http://schemas.openxmlformats.org/package/2006/relationships",Yt="application/vnd.openxmlformats-officedocument.spreadsheetml",ls=32767,gi=new Set(["#NULL!","#DIV/0!","#VALUE!","#REF!","#NAME?","#NUM!","#N/A"]);function _n(n){const t=new Set;return n.map((e,s)=>{let r=e.replace(/[:\\/?*[\]]/g,"_").replace(/^'+|'+$/g,"").trim();r||(r=`Sheet${s+1}`),r=[...r].slice(0,31).join("");let i=r;for(let o=2;t.has(i.toLowerCase());o++){const l=` (${o})`;i=[...r].slice(0,31-l.length).join("")+l}return t.add(i.toLowerCase()),i})}const Vn=n=>Math.max(0,Math.round((n-5)/7*256)/256),wi=n=>Math.round(n*.75*100)/100,Lt=(n,t)=>`${zt(t)}${n+1}`,be=(n,t,e,s)=>`${Lt(n,t)}:${Lt(n+e-1,t+s-1)}`;class yi{constructor(){v(this,"index",new Map);v(this,"list",[]);v(this,"count",0)}add(t){this.count++;let e=this.index.get(t);return e===void 0&&(e=this.list.push(t)-1,this.index.set(t,e)),e}toXml(){const t=this.list.map(e=>`<si>${vi(e)}</si>`).join("");return`${ht}<sst xmlns="${os}" count="${this.count}" uniqueCount="${this.list.length}">${t}</sst>`}}const vi=n=>`<t${/^\s|\s$|\n/.test(n)?' xml:space="preserve"':""}>${nt(n.slice(0,ls))}</t>`;function Bn(n){return gi.has(n.code)?n.code:"#VALUE!"}function bi(n,t,e,s){return e===null?t?`<c r="${n}"${t}/>`:"":typeof e=="number"?Number.isFinite(e)?`<c r="${n}"${t}><v>${e}</v></c>`:`<c r="${n}"${t} t="e"><v>#NUM!</v></c>`:typeof e=="boolean"?`<c r="${n}"${t} t="b"><v>${e?1:0}</v></c>`:e instanceof ct?`<c r="${n}"${t} t="e"><v>${Bn(e)}</v></c>`:`<c r="${n}"${t} t="s"><v>${s.add(e.slice(0,ls))}</v></c>`}function xi(n,t,e,s){const r=`<f>${nt(e.slice(1))}</f>`;return s==null?`<c r="${n}"${t}>${r}</c>`:typeof s=="number"?Number.isFinite(s)?`<c r="${n}"${t}>${r}<v>${s}</v></c>`:`<c r="${n}"${t} t="e">${r}<v>#NUM!</v></c>`:typeof s=="boolean"?`<c r="${n}"${t} t="b">${r}<v>${s?1:0}</v></c>`:s instanceof ct?`<c r="${n}"${t} t="e">${r}<v>${Bn(s)}</v></c>`:`<c r="${n}"${t} t="str">${r}<v>${nt(s.slice(0,ls))}</v></c>`}function Ai(n){const t=[];for(const e of n??[]){if(e.rowspan<1||e.colspan<1||e.rowspan*e.colspan<2||e.row<0||e.col<0)continue;t.some(r=>e.row<r.row+r.rowspan&&r.row<e.row+e.rowspan&&e.col<r.col+r.colspan&&r.col<e.col+e.colspan)||t.push(e)}return t}function Ci(n,t,e,s){var m,f,x,A,k;const r=n.data.length;let i=0;for(const F of n.data)i=Math.max(i,(F==null?void 0:F.length)??0);if(r>1048576||i>16384)throw new RangeError(`Sheet "${n.name}" exceeds 1048576 rows or 16384 columns`);let o=`${ht}<worksheet xmlns="${os}" xmlns:r="${xt}">`;o+=`<dimension ref="${r&&i?be(0,0,r,i):"A1"}"/>`;const l=Math.max(0,Math.floor(((m=n.frozen)==null?void 0:m.rows)??0)),a=Math.max(0,Math.floor(((f=n.frozen)==null?void 0:f.cols)??0)),c=t===0?' tabSelected="1"':"";if(l||a){const F=l&&a?"bottomRight":l?"bottomLeft":"topRight";o+=`<sheetViews><sheetView${c} workbookViewId="0"><pane${_e({xSplit:a||void 0,ySplit:l||void 0,topLeftCell:Lt(l,a),activePane:F,state:"frozen"})}/><selection pane="${F}" activeCell="${Lt(l,a)}" sqref="${Lt(l,a)}"/></sheetView></sheetViews>`}else o+=`<sheetViews><sheetView${c} workbookViewId="0"/></sheetViews>`;o+='<sheetFormatPr defaultRowHeight="15"/>';const h=n.colWidths??[],u=[];h.forEach((F,$)=>{typeof F=="number"&&F>0&&$<16384&&u.push(`<col min="${$+1}" max="${$+1}" width="${Vn(F)}" customWidth="1"/>`)}),u.length&&(o+=`<cols>${u.join("")}</cols>`);const d=n.rowHeights??[],p=Math.min(1048576,Math.max(r,d.length)),g=[];for(let F=0;F<p;F++){const $=n.data[F]??[];let L="";for(let _=0;_<$.length;_++){const R=e.styleId((x=n.format)==null?void 0:x.call(n,F,_)),E=R?` s="${R}"`:"",D=$[_],M=Lt(F,_);L+=V(D)?xi(M,E,D,(k=(A=n.values)==null?void 0:A[F])==null?void 0:k[_]):bi(M,E,at(D),s)}const H=d[F],X=typeof H=="number"&&H>0?` ht="${wi(H)}" customHeight="1"`:"";(L||X)&&g.push(`<row r="${F+1}"${X}>${L}</row>`)}o+=g.length?`<sheetData>${g.join("")}</sheetData>`:"<sheetData/>";const C=n.autoFilter;C&&C.rows>0&&C.cols>0&&(o+=`<autoFilter ref="${be(C.row,C.col,C.rows,C.cols)}"/>`);const y=Ai(n.merges);if(y.length){o+=`<mergeCells count="${y.length}">`;for(const F of y)o+=`<mergeCell ref="${be(F.row,F.col,F.rowspan,F.colspan)}"/>`;o+="</mergeCells>"}return o+='<pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>',o+"</worksheet>"}const Si=n=>n.toISOString().replace(/\.\d{3}Z$/,"Z");function as(n,t={}){if(!n.length)throw new Error("A workbook needs at least one sheet");const e=_n(n.map(f=>f.name)),s=new hi,r=new yi,i=n.map((f,x)=>Ci(f,x,s,r)),o=Si(t.modified??new Date),l=`${ht}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="${Yt}.sheet.main+xml"/>`+n.map((f,x)=>`<Override PartName="/xl/worksheets/sheet${x+1}.xml" ContentType="${Yt}.worksheet+xml"/>`).join("")+`<Override PartName="/xl/styles.xml" ContentType="${Yt}.styles+xml"/><Override PartName="/xl/sharedStrings.xml" ContentType="${Yt}.sharedStrings+xml"/><Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/><Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/></Types>`,a=`${ht}<Relationships xmlns="${ve}"><Relationship Id="rId1" Type="${xt}/officeDocument" Target="xl/workbook.xml"/><Relationship Id="rId2" Type="${ve}/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId3" Type="${xt}/extended-properties" Target="docProps/app.xml"/></Relationships>`,c=nt(t.creator??"CenituTable"),h=`${ht}<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><dc:creator>${c}</dc:creator><cp:lastModifiedBy>${c}</cp:lastModifiedBy><dcterms:created xsi:type="dcterms:W3CDTF">${o}</dcterms:created><dcterms:modified xsi:type="dcterms:W3CDTF">${o}</dcterms:modified></cp:coreProperties>`,u=`${ht}<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><Application>CenituTable</Application><HeadingPairs><vt:vector size="2" baseType="variant"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>${e.length}</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size="${e.length}" baseType="lpstr">`+e.map(f=>`<vt:lpstr>${nt(f)}</vt:lpstr>`).join("")+"</vt:vector></TitlesOfParts></Properties>",d=n.map((f,x)=>{const A=f.autoFilter;if(!A||A.rows<1||A.cols<1)return"";const k=($,L)=>`$${zt(L)}$${$+1}`,F=`'${e[x].replace(/'/g,"''")}'!${k(A.row,A.col)}:${k(A.row+A.rows-1,A.col+A.cols-1)}`;return`<definedName name="_xlnm._FilterDatabase" localSheetId="${x}" hidden="1">${nt(F)}</definedName>`}).join(""),p=`${ht}<workbook xmlns="${os}" xmlns:r="${xt}"><bookViews><workbookView activeTab="0"/></bookViews><sheets>`+e.map((f,x)=>`<sheet name="${nt(f)}" sheetId="${x+1}" r:id="rId${x+1}"/>`).join("")+"</sheets>"+(d?`<definedNames>${d}</definedNames>`:"")+'<calcPr calcId="191029" fullCalcOnLoad="1"/></workbook>',g=n.length,C=`${ht}<Relationships xmlns="${ve}">`+n.map((f,x)=>`<Relationship Id="rId${x+1}" Type="${xt}/worksheet" Target="worksheets/sheet${x+1}.xml"/>`).join("")+`<Relationship Id="rId${g+1}" Type="${xt}/styles" Target="styles.xml"/><Relationship Id="rId${g+2}" Type="${xt}/sharedStrings" Target="sharedStrings.xml"/></Relationships>`,y=new TextEncoder,m=(f,x)=>({path:f,data:y.encode(x)});return[m("[Content_Types].xml",l),m("_rels/.rels",a),m("docProps/core.xml",h),m("docProps/app.xml",u),m("xl/workbook.xml",p),m("xl/_rels/workbook.xml.rels",C),m("xl/styles.xml",s.toXml()),m("xl/sharedStrings.xml",r.toXml()),...i.map((f,x)=>m(`xl/worksheets/sheet${x+1}.xml`,f))]}function Ei(n,t={}){return Un(as(n,t),t.modified)}function Xn(n,t={}){return Pn(as(n,t),t.modified)}const zs=0,Mi=8,ki=1,Ve=22,Ri=1024**3;function Fi(n){const t=Math.max(0,n.byteLength-Ve-65535);for(let e=n.byteLength-Ve;e>=t;e--)if(n.getUint32(e,!0)===101010256)return e;throw new Error("Not a ZIP archive")}function Di(n){const t=new DataView(n.buffer,n.byteOffset,n.byteLength);if(n.length<Ve)throw new Error("Not a ZIP archive");const e=Fi(t),s=t.getUint16(e+10,!0);let r=t.getUint32(e+16,!0);const i=new TextDecoder,o=[];for(let l=0;l<s;l++){if(r+46>n.length||t.getUint32(r,!0)!==33639248)throw new Error("Corrupt ZIP directory");const a=t.getUint16(r+28,!0);o.push({path:i.decode(n.subarray(r+46,r+46+a)),flags:t.getUint16(r+8,!0),method:t.getUint16(r+10,!0),crc:t.getUint32(r+16,!0),compressedSize:t.getUint32(r+20,!0),size:t.getUint32(r+24,!0),headerOffset:t.getUint32(r+42,!0)}),r+=46+a+t.getUint16(r+30,!0)+t.getUint16(r+32,!0)}return o}function Ni(n,t){const e=new DataView(n.buffer,n.byteOffset,n.byteLength),s=t.headerOffset;if(s+30>n.length||e.getUint32(s,!0)!==67324752)throw new Error(`Corrupt ZIP entry: ${t.path}`);const r=s+30+e.getUint16(s+26,!0)+e.getUint16(s+28,!0);if(r+t.compressedSize>n.length)throw new Error(`Corrupt ZIP entry: ${t.path}`);return n.subarray(r,r+t.compressedSize)}async function $i(n,t,e){if(typeof DecompressionStream!="function")throw new Error("This environment cannot decompress ZIP entries");const s=new Blob([n]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader(),r=[];let i=0;for(;;){const{done:a,value:c}=await s.read();if(a)break;if(i+=c.length,i>t)throw await s.cancel(),new RangeError(`ZIP entry too large: ${e}`);r.push(c)}const o=new Uint8Array(i);let l=0;for(const a of r)o.set(a,l),l+=a.length;return o}class Wn{constructor(t,e={}){v(this,"entries",new Map);v(this,"remaining");this.bytes=t,this.remaining=e.maxSize??Ri;for(const s of Di(t))this.entries.set(s.path,s)}has(t){return this.entries.has(t)}get paths(){return[...this.entries.keys()]}async read(t){const e=this.entries.get(t);if(!e)return;if(e.flags&ki)throw new Error("Encrypted packages are not supported");if(e.method!==zs&&e.method!==Mi)throw new Error(`Unsupported ZIP compression: ${e.method}`);const s=Ni(this.bytes,e),r=e.method===zs?s:await $i(s,this.remaining,t);if(r.length>this.remaining)throw new RangeError(`ZIP entry too large: ${t}`);if(he(r)!==e.crc)throw new Error(`ZIP checksum mismatch: ${t}`);return this.remaining-=r.length,r}async readText(t){const e=await this.read(t);return e&&new TextDecoder().decode(e)}}const Li={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function Be(n){return n.includes("&")?n.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi,(t,e)=>{if(e[0]!=="#")return Li[e]??t;const s=e[1]==="x"||e[1]==="X"?parseInt(e.slice(2),16):parseInt(e.slice(1),10);return s<=1114111?String.fromCodePoint(s):t}):n}const Xe=n=>{const t=n.indexOf(":");return t<0?n:n.slice(t+1)},xe=/([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;function zi(n){const t={};xe.lastIndex=0;for(let e=xe.exec(n);e;e=xe.exec(n))e[1].startsWith("xmlns")||(t[Xe(e[1])]=Be(e[2]??e[3]));return t}function Ti(n,t){let e="";for(let s=t;s<n.length;s++){const r=n[s];if(e)r===e&&(e="");else if(r==='"'||r==="'")e=r;else if(r===">")return s}return-1}const Ae=(n,t,e)=>{const s=n.indexOf(t,e);if(s<0)throw new Error("Malformed XML");return s+t.length};function Ot(n,t){var s,r,i,o;let e=0;for(;e<n.length;){const l=n.indexOf("<",e);if(l<0){t.text&&e<n.length&&t.text(Be(n.slice(e)));return}if(l>e&&t.text&&t.text(Be(n.slice(e,l))),n.startsWith("<?",l))e=Ae(n,"?>",l);else if(n.startsWith("<!--",l))e=Ae(n,"-->",l);else if(n.startsWith("<![CDATA[",l))e=Ae(n,"]]>",l),(s=t.text)==null||s.call(t,n.slice(l+9,e-3));else if(n.startsWith("<!",l))e=Ii(n,l);else{const a=Ti(n,l);if(a<0)throw new Error("Malformed XML");if(e=a+1,n[l+1]==="/"){(r=t.close)==null||r.call(t,Xe(n.slice(l+2,a).trim()));continue}const c=n[a-1]==="/",h=n.slice(l+1,c?a-1:a),u=h.search(/\s/),d=Xe(u<0?h:h.slice(0,u));(i=t.open)==null||i.call(t,d,u>=0?zi(h.slice(u)):{},c),c&&((o=t.close)==null||o.call(t,d))}}}function Ii(n,t){let e=0;for(let s=t;s<n.length;s++)if(n[s]==="[")e++;else if(n[s]==="]")e--;else if(n[s]===">"&&e===0)return s+1;throw new Error("Malformed XML")}const Oi={1:"0",2:"0.00",3:"#,##0",4:"#,##0.00",9:"0%",10:"0.00%",11:"0.00E+00",12:"# ?/?",13:"# ??/??",14:"mm-dd-yy",15:"d-mmm-yy",16:"d-mmm",17:"mmm-yy",18:"h:mm AM/PM",19:"h:mm:ss AM/PM",20:"h:mm",21:"h:mm:ss",22:"m/d/yy h:mm",37:"#,##0;(#,##0)",38:"#,##0;[Red](#,##0)",39:"#,##0.00;(#,##0.00)",40:"#,##0.00;[Red](#,##0.00)",45:"mm:ss",46:"[h]:mm:ss",47:"mmss.0",48:"##0.0E+0",49:"@"},Ui=["000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","000000","FFFFFF","FF0000","00FF00","0000FF","FFFF00","FF00FF","00FFFF","800000","008000","000080","808000","800080","008080","C0C0C0","808080","9999FF","993366","FFFFCC","CCFFFF","660066","FF8080","0066CC","CCCCFF","000080","FF00FF","FFFF00","00FFFF","800080","800000","008080","0000FF","00CCFF","CCFFFF","CCFFCC","FFFF99","99CCFF","FF99CC","CC99FF","FFCC99","3366FF","33CCCC","99CC00","FFCC00","FF9900","FF6600","666699","969696","003366","339966","003300","333300","993300","993366","333399","333333"],Ts=["lt1","dk1","lt2","dk2","accent1","accent2","accent3","accent4","accent5","accent6","hlink","folHlink"];function Pi(n){const t=new Map;if(n){let e="";Ot(n,{open(s,r){Ts.includes(s)?e=s:e&&s==="srgbClr"?t.set(e,r.val):e&&s==="sysClr"&&t.set(e,r.lastClr??"")},close(s){s===e&&(e="")}})}return Ts.map(e=>t.get(e)??"")}function Hi(n,t){const e=s=>{const r=parseInt(n.slice(s,s+2),16),i=t<0?r*(1+t):r+(255-r)*t;return Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0")};return`${e(0)}${e(2)}${e(4)}`.toUpperCase()}function Is(n,t){let e;if(n.rgb?e=n.rgb.length===8?n.rgb.slice(2):n.rgb:n.theme!==void 0?e=t[Number(n.theme)]:n.indexed!==void 0&&(e=Ui[Number(n.indexed)]),!(!e||!/^[0-9a-f]{6}$/i.test(e)))return`#${(n.tint?Hi(e,Number(n.tint)):e).toLowerCase()}`}const Ce=n=>n.val!=="0"&&n.val!=="false",_i={left:"left",center:"center",right:"right",centerContinuous:"center"};class Vi{constructor(t,e){v(this,"codes",new Map);v(this,"fonts",[]);v(this,"fills",[]);v(this,"xfs",[]);v(this,"cache",new Map);this.theme=e,t&&this.parse(t)}parse(t){let e="",s,r,i;Ot(t,{open:(o,l)=>{o==="numFmts"||o==="fonts"||o==="fills"||o==="cellXfs"||o==="dxfs"||o==="cellStyleXfs"?e=o:e==="numFmts"&&o==="numFmt"?this.codes.set(Number(l.numFmtId),l.formatCode):e==="fonts"?o==="font"?s={}:s&&o==="b"?s.bold=Ce(l):s&&o==="i"?s.italic=Ce(l):s&&o==="strike"?s.strike=Ce(l):s&&o==="u"?s.underline=l.val!=="none":s&&o==="color"&&(s.color=Is(l,this.theme)):e==="fills"?o==="fill"?r={solid:!1}:r&&o==="patternFill"?r.solid=l.patternType==="solid":r&&o==="fgColor"&&(r.color=Is(l,this.theme)):e==="cellXfs"&&(o==="xf"?i={numFmtId:Number(l.numFmtId??0),fontId:Number(l.fontId??0),fillId:Number(l.fillId??0)}:i&&o==="alignment"&&(i.align=_i[l.horizontal],i.wrap=l.wrapText==="1"||l.wrapText==="true"))},close:o=>{o===e?e="":o==="font"&&s?(this.fonts.push(s),s=void 0):o==="fill"&&r?(this.fills.push(r.solid?r.color:void 0),r=void 0):o==="xf"&&i&&(this.xfs.push(i),i=void 0)}})}numberFormat(t){var s;const e=((s=this.xfs[t])==null?void 0:s.numFmtId)??0;return e?this.codes.get(e)??Oi[e]:void 0}isDate(t){return ce(this.numberFormat(t))}format(t){if(this.cache.has(t))return this.cache.get(t);const e=this.xfs[t];let s;if(e){const r=this.fonts[e.fontId],i=this.fonts[0],o={},l=this.numberFormat(t);l&&(o.numberFormat=l),r!=null&&r.bold&&(o.bold=!0),r!=null&&r.italic&&(o.italic=!0),r!=null&&r.underline&&(o.underline=!0),r!=null&&r.strike&&(o.strike=!0),r!=null&&r.color&&r.color!==(i==null?void 0:i.color)&&(o.color=r.color);const a=this.fills[e.fillId];a&&(o.background=a),e.align&&(o.align=e.align),e.wrap&&(o.wrap=!0),Object.keys(o).length&&(s=o)}return this.cache.set(t,s),s}}function Bi(n){var l;const t=n.split(";")[0].replace(/\[[^\]]*\]/g,"").replace(/\\(.)/g,"$1").replace(/"([^"]*)"/g,"$1");if(/AM\/PM|A\/P|mmm|ddd|[.]0|_|\*/i.test(t))return;const e=/yyyy|yy|mm|m|dd|d|hh|h|ss|s/gi;let s="",r=0,i="";const o=[...t.matchAll(e)];for(let a=0;a<o.length;a++){const c=o[a],h=c[0].toLowerCase();if(s+=t.slice(r,c.index),r=c.index+c[0].length,h[0]==="y")s+=h.length>2?"YYYY":"YY";else if(h[0]==="d")s+=h.length>1?"DD":"D";else if(h[0]==="h")s+="HH";else if(h[0]==="s")s+="ss";else{const u=(l=o[a+1])==null?void 0:l[0][0].toLowerCase();s+=i==="h"||u==="s"?"mm":h.length>1?"MM":"M"}i=h[0]}return/[^YMDHms\s\-/.:,]/.test(s+t.slice(r))?void 0:s+t.slice(r)}const Xi={"₺":"TRY",TL:"TRY","€":"EUR",$:"USD","£":"GBP"};function Wi(n){var l,a;const t=n.split(";")[0],e=((l=/\.([0#]+)/.exec(t))==null?void 0:l[1])??"",s={minimumFractionDigits:e.replace(/#/g,"").length,maximumFractionDigits:e.length,useGrouping:/#,##0|0,0/.test(t)};if(!/[0#]/.test(t)||/E[+-]|\?/i.test(t))return;if(t.includes("%"))return{style:"percent",...s};const r=/"([^"]+)"|\[\$([^\]-]*)/.exec(t),i=((r==null?void 0:r[1])??(r==null?void 0:r[2])??((a=/[₺€$£]/.exec(t))==null?void 0:a[0])??"").trim(),o=Xi[i]??(/^[A-Z]{3}$/.test(i)?i:void 0);return o?{style:"currency",currency:o,...s}:{style:"decimal",...s}}function ji(n){const t={};if(n.numberFormat&&n.numberFormat!=="@")if(t.formatCode=n.numberFormat,ce(n.numberFormat)){t.type="date";const u=n.numberFormat==="mm-dd-yy"?void 0:Bi(n.numberFormat);u&&(t.dateFormat=u)}else{const u=Wi(n.numberFormat);u&&(t.numericFormat=u)}const{bold:e,italic:s,underline:r,strike:i,color:o,background:l,align:a,wrap:c}=n,h=Object.fromEntries(Object.entries({bold:e,italic:s,underline:r,strike:i,color:o,background:l,align:a,wrap:c}).filter(([,u])=>u!==void 0));return Object.keys(h).length&&(t.style=h),t}const Yi=/^([A-Z]+)(\d+)$/;function We(n){const t=Yi.exec(n.replace(/\$/g,""));return t?{row:Number(t[2])-1,col:se(t[1])}:void 0}function Se(n){const[t,e=t]=n.split(":"),s=We(t),r=We(e);return s&&r?{start:s,end:r}:void 0}function Kt(n){return n===""?null:n[0]==="="||n[0]==="'"||typeof at(n)!="string"?`'${n}`:n}const Ki=n=>n.replace(/_xlfn\.(_xlws\.)?|_xlws\.|_xludf\./gi,""),Os={fromColWidth:n=>Math.round(n*7+5),fromPt:n=>Math.round(n/.75)};function Ee(n,t){if(t[0]==="/")return t.slice(1);const e=n.split("/").slice(0,-1);for(const s of t.split("/"))s===".."?e.pop():s!=="."&&e.push(s);return e.join("/")}function Us(n){const t=new Map;return n&&Ot(n,{open(e,s){e==="Relationship"&&s.TargetMode!=="External"&&t.set(s.Id,s.Target)}}),t}function qi(n){const t=[];if(!n)return t;let e="",s=!1,r=0;return Ot(n,{open(i){i==="si"?e="":i==="rPh"?r++:i==="t"&&(s=r===0)},close(i){i==="si"?t.push(e):i==="rPh"?r--:i==="t"&&(s=!1)},text(i){s&&(e+=i)}}),t}function Zi(n,t,e,s){const r=[],i=[],o=new Map,l=new Map,a=[],c=[],h=[],u=[],d=[],p={rows:0,cols:0};let g,C=null,y=null,m=0,f=0,x=-1,A=-1;const k=(R,E,D,M)=>{for(;r.length<=R;)r.push([]),i.push([]);r[R][E]=D,i[R][E]=M,x=Math.max(x,R),A=Math.max(A,E)},F=(R,E)=>{const D=R.value;switch(R.type){case"s":{const N=s.strings[Number(D)]??"";return{raw:Kt(N),value:N||null}}case"inlineStr":return{raw:Kt(R.inline),value:R.inline||null};case"str":return{raw:Kt(D),value:D||null};case"b":return{raw:D==="1",value:D==="1"};case"e":return{raw:`'${D}`,value:Zs.includes(D)?new ct(D):D};case"d":{const N=Date.parse(D),I=Number.isNaN(N)?null:N/864e5+25569;return{raw:I,value:I}}}if(D==="")return{raw:null,value:null};const M=Number(D)+(s.date1904&&E!==void 0?1462:0);return Number.isNaN(M)?{raw:Kt(D),value:D}:{raw:M,value:M}},$=(R,E,D)=>{const M=R.formulaAttrs;if(M){if(M.t==="shared"&&M.si!==void 0){if(R.formula)return l.set(M.si,{formula:R.formula,row:E,col:D}),R.formula;const N=l.get(M.si);return N&&s.shifter.shiftFormula(`=${N.formula}`,E-N.row,D-N.col).slice(1)}if(M.t==="array"&&M.ref){const N=Se(M.ref);N&&(N.start.row!==N.end.row||N.start.col!==N.end.col)&&a.push(N)}return R.formula||void 0}},L=R=>{const E=We(R.ref)??{row:m,col:f};if(f=E.col+1,E.row>=1048576||E.col>=16384)return;R.style&&o.set(E.row*16384+E.col,R.style);const D=R.style&&s.styles.isDate(R.style)?1:void 0,{raw:M,value:N}=F(R,D),I=s.values?void 0:$(R,E.row,E.col);I?k(E.row,E.col,`=${Ki(I)}`,N):M!==null&&k(E.row,E.col,M,N)};Ot(n,{open(R,E,D){switch(R){case"pane":(E.state==="frozen"||E.state==="frozenSplit")&&(p.rows=Number(E.ySplit??0),p.cols=Number(E.xSplit??0));break;case"col":{const M=Number(E.min)-1,N=Math.min(Number(E.max)-1,16383);for(let I=M;I<=N&&I<M+1024;I++)E.width&&E.customWidth!=="0"&&(h[I]=Os.fromColWidth(Number(E.width))),(E.hidden==="1"||E.hidden==="true")&&u.push(I);break}case"row":m=E.r?Number(E.r)-1:m,f=0,E.ht&&E.customHeight&&E.customHeight!=="0"&&m<1048576&&(d[m]=Os.fromPt(Number(E.ht)));break;case"c":C={ref:E.r??"",type:E.t??"n",style:Number(E.s??0),formula:"",formulaAttrs:null,value:"",inline:""},D&&(L(C),C=null);break;case"f":C&&(C.formulaAttrs=E,y=D?null:"f");break;case"v":C&&(y=D?null:"v");break;case"t":C&&(y=D?null:"t");break;case"mergeCell":{const M=E.ref?Se(E.ref):void 0;M&&c.push({row:M.start.row,col:M.start.col,rowspan:M.end.row-M.start.row+1,colspan:M.end.col-M.start.col+1});break}case"autoFilter":{const M=E.ref?Se(E.ref):void 0;M&&(g={row:M.start.row,col:M.start.col,rows:M.end.row-M.start.row+1,cols:M.end.col-M.start.col+1});break}}},close(R){R==="c"&&C?(L(C),C=null):R==="row"?m++:(R==="f"||R==="v"||R==="t")&&(y=null)},text(R){!C||!y||(y==="f"?C.formula+=R:y==="v"?C.value+=R:C.inline+=R)}});for(const R of a)for(let E=R.start.row;E<=R.end.row;E++)for(let D=R.start.col;D<=R.end.col;D++)E===R.start.row&&D===R.start.col||r[E]&&(r[E][D]=null);const H=Math.max(x+1,c.reduce((R,E)=>Math.max(R,E.row+E.rowspan),0)),X=Math.max(A+1,c.reduce((R,E)=>Math.max(R,E.col+E.colspan),0)),_=R=>Array.from({length:H},(E,D)=>Array.from({length:X},(M,N)=>{var I;return((I=R[D])==null?void 0:I[N])??null}));return{name:t,hidden:e,data:_(r),values:_(i),colWidths:h.slice(0,X),rowHeights:d.slice(0,H),frozen:p,merges:c,hiddenColumns:u.filter(R=>R<X),autoFilter:g,format:(R,E)=>{const D=o.get(R*16384+E);return D?s.styles.format(D):void 0}}}async function Gi(n){return n instanceof Uint8Array?n:n instanceof ArrayBuffer?new Uint8Array(n):new Uint8Array(await n.arrayBuffer())}async function jn(n,t={}){const e=new Wn(await Gi(n),t),r=[...Us(await e.readText("_rels/.rels")).values()].find(m=>/workbook[^/]*\.xml$/i.test(m))??"xl/workbook.xml",i=Ee("",r),o=await e.readText(i);if(!o)throw new Error("Not an .xlsx workbook");const l=Ee(i,`_rels/${i.split("/").pop()}.rels`),a=Us(await e.readText(l)),c=[],h=[];let u=!1,d=null;Ot(o,{open(m,f){m==="sheet"?c.push({name:f.name,id:f.id,hidden:f.state==="hidden"||f.state==="veryHidden"}):m==="workbookPr"?u=f.date1904==="1"||f.date1904==="true":m==="definedName"&&(d={name:f.name,text:"",local:f.localSheetId!==void 0})},text(m){d&&(d.text+=m)},close(m){m!=="definedName"||!d||(!d.local&&!d.name.startsWith("_xlnm.")&&h.push({name:d.name,expression:`=${d.text}`}),d=null)}});const p=m=>e.paths.find(f=>f.toLowerCase()===m),g=Pi(await e.readText(p("xl/theme/theme1.xml")??"")),C={strings:qi(await e.readText(p("xl/sharedstrings.xml")??"")),styles:new Vi(await e.readText(p("xl/styles.xml")??""),g),date1904:u,values:t.formulas==="values",shifter:ut.buildEmpty()},y=[];for(const m of c){const f=a.get(m.id),x=f?await e.readText(Ee(i,f)):void 0;x&&y.push(Zi(x,m.name,m.hidden,C))}return C.shifter.destroy(),{sheets:y,names:h}}function Qi(n){const t=ut.buildEmpty();n.sheets.forEach((e,s)=>{s===0?t.renameSheet(0,e.name):t.addSheet(e.name)});for(const{name:e,expression:s}of n.names)t.isItPossibleToAddNamedExpression(e)&&t.addNamedExpression(e,s);return t}function Ji(n){const t=[];n.bold&&t.push("font-weight:700"),n.italic&&t.push("font-style:italic");const e=[n.underline&&"underline",n.strike&&"line-through"].filter(Boolean).join(" ");return e&&t.push(`text-decoration:${e}`),n.color&&t.push(`color:${n.color}`),n.background&&t.push(`background-color:${n.background}`),n.align&&t.push(`text-align:${n.align}`),n.wrap&&t.push("white-space:normal"),t.join(";")}function to(n,t){const e=(r,i)=>{const o=i?Ji(i):"";return`<td${o?` style="${nt(o)}"`:""}>${nt(r)}</td>`};return`<table>${n.map((r,i)=>`<tr>${r.map((o,l)=>{var a;return e(o,(a=t[i])==null?void 0:a[l])}).join("")}</tr>`).join("")}</table>`}const Me=n=>Number(n).toString(16).padStart(2,"0"),eo=["auto","inherit","initial","unset","currentcolor","transparent","windowtext","window","none"];function Ps(n,t){const e=n==null?void 0:n.trim().toLowerCase();if(!e)return;const s=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,/]+([\d.]+))?\s*\)$/.exec(e),r=s?s[4]==="0"?void 0:`#${Me(s[1])}${Me(s[2])}${Me(s[3])}`:/^#[0-9a-f]{3,8}$/.test(e)?e:void 0;return r?t.includes(r)?void 0:r:/^[a-z]+$/.test(e)&&!eo.includes(e)&&!t.includes(e)?e:void 0}function Yn(n){const t=new Map;for(const e of n.split(";")){const s=e.indexOf(":");s>0&&t.set(e.slice(0,s).trim().toLowerCase(),e.slice(s+1).replace(/!important/i,"").trim())}return t}function so(n){const t=new Map;return n.querySelectorAll("style").forEach(e=>{const s=(e.textContent??"").replace(/<!--|-->|\/\*[\s\S]*?\*\//g," ");for(const r of s.matchAll(/([^{}]+)\{([^{}]*)\}/g))for(const i of r[1].split(","))t.set(i.trim().toLowerCase(),Yn(r[2]))}),t}function no(n){const t={},e=n.get("font-weight");(e==="bold"||Number(e)>=600)&&(t.bold=!0),n.get("font-style")==="italic"&&(t.italic=!0);const s=n.get("text-decoration")??n.get("text-decoration-line")??"";s.includes("underline")&&(t.underline=!0),s.includes("line-through")&&(t.strike=!0);const r=Ps(n.get("color"),["#000","#000000","black"]);r&&(t.color=r);const i=Ps(n.get("background-color")??n.get("background"),["#fff","#ffffff","white"]);i&&(t.background=i);const o=n.get("text-align");(o==="left"||o==="center"||o==="right")&&(t.align=o);const l=n.get("white-space");return(l==="normal"||l==="pre-wrap")&&(t.wrap=!0),Object.keys(t).length?t:void 0}function ro(n,t){const e=new t.DOMParser().parseFromString(n,"text/html"),s=e.querySelector("table");if(!s)return null;const r=so(e),i=[],o=[];return s.querySelectorAll("tr").forEach((l,a)=>{var h,u;i[a]??(i[a]=[]),o[a]??(o[a]=[]);let c=0;for(const d of Array.from(l.children)){for(;i[a][c]!==void 0;)c++;const p=new Map([...r.get(d.tagName.toLowerCase())??[],...[...d.classList].flatMap(m=>[...r.get(`.${m.toLowerCase()}`)??[]]),...Yn(d.getAttribute("style")??"")]),g=no(p),C=Math.max(1,d.rowSpan||1),y=Math.max(1,d.colSpan||1);for(let m=0;m<C;m++)for(let f=0;f<y;f++)(i[h=a+m]??(i[h]=[]))[c+f]=m===0&&f===0?(d.textContent??"").trim():"",(o[u=a+m]??(o[u]=[]))[c+f]=g;c+=y}}),i.length?{texts:i,styles:o}:null}function io(n,t,e,s,r){var y;const i=n.createElement("div");i.className="ct-menu ct-context",i.setAttribute("role","menu");const o=[];let l=!0;for(const m of t){if(m==="---"){l||i.append(Object.assign(n.createElement("div"),{className:"ct-menu-sep"})),l=!0;continue}l=!1;const f=n.createElement("button");f.type="button",f.className="ct-menu-item",f.setAttribute("role","menuitem"),f.dataset.key=m.key,f.disabled=!!m.disabled;const x=n.createElement("span");if(x.textContent=m.name,f.append(x),m.hint){const A=n.createElement("span");A.className="ct-menu-hint",A.textContent=m.hint,f.append(A)}f.addEventListener("click",()=>{C(),m.run()}),o.push(f),i.append(f)}n.body.append(i);const a=n.defaultView,c=i.offsetWidth||220,h=i.offsetHeight||300;i.style.left=`${Math.max(4,Math.min(e,((a==null?void 0:a.innerWidth)??1024)-c-4))}px`,i.style.top=`${Math.max(4,Math.min(s,((a==null?void 0:a.innerHeight)??768)-h-4))}px`;const u=()=>o.filter(m=>!m.disabled);(y=u()[0])==null||y.focus();const d=m=>{var A;const f=u(),x=f.indexOf(n.activeElement);if(m.key==="ArrowDown"||m.key==="ArrowUp"){m.preventDefault();const k=m.key==="ArrowDown"?(x+1)%f.length:(x-1+f.length)%f.length;(A=f[k])==null||A.focus()}else(m.key==="Escape"||m.key==="Tab")&&(m.preventDefault(),C());m.stopPropagation()},p=m=>{i.contains(m.target)||C()};i.addEventListener("keydown",d),n.addEventListener("mousedown",p,!0),a==null||a.addEventListener("blur",C);let g=!1;function C(){g||(g=!0,n.removeEventListener("mousedown",p,!0),a==null||a.removeEventListener("blur",C),i.remove(),r())}return C}function Hs(n,t,e,s){if(e.values&&!e.values.includes(t))return!1;const r=e.condition;if(!r)return!0;const i=n===null||t==="";switch(r.op){case"isEmpty":return i;case"isNotEmpty":return!i}const o=(r.value??"").toLocaleLowerCase(s),l=t.toLocaleLowerCase(s);switch(r.op){case"contains":return l.includes(o);case"notContains":return!l.includes(o)}const a=Ct((r.value??"").replace(",",".")),c=typeof n=="number"&&a!==void 0?Math.sign(n-a):P(l,o);switch(r.op){case"equals":return c===0;case"notEquals":return c!==0;case"greaterThan":return!i&&c>0;case"greaterOrEqual":return!i&&c>=0;case"lessThan":return!i&&c<0;default:return!i&&c<=0}}const _s=new Map;function oo(n){let t=_s.get(n);return t||_s.set(n,t=new Intl.Collator(n,{sensitivity:"base",numeric:!0})),t}const Vs=n=>typeof n=="number"?0:typeof n=="string"?1:typeof n=="boolean"?2:n instanceof ct?3:4;function lo(n,t,e,s){const r=n===null||n==="",i=t===null||t==="";if(r||i)return r===i?0:r?1:-1;const o=Vs(n),l=Vs(t);let a;return o!==l?a=o-l:o===3?a=0:o===1?a=oo(s).compare(n,t):a=P(n,t),e==="asc"?a:-a}const ke=n=>({start:{row:n.row,col:n.col},end:{row:n.row+n.rowspan-1,col:n.col+n.colspan-1}}),Bs=(n,t)=>n.start.row<=t.end.row&&n.end.row>=t.start.row&&n.start.col<=t.end.col&&n.end.col>=t.start.col;class ao{constructor(){v(this,"areas",[]);v(this,"index",new Map)}get list(){return this.areas}set(t){this.areas=[];for(const e of t)this.add(e);this.reindex()}add(t){if(t.rowspan<1||t.colspan<1||t.rowspan===1&&t.colspan===1)return!1;const e=ke(t);return this.areas=this.areas.filter(s=>!Bs(ke(s),e)),this.areas.push({...t}),this.reindex(),!0}removeAt(t,e){const s=this.get(t,e);return s?(this.areas=this.areas.filter(r=>r!==s),this.reindex(),!0):!1}get(t,e){return this.index.get(t*1048576+e)}expand(t){const e={start:{...t.start},end:{...t.end}};let s=this.areas.length>0;for(;s;){s=!1;for(const r of this.areas){const i=ke(r);Bs(i,e)&&(i.start.row<e.start.row&&(e.start.row=i.start.row,s=!0),i.start.col<e.start.col&&(e.start.col=i.start.col,s=!0),i.end.row>e.end.row&&(e.end.row=i.end.row,s=!0),i.end.col>e.end.col&&(e.end.col=i.end.col,s=!0))}}return e}shift(t,e,s){const r=t==="row"?"rowspan":"colspan",i=[];for(const o of this.areas){const l={...o},a=l[t],c=a+l[r]-1;if(s>0)a>=e?l[t]+=s:c>=e&&(l[r]+=s);else{const h=-s,u=Math.max(a,e),d=Math.min(c,e+h-1),p=Math.max(0,d-u+1);a>=e+h?l[t]-=h:a>=e&&(l[t]=e),l[r]-=p}l[r]>0&&(l.rowspan>1||l.colspan>1)&&i.push(l)}this.areas=i,this.reindex()}reindex(){this.index.clear();for(const t of this.areas)for(let e=t.row;e<t.row+t.rowspan;e++)for(let s=t.col;s<t.col+t.colspan;s++)this.index.set(e*1048576+s,t)}}const je={sortAsc:"Sort A → Z",sortDesc:"Sort Z → A",sortClear:"Clear sort",sortThenAsc:"Then sort A → Z",sortThenDesc:"Then sort Z → A",filterByCondition:"Filter by condition",filterByValue:"Filter by value",search:"Search",selectAll:"(Select all)",blanks:"(Blanks)",ok:"OK",cancel:"Cancel",clearFilter:"Clear filter",none:"None",contains:"Contains",notContains:"Does not contain",equals:"Is equal to",notEquals:"Is not equal to",greaterThan:"Greater than",greaterOrEqual:"Greater than or equal to",lessThan:"Less than",lessOrEqual:"Less than or equal to",isEmpty:"Is empty",isNotEmpty:"Is not empty",columnMenu:"Column menu",cut:"Cut",copy:"Copy",paste:"Paste",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",removeRow:"Delete row",removeRows:"Delete rows",insertColLeft:"Insert column left",insertColRight:"Insert column right",removeCol:"Delete column",removeCols:"Delete columns",mergeCells:"Merge cells",unmergeCells:"Unmerge cells",clearContents:"Clear contents",undo:"Undo",redo:"Redo",hideColumn:"Hide column",hideColumns:"Hide columns",showColumns:"Show hidden columns",cellAnnouncement:"{cell}: {value}",find:"Find",replace:"Replace",replaceAll:"Replace all",replaceWith:"Replace with",matchCase:"Match case",wholeCell:"Whole cell",lookInFormulas:"In formulas",noMatches:"No matches",matchCount:"{total} matches",replacedCount:"{count} replaced",next:"Next",previous:"Previous",close:"Close",formulaBar:"Cell content",pagerRange:"{from}–{to} of {total}",pageSize:"Rows per page",noRows:"No records",loading:"Loading…",loadError:"Could not load the data",dateFrom:"From",dateTo:"To",yes:"Yes",no:"No"},co={sortAsc:"A → Z sırala",sortDesc:"Z → A sırala",sortClear:"Sıralamayı kaldır",sortThenAsc:"Sonra A → Z sırala",sortThenDesc:"Sonra Z → A sırala",filterByCondition:"Koşula göre filtrele",filterByValue:"Değere göre filtrele",search:"Ara",selectAll:"(Tümünü seç)",blanks:"(Boş)",ok:"Tamam",cancel:"İptal",clearFilter:"Filtreyi temizle",none:"Yok",contains:"İçerir",notContains:"İçermez",equals:"Eşittir",notEquals:"Eşit değildir",greaterThan:"Büyüktür",greaterOrEqual:"Büyük veya eşittir",lessThan:"Küçüktür",lessOrEqual:"Küçük veya eşittir",isEmpty:"Boş",isNotEmpty:"Boş değil",columnMenu:"Sütun menüsü",cut:"Kes",copy:"Kopyala",paste:"Yapıştır",insertRowAbove:"Üste satır ekle",insertRowBelow:"Alta satır ekle",removeRow:"Satırı sil",removeRows:"Satırları sil",insertColLeft:"Sola sütun ekle",insertColRight:"Sağa sütun ekle",removeCol:"Sütunu sil",removeCols:"Sütunları sil",mergeCells:"Hücreleri birleştir",unmergeCells:"Birleştirmeyi kaldır",clearContents:"İçeriği temizle",undo:"Geri al",redo:"Yinele",hideColumn:"Sütunu gizle",hideColumns:"Sütunları gizle",showColumns:"Gizli sütunları göster",cellAnnouncement:"{cell}: {value}",find:"Bul",replace:"Değiştir",replaceAll:"Tümünü değiştir",replaceWith:"Yeni değer",matchCase:"Büyük/küçük harf",wholeCell:"Hücrenin tamamı",lookInFormulas:"Formüllerde",noMatches:"Sonuç yok",matchCount:"{total} sonuç",replacedCount:"{count} değiştirildi",next:"Sonraki",previous:"Önceki",close:"Kapat",formulaBar:"Hücre içeriği",pagerRange:"{from}–{to} / {total}",pageSize:"Sayfa başına satır",noRows:"Kayıt yok",loading:"Yükleniyor…",loadError:"Veri yüklenemedi",dateFrom:"Başlangıç",dateTo:"Bitiş",yes:"Evet",no:"Hayır"};class Re{constructor(t,e=0){v(this,"order");v(this,"hidden",new Set);v(this,"visible",[]);v(this,"inverse",new Int32Array(0));v(this,"sorted",!1);v(this,"identity",!0);this.pinned=e,this.order=Array.from({length:t},(s,r)=>r),this.rebuild()}get count(){return this.visible.length}get physicalCount(){return this.order.length}get pinnedCount(){return Math.min(this.pinned,this.order.length)}get isIdentity(){return this.identity}get isSorted(){return this.sorted}toPhysical(t){return this.visible[t]??t-this.visible.length+this.order.length}toVisual(t){return t<this.inverse.length?this.inverse[t]:-1}setPinned(t){this.pinned=t,this.rebuild()}sort(t){const e=this.order.filter(r=>r<this.pinned).sort((r,i)=>r-i),s=this.order.filter(r=>r>=this.pinned);s.sort(t??((r,i)=>r-i)),this.order=[...e,...s],this.rebuild()}setHidden(t){this.hidden=new Set([...t].filter(e=>e>=this.pinned)),this.rebuild()}insert(t,e,s=this.count){const r=a=>a>=t?a+e:a,i=this.visible[s];this.order=this.order.map(r),this.hidden=new Set([...this.hidden].map(r));const o=Array.from({length:e},(a,c)=>t+c),l=i===void 0?this.order.length:this.order.indexOf(r(i));this.order.splice(l,0,...o),this.rebuild()}remove(t,e){const s=i=>i>=t+e?i-e:i,r=i=>i>=t&&i<t+e;this.order=this.order.filter(i=>!r(i)).map(s),this.hidden=new Set([...this.hidden].filter(i=>!r(i)).map(s)),this.rebuild()}snapshot(){return{order:[...this.order],hidden:[...this.hidden]}}restore(t){this.order=[...t.order],this.hidden=new Set(t.hidden),this.rebuild()}reset(t){this.order=Array.from({length:t},(e,s)=>s),this.hidden.clear(),this.rebuild()}rebuild(){const t=this.order.filter(e=>e<this.pinned).sort((e,s)=>e-s);this.order=[...t,...this.order.filter(e=>e>=this.pinned)],this.visible=this.order.filter(e=>!this.hidden.has(e)),this.inverse=new Int32Array(this.order.length).fill(-1),this.visible.forEach((e,s)=>this.inverse[e]=s),this.sorted=!this.order.every((e,s)=>e===s),this.identity=!this.sorted&&this.hidden.size===0}}function ho(n,t){const e=n.toLocaleLowerCase(t);if(e.length===n.length)return{text:e,map:null};let s="";const r=[];for(let i=0;i<n.length;i++){const o=n[i].toLocaleLowerCase(t);s+=o;for(let l=0;l<o.length;l++)r.push(i)}return r.push(n.length),{text:s,map:r}}function Xs(n,t,e={},s){if(!t)return[];const r=e.matchCase?{text:n,map:null}:ho(n,s),i=e.matchCase?t:t.toLocaleLowerCase(s);if(e.wholeCell)return r.text===i?[[0,n.length]]:[];const o=[];for(let l=r.text.indexOf(i);l>=0;l=r.text.indexOf(i,l+i.length)){const a=l+i.length;o.push(r.map?[r.map[l],r.map[a]]:[l,a])}return o}function uo(n,t,e){let s="",r=0;for(const[i,o]of t)s+=n.slice(r,i)+e,r=o;return s+n.slice(r)}const fo=150;function po(n){const t=n.root.ownerDocument,e=n.messages,s=t.createElement("div");s.className="ct-menu ct-search",s.setAttribute("role","dialog"),s.setAttribute("aria-label",e.find);const r=(M,N)=>{const I=t.createElement("input");return I.type="text",I.value=N,I.placeholder=M,I.setAttribute("aria-label",M),I},i=(M,N,I)=>{const q=t.createElement("button");return q.type="button",q.className="ct-btn",q.textContent=M,q.title=N,q.setAttribute("aria-label",N),q.addEventListener("click",()=>{I(),R||a.focus()}),q},o=(...M)=>{const N=t.createElement("div");return N.className="ct-search-row",N.append(...M),N},l=(M,N)=>{const I=t.createElement("label"),q=t.createElement("input");return q.type="checkbox",q.checked=N,q.addEventListener("change",()=>k()),I.append(q,t.createTextNode(M)),[I,q]},a=r(e.find,n.query),c=r(e.replaceWith,""),h=t.createElement("span");h.className="ct-search-status",h.setAttribute("aria-live","polite");const[u,d]=l(e.matchCase,!!n.options.matchCase),[p,g]=l(e.wholeCell,!!n.options.wholeCell),[C,y]=l(e.lookInFormulas,n.options.lookIn==="formulas"),m=M=>h.textContent=a.value?M?e.matchCount.replace("{total}",String(M)):e.noMatches:"",f=({index:M,total:N})=>{N?h.textContent=`${M} / ${N}`:m(0)},x=()=>({matchCase:d.checked,wholeCell:g.checked,lookIn:y.checked?"formulas":"values"});let A=0;function k(){clearTimeout(A),A=0,m(n.onSearch(a.value,x()))}a.addEventListener("input",()=>{clearTimeout(A),A=setTimeout(k,fo)});const F=()=>{A&&k()},$=M=>{F(),a.value&&f(n.onNext(M))},L=()=>{F(),f(n.onReplace(c.value))},H=o(c,i(e.replace,e.replace,()=>L()),i(e.replaceAll,e.replaceAll,()=>{F();const M=n.onReplaceAll(c.value);h.textContent=e.replacedCount.replace("{count}",String(M))}));H.hidden=!0,s.append(o(a,h,i("↑",e.previous,()=>$(!0)),i("↓",e.next,()=>$(!1)),i("×",e.close,()=>E())),H,o(u,p,C)),s.addEventListener("keydown",M=>{M.key==="Escape"?(M.stopPropagation(),E()):M.key==="Enter"&&M.target===a?(M.preventDefault(),$(M.shiftKey)):M.key==="Enter"&&M.target===c&&(M.preventDefault(),L())}),t.body.append(s);const X=n.root.getBoundingClientRect(),_=s.offsetWidth||340;s.style.left=`${Math.max(8,X.right-_-20)}px`,s.style.top=`${X.top+30}px`,a.value&&k();let R=!1;function E(){R||(R=!0,clearTimeout(A),s.remove(),n.onClose())}const D=M=>{M&&n.replace&&(H.hidden=!1),a.focus(),a.select()};return D(n.replace),{close:E,focus:D}}const mo=`
5
+ --ct-bg: #fff;
6
+ --ct-fg: #1f2328;
7
+ --ct-muted: #57606a;
8
+ --ct-grid: #e1e4e8;
9
+ --ct-header-bg: #f6f8fa;
10
+ --ct-header-fg: #57606a;
11
+ --ct-header-hl: #dde7f8;
12
+ --ct-accent: #1a73e8;
13
+ --ct-range: rgba(26, 115, 232, 0.1);
14
+ --ct-error: #cf222e;
15
+ --ct-invalid-bg: #ffebe9;
16
+ --ct-readonly-fg: #6e7781;
17
+ --ct-shadow: rgba(31, 35, 40, .15);
18
+ --ct-match: #fff3b0;`,Ws=`
19
+ --ct-bg: #0d1117;
20
+ --ct-fg: #e6edf3;
21
+ --ct-muted: #8b949e;
22
+ --ct-grid: #30363d;
23
+ --ct-header-bg: #161b22;
24
+ --ct-header-fg: #8b949e;
25
+ --ct-header-hl: #1f3a5f;
26
+ --ct-accent: #4c8dff;
27
+ --ct-range: rgba(76, 141, 255, 0.16);
28
+ --ct-error: #ff7b72;
29
+ --ct-invalid-bg: #3d1d1f;
30
+ --ct-readonly-fg: #7d8590;
31
+ --ct-shadow: rgba(0, 0, 0, .5);
32
+ --ct-match: #5a4a00;`,go=`
33
+ .ct-root, .ct-menu, .ct-bar, .ct-pager {${mo}
34
+ }
35
+ @media (prefers-color-scheme: dark) {
36
+ .ct-root:not(.ct-light), .ct-menu, .ct-bar:not(.ct-light), .ct-pager:not(.ct-light) {${Ws}
37
+ }
38
+ }
39
+ .ct-root.ct-dark, .ct-bar.ct-dark, .ct-pager.ct-dark {${Ws}
40
+ }
41
+ .ct-root {
42
+ position: relative;
43
+ overflow: auto;
44
+ outline: none;
45
+ background: var(--ct-bg);
46
+ color: var(--ct-fg);
47
+ font: 13px/1.2 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
48
+ border: 1px solid var(--ct-grid);
49
+ box-sizing: border-box;
50
+ user-select: none;
51
+ }
52
+ .ct-canvas { position: relative; }
53
+ .ct-band { display: flex; }
54
+ .ct-band-top { position: sticky; top: 0; z-index: 3; }
55
+ .ct-pane { position: relative; flex: none; }
56
+ .ct-pane-corner, .ct-pane-left { position: sticky; left: 0; background: var(--ct-bg); }
57
+ .ct-pane-corner { z-index: 4; }
58
+ .ct-pane-left { z-index: 2; }
59
+ .ct-pane-top { background: var(--ct-bg); }
60
+ .ct-edge-r { box-shadow: 2px 0 3px -1px var(--ct-shadow); }
61
+ .ct-edge-b { box-shadow: 0 2px 3px -1px var(--ct-shadow); }
62
+ .ct-pane-corner.ct-edge-r.ct-edge-b { box-shadow: 2px 2px 3px -1px var(--ct-shadow); }
63
+
64
+ .ct-cell, .ct-header {
65
+ position: absolute; box-sizing: border-box; padding: 0 6px; overflow: hidden;
66
+ white-space: nowrap; text-overflow: ellipsis; display: flex; align-items: center;
67
+ border-right: 1px solid var(--ct-grid); border-bottom: 1px solid var(--ct-grid);
68
+ }
69
+ .ct-cell { background: var(--ct-bg); }
70
+ .ct-cell.ct-num, .ct-cell.ct-date { justify-content: flex-end; font-variant-numeric: tabular-nums; }
71
+ .ct-cell.ct-bool, .ct-cell.ct-check { justify-content: center; }
72
+ .ct-cell.ct-err { color: var(--ct-error); justify-content: center; }
73
+ .ct-cell.ct-readonly { color: var(--ct-readonly-fg); }
74
+ .ct-cell.ct-invalid { background: var(--ct-invalid-bg); box-shadow: inset 0 0 0 1px var(--ct-error); }
75
+ .ct-cell.ct-dd { padding-right: 18px; }
76
+ .ct-cell.ct-dd::after { content: "▾"; position: absolute; right: 5px; color: var(--ct-muted); font-size: 11px; }
77
+ .ct-cell.ct-b { font-weight: 700; }
78
+ .ct-cell.ct-i { font-style: italic; }
79
+ .ct-cell.ct-u { text-decoration: underline; }
80
+ .ct-cell.ct-s { text-decoration: line-through; }
81
+ .ct-cell.ct-u.ct-s { text-decoration: underline line-through; }
82
+ .ct-cell.ct-wrap { white-space: normal; overflow-wrap: anywhere; line-height: 1.25; }
83
+ .ct-cell.ct-al-l { justify-content: flex-start; }
84
+ .ct-cell.ct-al-c { justify-content: center; }
85
+ .ct-cell.ct-al-r { justify-content: flex-end; }
86
+ .ct-cell.ct-match { background: var(--ct-match); }
87
+ .ct-checkbox { font-size: 15px; cursor: pointer; line-height: 1; }
88
+
89
+ .ct-header { background: var(--ct-header-bg); color: var(--ct-header-fg); justify-content: center; font-size: 12px; cursor: default; }
90
+ .ct-header.ct-hl { background: var(--ct-header-hl); color: var(--ct-fg); font-weight: 600; }
91
+ .ct-colhead { gap: 3px; padding: 0 4px; }
92
+ .ct-label { overflow: hidden; text-overflow: ellipsis; }
93
+ .ct-sort { font-size: 9px; color: var(--ct-accent); }
94
+ .ct-sort:empty { display: none; }
95
+ .ct-menu-btn {
96
+ margin-left: auto; border: 0; background: transparent; color: var(--ct-muted); cursor: pointer;
97
+ font: inherit; font-size: 11px; padding: 1px 3px; border-radius: 3px; opacity: 0; flex: none;
98
+ }
99
+ .ct-colhead:hover .ct-menu-btn, .ct-filtered .ct-menu-btn { opacity: 1; }
100
+ .ct-menu-btn:hover { background: var(--ct-grid); }
101
+ .ct-filtered .ct-menu-btn { color: var(--ct-bg); background: var(--ct-accent); }
102
+ .ct-cornerhead { cursor: pointer; }
103
+ .ct-colhead.ct-gap-r { box-shadow: inset -3px 0 0 -1px var(--ct-accent); }
104
+ .ct-colhead.ct-gap-l { box-shadow: inset 3px 0 0 -1px var(--ct-accent); }
105
+ .ct-rresize { position: absolute; left: 0; bottom: 0; width: 100%; height: 5px; cursor: row-resize; z-index: 1; }
106
+ .ct-rresize:hover { background: var(--ct-accent); opacity: .5; }
107
+ .ct-drop { position: absolute; width: 3px; background: var(--ct-accent); z-index: 6; pointer-events: none; }
108
+ .ct-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
109
+ .ct-resize { position: absolute; top: 0; right: 0; width: 6px; height: 100%; cursor: col-resize; z-index: 1; }
110
+ .ct-resize:hover { background: var(--ct-accent); opacity: .5; }
111
+
112
+ .ct-range { position: absolute; pointer-events: none; background: var(--ct-range); border: 1px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
113
+ .ct-active { position: absolute; pointer-events: none; border: 2px solid var(--ct-accent); box-sizing: border-box; z-index: 1; }
114
+ .ct-fill-area { position: absolute; pointer-events: none; border: 1px dashed var(--ct-accent); box-sizing: border-box; z-index: 1; }
115
+ .ct-fill {
116
+ position: absolute; z-index: 2; background: var(--ct-accent); border: 1px solid var(--ct-bg);
117
+ box-sizing: border-box; cursor: crosshair;
118
+ }
119
+ /* Larger hit area than the visible square. Resize handles sit inside their header because headers clip overflow. */
120
+ .ct-fill::before { content: ""; position: absolute; inset: -4px; }
121
+
122
+ .ct-editor {
123
+ position: absolute; z-index: 5; box-sizing: border-box; margin: 0; padding: 3px 5px; resize: none; overflow: hidden;
124
+ border: 2px solid var(--ct-accent); outline: none; font: inherit; color: var(--ct-fg); background: var(--ct-bg);
125
+ white-space: pre; box-shadow: 0 2px 8px var(--ct-shadow);
126
+ }
127
+ .ct-editor.ct-idle { opacity: 0; pointer-events: none; box-shadow: none; z-index: 0; caret-color: transparent; }
128
+ .ct-dd-list {
129
+ position: absolute; z-index: 6; max-height: 220px; overflow: auto; background: var(--ct-bg);
130
+ border: 1px solid var(--ct-grid); box-shadow: 0 4px 12px var(--ct-shadow); padding: 2px 0;
131
+ }
132
+ .ct-dd-item { padding: 4px 8px; cursor: pointer; white-space: nowrap; }
133
+ .ct-dd-item:hover { background: var(--ct-range); }
134
+ .ct-dd-item.ct-on { background: var(--ct-accent); color: #fff; }
135
+
136
+ .ct-menu {
137
+ position: fixed; z-index: 1000; width: 240px; box-sizing: border-box; padding: 6px 0;
138
+ background: var(--ct-bg); color: var(--ct-fg); border: 1px solid var(--ct-grid); border-radius: 6px;
139
+ box-shadow: 0 8px 24px var(--ct-shadow); font: 13px/1.3 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
140
+ }
141
+ .ct-menu-section { padding: 4px 10px; border-bottom: 1px solid var(--ct-grid); display: flex; flex-direction: column; gap: 4px; }
142
+ .ct-menu-title { font-size: 11px; font-weight: 600; color: var(--ct-muted); text-transform: uppercase; letter-spacing: .03em; padding-top: 2px; }
143
+ .ct-menu-item { text-align: left; border: 0; background: transparent; color: inherit; font: inherit; padding: 4px 6px; border-radius: 4px; cursor: pointer; }
144
+ .ct-menu-item:hover { background: var(--ct-range); }
145
+ .ct-menu-item.ct-on { color: var(--ct-accent); font-weight: 600; }
146
+ .ct-menu select, .ct-menu input[type=text], .ct-menu input[type=search] {
147
+ font: inherit; padding: 4px 6px; border: 1px solid var(--ct-grid); border-radius: 4px; background: var(--ct-bg); color: inherit;
148
+ }
149
+ .ct-menu-list { max-height: 180px; overflow: auto; display: flex; flex-direction: column; }
150
+ .ct-menu-list label { display: flex; gap: 6px; align-items: center; padding: 2px 0; white-space: nowrap; cursor: pointer; }
151
+ .ct-menu-list label[hidden] { display: none; }
152
+ .ct-menu-footer { display: flex; gap: 6px; padding: 8px 10px 2px; align-items: center; }
153
+ .ct-menu-link { margin-right: auto; border: 0; background: transparent; color: var(--ct-accent); font: inherit; cursor: pointer; padding: 0; }
154
+ .ct-context { width: auto; min-width: 200px; padding: 4px; }
155
+ .ct-context .ct-menu-item { display: flex; justify-content: space-between; gap: 24px; width: 100%; padding: 5px 8px; }
156
+ .ct-context .ct-menu-item:focus { outline: none; background: var(--ct-range); }
157
+ .ct-context .ct-menu-item:disabled { opacity: .45; cursor: default; background: transparent; }
158
+ .ct-menu-hint { color: var(--ct-muted); font-size: 12px; }
159
+ .ct-menu-sep { height: 1px; background: var(--ct-grid); margin: 4px 2px; }
160
+ .ct-search { width: 360px; padding: 8px; display: flex; flex-direction: column; gap: 6px; }
161
+ .ct-search-row { display: flex; gap: 4px; align-items: center; }
162
+ .ct-search-row[hidden] { display: none; }
163
+ .ct-search-row input[type=text] { flex: 1; min-width: 0; }
164
+ .ct-search-row label { display: flex; gap: 4px; align-items: center; margin-right: 8px; font-size: 12px; white-space: nowrap; cursor: pointer; }
165
+ .ct-search-row .ct-btn { padding: 4px 8px; white-space: nowrap; }
166
+ .ct-search-status { font-size: 12px; color: var(--ct-muted); white-space: nowrap; }
167
+ .ct-bar {
168
+ display: flex; align-items: flex-start; box-sizing: border-box; background: var(--ct-bg); color: var(--ct-fg);
169
+ border: 1px solid var(--ct-grid); border-bottom: 0; font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
170
+ }
171
+ .ct-bar-address { flex: none; width: 72px; padding: 4px 6px; box-sizing: border-box; text-align: center; color: var(--ct-muted); border-right: 1px solid var(--ct-grid); }
172
+ .ct-bar-input {
173
+ flex: 1; min-width: 0; box-sizing: border-box; margin: 0; padding: 4px 6px; border: 0; outline: none; resize: none; overflow: auto;
174
+ font: inherit; font-family: ui-monospace, Consolas, monospace; color: inherit; background: transparent; white-space: pre-wrap;
175
+ }
176
+ .ct-pager {
177
+ display: flex; align-items: center; gap: 8px; box-sizing: border-box; padding: 4px 8px; background: var(--ct-bg); color: var(--ct-fg);
178
+ border: 1px solid var(--ct-grid); border-top: 0; font: 13px/1.4 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
179
+ }
180
+ .ct-pager-actions { display: flex; gap: 4px; margin-right: auto; }
181
+ .ct-pager select { font: inherit; padding: 2px 4px; border: 1px solid var(--ct-grid); border-radius: 4px; background: var(--ct-bg); color: inherit; }
182
+ .ct-pager .ct-btn:disabled { opacity: .45; cursor: default; }
183
+ .ct-root[aria-busy=true] .ct-pane { opacity: .6; }
184
+ .ct-status {
185
+ position: sticky; left: 0; display: flex; align-items: center; justify-content: center; box-sizing: border-box;
186
+ min-height: 80px; padding: 12px; color: var(--ct-muted);
187
+ }
188
+ .ct-status.ct-status-error { color: var(--ct-error); }
189
+ .ct-btn { font: inherit; padding: 4px 10px; border-radius: 4px; border: 1px solid var(--ct-grid); background: var(--ct-bg); color: inherit; cursor: pointer; }
190
+ .ct-btn.ct-primary { background: var(--ct-accent); border-color: var(--ct-accent); color: #fff; }
191
+ `;function wo(n){if(n.getElementById("ct-styles"))return;const t=n.createElement("style");t.id="ct-styles",t.textContent=go,n.head.appendChild(t)}function yo(n){return n.map(t=>t.map(e=>/[\t\n\r"]/.test(e)?`"${e.replace(/"/g,'""')}"`:e).join(" ")).join(`
192
+ `)}function vo(n){const t=[];let e=[],s="",r=0;const i=n.replace(/\r\n?/g,`
193
+ `).replace(/\n$/,"");for(;r<i.length;){const o=i[r];if(o==='"'&&s===""){const l=bo(i,r+1);if(l!==-1&&(l+1===i.length||i[l+1]===" "||i[l+1]===`
194
+ `)){s=i.slice(r+1,l).replace(/""/g,'"'),r=l+1;continue}}o===" "?(e.push(s),s=""):o===`
195
+ `?(e.push(s),t.push(e),e=[],s=""):s+=o,r++}return e.push(s),t.push(e),t}function bo(n,t){for(let e=t;e<n.length;e++)if(n[e]==='"'){if(n[e+1]==='"'){e++;continue}return e}return-1}const xo=26,Ao=50,qt=4,Co=5e4;class So{constructor(t,e={}){v(this,"root");v(this,"data",[]);v(this,"binding");v(this,"bindingPaused",!1);v(this,"rows");v(this,"cols");v(this,"mapper");v(this,"merges",new ao);v(this,"engine");v(this,"ownsEngine",!1);v(this,"sheet",0);v(this,"opts");v(this,"messages");v(this,"headerH");v(this,"rowHeaderW");v(this,"frozenRows");v(this,"frozenCols");v(this,"columnMeta",[]);v(this,"cellMeta",new Map);v(this,"labels");v(this,"filters",new Map);v(this,"sortKeys",[]);v(this,"invalid",new Map);v(this,"rowHeights",new Map);v(this,"rowsCustomized",!1);v(this,"hiddenCols",new Map);v(this,"announcer");v(this,"announceTimer",0);v(this,"canvas");v(this,"topBand");v(this,"bodyBand");v(this,"panes");v(this,"cornerHead");v(this,"input");v(this,"editing",!1);v(this,"editorEnterMode",!1);v(this,"dropdown");v(this,"closeMenu");v(this,"anchor",null);v(this,"selEnd",null);v(this,"dragging",null);v(this,"moveDrop",null);v(this,"fillTarget",null);v(this,"hooks",new Map);v(this,"undoStack",[]);v(this,"redoStack",[]);v(this,"clipboard",null);v(this,"searchPanel");v(this,"searchQuery","");v(this,"searchOptions",{});v(this,"searchHits",new Set);v(this,"bar");v(this,"server");v(this,"frame",0);v(this,"cleanup",[]);v(this,"onValuesUpdated",t=>{for(const{address:e}of t)(e.sheet??0)!==this.sheet||e.row>=this.data.length||(ge(this.metaAt(e.row,e.col))&&this.revalidate(e.row,e.col),this.bindingPaused||this.writeComputed(e.row,e.col,!0));this.scheduleRender()});v(this,"onInput",()=>{if(!this.editing){this.openEditor(this.input.value);return}this.autoSizeInput(),this.dropdown&&this.filterDropdown(this.input.value),this.bar&&!this.barFocused()&&(this.bar.input.value=this.input.value)});v(this,"onEditorKey",t=>{if(!this.editing)return;t.stopPropagation();const e=this.dropdown,s=(r,i)=>{t.preventDefault(),this.commitAndMove(r,i)};if(e&&e.items.length&&(t.key==="ArrowDown"||t.key==="ArrowUp")){t.preventDefault(),e.active=Math.max(0,Math.min(e.items.length-1,e.active+(t.key==="ArrowDown"?1:-1))),this.highlightDropdown();return}switch(t.key){case"Enter":if(t.altKey){t.preventDefault(),this.input.setRangeText(`
196
+ `,this.input.selectionStart,this.input.selectionEnd,"end");return}return e&&e.active>=0&&(this.input.value=e.items[e.active]),s(t.shiftKey?-1:1,0);case"Tab":return s(0,t.shiftKey?-1:1);case"Escape":t.preventDefault(),this.closeEditor(!1);return;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":if(this.editorEnterMode){const[r,i]=Fe[t.key];return s(r,i)}}});v(this,"dropLine");var c;this.opts=e,this.messages={...je,...e.language},this.headerH=e.colHeaders===!1?0:xo,this.rowHeaderW=e.rowHeaders===!1?0:Ao,this.labels=Array.isArray(e.colHeaders)?[...e.colHeaders]:void 0,this.columnMeta=[...e.columns??[]];const s=t.ownerDocument;wo(s),this.root=s.createElement("div"),this.root.className="ct-root",this.root.setAttribute("role","grid"),this.root.setAttribute("aria-multiselectable","true"),e.theme==="light"&&this.root.classList.add("ct-light"),e.theme==="dark"&&this.root.classList.add("ct-dark"),this.root.style.height=typeof e.height=="number"?`${e.height}px`:e.height??"400px",this.buildDom(),t.appendChild(this.root),e.formulaBar&&this.buildFormulaBar(),e.dataMode==="server"&&this.buildServerMode();const r=e.formulas instanceof ut?e.formulas:void 0,i=r&&e.sheetName!==void 0?r.getSheetId(e.sheetName):r?0:void 0,o=e.data??(r&&i!==void 0?r.getSheetSerialized(i):[]);this.data=this.normalize(this.bind(o)),this.frozenRows=Math.min(e.fixedRowsTop??0,this.data.length),this.frozenCols=Math.min(e.fixedColumnsStart??0,this.countCols()),this.mapper=new Re(this.data.length,this.frozenRows),this.rows=new Ft(this.data.length,e.rowHeight??24);const l=typeof e.colWidths=="number"?e.colWidths:100,a=Array.isArray(e.colWidths)?e.colWidths:this.columnMeta.some(h=>h==null?void 0:h.width)?Array.from({length:this.countCols()},(h,u)=>{var d;return((d=this.columnMeta[u])==null?void 0:d.width)??l}):e.colWidths;this.cols=new Ft(this.countCols(),100,a),e.mergeCells&&this.merges.set(e.mergeCells.filter(h=>this.mergeAllowed(h)));for(const h of e.hiddenColumns??[])this.hiddenCols.set(h,this.cols.size(h));for(const h of this.hiddenCols.keys())this.cols.setSize(h,0);r?(this.engine=r,this.sheet=i??r.addSheet(e.sheetName),(e.data||i===void 0)&&r.setSheetContent(this.data,this.sheet)):(e.formulas===!0||e.formulas===void 0&&!this.server)&&(this.engine=ut.buildFromArray(this.data,e.sheetName),this.ownsEngine=!0),(c=this.engine)==null||c.on("valuesUpdated",this.onValuesUpdated),this.syncBoundObjects(),e.columnLayout&&this.applyColumnLayout(e.columnLayout),this.validateAll(),this.bindEvents(),this.render()}getQuery(){return this.server&&structuredClone(this.server.query)}setQuery(t,e="filter"){const s=this.server;s&&(s.query={...s.query,...t,page:e==="page"?t.page??s.query.page:1},this.render(),this.run("afterQueryChange",this.getQuery(),e))}setPageRows(t,e){var o;const s=this.server;if(!s)return this.loadData(t);const r=this.anchor?this.rowKeyAt(this.mapper.toPhysical(this.anchor.row)):void 0,i=((o=this.anchor)==null?void 0:o.col)??0;if(this.data=this.normalize(this.bind(t)),this.mapper=new Re(this.data.length,Math.min(this.frozenRows,this.data.length)),this.syncRows(),this.cols.resize(this.countCols()),this.cellMeta.clear(),this.rowHeights.clear(),this.rowsCustomized=!1,this.syncRows(),this.undoStack=[],this.redoStack=[],this.engine&&(this.bindingPaused=!0,this.engine.setSheetContent(this.data,this.sheet),this.bindingPaused=!1),e!==void 0&&(s.total=e),r!==void 0){const l=this.data.findIndex((a,c)=>this.rowKeyAt(c)===r);l>=0&&(this.anchor=this.selEnd={row:l,col:i})}this.clampSelection(),this.validateAll(),this.render()}rowKeyAt(t){var r;const e=this.opts.rowKey;if(e===void 0)return;const s=((r=this.binding)==null?void 0:r.objects[t])??this.data[t];return typeof e=="function"?e(s):s==null?void 0:s[e]}getColumnId(t){var e,s,r;return((e=this.columnMeta[t])==null?void 0:e.id)??((s=this.columnMeta[t])==null?void 0:s.data)??((r=this.binding)==null?void 0:r.fields[t])}colOfId(t){for(let e=0;e<this.countCols();e++)if(this.getColumnId(e)===t)return e;return-1}buildServerMode(){var r;const t=this.opts,e=t.pageSizes??Yr,s={query:Kr(t.query,e),total:t.totalCount??0};this.server=s,t.pager!==!1&&(s.pager=new Gr(this.root.ownerDocument,this.messages,e,i=>this.setQuery({page:s.query.page+i},"page"),i=>this.setQuery({pageSize:i},"pageSize")),(t.theme==="light"||t.theme==="dark")&&s.pager.el.classList.add(`ct-${t.theme}`),(r=t.pagerActions)==null||r.call(t,s.pager.actions),this.root.after(s.pager.el))}renderServerState(){var i,o;const t=this.server;if(!t)return;const e=this.opts;(i=t.pager)==null||i.update(t.query,t.total),this.root.setAttribute("aria-busy",String(!!e.loading));const s=!this.data.length,r=e.loadError?"error":s?e.loading?"loading":"empty":null;if(!r){(o=t.status)==null||o.remove(),t.status=void 0;return}t.status||(t.status=this.el("ct-status",this.root)),t.status.nextSibling!==this.canvas&&this.root.insertBefore(t.status,this.canvas),t.status.dataset.state=r,t.status.classList.toggle("ct-status-error",r==="error"),t.status.setAttribute("role",r==="error"?"alert":"status"),t.status.textContent="",e.renderStatus?e.renderStatus(t.status,r):r==="error"?t.status.textContent=typeof e.loadError=="string"?e.loadError:this.messages.loadError:t.status.textContent=r==="empty"?this.messages.noRows:this.messages.loading}countRows(){return this.mapper.count}countSourceRows(){return this.data.length}countCols(){var t;return((t=this.data[0])==null?void 0:t.length)??(this.opts.dataMode==="server"?this.columnMeta.length:0)}getEngine(){return this.engine}getSheetId(){return this.sheet}getSheetName(){var t;return(t=this.engine)==null?void 0:t.getSheetName(this.sheet)}toPhysicalRow(t){return this.mapper.toPhysical(t)}toVisualRow(t){return this.mapper.toVisual(t)}getDataAtCell(t,e){return this.valueAt(this.mapper.toPhysical(t),e)}getSourceDataAtCell(t,e){return this.rawAt(this.mapper.toPhysical(t),e)}getData(){return Array.from({length:this.countRows()},(t,e)=>Array.from({length:this.countCols()},(s,r)=>this.getDataAtCell(e,r)))}getSourceData(){return this.data.map((t,e)=>t.map((s,r)=>this.rawAt(e,r)))}getBoundRows(){return this.data.map((t,e)=>t.map((s,r)=>this.boundValueAt(e,r)))}getSourceObjects(){var t;return(t=this.binding)==null?void 0:t.objects}getSourceDataAtRow(t){const e=this.mapper.toPhysical(t);return this.binding?this.binding.objects[e]:this.getSourceData()[e]}propToCol(t){var e;return((e=this.binding)==null?void 0:e.fields.indexOf(t))??-1}colToProp(t){var e;return(e=this.binding)==null?void 0:e.fields[t]}setDataAtCell(t,e,s,r){const i=typeof t=="number"?[[t,e,s]]:t,o=(typeof t=="number"?r:e)??"api";this.applyChanges(i.map(([l,a,c])=>this.change(this.mapper.toPhysical(l),a,c)),o)}loadData(t){var e;if(this.server)return this.setPageRows(t);this.data=this.normalize(this.bind(t)),this.frozenRows=Math.min(this.frozenRows,this.data.length),this.mapper=new Re(this.data.length,this.frozenRows),this.syncRows(),this.cols.resize(this.countCols()),this.filters.clear(),this.sortKeys=[],this.cellMeta.clear(),this.rowHeights.clear(),this.bindingPaused=!0,(e=this.engine)==null||e.setSheetContent(this.data,this.sheet),this.bindingPaused=!1,this.syncBoundObjects(),this.undoStack=[],this.redoStack=[],this.anchor=this.selEnd=null,this.validateAll(),this.render()}loadSheet(t){var r,i,o,l,a;this.merges.set([]),this.hiddenCols.clear(),this.loadData(t.data),this.frozenRows=Math.min(((r=t.frozen)==null?void 0:r.rows)??0,this.data.length),this.frozenCols=Math.min(((i=t.frozen)==null?void 0:i.cols)??0,this.countCols()),this.mapper.setPinned(this.frozenRows);const e=this.countCols();this.cols=new Ft(e,this.cols.defaultSize,Array.from({length:e},(c,h)=>{var u;return((u=t.colWidths)==null?void 0:u[h])??this.cols.defaultSize}));for(const c of t.hiddenColumns)this.hiddenCols.set(c,this.cols.size(c)),this.cols.setSize(c,0);(o=t.rowHeights)==null||o.forEach((c,h)=>{h<this.data.length&&this.rowHeights.set(h,c)}),this.rowsCustomized=this.rowHeights.size>0,this.syncRows();const s=new Map;for(let c=0;c<this.data.length;c++)for(let h=0;h<e;h++){const u=t.format(c,h);if(!u)continue;let d=s.get(u);if(d||s.set(u,d=ji(u)),d.type==="date"&&typeof((a=(l=t.values)==null?void 0:l[c])==null?void 0:a[h])=="string"){const{type:p,dateFormat:g,...C}=d;d=C}this.cellMeta.set(O(c,h),d)}this.merges.set((t.merges??[]).filter(c=>this.mergeAllowed(c))),this.validateAll(),this.render()}async importXLSX(t,e={}){var o;const s=await jn(t,e),{sheet:r=0}=e,i=typeof r=="number"?s.sheets[r]:s.sheets.find(l=>l.name===r);if(!i)throw new Error(`Sheet not found: ${r}`);for(const{name:l,expression:a}of s.names)(o=this.engine)!=null&&o.isItPossibleToAddNamedExpression(l)&&this.engine.addNamedExpression(l,a);return this.loadSheet(i),i}getCellMeta(t,e){return this.metaAt(this.mapper.toPhysical(t),e)}setCellMeta(t,e,s){const r=this.mapper.toPhysical(t),i=O(r,e);this.cellMeta.set(i,{...this.cellMeta.get(i),...s}),this.revalidate(r,e),this.render()}updateSettings(t){this.opts={...this.opts,...t},this.server&&(t.query&&(this.server.query={...this.server.query,...t.query}),t.totalCount!==void 0&&(this.server.total=t.totalCount)),t.language&&(this.messages={...je,...t.language}),t.columns&&(this.columnMeta=[...t.columns]),t.colHeaders!==void 0&&(this.labels=Array.isArray(t.colHeaders)?[...t.colHeaders]:void 0),(t.columnSorting!==void 0||t.filters!==void 0)&&this.resetHeaders(),(t.fixedRowsTop!==void 0||t.fixedColumnsStart!==void 0)&&(this.frozenRows=Math.min(t.fixedRowsTop??this.frozenRows,this.data.length),this.frozenCols=Math.min(t.fixedColumnsStart??this.frozenCols,this.countCols()),this.mapper.setPinned(this.frozenRows),this.syncRows(),this.merges.set(this.merges.list.filter(e=>this.mergeAllowed(e)))),t.mergeCells&&this.merges.set(t.mergeCells.filter(e=>this.mergeAllowed(e))),t.columns&&this.validateAll(),this.render()}selectCell(t,e,s=t,r=e){const i=h=>Math.max(0,Math.min(h,this.countRows()-1)),o=h=>Math.max(0,Math.min(h,this.countCols()-1));let l={row:i(t),col:o(e)},a={row:i(s),col:o(r)};const c=this.mergeAt(l.row,l.col);c&&t===s&&e===r&&(l={row:c.row,col:c.col},a={...l}),this.anchor=l,this.selEnd=a,this.scrollIntoView(this.selEnd),this.render(),this.announce(),this.run("afterSelection",l.row,l.col,a.row,a.col)}announce(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,s=this.mapper.toPhysical(t),r=this.messages.cellAnnouncement.replace("{cell}",$e({row:s,col:e})).replace("{value}",this.displayText(s,e)||"—");this.input.setAttribute("aria-label",r),clearTimeout(this.announceTimer),this.announceTimer=setTimeout(()=>this.announcer.textContent=r,120)}getSelected(){if(!(!this.anchor||!this.selEnd))return[[this.anchor.row,this.anchor.col,this.selEnd.row,this.selEnd.col]]}getSelectedRange(){if(!this.anchor||!this.selEnd)return;const t=Ks(this.anchor,this.selEnd);return this.mergesActive()?this.merges.expand(t):t}focus(){!this.anchor&&this.countRows()&&this.countCols()&&this.selectCell(0,0),this.focusInput()}deselectCell(){this.anchor=this.selEnd=null,this.render()}setCellStyle(t,e){const s=[];for(let r=t.start.row;r<=t.end.row;r++){const i=this.mapper.toPhysical(r);for(let o=t.start.col;o<=t.end.col;o++){const l=O(i,o),a=this.cellMeta.get(l),c={...a};e?c.style={...a==null?void 0:a.style,...e}:delete c.style,s.push({key:l,before:a,after:Object.keys(c).length?c:void 0})}}this.applyMeta(s,"after"),this.undoStack.push({kind:"meta",changes:s}),this.redoStack=[],this.render(),this.run("afterStyle",t,e)}getCellStyle(t,e){const s=this.mapper.toPhysical(t);return{...this.metaAt(s,e).style,...this.conditionalStyle(s,e,this.valueAt(s,e))}}toggleCellStyle(t){const e=this.getSelectedRange();if(!e||this.opts.readOnly)return;let s=!0;for(let r=e.start.row;r<=e.end.row&&s;r++)for(let i=e.start.col;i<=e.end.col&&s;i++)s=!!this.getCellStyle(r,i)[t];this.setCellStyle(e,{[t]:!s})}setRowHeight(t,e){const s=Math.max(12,Math.round(e));this.rowHeights.set(this.mapper.toPhysical(t),s),this.rowsCustomized=!0,this.rows.setSize(t,s),this.render()}getRowHeight(t){return this.rows.size(t)}getColumnLayout(){const t=[];for(let e=0;e<this.countCols();e++){const s=this.getColumnId(e);if(s===void 0)continue;const r=this.hiddenCols.has(e);t.push({id:s,width:r?this.hiddenCols.get(e):this.cols.size(e),hidden:r})}return{columns:t}}setColumnLayout(t){this.applyColumnLayout(t)&&(this.undoStack=[],this.redoStack=[]),this.validateAll(),this.render()}applyColumnLayout(t){let e=!1,s=0;for(const{id:r,width:i,hidden:o}of t.columns){const l=this.colOfId(r);if(l<0)continue;l!==s&&this.canMoveColumns(l,1,s)&&(this.relocateColumns(l,1,s,[]),e=!0);const a=this.colOfId(r);s=a+1,o?(this.hiddenCols.set(a,i),this.cols.setSize(a,0)):(this.hiddenCols.delete(a),this.cols.setSize(a,Math.max(24,i)))}return e}layoutChanged(){var t;(t=this.hooks.get("afterColumnLayout"))!=null&&t.size&&this.run("afterColumnLayout",this.getColumnLayout())}hideColumns(t){for(const e of t)e<0||e>=this.countCols()||this.hiddenCols.has(e)||(this.hiddenCols.set(e,this.cols.size(e)),this.cols.setSize(e,0));this.anchor&&this.hiddenCols.has(this.anchor.col)&&this.moveActive(0,0,!1),this.render(),this.layoutChanged()}showColumns(t){for(const e of t??[...this.hiddenCols.keys()]){const s=this.hiddenCols.get(e);s!==void 0&&(this.hiddenCols.delete(e),this.cols.setSize(e,s||this.cols.defaultSize))}this.render(),this.layoutChanged()}isColumnHidden(t){return this.hiddenCols.has(t)}getHiddenColumns(){return[...this.hiddenCols.keys()].sort((t,e)=>t-e)}toExportSheet(){const t=this.getSourceData(),e=t.map((l,a)=>l.map((c,h)=>this.valueAt(a,h))),s=this.opts.locale,r=(l,a)=>{var p,g,C;const c=this.metaAt(l,a),h={...c.style,...this.conditionalStyle(l,a,((p=e[l])==null?void 0:p[a])??null)},u={},d=Nn(c,s);return d&&(u.numberFormat=d),h.bold&&(u.bold=!0),h.italic&&(u.italic=!0),h.underline&&(u.underline=!0),h.strike&&(u.strike=!0),(g=h.color)!=null&&g.startsWith("#")&&(u.color=h.color),(C=h.background)!=null&&C.startsWith("#")&&(u.background=h.background),h.align&&(u.align=h.align),h.wrap&&(u.wrap=!0),Object.keys(u).length?u:void 0},i=this.rowHeights.size?Array.from({length:t.length},(l,a)=>this.rowHeights.get(a)??this.rows.defaultSize):void 0,o={name:this.getSheetName()??"Sheet1",data:t,values:e,colWidths:Array.from({length:this.countCols()},(l,a)=>this.cols.size(a)),rowHeights:i,frozen:{rows:this.frozenRows,cols:this.frozenCols},merges:this.mapper.isIdentity?this.getMergedCells():[],format:r,text:(l,a)=>{var c;return this.displayText(l,a,((c=e[l])==null?void 0:c[a])??null)}};return this.opts.filters&&this.frozenRows>0&&(o.autoFilter={row:this.frozenRows-1,col:0,rows:t.length-this.frozenRows+1,cols:this.countCols()}),o}exportCSV(t={}){const e=Eo(this.opts.locale);return Ln(this.toExportSheet(),{delimiter:e?";":",",decimalSeparator:e?",":".",locale:this.opts.locale,...t})}downloadCSV(t="data.csv",e={}){He(this.exportCSV(e),t,zn)}async downloadXLSX(t="data.xlsx",e=[]){const s=await Xn([this,...e].map(r=>r.toExportSheet()));He(s,t,Hn)}sort(t,e){if(this.server)return this.sortBy(e?[{col:t,order:e}]:[]);this.applySort(e?[{col:t,order:e}]:[]),this.run("afterColumnSort",t,e)}sortBy(t){if(this.server){const e=t.flatMap(({col:s,order:r})=>{var o;const i=this.getColumnId(s);return i!==void 0&&((o=this.columnMeta[s])!=null&&o.sortable)?[{field:i,desc:r==="desc"}]:[]});return this.setQuery({sort:e},"sort")}this.applySort(t)}applySort(t){if(t.length){const e=t.map(({col:s,order:r})=>({order:r,values:Array.from({length:this.data.length},(i,o)=>this.valueAt(o,s))}));this.mapper.sort((s,r)=>{for(const{values:i,order:o}of e){const l=lo(i[s],i[r],o,this.opts.locale);if(l)return l}return 0})}else this.mapper.sort(null);this.sortKeys=t.map(e=>({...e})),this.afterRowMapping(),this.run("afterSort",this.getSortKeys())}getSortState(){return this.getSortKeys()[0]??null}getSortKeys(){return this.server?this.server.query.sort.flatMap(({field:t,desc:e})=>{const s=this.colOfId(t);return s<0?[]:[{col:s,order:e?"desc":"asc"}]}):this.sortKeys.map(t=>({...t}))}setServerFilter(t,e){const s=this.server;if(!s)return;const r={...s.query.filters};e?r[t]=e:delete r[t],this.setQuery({filters:r},"filter")}setFilter(t,e){this.server||(e?this.filters.set(t,e):this.filters.delete(t),this.applyFilters())}clearFilters(){this.filters.clear(),this.applyFilters()}getFilters(){return new Map(this.filters)}applyFilters(){if(this.server)return;const t=[];if(this.filters.size){const e=[...this.filters];for(let s=this.mapper.pinnedCount;s<this.data.length;s++)this.passes(s,e)||t.push(s)}this.mapper.setHidden(t),this.afterRowMapping(),this.run("afterFilter",this.getFilters())}findCells(t,e={}){const s=[];if(!t)return s;for(let r=0;r<this.countRows();r++){const i=this.mapper.toPhysical(r);for(let o=0;o<this.countCols();o++){if(this.hiddenCols.has(o)||this.metaAt(i,o).type==="checkbox")continue;const l=this.mergeAt(r,o);l&&(l.row!==r||l.col!==o)||Xs(this.searchText(i,o,e),t,e,this.opts.locale).length&&s.push({row:r,col:o})}}return s}findNext(t,e={},s=!1){const r=this.findCells(t,e),i=r[this.nextHit(r,s)];return i&&this.selectCell(i.row,i.col),i??null}replaceNext(t,e,s={}){return this.anchor&&this.replaceIn([this.anchor],t,e,s),this.findNext(t,s)}replaceAll(t,e,s={}){return this.replaceIn(this.findCells(t,s),t,e,s)}openSearch(t=!1){if(this.searchPanel)return this.searchPanel.focus(t);const e=t&&!this.opts.readOnly;this.searchPanel=po({root:this.root,messages:this.messages,query:this.searchQuery,options:this.searchOptions,replace:e,onSearch:(s,r)=>(this.searchQuery=s,this.searchOptions=r,this.highlightHits().length),onNext:s=>this.stepSearch(s),onReplace:s=>(this.anchor&&this.replaceIn([this.anchor],this.searchQuery,s,this.searchOptions),this.stepSearch(!1)),onReplaceAll:s=>{const r=this.replaceAll(this.searchQuery,s,this.searchOptions);return this.highlightHits(),r},onClose:()=>{this.searchPanel=void 0,this.searchHits.clear(),this.render(),this.focusInput()}})}closeSearch(){var t;(t=this.searchPanel)==null||t.close()}searchText(t,e,s){return s.lookIn==="formulas"?jt(this.rawAt(t,e),this.metaAt(t,e),this.opts.locale):this.displayText(t,e)}nextHit(t,e){const s=this.anchor??{row:-1,col:-1},r=o=>o.row>s.row||o.row===s.row&&o.col>s.col,i=o=>o.row<s.row||o.row===s.row&&o.col<s.col;if(!e)return Math.max(0,t.findIndex(r));for(let o=t.length-1;o>=0;o--)if(i(t[o]))return o;return t.length-1}highlightHits(){const t=this.findCells(this.searchQuery,this.searchOptions);return this.searchHits=new Set(t.map(e=>O(this.mapper.toPhysical(e.row),e.col))),this.render(),t}stepSearch(t){const e=this.highlightHits(),s=this.nextHit(e,t);return e[s]&&this.selectCell(e[s].row,e[s].col),{index:s+1,total:e.length}}replaceIn(t,e,s,r){const i=[];for(const{row:o,col:l}of t){const a=this.mapper.toPhysical(o),c=this.rawAt(a,l);if(V(c)&&r.lookIn!=="formulas"||this.isReadOnly(a,l))continue;const h=this.metaAt(a,l),u=jt(c,h,this.opts.locale),d=Xs(u,e,r,this.opts.locale);d.length&&i.push(this.change(a,l,me(uo(u,d,s),h)))}return this.applyChanges(i,"replace"),i.length}mergeCells(t,e,s,r){const i={row:t,col:e,rowspan:s,colspan:r};return!this.mergeAllowed(i)||!this.merges.add(i)?!1:(this.render(),!0)}unmergeCells(t,e){const s=this.merges.removeAt(t,e);return s&&this.render(),s}getMergedCells(){return this.merges.list.map(t=>({...t}))}alter(t,e,s=1){const r=this.getSelectedRange(),i=t.includes("row");if(i&&this.server)return;const o=t.startsWith("remove"),l=t==="insert_row_below"||t==="insert_col_end",a=i?this.countRows():this.countCols();let c;if(e!==void 0?c=l?e+1:e:i?c=l?((r==null?void 0:r.end.row)??a-1)+1:(r==null?void 0:r.start.row)??0:c=l?((r==null?void 0:r.end.col)??a-1)+1:(r==null?void 0:r.start.col)??0,c=Math.max(0,Math.min(c,a)),o&&(s=Math.min(s,a-c)),s<=0)return;const h=this.snapshot(),u=[];i?this.alterRows(c,s,o,u):this.alterCols(c,s,o,u),this.undoStack.push({kind:"structure",state:h,ops:u}),this.redoStack=[],this.validateAll(),this.clampSelection(),this.render(),this.run("afterAlter",t,c,s),i||this.layoutChanged()}moveColumns(t,e,s){if(!this.canMoveColumns(t,e,s))return!1;const r=this.snapshot(),i=[];return this.relocateColumns(t,e,s,i),this.undoStack.push({kind:"structure",state:r,ops:i}),this.redoStack=[],this.validateAll(),this.render(),this.run("afterColumnMove",t,e,s),this.layoutChanged(),!0}relocateColumns(t,e,s,r){const i=this.countCols(),o=c=>js(c,t,e,s),l=c=>{const h=new Array(c.length);return c.forEach((u,d)=>h[o(d)]=u),h};this.data=this.data.map(c=>l(c)),this.binding&&(this.binding.fields=l(this.binding.fields.length<i?[...this.binding.fields,...Array(i-this.binding.fields.length)]:this.binding.fields));const a=l(Array.from({length:i},(c,h)=>this.cols.size(h)));this.cols=new Ft(i,this.cols.defaultSize,a),this.columnMeta.length&&(this.columnMeta=l([...this.columnMeta,...Array(Math.max(0,i-this.columnMeta.length))])),this.labels&&(this.labels=l([...this.labels,...Array(Math.max(0,i-this.labels.length)).fill("")])),this.filters=new Map([...this.filters].map(([c,h])=>[o(c),h])),this.sortKeys=this.sortKeys.map(c=>({...c,col:o(c.col)})),this.hiddenCols=Dt(this.hiddenCols,o),this.cellMeta=Dt(this.cellMeta,c=>c-c%16384+o(c%16384)),this.merges.set(this.merges.list.map(c=>({...c,col:o(c.col)}))),this.applyEngineOp(Pt(r,{axis:"col",index:t,count:e,remove:!1,target:s})),this.anchor&&this.selEnd&&(this.anchor={...this.anchor,col:o(this.anchor.col)},this.selEnd={...this.selEnd,col:o(this.selEnd.col)})}canMoveColumns(t,e,s){const r=this.countCols();if(e<=0||t<0||t+e>r||s<0||s>r||s>=t&&s<=t+e)return!1;const i=o=>js(o,t,e,s);return this.merges.list.every(o=>{for(let l=1;l<o.colspan;l++)if(i(o.col+l)!==i(o.col)+l)return!1;return!0})}undo(){this.replay(this.undoStack,this.redoStack,"undo")}redo(){this.replay(this.redoStack,this.undoStack,"redo")}isUndoAvailable(){return this.undoStack.length>0}isRedoAvailable(){return this.redoStack.length>0}setColWidth(t,e){this.cols.setSize(t,Math.max(24,e)),this.render()}getColWidth(t){return this.cols.size(t)}addHook(t,e){let s=this.hooks.get(t);s||this.hooks.set(t,s=new Set),s.add(e)}removeHook(t,e){var s;(s=this.hooks.get(t))==null||s.delete(e)}getCellError(t,e){return this.invalid.get(O(this.mapper.toPhysical(t),e))}openContextMenu(t,e){var o;const s=this.getSelectedRange();if(!s||!this.opts.contextMenu)return;if((o=this.closeMenu)==null||o.call(this),t===void 0||e===void 0){const l=this.input.getBoundingClientRect();t=l.left+l.width/2,e=l.bottom}const r=this.contextMenuEntries(s),i=typeof this.opts.contextMenu=="function"?this.opts.contextMenu(r,this):r;this.closeMenu=io(this.root.ownerDocument,i,t,e,()=>{this.closeMenu=void 0,this.focusInput()})}contextMenuEntries(t){var u;const e=this.messages,s=!!this.opts.readOnly,r=t.end.row-t.start.row+1,i=t.end.col-t.start.col+1,o=this.mergeAt(t.start.row,t.start.col),l=!!o&&r===o.rowspan&&i===o.colspan,a=(u=this.root.ownerDocument.defaultView)==null?void 0:u.navigator.clipboard,c=this.mergeAllowed({row:t.start.row,col:t.start.col,rowspan:r,colspan:i}),h=this.server?[]:[{key:"row_above",name:e.insertRowAbove,disabled:s,run:()=>this.alter("insert_row_above",t.start.row,r)},{key:"row_below",name:e.insertRowBelow,disabled:s,run:()=>this.alter("insert_row_below",t.end.row,r)},{key:"remove_row",name:r>1?e.removeRows:e.removeRow,disabled:s,run:()=>this.alter("remove_row",t.start.row,r)}];return[{key:"cut",name:e.cut,hint:"Ctrl+X",disabled:s,run:()=>this.writeClipboard(this.copy(!0))},{key:"copy",name:e.copy,hint:"Ctrl+C",run:()=>this.writeClipboard(this.copy())},{key:"paste",name:e.paste,hint:"Ctrl+V",disabled:s||!(a!=null&&a.readText)&&!this.clipboard,run:()=>{const d=()=>this.clipboard&&this.paste(this.clipboard.text);a!=null&&a.readText?a.readText().then(p=>p?this.paste(p):d(),d):d()}},"---",...h,...h.length?["---"]:[],{key:"col_left",name:e.insertColLeft,disabled:s,run:()=>this.alter("insert_col_start",t.start.col,i)},{key:"col_right",name:e.insertColRight,disabled:s,run:()=>this.alter("insert_col_end",t.end.col,i)},{key:"remove_col",name:i>1?e.removeCols:e.removeCol,disabled:s,run:()=>this.alter("remove_col",t.start.col,i)},{key:"hide_col",name:i>1?e.hideColumns:e.hideColumn,disabled:i>=this.countCols()-this.hiddenCols.size,run:()=>this.hideColumns(Array.from({length:i},(d,p)=>t.start.col+p))},...this.hiddenCols.size?[{key:"show_cols",name:e.showColumns,run:()=>this.showColumns()}]:[],"---",l?{key:"unmerge",name:e.unmergeCells,disabled:s,run:()=>this.unmergeCells(t.start.row,t.start.col)}:{key:"merge",name:e.mergeCells,disabled:s||r===1&&i===1||!c,run:()=>this.mergeCells(t.start.row,t.start.col,r,i)},{key:"clear",name:e.clearContents,hint:"Del",disabled:s,run:()=>this.clearRange(t,"clear")},"---",{key:"undo",name:e.undo,hint:"Ctrl+Z",disabled:!this.isUndoAvailable(),run:()=>this.undo()},{key:"redo",name:e.redo,hint:"Ctrl+Y",disabled:!this.isRedoAvailable(),run:()=>this.redo()}]}writeClipboard(t){var o;if(t===void 0)return;const e=this.root.ownerDocument.defaultView,s=e==null?void 0:e.navigator.clipboard,r=(o=this.clipboard)==null?void 0:o.html,i=()=>s==null?void 0:s.writeText(t).catch(()=>{});if(r&&(s!=null&&s.write)&&e&&"ClipboardItem"in e){const l=(a,c)=>new Blob([c],{type:a});s.write([new e.ClipboardItem({"text/plain":l("text/plain",t),"text/html":l("text/html",r)})]).catch(i)}else i()}copy(t=!1){var d;const e=this.getSelectedRange();if(!e)return;const s=[],r=[],i=[],o=[],l=[];let a=!1;for(let p=e.start.row;p<=e.end.row;p++){const g=this.mapper.toPhysical(p);i.push(g);const C=[],y=[],m=[],f=[];for(let x=e.start.col;x<=e.end.col;x++){C.push(this.rawAt(g,x)),y.push(this.displayText(g,x)),m.push((d=this.cellMeta.get(O(g,x)))==null?void 0:d.style);const A=this.metaAt(g,x).style;f.push(A),a||(a=!!A)}s.push(C),r.push(y),o.push(m),l.push(f)}const c=yo(r),h=r.length*r[0].length,u=a&&h<=Co?to(r,l):void 0;return this.clipboard={text:c,raws:s,rows:i,col:e.start.col,styles:o,html:u},t&&this.clearRange(e,"cut"),c}paste(t,e){var y;const s=this.getSelectedRange();if(!s||this.opts.readOnly)return;const r=this.clipboard&&this.clipboard.text===t?this.clipboard:null,i=this.root.ownerDocument.defaultView,o=!r&&e&&i?ro(e,i):null,l=r?r.raws:t?vo(t):(o==null?void 0:o.texts)??[];if(!l.length)return;const a=o&&o.texts.length===l.length&&o.texts.every((m,f)=>m.length===l[f].length),c=(r==null?void 0:r.styles)??(a?o.styles:void 0),h=l.length===1&&l[0].length===1;let u=h?s.end.row-s.start.row+1:l.length;if(this.server){const m=this.countRows()-s.start.row;u>m&&(this.run("afterPasteClipped",u-m),u=m)}const d=h?s.end.col-s.start.col+1:Zt(l,m=>m.length);this.ensureVisualRows(s.start.row+u);const p=[],g=[];for(let m=0;m<u;m++){const f=this.mapper.toPhysical(s.start.row+m);for(let x=0;x<d;x++){const A=s.start.col+x,k=h?0:m,F=h?0:x;let $=l[k][F]??null;if(r?V($)&&this.engine&&($=this.engine.shiftFormula($,f-r.rows[k],A-(r.col+F))):$=me(String($??""),this.metaAt(f,A)),p.push(this.change(f,A,$)),c&&!this.isReadOnly(f,A)){const L=O(f,A),H=this.cellMeta.get(L),X={...H},_=(y=c[k])==null?void 0:y[F];_?X.style=_:delete X.style,(_||H!=null&&H.style)&&g.push({key:L,before:H,after:Object.keys(X).length?X:void 0})}}}const C=this.undoStack.length;if(this.applyChanges(p,"paste"),g.length&&this.undoStack.length>C){this.applyMeta(g,"after");const m=this.undoStack.splice(C);this.undoStack.push({kind:"group",entries:[...m,{kind:"meta",changes:g}]})}this.selectCell(s.start.row,s.start.col,s.start.row+u-1,s.start.col+d-1)}autofill(t,e){const s=e.start.row>t.end.row?"down":e.end.row<t.start.row?"up":e.start.col>t.end.col?"right":"left",r=s==="down"||s==="up",i=r?e.end.row-e.start.row+1:e.end.col-e.start.col+1;s==="down"&&this.ensureVisualRows(e.end.row+1),s==="right"&&this.ensureSize(this.data.length,e.end.col+1);const o=[],[l,a]=r?[t.start.col,t.end.col]:[t.start.row,t.end.row];for(let h=l;h<=a;h++){let u=[];for(let y=r?t.start.row:t.start.col;y<=(r?t.end.row:t.end.col);y++)u.push(y);(s==="up"||s==="left")&&(u=u.reverse());const d=Array.from({length:i},(y,m)=>s==="down"?t.end.row+1+m:s==="up"?t.start.row-1-m:s==="right"?t.end.col+1+m:t.start.col-1-m),p=y=>r?{p:this.mapper.toPhysical(y),c:h}:{p:this.mapper.toPhysical(h),c:y},g=[...u,...d],C=Pr(u.map(y=>{const{p:m,c:f}=p(y);return this.rawAt(m,f)}),i,(y,m,f)=>{if(!this.engine)return y;const x=p(g[m]),A=p(g[f]);return this.engine.shiftFormula(y,A.p-x.p,A.c-x.c)});d.forEach((y,m)=>{const{p:f,c:x}=p(y);o.push(this.change(f,x,C[m]))})}this.applyChanges(o,"autofill");const c=Ys(t,e);this.selectCell(c.start.row,c.start.col,c.end.row,c.end.col),this.run("afterAutofill",t,e)}render(){ko(this.frame),this.frame=0,this.layout();const t=this.viewport(),{corner:e,top:s,left:r,main:i}=this.panes,o=[0,this.frozenRows-1],l=[0,this.frozenCols-1];this.renderPane(e,o,l),this.renderPane(s,o,[t.c0,t.c1]),this.renderPane(r,[t.r0,t.r1],l),this.renderPane(i,[t.r0,t.r1],[t.c0,t.c1]),this.editing||this.placeInput(),this.syncFormulaBar(),this.renderServerState()}destroy(){var t,e,s,r,i,o,l;(t=this.closeMenu)==null||t.call(this),(e=this.searchPanel)==null||e.close(),(s=this.bar)==null||s.el.remove(),(i=(r=this.server)==null?void 0:r.pager)==null||i.el.remove(),clearTimeout(this.announceTimer),this.cleanup.forEach(a=>a()),(o=this.engine)==null||o.off("valuesUpdated",this.onValuesUpdated),this.ownsEngine&&((l=this.engine)==null||l.destroy()),this.root.remove()}valueAt(t,e){var s;return this.engine?this.engine.getCellValue({row:t,col:e,sheet:this.sheet}):at((s=this.data[t])==null?void 0:s[e])}rawAt(t,e){var s;return this.engine?t<this.data.length?this.engine.getCellSerialized({row:t,col:e,sheet:this.sheet}):null:((s=this.data[t])==null?void 0:s[e])??null}metaAt(t,e){var l,a;const s=this.columnMeta[e],r=(a=(l=this.opts).cells)==null?void 0:a.call(l,t,e),i=this.cellMeta.size?this.cellMeta.get(O(t,e)):void 0;if(!r&&!i)return s??{};const o={...s,...r,...i};return(s!=null&&s.style||r!=null&&r.style||i!=null&&i.style)&&(o.style={...s==null?void 0:s.style,...r==null?void 0:r.style,...i==null?void 0:i.style}),o}displayText(t,e,s=this.valueAt(t,e)){return Ms(s,this.metaAt(t,e),this.opts.locale).text}passes(t,e){for(const[s,r]of e){const i=this.valueAt(t,s);if(!Hs(i,this.displayText(t,s,i),r,this.opts.locale))return!1}return!0}change(t,e,s){var l;const r=(l=this.binding)==null?void 0:l.fields[e],i=this.getColumnId(e),o=this.server?this.rowKeyAt(t):void 0;return{row:this.mapper.toVisual(t),physicalRow:t,col:e,...r?{prop:r}:{},...i!==void 0?{columnId:i}:{},...o!==void 0?{rowKey:o}:{},oldValue:this.rawAt(t,e),newValue:s}}isReadOnly(t,e){return!!this.opts.readOnly||!!this.metaAt(t,e).readOnly}applyChanges(t,e,s=!0){var l,a;this.server&&(t=t.filter(c=>c.physicalRow<this.data.length));const r=e!=="api"&&e!=="undo"&&e!=="redo";if(r&&(t=t.filter(c=>!this.isReadOnly(c.physicalRow,c.col))),!t.length||this.run("beforeChange",t,e)===!1||r&&(t=t.filter(c=>{const h=this.metaAt(c.physicalRow,c.col);return h.allowInvalid!==!1||V(c.newValue)?!0:!ks(at(c.newValue),c.newValue,h,c.physicalRow,c.col)}),!t.length))return;const i=Zt(t,c=>c.physicalRow),o=Zt(t,c=>c.col);this.ensureSize(i+1,o+1);for(const c of t)this.data[c.physicalRow][c.col]=c.newValue??null,this.computedBinding()&&V(c.newValue)||(l=this.binding)==null||l.write(c.physicalRow,c.col,c.newValue??null);(a=this.engine)==null||a.batch(()=>{for(const c of t)this.engine.setCellContents({row:c.physicalRow,col:c.col,sheet:this.sheet},c.newValue??null)});for(const c of t)this.revalidate(c.physicalRow,c.col);s&&(this.undoStack.push({kind:"cells",changes:t}),this.redoStack=[]),this.render(),this.run("afterChange",t,e)}clearRange(t,e){const s=[];for(let r=t.start.row;r<=t.end.row;r++){const i=this.mapper.toPhysical(r);for(let o=t.start.col;o<=t.end.col;o++)De(this.rawAt(i,o))||s.push(this.change(i,o,null))}this.applyChanges(s,e)}replay(t,e,s){const r=t.pop();r&&(this.replayEntry(r,s),e.push(r))}replayEntry(t,e){if(t.kind==="group")(e==="undo"?[...t.entries].reverse():t.entries).forEach(s=>this.replayEntry(s,e));else if(t.kind==="meta")this.applyMeta(t.changes,e==="undo"?"before":"after"),this.render();else if(t.kind==="cells"){const s=t.changes.map(r=>e==="undo"?{...r,oldValue:r.newValue,newValue:r.oldValue}:{...r});this.applyChanges(s,e,!1)}else{const s=this.snapshot();this.bindingPaused=!0,e==="undo"?[...t.ops].reverse().forEach(r=>this.undoEngineOp(r)):t.ops.forEach(r=>this.applyEngineOp(r)),this.bindingPaused=!1,this.restore(t.state),this.syncBoundObjects(),t.state=s,this.layoutChanged()}}applyMeta(t,e){for(const s of t){const r=s[e];r?this.cellMeta.set(s.key,r):this.cellMeta.delete(s.key)}}applyEngineOp(t){const e=this.engine;e&&(t.target!==void 0?e.moveColumns(t.index,t.count,t.target,this.sheet):t.remove?(t.record=e.captureRemoval(t.axis,t.index,t.count,this.sheet),t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)):t.axis==="row"?e.addRows(t.index,t.count,this.sheet):e.addColumns(t.index,t.count,this.sheet))}undoEngineOp(t){const e=this.engine;if(e)if(t.target!==void 0){const s=e.inverseMove(t.index,t.count,t.target);e.moveColumns(s.start,s.count,s.target,this.sheet)}else t.remove?e.restoreRemoval(t.record):t.axis==="row"?e.removeRows(t.index,t.count,this.sheet):e.removeColumns(t.index,t.count,this.sheet)}snapshot(){var t;return{data:this.data.map(e=>[...e]),binding:(t=this.binding)==null?void 0:t.snapshot(),colSizes:Array.from({length:this.cols.count},(e,s)=>this.cols.size(s)),rows:this.mapper.snapshot(),merges:this.getMergedCells(),columns:[...this.columnMeta],labels:this.labels&&[...this.labels],filters:[...this.filters].map(([e,s])=>[e,{...s}]),sort:this.getSortKeys(),cellMeta:[...this.cellMeta],rowHeights:[...this.rowHeights],hidden:[...this.hiddenCols]}}restore(t){var e;this.data=t.data.map(s=>[...s]),t.binding&&((e=this.binding)==null||e.restore(t.binding)),this.mapper.restore(t.rows),this.syncRows(),this.cols=new Ft(t.colSizes.length,this.cols.defaultSize,t.colSizes),this.merges.set(t.merges),this.columnMeta=[...t.columns],this.labels=t.labels&&[...t.labels],this.filters=new Map(t.filters),this.sortKeys=t.sort.map(s=>({...s})),this.cellMeta=new Map(t.cellMeta),this.rowHeights=new Map(t.rowHeights),this.hiddenCols=new Map(t.hidden),this.syncRows(),this.frozenCols=Math.min(this.frozenCols,this.countCols()),this.validateAll(),this.clampSelection(),this.render()}alterRows(t,e,s,r){var i,o;if(s){const l=Array.from({length:e},(a,c)=>this.mapper.toPhysical(t+c)).sort((a,c)=>c-a);for(const a of l)this.data.splice(a,1),(i=this.binding)==null||i.removeRows(a,1),this.mapper.remove(a,1),this.shiftRowState(a,-1),this.applyEngineOp(Pt(r,{axis:"row",index:a,count:1,remove:!0}));this.merges.shift("row",t,-e)}else{const l=t<this.countRows()?this.mapper.toPhysical(t):this.data.length;this.data.splice(l,0,...Array.from({length:e},()=>Array(this.countCols()).fill(null))),(o=this.binding)==null||o.insertRows(l,e),this.mapper.insert(l,e,t),this.shiftRowState(l,e),this.applyEngineOp(Pt(r,{axis:"row",index:l,count:e,remove:!1})),this.merges.shift("row",t,e)}this.syncRows()}shiftRowState(t,e){this.cellMeta=Dt(this.cellMeta,s=>{const r=Gt(Math.floor(s/16384),t,e);return r<0?-1:r*16384+s%16384}),this.rowHeights=Dt(this.rowHeights,s=>Gt(s,t,e))}alterCols(t,e,s,r){var l,a,c,h;for(const u of this.data)s?u.splice(t,e):u.splice(t,0,...Array(e).fill(null));s?(l=this.binding)==null||l.removeCols(t,e):(a=this.binding)==null||a.insertCols(t,e),s?(this.cols.remove(t,e),this.applyEngineOp(Pt(r,{axis:"col",index:t,count:e,remove:!0})),this.columnMeta.splice(t,e),(c=this.labels)==null||c.splice(t,e)):(this.cols.insert(t,e),this.applyEngineOp(Pt(r,{axis:"col",index:t,count:e,remove:!1})),t<this.columnMeta.length&&this.columnMeta.splice(t,0,...Array(e)),(h=this.labels)==null||h.splice(t,0,...Array(e).fill("")));const i=u=>s?u>=t+e?u-e:u>=t?-1:u:u>=t?u+e:u;this.filters=new Map([...this.filters].map(([u,d])=>[i(u),d]).filter(([u])=>u>=0)),this.sortKeys=this.sortKeys.map(u=>({...u,col:i(u.col)})).filter(u=>u.col>=0),this.merges.shift("col",t,s?-e:e),this.frozenCols=Math.min(this.frozenCols,this.countCols());const o=s?-e:e;this.cellMeta=Dt(this.cellMeta,u=>{const d=Gt(u%16384,t,o);return d<0?-1:u-u%16384+d}),this.hiddenCols=Dt(this.hiddenCols,u=>Gt(u,t,o))}ensureSize(t,e){var s;if(this.server&&(t=Math.min(t,this.data.length)),e>this.countCols()){for(const r of this.data)for(;r.length<e;)r.push(null);this.cols.resize(e)}if(t>this.data.length){const r=t-this.data.length;for(let i=0;i<r;i++)this.data.push(Array(this.countCols()).fill(null));(s=this.binding)==null||s.ensureRows(this.data.length),this.mapper.insert(this.data.length-r,r),this.syncRows()}}ensureVisualRows(t){t>this.countRows()&&this.ensureSize(this.data.length+t-this.countRows(),this.countCols())}bind(t){return Rn(t)?(this.binding=ae.create(t,this.columnMeta.map(e=>e==null?void 0:e.data),this.opts.dataSchema),this.binding.toRows()):(this.binding=void 0,t)}normalize(t){const e=t.length===0&&!this.opts.dataMode,s=Math.max(t.length,this.opts.minRows??(e?50:0)),r=Math.max(Zt(t,i=>i.length),this.opts.minCols??(e?26:0),this.columnMeta.length,1);return Array.from({length:s},(i,o)=>Array.from({length:r},(l,a)=>{var c;return((c=t[o])==null?void 0:c[a])??null}))}syncRows(){const t=this.mapper.count;if(!this.rowsCustomized){this.rows.resize(t);return}const e=this.rows.defaultSize,s=Array.from({length:t},(r,i)=>this.rowHeights.get(this.mapper.toPhysical(i))??e);this.rows=new Ft(t,e,s),this.rowsCustomized=this.rowHeights.size>0}afterRowMapping(){this.syncRows(),this.clampSelection(),this.render()}revalidate(t,e){const s=this.metaAt(t,e),r=O(t,e),i=this.invalid.get(r),o=ge(s)?ks(this.valueAt(t,e),this.rawAt(t,e),s,t,e):void 0;o?this.invalid.set(r,o):this.invalid.delete(r),o!==i&&this.run("afterValidate",this.mapper.toVisual(t),e,o)}validateAll(){this.invalid.clear();const t=Array.from({length:this.countCols()},(s,r)=>r),e=this.opts.cells?t:t.filter(s=>this.columnMeta[s]&&ge(this.columnMeta[s]));for(let s=0;s<this.data.length;s++)for(const r of e)this.revalidate(s,r);for(const s of this.cellMeta.keys())this.revalidate(Math.floor(s/16384),s%16384)}computedBinding(){return!!this.binding&&!!this.engine&&this.opts.bindFormulas!=="text"}boundValueAt(t,e){const s=this.rawAt(t,e);if(!this.computedBinding()||!(s===null||V(s)))return s;const r=this.valueAt(t,e);return r instanceof ct?null:r}writeComputed(t,e,s){if(!this.computedBinding())return;const r=this.boundValueAt(t,e);(V(this.rawAt(t,e))||r!==null||s&&this.rawAt(t,e)===null)&&this.binding.write(t,e,r)}syncBoundObjects(){if(this.computedBinding())for(let t=0;t<this.data.length;t++)for(let e=0;e<this.data[t].length;e++)this.writeComputed(t,e,!1)}run(t,...e){let s=!0;for(const r of this.hooks.get(t)??[])r(...e)===!1&&(s=!1);return s}mergesActive(){return this.merges.list.length>0&&this.mapper.isIdentity}mergeAt(t,e){return this.mergesActive()?this.merges.get(t,e):void 0}mergeAllowed(t){const e=(s,r,i)=>i>0&&s<i&&s+r>i;return this.mapper.isIdentity&&t.row>=0&&t.col>=0&&t.row+t.rowspan<=this.data.length&&t.col+t.colspan<=this.countCols()&&!e(t.row,t.rowspan,this.frozenRows)&&!e(t.col,t.colspan,this.frozenCols)}el(t,e,s="div"){const r=this.root.ownerDocument.createElement(s);return r.className=t,e.appendChild(r),r}makePane(t,e,s,r){const i=this.el(`ct-pane ${t}`,e);return{el:i,frozenRows:s,frozenCols:r,cells:new Map,pool:[],colHeads:[],rowHeads:[],rangeBox:this.el("ct-range",i),fillBox:this.el("ct-fill-area",i),activeBox:this.el("ct-active",i),handle:this.el("ct-fill",i)}}buildDom(){this.canvas=this.el("ct-canvas",this.root),this.topBand=this.el("ct-band ct-band-top",this.canvas),this.bodyBand=this.el("ct-band ct-band-body",this.canvas),this.panes={corner:this.makePane("ct-pane-corner",this.topBand,!0,!0),top:this.makePane("ct-pane-top",this.topBand,!0,!1),left:this.makePane("ct-pane-left",this.bodyBand,!1,!0),main:this.makePane("ct-pane-main",this.bodyBand,!1,!1)},this.cornerHead=this.el("ct-header ct-cornerhead",this.panes.corner.el),this.announcer=this.el("ct-sr",this.root),this.announcer.setAttribute("aria-live","polite"),this.announcer.setAttribute("aria-atomic","true"),this.input=this.root.ownerDocument.createElement("textarea"),this.input.className="ct-editor ct-idle",this.input.setAttribute("aria-label","Cell editor"),this.input.spellcheck=!1,this.input.addEventListener("keydown",this.onEditorKey),this.input.addEventListener("input",this.onInput),this.input.addEventListener("compositionstart",()=>this.openEditor("")),this.input.addEventListener("blur",t=>{(!this.bar||t.relatedTarget!==this.bar.input)&&this.closeEditor(!0)}),this.panes.main.el.appendChild(this.input)}resetHeaders(){for(const t of Object.values(this.panes))t.colHeads.forEach(e=>e.remove()),t.colHeads=[]}frozenSize(){return{fw:this.cols.offset(this.frozenCols),fh:this.rows.offset(this.frozenRows)}}layout(){const t=this.cols.total,e=this.rows.total,{fw:s,fh:r}=this.frozenSize(),i=(o,l,a)=>{o.style.width=`${Math.max(0,l)}px`,o.style.height=`${Math.max(0,a)}px`};i(this.canvas,this.rowHeaderW+t,this.headerH+e),i(this.topBand,this.rowHeaderW+t,this.headerH+r),this.topBand.style.display=this.headerH+r>0?"":"none",i(this.bodyBand,this.rowHeaderW+t,e-r),i(this.panes.corner.el,this.rowHeaderW+s,this.headerH+r),i(this.panes.top.el,t-s,this.headerH+r),i(this.panes.left.el,this.rowHeaderW+s,e-r),i(this.panes.main.el,t-s,e-r),this.panes.corner.el.classList.toggle("ct-edge-r",s>0),this.panes.left.el.classList.toggle("ct-edge-r",s>0),this.panes.corner.el.classList.toggle("ct-edge-b",r>0),this.panes.top.el.classList.toggle("ct-edge-b",r>0),this.root.setAttribute("aria-rowcount",String(this.countRows()+(this.headerH?1:0))),this.root.setAttribute("aria-colcount",String(this.countCols()+(this.rowHeaderW?1:0))),bt(this.cornerHead,0,0,this.rowHeaderW,this.headerH),this.cornerHead.style.display=this.rowHeaderW&&this.headerH?"":"none"}cellX(t,e){return(t.frozenCols?this.rowHeaderW:0)+this.cols.offset(e)-(t.frozenCols?0:this.cols.offset(this.frozenCols))}cellY(t,e){return(t.frozenRows?this.headerH:0)+this.rows.offset(e)-(t.frozenRows?0:this.rows.offset(this.frozenRows))}viewport(){const{fw:t,fh:e}=this.frozenSize(),s=this.root.scrollTop+e,r=this.root.scrollLeft+t,i=(this.root.clientHeight||600)-this.headerH-e,o=(this.root.clientWidth||1e3)-this.rowHeaderW-t;return{r0:Math.max(this.frozenRows,this.rows.indexAt(s)-qt),r1:Math.min(this.countRows()-1,this.rows.indexAt(s+i)+qt),c0:Math.max(this.frozenCols,this.cols.indexAt(r)-qt),c1:Math.min(this.countCols()-1,this.cols.indexAt(r+o)+qt)}}paneOf(t,e){const s=t<this.frozenRows,r=e<this.frozenCols;return s?r?this.panes.corner:this.panes.top:r?this.panes.left:this.panes.main}renderPane(t,[e,s],[r,i]){const o=[];if(s>=e&&i>=r){const c=new Set;for(let h=e;h<=s;h++)for(let u=r;u<=i;u++){if(this.hiddenCols.size&&this.hiddenCols.has(u))continue;const d=this.mergeAt(h,u);if(d&&(d.row!==h||d.col!==u)){(d.row<e||d.col<r)&&c.add(d);continue}o.push([h,u,d])}for(const h of c)o.push([h.row,h.col,h])}const l=new Set(o.map(([c,h])=>O(c,h)));for(const[c,h]of t.cells)l.has(c)||t.pool.push(h);const a=new Map;for(const[c,h,u]of o){const d=O(c,h),p=t.cells.get(d)??t.pool.pop()??this.makeCell(t);a.set(d,p);const g=u?this.cols.offset(h+u.colspan)-this.cols.offset(h):this.cols.size(h),C=u?this.rows.offset(c+u.rowspan)-this.rows.offset(c):this.rows.size(c);this.paintCell(p,c,h),bt(p,this.cellX(t,h),this.cellY(t,c),g,C),p.style.display=""}for(const c of t.pool)c.style.display="none";t.cells=a,this.renderHeaders(t,[e,s],[r,i]),this.renderSelection(t)}makeCell(t){const e=this.el("ct-cell",t.el);return e.setAttribute("role","gridcell"),e}paintCell(t,e,s){var m;const r=this.mapper.toPhysical(e),i=this.metaAt(r,s),o=this.valueAt(r,s),{text:l,kind:a}=Ms(o,i,this.opts.locale);let c=a?`ct-cell ct-${a}`:"ct-cell";i.type==="dropdown"&&(c+=" ct-dd"),i.readOnly&&(c+=" ct-readonly");const h=this.invalid.size?this.invalid.get(O(r,s)):void 0;h&&(c+=" ct-invalid"),i.className&&(c+=` ${i.className}`),this.searchHits.size&&this.searchHits.has(O(r,s))&&(c+=" ct-match");const u=this.conditionalStyle(r,s,o),d=u?{...i.style,...u}:i.style;d&&(c+=Wr(d)),t.className!==c&&(t.className=c);const p=(d==null?void 0:d.color)??"";t.dataset.fg!==p&&(t.style.color=p,t.dataset.fg=p);const g=(d==null?void 0:d.background)??"";t.dataset.bg!==g&&(t.style.backgroundColor=g,t.dataset.bg=g);const C=String(e+(this.headerH?2:1)),y=String(s+(this.rowHeaderW?2:1));t.getAttribute("aria-rowindex")!==C&&t.setAttribute("aria-rowindex",C),t.getAttribute("aria-colindex")!==y&&t.setAttribute("aria-colindex",y),a==="check"?t.dataset.check!==l&&(t.textContent="",this.el("ct-checkbox",t,"span").textContent=l,t.dataset.check=l):(t.dataset.check!==void 0&&delete t.dataset.check,t.textContent!==l&&(t.textContent=l)),h?t.title=h:t.title&&(t.title=""),(m=i.renderer)==null||m.call(i,t,o,{row:e,col:s,meta:i})}conditionalStyle(t,e,s){const r=this.opts.conditionalFormats;if(!(r!=null&&r.length))return;let i;for(const o of r){if(!o.entireRow&&o.columns&&!o.columns.includes(e))continue;(o.entireRow?o.columns??[]:[e]).some(c=>{const h=c===e?s:this.valueAt(t,c);return typeof o.when=="function"?o.when(h,this.mapper.toVisual(t),c):Hs(h,this.displayText(t,c,h),{condition:o.when},this.opts.locale)})&&(i={...i,...o.style})}return i}renderHeaders(t,[e,s],[r,i]){var l,a,c;const o=this.getSelectedRange();if(t.frozenRows&&this.headerH){const h=this.getSortKeys();let u=0;for(let d=r;d<=i;d++){if(this.hiddenCols.size&&this.hiddenCols.has(d))continue;const p=t.colHeads[u]??this.makeColHeader(t,u);u++,p.classList.toggle("ct-gap-r",this.hiddenCols.has(d+1)),p.classList.toggle("ct-gap-l",d>0&&this.hiddenCols.has(d-1)),p.setAttribute("aria-colindex",String(d+(this.rowHeaderW?2:1))),p.dataset.col=String(d);const g=((l=this.labels)==null?void 0:l[d])||((a=this.columnMeta[d])==null?void 0:a.title)||((c=this.binding)==null?void 0:c.fields[d])||zt(d),C=p.children[0];C.textContent!==g&&(C.textContent=g);const y=h.findIndex(A=>A.col===d),m=y<0?"":`${h[y].order==="asc"?"▲":"▼"}${h.length>1?y+1:""}`,f=p.children[1];f.textContent!==m&&(f.textContent=m),p.classList.toggle("ct-hl",!!o&&d>=o.start.col&&d<=o.end.col);const x=this.getColumnId(d);if(p.classList.toggle("ct-filtered",this.server?x!==void 0&&x in this.server.query.filters:this.filters.has(d)),this.server){const A=this.columnMeta[d];p.querySelector(".ct-menu-btn").hidden=!(x!==void 0&&(A!=null&&A.sortable||A!=null&&A.serverFilter))}bt(p,this.cellX(t,d),0,this.cols.size(d),this.headerH),p.style.display=""}for(;u<t.colHeads.length;u++)t.colHeads[u].style.display="none"}if(t.frozenCols&&this.rowHeaderW){let h=0;for(let u=e;u<=s;u++,h++){const d=t.rowHeads[h]??this.makeRowHeader(t,h);d.dataset.row=String(u);const p=String(this.mapper.toPhysical(u)+1),g=d.children[0];g.textContent!==p&&(g.textContent=p),d.setAttribute("aria-rowindex",String(u+(this.headerH?2:1))),d.classList.toggle("ct-hl",!!o&&u>=o.start.row&&u<=o.end.row),bt(d,0,this.cellY(t,u),this.rowHeaderW,this.rows.size(u)),d.style.display=""}for(;h<t.rowHeads.length;h++)t.rowHeads[h].style.display="none"}}makeRowHeader(t,e){const s=this.el("ct-header ct-rowhead",t.el);return s.setAttribute("role","rowheader"),this.el("ct-label",s,"span"),this.el("ct-rresize",s),t.rowHeads[e]=s,s}makeColHeader(t,e){const s=this.el("ct-header ct-colhead",t.el);if(s.setAttribute("role","columnheader"),this.el("ct-label",s,"span"),this.el("ct-sort",s,"span"),this.opts.columnSorting||this.opts.filters||this.opts.dataMode==="server"){const r=this.el("ct-menu-btn",s,"button");r.type="button",r.tabIndex=-1,r.textContent="▾",r.setAttribute("aria-label",this.messages.columnMenu)}return this.el("ct-resize",s),t.colHeads[e]=s,s}boxFor(t,e){const s=Math.max(e.start.row,t.frozenRows?0:this.frozenRows),r=Math.min(e.end.row,t.frozenRows?this.frozenRows-1:this.countRows()-1),i=Math.max(e.start.col,t.frozenCols?0:this.frozenCols),o=Math.min(e.end.col,t.frozenCols?this.frozenCols-1:this.countCols()-1);if(s>r||i>o)return null;const l=this.cellX(t,i),a=this.cellY(t,s);return[l-1,a-1,this.cellX(t,o+1)-l+1,this.cellY(t,r+1)-a+1]}renderSelection(t){const e=this.getSelectedRange(),s=(...c)=>c.forEach(h=>h.style.display="none");if(!e||!this.anchor){s(t.rangeBox,t.activeBox,t.handle,t.fillBox);return}const r=(c,h)=>{if(!h)return s(c);bt(c,...h),c.style.display=""},i=this.mergeAt(this.anchor.row,this.anchor.col),o=i?{start:{row:i.row,col:i.col},end:{row:i.row+i.rowspan-1,col:i.col+i.colspan-1}}:{start:this.anchor,end:this.anchor},l=e.start.row!==o.start.row||e.start.col!==o.start.col||e.end.row!==o.end.row||e.end.col!==o.end.col;r(t.rangeBox,l?this.boxFor(t,e):null),r(t.activeBox,this.boxFor(t,o)),r(t.fillBox,this.fillTarget?this.boxFor(t,Ys(e,this.fillTarget.range)):null),this.opts.fillHandle!==!1&&!this.opts.readOnly&&!this.editing&&this.paneOf(e.end.row,e.end.col)===t?(bt(t.handle,this.cellX(t,e.end.col+1)-4,this.cellY(t,e.end.row+1)-4,7,7),t.handle.style.display=""):s(t.handle)}scheduleRender(){this.frame||(this.frame=Mo(()=>{this.frame=0,this.render()}))}scrollIntoView({row:t,col:e}){const{fw:s,fh:r}=this.frozenSize(),i=this.root.clientHeight-this.headerH,o=this.root.clientWidth-this.rowHeaderW;if(!(i<=0||o<=0)){if(t>=this.frozenRows){const l=this.rows.offset(t),a=l+this.rows.size(t);l-r<this.root.scrollTop?this.root.scrollTop=l-r:a>this.root.scrollTop+i&&(this.root.scrollTop=a-i)}if(e>=this.frozenCols){const l=this.cols.offset(e),a=l+this.cols.size(e);l-s<this.root.scrollLeft?this.root.scrollLeft=l-s:a>this.root.scrollLeft+o&&(this.root.scrollLeft=a-o)}}}clampSelection(){if(!this.anchor||!this.selEnd)return;if(!this.countRows()||!this.countCols()){this.anchor=this.selEnd=null;return}const t=e=>({row:Math.min(e.row,this.countRows()-1),col:Math.min(e.col,this.countCols()-1)});this.anchor=t(this.anchor),this.selEnd=t(this.selEnd)}cellAtClient(t,e){const s=this.root.getBoundingClientRect(),{fw:r,fh:i}=this.frozenSize(),o=t-s.left-this.root.clientLeft-this.rowHeaderW,l=e-s.top-this.root.clientTop-this.headerH,a=o<r?Math.max(0,o):o+this.root.scrollLeft,c=l<i?Math.max(0,l):l+this.root.scrollTop;return{row:this.rows.indexAt(c),col:this.cols.indexAt(a)}}isEditing(){return this.editing}openEditor(t){if(!this.anchor||this.editing)return;const e=this.mapper.toPhysical(this.anchor.row),s=this.metaAt(e,this.anchor.col);if(this.isReadOnly(e,this.anchor.col)||s.type==="checkbox"){this.input.value="";return}const r=this.input;this.editing=!0,this.editorEnterMode=t!==void 0,r.value=t??jt(this.rawAt(e,this.anchor.col),s,this.opts.locale),r.classList.remove("ct-idle"),this.placeInput(),this.autoSizeInput(),this.focusInput(),r.setSelectionRange(r.value.length,r.value.length),s.type==="dropdown"&&s.source&&this.showDropdown(s.source,t!==void 0?r.value:""),this.render()}closeEditor(t){if(!this.editing||!this.anchor)return;this.editing=!1,this.hideDropdown();const e=this.mapper.toPhysical(this.anchor.row),s=this.anchor.col,r=this.input.value;if(this.input.value="",this.input.classList.add("ct-idle"),t){const i=me(r,this.metaAt(e,s));i!==this.rawAt(e,s)&&this.applyChanges([this.change(e,s,i)],"edit")}this.render()}focusInput(){this.barFocused()||this.root.ownerDocument.activeElement!==this.input&&this.input.focus({preventScroll:!0})}barFocused(){return!!this.bar&&this.root.ownerDocument.activeElement===this.bar.input}buildFormulaBar(){const t=this.root.ownerDocument.createElement("div");t.className=`ct-bar${this.opts.theme==="light"?" ct-light":this.opts.theme==="dark"?" ct-dark":""}`;const e=this.el("ct-bar-address",t),s=this.root.ownerDocument.createElement("textarea");s.className="ct-bar-input",s.rows=1,s.spellcheck=!1,s.setAttribute("aria-label",this.messages.formulaBar),t.appendChild(s),this.root.before(t),this.bar={el:t,address:e,input:s};const r=()=>{s.style.height="auto",s.style.height=`${Math.min(120,s.scrollHeight)}px`};s.addEventListener("focus",r),s.addEventListener("input",()=>{this.editing||this.openEditor(s.value),this.editing&&(this.input.value=s.value,this.onInput(),r())}),s.addEventListener("blur",i=>{s.style.height="",this.editing&&i.relatedTarget!==this.input&&this.closeEditor(!0)}),s.addEventListener("keydown",i=>this.onBarKey(i))}onBarKey(t){const e=this.bar.input,s=(r,i,o)=>{t.preventDefault();const l=this.editing;this.editing=!1,this.input.focus({preventScroll:!0}),this.editing=l,this.closeEditor(o),(r||i)&&this.moveActive(r,i,!1)};t.key==="Escape"?s(0,0,!1):t.key==="Tab"?s(0,t.shiftKey?-1:1,!0):t.key==="Enter"&&t.altKey?(t.preventDefault(),e.setRangeText(`
197
+ `,e.selectionStart,e.selectionEnd,"end"),e.dispatchEvent(new Event("input"))):t.key==="Enter"&&s(t.shiftKey?-1:1,0,!0)}syncFormulaBar(){const t=this.bar;if(!t)return;const e=this.anchor;if(!e){t.address.textContent="",t.input.value="",t.input.disabled=!0;return}const s=this.mapper.toPhysical(e.row),r=$e({row:s,col:e.col});if(t.address.textContent!==r&&(t.address.textContent=r),t.input.disabled=!1,t.input.readOnly=this.isReadOnly(s,e.col)||this.metaAt(s,e.col).type==="checkbox",this.barFocused()&&this.editing)return;const i=this.editing?this.input.value:jt(this.rawAt(s,e.col),this.metaAt(s,e.col),this.opts.locale);t.input.value!==i&&(t.input.value=i)}placeInput(){if(!this.anchor)return;const{row:t,col:e}=this.anchor,s=this.paneOf(t,e);if(this.input.parentElement!==s.el){const l=this.root.ownerDocument.activeElement===this.input;s.el.appendChild(this.input),l&&this.input.focus({preventScroll:!0})}const r=this.mergeAt(t,e),i=r?this.cols.offset(e+r.colspan)-this.cols.offset(e):this.cols.size(e),o=r?this.rows.offset(t+r.rowspan)-this.rows.offset(t):this.rows.size(t);bt(this.input,this.cellX(s,e)-1,this.cellY(s,t)-1,i+2,o+2),this.input.style.minWidth=this.editing?`${i+2}px`:""}autoSizeInput(){if(!this.editing||!this.anchor)return;const t=this.input,e=this.cols.size(this.anchor.col)+2;t.style.width="0",t.style.width=`${Math.max(e,t.scrollWidth+4)}px`}showDropdown(t,e){this.hideDropdown();const s=this.el("ct-dd-list",this.input.parentElement);s.setAttribute("role","listbox"),s.addEventListener("mousedown",r=>{r.preventDefault();const i=r.target.closest("[data-i]");!i||!this.dropdown||(this.input.value=this.dropdown.items[Number(i.dataset.i)],this.commitAndMove(1,0))}),this.dropdown={el:s,items:[],active:-1},s.style.left=this.input.style.left,s.style.top=`${parseFloat(this.input.style.top)+parseFloat(this.input.style.height)}px`,s.style.minWidth=this.input.style.width,this.filterDropdown(e,t)}filterDropdown(t,e){const s=this.dropdown;if(!s||!this.anchor)return;const r=e??this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col).source??[],i=this.opts.locale,o=t.toLocaleLowerCase(i);s.items=r.filter(l=>l.toLocaleLowerCase(i).includes(o)),s.active=o&&s.items.length?0:-1,s.el.textContent="",s.items.forEach((l,a)=>{const c=this.el("ct-dd-item",s.el);c.dataset.i=String(a),c.setAttribute("role","option"),c.textContent=l}),this.highlightDropdown()}highlightDropdown(){var e,s;const t=this.dropdown;t&&([...t.el.children].forEach((r,i)=>r.classList.toggle("ct-on",i===t.active)),(s=(e=t.el.children[t.active])==null?void 0:e.scrollIntoView)==null||s.call(e,{block:"nearest"}))}hideDropdown(){var t;(t=this.dropdown)==null||t.el.remove(),this.dropdown=void 0}commitAndMove(t,e){this.closeEditor(!0),this.moveActive(t,e,!1)}listen(t,e,s){t.addEventListener(e,s),this.cleanup.push(()=>t.removeEventListener(e,s))}bindEvents(){const t=this.root.ownerDocument;this.listen(this.root,"scroll",()=>{this.dropdown&&this.closeEditor(!0),this.scheduleRender()}),this.listen(this.root,"keydown",r=>this.onKeyDown(r)),this.listen(this.canvas,"mousedown",r=>this.onMouseDown(r)),this.listen(this.canvas,"click",r=>{const i=this.rowEventAt(r);i&&this.run("afterRowClick",i)}),this.listen(this.canvas,"dblclick",r=>this.onDoubleClick(r)),this.listen(this.canvas,"contextmenu",r=>this.onContextMenu(r)),this.listen(t,"mousemove",r=>this.onDrag(r)),this.listen(t,"mouseup",()=>this.onMouseUp());const e=()=>this.root.contains(t.activeElement)&&!this.editing,s=r=>i=>{var l,a,c;if(!e())return;const o=this.copy(r);o!==void 0&&((l=i.clipboardData)==null||l.setData("text/plain",o),(a=this.clipboard)!=null&&a.html&&((c=i.clipboardData)==null||c.setData("text/html",this.clipboard.html)),i.preventDefault())};this.listen(t,"copy",s(!1)),this.listen(t,"cut",s(!0)),this.listen(t,"paste",r=>{var l,a;if(!e())return;const i=((l=r.clipboardData)==null?void 0:l.getData("text/plain"))??"",o=(a=r.clipboardData)==null?void 0:a.getData("text/html");(i||o)&&(r.preventDefault(),this.paste(i,o))})}onMouseDown(t){const e=t.target;if(this.editing&&e===this.input||e.closest(".ct-dd-list")||t.button!==0)return;t.preventDefault(),this.editing&&this.closeEditor(!0),this.focusInput();const s=e.closest(".ct-menu-btn");if(s)return this.openMenu(Number(s.parentElement.dataset.col),s);const r=e.closest(".ct-resize");if(r)return this.startResize(Number(r.parentElement.dataset.col),t.clientX);const i=e.closest(".ct-rresize");if(i)return this.startRowResize(Number(i.parentElement.dataset.row),t.clientY);if(e.closest(".ct-fill")){this.dragging="fill";return}if(e.closest(".ct-cornerhead"))return this.selectCell(0,0,this.countRows()-1,this.countCols()-1);const o=e.closest(".ct-colhead");if(o){const c=Number(o.dataset.col),h=this.getSelectedRange(),u=!!h&&h.start.row===0&&h.end.row===this.countRows()-1;if(!t.shiftKey&&u&&c>=h.start.col&&c<=h.end.col&&!this.opts.readOnly){this.dragging="move",this.moveDrop=null;return}this.selectCell(0,t.shiftKey&&this.anchor?this.anchor.col:c,this.countRows()-1,c),this.dragging="cols";return}const l=e.closest(".ct-rowhead");if(l){const c=Number(l.dataset.row);this.selectCell(t.shiftKey&&this.anchor?this.anchor.row:c,0,c,this.countCols()-1),this.dragging="rows";return}const a=this.cellAtClient(t.clientX,t.clientY);if(e.closest(".ct-checkbox")){this.selectCell(a.row,a.col),this.toggleCheckboxes({start:a,end:a});return}t.shiftKey&&this.anchor?this.selectCell(this.anchor.row,this.anchor.col,a.row,a.col):this.selectCell(a.row,a.col),this.dragging="cells"}onContextMenu(t){if(!this.opts.contextMenu)return;t.preventDefault(),this.editing&&this.closeEditor(!0);const e=t.target,s=this.getSelectedRange(),r=(l,a)=>!!s&&l>=s.start.row&&l<=s.end.row&&a>=s.start.col&&a<=s.end.col,i=e.closest(".ct-colhead"),o=e.closest(".ct-rowhead");if(i){const l=Number(i.dataset.col),a=!!s&&s.start.row===0&&s.end.row===this.countRows()-1;(!r(0,l)||!a)&&this.selectCell(0,l,this.countRows()-1,l)}else if(o){const l=Number(o.dataset.row),a=!!s&&s.start.col===0&&s.end.col===this.countCols()-1;(!r(l,0)||!a)&&this.selectCell(l,0,l,this.countCols()-1)}else if(!e.closest(".ct-cornerhead")){const l=this.cellAtClient(t.clientX,t.clientY);r(l.row,l.col)||this.selectCell(l.row,l.col)}this.focusInput(),this.openContextMenu(t.clientX,t.clientY)}onDoubleClick(t){const e=t.target;if(e.closest(".ct-fill"))return this.fillToDataEnd();if(e.closest(".ct-header")||e.closest(".ct-checkbox")||e.closest(".ct-dd-list"))return;const s=this.rowEventAt(t);s&&this.run("afterRowDoubleClick",s)===!1||this.editing||this.openEditor()}rowEventAt(t){const e=t.target;if(!e.closest(".ct-cell")||e.closest(".ct-checkbox"))return null;const{row:s,col:r}=this.cellAtClient(t.clientX,t.clientY);if(s>=this.countRows())return null;const i=this.mapper.toPhysical(s),o=this.getColumnId(r),l=this.rowKeyAt(i);return{row:s,physicalRow:i,col:r,...o!==void 0?{columnId:o}:{},...l!==void 0?{rowKey:l}:{},rowData:this.getSourceDataAtRow(s),originalEvent:t}}onDrag(t){if(!this.dragging||!this.anchor)return;const e=this.cellAtClient(t.clientX,t.clientY);this.dragging==="cells"?this.selectCell(this.anchor.row,this.anchor.col,e.row,e.col):this.dragging==="rows"?this.selectCell(this.anchor.row,0,e.row,this.countCols()-1):this.dragging==="cols"?this.selectCell(0,this.anchor.col,this.countRows()-1,e.col):this.dragging==="move"?this.updateMoveDrop(t.clientX):this.updateFillTarget(e)}onMouseUp(){var e;if(this.dragging==="move"){const s=this.moveDrop;this.moveDrop=null,this.dragging=null,(e=this.dropLine)==null||e.remove(),this.dropLine=void 0,s&&this.moveColumns(s.start,s.count,s.target);return}const t=this.fillTarget;this.fillTarget=null,this.dragging==="fill"&&t?this.autofill(this.getSelectedRange(),t.range):t&&this.render(),this.dragging=null}updateMoveDrop(t){const e=this.getSelectedRange(),s=this.root.getBoundingClientRect(),{fw:r}=this.frozenSize(),i=t-s.left-this.root.clientLeft-this.rowHeaderW,o=i<r?Math.max(0,i):i+this.root.scrollLeft,l=this.cols.indexAt(o),a=o-this.cols.offset(l)>this.cols.size(l)/2?l+1:l,c=e.end.col-e.start.col+1,h=this.canMoveColumns(e.start.col,c,a);this.moveDrop=h?{start:e.start.col,count:c,target:a}:null,this.dropLine||(this.dropLine=this.el("ct-drop",this.root));const u=this.rowHeaderW+this.cols.offset(a)-(a>=this.frozenCols?this.root.scrollLeft:0);this.dropLine.style.display=h?"":"none",this.dropLine.style.left=`${this.root.scrollLeft+u-1}px`,this.dropLine.style.top=`${this.root.scrollTop}px`,this.dropLine.style.height=`${this.root.clientHeight}px`}updateFillTarget(t){const e=this.getSelectedRange(),s=t.row-e.end.row,r=e.start.row-t.row,i=t.col-e.end.col,o=e.start.col-t.col,l=Math.max(s,r,i,o);let a=null;l>0&&(l===s?a={direction:"down",range:{start:{row:e.end.row+1,col:e.start.col},end:{row:t.row,col:e.end.col}}}:l===r?a={direction:"up",range:{start:{row:t.row,col:e.start.col},end:{row:e.start.row-1,col:e.end.col}}}:l===i?a={direction:"right",range:{start:{row:e.start.row,col:e.end.col+1},end:{row:e.end.row,col:t.col}}}:a={direction:"left",range:{start:{row:e.start.row,col:t.col},end:{row:e.end.row,col:e.start.col-1}}}),this.fillTarget=a,this.render()}fillToDataEnd(){const t=this.getSelectedRange();if(!t)return;const e=t.start.col>0?t.start.col-1:t.end.col+1;if(e>=this.countCols())return;let s=t.end.row;for(;s+1<this.countRows()&&!De(this.getSourceDataAtCell(s+1,e));)s++;s>t.end.row&&this.autofill(t,{start:{row:t.end.row+1,col:t.start.col},end:{row:s,col:t.end.col}})}startResize(t,e){const s=this.root.ownerDocument,r=this.cols.size(t),i=l=>this.setColWidth(t,r+l.clientX-e),o=()=>{s.removeEventListener("mousemove",i),s.removeEventListener("mouseup",o),this.cols.size(t)!==r&&this.layoutChanged()};s.addEventListener("mousemove",i),s.addEventListener("mouseup",o)}startRowResize(t,e){const s=this.root.ownerDocument,r=this.rows.size(t),i=l=>this.setRowHeight(t,r+l.clientY-e),o=()=>{s.removeEventListener("mousemove",i),s.removeEventListener("mouseup",o)};s.addEventListener("mousemove",i),s.addEventListener("mouseup",o)}openServerMenu(t,e){const s=this.getColumnId(t),r=this.columnMeta[t],i=this.server;if(s===void 0)return;const o=r==null?void 0:r.serverFilter,l=this.getSortKeys().find(c=>c.col===t),a=i.query.sort.filter(c=>c.field!==s);this.closeMenu=Fs({anchor:e,messages:this.messages,locale:this.opts.locale,sort:(l==null?void 0:l.order)??null,sortedElsewhere:!1,filter:void 0,values:[],sortable:!!(r!=null&&r.sortable),filterable:!1,onSort:c=>this.setQuery({sort:c?[{field:s,desc:c==="desc"}]:a},"sort"),onFilter:()=>{},server:o&&{def:o,value:i.query.filters[s],onFilter:c=>this.setServerFilter(s,c)},onClose:()=>{this.closeMenu=void 0,this.focusInput()}})}openMenu(t,e){var o,l;if((o=this.closeMenu)==null||o.call(this),this.server)return this.openServerMenu(t,e);const s=[...this.filters].filter(([a])=>a!==t),r=new Set;for(let a=this.mapper.pinnedCount;a<this.data.length;a++)this.passes(a,s)&&r.add(this.displayText(a,t));const i=[...r].sort((a,c)=>a===""?1:c===""?-1:a.localeCompare(c,this.opts.locale,{numeric:!0,sensitivity:"base"}));this.closeMenu=Fs({anchor:e,messages:this.messages,locale:this.opts.locale,sort:((l=this.sortKeys.find(a=>a.col===t))==null?void 0:l.order)??null,sortedElsewhere:this.sortKeys.some(a=>a.col!==t),filter:this.filters.get(t),values:i,sortable:!!this.opts.columnSorting,filterable:!!this.opts.filters,onSort:(a,c)=>{const h=this.sortKeys.filter(u=>u.col!==t);if(a===null&&h.length)this.applySort(h);else if(c&&a)this.applySort([...h,{col:t,order:a}]);else return this.sort(t,a);this.run("afterColumnSort",t,a)},onFilter:a=>this.setFilter(t,a),onClose:()=>{this.closeMenu=void 0,this.focusInput()}})}toggleCheckboxes(t){const e=[];for(let s=t.start.row;s<=t.end.row;s++){const r=this.mapper.toPhysical(s);for(let i=t.start.col;i<=t.end.col;i++)this.metaAt(r,i).type==="checkbox"&&e.push(this.change(r,i,this.valueAt(r,i)!==!0))}this.applyChanges(e,"edit")}moveActive(t,e,s){if(!this.anchor||!this.selEnd)return;const r=s?this.selEnd:this.anchor;let i=r.row,o=r.col;const l=this.mergeAt(r.row,r.col);l&&!s&&(t>0&&(i=l.row+l.rowspan-1),e>0&&(o=l.col+l.colspan-1)),i+=t,o+=e;const a=e<0?-1:1;for(;this.hiddenCols.has(o)&&o+a>=0&&o+a<this.countCols();)o+=a;this.hiddenCols.has(o)&&(o=r.col),s?this.selectCell(this.anchor.row,this.anchor.col,i,o):this.selectCell(i,o)}jump(t,e,s){const r=s?this.selEnd:this.anchor,i=this.countRows()-1,o=this.countCols()-1,l=(u,d)=>!De(this.getSourceDataAtCell(u,d)),a=(u,d)=>u>=0&&d>=0&&u<=i&&d<=o;let c=r.row,h=r.col;if(a(c+t,h+e)&&l(c,h)&&l(c+t,h+e))for(;a(c+t,h+e)&&l(c+t,h+e);)c+=t,h+=e;else for(c+=t,h+=e;a(c,h)&&!l(c,h)&&a(c+t,h+e);)c+=t,h+=e;c=Math.max(0,Math.min(c,i)),h=Math.max(0,Math.min(h,o)),s?this.selectCell(this.anchor.row,this.anchor.col,c,h):this.selectCell(c,h)}onKeyDown(t){if(this.editing||!this.anchor||!this.selEnd)return;const e=t.ctrlKey||t.metaKey,s=t.key,r=this.metaAt(this.mapper.toPhysical(this.anchor.row),this.anchor.col);if(s==="ContextMenu"||t.shiftKey&&s==="F10"){this.opts.contextMenu&&(t.preventDefault(),this.openContextMenu());return}if(s in Fe){t.preventDefault();const[i,o]=Fe[s];if(t.altKey&&s==="ArrowDown"&&r.type==="dropdown")return this.openEditor();e?this.jump(i,o,t.shiftKey):this.moveActive(i,o,t.shiftKey);return}if(e){const i=s.toLowerCase();if((i==="f"||i==="h")&&this.opts.search)t.preventDefault(),this.openSearch(i==="h");else if(i==="b"||i==="i"||i==="u")t.preventDefault(),this.toggleCellStyle(i==="b"?"bold":i==="i"?"italic":"underline");else if(i==="a")t.preventDefault(),this.selectCell(0,0,this.countRows()-1,this.countCols()-1);else if(i==="z")t.preventDefault(),t.shiftKey?this.redo():this.undo();else if(i==="y")t.preventDefault(),this.redo();else if(i==="d"){t.preventDefault();const o=this.getSelectedRange();o.end.row>o.start.row&&this.autofill({start:o.start,end:{row:o.start.row,col:o.end.col}},{start:{row:o.start.row+1,col:o.start.col},end:o.end})}else s==="Home"?(t.preventDefault(),this.selectCell(0,0)):s==="End"&&(t.preventDefault(),this.selectCell(this.countRows()-1,this.countCols()-1));return}switch(s){case"Tab":t.preventDefault(),this.moveActive(0,t.shiftKey?-1:1,!1);return;case"Enter":case"F2":t.preventDefault(),r.type==="checkbox"?this.toggleCheckboxes(this.getSelectedRange()):this.openEditor();return;case" ":r.type==="checkbox"&&(t.preventDefault(),this.toggleCheckboxes(this.getSelectedRange()));return;case"Delete":case"Backspace":t.preventDefault(),this.clearRange(this.getSelectedRange(),"clear");return;case"Home":t.preventDefault(),this.moveActive(0,-this.selEnd.col,t.shiftKey);return;case"End":t.preventDefault(),this.moveActive(0,this.countCols(),t.shiftKey);return;case"PageDown":case"PageUp":{t.preventDefault();const i=Math.max(1,Math.floor((this.root.clientHeight-this.headerH)/this.rows.defaultSize)-1);this.moveActive(s==="PageDown"?i:-i,0,t.shiftKey);return}}}}const Fe={ArrowUp:[-1,0],ArrowDown:[1,0],ArrowLeft:[0,-1],ArrowRight:[0,1]},Pt=(n,t)=>(n.push(t),t);function Zt(n,t){let e=-1/0;for(const s of n)e=Math.max(e,t(s));return e}function Eo(n){return n?new Intl.NumberFormat(n).format(1.5).includes(","):!1}function js(n,t,e,s){const r=t+e;return n>=t&&n<r?s>t?n+(s-r):n-(t-s):s>r&&n>=r&&n<s?n-e:s<t&&n>=s&&n<t?n+e:n}const Gt=(n,t,e)=>n<t?n:e>0?n+e:n<t-e?-1:n+e;function Dt(n,t){const e=new Map;for(const[s,r]of n){const i=t(s);i>=0&&e.set(i,r)}return e}const De=n=>n==null||n==="",Ys=(n,t)=>({start:{row:Math.min(n.start.row,t.start.row),col:Math.min(n.start.col,t.start.col)},end:{row:Math.max(n.end.row,t.end.row),col:Math.max(n.end.col,t.end.col)}});function bt(n,t,e,s,r){const i=n.style;i.left=`${t}px`,i.top=`${e}px`,i.width=`${s}px`,i.height=`${r}px`}const Mo=n=>typeof requestAnimationFrame=="function"?requestAnimationFrame(n):setTimeout(n,16),ko=n=>{n&&(typeof cancelAnimationFrame=="function"?cancelAnimationFrame(n):clearTimeout(n))};exports.CSV_MIME=zn;exports.CellError=ct;exports.CenituGrid=So;exports.FormulaEngine=ut;exports.FormulaSyntaxError=W;exports.MAX_COLS=16384;exports.MAX_ROWS=1048576;exports.ObjectBinding=ae;exports.RangeValue=z;exports.SHEET_SPAN=17179869184;exports.XLSX_MIME=Hn;exports.ZipReader=Wn;exports.cellKey=O;exports.columnIndex=se;exports.columnLabel=zt;exports.crc32=he;exports.dateCodeFromPattern=Dn;exports.dateToSerial=Tt;exports.downloadBlob=He;exports.enUS=je;exports.formatDateCode=$n;exports.formatSerialDate=ts;exports.getRegisteredFunctionNames=sr;exports.inverseMove=En;exports.isDateFormat=ce;exports.isError=w;exports.isFormula=V;exports.isObjectData=Rn;exports.keyToAddress=Ne;exports.normalizeRange=Ks;exports.numberFormatFromMeta=Nn;exports.parseA1=Ye;exports.parseDateString=ie;exports.parseFormula=Oe;exports.pxToColWidth=Vn;exports.quoteSheetName=qs;exports.rangeContains=Gn;exports.readXLSX=jn;exports.registerFunction=b;exports.sanitizeSheetNames=_n;exports.serialToDate=gt;exports.setClock=lr;exports.setRandom=ar;exports.toA1=$e;exports.toCSV=Ln;exports.toXLSX=Ei;exports.toXLSXCompressed=Xn;exports.trTR=co;exports.unparse=Qt;exports.unregisterFunction=er;exports.workbookEngine=Qi;exports.xlsxParts=as;exports.zipDeflate=Pn;exports.zipStore=Un;