@grid-is/agent-tools 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,167 +1,3 @@
1
- import{C as e,_ as t,a as n,b as r,d as i,f as a,h as o,i as s,m as c,o as l,p as u,r as d,s as f,t as p,u as m,w as h}from"./dist-BJH7vBTb.js";import{McpServer as g}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as _}from"@modelcontextprotocol/sdk/server/stdio.js";import{existsSync as v,readFileSync as y,readdirSync as b,writeFileSync as ee}from"node:fs";import{basename as te,join as ne,resolve as re}from"node:path";import{fileURLToPath as ie}from"node:url";import{Cell as ae,CellVertexId as oe,FormulaError as x,Matrix as se,Model as ce,NameVertexId as le,RangeVertexId as ue,Reference as S,ValueSnapshot as de,a1ToRowColumn as fe,colFromOffs as pe,describeWorkbook as me,parseReference as he,unbox as ge,vertexIdToCell as _e,vertexIdToReference as ve}from"@grid-is/apiary";import{z as C}from"zod";var w=`operator`,ye=`operator-trim`,be=`bool`,xe=`error`,Se=`number`,Ce=`func`,we=`newline`,Te=`whitespace`,Ee=`string`,T=`context_quote`,E=`context`,D=`range`,O=`range_beam`,k=`range_ternary`,A=`range_named`,De=`structured`,j=`cell`,Oe=`fx_prefix`,ke=`unknown`,Ae=`UnaryExpression`,je=`BinaryExpression`,Me=`ReferenceIdentifier`,Ne=`Literal`,Pe=`ErrorLiteral`,Fe=`CallExpression`,Ie=`LambdaExpression`,Le=`LetExpression`,Re=`ArrayExpression`,ze=`Identifier`,Be=`LetDeclarator`,Ve=2**14-1,He=2**20-1,Ue=`$`,We=[[j,`:`,j],[j,`.:`,j],[j,`:.`,j],[j,`.:.`,j],[D],[O],[k],[E,`!`,j,`:`,j],[E,`!`,j,`.:`,j],[E,`!`,j,`:.`,j],[E,`!`,j,`.:.`,j],[E,`!`,j],[E,`!`,D],[E,`!`,O],[E,`!`,k],[T,`!`,j,`:`,j],[T,`!`,j,`.:`,j],[T,`!`,j,`:.`,j],[T,`!`,j,`.:.`,j],[T,`!`,j],[T,`!`,D],[T,`!`,O],[T,`!`,k],[A],[E,`!`,A],[T,`!`,A],[De],[A,De],[E,`!`,A,De],[T,`!`,A,De]],Ge={};function Ke(e,t){if(e.length){let n=e[0];t[n]||(t[n]={}),Ke(e.slice(1),t[n])}else t[Ue]=!0}We.forEach(e=>Ke(e.concat().reverse(),Ge));var qe=(e,t,n,r=0)=>{let i=r,a=t,o=e.length-r;for(;i<=o;){let t=e[n-i];if(t){let e=t.value,n=t.type===w?e:t.type;if(n===D&&!e.includes(`:`)&&(n=j),n in a){a=a[n],i+=1;continue}}return a[Ue]?i:0}};function Je(e){let t=[];for(let n=e.length-1;n>=0;n--){let r=e[n],i=r.type;if(i===D||i===O||i===k||i===A||i===De){let t=qe(e,Ge,n);if(t>1){r={...r,value:``};let i=n-t+1;for(let t=i;t<=n;t++)r.value+=e[t].value;r.loc&&e[i].loc&&(r.loc[0]=e[i].loc[0]),n-=t-1}}t[t.length]=r}return t.reverse()}var Ye=/#(?:NAME\?|FIELD!|CALC!|VALUE!|REF!|DIV\/0!|NULL!|NUM!|N\/A|GETTING_DATA\b|SPILL!|UNKNOWN!|SYNTAX\?|ERROR!|CONNECT!|BLOCKED!|EXTERNAL!)/iy,Xe=35;function Ze(e,t){if(e.charCodeAt(t)===Xe){Ye.lastIndex=t;let n=Ye.exec(e);if(n)return{type:xe,value:n[0]}}}var Qe=46,$e=58;function et(e,t){let n=e.charCodeAt(t);if(n===Qe||n===$e){let r=e.charCodeAt(t+1);if(n!==r){if(r===$e)return{type:ye,value:e.slice(t,t+(e.charCodeAt(t+2)===Qe?3:2))};if(r===Qe)return{type:ye,value:e.slice(t,t+2)}}}}function tt(e,t){let n=e.charCodeAt(t),r=e.charCodeAt(t+1);if(n===60&&r===61||n===62&&r===61||n===60&&r===62)return{type:w,value:e.slice(t,t+2)};if(n===123||n===125||n===33||n===35||n===37||n===38||n>=40&&n<=45||n===47||n>=58&&n<=62||n===64||n===94)return{type:w,value:e[t]}}function nt(e){return e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===95||e===92||e===40||e===46||e===63||e>160}function rt(e,t){let n=e.charCodeAt(t);if(n===84||n===116){let n=e.charCodeAt(t+1);if(n===82||n===114){let n=e.charCodeAt(t+2);if(n===85||n===117){let n=e.charCodeAt(t+3);if((n===69||n===101)&&!nt(e.charCodeAt(t+4)))return{type:be,value:e.slice(t,t+4)}}}}if(n===70||n===102){let n=e.charCodeAt(t+1);if(n===65||n===97){let n=e.charCodeAt(t+2);if(n===76||n===108){let n=e.charCodeAt(t+3);if(n===83||n===115){let n=e.charCodeAt(t+4);if((n===69||n===101)&&!nt(e.charCodeAt(t+5)))return{type:be,value:e.slice(t,t+5)}}}}}}function it(e,t){let n=t;for(;e.charCodeAt(t)===10;)t++;if(t!==n)return{type:we,value:e.slice(n,t)}}function at(e){return e===9||e===11||e===12||e===13||e===32||e===160||e===5760||e===8232||e===8233||e===8239||e===8287||e===12288||e===65279||e>=8192&&e<=8202}function ot(e,t){let n=t;for(;at(e.charCodeAt(t));)t++;if(t!==n)return{type:Te,value:e.slice(n,t)}}var st=34;function ct(e,t){let n=t;if(e.charCodeAt(t)===st){for(t++;t<e.length;){if(e.charCodeAt(t)===st&&(t++,e.charCodeAt(t)!==st))return{type:Ee,value:e.slice(n,t)};t++}return{type:Ee,value:e.slice(n,t),unterminated:!0}}}var lt=39,ut=91,dt=93,ft=33;function pt(e,t,n){let r=e.charCodeAt(t),i,a;if(r===lt){let r=t;for(t++;t<e.length;){let o=e.charCodeAt(t);if(o===ut){if(i)return;i=t}else if(o===dt){if(a)return;a=t}else if(o===lt&&(t++,e.charCodeAt(t)!==lt)){let o=i==null&&a==null;return n.xlsx&&i===r+1&&a===t-2&&(o=!0),i>=r+1&&a<t-2&&a>i+1&&(o=!0),o&&e.charCodeAt(t)===ft?{type:T,value:e.slice(r,t)}:void 0}t++}}}function mt(e,t,n){let r=e.charCodeAt(t),i,a;if(r!==lt&&r!==ft){let r=t;for(;t<e.length;){let o=e.charCodeAt(t);if(o===ut){if(i)return;i=t}else if(o===dt){if(a)return;a=t}else if(o===ft){let o=i==null&&a==null;if(n.xlsx&&i===r&&a===t-1&&(o=!0),i>=r&&a<t-1&&a>i+1&&(o=!0),o)return{type:E,value:e.slice(r,t)}}else if((i==null||a!=null)&&!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===46||o===95||o===161||o===164||o===167||o===168||o===170||o===173||o>=175))return;t++}}}var ht=46,gt=58;function _t(e,t){let n=e.charCodeAt(t);if(n===ht){if(e.charCodeAt(t+1)===gt)return e.charCodeAt(t+2)===ht?3:2}else if(n===gt)return e.charCodeAt(t+1)===ht?2:1;return 0}function vt(e,t){let n=e.charCodeAt(t);return!(n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===95||n===40||n>160)}function yt(e,t){let n=e.charCodeAt(t);return!(n>=65&&n<=90||n>=97&&n<=122||n>=48&&n<=57||n===95||n===40||n===36||n===46||n===33)}function bt(e,t){let n=t;e.charCodeAt(t)===36&&t++;let r=t+3,i=0;do{let n=e.charCodeAt(t);if(n>=65&&n<=90)i=26*i+n-64,t++;else if(n>=97&&n<=122)i=26*i+n-96,t++;else break}while(t<r&&t<e.length);return i&&i<=Ve+1?t-n:0}function xt(e,t){let n=t;e.charCodeAt(t)===36&&t++;let r=t+7,i=0,a=e.charCodeAt(t);if(a>=49&&a<=57){i=i*10+a-48,t++;do if(a=e.charCodeAt(t),a>=48&&a<=57)i=i*10+a-48,t++;else break;while(t<r&&t<e.length)}return i&&i<=He+1?t-n:0}function St(e,t,n){let r=t,i=bt(e,r),a=0,o=0;if(i){r+=i;let s=xt(e,r);r+=s;let c=_t(e,r),l=r;if(c){if(r+=c,a=bt(e,r),r+=a,o=xt(e,r),r+=o,s&&o&&a){if(vt(e,r)&&n.mergeRefs)return{type:D,value:e.slice(t,r)}}else if(!s&&!o){if(vt(e,r))return{type:O,value:e.slice(t,r)}}else if(n.allowTernary&&(o||a)&&yt(e,r))return{type:k,value:e.slice(t,r)}}if(s&&vt(e,l)&&e.charCodeAt(l)!==33)return{type:D,value:e.slice(t,l)}}else{let i=xt(e,r);if(i){r+=i;let s=_t(e,r);if(s){if(r+=s,a=bt(e,r),a&&(r+=a),o=xt(e,r),r+=o,a&&o&&n.allowTernary&&yt(e,r))return{type:k,value:e.slice(t,r)};if(!a&&o&&vt(e,r))return{type:O,value:e.slice(t,r)}}}}}var Ct=91,wt=93,Tt=82,Et=114,Dt=67,Ot=99,kt=43,At=45,jt=33;function Mt(e,t,n=!1){let r=t,i=e.charCodeAt(t);if(n?i===Tt||i===Et:i===Dt||i===Ot){t++;let i=0,a=0,o=e.length,s=e.charCodeAt(t),c,l=1,u=s===Ct;if(u)o=Math.min(o,t+(n?8:6)),t++,c=e.charCodeAt(t),(c===kt||c===At)&&(t++,o++,l=c===At?-1:1);else if(s<49||s>57||isNaN(s))return 1;do{let n=e.charCodeAt(t);if(n>=48&&n<=57)a=a*10+n-48,i++,t++;else break}while(t<o);let d=n?He:Ve;return u?e.charCodeAt(t)===wt?(t++,a*=l,i&&-d<=a&&a<=d?t-r:0):0:i&&a<=d+1?t-r:0}return 0}function Nt(e,t,n){let r=t,i=Mt(e,r,!0);r+=i;let a=Mt(e,r);if(r+=a,(a||i)&&e.charCodeAt(r)!==jt){let o=_t(e,r),s=r;if(o){r+=o;let s=Mt(e,r,!0);r+=s;let c=Mt(e,r);if(r+=c,i&&!a&&s&&c||!i&&a&&s&&c||i&&a&&s&&!c||i&&a&&!s&&c){if(n.allowTernary&&vt(e,r))return{type:k,value:e.slice(t,r)}}else if((a&&c&&!i&&!s||!a&&!c&&i&&s)&&vt(e,r))return{type:O,value:e.slice(t,r)}}if(vt(e,s))return{type:i&&a?D:O,value:e.slice(t,s)}}}function Pt(e,t,n){return n.r1c1?Nt(e,t,n):St(e,t,n)}var Ft=64,It=93,Lt=91,Rt=58,zt=44,Bt=35,Vt=39,Ht={headers:1,data:2,totals:4,all:8,"this row":16,"@":16},Ut=(...e)=>Object.freeze(e),Wt={0:Ut(),1:Ut(`headers`),2:Ut(`data`),4:Ut(`totals`),8:Ut(`all`),16:Ut(`this row`),3:Ut(`headers`,`data`),6:Ut(`data`,`totals`)};function Gt(e,t){let n=t;if(e.charCodeAt(n++)===Lt&&e.charCodeAt(n++)===Bt){do{let t=e.charCodeAt(n);if(t>=65&&t<=90||t>=97&&t<=122||t===32)n++;else break}while(n<t+11);if(e.charCodeAt(n++)===It)return n-t}}function Kt(e,t){let n=t;for(;at(e.charCodeAt(n));)n++;return n-t}function qt(e,t,n=!0){let r=t,i=``;if(e.charCodeAt(r)===Lt){r++;let n;do if(n=e.charCodeAt(r),n===Vt)if(r++,n=e.charCodeAt(r),n===Vt||n===Bt||n===Ft||n===Lt||n===It)i+=String.fromCharCode(n),r++;else return;else if(n===Vt||n===Bt||n===Ft||n===Lt)return;else if(n===It)return r++,[e.slice(t,r),i];else i+=String.fromCharCode(n),r++;while(r<e.length)}else if(n){let n;do{if(n=e.charCodeAt(r),n===Vt||n===Bt||n===Ft||n===Lt||n===It||n===Rt)break;i+=String.fromCharCode(n),r++}while(r<e.length);if(r!==t)return[i,i]}}function Jt(e,t=0){let n=[],r=t,i,a=0;if(e.charCodeAt(t)!==Lt)return;if(i=Gt(e,t)){let n=e.slice(t+2,t+i-1);t+=i;let r=Ht[n.toLowerCase()];if(!r)return;a|=r}else if(i=qt(e,t,!1))t+=i[0].length,i[1]&&n.push(i[1]);else{let r=!0;for(t++,t+=Kt(e,t);r&&(i=Gt(e,t));){let n=Ht[e.slice(t+2,t+i-1).toLowerCase()];if(!n)return;a|=n,t+=i,t+=Kt(e,t),r=e.charCodeAt(t)===zt,r&&(t++,t+=Kt(e,t))}if(r&&e.charCodeAt(t)===Ft&&(a|=Ht[`@`],t+=1,r=e.charCodeAt(t)!==It),!Wt[a])return;let o=r&&qt(e,t,!0);if(o){if(t+=o[0].length,n.push(o[1]),e.charCodeAt(t)===Rt){t++;let r=qt(e,t,!0);if(r)t+=r[0].length,n.push(r[1]);else return}r=!1}if(t+=Kt(e,t),r||e.charCodeAt(t)!==It)return;t++}let o=Wt[a];return{columns:n,sections:o&&o.concat(),length:t-r,token:e.slice(r,t)}}var Yt=33;function Xt(e,t){let n=Jt(e,t);if(n&&n.length){let r=n.length;for(;at(e.charCodeAt(t+r));)r++;if(e.charCodeAt(t+r)!==Yt)return{type:De,value:n.token}}}function Zt(e,t){let n=t;do{let n=e.charCodeAt(t);if(n<48||n>57)break;t++}while(t<e.length);return t-n}function Qt(e,t){let n=t,r=Zt(e,t);if(!r)return;if(t+=r,e.charCodeAt(t)===46){t++;let n=Zt(e,t);if(!n)return;t+=n}let i=e.charCodeAt(t);if(i===69||i===101){t++;let n=e.charCodeAt(t);(n===43||n===45)&&t++;let r=Zt(e,t);if(!r)return;t+=r}return{type:Se,value:e.slice(n,t)}}function $t(e,t){let n=t,r=e.charCodeAt(t);if(r>=65&&r<=90||r>=97&&r<=122||r===95||r===92||r>160)t++;else return;let i;do if(i=e.charCodeAt(t),i>=65&&i<=90||i>=97&&i<=122||i>=48&&i<=57||i===95||i===92||i===46||i===63||i>160)t++;else break;while(isFinite(i));let a=t-n;if(a&&a<255)return r===92&&a<3||a===1&&(r===114||r===82||r===99||r===67)?void 0:{type:A,value:e.slice(n,t)}}var en=33;function tn(e,t,n){if(e.charCodeAt(t)===en)return{type:w,value:e[t]};if(!n.r1c1){let n=_t(e,t);if(n)return{type:w,value:e.slice(t,t+n)}}}var nn=91,rn=40,an=33,on=32,sn=new Uint8Array(180-on),cn=1,ln=2,un=4,dn=8,fn=16,pn=32,mn=cn|ln|un,hn=dn|fn|pn,gn=cn|dn|un|pn;for(let e=on;e<180;e++){let t=String.fromCharCode(e),n=/^[a-zA-Z_\\\u00a1-\uffff]$/.test(t),r=/^[a-zA-Z_]$/.test(t),i=/^[a-zA-Z0-9_.\\?\u00a1-\uffff]$/.test(t),a=/^[a-zA-Z0-9_.]$/.test(t),o=/^[a-zA-Z0-9_.¡¤§¨ª\u00ad¯-\uffff]$/.test(t);sn[e-on]=(n?cn:0)|(i?dn:0)|(r?ln:0)|(a?fn:0)|(o?un:0)|(o?pn:0)}function _n(e,t,n,r,i){let a=r-n;return i&&a&&a<255?t===92&&a<3||a===1&&(t===114||t===82||t===99||t===67)?void 0:{type:A,value:e.slice(n,r)}:{type:ke,value:e.slice(n,r)}}function vn(e,t,n){let r=t,i=e.charCodeAt(t),a=i>180?gn:sn[i-on];if(a&un&&!(a&cn)&&!(a&ln)||i===nn)return mt(e,t,n);if(!(a&mn))return;let o=a&cn?1:0,s=a&ln?1:0,c=a&un?1:0;t++;let l;do{l=e.charCodeAt(t);let n=i>180?gn:sn[l-on]??0;if(n&hn)o&&!(n&dn)&&(o=0),s&&!(n&fn)&&(s=0),c&&!(n&pn)&&(c=0);else return l===rn&&s?{type:Ce,value:e.slice(r,t)}:l===an&&c?{type:E,value:e.slice(r,t)}:_n(e,i,r,t,o);t++}while((o||s||c)&&t<e.length);if(r!==t)return _n(e,i,r,t,o)}var yn=[Ze,et,tt,it,ot,ct,Pt,Qt,rt,pt,vn,Xt],bn=[tn,pt,mt,Pt,Xt,$t];function xn(e){return e===`r`||e===`R`||e===`c`||e===`C`}var Sn=/^l(?:ambda|et)$/i,Cn=(e,t)=>e&&e.type===t,wn=e=>e===A||e===Ce,Tn=e=>!Cn(e,w)||e.value===`%`||e.value===`}`||e.value===`)`||e.value===`#`;function En(e,t){let n=0,r=0,i;for(let a of e){let e=a.type;e===w?a.value===`(`?(r++,i.type===Ce&&Sn.test(i.value)&&(n=r)):a.value===`)`&&(r--,r<n&&(n=0)):(n&&e===ke&&xn(a.value)||n&&t&&e===O&&xn(a.value))&&(a.type=A),i=a}return e}function Dn(e,t,n={}){let{withLocation:r=!1,mergeRefs:i=!0,negativeNumbers:a=!0}=n,o={withLocation:r,mergeRefs:i,allowTernary:n.allowTernary??!1,negativeNumbers:a,r1c1:n.r1c1??!1,xlsx:n.xlsx??!1},s=[],c=0,l=0,u=0,d=[],f,p,m,h=e=>{let t=e.type,n=t===ke,i=m&&m.type===ke;m&&(n&&i||n&&wn(m.type)||i&&wn(t))?(m.value+=e.value,m.type=ke,r&&(m.loc[1]=e.loc[1])):(t===ye&&(d.push(s.length),t=ke,e.type=ke),s[s.length]=e,m=e,t!==Te&&t!==we&&(p=f,f=e))};if(e.startsWith(`=`)){let e={type:Oe,value:`=`};r&&(e.loc=[0,1]),c++,h(e)}let g=t.length;for(;c<e.length;){let n=c,i;for(let n=0;n<g;n++)if(i=t[n](e,c,o),i){c+=i.value.length;break}if(i||(i={type:ke,value:e[c]},c++),r&&(i.loc=[n,c]),m&&i.value===`(`&&m.type===Ce&&Sn.test(m.value)&&l++,i.value.length===1&&(i.type===ke||o.r1c1&&i.type===O)&&(u+=+!!xn(i.value)),a&&i.type===Se){let e=m;if(e?.type===w&&e.value===`-`&&(!p||p.type===Oe||!Tn(p))){let e=s.pop();i.value=`-`+i.value,i.loc&&(i.loc[0]=e.loc[0]),f=p,m=s[s.length-1]}}h(i)}u&&l&&En(s,o.r1c1);for(let e of d){let t=s[e-1],n=s[e+1];s[e].type=t?.type===D&&n?.type===D?w:ke}return i?Je(s):s}function On(e,t={}){return Dn(e,yn,{withLocation:t.withLocation??!1,mergeRefs:t.mergeRefs??!0,allowTernary:t.allowTernary??!1,negativeNumbers:t.negativeNumbers??!0,r1c1:t.r1c1??!1,xlsx:!0})}function kn(e){return!!e&&(e.type===D||e.type===O||e.type===k||e.type===De||e.type===A)}function An(e){return!!e&&(e.type===be||e.type===xe||e.type===Se||e.type===Ee)}function jn(e){return!!e&&e.type===xe}function Mn(e){return!!e&&(e.type===Te||e.type===we)}function Nn(e){return!!e&&e.type===Ce}function Pn(e){return!!e&&e.type===w}var Fn=`(END)`,In=`(FUNCTION)`,Ln=`(WHITESPACE)`,Rn=[`ANCHORARRAY`,`CHOOSE`,`DROP`,`IF`,`IFS`,`INDEX`,`INDIRECT`,`LAMBDA`,`LET`,`OFFSET`,`REDUCE`,`SINGLE`,`SWITCH`,`TAKE`,`TRIMRANGE`,`XLOOKUP`],zn={},M,Bn,N,Vn=!1,Hn=e=>Vn||Rn.includes(e.toUpperCase()),Un=(e,t=!1)=>{let n=(e&&e.value)+``;return!!(kn(e)||t&&Pn(e)&&(n===`:`||n===`,`||!n.trim())||Nn(e)&&Hn(n)||jn(e)&&n===`#REF!`)},Wn=e=>!!e&&(e.type===Me||(e.type===Pe||e.type===xe)&&e.value===`#REF!`||e.type===je&&(e.operator===`:`||e.operator===` `||e.operator===`,`)||kn(e)||e.type===Fe&&Hn(e.callee.name));function P(e,t=null){let n=Error(e);throw n.source=Bn.map(e=>e.value).join(``),n.sourceOffset=Bn.slice(0,t??N).reduce((e,t)=>e+t.value.length,0),n}function Gn(e=!1){let t=N,n;do n=Bn[++t];while(n&&(Mn(n)||Pn(n)&&n.value===`(`));return Un(n,e)}function F(e=null,t=null){if(e&&e!==M.id&&P(`Expected ${e} but got ${M.id}`),Mn(Bn[N])){let e=Wn(t),n=e&&Gn(!1),r=e&&Bn[N+1]&&Bn[N+1].value===`(`;if(!n&&!r)for(;Mn(Bn[N]);)N++}if(N>=Bn.length){M=zn[Fn];return}let n=Bn[N];N+=1,n.unterminated&&P(`Encountered an unterminated token`);let r;return Pn(n)?(r=zn[n.value],r||P(`Unknown operator ${n.value}`)):Mn(n)?r=zn[Ln]:An(n)?r=zn[Ne]:kn(n)?r=zn[Me]:Nn(n)?r=zn[In]:P(`Unexpected ${n.type} token: ${n.value}`),M=Object.create(r),M.type=n.type,M.value=n.value,n.loc&&(M.loc=[...n.loc]),M}function Kn(e){let t=M;F(null,t);let n=t.nud();for(;e<M.lbp;)t=M,F(null,t),n=t.led(n);return n}var qn={nud:()=>P(`Invalid syntax`),led:()=>P(`Missing operator`)};function Jn(e,t=0){let n=zn[e];return n?t>=n.lbp&&(n.lbp=t):(n={...qn},n.id=e,n.value=e,n.lbp=t,zn[e]=n),n}function I(e,t,n){let r=Jn(e,t);return r.led=n||function(e){this.type=je,this.operator=this.value,delete this.value;let n=Kn(t);return this.arguments=[e,n],this.loc&&=[e.loc[0],n.loc[1]],this},r}function Yn(e,t){let n=Jn(e,0);return n.lbp=70,n.led=t||function(e){return this.type=Ae,this.operator=this.value,delete this.value,this.arguments=[e],this.loc&&(this.loc[0]=e.loc[0]),this},n}function Xn(e,t){let n=Jn(e);return n.nud=t||function(){this.type=Ae,this.operator=this.value,delete this.value;let e=Kn(70);return this.arguments=[e],this.loc&&(this.loc[1]=e.loc[1]),this},n}function Zn(e,t){return I(e,t,function(n){Wn(n)||P(`Unexpected ${e} operator`);let r=Kn(t);return Wn(r)||P(`Unexpected ${M.type} following ${this.id}`),this.type=je,this.operator=this.value.trim()?this.value:` `,delete this.value,this.arguments=[n,r],this.loc&&=[n.loc[0],r.loc[1]],this})}Jn(Fn),Zn(`:`,80);var Qn=Zn(`,`,80);Zn(Ln,80);var L=e=>{let t=Qn.lbp>0;return e!=null&&(Qn.lbp=e?80:0),t};Yn(`%`),Yn(`#`,function(e){return Wn(e)||P(`# expects a reference`),this.type=Ae,this.operator=this.value,delete this.value,this.arguments=[e],this}),Xn(`+`),Xn(`-`),Xn(`@`),I(`^`,50),I(`*`,40),I(`/`,40),I(`+`,30),I(`-`,30),I(`&`,20),I(`=`,10),I(`<`,10),I(`>`,10),I(`<=`,10),I(`>=`,10),I(`<>`,10),Jn(Ne).nud=function(){let{type:e,value:t}=this;if(this.type=Ne,this.raw=t,e===Se)this.value=+t;else if(e===be)this.value=t.toUpperCase()===`TRUE`;else if(e===xe)this.type=Pe,this.value=t.toUpperCase();else if(e===Ee)this.value=t.slice(1,-1).replace(/""/g,`"`);else throw Error(`Unsupported literal type: `+e);return this},Jn(Me).nud=function(){return this.type===A?this.kind=`name`:this.type===De?this.kind=`table`:this.type===O?this.kind=`beam`:this.kind=`range`,this.type=Me,this},Jn(`)`),Xn(`(`,function(){let e=L(!0),t=Kn(0);return F(`)`,t),L(e),t}),Jn(In).nud=function(){return this},I(`(`,90,function(e){let t={type:ze,name:e.value};e.id!==In&&(e.type===Ie||e.type===Fe||e.type===Le||e.type===Me||e.type===Ae&&e.value===`#`||e.type===Pe&&e.value===`#REF!`?t=e:P(`Unexpected call`,N-1));let n=e.value.toLowerCase();if(n===`lambda`)return $n.call(this,e);if(n===`let`)return er.call(this,e);let r=[],i=!1;if(M.id!==`)`){let e=L(!1);for(;M.id!==`)`;)if(Mn(M)&&F(),M.id===`,`)r.push(null),i=!0,F();else{let e=Kn(0);r.push(e),i=!1,M.id===`,`&&(F(`,`),i=!0)}L(e)}i&&r.push(null);let a=M;return delete this.value,this.type=Fe,this.callee=t,e.loc&&(this.callee.loc=[...e.loc]),this.arguments=r,e.loc&&(this.loc=[e.loc[0],a.loc[1]]),F(`)`,this),this});function $n(e){let t=[],n={},r,i=!1,a=L(!1);if(M.id!==`)`)for(;!i;){Mn(M)&&F();let e=N,a=Kn(0);if(M.id===`,`){if(a.type===Me&&a.kind===`name`){let e=a.value.toLowerCase();e in n&&P(`Duplicate name: `+a.value),n[e]=1;let r={type:ze,name:a.value};a.loc&&(r.loc=a.loc),t.push(r)}else N=e,P(`LAMBDA argument is not a name`);F(`,`)}else r=a,i=!0}return L(a),delete this.value,this.type=Ie,this.params=t,this.body=r||null,e.loc&&(this.loc=[e.loc[0],M.loc[1]]),F(`)`,this),this}function er(e){let t=[],n=[],r={},i,a=0,o=(e,o)=>{if(i&&P(`Unexpected argument following calculation`),o&&a>=2)i=e;else if(a%2)n.push(e);else if(e&&e.type===Me&&e.kind===`name`){let n=e.value.toLowerCase();n in r&&P(`Duplicate name: `+e.value),r[n]=1,t.push({type:ze,name:e.value,loc:e.loc})}else a>=2?i=e:P(`Argument is not a name`);a++},s=L(!1),c=!1;if(M.id!==`)`){for(;M.id!==`)`;)Mn(M)&&F(),M.id===`,`?(o(null),c=!0,F()):(o(Kn(0),M.id!==`,`),c=!1,M.id===`,`&&(F(`,`),c=!0));L(s)}c&&o(null,!0),i===void 0&&P(`Unexpected end of arguments`),L(s),delete this.value,this.type=Le,this.declarations=[],t.length||P(`Unexpected end of arguments`);for(let e=0;e<t.length;e++){let r={type:Be,id:t[e],init:n[e],loc:t[e].loc&&[t[e].loc[0],n[e].loc[1]]};this.declarations.push(r)}return this.body=i,e.loc&&(this.loc=[e.loc[0],M.loc[1]]),F(`)`,this),this}Jn(`}`),Jn(`;`),Xn(`{`,function(){M.id===`}`&&P(`Unexpected empty array`);let e=[],t=!1,n=[e],r=L(!1);for(;!t;)Mn(M)&&F(),An(M)?(e.push(zn[Ne].nud.call(M)),F()):P(`Unexpected ${M.type} in array: ${M.value}`),M.id===`,`?F(`,`):M.id===`;`?(F(`;`),e=[],n.push(e)):t=!0;let i=M;return F(`}`),L(r),this.type=Re,this.elements=n,this.loc&&(this.loc[1]=i.loc[1]),delete this.value,this});var tr=/[^0-9A-Za-z._¡¤§¨ª\u00ad¯-\uffff]/,nr=/^(R|C|RC|[A-Z]{1,3}\d{1,7})$/i;function rr(e,t=0){return t||e&&(tr.test(e)||nr.test(e)||/^\d/.test(e))?1:0}function ir(e){return`'`+e.replace(/'/g,`''`)+`'`}function ar(e){let t=``,n=0,{workbookName:r,sheetName:i}=e;return r&&(t+=`[`+r+`]`,n+=rr(r)),i&&(t+=i,n+=rr(i)),n&&(t=ir(t)),t&&t+`!`}function or(e){return e===`both`?`.:.`:e===`head`?`.:`:e===`tail`?`:.`:`:`}var sr=(e,t,n)=>Math.min(Math.max(t,e),n);function cr(e,t){return t?String(e+1):e?`[`+e+`]`:``}function lr(e){let{r0:t,c0:n,r1:r,c1:i}=e,{$c0:a,$c1:o,$r0:s,$r1:c}=e,l=t==null,u=n==null,d=r==null,f=i==null,p=or(e.trim),m=!!e.trim;if(t=sr(s?0:-He,t|0,He),n=sr(a?0:-Ve,n|0,Ve),!l&&d&&!u&&f?(r=t,d=!1,i=n,f=!1):(r=sr(c?0:-He,r|0,He),i=sr(o?0:-Ve,i|0,Ve)),t===0&&r>=He&&!u&&!f||l&&d){let e=cr(n,a),t=cr(i,o);return`C`+(e===t&&!m?e:e+p+`C`+t)}if(n===0&&i>=Ve&&!l&&!d||u&&f){let e=cr(t,s),n=cr(r,c);return`R`+(e===n&&!m?e:e+p+`R`+n)}let h=cr(t,s),g=cr(r,c),_=cr(n,a),v=cr(i,o);return l||d||u||f?(l?``:`R`+h)+(u?``:`C`+_)+p+(d?``:`R`+g)+(f?``:`C`+v):h!==g||_!==v?`R`+h+`C`+_+p+`R`+g+`C`+v:`R`+h+`C`+_}function ur(e){return ar(e)+(`name`in e?e.name:lr(e.range))}var dr=36,fr=46,pr=58,mr=97,hr=65,gr=122,_r=90,vr=48,yr=49,br=57;function xr(e,t){let n=e.charCodeAt(t);if(n===fr){if(e.charCodeAt(t+1)===pr)return e.charCodeAt(t+2)===fr?[3,`both`]:[2,`head`]}else if(n===pr)return e.charCodeAt(t+1)===fr?[2,`tail`]:[1,``];return[0,``]}function Sr(e,t){let n=t,r=e.charCodeAt(t)===dr;r&&t++;let i=t+3,a=0;do{let n=e.charCodeAt(t);if(n>=hr&&n<=_r)a=26*a+n-(hr-1),t++;else if(n>=mr&&n<=gr)a=26*a+n-(mr-1),t++;else break}while(t<i&&t<e.length);return a&&a<=Ve+1?[t-n,a-1,r]:[0,0,!1]}function Cr(e,t){let n=t,r=e.charCodeAt(t)===dr;r&&t++;let i=t+7,a=0,o=e.charCodeAt(t);if(o>=yr&&o<=br){a=a*10+o-vr,t++;do if(o=e.charCodeAt(t),o>=vr&&o<=br)a=a*10+o-vr,t++;else break;while(t<i&&t<e.length)}return a&&a<=He+1?[t-n,a-1,r]:[0,0,!1]}function wr(e,t,n,r,i,a,o,s,c){o!=null&&(n==null||n!=null&&o<n)&&([n,o,r,s]=[o,n,s,r]),i!=null&&(e==null||e!=null&&i<e)&&([e,i,t,a]=[i,e,a,t]);let l={top:e,left:n,bottom:i,right:o,$top:t,$left:r,$bottom:a,$right:s};return c&&(l.trim=c),l}function Tr(e,t=!0){let n=0,[r,i,a]=Sr(e,n),o=0,s=!1,c=0,l=!1,u,d;if(r){n+=r;let[f,p,m]=Cr(e,n);n+=f;let[h,g]=xr(e,n);if(h){if(n+=h,[u,o,s]=Sr(e,n),n+=u,[d,c,l]=Cr(e,n),n+=d,f&&d&&u){if(n===e.length)return wr(p,m,i,a,c,l,o,s,g)}else if(!f&&!d){if(n===e.length)return wr(null,!1,i,a,null,!1,o,s,g)}else if(t&&(d||u)&&n===e.length)return f?d?wr(p,m,i,a,c,l,null,!1,g):wr(p,m,i,a,null,!1,o,s,g):wr(null,!1,i,a,c,l,o,s,g)}if(f&&n===e.length)return wr(p,m,i,a,p,m,i,a,g)}else{let[r,i,a]=Cr(e,n);if(r){n+=r;let[f,p]=xr(e,n);if(f){if(n+=f,[u,o,s]=Sr(e,n),n+=u,[d,c,l]=Cr(e,n),n+=d,u&&d&&t){if(n===e.length)return wr(i,a,null,!1,c,l,o,s,p)}else if(!u&&d&&n===e.length)return wr(i,a,null,!1,c,l,null,!1,p)}}}}function Er(e){let t=``;for(let n of e)t+=n.value;return t}function Dr(e){let t={type:e.type,value:e.value};return e.loc&&(t.loc=[e.loc[0],e.loc[1]]),e.unterminated!=null&&(t.unterminated=e.unterminated),typeof e.index==`number`&&(t.index=e.index,typeof e.groupId==`string`&&(t.groupId=e.groupId),typeof e.depth==`number`&&(t.depth=e.depth),typeof e.error==`boolean`&&(t.error=e.error)),t}function Or(e,t=!1){let n=!1,r=``,i=[],a=()=>{r&&i.push(t?r:{value:r,braced:n}),r=``};for(let t=0;t<e.length;t++){let i=e[t];i===`[`?(a(),n=!0):i===`]`?(a(),n=!1):r+=i}return a(),i}function kr(e,t,n){let r=Or(e,!n);if(n){if(r.length>1)t.workbookName=r[r.length-2].value,t.sheetName=r[r.length-1].value;else if(r.length===1){let e=r[0];e.braced?t.workbookName=e.value:t.sheetName=e.value}}else t.context=r}var Ar=e=>e.slice(1,-1).replace(/''/g,`'`),jr=(e,t)=>{let n=e?.value;if(n===`:`||n===`.:`||n===`:.`||n===`.:.`)return t.operator=n,1},Mr=(e,t)=>{if(e?.type===D)return t.r0=e.value,1},Nr=(e,t)=>{if(e?.type===k)return t.r0=e.value,1},Pr=(e,t)=>{if(e?.type===D)return t.r1=e.value,1},Fr=e=>{if(e?.type===w&&e.value===`!`)return 1},Ir=(e,t)=>{if(e?.type===O)return t.r0=e.value,1},Lr=(e,t)=>{if(e.type===De)return t.struct=e.value,1},Rr=(e,t,n)=>{let r=e?.type;if(r===E)return kr(e.value,t,n),1;if(r===T)return kr(Ar(e.value),t,n),1},zr=(e,t)=>{if(e?.type===A)return t.name=e.value,1},Br=[[Nr],[Mr,jr,Pr],[Mr],[Ir],[Rr,Fr,Nr],[Rr,Fr,Mr,jr,Pr],[Rr,Fr,Mr],[Rr,Fr,Ir]],Vr=Br.concat([[zr],[Rr,Fr,zr],[Lr],[zr,Lr],[Rr,Fr,zr,Lr]]);function Hr(e,t={}){let n={withLocation:t.withLocation??!1,mergeRefs:t.mergeRefs??!1,allowTernary:t.allowTernary??!1,allowNamed:t.allowNamed??!0,r1c1:t.r1c1??!1,xlsx:!0},r=Dn(e,bn,n);r.length&&r[0].type===Oe&&r.shift();let i=n.allowNamed?Vr:Br;for(let e of i)if(e.length===r.length){let t={workbookName:``,sheetName:``,r0:``,r1:``,name:``,struct:``,operator:``};if(e.every((e,n)=>e(r[n],t,!0)))return t}}var Ur=/^l(?:ambda|et)$/i,Wr=(e,t,n)=>t==null?null:e?t:t-n,Gr=e=>e.slice(1,-1).replace(/''/g,`'`);function Kr(e){let t=e.lastIndexOf(`!`),n={};return t>-1?(e.startsWith(`'`)?kr(Gr(e.slice(0,t)),n,!0):kr(e.slice(0,t),n,!0),n.range=Tr(e.slice(t+1))):n.range=Tr(e),n}function qr(e,t){let n=Tr(t);if(!n)throw Error(`translateTokensToR1C1 got an invalid anchorCell: `+t);let{top:r,left:i}=n,a=0,o=0,s=0,c=[];for(let t of e){let e=t?.type;if(e===w)if(t.value===`(`){o++;let e=c[c.length-1];e&&e.type===Ce&&Ur.test(e.value)&&(a=o)}else t.value===`)`&&(o--,o<a&&(a=0));if(e===D||e===O||e===k){t=Dr(t);let e=t.value,n=Kr(e);if(n){let e=n.range,o={};o.r0=Wr(e.$top,e.top,r),o.r1=Wr(e.$bottom,e.bottom,r),o.c0=Wr(e.$left,e.left,i),o.c1=Wr(e.$right,e.right,i),o.$r0=e.$top,o.$r1=e.$bottom,o.$c0=e.$left,o.$c1=e.$right,e.trim&&(o.trim=e.trim),n.range=o;let s=ur(n);xn(s)&&a&&(s+=`[0]`),t.value=s}t.loc&&(t.loc[0]+=s,s+=t.value.length-e.length,t.loc[1]+=s)}else s&&t.loc&&(t=Dr(t),t.loc[0]+=s,t.loc[1]+=s);c[c.length]=t}return c}function Jr(e,t,n={}){if(typeof e==`string`)return Er(qr(On(e,{mergeRefs:!1,allowTernary:n.allowTernary??!0}),t));throw Error(`translateFormulaToA1 expects a formula string`)}var Yr=String.fromCharCode;function Xr(e){return(e>=702?Yr(((e-702)/676-0)%26+65):``)+(e>=26?Yr((e/26-1)%26+65):``)+Yr(e%26+65)}var Zr=(e,t,n)=>Math.min(Math.max(t,e),n),R=(e,t)=>(t?`$`:``)+Xr(e),z=(e,t)=>(t?`$`:``)+Qr(e),Qr=e=>String(e+1);function $r(e){let{top:t,left:n,bottom:r,right:i,trim:a}=e,{$left:o,$right:s,$top:c,$bottom:l}=e,u=n==null,d=i==null,f=t==null,p=r==null;t=Zr(0,t|0,He),n=Zr(0,n|0,Ve),!u&&!f&&d&&p?(r=t,i=n):(r=Zr(0,r|0,He),i=Zr(0,i|0,Ve));let m=or(a);return t===0&&r>=He&&!u&&!d&&(!(o&&!u||s&&!d)||n===i)||f&&p?R(n,o)+m+R(i,s):n===0&&i>=Ve&&!f&&!p&&(!(c&&!f||l&&!p)||t===r)||u&&d?z(t,c)+m+z(r,l):!u&&!f&&!d&&p?R(n,o)+z(t,c)+m+R(i,s):!u&&f&&!d&&!p?R(n,o)+z(r,l)+m+R(i,s):!u&&!f&&d&&!p?R(n,o)+z(t,c)+m+z(r,l):u&&!f&&!d&&!p?R(i,s)+z(t,c)+m+z(r,l):i!==n||r!==t||s!==o||l!==c?R(n,o)+z(t,c)+m+R(i,s)+z(r,l):R(n,o)+z(t,c)}function ei(e){return ar(e)+(`name`in e?e.name:$r(e.range))}function ti(e,{allowNamed:t=!0,allowTernary:n=!1}={}){let r=Hr(e,{allowNamed:t,allowTernary:n,r1c1:!1});if(r){if(r.name)return{workbookName:r.workbookName,sheetName:r.sheetName,name:r.name};if(r.r0&&r.r0){let e=Tr(r.r1?r.r0+r.operator+r.r1:r.r0);if(e)return{workbookName:r.workbookName,sheetName:r.sheetName,range:e}}}}Object.freeze({OPERATOR:w,BOOLEAN:be,ERROR:xe,NUMBER:Se,FUNCTION:Ce,NEWLINE:we,WHITESPACE:Te,STRING:Ee,CONTEXT:E,CONTEXT_QUOTE:T,REF_RANGE:D,REF_BEAM:O,REF_TERNARY:k,REF_NAMED:A,REF_STRUCT:De,FX_PREFIX:Oe,UNKNOWN:ke}),Object.freeze({UNARY:Ae,BINARY:je,REFERENCE:Me,LITERAL:Ne,ERROR:Pe,CALL:Fe,ARRAY:Re,IDENTIFIER:ze,LAMBDA:Ie,LET:Le,LET_DECL:Be});var ni={"\n":.28,"\r":.28," ":.28,"\xA0":.28," ":.28,"᠎":0," ":.5," ":1," ":.5," ":1," ":.33," ":.25," ":.16," ":.56," ":.28," ":.2," ":.15,"​":0," ":.16," ":.22," ":1,"":0},ri=/^((?:[a-z\d-]+\s+)*)([\d.]+(%|em|px)|(?:x+-)?large|(?:x+-)?small|medium)(?:\s*\/\s*(normal|[\d.]+(%|px|em)?))?(\s.+)?$/,ii=/\bsmall-caps\b/,ai=/\b(?:italic|oblique)\b/,oi=/\bbold(?:er)?\b/,si=16,ci=13.3333333,li=.01*si,ui={"xx-small":9,"x-small":10,smaller:13.3333,small:13,medium:16,large:18,larger:19.2,"x-large":24,"xx-large":32},di=new Map;function fi(e){if(di.has(e))return di.get(e);let t=ri.exec(e);if(!t)return{};let n=(t[6]||``).trim(),r=ui[t[2]]||parseFloat(t[2]);t[3]===`%`?r*=li:t[3]===`em`?r*=si:t[3]===`pt`&&(r*=ci);let i;i=t[4]===`normal`||t[4]===`inherit`||!t[4]?Math.round(7/6*r):!t[5]||t[5]===`em`?parseFloat(t[4]||``)*r:t[5]===`pt`?parseFloat(t[4]||``)*ci:t[5]===`%`?r*.01:parseFloat(t[4]||``);let a=ii.test(t[1])?`small-caps`:`normal`,o=ai.test(t[1])?`italic`:`normal`,s=400;if(oi.test(t[1]))s=700;else{let e=/\b(\d+)\b/.exec(t[1]),n=e?parseInt(e[1],10):400;s=n>=100&&n!==400?n:400}let c={family:n,size:r,height:i??7/6*r,weight:s,variant:a,style:o};return di.set(e,c),c}function pi(e,t){let n=``;if(e.style&&e.style!==`normal`&&(n+=e.style),e.variant&&e.variant!==`normal`&&(n+=(n?` `:``)+e.variant),e.weight&&e.weight!==400&&(n+=n?` `:``,e.weight===700?n+=`bold`:n+=e.weight),e.size){let r=e.size;!t&&e.sizeAdjust&&e.sizeAdjust!==1&&(r*=e.sizeAdjust),n+=(n?` `:``)+r+`px`,e.height!==e.size&&(n+=`/`+e.height+`px`)}return e.family&&(n+=(n?` `:``)+e.family),t&&(n+=`::`+e.baseline),t&&(n+=`::`+e.color),t&&(n+=`::`+e.tracking),t&&(n+=`::`+(e.sizeAdjust??``)),n}var mi=fi(`12px/14px sans-serif`),hi={trim:!0,collapse:!0},gi={};function _i(){return(e,t)=>{let n=typeof t==`string`?fi(t):t,r=n.size??12;return n.family&&/\bmonospace\b/.test(n.family)?r*=.6:(r*=.45,n.weight&&n.weight>400&&(r*=1.18)),e.length*r}}function vi(e){if(e&&e.getContext){let t=e.getContext(`2d`);if(t&&typeof t.measureText==`function`)return(e,n)=>(t.font=String(n),t.measureText(e).width)}}function yi(){let e=typeof document<`u`?document:null;return typeof OffscreenCanvas<`u`&&new OffscreenCanvas(100,100)||e&&e.createElement&&e.createElement(`canvas`)||null}var bi=vi(yi())||_i();function xi(e){if(e==null)bi=vi(yi())||_i();else if(e)bi=vi(e)||_i();else throw Error(`setMeasureCanvas argument is not a canvas or null`)}function Si(e,t,n=hi){t=typeof t==`string`?fi(t):{...mi,...t};let r=Object.assign({},hi,n),i=String(e);if(!i)return 0;if(i in ni){let e=pi(t,!0)+`/`+i;return e in gi||(gi[e]=bi(`_${i}_`,pi(t))-bi(`__`,pi(t))),gi[e]}!r.trim||!r.collapse?i=i.replace(/\n/g,` `):r.trim?i=i.replace(/\n/g,` `).trim():r.collapse&&(i=i.replace(/\s+/g,` `));let a=typeof e==`string`?0:e.font.tracking||0;return bi(i,pi(t))+(t.size??12)*a}var B=class{value;width;whitespace;font;line;constructor(e=``,t={}){this.value=e,this.font=t,this.width=0}valueOf(){return this.value}toString(){return this.value}toJSON(){let e=this,t={type:`TK`,val:e.value??``};return e.font.style===`italic`&&(t.style=e.font.style),e.font.family&&e.font.family!==`sans-serif`&&(t.font=e.font.family),e.font.weight&&e.font.weight!==400&&(t.weight=e.font.weight),e.font.baseline&&(t[e.font.baseline<0?`sub`:`sup`]=!0),[`href`,`color`,`class`,`target`,`rel`].forEach(n=>{e.font[n]&&(t[n]=e.font[n])}),t}},Ci=class extends B{toJSON(){let e=super.toJSON();return e.type=`BR`,delete e.val,e}},V=class extends B{toJSON(){let e=super.toJSON();return e.type=`NL`,delete e.val,e}},wi=class extends B{toJSON(){let e=super.toJSON();return e.type=`SH`,delete e.val,e}},Ti=/[\r\n\xA0]+/g;function Ei(e,t){return{family:t.family??e.family??`sans-serif`,style:t.style??e.style??`normal`,variant:t.variant??e.variant??`normal`,weight:t.weight??e.weight??400,height:t.height??e.height??14,size:t.size??e.size??12,sizeAdjust:t.sizeAdjust??e.sizeAdjust??void 0,baseline:t.baseline??e.baseline??0,tracking:t.tracking??e.tracking??0,href:t.href??e.href??``,color:t.color??e.color??``,rel:t.rel??e.rel??``,target:t.target??e.target??``,class:t.class??e.class??``}}function Di(e,t,n){let r=e.width,i,a;for(;r+n.width>t&&e.length;)i=e[e.length-1],a=i.width??0,i.width&&i.width>n.width?(i.value=i.value.slice(0,-1),i.width=Si(i,i.font),r+=i.width):e.pop(),r-=a;e[e.length-1]instanceof wi&&e.pop(),i&&(i=e[e.length-1]||i||{},n.font=Object.create(i.font),n.font.href=e.length?i.font.href:void 0,n.font.rel=e.length?i.font.rel:void 0,n.font.target=e.length?i.font.target:void 0,e.push(n))}function Oi(e){return Object.assign([],{height:0,font:e,width:0,hasOverflow:!1,hasLineOverflow:!1})}function ki(e){let t=new B(e.value);return t.width=e.width??0,t.whitespace=e.whitespace,t.font=e.font,t}function Ai(e,t){let n=fi(t.font);if(!e.length)return Oi(n);let r=typeof t.height==`function`?t.height:()=>t.height,i=typeof t.width==`function`?t.width:()=>t.width,a=t.overflowLine,o=t.overflowWrap,s={...n,weight:700},c=n.height??n.size??12,l=isFinite(r())?Math.floor(r()/c):1/0;if(!r()&&!i(0)||!l)return Oi(n);let u=0,d=0,f=0,p=[],m=[],h=!1;for(;u<e.length&&d<l;){let t=e[u],r=Ei(n,t.font);if(t.width=Si(t,r),t.font=r,t.line=d,t.whitespace=t.value in ni,t.value&&=t.value.replace(Ti,` `),!(!f&&t.whitespace||h&&t.whitespace))if(t instanceof V)f=0,m=[],p.push(u+1),d++;else if(t instanceof Ci||t instanceof wi)m.push({index:u,width:f});else if(t.whitespace||f+t.width<i(d))f+=t.width;else if(m.length){let t,r;do{r=!0,t=m.pop();let a=e[t.index],o;a instanceof wi&&(o=Si(`-`,a.font||n),t.width+o>i(d)&&(r=!m.length))}while(!r);p.push(t.index+1),f=0,d++,u=t.index,m=[]}else if(o===`break-word`){let r=i(d);if(f+t.width>r){let i=ki(t);do t.value=t.value.slice(0,-1),t.width=Si(t,t.font||n),f+=t.width;while(t.value&&t.width>r);i.value=i.value.slice(t.value.length),e.splice(u+1,0,new Ci,i)}p.push(u+1),f=0,d++}else f+=t.width;u++,h=t.whitespace}u!==p[p.length-1]&&p.push(u);let g=0,_=0,v=p.map(t=>{let r=g,i;for(;(i=e[r])&&(i.whitespace||!i.value);)r++;let a=t,o=null;for(;a>r&&(i=e[a-1])&&(i.whitespace||!(i.value||i instanceof wi));)i instanceof V&&(o=i),a--;i instanceof wi&&(i.value=`-`,i.width=Si(`-`,i.font||n)),g=t;let s=Object.assign(e.slice(r,a).filter(e=>e.value),{width:0});return o&&s.push(o),s.width=s.reduce((e,t)=>e+(t.width||0),0),s.width>_&&(_=s.width),s}),y=!1;if(a){let e=a===`ellipsis`?`…`:a;v.forEach((t,r)=>{let a=i(r);if(t.width>a){let r=new B(e);r.font=n,r.width=Si(e,s),Di(t,a,r),y=!0}})}let b=!1,ee=t.overflow===`ellipsis`?`…`:t.overflow;if(ee&&u!==e.length){let e=i(v.length-1),t=v[v.length-1],r=new B(ee);r.font=n,r.width=Si(ee,s),Di(t,e,r),b=!0}else b=!1;return Object.assign(v,{height:v.length*c,font:n,width:_,hasOverflow:b,hasLineOverflow:y})}function ji(e){return Math.round(e*1e6)/1e6}var Mi={center:`middle`,right:`end`},Ni={middle:.5,center:.5,bottom:1,end:1},Pi=(e,t)=>!e&&!t||e===t;function Fi(e,t){let n=[],r=fi(t.font),i=r.size??12,a=r.family??`sans-serif`,o=t.align??`left`,s=t.createElement;if(e.length){let c=r.height??7/6*i,l=t.valign,u=typeof t.height==`function`?t.height():t.height,d=typeof t.width==`function`?t.width(0):t.width,f=typeof t.x==`function`?t.x:()=>t.x,p=!isFinite(d)&&e.length===1,m=ji(c/i)??0,h=p?0:ji(c/(i*1.15+(c-i)/2));if(Ni[l]&&isFinite(u)){let t=l===`bottom`?1:.5;h=(h||0)+(u*t-c*e.length*t)/i}let g=o===`justify`,_=0;o===`right`?_=d:o===`center`&&(_=d/2);let v=[],y=`tspan`,b=null,ee=``,te=()=>{if(ee){let e=s(y,b,ee);v.push(e)}y=`tspan`,b=null,ee=``};for(let t=0,r=e.length;t<r;t++){let o=``,c=``,l=0,u=e[t];if(!u.length){n.push(s(`tspan`,{x:f(t),dy:ji(t?m:h)+`em`},`\xA0`));continue}v=[];let ne=0,re=0,ie=``;for(let e=0,t=u.length;e<t;e++){let t=u[e],n=t.font,r=pi(n,!0);if(t.whitespace&&ne++,re+=t.width,e&&!t.font.tracking&&!l&&Pi(r,o)&&Pi(t.font.class,c)&&Pi(ie,t.font.href))ee+=t.value;else{te();let e=(n.size??i)*(n.sizeAdjust??1);ee=t.value,b={fontFamily:n.family!==a&&n.family||null,fontSize:e===i?null:e,fontWeight:n.weight===400?null:n.weight||null,fontStyle:n.style===`normal`?null:n.style||null,fontVariant:n.variant===`normal`?null:n.variant||null,fill:n.color||null,baselineShift:n.baseline?n.baseline*100+`%`:null,className:t.font.class||null,dx:0,href:null,rel:null,target:null},l&&=(b.dx=ji(l),0),t.font.tracking&&(l=e*t.font.tracking),t.font.href&&!ie?(ie=t.font.href,y=`a`,b.href=ie,b.rel=t.font.rel,b.target=t.font.target):ie=``,o=r,c=t.font.class??``}}if(te(),p)n.push(...v);else{let e=null,i=t===r-1||u[u.length-1]instanceof V;g&&u.length>1&&!i&&(e=ji((d-re)/ne)),n.push(s(`tspan`,{wordSpacing:e,x:f(t)+_,dy:ji(t?m:h)+`em`},...v))}}}return s(`text`,{fontFamily:a,fontSize:i,textAnchor:Mi[o]||`start`},...n)}var Ii={middle:.5,center:.5,bottom:1,end:1};function Li(e){return e.color||(e.href?`#00C`:`#000`)}function Ri(e,t,n){if(!e.length)return;n.textBaseline=`middle`;let r=fi(t.font),i=r.size??12,a=r.height??7/6*i,o=t.valign,s=typeof t.height==`function`?t.height():t.height,c=typeof t.width==`function`?t.width(0):t.width,l=typeof t.x==`function`?t.x:()=>t.x,u=t.align,d=u===`justify`,f=a*.5,p=Ii[o];if(p&&isFinite(s)){let t=e.length*a;f+=s*p-t*p}let m;e.forEach((t,r)=>{m=null;let o=l(r),s=r*a+f,p=0,h=0;t.forEach(e=>{e.whitespace&&p++,h+=e.width});let g=0,_=r===e.length-1||t[t.length-1]instanceof V;d&&t.length>1&&!_&&(g=(c-h)/p);for(let e of t){n.font=pi(e.font);let t=e.font,r=t.baseline?i*-t.baseline+i*.15:0;n.fillStyle=Li(t);let a=0;if(u===`right`?a+=c-h:u===`center`?a+=c/2-h/2:u===`justify`&&(e.whitespace||e instanceof V)&&(o+=g),n.fillText(e.value,o+a,s+r),e.font.href){n.beginPath(),n.strokeStyle=n.fillStyle;let t=Math.floor(s+i*.45)+.5;m||=[o+a,t],n.moveTo(...m),n.lineTo(o+a+e.width,t),n.stroke()}else m=null;o+=e.width}})}var zi=Object.prototype.hasOwnProperty,Bi={};function Vi(e){return Bi[e]||(Bi[e]=e.replace(/([a-z])([A-Z])/g,(e,t,n)=>t+`-`+n.toLowerCase())),Bi[e]}function Hi(e,t){if(Array.isArray(t))t.forEach(t=>Hi(e,t));else if(typeof t==`string`){let n=document.createTextNode(t);e.appendChild(n)}else e.appendChild(t)}function Ui(e,t,...n){if(typeof document>`u`)throw Error(`No document found, cannot create elements`);let r=typeof e==`string`?document.createElementNS(`http://www.w3.org/2000/svg`,e):e;if(t&&r.setAttribute)for(let e in t)zi.call(t,e)&&t[e]!=null&&r.setAttribute(e===`className`?`class`:Vi(e),String(t[e]));return n!=null&&n.length&&n.forEach(e=>{e&&Hi(r,e)}),r}var Wi=/^[\n\r\t\x20\xA0\u2000-\u200B\u205F\u3000]/,Gi=/^[^\n\r\t\u0020\u2000-\u200B\u205F\u3000]{2,}/,Ki=/^[\xA0\u2011\u202F\u2060\uFEFF]/,qi=/^(?:[;\xAD%?…]|,(?!\d))/,Ji=/^[´±°¢£¤$¥\u2212]/,Yi=`'“‘[「【﹝〔<‹«{『((<《`.split(``),Xi=`',,,!!??”]」】》>’»﹞〕〗〉}))』。`.split(``),Zi=e=>{let t=e.charCodeAt(0);return t>=19968&&t<=40959};function Qi(e){e||=``;let t=[],n=e.charAt(0),r=``,i=``,a=0;for(let o=1,s=e.length;o<s;o++){r=e.charAt(o),i=e.charAt(o+1);let s=Wi.test(n),c=Wi.test(r),l=c||s||Zi(n)||Zi(r);if((Ji.test(r)&&!Ki.test(n)||qi.test(n+i)&&!Ki.test(r))&&(l=!0),l&&(Xi.includes(r)||Yi.includes(n))&&(l=!1),n===`-`||n===`‐`||n===`–`||n===`—`){let t=Wi.test(e.charAt(o-2));t&&!c&&(l=!1),!t&&Gi.test(r+i)&&(l=!0)}if(l){let n=e.slice(a,o);n.endsWith(`­`)?(t.push(new B(n.slice(0,-1))),t.push(new wi)):(t.push(new B(n)),t.push(new Ci)),a=o}n=r}return t.push(new B(e.slice(a))),t}var $i={nbsp:`\xA0`,iexcl:`¡`,cent:`¢`,pound:`£`,curren:`¤`,yen:`¥`,brvbar:`¦`,sect:`§`,uml:`¨`,copy:`©`,ordf:`ª`,laquo:`«`,not:`¬`,shy:`­`,reg:`®`,macr:`¯`,deg:`°`,plusmn:`±`,sup2:`²`,sup3:`³`,acute:`´`,micro:`µ`,para:`¶`,middot:`·`,cedil:`¸`,sup1:`¹`,ordm:`º`,raquo:`»`,frac14:`¼`,frac12:`½`,frac34:`¾`,iquest:`¿`,Agrave:`À`,Aacute:`Á`,Acirc:`Â`,Atilde:`Ã`,Auml:`Ä`,Aring:`Å`,AElig:`Æ`,Ccedil:`Ç`,Egrave:`È`,Eacute:`É`,Ecirc:`Ê`,Euml:`Ë`,Igrave:`Ì`,Iacute:`Í`,Icirc:`Î`,Iuml:`Ï`,ETH:`Ð`,Ntilde:`Ñ`,Ograve:`Ò`,Oacute:`Ó`,Ocirc:`Ô`,Otilde:`Õ`,Ouml:`Ö`,times:`×`,Oslash:`Ø`,Ugrave:`Ù`,Uacute:`Ú`,Ucirc:`Û`,Uuml:`Ü`,Yacute:`Ý`,THORN:`Þ`,szlig:`ß`,agrave:`à`,aacute:`á`,acirc:`â`,atilde:`ã`,auml:`ä`,aring:`å`,aelig:`æ`,ccedil:`ç`,egrave:`è`,eacute:`é`,ecirc:`ê`,euml:`ë`,igrave:`ì`,iacute:`í`,icirc:`î`,iuml:`ï`,eth:`ð`,ntilde:`ñ`,ograve:`ò`,oacute:`ó`,ocirc:`ô`,otilde:`õ`,ouml:`ö`,divide:`÷`,oslash:`ø`,ugrave:`ù`,uacute:`ú`,ucirc:`û`,uuml:`ü`,yacute:`ý`,thorn:`þ`,yuml:`ÿ`,fnof:`ƒ`,Alpha:`Α`,Beta:`Β`,Gamma:`Γ`,Delta:`Δ`,Epsilon:`Ε`,Zeta:`Ζ`,Eta:`Η`,Theta:`Θ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Xi:`Ξ`,Omicron:`Ο`,Pi:`Π`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Upsilon:`Υ`,Phi:`Φ`,Chi:`Χ`,Psi:`Ψ`,Omega:`Ω`,alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,omicron:`ο`,pi:`π`,rho:`ρ`,sigmaf:`ς`,sigma:`σ`,tau:`τ`,upsilon:`υ`,phi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,thetasym:`ϑ`,upsih:`ϒ`,piv:`ϖ`,bull:`•`,hellip:`…`,prime:`′`,Prime:`″`,oline:`‾`,frasl:`⁄`,weierp:`℘`,image:`ℑ`,real:`ℜ`,trade:`™`,alefsym:`ℵ`,larr:`←`,uarr:`↑`,rarr:`→`,darr:`↓`,harr:`↔`,crarr:`↵`,lArr:`⇐`,uArr:`⇑`,rArr:`⇒`,dArr:`⇓`,hArr:`⇔`,forall:`∀`,part:`∂`,exist:`∃`,empty:`∅`,nabla:`∇`,isin:`∈`,notin:`∉`,ni:`∋`,prod:`∏`,sum:`∑`,minus:`−`,lowast:`∗`,radic:`√`,prop:`∝`,infin:`∞`,ang:`∠`,and:`⊥`,or:`⊦`,cap:`∩`,cup:`∪`,int:`∫`,there4:`∴`,sim:`∼`,cong:`≅`,asymp:`≈`,ne:`≠`,equiv:`≡`,le:`≤`,ge:`≥`,sub:`⊂`,sup:`⊃`,nsub:`⊄`,sube:`⊆`,supe:`⊇`,oplus:`⊕`,otimes:`⊗`,perp:`⊥`,sdot:`⋅`,lceil:`⌈`,rceil:`⌉`,lfloor:`⌊`,rfloor:`⌋`,lang:`〈`,rang:`〉`,loz:`◊`,spades:`♠`,clubs:`♣`,hearts:`♥`,diams:`♦`,quot:`"`,amp:`&`,lt:`<`,gt:`>`,OElig:`Œ`,oelig:`œ`,Scaron:`Š`,scaron:`š`,Yuml:`Ÿ`,circ:`ˆ`,tilde:`˜`,ensp:` `,emsp:` `,thinsp:` `,zwnj:`‌`,zwj:`‍`,lrm:`‎`,rlm:`‏`,ndash:`–`,mdash:`—`,lsquo:`‘`,rsquo:`’`,sbquo:`‚`,ldquo:`“`,rdquo:`”`,bdquo:`„`,dagger:`†`,Dagger:`‡`,permil:`‰`,lsaquo:`‹`,rsaquo:`›`},ea=-.3,ta=.45,na=.7,ra={weight:400,style:`normal`,variant:`normal`,baseline:0,tracking:0,href:``},ia=/^[\n\r\x20\u2000-\u200B\u205F\u3000]/,aa=class{tokens;stack;props;constructor(){this.tokens=[],this.stack=[],this.props={...ra}}add_token(e){return e.font=this.props,this.tokens.push(e),e}open_context(){this.stack.push(this.props),this.props=Object.create(this.props)}close_context(){if(!this.stack.length)throw Error(`Unexpected }`);this.props=this.stack.pop()}trimEnd(){let e=this.tokens[this.tokens.length-1];for(;e instanceof V;)this.tokens.pop(),e=this.tokens[this.tokens.length-1]}setProps(e){for(let[t,n]of Object.entries(e))n!=null&&(this.props[t]=n)}maybeLineBreak(e){let t=this.tokens.length;if(t>0&&e&&e>0){let n=t-1;for(;this.tokens[n]&&(this.tokens[n]instanceof Ci||ia.test(this.tokens[n].value));)n--;for(;e&&this.tokens[n]&&this.tokens[n]instanceof V;)n--,e--;for(;e-->0;)this.tokens.push(new V)}}},oa=/^<\/([a-zA-Z0-9]+)([^>]*)>/,sa=/^<([a-zA-Z0-9]+)((?:\s[^=\s/]+(?:\s*=\s*(?:"[^"]+"|'[^']+'|[^>\\s]+))?)+)?\s*(\/?)>(\n*)/,ca=/^<!--(.+?)-->/,la=/&(?:#(\d\d{2,})|#x([\da-fA-F]{2,})|([a-zA-Z][a-zA-Z1-4]{1,8}));/g,ua={b:e=>e.weight=700,strong:e=>e.weight=700,i:e=>e.style=`italic`,em:e=>e.style=`italic`,dfn:e=>e.style=`italic`,cite:e=>e.style=`italic`,code:e=>e.family=`monospace`,kbd:e=>e.family=`monospace`,samp:e=>e.family=`monospace`,var:e=>e.family=`monospace`,tt:e=>e.family=`monospace`,sub:e=>{e.baseline=ea,e.sizeAdjust=na},sup:e=>{e.baseline=ta,e.sizeAdjust=na}},da={div:1,li:1,blockquote:2,h1:2,h2:2,h3:2,h4:2,h5:2,h6:2,ul:2,ol:2,hr:2,p:2};function fa(e){return e.replace(la,function(e,t,n,r){if(t||n){let e=t?10:16;return String.fromCharCode(parseInt(t||n,e))}else if(r in $i)return $i[r];return e})}function pa(e){return e&&e.length>1&&(e.startsWith(`"`)&&e.endsWith(`"`)||e.startsWith(`'`)&&e.endsWith(`'`))?e.slice(1,-1):e}var ma=/^\s*([^=\s&]+)(?:\s*=\s*("[^"]+"|'[^']+'|[^>\s]+))?/;function ha(e){let t,n={};if(e){do if(t=ma.exec(e),t){let r=fa(pa(t[2]||``)).replace(/[ \r\n\t]+/g,` `).trim();if(n[t[1]]=r,e=e.slice(t[0].length),e.length&&/^\S/.test(e[0]))throw Error(`Attribute error`)}while(t&&e.length);if(/\S/.test(e))throw Error(`Attribute error`)}return n}function ga(e){e=String(e||``).trim();let t,n,r=new aa;for(;e.length;){if(t=/^[^<]+/.exec(e))Qi(fa(t[0])).forEach(e=>r.add_token(e));else if(!(t=ca.exec(e)))if(t=oa.exec(e))r.close_context(),r.maybeLineBreak(da[t[1]]);else if(t=sa.exec(e)){let e=t[1];r.maybeLineBreak(da[e]),r.open_context(),ua[e]&&ua[e].call(r,r.props);let i=ha(t[2]);e===`a`&&r.setProps({href:i.href,rel:i.rel,target:i.target}),i.class&&(r.props.class=r.props.class?r.props.class+` `+i.class:i.class),i.style&&(n=/(?:^|\s|;)color\s*:\s*([^;\s"']+)/.exec(i.style),n&&n[1]&&(r.props.color=n[1])),e===`br`&&r.tokens.push(new V)}else t=[e.slice(0,1)],r.add_token(new B(t[0]));e=e.slice(t[0].length)}return r.trimEnd(),r.tokens}var _a={copyright:`©`,textcopyright:`©`,dag:`†`,textdagger:`†`,ddag:`‡`,textdaggerdbl:`‡`,guillemotleft:`«`,guillemotright:`»`,guilsinglleft:`‹`,guilsinglright:`›`,ldots:`…`,dots:`…`,textellipsis:`…`,lq:`‘`,P:`¶`,textparagraph:`¶`,pounds:`£`,textsterling:`£`,quotedblbase:`„`,quotesinglbase:`‚`,rq:`’`,S:`§`,sim:`~`,textasciicircum:`^`,textasciitilde:`˜`,texttildelow:`~`,textasteriskcentered:`*`,textbackslash:`'`,textbar:`|`,textbardbl:`╎`,textbigcircle:`◯`,textbraceleft:`{`,textbraceright:`}`,textbullet:`•`,textdollar:`$`,textemdash:`—`,textendash:`—`,texteuro:`€`,eurosym:`€`,euro:`€`,textexclamdown:`¡`,textgreater:`>`,textless:`<`,textordfeminine:`ª`,textordmasculine:`º`,textperiodcentered:`·`,cdot:`·`,textquestiondown:`¿`,textquotedblleft:`“`,textquotedblright:`”`,textquoteleft:`‘`,textquoteright:`’`,textquotestraightbase:`‚`,textquotestraightdblbase:`„`,textregistered:`®`,textthreequartersemdash:`-`,texttrademark:`™`,texttwelveudash:`-`,textunderscore:`_`,textvisiblespace:`␣`,gets:`←`,textleftarrow:`←`,to:`→`,textrightarrow:`→`,textdegree:`°`,infty:`∞`,triangle:`△`,triangledown:`▽`,blacktriangle:`▲`,blacktriangledown:`▼`,angle:`∠`,sphericalangle:`∢`,aleph:`ℵ`,hbar:`ħ`,imath:`𝚤`,jmath:`𝚥`,ell:`ℓ`,wp:`℘`,Re:`ℜ`,Im:`ℑ`,mho:`℧`,prime:`′`,emptyset:`∅`,nabla:`∇`,surd:`√`,partial:`∂`,top:`⟙`,bot:`⟂`,vdash:`⟝`,dashv:`⟞`,forall:`∀`,exists:`∃`,nexists:`∄`,neg:`¬`,lnot:`¬`,flat:`♭`,natural:`♮`,sharp:`♯`,backslash:`\\`,Box:`□`,Diamond:`♢`,clubsuit:`♣`,diamondsuit:`♦`,heartsuit:`♥`,spadesuit:`♠`,Join:`⨝`,blacksquare:`■`,bigstar:`★`,diagdown:`╲`,diagup:`╱`,blacklozenge:`⧫`,rfloor:`⌋`,lfloor:`⌊`,rceil:`⌉`,lceil:`⌈`,rangle:`⟩`,langle:`⟨`,sum:`∑`,int:`∫`,oint:`∮`,prod:`∏`,coprod:`∏`,bigcap:`∩`,bigcup:`∪`,bigsqcup:`⊔`,bigvee:`∨`,bigwedge:`∧`,bigodot:`⊙`,bigotimes:`⊗`,bigoplus:`⊕`,biguplus:`⊎`,alpha:`α`,beta:`β`,chi:`χ`,delta:`δ`,epsilon:`ε`,eta:`η`,gamma:`γ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,omega:`ω`,phi:`φ`,pi:`π`,psi:`ψ`,rho:`ρ`,sigma:`σ`,tau:`τ`,theta:`θ`,upsilon:`υ`,xi:`ξ`,zeta:`ζ`,Alpha:`Α`,Beta:`Β`,Chi:`Χ`,Delta:`Δ`,Epsilon:`Ε`,Eta:`Η`,Gamma:`Γ`,Iota:`Ι`,Kappa:`Κ`,Lambda:`Λ`,Mu:`Μ`,Nu:`Ν`,Omega:`Ω`,Phi:`Φ`,Pi:`Π`,Psi:`Ψ`,Rho:`Ρ`,Sigma:`Σ`,Tau:`Τ`,Theta:`Θ`,Upsilon:`Υ`,Xi:`Ξ`,Zeta:`Ζ`,aa:`å`,AA:`Å`,ae:`æ`,AE:`Æ`,dh:`ð`,DH:`Ð`,dj:`đ`,DJ:`Đ`,ij:`ij`,IJ:`IJ`,l:`ł`,L:`Ł`,ng:`ŋ`,NG:`Ŋ`,o:`ø`,O:`Ø`,oe:`œ`,OE:`Œ`,ss:`ß`,SS:`SS`,th:`þ`,TH:`Þ`},va=/^(\^|_|\\[^#$%&~_^\\{}()\s]+)(\{)?/,ya=/^%[^\n]+(?:\n|$)/,ba=/^[^#$%&~_^\\{}]+/,xa=/^\\([&{}$%#_])/,Sa=/(?:\\[\\@,!:;-]|-{2,3}|[!?]`|``?|,,|''?|~|<<|>>)/g,Ca={"---":`—`,"--":`–`,"!`":`¡`,"?`":`¿`,"``":`“`,",,":`„`,"''":`”`,"`":`‘`,"'":`’`,"<<":`«`,">>":`»`,"~":`\xA0`,"\\-":`­`,"\\,":` `,"\\;":` `,"\\:":` `,"\\!":` `,"\\@":``,"\\\\":`\\newline{}`},H={bf:e=>e.weight=700,emph:e=>{e.style===`italic`?e.style=`normal`:e.style=`italic`},it:e=>e.style=`italic`,sl:e=>e.style=`italic`,color:(e,t)=>e.color=t,href:(e,t)=>e.href=t,"^":e=>{e.baseline=ta,e.sizeAdjust=na},_:e=>{e.baseline=ea,e.sizeAdjust=na},par:function(){this.tokens.push(new V,new V)},newline:function(){this.tokens.push(new V)},url:function(e,t){this.open_context(),this.props.href=t,this.add_token(new B(t)),this.close_context()}};H.textsuperscript=H[`^`],H.textsubscript=H._,H.textsl=H.sl,H.mathbf=H.bf,H.mathit=H.it,H.textbf=H.bf,H.textit=H.it,H.textcolor=H.color;function wa(e){e=String(e||``).trim();let t=[``];e=e.replace(/\\verb,(.*?),/,(e,n)=>(t.push(n),`\\verb,`+(t.length-1)+`,`)).replace(/\\\\\n/g,()=>`\\\\`).replace(Sa,(e,t,n)=>n.charAt(t-1)===`\\`?e:Ca[e]).replace(/\n\s+/g,e=>e.slice(1).includes(`
2
- `)?`\\par `:e).replace(/\\symbol\{(\d+)\}/,(e,t,n,r)=>r.charAt(n-1)===`\\`?e:String.fromCharCode(1*t)).replace(/(^|[^\\])(\^|_)(\d|[^{]\S*)/g,(e,t,n,r)=>t+n+`{`+r+`}`).replace(/\\verb,(.*?),/,(e,n)=>`\\verb,${t[+n]},`);let n=new aa,r;for(;e.length;){if(r=ba.exec(e))Qi(r[0]).forEach(e=>n.add_token(e));else if(r=xa.exec(e))n.add_token(new B(r[1]));else if(!(r=ya.exec(e))){if(r=/^\{/.exec(e))n.open_context();else if(r=/^\}/.exec(e))n.close_context();else if(!(r=/^\$/.exec(e)))if(r=/^\\verb,([^,]+),/.exec(e))n.add_token(new B(r[1]));else if(r=va.exec(e)){let t=r[1].slice(1)||r[1],i=!!r[2];if(/^(La)?TeX$/i.test(t)){n.open_context(),n.props.family=`serif`;let e;t===`LaTeX`&&(e=n.add_token(new B(`L`)),e.font=Object.create(e.font),e.font.tracking=-.25,e=n.add_token(new B(`A`)),e.font=Object.create(e.font),e.font.sizeAdjust=.7,e.font.baseline=.3,e.font.tracking=-.1),e=n.add_token(new B(`T`)),e.font=Object.create(e.font),e.font.tracking=-.17,e=n.add_token(new B(`E`)),e.font=Object.create(e.font),e.font.baseline=-.22,e.font.tracking=-.13,e=n.add_token(new B(`X`)),n.close_context()}else if(t in _a)n.add_token(new B(_a[t])),i&&n.open_context();else if(t in H){let a=[],o=Math.max(0,H[t].length-1),s;if(o){for(i=!1,e=e.slice(r[0].length-1);o--;)if(s=/^\{([^}]+)\}/.exec(e))a.push(s[1]),e=e.slice(s[0].length);else throw Error(t+` is missing an argument`);r[0]=/^\{/.exec(e)?`{`:``,i=!!r[0]}i&&n.open_context(),H[t].apply(n,[n.props,...a])}else n.add_token(new B(r[1])),i&&n.open_context()}else r=[e.slice(0,1)],n.add_token(new B(r[0]))}e=e.slice(r[0].length)}return n.tokens}var U={overflow:`ellipsis`,overflowWrap:`normal`,overflowLine:``,align:`left`,valign:`top`,width:1/0,height:1/0,x:0,font:`12px/14px sans-serif`},Ta=class e{static createElement=Ui;static defaultparser=Qi;static measureText=Si;static setMeasureCanvas=xi;props;constructor(t){this.props={overflow:t?.overflow??U.overflow,overflowWrap:t?.overflowWrap??U.overflowWrap,overflowLine:t?.overflowLine??U.overflowLine,align:t?.align??U.align,valign:t?.valign??U.valign,width:t?.width??U.width,height:t?.height??U.height,x:t?.x??U.x,font:t?.font??U.font,parser:t?.parser??e.defaultparser,createElement:t?.createElement??e.createElement},t?.parser&&this.parser(t.parser)}linebreak(e){return Ai(this.props.parser(String(e).trim()),this.props)}font(e){return arguments.length?(this.props.font=e??U.font,this):this.props.font||U.font}overflow(e){return arguments.length?(this.props.overflow=e??U.overflow,this):this.props.overflow}overflowLine(e){return arguments.length?(this.props.overflowLine=e??U.overflowLine,this):this.props.overflowLine}overflowWrap(e){if(!arguments.length)return this.props.overflowWrap;let t=String(e).toLowerCase();return this.props.overflowWrap=t===`break-word`?t:U.overflowWrap,this}valign(e){return arguments.length?(this.props.valign=e??U.valign,this):this.props.valign}align(e){return arguments.length?(this.props.align=e??U.align,this):this.props.align}width(e){return arguments.length?(this.props.width=e??U.width,this):this.props.width}height(e){return arguments.length?(this.props.height=e??U.height,this):this.props.height}x(e){return arguments.length?(this.props.x=e??U.x,this):this.props.height}parser(t){return arguments.length?(t===`html`?this.props.parser=ga:t===`text`?this.props.parser=Qi:t===`latex`?this.props.parser=wa:this.props.parser=t??e.defaultparser,this):this.props.parser}createElement(t){return arguments.length?(this.props.createElement=t??e.createElement,this):this.props.createElement}renderSVG(e){return Fi(typeof e==`string`?this.linebreak(e):e,this.props)}renderCanvas(e,t){let n=typeof e==`string`?this.linebreak(e):e;if(t instanceof CanvasRenderingContext2D)Ri(n,this.props,t);else{let e=t.getContext(`2d`);e instanceof CanvasRenderingContext2D&&Ri(n,this.props,e)}}render(e,t){let n=typeof e==`string`?this.linebreak(e):e;return t?this.renderCanvas(n,t):this.renderSVG(n)}},Ea=[`sans-serif`,`serif`,`cursive`,`monospace`,`fantasy`],Da=`Abadi,Arial,Abadi Extra Light,Helvetica Light,Abadi MT Condensed Extra Bold,Abadi MT Condensed Light,Academy Engraved LET,Colonna MT,Academy Engraved LET PLAIN:1.0,Akzidenz Grotesk,Helvetica Neue,AkzidenzGroteskBQ-Ext,Amatic SC,Chalkboard,American Typewriter,Courier,American Typewriter Condensed,American Typewriter Light,Andale Mono,Lucida Console,Andale Mono WT,Angsana New,Times New Roman,Apple Chancery,Bradley Hand ITC,Apple SD Gothic Neo,MS Gothic,Apple SD Gothic Neo Regular,AppleGothic,Century Gothic,Apple Gothic,AppleGothic Regular,AppleMyungio,Aptos,Aptos Display,Aptos Mono,Aptos Narrow,Calibri,Aptos Serif,Century,Arial Nova,Arial Black,Arial Narrow,Arial Rounded,Arial Rounded MT,Arial Rounded MT Bold,Arvo,Roboto Slab,Avant Garde,Avantgarde,Avenir,Museo Sans,Avenir Next,Avenir Next Regular,Avenir Book,Avenir Next Condensed Regular,Bahnschrift,DIN 1451,Baskerville,Big Caslon,Baskerville Old Face,Bauhaus 93,Futura,Beirut,Beirut Regular,Bell MT,Bodoni MT,Berlin Sans FB,Verdana,Bernard MT Condensed,Big Caslon Medium,Bitstream Vera Sans Mono,Consolas,BlinkMacSystemFont,Roboto,Bodoni Moda,Didot,Bodoni,Bodoni 72 Book,Bodoni 72 Oldstyle Book,Bodoni 72 Smallcaps Book,Book Antiqua,Palatino,Bookman Old Style,PT Serif,Tempus Sans ITC,Bradley Hand Bold,Braggadocio,Britannic,Lucida Grande,Britannic Bold,Brush Script,Brush Script MT,Brush Script MT Italic,Cabin,Tahoma,Caladea,Hoefler Text,Carlito,Calibri Light,Carlito Light,Calisto MT,Cambria,Cambria Math,Candara,Segoe,Canela Text,Canela Text Regular,Caveat,CenturyGothic,Century Schoolbook,Comic Sans MS,Chalkboard SE Regular,Chalkboard SE,Chalkduster,Charcoal,Helvetica Inserat,Charter Roman,Chivo,Helvetica,Cochin,Comfortaa,ComicSansMS,Comic Sans MS Bold,Comic Sans Pro,monaco,Constantia,Lucida Bright,Constantina,Cooper Black,Cooper,Copperplate,Copperplate Gothic Light,Copperplate Gothic Bold,Copperplate Light,Corbel,Cordia New,CordiaUPC,Corsiva,Lucida Handwriting,Corsiva Hebrew,Liberation Mono,Courier New,Courier Prime,Curlz MT,Party LET,Damascus,Damascus Regular,David,DecoType Naskh,DecoType Naskh Regular,Dejavu Sans,DejaVu Sans Condensed,DejaVu Sans Mono,Desdemona,Didot LT STD,DIN,DIN Alternate,DIN Alternate Bold,DIN Condensed,DIN Condensed Bold,DM Sans,Domine,Droid Sans,Myriad,Droid Serif,Liberation Serif,Edwardian Script ITC,Savoye LET,Engravers MT,Eurostile,Franklin Gothic,Fira Sans,Footlight MT,Footlight MT Light,Franklin Gothic Medium,ITC Franklin Gothic,Franklin Gothic Book,Frutiger,Frutiger Linotype,Trebuchet MS,Futura Medium,Gabriola,Garamond,EB Garamond,Geneva,Georgia,Georgia Pro,Gigi,Gill Sans,Gill Sans MT,Gill Sans Nova,Gill Sans Condensed,Gill Sans MT Condensed,Gill Sans Nova Cond,Gill Sans MT Ext Condensed Bold,Gill Sans Light,Gill Sans MT Light,Gill Sans Nova Light,Gill Sans Ultra Bold,Gill Sans Nova Ultra Bold,Gloucester MT,Lucida Sans,Gloucester MT Extra Condensed,Gotham Rounded,GothamRounded-Medium,Goudy Old Style,Haettenschweiler,Harrington,Liberation Sans,Helvetica Neue Condensed,Helvetica Neue Condensed Bold,Helvetica Neue Light,Herculanum,Papyrus,Impact,Imprint MT Shadow,Ink Free,Segoe Print,Inter,helvetica,Jokerman,Josefin Sans,futura,Juice ITC,Jumble,Kannada MN,Optima,Kefa,Rockwell Nova,Kefa Regular,Kino MN,Kristen ITC,Latha,Libre Baskerville,Libre Franklin,Lobster,Lora,Lucida Blackletter,Lucidabright,Lucida Calligraphy,Lucida Calligraphy Italic,Lucida Fax,Lucida Fax Regular,Lucida Sans Unicode,Monotype Corsiva,Lucida Handwriting Italic,Lucida Sans Regular,Lucida Sans Typewriter,Lucida Sans Typewriter Regular,Luminari,Marker Felt,Mistral,Marker Felt Thin,Marlett,Matura MT Script Capitals,Zapfino,Menlo,Menlo Regular,Merriweather,Microsoft Himalaya,Microsoft Sans Serif,Modern No. 20,Moderne Fractur,Monaco,Montserrat,Roboto Sans,MS Mincho,MS UI Gothic,Myriad Pro,Neue Haas Grotesk Text Pro,News Gothic MT,Noteworthy,Noteworthy Light,Nunito,Onyx,Open Sans,Segoe UI,Open Sans Medium,Optima Regular,Oswald,Overpass,Pacifico,Palatino Linotype,Party LET Plain,Perpetua,Phosphate,Playfair Display,Poppins,Proxima Nova,Proxima Nova Extrabold,Proxima Nova Light,PT Mono,PT Sans,PT Sans Caption,PT Serif Caption,Publico Text,PublicoText-Roman,Raleway,Roboto Mono,Rockwell Condensed,Rockwell Extra Bold,Rockwell,Rockwell Nova Cond,Rockwell Nova Extra Bold,Rockwell Nova Light,Rubik,Savoye LET Plain:1.0,Script MT,Script MT Bold,Segoe Historic,Segoe Print Bold,Segoe Script,Segoe Script Bold,Segoe Symbol,SignPainter,SignPainter-HouseScript,Skia,Snap ITC,Snell Roundhand,Source Sans Pro,Source Sans Pro Regular,Source Serif Pro,Space Mono,Spectral,Stencil,Symbol,Syncopate,Times,Trattatello,Ubuntu,Univers,Univers Condensed,Univers Light,Verdana Pro,Verdana Pro Black,Verdana Pro Cond,Westminster,OCR-A,Wide Latin,Work Sans`.split(`,`),Oa=[[0,1,0],[2,3,0],[4,null,0],[5,1,0],[6,7,1,8],[8,7,1,6],[9,10,0,9,11],[9,10,0,9,11],[11,10,0,9,9],[12,13,2],[14,15,3],[16,null,3],[17,15,3],[18,19,3,20],[20,19,3,18],[21,22,1],[23,24,2],[25,26,0,27],[27,26,0,25],[28,29,0,30,31],[30,29,0,28,31],[31,29,0,28,30],[32,22,1],[33,1,0],[34,26,0],[35,18,3],[36,37,0],[38,39,1],[1,10,0,40],[40,10,0,1],[41,1,0],[42,1,0],[40,1,0],[43,1,0,44,45],[44,1,0,43,45],[45,1,0,43,44],[46,47,0],[48,29,0,49],[49,29,0,48],[50,51,0,52,53,54],[52,51,0,50,53,54],[53,51,0,50,52,54],[54,51,0,50,52,53],[55,null,0],[56,57,0],[58,59,1],[60,58,1],[61,62,0],[63,null,1,64],[64,null,1,63],[65,66,1],[67,68,0],[69,57,0],[59,22,1],[70,59,1],[71,72,3],[73,74,0],[75,66,1],[66,76,1,77,78,79,80],[77,76,1,66,78,79,80],[78,76,1,66,77,79,80],[79,76,1,66,77,78,80],[80,76,1,66,77,78,79],[81,82,1],[83,84,1],[24,85,2,86],[86,85,2,24],[87,null,0],[88,89,0,90],[90,89,0,88],[91,null,2,92,93],[92,null,2,91,93],[93,null,2,91,92],[94,95,0],[96,97,1],[37,98,0],[99,100,0],[101,82,1],[102,96,1,103],[103,96,1,102],[104,105,0],[106,81,1,107],[107,81,1,106],[98,104,0],[108,13,2],[39,null,1],[29,28,0,109],[109,28,0,29],[110,39,1],[13,111,2,112,113],[112,111,2,13,113],[113,111,2,13,112],[114,13,2],[115,116,0],[117,null,1],[118,119,0],[120,58,1],[7,6,1],[121,62,0],[111,13,2,122,123,124],[122,13,2,111,123,124],[123,13,2,111,122,124],[124,13,2,111,122,123],[72,125,3],[126,127,1],[128,127,1],[129,null,1,130],[130,null,1,129],[131,132,4],[133,131,4],[132,131,4],[134,132,4],[135,89,0],[136,119,0,137],[137,119,0,136],[138,139,2,140],[140,139,2,138],[15,141,3,142],[142,141,3,15],[143,15,3],[144,145,4],[146,null,0,147],[147,null,0,146],[148,22,1],[149,null,1,150],[150,null,1,149],[151,10,0],[152,68,0],[153,71,3],[154,null,4],[76,97,1,155],[155,97,1,76],[57,56,0,156,157,158],[156,56,0,57,157,158],[157,56,0,57,156,158],[158,56,0,57,156,157],[159,57,0,160],[160,57,0,159],[161,73,0],[162,101,1],[163,164,0],[165,166,1],[167,168,2],[169,null,1],[170,171,0],[172,119,0],[173,null,1,174],[174,null,1,173],[171,30,0,175,176,177],[175,30,0,171,176,177],[176,30,0,171,175,177],[177,30,0,171,175,176],[178,151,0,179],[179,151,0,178],[62,180,0,181],[181,180,0,62],[182,139,2],[183,81,1,184],[184,81,1,183],[185,95,0],[186,22,1,187],[187,22,1,186],[188,null,2],[189,37,0,190,191],[190,37,0,189,191],[191,37,0,189,190],[192,null,0,193,194,195],[193,null,0,192,194,195],[194,null,0,192,193,195],[195,null,0,192,193,194],[196,null,0,197,198],[197,null,0,196,198],[198,null,0,196,197],[199,null,0,200],[200,null,0,199],[201,202,1,203],[203,202,1,201],[204,43,0,205],[205,43,0,204],[206,183,1],[207,115,0],[208,144,4],[119,209,0],[116,41,0],[3,null,0],[10,119,0],[210,null,0,211],[211,null,0,210],[212,3,0],[213,214,4],[97,166,1],[215,207,0],[216,6,1],[217,218,2],[219,220,0],[221,145,2],[222,223,0],[224,null,1],[225,111,2],[226,227,0],[228,229,1,230],[230,229,1,228],[231,null,0],[232,218,2],[233,null,0],[141,125,3],[209,1,0],[166,22,0],[234,58,1],[235,171,0],[236,91,2],[237,82,1],[238,null,4],[127,38,1,239],[239,38,1,127],[240,139,2,241],[241,139,2,240],[19,71,3],[242,127,1,243],[243,127,1,242],[89,244,0],[139,245,2,246],[246,245,2,139],[202,185,0,247],[247,185,0,202],[248,19,3,249],[249,19,3,248],[244,202,0],[250,null,4],[251,252,2,253],[253,252,2,251],[254,92,2],[255,256,4],[257,19,0,258],[258,19,0,257],[259,82,1],[260,22,1],[261,10,0],[252,92,2],[262,110,1],[263,238,4],[264,19,3],[245,24,2],[265,266,0],[26,null,0],[267,null,1],[268,null,0],[51,29,0],[164,178,0,269],[269,178,0,164],[270,10,0],[271,171,0],[272,218,4,273],[273,218,4,272],[274,74,0],[275,null,1],[276,277,0],[278,277,0],[227,105,0,279],[279,105,0,227],[280,5,0],[281,119,0],[282,null,2],[82,283,1],[283,183,1],[214,null,4],[284,221,4,145],[145,221,4,284],[285,58,1],[286,62,0],[287,66,1],[288,89,0],[289,265,0],[290,null,0],[291,null,0],[292,18,3],[293,null,0],[294,null,0],[84,null,1],[295,null,1],[296,null,1,297],[297,null,1,296],[298,1,0],[74,119,0,266],[266,119,0,74],[299,72,3],[47,229,0],[300,null,1],[301,null,1],[229,171,1,302],[302,171,1,229],[303,null,1],[304,null,1],[305,null,1],[306,1,0],[168,139,2,307],[307,139,2,168],[308,139,2,309],[309,139,2,308],[310,119,0],[218,218,2,311],[311,218,2,218],[312,111,2,313],[313,111,2,312],[314,null,0],[277,178,0,105],[105,178,0,277],[315,null,2,316],[316,null,2,315],[317,null,0],[318,null,1],[319,168,2],[320,74,0,321],[321,74,0,320],[322,186,1],[323,15,3],[324,22,0],[325,null,1],[326,22,1],[327,62,0],[95,152,0],[85,139,2],[328,22,0],[22,166,1,328],[328,166,1,22],[329,null,4],[180,89,0],[330,37,0],[331,null,0],[332,null,0],[333,null,0],[68,185,0],[334,185,0],[335,null,0],[336,null,0],[337,338,3],[339,null,1],[340,89,0],[256,null,2]].map(e=>({name:Da[e[0]],next:e[1]?Da[e[1]]:null,type:Ea[e[2]],alt:e.slice(3).filter(e=>e!==null).map(e=>Da[e])})),ka=new Map;function Aa(e,t=`sans-serif`){if(!e)return t;let n=ka.get(e);if(n)return n;let r=ja(e);return ka.set(e,r),r}function ja(e){e=e.replace(/\(\w+\)/i,``).trim();let t=``,n=new Set,r=e=>{let i=e&&Oa.find(t=>t.name.toLowerCase()===e.toLowerCase());i&&(t||=i.type,n.add(i.name),i.alt&&i.alt.forEach(e=>n.add(e)),i.next&&!n.has(i.next)&&r(i.next))};return r(e),t&&n.add(t),n.size||n.add(e),Array.from(n).map(e=>/[ ,]/.test(e)?`"`+e+`"`:e).join(`, `)}var W=class e{x;y;width;height;constructor(e,t,n,r){if(!isFinite(e)||!isFinite(t)||!isFinite(n)||!isFinite(r))throw Error(`Invalid Rect coords: x=${e}, y=${t}, w=${n}, h=${r}`);this.x=e,this.y=t,this.width=n,this.height=r}get top(){return this.y}get left(){return this.x}get bottom(){return this.y+this.height}get right(){return this.x+this.width}get size(){return[this.width,this.height]}equals(e){return this.x===e.x&&this.y===e.y&&this.width===e.width&&this.height===e.height}intersects(e){return!(this.x>e.right||this.right<e.x||this.y>e.bottom||this.bottom<e.y)}contains(e){return e.x>=this.x&&e.y>=this.y&&e.right<=this.right&&e.bottom<=this.bottom}resize(t,n){return new e(this.x,this.y,t,n)}translate(t=0,n=0){return new e(this.x+t,this.y+n,this.width,this.height)}getTopEdge(){return[[this.x,this.y],[this.x+this.width,this.y]]}getBottomEdge(){return[[this.x,this.y+this.height],[this.x+this.width,this.y+this.height]]}getLeftEdge(){return[[this.x,this.y],[this.x,this.y+this.height]]}getRightEdge(){return[[this.x+this.width,this.y],[this.x+this.width,this.y+this.height]]}getBorders(){let{x:e,y:t}=this,n=e+this.width,r=t+this.height;return[[[e,t],[n,t],[12,6]],[[n,t],[n,r],[3,6]],[[e,r],[n,r],[9,3]],[[e,t],[e,r],[9,12]]]}};const G=2**14-1,Ma=2**20-1;var Na=class e{range;workbookName;sheetName;constructor(t,n){if(t instanceof e)this.workbookName=t.workbookName||n?.workbookName||``,this.sheetName=t.sheetName||n?.sheetName||``,this.range=Object.assign({},t.range);else if(typeof t==`string`){let e=ti(t);if(!e||!(`range`in e)||!e.range)throw Error(`Not a valid reference: ${t}`);this.workbookName=e.workbookName||n?.workbookName||``,this.sheetName=e.sheetName||n?.sheetName||``,this.range={top:e.range.top||0,left:e.range.left||0,bottom:e.range.bottom||e.range.top||0,right:e.range.right||e.range.left||0}}else this.workbookName=n?.workbookName||``,this.sheetName=n?.sheetName||``,this.range=Object.assign({top:0,left:0,right:0,bottom:0},t);let r=this.range;if(r.left<0||r.left>G||r.right<0||r.right>G||r.top<0||r.top>Ma||r.bottom<0||r.bottom>Ma)throw Error(`Not a valid reference: ${String(t)}`)}get left(){return this.range.left}get right(){return this.range.right}get top(){return this.range.top}get bottom(){return this.range.bottom}get height(){return this.range.bottom-this.range.top+1}get width(){return this.range.right-this.range.left+1}toString(){return ei({range:this.range,workbookName:this.workbookName,sheetName:this.sheetName})}};const Pa=65536,Fa=16383,Ia=1048575;function K(e,t){return(e&Fa)*1+(t&Ia)*Pa}function La(e){return[e/1&Fa,e/Pa&Ia]}const Ra={style:`none`,color:`none`},za={style:`hair`,color:`#d8d9e5`};var q=class e{static TOP=`T`;static LEFT=`L`;static BOTTOM=`B`;static RIGHT=`R`;_;constructor(){this._=new Map}clear(){this._.clear()}set(t,n,r){let[i,a]=t;if(n===e.BOTTOM)this.set([i,a+1],e.TOP,r);else if(n===e.RIGHT)this.set([i+1,a],e.LEFT,r);else if(n===e.LEFT||n===e.TOP){let i=K(t[0],t[1]),a=this._.get(i);a||(a={[e.TOP]:Ra,[e.LEFT]:Ra},this._.set(i,a)),r==null||r.style===`none`?a[n]=Ra:a[n]=r}}get(t,n){if(n===e.BOTTOM)return this.get([t[0],t[1]+1],e.TOP);if(n===e.RIGHT)return this.get([t[0]+1,t[1]],e.LEFT);if(n===e.LEFT||n===e.TOP){let e=K(t[0],t[1]),r=this._.get(e);if(r&&r[n])return r[n]}return Ra}isSet(e,t){let n=this.get(e,t).style;return n!==`none`&&n!==`hair`}getJoin(t,n){let r=0;return this.isSet([t,n],e.TOP)&&(r|=8),this.isSet([t,n],e.LEFT)&&(r|=4),this.isSet([t-1,n],e.TOP)&&(r|=2),this.isSet([t,n-1],e.LEFT)&&(r|=1),r}forEach(t){for(let[n,r]of this._.entries()){let i=La(n),a=r[e.TOP];a&&a.color!==`none`&&a.style!==`none`&&t(i,e.TOP,a);let o=r[e.LEFT];o&&o.color!==`none`&&o.style!==`none`&&t(i,e.LEFT,o)}}*[Symbol.iterator](){for(let[t,n]of this._.entries()){let r=La(t),i=n[e.TOP];i&&i.color!==`none`&&i.style!==`none`&&(yield[r,e.TOP,i]);let a=n[e.LEFT];a&&a.color!==`none`&&a.style!==`none`&&(yield[r,e.LEFT,a])}}fillGridLines(t){let[n,r]=t[0],[i,a]=t[1];for(let t=n;t<=i;t++)for(let n=r;n<=a;n++)this.set([t,n],e.TOP,za),this.set([t,n],e.LEFT,za)}};function Ba(e){return Va(e.v)}function Va(e){return e&&typeof e==`object`}const Ha=`#282b3e`,Ua=`#f5f5f5`,Wa=`#d8d9e5`,Ga={fontFamily:`Calibri`,fontSize:11},Ka={...Ga,color:Ha},qa={...Ga,fillColor:Ua,color:Ha,borderTopColor:Wa,borderTopStyle:`medium`,borderBottomColor:Wa,borderBottomStyle:`medium`,borderLeftColor:Wa,borderLeftStyle:`medium`,borderRightColor:Wa,borderRightStyle:`medium`,horizontalAlignment:`center`,verticalAlignment:`bottom`,fontSize:11},Ja={fillColor:Ua,patternColor:Wa,patternStyle:`lightDown`},Ya={name:`Office`,colorScheme:{name:`Office`,dk1:{type:`system`,value:`windowText`},lt1:{type:`system`,value:`window`},dk2:{type:`srgb`,value:`44546A`},lt2:{type:`srgb`,value:`E7E6E6`},accent1:{type:`srgb`,value:`4472C4`},accent2:{type:`srgb`,value:`ED7D31`},accent3:{type:`srgb`,value:`A5A5A5`},accent4:{type:`srgb`,value:`FFC000`},accent5:{type:`srgb`,value:`5B9BD5`},accent6:{type:`srgb`,value:`70AD47`},hlink:{type:`srgb`,value:`0563C1`},folHlink:{type:`srgb`,value:`954F72`}},fontScheme:{name:`Office`,major:{latin:{typeface:`Aptos Display`},eastAsian:{typeface:``},complexScript:{typeface:``}},minor:{latin:{typeface:`Aptos Narrow`},eastAsian:{typeface:``},complexScript:{typeface:``}}}},Xa=[`color`,`fillColor`,`patternColor`,`borderTopColor`,`borderLeftColor`,`borderBottomColor`,`borderRightColor`];var Za=class{_;constructor(){this._=new Map}clear(){this._.clear()}setMerges(e){this.clear();for(let t of e){let e=c(t);if(!e||e.left==null||e.top==null||e.bottom==null||e.right==null)continue;let n=K(e.left,e.top),r=Object.freeze({top:e.top,left:e.left,bottom:e.bottom,right:e.right});this._.set(n,r)}}find(e,t){for(let n of this)if(n.left<=e&&n.right>=e&&n.top<=t&&n.bottom>=t)return n}*[Symbol.iterator](){for(let e of this._.values())yield e}getByCellId(e){if(e){let t=c(e);if(t&&t.left!=null&&t.top!=null){let e=K(t.left,t.top);return this._.get(e)??null}}return null}};function Qa(e,t=!1){let[n,r]=e.getSize();if(e.merged_cells.forEach(e=>{let t=c(e);t&&t.right!=null&&t.right>=n&&(n=t.right+1),t&&t.bottom!=null&&t.bottom>=r&&(r=t.bottom+1)}),t){if(e.columns&&e.columns.length){let t=e.columns.at(-1)?.end??1;t>n&&(n=t)}if(e.rows&&e.rows.length){let t=e.rows.at(-1)?.end??1;t>r&&(r=t)}}return[n,r]}const $a=1.17,eo=1.3;function to(e,t,n,r=1,i=!1){let a=[],o=(e,t,n,r)=>{let i={index:e-1,start:t,size:n,hidden:!1,end:t+n};return r!=null&&(i.style=r),a[e-1]=i},s=0,c=1,l=n*r;for(let t of e){for(;c<t.start;)o(c,s,l),c++,s+=l;for(c=t.start;c<=t.end;c++){let e=!t.size&&i?l:(t.size??n)*r,a=o(c,s,e,t.s);t.size||(a.hidden=!0),s+=e}}for(;c<=t;)o(c,s,l),c++,s+=l;return a}function no(e){for(let t=e.length-1;t>=0;t--)if(e[t].size>0)return t;return-1}var ro=class e{defaultCellHeight=21;defaultCellWidth=76;tilt=[0,0];viewBox={top:0,left:0,bottom:Ma,right:G};renderBox={top:0,left:0,bottom:Ma,right:G};col;row;width;height;lastSizedColIndex=-1;lastSizedRowIndex=-1;constructor(){this.col=[],this.width=0,this.row=[],this.height=0}get viewWidth(){let e=this.getCellRect(this.viewBox.left,this.viewBox.top);return this.getCellRect(this.viewBox.right,this.viewBox.bottom).right-e.left}get viewHeight(){let e=this.getCellRect(this.viewBox.left,this.viewBox.top);return this.getCellRect(this.viewBox.right,this.viewBox.bottom).bottom-e.top}get viewLeft(){return this.getCol(this.viewBox.left).start}get viewTop(){return this.getCol(this.viewBox.left).start}get rows(){return this.row.length}get columns(){return this.col.length}_offsetDims(e,t,n){let r=Array(e);for(let i=e-1;i>=0;i--){let a=t[i]||n;i===e-1?r[i]=a:r[i]=a+r[i+1]}return r}toMeasure(e,t,n,r=10,i=1/0){if((e<0||!isFinite(e))&&(e=0),e<=n){let n=t.find(t=>e>=t.start&&e<=t.end);if(n)return n}let a=t[t.length-1],o=r<1?100:r;if(!a){let t=Math.floor(e/o);return{index:t,start:t*o,size:r,end:(t+1)*o,hidden:!1}}if(r<1||a.index>=i)return a;let s=e-a.end,c=Math.ceil(s/o)+a.index;return{index:c,start:c*o-o,size:r,end:c*o,hidden:!1}}getCol(e){let t=this.columns;if(e<t)return this.col[e];let n=0;t&&(n=this.col[t-1].end);let r=n+(e-t)*this.defaultCellWidth;return{index:e,size:this.defaultCellWidth,start:r,end:r+this.defaultCellWidth,hidden:!1}}toCol(e){return this.toMeasure(e,this.col,this.width,this.defaultCellWidth,G)}getRow(e){let t=this.rows;if(e<t)return this.row[e];let n=0;t&&(n=this.row[t-1].end);let r=n+(e-t)*this.defaultCellHeight;return{index:e,size:this.defaultCellHeight,start:r,end:r+this.defaultCellHeight,hidden:!1}}toRow(e){return this.toMeasure(e,this.row,this.height,this.defaultCellHeight,Ma)}dims(e,t){let n=this.getCol(e),r=this.getRow(t);return{index:[e,t],size:[n.size,r.size],start:[n.start,r.start],end:[n.end,r.end]}}getCellRect(e,t){let n=this.getCol(e),r=this.getRow(t),i=this.getCol(this.viewBox.left),a=this.getRow(this.viewBox.top);return new W(n.start-i.start,r.start-a.start,n.size,r.size)}getColSize(e){let t=this.getCol(e),n=this.getCol(this.viewBox.left);return{index:t.index,size:t.size,hidden:!!t.hidden,start:t.start-n.start,end:t.end-n.start}}getRowSize(e){let t=this.getRow(e),n=this.getRow(this.viewBox.top);return{index:t.index,size:t.size,hidden:!!t.hidden,start:t.start-n.start,end:t.end-n.start}}rangeToRect(e){let t=this.getCol(e.left),n=e.right===e.left?t:this.getCol(e.right),r=this.getRow(e.top),i=e.top===e.bottom?r:this.getRow(e.bottom),a=this.getCol(this.viewBox.left),o=this.getRow(this.viewBox.top);return new W(t.start-a.start,r.start-o.start,n.end-t.start,i.end-r.start)}rectToRange(e){let t=this.toRow(e.top).index,n=this.toCol(e.left).index;return{top:t,left:n,bottom:e.bottom===e.top?t:Math.max(0,this.toRow(e.bottom).index),right:e.right===e.left?n:Math.max(0,this.toCol(e.right).index)}}setView(e,t,n,r){let i=new W(e,t,n,r);this.viewBox=this.rectToRange(i),this.renderBox={top:this.viewBox.top,left:this.viewBox.left,right:this._clampTail(this.viewBox.right,this.col,this.lastSizedColIndex,this.defaultCellWidth,G),bottom:this._clampTail(this.viewBox.bottom,this.row,this.lastSizedRowIndex,this.defaultCellHeight,Ma)},this.tilt=[this.getCol(this.viewBox.left).start-e,this.getRow(this.viewBox.top).start-t]}_clampTail(e,t,n,r,i){let a=t[t.length-1];return r<1||a&&a.index>=i?Math.min(e,Math.max(n,0)):e}addHeights(e,t,n=16,r=!1){this.row=to(e,t,n,eo,r),this.defaultCellHeight=n*eo,this.height=this.row.at(-1)?.end||0,this.lastSizedRowIndex=no(this.row)}addWidths(e,t,n=65,r=!1){this.col=to(e,t,n,$a,r),this.defaultCellWidth=n*$a,this.width=this.col.at(-1)?.end||0,this.lastSizedColIndex=no(this.col)}static from(t,n,r=!1){let i=new e,a=n.getSheet(t.sheetName);if(a){let[e,t]=Qa(a,!0);i.addHeights(a.rows??[],t,a.defaults?.rowHeight,r),i.addWidths(a.columns??[],e,a.defaults?.colWidth,r)}return i}};function*io(e){for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++)yield[t,n]}const ao={dashDot:{lineWidth:.5,lineDash:[7,3,3,3]},dashDotDot:{lineWidth:.5,lineDash:[7,3,3,3,3,3]},dashed:{lineWidth:.5,lineDash:[3,3,3,3]},dotted:{lineWidth:.5,lineDash:[3,3,3,3]},double:{lineWidth:.8,lineDash:null,gap:1,slant:0},hair:{lineWidth:.5,lineDash:null},medium:{lineWidth:1.5,lineDash:null},mediumDashDot:{lineWidth:2,lineDash:[7,3,3,3]},mediumDashDotDot:{lineWidth:1.5,lineDash:[7,3,3,3,3,3]},mediumDashed:{lineWidth:1.5,lineDash:[7,3]},slantDashDot:{lineWidth:1,lineDash:[7,1,3,1],gap:0,slant:.5},thick:{lineWidth:3,lineDash:null},thin:{lineWidth:.5,lineDash:null},none:{lineWidth:0,lineDash:null},default:{lineWidth:1,lineDash:null}},oo=e=>e&&typeof e==`object`;function so(e){return e==null||e===``?`left`:typeof e==`boolean`||oo(e)?`center`:typeof e==`number`?`right`:`left`}function co(e,t){let n;if(typeof window<`u`&&`OffscreenCanvas`in window)n=new OffscreenCanvas(e,t);else if(typeof OffscreenCanvas<`u`)n=new OffscreenCanvas(e,t);else if(typeof Canvas<`u`)n=new Canvas(e,t);else if(typeof document<`u`)n=document.createElement(`canvas`),n.width=e,n.height=t;else throw Error(`No canvas implementation available`);return n}const lo=new Map;lo.set(`none`,[0,0,0,0]);function uo(e){let t=e.toLowerCase(),n=lo.get(t);if(n)return n;let r=co(1,1).getContext(`2d`);if(!r)return[0,0,0,0];r.clearRect(0,0,1,1),r.fillStyle=`#000`,r.fillStyle=e;let i=r.fillStyle;if(r.fillStyle=`#fff`,r.fillStyle=e,i!==r.fillStyle)return[0,0,0,0];r.fillRect(0,0,1,1);let a=r.getImageData(0,0,1,1).data,o=[a[0],a[1],a[2],a[3]];return lo.set(t,o),o}function fo(e,t=null,n=null){let r=co(8,8),i=r.getContext(`2d`);if(i){let r=p(e,uo(t??`rgba(0,0,0,1)`),uo(n??`rgba(0,0,0,0)`)),a=i.createImageData(8,8);a.data.set(r),i.putImageData(a,0,0)}return r}let J,po=1.2;const mo=1.4;function ho(e=null){return e&&(J=e),J}function go(e){po=e}function _o(e,t,n=null){return e&&e[t]?e[t]:n}function vo(e){let t=_o(e,`fontSize`,11);return Math.round(t*po)}function yo(e){let t=``;_o(e,`italic`,!1)===!0&&(t+=`italic `),_o(e,`bold`,!1)===!0&&(t+=`bold `);let n=vo(e);t+=n+`px/`+Math.round(n*mo)+`px `;let r=_o(e,`fontFamily`,`Calibri`);return t+=Aa(String(r)),t}function bo(e,t){return xo(e&&typeof e==`object`?e.v:e,e?.z??``,t)}function xo(e,t,r){let i,a=typeof e;if(e==null||e===``)i=``;else if(a===`boolean`||Va(e))i=String(e).toUpperCase();else try{i=n(t||`General`,e,{locale:r})}catch{i=`#########`}return i}function So(e,t){if(t)try{return l(t,e,{indexColors:!0})}catch{return null}return null}function Co(e,t,n){J.restore();let r=bo(e,n);return J.font=yo(t||Ka),J.measureText(r).width}function wo(e,t,n,r){let i=_o(r,`underline`,`none`);if(i!==`none`){let a=_o(r,`color`,Ha),[o,s]=e;J.beginPath(),J.strokeStyle=String(a),J.lineWidth=.7,i===`single`?(J.translate(0,.5),J.moveTo(o,s+1),J.lineTo(o+t,s+1)):i===`singleAccounting`?(J.translate(0,.5),J.moveTo(8,s+1),J.lineTo(8+n-16,s+1)):i===`double`?(J.moveTo(o,s+2),J.lineTo(o+t,s+2),J.moveTo(o,s+.5),J.lineTo(o+t,s+.5)):i===`doubleAccounting`&&(J.moveTo(8,s+2),J.lineTo(8+n-16,s+2),J.moveTo(8,s+.5),J.lineTo(8+n-16,s+.5)),J.stroke(),J.closePath()}}function To(e,t,n,r,i){let a=t.width-8;J.beginPath(),J.rect(.5,.5,t.width,t.height),J.clip();let o=vo(n),s=Math.round(o*mo),c=new Ta({width:a,font:yo(n||Ka),align:r,valign:i}).linebreak(e),l=4,u=0;r===`right`?l=t.width-c.width-4:r===`center`&&(l=(t.width-c.width)/2),i===`bottom`?u=t.height-c.height:i===`center`&&(u=(t.height-c.height)/2),c.forEach((e,i)=>{let a=u+i*s+s*.5,d=0,f=e.width;r===`right`?d+=c.width-f:r===`center`&&(d+=c.width/2-f/2);let p=a+Math.floor(o*.35)+.5;wo([l+d,p],f,t.width,n),J.textBaseline=`middle`,e.reduce((e,t)=>{J.font=String(t.font);let n=t.font.baseline?o*-t.font.baseline+o*.15:0;return J.fillText(t.value,e+d,a+n),e+t.width},l)})}function Eo(e,t,n){let r=n.cellRect,i=n.clipRect||r,a=n.locale||`en-US`;J.save();let o=_o(t,`numberFormat`,`General`),s=xo(e,o,a);if(s){let n=so(e),a=_o(t,`horizontalAlignment`,n);a.toLowerCase()===`general`&&(a=n);let c=_o(t,`verticalAlignment`,`bottom`);if(J.font=yo(t),J.fillStyle=So(e,o)??String(_o(t,`color`,`#282b3e`)),_o(t,`wrapText`,!1))J.translate(r.x,r.y),To(s,r,t,a,c);else{J.translate(i.x,i.y),J.save(),J.beginPath(),J.rect(.5,.5,i.width,i.height),J.clip(),J.closePath(),J.textBaseline=`middle`;let e=J.measureText(s).width,n=vo(t),o=n*mo,l=o*.5;c===`bottom`?l=r.height-o*.5:c===`center`&&(l=r.height/2);let u=4;a===`center`?u=r.x-i.x+r.width/2-e/2:a===`right`&&(u=i.width-e-4),J.fillText(s,u,l),J.closePath();let d=l+Math.floor(n*.35)+.5;wo([u,d],e,r.width,t),J.restore()}}J.restore()}function Do(e,t,n,r=1,i=[],a=1){J.save(),J.globalAlpha=a??1,J.beginPath(),J.strokeStyle=n||`#d8d9e5`,J.lineWidth=r,J.setLineDash(i),J.moveTo(e[0],e[1]),J.lineTo(t[0],t[1]),J.stroke(),J.setLineDash([]),J.closePath(),J.globalAlpha=1,J.restore()}function Oo(e){J.save(),J.translate(e.x,e.y),(e.width<6||e.height<6)&&(J.beginPath(),J.rect(0,0,e.width,e.height),J.clip()),J.fillStyle=`#d93025`,J.beginPath(),J.moveTo(0,0),J.lineTo(6,0),J.lineTo(0,6),J.fill(),J.restore()}function ko(e){J.save(),J.translate(e.x+e.width,e.y),(e.width<6||e.height<6)&&(J.beginPath(),J.rect(-e.width,0,e.width,e.height),J.clip()),J.fillStyle=`#fcbc03`,J.beginPath(),J.moveTo(0,0),J.lineTo(-6,0),J.lineTo(0,6),J.fill(),J.restore()}function Ao(e,t,n,r,i){let a=n+r*.5,o=i?1:2,s=i?4:8,c=n,l=n,u=-n,d=-n;return e&o&&!(e&s)?l=-a:e&s&&!(e&o)?c=-a:!(e&o)&&!(e&s)&&(c=0,l=0),t&o&&!(t&s)?d=a:t&s&&!(t&o)?u=a:!(t&o)&&!(t&s)&&(u=0,d=0),[c,l,u,d]}function jo(e,t,n,r,i=0,a=0,o=1){let s=ao[n]||ao.thin,c=s.lineDash||[],l=s.lineWidth,u=s.slant||0,d=s.gap||(u?l*.5:0),f=r||`#282b3e`;if(d||u){let[n,r]=e,[s,p]=t;if(r===p){let[e,t,m,h]=u?[0,0,0,0]:Ao(i,a,l,d,!0);Do([n+u+e,r-d],[s+u+m,p-d],f,l,c,o),Do([n-u+t,r+d],[s-u+h,p+d],f,l,c,o)}else{let[e,t,m,h]=u?[0,0,0,0]:Ao(i,a,l,d,!1);Do([n-d,r+u+e],[s-d,p+u+m],f,l,c,o),Do([n+d,r-u+t],[s+d,p-u+h],f,l,c,o)}}else Do(e,t,f,l,c,o)}function Mo(e,t){J.save(),t.fillColor&&(J.globalAlpha=t.fillOpacity??1,J.fillStyle=t.fillColor||`transparent`,J.fillRect(e.x,e.y,e.width,e.height),J.globalAlpha=1),J.restore()}function No(e,t){J.save(),t||={};let n=fo(t.patternStyle,t.patternColor,t.fillColor),r=J.createPattern(n,`repeat`);r&&(J.fillStyle=r),J.fillRect(e.x,e.y,e.width,e.height),J.restore()}function Po(e,t){J.save(),J.translate(e.x,e.y),t&&(J.fillStyle=t,J.fillRect(-.2,-.2,e.width+.4,e.height+.4)),J.restore()}function Fo(e){let t=c(e);if(t&&t.top!=null&&t.left!=null)return[t.top,t.left];throw Error(`Invalid A1-reference`)}function Y(e){return{type:`srgb`,value:e}}function X(e,t=`thin`){return{borderTopColor:e,borderTopStyle:t,borderBottomColor:e,borderBottomStyle:t,borderLeftColor:e,borderLeftStyle:t,borderRightColor:e,borderRightStyle:t}}function Io(e,t,n){return{table:{borderTopColor:e,borderTopStyle:`thin`,borderBottomColor:e,borderBottomStyle:`thin`},header:{borderBottomColor:e,borderBottomStyle:`thin`,color:n??e,bold:!0},footer:{borderTopColor:e,borderTopStyle:`thin`,color:n??e,bold:!0},cell:{color:n??e},altRow:{fillColor:t},altCol:{fillColor:t},emFirst:{bold:!0},emLast:{bold:!0}}}function Lo(e){return{table:X(e),header:{fillColor:e,color:Y(`ffffff`),bold:!0},footer:{borderTopColor:e,borderTopStyle:`double`,bold:!0},altRow:{borderTopColor:e,borderTopStyle:`thin`,borderBottomColor:e,borderBottomStyle:`thin`},altCol:{borderLeftColor:e,borderLeftStyle:`thin`,borderRightColor:e,borderRightStyle:`thin`},emFirst:{bold:!0},emLast:{bold:!0}}}function Ro(e,t){return{table:X(e),header:{bold:!0,fillColor:Y(`ffffff`),...X(e),borderBottomColor:e,borderBottomStyle:`medium`},cell:{...X(e)},footer:{...X(e),borderTopColor:e,borderTopStyle:`double`,bold:!0},altRow:{fillColor:t},altCol:{fillColor:t},emFirst:{bold:!0},emLast:{bold:!0}}}function zo(e,t,n){return{table:X(n),header:{borderBottomColor:n,borderBottomStyle:`thin`,fillColor:e,color:Y(`ffffff`),bold:!0},footer:{borderTopColor:n,borderTopStyle:`double`,bold:!0},cell:{borderTopColor:n,borderTopStyle:`thin`,borderBottomColor:n,borderBottomStyle:`thin`},altRow:{fillColor:t},altCol:{fillColor:t},emFirst:{bold:!0},emLast:{bold:!0}}}function Bo(e,t,n){return{header:{...X(Y(`ffffff`)),borderBottomColor:Y(`ffffff`),borderBottomStyle:`thick`,fillColor:e,color:Y(`ffffff`),bold:!0},footer:{...X(Y(`ffffff`)),borderTopStyle:`thick`,fillColor:e,color:Y(`ffffff`),bold:!0},cell:{...X(Y(`ffffff`)),fillColor:t},altRow:{fillColor:n},altCol:{fillColor:n},emFirst:{fillColor:e,color:Y(`ffffff`),bold:!0},emLast:{fillColor:e,color:Y(`ffffff`),bold:!0}}}function Vo(e){return{table:{borderTopColor:Y(`000000`),borderTopStyle:`medium`,borderBottomColor:Y(`000000`),borderBottomStyle:`medium`},header:{fillColor:e,color:Y(`ffffff`),bold:!0},cell:{...X(Y(`000000`))},altRow:{fillColor:Y(`dddddd`)},altCol:{fillColor:Y(`dddddd`)},footer:{...X(Y(`000000`)),borderTopColor:Y(`000000`),borderTopStyle:`double`},emFirst:{fillColor:e,color:Y(`ffffff`),bold:!0},emLast:{fillColor:e,color:Y(`ffffff`),bold:!0}}}function Ho(e,t,n){return{cell:{...X(n),fillColor:e},header:{...X(n),fillColor:e,bold:!0},footer:{...X(n),borderTopStyle:`medium`,fillColor:e,bold:!0},altRow:{fillColor:t},altCol:{fillColor:t},emFirst:{bold:!0},emLast:{bold:!0}}}function Uo(e,t){return{header:{borderBottomColor:Y(`ffffff`),borderBottomStyle:`medium`,fillColor:Y(`000000`),color:Y(`ffffff`),bold:!0},footer:{borderTopColor:Y(`ffffff`),borderTopStyle:`medium`,fillColor:Y(`000000`),color:Y(`ffffff`),bold:!0},cell:{color:Y(`ffffff`),fillColor:e},altRow:{fillColor:t},altCol:{fillColor:t},emFirst:{fillColor:t,borderRightColor:Y(`ffffff`),borderRightStyle:`medium`,bold:!0},emLast:{fillColor:t,borderLeftColor:Y(`ffffff`),borderLeftStyle:`medium`,bold:!0}}}function Wo(e,t,n){return{header:{fillColor:e,color:Y(`ffffff`)},footer:{borderTopColor:Y(`000000`),borderTopStyle:`double`,fillColor:t,bold:!0},cell:{fillColor:t},altRow:{fillColor:n},altCol:{fillColor:n},emFirst:{bold:!0},emLast:{bold:!0}}}const Go={TableStyleLight1:Io(Y(`000000`),Y(`dddddd`)),TableStyleLight2:Io(Y(`134c6f`),Y(`b4e1f3`)),TableStyleLight3:Io(Y(`e25a26`),Y(`f9dccc`),Y(`ae3c11`)),TableStyleLight4:Io(Y(`165a1a`),Y(`b6efbc`)),TableStyleLight5:Io(Y(`168ccc`),Y(`c0e9fb`),Y(`10628d`)),TableStyleLight6:Io(Y(`8c1180`),Y(`efc1ec`),Y(`63105d`)),TableStyleLight7:Io(Y(`409b23`),Y(`d2f1c6`),Y(`306d1a`)),TableStyleLight8:Lo(Y(`000000`)),TableStyleLight9:Lo(Y(`134c6f`)),TableStyleLight10:Lo(Y(`e25a26`)),TableStyleLight11:Lo(Y(`165a1a`)),TableStyleLight12:Lo(Y(`168ccc`)),TableStyleLight13:Lo(Y(`8c1180`)),TableStyleLight14:Lo(Y(`409b23`)),TableStyleLight15:Ro(Y(`000000`),Y(`dddddd`)),TableStyleLight16:Ro(Y(`134c6f`),Y(`b4e1f3`)),TableStyleLight17:Ro(Y(`e25a26`),Y(`f9dccc`)),TableStyleLight18:Ro(Y(`165a1a`),Y(`b6efbc`)),TableStyleLight19:Ro(Y(`168ccc`),Y(`c0e9fb`)),TableStyleLight20:Ro(Y(`8c1180`),Y(`efc1ec`)),TableStyleLight21:Ro(Y(`409b23`),Y(`d2f1c6`)),TableStyleMedium1:zo(Y(`000000`),Y(`dddddd`),Y(`000000`)),TableStyleMedium2:zo(Y(`134c6f`),Y(`b4e1f3`),Y(`39a3da`)),TableStyleMedium3:zo(Y(`e25a26`),Y(`f9dccc`),Y(`ec9870`)),TableStyleMedium4:zo(Y(`165a1a`),Y(`b6efbc`),Y(`3ece47`)),TableStyleMedium5:zo(Y(`168ccc`),Y(`c0e9fb`),Y(`52c0f0`)),TableStyleMedium6:zo(Y(`8c1180`),Y(`efc1ec`),Y(`cd50c2`)),TableStyleMedium7:zo(Y(`409b23`),Y(`d2f1c6`),Y(`7ed560`)),TableStyleMedium8:Bo(Y(`000000`),Y(`dddddd`),Y(`bbbbbb`)),TableStyleMedium9:Bo(Y(`134c6f`),Y(`b4e1f3`),Y(`73c0e7`)),TableStyleMedium10:Bo(Y(`e25a26`),Y(`f9dccc`),Y(`f4ba9c`)),TableStyleMedium11:Bo(Y(`165a1a`),Y(`b6efbc`),Y(`74df7b`)),TableStyleMedium12:Bo(Y(`168ccc`),Y(`c0e9fb`),Y(`84d5f7`)),TableStyleMedium13:Bo(Y(`8c1180`),Y(`efc1ec`),Y(`dc87d6`)),TableStyleMedium14:Bo(Y(`409b23`),Y(`d2f1c6`),Y(`a9e391`)),TableStyleMedium15:Vo(Y(`000000`)),TableStyleMedium16:Vo(Y(`134c6f`)),TableStyleMedium17:Vo(Y(`e25a26`)),TableStyleMedium18:Vo(Y(`165a1a`)),TableStyleMedium19:Vo(Y(`168ccc`)),TableStyleMedium20:Vo(Y(`8c1180`)),TableStyleMedium21:Vo(Y(`409b23`)),TableStyleMedium22:Ho(Y(`dddddd`),Y(`bbbbbb`),Y(`000000`)),TableStyleMedium23:Ho(Y(`b4e1f3`),Y(`73c0e7`),Y(`39a4da`)),TableStyleMedium24:Ho(Y(`f9dccc`),Y(`f4ba9c`),Y(`ed9870`)),TableStyleMedium25:Ho(Y(`b6efbc`),Y(`74df7b`),Y(`3ecf47`)),TableStyleMedium26:Ho(Y(`c0e9fb`),Y(`84d5f7`),Y(`52c0f1`)),TableStyleMedium27:Ho(Y(`efc1ec`),Y(`dc87d6`),Y(`cd50c2`)),TableStyleMedium28:Ho(Y(`d2f1c6`),Y(`a9e391`),Y(`7ed560`)),TableStyleDark1:Uo(Y(`606060`),Y(`313131`)),TableStyleDark2:Uo(Y(`134d6f`),Y(`0f384e`)),TableStyleDark3:Uo(Y(`e25b26`),Y(`af3b11`)),TableStyleDark4:Uo(Y(`175a1b`),Y(`114113`)),TableStyleDark5:Uo(Y(`158ccc`),Y(`11628d`)),TableStyleDark6:Uo(Y(`8d1181`),Y(`640f5d`)),TableStyleDark7:Uo(Y(`409b22`),Y(`306c19`)),TableStyleDark8:Wo(Y(`000000`),Y(`dddddd`),Y(`bbbbbb`)),TableStyleDark9:Wo(Y(`e25b26`),Y(`b5e0f3`),Y(`73c0e7`)),TableStyleDark10:Wo(Y(`158ccc`),Y(`b5f0bc`),Y(`74df7b`)),TableStyleDark11:Wo(Y(`409b22`),Y(`eec0eb`),Y(`dc87d6`))},Ko=[[`font-name`,`fontFamily`],[`font-size`,`fontSize`],[`font-color`,`color`],[`bold`,`bold`],[`italic`,`italic`],[`underline`,`underline`],[`fill-color`,`fillColor`],[`border-left-style`,`borderLeftStyle`],[`border-left-color`,`borderLeftColor`],[`border-right-style`,`borderRightStyle`],[`border-right-color`,`borderRightColor`],[`border-top-style`,`borderTopStyle`],[`border-top-color`,`borderTopColor`],[`border-bottom-style`,`borderBottomStyle`],[`border-bottom-color`,`borderBottomColor`],[`horizontal-alignment`,`horizontalAlignment`],[`vertical-alignment`,`verticalAlignment`],[`wrap-text`,`wrapText`],[`shrink-to-fit`,`shrinkToFit`],[`number-format`,`numberFormat`],[`stroke-opacity`,`strokeOpacity`],[`fill-opacity`,`fillOpacity`]];function qo(e){if(typeof e==`object`&&e){let t=e;for(let[e,n]of Ko)t[e]!=null&&(t[n]=t[e])}return e}const Jo=(e,t,n)=>Math.max(e,Math.min(t,n)),Yo=[[`top`,q.TOP],[`left`,q.LEFT],[`bottom`,q.BOTTOM],[`right`,q.RIGHT]],Xo={top:[`borderTopColor`,`borderTopStyle`],bottom:[`borderBottomColor`,`borderBottomStyle`],left:[`borderLeftColor`,`borderLeftStyle`],right:[`borderRightColor`,`borderRightStyle`]},Zo={color:{type:`srgb`,value:`999999`},horizontalAlignment:`left`,verticalAlignment:`bottom`,fillColor:void 0,numberFormat:`@`,wrapText:!1,bold:!1,italic:!1,underline:`none`};function Qo(e){return e===`centerContinuous`?e=`center`:(e===`distributed`||e===`justify`||e===`fill`||e===`general`)&&(e=`left`),e}var $o=class{workbook;sheetName;highlightColor;locale;viewRef;headers;headerStyle={...qa};hiddenStyle={...qa,...Ja};allowRangeSelections;allowHeaderSelections;showHidden=!1;showValuelessFormulas=!1;showAnnotations=!0;skipCells;borders;merges;fontAdjust;scale;tables=new Map;annotatedCells;onCellContent;constructor(e={}){this.workbook=null,this.sheetName=``,this.highlightColor=`#39c6d9`,this.viewRef=new Na(`A1`),this.headers=!0,this.allowRangeSelections=!0,this.allowHeaderSelections=!0,this.locale=`en-us`,this.setOptions(e),this.skipCells=new Map,this.borders=new q,this.merges=new Za,this.scale=new ro,this.fontAdjust=1.2,this.annotatedCells=new Set,this.onCellContent=e.onCellContent}setOptions(e){this.headers=e.headers??this.headers,this.locale=e.locale??this.locale,this.highlightColor=e.highlightColor??this.highlightColor,this.headerStyle=Object.assign({},qa,e.headerStyle),this.hiddenStyle=Object.assign({},this.headerStyle,Ja,e.hiddenStyle),this.allowRangeSelections=e.allowRangeSelections??!0,this.allowHeaderSelections=e.allowHeaderSelections??!0,this.showHidden=e.showHidden??!1,this.showValuelessFormulas=e.showValuelessFormulas??!1,this.showAnnotations=e.showAnnotations??!0}getFullSheetRef(){let e=this.workbook?.getSheet(this.sheetName);if(!e)throw Error(`sheet "${this.sheetName}" not found`);let t=Qa(e);return new Na({top:0,left:0,right:Math.max(0,t[0]-1),bottom:Math.max(0,t[1]-1)},{workbookName:this.workbook?.name,sheetName:e.name})}updateTables(){let e=new Map;this.workbook?.tables.getAll().map(t=>{if(t.sheetName===this.sheetName){let n=new Na(t.ref);if(n){let r=n.range;for(let[n,i]of io(r))e.set(K(n,i),[t.name,r])}}}),this.tables=e}updateAnnotatedCells(){let e=this.getCurrentSheet(),t=new Set;if(e&&this.workbook){if(this.workbook.comments)for(let n of this.workbook.comments.get(e.name,{excludeReplies:!0,excludeResolved:!0})){let[e,r]=Fo(n.ref);t.add(K(r,e))}if(this.workbook.notes)for(let n of this.workbook.notes.get(e.name)){let[e,r]=Fo(n.ref);t.add(K(r,e))}}this.annotatedCells=t}updateScale(){this.workbook&&(this.viewRef=this.getFullSheetRef(),this.scale=ro.from(this.viewRef,this.workbook,this.showHidden),this.updateTables(),this.updateAnnotatedCells())}getVisibleColumns(){let e=[],t=this.getHeadersSize(),n=this.scale.renderBox,[r]=this.scale.tilt;for(let i=n.left;i<=n.right;i++){let n=this.scale.getColSize(i);e.push({index:i,offset:t.width+n.start+r,height:t.height,width:n.size})}return e}getColumnSize(e){return e<0||e>G||e!==Math.trunc(e)?0:this.scale.getColSize(e).size}setColumnSize(e,t){e>=0&&e<=G&&e===Math.trunc(e)&&(this.workbook?.setColumnWidth(this.sheetName,e,t),this.updateScale())}getVisibleRows(){let e=[],t=this.getHeadersSize(),n=this.scale.renderBox,[,r]=this.scale.tilt;for(let i=n.top;i<=n.bottom;i++){let n=this.scale.getRowSize(i);e.push({index:i,offset:t.height+n.start+r,height:n.size,width:t.width})}return e}getRowSize(e){return e<0||e>Ma||e!==Math.trunc(e)?0:this.scale.getRowSize(e).size}setRowSize(e,t){e>=0&&e<=Ma&&e===Math.trunc(e)&&(this.workbook?.setRowHeight(this.sheetName,e,t/1.3),this.updateScale())}setWorkbook(e){this.workbook=e;let t=e.getSheet(null);if(!t)throw Error(`workbook has no sheets`);this.setSheet(t.name)}setSheet(e){this.sheetName=e,this.viewRef.sheetName=e,this.updateScale()}refToRect(e,t=!0){let n=this.scale.rangeToRect(e.range);if(t){let e=this.getHeadersSize();return new W(n.x,n.y,n.width+e.width,n.height+e.height)}return n}getHeadersSize(){let e=this.headerStyle.fontSize||11;return{height:this.headers?Math.round(e*1.64):0,width:this.headers?Math.round(e*2.27):0}}getCurrentSheet(){return this.workbook?.getSheet(this.viewRef?.sheetName)??null}getColumnStyle(e){let t=this.getCurrentSheet();if(t&&t.columns){let n=e+1,r=t.columns.find(e=>e.start<=n&&n<=e.end);if(r?.s!=null)return this.workbook?.styles.get(r.s)??null}return null}getTableStyle(e,t){let n={},r=this.tables.get(K(e,t));if(r){let[i,a]=r,o=this.workbook?.tables.get(i);if(o){let r=o.jsf.style??{name:`TableStyleMedium2`,showRowStripes:!0},i=Go[r.name??``]??{},s=t-a.top<(o.headerRowCount??0),c=a.bottom-t<(o.totalsRowCount??0);if(s)Object.assign(n,i.header);else if(c)Object.assign(n,i.footer);else{let s=t-a.top-(o.headerRowCount??0),c=s%2,l=(e-a.left)%2;Object.assign(n,i.cell,c||!r.showRowStripes?null:i.altRow,l||!r.showColumnStripes?null:i.altCol,e===a.left&&r.showFirstColumn?i.emFirst:null,e===a.right&&r.showLastColumn?i.emLast:null),s===0&&i.header?.borderBottomStyle&&(n.borderTopColor=i.header.borderBottomColor,n.borderTopStyle=i.header.borderBottomStyle)}if(i.table){let r=[[`top`,t===a.top],[`bottom`,t===a.bottom],[`left`,e===a.left],[`right`,e===a.right]];for(let[e,t]of r)if(t){let[t,r]=Xo[e];i.table[r]&&(n[t]=i.table[t],n[r]=i.table[r])}}}}return n}getStyles(e,t){let n=this.getCurrentSheet(),r=n&&n.getCellByCoords(t,e)||null,i=this.getTableStyle(e,t),a=this.workbook?.styles.get(r?.s??0)??{},o=this.getColumnStyle(e),c={...i,...o,...a};r&&r.f!=null&&r.v==null&&this.showValuelessFormulas&&Object.assign(c,Zo);let l=this.workbook?.theme?.get()??Ya;!c.fontFamily&&c.fontScheme&&(c.fontFamily=l.fontScheme[c.fontScheme].latin.typeface||`Aptos Narrow`);let u={};return Xa.forEach(e=>{if(e in c){let t=c[e];t&&typeof t!=`string`&&(u[e]=`#`+d(s(t,l.colorScheme)))}}),{...c,...u}}getMergeRange(e){return this.merges.getByCellId(e?.M)}resize(e,t){if(!e)return;let n=e.getContext(`2d`,{alpha:!1});if(!n)return;let r,i;if(t)r=t.width,i=t.height;else{let e=this.getHeadersSize(),t=this.scale.rangeToRect(this.viewRef.range);r=t.width+e.width,i=t.height+e.height}r>1e4&&(r=1e4),i>1e4&&(i=1e4);let a=(typeof window>`u`?1:window.devicePixelRatio)||1;e.style&&(e.style.height=i+`px`,e.style.width=r+`px`),e.height=i*a,e.width=r*a,n.scale(a,a)}getCellAt(e,t){let n=this.getCurrentSheet();return n&&n.getCellByCoords(t,e)||null}shouldRenderGridLines(){let e=this.getCurrentSheet();return e?.views?e.views.find(e=>!e.activeLayout||e.activeLayout===`normal`)?.showGridLines??!0:!0}detectBorders(){let e=this.shouldRenderGridLines(),{renderBox:t}=this.scale,n=Jo(0,t.left,G),r=Jo(0,t.right,G),i=Jo(0,t.top,Ma),a=Jo(0,t.bottom,Ma);if(e){for(let e=n;e<=r+1;e++)for(let t=i;t<=a+1;t++){let n=[e,t];this.borders.set(n,q.TOP,za),this.borders.set(n,q.LEFT,za)}for(let e=n;e<=r+1;e++)for(let t=i;t<=a+1;t++){let n=this.getStyles(e,t);if(n&&n.fillColor){let n=[e,t];this.borders.set(n,q.TOP,null),this.borders.set(n,q.LEFT,null),this.borders.set(n,q.BOTTOM,null),this.borders.set(n,q.RIGHT,null)}}for(let e of this.merges)for(let t=e.left;t<=e.right;t++)for(let n=e.top;n<=e.bottom;n++){let r=[t,n];n>e.top&&this.borders.set(r,q.TOP,null),t>e.left&&this.borders.set(r,q.LEFT,null)}}for(let e=n;e<=r;e++)for(let t=i;t<=a;t++){let n=this.getStyles(e,t);if(n)for(let[r,i]of Yo){let[a,o]=Xo[r],s=n[o],c=n[a]||`#000`;s&&s!==`none`&&this.borders.set([e,t],i,{style:s,color:c})}}}getCellAlignment(e){let t=(this.workbook?.styles.get(e.s??0)??{}).horizontalAlignment;return(t===`general`||!t)&&(t=so(e?e.v:null)),t}canOverflow(e){if(!e||typeof e.v!=`string`||!e.v||e.M||(this.workbook?.styles.get(e.s??0)??{}).wrapText)return 0;let t=Qo(this.getCellAlignment(e));return t===`center`||t===`left`?1:-1}absolutePosition(e){let{scale:t}=this,n=t.dims(e.left,e.top),r=t.dims(e.right,e.bottom);return new W(n.start[0],n.start[1],r.end[0]-n.start[0],r.end[1]-n.start[1])}renderCellText(e,t,n=!1){let{scale:r}=this,i=this.getCurrentSheet();if(!i)return;let{skipCells:a,borders:o}=this,s=this.getCellAt(e,t),c=s&&s.v==null&&s.f!=null;if(!s||c&&!this.showValuelessFormulas||s.v===``)return;let l=r.getCol(e),u=this.getStyles(e,t),d=Co(s,u,this.locale)+8,f=Qo(this.getCellAlignment(s)),p=f===`left`||f===`center`?1:-1,m=(d>l.size?p:0)&&this.canOverflow(s);if(n&&!m)return;let h=r.renderBox.left,g=r.renderBox.right;if(m||(h=e,g=e),m&&(f===`left`||f===`center`)){let n=i.nextValueCellByCoords(t,e,`right`);n&&(g=Fo(n.id)[1]-1)}if(m&&(f===`right`||f===`center`)){let n=i.nextValueCellByCoords(t,e,`left`);n&&(h=Fo(n.id)[1]+1)}let _=l.start,v=l.end;if(m){if(f===`left`&&g>e){let n=r.toCol(l.start+d).index,i=Math.min(g,n??G);v=r.getCol(i).end;for(let n=e+1;n<=i;n++)o.set([n,t],q.LEFT,null),a.set(K(n,t),1)}else if(f===`right`&&h<e){let n=r.toCol(l.end-d).index,i=Math.max(h,n||0);_=r.getCol(i).start;for(let n=e;n>=i;n--)o.set([n,t],q.LEFT,null),a.set(K(n,t),1)}else if(f===`center`){let n=l.start+l.size/2,i=r.toCol(n+d/2).index,s=Math.min(g,i??G);v=r.getCol(s).end;for(let n=e+1;n<=s;n++)o.set([n,t],q.LEFT,null),a.set(K(n,t),1);let c=r.toCol(n-d/2).index,u=Math.max(h,c||0);_=r.getCol(u).start;for(let n=e;n>u;n--)o.set([n,t],q.LEFT,null),a.set(K(n,t),1)}}let y=this.getHeadersSize(),b=r.getCellRect(e,t).translate(y.width,y.height),ee=new W(y.width+_-r.viewLeft,b.y,v-_,b.height),te=s.v;c&&this.showValuelessFormulas&&(te=`=${s.f}`),Eo(te,u,{cellRect:b.translate(...r.tilt),clipRect:ee.translate(...r.tilt),locale:this.locale})}renderBackgrounds(){let{scale:e}=this,t=this.getHeadersSize();for(let n of io(e.renderBox)){let[r,i]=n,a=this.getMergeRange(this.getCellAt(r,i)),o=a?this.getStyles(a.left,a.top):this.getStyles(r,i),s=e.getCellRect(r,i).translate(t.width,t.height).translate(...e.tilt),c=o.fillColor?String(o.fillColor):null,{patternStyle:l}=o;l?No(s,{...o,patternStyle:l}):c&&Po(s,c)}}renderContent(){let{scale:e}=this,t=this.getCurrentSheet();if(!t)return;let n=this.getHeadersSize(),r=e.renderBox;for(let i=r.top;i<=r.bottom;i++){if(r.left>0){let e=t.nextValueCellByCoords(i,r.left,`left`);if(e&&this.canOverflow(e)){let t=c(e.id);t&&t.left!=null&&this.renderCellText(t.left,i,!0)}}if(r.right<G){let e=t.nextValueCellByCoords(i,r.right,`right`);if(e&&this.canOverflow(e)){let t=c(e.id);t&&t.left!=null&&this.renderCellText(t.left,i,!0)}}for(let t=r.left;t<=r.right;t++){if(this.skipCells.has(K(t,i)))continue;let r=this.getCellAt(t,i),a=this.getMergeRange(r);a&&r?.M!==r?.id&&(r=this.getCellAt(a.left,a.top));let o=r?.v==null&&r?.f!=null;if(!r||o&&!this.showValuelessFormulas||r.v===``)continue;let s;if(a){s=e.rangeToRect(a).translate(n.width,n.height).translate(...e.tilt);for(let[e,t]of io(a))this.skipCells.set(K(e,t),1)}else s=e.getCellRect(t,i).translate(n.width,n.height).translate(...e.tilt);let c=!0;if(s.width>0&&s.height>0){if(this.onCellContent)try{c=this.onCellContent.call(this,{rect:s,cell:r,ctx:ho()})}catch(e){console.error(e)}}else c=!1;c!==!1&&(a?Eo(r.v,this.getStyles(t,i),{cellRect:s,locale:this.locale}):this.renderCellText(t,i),this.showAnnotations&&s.width>0&&s.height>0&&this.annotatedCells.has(K(t,i))&&ko(s),Ba(r)&&s.width>0&&s.height>0&&Oo(s))}}}renderBorders(e){e||=this.borders;let{scale:t}=this,[n,r]=t.tilt,i=this.getHeadersSize();e.forEach((a,o,s)=>{let c=t.getCellRect(a[0],a[1]).translate(i.width,i.height);o===q.TOP?jo([c.x+n,c.y+r],[c.right+n,c.y+r],s.style||`none`,s.color,e.getJoin(a[0],a[1]),e.getJoin(a[0]+1,a[1])):o===q.LEFT&&jo([c.x+n,c.y+r],[c.x+n,c.bottom+r],s.style||`none`,s.color,e.getJoin(a[0],a[1]),e.getJoin(a[0],a[1]+1))})}renderHighlight(e){if(e&&e.range&&(!e.workbookName||e.workbookName===this.workbook?.name)&&(!e.sheetName||e.sheetName===this.sheetName)){qo(e);let t=e.fill||`none`,n=Jo(0,e.fillOpacity??1,1),r=e.stroke||this.highlightColor||`#39c6d9`,i=e.style||`medium`,a=Jo(0,e.strokeOpacity??1,1),o=this.getHeadersSize(),s=this.scale.rangeToRect(e.range).translate(o.width,o.height).translate(...this.scale.tilt);t&&t!==`none`&&t!==`transparent`&&Mo(s,{fillOpacity:n,fillColor:t}),s.getBorders().forEach(([e,t,n])=>{jo(e,t,i,r,n[0],n[1],a)})}}renderHeaderBorders(e){let{scale:t}=this,[n,r]=t.tilt,i=this.getHeadersSize(),a=t.renderBox,o=i.height,s=i.width,c=(t,n,r)=>{let[i,a]=t,o=e.getJoin(i,a),s=e.getJoin(i+1,a),c=e.getJoin(i,a+1),l=e.getJoin(i+1,a+1);if(n.includes(q.TOP)){let n=e.get(t,q.TOP),i=r.getTopEdge();jo(i[0],i[1],n.style,n.color,o,s)}if(n.includes(q.BOTTOM)){let n=e.get(t,q.BOTTOM),i=r.getBottomEdge();jo(i[0],i[1],n.style,n.color,c,l)}if(n.includes(q.LEFT)){let n=e.get(t,q.LEFT),i=r.getLeftEdge();jo(i[0],i[1],n.style,n.color,o,c)}if(n.includes(q.RIGHT)){let n=e.get(t,q.RIGHT),i=r.getRightEdge();jo(i[0],i[1],n.style,n.color,s,l)}};for(let e=a.left;e<=a.right;e++){let r=t.getColSize(e);r.size&&c([e+1,0],[q.BOTTOM,q.TOP,q.RIGHT],new W(s+r.start+n+0,0,r.size,o))}for(let e=a.top;e<=a.bottom;e++){let n=t.getRowSize(e);n.size&&c([0,e+1],[q.BOTTOM,q.LEFT,q.RIGHT],new W(0,0+o+n.start+r,s,n.size))}c([0,0],[q.TOP,q.BOTTOM,q.LEFT,q.RIGHT],new W(0,0,s,o))}renderHeaders(){if(!this.headers)return;let e=(e,t,n=!1)=>{if(n){let{patternStyle:n}=this.hiddenStyle;n&&No(e,{...this.hiddenStyle,patternStyle:n}),Eo(t,this.hiddenStyle,{cellRect:e})}else Mo(e,this.headerStyle),Eo(t,this.headerStyle,{cellRect:e})},t=this.headerStyle,n=new q,i=(e,r)=>{for(let[i,a]of Yo){let[o,s]=Xo[i],c=t[s]||`none`,l=t[o]||`#000`;c!==`none`&&l!==`transparent`&&n.set([e,r],a,{style:c,color:l})}},a=this.getHeadersSize(),{scale:o}=this,s=o.renderBox,[c,l]=o.tilt;for(let t=s.top;t<=s.bottom;t++){let n=o.getRowSize(t);n.size&&(e(new W(0,a.height+n.start-1+l,a.width,n.size),String(t+1),n.hidden),i(0,t+1))}for(let t=s.left;t<=s.right;t++){let n=o.getColSize(t);n.size&&(e(new W(a.width+n.start+c,0,n.size,a.height),r(t),n.hidden),i(t+1,0))}e(new W(0,0,a.width,a.height),``),i(0,0),this.renderHeaderBorders(n)}toRect(e){let t=this.getHeadersSize(),n=this.scale.tilt;return this.scale.rangeToRect(e).translate(t.width,t.height).translate(n[0],n[1])}invert(e,t=null){let n=this.getHeadersSize();e[0]<n.width&&(e=[n.width+1,e[1]]),e[1]<n.height&&(e=[e[0],n.height+1]);let r=e[0]+(t?.left||0),i=e[1]+(t?.top||0),a=new W(r-n.width,i-n.height,0,0),o=Object.freeze(this.scale.rectToRange(a));return{cellPos:this.merges.find(o.left,o.top)||o,gridPos:o}}rectToRanges(e,t,n){let r=this.allowRangeSelections,i=this.allowHeaderSelections,a=this.getHeadersSize(),o=r&&i&&e[0]<a.width,s=r&&i&&e[1]<a.height,c=this.invert(e,n);if(c){let e=this.invert(t,n);r||(c=e);let i=s||o?c.gridPos:c.cellPos,a=s||o?e.gridPos:e.cellPos;return{focus:e.cellPos,anchor:c.cellPos,selection:{top:s?0:Math.min(i.top,a.top),bottom:s?1048575:Math.max(i.bottom,a.bottom),left:o?0:Math.min(i.left,a.left),right:o?16383:Math.max(i.right,a.right)}}}return null}render(e,t=null,n){if(!e)return;let r=e.getContext(`2d`,{alpha:!1});if(!r)return;let i=(typeof window>`u`?1:window.devicePixelRatio)||1,a=(e.width||e.clientWidth||0)/i,o=(e.height||e.clientHeight||0)/i;if(a<=0||o<=0)return;if(!isFinite(a))throw Error(`Canvas width cannot be infinite: `+a);if(!isFinite(o))throw Error(`Canvas height cannot be infinite: `+o);this.scale.setView(t?.left||0,t?.top||0,a,o),r.fillStyle=`#fff`,r.fillRect(0,0,a,o),ho(r),go(this.fontAdjust),this.skipCells.clear(),this.merges.clear();let s=this.getCurrentSheet();if(s&&this.merges.setMerges(s.merged_cells),this.borders.clear(),this.detectBorders(),this.renderBackgrounds(),this.renderContent(),this.renderBorders(),n)for(let e of n)e&&this.renderHighlight(e);this.renderHeaders(),this.borders.clear(),this.skipCells.clear()}};function es(e){return e._recalcState}function ts(e){return typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`string`}var Z=class{name;description;parameters;_run;constructor(e){this.name=e.name,this.description=e.description,this.parameters=e.parameters,this._run=e.run}execute(e,t){try{return this._run(e,t)}catch(e){return{error:e instanceof Error?e.message:String(e)}}}};function ns(e){if(!e)return{error:`Workbook not found`};let t=e.getWorkbook();return t?{workbook:t}:{error:`Model has no workbook`}}function rs(e){return fe(`${e}1`)[1]}function is(e){let t=e.lastIndexOf(`!`);return t>=0?e.slice(t+1):e}function as(e){return e instanceof x?`Unable to solve goalSeek: ${e.detail}`:null}var os=class extends Error{sheetRef;availableSheets;constructor(e,t){super(`Sheet "${e}" not found. Available sheets: ${t.join(`, `)}`),this.name=`SheetNotFoundError`,this.sheetRef=e,this.availableSheets=t}};function ss(e){let t=e.match(/^\[([^\]]+)\](.*)$/);return t?{workbookName:t[1]??``,sheetName:t[2]??``}:{workbookName:null,sheetName:e}}function cs(e,t){let{workbookName:n,sheetName:r}=ss(e),i=t.resolveSheet(r,n);return i?n?{workbookName:t.resolveWorkbook(n)?.name??n,sheetName:i.name}:{workbookName:null,sheetName:i.name}:null}function ls(e){let t=e.getWorkbook(),n=[];for(let r of e.getWorkbooks()){let e=t!=null&&r===t;for(let t of r.getSheets())n.push(e?t.name:`[${r.name}]${t.name}`)}return n}function Q(e,n){let r=o(e);if(r){if(r.context&&r.context.length>0){let e=r.context[r.context.length-1]??``,i=r.context.length>1?r.context[0]??null:null,a=i?`[${i}]${e}`:e,o=cs(a,n);if(o){let e=o.workbookName?[o.workbookName,o.sheetName]:[o.sheetName];return t({...r,context:e})}throw us(a,n)}return t(r)}let i=e.lastIndexOf(`!`);if(i===-1)return e;let a=e.slice(0,i),s=e.slice(i+1),c=cs(a,n);if(!c&&a.startsWith(`'`)&&a.endsWith(`'`)&&(c=cs(a.slice(1,-1),n)),c){let n=c.workbookName?[c.workbookName,c.sheetName]:[c.sheetName],r=o(s);if(r)return t({...r,context:n});let i=o(`X!${s}`);return i?t({...i,context:n}):e}throw us(a,n)}function us(e,t){return new os(e,ls(t))}function ds(e,t){return e.people.find(e=>e.id===t)?.displayName??t}function fs(e,t){return new S(t,{sheetName:e}).toString()}function ps(e){let t=e.replace(/\s+/g,` `).trim(),n=[...t];return n.length<=100?{preview:t,truncated:!1}:{preview:`${n.slice(0,99).join(``)}…`,truncated:!0}}function ms(e){let t=new Map;for(let n of e)n.parentId===void 0&&t.set(n.id,{root:n,replies:[]});for(let n of e)n.parentId!==void 0&&t.get(n.parentId)?.replies.push(n);return[...t.values()]}function hs(e,t){let n=[];for(let r of ms(e.comments.get(t))){let{preview:i,truncated:a}=ps(r.root.text),o={address:fs(t,r.root.ref),kind:`thread`,author:ds(e,r.root.personId),preview:i};r.root.datetime!==void 0&&(o.datetime=r.root.datetime),r.replies.length>0&&(o.replyCount=r.replies.length),r.root.resolved!==void 0&&(o.resolved=r.root.resolved),a&&(o.truncated=!0),n.push(o)}for(let r of e.notes.get(t)){let{preview:e,truncated:i}=ps(r.text),a={address:fs(t,r.ref),kind:`note`,author:r.author,preview:e};i&&(a.truncated=!0),n.push(a)}return n}const gs=new Z({name:`getComment`,description:'Read the full text of the comment or note on a specific cell, including all replies for threaded comments. Returns kind="none" if the cell has neither. Use after `getComments` to see the body of an entry whose preview was truncated, or when an agent message refers to a specific cell with a TODO/question on it.',parameters:C.object({address:C.string().describe(`Sheet-qualified cell reference, e.g. "'LBO Model'!E46" or "Sheet1!B2". For non-default sheets you must include the sheet name; otherwise the first sheet is assumed.`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return n;let{workbook:r}=n,i=new S(Q(t.address,e.model));if(!i.range)return{error:`Address "${t.address}" is a name reference, not a cell reference.`};let a=i.sheetName||r.getSheets()[0]?.name;if(!a)return{error:`Workbook has no sheets.`};let o=i.getCellId(),s=fs(a,o),c=r.comments.getByCell(a,o);if(c.length>0){let e=c.find(e=>e.parentId===void 0),t={address:s,kind:`thread`,entries:(e?[e,...c.filter(t=>t.parentId===e.id)]:c).map(e=>{let t={author:ds(r,e.personId),text:e.text,isReply:e.parentId!==void 0};return e.datetime!==void 0&&(t.datetime=e.datetime),t})};return e?.resolved!==void 0&&(t.resolved=e.resolved),t}let l=r.notes.getByCell(a,o);return l?{address:s,kind:`note`,author:l.author,text:l.text}:{address:s,kind:`none`}}}),_s=new Z({name:`getComments`,description:"List the cells in the workbook that have a comment or note attached, with author, kind (threaded comment vs. legacy note), reply count, and a short text preview. Comments are how a reviewer flags TODOs, justifies a number, or asks a question on a specific cell — read them when auditing, debugging, or completing a partly-built workbook. Returns up to 25 entries; pass `offset` to page. Use `getComment` to read the full text or thread for a specific cell.",parameters:C.object({sheet:C.string().optional().describe(`Restrict to a single sheet by name. Omit to list across the whole workbook.`),offset:C.number().int().nonnegative().optional().describe(`Pagination offset; results are returned in pages of 25.`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return n;let{workbook:r}=n,i;if(t.sheet!==void 0){if(!r.getSheet(t.sheet))return{error:`Sheet "${t.sheet}" not found.`};i=[t.sheet]}else i=r.getSheets().map(e=>e.name);let a=[];for(let e of i)a.push(...hs(r,e));let o=t.offset??0,s=a.slice(o,o+25),c=o+s.length<a.length,l={comments:s,total:a.length,offset:o,hasMore:c};return c&&(l.nextOffset=o+s.length),l}});function vs(e){let t=e.getWorkbook();if(!t)return{};let n={};for(let e of t.getSheets()){let t=0;for(let n of e.getCells())n.v instanceof x&&t++;t>0&&(n[e.name]=t)}return n}function ys(e,t){let n=new Map,r=e.getWorkbook();if(!r)return{};for(let i of t){let t=new S(i,{ctx:e}),a=t.sheetName||r.getSheets()[0]?.name,o=a?r.getSheet(a):null;if(o&&!t.name?.startsWith(`_xlnm.`))for(let e of t){let t=o.getCellByRange({top:e.top,left:e.left});if(t&&t.v instanceof x){let e=`${t.v}: ${t.v.detail}`,r=n.get(e);r?r.push(t.id):n.set(e,[t.id])}}}return Object.fromEntries(n)}function bs(e,t){return t.map(t=>{let n=new S(t);if(!n.isAddress)throw Error(`Defined-name references are not supported as write targets: "${t}".`);if(n.size!==1)throw Error(`Range references are not supported as write targets: "${t}". Target a single cell.`);let r=n.getCellId(),i=e.getCell(r,n.sheetName||null,n.workbookName||null);return{refId:n.getRefId(),cellId:r,sheetName:n.sheetName,workbookName:n.workbookName,existed:i!==null,f:i?.f??null}})}function xs(e,t){for(let n of t){let t=e.getCell(n.cellId,n.sheetName||null,n.workbookName||null);n.existed?(t?.f??null)!==n.f&&e.getWorkbook(n.workbookName||null)?.editCell(n.refId,{f:n.f}):t!==null&&e.clearCells(n.refId)}}function Ss(e,t,n=[]){let r=bs(e,n),i=de.capture(e);try{return t(e)}finally{xs(e,r),i.applyTo(e)}}function Cs(e){let t=new Map;for(let n of e.getCells()){if(!(n.v instanceof x))continue;let r=new S(n.id,{sheetName:e.name}).toString(),i=n.v.detail?`${n.v.name} (${n.v.detail})`:n.v.name,a=t.get(i);a||(a={key:i,cells:[]},t.set(i,a)),a.cells.push(r)}return Array.from(t.values()).sort((e,t)=>t.cells.length-e.cells.length).slice(0,3).map(e=>({key:e.key,count:e.cells.length,cells:e.cells.slice(0,5)}))}const ws=new Z({name:`describeStructure`,description:`Analyzes the spreadsheet and returns a structured description of all data regions, headers, and labels.
3
- This helps you understand:
4
- - Where data tables are located (islands/regions)
5
- - Which rows are headers vs data
6
- - Column and row labels for each data region
7
- - Sheet names and their contents
8
-
9
- Labels are limited to 50 per sheet. Use totalLabels to check if more exist, and labelOffset to paginate.
10
-
11
- Use this information to write accurate formulas that reference the correct cells and ranges.`,parameters:C.object({sheets:C.array(C.string()).optional().describe(`Optional: limit analysis to specific sheet names. If omitted, all sheets are analyzed.`),labelOffset:C.number().optional().describe(`Optional: skip N labels before returning up to 50. Use for pagination when totalLabels > 50.`)}),run:(e,t)=>{let n=vs(e.model),r=Object.values(n).reduce((e,t)=>e+t,0),i={},a=e.model.getWorkbook();if(a)for(let e of a.getSheets())(n[e.name]??0)>0&&(i[e.name]=Cs(e));return Ss(e.model,e=>{let a=e.getWorkbook();if(!a)return{error:`Model has no workbook`};let o=me(a,{which:[`summary`],recognize2dTables:!0}),s={sheets:[],summary:``,...r>0?{totalErrors:r}:{}},c=t.sheets?.length?new Set(t.sheets.map(e=>e.toLowerCase())):null;for(let e of o.sheets){if(c&&!c.has(e.name.toLowerCase()))continue;let r=n[e.name]??0,a={name:e.name,cellCount:e.cells,formulaCount:e.formulas,...r>0?{errorCount:r}:{},labels:[]};r>0&&i[e.name]&&(a.errorSample=i[e.name]);let o=Math.max(0,t.labelOffset??0),l=e.labels.length,u=e.labels.slice(o);for(let e of u){if(a.labels.length>=50)break;let t=e.for.map(e=>e.ref).join(`, `);a.labels.push(`${e.text} | ${t}`)}l>0&&(a.totalLabels=l),s.sheets.push(a)}return s.summary=`Found ${s.sheets.length} sheet(s).`,s})}}),Ts=C.enum([`none`,`dashDot`,`dashDotDot`,`dashed`,`dotted`,`double`,`hair`,`medium`,`mediumDashDot`,`mediumDashDotDot`,`mediumDashed`,`slantDashDot`,`thick`,`thin`]),Es=C.enum([`none`,`single`,`singleAccounting`,`double`,`doubleAccounting`]),Ds=C.enum([`general`,`left`,`center`,`right`,`fill`,`justify`,`centerContinuous`,`distributed`]),Os=C.enum([`bottom`,`top`,`center`,`justify`,`distributed`]),ks=C.object({bold:C.boolean().describe(`Bold text`).optional(),borderBottomColor:C.string().describe(`Bottom border color`).optional(),borderBottomStyle:Ts.describe(`Bottom border style`).optional(),borderLeftColor:C.string().describe(`Left border color`).optional(),borderLeftStyle:Ts.describe(`Left border style`).optional(),borderRightColor:C.string().describe(`Right border color`).optional(),borderRightStyle:Ts.describe(`Right border style`).optional(),borderTopColor:C.string().describe(`Top border color`).optional(),borderTopStyle:Ts.describe(`Top border style`).optional(),fillColor:C.string().describe(`Cell background color as hex code`).optional(),fontColor:C.string().describe(`Font color as hex code`).optional(),fontName:C.string().describe(`Font family name`).optional(),fontSize:C.number().describe(`Font size in points`).optional(),horizontalAlignment:Ds.describe(`Horizontal text alignment`).optional(),italic:C.boolean().describe(`Italic text`).optional(),numberFormat:C.string().describe(`Number format pattern`).optional(),numberFormatFromFormula:C.string().describe(`Number format from formula`).optional(),shrinkToFit:C.boolean().describe(`Shrink text to fit cell`).optional(),underline:Es.describe(`Text underline style`).optional(),verticalAlignment:Os.describe(`Vertical text alignment`).optional(),wrapText:C.boolean().describe(`Wrap text within cell`).optional()}).describe(`Cell style properties`);function As(e,t){let n=new S(e,{sheetName:t});return(n.height||0)*(n.width||0)<=1e5}function js(e){let t=e.trim().replace(/^#/,``);return/^[0-9a-fA-F]{6}$/.test(t)?t.toUpperCase():/^[0-9a-fA-F]{3}$/.test(t)?[...t].map(e=>e+e).join(``).toUpperCase():null}const Ms=e=>({type:`srgb`,value:e});function Ns(e){let{fillColor:t,fontColor:n,fontName:r,borderTopColor:i,borderBottomColor:a,borderLeftColor:o,borderRightColor:s,...c}=e,l={...c};r!==void 0&&(l.fontFamily=r);let u=[[`fillColor`,t,`fillColor`],[`color`,n,`fontColor`],[`borderTopColor`,i,`borderTopColor`],[`borderBottomColor`,a,`borderBottomColor`],[`borderLeftColor`,o,`borderLeftColor`],[`borderRightColor`,s,`borderRightColor`]];for(let[e,t,n]of u){if(t===void 0)continue;let r=js(t);if(r===null)return{error:`Invalid ${n} "${t}": expected a hex color such as "#RRGGBB"`};l[e]=Ms(r)}return{style:l}}const Ps=new Z({name:`editCellStyles`,description:`Apply formatting styles to cells without changing values.
12
-
13
- IMPORTANT: After using fillCells, you MUST call this to apply formatting to the filled range.`,parameters:C.object({sheet:C.string().describe(`Sheet name to operate on`),apply:C.array(C.object({target:C.string().describe(`Cell or range reference (e.g., "A1", "B2:D10")`),styles:ks})).describe(`Array of style applications`),note:C.string().optional().describe(`Description of this operation for version history`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n,i=r.getSheet(t.sheet);if(!i)return{error:`Sheet not found: ${t.sheet}`};for(let e of t.apply){if(!As(e.target,t.sheet))return{error:`Target range too large: ${e.target}`};let n=Ns(e.styles);if(`error`in n)return{error:n.error};let a=new S(e.target,{sheetName:t.sheet});for(let e of a){let t=i.getCellByRange({top:e.top,left:e.left}),a={s:{...t?.style??{},...n.style}};t?.v!=null&&(a.v=t.v),t?.f!=null&&(a.f=t.f),r.editCell(e,a)}}return e.model.recalculate(),{success:!0,rangesStyled:t.apply.length}}});function Fs(e){let t=[],n=n=>{if(n.type===`trigger`){if(n.what===`edited`||n.what===`written`){let r=ve(e,n.where,!1);r&&t.push(r)}}else n.type===`evaluate`&&n.changed.length>0&&t.push(...n.changed)};e.on(`recalcEvent`,n);try{e.recalculate()}finally{e.off(`recalcEvent`,n)}return Is(t)}function Is(e){let t=[];if(e.length===0)return[];let n=[];for(let r of e){if(r.name){t.push(r);continue}let e=r.sheetName??``;for(let t of r)n.push({sheet:e,row:t.top,col:t.left})}let r=new Set,i=n.filter(e=>{let t=`${e.sheet}|${e.row}|${e.col}`;return r.has(t)?!1:(r.add(t),!0)});i.sort((e,t)=>e.sheet===t.sheet?e.col===t.col?e.row-t.row:e.col-t.col:e.sheet.localeCompare(t.sheet));let a=[],o=0;for(;o<i.length;){let e=i[o];if(!e)break;let t=e,n=i[o+1];for(;n&&n.sheet===e.sheet&&n.col===e.col&&n.row===t.row+1;)o++,t=n,n=i[o+1];let r=pe(e.col),s=e.row+1,c=t.row+1,l=s===c?`${r}${s}`:`${r}${s}:${r}${c}`,u=e.sheet?new S(l,{sheetName:e.sheet}):new S(l);a.push(u.toString()),o++}return a.concat(t.map(e=>e.toString()))}const Ls=C.object({apply:C.array(C.object({target:C.string().describe(`Cell reference (e.g., "A1", "Sheet1!B2")`),value:C.union([C.string(),C.number(),C.boolean(),C.null()]).optional().describe(`Value or formula to write. Formulas start with "=". Omit to only apply style.`),styleIndex:C.number().optional().describe(`Index into the styles array to apply`)})).describe(`Array of cell edits to apply`),styles:C.array(ks).optional().describe(`Array of style objects referenced by styleIndex in apply items`),note:C.string().optional().describe(`Description of this edit for version history`),merge:C.array(C.string()).optional().describe(`Array of ranges to merge (e.g., ["A1:B2", "D4:E6"]). Each range must span at least 2 cells.`),unmerge:C.array(C.string()).optional().describe(`Array of ranges to unmerge. Can specify exact merged range or any cell within a merge.`)});function Rs(e,t){let n=t.range;if(!n||n.size<2)return`Range must span at least 2 cells`;try{return e.mergeCells(n.toString()),null}catch(e){return e instanceof Error?e.message:`Unknown error`}}function zs(e,t){let n=[],r={};for(let i of t)try{let t=new S(i),a=t.sheetName||e.getSheets()[0]?.name;if(!a){r[i]=`No sheet available`;continue}let o=e.getSheet(a);if(!o){r[i]=`Sheet not found: ${a}`;continue}let s=Rs(o,t);s?r[i]=s:n.push(i)}catch(e){r[i]=e instanceof Error?e.message:`Unknown error`}return{merged:n,errors:r}}function Bs(e,t){let n=[],r={};for(let i of t)try{let t=new S(i),a=t.sheetName||e.getSheets()[0]?.name;if(!a){r[i]=`No sheet available`;continue}let o=e.getSheet(a);if(!o){r[i]=`Sheet not found: ${a}`;continue}let s=t.range;if(!s){r[i]=`No merge found in range`;continue}let c=Object.keys(o.merges).length;if(o.unmergeCells(s.toString()),Object.keys(o.merges).length===c){r[i]=`No merge found in range`;continue}n.push(i)}catch(e){r[i]=e instanceof Error?e.message:`Unknown error`}return{unmerged:n,errors:r}}function Vs(e,t,n){if(typeof n!=`string`||n.startsWith(`=`))return null;let r;try{r=new S(t)}catch{return null}let a=r.sheetName||e.getSheets()[0]?.name,o=(a?e.getSheet(a):void 0)?.getCellByRange({top:r.top,left:r.left});if(!o||o.f||typeof o.v!=`number`)return null;let s=f(o.style?.numberFormat??``)?`date`:`number`,c=i(n);return{level:s===`date`||c!=null&&typeof c.v==`number`?`high`:`low`,note:`wrote text "${n}" over a ${s} value — the cell now holds text, not a ${s}`}}const Hs=new Z({name:`editCells`,description:`Permanently write values or formulas to cells. Merge or unmerge cells.
14
-
15
- IMPORTANT: After editing, you MUST call readCalculatedValues to see the resulting changes.
16
- The tool returns a delta showing changes, but you should verify formulas propagated correctly.
17
-
18
- Writing text over a cell that held a number or date is reported in \`warnings\` (level "high" or "low"). A "high" warning usually means a real value was turned into a text string that only looks the same — write the value itself, not its displayed text.
19
-
20
- Examples:
21
- - Set value: { "apply": [{ "target": "A1", "value": 100 }], "note": "Set initial value" }
22
- - Set formula: { "apply": [{ "target": "B1", "value": "=A1*2" }], "note": "Add formula" }
23
- - With style: { "apply": [{ "target": "A1", "value": 100, "styleIndex": 0 }], "styles": [{ "bold": true }], "note": "Bold value" }
24
- - Merge cells: { "apply": [], "merge": ["A1:B2"], "note": "Merge header" }
25
- - Unmerge: { "apply": [], "unmerge": ["A1:B2"], "note": "Unmerge cells" }
26
-
27
- Formulas must start with "=". Values are auto-detected as number, boolean, or string.`,parameters:Ls,run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n,i={},a={},o=[];for(let[e,n]of(t.styles??[]).entries()){let t=Ns(n);if(`error`in t)return{error:`styles[${e}]: ${t.error}`};o.push(t.style)}let s=t.apply.map(t=>({...t,target:Q(t.target,e.model)})),c=t.merge?.map(t=>Q(t,e.model)),l=t.unmerge?.map(t=>Q(t,e.model)),u=[];for(let{target:e}of s)try{let t=new S(e),n=t.sheetName??r.getSheets()[0]?.name;if(!n)continue;let i=r.getSheet(n);if(!i)continue;let a=i.getCellByRange({top:t.top,left:t.left}),o=t.getCellId();a?.M&&a.M!==o&&u.push(`${e} is merged into ${a.M}`)}catch{}if(u.length>0)return{error:`Cannot write to non-anchor merged cells: ${u.join(`, `)}. Write to anchor cells instead.`};for(let{target:e,value:t,styleIndex:n}of s)try{let i=Vs(r,e,t),s={};if(typeof t==`string`&&t.startsWith(`=`)?s.f=t.replace(/^=/,``):t!==void 0&&(s.v=t),n!==void 0&&o[n]&&(s.s=o[n]),s.f===void 0&&s.v===void 0&&s.s===void 0)continue;r.editCell(e,s),i&&(a[e]=i)}catch(t){i[e]=t instanceof Error?t.message:`Unknown error`}let d=c?zs(r,c):{merged:[],errors:{}},f=l?Bs(r,l):{unmerged:[],errors:{}},p={...d.errors,...f.errors},m=Fs(e.model),h=ys(e.model,m);return{success:!0,cellsModified:s.length,changedCells:m,merged:d.merged.length>0?d.merged:void 0,unmerged:f.unmerged.length>0?f.unmerged:void 0,errors:Object.keys(i).length>0?i:void 0,mergeErrors:Object.keys(p).length>0?p:void 0,cell_errors:Object.keys(h).length>0?h:void 0,warnings:Object.keys(a).length>0?a:void 0}}});function Us(e){return e?.z||``}var Ws=class{_stepsize;_dir;_anchor;_cells;_style;constructor(e,t,n){this._anchor=n,this._dir=t||`row`,this._cells=e}_cellIdToFillIndex(e){let[t,n]=fe(this._anchor),[r,i]=fe(e),a=r-t;return this._dir===`col`&&(a=i-n),a}_matchingCellByIndex(e){let t=Math.abs(e);e<0&&this._stepsize&&--t,t>this._cells.length-1&&(t%=this._cells.length);let n=this._cells[t];if(!n)throw Error(`No cell at index ${t}`);return n}_numfmtAt(e){let t=this._cellIdToFillIndex(e);return Us(this._matchingCellByIndex(t))}_formulaAt(t,n){let r=n.f;if(!r)throw Error(`Cell has no formula`);let i=h(r,n.id),a=this._numfmtAt(t);return{f:e(i,t,{wrapEdges:!1}),z:a}}at(e){let t=this._cellIdToFillIndex(e),n=this._matchingCellByIndex(t);if(n.f)return this._formulaAt(e,n);let r={z:this._numfmtAt(e),s:this._style??void 0};return n.v!==null&&(r.v=n.v),r}},Gs=class extends Ws{constructor(e,t,n){super(e,t||`col`,n),this._constructSequence(e)}_constructSequence(e){if(e.length===1)return;let t=e[0],n=e[1];if(!t||!n||(this._style=t.style,typeof t.v!=`number`||typeof n.v!=`number`))return;let r=n.v-t.v;if(r!==0){for(let t=2;t<e.length;t++){let n=e[t]?.v,i=e[t-1]?.v;if(typeof n!=`number`||typeof i!=`number`||r!==n-i)return}this._stepsize=r}}_getDecimalPlaces(e){let t=e.toString(),n=t.indexOf(`.`);return n===-1?0:t.length-n-1}at(e){if(this._stepsize){let t=this._cellIdToFillIndex(e),n=this._matchingCellByIndex(this._cellIdToFillIndex(this._anchor));if(typeof n.v!=`number`)return super.at(e);let r=n.v,i=r+t*this._stepsize,a=Math.max(this._getDecimalPlaces(r),this._getDecimalPlaces(this._stepsize));return i=Number(i.toFixed(a)),{v:i,z:this._numfmtAt(e),s:this._style??void 0}}return super.at(e)}},Ks=class extends Ws{_granularity;constructor(e,t,n){super(e,t||`col`,n),this._constructSequence(e)}_constructSequence(e){if(e.length===1)this._stepsize=1,this._granularity=`day`;else{let t=this._dateStepsize(e,`day`),n=this._dateStepsize(e,`month`),r=this._dateStepsize(e,`year`),i=null;t&&(i=`day`),n&&(i=`month`),r&&(i=`year`),i&&(this._stepsize=r||n||t,this._granularity=i)}}_dateStepsize(e,t=`day`){let n=e[0],r=e[1];if(!n||!r)return null;let i=this._stepBetweenDates(n,r,t);if(i===0)return null;for(let n=2;n<e.length;n++){let r=e[n],a=e[n-1];if(!r||!a||this._stepBetweenDates(a,r,t)!==i)return null}return i}_stepBetweenDates(e,t,n=`day`){let[r=0,i=0]=a(e.v),[o=0,s=0]=a(t.v);if(n===`year`)return o-r;if(n===`month`)return s-i;if(n===`day`)return typeof t.v!=`number`||typeof e.v!=`number`?0:t.v-e.v;throw Error(`Only supports [year, month, day] as steps but received: ${String(n)}`)}at(e){if(this._stepsize&&this._granularity){let t=this._cellIdToFillIndex(e),n=this._cells[0];if(!n)return super.at(e);let r=n.v,i=a(r),o={day:2,month:1,year:0}[this._granularity];return i[o]=(i[o]??0)+t*this._stepsize,{v:u(i),z:this._numfmtAt(e)}}return super.at(e)}};function qs(e){return e.f?`formula`:typeof e.v==`number`?f(Us(e))?`date`:`number`:typeof e.v==`string`&&(e.v===`true`||e.v===`false`)?`boolean`:`unknown`}function Js(e,t){let n=new S(e).range,r=new S(t).range;if(!n||!r)throw Error(`Both selection and extend_to must be valid ranges`);let i=n.top===r.top&&n.bottom===r.bottom,a=n.left===r.left&&n.right===r.right;if(a&&!i)return`row`;if(i&&!a)return`col`;throw Error(a&&i?`Selection and extend_to ranges are identical — nothing to fill`:`Selection and extend_to differ in both dimensions — cannot determine fill direction`)}var Ys=class{_dir;_anchor;_seq;constructor(e,t,n){let r=e.range,i=t.range;if(!r||!i)throw Error(`Selection and extend_to must be valid ranges`);this._dir=Js(e.toString(),t.toString()),this._anchor=r.collapse().toString(),this._seq=new Map,this._constructSequences(e,n)}_cellIdToSeqIndex(e){let[t,n]=fe(this._anchor),[r,i]=fe(e);return this._dir===`col`?r-t:i-n}_constructSequences(e,t){let n=new Map;for(let r of e){let e=t(r.top,r.left);if(!e)continue;let i=this._cellIdToSeqIndex(e.id),a=n.get(i);a||(a=[],n.set(i,a)),a.push(e)}for(let[e,t]of n){let n=new Set(t.map(qs));n.size===1&&n.has(`number`)?this._seq.set(e,new Gs(t,this._dir,this._anchor)):n.size===1&&n.has(`date`)?this._seq.set(e,new Ks(t,this._dir,this._anchor)):this._seq.set(e,new Ws(t,this._dir,this._anchor))}}at(e){let t=this._cellIdToSeqIndex(e),n=this._seq.get(t);return n?n.at(e):{}}};const Xs=new Z({name:`fillCells`,description:`Extend a selection by filling cells with auto-detected patterns (numbers, dates, formulas).
28
- Similar to Excel's fill handle - detects sequences and continues them.
29
- Fill direction is inferred from selection and extend_to: the dimension that changes determines the fill axis.
30
-
31
- IMPORTANT: After filling, you MUST call editCellStyles to apply formatting to the filled cells.
32
-
33
- Examples:
34
- - Fill down: { "sheet": "Sheet1", "selection": "A1:A3", "extend_to": "A1:A10", "note": "Extend series" }
35
- - Fill right: { "sheet": "Sheet1", "selection": "A1:C1", "extend_to": "A1:F1", "note": "Extend headers" }
36
- - Fill up: { "sheet": "Sheet1", "selection": "A8:B10", "extend_to": "A1:B10", "note": "Extend upward" }`,parameters:C.object({sheet:C.string().describe(`Sheet name to operate on`),selection:C.string().describe(`Source range containing the pattern (e.g., "A1:A3")`),extend_to:C.string().describe(`Target range to fill to (e.g., "A1:A10")`),note:C.string().optional().describe(`Description of this operation for version history`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n,i=r.getSheet(t.sheet);if(!i)return{error:`Sheet not found: ${t.sheet}`};if(!As(t.selection,t.sheet))return{error:`Selection range too large: ${t.selection}`};if(!As(t.extend_to,t.sheet))return{error:`Extend_to range too large: ${t.extend_to}`};let a=new S(t.selection),o=new S(t.extend_to);if(!a.range||!o.range)return{error:`Invalid range: ${t.selection} or ${t.extend_to}`};let s=new Ys(a,o,(e,t)=>i.getCellByRange({top:e,left:t})),c=new S(t.extend_to,{sheetName:i.name});for(let e of c){let t=is(e.range.toString()),n=s.at(t);r.editCell(e,n)}let l=Fs(e.model),u=ys(e.model,l);return{success:!0,filledRange:t.extend_to,changedCells:l,cell_errors:Object.keys(u).length>0?u:void 0}}});function Zs(e){switch(e.type){case`srgb`:case`preset`:case`system`:case`theme`:return e.value.toLowerCase();case`scrgb`:return`scrgb(${e.red}%,${e.green}%,${e.blue}%)`;case`hsl`:return`hsl(${e.hue},${e.saturation}%,${e.lightness}%)`;case`indexed`:return`indexed(${e.value})`;case`auto`:return`auto`;default:return e}}function Qs(e){return e==null?null:e instanceof x?String(e):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:String(e)}function $s(e){return e===null?`null`:typeof e==`string`?JSON.stringify(e):e.toString()}function ec(e){let t=e.origin?e.origin.withPrefix({workbookName:``}).toString():void 0;return{name:e.name,code:e.code,...e.detail?{detail:e.detail}:{},...t?{origin:t}:{}}}const tc=65536;function nc(e){if(e==null)return`z`;if(typeof e==`boolean`)return`b`;if(typeof e==`number`)return`n`;if(typeof e==`string`)return`s`;if(e instanceof x)return`e`}function rc(e){return e.replace(/^=?/,`=`)}function ic(e,t){return pe(e)+(t+1)}function ac(e,t,r,i,a,o){if(!e)return{t:`z`,ref:t};let s={ref:t},c=e.v,l=nc(c);l&&(s.t=l);let u=Qs(c);u!=null&&(s.v=u),e.f&&(s.f=e.f),c instanceof x&&(s.error=ec(c));let d=e.style?.numberFormat;if(d){s.num_format=d;try{s.formatted=n(d,c)}catch{s.formatted=`######`}}let{numberFormatFromFormula:f,...p}=e.style??{};if(r&&Object.keys(p).length>0&&(s.style_index=r.styles.findOrCreate(p)),i){let t=e.style;t&&(s.style=t);let n=e.href;n&&(s.href=n)}if(a&&o){let e=a.get(o,t);e&&(s.mismatch={note:`Excel cached ${$s(e.cachedValue)}; Apiary computed ${$s(e.calculatedValue)}`,cachedValue:e.cachedValue,calculatedValue:e.calculatedValue})}return s}function oc(e,t,n){let r=rc(t),i=e.runFormula(r,n?.evalContext??null);if(i instanceof S&&(i=i.withContext(e),i.name&&(i=ge(i.resolveToNonName()))),i==null)return{t:`z`,ref:`#RESULT`};let a=!1;if((typeof i==`number`||typeof i==`string`||typeof i==`boolean`||i instanceof x)&&(i=se.of(i),a=!0),i instanceof se||i instanceof S){let t=i.size??0;if(t>tc)throw Error(`Query exceeds ${tc} cell limit`);let r=i.resolveAreaCells(`any-cell-information`),o=i.width??0,s=i.height??0,c=i instanceof S?i.left??0:0,l=i instanceof S?i.top??0:0,u=e.getWorkbook(),d=i instanceof S?i.sheetName||u?.getSheets()[0]?.name:void 0,f=d?u?.getSheet(d)??null:null;if(t===1){let e=r?.[0]?.[0]??null,t=a?`#RESULT`:ic(c,l),o=ac(e,t,u,n?.includeStyles,n?.mismatches,a?void 0:d);if(e?.M&&i instanceof S&&f){let n=e.M;if(t===n){let e=f.merges[n];if(e){let[t,r]=e,i=new S(n);o.mergedRange=`${n}:${ic(i.left+t-1,i.top+r-1)}`}}else o.mergedInto=n}return o}let p={},m=n?.maxFormulas!=null&&t>n.maxFormulas;for(let e=0;e<s;e++){let t=r[e];for(let r=0;r<o;r++){let i=t?.[r];if(!i)continue;let a=ic(c+r,l+e),{ref:o,...s}=ac(i,a,u,n?.includeStyles,n?.mismatches,d);if(s.t!==`z`){if(m&&s.f&&(s.f=`[formula]`),i.M&&f&&a===i.M){let e=f.merges[i.M];if(e){let[t,n]=e,r=new S(i.M),a=ic(r.left+t-1,r.top+n-1);s.mergedRange=`${i.M}:${a}`}}p[a]=s}}}return m&&(p._note=`Formulas suppressed (${t} cells). Read ≤${n?.maxFormulas} cells to see formulas.`),p}throw Error(`Cannot read expression: ${t}`)}function sc(e,t,n,r){let i=e.getWorkbook();if(!i)throw Error(`readCellsByCoords: model has no workbook`);let a=t||i.getSheets()[0]?.name;if(!a)throw Error(`readCellsByCoords: workbook has no sheets`);let o=i.getSheet(a);if(!o)throw Error(`readCellsByCoords: sheet "${a}" not found`);let s=r?.maxFormulas!=null&&n.length>r.maxFormulas,c={};for(let{row:e,column:t}of n){let n=o.getCellByRange({top:e,left:t});if(!n)continue;let l=ic(t,e),{ref:u,...d}=ac(n,l,i,r?.includeStyles,r?.mismatches,a);if(d.t!==`z`){if(s&&d.f&&(d.f=`[formula]`),n.M&&l===n.M){let e=o.merges[n.M];if(e){let[t,r]=e,i=new S(n.M),a=ic(i.left+t-1,i.top+r-1);d.mergedRange=`${n.M}:${a}`}}c[l]=d}}return s&&(c._note=`Formulas suppressed (${n.length} cells). Read ≤${r?.maxFormulas} cells to see formulas.`),c}const cc=1e4,lc={red:`FF0000`,darkred:`8B0000`,lightcoral:`F08080`,crimson:`DC143C`,firebrick:`B22222`,indianred:`CD5C5C`,salmon:`FA8072`,darksalmon:`E9967A`,lightsalmon:`FFA07A`,tomato:`FF6347`,orangered:`FF4500`,orange:`FFA500`,darkorange:`FF8C00`,coral:`FF7F50`,yellow:`FFFF00`,lightyellow:`FFFFE0`,lemonchiffon:`FFFACD`,lightgoldenrodyellow:`FAFAD2`,papayawhip:`FFEFD5`,moccasin:`FFE4B5`,peachpuff:`FFDAB9`,palegoldenrod:`EEE8AA`,khaki:`F0E68C`,darkkhaki:`BDB76B`,gold:`FFD700`,goldenrod:`DAA520`,darkgoldenrod:`B8860B`,green:`008000`,darkgreen:`006400`,lightgreen:`90EE90`,palegreen:`98FB98`,lime:`00FF00`,limegreen:`32CD32`,forestgreen:`228B22`,seagreen:`2E8B57`,mediumseagreen:`3CB371`,darkseagreen:`8FBC8F`,lightseagreen:`20B2AA`,springgreen:`00FF7F`,mediumspringgreen:`00FA9A`,yellowgreen:`9ACD32`,greenyellow:`ADFF2F`,chartreuse:`7FFF00`,lawngreen:`7CFC00`,olivedrab:`6B8E23`,olive:`808000`,darkolivegreen:`556B2F`,teal:`008080`,cyan:`00FFFF`,aqua:`00FFFF`,aquamarine:`7FFFD4`,mediumaquamarine:`66CDAA`,turquoise:`40E0D0`,mediumturquoise:`48D1CC`,darkturquoise:`00CED1`,paleturquoise:`AFEEEE`,lightcyan:`E0FFFF`,blue:`0000FF`,darkblue:`00008B`,mediumblue:`0000CD`,lightblue:`ADD8E6`,powderblue:`B0E0E6`,skyblue:`87CEEB`,lightskyblue:`87CEFA`,deepskyblue:`00BFFF`,dodgerblue:`1E90FF`,cornflowerblue:`6495ED`,royalblue:`4169E1`,steelblue:`4682B4`,lightsteelblue:`B0C4DE`,cadetblue:`5F9EA0`,purple:`800080`,darkmagenta:`8B008B`,magenta:`FF00FF`,fuchsia:`FF00FF`,mediumpurple:`9370DB`,blueviolet:`8A2BE2`,darkviolet:`9400D3`,darkorchid:`9932CC`,mediumorchid:`BA55D3`,orchid:`DA70D6`,violet:`EE82EE`,plum:`DDA0DD`,thistle:`D8BFD8`,lavender:`E6E6FA`,indigo:`4B0082`,slateblue:`6A5ACD`,mediumslateblue:`7B68EE`,darkslateblue:`483D8B`,rebeccapurple:`663399`,pink:`FFC0CB`,lightpink:`FFB6C1`,hotpink:`FF69B4`,deeppink:`FF1493`,mediumvioletred:`C71585`,palevioletred:`DB7093`,brown:`A52A2A`,maroon:`800000`,saddlebrown:`8B4513`,sienna:`A0522D`,chocolate:`D2691E`,peru:`CD853F`,sandybrown:`F4A460`,rosybrown:`BC8F8F`,tan:`D2B48C`,burlywood:`DEB887`,wheat:`F5DEB3`,navajowhite:`FFDEAD`,bisque:`FFE4C4`,blanchedalmond:`FFEBCD`,cornsilk:`FFF8DC`,white:`FFFFFF`,snow:`FFFAFA`,honeydew:`F0FFF0`,mintcream:`F5FFFA`,azure:`F0FFFF`,aliceblue:`F0F8FF`,ghostwhite:`F8F8FF`,whitesmoke:`F5F5F5`,seashell:`FFF5EE`,beige:`F5F5DC`,oldlace:`FDF5E6`,floralwhite:`FFFAF0`,ivory:`FFFFF0`,antiquewhite:`FAEBD7`,linen:`FAF0E6`,lavenderblush:`FFF0F5`,mistyrose:`FFE4E1`,gainsboro:`DCDCDC`,lightgray:`D3D3D3`,lightgrey:`D3D3D3`,silver:`C0C0C0`,darkgray:`A9A9A9`,darkgrey:`A9A9A9`,gray:`808080`,grey:`808080`,dimgray:`696969`,dimgrey:`696969`,lightslategray:`778899`,lightslategrey:`778899`,slategray:`708090`,slategrey:`708090`,darkslategray:`2F4F4F`,darkslategrey:`2F4F4F`,black:`000000`,navy:`000080`,midnightblue:`191970`},uc={};for(let[e,t]of Object.entries(lc)){let n=uc[t];(!n||n.length>e.length)&&(uc[t]=e)}function dc(e){let t=e.toLowerCase().trim().replace(/^#/,``).replace(/\s+/g,``),n=lc[t];return n?[t,n.toLowerCase()]:[t]}const fc=C.enum([`AND`,`OR`]),pc=C.object({sheet:C.string().optional().describe(`Restrict search to a single sheet by name.`),range:C.string().optional().describe(`Restrict search to an A1-style range, e.g. 'Sheet1!B2:D10' or 'B2:D10'. An unqualified range resolves against 'sheet' if given, otherwise the first sheet. Defined names are not accepted. Ranges larger than 10,000 cells are rejected.`),matchMode:fc.optional().describe(`"AND" = all criteria must match (narrows results). "OR" = any criterion matches (broader sweep). Defaults to "AND".`),hasFormula:C.boolean().optional().describe(`Match cells that have (true) or don't have (false) a formula.`),fillColor:C.string().min(1,`fillColor must not be an empty string`).optional().describe(`Match cells whose fill color matches this search term. Accepts hex values ("FFFF00", "#FF0000"), partial hex ("FF"), named colors ("yellow", "light blue", "dark green"), and Excel preset names. Case-insensitive.`),formulaContains:C.string().min(1,`formulaContains must not be an empty string`).optional().describe(`Match cells whose formula text contains this substring (case-insensitive).`),valueContains:C.string().min(1,`valueContains must not be an empty string`).optional().describe(`Match cells whose value (converted to text) contains this substring (case-insensitive).`),valueWithin:C.array(C.number()).length(2).optional().describe(`Match cells whose numeric value falls within this inclusive range [min, max].`)});function mc(e){let t=e?.fillColor;if(!t)return;let n=Zs(t),r=uc[n.toUpperCase()];return r?`${n} (${r})`:n}function hc(e,t){let n=e?.fillColor;if(!n)return!1;let r=Zs(n);return t.some(e=>r.includes(e))}function gc(e){return e==null?``:typeof e==`string`?e:String(e)}const _c=new Z({name:`findCells`,description:`Search for cells matching specified criteria within a sheet or range. Returns up to 200 matches. Use matchMode to control whether all criteria must match (AND, default) or any (OR). Range iteration is limited to ${cc.toLocaleString()} cells — use sheet scope for larger searches.`,parameters:pc,run:(e,t)=>{let n=ns(e.model);if(`error`in n)return n;let{workbook:r}=n,i=t.matchMode??`AND`,a,o;if(t.range){if(o=new S(Q(t.range,e.model),{ctx:e.model,sheetName:t.sheet}),!o.range)return{error:`"${t.range}" is a name reference, which is not supported for 'range'. Pass an A1-style range like 'Sheet1!B2:D10' instead.`};let n=o.sheetName||r.getSheets()[0]?.name||``,i=n?r.getSheet(n):null;if(!i)return{error:`Sheet "${n}" not found.`};a=[i];let s=o.range?.size;if(s!==void 0&&s>cc)return{error:`Range "${t.range}" covers ${s.toLocaleString()} cells, exceeding the ${cc.toLocaleString()}-cell limit. Narrow the range or search by sheet instead.`}}else if(t.sheet){let e=r.getSheet(t.sheet);if(!e)return{error:`Sheet "${t.sheet}" not found.`};a=[e]}else a=r.getSheets();let s=[`fillColor`,`formulaContains`,`valueContains`].find(e=>t[e]===``);if(s)return{error:`Parameter "${s}" must not be an empty string.`};if(t.hasFormula===void 0&&t.fillColor===void 0&&t.formulaContains===void 0&&t.valueContains===void 0&&t.valueWithin===void 0)return{error:`At least one search criterion is required (hasFormula, fillColor, formulaContains, valueContains, or valueWithin).`};let[c,l]=t.valueWithin??[];if(c!==void 0&&l!==void 0&&c>l)return{error:`valueWithin bounds are inverted: min ${c} is greater than max ${l}. Pass [min, max].`};let u=t.fillColor?dc(t.fillColor):void 0,d={matchMode:i,hasFormula:t.hasFormula,fillColorTerms:u,formulaContainsLower:t.formulaContains?.toLowerCase(),valueContainsLower:t.valueContains?.toLowerCase(),valueWithinMin:c,valueWithinMax:l},f=0,p=[];for(let e of a)if(o?.range)for(let{row:t,column:n}of o.range.iterCoordinates()){let r=e.getCellByRange({top:t,left:n});if(!r)continue;let i=vc(r,d);if(i&&(f++,p.length<200)){let r=new S(ic(n,t),{sheetName:e.name}).toString();p.push({ref:r,...i})}}else for(let t of e.getCells(!0)){let n=vc(t,d);if(n&&(f++,p.length<200)){let r=new S(t.id,{sheetName:e.name}).toString();p.push({ref:r,...n})}}let m=f>p.length;return{matches:p,totalMatches:f,...m?{truncated:{maxMatches:200,hint:`Search reached the maximum of 200 matches. Narrow the scope or add more criteria to find specific cells.`}}:{}}}});function vc(e,t){let n=[];if(t.hasFormula!==void 0){let r=e.f!=null;n.push(r===t.hasFormula)}if(t.formulaContainsLower!==void 0){let r=e.f!=null&&e.f.toLowerCase().includes(t.formulaContainsLower);n.push(r)}if(t.valueContainsLower!==void 0){let r=gc(e.v).toLowerCase();n.push(r.includes(t.valueContainsLower))}if(t.valueWithinMin!==void 0&&t.valueWithinMax!==void 0){let r=typeof e.v==`number`&&e.v>=t.valueWithinMin&&e.v<=t.valueWithinMax;n.push(r)}if(t.fillColorTerms!==void 0&&n.push(hc(e.style,t.fillColorTerms)),n.length===0)return null;if(t.matchMode===`AND`){if(!n.every(Boolean))return null}else if(!n.some(Boolean))return null;let r={};e.v!==null&&(r.value=gc(e.v)),e.f&&(r.formula=e.f);let i=mc(e.style);return i&&(r.fillColor=i),r}const yc=new Z({name:`getStyles`,description:`Get the workbook's style definitions. Returns styles where each index corresponds to a style_index in cell data. Use this to understand what formatting (colors, fonts, borders, etc.) is applied to cells.
37
-
38
- If no indices are provided, returns all styles as an array.
39
- If indices are provided, returns only those styles as an object keyed by index.`,parameters:C.object({indices:C.array(C.number()).optional().describe(`Optional array of style indices to fetch. If omitted, returns all styles.`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n;if(t.indices&&t.indices.length>0){let e={};for(let n of t.indices)e[n]=r.styles.get(n);return e}return r.styles.toArray()}}),bc=new Z({name:`goalSeek`,description:`Find the input value needed to achieve a target result (like Excel's Goal Seek).
40
- Iteratively adjusts the control cell until the target cell reaches the desired value.`,parameters:C.object({write:C.array(C.object({cell:C.string().describe(`Cell reference`),value:C.union([C.string(),C.number(),C.boolean(),C.null()]).describe(`Value to write before running goal seek`)})).describe(`Values to write before goal seeking`),goalSeek:C.object({targetCell:C.string().describe(`Cell containing the formula to reach target value`),targetValue:C.number().describe(`Desired value for the target cell`),controlCell:C.string().describe(`Cell to adjust to achieve the target`)}).describe(`Goal seek parameters`),persist:C.boolean().optional().describe(`Whether to persist the solved control cell (and any pre-seek writes) to the workbook. Defaults to false: a pure calculation that reports the solution without changing the model.`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let r=Q(t.goalSeek.targetCell,e.model),i=Q(t.goalSeek.controlCell,e.model),a=S.from(r);if(!a)return{error:`goalSeek targetCell is not a valid reference`};let o=S.from(i);if(!o)return{error:`goalSeek controlCell is not a valid reference`};let s=(t.write??[]).map(({cell:t,value:n})=>({cell:Q(t,e.model),value:n})),c=new Set([r]),l=e=>{if(s.length>0){let t=s.filter(({cell:e})=>!c.has(e)).map(({cell:e,value:t})=>[e,t]);t.length>0&&(e.writeMultiple(t,{skipRecalc:!0}),e.recalculate())}let n=e.goalSeek(o,a,t.goalSeek.targetValue),l=as(n);return l?{error:l}:{success:!0,goalSeek:{targetCell:r,targetValue:t.goalSeek.targetValue,controlCell:i,solution:n}}};if(!t.persist){let t=s.map(({cell:e})=>e).filter(e=>!c.has(e)).concat(i);return Ss(e.model,l,t)}let u=e.model.readValue(`=${i}`),d=l(e.model);if(`error`in d){let t=e.model.readValue(`=${i}`);return{error:`${d.error} Control cell ${i} was not reverted and is left at ${String(t)} (previously ${String(u)}).`}}return d}});function xc(e,t){let n=e.chunkedGraph._getVertices(t.workbookKey)?.get(t);if(n?.data)return{id:t,data:n.data};for(let n of e.calculated)if(n.vertexId.contains(t))return{id:n.vertexId,data:n};let r=null;return e.chunkedGraph.visitRangeVertices(e=>{!r&&e.data&&e.id.contains(t)&&(r={id:e.id,data:e.data})}),r||null}var Sc=class{desc;direction;maxDepth;maxNodes;visited=new Set;queue=[];nodeCount=0;constructor(e,t,n,r){this.desc=e,this.direction=t,this.maxDepth=n,this.maxNodes=r}walk(e,t){let n=this.createNode(t);this.nodeCount=1,this.enqueueIfWalkable(n,e,t,0);for(let e=this.queue.shift();e!=null;e=this.queue.shift())this.populateChildren(e.node,e.id,e.depth);return{[t.ref.toString()]:n}}createNode(e){let t={type:e.type,labels:e.labels.map(e=>e.text),formula:e.formula??null};return e.rootHeight!=null&&(t.rootHeight=e.rootHeight),e.leafDepth!=null&&(t.leafDepth=e.leafDepth),t}enqueueIfWalkable(e,t,n,r){this.direction===`precedents`&&!n.formula||this.queue.push({node:e,id:t,depth:r})}populateChildren(e,t,n){if(this.visited.has(t.key)){e.alreadyVisited=!0;return}if(n>=this.maxDepth){e.truncated={reason:`maxDepth`};return}this.visited.add(t.key);let r=(this.direction===`precedents`?this.desc.chunkedGraph.getOutgoingEdges(t):this.desc.chunkedGraph.getIncomingEdges(t)).filter(e=>e.kind!==`nonvalue`),i={},a=0,o=0;for(let e of r){let t=this.direction===`precedents`?e.to:e.from,r=t.data;if(!r||(o+=1,this.nodeCount>=this.maxNodes))continue;let s=this.createNode(r);this.nodeCount+=1,this.enqueueIfWalkable(s,t.id,r,n+1),i[r.ref.toString()]=s,a+=1}a>0&&(this.direction===`precedents`?e.precedents=i:e.dependents=i),o>a&&(e.truncated={reason:`maxNodes`,totalChildren:o})}};function Cc(e,t){try{let n=ve(e,t,!1);return n?n.toString():t.key}catch{return t.key}}var wc=class{model;direction;maxDepth;maxNodes;graph;visited=new Set;queue=[];nodeCount=0;constructor(e,t,n,r){this.model=e,this.direction=t,this.maxDepth=n,this.maxNodes=r,this.graph=e._graph}walk(e){let t=this.createCellNode(e);this.nodeCount=1,this.enqueueIfWalkable(t,e,0);for(let e=this.queue.shift();e!=null;e=this.queue.shift())this.populateChildren(e.node,e.id,e.depth);return{[Cc(this.model,e)]:t}}enqueueIfWalkable(e,t,n){this.direction===`precedents`&&!e.formula||this.queue.push({node:e,id:t,depth:n})}createCellNode(e){let t=_e(this.model,e),n={kind:`cell`,formula:t?.f??null};return Tc(n,t),n}createNameNode(e){let t=_e(this.model,e),n={kind:`name`,formula:t?.f??null};return Tc(n,t),n}createRangeNode(e,t){let n={kind:`range`,formula:null};this.nodeCount+=1;let r=[];if(e.visitCells(e=>r.push(e)),!r.some(e=>_e(this.model,e)?.f!=null))return n;let i={},a=0;for(let e of r){if(this.nodeCount>=this.maxNodes)break;let n=this.createCellNode(e);this.nodeCount+=1,i[Cc(this.model,e)]=n,this.enqueueIfWalkable(n,e,t),a+=1}return n.precedents=i,r.length>a&&(n.truncated={reason:`maxNodes`,totalChildren:r.length}),n}populateChildren(e,t,n){if(this.visited.has(t.key)){e.alreadyVisited=!0;return}if(n>=this.maxDepth){e.truncated={reason:`maxDepth`};return}this.visited.add(t.key);let r=(this.direction===`precedents`?this.graph.getOutgoingEdges(t):this.graph.getIncomingEdges(t)).filter(e=>e.kind!==`nonvalue`),i={},a=0;for(let e of r){if(this.nodeCount>=this.maxNodes)break;let t=this.direction===`precedents`?e.to.id:e.from.id,r=this.createChildForId(t,n+1);r&&(i[Cc(this.model,t)]=r,a+=1)}a>0&&(this.direction===`precedents`?e.precedents=i:e.dependents=i),r.length>a&&(e.truncated={reason:`maxNodes`,totalChildren:r.length})}createChildForId(e,t){if(e instanceof oe){let n=this.createCellNode(e);return this.nodeCount+=1,this.enqueueIfWalkable(n,e,t),n}if(e instanceof le){let n=this.createNameNode(e);return this.nodeCount+=1,this.enqueueIfWalkable(n,e,t),n}return e instanceof ue?this.createRangeNode(e,t):null}};function Tc(e,t){if(!t){e.value=null;return}let n=t.v;if(n instanceof x){e.value=null,e.errorValue=n.name;return}if(n==null||typeof n==`string`||typeof n==`number`||typeof n==`boolean`){e.value=n;return}e.value=String(n)}function Ec(e,t){let n=rc(Q(t,e)),r=e.readCell(n);return r instanceof ae?r:{error:`Could not resolve reference to a cell.`}}const Dc=C.object({reference:C.string().describe(`Cell reference to trace (e.g. 'C1', 'Sheet2!A1')`),mode:C.enum([`cells`,`grouped`]).default(`grouped`).describe(`Output mode: 'grouped' (default) shows chunks of cells sharing a formula pattern, labeled from nearby headers — token-efficient for structure. 'cells' drills into individual cells.`),maxDepth:C.number().int().positive().max(50).optional().describe(`Maximum recursion depth through formula cells (default 10). Range expansion does not consume depth.`),maxNodes:C.number().int().positive().max(500).optional().describe(`Total node budget for the returned tree (default 100). When the budget is exhausted, the node whose children were cut is marked truncated with totalChildren; re-query a specific cell to drill deeper.`)});function Oc(e,t,n){return new Z({name:t,description:n,parameters:Dc,run:(t,n)=>n.mode===`cells`?kc(t.model,e,n):Ac(t.model,e,n)})}function kc(e,t,n){let r=Ec(e,n.reference);return ts(r)?r:new wc(e,t,n.maxDepth??10,n.maxNodes??100).walk(new oe(r.workbookKey,r.sheetIndex,r.rowIndex,r.colIndex))}function Ac(e,t,n){let r=Ec(e,n.reference);if(ts(r))return r;let i=e.getWorkbook();if(!i)return{error:`Model has no workbook.`};let a=me(i,{which:[`parameters`,`calculated`,`chunkedGraph`],recognize2dTables:!0}),o=xc(a,new oe(r.workbookKey,r.sheetIndex,r.rowIndex,r.colIndex));return o?new Sc(a,t,n.maxDepth??10,n.maxNodes??100).walk(o.id,o.data):{error:`Cell ${n.reference} has no formula dependencies in this workbook.`}}const jc=Oc(`dependents`,`dependents`,`Trace downstream dependents — the cells that read from a given cell, transitively.
41
- Default mode 'grouped': cells sharing a formula pattern are collapsed into labeled chunks,
42
- labeled from nearby headers. This provides a token-efficient structural view that shows how
43
- values flow from parameters through intermediate calculations to outputs.
44
-
45
- Switch to mode: "cells" to drill into individual cells: each node carries the formula, value,
46
- and error of the dependent cell so you can see exactly how a value propagates through the sheet.
47
- When a formula uses a range, Apiary resolves range containment internally; the dependent formula
48
- appears as a direct child of the queried cell rather than via an intermediate range node.
49
-
50
- "grouped" response shape — each node carries:
51
- - type: "output" (computed, no dependents), "inter" (computed, has dependents), "data" (value range), "param" (single value cell)
52
- - labels: human-readable names derived from nearby headers
53
- - formula: the formula pattern for this chunk (with relative references)
54
- - rootHeight: dependency distance from graph roots (parameters/data)
55
- - leafDepth: dependency distance from graph leaves (outputs)
56
- - dependents: dict of downstream chunk nodes keyed by their ref (omitted for terminal outputs)
57
- - alreadyVisited: true when this chunk was expanded elsewhere in the tree (diamond/cycle cut)
58
- - truncated: present when traversal stopped early; reason is "maxDepth" or "maxNodes"; totalChildren reports the real count when children were cut short
59
-
60
- "cells" response shape — each node carries:
61
- - kind: "cell" or "name"
62
- - formula: the formula string, or null for value cells
63
- - value: the calculated value
64
- - errorValue: present only when the cell evaluates to a formula error
65
- - dependents: a dict of child nodes keyed by their own ref (omitted for leaves with no downstream consumers)
66
- - alreadyVisited: true when this node has been fully expanded elsewhere in the tree (diamond/cycle cut)
67
- - truncated: present when traversal stopped early; reason is "maxDepth" or "maxNodes"; totalChildren reports the real count when children were cut short
68
-
69
- Both modes use maxDepth (default 10, max 50) to bound recursion and maxNodes (default 100, max 500) as a global budget on the returned tree.`);function Mc(e,t){let{limit:n}=t,r=t.offset??0;if(!Number.isInteger(n)||n<=0)throw Error(`sliceRange: limit must be a positive integer (got ${n})`);if(!Number.isInteger(r)||r<0)throw Error(`sliceRange: offset must be a non-negative integer (got ${r})`);let i=typeof e==`string`?new S(e):e,a=i.range;if(!a)throw Error(`sliceRange: reference has no range (got "${i.toString()}")`);let o=a.size;if(r>o)throw Error(`sliceRange: offset ${r} exceeds totalCells ${o} for "${i.toString()}"`);let s=a.width,c=Math.min(r+n,o),l=[];for(let e=r;e<c;e++)l.push({row:a.top+Math.floor(e/s),column:a.left+e%s});let u=l.length,d=r+u,f=d<o;return{coords:l,sheetName:i.sheetName,reference:i.toString(),totalCells:o,returnedCells:u,offset:r,nextOffset:f?d:void 0,truncated:f}}function Nc(e,t,n){let r=n.offset??0,i=new S(t),a=i.range?.size??1,o={includeStyles:n.includeStyles,maxFormulas:n.maxFormulas,mismatches:n.mismatches};if(i.range===null||a===1&&r===0)return oc(e,t,o);let s=Mc(i,{offset:r,limit:n.limit}),c=sc(e,s.sheetName,s.coords,o);return s.truncated&&s.nextOffset!==void 0?{data:c,truncated:!0,totalCells:s.totalCells,returnedCells:s.returnedCells,offset:s.offset,nextOffset:s.nextOffset,reference:s.reference}:c}const Pc=new Z({name:`inspect`,description:`Inspect detailed per-cell information including value, formula, number format, style, and hyperlink.
70
- Returns up to 20 cells per call. When the range is larger, the response is truncated and includes \`nextOffset\` — call again with the same \`reference\` and \`offset: <nextOffset>\` to continue.
71
-
72
- Examples:
73
- - Single cell: { "reference": "A1" }
74
- - Range: { "reference": "B2:C5" }
75
- - Cross-sheet: { "reference": "Sheet2!A1" }
76
- - Next page: { "reference": "A1:K10", "offset": 20 }`,parameters:C.object({reference:C.string().describe(`Cell reference or range to inspect (e.g. 'A1', 'B2:C5', 'Sheet2!A1')`),offset:C.number().int().nonnegative().optional().describe("Pagination offset into the range (0-based, row-major). When the previous response had `nextOffset`, pass that value here to read the next page.")}),run:(e,t)=>Nc(e.model,Q(t.reference,e.model),{offset:t.offset,limit:20,includeStyles:!0,mismatches:e.mismatches})}),Fc=Oc(`precedents`,`precedents`,`Trace upstream dependencies — the cells a formula reads from, transitively.
77
- Default mode 'grouped': cells sharing a formula pattern are collapsed into labeled chunks,
78
- labeled from nearby headers. This provides a token-efficient structural view that surfaces
79
- which parameters feed into which outputs.
80
-
81
- Switch to mode: "cells" to drill into individual cells: each node carries the formula,
82
- calculated value, and error (e.g. #DIV/0!) so you can follow error propagation to its source.
83
- Ranges referenced by formulas appear as 'range' nodes. If every range member is a leaf value
84
- cell, the range is collapsed into a single node with no further children.
85
-
86
- "grouped" response shape — each node carries:
87
- - type: "output" (computed, no dependents), "inter" (computed, has dependents), "data" (value range), "param" (single value cell)
88
- - labels: human-readable names derived from nearby headers
89
- - formula: the formula pattern for this chunk (with relative references)
90
- - rootHeight: dependency distance from graph roots (parameters/data)
91
- - leafDepth: dependency distance from graph leaves (outputs)
92
- - precedents: dict of upstream chunk nodes keyed by their ref (omitted for leaves)
93
- - alreadyVisited: true when this chunk was expanded elsewhere in the tree (diamond/cycle cut)
94
- - truncated: present when traversal stopped early; reason is "maxDepth" or "maxNodes"; totalChildren reports the real count when children were cut short
95
-
96
- "cells" response shape — each node carries:
97
- - kind: "cell", "range", or "name"
98
- - formula: the formula string, or null for value cells and range vertices
99
- - value: the calculated value (cell and name nodes)
100
- - errorValue: present only when the cell evaluates to a formula error
101
- - precedents: a dict of child nodes keyed by their own ref (omitted for leaves)
102
- - alreadyVisited: true when this node has been fully expanded elsewhere in the tree (diamond/cycle cut)
103
- - truncated: present when traversal stopped early; reason is "maxDepth" or "maxNodes"; totalChildren reports the real count when children were cut short
104
-
105
- Both modes use maxDepth (default 10, max 50) to bound recursion and maxNodes (default 100, max 500) as a global budget on the returned tree.`),Ic=new Z({name:`symbols`,description:`Get workbook structural metadata: sheet dimensions, named ranges, tables, and dependency graph stats.
106
- Complements describeStructure (which provides labels and data regions) with structural/entity information.
107
-
108
- Use this to understand the workbook's overall shape before inspecting specific cells.`,parameters:C.object({}),run:(e,t)=>{let n=e.model.getWorkbook();if(!n)return{error:`No workbook loaded`};let r=n.getSheets().map(e=>({name:e.name,size:e.getSize()})),i=[],a=[];for(let t of e.model.getEntities())t.type===`name`?i.push({name:t.name,formula:t.resolvesTo,scope:`workbook`}):t.type===`table`&&a.push({name:t.name,sheet:t.sheetName,ref:t.resolvesTo,headers:t.headers,totals:t.totals});let o=e.model.meta;return{sheets:r,namedRanges:i,tables:a,stats:{cells:o.cellCount,graphNodes:o.graphNodes,graphEdges:o.graphEdges}}}}),Lc=new Z({name:`whatIf`,description:`Test hypothetical value changes and see which formula cells are affected.
109
- Applies temporary changes, recalculates, shows before/after diff of affected formula cells,
110
- then restores the original state. A string value starting with "=" is applied as a temporary
111
- formula. Max 20 changes, max 100 affected cells reported.
112
-
113
- Example: { "changes": { "A1": 50, "B1": "=A1*2" } }`,parameters:C.object({changes:C.record(C.string(),C.union([C.string(),C.number(),C.boolean(),C.null()])).describe(`Map of cell references to hypothetical values (e.g. { 'A1': 50, 'B1': 100 })`)}),run:(e,t)=>{let n=Object.entries(t.changes);return n.length===0?{error:`No changes provided.`}:n.length>20?{error:`Too many changes (${n.length}). Maximum is 20.`}:Ss(e.model,e=>{let t=[],r=[];for(let[e,i]of n)typeof i==`string`&&i.startsWith(`=`)?r.push([e,i.slice(1)]):t.push([e,i]);t.length>0&&e.writeMultiple(t,{skipRecalc:!0});for(let[t,n]of r)e.getWorkbook(new S(t).workbookName||null)?.editCell(t,{f:n});e.recalculate();let i=es(e).lastRecalc,a={},o=0;if(i?.formulaCellsUpdated){for(let[t,n]of i.formulaCellsUpdated)if(o++,o<=100&&t instanceof ae){let r=Cc(e,new oe(t.workbookKey,t.sheetIndex,t.rowIndex,t.colIndex));a[r]={before:Qs(n),after:Qs(t.v),formula:t.f??null}}}let s={};for(let[e,t]of n)s[e]=t;let c={applied:s,affected:a};return o>100&&(c.truncated=!0,c.totalAffected=o),c},n.map(([e])=>e))}}),Rc=C.object({sheet:C.string().optional().describe(`Restrict to a single sheet by name.`),range:C.string().optional().describe(`Restrict to a range, e.g. 'Sheet1!B2:D10' or 'B2:D10' (resolved against the default/first sheet). Takes precedence over 'sheet' if both are given.`),max:C.number().int().positive().optional().describe(`Max cells listed per formula-error group (default 50).`)});function zc(e){return e>=3?`ERROR`:e===2?`WARNING`:`NOTICE`}function Bc(e,t,n,r){if(!t&&!n)return!0;let i=Array.from(e.references);if(n&&!t){let e=`${n}!`;return i.some(t=>t.startsWith(e)||!t.includes(`!`))}return!t||i.some(e=>{if(e.startsWith(`[`))return!1;try{let n=new S(e,{ctx:r});return t.contains(n)}catch{return!1}})}const Vc=new Z({name:`listErrors`,description:`List all formula errors and model errors in a workbook, grouped by error kind. Results are scoped to a sheet or range when provided, and truncated per group when the default cell limit is exceeded.`,parameters:Rc,run:(e,t)=>{let n=t.max??50,r=e.model.getWorkbook();if(!r)return{error:`Model has no workbook.`};let i,a;t.range?(i=new S(t.range,{ctx:e.model}),a=i.sheetName??r.getSheets()[0]?.name):t.sheet&&(a=t.sheet);let o=a===void 0?r.getSheets():[r.getSheet(a)].filter(e=>e!==null),s=new Map;function c(e,t,n){let r=t.detail?`${t.name} (${t.detail})`:t.name,i=`${n}\x00${r}`,a=s.get(i);a||(a={key:r,cells:[],sheet:n},s.set(i,a)),a.cells.push(e.toString())}for(let e of o)if(i)for(let t of i){let n=e.getCell(t.getCellId());!n||!(n.v instanceof x)||c(new S(n.id,{sheetName:e.name}),n.v,e.name)}else for(let t of e.getCells())t.v instanceof x&&c(new S(t.id,{sheetName:e.name}),t.v,e.name);let l=[],u=0,d={},f=0;for(let[,e]of s){let t=e.cells.length;u+=t,d[e.sheet]=(d[e.sheet]??0)+t;let r=e.cells.slice(0,n),i=t-r.length;l.push({key:e.key,count:t,cells:r,...i>0?{omittedCells:i}:{}}),i>0&&f++}let p=[];for(let t of r.errors)Bc(t,i,a,e.model)&&p.push({type:t.type,level:zc(t.level),message:t.message,references:Array.from(t.references)});return{formulaErrors:{groups:l,totalCells:u,perSheet:d},modelErrors:{entries:p,total:p.length},...f>0?{truncated:{groupsWithOmittedCells:f,hint:`Some groups had cells omitted. Narrow the scope using the sheet or range parameter, or increase max.`}}:{}}}}),Hc=96/72,Uc={W:1.5,M:1.4,"@":1.4,m:1.2,w:1.2,i:.4,l:.4,I:.4,j:.4," ":.5,".":.5,",":.5,":":.5,";":.5};function Wc(e,t){let{fontSize:n,isBold:r}=t,i=0;for(let t of e){let e=Uc[t]||1;i+=e}let a=n/11,o=r?1.2:1,s=t.isItalic?.95:1,c=i*a*o*s;return Math.min(500,c*7)}function Gc(e,t){return t.fontSize*Hc}function Kc(e,t,n){let r=7*(t.fontSize/11)*(t.isBold?1.2:1),i=n-7,a=Math.max(1,Math.floor(i/r));return Math.ceil(e.length/a)*Gc(e,t)}function qc(e){try{return n(e.z||`General`,e.v)}catch{return`######`}}function Jc(e){let t=e.style;return{fontFamily:t?.fontFamily||`Calibri`,fontSize:t?.fontSize||12,isBold:t?.bold||!1,isItalic:t?.italic||!1,isWrapped:t?.wrapText||!1}}function Yc(e,t){let[,n]=e.getSize(),r=0,i=0;for(let a=0;a<n&&i<300;a++){let n=e.getCellByRange({top:a,left:t});if(!n||n.v==null)continue;i++;let o=qc(n);if(!o)continue;let s=Wc(o,Jc(n));if(s>r&&(r=s),r>=500)break}return(r+7)/7+.5}function Xc(e,t){let n=e.col_widths?.[t],r=e.defaults?.col_width;return((n??r??8.43)-.5)*7}function Zc(e,t){let[n]=e.getSize(),r=0,i=0;for(let a=0;a<n&&i<300;a++){let n=e.getCellByRange({top:t,left:a});if(!n||n.v==null)continue;i++;let o=qc(n);if(!o)continue;let s=Jc(n),c=s.isWrapped?Kc(o,s,Xc(e,a)):Gc(o,s);if(c>r&&(r=c),r>=409*1.3333333333333333)break}let a=(r+5)/Hc;return Math.max(a,16)}const Qc=new Z({name:`manageRowsAndColumns`,description:`Insert, delete, or auto-size rows and columns.
114
- Operations are executed in order: column insert → column delete → row insert → row delete → column autosize → row autosize.`,parameters:C.object({sheet:C.string().describe(`Sheet name to operate on`),columns:C.object({insert:C.object({column:C.string().describe(`Column letter (e.g., "A", "B", "AA")`),count:C.number().describe(`Number of columns to insert`)}).optional(),delete:C.object({column:C.string().describe(`Column letter (e.g., "A", "B", "AA")`),count:C.number().describe(`Number of columns to delete`)}).optional(),autoSize:C.array(C.string()).optional().describe(`Array of column letters to auto-size (e.g., ["A", "B", "C"])`)}).optional().describe(`Column operations`),rows:C.object({insert:C.object({row:C.number().describe(`1-based row number (e.g., 1, 2, 10)`),count:C.number().describe(`Number of rows to insert`)}).optional(),delete:C.object({row:C.number().describe(`1-based row number (e.g., 1, 2, 10)`),count:C.number().describe(`Number of rows to delete`)}).optional(),autoSize:C.array(C.number()).optional().describe(`Array of 1-based row numbers to auto-size (e.g., [1, 2, 3])`)}).optional().describe(`Row operations`),note:C.string().optional().describe(`Description of this operation for version history`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n,i=r.getSheet(t.sheet);if(!i)return{error:`Sheet not found: ${t.sheet}`};let{columns:a,rows:o}=t;if(a?.insert){let e=rs(a.insert.column);r.insertColumns(t.sheet,e,a.insert.count,!1)}if(a?.delete){let e=rs(a.delete.column);r.deleteColumns(t.sheet,e,a.delete.count)}if(o?.insert){let e=o.insert.row-1;r.insertRows(t.sheet,e,o.insert.count,!1)}if(o?.delete){let e=o.delete.row-1;r.deleteRows(t.sheet,e,o.delete.count)}if(a?.autoSize)for(let e of a.autoSize){let n=rs(e),a=Yc(i,n);r.setColumnWidth(t.sheet,n,a)}if(o?.autoSize)for(let e of o.autoSize){let n=e-1,a=Zc(i,n);r.setRowHeight(t.sheet,n,a)}return{success:!0,changedCells:Fs(e.model)}}}),$c={visible:0,hidden:1,veryHidden:2},el=new Z({name:`manageSheets`,description:`Add, remove, rename, or change visibility of sheets.
115
- Operations are executed in order: add → rename → setVisibility → remove.`,parameters:C.object({add:C.object({name:C.string().describe(`Name for the new sheet`)}).optional().describe(`Add a new sheet`),remove:C.object({sheet:C.string().describe(`Name of the sheet to remove`)}).optional().describe(`Remove a sheet`),rename:C.object({sheet:C.string().describe(`Current name of the sheet`),name:C.string().describe(`New name for the sheet`)}).optional().describe(`Rename a sheet`),setVisibility:C.object({sheet:C.string().describe(`Name of the sheet`),hidden:C.enum([`visible`,`hidden`,`veryHidden`]).describe(`visible = normal, hidden = hidden tab, veryHidden = cannot be unhidden from UI`)}).optional().describe(`Set sheet visibility`),note:C.string().optional().describe(`Description of this operation for version history`)}),run:(e,t)=>{let n=ns(e.model);if(`error`in n)return{error:n.error};let{workbook:r}=n;if(t.add&&r.addSheet(t.add.name),t.rename){if(!r.getSheet(t.rename.sheet))return{error:`Sheet not found: ${t.rename.sheet}`};r.renameSheet(t.rename.sheet,t.rename.name)}if(t.setVisibility){let e=r.getSheet(t.setVisibility.sheet);if(!e)return{error:`Sheet not found: ${t.setVisibility.sheet}`};e.hidden=$c[t.setVisibility.hidden]}return t.remove&&!r.removeSheet(t.remove.sheet)?{error:`Sheet not found: ${t.remove.sheet}`}:{success:!0,sheets:r.getSheets().map(e=>e.name)}}});function tl(e){return/QUERY/i.test(e)?e.replace(/QUERY\s*\(([^,]+),\s*"(.+)"(.*)\)/gi,(e,t,n,r)=>`QUERY(${t}, "${n.replace(/"/g,`'`)}"${r})`):e}const nl=C.object({read:C.array(C.string()).describe(`Cell references, ranges, or formulas to read. Examples: "A1", "B1:B10", "Sheet1!C5", "=XLOOKUP(\\"Revenue\\", A1:A10, B1:B10)", "=AVERAGE(C1:C10)"`),apply:C.array(C.object({cell:C.string(),value:C.union([C.string(),C.number(),C.boolean(),C.null()])})).optional().describe(`Temporary values to apply before reading (not persisted)`),cursors:C.record(C.string(),C.number().int().nonnegative()).optional().describe("Optional pagination cursors keyed by entries in `read`. Pass `nextOffset` from a previous truncated response to continue paging through that range. Formula entries (those starting with `=`) ignore cursors.")});function rl(e){return e.startsWith(`=`)||/^[A-Z]+\s*\(/i.test(e)}function il(e,t){let n=e.read.map(e=>{if(rl(e))return{original:e,normalized:e};let n=Q(e,t);if(he(n)===null)throw Error(`Invalid cell reference: "${e}". Sheet names with special characters must be quoted (e.g., "'My Sheet'!A1").`);return{original:e,normalized:n}});return{reads:n,apply:(e.apply??[]).map(({cell:e,value:n})=>{let r=Q(e,t);if(he(r)===null)throw Error(`Invalid cell reference: "${e}". Sheet names with special characters must be quoted (e.g., "'My Sheet'!A1").`);return{cell:r,value:n}}),cursors:al(e.cursors,n,t)}}function al(e,t,n){if(!e)return;let r=new Map;for(let e of t)r.set(e.original,e.original),r.has(e.normalized)||r.set(e.normalized,e.original);let i={};for(let[t,a]of Object.entries(e)){let e=r.get(t);if(!e)try{e=r.get(Q(t,n))}catch{}if(!e)throw Error(`Unknown cursor key "${t}". Cursor keys must match an entry in \`read\` (either verbatim or in the canonical form echoed by \`reference\`).`);i[e]=a}return i}function ol(e,t,n){try{return oc(e,t,n)}catch(r){if(r instanceof Error&&/QUERY/i.test(t)){let r=tl(t);if(r!==t)try{return oc(e,r,n)}catch{}}return{error:r instanceof Error?r.message:`Unknown error`}}}function sl(e,t,n,r){let i={},a={maxFormulas:10,mismatches:r};for(let{original:r,normalized:o}of t)try{if(rl(o)){i[r]=ol(e,o,a);continue}i[r]=Nc(e,o,{offset:n?.[r],limit:500,...a})}catch(e){i[r]={error:e instanceof Error?e.message:`Unknown error`}}return i}const cl=new Z({name:`readCalculatedValues`,description:`Read cell values, formula results, and lookups from spreadsheets, and optionally apply temporary values for what-if calculations.
116
- The 'read' array accepts cell references, ranges, and formulas. Use formulas like XLOOKUP, QUERY, AVERAGE, etc. directly in 'read' to find and compute values in a single call.
117
-
118
- Examples:
119
- - Read cells: { "read": ["A1", "B1:B10", "Sheet2!C5"] }
120
- - Lookup: { "read": ["=XLOOKUP(\\"Revenue\\", A1:A10, B1:B10)"] }
121
- - Filtered average: { "read": ["=QUERY(Sheet1!A1:D100, \\"SELECT AVG(D) WHERE A = 'Category1'\\")"] }
122
- - What-if: { "read": ["C8"], "apply": [{ "cell": "B1", "value": 100 }] }
123
-
124
- Large ranges are automatically truncated. When a range entry is truncated the response includes \`nextOffset\` — call again with \`cursors: { "<same expression>": <nextOffset> }\` to read the next page.`,parameters:nl,run:(e,t)=>{let n=il(t,e.model);return n.apply.length>0?Ss(e.model,t=>{let r=n.apply.map(({cell:e,value:t})=>[e,t]);return t.writeMultiple(r,{skipRecalc:!0}),t.recalculate(),sl(t,n.reads,n.cursors,e.mismatches)},n.apply.map(({cell:e})=>e)):sl(e.model,n.reads,n.cursors,e.mismatches)}}),ll=C.object({apply:C.array(C.object({cell:C.string().describe(`Cell reference`),value:C.union([C.string(),C.number(),C.boolean(),C.null()]).describe(`Temporary value to apply`)})).optional().describe(`Optional temporary values to apply before running formula(s)`),formula:C.string().optional().describe(`Single formula to evaluate (must start with "=")`),formulas:C.array(C.string()).optional().describe(`Array of formulas to evaluate (more efficient for multiple formulas)`),sheet:C.string().optional().describe(`Sheet name against which bare cell references (e.g. A1, SUM(A:A)) resolve. Defaults to the primary workbook's first sheet. Use this when you need formulas to evaluate in the context of a different sheet. Sheet names are matched across all workbooks in the model; on a name collision the primary workbook's sheet wins, so external sheets with colliding names are only reachable via workbook-qualified references in the formula itself.`)});function ul(e,t,n){try{return oc(e,t,{evalContext:n})}catch(r){if(r instanceof Error&&/QUERY/i.test(t)){let r=tl(t);if(r!==t)try{return oc(e,r,{evalContext:n})}catch{}}return{error:r instanceof Error?r.message:`Unknown error`}}}const dl=new Z({name:`runFormula`,description:`Run one or more formulas without writing to any cell. Returns the calculated results.
125
- Useful for testing formulas or computing values without modifying the workbook.
126
-
127
- Examples:
128
- - Single: { "formula": "=SUM(A1:A10)" }
129
- - Batch: { "formulas": ["=SUM(A1:A10)", "=AVERAGE(B1:B10)", "=COUNT(C1:C10)"] }
130
- - With temp values: { "formula": "=A1*B1", "apply": [{ "cell": "A1", "value": 5 }] }
131
- - Against a specific sheet: { "formula": "=SUM(A:A)", "sheet": "Sheet2" }
132
-
133
- Use "formulas" array to test multiple formulas in one call (more efficient than multiple calls).
134
-
135
- Bare cell references (e.g. A1, SUM(A:A)) resolve against the primary workbook's first sheet
136
- by default. Use the "sheet" parameter when you need them to resolve against a different sheet.
137
- The response includes a "_note" field identifying the sheet bare references resolved
138
- against, so you can verify they resolved where you intended.
139
-
140
- Sheets in external (linked) workbooks can be read with workbook-qualified references inside
141
- the formula itself, e.g. ='[external.xlsx]Sheet1'!A1. If an external sheet shares its name
142
- with a sheet in the primary workbook, the primary workbook's sheet always wins for plain
143
- references — only the workbook-qualified form reaches the external one.`,parameters:ll,run:(e,t)=>{let n=t.formulas??(t.formula?[t.formula]:[]);if(n.length===0)return{error:`Either "formula" or "formulas" is required`};let r=(t.apply??[]).map(({cell:t,value:n})=>({cell:Q(t,e.model),value:n})),i=e.model.resolveSheet(t.sheet);if(t.sheet&&!i)return{error:`Sheet "${t.sheet}" not found.`};let a=e.model.getWorkbook()?.name??null,o=i?.name??null,s={workbookName:a,sheetName:o},c=e=>{let r={};for(let t of n){let n=ul(e,t,s);if(n&&typeof n==`object`&&`ref`in n){let{ref:e,...i}=n;r[t]=i}else r[t]=n}return o&&(r._note=t.sheet?`Resolved bare cell references against sheet "${o}"`:`Resolved bare cell references against ${a?`[${a}]`:``}${o}`),r};return r.length>0?Ss(e.model,e=>{let t=r.map(({cell:e,value:t})=>[e,t]);return e.writeMultiple(t,{skipRecalc:!0}),e.recalculate(),c(e)},r.map(({cell:e})=>e)):c(e.model)}}),fl=C.enum([`value`,`rawValue`,`fontColor`,`fill`,`numberFormat`,`formula`]),pl=C.object({reference:C.string().describe(`A1 range to view, sheet-qualified where needed (e.g. "'LBO Model'!B40:N80"). A single cell is allowed.`),show:fl.optional().describe(`What each cell renders. 'value' (default): formatted display values; a † marks a number whose format hides that it is numeric (a date, an accounting dash) — a legend below the grid explains it. 'rawValue': underlying unformatted values. 'fontColor'/'fill'/'numberFormat': that style property ('-' when unset; colors as lowercase hex for RGB, raw token for theme/preset/indexed colors). 'formula': formula cells render a short key like [1] with a legend below the grid — formulas are compared in R1C1 form, so a formula filled across a range shares one key and anomalies stand out; non-formula cells show their raw value, so hardcoded overrides stand out too.`)});function ml(e,t){if(!e)return`-`;if(t===`numberFormat`)return e.numberFormat??`-`;let n=t===`fill`?e.fillColor:e.color;return n?Zs(n):`-`}function hl(e){return e?e.t===`e`?e.error?.name??String(e.v??``):typeof e.formatted==`string`?e.formatted:gl(e.v):``}function gl(e){return e==null?``:typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e)}function _l(e,t){let n=e.getWorkbook(),r=t||n?.getSheets()[0]?.name,i=r?n?.getSheet(r):null;if(!i)throw Error(`viewRange: sheet "${r}" not found`);return i}function vl(e,t,n){let r=_l(e,t);return{textAt:(e,t)=>ml(r.getCellByRange({top:t,left:e})?.style,n)}}function yl(e,t){let n=_l(e,t);return{textAt:(e,t)=>gl(n.getCellByRange({top:t,left:e})?.v)}}function bl(e,t){let n=_l(e,t),r=new Map,i=[];return{textAt:(e,t)=>{let a=n.getCellByRange({top:t,left:e});if(!a)return``;if(!a.f)return gl(a.v);let o=Jr(a.f,a.id),s=r.get(o);return s===void 0&&(s=r.size+1,r.set(o,s),i.push(`[${s}] =${o}`)),`[${s}]`},footer:()=>i.length>0?[``,`Formulas:`,...i]:[]}}function xl(e,t){return e?.t===`n`&&m(t)==null}function Sl(e,t,n){let r=[];for(let e=0;e<n.rowsShown;e++)for(let t=0;t<n.colsShown;t++)r.push({row:n.top+e,column:n.left+t});let i=sc(e,t,r),a=!1;return{textAt:(e,t)=>{let n=i[ic(e,t)],r=hl(n);return xl(n,r)?(a=!0,`${r}†`):r},footer:()=>a?[``,`† = formatted number (date/time/accounting); the value is numeric, not text — write the number or date, not this string.`]:[]}}function Cl(e,t,n,r){switch(n){case`value`:return Sl(e,t,r);case`rawValue`:return yl(e,t);case`fontColor`:case`fill`:case`numberFormat`:return vl(e,t,n);case`formula`:return bl(e,t)}}function wl(e,t,n=`value`){let r=new S(Q(t,e)),i=r.range;if(!i)throw Error(`viewRange: "${t}" is not a cell or range reference`);let{top:a,left:o,width:s,height:c}=i,l=Math.min(s,500),u=Math.min(c,Math.max(1,Math.floor(500/l))),d=Cl(e,r.sheetName,n,{top:a,left:o,rowsShown:u,colsShown:l}),{textAt:f}=d,p=Array.from({length:l},(e,t)=>pe(o+t)),m=Array.from({length:u},(e,t)=>String(a+t+1)),h=m.map((e,t)=>p.map((e,n)=>f(o+n,a+t))),g=Math.max(...m.map(e=>e.length),0),_=p.map((e,t)=>Math.max(e.length,...h.map(e=>e[t]?.length??0))),v=(e,t)=>`${e.padStart(g)} | ${t.map((e,t)=>e.padEnd(_[t]??0)).join(` | `)}`,y=[v(``,p),`${`-`.repeat(g)}-+-${_.map(e=>`-`.repeat(e)).join(`-+-`)}`,...h.map((e,t)=>v(m[t]??``,e))],b=[];return u<c&&b.push(`rows ${a+u+1}–${i.bottom+1}`),l<s&&b.push(`columns ${pe(o+l)}–${pe(i.right)}`),b.length>0&&y.push(``,`… showing ${u}×${l} of ${c}×${s} cells (cap 500). Request ${b.join(` and `)} in a follow-up call.`),y.push(...d.footer?.()??[]),y.join(`
144
- `)}const Tl=new Z({name:`viewRange`,description:`Render a worksheet rectangle as a compact text grid — by default the displayed (number-formatted) values, what a human sees in the cells — with column letters and row numbers.
145
- Use this FIRST to scan or orient in an area (a financial statement, a block, a table): one call returns the whole rectangle instead of reading it cell-by-cell.
146
- Pass \`show\` to audit other layers of the same grid: raw unformatted values, a style property ('-' marks unset cells), or the formula structure — formula cells get a legend key, identical fills share one key, so a miscolored cell, a wrong format, or a hardcoded override stands out against the value grid you just read.
147
- For precedents/dependents or error provenance, use \`inspect\`.
148
- Returns at most 500 cells; a larger rectangle renders the cells that fit and names the rows or columns that remain — request those in a follow-up call.
149
-
150
- Examples:
151
- - Range: { "reference": "B40:N80" }
152
- - Sheet-qualified: { "reference": "'LBO Model'!B40:N80" }
153
- - Single cell: { "reference": "C12" }
154
- - Font colors: { "reference": "B40:N80", "show": "fontColor" }
155
- - Formula structure: { "reference": "B40:N80", "show": "formula" }`,parameters:pl,run:(e,t)=>wl(e.model,t.reference,t.show)}),El=C.object({reference:C.string().describe(`A1 range to capture, sheet-qualified where needed (e.g. "'LBO Model'!B40:N80"). A single cell is allowed.`),headers:C.boolean().default(!0).describe(`Draw row/column headers (A, B, C … / 1, 2, 3 …).`),scale:C.number().min(1).max(4).default(2).describe(`Output pixel density for headless (Node/Worker) rendering — 2 = crisp/retina. Ignored on a browser main thread, where the display's devicePixelRatio governs.`)});function Dl(e){return import(e)}let Ol;function kl(e){return Ol??=(async()=>{try{let[t,n,r,i]=await Promise.all([Dl(`node:fs`),Dl(`node:module`),Dl(`node:path`),Dl(`@grid-is/fontstack`)]),a=r.join(r.dirname(n.createRequire(import.meta.url).resolve(`@grid-is/fontstack`)),`..`,`fonts`);for(let n of i.availableFonts()){let{id:r,license:i}=n,o=[n.regular?`${a}/${i}/${r}/${r}-regular.ttf`:``,n.bold?`${a}/${i}/${r}/${r}-bold.ttf`:``,n.italic?`${a}/${i}/${r}/${r}-italic.ttf`:``,n.boldItalic?`${a}/${i}/${r}/${r}-bolditalic.ttf`:``].filter(e=>e!==``&&t.existsSync(e));o.length>0&&e.use(n.name,o)}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`captureRange: font registration unavailable (${t}); rendering with system fonts.`)}})(),Ol}function Al(e,t,n,r){let i=`window`in globalThis,a=Reflect.get(globalThis,`window`);Reflect.set(globalThis,`window`,{devicePixelRatio:r});try{e.resize(t,n),e.render(t,n)}finally{i?Reflect.set(globalThis,`window`,a):Reflect.deleteProperty(globalThis,`window`)}}async function jl(e,t,n){if(typeof OffscreenCanvas<`u`){let r=new OffscreenCanvas(t.width,t.height);Al(e,r,t,n);let i=await r.convertToBlob({type:`image/png`});return new Uint8Array(await i.arrayBuffer())}let r=await Dl(`skia-canvas`).catch(()=>{throw Error(`captureRange: no canvas backend (browser OffscreenCanvas or Node skia-canvas).`)});await kl(r.FontLibrary);let i=new r.Canvas(t.width,t.height);return Al(e,i,t,n),i.toBufferSync(`png`)}const Ml=new Z({name:`captureRange`,description:`Render a range as a PNG image and return its raw bytes (Uint8Array).
156
-
157
- Use this when the formatting itself is the information — fills, font colors, borders,
158
- merged cells, number formats — that the text-grid tools (viewRange) can't convey, or when
159
- the user asks to *see* part of the workbook. The bytes are ready to attach to a multimodal
160
- message or write to a file; this tool does no LLM wiring itself.
161
-
162
- Gridlines and row/column headers render as Excel shows them. Renders against the browser's
163
- native canvas when available, and skia-canvas in Node.`,parameters:El,run:async(e,t)=>{try{let n=ns(e.model);if(`error`in n)return n;let{workbook:r}=n,i=Q(t.reference,e.model),a=new S(i);if(!a.range)return{error:`captureRange: "${t.reference}" is not a cell or range reference`};let o=a.sheetName||r.getSheets()[0]?.name;if(!o)return{error:`captureRange: no sheet to render`};let s=new $o({headers:t.headers});return s.setWorkbook(r),s.setSheet(o),await jl(s,s.refToRect(new Na(i,{sheetName:o})),t.scale)}catch(e){return{error:e instanceof Error?e.message:String(e)}}}});function $(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Nl(e){try{return new S(e).withPrefix({workbookName:``}).toString()}catch{return e}}function Pl(e){let t=Ic.execute({model:e},{});if(ts(t))return null;let n=ws.execute({model:e},{});return ts(n)?null:Fl(t,n,e.getWorkbook()?.name??void 0)}function Fl(e,t,n){let r=[];if(r.push(`## Workbook Summary`),r.push(``),e.stats.cells===0){let t=`${$(e.sheets.length,`sheet`)}, 0 cells. The workbook is empty.`;return r.push(n?`"${n}" — ${t}`:t),r.join(`
164
- `).trimEnd()}let i=t.sheets.reduce((e,t)=>e+t.formulaCount,0),a=`${$(e.sheets.length,`sheet`)}, ${$(e.stats.cells,`total cell`)}, ${$(i,`formula`)}.`;if(r.push(n?`"${n}" \u2014 ${a}`:a),r.push(``),e.namedRanges.length>0){r.push(`Defined names:`);let t=e.namedRanges.slice(0,10);for(let e of t){let t=e.formula==null?``:` = ${Nl(e.formula)}`;r.push(`- ${e.name}${t}`)}e.namedRanges.length>10&&r.push(`- ... ${$(e.namedRanges.length-10,`more defined name`)}`),r.push(``)}if(e.tables.length>0){r.push(`Tables:`);let t=e.tables.slice(0,10);for(let e of t){let t=e.headers?`, ${$(e.headers,`header row`)}`:``,n=e.totals?`, ${$(e.totals,`totals row`)}`:``;r.push(`- ${e.name} on "${e.sheet}" (${Nl(e.ref)}${t}${n})`)}e.tables.length>10&&r.push(`- ... ${$(e.tables.length-10,`more table`)}`),r.push(``)}let o=new Map(t.sheets.map(e=>[e.name,e]));for(let[t,n]of e.sheets.entries()){let e=o.get(n.name),[i,a]=n.size,s=e?.cellCount??0,c=e?.formulaCount??0,l=e?.errorCount,u=`${$(a,`row`)}, ${$(i,`column`)}, ${$(s,`cell`)}, ${$(c,`formula`)}`;if(l&&(u+=`, ${$(l,`error`)}`),r.push(`Sheet "${n.name}" \u2014 ${u}`),e){let i=e.totalLabels??e.labels.length;if(t<8){let t=e.labels.slice(0,15);for(let e of t)r.push(`- ${e}`);if(i>t.length){let e=i-t.length,a=JSON.stringify([n.name]);r.push(`- ... ${$(e,`more label`)} (use describeStructure({sheets: ${a}, labelOffset: ${t.length}}) to page forward)`)}}else if(i>0){let e=JSON.stringify([n.name]);r.push(`- ${$(i,`label`)} (use describeStructure({sheets: ${e}}) to see them)`)}}r.push(``)}return r.join(`
165
- `).trimEnd()}let Il;function Ll(){return Il??=(async()=>{try{let{FontLibrary:e}=await import(`skia-canvas`),t=ie(new URL(`../assets/fonts`,import.meta.url));for(let n of b(t)){let r=ne(t,n),i=b(r).filter(e=>e.endsWith(`.ttf`)).map(e=>ne(r,e));i.length>0&&e.use(i)}}catch{}})(),Il}function Rl(e){return e instanceof Error?e.message:String(e)}function zl(e=process.cwd()){let t=new Map,n=null,r={text:`No workbook loaded. Use loadWorkbook first.`,isError:!0};function i(){if(n==null)return null;let e=t.get(n);return e?{path:n,model:e}:null}function a(e){return e.getWorkbooks().flatMap(e=>e.getSheets().map(t=>`${e.workbookName||`workbook`}/${t.name}`))}function o(e){let t=e.parameters;return{name:e.name,description:e.description,inputSchema:t instanceof C.ZodObject?t.shape:{},async run(n){let a=i();if(!a)return r;e.name===`captureRange`&&await Ll();let o={model:a.model},s=await e.execute(o,t.parse(n));return ts(s)?{text:`Error: ${s.error}`,isError:!0}:s instanceof Uint8Array?{text:`Rendered ${s.length}-byte PNG.`,image:{data:Buffer.from(s).toString(`base64`),mimeType:`image/png`},isError:!1}:{text:JSON.stringify(s,null,2),isError:!1}}}}let s=C.object({path:C.string().describe(`Absolute or relative path to the .xlsx file.`)}),c={name:`loadWorkbook`,description:`Load an .xlsx file into memory and make it the active workbook. A session starts with this or createWorkbook. Returns the sheet names.`,inputSchema:s.shape,async run(r){let{path:i}=s.parse(r),o=re(e,i);try{await ce.preconditions;let e=await ce.fromXLSXFile(o);t.set(o,e),n=o;let r=a(e);return{text:`Loaded "${o}" (${e.getWorkbooks().length} workbook(s), ${r.length} sheet(s)).\nSheets: ${r.join(`, `)}`,isError:!1}}catch(e){return{text:`Failed to load "${o}": ${Rl(e)}`,isError:!0}}}},l=ie(new URL(`../assets/blank.xlsx`,import.meta.url)),u=C.object({path:C.string().describe(`Path for the new .xlsx file. saveWorkbook writes it here by default.`)}),d={name:`createWorkbook`,description:`Create a blank single-sheet workbook in memory and make it the active workbook. Nothing is written to disk until saveWorkbook.`,inputSchema:u.shape,async run(r){let{path:i}=u.parse(r),a=re(e,i);if(t.has(a))return{text:`"${a}" is already loaded. Use selectWorkbook.`,isError:!0};if(v(a))return{text:`"${a}" already exists. Use loadWorkbook.`,isError:!0};try{await ce.preconditions;let e=await ce.fromXLSX(y(l),te(a));return t.set(a,e),n=a,{text:`Created blank workbook "${a}" (1 sheet: Sheet1). Use saveWorkbook to write it to disk.`,isError:!1}}catch(e){return{text:`Failed to create workbook: ${Rl(e)}`,isError:!0}}}},f=C.object({path:C.string().optional().describe(`Output path. Defaults to the source path.`),overwrite:C.boolean().optional().describe(`Overwrite an existing file. Default false.`)}),p={name:`saveWorkbook`,description:`Save the active workbook to an .xlsx file. Provide a new path, or set overwrite: true to write over an existing file (including the source).`,inputSchema:f.shape,async run(t){let{path:n,overwrite:a}=f.parse(t),o=i();if(!o)return r;let s=n?re(e,n):o.path;if(v(s)&&!a)return{text:`"${s}" exists. Set overwrite: true or choose a new path.`,isError:!0};try{let e=o.model.getWorkbooks();return e.length===0?{text:`No workbooks to save.`,isError:!0}:(ee(s,await e[0].toXLSX()),{text:`Saved to "${s}".`,isError:!1})}catch(e){return{text:`Failed to save: ${Rl(e)}`,isError:!0}}}},m=C.object({path:C.string().describe(`Path of a previously loaded workbook, as shown by listWorkbooks.`)}),h={name:`selectWorkbook`,description:`Make a previously loaded workbook the active one for all other spreadsheet tools. Switching keeps in-memory state, so unsaved edits survive. Use listWorkbooks to see what is loaded; use loadWorkbook to (re)load from disk.`,inputSchema:m.shape,async run(r){let{path:i}=m.parse(r),o=re(e,i),s=t.get(o);if(!s){let e=[...t.keys()];return{text:e.length?`"${o}" is not loaded. Loaded workbooks:\n${e.join(`
166
- `)}`:`"${o}" is not loaded. No workbooks loaded — use loadWorkbook first.`,isError:!0}}return n=o,{text:`Active workbook: "${o}".\nSheets: ${a(s).join(`, `)}`,isError:!1}}},g=C.object({}),_={name:`listWorkbooks`,description:`List all loaded workbooks and their sheet names.`,inputSchema:g.shape,async run(){if(t.size===0)return{text:`No workbooks loaded.`,isError:!1};let e=[];for(let[r,i]of t){let t=r===n?` [active]`:``;e.push(`${r}${t}: ${a(i).join(`, `)}`)}return{text:e.join(`
167
- `),isError:!1}}},b={name:`generateWorkbookContext`,description:`Generate a comprehensive natural-language description of the active workbook: sheet structures, data regions, labels, and relationships. More detailed than describeStructure.`,inputSchema:g.shape,async run(){let e=i();if(!e)return r;let t=Pl(e.model);return t==null?{text:`Could not generate context.`,isError:!0}:{text:t,isError:!1}}},ne=C.object({code:C.string().describe("Office.js JavaScript to run against the active workbook. `context` (RequestContext) and `Excel` are in scope; call `await context.sync()` to flush writes.")}),ae={name:`executeOfficeJs`,description:`Execute an Office.js code snippet directly against the active workbook. Returns any error plus the list of Office.js APIs the code used that are not yet implemented. Edits synced before a script error remain applied.`,inputSchema:ne.shape,async run(e){let{code:t}=ne.parse(e),n=i();if(!n)return r;if(n.model.getWorkbooks().length===0)return{text:`No workbooks in the active model.`,isError:!0};try{let{ApiaryOfficeJs:e}=await import(`./dist-RYXWtRir.js`),r=new e;await r.attach(n.model);let i=await r.runString(t);return i.error?{text:JSON.stringify({error:{name:i.error.name,message:i.error.message},unimplementedAccesses:i.unimplementedAccesses},null,2),isError:!0}:{text:JSON.stringify({ok:!0,returnValue:i.returnValue,unimplementedAccesses:i.unimplementedAccesses},null,2),isError:!1}}catch(e){return{text:`executeOfficeJs failed: ${Rl(e)}`,isError:!0}}}};return[c,d,p,_,h,...[ws,cl,Hs,Xs,Ps,el,Qc,dl,bc,Lc,yc,gs,_s,jc,Fc,Pc,Vc,Ic,Tl,_c,Ml].map(o),b,ae]}function Bl(e=zl(),t={}){let n=new g({name:t.name??`agent-tools`,version:t.version??`0.1.0`});for(let t of e)n.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},async e=>{let n=await t.run(e),r=[{type:`text`,text:n.text}];return n.image&&r.push({type:`image`,data:n.image.data,mimeType:n.image.mimeType}),{content:r,isError:n.isError}});return n}async function Vl(e={}){await Bl(e.tools,{name:e.name,version:e.version}).connect(new _)}export{Ml as captureRange,zl as createGridTools,jc as dependents,ws as describeStructure,Ps as editCellStyles,Hs as editCells,Xs as fillCells,_c as findCells,Pl as generateWorkbookContext,gs as getComment,_s as getComments,yc as getStyles,bc as goalSeek,Pc as inspect,ts as isToolError,Vc as listErrors,Qc as manageRowsAndColumns,el as manageSheets,Fc as precedents,cl as readCalculatedValues,dl as runFormula,Vl as serveStdio,Ic as symbols,Bl as toMcpServer,Tl as viewRange,Lc as whatIf};
1
+ import{C as e,T as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,u as v,v as y,w as b,x,y as S}from"./dist-B8AoRnKf.js";import{McpServer as C}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as w}from"@modelcontextprotocol/sdk/server/stdio.js";import{existsSync as T,readFileSync as E,readdirSync as D,writeFileSync as O}from"node:fs";import{basename as k,join as A,resolve as j}from"node:path";import{fileURLToPath as M}from"node:url";import{Model as N}from"@grid-is/apiary";import{z as P}from"zod";let F;function I(){return F??=(async()=>{try{let{FontLibrary:e}=await import(`skia-canvas`),t=M(new URL(`../assets/fonts`,import.meta.url));for(let n of D(t)){let r=A(t,n),i=D(r).filter(e=>e.endsWith(`.ttf`)).map(e=>A(r,e));i.length>0&&e.use(i)}}catch{}})(),F}function L(e){return e instanceof Error?e.message:String(e)}function R(C=process.cwd()){let w=new Map,D=null,A={text:`No workbook loaded. Use loadWorkbook first.`,isError:!0};function F(){if(D==null)return null;let e=w.get(D);return e?{path:D,model:e}:null}function R(e){return e.getWorkbooks().flatMap(e=>e.getSheets().map(t=>`${e.workbookName||`workbook`}/${t.name}`))}function z(e){let t=e.parameters;return{name:e.name,description:e.description,inputSchema:t instanceof P.ZodObject?t.shape:{},async run(n){let r=F();if(!r)return A;e.name===`captureRange`&&await I();let i={model:r.model},a=await e.execute(i,t.parse(n));return l(a)?{text:`Error: ${a.error}`,isError:!0}:a instanceof Uint8Array?{text:`Rendered ${a.length}-byte PNG.`,image:{data:Buffer.from(a).toString(`base64`),mimeType:`image/png`},isError:!1}:{text:JSON.stringify(a,null,2),isError:!1}}}}let B=P.object({path:P.string().describe(`Absolute or relative path to the .xlsx file.`)}),V={name:`loadWorkbook`,description:`Load an .xlsx file into memory and make it the active workbook. A session starts with this or createWorkbook. Returns the sheet names.`,inputSchema:B.shape,async run(e){let{path:t}=B.parse(e),n=j(C,t);try{await N.preconditions;let e=await N.fromXLSXFile(n);w.set(n,e),D=n;let t=R(e);return{text:`Loaded "${n}" (${e.getWorkbooks().length} workbook(s), ${t.length} sheet(s)).\nSheets: ${t.join(`, `)}`,isError:!1}}catch(e){return{text:`Failed to load "${n}": ${L(e)}`,isError:!0}}}},H=M(new URL(`../assets/blank.xlsx`,import.meta.url)),U=P.object({path:P.string().describe(`Path for the new .xlsx file. saveWorkbook writes it here by default.`)}),W={name:`createWorkbook`,description:`Create a blank single-sheet workbook in memory and make it the active workbook. Nothing is written to disk until saveWorkbook.`,inputSchema:U.shape,async run(e){let{path:t}=U.parse(e),n=j(C,t);if(w.has(n))return{text:`"${n}" is already loaded. Use selectWorkbook.`,isError:!0};if(T(n))return{text:`"${n}" already exists. Use loadWorkbook.`,isError:!0};try{await N.preconditions;let e=await N.fromXLSX(E(H),k(n));return w.set(n,e),D=n,{text:`Created blank workbook "${n}" (1 sheet: Sheet1). Use saveWorkbook to write it to disk.`,isError:!1}}catch(e){return{text:`Failed to create workbook: ${L(e)}`,isError:!0}}}},G=P.object({path:P.string().optional().describe(`Output path. Defaults to the source path.`),overwrite:P.boolean().optional().describe(`Overwrite an existing file. Default false.`)}),K={name:`saveWorkbook`,description:`Save the active workbook to an .xlsx file. Provide a new path, or set overwrite: true to write over an existing file (including the source).`,inputSchema:G.shape,async run(e){let{path:t,overwrite:n}=G.parse(e),r=F();if(!r)return A;let i=t?j(C,t):r.path;if(T(i)&&!n)return{text:`"${i}" exists. Set overwrite: true or choose a new path.`,isError:!0};try{let e=r.model.getWorkbooks();return e.length===0?{text:`No workbooks to save.`,isError:!0}:(O(i,await e[0].toXLSX()),{text:`Saved to "${i}".`,isError:!1})}catch(e){return{text:`Failed to save: ${L(e)}`,isError:!0}}}},q=P.object({path:P.string().describe(`Path of a previously loaded workbook, as shown by listWorkbooks.`)}),J={name:`selectWorkbook`,description:`Make a previously loaded workbook the active one for all other spreadsheet tools. Switching keeps in-memory state, so unsaved edits survive. Use listWorkbooks to see what is loaded; use loadWorkbook to (re)load from disk.`,inputSchema:q.shape,async run(e){let{path:t}=q.parse(e),n=j(C,t),r=w.get(n);if(!r){let e=[...w.keys()];return{text:e.length?`"${n}" is not loaded. Loaded workbooks:\n${e.join(`
2
+ `)}`:`"${n}" is not loaded. No workbooks loaded — use loadWorkbook first.`,isError:!0}}return D=n,{text:`Active workbook: "${n}".\nSheets: ${R(r).join(`, `)}`,isError:!1}}},Y=P.object({}),X={name:`listWorkbooks`,description:`List all loaded workbooks and their sheet names.`,inputSchema:Y.shape,async run(){if(w.size===0)return{text:`No workbooks loaded.`,isError:!1};let e=[];for(let[t,n]of w){let r=t===D?` [active]`:``;e.push(`${t}${r}: ${R(n).join(`, `)}`)}return{text:e.join(`
3
+ `),isError:!1}}},Z={name:`generateWorkbookContext`,description:`Generate a comprehensive natural-language description of the active workbook: sheet structures, data regions, labels, and relationships. More detailed than describeStructure.`,inputSchema:Y.shape,async run(){let e=F();if(!e)return A;let t=d(e.model);return t==null?{text:`Could not generate context.`,isError:!0}:{text:t,isError:!1}}},Q=P.object({code:P.string().describe("Office.js JavaScript to run against the active workbook. `context` (RequestContext) and `Excel` are in scope; call `await context.sync()` to flush writes.")}),$={name:`executeOfficeJs`,description:`Execute an Office.js code snippet directly against the active workbook. Returns any error plus the list of Office.js APIs the code used that are not yet implemented. Edits synced before a script error remain applied.`,inputSchema:Q.shape,async run(e){let{code:t}=Q.parse(e),n=F();if(!n)return A;if(n.model.getWorkbooks().length===0)return{text:`No workbooks in the active model.`,isError:!0};try{let{ApiaryOfficeJs:e}=await import(`./dist-RYXWtRir.js`),r=new e;await r.attach(n.model);let i=await r.runString(t);return i.error?{text:JSON.stringify({error:{name:i.error.name,message:i.error.message},unimplementedAccesses:i.unimplementedAccesses},null,2),isError:!0}:{text:JSON.stringify({ok:!0,returnValue:i.returnValue,unimplementedAccesses:i.unimplementedAccesses},null,2),isError:!1}}catch(e){return{text:`executeOfficeJs failed: ${L(e)}`,isError:!0}}}};return[V,W,K,X,J,...[u,i,m,_,r,y,n,x,h,t,s,v,o,g,S,f,c,e,b,a,p].map(z),Z,$]}function z(e=R(),t={}){let n=new C({name:t.name??`agent-tools`,version:t.version??`0.1.0`});for(let t of e)n.registerTool(t.name,{description:t.description,inputSchema:t.inputSchema},async e=>{let n=await t.run(e),r=[{type:`text`,text:n.text}];return n.image&&r.push({type:`image`,data:n.image.data,mimeType:n.image.mimeType}),{content:r,isError:n.isError}});return n}async function B(e={}){await z(e.tools,{name:e.name,version:e.version}).connect(new w)}export{p as captureRange,R as createGridTools,g as dependents,u as describeStructure,r as editCellStyles,m as editCells,_ as fillCells,a as findCells,d as generateWorkbookContext,v as getComment,o as getComments,s as getStyles,h as goalSeek,f as inspect,l as isToolError,c as listErrors,n as manageRowsAndColumns,y as manageSheets,S as precedents,i as readCalculatedValues,x as runFormula,B as serveStdio,e as symbols,z as toMcpServer,b as viewRange,t as whatIf};